如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

電腦

讓智慧體在 OpenAI 代管的瀏覽器中完成任務。

透過電腦功能,智慧體可以瀏覽網站、操作瀏覽器介面,藉此測試網站、收集資訊,或透過使用者介面操作應用程式。

Agents API 會在 OpenAI 代管的環境中執行瀏覽器。應用程式負責啟動工作階段並追蹤事件,智慧體則根據在瀏覽器中觀察到的內容決定下一步。

執行瀏覽器任務的步驟如下:

  1. 建立瀏覽器工作階段,並儲存工作階段 ID。
  2. 追蹤工作階段事件,並將任務傳送給智慧體。
  3. 逐一處理網站存取請求。如果任務需要使用帳號,請處理登入。
  4. 等待主要智慧體完成回合,並驗證結果。如果連線中斷,請先恢復原本的工作階段,再重試。
  5. 檢查已儲存的瀏覽器活動,並在完成後刪除工作階段。

設定瀏覽器

按照 Agents API 快速入門的先決條件建立 API 金鑰並匯出 OPENAI_API_KEY,然後安裝適用於所用程式語言的 OpenAI SDK。若要執行 TypeScript 範例,請安裝 openai 和 prompt-sync。cURL 範例需要 Bash 和 jq。

若要啟用瀏覽器存取功能:

  • 將 { "type": "computer_use" } 加入 agent.tools。
  • 將 environment.type 設為 openai_hosted,並將 environment.desktop.enabled 設為 true。

以下 TypeScript 範例依序示範如何建立工作階段、處理網站存取核准,再傳送任務並印出答案。首先,建立瀏覽器工作階段並啟用螢幕截圖。這個步驟不會啟動任務。

建立瀏覽器工作階段
import OpenAI from "openai";
import { open } from "node:fs/promises";

const client = new OpenAI();
const session = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "Read public documentation in the browser. Do not sign in or change any website data. Report the page title and URL you find.",
    tools: [{ type: "computer_use", include_screenshots: true }],
  },
  environment: {
    type: "openai_hosted",
    desktop: { enabled: true },
    network: { access: "enabled" },
  },
});
console.log("Session ID:", session.id);

處理網站來源存取請求

瀏覽器每次存取新的網站來源前,都必須取得使用者核准,即使是公開網站也一樣。啟用網路存取不會自動核准這些請求。

即使啟用自動審查,瀏覽器仍會要求使用者核准網站來源存取,也仍會在需要時發出登入請求。請繼續在應用程式中處理這兩類請求。

處理來源存取核准的步驟如下:

  1. 收到 agent.session.requires_action 事件時,取得工作階段並檢查目前的 required_actions。
  2. 找出待處理的 computer_use_approval_request 項目,其中巢狀欄位 request.type 的值為 browser_origin_access。
  3. 顯示請求存取的 origin 和 reason(如有提供),讓使用者選擇 approve、deny 或 cancel。接著透過工作階段事件端點提交決定。如下例所示,請使用同一個 request_id,並在巢狀的 response 中包含 type: "browser_origin_access" 和 decision。
核准網站來源不會強制要求逐項確認操作

如果應用程式必須確保使用者在購買、進行破壞性變更或執行其他影響重大的操作前先行確認,請限制代管瀏覽器只能存取無法執行這些操作的資源,或使用由你控制的瀏覽器執行環境。若透過函式工具要求確認,必須等智慧體呼叫該函式,使用者才會收到確認要求。

請將網站內容視為不受信任的資料。網站內容無法授予權限,也不能凌駕於使用者的指示之上。請參閱在自行控制的執行環境中取得使用者確認與同意的指引。

請在任務程式碼之前定義這個輔助函式。它會處理來源存取核准,並取消登入請求,因為這項任務只會讀取公開網頁。

回應來源存取請求
import { createInterface } from "node:readline";

const inputLines = createInterface({
  input: process.stdin,
  crlfDelay: Infinity,
});
const answers = inputLines[Symbol.asyncIterator]();

