Skip to content

Commit fc2b180

Browse files
fix(providers): read input and cache usage from Anthropic message_delta (#1667)
Some Anthropic-compatible endpoints report the real input/cache token counts in the cumulative message_delta usage, not in message_start. The stream handler only read output_tokens from message_delta, so prompt usage was underestimated. Non-zero input and cache counts from message_delta now override the message_start values; zero or absent fields keep them. Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>
1 parent 90cb517 commit fc2b180

2 files changed

Lines changed: 82 additions & 2 deletions

File tree

‎internal/providers/anthropic_stream.go‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,26 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req ChatRequest, onC
141141
result.FinishReason = "stop"
142142
}
143143
}
144-
if ev.Usage.OutputTokens > 0 {
144+
if u := ev.Usage; u.OutputTokens > 0 || u.InputTokens > 0 ||
145+
u.CacheCreationInputTokens > 0 || u.CacheReadInputTokens > 0 {
145146
if result.Usage == nil {
146147
result.Usage = &Usage{}
147148
}
148-
result.Usage.CompletionTokens = ev.Usage.OutputTokens
149+
// message_delta usage is cumulative. Some Anthropic-compatible
150+
// endpoints report the real input/cache counts here instead of
151+
// in message_start, so a non-zero value overrides it.
152+
if u.InputTokens > 0 {
153+
result.Usage.PromptTokens = u.InputTokens
154+
}
155+
if u.CacheCreationInputTokens > 0 {
156+
result.Usage.CacheCreationTokens = u.CacheCreationInputTokens
157+
}
158+
if u.CacheReadInputTokens > 0 {
159+
result.Usage.CacheReadTokens = u.CacheReadInputTokens
160+
}
161+
if u.OutputTokens > 0 {
162+
result.Usage.CompletionTokens = u.OutputTokens
163+
}
149164
}
150165
}
151166

‎internal/providers/anthropic_stream_test.go‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,3 +301,68 @@ func TestStreamChat_RedactedThinkingPassback(t *testing.T) {
301301
t.Errorf("data = %v, want encrypted-blob", blocks[0]["data"])
302302
}
303303
}
304+
305+
// TestStreamChat_MessageDeltaUsage verifies that input and cache token counts
306+
// sent in message_delta (cumulative usage, as some Anthropic-compatible
307+
// endpoints do) override the placeholder values from message_start, and that
308+
// absent/zero fields in message_delta do not wipe the earlier counts.
309+
func TestStreamChat_MessageDeltaUsage(t *testing.T) {
310+
run := func(t *testing.T, startUsage, deltaUsage string) *ChatResponse {
311+
t.Helper()
312+
events := []string{
313+
"event: message_start\n",
314+
`data: {"message":{"usage":` + startUsage + `}}` + "\n\n",
315+
316+
"event: content_block_start\n",
317+
`data: {"index":0,"content_block":{"type":"text","text":""}}` + "\n\n",
318+
319+
"event: content_block_delta\n",
320+
`data: {"index":0,"delta":{"type":"text_delta","text":"hi"}}` + "\n\n",
321+
322+
"event: content_block_stop\n",
323+
"data: {}\n\n",
324+
325+
"event: message_delta\n",
326+
`data: {"delta":{"stop_reason":"end_turn"},"usage":` + deltaUsage + `}` + "\n\n",
327+
328+
"event: message_stop\n",
329+
"data: {}\n\n",
330+
}
331+
server := newAnthropicSSEServer(t, events)
332+
p := newTestAnthropicProvider(server.URL)
333+
result, err := p.ChatStream(context.Background(), ChatRequest{
334+
Model: "claude-sonnet-4-5-20250929",
335+
Messages: []Message{{Role: "user", Content: "hello"}},
336+
}, nil)
337+
if err != nil {
338+
t.Fatalf("unexpected error: %v", err)
339+
}
340+
if result == nil || result.Usage == nil {
341+
t.Fatal("expected non-nil result with usage")
342+
}
343+
return result
344+
}
345+
346+
t.Run("delta overrides start", func(t *testing.T) {
347+
r := run(t,
348+
`{"input_tokens":1,"output_tokens":1}`,
349+
`{"input_tokens":500,"cache_creation_input_tokens":40,"cache_read_input_tokens":300,"output_tokens":20}`)
350+
u := r.Usage
351+
if u.PromptTokens != 500 || u.CacheCreationTokens != 40 || u.CacheReadTokens != 300 || u.CompletionTokens != 20 {
352+
t.Errorf("usage = %+v, want prompt=500 cacheCreate=40 cacheRead=300 completion=20", u)
353+
}
354+
if u.TotalTokens != 520 {
355+
t.Errorf("TotalTokens = %d, want 520", u.TotalTokens)
356+
}
357+
})
358+
359+
t.Run("delta without input keeps start", func(t *testing.T) {
360+
r := run(t,
361+
`{"input_tokens":10,"cache_creation_input_tokens":4,"cache_read_input_tokens":6}`,
362+
`{"output_tokens":20}`)
363+
u := r.Usage
364+
if u.PromptTokens != 10 || u.CacheCreationTokens != 4 || u.CacheReadTokens != 6 || u.CompletionTokens != 20 {
365+
t.Errorf("usage = %+v, want prompt=10 cacheCreate=4 cacheRead=6 completion=20", u)
366+
}
367+
})
368+
}

0 commit comments

Comments
 (0)