如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

多智能体

让模型在一次 Responses API 请求中创建子智能体,并行处理各自的任务。

概述

多智能体功能让模型可以创建多个子智能体,协调它们并行工作,并汇总各自的结果,给出最终响应。如果应用需要处理适合并行分工的复杂任务,例如探索代码库、编写文档和实现功能,这一功能尤其有效。

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 时,根智能体可以创建一棵由子智能体组成的树。各子智能体使用请求中指定的同一模型和同一组可用工具。智能体之间通过创建子智能体、发送消息和等待等基本操作进行协作(请参阅多智能体的工作原理)。根智能体负责汇总各子智能体的响应,并给出最终响应。

使用子智能体审查 pull request
from 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"
    )

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 请求的模型调用中配置的工具。

在 Responses API 中使用多智能体

HTTP 与 WebSocket 的性能比较

HTTP 和 WebSocket 支持相同的多智能体功能。对于频繁使用工具或运行时间较长的工作流,建议使用 WebSocket。通过持久连接,您的应用可以在每个函数输出就绪后立即返回结果,从而降低继续执行的开销,缩短智能体的等待时间。

使用 HTTP 时,每个活动智能体都必须完成工作,或暂停以等待客户端执行函数调用,当前响应才会结束。随后,您的应用执行所有待处理的函数调用,并在新的 Responses API 请求中提交输出,使暂停的智能体恢复执行。

使用 WebSocket 时,您的应用可以在每个函数输出就绪后立即将其注入当前响应,无需等待响应结束。正在等待的智能体可以立即恢复执行,其他智能体则继续工作。当各智能体在不同时间完成工作或请求使用工具时,这种方式可以缩短协调延迟,避免额外的请求往返。

对于需要调用多个托管工具的工作流(例如并行进行网页搜索),或者只需一次请求且函数调用较少的工作流,HTTP 可能就足够了。对于大多数多智能体工作流,WebSocket 更有可能降低延迟并提高端到端性能。

通过 HTTP 执行函数调用

应用、Responses API 根智能体和三个子智能体通过 HTTP 执行函数调用的流程。

通过 WebSocket 执行函数调用

应用、Responses API 根智能体和三个子智能体通过 WebSocket 执行函数调用的流程。

HTTP

这些示例需要使用支持测试版 Responses API 的测试版 SDK。对于 HTTP 流式请求,请调用 client.beta.responses.create,并将 responses_multi_agent=v1 传给 betas 参数,以启用测试版类型和自动补全。在 Python 中添加类型注解时,请从 openai.types.beta 导入测试版响应项类型。

客户端代码示例:

处理 HTTP 流中的工具调用
from __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

如果一个或多个智能体调用了开发者自定义函数,请执行每个待处理的调用,再创建包含所有调用输出的后续请求。

WebSocket

在 WebSocket 模式下,当智能体调用开发者自定义函数时,请在您的应用中执行该函数,并通过 response.inject 事件将结果发送给当前响应。正在等待的智能体随后即可恢复执行,无需等待整个多智能体响应结束。

{
  "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。
{
  "type": "response.inject.created",
  "sequence_number": 42,
  "response_id": "resp_123"
}
{
  "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 事件。

通过 WebSocket 注入工具输出
from __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"
        )
    )

发送 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。如果您的应用需要回放或追踪,请保留这两个输出项。

[
  {
    "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 属性。

{
  "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" }
  }
}

限制

  1. 压缩:
    1. 启用多智能体功能时,不支持 /responses/compact 端点。
    2. 当 multi_agent.enabled 设为 true 时,即使请求中未配置 context_management,服务端也会启用自动压缩。根智能体和每个子智能体的上下文会分别压缩,以保持彼此独立。您仍可覆盖 compact_threshold,只需在请求中显式设置 context_management.compact_threshold。
  2. 启用多智能体功能时,不支持 reasoning.summary。
  3. 启用多智能体功能时,不支持 max_tool_calls。
  4. 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} 个。

相关指南