OpenAI 多智能体

2026-11-06 14:59 更新

多智能体允许主智能体把任务委派给子智能体。每个子智能体有独立上下文,可并行工作;主智能体协调并合并结果。

何时使用子智能体

适合相互独立的任务,例如分别审查文档或调查故障的不同原因。为各任务指定明确问题和预期结果。

短任务及有依赖的步骤留在主智能体。同改一个文件的智能体必须协调变更。

启用多智能体编排

创建会话时设 agent.multi_agent.enabled: true。框架自动提供创建、发送消息、等待、打断子智能体的工具,不需要自行声明。

以下用户输入明确要求两个子智能体,各自审查一组发行说明,再由主智能体合并;无需环境或已配置工具:

来源示例 1(javascript):

程序文字说明8:将各版本分别交给一个子智能体,仅依据各自发行说明,提取用户可见变化及必需迁移步骤;等两份结果后合并为带版本标签的摘要,不编造缺失细节。

程序文字说明9:此拼接指令要求按版本分别委派、提取用户可见变化与迁移步骤,再合并结果,不编造信息。

程序文字说明31:使用两个子智能体,每个负责一个版本,再合并为带标签摘要。A版:搜索新增按日期筛选,已有查询继续可用。B版:导出端点由返回文件字节改为下载URL,客户端需再获取该URL。

程序文字说明32:此拼接输入提供A/B版发行说明,要求分别委派并合并摘要:A新增日期筛选且兼容旧查询,B改为返回下载URL,客户端需取回文件。

// [中文] 示例 1:启用多智能体编排。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
import OpenAI from "openai";

const client = new OpenAI();

const events = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "Delegate each release to a separate subagent. Ask each to extract customer-visible changes and required migration steps using only its release notes. Wait for both results, then combine them into one release summary with release labels. Do not invent missing details.",
    multi_agent: { enabled: true, max_concurrent_subagents: 2 },
  },
  environment: { type: "none" },
  input:
    "Use two subagents, one for each release, and combine their findings into a labeled summary. Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",
  stream: true,
});
events.withResultCollection();
try {
  for await (const event of events) {
    console.log(JSON.stringify(event));
  }
  console.log((await events.finalResult()).output_text);
} finally {
  events.controller.abort();
}

来源示例 2(python):

沿用程序文字说明8。

沿用程序文字说明9。

沿用程序文字说明31。

沿用程序文字说明32。

## [中文] 示例 2:启用多智能体编排。
## [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
from openai import OpenAI

client = OpenAI()

with client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": "Delegate each release to a separate subagent. Ask each to extract customer-visible changes and required migration steps using only its release notes. Wait for both results, then combine them into one release summary with release labels. Do not invent missing details.",
        "multi_agent": {"enabled": True, "max_concurrent_subagents": 2},
    },
    environment={"type": "none"},
    input="Use two subagents, one for each release, and combine their findings into a labeled summary. Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",
    stream=True,
).with_result_collection() as stream:
    for event in stream:
        print(event.model_dump_json())
    result = stream.get_final_result()
print(result.output_text)

来源示例 3(go):

沿用程序文字说明8。

沿用程序文字说明9。

沿用程序文字说明31。

沿用程序文字说明32。

// [中文] 示例 3:启用多智能体编排。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
import (
    "context"
    "fmt"
    "github.com/openai/openai-go/v3"
)

ctx := context.Background()
client := openai.NewClient()
events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra"),
    Instructions: openai.String("Delegate each release to a separate subagent. Ask each to extract customer-visible changes and required migration steps using only its release notes. Wait for both results, then combine them into one release summary with release labels. Do not invent missing details."),
    MultiAgent: openai.MultiAgentConfigParam{Enabled: true,
        MaxConcurrentSubagents: openai.Int(2)}},
    Environment: openai.EnvironmentParamUnion{OfParamNone: &openai.EnvironmentParamNone{}},
    Input:       openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Use two subagents, one for each release, and combine their findings into a labeled summary. Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.")}})
defer events.Close()
openai.BetaAgentSessionWithResultCollection(events)
for events.Next() {
    fmt.Println(events.Current().RawJSON())
}
result, err := openai.BetaAgentSessionFinalResult(events)
if err != nil {
    panic(err)
}
fmt.Println(result.OutputText())

来源示例 4(java):

沿用程序文字说明9。

沿用程序文字说明32。