/** @param {OpenAI} client */
async function respondToOriginApproval(
  client: OpenAI,
  sessionId: string,
  approval: OpenAI.Beta.Agents.AgentSession.SessionRequiredActionResourceComputerUseApprovalRequest
) {
  const request = approval.request;
  if (request.type === "browser_origin_access") {
    console.log("Requested origin:", request.origin);
    console.log(request.reason ?? "The browser needs access to this origin.");
    let input;
    do {
      process.stdout.write(
        "Allow access? [approve/deny/cancel, default deny] "
      );
      const answer = await answers.next();
      input = (answer.done ? "" : answer.value).trim().toLowerCase() || "deny";
    } while (!["approve", "deny", "cancel"].includes(input));
    const decision =
      input === "approve" ? "approve" : input === "cancel" ? "cancel" : "deny";
    await client.beta.agents.sessions.events.create(sessionId, {
      events: [
        {
          type: "agent.session.input.computer_use_approval_request_result",
          request_id: approval.request_id,
          response: { type: "browser_origin_access", decision },
        },
      ],
    });
  } else if (request.type === "browser_authentication") {
    // This public-page task must not sign in.
    await client.beta.agents.sessions.events.create(sessionId, {
      events: [
        {
          type: "agent.session.input.computer_use_approval_request_result",
          request_id: approval.request_id,
          response: { type: "browser_authentication", action: "cancel" },
        },
      ],
    });
  } else {
    throw new Error("Unsupported approval request");
  }
}

請保持事件串流開啟,並處理所有待核准的請求。使用 request_id 追蹤請求。當請求不再列於工作階段的 required_actions 中時,請移除對應的核准控制項。取消核准請求不會取消任務。

收到 202 回應表示系統已接受該決定。此時瀏覽器可能尚未完成導覽。

執行瀏覽器任務

請智慧體在公開的開發人員網站上找到 Agents API 快速入門指南,並回報指南的標題和網址。

傳送任務前先開啟事件串流,讓應用程式能收到最初的進度事件。收到來源存取核准請求時就加以處理,讓瀏覽器能繼續執行任務。

傳送任務並追蹤結果
let screenshot;
const events = await client.beta.agents.sessions.events.stream(session.id);
const handledRequests = new Set();
let completed = false;
try {
  await client.beta.agents.sessions.events.create(session.id, {
    events: [
      {
        type: "agent.session.input.message",
        input: [
          {
            role: "user",
            content: [
              {
                type: "input_text",
                text: "Open https://developers.openai.com in the browser. Find the Agents API quickstart, then report its page title and URL.",
              },
            ],
          },
        ],
      },
    ],
  });
  for await (const event of events) {
    switch (event.type) {
      case "agent.session.requires_action": {
        const current = await client.beta.agents.sessions.retrieve(
          session.id
        );
        for (const approval of current.required_actions) {
          if (
            approval.type === "computer_use_approval_request" &&
            !handledRequests.has(approval.request_id)
          ) {
            await respondToOriginApproval(client, session.id, approval);
            handledRequests.add(approval.request_id);
          }
        }
        break;
      }
      case "agent.session.turn.item.done": {
        // Preserve streamed screenshots; retrieved history may omit image bytes.
        const item = event.item;
        if (item.type === "computer_use_call") {
          const output = item.output;
          if (
            output?.type === "computer_screenshot" &&
            output.image_url.startsWith("data:image/jpeg;base64,")
          ) {
            screenshot = Buffer.from(
              output.image_url.split(",", 2)[1],
              "base64"
            );
          }
        }
        break;
      }
      case "agent.session.turn.output_text.done":
        console.log(event.text);
        break;
      case "error":
        throw new Error(event.error.message);
      case "agent.session.failed":
      case "agent.session.environment.failed":
        throw new Error(`Agent lifecycle failure: ${event.type}`);
      case "agent.session.turn.failed":
        if (event.turn.subagent_id === null) {
          throw new Error(event.turn.error?.message ?? "Browser task failed");
        }
        break;
      case "agent.session.turn.cancelled":
        if (event.turn.subagent_id === null) {
          throw new Error("Browser task was cancelled");
        }
        break;
      case "agent.session.turn.completed":
        if (event.turn.subagent_id === null) completed = true;
        break;
    }
    if (completed) break;
  }
  if (!completed) {
    throw new Error("Stream closed before the browser task finished");
  }
  console.log();
} finally {
  events.controller.abort();
}

這個範例會印出智慧體的答案。請確認答案包含快速入門指南的標題和網址。

關閉事件串流不會停止任務。若要停止任務,請取消該回合。如果連線失敗或無法確定結果,請依照復原指引處理。完整的 cURL 範例包含傳輸與錯誤診斷資訊。

