diff --git a/v3/@claude-flow/providers/src/__tests__/anthropic-cache-usage.test.ts b/v3/@claude-flow/providers/src/__tests__/anthropic-cache-usage.test.ts new file mode 100644 index 0000000000..5a8057cb1e --- /dev/null +++ b/v3/@claude-flow/providers/src/__tests__/anthropic-cache-usage.test.ts @@ -0,0 +1,134 @@ +/** + * #4597 performance/security scan: Anthropic prompt-cache usage was ignored. + * `input_tokens` excludes cache writes/reads, so the old response mapping + * undercounted prompt tokens and over/under-stated cost; cache reads (0.1x) + * and writes (1.25x) need their own accounting. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { AnthropicProvider } from '../anthropic-provider.js'; +import { consoleLogger } from '../base-provider.js'; + +function provider(): AnthropicProvider { + return new AnthropicProvider({ + config: { + provider: 'anthropic', + apiKey: 'test-key', + model: 'claude-3-5-sonnet-latest', + }, + logger: consoleLogger, + }); +} + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Anthropic prompt-cache usage accounting', () => { + it('counts cache writes/reads and applies their pricing multipliers', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ + id: 'msg_cache', + type: 'message', + role: 'assistant', + model: 'claude-3-5-sonnet-latest', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + usage: { + input_tokens: 100, + output_tokens: 50, + cache_creation_input_tokens: 200, + cache_read_input_tokens: 800, + }, + }))); + + const anthropic = provider(); + await anthropic.initialize(); + const response = await anthropic.complete({ + messages: [{ role: 'user', content: 'hi' }], + }); + + expect(response.usage).toMatchObject({ + promptTokens: 1100, + completionTokens: 50, + totalTokens: 1150, + cacheCreationInputTokens: 200, + cacheReadInputTokens: 800, + }); + // (100 + 200*1.25 + 800*0.1) / 1000 * 0.003 = 0.00129 + expect(response.cost?.promptCost).toBeCloseTo(0.00129, 8); + expect(response.cost?.completionCost).toBeCloseTo(0.00075, 8); + expect(response.cost?.totalCost).toBeCloseTo(0.00204, 8); + }); + + it('keeps the existing usage/cost for a response with no cache tokens', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ + id: 'msg_plain', + type: 'message', + role: 'assistant', + model: 'claude-3-5-sonnet-latest', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + usage: { input_tokens: 100, output_tokens: 50 }, + }))); + + const anthropic = provider(); + await anthropic.initialize(); + const response = await anthropic.complete({ + messages: [{ role: 'user', content: 'hi' }], + }); + + expect(response.usage).toEqual({ + promptTokens: 100, + completionTokens: 50, + totalTokens: 150, + }); + expect(response.cost?.promptCost).toBeCloseTo(0.0003, 8); + }); + + it('carries the same accounting through the streaming done event', async () => { + const events = [ + 'data: {"type":"message_start","message":{"usage":{"input_tokens":10,"cache_creation_input_tokens":20,"cache_read_input_tokens":30}}}\n\n', + 'data: {"type":"content_block_delta","delta":{"text":"hi"}}\n\n', + 'data: {"type":"message_delta","usage":{"output_tokens":5}}\n\n', + 'data: {"type":"message_stop"}\n\n', + ]; + vi.stubGlobal('fetch', vi.fn(async () => { + const encoder = new TextEncoder(); + return new Response(new ReadableStream({ + start(controller) { + for (const event of events) controller.enqueue(encoder.encode(event)); + controller.close(); + }, + }), { status: 200 }); + })); + + const anthropic = provider(); + await anthropic.initialize(); + const done: Array<{ usage?: Record; cost?: Record }> = []; + for await (const event of anthropic.streamComplete({ + messages: [{ role: 'user', content: 'hi' }], + stream: true, + })) { + if (event.type === 'done') { + done.push(event as { usage?: Record; cost?: Record }); + } + } + + expect(done).toHaveLength(1); + expect(done[0].usage).toMatchObject({ + promptTokens: 60, + completionTokens: 5, + totalTokens: 65, + cacheCreationInputTokens: 20, + cacheReadInputTokens: 30, + }); + expect(done[0].cost?.promptCost).toBeCloseTo(0.000114, 8); + expect(done[0].cost?.completionCost).toBeCloseTo(0.000075, 8); + }); +}); diff --git a/v3/@claude-flow/providers/src/anthropic-provider.ts b/v3/@claude-flow/providers/src/anthropic-provider.ts index 7f5e0709c4..e71097b2ce 100644 --- a/v3/@claude-flow/providers/src/anthropic-provider.ts +++ b/v3/@claude-flow/providers/src/anthropic-provider.ts @@ -52,6 +52,55 @@ interface AnthropicResponse { usage: { input_tokens: number; output_tokens: number; + cache_creation_input_tokens?: number; + cache_read_input_tokens?: number; + }; +} + +interface AnthropicPricing { + promptCostPer1k: number; + completionCostPer1k: number; + currency: string; +} + +/** + * Anthropic reports cached input separately from input_tokens: + * total input = input_tokens + cache_creation + cache_read. + * Cached writes cost 1.25x base input (5-minute cache), reads 0.1x. + * @internal + */ +export function computeAnthropicUsageCost( + usage: AnthropicResponse['usage'], + pricing: AnthropicPricing, +): { usage: LLMResponse['usage']; cost: NonNullable } { + const cacheCreation = usage.cache_creation_input_tokens ?? 0; + const cacheRead = usage.cache_read_input_tokens ?? 0; + const promptTokens = usage.input_tokens + cacheCreation + cacheRead; + const promptCost = ( + usage.input_tokens + + cacheCreation * 1.25 + + cacheRead * 0.1 + ) / 1000 * pricing.promptCostPer1k; + const completionCost = (usage.output_tokens / 1000) * pricing.completionCostPer1k; + + return { + usage: { + promptTokens, + completionTokens: usage.output_tokens, + totalTokens: promptTokens + usage.output_tokens, + ...(usage.cache_creation_input_tokens !== undefined + ? { cacheCreationInputTokens: usage.cache_creation_input_tokens } + : {}), + ...(usage.cache_read_input_tokens !== undefined + ? { cacheReadInputTokens: usage.cache_read_input_tokens } + : {}), + }, + cost: { + promptCost, + completionCost, + totalCost: promptCost + completionCost, + currency: pricing.currency, + }, }; } @@ -192,6 +241,8 @@ export class AnthropicProvider extends BaseProvider { let buffer = ''; let totalOutputTokens = 0; let inputTokens = 0; + let cacheCreationInputTokens = 0; + let cacheReadInputTokens = 0; while (true) { const { done, value } = await reader.read(); @@ -218,26 +269,29 @@ export class AnthropicProvider extends BaseProvider { totalOutputTokens = event.usage.output_tokens; } else if (event.type === 'message_start' && event.message?.usage) { inputTokens = event.message.usage.input_tokens; + cacheCreationInputTokens = event.message.usage.cache_creation_input_tokens ?? 0; + cacheReadInputTokens = event.message.usage.cache_read_input_tokens ?? 0; } else if (event.type === 'message_stop') { const model = request.model || this.config.model; const pricing = this.capabilities.pricing[model]; - - const promptCost = (inputTokens / 1000) * pricing.promptCostPer1k; - const completionCost = (totalOutputTokens / 1000) * pricing.completionCostPer1k; + const { usage, cost } = computeAnthropicUsageCost( + { + input_tokens: inputTokens, + output_tokens: totalOutputTokens, + ...(cacheCreationInputTokens > 0 + ? { cache_creation_input_tokens: cacheCreationInputTokens } + : {}), + ...(cacheReadInputTokens > 0 + ? { cache_read_input_tokens: cacheReadInputTokens } + : {}), + }, + pricing, + ); yield { type: 'done', - usage: { - promptTokens: inputTokens, - completionTokens: totalOutputTokens, - totalTokens: inputTokens + totalOutputTokens, - }, - cost: { - promptCost, - completionCost, - totalCost: promptCost + completionCost, - currency: 'USD', - }, + usage, + cost, }; } } catch { @@ -385,9 +439,7 @@ export class AnthropicProvider extends BaseProvider { private transformResponse(data: AnthropicResponse, request: LLMRequest): LLMResponse { const model = request.model || this.config.model; const pricing = this.capabilities.pricing[model]; - - const promptCost = (data.usage.input_tokens / 1000) * pricing.promptCostPer1k; - const completionCost = (data.usage.output_tokens / 1000) * pricing.completionCostPer1k; + const { usage, cost } = computeAnthropicUsageCost(data.usage, pricing); // Extract text content const textContent = data.content @@ -413,17 +465,8 @@ export class AnthropicProvider extends BaseProvider { provider: 'anthropic', content: textContent, toolCalls: toolCalls.length > 0 ? toolCalls : undefined, - usage: { - promptTokens: data.usage.input_tokens, - completionTokens: data.usage.output_tokens, - totalTokens: data.usage.input_tokens + data.usage.output_tokens, - }, - cost: { - promptCost, - completionCost, - totalCost: promptCost + completionCost, - currency: 'USD', - }, + usage, + cost, finishReason: data.stop_reason === 'end_turn' ? 'stop' : 'length', }; } diff --git a/v3/@claude-flow/providers/src/types.ts b/v3/@claude-flow/providers/src/types.ts index 98d559a504..be4d17895d 100644 --- a/v3/@claude-flow/providers/src/types.ts +++ b/v3/@claude-flow/providers/src/types.ts @@ -188,6 +188,10 @@ export interface LLMResponse { promptTokens: number; completionTokens: number; totalTokens: number; + /** Anthropic prompt-cache write tokens (billed at a premium). */ + cacheCreationInputTokens?: number; + /** Anthropic prompt-cache read tokens (billed at a discount). */ + cacheReadInputTokens?: number; }; // Cost tracking