// [中文] 示例 4:启用多智能体编排。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.MultiAgentConfigParam;
import com.openai.models.beta.agents.sessions.SessionCreateParams;
import com.openai.services.beta.agents.AgentTurnResults;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
try (var events =
    client
        .beta()
        .agents()
        .sessions()
        .createStreaming(
            SessionCreateParams.builder()
                .agent(
                    SessionCreateParams.Agent.builder()
                        .model("gpt-6-astra")
                        .instructions(
                            "Delegate each release to a separate subagent. Ask each to extract"
                                + " customer-visible changes and required migration steps using"
                                + " only its release notes. Wait for both results, then combine"
                                + " them into one release summary with release labels. Do not"
                                + " invent missing details.")
                        .multiAgent(
                            MultiAgentConfigParam.builder()
                                .enabled(true)
                                .maxConcurrentSubagents(2L)
                                .build())
                        .build())
                .environmentNone()
                .input(
                    "Use two subagents, one for each release, and combine their findings into"
                        + " a labeled summary. Release A: Search now supports filtering by date."
                        + " Existing queries"
                        + " continue to work. Release B: The export endpoint now returns a"
                        + " download URL instead of file bytes. Update clients to fetch that"
                        + " URL.")
                .build())) {
  AgentTurnResults.withResultCollection(events);
  events.stream().forEach(System.out::println);
  System.out.println(AgentTurnResults.getFinalResult(events).outputText());
}

来源示例 5(ruby):

沿用程序文字说明8。

沿用程序文字说明9。

沿用程序文字说明31。

沿用程序文字说明32。

## [中文] 示例 5:启用多智能体编排。
## [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
require "openai"
require "json"

client = OpenAI::Client.new

events = client.beta.agents.sessions.create_streaming(
  agent: {
    model: "gpt-6-astra",
    instructions: "Delegate each release to a separate subagent. Ask each to extract customer-visible changes and required migration steps using only its release notes. Wait for both results, then combine them into one release summary with release labels. Do not invent missing details.",
    multi_agent: {
      enabled: true,
      max_concurrent_subagents: 2
    }
  },
  environment: { type: "none" },
  input: "Use two subagents, one for each release, and combine their findings into a labeled summary. Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL."
)
begin
  events.with_result_collection
  events.each { |event| puts JSON.generate(event.to_h) }
  result = events.get_final_result
  puts result.output_text
ensure
  events.close
end

来源示例 6(bash):

沿用程序文字说明8。

沿用程序文字说明9。

沿用程序文字说明31。

沿用程序文字说明32。

## [中文] 示例 6:启用多智能体编排。
## [中文] 本段涉及的请求或服务地址:https://api.openai.com/v1/agents/sessions;示例占位地址需替换为实际资源。
curl --no-buffer --fail-with-body 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": "Delegate each release to a separate subagent. Ask each to extract customer-visible changes and required migration steps using only its release notes. Wait for both results, then combine them into one release summary with release labels. Do not invent missing details.",
      "multi_agent": { "enabled": true, "max_concurrent_subagents": 2 }
    },
    "environment": { "type": "none" },
    "input": "Use two subagents, one for each release, and combine their findings into a labeled summary. Release A: Search now supports filtering by date. Existing queries continue to work. Release B: The export endpoint now returns a download URL instead of file bytes. Update clients to fetch that URL.",
    "stream": true
  }'

environment.type: "none" 时,将初始 input 放在创建请求中;stream: true 同时流式返回首轮。流处理与恢复见会话事件及项目。

并发设置

max_concurrent_subagents 限制同时运行的子智能体数量,默认 6,不含协调者。启用委派时可设为正整数。

禁用时省略 multi_agent,或设 enabled: false 并省略数量上限。设置在创建会话时生效,修改已保存智能体只影响新会话。

使用环境

需要文件或命令执行时添加环境。协调者和子智能体共享其文件系统;创建子智能体不会另建环境。

以下示例为自己的环境创建会话:

来源示例 7(javascript):

程序文字说明10:从仓库准备发行说明:一个子智能体找用户可见变化,另一个检查迁移指南和示例,再合并发现。

程序文字说明11:此拼接指令要求两个子智能体分别调查仓库变化及迁移指南和示例,再合并结果。

// [中文] 示例 7:使用环境。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
const result = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings.",
    multi_agent: {
      enabled: true,
      max_concurrent_subagents: 3,
    },
  },
  environment: {
    type: "self_hosted",
    workspace_directory: "/workspace",
  },
});

来源示例 8(python):

沿用程序文字说明10。

沿用程序文字说明11。

## [中文] 示例 8:使用环境。
## [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
result = client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": "Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings.",
        "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},
    },
    environment={"type": "self_hosted", "workspace_directory": "/workspace"},
)

来源示例 9(go):

沿用程序文字说明10。

沿用程序文字说明11。

// [中文] 示例 9:使用环境。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
result, err := client.Beta.Agents.Sessions.New(ctx,
    openai.BetaAgentSessionNewParams{
        Agent: openai.BetaAgentSessionNewParamsAgent{
            Model:        openai.String("gpt-6-astra"),
            Instructions: openai.String("Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings."),
            MultiAgent: openai.MultiAgentConfigParam{
                Enabled:                true,
                MaxConcurrentSubagents: openai.Int(3),
            },
        },
        Environment: openai.EnvironmentParamUnion{
            OfParamSelfHosted: &openai.EnvironmentParamSelfHosted{WorkspaceDirectory: "/workspace"},
        },
    })