追蹤瀏覽器活動

瀏覽器操作會以 computer_use_call 項目的形式出現在工作階段輸出中。串流中的活動項目與工作階段歷程記錄中的項目採用相同的資料結構。

欄位 說明
id 活動項目的識別碼。
turn_id 產生這項活動的回合。
title 瀏覽器活動的說明,也可能是 null。
status in_progress、completed、failed 或 incomplete。
output 螢幕截圖輸出(如有)。

使用標題和狀態在應用程式中顯示進度。每個瀏覽器活動項目描述一次工具操作,無法代表智慧體的最終答案或整個回合的完成狀態。如需瞭解工作階段的事件模型,請參閱事件與項目。

包含螢幕截圖

若要在應用程式中顯示瀏覽器的執行進度,請將 include_screenshots 設為 true。這項設定位於 computer_use 工具中。API 預設不會輸出螢幕截圖,但智慧體仍可看到截圖。

瀏覽器活動完成時,如果該活動曾輸出螢幕截圖,完成事件的 item.output 就會包含最後一張截圖:

{
  "type": "computer_screenshot",
  "image_url": "data:image/jpeg;base64,..."
}

使用 image_url 顯示螢幕截圖。即使已啟用截圖,部分操作仍會傳回 output: null,因此應用程式也應能處理沒有圖片的活動項目。

螢幕截圖可能包含網頁或帳號的敏感資料。請只向獲得授權的使用者顯示截圖,並避免將截圖寫入應用程式日誌。

讀取串流時,請從 agent.session.turn.item.done 事件擷取可用的螢幕截圖。之後取得的歷程記錄可能不含圖片的位元組資料,因此請在應用程式中保留圖片,避免仰賴後續列出項目的請求來取得圖片。回合結束後,SDK 範例會列出瀏覽器活動,並儲存最近擷取的螢幕截圖。大多數範例使用 browser-screenshot.jpg,Java 範例則使用暫存檔。

讀取瀏覽器活動
for await (const item of client.beta.agents.sessions.items.list(session.id, {
  order: "asc",
  limit: 100,
})) {
  if (item.type !== "computer_use_call") continue;
  console.log(item.title ?? "Browser activity", item.status);
}
if (screenshot) {
  const file = await open("browser-screenshot.jpg", "wx", 0o600);
  try {
    await file.writeFile(screenshot);
  } finally {
    await file.close();
  }
  console.log("Saved browser-screenshot.jpg");
} else {
  console.log("No browser screenshot was returned.");
}

SDK 範例不會覆寫現有檔案。再次執行前,請移動或移除 browser-screenshot.jpg。

處理登入

有些任務需要瀏覽器處於已登入狀態,例如讀取私人 GitHub 程式碼庫中的議題。登入流程由應用程式處理,讓使用者能在對話之外選擇登入方式並輸入登入資料。

登入可能需要處理多個請求。例如,網站可能先要求使用者選擇以電子郵件登入,再要求輸入電子郵件地址,最後要求輸入驗證碼。請根據每個請求提供的登入方式和欄位建立使用者介面。

只有主要智慧體能要求瀏覽器驗證身分,子代理程式無法提出這項請求。此流程支援電子郵件地址、密碼和驗證碼,不支援通行金鑰或 QR Code 登入。如果網站要求使用不支援的方式,就無法透過此流程完成登入。

請保持任務的事件串流開啟,並在收到來源存取核准請求時加以處理。收到 agent.session.requires_action 事件時,取得工作階段,並在目前的 required_actions 中找出 computer_use_approval_request 項目,其中巢狀欄位 request.type 的值為 browser_authentication。

使用巢狀的 request 產生登入介面:

欄位 使用方式
reason 如有提供,請用來說明為何需要使用者輸入資料。值可能是 null。
credential_origin 顯示這組登入資料要用於哪個網站來源。值可能是 null。
fields 根據每個欄位的 id、label、type 和 required 值顯示輸入欄位。欄位清單可能為空。
options 顯示可用的登入方式。每個選項都有 id、label 和 field_ids,其中最後一項列出該方式使用的輸入欄位。

如果請求提供登入方式,請讓使用者選擇一種,並顯示對應的欄位。否則,直接顯示請求中的欄位。

