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

api.openai-computer-use-wire.ts

134 lines3.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​
15// The computer tool sends a batch of actions.
16const batchCall = {
17 type: 'computer_call',
18 id: 'cu_e2e_batch',
19 call_id: 'call_cu_e2e_batch',
20 status: 'completed',
21 actions: [
22 { type: 'click', button: 'left', x: 10, y: 20 },
23 { type: 'type', text: 'hello' },
24 ],
25 pending_safety_checks: [safetyCheck],
27​
28const screenshot = [
29 {
30 type: 'image' as const,
31 source: { type: 'data' as const, value: SCREENSHOT, mimeType: 'image/png' },
32 },
34​
35const answer = {
36 type: 'message',
37 id: 'msg_cu_e2e',
38 role: 'assistant',
39 status: 'completed',
40 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
42​
43function responseStream(
44 id: string,
45 output: Array<unknown>,
46): ReadableStream<Uint8Array> {
47 const encoder = new TextEncoder()
48 const events = [
49 {
50 type: 'response.created',
51 response: { id, object: 'response', status: 'in_progress', output: [] },
52 },
53 {
54 type: 'response.completed',
55 response: {
56 id,
57 object: 'response',
58 status: 'completed',
59 output,
60 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
61 },
62 },
63 ]
64 return new ReadableStream<Uint8Array>({
65 start(controller) {
66 for (const event of events) {
67 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
68 }
69 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
70 controller.close()
71 },
72 })
74​
75/**
76 * Drives the OpenAI Responses adapter through one computer use step. A
77 * custom `fetch` answers the first request with a `computer_call` and the
78 * second with text, and records each request body. aimock cannot send a
79 * `computer_call`, so this route serves the stream itself.
80 * It uses the `computer` tool of `gpt-6.1-sol`, with a batch of actions.
81 */
82export const Route = createFileRoute('/api/openai-computer-use-wire')({
83 server: {
84 handlers: {
85 POST: async () => {
86 const requestBodies: Array<unknown> = []
87 const mockFetch: typeof fetch = async (input, init) => {
88 const req =
89 input instanceof Request ? input : new Request(input, init)
90 requestBodies.push(JSON.parse(await req.text()))
91 const stream =
92 requestBodies.length === 1
93 ? responseStream('resp_cu_e2e_1', [batchCall])
94 : responseStream('resp_cu_e2e_2', [answer])
95 return new Response(stream, {
96 status: 200,
97 headers: { 'Content-Type': 'text/event-stream' },
98 })
99 }
100​
101 const toolInputs: Array<unknown> = []
102 const execute = async (input: unknown) => {
103 toolInputs.push(input)
104 return screenshot
105 }
106 const messages = [
107 { role: 'user' as const, content: 'Click the button.' },
108 ]
109 try {
110 const stream = chat({
111 threadId: 'openai-computer-use-wire',
112 ...createChatOptions({
113 adapter: createOpenaiChat('gpt-6.1-sol', DUMMY_KEY, {
114 fetch: mockFetch,
115 }),
116 }),
117 messages,
118 tools: [{ ...computerUseTool({ type: 'computer' }), execute }],
119 })
120 for await (const _ of stream) {
121 // Drain the stream.
122 }
123 } catch (error) {
124 return Response.json({
125 ok: false,
126 error: error instanceof Error ? error.message : String(error),
127 })
128 }
129​
130 return Response.json({ ok: true, toolInputs, requestBodies })
131 },
132 },
133 },
134})