OpenAI 推出 Agents API:通过托管 Codex harness 构建可执行任务的 Agent
英文标题:🔶 OpenAI Agents API
OpenAI Agents API 让应用可通过由 OpenAI 托管的 API 使用 Codex harness,并由平台负责会话、编排、上下文压缩与恢复。开发者可为 Agent 配置模型、指令、工具、MCP 服务器及运行环境,Agent 能在沙箱中执行代码、编辑文件、访问 MCP 服务并生成产物。该 API 支持流式事件、Webhook、会话续接、多 Agent 子任务委派等能力,适用于需要长期执行、多步骤操作的 AI 应用。模型调用、OpenAI 工具及托管沙箱将分别按照 API、内置工具和容器的标准费率计费。
26.5 KB
24.2 KB
224.6 KB
中文
Agents API 让你的应用能够通过由 OpenAI 托管的 API 访问 Codex harness。
OpenAI 负责管理会话、编排、上下文压缩和恢复;你的应用则提供工具,并选择其执行环境。
Agent 可在沙箱中运行,在其中执行代码、编辑文件、连接 MCP 服务器并生成产物。
模型使用将按所选模型的 API 费率计费。OpenAI 工具采用其标准费率,OpenAI 托管的沙箱则采用标准容器费率。
试用以下完整示例:
探索完整应用:
Agents API 围绕四个核心概念构建:
- Agent: 可供 Agent 使用的模型、指令、工具和 MCP 服务器。
- 环境(Environment): 可选的沙箱或计算机,Agent 可在其中访问文件、加载技能并运行命令。
- 会话(Session): Agent 的持久化实例,可处理任务并响应输入。
- 事件与项目(Events and items): 发送给 Agent 的输入,以及会话期间生成的输出。
在快速入门中,从一个 OpenAI 托管沙箱开始:
- 创建会话。 配置 Agent;OpenAI 将为其配置环境。
- 向其下达任务。 环境准备就绪后,用户输入将启动一个工作轮次。
- 跟踪进度。 流式接收输出,或使用 Webhook 了解 Agent 何时完成或需要输入。
- 继续或引导。 向同一会话发送另一项任务,或在 Agent 当前工作轮次中引导它。
使用 OpenAI 托管会话时,你的应用负责发送输入和接收事件,而 OpenAI 负责运行 Agent,并配置和管理其沙箱。有关设置和限制,请参阅环境选项。

