電腦功能可讓模型操作瀏覽器和桌面介面。你可以用它填寫表單、測試使用者流程,或透過應用程式的 UI 完成任務。
你負責提供環境並執行模型的要求。模型會根據螢幕擷取畫面和其他工具結果,決定接下來的動作。請選擇將模型連接至應用程式的方式:
- 程式碼執行: 模型會編寫程式碼,使用 PyAutoGUI 或 Playwright 等程式庫操作介面。一次呼叫可結合多個動作、迴圈或條件邏輯。
- 電腦工具: 模型會傳回結構化的滑鼠和鍵盤動作,再由你的應用程式將其轉換為瀏覽器或桌面輸入。
使用 GPT-6 Astra 時,我們建議採用程式碼執行方式。computer 工具仍受支援,可作為替代方案。
如果你已透過函式呼叫或遠端 MCP 工具提供 UI 操作,就可以沿用該介面。請參閱使用自己的 UI 工具,瞭解這些整合方式在執行工具及傳回結果時的差異。
使用程式碼執行
程式碼執行整合會為模型提供一個可接收指令碼的函式工具。你的應用程式會在隔離的瀏覽器或桌面環境中執行指令碼,並傳回包含螢幕擷取畫面在內的輸出。請在各次呼叫之間維持環境可用,讓模型能接續先前的工作。
執行範例應用程式
CUA 範例應用程式包含 JavaScript/Playwright 和 Python/PyAutoGUI 實作,並提供本機任務和共用主控台:
- 請在隔離的環境中,依照所選實作的設定指示操作。
- 選擇一個內建情境並開始執行。
- 檢視動作、螢幕擷取畫面和最終狀態,以評估任務是否成功。
安裝方式、桌面權限和支援的環境,請參閱應用程式的 README。將其改用於實際網站或帳戶之前,請先閱讀安全執行。
連接自己的執行階段
以下範例展示搭配你提供的執行階段運作的 API 迴圈。Python 和 Ruby 會將 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, prompt, model = "gpt-6-astra") {
const client = new OpenAI();
const sessionId = randomUUID();
const tools = [
{
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 = [{ role: "user", content: prompt }];
let previousResponseId;
for (let turn = 0; turn < 20; turn++) {
const 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
end完整的用戶端介接器,以及預期的文字和圖像輸出格式,請參閱連接至你的執行服務。這些範例中的服務介面屬於你的應用程式,並非由 OpenAI 託管的端點。
保留狀態並傳回觀察結果
請在各次呼叫之間保持瀏覽器或桌面工作階段運作。持續存在的 Python 或 JavaScript 命名空間也能保留變數。請在工具定義中說明可用的物件和輔助函式,讓模型知道可以使用哪些資源。
當 UI 狀態未知時,請向模型提供目前的螢幕擷取畫面。執行一小組動作後,再傳回一張螢幕擷取畫面,讓模型檢查結果。請將圖像保留在記憶體中,並使用 detail: "original" 保留解析度。如果你縮小了螢幕擷取畫面,請在執行動作前,將模型的座標轉換回環境的座標空間。請參閱螢幕擷取與解析度。
API 對話和執行環境各自維護獨立的狀態。請在對話中保留工具呼叫及其輸出,並在應用程式中維持對應環境可用。接續回應並不會還原瀏覽器工作階段、登入狀態或執行階段變數。
使用電腦工具
如果你的整合需要的是結構化動作,而非生成的程式碼,可以採用此替代方案。若要採用建議的方式,請從程式碼執行開始。
若要嘗試此方式,請按照相同的範例應用程式設定步驟操作,選擇 原生 模式,並執行內建情境。請使用支援電腦工具的模型。
API 互動分為三個步驟:傳送任務、執行傳回的動作,再傳回螢幕擷取畫面。這裡的程式碼片段使用的頁面包含 顯示篩選條件 控制項和搜尋欄位。整合工具時,請依自己的介面調整該任務。
環境設定和動作處理常式的實作方式,請參閱整合實作範例。
傳送任務
在 tools 陣列中啟用 computer,並描述你想要的結果:
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.6-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 動作。遇到這種情況,請擷取並傳回目前畫面,不要變更 UI。呼叫中的 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-5.6-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 項目。檢查其餘輸出中是否包含答案、求助要求或其他工具呼叫,並在應用程式中驗證結果。在此範例中,篩選條件面板應已開啟,且搜尋欄位應包含 penguin。
請參閱重複執行電腦操作迴圈,瞭解迴圈的基本架構,包括所需的動作和螢幕擷取輔助函式。
安全執行
電腦功能可能影響實際帳戶和資料。請在應用程式、執行環境及模型指示中,套用以下控制措施:
- 限制環境。 使用隔離的瀏覽器或 VM,並設定網站和動作的允許清單。將存取權限限制在任務所需的範圍內。
- 將螢幕內容視為不可信任的資料。 頁面、文件或工具結果中的文字不能授予權限,也不能凌駕使用者的指示。
- 執行重大動作前先取得確認。 確保使用者能掌控購買、資料傳輸、破壞性變更,以及其他難以復原的動作。在表單中輸入敏感資訊也算是傳輸。
- 設定執行限制並驗證結果。 設定步驟數、時間或費用上限,支援取消操作,並檢查實際結果,不要只依賴模型的最終回答。
如需瞭解具體的核准要求、轉交人工處理的方式及提示詞範例,請參閱確認與同意指引。
後續步驟
- 如需設定環境、實作動作處理常式、擷取螢幕截圖及建立執行服務配接器,請參閱整合實作範例。
- 更新舊版整合時,請依照從 computer-use-preview 遷移的指引進行。
- 探索 CUA 範例應用程式,瞭解完整的瀏覽器與桌面工作流程。