mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Cache the tools array for Anthropic via OpenRouter
The tools JSON is typically 7-12K tokens, stable across every turn in a session, and was previously re-billed at full input price on every turn. OpenRouter explicitly supports cache_control on tool definitions for Anthropic models (announced in their 'tool caching' release), and the OpenAI SDK serializes the body via JSON.stringify so unknown fields like cache_control pass through untouched. This adds a cache_control breakpoint on the last tool, which caches the entire tools array. Combined with the existing system + last-2-messages breakpoints, we now use all 4 breakpoints Anthropic allows, matching the cache hierarchy (tools -> system -> messages). Expected savings for a 280-turn session (Opus): ~$27 for 16 tools or ~$47 for 31 tools. Refactors the request-body transform into a named, exported applyOpenRouterTransforms function with unit tests covering: - cache_control placement on tools, system, and last two messages - non-Anthropic models skip the transform - byte-stability of the tools JSON across calls (the property the cache actually relies on) - no mutation of the caller's tools array
This commit is contained in:
2 files changed
+214
-28
No files matched your search
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type OpenAI from 'openai';
|
||||
import { applyOpenRouterTransforms } from './ai-client';
|
||||
|
||||
/**
|
||||
* Helper: minimal valid ChatCompletionCreateParams for transform tests.
|
||||
*/
|
||||
function makeBody(overrides: Partial<OpenAI.Chat.Completions.ChatCompletionCreateParams> = {})
|
||||
: OpenAI.Chat.Completions.ChatCompletionCreateParams {
|
||||
return {
|
||||
model: 'anthropic/claude-opus-4.6',
|
||||
messages: [
|
||||
{ role: 'system', content: 'you are helpful' },
|
||||
{ role: 'user', content: 'hello' },
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('applyOpenRouterTransforms', () => {
|
||||
it('adds usage accounting to the body regardless of model', () => {
|
||||
const body = makeBody({ model: 'openai/gpt-4' });
|
||||
applyOpenRouterTransforms(body);
|
||||
expect((body as { usage?: { include?: boolean } }).usage).toEqual({ include: true });
|
||||
});
|
||||
|
||||
it('does not apply cache_control for non-Anthropic models', () => {
|
||||
const body = makeBody({
|
||||
model: 'openai/gpt-4',
|
||||
tools: [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
// messages remain as plain strings (no normalization)
|
||||
expect(body.messages[0].content).toBe('you are helpful');
|
||||
// tools untouched
|
||||
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
});
|
||||
|
||||
it('places cache_control on the last tool for Anthropic models', () => {
|
||||
const body = makeBody({
|
||||
tools: [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
{ type: 'function', function: { name: 't2', description: '', parameters: { type: 'object' } } },
|
||||
{ type: 'function', function: { name: 't3', description: '', parameters: { type: 'object' } } },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
// Only the LAST tool gets cache_control — Anthropic caches everything
|
||||
// up to and including the marked block, so marking the last tool is
|
||||
// sufficient and we spend only one of the 4 breakpoints.
|
||||
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
expect((body.tools![1] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
expect((body.tools![2] as { cache_control?: { type: string } }).cache_control)
|
||||
.toEqual({ type: 'ephemeral' });
|
||||
});
|
||||
|
||||
it('places cache_control on the system message and last two non-system messages', () => {
|
||||
const body = makeBody({
|
||||
messages: [
|
||||
{ role: 'system', content: 'you are helpful' },
|
||||
{ role: 'user', content: 'first' },
|
||||
{ role: 'assistant', content: 'reply 1' },
|
||||
{ role: 'user', content: 'second' },
|
||||
{ role: 'assistant', content: 'reply 2' },
|
||||
],
|
||||
});
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
const hasCache = (m: OpenAI.Chat.Completions.ChatCompletionMessageParam): boolean => {
|
||||
if (!Array.isArray(m.content)) return false;
|
||||
return m.content.some((b) => {
|
||||
const block = b as { cache_control?: unknown };
|
||||
return block.cache_control !== undefined;
|
||||
});
|
||||
};
|
||||
|
||||
// System: cached
|
||||
expect(hasCache(body.messages[0])).toBe(true);
|
||||
// Old turns: not cached
|
||||
expect(hasCache(body.messages[1])).toBe(false);
|
||||
expect(hasCache(body.messages[2])).toBe(false);
|
||||
// Last two non-system: cached
|
||||
expect(hasCache(body.messages[3])).toBe(true);
|
||||
expect(hasCache(body.messages[4])).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes string content to text block arrays for Anthropic', () => {
|
||||
const body = makeBody();
|
||||
applyOpenRouterTransforms(body);
|
||||
// System and user both turned into arrays of text blocks
|
||||
expect(Array.isArray(body.messages[0].content)).toBe(true);
|
||||
expect(Array.isArray(body.messages[1].content)).toBe(true);
|
||||
const sysBlocks = body.messages[0].content as Array<{ type: string; text: string }>;
|
||||
expect(sysBlocks[0]).toEqual(
|
||||
expect.objectContaining({ type: 'text', text: 'you are helpful' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not crash when tools is undefined or empty', () => {
|
||||
const a = makeBody();
|
||||
expect(() => applyOpenRouterTransforms(a)).not.toThrow();
|
||||
expect(a.tools).toBeUndefined();
|
||||
|
||||
const b = makeBody({ tools: [] });
|
||||
expect(() => applyOpenRouterTransforms(b)).not.toThrow();
|
||||
expect(b.tools).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not mutate the original tools array reference (uses structuredClone)', () => {
|
||||
const originalTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||
];
|
||||
const originalRef = originalTools;
|
||||
const body = makeBody({ tools: originalTools });
|
||||
applyOpenRouterTransforms(body);
|
||||
|
||||
// body.tools is now a clone, original array untouched
|
||||
expect(body.tools).not.toBe(originalRef);
|
||||
expect((originalTools[0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||
// But body.tools has cache_control
|
||||
expect((body.tools![0] as { cache_control?: { type: string } }).cache_control)
|
||||
.toEqual({ type: 'ephemeral' });
|
||||
});
|
||||
|
||||
it('produces byte-identical output across two calls with the same input (cache stability)', () => {
|
||||
// This is the property the Anthropic cache relies on: the tools block
|
||||
// hashes to the same value on every turn. If this test ever fails, tool
|
||||
// caching will silently stop working.
|
||||
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||
{ type: 'function', function: { name: 'a', description: 'x', parameters: { type: 'object', properties: { foo: { type: 'string' } } } } },
|
||||
{ type: 'function', function: { name: 'b', description: 'y', parameters: { type: 'object' } } },
|
||||
];
|
||||
|
||||
const body1 = makeBody({ tools: structuredClone(tools) });
|
||||
const body2 = makeBody({ tools: structuredClone(tools) });
|
||||
applyOpenRouterTransforms(body1);
|
||||
applyOpenRouterTransforms(body2);
|
||||
|
||||
expect(JSON.stringify(body1.tools)).toEqual(JSON.stringify(body2.tools));
|
||||
});
|
||||
});
|
||||
+70
-28
@@ -74,34 +74,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter-specific hacks
|
||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||
// Usage accounting field to get token usage and cost per request
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
// Prompt caching for Claude models
|
||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
if (body.model.startsWith("anthropic/")) {
|
||||
// First normalize the message history to use content blocks
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
}
|
||||
applyOpenRouterTransforms(body);
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
@@ -110,6 +83,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
return openai;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply OpenRouter-specific request body mutations: opt into usage accounting,
|
||||
* and (for Anthropic models) place `cache_control` breakpoints so the tools
|
||||
* array, system prompt, and last two messages get cached. Exported for tests.
|
||||
*
|
||||
* References:
|
||||
* - OpenRouter prompt caching guide:
|
||||
* https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
* - OpenRouter tool caching announcement: "gif-prompts-omni-search-tool-caching-and-byok-flags"
|
||||
* - Anthropic prompt caching docs:
|
||||
* https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
|
||||
*
|
||||
* Anthropic's cache hierarchy is `tools` → `system` → `messages`. We use all
|
||||
* four breakpoints Anthropic allows per request:
|
||||
* 1. last tool definition (caches the entire tools array)
|
||||
* 2. system message (caches system prompt + AGENTS.md)
|
||||
* 3. second-to-last non-system (caches most of conversation)
|
||||
* 4. last non-system (caches everything including latest msg)
|
||||
*/
|
||||
export function applyOpenRouterTransforms(
|
||||
body: OpenAI.Chat.Completions.ChatCompletionCreateParams,
|
||||
): void {
|
||||
// Usage accounting field to get token usage and cost per request.
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
if (!body.model.startsWith("anthropic/")) return;
|
||||
|
||||
// Normalize the message history to use content blocks so we can attach
|
||||
// cache_control to individual text parts.
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
|
||||
// Cache the tools array by marking the last tool with cache_control.
|
||||
// Anthropic caches everything up to and including the marked block, so
|
||||
// marking just the last tool caches the whole array. The tools array
|
||||
// must be byte-stable across turns for cache hits — Shakespeare builds
|
||||
// it once per session in `ChatPane`, so this holds as long as we don't
|
||||
// mutate session.tools mid-session.
|
||||
//
|
||||
// Note: the OpenAI SDK serializes the body via plain `JSON.stringify`
|
||||
// (see node_modules/openai/internal/request-options) and does not strip
|
||||
// unknown fields, so the `cache_control` property survives the trip to
|
||||
// OpenRouter.
|
||||
if (body.tools && body.tools.length > 0) {
|
||||
body.tools = structuredClone(body.tools);
|
||||
const lastTool = body.tools[body.tools.length - 1];
|
||||
(lastTool as { cache_control?: { type: "ephemeral" } })
|
||||
.cache_control = { type: "ephemeral" };
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
|
||||
Reference in new issue
Block a user