只有在使用者能核實登入資料的目的地時,才請他們輸入資料。如果請求未提供網站來源,或提供的來源讓使用者感到陌生,而使用者又無法自行核實目的地,請取消身分驗證請求。

提交使用者輸入的資料時,請使用外層動作的 request_id。如果使用者拒絕登入,請取消身分驗證請求。後續收到請求時,請繼續逐一處理。提交回應不代表登入成功,請持續追蹤任務直到完成,並檢查結果。

範例:先選擇登入方式,再輸入驗證碼

如果網站提供電子郵件驗證碼和密碼兩種登入方式,可能會先請使用者選擇一種方式,而不要求填寫任何欄位:

選擇登入方式
{
  "type": "computer_use_approval_request",
  "turn_id": "turn_example",
  "request_id": "request_choose_method",
  "request": {
    "type": "browser_authentication",
    "reason": "Choose how to sign in to the issue tracker",
    "credential_origin": "https://issues.example.com",
    "fields": [],
    "options": [
      { "id": "email_code", "label": "Email me a code", "field_ids": [] },
      { "id": "password", "label": "Use a password", "field_ids": [] }
    ]
  }
}

如果使用者選擇以電子郵件驗證碼登入,請一併提交 selected_option: "email_code" 和 fields: [],並使用這個請求的 request_id。接著,網站可能會分別發出請求,要求輸入電子郵件地址和驗證碼。請根據每個新請求各自的欄位和 ID 顯示表單,並且只在該請求提供選項時包含 selected_option。

傳回使用者輸入的資料

使用者填妥登入表單後,請透過工作階段事件端點傳送回應。將 action 設為 submit,並使用待核准請求中的請求 ID 和欄位 ID。例如,針對電子郵件地址請求的回應如下:

{
  "events": [
    {
      "type": "agent.session.input.computer_use_approval_request_result",
      "request_id": "REQUEST_ID",
      "response": {
        "type": "browser_authentication",
        "action": "submit",
        "fields": [{ "field_id": "email", "value": "USER_ENTERED_VALUE" }]
      }
    }
  ]
}

如果請求提供登入方式,請在 response.selected_option 中填入所選方式的 ID。只提交該方式的 field_ids 所列欄位,且每個必填欄位都必須有非空值。如果該方式沒有欄位,請傳送 fields: []。

如果請求未提供登入方式,請省略 selected_option,直接提交請求中的欄位。只要請求列出欄位,即使全部都是選填,也必須至少提交一個。

登入資料只能透過此專用事件傳送。提交的值不會納入智慧體的模型輸入,也不會出現在工作階段歷程記錄的身分驗證回應項目中。

所有值都是敏感資料,包括電子郵件地址。請遮蔽使用者輸入的值,不要將其寫入日誌、分析資料或已儲存的介面狀態,並在提交後清空表單。請勿透過一般訊息或函式工具的結果傳送登入資料。

請勿在提交事件中包含 turn_id。如需瞭解欄位與承載資料的限制,請參閱身分驗證資料的提交限制。

收到 202 回應且回應本文為空,表示系統已接受提交的資料,但此時仍無法確認登入是否成功。請繼續追蹤工作階段事件,留意是否有後續請求或任務是否已恢復執行。提交登入資料時,請停用 HTTP 或 SDK 的自動重試功能。如果不確定系統是否已接受提交的資料,請先重新取得工作階段,再繼續處理。

讓使用者取消登入

如果使用者拒絕登入,請以 action: "cancel" 回應待處理的請求。使用該請求的 request_id,並省略 fields 和 selected_option:

{
  "events": [
    {
      "type": "agent.session.input.computer_use_approval_request_result",
      "request_id": "REQUEST_ID",
      "response": { "type": "browser_authentication", "action": "cancel" }
    }
  ]
}

這只會取消身分驗證請求。若要停止任務本身,請取消該回合。

執行需要登入的瀏覽器任務

應用程式會在追蹤工作階段事件的同時,處理來源存取核准與登入請求。請先定義下列輔助函式,再執行任務。函式會顯示登入資料的目的地,收集使用者輸入的資料並遮蔽輸入值,然後提交回應。如果使用者拒絕登入,函式就會取消登入請求。

處理瀏覽器存取核准與登入
import promptSync from "prompt-sync";

const prompt = promptSync({ sigint: true });

