Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix prime inference anthropic prompt caching (#478)

kt58c4b7c59609
diff --git a/packages/ai/CHANGELOG.md b/packages/ai/CHANGELOG.md
index db27f93a0a..13658340c7 100644
--- a/packages/ai/CHANGELOG.md
+++ b/packages/ai/CHANGELOG.md
@@ -3,6 +3,7 @@
## [Unreleased]
- Added Kimi K3 to the Prime Inference and OpenRouter model catalogs with multimodal input and mandatory max reasoning.
+- Fixed prompt caching and retention-aware cache-cost estimates for Anthropic models routed through Prime Inference ([ENG-4723](https://linear.app/primeintellect/issue/ENG-4723)).
## [0.3.1] - 2026-07-15
diff --git a/packages/ai/scripts/generate-models.ts b/packages/ai/scripts/generate-models.ts
index f1b7c5252c..e48a037a3f 100644
--- a/packages/ai/scripts/generate-models.ts
+++ b/packages/ai/scripts/generate-models.ts
@@ -4,6 +4,7 @@ import { readFileSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
+import { getAnthropicCacheCosts } from "../src/cache-pricing.js";
import {
CLOUDFLARE_AI_GATEWAY_ANTHROPIC_BASE_URL,
CLOUDFLARE_AI_GATEWAY_COMPAT_BASE_URL,
@@ -116,7 +117,6 @@ const PRIME_INFERENCE_COMPAT: OpenAICompletionsCompat = {
maxTokensField: "max_tokens",
supportsStrictMode: false,
};
-
interface PrimeInferenceCatalogEntry {
id: string;
input: number;
@@ -415,6 +415,12 @@ function getPrimeInferenceHeaders(apiKey: string | undefined, teamId: string | u
return Object.keys(headers).length > 0 ? headers : undefined;
}
+function getPrimeInferenceCacheCosts(modelId: string, inputCost: number): { cacheRead: number; cacheWrite: number } {
+ return modelId.toLowerCase().startsWith("anthropic/")
+ ? getAnthropicCacheCosts(inputCost, "5m")
+ : { cacheRead: 0, cacheWrite: 0 };
+}
+
function getExistingPrimeInferenceModels(): Model<"openai-completions">[] {
const models = EXISTING_MODELS["prime-inference"] as unknown as Record<string, Model<"openai-completions">>;
return Object.values(models)
@@ -422,7 +428,10 @@ function getExistingPrimeInferenceModels(): Model<"openai-completions">[] {
.map((model) => ({
...model,
input: [...model.input],
- cost: { ...model.cost },
+ cost: {
+ ...model.cost,
+ ...getPrimeInferenceCacheCosts(model.id, model.cost.input),
+ },
...(model.compat ? { compat: { ...model.compat } } : {}),
...(model.thinkingLevelMap ? { thinkingLevelMap: { ...model.thinkingLevelMap } } : {}),
...(model.headers ? { headers: { ...model.headers } } : {}),
@@ -672,6 +681,7 @@ function createPrimeInferenceModel(
openRouter: PrimeInferenceOpenRouterMetadata | undefined,
): Model<"openai-completions"> {
const vision = override?.vision ?? openRouter?.vision ?? false;
+ const cacheCosts = getPrimeInferenceCacheCosts(entry.id, entry.input);
const contextWindow =
entry.contextWindow ??
override?.contextWindow ??
@@ -695,8 +705,7 @@ function createPrimeInferenceModel(
cost: {
input: entry.input,
output: entry.output,
- cacheRead: 0,
- cacheWrite: 0,
+ ...cacheCosts,
},
contextWindow,
maxTokens,
diff --git a/packages/ai/src/cache-pricing.ts b/packages/ai/src/cache-pricing.ts
new file mode 100644
index 0000000000..0def44a18e
--- /dev/null
+++ b/packages/ai/src/cache-pricing.ts
@@ -0,0 +1,63 @@
+import type { Api, Model } from "./types.js";
+
+export type AnthropicCacheDuration = "5m" | "1h";
+
+export interface AnthropicCacheCreationUsage {
+ ephemeral_5m_input_tokens: number;
+ ephemeral_1h_input_tokens: number;
+}
+
+const ANTHROPIC_CACHE_READ_COST_MULTIPLIER = 0.1;
+const ANTHROPIC_FIVE_MINUTE_CACHE_WRITE_COST_MULTIPLIER = 1.25;
+const ANTHROPIC_ONE_HOUR_CACHE_WRITE_COST_MULTIPLIER = 2;
+
+export function hasStandardAnthropicCachePricing<TApi extends Api>(model: Model<TApi>): boolean {
+ const modelId = model.id.toLowerCase();
+ const isAnthropicModel =
+ model.provider === "anthropic" || modelId.startsWith("anthropic/") || modelId.startsWith("claude-");
+ if (!isAnthropicModel) {
+ return false;
+ }
+
+ const expectedCacheWriteCost = model.cost.input * ANTHROPIC_FIVE_MINUTE_CACHE_WRITE_COST_MULTIPLIER;
+ const tolerance = Number.EPSILON * Math.max(1, model.cost.cacheWrite, expectedCacheWriteCost);
+ return Math.abs(model.cost.cacheWrite - expectedCacheWriteCost) <= tolerance;
+}
+
+export function getAnthropicCacheCosts(
+ inputCost: number,
+ duration: AnthropicCacheDuration,
+): { cacheRead: number; cacheWrite: number } {
+ return {
+ cacheRead: inputCost * ANTHROPIC_CACHE_READ_COST_MULTIPLIER,
+ cacheWrite:
+ inputCost *
+ (duration === "1h"
+ ? ANTHROPIC_ONE_HOUR_CACHE_WRITE_COST_MULTIPLIER
+ : ANTHROPIC_FIVE_MINUTE_CACHE_WRITE_COST_MULTIPLIER),
+ };
+}
+
+export function getAnthropicCacheWriteCost(
+ inputCost: number,
+ duration: AnthropicCacheDuration,
+ cacheCreation?: AnthropicCacheCreationUsage | null,
+): number {
+ if (!cacheCreation) {
+ return getAnthropicCacheCosts(inputCost, duration).cacheWrite;
+ }
+
+ const fiveMinuteTokens = cacheCreation.ephemeral_5m_input_tokens;
+ const oneHourTokens = cacheCreation.ephemeral_1h_input_tokens;
+ const totalTokens = fiveMinuteTokens + oneHourTokens;
+ if (totalTokens === 0) {
+ return getAnthropicCacheCosts(inputCost, duration).cacheWrite;
+ }
+
+ return (
+ (inputCost *
+ (fiveMinuteTokens * ANTHROPIC_FIVE_MINUTE_CACHE_WRITE_COST_MULTIPLIER +
+ oneHourTokens * ANTHROPIC_ONE_HOUR_CACHE_WRITE_COST_MULTIPLIER)) /
+ totalTokens
+ );
+}
diff --git a/packages/ai/src/models.generated.ts b/packages/ai/src/models.generated.ts
index 6735eebb0a..57c29e558c 100644
--- a/packages/ai/src/models.generated.ts
+++ b/packages/ai/src/models.generated.ts
@@ -14269,8 +14269,8 @@ export const MODELS = {
cost: {
input: 10,
output: 50,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 1,
+ cacheWrite: 12.5,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -14288,8 +14288,8 @@ export const MODELS = {
cost: {
input: 1,
output: 5,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.1,
+ cacheWrite: 1.25,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -14307,8 +14307,8 @@ export const MODELS = {
cost: {
input: 15,
output: 75,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 1.5,
+ cacheWrite: 18.75,
},
contextWindow: 200000,
maxTokens: 32000,
@@ -14325,8 +14325,8 @@ export const MODELS = {
cost: {
input: 5,
output: 25,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -14344,8 +14344,8 @@ export const MODELS = {
cost: {
input: 5,
output: 25,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -14364,8 +14364,8 @@ export const MODELS = {
cost: {
input: 5,
output: 25,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -14384,8 +14384,8 @@ export const MODELS = {
cost: {
input: 5,
output: 25,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -14403,8 +14403,8 @@ export const MODELS = {
cost: {
input: 3,
output: 15,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.3,
+ cacheWrite: 3.75,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -14421,8 +14421,8 @@ export const MODELS = {
cost: {
input: 3,
output: 15,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.3,
+ cacheWrite: 3.75,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -14441,8 +14441,8 @@ export const MODELS = {
cost: {
input: 3,
output: 15,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.3,
+ cacheWrite: 3.75,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -14461,8 +14461,8 @@ export const MODELS = {
cost: {
input: 2,
output: 10,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.2,
+ cacheWrite: 2.5,
},
contextWindow: 1000000,
maxTokens: 128000,
diff --git a/packages/ai/src/models.ts b/packages/ai/src/models.ts
index 2231a89f9b..fc7ba59b49 100644
--- a/packages/ai/src/models.ts
+++ b/packages/ai/src/models.ts
@@ -44,11 +44,19 @@ export function supportsFastMode<TApi extends Api>(model: Model<TApi>): boolean
);
}
-export function calculateCost<TApi extends Api>(model: Model<TApi>, usage: Usage): Usage["cost"] {
+export interface CostOverrides {
+ cacheWrite?: number;
+}
+
+export function calculateCost<TApi extends Api>(
+ model: Model<TApi>,
+ usage: Usage,
+ overrides?: CostOverrides,
+): Usage["cost"] {
usage.cost.input = (model.cost.input / 1000000) * usage.input;
usage.cost.output = (model.cost.output / 1000000) * usage.output;
usage.cost.cacheRead = (model.cost.cacheRead / 1000000) * usage.cacheRead;
- usage.cost.cacheWrite = (model.cost.cacheWrite / 1000000) * usage.cacheWrite;
+ usage.cost.cacheWrite = ((overrides?.cacheWrite ?? model.cost.cacheWrite) / 1000000) * usage.cacheWrite;
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
return usage.cost;
}
diff --git a/packages/ai/src/providers/anthropic.ts b/packages/ai/src/providers/anthropic.ts
index 20c3b416f9..4dcffb03b6 100644
--- a/packages/ai/src/providers/anthropic.ts
+++ b/packages/ai/src/providers/anthropic.ts
@@ -6,6 +6,7 @@ import type {
MessageParam,
RawMessageStreamEvent,
} from "@anthropic-ai/sdk/resources/messages.js";
+import { getAnthropicCacheWriteCost, hasStandardAnthropicCachePricing } from "../cache-pricing.js";
import { getEnvApiKey } from "../env-api-keys.js";
import { calculateCost, clampThinkingLevel } from "../models.js";
import type {
@@ -510,7 +511,13 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
client = created.client;
isOAuth = created.isOAuthToken;
}
- let params = buildParams(model, context, isOAuth, options);
+ const { cacheControl } = getCacheControl(model, options?.cacheRetention);
+ const usesAnthropicCachePricing = hasStandardAnthropicCachePricing(model);
+ let cacheWriteCost =
+ cacheControl && usesAnthropicCachePricing
+ ? getAnthropicCacheWriteCost(model.cost.input, cacheControl.ttl === "1h" ? "1h" : "5m")
+ : undefined;
+ let params = buildParams(model, context, isOAuth, options, cacheControl);
const nextParams = await options?.onPayload?.(params, model);
if (nextParams !== undefined) {
params = nextParams as MessageCreateParamsStreaming;
@@ -540,7 +547,18 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
// Anthropic doesn't provide total_tokens, compute from components
output.usage.totalTokens =
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
- calculateCost(model, output.usage);
+ if (cacheControl && usesAnthropicCachePricing) {
+ cacheWriteCost = getAnthropicCacheWriteCost(
+ model.cost.input,
+ cacheControl.ttl === "1h" ? "1h" : "5m",
+ event.message.usage.cache_creation,
+ );
+ }
+ calculateCost(
+ model,
+ output.usage,
+ cacheWriteCost === undefined ? undefined : { cacheWrite: cacheWriteCost },
+ );
} else if (event.type === "content_block_start") {
if (event.content_block.type === "text") {
const block: Block = {
@@ -685,7 +703,11 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
// Anthropic doesn't provide total_tokens, compute from components
output.usage.totalTokens =
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
- calculateCost(model, output.usage);
+ calculateCost(
+ model,
+ output.usage,
+ cacheWriteCost === undefined ? undefined : { cacheWrite: cacheWriteCost },
+ );
}
}
@@ -934,8 +956,8 @@ function buildParams(
context: Context,
isOAuthToken: boolean,
options?: AnthropicOptions,
+ cacheControl?: CacheControlEphemeral,
): MessageCreateParamsStreaming {
- const { cacheControl } = getCacheControl(model, options?.cacheRetention);
const params: MessageCreateParamsStreaming = {
model: model.id,
messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),
diff --git a/packages/ai/src/providers/openai-completions.ts b/packages/ai/src/providers/openai-completions.ts
index 768ac52ed7..155c5a0703 100644
--- a/packages/ai/src/providers/openai-completions.ts
+++ b/packages/ai/src/providers/openai-completions.ts
@@ -10,6 +10,7 @@ import type {
ChatCompletionSystemMessageParam,
ChatCompletionToolMessageParam,
} from "openai/resources/chat/completions.js";
+import { getAnthropicCacheWriteCost, hasStandardAnthropicCachePricing } from "../cache-pricing.js";
import { getEnvApiKey, getPrimeTeamId } from "../env-api-keys.js";
import { calculateCost, clampThinkingLevel } from "../models.js";
import type {
@@ -138,9 +139,14 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
const compat = getCompat(model);
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
+ const cacheControl = getCompatCacheControl(compat, cacheRetention);
+ const cacheWriteCost =
+ cacheControl && hasStandardAnthropicCachePricing(model)
+ ? getAnthropicCacheWriteCost(model.cost.input, cacheControl.ttl === "1h" ? "1h" : "5m")
+ : undefined;
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);
- let params = buildParams(model, context, options, compat, cacheRetention);
+ let params = buildParams(model, context, options, compat, cacheRetention, cacheControl);
const nextParams = await options?.onPayload?.(params, model);
if (nextParams !== undefined) {
params = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
@@ -270,7 +276,7 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
output.responseModel ||= chunk.model;
}
if (chunk.usage) {
- output.usage = parseChunkUsage(chunk.usage, model);
+ output.usage = parseChunkUsage(chunk.usage, model, cacheWriteCost);
}
const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined;
@@ -279,7 +285,7 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
// Fallback: some providers (e.g., Moonshot) return usage
// in choice.usage instead of the standard chunk.usage
if (!chunk.usage && (choice as any).usage) {
- output.usage = parseChunkUsage((choice as any).usage, model);
+ output.usage = parseChunkUsage((choice as any).usage, model, cacheWriteCost);
}
if (choice.finish_reason) {
@@ -501,9 +507,9 @@ function buildParams(
options?: OpenAICompletionsOptions,
compat: ResolvedOpenAICompletionsCompat = getCompat(model),
cacheRetention: CacheRetention = resolveCacheRetention(options?.cacheRetention),
+ cacheControl: OpenAICompatCacheControl | undefined = getCompatCacheControl(compat, cacheRetention),
) {
const messages = convertMessages(model, context, compat);
- const cacheControl = getCompatCacheControl(compat, cacheRetention);
const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {
model: model.id,
@@ -1004,6 +1010,7 @@ function parseChunkUsage(
prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };
},
model: Model<"openai-completions">,
+ cacheWriteCost?: number,
): AssistantMessage["usage"] {
const promptTokens = rawUsage.prompt_tokens || 0;
const reportedCachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;
@@ -1028,7 +1035,7 @@ function parseChunkUsage(
totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
- calculateCost(model, usage);
+ calculateCost(model, usage, cacheWriteCost === undefined ? undefined : { cacheWrite: cacheWriteCost });
return usage;
}
@@ -1092,7 +1099,9 @@ function detectCompat(model: Model<"openai-completions">): ResolvedOpenAIComplet
const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
const isDeepSeek = provider === "deepseek" || baseUrl.includes("deepseek.com");
- const cacheControlFormat = provider === "openrouter" && model.id.startsWith("anthropic/") ? "anthropic" : undefined;
+ const isAnthropicModel = model.id.startsWith("anthropic/");
+ const cacheControlFormat =
+ isAnthropicModel && (provider === "openrouter" || isPrimeInference) ? "anthropic" : undefined;
return {
supportsStore: !isNonStandard,
diff --git a/packages/ai/test/anthropic-sse-parsing.test.ts b/packages/ai/test/anthropic-sse-parsing.test.ts
index 5bbc7d7293..147eb874d4 100644
--- a/packages/ai/test/anthropic-sse-parsing.test.ts
+++ b/packages/ai/test/anthropic-sse-parsing.test.ts
@@ -78,7 +78,96 @@ function createFakeAnthropicClient(response: Response): Anthropic {
} as unknown as Anthropic;
}
+function createCacheUsageEvents(cacheCreation: {
+ ephemeral_5m_input_tokens: number;
+ ephemeral_1h_input_tokens: number;
+}): Array<{ event: string; data: string }> {
+ const cacheWriteTokens = cacheCreation.ephemeral_5m_input_tokens + cacheCreation.ephemeral_1h_input_tokens;
+ return [
+ {
+ event: "message_start",
+ data: JSON.stringify({
+ type: "message_start",
+ message: {
+ id: "msg_cache_test",
+ usage: {
+ input_tokens: 12,
+ output_tokens: 0,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: cacheWriteTokens,
+ cache_creation: cacheCreation,
+ },
+ },
+ }),
+ },
+ {
+ event: "message_delta",
+ data: JSON.stringify({
+ type: "message_delta",
+ delta: { stop_reason: "end_turn" },
+ usage: {
+ input_tokens: 12,
+ output_tokens: 5,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: cacheWriteTokens,
+ },
+ }),
+ },
+ { event: "message_stop", data: JSON.stringify({ type: "message_stop" }) },
+ ];
+}
+
describe("Anthropic raw SSE parsing", () => {
+ it.each([
+ {
+ name: "five-minute writes",
+ cacheRetention: "short" as const,
+ cacheCreation: { ephemeral_5m_input_tokens: 1000, ephemeral_1h_input_tokens: 0 },
+ expectedCacheWriteCost: 0.00125,
+ },
+ {
+ name: "one-hour writes",
+ cacheRetention: "long" as const,
+ cacheCreation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 1000 },
+ expectedCacheWriteCost: 0.002,
+ },
+ {
+ name: "mixed TTL writes",
+ cacheRetention: "long" as const,
+ cacheCreation: { ephemeral_5m_input_tokens: 250, ephemeral_1h_input_tokens: 750 },
+ expectedCacheWriteCost: 0.0018125,
+ },
+ ])("prices $name from the reported Anthropic usage breakdown", async (testCase) => {
+ const model = getModel("anthropic", "claude-haiku-4-5");
+ const response = createSseResponse(createCacheUsageEvents(testCase.cacheCreation));
+ const result = await streamAnthropic(
+ model,
+ { messages: [{ role: "user", content: "Say hello.", timestamp: Date.now() }] },
+ {
+ client: createFakeAnthropicClient(response),
+ cacheRetention: testCase.cacheRetention,
+ },
+ ).result();
+
+ expect(result.usage.cacheWrite).toBe(1000);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo(testCase.expectedCacheWriteCost);
+ });
+
+ it("preserves configured cache write pricing for non-Anthropic models", async () => {
+ const model = getModel("minimax", "MiniMax-M2.7-highspeed");
+ const response = createSseResponse(
+ createCacheUsageEvents({ ephemeral_5m_input_tokens: 1000, ephemeral_1h_input_tokens: 0 }),
+ );
+ const result = await streamAnthropic(
+ model,
+ { messages: [{ role: "user", content: "Say hello.", timestamp: Date.now() }] },
+ { client: createFakeAnthropicClient(response) },
+ ).result();
+
+ expect(result.usage.cacheWrite).toBe(1000);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((1000 * model.cost.cacheWrite) / 1_000_000);
+ });
+
it("repairs malformed SSE JSON and malformed streamed tool JSON", async () => {
const model = getModel("anthropic", "claude-haiku-4-5");
const context: Context = {
diff --git a/packages/ai/test/openai-completions-cache-control-format.test.ts b/packages/ai/test/openai-completions-cache-control-format.test.ts
index de69d02ac2..f1ff9a5c7b 100644
--- a/packages/ai/test/openai-completions-cache-control-format.test.ts
+++ b/packages/ai/test/openai-completions-cache-control-format.test.ts
@@ -2,7 +2,7 @@ import { Type } from "typebox";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getModel } from "../src/models.js";
import { streamOpenAICompletions } from "../src/providers/openai-completions.js";
-import type { Model } from "../src/types.js";
+import type { AssistantMessage, Model } from "../src/types.js";
interface CacheControl {
type: "ephemeral";
@@ -38,15 +38,19 @@ vi.mock("openai", () => {
completions: {
create: (params: CapturedParams) => {
mockState.lastParams = params;
+ const hasCacheControl = JSON.stringify(params).includes("cache_control");
const stream = {
async *[Symbol.asyncIterator]() {
yield {
id: "chatcmpl-test",
choices: [{ delta: {}, finish_reason: "stop" }],
usage: {
- prompt_tokens: 1,
- completion_tokens: 1,
- prompt_tokens_details: { cached_tokens: 0 },
+ prompt_tokens: 100,
+ completion_tokens: 10,
+ prompt_tokens_details: {
+ cached_tokens: hasCacheControl ? 80 : 0,
+ cache_write_tokens: hasCacheControl ? 80 : 0,
+ },
completion_tokens_details: { reasoning_tokens: 0 },
},
};
@@ -71,13 +75,13 @@ vi.mock("openai", () => {
return { default: FakeOpenAI };
});
-async function capturePayload(
+async function runCompletion(
model: Model<"openai-completions">,
options?: { cacheRetention?: "none" | "short" | "long" },
-): Promise<CapturedParams> {
+): Promise<{ params: CapturedParams; result: AssistantMessage }> {
const timestamp = Date.now();
- await streamOpenAICompletions(
+ const result = await streamOpenAICompletions(
model,
{
systemPrompt: "System prompt",
@@ -99,26 +103,43 @@ async function capturePayload(
throw new Error("Expected payload to be captured");
}
- return mockState.lastParams;
+ return { params: mockState.lastParams, result };
+}
+
+async function capturePayload(
+ model: Model<"openai-completions">,
+ options?: { cacheRetention?: "none" | "short" | "long" },
+): Promise<CapturedParams> {
+ return (await runCompletion(model, options)).params;
}
function getInstructionMessage(params: CapturedParams) {
return params.messages.find((message) => message.role === "system" || message.role === "developer");
}
-function expectAnthropicCacheMarkers(params: CapturedParams): void {
+function expectAnthropicCacheMarkers(
+ params: CapturedParams,
+ expectedCacheControl: CacheControl = { type: "ephemeral" },
+): void {
const instructionMessage = getInstructionMessage(params);
expect(instructionMessage).toBeDefined();
expect(Array.isArray(instructionMessage?.content)).toBe(true);
- expect((instructionMessage?.content as TextPart[])[0]?.cache_control).toEqual({ type: "ephemeral" });
+ expect((instructionMessage?.content as TextPart[])[0]?.cache_control).toEqual(expectedCacheControl);
expect(params.tools).toHaveLength(1);
- expect(params.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" });
+ expect(params.tools?.[0]?.cache_control).toEqual(expectedCacheControl);
const lastMessage = params.messages[params.messages.length - 1];
expect(lastMessage.role).toBe("user");
expect(Array.isArray(lastMessage.content)).toBe(true);
- expect((lastMessage.content as TextPart[])[0]?.cache_control).toEqual({ type: "ephemeral" });
+ expect((lastMessage.content as TextPart[])[0]?.cache_control).toEqual(expectedCacheControl);
+}
+
+function expectNoAnthropicCacheMarkers(params: CapturedParams): void {
+ const instructionMessage = getInstructionMessage(params);
+ expect(Array.isArray(instructionMessage?.content)).toBe(false);
+ expect(params.tools?.[0]?.cache_control).toBeUndefined();
+ expect(typeof params.messages[params.messages.length - 1]?.content).toBe("string");
}
describe("openai-completions cacheControlFormat", () => {
@@ -135,12 +156,7 @@ describe("openai-completions cacheControlFormat", () => {
baseUrl: "https://example.com/v1",
reasoning: true,
input: ["text"],
- cost: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- },
+ cost: { input: 4, output: 12, cacheRead: 0.4, cacheWrite: 9 },
contextWindow: 128000,
maxTokens: 32000,
compat: {
@@ -148,8 +164,9 @@ describe("openai-completions cacheControlFormat", () => {
},
};
- const params = await capturePayload(model);
+ const { params, result } = await runCompletion(model);
expectAnthropicCacheMarkers(params);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.cacheWrite) / 1_000_000);
});
it("preserves Anthropic-style cache markers for OpenRouter Anthropic models", async () => {
@@ -158,6 +175,63 @@ describe("openai-completions cacheControlFormat", () => {
expectAnthropicCacheMarkers(params);
});
+ it("preserves route-specific cache write pricing for Anthropic models", async () => {
+ const model = getModel("openrouter", "anthropic/claude-3-haiku");
+ const { params, result } = await runCompletion(model);
+ expectAnthropicCacheMarkers(params);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.cacheWrite) / 1_000_000);
+ });
+
+ it("applies Anthropic-style cache markers for Prime Inference Anthropic models", async () => {
+ const model = getModel("prime-inference", "anthropic/claude-fable-5");
+ const { params, result } = await runCompletion(model);
+ expectAnthropicCacheMarkers(params);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.input * 1.25) / 1_000_000);
+ });
+
+ it("prices one-hour Prime Inference cache writes at twice the input rate", async () => {
+ const model = getModel("prime-inference", "anthropic/claude-fable-5");
+ const { params, result } = await runCompletion(model, { cacheRetention: "long" });
+ expectAnthropicCacheMarkers(params, { type: "ephemeral", ttl: "1h" });
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.input * 2) / 1_000_000);
+ });
+
+ it("prices one-hour OpenRouter Anthropic cache writes at twice the input rate", async () => {
+ const model = getModel("openrouter", "anthropic/claude-sonnet-4");
+ const { params, result } = await runCompletion(model, { cacheRetention: "long" });
+ expectAnthropicCacheMarkers(params, { type: "ephemeral", ttl: "1h" });
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.input * 2) / 1_000_000);
+ });
+
+ it("uses five-minute pricing when a model cannot apply long retention", async () => {
+ const model: Model<"openai-completions"> = {
+ id: "custom-anthropic-proxy",
+ name: "Custom Anthropic Proxy",
+ api: "openai-completions",
+ provider: "openrouter",
+ baseUrl: "https://example.com/v1",
+ reasoning: false,
+ input: ["text"],
+ cost: { input: 4, output: 12, cacheRead: 0.4, cacheWrite: 5 },
+ contextWindow: 128000,
+ maxTokens: 32000,
+ compat: {
+ cacheControlFormat: "anthropic",
+ supportsLongCacheRetention: false,
+ },
+ };
+
+ const { params, result } = await runCompletion(model, { cacheRetention: "long" });
+ expectAnthropicCacheMarkers(params);
+ expect(result.usage.cost.cacheWrite).toBeCloseTo((80 * model.cost.input * 1.25) / 1_000_000);
+ });
+
+ it("does not apply Anthropic-style cache markers to other Prime Inference models", async () => {
+ const model = getModel("prime-inference", "openai/gpt-5.6-sol");
+ const params = await capturePayload(model);
+ expectNoAnthropicCacheMarkers(params);
+ });
+
it("omits Anthropic-style cache markers when cacheRetention is none", async () => {
const model: Model<"openai-completions"> = {
id: "custom-qwen",
@@ -180,10 +254,6 @@ describe("openai-completions cacheControlFormat", () => {
},
};
const params = await capturePayload(model, { cacheRetention: "none" });
- const instructionMessage = getInstructionMessage(params);
-
- expect(Array.isArray(instructionMessage?.content)).toBe(false);
- expect(params.tools?.[0]?.cache_control).toBeUndefined();
- expect(typeof params.messages[params.messages.length - 1]?.content).toBe("string");
+ expectNoAnthropicCacheMarkers(params);
});
});
diff --git a/packages/ai/test/prime-inference-models.test.ts b/packages/ai/test/prime-inference-models.test.ts
index 413e6a57c1..3d7c75838f 100644
--- a/packages/ai/test/prime-inference-models.test.ts
+++ b/packages/ai/test/prime-inference-models.test.ts
@@ -154,8 +154,8 @@ describe("Prime Inference models", () => {
expect(sonnet5.cost).toEqual({
input: 2,
output: 10,
- cacheRead: 0,
- cacheWrite: 0,
+ cacheRead: 0.2,
+ cacheWrite: 2.5,
});
expect(getSupportedThinkingLevels(sonnet5)).toContain("xhigh");
expect(getSupportedThinkingLevels(sonnet5)).toContain("max");
@@ -186,7 +186,14 @@ describe("Prime Inference models", () => {
});
it("uses route-specific context windows for Prime Inference Claude routes", () => {
- expect(getModel("prime-inference", "anthropic/claude-fable-5").contextWindow).toBe(1000000);
+ const fable = getModel("prime-inference", "anthropic/claude-fable-5");
+ expect(fable.contextWindow).toBe(1000000);
+ expect(fable.cost).toEqual({
+ input: 10,
+ output: 50,
+ cacheRead: 1,
+ cacheWrite: 12.5,
+ });
expect(getModel("prime-inference", "anthropic/claude-opus-4.6").contextWindow).toBe(1000000);
expect(getModel("prime-inference", "anthropic/claude-opus-4.7").contextWindow).toBe(1000000);
expect(getModel("prime-inference", "anthropic/claude-opus-4.8").contextWindow).toBe(1000000);