Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createChatOptions,
6} from '@tanstack/ai'
7import { StreamProcessor, uiMessagesToWire } from '@tanstack/ai/client'
8import { createOpenaiChat } from '@tanstack/ai-openai'
9
10const DUMMY_KEY = 'sk-e2e-test-dummy-key'
11
12/** A Responses stream with one answer item. Only the first call has a phase. */
13function answerStream(call: number): Response {
14 const id = `msg_answer_${call}`
15 const item = {
16 id,
17 type: 'message',
18 role: 'assistant',
19 status: 'completed',
20 ...(call === 1 ? { phase: 'final_answer' } : {}),
21 content: [{ type: 'output_text', text: 'Hi there', annotations: [] }],
22 }
23 const events = [
24 {
25 type: 'response.output_text.delta',
26 item_id: id,
27 output_index: 0,
28 content_index: 0,
29 delta: 'Hi there',
30 },
31 {
32 type: 'response.completed',
33 response: {
34 id: `resp_answer_${call}`,
35 object: 'response',
36 status: 'completed',
37 output: [item],
38 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
39 },
40 },
41 ]
42 return new Response(
43 events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(''),
44 { headers: { 'Content-Type': 'text/event-stream' } },
45 )
46}
47
48type InputItem = Record<string, unknown> & { role?: string }
49
50/**
51 * Turn 1 runs on OpenAI Responses and answers with one `final_answer` item.
52 * The client keeps the turn and sends it back over the wire. Turn 2 sends
53 * that history to the same model, then to another model. The route returns
54 * the assistant items of each turn-2 request.
55 */
56export const Route = createFileRoute('/api/responses-answer-items-wire')({
57 server: {
58 handlers: {
59 POST: async () => {
60 try {
61 const bodies: Array<{ input: Array<InputItem> }> = []
62 const fetch: typeof globalThis.fetch = async (input, init) => {
63 const request =
64 input instanceof Request ? input : new Request(input, init)
65 bodies.push(JSON.parse(await request.text()))
66 return answerStream(bodies.length)
67 }
68 const sameModel = createOpenaiChat('gpt-5.5', DUMMY_KEY, { fetch })
69 const otherModel = createOpenaiChat('gpt-5.2', DUMMY_KEY, { fetch })
70
71 const client = new StreamProcessor({})
72 client.addUserMessage('Hi')
73 for await (const chunk of chat({
74 ...createChatOptions({ adapter: sameModel }),
75 messages: [{ role: 'user', content: 'Hi' }],
76 stream: true,
77 })) {
78 client.processChunk(chunk)
79 }
80 client.finalizeStream()
81 client.addUserMessage('Again')
82
83 const params = await chatParamsFromRequestBody({
84 threadId: 'responses-answer-items',
85 runId: 'responses-answer-items-2',
86 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
87 messages: JSON.parse(
88 JSON.stringify(uiMessagesToWire(client.getMessages())),
89 ),
90 tools: [],
91 context: [],
92 })
93 for (const adapter of [sameModel, otherModel]) {
94 for await (const _ of chat({
95 ...createChatOptions({ adapter }),
96 messages: params.messages,
97 stream: true,
98 })) {
99 // Drain the stream.
100 }
101 }
102
103 const assistantItems = (index: number) =>
104 (bodies[index]?.input ?? []).filter(
105 (item) => item.role === 'assistant',
106 )
107 return Response.json({
108 ok: true,
109 calls: bodies.length,
110 sameModel: assistantItems(1),
111 otherModel: assistantItems(2),
112 })
113 } catch (error) {
114 return Response.json({
115 ok: false,
116 error: error instanceof Error ? error.message : String(error),
117 })
118 }
119 },
120 },
121 },
122})