/** @param {OpenAI} client */
async function respondToComputerUseApproval(
  client: OpenAI,
  sessionId: string,
  approval: OpenAI.Beta.Agents.AgentSession.SessionRequiredActionResourceComputerUseApprovalRequest
) {
  const request = approval.request;
  if (request.type === "browser_origin_access") {
    console.log("Requested origin:", request.origin);
    console.log(request.reason ?? "The browser needs access to this origin.");
    let input;
    do {
      input =
        prompt("Allow access? [approve/deny/cancel, default deny] ")
          .trim()
          .toLowerCase() || "deny";
    } while (!["approve", "deny", "cancel"].includes(input));
    const decision =
      input === "approve" ? "approve" : input === "cancel" ? "cancel" : "deny";
    await client.beta.agents.sessions.events.create(sessionId, {
      events: [
        {
          type: "agent.session.input.computer_use_approval_request_result",
          request_id: approval.request_id,
          response: { type: "browser_origin_access", decision },
        },
      ],
    });
    return;
  }
  if (request.type !== "browser_authentication") {
    throw new Error("Unsupported approval request");
  }
  async function cancelSignIn() {
    await client.beta.agents.sessions.events.create(
      sessionId,
      {
        events: [
          {
            type: "agent.session.input.computer_use_approval_request_result",
            request_id: approval.request_id,
            response: { type: "browser_authentication", action: "cancel" },
          },
        ],
      },
      { maxRetries: 0 }
    );
  }
  console.log(request.reason ?? "Sign in to continue");
  console.log(
    "Credential origin:",
    request.credential_origin ?? "Not supplied"
  );
  const consent = prompt("Have you verified the sign-in destination? [y/N] ")
    .trim()
    .toLowerCase();
  if (!["y", "yes"].includes(consent)) {
    await cancelSignIn();
    return;
  }

  let selectedOption: (typeof request.options)[number] | undefined;
  let activeFields = request.fields;
  if (request.options.length > 0) {
    request.options.forEach((option, index) => {
      console.log(`${index + 1}. ${option.label}`);
    });
    let choice;
    do {
      const input = prompt("Choose a sign-in method, or enter cancel: ")
        .trim()
        .toLowerCase();
      if (input === "cancel") {
        await cancelSignIn();
        return;
      }
      choice = Number(input);
    } while (
      !Number.isInteger(choice) ||
      choice < 1 ||
      choice > request.options.length
    );
    const option = request.options[choice - 1];
    selectedOption = option;
    activeFields = request.fields.filter((field) =>
      option.field_ids.includes(field.id)
    );
  }

  const fields = [];
  do {
    for (const field of activeFields) {
      while (true) {
        const value = prompt.hide(
          `${field.label}${field.required ? "" : " (optional)"} (leave blank for options): `
        );
        if (value.length > 0) {
          fields.push({ field_id: field.id, value });
          break;
        }
        let action;
        do {
          action = prompt(
            field.required
              ? "Enter a value or cancel sign-in? [enter/cancel, default enter] "
              : "Skip this field, enter a value, or cancel sign-in? [skip/enter/cancel, default skip] "
          )
            .trim()
            .toLowerCase();
        } while (
          ![
            "",
            "enter",
            "cancel",
            ...(field.required ? [] : ["skip"]),
          ].includes(action)
        );
        if (action === "cancel") {
          await cancelSignIn();
          return;
        }
        if (!field.required && (action === "" || action === "skip")) break;
      }
    }
    if (!selectedOption && activeFields.length > 0 && fields.length === 0) {
      console.log(
        "This form requires at least one field. Enter a value or cancel sign-in."
      );
    }
  } while (!selectedOption && activeFields.length > 0 && fields.length === 0);
  await client.beta.agents.sessions.events.create(
    sessionId,
    {
      events: [
        {
          type: "agent.session.input.computer_use_approval_request_result",
          request_id: approval.request_id,
          response: {
            type: "browser_authentication",
            action: "submit",
            fields,
            ...(selectedOption ? { selected_option: selectedOption.id } : {}),
          },
        },
      ],
    },
    { maxRetries: 0 }
  );
}

下例會請智慧體讀取私人 GitHub 程式碼庫中的議題。請將 https://github.com/acme/private-repo/issues 替換為你有權存取的議題頁面網址。

傳送任務前先開啟事件串流,並在工作階段每次需要輸入時呼叫輔助函式。

