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'
11const config = { maxRetries: 0 }
12
13const apis = {
14 anthropic: {
15 prompt: '[context-overflow-anthropic] say hello',
16 adapter: () =>
17 createAnthropicChat('claude-haiku-4-5', DUMMY_KEY, {
18 ...config,
19 baseURL: LLMOCK_DEFAULT_BASE,
20 }),
21 },
22 'openai-responses': {
23 prompt: '[context-overflow-openai] say hello',
24 adapter: () =>
25 createOpenaiChat('gpt-4o', DUMMY_KEY, {
26 ...config,
27 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
28 }),
29 },
30 'openai-chat-completions': {
31 prompt: '[context-overflow-openai] say hello',
32 adapter: () =>
33 createOpenaiChatCompletions('gpt-4o', DUMMY_KEY, {
34 ...config,
35 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
36 }),
37 },
38}
39
40/**
41 * Streams one chat against the aimock fixtures in `fixtures/context-overflow`.
42 * aimock answers with the provider's context overflow error. Returns the
43 * `code` and `message` of the `RUN_ERROR` that `chat()` yields. `?api=` picks
44 * the adapter.
45 */
46export const Route = createFileRoute('/api/context-overflow')({
47 server: {
48 handlers: {
49 POST: async ({ request }) => {
50 const api = new URL(request.url).searchParams.get('api')
51 if (
52 api !== 'anthropic' &&
53 api !== 'openai-responses' &&
54 api !== 'openai-chat-completions'
55 ) {
56 return Response.json({ ok: false, error: `Unknown api: ${api}` })
57 }
58
59 let runError: { code?: string; message: string } | undefined
60 try {
61 for await (const chunk of chat({
62 threadId: 'context-overflow',
63 adapter: apis[api].adapter(),
64 messages: [{ role: 'user', content: apis[api].prompt }],
65 })) {
66 if (chunk.type === 'RUN_ERROR') {
67 runError = { code: chunk.code, message: chunk.message }
68 }
69 }
70 } catch (error) {
71 return Response.json({
72 ok: false,
73 error: error instanceof Error ? error.message : String(error),
74 })
75 }
76
77 return Response.json({ ok: true, runError })
78 },
79 },
80 },
81})