Open History to see the last commit
1import type { ResolvedPromptCache } from '@tanstack/ai'
2import type {
3 ChatContentCacheControl,
4 ChatMessages,
5 ChatRequest,
6} from '@openrouter/sdk/models'
7
8type OpenRouterChatRequest = Omit<ChatRequest, 'stream'>
9
10/** True when one of the items already has a cache marker. */
11function hasMarker(items: ReadonlyArray<object> | undefined) {
12 return items?.some((item) => 'cacheControl' in item) ?? false
13}
14
15/**
16 * Put the marker on the last text block that is not empty. A string becomes
17 * one text block. An empty string does not change.
18 */
19function markLastText<TPart extends { type: string }>(
20 content: string | Array<TPart>,
21 cacheControl: ChatContentCacheControl,
22) {
23 if (typeof content === 'string') {
24 return content === ''
25 ? content
26 : [{ type: 'text' as const, text: content, cacheControl }]
27 }
28 const index = content.findLastIndex(
29 (part) => part.type === 'text' && 'text' in part && part.text !== '',
30 )
31 return content.map((part, i) =>
32 i === index ? { ...part, cacheControl } : part,
33 )
34}
35
36/** Put the marker on the last text block of one message. */
37function markMessage(
38 message: ChatMessages,
39 cacheControl: ChatContentCacheControl,
40) {
41 switch (message.role) {
42 // A system message has its own case: it takes only text blocks.
43 case 'system':
44 return {
45 ...message,
46 content: markLastText(message.content, cacheControl),
47 }
48 case 'user':
49 case 'tool':
50 return {
51 ...message,
52 content: markLastText(message.content, cacheControl),
53 }
54 case 'assistant':
55 // The converter gives an assistant a string, or null when the message
56 // has only tool calls. Null has no text to mark.
57 return typeof message.content === 'string'
58 ? { ...message, content: markLastText(message.content, cacheControl) }
59 : message
60 case 'developer':
61 // The converter never makes a developer message.
62 return message
63 }
64}
65
66/**
67 * Add the automatic prompt cache fields for `chat({ promptCache })` to an
68 * OpenRouter chat request.
69 *
70 * - The cache key becomes `sessionId` on every model, so OpenRouter sends the
71 * requests of one session to the same provider. A `sessionId` from
72 * `modelOptions` wins.
73 * - Only `anthropic/*` models get cache markers, and only when the request
74 * has no manual marker (system prompt, tool, or content block). Then the
75 * system message, the last function tool, and the last message each get a
76 * marker on their last text block. If the last message is a user message
77 * with no text block, the message before it gets that marker.
78 *
79 * `'none'` returns the request with no change. `'long'` asks for the 1-hour
80 * TTL. The function returns a new request and does not change `request`.
81 */
82export function addPromptCacheMarkers(
83 request: OpenRouterChatRequest,
84 promptCache: ResolvedPromptCache,
85) {
86 if (promptCache.retention === 'none') return request
87 // OpenRouter accepts a session id of at most 256 characters.
88 const key =
89 promptCache.key && Array.from(promptCache.key).slice(0, 256).join('')
90 const sessionId = request.sessionId ?? key
91 const withSession = { ...request, ...(sessionId && { sessionId }) }
92
93 const isClaude = request.model?.startsWith('anthropic/') ?? false
94 const hasManualMarker =
95 hasMarker(request.tools) ||
96 request.messages.some(
97 (message) => Array.isArray(message.content) && hasMarker(message.content),
98 )
99 if (!isClaude || hasManualMarker) return withSession
100
101 const cacheControl: ChatContentCacheControl =
102 promptCache.retention === 'long'
103 ? { type: 'ephemeral', ttl: '1h' }
104 : { type: 'ephemeral' }
105 // A last message with no text block (e.g. the images of tool results) cannot
106 // take a marker, so the message before it gets the marker.
107 const last = request.messages.at(-1)
108 const lastMessage =
109 request.messages.length -
110 (last?.role === 'user' &&
111 Array.isArray(last.content) &&
112 !last.content.some((part) => part.type === 'text')
113 ? 2
114 : 1)
115 const lastTool =
116 request.tools?.findLastIndex((tool) => tool.type === 'function') ?? -1
117 return {
118 ...withSession,
119 messages: request.messages.map((message, i) =>
120 message.role === 'system' || i === lastMessage
121 ? markMessage(message, cacheControl)
122 : message,
123 ),
124 ...(request.tools && {
125 tools: request.tools.map((tool, i) =>
126 i === lastTool ? { ...tool, cacheControl } : tool,
127 ),
128 }),
129 }
130}