讀取私人程式碼庫中的議題
import OpenAI from "openai";

const client = new OpenAI();
const session = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "Read the requested GitHub issue list in the browser. Request sign-in when needed. Do not create, edit, comment on, or close issues.",
    tools: [{ type: "computer_use", include_screenshots: false }],
  },
  environment: {
    type: "openai_hosted",
    desktop: { enabled: true },
    network: { access: "enabled" },
  },
});
console.log("Session ID:", session.id);

let completed = false;
let readyToDelete = false;
try {
  const events = await client.beta.agents.sessions.events.stream(session.id);
  const handledRequests = new Set();
  try {
    await client.beta.agents.sessions.events.create(session.id, {
      events: [
        {
          type: "agent.session.input.message",
          input: [
            {
              role: "user",
              content: [
                {
                  type: "input_text",
                  // Replace this illustrative URL with your private repository.
                  text: "Open https://github.com/acme/private-repo/issues in the browser. Sign in if needed, then report the title and URL of the most recently updated open issue. Do not make changes.",
                },
              ],
            },
          ],
        },
      ],
    });
    for await (const event of events) {
      switch (event.type) {
        case "agent.session.requires_action": {
          const current = await client.beta.agents.sessions.retrieve(
            session.id
          );
          for (const approval of current.required_actions) {
            if (
              approval.type === "computer_use_approval_request" &&
              !handledRequests.has(approval.request_id)
            ) {
              await respondToComputerUseApproval(client, session.id, approval);
              handledRequests.add(approval.request_id);
            }
          }
          break;
        }
        case "agent.session.turn.output_text.done":
          console.log(event.text);
          break;
        case "error":
          throw new Error(event.error.message);
        case "agent.session.failed":
        case "agent.session.environment.failed":
          throw new Error(`Agent lifecycle failure: ${event.type}`);
        case "agent.session.turn.failed":
          if (event.turn.subagent_id === null) {
            throw new Error(event.turn.error?.message ?? "Browser task failed");
          }
          break;
        case "agent.session.turn.cancelled":
          if (event.turn.subagent_id === null) {
            throw new Error("Browser task was cancelled");
          }
          break;
        case "agent.session.turn.completed":
          if (event.turn.subagent_id === null) completed = true;
          break;
      }
      if (completed) break;
    }
    if (!completed) {
      throw new Error("Stream closed before the browser task finished");
    }
    console.log();
  } finally {
    events.controller.abort();
  }
  readyToDelete = completed;
} catch (error) {
  console.error(
    `Session ${session.id} was kept. Use the same ID to check its status before trying again.`
  );
  throw error;
} finally {
  if (readyToDelete) await client.beta.agents.sessions.delete(session.id);
}

登入可能需要處理多個請求,因此請持續處理核准請求,直到任務完成。接著,依照任務要求檢查智慧體回傳的結果。在這個範例中,請核對智慧體回報的議題標題和網址。

讀取登入歷程記錄

身分驗證請求和系統已接受的回應會出現在工作階段歷程記錄和 agent.session.turn.item.added 事件中。請求項目包含登入表單的中繼資料,回應項目則記錄已接受的動作,不含使用者提交的登入資料值。

使用這些記錄即可檢查先前的互動。若要判斷登入表單是否仍需要使用者輸入,請取得工作階段目前的 required_actions。歷程記錄中有回應並不代表登入成功。

來源存取核准沒有專屬的請求或回應歷程項目。請透過 required_actions 處理這些核准請求。

向使用者提問

若要在任務期間請使用者釐清需求或做出選擇,請定義一個函式工具,並將它加入 agent.tools。例如,你可以定義 request_user_response 來顯示問題並收集答案。應用程式負責提供工具名稱、引數的結構描述和使用者介面。

收到 agent.session.requires_action 事件時,請找出該工具待處理的 function_call,並根據其中的 arguments 顯示問題。透過 agent.session.input.tool_result 傳回答案,並使用該動作的 turn_id 和 call_id。設定 success: true,並將答案放入 output。如果答案是結構化資料,請將其序列化為 JSON 字串。如果使用者拒絕回答,請傳回 success: false,並在 error 中提供錯誤訊息。

傳回答案後,請繼續追蹤工作階段事件。先前示範的瀏覽器核准輔助函式會處理來源存取與登入。請擴充事件處理常式,讓它也能處理提問工具的呼叫。

