如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .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 快速入门,并返回其标题和 URL。

请先打开事件流,再发送任务,以便您的应用收到最早的进度事件。每当收到网站源访问审批请求时,请及时处理,让浏览器继续执行任务。

发送任务并跟踪结果
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();
}

示例会打印智能体的回答。请检查回答是否包含快速入门的标题和 URL。

关闭事件流不会停止任务。要停止任务,请取消当前轮次。如果连接失败或无法确定操作结果,请按照恢复指南操作。详细的 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 私有代码仓库中的议题等任务需要浏览器处于已登录状态。由您的应用处理登录,用户就可以在聊天之外选择登录方式并输入凭据。

一次登录可能涉及多个请求。例如,网站可能会先让用户选择邮箱登录,再输入邮箱地址,最后输入验证码。请根据每个请求提供的登录方式和字段构建界面。

只有主智能体可以请求浏览器身份验证,子智能体不能发起此类请求。此流程支持使用邮箱地址、密码和验证码登录,不支持使用通行密钥或扫码登录。如果网站要求使用不受支持的登录方式,就无法通过此流程完成登录。

保持任务的事件流打开,并在收到网站源访问审批请求时及时处理。收到 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);
}

登录可能涉及多个请求,因此请持续处理审批,直到任务完成。对照任务要求检查智能体的结果。在本例中,请核实智能体返回的议题标题和 URL。

查看登录历史记录

身份验证请求和已接受的响应会出现在会话历史记录和 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."
        }]
      }]
    }]
  }'