Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.structured-output-length-wire.ts

209 lines6.9 KB

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 })
32​
33const outputSchema = {
34 type: 'object',
35 properties: { title: { type: 'string' } },
36 required: ['title'],
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 }
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 }
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 ...createChatOptions({ adapter: compatible('gpt-4o') }),
101 messages: [{ role: 'user', content: 'Give me a title' }],
102 outputSchema,
103 }),
104 )
105​
106 const openRouter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
107 httpClient: new HTTPClient({
108 fetcher: async () => lengthResponse(content),
109 }),
110 })
111 errors[`openrouter-${label}`] = await errorOf(() =>
112 chat({
113 ...createChatOptions({ adapter: openRouter }),
114 messages: [{ role: 'user', content: 'Give me a title' }],
115 outputSchema,
116 }),
117 )
118 }
119​
120 // A pre-4.5 model takes the forced-tool `structuredOutput()` path
121 // (4.5+ use the native combined path). The forced tool call stopped
122 // at max_tokens, with partial input.
123 const anthropic = createAnthropicChat('claude-opus-4-1', DUMMY_KEY, {
124 fetch: async () =>
125 Response.json({
126 id: 'msg_length',
127 type: 'message',
128 role: 'assistant',
129 model: 'claude-opus-4-1',
130 content: [
131 {
132 type: 'tool_use',
133 id: 'toolu_length',
134 name: 'structured_output',
135 input: {},
136 },
137 ],
138 stop_reason: 'max_tokens',
139 stop_sequence: null,
140 usage: { input_tokens: 10, output_tokens: 5 },
141 }),
142 })
143 errors['anthropic-truncated'] = await errorOf(() =>
144 chat({
145 ...createChatOptions({ adapter: anthropic }),
146 messages: [{ role: 'user', content: 'Give me a title' }],
147 outputSchema,
148 }),
149 )
150​
151 errors['mistral-truncated'] = await withServer(
152 {
153 id: 'cmpl-length',
154 object: 'chat.completion',
155 created: 1,
156 model: 'mistral-large-latest',
157 choices: [
158 {
159 index: 0,
160 message: { role: 'assistant', content: '{"title":"cut o' },
161 finish_reason: 'length',
162 },
163 ],
164 usage: {
165 prompt_tokens: 10,
166 completion_tokens: 5,
167 total_tokens: 15,
168 },
169 },
170 (baseURL) =>
171 errorOf(() =>
172 chat({
173 ...createChatOptions({
174 adapter: createMistralText(
175 'mistral-large-latest',
176 DUMMY_KEY,
177 { baseURL },
178 ),
179 }),
180 messages: [{ role: 'user', content: 'Give me a title' }],
181 outputSchema,
182 }),
183 ),
184 )
185​
186 errors['ollama-truncated'] = await withServer(
187 {
188 model: 'mistral',
189 created_at: '2026-01-01T00:00:00Z',
190 message: { role: 'assistant', content: '{"title":"cut o' },
191 done: true,
192 done_reason: 'length',
193 },
194 (baseURL) =>
195 errorOf(() =>
196 chat({
197 ...createChatOptions({
198 adapter: createOllamaChat('mistral', { baseURL }),
199 }),
200 messages: [{ role: 'user', content: 'Give me a title' }],
201 outputSchema,
202 }),
203 ),
204 )
205 return Response.json({ errors })
206 },
207 },
208 },
209})