模型可以看到函式工具的結果,這些結果也會儲存在工作階段歷程記錄中。請透過瀏覽器身分驗證收集密碼和驗證碼。

恢復處理核准請求

如果應用程式斷線或傳送核准回應失敗,請先重新取得同一個工作階段,檢查目前的 required_actions,再繼續處理。只為仍待處理的請求重建表單,並移除已不在清單中的請求所對應的控制項。

如果事件串流中斷,請依照串流復原步驟恢復接收事件。重新連線時,不得自動重新傳送任務或核准回應。

請根據回應狀態決定下一步:

結果 應用程式應採取的動作
202 清除已提交的值,並追蹤工作階段事件以確認結果。
400 對照待處理的請求,檢查回應類型、所選選項、欄位 ID 和必填值。取消請求或回應來源存取請求時,請省略欄位。
404 檢查工作階段 ID、請求 ID 和回應類型。請重新取得工作階段,因為該請求可能已不再可用。
409 重新取得工作階段。請求可能已過期、所屬回合可能已結束,或系統可能已接受其他回應。
收到確認前連線中斷 此時無法確定系統是否已接受回應。請重新連線並取得工作階段,再決定是否重試。

身分驗證請求會在五分鐘後過期,而且使用者輸入資料期間,請求所屬的回合也可能結束。恢復顯示登入表單前,請重新取得工作階段。

如果重試提交身分驗證資料,請使用相同的 request_id、所選選項,以及相同的欄位與值對應關係。重試時提交完全相同的資料,不會再次填寫瀏覽器中的表單。系統接受提交的資料後,若變更值再提交,系統會傳回 409。若要重新嘗試登入,智慧體必須發出新的請求。

如果來源存取核准決定傳送失敗,請以相同的決定重試。若變更系統已接受的決定,系統會傳回 409。來源存取請求在所屬回合內會保持待處理狀態,不受身分驗證請求五分鐘逾時限制的影響。

控制網路存取

使用代管環境的 network 設定,控制瀏覽器和環境中執行的程式碼對外存取網路的權限。請允許存取目標網站,以及載入網頁資源或重新導向所需的所有網域。

是否核准來源存取由使用者另行決定,核准不會覆寫網路政策。如需設定環境,請參閱網路存取設定。

繼續執行任務與清理環境

如果後續任務需要沿用瀏覽器狀態,請繼續使用同一個工作階段。登入 Cookie 可能會過期,回收環境則會清除瀏覽器狀態。

完成後,請先取得所需的結果,再刪除工作階段以要求清理環境:

刪除瀏覽器工作階段
await client.beta.agents.sessions.delete(session.id);

如需瞭解環境的存續時間和刪除行為,請參閱 OpenAI 代管的沙盒。

請求處理參考

身分驗證資料的提交限制

每次最多可提交六個欄位值,每個欄位只能出現一次。每個值最多可包含 16,384 個字元。欄位值與所選選項序列化後的總大小不得超過 120 KiB。

請使用待核准請求中的請求 ID 和欄位 ID,並為每個必填欄位提供非空值。如需查閱請求的結構描述,請參閱工作階段事件 API 參考文件。

完整的 cURL 請求與串流處理範例

需要區分傳輸失敗、HTTP 錯誤,以及建立工作階段時收到的無效回應時,請使用這個版本。它也會篩選串流輸出,並回報錯誤類型與錯誤碼。操作流程與第一個範例相同,需要使用兩個終端。收到核准請求時,請在第二個終端處理。

