Skip to content

Commit

Permalink
feat: bind usage in stream mode
Browse files Browse the repository at this point in the history
  • Loading branch information
northes committed Jun 6, 2024
1 parent 5bfd815 commit a4e53cb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 5 additions & 1 deletion api_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ type ChatCompletionsResponse struct {
Created int `json:"created"`
Model string `json:"model"`
Choices []*ChatCompletionsResponseChoices `json:"choices"`
Usage *ChatCompletionsResponseUsage `json:"usage"`
// returns only in non-stream mode
Usage *ChatCompletionsResponseUsage `json:"usage,omitempty"`
}

type ChatCompletionsResponseChoices struct {
Expand All @@ -65,6 +66,9 @@ type ChatCompletionsResponseChoices struct {
Delta *ChatCompletionsMessage `json:"delta,omitempty"`

FinishReason ChatCompletionsFinishReason `json:"finish_reason"`

// returns only in stream mode
Usage *ChatCompletionsResponseUsage `json:"usage,omitempty"`
}

type ChatCompletionsResponseUsage struct {
Expand Down
8 changes: 7 additions & 1 deletion api_chat_completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ func TestChatStream(t *testing.T) {
msg, err := receive.GetMessage()
if err != nil {
if errors.Is(err, io.EOF) {
// Finish usage
if len(receive.Choices) != 0 {
choice := receive.Choices[0]
if choice.FinishReason == moonshot.FinishReasonStop && choice.Usage != nil {
t.Logf("Finish Usage: PromptTokens: %d, CompletionTokens: %d, TotalTokens: %d", choice.Usage.PromptTokens, choice.Usage.CompletionTokens, choice.Usage.TotalTokens)
}
}
break
}
t.Error(err)
Expand All @@ -68,7 +75,6 @@ func TestChatStream(t *testing.T) {
default:
t.Logf("Role: %s,Content: %s", msg.Role, msg.Content)
}

}
}

Expand Down

0 comments on commit a4e53cb

Please sign in to comment.