Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(model-runtime): treat Anthropic message_delta usage as cumulative (#22071)

YuTengjing2aded5f43ff4
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index 4567b59c76e..3ac34e19116 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -727,6 +727,57 @@ describe('createAnthropicCompatibleRuntime', () => {
);
});
+ it('should keep the real output tokens when replaying a non-stream response as a stream', async () => {
+ const messagesCreate = vi.fn().mockResolvedValue({
+ content: [{ text: 'Answer', type: 'text' }],
+ id: 'msg_non_stream',
+ model: 'custom-model',
+ role: 'assistant',
+ stop_reason: 'end_turn',
+ stop_sequence: null,
+ type: 'message',
+ usage: { cache_read_input_tokens: 300, input_tokens: 12, output_tokens: 42 },
+ });
+ const Runtime = createAnthropicCompatibleRuntime({
+ chatCompletion: {
+ handlePayload: (payload) => ({
+ max_tokens: 1024,
+ messages: [{ content: 'Question', role: 'user' }],
+ model: payload.model,
+ }),
+ },
+ customClient: {
+ createClient: () =>
+ ({
+ baseURL: 'https://example.com/anthropic',
+ messages: { create: messagesCreate },
+ }) as unknown as Anthropic,
+ },
+ provider: 'test-provider',
+ });
+ const runtime = new Runtime({ apiKey: 'test-key' });
+
+ const response = await runtime.chat({
+ messages: [{ content: 'Question', role: 'user' }],
+ model: 'custom-model',
+ stream: false,
+ });
+ const text = await response.text();
+ const usageLine = text
+ .split('\n\n')
+ .find((event) => event.includes('event: usage'))
+ ?.split('\n')
+ .find((line) => line.startsWith('data: '));
+
+ expect(JSON.parse(usageLine!.slice('data: '.length))).toMatchObject({
+ inputCacheMissTokens: 12,
+ inputCachedTokens: 300,
+ totalInputTokens: 312,
+ totalOutputTokens: 42,
+ totalTokens: 354,
+ });
+ });
+
it('should strip trailing assistant prefill when a logical id maps to a Claude 5 model', async () => {
// The prefill strip inside handlePayload sees the logical id; when the
// mapping only later resolves to a Claude 4.6+/5 upstream id, chat() must
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index cc5a48f32ec..29efdeaa734 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -754,7 +754,8 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
cache_creation_input_tokens: message.usage?.cache_creation_input_tokens ?? null,
cache_read_input_tokens: message.usage?.cache_read_input_tokens ?? null,
input_tokens: message.usage?.input_tokens ?? null,
- output_tokens: 0,
+ // `message_delta.usage` is cumulative, so it repeats the full output count.
+ output_tokens: message.usage?.output_tokens ?? 0,
server_tool_use: message.usage?.server_tool_use ?? null,
},
} satisfies Anthropic.MessageStreamEvent);
diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.ts
index 5f6cbcda0d7..98cffec2cfe 100644
--- a/packages/model-runtime/src/core/streams/anthropic.test.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts
@@ -247,7 +247,7 @@ describe('AnthropicStream', () => {
'id: msg_017aTuY86wNxth5TE544yqJq',
'event: usage',
- 'data: {"inputCacheMissTokens":457,"totalInputTokens":457,"totalOutputTokens":84,"totalTokens":541}\n',
+ 'data: {"inputCacheMissTokens":457,"totalInputTokens":457,"totalOutputTokens":83,"totalTokens":540}\n',
].map((item) => `${item}\n`),
);
@@ -405,7 +405,7 @@ describe('AnthropicStream', () => {
'id: msg_0175ryA67RbGrnRrGBXFQEYK',
'event: usage',
- 'data: {"inputCacheMissTokens":485,"totalInputTokens":485,"totalOutputTokens":154,"totalTokens":639}\n',
+ 'data: {"inputCacheMissTokens":485,"totalInputTokens":485,"totalOutputTokens":150,"totalTokens":635}\n',
'id: msg_0175ryA67RbGrnRrGBXFQEYK',
'event: stop',
'data: "message_stop"\n',
@@ -492,7 +492,7 @@ describe('AnthropicStream', () => {
'data: "end_turn"\n',
'id: msg_01Vxc4yQTEjkDSba3N3BMbH8',
'event: usage',
- 'data: {"inputCacheMissTokens":6,"inputCachedTokens":17918,"inputWriteCacheTokens":457,"totalInputTokens":18381,"totalOutputTokens":3224,"totalTokens":21605}\n',
+ 'data: {"inputCacheMissTokens":6,"inputCachedTokens":17918,"inputWriteCacheTokens":457,"totalInputTokens":18381,"totalOutputTokens":3222,"totalTokens":21603}\n',
'id: msg_01Vxc4yQTEjkDSba3N3BMbH8',
'event: stop',
@@ -623,7 +623,7 @@ describe('AnthropicStream', () => {
'data: "end_turn"\n',
'id: msg_01MNsLe7n1uVLtu6W8rCFujD',
'event: usage',
- 'data: {"inputCacheMissTokens":46,"inputCachedTokens":0,"totalInputTokens":46,"totalOutputTokens":365,"totalTokens":411}\n',
+ 'data: {"inputCacheMissTokens":46,"inputCachedTokens":0,"totalInputTokens":46,"totalOutputTokens":354,"totalTokens":400}\n',
'id: msg_01MNsLe7n1uVLtu6W8rCFujD',
'event: stop',
'data: "message_stop"\n',
@@ -783,7 +783,7 @@ describe('AnthropicStream', () => {
'data: "end_turn"\n',
'id: msg_019q32esPvu3TftzZnL6JPys',
'event: usage',
- 'data: {"inputCacheMissTokens":92,"inputCachedTokens":0,"totalInputTokens":92,"totalOutputTokens":263,"totalTokens":355}\n',
+ 'data: {"inputCacheMissTokens":92,"inputCachedTokens":0,"totalInputTokens":92,"totalOutputTokens":259,"totalTokens":351}\n',
'id: msg_019q32esPvu3TftzZnL6JPys',
'event: stop',
'data: "message_stop"\n',
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
index 6a0fbd2a06e..865b19298db 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
@@ -37,7 +37,7 @@ describe('convertAnthropicUsage', () => {
});
});
- it('should accumulate output tokens on message_delta', () => {
+ it('should treat message_delta output tokens as cumulative, not additive', () => {
const previousUsage = {
inputCacheMissTokens: 100,
inputCachedTokens: 10,
@@ -63,8 +63,276 @@ describe('convertAnthropicUsage', () => {
inputCachedTokens: 10,
inputWriteCacheTokens: 20,
totalInputTokens: 130,
- totalOutputTokens: 13,
- totalTokens: 143,
+ totalOutputTokens: 8,
+ totalTokens: 138,
+ });
+ });
+
+ /**
+ * Replays the usage-bearing events of real streams, one per relay shape.
+ */
+ describe('relay event shapes', () => {
+ const replay = (
+ startUsage: Record<string, unknown>,
+ deltaUsage: Record<string, unknown> | null,
+ ) => {
+ const start = convertAnthropicUsage({
+ message: { id: 'msg', usage: startUsage },
+ type: 'message_start',
+ } as unknown as Anthropic.MessageStreamEvent);
+
+ return convertAnthropicUsage(
+ {
+ delta: { stop_reason: 'end_turn' },
+ type: 'message_delta',
+ usage: deltaUsage,
+ } as unknown as Anthropic.MessageStreamEvent,
+ start,
+ );
+ };
+
+ it('native Anthropic / Bedrock: input and cache on start, cumulative output on delta', () => {
+ expect(
+ replay(
+ {
+ cache_creation_input_tokens: 2048,
+ cache_read_input_tokens: 4096,
+ input_tokens: 25,
+ output_tokens: 1,
+ },
+ { output_tokens: 312 },
+ ),
+ ).toEqual({
+ inputCacheMissTokens: 25,
+ inputCachedTokens: 4096,
+ inputWriteCacheTokens: 2048,
+ totalInputTokens: 6169,
+ totalOutputTokens: 312,
+ totalTokens: 6481,
+ });
+ });
+
+ it('native Anthropic: a delta repeating the input and cache fields changes nothing else', () => {
+ expect(
+ replay(
+ { cache_read_input_tokens: 4096, input_tokens: 25, output_tokens: 1 },
+ {
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 4096,
+ input_tokens: 25,
+ output_tokens: 312,
+ },
+ ),
+ ).toEqual({
+ inputCacheMissTokens: 25,
+ inputCachedTokens: 4096,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 4121,
+ totalOutputTokens: 312,
+ totalTokens: 4433,
+ });
+ });
+
+ it('Vercel AI Gateway cache write: start is 0/0, full usage arrives on the delta', () => {
+ expect(
+ replay(
+ { input_tokens: 0, output_tokens: 0 },
+ { cache_creation_input_tokens: 58_802, input_tokens: 17, output_tokens: 6 },
+ ),
+ ).toEqual({
+ inputCacheMissTokens: 17,
+ inputCachedTokens: undefined,
+ inputWriteCacheTokens: 58_802,
+ totalInputTokens: 58_819,
+ totalOutputTokens: 6,
+ totalTokens: 58_825,
+ });
+ });
+
+ it('Vercel AI Gateway cache hit: start is 0/0, full usage arrives on the delta', () => {
+ expect(
+ replay(
+ { input_tokens: 0, output_tokens: 0 },
+ { cache_read_input_tokens: 58_802, input_tokens: 17, output_tokens: 6 },
+ ),
+ ).toEqual({
+ inputCacheMissTokens: 17,
+ inputCachedTokens: 58_802,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 58_819,
+ totalOutputTokens: 6,
+ totalTokens: 58_825,
+ });
+ });
+
+ it('OpenRouter: start and delta repeat the same usage without doubling output', () => {
+ const usage = { cache_creation_input_tokens: 8002, input_tokens: 17, output_tokens: 6 };
+
+ expect(replay(usage, usage)).toEqual({
+ inputCacheMissTokens: 17,
+ inputCachedTokens: undefined,
+ inputWriteCacheTokens: 8002,
+ totalInputTokens: 8019,
+ totalOutputTokens: 6,
+ totalTokens: 8025,
+ });
+ });
+
+ it('OpenRouter cache hit: start and delta repeat the same usage', () => {
+ const usage = { cache_read_input_tokens: 8002, input_tokens: 17, output_tokens: 6 };
+
+ expect(replay(usage, usage)).toMatchObject({
+ inputCacheMissTokens: 17,
+ inputCachedTokens: 8002,
+ totalInputTokens: 8019,
+ totalOutputTokens: 6,
+ });
+ });
+
+ it('MiniMax: start is 0/0, input and cache read arrive on the delta', () => {
+ // Captured from api.minimax.io/anthropic, model MiniMax-M3, 2026-11-01.
+ expect(
+ replay(
+ { input_tokens: 0, output_tokens: 0, service_tier: 'standard' },
+ {
+ cache_read_input_tokens: 128,
+ input_tokens: 3650,
+ output_tokens: 5,
+ service_tier: 'standard',
+ },
+ ),
+ ).toEqual({
+ inputCacheMissTokens: 3650,
+ inputCachedTokens: 128,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 3778,
+ totalOutputTokens: 5,
+ totalTokens: 3783,
+ });
+ });
+
+ it('MiniMax: a start carrying only cache read is completed by the delta input', () => {
+ // Production rows recorded input == cache read: the start held cache read with zero input.
+ expect(
+ replay(
+ { cache_read_input_tokens: 18_203, input_tokens: 0, output_tokens: 0 },
+ { cache_read_input_tokens: 18_203, input_tokens: 1, output_tokens: 36 },
+ ),
+ ).toMatchObject({
+ inputCacheMissTokens: 1,
+ inputCachedTokens: 18_203,
+ totalInputTokens: 18_204,
+ totalOutputTokens: 36,
+ });
+ });
+
+ it('AiHubMix DeepSeek: the terminal delta input replaces the start estimate', () => {
+ // Captured from aihubmix.com/v1/messages, model deepseek-v4-pro, 2026-11-01.
+ expect(
+ replay(
+ {
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ input_tokens: 404,
+ output_tokens: 0,
+ },
+ {
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ input_tokens: 291,
+ output_tokens: 64,
+ },
+ ),
+ ).toMatchObject({
+ inputCacheMissTokens: 291,
+ totalInputTokens: 291,
+ totalOutputTokens: 64,
+ totalTokens: 355,
+ });
+ });
+
+ it('keeps the start snapshot when a delta reports zero input and cache', () => {
+ expect(
+ replay(
+ { cache_read_input_tokens: 4096, input_tokens: 25, output_tokens: 1 },
+ { cache_read_input_tokens: 0, input_tokens: 0, output_tokens: 312 },
+ ),
+ ).toMatchObject({
+ inputCacheMissTokens: 25,
+ inputCachedTokens: 4096,
+ totalInputTokens: 4121,
+ totalOutputTokens: 312,
+ });
+ });
+
+ it('keeps the start output when a delta reports zero output', () => {
+ expect(
+ replay({ input_tokens: 12, output_tokens: 6 }, { input_tokens: 12, output_tokens: 0 }),
+ ).toMatchObject({
+ totalInputTokens: 12,
+ totalOutputTokens: 6,
+ totalTokens: 18,
+ });
+ });
+
+ it('keeps the start snapshot when the delta reports only a zero cache field', () => {
+ expect(
+ replay(
+ { cache_read_input_tokens: 4096, input_tokens: 25, output_tokens: 1 },
+ { cache_read_input_tokens: 0, output_tokens: 312 },
+ ),
+ ).toMatchObject({
+ inputCacheMissTokens: 25,
+ inputCachedTokens: 4096,
+ totalInputTokens: 4121,
+ totalOutputTokens: 312,
+ });
+ });
+
+ it('lets a terminal zero input correct a start estimate when cache fields are reported', () => {
+ expect(
+ replay(
+ { cache_read_input_tokens: 0, input_tokens: 404, output_tokens: 0 },
+ { cache_read_input_tokens: 400, input_tokens: 0, output_tokens: 64 },
+ ),
+ ).toMatchObject({
+ inputCacheMissTokens: 0,
+ inputCachedTokens: 400,
+ totalInputTokens: 400,
+ totalOutputTokens: 64,
+ });
+ });
+
+ it('prices the Vercel cache write from the delta usage', () => {
+ const start = convertAnthropicUsage({
+ message: { id: 'msg', usage: { input_tokens: 0, output_tokens: 0 } },
+ type: 'message_start',
+ } as unknown as Anthropic.MessageStreamEvent);
+ const usage = convertAnthropicUsage(
+ {
+ delta: { stop_reason: 'end_turn' },
+ type: 'message_delta',
+ usage: { cache_creation_input_tokens: 58_802, input_tokens: 17, output_tokens: 6 },
+ } as unknown as Anthropic.MessageStreamEvent,
+ start,
+ {
+ pricing: {
+ units: [
+ { name: 'textInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 15, strategy: 'fixed', unit: 'millionTokens' },
+ {
+ lookup: { prices: { '5m': 3.75 }, pricingParams: ['ttl'] },
+ name: 'textInput_cacheWrite',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ },
+ } as any,
+ );
+
+ // 17 * 3 + 58,802 * 3.75 + 6 * 15 per million tokens
+ expect(usage?.cost).toBeCloseTo(0.220_648_5, 4);
});
});
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.ts b/packages/model-runtime/src/core/usageConverters/anthropic.ts
index 6f1169c3660..5a190e354a7 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.ts
@@ -30,19 +30,64 @@ export const buildAnthropicInitialUsage = (
} satisfies ModelUsage;
};
+/** A field the delta reports replaces the earlier value, as the official SDK's MessageStream does. */
+const pickReported = (previous: number | undefined, reported: number | null | undefined) =>
+ typeof reported === 'number' ? reported : previous;
+
+/**
+ * `message_delta.usage` is a cumulative snapshot, not an increment
+ * (https://platform.claude.com/docs/en/build-with-claude/streaming), and the official SDK's
+ * MessageStream overwrites the snapshot with it. Relays differ in where the full usage lives:
+ *
+ * - Native Anthropic / Bedrock: input and cache on `message_start`; the final delta repeats them
+ * (or omits them) and carries the cumulative output.
+ * - Vercel AI Gateway and MiniMax: `message_start` reports 0/0 and only the final delta carries
+ * input, cache and output (https://github.com/vercel/ai/issues/17326).
+ * - OpenRouter: both events carry the same full usage, so adding output double counts it.
+ *
+ * Two zeros are treated as "not counted here" instead of a correction, so they cannot erase a
+ * value `message_start` already reported: an output of 0 (cumulative output never shrinks), and a
+ * delta whose input and cache fields are all 0.
+ */
const mergeDeltaUsage = (
previousUsage: ModelUsage | undefined,
- usage: Anthropic.MessageDeltaUsage | null | undefined,
+ deltaUsage: Anthropic.MessageDeltaUsage | null | undefined,
): ModelUsage | undefined => {
- const deltaOutputTokens = usage?.output_tokens || 0;
+ const usage: Partial<Anthropic.MessageDeltaUsage> = deltaUsage ?? {};
+ const reportsInput =
+ typeof usage.input_tokens === 'number' ||
+ typeof usage.cache_read_input_tokens === 'number' ||
+ typeof usage.cache_creation_input_tokens === 'number';
+ const reportedInputTokens =
+ (usage.input_tokens || 0) +
+ (usage.cache_read_input_tokens || 0) +
+ (usage.cache_creation_input_tokens || 0);
- if (!previousUsage && deltaOutputTokens === 0) {
+ if (!previousUsage && !reportsInput && !usage.output_tokens) {
return undefined;
}
const base: ModelUsage = previousUsage ? { ...previousUsage } : {};
- const totalOutputTokens = (previousUsage?.totalOutputTokens || 0) + deltaOutputTokens;
- const totalInputTokens = previousUsage?.totalInputTokens || 0;
+ const totalOutputTokens = usage.output_tokens || previousUsage?.totalOutputTokens || 0;
+
+ if (reportsInput && (reportedInputTokens > 0 || !previousUsage?.totalInputTokens)) {
+ const initial = buildAnthropicInitialUsage({
+ cache_creation_input_tokens:
+ pickReported(previousUsage?.inputWriteCacheTokens, usage.cache_creation_input_tokens) ??
+ null,
+ cache_read_input_tokens:
+ pickReported(previousUsage?.inputCachedTokens, usage.cache_read_input_tokens) ?? null,
+ input_tokens: pickReported(previousUsage?.inputCacheMissTokens, usage.input_tokens) || 0,
+ output_tokens: totalOutputTokens,
+ } as Anthropic.Messages.Usage)!;
+
+ base.inputCacheMissTokens = initial.inputCacheMissTokens;
+ base.inputCachedTokens = initial.inputCachedTokens;
+ base.inputWriteCacheTokens = initial.inputWriteCacheTokens;
+ base.totalInputTokens = initial.totalInputTokens;
+ }
+
+ const totalInputTokens = base.totalInputTokens || 0;
const totalTokens = totalInputTokens + totalOutputTokens;
base.totalInputTokens = totalInputTokens;