Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import type { AnyTextAdapter, PromptCacheRetention, Tool } from '@tanstack/ai'
4import { createAnthropicChat } from '@tanstack/ai-anthropic'
5import { createOpenaiChat } from '@tanstack/ai-openai'
6
7/**
8 * Wire check for the `promptCache` option of `chat()`.
9 *
10 * The route runs one chat turn four times: Anthropic and OpenAI Responses,
11 * each once with the default `promptCache` and once with `'none'`. Every turn
12 * has a `threadId`, a system prompt, and a tool. A custom `fetch` records the
13 * request body and answers with a canned stream, so no aimock fixture is
14 * needed. The route returns the four request bodies for the spec to check.
15 */
16
17const THREAD_ID = 'thread-prompt-cache-wire'
18
19const getGuitarsTool = {
20 name: 'get_guitars',
21 description: 'List the guitars in stock',
22 inputSchema: { type: 'object', properties: {} },
23} satisfies Tool
24
25const ANTHROPIC_REPLY = [
26 {
27 type: 'message_start',
28 message: {
29 id: 'msg_prompt_cache_wire',
30 type: 'message',
31 role: 'assistant',
32 content: [],
33 model: 'claude-sonnet-4-6',
34 stop_reason: null,
35 stop_sequence: null,
36 usage: { input_tokens: 5, output_tokens: 0 },
37 },
38 },
39 {
40 type: 'content_block_start',
41 index: 0,
42 content_block: { type: 'text', text: '' },
43 },
44 {
45 type: 'content_block_delta',
46 index: 0,
47 delta: { type: 'text_delta', text: 'ok' },
48 },
49 { type: 'content_block_stop', index: 0 },
50 {
51 type: 'message_delta',
52 delta: { stop_reason: 'end_turn', stop_sequence: null },
53 usage: { output_tokens: 1 },
54 },
55 { type: 'message_stop' },
56]
57
58const OPENAI_REPLY = [
59 {
60 type: 'response.created',
61 response: {
62 id: 'resp_prompt_cache_wire',
63 status: 'in_progress',
64 output: [],
65 },
66 },
67 {
68 type: 'response.output_text.delta',
69 item_id: 'msg_prompt_cache_wire',
70 output_index: 0,
71 content_index: 0,
72 delta: 'ok',
73 },
74 {
75 type: 'response.completed',
76 response: {
77 id: 'resp_prompt_cache_wire',
78 status: 'completed',
79 output: [],
80 usage: { input_tokens: 5, output_tokens: 1, total_tokens: 6 },
81 },
82 },
83]
84
85/** Sends the events as one SSE body. Both SDKs read the `event:` line. */
86function sseResponse(events: Array<{ type: string }>) {
87 const body = events
88 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
89 .join('')
90 return new Response(body, {
91 headers: { 'Content-Type': 'text/event-stream' },
92 })
93}
94
95/** Runs one chat turn to the end. No `promptCache` means the default. */
96async function runTurn(
97 adapter: AnyTextAdapter,
98 promptCache?: PromptCacheRetention,
99) {
100 for await (const _ of chat({
101 adapter,
102 messages: [
103 {
104 role: 'user',
105 content: '[prompt-cache-wire] which guitars are in stock?',
106 },
107 ],
108 systemPrompts: ['You help the customers of a guitar shop.'],
109 tools: [getGuitarsTool],
110 threadId: THREAD_ID,
111 ...(promptCache && { promptCache }),
112 })) {
113 // Drain the stream.
114 }
115}
116
117export const Route = createFileRoute('/api/prompt-cache-wire')({
118 server: {
119 handlers: {
120 POST: async () => {
121 const bodies: Array<unknown> = []
122 const fetchReplying =
123 (events: Array<{ type: string }>): typeof fetch =>
124 async (input, init) => {
125 bodies.push(await new Request(input, init).json())
126 return sseResponse(events)
127 }
128 const anthropic = createAnthropicChat(
129 'claude-sonnet-4-6',
130 'sk-ant-e2e-test-dummy-key',
131 { fetch: fetchReplying(ANTHROPIC_REPLY) },
132 )
133 const openai = createOpenaiChat('gpt-5.2', 'sk-e2e-test-dummy-key', {
134 fetch: fetchReplying(OPENAI_REPLY),
135 })
136
137 try {
138 await runTurn(anthropic)
139 await runTurn(anthropic, 'none')
140 await runTurn(openai)
141 await runTurn(openai, 'none')
142 } catch (error) {
143 return Response.json({
144 error: error instanceof Error ? error.message : String(error),
145 })
146 }
147
148 const [anthropicDefault, anthropicNone, openaiDefault, openaiNone] =
149 bodies
150 return Response.json({
151 anthropic: { default: anthropicDefault, none: anthropicNone },
152 openai: { default: openaiDefault, none: openaiNone },
153 })
154 },
155 },
156 },
157})