Skip to content

Commit 69a7142

Browse files
authored
feat(core): configure Anthropic cache breakpoints with compatibility.cacheFormat (anomalyco#54945)
1 parent 6a12383 commit 69a7142

15 files changed

Lines changed: 196 additions & 14 deletions

File tree

‎packages/ai/src/cache-policy.ts‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -171,17 +171,7 @@ const countHints = (request: LLMRequest) =>
171171
)
172172

173173
export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
174-
const route = request.model.route.id
175-
if (!RESPECTS_INLINE_HINTS.has(route)) return request
176-
const policy =
177-
(route === "openrouter" || route === "vercel-ai-gateway-messages") &&
178-
(request.cache === undefined || request.cache === "auto")
179-
? gatewayPolicy(request.model.id)
180-
: route === "alibaba-chat" && (request.cache === undefined || request.cache === "auto")
181-
? request.model.id.toLowerCase().startsWith("qwen")
182-
? QWEN
183-
: NONE
184-
: resolve(request.cache)
174+
const policy = selectPolicy(request)
185175
if (!policy.tools && !policy.system && !policy.messages) return request
186176

187177
const hint = makeHint(policy.ttlSeconds)
@@ -193,3 +183,17 @@ export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
193183
if (tools === request.tools && system === request.system && messages === request.messages) return request
194184
return LLMRequest.update(request, { tools, system, messages })
195185
}
186+
187+
// A declared cache format overrides the route allowlist and its model-ID heuristics.
188+
const selectPolicy = (request: LLMRequest): CachePolicyObject => {
189+
const format = request.model.compatibility?.cacheFormat
190+
const route = request.model.route.id
191+
const auto = request.cache === undefined || request.cache === "auto"
192+
if (format === "alibaba") return auto ? QWEN : { ...resolve(request.cache), tools: false }
193+
if (format === "anthropic") return resolve(request.cache)
194+
if (!RESPECTS_INLINE_HINTS.has(route)) return NONE
195+
if (!auto) return resolve(request.cache)
196+
if (route === "openrouter" || route === "vercel-ai-gateway-messages") return gatewayPolicy(request.model.id)
197+
if (route === "alibaba-chat") return request.model.id.toLowerCase().startsWith("qwen") ? QWEN : NONE
198+
return AUTO
199+
}

‎packages/ai/src/protocols/openai-chat.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
} from "../schema/index.js"
2525
import { classifyProviderFailure } from "../provider-error.js"
2626
import { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
27+
import { cacheControl } from "./utils/cache.js"
2728
import { OpenAIOptions } from "./utils/openai-options.js"
2829
import { Lifecycle } from "./utils/lifecycle.js"
2930
import { ToolStream } from "./utils/tool-stream.js"
@@ -827,15 +828,16 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
827828
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
828829
const hasHistory = hasToolHistory(request.messages)
829830
const hasActiveTools = flattened.tools.length > 0
831+
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request) }
830832
return {
831833
model: request.model.id,
832-
messages: yield* lowerMessages(flattened.request, options),
834+
messages: yield* lowerMessages(flattened.request, lowering),
833835
tools:
834836
flattened.tools.length === 0
835837
? hasHistory
836838
? []
837839
: undefined
838-
: flattened.tools.map((tool) => lowerTool(tool, options, supportsStrictMode)),
840+
: flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode)),
839841
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
840842
stream: true as const,
841843
...(supportsUsageInStreaming ? { stream_options: { include_usage: true } } : {}),
@@ -853,6 +855,10 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
853855
}
854856
})
855857

858+
// Provider wrappers that pass their own marker writer keep it; otherwise a declared cache format adds one.
859+
const declaredCacheControl = (request: LLMRequest) =>
860+
request.model.compatibility?.cacheFormat === undefined ? undefined : cacheControl()
861+
856862
// =============================================================================
857863
// Stream Parsing
858864
// =============================================================================

‎packages/ai/src/schema/options.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,9 @@ export type LanguageModelMaxTokensFieldCompatibility = Schema.Schema.Type<
201201
typeof LanguageModelMaxTokensFieldCompatibility
202202
>
203203

