Open History to see the last commit
1import { createServer } from 'node:http'
2import { createFileRoute } from '@tanstack/react-router'
3import { chat, createChatOptions } from '@tanstack/ai'
4import { createAnthropicChat } from '@tanstack/ai-anthropic'
5import { createMistralText } from '@tanstack/ai-mistral'
6import { createOllamaChat } from '@tanstack/ai-ollama'
7import { openaiCompatible } from '@tanstack/ai-openai/compatible'
8import { createOpenRouterText } from '@tanstack/ai-openrouter'
9import { HTTPClient } from '@openrouter/sdk'
10import type { AddressInfo } from 'node:net'
11
12const DUMMY_KEY = 'sk-e2e-test-dummy-key'
13
14/** A streamed chat completion that stops at the output cap. */
15function lengthResponse(content: string): Response {
16 const chunk = (delta: Record<string, unknown>, finishReason: string | null) =>
17 `data: ${JSON.stringify({
18 id: 'chatcmpl-length',
19 object: 'chat.completion.chunk',
20 created: 1,
21 model: 'gpt-4o',
22 choices: [{ index: 0, delta, finish_reason: finishReason }],
23 })}\n\n`
24 const body =
25 (content ? chunk({ role: 'assistant', content }, null) : '') +
26 chunk({}, 'length') +
27 'data: [DONE]\n\n'
28 return new Response(body, {
29 headers: { 'Content-Type': 'text/event-stream' },
30 })
31}
32
33const outputSchema = {
34 type: 'object',
35 properties: { title: { type: 'string' } },
36 required: ['title'],
37}
38
39async function errorOf(run: () => Promise<unknown>): Promise<string | null> {
40 try {
41 await run()
42 return null
43 } catch (error) {
44 return error instanceof Error ? error.message : String(error)
45 }
46}
47
48/** Answers every request with `body`, for clients that take no custom `fetch`. */
49async function withServer<T>(
50 body: unknown,
51 run: (baseURL: string) => Promise<T>,
52): Promise<T> {
53 const server = createServer((req, res) => {
54 req.resume().on('end', () => {
55 res.writeHead(200, { 'Content-Type': 'application/json' })
56 res.end(JSON.stringify(body))
57 })
58 })
59 await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
60 try {
61 return await run(
62 `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
63 )
64 } finally {
65 server.close()
66 server.closeAllConnections()
67 }
68}
69
70/**
71 * `chat({ outputSchema })` on a response that stopped at the output cap
72 * (`finish_reason: "length"`). For OpenAI-compatible and OpenRouter,
73 * `chat()` takes the adapter's streaming structured-output path. A scripted
74 * `fetch` returns a truncated JSON document and, for a reasoning model that
75 * spent the budget, empty content. Anthropic, Mistral and Ollama have no
76 * streaming structured output, so `chat()` calls their `structuredOutput()`;
77 * Mistral and Ollama take no custom `fetch` and get a local server instead.
78 * The companion spec checks that each adapter reports the token limit
79 * instead of a JSON parse or empty-content error. No aimock fixture is used.
80 */
81export const Route = createFileRoute('/api/structured-output-length-wire')({
82 server: {
83 handlers: {
84 POST: async () => {
85 const errors: Record<string, string | null> = {}
86 for (const [label, content] of [
87 ['truncated', '{"title":"cut o'],
88 ['empty', ''],
89 ] as const) {
90 const compatible = openaiCompatible({
91 name: 'custom-compatible',
92 baseURL: 'http://127.0.0.1:1/v1',
93 apiKey: DUMMY_KEY,
94 models: ['gpt-4o'],
95 maxRetries: 0,
96 fetch: async () => lengthResponse(content),
97 })
98 errors[`compatible-${label}`] = await errorOf(() =>
99 chat({
100 threadId: 'structured-output-length-wire',
101 ...createChatOptions({ adapter: compatible('gpt-4o') }),
102 messages: [{ role: 'user', content: 'Give me a title' }],
103 outputSchema,
104 }),
105 )
106
107 const openRouter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
108 httpClient: new HTTPClient({
109 fetcher: async () => lengthResponse(content),
110 }),
111 })
112 errors[`openrouter-${label}`] = await errorOf(() =>
113 chat({
114 threadId: 'structured-output-length-wire',
115 ...createChatOptions({ adapter: openRouter }),
116 messages: [{ role: 'user', content: 'Give me a title' }],
117 outputSchema,
118 }),
119 )
120 }
121
122 // A pre-4.5 model takes the forced-tool `structuredOutput()` path
123 // (4.5+ use the native combined path). The forced tool call stopped
124 // at max_tokens, with partial input.
125 const anthropic = createAnthropicChat('claude-opus-4-1', DUMMY_KEY, {
126 fetch: async () =>
127 Response.json({
128 id: 'msg_length',
129 type: 'message',
130 role: 'assistant',
131 model: 'claude-opus-4-1',
132 content: [
133 {
134 type: 'tool_use',
135 id: 'toolu_length',
136 name: 'structured_output',
137 input: {},
138 },
139 ],
140 stop_reason: 'max_tokens',
141 stop_sequence: null,
142 usage: { input_tokens: 10, output_tokens: 5 },
143 }),
144 })
145 errors['anthropic-truncated'] = await errorOf(() =>
146 chat({
147 threadId: 'structured-output-length-wire',
148 ...createChatOptions({ adapter: anthropic }),
149 messages: [{ role: 'user', content: 'Give me a title' }],
150 outputSchema,
151 }),
152 )
153
154 errors['mistral-truncated'] = await withServer(
155 {
156 id: 'cmpl-length',
157 object: 'chat.completion',
158 created: 1,
159 model: 'mistral-large-latest',
160 choices: [
161 {
162 index: 0,
163 message: { role: 'assistant', content: '{"title":"cut o' },
164 finish_reason: 'length',
165 },
166 ],
167 usage: {
168 prompt_tokens: 10,
169 completion_tokens: 5,
170 total_tokens: 15,
171 },
172 },
173 (baseURL) =>
174 errorOf(() =>
175 chat({
176 threadId: 'structured-output-length-wire',
177 ...createChatOptions({
178 adapter: createMistralText(
179 'mistral-large-latest',
180 DUMMY_KEY,
181 { baseURL },
182 ),
183 }),
184 messages: [{ role: 'user', content: 'Give me a title' }],
185 outputSchema,
186 }),
187 ),
188 )
189
190 errors['ollama-truncated'] = await withServer(
191 {
192 model: 'mistral',
193 created_at: '2026-01-01T00:00:00Z',
194 message: { role: 'assistant', content: '{"title":"cut o' },
195 done: true,
196 done_reason: 'length',
197 },
198 (baseURL) =>
199 errorOf(() =>
200 chat({
201 threadId: 'structured-output-length-wire',
202 ...createChatOptions({
203 adapter: createOllamaChat('mistral', { baseURL }),
204 }),
205 messages: [{ role: 'user', content: 'Give me a title' }],
206 outputSchema,
207 }),
208 ),
209 )
210 return Response.json({ errors })
211 },
212 },
213 },
214})