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 | 使用 Stagehand 瀏覽器驅動程式連接 Browserbase 託管的工作階段。請依照 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。
模型會看到模擬包裹取件頁面的螢幕截圖,接著點選控制項以顯示取件資訊。驅動程式只允許擷取螢幕畫面,以及用滑鼠左鍵點選該控制項。它會封鎖網頁發出的請求,並在執行結束時關閉瀏覽器。指令碼最多會發出六次 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.1-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-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 與函式呼叫。如果驅動程式會回傳影像,也要確認模型支援影像輸入。若要根據螢幕截圖執行電腦動作,請查看模型說明的工具一節,確認模型支援電腦功能。請參閱模型目錄,並檢查專案的存取權。
- 費用: 每次 Responses 請求都可能依輸入與輸出的 Token 數計費。螢幕截圖會計入影像輸入。你可以查看 API 定價、估算影像輸入費用,或查看請求用量。託管環境可能另行收費。
- 資料: SDK 會將驅動程式回傳的網頁文字或螢幕截圖傳送給 OpenAI。範例將
store設為false,但在某些情況下,資料仍會保留。請查閱資料控管措施與影像輸入的例外情況。你的環境供應商另有自己的資料政策。
查看並核准變更
接著,試試 Python 或 Node 的預約示範。它會填寫模擬預約資料,在送出前要求核准,並檢查已儲存的欄位與預約確認資訊。你可以觀看瀏覽器的操作過程、接手操作、交還控制權,或停止執行。兩個版本都提供本機演練,會使用實際的瀏覽器,無須呼叫 API。
若要在桌面上觀看 SDK 的操作過程,請試用視覺化桌面示範。
調整驅動程式
將範例頁面換成由你的應用程式控制的環境。如果使用瀏覽器驅動程式,請透過 members 只開放任務所需的操作。如果使用電腦驅動程式,請實作必要的方法,並拒絕不支援的動作。讓工作階段保持開啟,直到執行結束,再關閉應用程式建立的資源。
頁面內容可能影響模型。請使用全新的瀏覽器設定檔或隔離的桌面環境。限制網路存取,並避免讓憑證出現在網頁文字或螢幕截圖中。進行變更前先要求核准,並在回報成功前檢查已儲存的結果。如需瞭解方法規格、核准機制、網址政策與復原方式,請參閱驅動程式參考文件。
選項已確定時改用 Decisions
當模型需要自行選擇動作並產生引數時,請使用 Responses。只有當應用程式已知所有允許的動作及各動作的完整引數時,才使用 Decisions。例如,應用程式可能提供 route_billing、route_technical 與 review 三個選項。Decisions 負責選出一項,仍由你的應用程式核准並執行該動作,然後檢查結果。頁面變更時,請捨棄先前提供的所有選項。詳見 Decisions 指南。
若要在預約示範中試用 Decisions,請使用有權存取 Decisions 的金鑰,設定 OPENAI_DECISIONS_MODEL,然後重新啟動伺服器。開始新一輪執行,並選取 Decisions。
直接使用 API
如果需要自行管理工具呼叫迴圈,請直接使用 Responses API。你需要提供執行環境,並執行模型要求的操作。請選擇適合應用程式的整合方式:
- 執行程式碼: 模型會撰寫程式碼,使用 PyAutoGUI 或 Playwright 等程式庫操作介面。一次呼叫可以結合多個動作、迴圈或條件邏輯。
- 電腦工具: 模型會回傳結構化的滑鼠與鍵盤動作,由你的應用程式轉換為瀏覽器或桌面輸入。
對於 GPT-6 Astra,建議採用執行程式碼的方式。你也可以使用仍受支援的 computer 工具。
如果你已透過函式呼叫或遠端 MCP 工具提供使用者介面操作,可以沿用現有介面。如需瞭解這些整合方式在執行工具與回傳結果時有何差異,請參閱使用自己的使用者介面工具。
使用程式碼執行功能
採用這種整合方式時,你會提供一個能接收指令碼的函式工具給模型使用。你的應用程式會在隔離的瀏覽器或桌面環境中執行指令碼,並回傳輸出,包括螢幕截圖。請在各次呼叫之間保留環境,讓模型能接續先前的工作。
執行範例應用程式
你可以在 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.1-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 與你處理的呼叫相符。使用 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.1-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 範例應用程式,瞭解完整的瀏覽器與桌面工作流程。