Open History to see the last commit
1import type { ResolvedPromptCache } from '@tanstack/ai'
2import type {
3 BetaCacheControlEphemeral,
4 BetaContentBlockParam,
5 BetaMessageParam,
6} from '@anthropic-ai/sdk/resources/beta/messages'
7import type { TextBlockParam } from '@anthropic-ai/sdk/resources/messages'
8import type { InternalTextProviderOptions } from './text/text-provider-options'
9
10/**
11 * The block types that can take the automatic cache marker when they are
12 * the last block of the last user message, or of a mid-conversation
13 * `system` message at the end.
14 */
15export const ANTHROPIC_CACHEABLE_BLOCK_TYPES: ReadonlySet<string> = new Set([
16 'text',
17 'image',
18 'document',
19 'tool_result',
20 'tool_addition',
21 'tool_removal',
22])
23
24/**
25 * The name of the deferred placeholder tool of mid-conversation tool mode.
26 * The text adapter puts it on the placeholder, and the cache markers find
27 * the placeholder by it.
28 */
29export const ANTHROPIC_DEFERRED_TOOL_PLACEHOLDER_NAME =
30 '__tanstack_deferred_placeholder__'
31
32// Anthropic rejects a request with more than 4 cache markers.
33const MAX_CACHE_MARKERS = 4
34
35// `null` and `undefined` are not markers: custom tools always send
36// `cache_control: null` when the caller set none.
37function hasCacheControl(item: object) {
38 return 'cache_control' in item && item.cache_control != null
39}
40
41function blockHasCacheControl(block: BetaContentBlockParam) {
42 // A marker inside a tool result also counts toward the limit of 4.
43 const isMarkedToolResult =
44 block.type === 'tool_result' &&
45 Array.isArray(block.content) &&
46 block.content.some(hasCacheControl)
47 return hasCacheControl(block) || isMarkedToolResult
48}
49
50function hasManualCacheControl(request: InternalTextProviderOptions) {
51 const systemBlocks = Array.isArray(request.system) ? request.system : []
52 const tools = request.tools ?? []
53 const hasMessageMarker = request.messages.some(
54 (message) =>
55 Array.isArray(message.content) &&
56 message.content.some(blockHasCacheControl),
57 )
58 return (
59 request.cache_control != null ||
60 systemBlocks.some(hasCacheControl) ||
61 tools.some(hasCacheControl) ||
62 hasMessageMarker
63 )
64}
65
66function withCacheControl<T extends object>(
67 item: T,
68 cacheControl: BetaCacheControlEphemeral,
69) {
70 return { ...item, cache_control: cacheControl }
71}
72
73/**
74 * The messages with a marker on the last block of the last message. Returns
75 * `null` when that message is not from the user or a mid-conversation
76 * `system` message, or when its last block cannot take a marker.
77 */
78function markLastUserMessage(
79 messages: Array<BetaMessageParam>,
80 cacheControl: BetaCacheControlEphemeral,
81) {
82 const last = messages.at(-1)
83 // A mid-conversation `system` message at the end takes the marker, as in
84 // pi 0.87.1. The SDK type has no `system` role, so compare it as a string.
85 const role: string | undefined = last?.role
86 if (last === undefined || (role !== 'user' && role !== 'system')) {
87 return null
88 }
89 const blocks: Array<BetaContentBlockParam> =
90 typeof last.content !== 'string'
91 ? last.content
92 : last.content
93 ? [{ type: 'text', text: last.content }]
94 : []
95 const lastBlock = blocks.at(-1)
96 if (
97 lastBlock === undefined ||
98 !ANTHROPIC_CACHEABLE_BLOCK_TYPES.has(lastBlock.type)
99 ) {
100 return null
101 }
102 return [
103 ...messages.slice(0, -1),
104 {
105 ...last,
106 content: [
107 ...blocks.slice(0, -1),
108 withCacheControl(lastBlock, cacheControl),
109 ],
110 },
111 ]
112}
113
114/**
115 * Adds Anthropic cache markers to a Messages request, so a later request
116 * with the same start reads it from the cache.
117 *
118 * It adds nothing when `promptCache` is absent or `'none'`, or when the
119 * request already has a marker of the caller's (on a system block, a message
120 * block, a tool, or the top-level `cache_control`). Otherwise it marks, with
121 * at most 4 markers:
122 * 1. the last tool. In mid-conversation tool mode (the tools hold the
123 * placeholder), the last start tool, right before the placeholder,
124 * 2. the last block of the last message, when it is a user message or a
125 * mid-conversation `system` message and the block type is in
126 * {@link ANTHROPIC_CACHEABLE_BLOCK_TYPES},
127 * 3. the system blocks from the end, with the markers that are left.
128 *
129 * It does not change the request it gets. It returns a new request, or the
130 * same request when it adds nothing.
131 *
132 * @param request - The finished Messages request.
133 * @param promptCache - The `promptCache` that `chat()` resolved.
134 *
135 * @example
136 * const body = applyAnthropicPromptCache(request, { retention: 'short' })
137 */
138export function applyAnthropicPromptCache(
139 request: InternalTextProviderOptions,
140 promptCache: ResolvedPromptCache | undefined,
141) {
142 const retention = promptCache?.retention ?? 'none'
143 if (retention === 'none' || hasManualCacheControl(request)) return request
144
145 const cacheControl: BetaCacheControlEphemeral =
146 retention === 'long'
147 ? { type: 'ephemeral', ttl: '1h' }
148 : { type: 'ephemeral' }
149
150 // Mid-conversation tool mode: the placeholder and the deferred added tools
151 // are not in the cached start, so the marker goes on the last start tool,
152 // right before the placeholder (pi 0.87.1). Without the placeholder, the
153 // last tool, as before.
154 const placeholder =
155 request.tools?.findIndex(
156 // The computer toolset entry has no name.
157 (tool) =>
158 'name' in tool &&
159 tool.name === ANTHROPIC_DEFERRED_TOOL_PLACEHOLDER_NAME,
160 ) ?? -1
161 const tools = request.tools?.map((tool, index, all) =>
162 index === (placeholder > 0 ? placeholder - 1 : all.length - 1)
163 ? withCacheControl(tool, cacheControl)
164 : tool,
165 )
166 const messages = markLastUserMessage(request.messages, cacheControl)
167
168 const usedMarkers = (tools?.length ? 1 : 0) + (messages ? 1 : 0)
169 const systemBlocks: Array<TextBlockParam> =
170 typeof request.system !== 'string'
171 ? (request.system ?? [])
172 : request.system
173 ? [{ type: 'text', text: request.system }]
174 : []
175 const firstMarkedSystem =
176 systemBlocks.length - (MAX_CACHE_MARKERS - usedMarkers)
177 const system = systemBlocks.map((block, index) =>
178 index >= firstMarkedSystem ? withCacheControl(block, cacheControl) : block,
179 )
180
181 return {
182 ...request,
183 ...(tools && { tools }),
184 ...(system.length > 0 && { system }),
185 ...(messages && { messages }),
186 }
187}