if err != nil {
    panic(err)
}

来源示例 10(java):

沿用程序文字说明11。

// [中文] 示例 10:使用环境。
// [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
var result =
    client
        .beta()
        .agents()
        .sessions()
        .create(
            SessionCreateParams.builder()
                .agent(
                    SessionCreateParams.Agent.builder()
                        .model("gpt-6-astra")
                        .instructions(
                            "Prepare release notes from the repository. Have one subagent"
                                + " identify customer-visible changes and another check"
                                + " migration guides and examples, then combine their"
                                + " findings.")
                        .multiAgent(
                            MultiAgentConfigParam.builder()
                                .enabled(true)
                                .maxConcurrentSubagents(3L)
                                .build())
                        .build())
                .environment(
                    EnvironmentParam.SelfHosted.builder()
                        .workspaceDirectory("/workspace")
                        .build())
                .build());

来源示例 11(ruby):

沿用程序文字说明10。

沿用程序文字说明11。

## [中文] 示例 11:使用环境。
## [中文] 创建会话,保存返回会话 ID;设置 stream 时继续读取事件,创建请求本身不保证任务成功。
result = client.beta.agents.sessions.create(
  agent: {
    model: "gpt-6-astra",
    instructions: "Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings.",
    multi_agent: {
      enabled: true,
      max_concurrent_subagents: 3
    }
  },
  environment: {
    type: "self_hosted",
    workspace_directory: "/workspace"
  }
)

来源示例 12(bash):

沿用程序文字说明10。

沿用程序文字说明11。

## [中文] 示例 12:使用环境。
## [中文] 本段涉及的请求或服务地址:https://api.openai.com/v1/agents/sessions;示例占位地址需替换为实际资源。
curl 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": "Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings.",
      "multi_agent": {
        "enabled": true,
        "max_concurrent_subagents": 3
      }
    },
    "environment": {
      "type": "self_hosted",
      "workspace_directory": "/workspace"
    }
  }'

在应用保存会话及环境ID,连接环境,再发送输入启动任务。

子智能体可用工具

子智能体继承已配置MCP工具、凭证、允许工具和网页搜索设置,也能使用环境文件与命令行工具;不支持函数工具。

观察委派过程

会话事件流报告子智能体活动:

  • agent.session.subagent.created:提供新子智能体ID。
  • agent.session.turn.item.added、agent.session.turn.item.done:报告协调动作,项目类型包括 create_subagent_call、send_subagent_input_call、wait_for_subagents_call、interrupt_subagent_call。

框架执行这些动作。创建或等待动作完成,不等于子智能体任务完成。创建项目的 agent_id 标识发起委派的智能体。

协调项目可能不含消息内容。可用时 agent_message 包含智能体间文字,但事件流不提供完整对话记录。

合并结果读主智能体回复;既往工作及各子智能体历史,用已保存项目与轮次检查。

归属命令执行

给定命令项目和会话ID,读取该命令所属轮次,判断执行者。主智能体轮次的 subagent_id 为 null:

来源示例 13(javascript):

// [中文] 示例 13:归属命令执行。
// [中文] 通过轮次 ID 读取状态及 subagent_id;null 表示主智能体。
// Use the saved session ID and command execution item from your application.
const turn = await client.beta.agents.sessions.turns.retrieve(
  command.turn_id,
  { session_id: sessionId }
);
console.log(turn.subagent_id);

来源示例 14(python):

## [中文] 示例 14:归属命令执行。
## [中文] 通过轮次 ID 读取状态及 subagent_id;null 表示主智能体。
## Use the saved session ID and command execution item from your application.
turn = client.beta.agents.sessions.turns.retrieve(
    command.turn_id, session_id=session_id
)
print(turn.subagent_id)

来源示例 15(go):

// [中文] 示例 15:归属命令执行。
// [中文] 通过轮次 ID 读取状态及 subagent_id;null 表示主智能体。
// Use the saved session ID and command execution item from your application.
turn, err := client.Beta.Agents.Sessions.Turns.Get(ctx, sessionID, item.TurnID)
if err != nil {
    panic(err)
}
fmt.Println(turn.SubagentID)

来源示例 16(java):

// [中文] 示例 16:归属命令执行。
// [中文] 通过轮次 ID 读取状态及 subagent_id;null 表示主智能体。
// Use the saved session ID and command execution item from your application.
var turn =
    client
        .beta()
        .agents()
        .sessions()
        .turns()
        .retrieve(
            TurnRetrieveParams.builder()
                .sessionId(sessionId)
                .turnId(command.turnId())
                .build());
System.out.println(turn.subagentId());

来源示例 17(ruby):

## [中文] 示例 17:归属命令执行。
## [中文] 通过轮次 ID 读取状态及 subagent_id;null 表示主智能体。
## Use the saved session ID and command execution item from your application.
turn = client.beta.agents.sessions.turns.retrieve(item.turn_id, session_id: session_id)
puts turn.subagent_id
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号