Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenRouterText } from '@tanstack/ai-openrouter'
4import { HTTPClient } from '@openrouter/sdk'
5
6const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
7const DUMMY_KEY = 'sk-e2e-test-dummy-key'
8
9/**
10 * Drives the OpenRouter chat adapter with `retryCodes: ['429', '5XX']`
11 * against an aimock fixture that answers the first request with a 429 and the
12 * second with content. The companion spec asserts the SDK retried the 429 and
13 * the stream finished with the second response's text.
14 */
15export const Route = createFileRoute('/api/openrouter-retry-codes')({
16 server: {
17 handlers: {
18 POST: async ({ request }) => {
19 const url = new URL(request.url)
20 const testId = url.searchParams.get('testId') ?? undefined
21
22 const httpClient = new HTTPClient()
23 if (testId) {
24 httpClient.addHook('beforeRequest', (req) => {
25 const next = new Request(req)
26 next.headers.set('X-Test-Id', testId)
27 return next
28 })
29 }
30
31 const adapter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
32 serverURL: `${LLMOCK_DEFAULT_BASE}/v1`,
33 httpClient,
34 retryCodes: ['429', '5XX'],
35 })
36
37 let text = ''
38 let error: string | undefined
39 for await (const chunk of chat({
40 threadId: 'openrouter-retry-codes',
41 ...createChatOptions({ adapter }),
42 messages: [
43 { role: 'user', content: '[openrouter-retry-codes] say hello' },
44 ],
45 })) {
46 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
47 if (chunk.type === 'RUN_ERROR') error = chunk.message
48 }
49
50 return Response.json({ text, error: error ?? null })
51 },
52 },
53 },
54})