Repository navigation
fix(ai-anthropic): keep the input usage when a stream fails after message_start #1793
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AlemTuzlak
merged 5 commits into
TanStack:main
from
ktrz:fix/anthropic-stream-failure-usage
Oct 22, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
82e3903
fix(ai-anthropic): keep the input usage when a stream fails after mes…
ktrz 9cfa013
docs(ai-anthropic): say that a stream that fails mid-way reports its …
ktrz 6d5b0d6
test(e2e): cover the usage on an Anthropic stream that fails after me…
ktrz a5c9cf1
Merge commit 'fa2a291f5526f6dec9a91fe5b71de15dfaf59ec7' into HEAD
AlemTuzlak 945457d
Merge main into fix/anthropic-stream-failure-usage
AlemTuzlak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@tanstack/ai-anthropic': patch | ||
| --- | ||
|
|
||
| Report the input token usage when a streamed response fails after its first event. A dropped connection or an Anthropic `error` event in the stream ended in a `RUN_ERROR` with no `usage`. Anthropic bills the input tokens of that call, so this `RUN_ERROR` now carries the `usage` that `message_start` reported. The output count is the one from `message_start`, so it can be lower than the real output count. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
packages/ai-anthropic/tests/stream-failure-usage-wire.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { resolveDebugOption } from '@tanstack/ai/adapter-internals' | ||
| import { createAnthropicChat } from '../src/adapters/text' | ||
| import type { StreamChunk } from '@tanstack/ai' | ||
|
|
||
| const model = 'claude-haiku-4-5' | ||
|
|
||
| const sse = (events: Array<{ type: string }>) => | ||
| new Response( | ||
| events | ||
| .map( | ||
| (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`, | ||
| ) | ||
| .join(''), | ||
| { headers: { 'content-type': 'text/event-stream' } }, | ||
| ) | ||
|
|
||
| describe('Anthropic adapter on a stream that fails mid-way', () => { | ||
| it('reports the message_start usage on the RUN_ERROR of an SSE error event (#1735)', async () => { | ||
| const adapter = createAnthropicChat(model, 'test-key', { | ||
| maxRetries: 0, | ||
| fetch: async () => | ||
| sse([ | ||
| { | ||
| type: 'message_start', | ||
| message: { | ||
| id: 'msg_1', | ||
| type: 'message', | ||
| role: 'assistant', | ||
| model, | ||
| content: [], | ||
| stop_reason: null, | ||
| stop_sequence: null, | ||
| usage: { input_tokens: 18, output_tokens: 1 }, | ||
| }, | ||
| } as { type: string }, | ||
| { | ||
| type: 'content_block_start', | ||
| index: 0, | ||
| content_block: { type: 'text', text: '' }, | ||
| } as { type: string }, | ||
| { | ||
| type: 'content_block_delta', | ||
| index: 0, | ||
| delta: { type: 'text_delta', text: 'One, two' }, | ||
| } as { type: string }, | ||
| { | ||
| type: 'error', | ||
| error: { type: 'overloaded_error', message: 'Overloaded' }, | ||
| } as { type: string }, | ||
| ]), | ||
| }) | ||
| const chunks: Array<StreamChunk> = [] | ||
| for await (const chunk of adapter.chatStream({ | ||
| logger: resolveDebugOption(false), | ||
| model, | ||
| threadId: 'thread-1', | ||
| messages: [{ role: 'user', content: 'Count to thirty' }], | ||
| })) { | ||
| chunks.push(chunk) | ||
| } | ||
|
|
||
| const error = chunks.find((chunk) => chunk.type === 'RUN_ERROR') | ||
| expect(error?.message).toContain('Overloaded') | ||
| expect(error).toMatchObject({ | ||
| usage: { promptTokens: 18, completionTokens: 1, totalTokens: 19 }, | ||
| }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| { | ||
| "fixtures": [ | ||
| { | ||
| "match": { "userMessage": "[stream-failure-usage] count to thirty" }, | ||
| "response": { | ||
| "content": "One, two, three, four, five, six, seven, eight, nine, ten", | ||
| "usage": { "input_tokens": 18, "output_tokens": 1 } | ||
| }, | ||
| "chunkSize": 4, | ||
| "latency": 20, | ||
| "truncateAfterChunks": 4 | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
testing/e2e/src/routes/api.anthropic-stream-failure-usage.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { createFileRoute } from '@tanstack/react-router' | ||
| import { chat } from '@tanstack/ai' | ||
| import { createAnthropicChat } from '@tanstack/ai-anthropic' | ||
|
|
||
| const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010' | ||
| const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key' | ||
|
|
||
| /** | ||
| * Streams one Anthropic chat against the aimock fixture in | ||
| * `fixtures/stream-failure-usage`. aimock sends `message_start`, the start of | ||
| * a text block and one text delta, then drops the connection. Returns the | ||
| * `RUN_ERROR` that `chat()` yields (issue #1735). | ||
| */ | ||
| export const Route = createFileRoute('/api/anthropic-stream-failure-usage')({ | ||
| server: { | ||
| handlers: { | ||
| POST: async () => { | ||
| const adapter = createAnthropicChat('claude-haiku-4-5', DUMMY_KEY, { | ||
| baseURL: LLMOCK_DEFAULT_BASE, | ||
| }) | ||
|
|
||
| let runError: Record<string, unknown> | undefined | ||
| try { | ||
| for await (const chunk of chat({ | ||
| adapter, | ||
| threadId: 'stream-failure-usage', | ||
| messages: [ | ||
| { | ||
| role: 'user', | ||
| content: '[stream-failure-usage] count to thirty', | ||
| }, | ||
| ], | ||
| })) { | ||
| if (chunk.type === 'RUN_ERROR') { | ||
| runError = { usage: chunk.usage } | ||
| } | ||
| } | ||
| } catch (error) { | ||
| return Response.json({ | ||
| ok: false, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }) | ||
| } | ||
|
|
||
| return Response.json({ ok: true, runError }) | ||
| }, | ||
| }, | ||
| }, | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Limit the RUN_ERROR usage claim to failures before the closing delta.
If the stream fails after a terminal
message_delta,RUN_FINISHEDalready carries usage. The laterRUN_ERRORhas no usage. Line 183 says that any stream failure after the stream starts putsmessage_startusage onRUN_ERROR. Qualify the sentence so readers do not look for usage on the wrong chunk.🤖 Prompt for AI Agents