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

computer-use.md

236 lines9.1 KB

1---
2title: Computer Use
3id: computer-use
4order: 1
5description: "Let the model use a web page for the user. It sees screenshots and sends clicks and key presses. Each conversation gets its own browser page, and the same code runs on OpenAI and Anthropic."
6keywords:
7 - tanstack ai
8 - computer use
9 - createComputerUse
10 - playwrightComputer
11 - browser agent
12 - playwright
13 - openai
14 - anthropic
15---
16​
17You have a chat app. You want the model to do a task on a web page for the user, for example fill in a form or find a price. Computer use gives the model a screen, a mouse, and a keyboard. Each conversation gets its own browser page. The same code runs on OpenAI and on Anthropic.
18​
19To build a full app step by step, with the screenshots in the chat, open the [Computer Use tutorial](../tutorials/computer-use).
20​
21## Install
22​
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24​
25react: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
26vue: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
27solid: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
28svelte: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
29preact: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
30angular: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
31vanilla: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
32octane: @tanstack/ai-computer-use @tanstack/ai-computer-playwright playwright-core zod
33​
34<!-- ::end:tabs -->
35​
36Then download Chromium one time:
37​
38```bash
39npx playwright-core install chromium
40```
41​
42## Give the model a browser
43​
441. Create the computer with `playwrightComputer()`, one time, at module scope.
452. Give `tools`, `middleware`, and `interrupt` to `chat()`.
463. Give the `threadId` of the request to `chat()`.
47​
48```ts
49// app/api/chat/route.ts
50import { chat, chatParamsFromRequest, toServerSentEventsResponse } from '@tanstack/ai'
51import { openaiText } from '@tanstack/ai-openai'
52import { createComputerUse } from '@tanstack/ai-computer-use'
53import { playwrightComputer } from '@tanstack/ai-computer-playwright'
54​
55const computerUse = createComputerUse({
56 driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
57})
58​
59export async function POST(request: Request) {
60 const params = await chatParamsFromRequest(request)
61 const stream = chat({
62 adapter: openaiText('gpt-6.1-sol'),
63 messages: params.messages,
64 threadId: params.threadId,
65 runId: params.runId,
66 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
67 ...(params.resume ? { resume: params.resume } : {}),
68 tools: computerUse.tools,
69 middleware: [computerUse.middleware],
70 interrupts: [computerUse.interrupt],
71 })
72 return toServerSentEventsResponse(stream)
74```
75​
76- `tools`: the `computer` tool and the `navigate` tool. With `computer`, the model clicks, types, and takes screenshots. With `navigate`, it opens a URL.
77- `middleware`: stops the rest of a turn after a failed action. It also runs the OpenAI safety checks.
78- `interrupt`: asks a person to approve an action that has a safety check.
79​
80Chromium starts on the first action. Each thread gets a new page on its own first action, and the page opens `startUrl`.
81​
82To use Anthropic, change only the adapter:
83​
84```ts
85import { anthropicText } from '@tanstack/ai-anthropic'
86​
87const adapter = anthropicText('claude-opus-5-5')
88```
89​
90Need a full Linux desktop or your own computer, and not a browser page? See [Drivers](./drivers).
91​
92## One page for each thread
93​
94Each `threadId` gets its own machine. With `playwrightComputer()`, the machine is a browser context with one page:
95​
96- Each thread has its own cookies and storage.
97- Each thread has its own action queue and its own safety-check approvals.
98- All threads share one Chromium process.
99​
100Give a stable `threadId` to `chat()`. If `chat()` gets no `threadId`, it makes a new id for each request. Then each request gets a new page.
101​
102`useChat` sends the same thread id with each request of a chat. `chatParamsFromRequest` reads it, as in the route above.
103​
104## Close the pages
105​
106Each open page uses memory on your server. Close the page of a thread when its conversation ends. Close all pages when the server stops:
107​
108```ts
109import { createComputerUse } from '@tanstack/ai-computer-use'
110import { playwrightComputer } from '@tanstack/ai-computer-playwright'
111​
112declare const threadId: string
113​
114const computerUse = createComputerUse({
115 driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
116 idleTimeout: 30 * 60_000,
117})
118​
119// The conversation ended. Close the page of this thread.
120await computerUse.close(threadId)
121​
122// The server stops. Close every page, then Chromium.
123await computerUse.close()
124```
125​
126A thread that stays idle closes by itself. `idleTimeout` sets this time in ms:
127​
128- The default is 10 minutes.
129- When the time ends, the page of the thread closes. The next action of that thread opens a new page at `startUrl`.
130- `false` keeps every thread open until you call `close`.
131​
132## Keep the browser away from private addresses
133​
134CAUTION: Run the browser in a network where it cannot reach private services. The browser can open every address that your server can reach.
135​
136For example, a page can link to an internal admin page or to a cloud metadata URL. The `navigate` tool accepts only `http:` and `https:` URLs. It does not block private addresses.
137​
138To keep the machine off your network, use an [E2B sandbox](./drivers#e2b).
139​
140## Register the interrupt on the client
141​
142The client imports `computerSafetyCheck`. It is the same object as `interrupt`, so the client does not load the driver or Playwright.
143​
144```tsx
145// app/chat.tsx
146import { useState } from 'react'
147import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
148import { computerSafetyCheck } from '@tanstack/ai-computer-use'
149​
150export function Chat() {
151 const [input, setInput] = useState('')
152 const { messages, sendMessage } = useChat({
153 connection: fetchServerSentEvents('/api/chat'),
154 interrupts: [computerSafetyCheck],
155 })
156​
157 return (
158 <>
159 {messages.map((message) => (
160 <div key={message.id}>
161 {message.parts.map((part, index) =>
162 part.type === 'text' ? <p key={index}>{part.content}</p> : null,
163 )}
164 </div>
165 ))}
166 <form
167 onSubmit={(event) => {
168 event.preventDefault()
169 sendMessage(input)
170 setInput('')
171 }}
172 >
173 <input value={input} onChange={(event) => setInput(event.target.value)} />
174 <button type="submit">Send</button>
175 </form>
176 </>
177 )
179```
180​
181To show the approval card for a safety check, see [Safety checks](./safety-checks).
182​
183## What the model can do
184​
185The model clicks, double-clicks, drags, moves the mouse, scrolls, types text, and presses key combos. It can also wait.
186​
187- A normal action returns a screenshot 500 ms later, so the page can settle. An OpenAI batch returns one screenshot after the last action.
188- `zoom` returns an image of one region. `cursor_position` returns the mouse position as text. Neither takes another screenshot.
189- `navigate` opens a URL, then returns a screenshot.
190​
191To change the delay, set `screenshotDelay` in ms:
192​
193```ts
194import { createComputerUse } from '@tanstack/ai-computer-use'
195import { playwrightComputer } from '@tanstack/ai-computer-playwright'
196​
197const computerUse = createComputerUse({
198 driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
199 screenshotDelay: 1000,
200})
201```
202​
203## Order and failures
204​
205In one thread, actions run one at a time, in the order that the model calls them. A driver factory gives each thread its own machine, and those threads can run at the same time. A driver that you pass in is one machine. Actions on that machine run one at a time, even from two threads.
206​
207If one action fails, the other actions of that model turn do not run. The model gets this result for each of them:
208​
209```text
210Not executed: an earlier computer action in this turn failed.
211```
212​
213The next model turn starts clean. The model sees the error and can try again.
214​
215## Limits
216​
217- **One server process.** The pages live in the memory of one process. If the next request of a thread goes to another server, the thread gets a new page there.
218- **Time to approve.** If a person answers a safety check after `idleTimeout`, the page is already closed. The approved action then runs on a new page. Set `idleTimeout` above the time that a person takes to answer.
219​
220## Model support
221​
222- A model with no computer use is a type error at `chat()`.
223- The Anthropic adapter picks the newest computer tool version that the model supports. If the model supports no version, the adapter throws an error.
224- `openaiText` uses the Responses API, which has the computer tool. The Chat Completions adapters throw an error, because that API has no computer tool.
225​
226## Try it
227​
228Start the app and send this message:
229​
230```text
231Go to https://tanstack.com/ai and tell me the title of the page.
232```
233​
234The model calls `navigate`, reads the screenshot, and answers in the chat. You now have a browser agent.
235​
236To let the model use your own computer, see [Your own computer](./drivers#your-own-computer). For a machine that no driver controls, see [Custom driver](./custom-driver).