Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { OpenAIBaseChatCompletionsTextAdapter } from '../src/adapters/chat-completions-text'
4import { OpenAIBaseResponsesTextAdapter } from '../src/adapters/responses-text'
5import { convertToolsToProviderFormat } from '../src/tools/tool-converter'
6import type OpenAI from 'openai'
7import type { StreamChunk, Tool } from '@tanstack/ai'
8
9const safetyCheck = {
10 id: 'sc_1',
11 code: 'malicious_instructions',
12 message: 'The page asks the model to do something else.',
13}
14
15async function* completed(output: Array<Record<string, unknown>>) {
16 yield* [
17 {
18 type: 'response.created',
19 response: { id: 'resp_1', model: 'm', status: 'in_progress' },
20 },
21 {
22 type: 'response.completed',
23 response: {
24 id: 'resp_1',
25 model: 'm',
26 status: 'completed',
27 output,
28 usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
29 },
30 },
31 ]
32}
33
34const answer = {
35 type: 'message',
36 id: 'msg_1',
37 role: 'assistant',
38 status: 'completed',
39 content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
40}
41
42const screenshot = [
43 {
44 type: 'image',
45 source: { type: 'data', value: 'iVBORw0KGgo=', mimeType: 'image/png' },
46 },
47]
48
49const screenshotOutput = {
50 type: 'computer_screenshot',
51 image_url: 'data:image/png;base64,iVBORw0KGgo=',
52 detail: 'original',
53}
54
55// The stub clients below implement only the one SDK method the adapter calls.
56// A full OpenAI client is too large to build, so they are cast.
57
58// The OpenAI adapter sends provider tools in their native shape.
59class TestAdapter extends OpenAIBaseResponsesTextAdapter<string> {
60 protected override convertTools(tools: Array<Tool>) {
61 return convertToolsToProviderFormat(tools)
62 }
63}
64
65// The portable tool, as `@tanstack/ai-computer-use` builds it.
66function genericComputerTool() {
67 return {
68 name: 'computer',
69 description: 'Use the computer.',
70 metadata: {
71 __kind: 'computer_use',
72 display: { width: 1280, height: 800 },
73 environment: 'linux',
74 capabilities: { zoom: false, cursorPosition: true },
75 },
76 execute: vi.fn(async (_input: unknown) => screenshot),
77 } satisfies Tool
78}
79
80async function runLoop(model: string, call: Record<string, unknown>) {
81 const create = vi
82 .fn()
83 .mockResolvedValueOnce(completed([call]))
84 .mockResolvedValueOnce(completed([answer]))
85 const client = {
86 responses: { create: (params: unknown) => create(params) },
87 } as unknown as OpenAI
88 const tool = genericComputerTool()
89 for await (const _ of chat({
90 adapter: new TestAdapter(model, 'openai', client),
91 messages: [{ role: 'user', content: 'Click the button.' }],
92 tools: [tool],
93 })) {
94 // Drain the stream.
95 }
96 const [first, second] = create.mock.calls.map(([params]) => params)
97 return { first, second, execute: tool.execute }
98}
99
100describe('portable computer tool on the Responses API', () => {
101 it('sends computer_use_preview to computer-use-preview and runs the single action', async () => {
102 const action = { type: 'click', button: 'left', x: 10, y: 20 }
103 const { first, second, execute } = await runLoop('computer-use-preview', {
104 type: 'computer_call',
105 id: 'cu_1',
106 call_id: 'call_cu',
107 status: 'completed',
108 action,
109 pending_safety_checks: [safetyCheck],
110 })
111
112 expect(first.tools).toEqual([
113 {
114 type: 'computer_use_preview',
115 display_width: 1280,
116 display_height: 800,
117 environment: 'linux',
118 },
119 ])
120 expect(execute.mock.calls[0]?.[0]).toEqual({
121 action,
122 pending_safety_checks: [safetyCheck],
123 })
124 expect(second.input).toContainEqual({
125 type: 'computer_call_output',
126 call_id: 'call_cu',
127 output: screenshotOutput,
128 acknowledged_safety_checks: [safetyCheck],
129 })
130 })
131
132 it('sends the computer tool to other models and runs the batch', async () => {
133 const actions = [
134 { type: 'click', button: 'left', x: 10, y: 20 },
135 { type: 'type', text: 'hello' },
136 ]
137 const { first, second, execute } = await runLoop('gpt-6.1-sol', {
138 type: 'computer_call',
139 id: 'cu_2',
140 call_id: 'call_batch',
141 status: 'completed',
142 actions,
143 pending_safety_checks: [safetyCheck],
144 })
145
146 expect(first.tools).toEqual([{ type: 'computer' }])
147 expect(execute.mock.calls[0]?.[0]).toEqual({
148 actions,
149 pending_safety_checks: [safetyCheck],
150 })
151 expect(second.input).toContainEqual({
152 type: 'computer_call_output',
153 call_id: 'call_batch',
154 output: screenshotOutput,
155 acknowledged_safety_checks: [safetyCheck],
156 })
157 })
158
159 it('keeps safety checks that do not parse on the tool input', async () => {
160 const action = { type: 'click', button: 'left', x: 10, y: 20 }
161 const badChecks = [{ code: 'x' }]
162 const { second, execute } = await runLoop('gpt-6.1-sol', {
163 type: 'computer_call',
164 id: 'cu_bad',
165 call_id: 'call_bad',
166 status: 'completed',
167 action,
168 pending_safety_checks: badChecks,
169 })
170
171 expect(execute.mock.calls[0]?.[0]).toEqual({
172 action,
173 pending_safety_checks: badChecks,
174 })
175 expect(second.input).toContainEqual({
176 type: 'computer_call_output',
177 call_id: 'call_bad',
178 output: screenshotOutput,
179 })
180 expect(JSON.stringify(second.input)).not.toContain(
181 'acknowledged_safety_checks',
182 )
183 })
184})
185
186class TestChatCompletionsAdapter extends OpenAIBaseChatCompletionsTextAdapter<string> {}
187
188describe('portable computer tool on the Chat Completions API', () => {
189 it('fails before any request', async () => {
190 const create = vi.fn()
191 const client = {
192 chat: { completions: { create } },
193 } as unknown as OpenAI
194 const chunks: Array<StreamChunk> = []
195 for await (const chunk of chat({
196 adapter: new TestChatCompletionsAdapter('gpt-6.1-sol', 'openai', client),
197 messages: [{ role: 'user', content: 'Click the button.' }],
198 tools: [genericComputerTool()],
199 })) {
200 chunks.push(chunk)
201 }
202
203 expect(create).not.toHaveBeenCalled()
204 expect(chunks).toContainEqual(
205 expect.objectContaining({
206 type: 'RUN_ERROR',
207 message:
208 'Computer use needs the Responses API. The Chat Completions API has no computer tool.',
209 }),
210 )
211 })
212})