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

computer-use.md

310 lines9.6 KB

1---
2title: Computer Use
3id: computer-use
4order: 8
5description: "Add computer use to a React chat. The model opens tanstack.com in Chromium, reads each screenshot, and clicks until it finds the computer use docs. The chat shows each screenshot."
6keywords:
7 - tanstack ai
8 - tutorial
9 - computer use
10 - createComputerUse
11 - playwrightComputer
12 - useChat
13 - openai
14 - tanstack start
15---
16​
17This tutorial adds `computerUse()` to a chat so the model can complete a task on a web page.
18​
19With computer use, the model sees only screenshots. It clicks, types, and scrolls on what it sees. In this tutorial, the model opens tanstack.com and finds the TanStack AI computer use docs. Each screenshot shows in your chat.
20​
21This tutorial uses React, TanStack Start, and OpenAI. It takes about 15 minutes.
22​
23## 1. Create a Start app
24​
25```bash
26npx @tanstack/cli@latest create
27```
28​
29Pick React. Then install the packages:
30​
31<!-- ::start:tabs variant="package-manager" mode="install" -->
32​
33react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
34​
35<!-- ::end:tabs -->
36​
37Download Chromium one time:
38​
39```bash
40npx playwright-core install chromium
41```
42​
43Put your OpenAI key in `.env.local`:
44​
45```bash
46OPENAI_API_KEY=sk-...
47```
48​
49## Client and server
50​
51The **server** owns the browser. It runs each action that the model asks for, then sends a screenshot back to the model.
52​
53The **client** sends the task. It shows each screenshot, so your user can see what the model sees.
54​
55The next steps build the server. Then they build the client.
56​
57## 2. Give the model a browser
58​
59Create `src/routes/api.chat.ts`, next to `index.tsx`. Start maps that file name to the `/api/chat` path.
60​
61```typescript ignore
62import { createFileRoute } from '@tanstack/react-router'
63import {
64 chat,
65 chatParamsFromRequest,
66 maxIterations,
67 toServerSentEventsResponse,
68} from '@tanstack/ai'
69import { openaiText } from '@tanstack/ai-openai'
70import { createComputerUse } from '@tanstack/ai-computer-use'
71import { playwrightComputer } from '@tanstack/ai-computer-playwright'
72​
73// One computer for the whole server. Each chat thread gets its own page.
74const computerUse = createComputerUse({
75 driver: playwrightComputer({
76 startUrl: 'https://tanstack.com',
77 // Show the Chromium window, so you can watch the model work.
78 launch: { headless: false },
79 }),
80 // tanstack.com renders in the browser. Give each page time to draw.
81 screenshotDelay: 1000,
82})
83​
84export async function POST({ request }: { request: Request }) {
85 const params = await chatParamsFromRequest(request)
86 const stream = chat({
87 adapter: openaiText('gpt-6.1-sol'),
88 messages: params.messages,
89 threadId: params.threadId,
90 runId: params.runId,
91 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
92 ...(params.resume ? { resume: params.resume } : {}),
93 tools: computerUse.tools,
94 middleware: [computerUse.middleware],
95 interrupts: [computerUse.interrupt],
96 // Each action is one step. A search takes more than the default 5.
97 agentLoopStrategy: maxIterations(20),
98 })
99 return toServerSentEventsResponse(stream)
101​
102export const Route = createFileRoute('/api/chat')({
103 server: {
104 handlers: {
105 POST,
106 },
107 },
108})
109```
110​
111- `createComputerUse` is at module scope. Every request uses the same browser.
112- `threadId` gives each chat its own page. The page stays open between requests of the same chat.
113- `tools` gives the model the `computer` tool and the `navigate` tool.
114- `middleware` and `interrupts` pause a risky action until a person approves it.
115- `maxIterations(20)` lets the model take up to 20 actions in one reply.
116​
117> [!WARNING]
118> The browser can open every address that your server can reach. Run this app only on your own machine.
119​
120## 3. Show the screenshots
121​
122Each computer action returns a screenshot. On the client, the screenshot is an `image` part inside a `tool-result` part.
123​
124Replace `src/routes/index.tsx` with this file. It shows the text of each message and every screenshot:
125​
126```tsx ignore
127import { useState } from 'react'
128import { createFileRoute } from '@tanstack/react-router'
129import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
130import type { UIMessage } from '@tanstack/ai-react'
131​
132type Part = UIMessage['parts'][number]
133​
134/** The screenshots in one tool result, as `<img>` sources. */
135function screenshots(part: Part) {
136 if (part.type !== 'tool-result' || typeof part.content === 'string') return []
137 return part.content.flatMap((content) => {
138 if (content.type !== 'image') return []
139 const { source } = content
140 if (source.type === 'data') {
141 return [`data:${source.mimeType};base64,${source.value}`]
142 }
143 return source.type === 'url' ? [source.value] : []
144 })
146​
147function ChatPage() {
148 const [input, setInput] = useState('')
149 const { messages, sendMessage, isLoading } = useChat({
150 connection: fetchServerSentEvents('/api/chat'),
151 threadId: 'support-chat',
152 })
153​
154 return (
155 <main>
156 {messages.map((message) => (
157 <div key={message.id}>
158 {message.parts.map((part, index) => {
159 if (part.type === 'text' && part.content) {
160 return <p key={index}>{part.content}</p>
161 }
162 return screenshots(part).map((src) => (
163 <img key={`${index}-${src.slice(-16)}`} src={src} alt="What the model sees" />
164 ))
165 })}
166 </div>
167 ))}
168 <form
169 onSubmit={(event) => {
170 event.preventDefault()
171 if (!input.trim()) return
172 sendMessage(input.trim())
173 setInput('')
174 }}
175 >
176 <textarea
177 value={input}
178 onChange={(event) => setInput(event.target.value)}
179 rows={3}
180 disabled={isLoading}
181 />
182 <button type="submit" disabled={isLoading}>
183 Send
184 </button>
185 </form>
186 </main>
187 )
189​
190export const Route = createFileRoute('/')({
191 component: ChatPage,
192})
193```
194​
195- `screenshots` turns the `image` parts of a tool result into `<img>` sources.
196- Each message shows its text parts and its screenshots, in order.
197​
198## 4. Approve risky actions
199​
200OpenAI can mark an action as risky, for example a form submit. The run then pauses until a person answers.
201​
2021. Add these imports to the top of `src/routes/index.tsx`:
203​
204```tsx ignore
205import type { GenericInterrupt } from '@tanstack/ai-react'
206import { computerSafetyCheck } from '@tanstack/ai-computer-use'
207```
208​
2092. Add the card above `ChatPage`:
210​
211```tsx ignore
212function SafetyCheckCard({
213 interrupt,
214}: {
215 interrupt: GenericInterrupt<typeof computerSafetyCheck>
216}) {
217 const checks = interrupt.payload?.checks ?? []
218 return (
219 <div>
220 <p>Approve this computer action?</p>
221 <ul>
222 {checks.map((check) => (
223 <li key={check.id}>{check.message ?? check.code ?? check.id}</li>
224 ))}
225 </ul>
226 <button onClick={() => interrupt.resolveInterrupt({ approved: true })}>
227 Approve
228 </button>
229 <button onClick={() => interrupt.resolveInterrupt({ approved: false })}>
230 Decline
231 </button>
232 </div>
233 )
235```
236​
2373. Replace `ChatPage` with this version. It registers `computerSafetyCheck` with `useChat`, and shows a card above the input for each pause:
238​
239```tsx ignore
240function ChatPage() {
241 const [input, setInput] = useState('')
242 const { messages, sendMessage, isLoading, interrupts } = useChat({
243 connection: fetchServerSentEvents('/api/chat'),
244 threadId: 'support-chat',
245 interrupts: [computerSafetyCheck],
246 })
247​
248 return (
249 <main>
250 {messages.map((message) => (
251 <div key={message.id}>
252 {message.parts.map((part, index) => {
253 if (part.type === 'text' && part.content) {
254 return <p key={index}>{part.content}</p>
255 }
256 return screenshots(part).map((src) => (
257 <img key={`${index}-${src.slice(-16)}`} src={src} alt="What the model sees" />
258 ))
259 })}
260 </div>
261 ))}
262 {interrupts.map((interrupt) => {
263 if (interrupt.kind !== 'generic') return null
264 if (!('definitionId' in interrupt)) return null
265 if (interrupt.definitionId !== computerSafetyCheck.id) return null
266 return <SafetyCheckCard key={interrupt.id} interrupt={interrupt} />
267 })}
268 <form
269 onSubmit={(event) => {
270 event.preventDefault()
271 if (!input.trim()) return
272 sendMessage(input.trim())
273 setInput('')
274 }}
275 >
276 <textarea
277 value={input}
278 onChange={(event) => setInput(event.target.value)}
279 rows={3}
280 disabled={isLoading}
281 />
282 <button type="submit" disabled={isLoading}>
283 Send
284 </button>
285 </form>
286 </main>
287 )
289```
290​
291- If you click Approve, the action runs.
292- If you click Decline, no action of that turn runs.
293​
294For more, see [Safety checks](../computer-use/safety-checks).
295​
296## 5. Send the task
297​
298Start the app with `npm run dev`. Open it in your browser and send this task:
299​
300```text
301You are on the TanStack home page. Find the TanStack AI documentation page about computer use.
302Use the screenshots. Click, type, and scroll only on what you can see. Do not type a URL from memory.
303When the page is the computer use docs, say the page title and stop.
304```
305​
306A Chromium window opens on tanstack.com. The model clicks through the site, and each screenshot shows in the chat. At the end, the model says the title of the computer use page.
307​
308The full example is on GitHub: [TanStack/ai `examples/react/computer-use`](https://github.com/TanStack/ai/tree/main/examples/react/computer-use). It has the same task in the input box.
309​
310To use Anthropic, change only the adapter. To run a full desktop in a sandbox, see [Drivers](../computer-use/drivers).