建立工作階段並檢查串流失敗原因
create_browser_session() {
  unset session_id
  local result http_status body curl_status
  if result=$(curl --silent --fail-with-body --write-out '\n%{http_code}' \
    https://api.openai.com/v1/agents/sessions \
    -H "OpenAI-Beta: agents=v1" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "agent": {
        "model": "gpt-6-astra",
        "instructions": "Read public documentation in the browser. Do not sign in or change any website data. Report the page title and URL you find.",
        "tools": [{ "type": "computer_use", "include_screenshots": true }]
      },
      "environment": {
        "type": "openai_hosted",
        "desktop": { "enabled": true },
        "network": { "access": "enabled" }
      }
    }'); then curl_status=0; else curl_status=$?; fi
  http_status=$(printf '%s\n' "$result" | tail -n 1)
  body=$(printf '%s\n' "$result" | sed '$d')
  [[ "$http_status" =~ ^[0-9]{3}$ ]] || http_status=000

  if [ "$curl_status" -ne 0 ] || [[ ! "$http_status" =~ ^2[0-9][0-9]$ ]]; then
    printf '%s' "$body" | jq --raw-input --slurp --compact-output \
      --arg status "$http_status" --arg curl_status "$curl_status" '
        def identifier:
          if type == "string" and test("^[A-Za-z][A-Za-z0-9_]{0,79}$") then . else null end;
        (try fromjson catch {}) as $response
        | (if ($response | type) == "object" then $response.error // $response else {} end) as $error
        | if $curl_status != "0" and $curl_status != "22" then
            {status: $status, type: "transport_error", code: ("curl_" + $curl_status)}
          else
            {status: $status, type: ((try ($error.type | identifier) catch null) // "http_error"),
             code: (try ($error.code | identifier) catch null)}
          end' >&2
    return 1
  fi
  if ! session_id=$(printf '%s' "$body" | jq --exit-status --raw-output \
    'select(type == "object") | .id | select(type == "string" and length > 0)' 2>/dev/null); then
    unset session_id
    printf '{"status":"%s","type":"invalid_response","code":"missing_session_id"}\n' "$http_status" >&2
    return 1
  fi
  printf 'Session ID: %s\n' "$session_id"
}
create_browser_session

# Terminal 1: use session_id from the creation request.
# Keep this stream open. Wait for HTTP 200 before sending input.
set -o pipefail
curl --silent --show-error --dump-header - --suppress-connect-headers \
  --no-buffer --fail-with-body \
  "https://api.openai.com/v1/agents/sessions/$session_id/events" \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Accept: text/event-stream" \
  | jq --null-input --raw-input --compact-output --unbuffered '
      def identifier:
        if type == "string" and test("^[A-Za-z][A-Za-z0-9_]{0,79}$") then . else null end;
      def safe_error:
        if type == "object" then {type: (.type | identifier), code: (.code | identifier)} else null end;
      def public_event:
        if .type == "agent.session.turn.output_text.done" then {type, text}
        elif .type == "agent.session.turn.completed" or .type == "agent.session.turn.failed" or .type == "agent.session.turn.cancelled" then
          {type, turn_id: .turn.id, subagent_id: .turn.subagent_id, error: (.turn.error | safe_error)}
        elif .type == "error" or .type == "agent.session.failed" or .type == "agent.session.environment.failed" then
          {type, error: ((.error // .session.error // .environment.error) | safe_error)}
        elif .type == "agent.session.requires_action" then {type}
        else empty end;
      foreach inputs as $raw (
        {body: "", headers: false, failed: false, output: []};
        .output = []
        | ($raw | rtrimstr([13] | implode)) as $line
        | if ($line | startswith("HTTP/")) then
            (try ($line | capture("^(?<protocol>HTTP/[0-9.]+) (?<status>[0-9]{3})(?: |$)")) catch null) as $http
            | if $http == null then . else
                .body = "" | .headers = true | .status = $http.status
                | .failed = (($http.status | tonumber) >= 300)
                | .output = [$http.protocol + " " + $http.status]
              end
          elif .headers then
            if $line == "" then .headers = false else . end
          elif ($line | startswith("data:")) then
            (try ($line | ltrimstr("data:") | fromjson) catch null) as $event
            | .output = [$event | select(type == "object") | public_event]
          elif .failed and .body != null then
            .body += ($line + "\n")
            | (try (.body | fromjson) catch null) as $body
            | if ($body | type) == "object" then
                (($body.error // $body) | safe_error) as $error
                | .output = [{status: .status, type: ($error.type // "http_error"), code: $error.code}]
                | .body = null
              else . end
          else . end;
        .output[])'

# Terminal 2: replace sess_123 with the ID printed in terminal 1.
# Export OPENAI_API_KEY in this terminal too.
session_id="sess_123"
curl --fail-with-body "https://api.openai.com/v1/agents/sessions/$session_id/events" \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "type": "agent.session.input.message",
      "input": [{
        "role": "user",
        "content": [{
          "type": "input_text",
          "text": "Open https://developers.openai.com in the browser. Find the Agents API quickstart, then report its page title and URL."
        }]
      }]
    }]
  }'