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

api.openai-computer-use-wire.ts

168 lines4.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createOpenaiChat } from '@tanstack/ai-openai'
4import { computerUseTool } from '@tanstack/ai-openai/tools'
5​
6const DUMMY_KEY = 'sk-e2e-test-dummy-key'
7const SCREENSHOT = 'iVBORw0KGgo='
8​
9const safetyCheck = {
10 id: 'sc_e2e',
11 code: 'malicious_instructions',
12 message: 'The page asks the model to do something else.',
14​
15const computerCall = {
16 type: 'computer_call',
17 id: 'cu_e2e',
18 call_id: 'call_cu_e2e',
19 status: 'completed',
20 action: { type: 'click', button: 'left', x: 10, y: 20 },
21 pending_safety_checks: [safetyCheck],
23​
24// The computer tool of the newer models sends a batch of actions.
25const batchCall = {
26 type: 'computer_call',
27 id: 'cu_e2e_batch',
28 call_id: 'call_cu_e2e_batch',
29 status: 'completed',
30 actions: [
31 { type: 'click', button: 'left', x: 10, y: 20 },
32 { type: 'type', text: 'hello' },
33 ],
34 pending_safety_checks: [],
36​
37const screenshot = [
38 {
39 type: 'image' as const,
40 source: { type: 'data' as const, value: SCREENSHOT, mimeType: 'image/png' },
41 },
43​
44const answer = {
45 type: 'message',
46 id: 'msg_cu_e2e',
47 role: 'assistant',
48 status: 'completed',
49 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
51​
52function responseStream(
53 id: string,
54 output: Array<unknown>,
55): ReadableStream<Uint8Array> {
56 const encoder = new TextEncoder()
57 const events = [
58 {
59 type: 'response.created',
60 response: { id, object: 'response', status: 'in_progress', output: [] },
61 },
62 {
63 type: 'response.completed',
64 response: {
65 id,
66 object: 'response',
67 status: 'completed',
68 output,
69 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
70 },
71 },
72 ]
73 return new ReadableStream<Uint8Array>({
74 start(controller) {
75 for (const event of events) {
76 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
77 }
78 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
79 controller.close()
80 },
81 })
83​
84/**
85 * Drives the OpenAI Responses adapter through one computer use step. A
86 * custom `fetch` answers the first request with a `computer_call` and the
87 * second with text, and records each request body. aimock cannot send a
88 * `computer_call`, so this route serves the stream itself.
89 *
90 * `?tool=computer` uses the `computer` tool of `gpt-6.1-sol`, with a batch
91 * of actions. Anything else uses `computer_use_preview`.
92 */
93export const Route = createFileRoute('/api/openai-computer-use-wire')({
94 server: {
95 handlers: {
96 POST: async ({ request }) => {
97 const batch =
98 new URL(request.url).searchParams.get('tool') === 'computer'
99 const requestBodies: Array<unknown> = []
100 const mockFetch: typeof fetch = async (input, init) => {
101 const req =
102 input instanceof Request ? input : new Request(input, init)
103 requestBodies.push(JSON.parse(await req.text()))
104 const stream =
105 requestBodies.length === 1
106 ? responseStream('resp_cu_e2e_1', [
107 batch ? batchCall : computerCall,
108 ])
109 : responseStream('resp_cu_e2e_2', [answer])
110 return new Response(stream, {
111 status: 200,
112 headers: { 'Content-Type': 'text/event-stream' },
113 })
114 }
115​
116 const toolInputs: Array<unknown> = []
117 const execute = async (input: unknown) => {
118 toolInputs.push(input)
119 return screenshot
120 }
121 const messages = [
122 { role: 'user' as const, content: 'Click the button.' },
123 ]
124 try {
125 const stream = batch
126 ? chat({
127 ...createChatOptions({
128 adapter: createOpenaiChat('gpt-6.1-sol', DUMMY_KEY, {
129 fetch: mockFetch,
130 }),
131 }),
132 messages,
133 tools: [{ ...computerUseTool({ type: 'computer' }), execute }],
134 })
135 : chat({
136 ...createChatOptions({
137 adapter: createOpenaiChat('computer-use-preview', DUMMY_KEY, {
138 fetch: mockFetch,
139 }),
140 }),
141 messages,
142 tools: [
143 {
144 ...computerUseTool({
145 type: 'computer_use_preview',
146 display_width: 1024,
147 display_height: 768,
148 environment: 'browser',
149 }),
150 execute,
151 },
152 ],
153 })
154 for await (const _ of stream) {
155 // Drain the stream.
156 }
157 } catch (error) {
158 return Response.json({
159 ok: false,
160 error: error instanceof Error ? error.message : String(error),
161 })
162 }
163​
164 return Response.json({ ok: true, toolInputs, requestBodies })
165 },
166 },
167 },
168})