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

safety-checks.md

144 lines5.2 KB

1---
2title: Computer Use Safety Checks
3id: computer-use-safety-checks
4order: 3
5description: "Pause a computer action until a person approves it. OpenAI attaches safety checks to risky actions, and TanStack AI turns each one into an interrupt."
6keywords:
7 - tanstack ai
8 - computer use
9 - safety checks
10 - pending_safety_checks
11 - computerSafetyCheck
12 - interrupt
13 - approval
14---
15​
16A safety check runs before a computer action. It blocks an action the user did not ask for, or an action that sends data.
17​
18OpenAI attaches safety checks to these actions. TanStack AI pauses the run, and a person approves or declines the action. This page adds the approval card to your [computer use](./computer-use) app.
19​
20## 1. Add the server route
21​
22Give `tools`, `middleware`, and `interrupt` to `chat()`. Also give `parentRunId` and `resume`, so that the approval can continue the run.
23​
24```ts
25// app/api/chat/route.ts
26import { chat, chatParamsFromRequest, toServerSentEventsResponse } from '@tanstack/ai'
27import { openaiText } from '@tanstack/ai-openai'
28import { createComputerUse } from '@tanstack/ai-computer-use'
29import { playwrightComputer } from '@tanstack/ai-computer-playwright'
30​
31const computerUse = createComputerUse({
32 driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
33 // A person has up to one hour to answer before the page closes.
34 idleTimeout: 60 * 60_000,
35})
36​
37export async function POST(request: Request) {
38 const params = await chatParamsFromRequest(request)
39 const stream = chat({
40 adapter: openaiText('gpt-6.1-sol'),
41 messages: params.messages,
42 threadId: params.threadId,
43 runId: params.runId,
44 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
45 ...(params.resume ? { resume: params.resume } : {}),
46 tools: computerUse.tools,
47 middleware: [computerUse.middleware],
48 interrupts: [computerUse.interrupt],
49 })
50 return toServerSentEventsResponse(stream)
52```
53​
54## 2. Show the approval card
55​
56Register `computerSafetyCheck` with `useChat`. Then show a card for each paused action. Each interrupt has these fields:
57​
58- `payload.checks`: the safety checks. Each check has an `id`, and can have a `code` and a `message`.
59- `payload.action`: the action that waits. For a batch, this is the list of actions.
60​
61```tsx
62// app/chat.tsx
63import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
64import type { GenericInterrupt } from '@tanstack/ai-react'
65import { computerSafetyCheck } from '@tanstack/ai-computer-use'
66​
67function SafetyCheckCard({
68 interrupt,
69}: {
70 interrupt: GenericInterrupt<typeof computerSafetyCheck>
71}) {
72 const checks = interrupt.payload?.checks ?? []
73 return (
74 <article>
75 <h2>Approve this computer action?</h2>
76 <ul>
77 {checks.map((check) => (
78 <li key={check.id}>{check.message ?? check.code ?? check.id}</li>
79 ))}
80 </ul>
81 <pre>{JSON.stringify(interrupt.payload?.action, null, 2)}</pre>
82 <button onClick={() => interrupt.resolveInterrupt({ approved: true })}>
83 Approve
84 </button>
85 <button onClick={() => interrupt.resolveInterrupt({ approved: false })}>
86 Decline
87 </button>
88 </article>
89 )
91​
92export function Chat() {
93 const { interrupts } = useChat({
94 connection: fetchServerSentEvents('/api/chat'),
95 threadId: 'support-chat',
96 interrupts: [computerSafetyCheck],
97 })
98​
99 return (
100 <>
101 {interrupts.map((interrupt) => {
102 if (interrupt.kind !== 'generic') return null
103 if (!('definitionId' in interrupt)) return null
104 if (interrupt.definitionId !== computerSafetyCheck.id) return null
105 return <SafetyCheckCard key={interrupt.id} interrupt={interrupt} />
106 })}
107 </>
108 )
110```
111​
112`interrupt.cancel()` also declines the action. When every interrupt of the batch has an answer, the client sends the answers. For more about generic interrupts, see [Generic Interrupts](../interrupts/generic).
113​
114## 3. Try it
115​
116Ask the model to do a task that sends data, for example a form submit. When OpenAI adds a safety check, the card shows.
117​
118- Click **Approve**, and the action runs.
119- Click **Decline**, and the page stays as it was.
120​
121## How it works
122​
1231. The model sends a computer call with `pending_safety_checks`.
1242. The `middleware` pauses the run with one interrupt for each call that has checks.
1253. A person approves or declines on the client.
126​
127After the answer:
128​
129- If the person approves all calls, the calls run. The checks go back to OpenAI as acknowledged.
130- If the person declines one call, no call of that turn runs.
131- A call with checks that nobody approved does not run. The tool refuses it.
132​
133Safety checks are an OpenAI feature. Anthropic models do not send them, so this code does nothing on Anthropic.
134​
135## Advanced
136​
137### Keep the approval until the resume request
138​
139`computerUse` keeps the approval for the thread until the resume request comes. To keep it there:
140​
141- Create `computerUse` one time, at module scope. Every request uses the same one.
142- Give `params.threadId` to `chat()`. The resume request has the same thread id as the request that paused.
143- Set `idleTimeout` above the time that a person takes to answer. If the time ends first, the page closes, and the approved action runs on a new page.
144- Send the resume request to the same server process. The approvals live in the memory of that process.