-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathpromptCacheStrategy.ts
More file actions
328 lines (277 loc) · 7.96 KB
/
promptCacheStrategy.ts
File metadata and controls
328 lines (277 loc) · 7.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { createHash } from 'crypto'
import Anthropic from '@anthropic-ai/sdk'
import type { ChatCompletionContentPart, ChatCompletionMessageParam } from 'openai/resources'
import type { MCPToolDefinition } from '@shared/presenter'
import { resolvePromptCacheMode, type PromptCacheMode } from './promptCacheCapabilities'
export type PromptCacheApiType = 'openai_chat' | 'openai_responses' | 'anthropic'
export type PromptCacheTtl = '5m'
export interface PromptCacheBreakpointPlan {
messageIndex: number
contentIndex: number
}
export interface PromptCachePlan {
mode: PromptCacheMode
ttl: PromptCacheTtl | null
cacheKey?: string
breakpointPlan?: PromptCacheBreakpointPlan
}
export interface ResolvePromptCachePlanParams {
providerId: string
apiType: PromptCacheApiType
modelId: string
messages: unknown[]
tools?: MCPToolDefinition[]
conversationId?: string
}
type EphemeralCacheControl = { type: 'ephemeral' }
const EPHEMERAL_CACHE_CONTROL: EphemeralCacheControl = { type: 'ephemeral' }
type AnthropicTextBlockWithCache = Anthropic.TextBlockParam & {
cache_control?: EphemeralCacheControl
}
function normalizeId(value: string | undefined): string {
return value?.trim().toLowerCase() ?? ''
}
function buildPromptCacheKey(
providerId: string,
modelId: string,
conversationId?: string
): string | undefined {
const normalizedConversationId = conversationId?.trim()
if (!normalizedConversationId) {
return undefined
}
const digest = createHash('sha256')
.update(`${normalizeId(providerId)}:${normalizeId(modelId)}:${normalizedConversationId}`)
.digest('hex')
.slice(0, 20)
return `deepchat:${normalizeId(providerId)}:${normalizeId(modelId)}:${digest}`
}
function findOpenAIChatBreakpoint(
messages: ChatCompletionMessageParam[]
): PromptCacheBreakpointPlan | undefined {
let prefixEnd = messages.length
while (prefixEnd > 0) {
const role = messages[prefixEnd - 1]?.role
if (role === 'user' || role === 'tool') {
prefixEnd -= 1
continue
}
break
}
for (let messageIndex = prefixEnd - 1; messageIndex >= 0; messageIndex -= 1) {
const message = messages[messageIndex]
if (!message || message.role === 'tool') {
continue
}
const content = 'content' in message ? message.content : undefined
if (typeof content === 'string') {
if (content.trim()) {
return { messageIndex, contentIndex: 0 }
}
continue
}
if (!Array.isArray(content)) {
continue
}
for (let contentIndex = content.length - 1; contentIndex >= 0; contentIndex -= 1) {
const part = content[contentIndex]
if (part?.type === 'text' && typeof part.text === 'string' && part.text.trim()) {
return { messageIndex, contentIndex }
}
}
}
return undefined
}
function findAnthropicBreakpoint(
messages: Anthropic.MessageParam[]
): PromptCacheBreakpointPlan | undefined {
let prefixEnd = messages.length
while (prefixEnd > 0) {
const role = messages[prefixEnd - 1]?.role
if (role === 'user') {
prefixEnd -= 1
continue
}
break
}
for (let messageIndex = prefixEnd - 1; messageIndex >= 0; messageIndex -= 1) {
const message = messages[messageIndex]
if (!message) {
continue
}
const content = message.content
if (typeof content === 'string') {
if (content.trim()) {
return { messageIndex, contentIndex: 0 }
}
continue
}
if (!Array.isArray(content)) {
continue
}
for (let contentIndex = content.length - 1; contentIndex >= 0; contentIndex -= 1) {
const block = content[contentIndex]
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
return { messageIndex, contentIndex }
}
}
}
return undefined
}
export function resolvePromptCachePlan(params: ResolvePromptCachePlanParams): PromptCachePlan {
const mode = resolvePromptCacheMode(params.providerId, params.modelId)
if (mode === 'disabled') {
return { mode, ttl: null }
}
if (mode === 'openai_implicit') {
return {
mode,
ttl: null,
cacheKey: buildPromptCacheKey(params.providerId, params.modelId, params.conversationId)
}
}
if (mode === 'anthropic_auto') {
return {
mode,
ttl: '5m'
}
}
const breakpointPlan =
params.apiType === 'anthropic'
? findAnthropicBreakpoint(params.messages as Anthropic.MessageParam[])
: findOpenAIChatBreakpoint(params.messages as ChatCompletionMessageParam[])
return {
mode,
ttl: '5m',
breakpointPlan
}
}
export function applyOpenAIPromptCacheKey<T extends Record<string, unknown>>(
requestParams: T,
plan: PromptCachePlan
): T {
if (plan.mode !== 'openai_implicit' || !plan.cacheKey) {
return requestParams
}
return {
...requestParams,
prompt_cache_key: plan.cacheKey
}
}
export function applyAnthropicTopLevelCacheControl<T extends Record<string, unknown>>(
requestParams: T,
plan: PromptCachePlan
): T {
if (plan.mode !== 'anthropic_auto') {
return requestParams
}
return {
...requestParams,
cache_control: EPHEMERAL_CACHE_CONTROL
}
}
export function applyOpenAIChatExplicitCacheBreakpoint(
messages: ChatCompletionMessageParam[],
plan: PromptCachePlan
): ChatCompletionMessageParam[] {
if (plan.mode !== 'anthropic_explicit' || !plan.breakpointPlan) {
return messages
}
const { messageIndex, contentIndex } = plan.breakpointPlan
const target = messages[messageIndex]
if (!target || !('content' in target)) {
return messages
}
const content = target.content
let nextContent: ChatCompletionMessageParam['content'] =
content as ChatCompletionMessageParam['content']
if (typeof content === 'string') {
if (!content.trim() || contentIndex !== 0) {
return messages
}
nextContent = [
{
type: 'text',
text: content,
cache_control: EPHEMERAL_CACHE_CONTROL
} as unknown as ChatCompletionContentPart
]
} else if (Array.isArray(content)) {
nextContent = content.map((part, index) => {
if (
index !== contentIndex ||
part?.type !== 'text' ||
typeof part.text !== 'string' ||
!part.text.trim()
) {
return part
}
return {
...part,
cache_control: EPHEMERAL_CACHE_CONTROL
} as unknown as ChatCompletionContentPart
}) as ChatCompletionMessageParam['content']
} else {
return messages
}
return messages.map((message, index) =>
index === messageIndex
? ({
...message,
content: nextContent
} as ChatCompletionMessageParam)
: message
)
}
export function applyAnthropicExplicitCacheBreakpoint(
messages: Anthropic.MessageParam[],
plan: PromptCachePlan
): Anthropic.MessageParam[] {
if (plan.mode !== 'anthropic_explicit' || !plan.breakpointPlan) {
return messages
}
const { messageIndex, contentIndex } = plan.breakpointPlan
const target = messages[messageIndex]
if (!target) {
return messages
}
const content = target.content
let nextContent: Anthropic.MessageParam['content'] = content
if (typeof content === 'string') {
if (!content.trim() || contentIndex !== 0) {
return messages
}
nextContent = [
{
type: 'text',
text: content,
cache_control: EPHEMERAL_CACHE_CONTROL
} satisfies AnthropicTextBlockWithCache
]
} else if (Array.isArray(content)) {
nextContent = content.map((block, index) => {
if (
index !== contentIndex ||
block?.type !== 'text' ||
typeof block.text !== 'string' ||
!block.text.trim()
) {
return block
}
return {
...block,
cache_control: EPHEMERAL_CACHE_CONTROL
} satisfies AnthropicTextBlockWithCache
})
} else {
return messages
}
return messages.map((message, index) =>
index === messageIndex
? ({
...message,
content: nextContent
} as Anthropic.MessageParam)
: message
)
}