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 threadId: 'responses-answer-items-wire',
75 ...createChatOptions({ adapter: sameModel }),
76 messages: [{ role: 'user', content: 'Hi' }],
77 stream: true,
78 })) {
79 client.processChunk(chunk)
80 }
81 client.finalizeStream()
82 client.addUserMessage('Again')
83
84 const params = await chatParamsFromRequestBody({
85 threadId: 'responses-answer-items',
86 runId: 'responses-answer-items-2',
87 // `JSON.parse(JSON.stringify(...))` stands in for the HTTP hop.
88 messages: JSON.parse(
89 JSON.stringify(uiMessagesToWire(client.getMessages())),
90 ),
91 tools: [],
92 context: [],
93 })
94 for (const adapter of [sameModel, otherModel]) {
95 for await (const _ of chat({
96 threadId: 'responses-answer-items-wire',
97 ...createChatOptions({ adapter }),
98 messages: params.messages,
99 stream: true,
100 })) {
101 // Drain the stream.
102 }
103 }
104
105 const assistantItems = (index: number) =>
106 (bodies[index]?.input ?? []).filter(
107 (item) => item.role === 'assistant',
108 )
109 return Response.json({
110 ok: true,
111 calls: bodies.length,
112 sameModel: assistantItems(1),
113 otherModel: assistantItems(2),
114 })
115 } catch (error) {
116 return Response.json({
117 ok: false,
118 error: error instanceof Error ? error.message : String(error),
119 })
120 }
121 },
122 },
123 },
124})