托管的 Codex harness 支持:
- 在沙箱中运行命令和代码。
- 应用相关技能和指令。
- 通过工具或 MCP 连接外部数据。
- 在 Agent 工作期间对其进行引导。
- 汇总此前工作,以管理其上下文窗口。
- 将工作拆分为子任务,并委派给子 Agent。
- 从此前中断的位置恢复会话。
请查看快速入门前提条件,了解 API 密钥权限和 SDK 设置。在创建会话时配置以下能力:
javascript import OpenAI from "openai";
const client = new OpenAI();
const session = await client.beta.agents.sessions.create({ agent: { model: "gpt-6-astra", instructions: "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.", tools: [ { type: "programmatic_tool_calling" }, { type: "mcp", server_label: "openai_docs", transport: { type: "http", server_url: "https://developers.openai.com/mcp", }, }, { type: "web_search" }, ], multi_agent: { enabled: true, max_concurrent_subagents: 4 }, }, environment: { type: "self_hosted", workspace_directory: "/workspace", capability_directories: ["/workspace/capabilities/skills"], }, input: [ { role: "user", content: [ { type: "input_text", text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup.", }, ], }, ], }); console.log(session.id);
python from openai import OpenAI
client = OpenAI()
session = client.beta.agents.sessions.create( agent={ "model": "gpt-6-astra", "instructions": "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.", "tools": [ {"type": "programmatic_tool_calling"}, { "type": "mcp", "server_label": "openai_docs", "transport": { "type": "http", "server_url": "https://developers.openai.com/mcp", }, }, {"type": "web_search"}, ], "multi_agent": {"enabled": True, "max_concurrent_subagents": 4}, }, environment={ "type": "self_hosted", "workspace_directory": "/workspace", "capability_directories": ["/workspace/capabilities/skills"], }, input=[ { "role": "user", "content": [ { "type": "input_text", "text": "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup.", } ], } ], ) print(session.id)
go import ( "context" "fmt" "github.com/openai/openai-go/v3" )
ctx := context.Background() client := openai.NewClient() session, err := client.Beta.Agents.Sessions.New(ctx, openai.BetaAgentSessionNewParams{Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra"), Instructions: openai.String("Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful."), Tools: []openai.AgentToolParamUnion{openai.AgentToolParamUnion{OfParamProgrammaticToolCalling: &openai.AgentToolParamProgrammaticToolCalling{}}, openai.AgentToolParamUnion{OfParamMcp: &openai.AgentToolParamMcp{ServerLabel: "openai_docs", Transport: openai.McpTransportParamUnion{OfParamHTTP: &openai.McpTransportParamHTTP{ServerURL: "https://developers.openai.com/mcp"}}}}, openai.AgentToolParamUnion{OfParamWebSearch: &openai.AgentToolParamWebSearch{}}}, MultiAgent: openai.MultiAgentConfigParam{Enabled: true, MaxConcurrentSubagents: openai.Int(4)}}, Environment: openai.EnvironmentParamUnion{OfParamSelfHosted: &openai.EnvironmentParamSelfHosted{WorkspaceDirectory: "/workspace", CapabilityDirectories: []string{"/workspace/capabilities/skills"}}}, Input: openai.BetaAgentSessionNewParamsInputUnion{OfArrayOfInputMessages: []openai.AgentSessionInputMessageParam{openai.AgentSessionInputMessageParam{Content: []openai.InputContentParamUnion{openai.InputContentParamUnion{OfParamInputText: &openai.InputContentParamInputText{Text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup."}}}}}}}) if err != nil { panic(err) } fmt.Println(session.ID)
java import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.beta.agents.AgentToolParam; import com.openai.models.beta.agents.EnvironmentParam; import com.openai.models.beta.agents.McpTransportParam; import com.openai.models.beta.agents.MultiAgentConfigParam; import com.openai.models.beta.agents.sessions.SessionCreateParams; import java.util.List;
OpenAIClient client = OpenAIOkHttpClient.fromEnv(); var session = client .beta() .agents() .sessions() .create( SessionCreateParams.builder() .agent( SessionCreateParams.Agent.builder() .model("gpt-6-astra") .instructions( "Use the OpenAI documentation MCP and web search to answer" + " technical questions accurately. Delegate independent" + " research tasks to subagents when useful.") .addTool(AgentToolParam.ProgrammaticToolCalling.builder().build()) .addTool( AgentToolParam.Mcp.builder() .serverLabel("openai_docs") .transport( McpTransportParam.Http.builder() .serverUrl("https://developers.openai.com/mcp") .build()) .build()) .addTool(AgentToolParam.WebSearch.builder().build()) .multiAgent( MultiAgentConfigParam.builder() .enabled(true) .maxConcurrentSubagents(4L) .build()) .build()) .environment( EnvironmentParam.SelfHosted.builder() .workspaceDirectory("/workspace") .capabilityDirectories(List.of("/workspace/capabilities/skills")) .build()) .input( "Research how to connect an MCP server to an OpenAI agent, check for recent" + " updates, and summarize the recommended setup.") .build()); System.out.println(session.id());
ruby require "openai"
client = OpenAI::Client.new
session = client.beta.agents.sessions.create(agent: {model: "gpt-6-astra", instructions: "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.", tools: [{type: "programmatic_tool_calling"}, {type: "mcp", server_label: "openai_docs", transport: {type: "http", server_url: "https://developers.openai.com/mcp"}}, {type: "web_search"}], multi_agent: {enabled: true, max_concurrent_subagents: 4}}, environment: {type: "self_hosted", workspace_directory: "/workspace", capability_directories: ["/workspace/capabilities/skills"]}, input: [{role: "user", content: [{type: "input_text", text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup."}]}]) puts session.id
bash
curl -sS -X POST "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": "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.",
"tools": [
{
"type": "programmatic_tool_calling"
},
{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp"
}
},
{
"type": "web_search"
}
],
"multi_agent": {
"enabled": true,
"max_concurrent_subagents": 4
}
},
"environment": {
"type": "self_hosted",
"workspace_direct
English / 原文
The Agents API gives your application access to the Codex harness through an OpenAI-managed API.
OpenAI manages sessions, orchestration, context compaction, and recovery while your application provides tools and chooses its execution environment.
Agents can operate in a sandbox where they can execute code, edit files, connect to MCP servers, and produce artifacts.
Model usage is billed at the selected model’s API rates. OpenAI tools use their standard rates, and OpenAI-hosted sandboxes use standard container rates.
Try these complete examples:
Explore complete applications:
The Agents API is built around four main concepts:
- Agent: The model, instructions, tools, and MCP servers available to the agent.
- Environment: An optional sandbox or computer where the agent accesses files, loads skills, and runs commands.
- Session: A durable instance of an agent that works on tasks and responds to input.
- Events and items: The inputs sent to an agent and the output produced during a session.
Start with an OpenAI-hosted sandbox in the quickstart:
- Create a session. Configure the agent; OpenAI provisions its environment.
- Give it a task. User input starts a turn of work once the environment is ready.
- Follow progress. Stream output or use webhooks to learn when the agent finishes or needs input.
- Continue or steer. Send another task to the same session, or guide the agent during its current turn.
With an OpenAI-hosted session, your application sends input and receives events, while OpenAI runs the agent and provisions and manages its sandbox. See environment options for setup and limitations.

The managed Codex harness supports:
- Running commands and code in a sandbox.
- Applying relevant skills and instructions.
- Connecting to external data through tools or MCP.
- Steering the agent while it works.
- Summarizing previous work to manage its context window.
- Breaking work into subtasks and delegating to subagents.
- Resuming a session where it left off.
Check the quickstart prerequisites for API-key permissions and SDK setup. Configure these capabilities when you create a session:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41import OpenAI from "openai";
const client = new OpenAI();
const session = await client.beta.agents.sessions.create({
agent: {
model: "gpt-6-astra",
instructions:
"Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.",
tools: [
{ type: "programmatic_tool_calling" },
{
type: "mcp",
server_label: "openai_docs",
transport: {
type: "http",
server_url: "https://developers.openai.com/mcp",
},
},
{ type: "web_search" },
],
multi_agent: { enabled: true, max_concurrent_subagents: 4 },
},
environment: {
type: "self_hosted",
workspace_directory: "/workspace",
capability_directories: ["/workspace/capabilities/skills"],
},
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup.",
},
],
},
],
});
console.log(session.id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40from openai import OpenAI
client = OpenAI()
session = client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.",
"tools": [
{"type": "programmatic_tool_calling"},
{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp",
},
},
{"type": "web_search"},
],
"multi_agent": {"enabled": True, "max_concurrent_subagents": 4},
},
environment={
"type": "self_hosted",
"workspace_directory": "/workspace",
"capability_directories": ["/workspace/capabilities/skills"],
},
input=[
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup.",
}
],
}
],
)
print(session.id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
ctx := context.Background()
client := openai.NewClient()
session, err := client.Beta.Agents.Sessions.New(ctx, openai.BetaAgentSessionNewParams{Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra"),
Instructions: openai.String("Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful."),
Tools: []openai.AgentToolParamUnion{openai.AgentToolParamUnion{OfParamProgrammaticToolCalling: &openai.AgentToolParamProgrammaticToolCalling{}},
openai.AgentToolParamUnion{OfParamMcp: &openai.AgentToolParamMcp{ServerLabel: "openai_docs",
Transport: openai.McpTransportParamUnion{OfParamHTTP: &openai.McpTransportParamHTTP{ServerURL: "https://developers.openai.com/mcp"}}}},
openai.AgentToolParamUnion{OfParamWebSearch: &openai.AgentToolParamWebSearch{}}},
MultiAgent: openai.MultiAgentConfigParam{Enabled: true,
MaxConcurrentSubagents: openai.Int(4)}},
Environment: openai.EnvironmentParamUnion{OfParamSelfHosted: &openai.EnvironmentParamSelfHosted{WorkspaceDirectory: "/workspace",
CapabilityDirectories: []string{"/workspace/capabilities/skills"}}},
Input: openai.BetaAgentSessionNewParamsInputUnion{OfArrayOfInputMessages: []openai.AgentSessionInputMessageParam{openai.AgentSessionInputMessageParam{Content: []openai.InputContentParamUnion{openai.InputContentParamUnion{OfParamInputText: &openai.InputContentParamInputText{Text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup."}}}}}}})
if err != nil {
panic(err)
}
fmt.Println(session.ID)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.AgentToolParam;
import com.openai.models.beta.agents.EnvironmentParam;
import com.openai.models.beta.agents.McpTransportParam;
import com.openai.models.beta.agents.MultiAgentConfigParam;
import com.openai.models.beta.agents.sessions.SessionCreateParams;
import java.util.List;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var session =
client
.beta()
.agents()
.sessions()
.create(
SessionCreateParams.builder()
.agent(
SessionCreateParams.Agent.builder()
.model("gpt-6-astra")
.instructions(
"Use the OpenAI documentation MCP and web search to answer"
+ " technical questions accurately. Delegate independent"
+ " research tasks to subagents when useful.")
.addTool(AgentToolParam.ProgrammaticToolCalling.builder().build())
.addTool(
AgentToolParam.Mcp.builder()
.serverLabel("openai_docs")
.transport(
McpTransportParam.Http.builder()
.serverUrl("https://developers.openai.com/mcp")
.build())
.build())
.addTool(AgentToolParam.WebSearch.builder().build())
.multiAgent(
MultiAgentConfigParam.builder()
.enabled(true)
.maxConcurrentSubagents(4L)
.build())
.build())
.environment(
EnvironmentParam.SelfHosted.builder()
.workspaceDirectory("/workspace")
.capabilityDirectories(List.of("/workspace/capabilities/skills"))
.build())
.input(
"Research how to connect an MCP server to an OpenAI agent, check for recent"
+ " updates, and summarize the recommended setup.")
.build());
System.out.println(session.id());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21require "openai"
client = OpenAI::Client.new
session = client.beta.agents.sessions.create(agent: {model: "gpt-6-astra",
instructions: "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.",
tools: [{type: "programmatic_tool_calling"},
{type: "mcp",
server_label: "openai_docs",
transport: {type: "http",
server_url: "https://developers.openai.com/mcp"}},
{type: "web_search"}],
multi_agent: {enabled: true,
max_concurrent_subagents: 4}},
environment: {type: "self_hosted",
workspace_directory: "/workspace",
capability_directories: ["/workspace/capabilities/skills"]},
input: [{role: "user",
content: [{type: "input_text",
text: "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup."}]}])
puts session.id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46curl -sS -X POST "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": "Use the OpenAI documentation MCP and web search to answer technical questions accurately. Delegate independent research tasks to subagents when useful.",
"tools": [
{
"type": "programmatic_tool_calling"
},
{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp"
}
},
{
"type": "web_search"
}
],
"multi_agent": {
"enabled": true,
"max_concurrent_subagents": 4
}
},
"environment": {
"type": "self_hosted",
"workspace_directory": "/workspace",
"capability_directories": ["/workspace/capabilities/skills"]
},
"input": [
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "Research how to connect an MCP server to an OpenAI agent, check for recent updates, and summarize the recommended setup."
}
]
}
]
}'
For a runtime comparison, see the Agents overview.
The Agents API retains session state so you can continue work across turns without rebuilding the conversation context. You can delete sessions and published artifacts when you no longer need them. The Agents API currently supports data residency only in the United States and does not support Zero Data Retention (ZDR). Choosing a self-hosted sandbox does not make the Agents API ZDR-eligible. See Data controls in the OpenAI platform for details on data residency and retention.