fix(providers): account for Anthropic prompt-cache tokens (#4673)

* fix(providers): account for Anthropic prompt-cache tokens

Anthropic reports input_tokens separately from cache_creation_input_tokens and cache_read_input_tokens, with cache writes priced at 1.25x and reads at 0.1x base input. The provider ignored both fields: promptTokens undercounted every cache hit/write and promptCost used the full base rate for all input (#4597 performance/security scan).\n\nAdd optional cache fields to LLMResponse.usage, compute total prompt tokens from all three, apply the cache multipliers in cost accounting, and carry the same fields through the streaming done event. Non-cached responses are unchanged.\n\nTwo tests mock the Anthropic REST/SSE responses: a non-streamed response (100 ordinary + 200 write + 800 read -> 1100 prompt tokens, .00129 prompt cost) and a streamed response (60 prompt, 5 output, .000114 prompt). Baseline returns 100/10 prompt tokens and omits the cache fields; candidate passes 2/2. Full provider unit tests pass (the integration suite is skipped locally: missing dotenv); tsc only reports the pre-existing missing @ruvector/ruvllm.

* test(providers): keep non-cached Anthropic usage unchanged

Add a compatibility control proving the new cache accounting leaves a response with no cache tokens byte-identical: 100 prompt, 50 completion, 150 total, \.0003 prompt cost.
This commit is contained in:
ordinary being authored and GitHub committed 2026-11-04 09:04:55 -06:00
1 parent cc665b12f6
commit d45db2597d
3 files changed
+209 -28

No files matched your search

@@ -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<string, number>; cost?: Record<string, number> }> = [];
for await (const event of anthropic.streamComplete({
messages: [{ role: 'user', content: 'hi' }],
stream: true,
})) {
if (event.type === 'done') {
done.push(event as { usage?: Record<string, number>; cost?: Record<string, number> });
}
}
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);
});
});
@@ -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<LLMResponse['cost']> } {
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',
};
}
+4
View File
@@ -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