diff --git a/src/proxy/server.ts b/src/proxy/server.ts index 99518e9..31b5d0c 100644 --- a/src/proxy/server.ts +++ b/src/proxy/server.ts @@ -74,6 +74,31 @@ import { isTestFixtureModel } from '../stats/test-fixture.js'; const DEFAULT_MAX_TOKENS = 4096; +/** + * Pull token usage out of an accumulated SSE stream. Anthropic reports + * input_tokens in `message_start` (under `message.usage`) and the final + * output_tokens in `message_delta` (top-level `usage`); OpenAI-style chunks + * carry a top-level `usage`. Read both shapes, keeping the last non-zero value. + */ +export function parseStreamUsage(sse: string): { inputTokens: number; outputTokens: number } { + let outputTokens = 0; + let inputTokens = 0; + for (const line of sse.split('\n')) { + if (!line.startsWith('data: ')) continue; + const json = line.slice(6).trim(); + if (json === '[DONE]') continue; + try { + const parsed = JSON.parse(json); + const usages = [parsed.usage, parsed.message?.usage]; + for (const u of usages) { + if (u?.output_tokens) outputTokens = u.output_tokens; + if (u?.input_tokens) inputTokens = u.input_tokens; + } + } catch { /* skip malformed */ } + } + return { inputTokens, outputTokens }; +} + /** * Decide the `max_tokens` the proxy forwards upstream. * @@ -760,19 +785,7 @@ export function createProxy(options: ProxyOptions): http.Server { // Record stats from streaming response if (isStreaming && fullResponse) { // Extract token usage from SSE stream by parsing message_delta events - let outputTokens = 0; - let inputTokens = 0; - // Find all data: lines and parse JSON to extract usage - for (const line of fullResponse.split('\n')) { - if (!line.startsWith('data: ')) continue; - const json = line.slice(6).trim(); - if (json === '[DONE]') continue; - try { - const parsed = JSON.parse(json); - if (parsed.usage?.output_tokens) outputTokens = parsed.usage.output_tokens; - if (parsed.usage?.input_tokens) inputTokens = parsed.usage.input_tokens; - } catch { /* skip malformed */ } - } + const { inputTokens, outputTokens } = parseStreamUsage(fullResponse); if (outputTokens > 0) { trackOutputTokens(finalModel, outputTokens); const latencyMs = Date.now() - requestStartTime; diff --git a/test/local.mjs b/test/local.mjs index 7965157..d89f29c 100644 --- a/test/local.mjs +++ b/test/local.mjs @@ -13195,3 +13195,15 @@ test('modalCreatePriceUsd bills a lifetime above 300 s hourly at any size, CPU i assert.deepEqual(modalCreatePricing('T4', 8, undefined, 10), { priceUsd: 0.05, model: 'flat', flatFloor: true }); assert.deepEqual(modalCreatePricing('T4', 1, 1024, 300), { priceUsd: 0.05, model: 'flat' }, 'genuinely flat-eligible: no floor flag'); }); + +test('proxy streaming usage reads input_tokens from message_start', async () => { + const { parseStreamUsage } = await import('../dist/proxy/server.js'); + const sse = [ + 'event: message_start', + 'data: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":1234,"output_tokens":1}}}', + 'event: message_delta', + 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":56}}', + 'data: [DONE]', + ].join('\n'); + assert.deepEqual(parseStreamUsage(sse), { inputTokens: 1234, outputTokens: 56 }); +});