Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import {
5 createOpenaiChat,
6 createOpenaiChatCompletions,
7} from '@tanstack/ai-openai'
8
9const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
10const DUMMY_KEY = 'sk-e2e-test-dummy-key'
11// The SDKs must not retry the 429 themselves.
12const config = { maxRetries: 0 }
13
14const adapters = {
15 anthropic: () =>
16 createAnthropicChat('claude-haiku-4-5', DUMMY_KEY, {
17 ...config,
18 baseURL: LLMOCK_DEFAULT_BASE,
19 }),
20 'openai-responses': () =>
21 createOpenaiChat('gpt-4o', DUMMY_KEY, {
22 ...config,
23 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
24 }),
25 'openai-chat-completions': () =>
26 createOpenaiChatCompletions('gpt-4o', DUMMY_KEY, {
27 ...config,
28 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
29 }),
30}
31
32/**
33 * `chat({ retry })` against `[chat-retry]`: aimock answers the first call with
34 * a 429 and `Retry-After: 1`, and the second call with text. `testId` gives the
35 * test its own aimock `sequenceIndex` count.
36 */
37async function retryThenAnswer(testId: string | undefined) {
38 const adapter = createOpenaiChatCompletions('gpt-4o', DUMMY_KEY, {
39 ...config,
40 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
41 ...(testId ? { defaultHeaders: { 'X-Test-Id': testId } } : {}),
42 })
43 const types: Array<string> = []
44 let text = ''
45 for await (const chunk of chat({
46 threadId: 'retry-after',
47 adapter,
48 messages: [{ role: 'user', content: '[chat-retry] say hello' }],
49 retry: { maxRetries: 1 },
50 })) {
51 types.push(chunk.type)
52 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
53 }
54 return Response.json({ types, text })
55}
56
57/**
58 * Streams one chat against the aimock fixture in `fixtures/retry-after`. aimock
59 * answers with a 429 and `Retry-After: 7`. Returns the `retryAfterMs` of the
60 * `RUN_ERROR` that `chat()` yields. `?api=` picks the adapter.
61 * `?mode=retry` runs `retryThenAnswer`.
62 */
63export const Route = createFileRoute('/api/retry-after')({
64 server: {
65 handlers: {
66 POST: async ({ request }) => {
67 const url = new URL(request.url)
68 if (url.searchParams.get('mode') === 'retry') {
69 return retryThenAnswer(url.searchParams.get('testId') ?? undefined)
70 }
71 const api = url.searchParams.get('api')
72 if (
73 api !== 'anthropic' &&
74 api !== 'openai-responses' &&
75 api !== 'openai-chat-completions'
76 ) {
77 return Response.json({ ok: false, error: `Unknown api: ${api}` })
78 }
79
80 let runError: Record<string, unknown> | undefined
81 try {
82 for await (const chunk of chat({
83 threadId: 'retry-after',
84 adapter: adapters[api](),
85 messages: [{ role: 'user', content: '[retry-after] say hello' }],
86 })) {
87 if (chunk.type === 'RUN_ERROR') {
88 runError = {
89 message: chunk.message,
90 retryAfterMs: chunk.metadata?.tanstack?.retryAfterMs,
91 }
92 }
93 }
94 } catch (error) {
95 return Response.json({
96 ok: false,
97 error: error instanceof Error ? error.message : String(error),
98 })
99 }
100
101 return Response.json({ ok: true, runError })
102 },
103 },
104 },
105})