多智能体功能让模型可以创建多个子智能体,协调它们并行工作,并汇总各自的结果,给出最终响应。如果应用需要处理适合并行分工的复杂任务,例如探索代码库、编写文档和实现功能,这一功能尤其有效。
GPT-6.2 Astra、GPT-6.2 Sol、GPT-6.1 Sol 和所有 GPT-5.6 模型均支持多智能体功能,该功能目前处于测试阶段。在您的应用中启用前,请先查看模型页面。
一项任务通常可以拆分成若干相互独立的子任务。单个智能体需要依次完成这些子任务,而多个智能体可以并行处理。在多智能体模式下,根智能体可以将工作分配给多个子智能体,让它们同时执行。这样做有几个好处:
- 并行执行。 相互独立的调研、分析或实现任务可以同时进行,有助于缩短执行时间。
- 上下文更集中。 每个子智能体都负责一项范围明确的任务,并维护自己的上下文。这能减少无关任务之间的上下文干扰,提高性能。
- 由模型协调。 根智能体可以创建子智能体、向它们补充信息、等待结果并汇总成最终答案,无需您的应用实现编排逻辑。
当任务可以拆分成多项具体、相互独立的工作时,多智能体编排最为有用。例如:
- 探索大型代码库的不同部分
- 比较多个提案、文档或假设
- 并行查阅多个信息来源
- 实现相互独立的组件,或编写相互独立的测试套件
- 并行排查故障的多种可能原因
- 同时探索解决同一问题的不同方法
增加子智能体可能会增加 Token 用量。如果任务依赖一条必须按顺序展开的推理链、需要频繁写入共享的可变状态,或者大部分时间都花在同一个缓慢的外部操作上,增加子智能体的收益可能较小。
| 适合使用多智能体的情况 |
更适合使用单个智能体的情况 |
| 工作可以拆分成范围明确、相互独立的任务 |
每一步都直接依赖上一步 |
| 分开维护上下文有助于专注于各自的任务 |
任务较小,一次短时间运行即可完成 |
| 并行探索可以缩短实际耗时 |
多个智能体会争用同一可变资源 |
| 对比独立得出的结果有助于覆盖更多情况 |
您需要固定且确定的执行图 |
Python 和 TypeScript 示例使用测试版 Responses SDK。对于 HTTP 请求,请使用 client.beta.responses,并将 responses_multi_agent=v1 传给 betas 参数。对于原始 HTTP 请求和 WebSocket 连接,请在相应的请求头或连接头中传入 OpenAI-Beta: responses_multi_agent=v1。在多智能体功能的测试阶段,数据项的模式可能会发生变化。
在 Responses API 请求中使用 multi_agent.enabled 启用多智能体功能。当 multi_agent.enabled 为 true 时,根智能体可以创建一棵由子智能体组成的树。各子智能体使用请求中指定的同一模型和同一组可用工具。智能体之间通过创建子智能体、发送消息和等待等基本操作进行协作(请参阅多智能体的工作原理)。根智能体负责汇总各子智能体的响应,并给出最终响应。
Go 示例使用 github.com/openai/openai-go/v3 的 v3.99.0 版本及其带有类型定义的 client.Beta.Responses API。发送 HTTP 请求时,将 Betas 设为 []string {"responses_multi_agent=v1"}。WebSocket 示例使用 client.Beta.Responses.Connect 建立连接,并在建立连接时传入测试版请求头。该示例的完整程序从标准输入读取用于比较的提示词。
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
32import OpenAI from "openai";
const client = new OpenAI();
async function reviewPullRequest(diff: string) {
const response = await client.beta.responses.create({
model: "gpt-6.2-sol",
input:
"Review the pull-request diff below with three agents: one for " +
"correctness, one for security, and one for missing tests. " +
"Reconcile duplicate or conflicting findings, then return a " +
"prioritized review with file and line references.\n\n" +
`<diff>\n${diff}\n</diff>`,
multi_agent: {
enabled: true,
max_concurrent_subagents: 3,
},
betas: ["responses_multi_agent=v1"],
});
return response.output
.flatMap((item) =>
item.type === "message" &&
item.agent?.agent_name === "/root" &&
item.phase === "final_answer"
? item.content
: []
)
.filter((part) => part.type === "output_text")
.map((part) => part.text)
.join("");
}
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
34from openai import OpenAI
client = OpenAI()
def review_pull_request(diff: str) -> str:
response = client.beta.responses.create(
model="gpt-6.2-sol",
input=(
"Review the pull-request diff below with three agents: one for "
"correctness, one for security, and one for missing tests. "
"Reconcile duplicate or conflicting findings, then return a "
"prioritized review with file and line references.\n\n"
f"<diff>\n{diff}\n</diff>"
),
multi_agent={
"enabled": True,
"max_concurrent_subagents": 3,
},
betas=["responses_multi_agent=v1"],
)
return "".join(
part.text
for item in response.output
if (
item.type == "message"
and item.agent is not None
and item.agent.agent_name == "/root"
and item.phase == "final_answer"
)
for part in item.content
if part.type == "output_text"
)
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
26func reviewPullRequest(ctx context.Context, client openai.Client, diff string) (string, error) {
response, err := client.Beta.Responses.New(ctx, openai.BetaResponseNewParams{
Model: "gpt-6.2-sol",
Input: openai.BetaResponseNewParamsInputUnion{OfString: openai.String("Review the pull-request diff below with three agents: one for correctness, one for security, and one for missing tests. Reconcile duplicate or conflicting findings, then return a prioritized review with file and line references.\n\n<diff>\n" + diff + "\n</diff>")},
MultiAgent: openai.BetaResponseNewParamsMultiAgent{Enabled: true, MaxConcurrentSubagents: openai.Int(3)},
Betas: []string{"responses_multi_agent=v1"},
})
if err != nil {
return "", err
}
if response.Status != "completed" {
return "", fmt.Errorf("review did not complete: %s", response.Status)
}
var text strings.Builder
for _, item := range response.Output {
if item.Type != "message" || item.Agent.AgentName != "/root" || item.Phase != "final_answer" {
continue
}
for _, part := range item.AsMessage().Content {
if part.Type == "output_text" {
text.WriteString(part.Text)
}
}
}
return text.String(), nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20def review_pull_request(client, diff)
response = client.beta.responses.create(
model: "gpt-6.2-sol",
input: "Review the pull-request diff below with three agents: one for " \
"correctness, one for security, and one for missing tests. " \
"Reconcile duplicate or conflicting findings, then return a " \
"prioritized review with file and line references.\n\n<diff>\n#{diff}\n</diff>",
multi_agent: {
enabled: true,
max_concurrent_subagents: 3
},
betas: ["responses_multi_agent=v1"]
)
response.output.filter_map do |item|
next unless item.type == :message && item.agent&.agent_name == "/root" && item.phase == :final_answer
item.content.filter_map { |part| part.text if part.type == :output_text }.join
end.join
end
max_concurrent_subagents 设置整棵智能体树中可同时处于活动状态的子智能体数量上限。计数涵盖所有后代,包括直接子智能体、孙级子智能体以及更深层的子智能体,但不包括根智能体。
API 未对该设置规定固定上限。默认值为 3,建议大多数工作负载使用此值。每次多智能体运行的树深度和运行期间创建的子智能体总数也没有固定上限。
您可以添加开发者消息,调整根模型创建子智能体的时机。这条消息用于补充系统为根智能体和子智能体注入的指令。
开发者消息示例:
- “只有当用户明确要求使用子智能体、委派任务或让多个智能体并行工作时,才创建子智能体。”
- “已启用多智能体主动委派。如果并行工作能明显提高速度或质量,请使用子智能体。”
Responses API 为根智能体和子智能体所用的模型提供托管的编排操作及其使用指令。根智能体名为 /root。创建的子智能体使用分层路径,例如:
/root
├── /root/researcher
├── /root/reviewer
└── /root/reviewer/tester
多智能体功能对子智能体总数和树深度均无固定限制。对于大多数任务,请将 max_concurrent_subagents 保持为默认值 3。此设置限制整棵树中可同时进行的子智能体回合数,涵盖直接子智能体和更深层的后代。
启用多智能体模式后,Responses API 会提供六种托管协作操作。您可能会看到表示这些操作的 multi_agent_call 项。您的应用不应执行这些操作,也不应为其提交输出。
| 操作 |
用途 |
spawn_agent |
创建子智能体并分配初始任务。 |
send_message |
将消息放入现有智能体的消息队列,不启动新回合。 |
followup_task |
向现有的非根智能体分配后续任务,并启动或恢复其回合。 |
wait_agent |
等待发起调用的智能体在自己的收件箱中收到更新。 |
interrupt_agent |
中断另一个智能体当前的回合,并保留其上下文。 |
list_agents |
返回当前的智能体树、各智能体的状态及其 last_task_message。 |
开发者自定义工具调用的处理方式与未启用多智能体时相同。树中的任何智能体都可能发出 function_call。您的应用必须执行该调用,并提交与之匹配的 function_call_output。
树中的所有智能体都可以访问 API 请求的模型调用中配置的工具。
HTTP 和 WebSocket 支持相同的多智能体功能。对于频繁使用工具或运行时间较长的工作流,建议使用 WebSocket。通过持久连接,您的应用可以在每个函数输出就绪后立即返回结果,从而降低继续执行的开销,缩短智能体的等待时间。
使用 HTTP 时,每个活动智能体都必须完成工作,或暂停以等待客户端执行函数调用,当前响应才会结束。随后,您的应用执行所有待处理的函数调用,并在新的 Responses API 请求中提交输出,使暂停的智能体恢复执行。
使用 WebSocket 时,您的应用可以在每个函数输出就绪后立即将其注入当前响应,无需等待响应结束。正在等待的智能体可以立即恢复执行,其他智能体则继续工作。当各智能体在不同时间完成工作或请求使用工具时,这种方式可以缩短协调延迟,避免额外的请求往返。
对于需要调用多个托管工具的工作流(例如并行进行网页搜索),或者只需一次请求且函数调用较少的工作流,HTTP 可能就足够了。对于大多数多智能体工作流,WebSocket 更有可能降低延迟并提高端到端性能。


这些示例需要使用支持测试版 Responses API 的测试版 SDK。对于 HTTP 流式请求,请调用 client.beta.responses.create,并将 responses_multi_agent=v1 传给 betas 参数,以启用测试版类型和自动补全。在 Python 中添加类型注解时,请从 openai.types.beta 导入测试版响应项类型。
客户端代码示例:
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112import OpenAI from "openai";
const client = new OpenAI();
const ROOT = "/root";
const proposals = {
alpha: { estimated_weeks: 6, risk: "medium" },
beta: { estimated_weeks: 8, risk: "low" },
};
const tools: OpenAI.Beta.Responses.BetaTool[] = [
{
type: "function",
name: "get_proposal",
description:
"Return details for a proposal that the agents should compare.",
parameters: {
type: "object",
properties: {
proposal: {
type: "string",
enum: ["alpha", "beta"],
},
},
required: ["proposal"],
additionalProperties: false,
},
strict: true,
},
];
const history: (
| OpenAI.Beta.Responses.BetaResponseInputItem
| OpenAI.Beta.Responses.BetaResponseOutputItem
)[] = [
{
role: "user",
content: "Compare proposal alpha and proposal beta.",
},
];
function agentName(item: OpenAI.Beta.Responses.BetaResponseOutputItem) {
return item.agent?.agent_name ?? ROOT;
}
function processToolCall(name: string, argumentsJson: string) {
if (name !== "get_proposal") {
throw new Error(`Unknown tool: ${name}`);
}
const { proposal }: { proposal: unknown } = JSON.parse(argumentsJson);
if (proposal !== "alpha" && proposal !== "beta")
throw new Error(`Unknown proposal: ${proposal}`);
return JSON.stringify(proposals[proposal]);
}
while (true) {
const outputItems = [];
const pendingCalls = [];
const itemAgents = new Map();
const stream = await client.beta.responses.create({
model: "gpt-6.2-sol",
// Replay Beta output unchanged, including agent metadata. The SDK input
// union is narrower than the agent_message content returned by the API.
input: history as OpenAI.Beta.Responses.BetaResponseInput,
tools,
store: false,
multi_agent: {
enabled: true,
max_concurrent_subagents: 3,
},
stream: true,
betas: ["responses_multi_agent=v1"],
});
for await (const event of stream) {
if (event.type === "response.output_item.added") {
itemAgents.set(event.output_index, agentName(event.item));
} else if (event.type === "response.output_text.delta") {
const agent = itemAgents.get(event.output_index) ?? ROOT;
const destination = agent === ROOT ? process.stdout : process.stderr;
destination.write(
agent === ROOT ? event.delta : `[${agent}] ${event.delta}`
);
} else if (event.type === "response.output_item.done") {
outputItems.push(event.item);
if (event.item.type === "function_call") {
pendingCalls.push(event.item);
}
} else if (event.type === "response.completed") {
console.error("\nUsage:", event.response.usage);
break;
} else if (
event.type === "error" ||
event.type === "response.failed" ||
event.type === "response.incomplete"
) {
throw new Error(JSON.stringify(event));
}
}
history.push(...outputItems);
for (const call of pendingCalls) {
history.push({
type: "function_call_output",
call_id: call.call_id,
output: processToolCall(call.name, call.arguments),
});
}
if (pendingCalls.length === 0) break;
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125from __future__ import annotations
import json
import sys
from openai import OpenAI
from openai.types.beta import BetaResponseOutputItem
client = OpenAI()
ROOT = "/root"
PROPOSALS = {
"alpha": {"estimated_weeks": 6, "risk": "medium"},
"beta": {"estimated_weeks": 8, "risk": "low"},
}
tools = [
{
"type": "function",
"name": "get_proposal",
"description": "Return details for a proposal that the agents should compare.",
"parameters": {
"type": "object",
"properties": {
"proposal": {
"type": "string",
"enum": ["alpha", "beta"],
}
},
"required": ["proposal"],
"additionalProperties": False,
},
"strict": True,
}
]
history = [
{
"role": "user",
"content": (
"Use two subagents, one for proposal alpha and one for proposal beta. "
"Have each call get_proposal, then compare their findings."
),
}
]
def agent_name(item: BetaResponseOutputItem) -> str:
return item.agent.agent_name if item.agent else ROOT
def render_to_user(delta: str) -> None:
print(delta, end="", flush=True)
def log_subagent_text(agent: str, delta: str) -> None:
print(f"[{agent}] {delta}", end="", file=sys.stderr, flush=True)
def process_tool_call(name: str, arguments: str) -> str:
if name != "get_proposal":
raise ValueError(f"Unknown tool: {name}")
parsed_arguments = json.loads(arguments)
return json.dumps(PROPOSALS[parsed_arguments["proposal"]])
while True:
output_items = []
pending_calls = []
item_agents: dict[int, str] = {}
completed = False
with client.beta.responses.create(
model="gpt-6.2-sol",
instructions=(
"After launching both subagents, call get_proposal for alpha yourself "
"before waiting for their findings. Use that direct result to check the final comparison."
),
input=history,
tools=tools,
store=False,
multi_agent={
"enabled": True,
"max_concurrent_subagents": 3,
},
stream=True,
betas=["responses_multi_agent=v1"],
) as stream:
for event in stream:
if event.type == "response.output_item.added":
item_agents[event.output_index] = agent_name(event.item)
elif event.type == "response.output_text.delta":
agent = item_agents.get(event.output_index, ROOT)
if agent == ROOT:
render_to_user(event.delta)
else:
log_subagent_text(agent, event.delta)
elif event.type == "response.output_item.done":
output_items.append(event.item)
if event.item.type == "function_call":
# Handle function calls from both the root agent and subagents.
pending_calls.append(event.item)
elif event.type == "response.completed":
print(f"\nUsage: {event.response.usage}", file=sys.stderr)
completed = True
elif event.type in {
"error",
"response.failed",
"response.incomplete",
}:
raise RuntimeError(event)
if not completed:
raise RuntimeError("Stream ended without a completed response")
history.extend(output_items)
for call in pending_calls:
history.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": process_tool_call(call.name, call.arguments),
}
)
if not pending_calls:
break
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/openai/openai-go/v3"
)
func run(ctx context.Context) error {
client := openai.NewClient()
proposals := map[string]any{"alpha": map[string]any{"estimated_weeks": 6, "risk": "medium"}, "beta": map[string]any{"estimated_weeks": 8, "risk": "low"}}
tools := []openai.BetaToolUnionParam{{OfFunction: &openai.BetaFunctionToolParam{
Name: "get_proposal", Description: openai.String("Return details for a proposal that the agents should compare."), Strict: openai.Bool(true),
Parameters: map[string]any{"type": "object", "properties": map[string]any{"proposal": map[string]any{"type": "string", "enum": []string{"alpha", "beta"}}}, "required": []string{"proposal"}, "additionalProperties": false},
}}}
history := []openai.BetaResponseInputItemUnionParam{{OfMessage: &openai.BetaEasyInputMessageParam{Role: "user", Content: openai.BetaEasyInputMessageContentUnionParam{OfString: openai.String("Use two subagents, one for proposal alpha and one for proposal beta. Have each call get_proposal, then compare their findings.")}}}}
for {
stream := client.Beta.Responses.NewStreaming(ctx, openai.BetaResponseNewParams{
Model: "gpt-6.2-sol", Input: openai.BetaResponseNewParamsInputUnion{OfInputItemList: history}, Tools: tools, Store: openai.Bool(false),
Instructions: openai.String("After launching both subagents, call get_proposal for alpha yourself before waiting for their findings. Use that direct result to check the final comparison."),
MultiAgent: openai.BetaResponseNewParamsMultiAgent{Enabled: true, MaxConcurrentSubagents: openai.Int(3)}, Betas: []string{"responses_multi_agent=v1"},
})
completed := false
agents := map[int64]string{}
var outputs []openai.BetaResponseOutputItemUnion
var calls []openai.BetaResponseFunctionToolCall
for stream.Next() {
event := stream.Current()
switch event.Type {
case "response.output_item.added":
agent := event.Item.Agent.AgentName
if agent == "" {
agent = "/root"
}
agents[event.OutputIndex] = agent
case "response.output_text.delta":
agent := agents[event.OutputIndex]
if agent == "" {
agent = "/root"
}
if agent == "/root" {
fmt.Print(event.Delta)
} else {
fmt.Fprintf(os.Stderr, "[%s] %s", agent, event.Delta)
}
case "response.output_item.done":
outputs = append(outputs, event.Item)
if event.Item.Type == "function_call" {
calls = append(calls, event.Item.AsFunctionCall())
}
case "response.completed":
completed = true
usage, err := json.Marshal(event.Response.Usage)
if err != nil {
stream.Close()
return err
}
fmt.Fprintf(os.Stderr, "\nUsage: %s\n", usage)
case "error", "response.failed", "response.incomplete":
stream.Close()
return fmt.Errorf("multi-agent response failed: %s", event.RawJSON())
}
}
err := stream.Err()
stream.Close()
if err != nil {
return err
}
if !completed {
return fmt.Errorf("stream ended without a completed response")
}
// Keep every agent's output, including attribution and encrypted reasoning.
for _, item := range outputs {
var input openai.BetaResponseInputItemUnionParam
if item.Type == "message" {
// Select the output-message variant to retain agent attribution.
message := item.AsMessage().ToParam()
input.OfOutputMessage = &message
} else if err := json.Unmarshal([]byte(item.RawJSON()), &input); err != nil {
return err
}
history = append(history, input)
}
for _, call := range calls {
if call.Name != "get_proposal" {
return fmt.Errorf("unknown tool: %s", call.Name)
}
var args struct {
Proposal string `json:"proposal"`
}
if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil {
return err
}
proposal, ok := proposals[args.Proposal]
if !ok {
return fmt.Errorf("unknown proposal: %s", args.Proposal)
}
output, err := json.Marshal(proposal)
if err != nil {
return err
}
history = append(history, openai.BetaResponseInputItemUnionParam{OfFunctionCallOutput: &openai.BetaResponseInputItemFunctionCallOutputParam{CallID: openai.String(call.CallID), Output: openai.BetaResponseInputItemFunctionCallOutputOutputUnionParam{OfString: openai.String(string(output))}}})
}
if len(calls) == 0 {
return nil
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
if err := run(ctx); err != nil {
log.Fatal(err)
}
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106require "openai"
require "json"
client = OpenAI::Client.new
proposals = {
"alpha" => {
estimated_weeks: 6,
risk: "medium"
},
"beta" => {
estimated_weeks: 8,
risk: "low"
}
}
tools = [
{
type: :function,
name: "get_proposal",
description: "Return details for a proposal that the agents should compare.",
parameters: {
type: "object",
properties: {
proposal: {
type: "string",
enum: ["alpha", "beta"]
}
},
required: ["proposal"],
additionalProperties: false
},
strict: true
}
]
history = [
{
role: :user,
content: "Use two subagents, one for proposal alpha and one for proposal beta. " \
"Have each call get_proposal, then compare their findings."
}
]
loop do
output_items = []
pending_calls = []
item_agents = {}
state = { completed: false }
stream = client.beta.responses.stream_raw(
model: "gpt-6.2-sol", input: history, tools: tools, store: false,
instructions: "After launching both subagents, call get_proposal for alpha yourself " \
"before waiting for their findings. Use that direct result to check the final comparison.",
multi_agent: {
enabled: true,
max_concurrent_subagents: 3
},
betas: ["responses_multi_agent=v1"]
)
begin
stream.each do |event|
case event
when OpenAI::Models::Beta::BetaResponseOutputItemAddedEvent
item_agents[event.output_index] = event.item.agent&.agent_name || "/root"
when OpenAI::Models::Beta::BetaResponseTextDeltaEvent
agent = item_agents.fetch(event.output_index, "/root")
if agent == "/root"
$stdout.print(event.delta)
$stdout.flush
else
$stderr.print("[#{agent}] #{event.delta}")
$stderr.flush
end
when OpenAI::Models::Beta::BetaResponseOutputItemDoneEvent
output_items << event.item
pending_calls << event.item if event.item.is_a?(OpenAI::Models::Beta::BetaResponseFunctionToolCall)
when OpenAI::Models::Beta::BetaResponseCompletedEvent
state[:completed] = true
warn("\nUsage: #{event.response.usage.to_json}")
when OpenAI::Models::Beta::BetaResponseErrorEvent,
OpenAI::Models::Beta::BetaResponseFailedEvent,
OpenAI::Models::Beta::BetaResponseIncompleteEvent
raise "Multi-agent response failed: #{event.type}"
end
end
ensure
stream.close
end
raise "Stream ended without a completed response" unless state[:completed]
# Preserve every output item, including subagent calls, for the next turn.
history.concat(output_items)
pending_calls.each do |call|
raise "Unknown tool: #{call.name}" unless call.name == "get_proposal"
proposal = JSON.parse(call.arguments).fetch("proposal")
history << {
type: :function_call_output,
call_id: call.call_id,
output: JSON.generate(proposals.fetch(proposal))
}
end
break if pending_calls.empty?
end
如果一个或多个智能体调用了开发者自定义函数,请执行每个待处理的调用,再创建包含所有调用输出的后续请求。
在 WebSocket 模式下,当智能体调用开发者自定义函数时,请在您的应用中执行该函数,并通过 response.inject 事件将结果发送给当前响应。正在等待的智能体随后即可恢复执行,无需等待整个多智能体响应结束。
1234567891011{
"type": "response.inject",
"response_id": "resp_123",
"input": [
{
"type": "function_call_output",
"call_id": "call_123",
"output": "{\"temperature\":72}"
}
]
}
对于有效的 response.inject 请求,服务器会返回以下两种事件之一:
response.inject.created:输入已通过验证,服务器已接受该输入以进行注入。
response.inject.failed:输入未能注入。请检查 error.code。
12345{
"type": "response.inject.created",
"sequence_number": 42,
"response_id": "resp_123"
}
12345678910111213141516{
"type": "response.inject.failed",
"sequence_number": 43,
"response_id": "resp_123",
"input": [
{
"type": "function_call_output",
"call_id": "call_123",
"output": "{\"temperature\":72}"
}
],
"error": {
"code": "response_already_completed",
"message": "Response 'resp_123' has already completed."
}
}
如果请求不符合 response.inject 模式,服务器会发送状态码为 400 的通用错误,并关闭 WebSocket 连接。请修正请求并建立新的 WebSocket 连接,然后再发送事件。
Python 测试版 SDK 通过 client.beta.responses.connect 提供 WebSocket 模式,TypeScript 测试版 SDK 则通过 ResponsesWS 提供该模式。请在连接头中传入 OpenAI-Beta: responses_multi_agent=v1。与 HTTP 流式请求不同,WebSocket 连接器尚不接受 betas 参数。
请保存 response.created 事件中的响应 ID,并在针对该响应发送的每个 response.inject 事件中包含此 ID。发送注入项后,请继续从 WebSocket 读取事件,直到响应结束,且每次注入都已产生 response.inject.created 或 response.inject.failed 事件。
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148import OpenAI from "openai";
import { ResponsesWS } from "openai/resources/beta/responses/ws";
const client = new OpenAI();
const proposals = {
alpha: { estimated_weeks: 6, risk: "medium" },
beta: { estimated_weeks: 8, risk: "low" },
};
const tools: OpenAI.Beta.Responses.BetaTool[] = [
{
type: "function",
name: "get_proposal",
description:
"Return details for a proposal that the agents should compare.",
parameters: {
type: "object",
properties: {
proposal: {
type: "string",
enum: ["alpha", "beta"],
},
},
required: ["proposal"],
additionalProperties: false,
},
strict: true,
},
];
function processToolCall(name: string, argumentsJson: string) {
if (name !== "get_proposal") {
throw new Error(`Unknown tool: ${name}`);
}
const { proposal }: { proposal: unknown } = JSON.parse(argumentsJson);
if (proposal !== "alpha" && proposal !== "beta")
throw new Error(`Unknown proposal: ${proposal}`);
return JSON.stringify(proposals[proposal]);
}
async function runMultiAgent(ws: ResponsesWS) {
let previousResponseId;
let pendingInput: OpenAI.Beta.Responses.BetaResponseInput = [
{ role: "user", content: process.argv.slice(2).join(" ") },
];
while (pendingInput.length > 0) {
ws.send({
type: "response.create",
model: "gpt-6.2-sol",
store: true,
multi_agent: {
enabled: true,
max_concurrent_subagents: 3,
},
tools,
input: pendingInput,
previous_response_id: previousResponseId,
});
const nextInput = [];
let completedResponse;
let responseId;
let pendingInjections = 0;
for await (const message of ws) {
if (message.type === "error") throw message.error;
if (message.type !== "message") continue;
const event = message.message;
if (event.type === "response.created") {
responseId = event.response.id;
} else if (
event.type === "response.output_item.done" &&
event.item.type === "function_call"
) {
if (!responseId) {
throw new Error("Received a function call before response.created");
}
pendingInjections += 1;
ws.send({
type: "response.inject",
response_id: responseId,
input: [
{
type: "function_call_output",
call_id: event.item.call_id,
output: processToolCall(event.item.name, event.item.arguments),
},
],
});
} else if (event.type === "response.inject.created") {
pendingInjections -= 1;
} else if (event.type === "response.inject.failed") {
pendingInjections -= 1;
if (event.error.code !== "response_already_completed") {
throw new Error(JSON.stringify(event.error));
}
nextInput.push(...event.input);
} else if (event.type === "response.completed") {
completedResponse = event.response;
} else if (
event.type === "error" ||
event.type === "response.failed" ||
event.type === "response.incomplete"
) {
throw new Error(JSON.stringify(event));
}
if (completedResponse && pendingInjections === 0) break;
}
if (!completedResponse) {
throw new Error("Connection ended before response.completed");
}
if (pendingInjections !== 0) {
throw new Error("Connection ended with unacknowledged tool results");
}
if (nextInput.length === 0) return completedResponse;
previousResponseId = completedResponse.id;
pendingInput = nextInput;
}
throw new Error("The response ended without a result.");
}
const ws = new ResponsesWS(client, {
headers: { "OpenAI-Beta": "responses_multi_agent=v1" },
});
try {
const response = await runMultiAgent(ws);
const text = response.output
.flatMap((item) =>
item.type === "message" &&
item.agent?.agent_name === "/root" &&
item.phase === "final_answer"
? item.content
: []
)
.filter((part) => part.type === "output_text")
.map((part) => part.text)
.join("");
console.log(text);
} finally {
ws.close();
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146from __future__ import annotations
import json
from openai import OpenAI
client = OpenAI()
PROPOSALS = {
"alpha": {"estimated_weeks": 6, "risk": "medium"},
"beta": {"estimated_weeks": 8, "risk": "low"},
}
tools = [
{
"type": "function",
"name": "get_proposal",
"description": "Return details for a proposal that the agents should compare.",
"parameters": {
"type": "object",
"properties": {
"proposal": {
"type": "string",
"enum": ["alpha", "beta"],
}
},
"required": ["proposal"],
"additionalProperties": False,
},
"strict": True,
}
]
def process_tool_call(name: str, arguments: str) -> str:
if name != "get_proposal":
raise ValueError(f"Unknown tool: {name}")
parsed_arguments = json.loads(arguments)
return json.dumps(PROPOSALS[parsed_arguments["proposal"]])
def run_multi_agent(connection):
previous_response_id: str | None = None
pending_input: list[dict[str, object]] = [{"role": "user", "content": input()}]
while pending_input:
request = {
"type": "response.create",
"model": "gpt-6.2-sol",
"store": True,
"multi_agent": {"enabled": True},
"tools": tools,
"input": pending_input,
}
if previous_response_id is not None:
request["previous_response_id"] = previous_response_id
connection.send(request)
next_input: list[dict[str, object]] = []
completed_response = None
response_id: str | None = None
pending_injections = 0
for event in connection:
event_type = event.type
if event_type == "response.created":
response_id = event.response.id
elif event_type == "response.output_item.done":
item = event.item
if item.type == "function_call":
if response_id is None:
raise RuntimeError(
"Received a function call before response.created"
)
output = {
"type": "function_call_output",
"call_id": item.call_id,
"output": process_tool_call(item.name, item.arguments),
}
pending_injections += 1
connection.send(
{
"type": "response.inject",
"response_id": response_id,
"input": [output],
}
)
elif event_type == "response.inject.created":
pending_injections -= 1
elif event_type == "response.inject.failed":
pending_injections -= 1
if event.error.code != "response_already_completed":
raise RuntimeError(event.error)
next_input.extend(item.model_dump(mode="json") for item in event.input)
elif event_type == "response.completed":
completed_response = event.response
elif event_type in {
"error",
"response.failed",
"response.incomplete",
}:
raise RuntimeError(event)
if completed_response is not None and pending_injections == 0:
break
if completed_response is None:
raise RuntimeError("Connection ended before response.completed")
if pending_injections:
raise RuntimeError("Connection ended with unacknowledged tool results")
if not next_input:
return completed_response
previous_response_id = completed_response.id
pending_input = next_input
with client.beta.responses.connect(
extra_headers={"OpenAI-Beta": "responses_multi_agent=v1"},
) as connection:
response = run_multi_agent(connection)
print(
"".join(
part.text
for item in response.output
if (
item.type == "message"
and item.agent is not None
and item.agent.agent_name == "/root"
and item.phase == "final_answer"
)
for part in item.content
if part.type == "output_text"
)
)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
)
func toolOutput(call openai.BetaResponseFunctionToolCall) (openai.BetaResponseInputItemUnionParam, error) {
var zero openai.BetaResponseInputItemUnionParam
if call.Name != "get_proposal" {
return zero, fmt.Errorf("unknown tool: %s", call.Name)
}
var args struct {
Proposal string `json:"proposal"`
}
if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil {
return zero, err
}
proposals := map[string]any{"alpha": map[string]any{"estimated_weeks": 6, "risk": "medium"}, "beta": map[string]any{"estimated_weeks": 8, "risk": "low"}}
value, ok := proposals[args.Proposal]
if !ok {
return zero, fmt.Errorf("unknown proposal: %s", args.Proposal)
}
output, err := json.Marshal(value)
if err != nil {
return zero, err
}
return openai.BetaResponseInputItemUnionParam{OfFunctionCallOutput: &openai.BetaResponseInputItemFunctionCallOutputParam{CallID: openai.String(call.CallID), Output: openai.BetaResponseInputItemFunctionCallOutputOutputUnionParam{OfString: openai.String(string(output))}}}, nil
}
func runMultiAgent(ctx context.Context, connection *openai.BetaResponseConnection, prompt string) (*openai.BetaResponse, error) {
tools := []openai.BetaToolUnionParam{{OfFunction: &openai.BetaFunctionToolParam{Name: "get_proposal", Description: openai.String("Return details for a proposal that the agents should compare."), Strict: openai.Bool(true), Parameters: map[string]any{"type": "object", "properties": map[string]any{"proposal": map[string]any{"type": "string", "enum": []string{"alpha", "beta"}}}, "required": []string{"proposal"}, "additionalProperties": false}}}}
input := openai.BetaResponseInputParam{{OfMessage: &openai.BetaEasyInputMessageParam{Role: "user", Content: openai.BetaEasyInputMessageContentUnionParam{OfString: openai.String(prompt)}}}}
previous := ""
for len(input) > 0 {
request := openai.BetaResponsesClientEventResponseCreateParam{Model: "gpt-6.2-sol", Store: openai.Bool(true), MultiAgent: openai.BetaResponsesClientEventResponseCreateMultiAgentParam{Enabled: true}, Tools: tools, Input: openai.BetaResponsesClientEventResponseCreateInputUnionParam{OfResponse: &input}}
if previous != "" {
request.PreviousResponseID = openai.String(previous)
}
if err := connection.Send(ctx, openai.BetaResponsesClientEventUnionParam{OfResponseCreate: &request}); err != nil {
return nil, err
}
responseID := ""
pending := 0
var completed *openai.BetaResponse
var retry []openai.BetaResponseInputItemUnionParam
for completed == nil || pending != 0 {
event, err := connection.Recv(ctx)
if err != nil {
return nil, fmt.Errorf("connection ended before completion and injection acknowledgements: %w", err)
}
switch event.Type {
case "response.created":
responseID = event.AsResponseCreated().Response.ID
case "response.output_item.done":
item := event.AsResponseOutputItemDone().Item
if item.Type != "function_call" {
continue
}
if responseID == "" {
return nil, fmt.Errorf("function call arrived before response creation")
}
output, err := toolOutput(item.AsFunctionCall())
if err != nil {
return nil, err
}
pending++
if err := connection.Send(ctx, openai.BetaResponsesClientEventUnionParam{OfResponseInject: &openai.BetaResponseInjectEventParam{ResponseID: responseID, Input: []openai.BetaResponseInputItemUnionParam{output}}}); err != nil {
return nil, err
}
case "response.inject.created":
ack := event.AsBetaResponseInjectCreatedEvent()
if responseID == "" || ack.ResponseID != responseID || pending == 0 {
return nil, fmt.Errorf("unexpected injection acknowledgement")
}
pending--
case "response.inject.failed":
ack := event.AsBetaResponseInjectFailedEvent()
if responseID == "" || ack.ResponseID != responseID || pending == 0 {
return nil, fmt.Errorf("unexpected injection acknowledgement")
}
pending--
if ack.Error.Code != "response_already_completed" {
return nil, fmt.Errorf("injection failed: %s", ack.Error.Code)
}
for _, item := range ack.Input {
var value openai.BetaResponseInputItemUnionParam
if err := json.Unmarshal([]byte(item.RawJSON()), &value); err != nil {
return nil, err
}
retry = append(retry, value)
}
case "response.completed":
response := event.AsResponseCompleted().Response
if responseID == "" || response.ID != responseID {
return nil, fmt.Errorf("unexpected response completion")
}
completed = &response
case "error", "response.failed", "response.incomplete":
return nil, fmt.Errorf("multi-agent response failed: %s", event.RawJSON())
}
}
if len(retry) == 0 {
return completed, nil
}
previous = completed.ID
input = retry
}
return nil, fmt.Errorf("no response was created")
}
func run(ctx context.Context) error {
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return err
}
return fmt.Errorf("expected a prompt on stdin")
}
client := openai.NewClient()
connection, err := client.Beta.Responses.Connect(ctx, openai.BetaResponseConnectionOptions{}, option.WithQuery("beta", "true"), option.WithHeader("OpenAI-Beta", "responses_multi_agent=v1"))
if err != nil {
return err
}
defer connection.Close()
response, err := runMultiAgent(ctx, connection, scanner.Text())
if err != nil {
return err
}
var text strings.Builder
for _, item := range response.Output {
if item.Type != "message" || item.Agent.AgentName != "/root" || item.Phase != "final_answer" {
continue
}
for _, part := range item.AsMessage().Content {
if part.Type == "output_text" {
text.WriteString(part.Text)
}
}
}
fmt.Println(text.String())
return nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
if err := run(ctx); err != nil {
log.Fatal(err)
}
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141require "async"
require "async/http/endpoint"
require "async/websocket/client"
require "json"
PROPOSALS = {
"alpha" => {
estimated_weeks: 6,
risk: "medium"
},
"beta" => {
estimated_weeks: 8,
risk: "low"
}
}.freeze
def process_tool_call(name, arguments)
raise "Unknown tool: #{name}" unless name == "get_proposal"
JSON.generate(PROPOSALS.fetch(JSON.parse(arguments).fetch("proposal")))
end
def run_multi_agent(connection, tools)
state = {
previous: nil,
input: [
{
role: "user",
content: $stdin.readline.chomp
}
]
}
until state[:input].empty?
request = {
type: "response.create",
model: "gpt-6.2-sol",
store: true,
multi_agent: { enabled: true },
tools: tools,
input: state[:input]
}
request[:previous_response_id] = state[:previous] if state[:previous]
connection.write(JSON.generate(request))
connection.flush
round = {
response_id: nil,
completed: nil,
pending: 0,
retry: []
}
while (message = connection.read)
event = JSON.parse(message.to_str)
case event.fetch("type")
when "response.created"
round[:response_id] = event.fetch("response").fetch("id")
when "response.output_item.done"
item = event.fetch("item")
if item["type"] == "function_call"
raise "Function call arrived before response creation" unless round[:response_id]
output = {
type: "function_call_output",
call_id: item.fetch("call_id"),
output: process_tool_call(item.fetch("name"), item.fetch("arguments"))
}
round[:pending] += 1
connection.write(JSON.generate(type: "response.inject", response_id: round[:response_id], input: [output]))
connection.flush
end
when "response.inject.created", "response.inject.failed"
unless event.fetch("response_id") == round[:response_id] && round[:pending].positive?
raise "Unexpected injection acknowledgement"
end
round[:pending] -= 1
if event["type"] == "response.inject.failed"
raise "Injection failed: #{event.fetch("error")}" unless event.fetch("error").fetch("code") == "response_already_completed"
round[:retry].concat(event.fetch("input"))
end
when "response.completed"
round[:completed] = event.fetch("response")
when "error", "response.failed", "response.incomplete"
raise "Multi-agent response failed: #{event}"
end
break if round[:completed] && round[:pending].zero?
end
raise "Connection closed before response completion" unless round[:completed]
raise "Connection closed with unacknowledged results" unless round[:pending].zero?
return round[:completed] if round[:retry].empty?
state[:previous] = round[:completed].fetch("id")
state[:input] = round[:retry]
end
raise "No response was created"
end
tools = [
{
type: "function",
name: "get_proposal",
description: "Return details for a proposal that the agents should compare.",
parameters: {
type: "object",
properties: {
proposal: {
type: "string",
enum: ["alpha", "beta"]
}
},
required: ["proposal"],
additionalProperties: false
},
strict: true
}
]
base = ENV.fetch("OPENAI_BASE_URL", "https://api.openai.com/v1").sub(%r{/+\z}, "")
endpoint = Async::HTTP::Endpoint.parse("#{base.sub(/\Ahttp/, "ws")}/responses?beta=true", timeout: 30, alpn_protocols: ["http/1.1"])
headers = {
"Authorization" => "Bearer #{ENV.fetch("OPENAI_API_KEY")}",
"OpenAI-Beta" => "responses_multi_agent=v1"
}
Sync do |task|
task.with_timeout(240) do
Async::WebSocket::Client.connect(endpoint, headers: headers) do |connection|
response = run_multi_agent(connection, tools)
text = response.fetch("output").select do |item|
item["type"] == "message" && item.dig("agent", "agent_name") == "/root" && item["phase"] == "final_answer"
end.flat_map { |item| item.fetch("content") }.select { |part| part["type"] == "output_text" }.map { |part| part.fetch("text") }.join
puts text
end
end
end
发送 response.inject 事件后,请继续从 WebSocket 读取事件,并根据服务器返回的结果进行处理:
response.inject.created:函数输出已添加到当前响应。请继续读取该响应的事件。
response.inject.failed 且错误码为 response_already_completed:函数输出尚未添加,响应就已结束。请取出失败事件返回的 input,在新的 response.create 请求中发送,以便从已完成的响应继续执行。
response.inject.failed 且错误码为 response_not_found:服务器找不到 response_id 指定的响应。请确认您使用的是从 response.created 事件收到的 ID。
一次多智能体运行可能跨越多个 Responses API 请求。通过 HTTP 处理智能体发起的开发者自定义函数调用时,您的应用会执行该函数,并通过新的 response.create 调用提交输出。使用 WebSocket 时,您的应用会将函数输出直接注入当前响应。
多智能体响应可以包含三种额外的输出项类型:
multi_agent_call:记录托管的多智能体操作,例如 spawn_agent。
multi_agent_call_output:包含托管操作的执行结果。
agent_message:承载从一个智能体发给另一个智能体的加密消息。
call_id 字段将每个 multi_agent_call 与对应的 multi_agent_call_output 关联起来。
每个输出项还包含 agent 属性。对于 agent_message,agent.agent_name 标识接收消息的智能体。您可以通过 author 和 recipient 追踪消息的发送方向。
当您的应用收到 multi_agent_call 时,请勿将其作为函数调用执行,也不要回传结果。Responses API 会执行该托管操作并返回相应的 multi_agent_call_output。如果您的应用需要回放或追踪,请保留这两个输出项。
1234567891011121314151617181920212223242526272829303132333435363738[
{
"type": "multi_agent_call",
"id": "mac_123",
"call_id": "call_spawn_a",
"action": "spawn_agent",
"arguments": "{\"task_name\":\"agent_a\",\"fork_turns\":\"all\",\"message\":\"enc_...\"}",
"agent": { "agent_name": "/root" }
},
{
"type": "multi_agent_call_output",
"id": "maco_123",
"call_id": "call_spawn_a",
"action": "spawn_agent",
"output": [
{
"type": "output_text",
"text": "{\"task_name\":\"/root/agent_a\"}",
"annotations": [],
"logprobs": []
}
],
"agent": { "agent_name": "/root" }
},
{
"type": "agent_message",
"id": "amsg_123",
"author": "/root/agent_a",
"recipient": "/root",
"content": [
{
"type": "encrypted_content",
"encrypted_content": "enc_..."
}
],
"agent": { "agent_name": "/root" }
}
]
归属于特定智能体的 SSE 事件包含顶层 agent 属性。对于 agent_message 事件,agent.agent_name 标识接收消息的智能体。response.created 和 response.completed 等响应生命周期事件描述的是整个响应,因此不包含用于标识单个智能体的 agent 属性。
1234567891011121314151617{
"type": "response.output_item.done",
"agent": { "agent_name": "/root" },
"item": {
"type": "agent_message",
"id": "amsg_123",
"author": "/root/agent_a",
"recipient": "/root",
"content": [
{
"type": "encrypted_content",
"encrypted_content": "enc_..."
}
],
"agent": { "agent_name": "/root" }
}
}
- 压缩:
- 启用多智能体功能时,不支持
/responses/compact 端点。
- 当
multi_agent.enabled 设为 true 时,即使请求中未配置 context_management,服务端也会启用自动压缩。根智能体和每个子智能体的上下文会分别压缩,以保持彼此独立。您仍可覆盖 compact_threshold,只需在请求中显式设置 context_management.compact_threshold。
- 启用多智能体功能时,不支持
reasoning.summary。
- 启用多智能体功能时,不支持
max_tool_calls。
max_concurrent_subagents 的默认值为 3,建议使用此设置。
启用多智能体功能后,系统会以新开发者消息的形式,自动为根智能体和子智能体追加以下指令。您无法编辑或移除这些指令。编写自己的开发者指令时,请将其作为对这些自动注入指令的补充。
您是 `/root`,负责带领团队中的智能体共同实现用户的目标。
在您的回合开始时,您处于活动状态。
您可以创建子智能体来处理子任务,这些子智能体也可以创建自己的子智能体。
团队中的所有智能体,包括您可以分配任务的智能体,都具有同等的智能和能力,也都可以使用同一组工具。
您可以使用 `spawn_agent` 创建新的智能体,使用 `followup_task` 为现有智能体分配新任务并触发一个回合,也可以使用 `send_message` 向正在运行的智能体发送消息,而不触发新回合。
子智能体也可以创建自己的子智能体。
您可以通过 `fork_turns` 参数决定向子智能体传递多少上下文。
您收到的消息格式如下:
```
Message Type: MESSAGE | FINAL_ANSWER
Task name: <recipient>
Sender: <author>
Payload:
<payload text>
```
这些消息的收件方可能标记为 to=/root。
共有 {max_concurrent_subagents + 1} 个可用的并发名额。包括您在内,同时处于活动状态的智能体最多有 {max_concurrent_subagents + 1} 个。
您是团队中的一个智能体,负责与其他智能体协作完成任务。
您可以创建子智能体来处理子任务,这些子智能体也可以创建自己的子智能体。团队中的所有智能体,包括您可以分配任务的智能体,都具有同等的智能和能力,也都可以使用同一组工具。
您可以使用 `spawn_agent` 创建新的智能体,使用 `followup_task` 为现有智能体分配新任务并触发一个回合,也可以使用 `send_message` 向正在运行的智能体发送消息。
子智能体也可以创建自己的子智能体。
当您在 final 通道中给出响应时,响应内容会立即发回给您的父智能体。
您收到的消息格式如下:
```
Message Type: NEW_TASK | MESSAGE | FINAL_ANSWER
Task name: <recipient>
Sender: <author>
Payload:
<payload text>
```
您也可能看到消息的收件方标记为 to=/root/...,这表示您的标识是 /root/...
共有 {max_concurrent_subagents + 1} 个可用的并发名额。包括您在内,同时处于活动状态的智能体最多有 {max_concurrent_subagents + 1} 个。