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 adapter,
47 messages: [{ role: 'user', content: '[chat-retry] say hello' }],
48 retry: { maxRetries: 1 },
49 })) {
50 types.push(chunk.type)
51 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
52 }
53 return Response.json({ types, text })
54}
55
56/**
57 * Streams one chat against the aimock fixture in `fixtures/retry-after`. aimock
58 * answers with a 429 and `Retry-After: 7`. Returns the `retryAfterMs` of the
59 * `RUN_ERROR` that `chat()` yields. `?api=` picks the adapter.
60 * `?mode=retry` runs `retryThenAnswer`.
61 */
62export const Route = createFileRoute('/api/retry-after')({
63 server: {
64 handlers: {
65 POST: async ({ request }) => {
66 const url = new URL(request.url)
67 if (url.searchParams.get('mode') === 'retry') {
68 return retryThenAnswer(url.searchParams.get('testId') ?? undefined)
69 }
70 const api = url.searchParams.get('api')
71 if (
72 api !== 'anthropic' &&
73 api !== 'openai-responses' &&
74 api !== 'openai-chat-completions'
75 ) {
76 return Response.json({ ok: false, error: `Unknown api: ${api}` })
77 }
78
79 let runError: Record<string, unknown> | undefined
80 try {
81 for await (const chunk of chat({
82 adapter: adapters[api](),
83 messages: [{ role: 'user', content: '[retry-after] say hello' }],
84 })) {
85 if (chunk.type === 'RUN_ERROR') {
86 runError = {
87 message: chunk.message,
88 retryAfterMs: chunk.metadata?.tanstack?.retryAfterMs,
89 }
90 }
91 }
92 } catch (error) {
93 return Response.json({
94 ok: false,
95 error: error instanceof Error ? error.message : String(error),
96 })
97 }
98
99 return Response.json({ ok: true, runError })
100 },
101 },
102 },
103})