Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { openaiCompatible } from '@tanstack/ai-openai/compatible'
4import { createOpenRouterText } from '@tanstack/ai-openrouter'
5import { HTTPClient } from '@openrouter/sdk'
6
7const DUMMY_KEY = 'sk-e2e-test-dummy-key'
8
9/** A streamed chat completion that stops at the output cap. */
10function lengthResponse(content: string): Response {
11 const chunk = (delta: Record<string, unknown>, finishReason: string | null) =>
12 `data: ${JSON.stringify({
13 id: 'chatcmpl-length',
14 object: 'chat.completion.chunk',
15 created: 1,
16 model: 'gpt-4o',
17 choices: [{ index: 0, delta, finish_reason: finishReason }],
18 })}\n\n`
19 const body =
20 (content ? chunk({ role: 'assistant', content }, null) : '') +
21 chunk({}, 'length') +
22 'data: [DONE]\n\n'
23 return new Response(body, {
24 headers: { 'Content-Type': 'text/event-stream' },
25 })
26}
27
28const outputSchema = {
29 type: 'object',
30 properties: { title: { type: 'string' } },
31 required: ['title'],
32}
33
34async function errorOf(run: () => Promise<unknown>): Promise<string | null> {
35 try {
36 await run()
37 return null
38 } catch (error) {
39 return error instanceof Error ? error.message : String(error)
40 }
41}
42
43/**
44 * `chat({ outputSchema })` on a response that stopped at the output cap
45 * (`finish_reason: "length"`). `chat()` takes the adapter's streaming
46 * structured-output path. A scripted `fetch` returns a truncated JSON
47 * document and, for a reasoning model that spent the budget, empty content.
48 * The companion spec checks that each adapter reports the token limit
49 * instead of a JSON parse or empty-content error. No aimock fixture is used.
50 */
51export const Route = createFileRoute('/api/structured-output-length-wire')({
52 server: {
53 handlers: {
54 POST: async () => {
55 const errors: Record<string, string | null> = {}
56 for (const [label, content] of [
57 ['truncated', '{"title":"cut o'],
58 ['empty', ''],
59 ] as const) {
60 const compatible = openaiCompatible({
61 name: 'custom-compatible',
62 baseURL: 'http://127.0.0.1:1/v1',
63 apiKey: DUMMY_KEY,
64 models: ['gpt-4o'],
65 maxRetries: 0,
66 fetch: async () => lengthResponse(content),
67 })
68 errors[`compatible-${label}`] = await errorOf(() =>
69 chat({
70 ...createChatOptions({ adapter: compatible('gpt-4o') }),
71 messages: [{ role: 'user', content: 'Give me a title' }],
72 outputSchema,
73 }),
74 )
75
76 const openRouter = createOpenRouterText('openai/gpt-4o', DUMMY_KEY, {
77 httpClient: new HTTPClient({
78 fetcher: async () => lengthResponse(content),
79 }),
80 })
81 errors[`openrouter-${label}`] = await errorOf(() =>
82 chat({
83 ...createChatOptions({ adapter: openRouter }),
84 messages: [{ role: 'user', content: 'Give me a title' }],
85 outputSchema,
86 }),
87 )
88 }
89 return Response.json({ errors })
90 },
91 },
92 },
93})