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

api.openai-completed-response-text.ts

136 lines3.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { createOpenaiChat } from '@tanstack/ai-openai'
4import { z } from 'zod'
5​
6const DUMMY_KEY = 'sk-e2e-test-dummy-key'
7const FINAL_TEXT = 'Recovered from response.completed'
8​
9function makeCompletionOnlyResponsesStream(
10 missingStructuredTerminal = false,
11): ReadableStream<Uint8Array> {
12 const encoder = new TextEncoder()
13 const responseId = 'resp_completion_only'
14 const events: Array<Record<string, unknown>> = [
15 {
16 type: 'response.created',
17 response: {
18 id: responseId,
19 object: 'response',
20 status: 'in_progress',
21 model: 'gpt-5.2',
22 output: [],
23 },
24 },
25 {
26 type: 'response.content_part.added',
27 response_id: responseId,
28 item_id: 'msg_completion_only',
29 output_index: 0,
30 content_index: 0,
31 part: { type: 'output_text', text: '' },
32 },
33 {
34 type: 'response.completed',
35 response: {
36 id: responseId,
37 object: 'response',
38 status: 'completed',
39 model: 'gpt-5.2',
40 output: [
41 {
42 id: 'msg_completion_only',
43 type: 'message',
44 role: 'assistant',
45 status: 'completed',
46 content: [
47 { type: 'output_text', text: FINAL_TEXT, annotations: [] },
48 ],
49 },
50 ],
51 usage: {
52 input_tokens: 5,
53 output_tokens: 4,
54 total_tokens: 9,
55 },
56 },
57 },
58 ]
59 if (missingStructuredTerminal) {
60 events.splice(1, 2, {
61 type: 'response.output_text.delta',
62 delta: '{"answer":"partial"}',
63 })
64 }
65​
66 return new ReadableStream<Uint8Array>({
67 start(controller) {
68 for (const event of events) {
69 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
70 }
71 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
72 controller.close()
73 },
74 })
76​
77export const Route = createFileRoute('/api/openai-completed-response-text')({
78 server: {
79 handlers: {
80 POST: async ({ request }) => {
81 const missingStructuredTerminal =
82 new URL(request.url).searchParams.get('scenario') ===
83 'structured-missing-terminal'
84 const adapter = createOpenaiChat('gpt-5.2', DUMMY_KEY, {
85 fetch: async () =>
86 new Response(
87 makeCompletionOnlyResponsesStream(missingStructuredTerminal),
88 {
89 status: 200,
90 headers: { 'Content-Type': 'text/event-stream' },
91 },
92 ),
93 })
94​
95 if (missingStructuredTerminal) {
96 let text = ''
97 let errorCode: string | undefined
98 let completed = false
99 const events: Array<string> = []
100 for await (const chunk of chat({
101 threadId: 'openai-completed-response-text',
102 adapter,
103 messages: [{ role: 'user', content: 'Extract an answer' }],
104 outputSchema: z.object({ answer: z.string() }),
105 stream: true,
106 })) {
107 events.push(chunk.type)
108 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
109 if (chunk.type === 'RUN_ERROR') errorCode = chunk.code
110 if (
111 chunk.type === 'CUSTOM' &&
112 chunk.name === 'structured-output.complete'
113 ) {
114 completed = true
115 }
116 }
117 return Response.json({ events, text, errorCode, completed })
118 }
119​
120 const { text } = await chat({
121 threadId: 'openai-completed-response-text',
122 adapter,
123 messages: [
124 {
125 role: 'user',
126 content: '[completed-response-text] answer carefully',
127 },
128 ],
129 stream: false,
130 })
131​
132 return Response.json({ text })
133 },
134 },
135 },
136})