主页
过去两年,每个做 agent 的团队都自己写过一遍「循环」——调模型、调工具、压上下文、派子任务、断线重连。2026 年 9 月 10 日,OpenAI 把驱动 Codex 的那套循环打包成了 API。这篇讲清楚:它到底托管了什么、怎么用、什么时候该用、什么时候不该。
For two years, every team building agents wrote the same loop by hand: call the model, call the tools, compact the context, fan out subtasks, recover from disconnects. On 10 September 2026, OpenAI packaged the loop behind Codex into an API. This piece covers what it actually manages, how to use it, when it fits, and when it doesn't.
先给全貌,细节后面逐层展开。
The whole picture first; details come layer by layer.
Agents API 是 OpenAI 在 2026 年 9 月 10 日开放公测的一套托管 agent 运行服务。你用一次 API 调用创建一个「会话」(session),在里面指定任务、模型、工具和运行环境;OpenAI 负责把 agent 跑起来并让它一直跑下去——包括调用模型、执行工具循环、在上下文快满时自动压缩、把活拆给子 agent、以及在断线后保住进度。
The Agents API is a managed service for running agents, opened in public beta by OpenAI on 10 September 2026. You create a session in a single API call, specifying the task, model, tools, and environment; OpenAI runs the agent and keeps it running — calling the model, driving the tool loop, compacting context as it fills up, splitting work across subagents, and preserving progress across disconnects.
来源:Introducing the Agents API — OpenAI, 2026-09-10
Source: Introducing the Agents API — OpenAI, 10 Sep 2026
图 1:三方关系。你的应用提交任务、收事件;OpenAI 托管的 harness 跑循环;环境负责真正执行命令。依据官方架构文档绘制。
Fig. 1: The three parties. Your app submits tasks and receives events; OpenAI's managed harness runs the loop; the environment actually executes. Drawn from the official architecture guide.
先讲问题,再讲答案——否则你很难判断这个答案值不值。
Problem first, answer second — otherwise you can't judge whether the answer is worth it.
要理解这个 API,得先明白一个词:harness。
To understand this API, you first need one word: harness.
写一个「能跑通 demo」的 harness 是一个下午的事。让它在生产环境跑几小时几天不出事,是另一回事。真正吃掉时间的是这几样:
Writing a harness that survives a demo takes an afternoon. Making one that runs for hours or days in production is a different job. The time goes into these:
来源:OpenAI 发布公告 · Agents API Architecture 文档
Sources: OpenAI launch post · Agents API architecture guide
官方架构文档把整个系统拆成三块。搞清这三块,后面所有配置都有地方安放。
The official architecture guide splits the system into three parts. Once these click, every config option has a place to live.
无论选哪种环境,拿进度和结果都有两条路,可以同时用:streaming(开着流,实时拿到细粒度事件,适合在产品里显示 agent 正在做什么)和 webhooks(不用一直挂着连接,会话状态变化时回调你的 handler;handler 里可以取结果、跑 function tool、管自托管环境)。
Whichever environment you pick, there are two ways to get progress — and you can use both: streaming (keep a stream open for fine-grained events, good for showing users what the agent is doing) and webhooks (no long-lived connection; your handler is called on session state changes and can fetch results, run function tools, or manage a self-hosted environment).
来源:Architecture — OpenAI API Docs
Source: Architecture — OpenAI API Docs
以下代码取自官方 quickstart,未做改写。
The code below is taken from the official quickstart, unmodified.
api.agents.read 与 api.agents.write(会话操作)以及 api.responses.write(模型推理)。官方特别提醒:把这个 key 放在 agent 沙箱之外。OpenAI-Beta: agents=v1。官方 SDK 会自动加,用 cURL 时要自己写。beta.agents 命名空间,一次调用同时完成「建会话 + 提交任务 + 开流」。agent.session.turn.completed 再检查 agent 报告的执行结果。session_id 发后续任务,或者在保存好需要的文件后删除会话。api.agents.read and api.agents.write (session operations) plus api.responses.write (model inference). The docs add a pointed reminder: keep this key outside the agent's sandbox.OpenAI-Beta: agents=v1. The official SDKs add it; with cURL you supply it yourself.beta.agents namespace; one call creates the session, submits the task, and opens the stream.agent.session.turn.completed, check the execution result the agent reports.session_id for follow-ups, or delete the session after saving any files you need.最小可运行例子(Python,官方 quickstart 原样):
Minimal runnable example (Python, verbatim from the official quickstart):
# pip install --upgrade openai
from openai import OpenAI
with OpenAI() as client:
with client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output.",
},
environment={"type": "openai_hosted"},
input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream=True,
) as events:
for event in events:
print(event.to_json(indent=None), flush=True)
# pip install --upgrade openai
from openai import OpenAI
with OpenAI() as client:
with client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output.",
},
environment={"type": "openai_hosted"},
input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream=True,
) as events:
for event in events:
print(event.to_json(indent=None), flush=True)
发布公告里给的那个例子更能说明「生产级 agent 一次调用建好」是什么意思——注意 tools 里直接挂了一个远程 MCP server,multi_agent 开了三个并发子 agent,vault_ids 传了密钥保管库,capability_directories 指向沙箱里的 skills 目录:
The example in the launch post shows better what "a production-ready agent in a single call" means — note the remote MCP server wired straight into tools, three concurrent subagents via multi_agent, a secrets vault through vault_ids, and capability_directories pointing at a skills folder inside the sandbox:
const session = await client.beta.agents.sessions.create({
agent: {
model: "gpt-6-astra",
tools: [{
type: "mcp",
server_label: "observability",
transport: { type: "http", server_url: "https://observability.example.com/mcp" },
}],
multi_agent: { enabled: true, max_concurrent_subagents: 3 },
},
vault_ids: ["vault_YOUR_VAULT_ID"],
environment: {
type: "openai_hosted",
capability_directories: ["/workspace/capabilities/skills"],
},
input:
"Investigate service-api's elevated 5xx rate over the last 30 minutes. " +
"Delegate deployment, error, and dependency analysis to subagents. " +
"Save findings, evidence, and recommended mitigation in /workspace/outputs.",
});
const session = await client.beta.agents.sessions.create({
agent: {
model: "gpt-6-astra",
tools: [{
type: "mcp",
server_label: "observability",
transport: { type: "http", server_url: "https://observability.example.com/mcp" },
}],
multi_agent: { enabled: true, max_concurrent_subagents: 3 },
},
vault_ids: ["vault_YOUR_VAULT_ID"],
environment: {
type: "openai_hosted",
capability_directories: ["/workspace/capabilities/skills"],
},
input:
"Investigate service-api's elevated 5xx rate over the last 30 minutes. " +
"Delegate deployment, error, and dependency analysis to subagents. " +
"Save findings, evidence, and recommended mitigation in /workspace/outputs.",
});
turn.failed、turn.cancelled、session.failed 结尾的事件表示失败或取消;而 agent.session.idle 单独出现并不意味着成功。如果流提前断开,先取回会话及其已保存的 items,再决定是否重试。turn.failed, turn.cancelled, or session.failed mean failure or cancellation; agent.session.idle on its own does not mean success. If the stream disconnects early, retrieve the session and its saved items before retrying.因为大多数人写重试逻辑时,判断条件就是「这一轮结束了吗」。如果你只看 turn 完成就返回成功,那么一个「跑了脚本、脚本报错、agent 如实汇报了错误、然后正常结束这一轮」的过程,在你的系统里会被记成一次成功交付。错误会静悄悄地流到下游。正确做法是:既看事件类型,也读 agent 报告的执行结果。
Because most retry logic keys off "did this turn end?". If you treat a completed turn as success, then a run where the script failed, the agent faithfully reported the error, and the turn ended normally gets recorded as a successful delivery. The failure flows silently downstream. The fix: check the event type and read the execution result the agent reports.
来源:Agents API quickstart · 发布公告
Sources: Agents API quickstart · launch post
这四件,正是过去每个团队自己重写一遍的部分。
These four are exactly what every team used to reimplement.
会话逼近上下文上限时,Agents API 会自动压缩较早的上下文,保留 agent 继续干活所需的信息。官方给的意义是:开发者可以写「跨多个上下文窗口」的工作流,而不必自己实现压缩逻辑。
As a session approaches its context limit, the Agents API automatically compacts earlier context, preserving what the agent needs to continue. The stated upshot: you can build workflows that span multiple context windows without implementing your own compaction logic.
tool search 按需加载相关的工具定义,而不是把所有工具一次性塞进上下文。官方说明这样做有两个好处:降低 token 用量与成本,以及保住模型的缓存——后者常被忽略,但它才是大头:工具列表是 prompt 前缀里最靠前的一段,一动就让整个缓存前缀失效。
Tool search loads relevant tool definitions as needed rather than dumping every tool into context. The docs cite two benefits: lower token usage and cost, and preserving the model's cache — the second matters more than people expect, since the tool list sits near the front of the prompt prefix, and touching it invalidates the whole cached prefix.
工具可用之后,programmatic tool calling 让 agent 并行发起调用、串联相关操作、并在代码里过滤或合并结果,从而处理大批量数据,而只把相关的那部分带回上下文。
Once tools are available, programmatic tool calling lets the agent run calls in parallel, chain related operations, and filter or combine results in code, so it can work through large volumes of data while bringing only the relevant results back into context.
开启多 agent 支持后,Agents API 可以把复杂任务拆成互相独立的几块,交给并行工作的子 agent。关键设计:每个子 agent 维护自己的上下文,以便专注于自己那一份;主 agent 负责协调并汇总结果。配置极简:
With multi-agent support enabled, the Agents API can break a complex task into independent pieces and delegate them to subagents working in parallel. The key design point: each subagent keeps its own context so it stays focused on its assignment, while the main agent coordinates and merges results. The config is minimal:
"agent": {
"model": "gpt-6-astra",
"multi_agent": {
"enabled": true,
"max_concurrent_subagents": 3
}
}
"agent": {
"model": "gpt-6-astra",
"multi_agent": {
"enabled": true,
"max_concurrent_subagents": 3
}
}
图 2:compaction 管时间轴、tool search 管工具清单、subagents 管任务分流。三者共同把进入模型的上下文压小。依据官方文档整理。
Fig. 2: compaction works on the timeline, tool search on the tool list, subagents on task fan-out. Together they keep the model's context small. Compiled from the official docs.
来源:Compaction · Tool search · Programmatic tool calling · Multi-agent
Sources: Compaction · Tool search · Programmatic tool calling · Multi-agent
这是接入时第一个要拍板的决定,也是责任边界最不一样的地方。
This is the first decision you'll make, and the one where responsibility shifts most.
图 3:三种环境模式与各自的责任边界。越往右,能力越大、你要管的事越多。依据官方架构文档绘制。
Fig. 3: the three environment modes and where responsibility sits. Further right means more capability and more to operate. Drawn from the official architecture guide.
| 模式 | 什么时候选 | 你要负责什么 | 注意 |
|---|---|---|---|
none | agent 只回答问题、或只通过工具访问外部服务,不需要自己的计算和文件 | function tool 的 handler | 内建 Bash 与 apply-patch 工具、工作区文件、executor MCP 全部不可用 |
openai_hosted | agent 需要跑脚本、改文件、产出 artifacts,又想快速起步并弹性扩展 | 提交任务、收事件、处理 function tool | 用的是与 Codex / ChatGPT 相同的沙箱基础设施;可配置文件、包、skills 与 plugins |
self_hosted | agent 需要你的基础设施、内网,或自定义软件 | 启动环境并接上 executor;开通、重连、关停;需要保留的文件 | 关停算力前必须协调好待进入的工作,并确认没有执行中的调用 |
| Mode | When to pick it | What you own | Watch out |
|---|---|---|---|
none | The agent only answers questions or reaches external services through tools; no compute or files of its own | Handlers for your function tools | Built-in Bash and apply-patch tools, workspace files, and executor MCPs are all unavailable |
openai_hosted | The agent runs scripts, edits files, produces artifacts — and you want to start fast and scale | Submitting tasks, receiving events, handling function tools | Same sandbox infrastructure that powers Codex and ChatGPT; configurable files, packages, skills and plugins |
self_hosted | The agent needs your infrastructure, private network, or custom software | Starting the environment and attaching an executor; provisioning, reconnection, shutdown; any files to preserve | Before stopping compute, coordinate incoming work and confirm no execution is pending |
自托管不必从零搭。OpenAI 同时公布了沙箱生态合作方,提供一等公民集成:Blaxel、Cloudflare、Daytona、DigitalOcean、E2B、Modal、Oracle、Runloop、Vercel。官方列出的差异化维度是:全托管环境 vs 部署进你自己的 VPC;不同的文件与密钥存储机制;不同的 CPU / GPU / 内存配置,以及各自的性能、冷启动与成本曲线。
Self-hosting doesn't mean building from scratch. OpenAI also named sandbox ecosystem partners with first-class integrations: Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop, Vercel. The dimensions they differ on, per the announcement: fully managed environments versus deployment inside your own VPC; different file and secret storage mechanisms; different CPU, GPU and memory configurations with their own performance, cold-start and cost profiles.
来源:Architecture · OpenAI-hosted sandboxes · Self-hosted sandboxes
Sources: Architecture · OpenAI-hosted sandboxes · Self-hosted sandboxes
以下按各方公开定位对比,非逐项实测;选型请以自己的工作负载实测为准。
Compared on publicly stated positioning, not head-to-head benchmarks; validate against your own workload before committing.
| 方案 | 它的主张 | 适合 | 代价 |
|---|---|---|---|
| 自己写 harness | 完全控制循环逻辑 | 有特殊的编排需求;必须离线或完全自主可控;把 harness 本身当作差异化能力 | 上下文管理、工具检索、并行编排、断线恢复全部自己实现并持续维护;模型换代要重写 |
| OpenAI Agents API | 托管 Codex harness,随模型版本化演进 | 长时运行、多工具、需要沙箱与子 agent 的生产 agent;不想把工程预算花在循环上 | 绑定 OpenAI 模型与运行时;harness 内部由 OpenAI 决定(底座开源可读,但你不运维);公测期 API 会变 |
| Claude Agent SDK | 把 Claude Code 的 agent 能力以 SDK 形式提供,在你自己的进程里跑 | 已在 Anthropic 生态;希望 agent 跑在自己的机器/网络里并完全掌控进程 | 运行时归你运维;跨厂商迁移成本仍在 |
| LangGraph | 把工作流建模成节点与边的图,提供持久状态、人类介入检查点、分支与循环 | 需要显式控制流、人审节点、失败重试与恢复语义的工作流 | 图要自己设计和维护;上下文压缩、工具检索等仍多为自建或选装 |
| Option | Its claim | Good fit when | What it costs you |
|---|---|---|---|
| Roll your own harness | Total control over the loop | You have unusual orchestration needs, must run offline or fully self-governed, or treat the harness itself as differentiation | You implement and maintain context management, tool retrieval, parallel orchestration and recovery — and rework it at every model generation |
| OpenAI Agents API | A managed Codex harness, versioned alongside the models | Long-running, many-tool production agents needing sandboxes and subagents, where engineering budget shouldn't go into the loop | Coupling to OpenAI models and runtime; harness internals decided by OpenAI (the base is open source to read, but you don't operate it); the API will change during beta |
| Claude Agent SDK | Claude Code's agent capabilities as an SDK, running inside your own process | You're already in Anthropic's ecosystem and want the agent on your machines and network, fully under your control | The runtime is yours to operate; cross-vendor migration cost remains |
| LangGraph | Workflows as graphs of nodes and edges, with durable state, human-in-the-loop checkpoints, branching and cycles | Workflows needing explicit control flow, approval steps, and well-defined retry/resume semantics | You design and maintain the graph; compaction, tool retrieval and similar remain build-or-bolt-on |
发布页上有八条客户证言,其中带数字的几条:SafetyKit 称把案件审查工作流迁过来后「每案成本下降 60%、延迟下降、token 效率显著提升,性能维持不变」;Hypha 称「把 agent harness 与 sandbox 分离后,失败的 agent 响应减少了 86%」;Ciridae 称评测分从 0.71 升到 0.85,并称子 agent 流带来「4 倍延迟下降」。这些均为客户自述、无独立验证,也没有公开方法论。截至调研时,我们没有检索到第三方对 Agents API 的独立评测。
The launch page carries eight customer testimonials; the ones with numbers: SafetyKit reports "a 60% reduction in cost per case, lower latency, and significantly improved token efficiency while maintaining existing performance" after migrating its case-review workflow; Hypha reports "reduced failed agent responses by 86%" by separating the harness from the sandbox; Ciridae reports an evaluation score moving from 0.71 to 0.85 and "a 4x latency reduction" from subagent flows. All are self-reported, unverified, and published without methodology. As of this research date we found no independent third-party evaluation of the Agents API.
来源:OpenAI 发布公告(客户证言) · LangGraph 定位据 LangChain 官方框架介绍页
Sources: OpenAI launch post (testimonials) · LangGraph positioning per LangChain's own framework overview
分两类:官方明说的,和我们基于公开信息的判断(已标注)。
Two kinds: what the docs say outright, and our reading of the public information (labelled as such).
agent.session.idle 当成功信号。agent.session.idle as a success signal.session_id 就能发后续任务。agent.session.turn.completed。session_id to send follow-ups.agent.session.turn.completed.