Open History to see the last commit
1import type { ResolvedPromptCache } from '@tanstack/ai'
2
3/**
4 * Cut a cache key to 64 characters, the most OpenAI accepts. It counts code
5 * points, so an emoji or a CJK character is never cut in half.
6 */
7export function clampPromptCacheKey(key: string | undefined) {
8 return key === undefined ? undefined : Array.from(key).slice(0, 64).join('')
9}
10
11/**
12 * True when `baseURL` points at OpenAI's own API: `api.openai.com` or a
13 * subdomain, such as the data residency hosts (`eu.api.openai.com`).
14 */
15function isOpenAIHost(baseURL: string) {
16 try {
17 const host = new URL(baseURL).hostname
18 return host === 'api.openai.com' || host.endsWith('.api.openai.com')
19 } catch {
20 return false
21 }
22}
23
24/**
25 * The prompt cache fields of a Responses request.
26 *
27 * - `explicitMode`: the model takes `prompt_cache_options` in place of
28 * `prompt_cache_retention` (see `openAIModelUsesExplicitPromptCache`).
29 * - `longRetention`: the endpoint keeps a cache for longer than a few minutes.
30 * - `baseURL`: a short retention sends the key only to `api.openai.com`.
31 * Another server can reject a field it does not know. A long retention
32 * still sends the key.
33 */
34export function responsesPromptCacheFields(
35 promptCache: ResolvedPromptCache | undefined,
36 flags: { explicitMode: boolean; longRetention: boolean; baseURL: string },
37) {
38 const fields: Record<string, unknown> = {}
39 if (!promptCache) return fields
40 const { retention } = promptCache
41 const key = clampPromptCacheKey(promptCache.key)
42 const isLong = retention === 'long' && flags.longRetention
43 const sendsKey = isLong || isOpenAIHost(flags.baseURL)
44 if (retention !== 'none' && key && sendsKey) fields.prompt_cache_key = key
45 if (!flags.explicitMode) {
46 if (isLong) fields.prompt_cache_retention = '24h'
47 return fields
48 }
49 if (retention === 'none') fields.prompt_cache_options = { mode: 'explicit' }
50 else if (isLong) fields.prompt_cache_options = { ttl: '30m' }
51 return fields
52}
53
54/**
55 * The prompt cache fields of a Chat Completions request.
56 *
57 * A short retention sends the key only to `api.openai.com`, because another
58 * server can reject a field it does not know. A long retention sends the key
59 * and `24h` when `longRetention` is true.
60 */
61export function chatPromptCacheFields(
62 promptCache: ResolvedPromptCache | undefined,
63 flags: { baseURL: string; longRetention: boolean },
64) {
65 const fields: Record<string, unknown> = {}
66 if (!promptCache || promptCache.retention === 'none') return fields
67 const key = clampPromptCacheKey(promptCache.key)
68 const isLong = promptCache.retention === 'long' && flags.longRetention
69 const sendsKey = isLong || isOpenAIHost(flags.baseURL)
70 if (key && sendsKey) fields.prompt_cache_key = key
71 if (isLong) fields.prompt_cache_retention = '24h'
72 return fields
73}