Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

anthropic: add InputTokens to streaming response (#13934)

Aleksandr Vukmirovich71896485fd85
diff --git a/anthropic/anthropic.go b/anthropic/anthropic.go
old mode 100644
new mode 100755
index 9cb2c75c4..f5799fc1e
--- a/anthropic/anthropic.go
+++ b/anthropic/anthropic.go
@@ -211,6 +211,7 @@ type MessageDelta struct {
// DeltaUsage contains cumulative token usage
type DeltaUsage struct {
+ InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
}
@@ -721,6 +722,7 @@ func (c *StreamConverter) Process(r api.ChatResponse) []StreamEvent {
})
}
+ c.inputTokens = r.Metrics.PromptEvalCount
c.outputTokens = r.Metrics.EvalCount
stopReason := mapStopReason(r.DoneReason, len(c.toolCallsSent) > 0)
@@ -732,6 +734,7 @@ func (c *StreamConverter) Process(r api.ChatResponse) []StreamEvent {
StopReason: stopReason,
},
Usage: DeltaUsage{
+ InputTokens: c.inputTokens,
OutputTokens: c.outputTokens,
},
},
diff --git a/anthropic/anthropic_test.go b/anthropic/anthropic_test.go
old mode 100644
new mode 100755
index 117d183c9..1c2a4a868
--- a/anthropic/anthropic_test.go
+++ b/anthropic/anthropic_test.go
@@ -642,7 +642,7 @@ func TestStreamConverter_Basic(t *testing.T) {
},
Done: true,
DoneReason: "stop",
- Metrics: api.Metrics{EvalCount: 5},
+ Metrics: api.Metrics{PromptEvalCount: 10, EvalCount: 5},
}
events2 := conv.Process(resp2)
@@ -650,6 +650,24 @@ func TestStreamConverter_Basic(t *testing.T) {
// Should have content_block_delta, content_block_stop, message_delta, message_stop
hasStop := false
for _, e := range events2 {
+ if e.Event == "message_delta" {
+ if data, ok := e.Data.(MessageDeltaEvent); ok {
+ if data.Type != "message_delta" {
+ t.Errorf("unexpected data type: %+v", data)
+ }
+
+ if data.Delta.StopReason != "end_turn" {
+ t.Errorf("unexpected stop reason: %+v", data.Delta.StopReason)
+ }
+
+ if data.Usage.InputTokens != 10 || data.Usage.OutputTokens != 5 {
+ t.Errorf("unexpected usage: %+v", data.Usage)
+ }
+ } else {
+ t.Errorf("unexpected data: %+v", e.Data)
+ }
+ }
+
if e.Event == "message_stop" {
hasStop = true
}