204+
export const LanguageModelCacheFormatCompatibility = Schema.Literals(["anthropic", "alibaba"])
205+
export type LanguageModelCacheFormatCompatibility = Schema.Schema.Type<typeof LanguageModelCacheFormatCompatibility>
206+
204207
export class LanguageModelCompatibility extends Schema.Class<LanguageModelCompatibility>(
205208
"LLM.LanguageModelCompatibility",
206209
)({
@@ -218,6 +221,8 @@ export class LanguageModelCompatibility extends Schema.Class<LanguageModelCompat
218221
// this is true; other protocols omit it only when this is false.
219222
// Session-affinity headers still flow regardless.
220223
supportsPromptCacheKey: Schema.optional(Schema.Boolean),
224+
/** Prompt-cache marker syntax the endpoint accepts. Overrides the route default; both send `cache_control`, and `alibaba` skips tool definitions. */
225+
cacheFormat: Schema.optional(LanguageModelCacheFormatCompatibility),
221226
zaiToolStream: Schema.optional(Schema.Boolean),
222227
requireSignature: Schema.optional(Schema.Boolean),
223228
/** Supports Anthropic's thinking-prefix mismatch controls. Overrides model-ID detection. */

‎packages/ai/test/provider/openai-compatible-chat.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,43 @@ describe("OpenAI-compatible Chat route", () => {
9999
}),
100100
)
101101

102+
it.effect("places cache breakpoints only when compatibility declares the format", () =>
103+
Effect.gen(function* () {
104+
const prepare = (cacheFormat: "anthropic" | "alibaba" | undefined) =>
105+
compileRequest(
106+
LLM.request({
107+
model: OpenAICompatibleChat.route
108+
.with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } })
109+
.model({ id: "claude-sonnet-5", compatibility: cacheFormat === undefined ? undefined : { cacheFormat } }),
110+
system: "You are concise.",
111+
prompt: "Say hello.",
112+
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: {} })],
113+
}),
114+
)
115+
116+
const declared = yield* prepare("anthropic")
117+
expect(declared.body).toMatchObject({
118+
messages: [
119+
{ role: "system", content: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }] },
120+
{ role: "user", content: [{ type: "text", text: "Say hello.", cache_control: { type: "ephemeral" } }] },
121+
],
122+
tools: [{ function: { name: "lookup" }, cache_control: { type: "ephemeral" } }],
123+
})
124+
expect(JSON.stringify(declared.body)).not.toContain('"ttl"')
125+
126+
const alibaba = yield* prepare("alibaba")
127+
expect(alibaba.body).toMatchObject({
128+
messages: [
129+
{ role: "system", content: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }] },
130+
{ role: "user", content: [{ type: "text", text: "Say hello.", cache_control: { type: "ephemeral" } }] },
131+
],
132+
})
133+
expect(alibaba.body.tools?.[0]?.cache_control).toBeUndefined()
134+
135+
expect(JSON.stringify((yield* prepare(undefined)).body)).not.toContain("cache_control")
136+
}),
137+
)
138+
102139
it.effect("configures the max tokens request field", () =>
103140
Effect.gen(function* () {
104141
const compatible = OpenAICompatibleChat.route

‎packages/ai/test/provider/openrouter.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect } from "bun:test"
22
import { Effect } from "effect"
3-
import { CacheHint, LLM, Message } from "../../src/index.js"
3+
import { CacheHint, LanguageModel, LLM, Message } from "../../src/index.js"
44
import { LLMClient } from "../../src/route.js"
55
import { compileRequest } from "../../src/route/client.js"
66
import * as OpenRouter from "../../src/providers/openrouter.js"
@@ -127,6 +127,26 @@ describe("OpenRouter", () => {
127127
}),
128128
)
129129

130+
it.effect("places breakpoints for any upstream when compatibility declares the cache format", () =>
131+
Effect.gen(function* () {
132+
const model = OpenRouter.configure({ apiKey: "test-key" }).model("vendor/claude-proxy")
133+
const prepared = yield* compileRequest(
134+
LLM.request({
135+
model: LanguageModel.update(model, { compatibility: { cacheFormat: "anthropic" } }),
136+
system: "Base agent",
137+
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
138+
prompt: "Hello",
139+
}),
140+
)
141+
142+
expect(prepared.body.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" })
143+
expect(prepared.body.messages).toMatchObject([
144+
{ role: "system", content: [{ text: "Base agent", cache_control: { type: "ephemeral" } }] },
145+
{ role: "user", content: [{ text: "Hello", cache_control: { type: "ephemeral" } }] },
146+
])
147+
}),
148+
)
149+
130150
it.effect("sends no default breakpoints to upstreams that cache without them", () =>
131151
Effect.gen(function* () {
132152
const openrouter = OpenRouter.configure({ apiKey: "test-key" })

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,8 @@ export type ModelReasoningField = "reasoning" | "reasoning_content" | "reasoning
166166

167167
export type ModelMaxTokensField = "max_completion_tokens" | "max_tokens"
168168

169+
export type ModelCacheFormat = "anthropic" | "alibaba"
170+
169171
export type ModelCapabilities = { tools: boolean; input: Array<string>; output: Array<string> }
170172

171173
export type MoneyUSDPerMillionTokens = number
@@ -632,6 +634,7 @@ export type ModelCompatibility = {
632634
requireFinishReason?: boolean
633635
requireAssistantAfterTool?: boolean
634636
supportsPromptCacheKey?: boolean
637+
cacheFormat?: ModelCacheFormat
635638
supportsThinkingBlockBinding?: boolean
636639
supportsEffortUpdates?: boolean
637640
}
@@ -643,6 +646,7 @@ export type ProviderCompatibility = {
643646
requireFinishReason?: boolean
644647
requireAssistantAfterTool?: boolean
645648
supportsPromptCacheKey?: boolean
649+
cacheFormat?: ModelCacheFormat
646650
}
647651

648652
export type ModelCost = {

‎packages/core/src/plugin/provider/databricks.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,14 @@ export const DatabricksPlugin = define({
88
// models.dev also lists DATABRICKS_HOST, which only fills the base URL template.
99
editor.method.update({ integrationID: "databricks", method: { type: "env", names: ["DATABRICKS_TOKEN"] } })
1010
})
11+
yield* ctx.model.transform((models) => {
12+
for (const item of models.list("databricks")) {
13+
// Databricks caches Claude only through explicit `cache_control` breakpoints.
14+
if (!(item.modelID ?? item.id).includes("claude")) continue
15+
models.update(item.providerID, item.id, (model) => {
16+
model.compatibility = { cacheFormat: "anthropic", ...model.compatibility }
17+
})
18+
}
19+
})
1120
}),
1221
})

‎packages/core/src/plugin/provider/snowflake-cortex.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,9 @@ export const SnowflakeCortexPlugin = define({
197197
for (const item of models.list(providerID)) {
198198
models.update(providerID, item.id, (model) => {
199199
model.compatibility = { maxTokensField: "max_completion_tokens", ...model.compatibility }
200+
// Cortex Chat Completions caches Claude only through explicit `cache_control` breakpoints.
201+
if ((model.modelID ?? model.id).includes("claude"))
202+
model.compatibility = { cacheFormat: "anthropic", ...model.compatibility }
200203
if (model.settings?.baseURL !== undefined)
201204
model.settings.baseURL = endpoint(model.settings.baseURL, account.value)
202205
})

‎packages/core/test/config/provider.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,31 @@ describe("ConfigProviderPlugin.Plugin", () => {
170170
}),
171171
)
172172

173+
it.effect("carries a configured provider cache format to the runtime model", () =>
174+
Effect.gen(function* () {
175+
const models = yield* Model.Service
176+
yield* addPlugin([
177+
new Document({
178+
type: "document",
179+
info: decode({
180+
providers: {
181+
litellm: {
182+
package: "@opencode/ai/providers/openai-compatible",
183+
settings: { baseURL: "https://litellm.test/v1" },
184+
compatibility: { cacheFormat: "anthropic" },
185+
models: { "claude-sonnet-5": {} },
186+
},
187+
},
188+
}),
189+
}),
190+
])
191+
192+
const model = required(yield* models.get(Provider.ID.make("litellm"), Model.ID.make("claude-sonnet-5")))
193+
expect(model.compatibility).toEqual({ cacheFormat: "anthropic" })
194+
expect((yield* ModelResolver.fromCatalogModel(model)).compatibility?.cacheFormat).toBe("anthropic")
195+
}),
196+
)
197+
173198
it.effect("applies provider compatibility to every provider model with model overrides", () =>
174199
Effect.gen(function* () {
175200
const providers = yield* Provider.Service

‎packages/core/test/plugin/provider-snowflake-cortex.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ it.live("manual PAT uses its account and native compatibility rather than an SDK
192192
const body = yield* Effect.promise(() => request.json())
193193
expect(body).toMatchObject({ model: modelID, max_completion_tokens: 1024 })
194194
expect(body).not.toHaveProperty("max_tokens")
195+
// Cortex caches Claude only through explicit Anthropic-style breakpoints.
196+
expect(JSON.stringify(body)).toContain('"cache_control":{"type":"ephemeral"}')
195197
}),
196198
),
197199
)

0 commit comments

Comments
 (0)