import json
import uuid
from openai import OpenAI
from openai.types.responses import (
FunctionToolParam,
ResponseInputParam,
)
def run_computer_use(endpoint, prompt, model="gpt-6-astra"):
client = OpenAI()
session_id = str(uuid.uuid4())
tools: list[FunctionToolParam] = [
{
"type": "function",
"name": "exec_py",
"description": (
"Run Python in a persistent desktop. Variables persist across calls. "
"PyAutoGUI operations are synchronous. Available: pyautogui, time, "
"log(value), and display(PIL_image). Inspect the screen with "
"display(pyautogui.screenshot()) before acting. Use screenshot "
"coordinates and check the screen after a short group of actions. "
"Keep screenshots in memory and PyAutoGUI's fail-safe enabled."
),
"parameters": {
"type": "object",
"properties": {"code": {"type": "string"}},
"required": ["code"],
"additionalProperties": False,
},
"strict": True,
}
]
next_input: ResponseInputParam = [{"role": "user", "content": prompt}]
previous_response_id = None
for turn in range(20):
response = client.responses.create(
model=model,
tools=tools,
input=next_input,
previous_response_id=previous_response_id,
)
if response.status != "completed":
raise RuntimeError(f"Response stopped with status: {response.status}")
calls = [item for item in response.output if item.type == "function_call"]
if not calls and any(
item.type == "message" and item.phase != "commentary"
for item in response.output
):
print(response.output_text)
return
if turn == 19:
raise RuntimeError(
"The task reached the 20-response limit. Inspect the last result."
)
next_input = []
for call in calls:
if call.name != "exec_py":
raise ValueError(f"Unexpected tool: {call.name}")
code = json.loads(call.arguments)["code"]
output = execute_in_sandbox(code, session_id, endpoint)
next_input.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": output,
}
)
previous_response_id = response.id计算机使用功能让模型能够操作浏览器或桌面界面。您可以用它填写表单、测试用户操作流程,或在应用中完成任务。
根据模型需要查看的内容以及由谁运行环境,选择合适的方式:
| 任务 | 入门方式 |
|---|---|
| 在您的浏览器或桌面中查看截图并使用鼠标或键盘操作 | 将 ComputerToolset 与 Responses 的计算机工具配合使用。 |
| 在您的浏览器中读取页面文本或使用控件和标签页 | 使用 BrowserToolset。您的驱动程序将选定的操作公开为函数工具。 |
| 运行由 OpenAI 托管的浏览器 | 请参阅单独的 Agents API 计算机使用指南。 |
如果只需获取公开信息,无需与页面交互,请使用网页搜索。
使用 SDK
SDK 在 Python 或 Node 中运行 Responses 工具调用循环。您的应用提供驱动程序,即读取环境信息或执行获准操作的代码。应用负责管理会话和权限,并清理资源。
连接托管环境
您可以直接使用合作伙伴提供的浏览器或桌面,无需自行运行。有些集成提供驱动程序,有些则提供操作接口,由您的应用将其映射到 SDK。有关设置步骤和支持的软件包版本,请参阅合作伙伴的指南。
| 环境 | 集成方式 |
|---|---|
| Browserbase | 在 Browserbase 托管会话中使用 Stagehand 浏览器驱动程序。请参阅 Stagehand 集成指南或查看 Python 和 TypeScript 示例。 |
| Browser Use | 使用 Browser Use 库的驱动程序,或通过 Browser Use Cloud 集成接入现有的 Playwright 代码。两份指南都使用 Python。 |
| Daytona | 将 ComputerToolset 与 Daytona 桌面沙盒配合使用。请参阅 Daytona 计算机使用辅助工具指南(Python)。如需 Agents SDK 示例,请参阅 Daytona 计算机使用集成示例。 |
| E2B Desktop | 在桌面沙盒中执行计算机操作或运行代码。请参阅 E2B 计算机使用指南,或查看 Python 和 TypeScript 示例。 |
设置会话超时时间,即使运行失败也要关闭或释放会话。如果清理失败,请检查提供商的控制面板。使用提供商的网络规则限制会话可访问的站点和资源。
运行您的第一个任务
使用 Python 3.11 或更高版本,或 Node.js 22.6 或更高版本。创建并导出 API 密钥。两个示例都会使用临时本地浏览器并调用 Responses API,可能产生费用。
在新文件夹中安装软件包和 Chromium:
# Python
python3 -m venv .venv
.venv/bin/python -m pip install openai==3.31.0 playwright==1.61.0
.venv/bin/python -m playwright install chromium
# Node
npm install openai@7.33.0 playwright@1.61.1
npx playwright install chromium
在 Windows 上,请用 py -3 替代 python3,用 .venv\Scripts\python.exe 替代 .venv/bin/python。
模型查看一个模拟包裹取件页面的截图,然后点击控件以显示取件详情。驱动程序只允许截取屏幕和用鼠标左键单击该控件。它会拦截页面发出的请求,并在运行结束时关闭浏览器。脚本最多发送 6 次 Responses 请求,并在报告成功之前检查页面。您的项目必须有权访问支持计算机工具的模型。
将所选语言的示例保存为 pickup.py 或 pickup.mts:
import asyncio
import base64
from openai import AsyncComputerToolset, AsyncOpenAI
from playwright.async_api import async_playwright
class PickupDriver:
def __init__(self, page):
self.page = page
async def screenshot(self):
image = await self.page.screenshot(type="png")
return {
"type": "computer_screenshot",
"image_url": "data:image/png;base64," + base64.b64encode(image).decode(),
}
async def allowed(self, action):
if action.type == "screenshot":
return True
if action.type != "click" or action.button != "left" or action.keys:
return False
box = await self.page.locator("summary").bounding_box()
return bool(
box
and box["x"] <= action.x < box["x"] + box["width"]
and box["y"] <= action.y < box["y"] + box["height"]
)
async def click(self, action):
# The page may have changed after approval, so bind the click again.
if not await self.allowed(action):
raise RuntimeError("Pickup details moved or the click is not allowed.")
await self.page.mouse.click(action.x, action.y)
async def refuse(self, action):
raise RuntimeError(f"This exercise does not allow {action.type}.")
double_click = drag = keypress = move = scroll = type = wait = refuse
async def main():
async with (
async_playwright() as playwright,
AsyncOpenAI(timeout=30, max_retries=0) as client,
):
browser = await playwright.chromium.launch(env={}, chromium_sandbox=True)
try:
page = await browser.new_page(viewport={"width": 1024, "height": 768})
await page.route("**/*", lambda route: route.abort())
await page.set_content(
"<title>Parcel pickup</title><main>"
"<h1>Parcel pickup</h1><p>Order #1042 is ready.</p>"
"<details><summary>Show pickup details</summary>"
"<p>Locker 18. Pickup code: 6249.</p></details></main>"
)
driver = PickupDriver(page)
tools = AsyncComputerToolset(driver)
try:
response = await tools.run(
client,
{
"model": "gpt-6.2-sol",
"store": False,
"input": "Take a screenshot. Open 'Show pickup details' and report the locker and pickup code. Use only screenshots and left clicks.",
},
before_action=driver.allowed,
max_steps=6,
)
if await page.locator("details").get_attribute("open") is None:
raise RuntimeError("Pickup details are still closed.")
print(
"Verified pickup details:",
await page.locator("details p").inner_text(),
)
print("Answer:", response.output_text)
finally:
tools.close()
finally:
await browser.close()
if __name__ == "__main__":
asyncio.run(main())运行 .venv/bin/python pickup.py 或 node --experimental-strip-types pickup.mts。成功时,脚本会输出 Verified pickup details: Locker 18. Pickup code: 6249.,随后输出模型的回答。如果有待处理的 API 安全检查,示例就会停止运行。只有当您的应用能够处理这些检查时,才应添加人工审批回调。
模型在访客证表单中输入姓名,然后点击 Create badge。驱动程序只提供读取页面、输入文本和点击这三种操作。确认回调只允许操作此表单中的控件,且只允许输入姓名 Mira。脚本会验证页面上的结果,然后才报告成功。
将所选语言的示例保存为 badge.py 或 badge.mts:
import asyncio
from openai import AsyncOpenAI
from openai.lib.browser import AsyncBrowserToolset
from openai.lib.responses_tool_runner import AsyncResponsesToolRunner
from playwright.async_api import async_playwright
class BadgeForm:
def __init__(self, page):
self.page = page
async def state(self):
return {
"tabs": [
{
"id": "badge",
"title": await self.page.title(),
"url": self.page.url,
"active": True,
}
]
}
async def read_page(self, args):
return {
"version": 1,
"text": await self.page.locator("body").inner_text(),
"elements": [
{"ref": "name", "role": "textbox", "label": "Name"},
{"ref": "save", "role": "button", "label": "Create badge"},
],
"omitted": [],
}
async def type(self, args):
await self.page.locator("#name").fill(args["text"])
async def click(self, args):
await self.page.locator("#save").click()
async def confirm(self, context):
args = context["arguments"]
if self.page.url != "about:blank" or args["tab_id"] not in (None, "badge"):
return False
return (
context["member"] == "type"
and args["target"] == "name"
and args["text"] == "Mira"
) or (context["member"] == "click" and args["target"] == "save")
async def main():
async with (
async_playwright() as playwright,
AsyncOpenAI(timeout=30, max_retries=0) as client,
):
browser = await playwright.chromium.launch(env={}, chromium_sandbox=True)
try:
page = await browser.new_page()
await page.route("**/*", lambda route: route.abort())
await page.set_content("""
<title>Visitor badge</title>
<label>Name <input id="name"></label>
<button id="save" onclick="document.querySelector('output').innerText =
'Badge ready: ' + document.querySelector('#name').value">Create badge</button>
<output></output>
""")
driver = BadgeForm(page)
tools = AsyncBrowserToolset(
driver, members=["read_page", "type", "click"], confirm=driver.confirm
)
response = await AsyncResponsesToolRunner(browser=tools).run(
client,
{
"model": "gpt-6.2-astra",
"store": False,
"input": "Create a visitor badge for Mira.",
},
max_steps=6,
)
result = await page.locator("output").inner_text()
if result != "Badge ready: Mira":
raise RuntimeError(f"The badge was not created: {result!r}")
print(result)
print("Answer:", response.output_text)
finally:
await browser.close()
if __name__ == "__main__":
asyncio.run(main())运行 .venv/bin/python badge.py 或 node --experimental-strip-types badge.mts。成功时,脚本会输出 Badge ready: Mira,随后输出模型的回答。
如果 API 拒绝使用该工具,或 Chromium 无法启动,请排查运行问题。如果点击位置不准确,请检查截图和坐标。
检查模型访问权限、费用和数据处理方式
- 模型:使用浏览器函数工具时,请确认模型支持 Responses 和函数调用。如果驱动程序会返回图像,还需确认模型支持图像输入。对于基于截图的计算机操作,请查看模型的 Tools 部分,确认是否支持计算机使用。请参阅模型目录并检查您项目的访问权限。
- 费用:每次 Responses 请求都可能按输入和输出的 Token 数量收费。屏幕截图计为图像输入。您可以查看 API 价格、估算图像输入费用或查看请求用量。托管环境可能会单独收费。
- 数据:SDK 会将驱动程序返回的页面文本或截图发送给 OpenAI。示例将
store设置为false,但某些形式的数据保留仍然适用。请查看数据控制措施和图像输入的例外情况。您的环境提供商有自己的数据政策。
查看并审批更改
接下来,试运行 Python 或 Node 版预订演示。演示会填写模拟预订信息,在提交前请求审批,然后检查已保存的字段和预订确认信息。您可以观察浏览器、接管操作、交还控制权或停止运行。两个版本均支持使用真实浏览器在本地演练,无需调用 API。
如需在桌面上观察 SDK 的操作,请试用可视化桌面演示。
调整驱动程序
将示例页面替换为您的应用可控制的环境。对于浏览器驱动程序,请通过 members 仅公开任务所需的操作。对于计算机驱动程序,请实现必需的方法,并拒绝不支持的操作。保持会话打开,直到运行结束,再关闭由您的应用创建的资源。
页面内容可能影响模型。请使用全新的浏览器配置文件或隔离的桌面环境。限制网络访问,避免凭据出现在页面文本和截图中。进行更改前请求审批,并在报告成功前检查已保存的结果。有关方法约定、审批、URL 策略和故障恢复,请参阅驱动程序参考文档。
选项固定时改用 Decisions
如果模型需要选择操作并生成相应参数,请使用 Responses。只有当您的应用已知所有允许的操作及其完整参数时,才使用 Decisions。例如,应用可以提供 route_billing、route_technical 和 review 三个选项。Decisions 负责选择,您的应用仍负责审批并执行所选操作,然后检查结果。页面发生变化时,请丢弃之前的选择。请参阅 Decisions 指南。
如需在预订演示中试用此功能,请使用具有 Decisions 访问权限的密钥,设置 OPENAI_DECISIONS_MODEL,然后重启服务器。开始一次新的运行,并选择 Decisions。
直接使用 API
如果您需要自行管理工具调用循环,请直接使用 Responses API。您需要提供运行环境,并执行模型请求的操作。选择适合您应用的集成方式:
- 代码执行:模型编写代码,通过 PyAutoGUI 或 Playwright 等库操作界面。一次调用可以组合多个操作,也可以使用循环或条件逻辑。
- 计算机工具:模型返回结构化的鼠标和键盘操作,由您的应用将其转换为浏览器或桌面输入。
对于 GPT-6 Astra,我们建议使用代码执行。您也可以继续使用 computer 工具。
如果您已经通过函数调用或远程 MCP 工具公开了界面操作,可以继续使用现有接口。有关这些集成在执行工具和返回结果方面的差异,请参阅使用您自己的 UI 工具。
使用代码执行
集成代码执行时,您需要为模型提供一个接受脚本的函数工具。您的应用在隔离的浏览器或桌面环境中运行脚本,并返回输出,包括屏幕截图。请在各次调用之间保持环境可用,以便模型在之前的操作基础上继续工作。
运行示例应用
CUA 示例应用提供 JavaScript/Playwright 和 Python/PyAutoGUI 两种实现,并配有本地任务和共用控制台:
- 在隔离环境中,按照所选实现的说明完成设置。
- 选择一个内置场景并开始运行。
- 检查执行的操作、截图和最终状态,判断任务是否成功。
有关安装、桌面权限和支持的环境,请参阅应用的 README。在将示例改用于真实站点或账户前,请阅读安全运行。
连接您自己的运行时
以下示例展示如何为您提供的运行时实现 API 调用循环。Python、Ruby 和 Go 客户端将 Python 代码发送到使用 PyAutoGUI 的桌面运行时。JavaScript 客户端则使用 Playwright 操作浏览器。每个客户端都公开一个普通函数工具,返回文本或图像时附上原始 call_id。
execute_in_sandbox 或 executeInSandbox 辅助函数将代码发送到您的执行环境,并返回观察结果。它必须保留浏览器或桌面会话,强制执行运行限制,并应用您的权限规则。这些示例演示如何进行集成,与运行示例应用是两个独立的流程。
import json
import uuid
from openai import OpenAI
from openai.types.responses import (
FunctionToolParam,
ResponseInputParam,
)
def run_computer_use(endpoint, prompt, model="gpt-6-astra"):
client = OpenAI()
session_id = str(uuid.uuid4())
tools: list[FunctionToolParam] = [
{
"type": "function",
"name": "exec_py",
"description": (
"Run Python in a persistent desktop. Variables persist across calls. "
"PyAutoGUI operations are synchronous. Available: pyautogui, time, "
"log(value), and display(PIL_image). Inspect the screen with "
"display(pyautogui.screenshot()) before acting. Use screenshot "
"coordinates and check the screen after a short group of actions. "
"Keep screenshots in memory and PyAutoGUI's fail-safe enabled."
),
"parameters": {
"type": "object",
"properties": {"code": {"type": "string"}},
"required": ["code"],
"additionalProperties": False,
},
"strict": True,
}
]
next_input: ResponseInputParam = [{"role": "user", "content": prompt}]
previous_response_id = None
for turn in range(20):
response = client.responses.create(
model=model,
tools=tools,
input=next_input,
previous_response_id=previous_response_id,
)
if response.status != "completed":
raise RuntimeError(f"Response stopped with status: {response.status}")
calls = [item for item in response.output if item.type == "function_call"]
if not calls and any(
item.type == "message" and item.phase != "commentary"
for item in response.output
):
print(response.output_text)
return
if turn == 19:
raise RuntimeError(
"The task reached the 20-response limit. Inspect the last result."
)
next_input = []
for call in calls:
if call.name != "exec_py":
raise ValueError(f"Unexpected tool: {call.name}")
code = json.loads(call.arguments)["code"]
output = execute_in_sandbox(code, session_id, endpoint)
next_input.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": output,
}
)
previous_response_id = response.idimport { randomUUID } from "node:crypto";
import OpenAI from "openai";
async function runComputerUse(
endpoint: string,
prompt: string,
model = "gpt-6-astra"
) {
const client = new OpenAI();
const sessionId = randomUUID();
const tools: OpenAI.Responses.Tool[] = [
{
type: "function",
name: "exec_js",
description: `Run JavaScript in a persistent browser. Available: Playwright's
browser, context, and page objects; console.log(value); and display(base64Image).
Save reusable variables on globalThis. Inspect a screenshot before acting and
check the screen after a short group of actions. Keep screenshots in memory.
Use top-level await for async operations. Return images with display() and concise
text with console.log(). The context viewport is 1440x900.`,
parameters: {
type: "object",
properties: { code: { type: "string" } },
required: ["code"],
additionalProperties: false,
},
strict: true,
},
];
let nextInput: OpenAI.Responses.ResponseInput = [
{ role: "user", content: prompt },
];
let previousResponseId: string | undefined;
for (let turn = 0; turn < 20; turn++) {
const response: OpenAI.Responses.Response = await client.responses.create({
model,
tools,
input: nextInput,
previous_response_id: previousResponseId,
reasoning: { effort: "low" },
});
if (response.status !== "completed") {
throw new Error(`Response stopped with status: ${response.status}`);
}
const calls = response.output.filter(
(item) => item.type === "function_call"
);
if (
calls.length === 0 &&
response.output.some(
(item) => item.type === "message" && item.phase !== "commentary"
)
) {
console.log(response.output_text);
return;
}
if (turn === 19) {
throw new Error(
"The task reached the 20-response limit. Inspect the last result."
);
}
nextInput = [];
for (const call of calls) {
if (call.name !== "exec_js")
throw new Error(`Unexpected tool: ${call.name}`);
const { code } = JSON.parse(call.arguments);
const output = await executeInSandbox(code, sessionId, endpoint);
nextInput.push({
type: "function_call_output",
call_id: call.call_id,
output,
});
}
previousResponseId = response.id;
}
}require "json"
require "openai"
require "securerandom"
def run_computer_use(endpoint, prompt)
client = OpenAI::Client.new
session_id = SecureRandom.uuid
tools = [
{
type: :function,
name: "exec_py",
description: "Run Python in a persistent desktop. Variables persist across calls. PyAutoGUI operations are synchronous. Available: pyautogui, time, log(value), and display(PIL_image). Inspect the screen with display(pyautogui.screenshot()) before acting. Use screenshot coordinates and check the screen after a short group of actions. Keep screenshots in memory and PyAutoGUI's fail-safe enabled.",
parameters: {
type: :object,
properties: { code: { type: :string } },
required: ["code"],
additionalProperties: false
},
strict: true
}
]
next_input = []
next_input << {
role: :user,
content: prompt
}
history = {}
20.times do |turn|
response = client.responses.create(
model: "gpt-6-astra", tools: tools, input: next_input, previous_response_id: history[:id]
)
raise "Response stopped with status: #{response.status}" unless response.status == OpenAI::Responses::ResponseStatus::COMPLETED
calls = response.output.grep(OpenAI::Responses::ResponseFunctionToolCall)
if calls.empty? && response.output.any? { |item| item.is_a?(OpenAI::Responses::ResponseOutputMessage) && item.phase != :commentary }
puts(response.output_text)
return response
end
raise "The task reached the 20-response limit" if turn == 19
next_input.clear
calls.each do |call|
raise "Unexpected tool: #{call.name}" unless call.name == "exec_py"
code = JSON.parse(call.arguments).fetch("code")
raise "Expected Python source text" unless code.is_a?(String)
output = execute_in_sandbox(code, session_id, endpoint)
next_input << {
type: :function_call_output,
call_id: call.call_id,
output: output
}
end
history[:id] = response.id
end
endfunc runComputerUse(ctx context.Context, client openai.Client, endpoint, prompt string, terminal *bufio.Scanner, output io.Writer) error {
session := make([]byte, 16)
if _, err := rand.Read(session); err != nil {
return err
}
sessionID := hex.EncodeToString(session)
tool := responses.ToolParamOfFunction("exec_py", map[string]any{
"type": "object", "properties": map[string]any{"code": map[string]any{"type": "string"}},
"required": []string{"code"}, "additionalProperties": false,
}, true)
tool.OfFunction.Description = openai.String("Run Python in a persistent desktop. Variables persist across calls. " +
"PyAutoGUI operations are synchronous. Available: pyautogui, time, " +
"log(value), and display(PIL_image). Inspect the screen with " +
"display(pyautogui.screenshot()) before acting. Use screenshot " +
"coordinates and check the screen after a short group of actions. " +
"Keep screenshots in memory and PyAutoGUI's fail-safe enabled.")
params := responses.ResponseNewParams{
Model: "gpt-6-astra", Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(prompt)},
}
for turn := 0; turn < 20; turn++ {
response, err := client.Responses.New(ctx, params)
if err != nil {
return err
}
if response.Status != "completed" {
return fmt.Errorf("response stopped with status: %s", response.Status)
}
var calls []responses.ResponseFunctionToolCall
finalMessage := false
for _, item := range response.Output {
if item.Type == "function_call" {
calls = append(calls, item.AsFunctionCall())
}
if item.Type == "message" && item.AsMessage().Phase != "commentary" {
finalMessage = true
}
}
if len(calls) == 0 && finalMessage {
fmt.Fprintln(output, response.OutputText())
return nil
}
if turn == 19 {
return fmt.Errorf("task reached the 20-response limit; inspect the last result")
}
nextInput := responses.ResponseInputParam{}
for _, call := range calls {
if call.Name != "exec_py" {
return fmt.Errorf("unexpected tool: %s", call.Name)
}
var arguments struct {
Code *string `json:"code"`
}
if err := json.Unmarshal([]byte(call.Arguments), &arguments); err != nil {
return err
}
if arguments.Code == nil {
return fmt.Errorf("exec_py requires code")
}
observations, err := executeInSandbox(ctx, endpoint, sessionID, *arguments.Code, terminal, output)
if err != nil {
return err
}
nextInput = append(nextInput, responses.ResponseInputItemUnionParam{
OfFunctionCallOutput: &responses.ResponseInputItemFunctionCallOutputParam{
CallID: openai.String(call.CallID),
Output: responses.ResponseInputItemFunctionCallOutputOutputUnionParam{OfResponseFunctionCallOutputItemArray: observations},
},
})
}
params.Input = responses.ResponseNewParamsInputUnion{OfInputItemList: nextInput}
params.PreviousResponseID = openai.String(response.ID)
}
return nil
}有关完整的客户端适配器以及文本和图像输出应采用的结构,请参阅连接到您的执行服务。这些示例中的服务接口由您的应用提供,并非 OpenAI 托管的端点。
保留状态并返回观察结果
在各次调用之间保持浏览器或桌面会话运行。持久化的 Python 或 JavaScript 命名空间也可以保留变量。在工具定义中描述可用的对象和辅助函数,让模型知道可以使用哪些资源。
如果界面状态未知,请向模型提供当前屏幕的截图。执行一小组操作后,再返回一张截图,以便模型检查结果。将图像保存在内存中,并使用 detail: "original" 保留原始分辨率。如果缩小了截图,请先将模型给出的坐标映射回环境的坐标空间,再执行操作。请参阅屏幕截图与分辨率。
API 对话与执行环境各自维护状态。请在对话中保留工具调用及其输出,同时在应用中保持对应环境可用。继续之前的响应并不会恢复浏览器会话、登录状态或运行时变量。
使用计算机工具
如果您的集成需要接收结构化操作,而非模型生成的代码,请使用这种方式。
如需试用,请按照同一示例应用的设置说明完成设置,选择 Native 模式,然后运行一个内置场景。请使用支持计算机工具的模型。
API 交互分为三步:发送任务、执行返回的操作、返回屏幕截图。这里的代码片段使用的页面包含 Show filters 控件和搜索框。集成工具时,请根据您自己的界面调整任务。
有关环境设置和操作处理程序,请参阅集成示例。
发送任务
将 computer 加入 tools 数组以启用计算机工具,并描述您想要的结果:
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-sol",
tools=[{"type": "computer"}],
input="Check whether the Filters panel is open. If it is not open, click Show filters. Then type penguin in the search box. Use the computer tool for UI interaction.",
)
print(response.output)执行请求的操作
每个 computer_call 都包含一个有序的 actions 数组。例如,以下调用会选中搜索框并输入 penguin:
{
"output": [
{
"type": "computer_call",
"call_id": "call_002",
"actions": [
{ "type": "click", "button": "left", "x": 405, "y": 157 },
{ "type": "type", "text": "penguin" }
],
"status": "completed"
}
]
}您的操作处理程序负责将这些请求转换为浏览器或操作系统输入。请按顺序执行获准的操作,然后截取更新后的屏幕。模型可以请求 click、double_click、drag、move、scroll、keypress、type、wait 或 screenshot。
首次调用可能只包含一个 screenshot 操作。这时请截取当前屏幕并返回截图,保持界面原样。调用中的 status: "completed" 表示模型已生成完整的调用,您的应用仍需执行该调用。
有关按键映射、拖动路径和修饰键,请参阅操作处理程序示例。
返回屏幕截图
返回一个 computer_call_output,其 call_id 必须与您处理的调用 ID 一致。使用 previous_response_id 继续与模型对话:
from openai import OpenAI
client = OpenAI()
def send_computer_screenshot(response, call_id, screenshot_base64):
return client.responses.create(
model="gpt-6.2-sol",
tools=[{"type": "computer"}],
previous_response_id=response.id,
input=[
{
"type": "computer_call_output",
"call_id": call_id,
"output": {
"type": "computer_screenshot",
"image_url": f"data:image/png;base64,{screenshot_base64}",
"detail": "original",
},
}
],
)前文的截图和状态管理说明同样适用于此循环。使用 previous_response_id 继续与模型对话时,请保持环境可用。
继续循环,直到模型不再返回 computer_call 项。检查其余输出,看看模型是否给出了回答、请求帮助或发起了其他工具调用,并在应用中验证结果。在此示例中,Filters 面板应处于打开状态,搜索框中应包含 penguin。
有关循环的基本结构及其所需的操作和截图辅助函数,请参阅重复计算机使用循环。
安全运行
计算机使用功能可能影响真实账户和数据。请在应用和执行环境中落实以下控制措施,并将这些要求写入模型指令:
- 限制环境。使用隔离的浏览器或虚拟机,并设置允许访问的站点和允许执行的操作清单。仅授予任务所需的访问权限。
- 将屏幕内容视为不可信。页面、文档或工具结果中的文本不能授予权限,也不能覆盖用户的指令。
- 确认影响重大的操作。购买、传输数据、进行破坏性更改及其他难以撤销的操作都应由用户掌控。向表单输入敏感信息即视为传输该信息。
- 限制运行范围并验证结果。设置步数、时间或费用上限,支持取消运行,并检查实际结果,不能仅依赖模型的最终回答。
有关具体审批要求、人工接管和提示词示例,请参阅确认与同意指南。
后续步骤
- 参阅集成示例,了解如何设置环境、实现操作处理程序、截取屏幕和编写执行服务适配器。
- 更新旧版集成时,请按照从 computer-use-preview 迁移中的步骤操作。
- 查看 CUA 示例应用,了解完整的浏览器和桌面工作流程。