SPB Git

Repository Public

multi-agent.md 15.3 KB 385 lines markdown

1# Multi-agent23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Multi-agent lets an agent delegate tasks to subagents. Each subagent has its own context and can work in parallel with the others. The main agent coordinates their work and combines their results.67## When to use subagents89Use subagents for independent tasks, such as reviewing separate documents or investigating different causes of a failure. Give each task a clear question and expected result.1011Keep short tasks and dependent steps in the main agent. Agents that edit the same files must coordinate their changes.1213141516## Enable multi-agent orchestration1718Set `agent.multi_agent.enabled` to `true` when you create a session. The harness supplies tools to create, message, wait for, and interrupt subagents. You do not declare these tools yourself.1920212223This example asks two subagents to review separate release notes, then combines their findings. It needs no environment or configured tools:2425Compare release notes2627```javascript28import OpenAI from "openai";2930const client = new OpenAI();3132const events = await client.beta.agents.sessions.create({33  agent: {34    model: "gpt-6-astra",35    instructions:36      "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.",37    multi_agent: { enabled: true, max_concurrent_subagents: 2 },38  },39  environment: { type: "none" },40  input:41    "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.",42  stream: true,43});44for await (const event of events) {45  console.log(JSON.stringify(event));46}47```4849```python50from openai import OpenAI5152client = OpenAI()5354with client.beta.agents.sessions.create(55    agent={56        "model": "gpt-6-astra",57        "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.",58        "multi_agent": {"enabled": True, "max_concurrent_subagents": 2},59    },60    environment={"type": "none"},61    input="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.",62    stream=True,63) as events:64    for event in events:65        print(event.model_dump_json())66```6768```go69import (70	"context"71	"fmt"72	"github.com/openai/openai-go/v3"73)7475ctx := context.Background()76client := openai.NewClient()77events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra"),78	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."),79	MultiAgent: openai.MultiAgentConfigParam{Enabled: true,80		MaxConcurrentSubagents: openai.Int(2)}},81	Environment: openai.EnvironmentParamUnion{OfParamNone: &openai.EnvironmentParamNone{}},82	Input:       openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("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.")}})83defer events.Close()84for events.Next() {85	fmt.Println(events.Current().RawJSON())86}87if err := events.Err(); err != nil {88	panic(err)89}90```9192```java93import com.openai.client.OpenAIClient;94import com.openai.client.okhttp.OpenAIOkHttpClient;95import com.openai.models.beta.agents.MultiAgentConfigParam;96import com.openai.models.beta.agents.sessions.SessionCreateParams;9798OpenAIClient client = OpenAIOkHttpClient.fromEnv();99try (var events =100    client101        .beta()102        .agents()103        .sessions()104        .createStreaming(105            SessionCreateParams.builder()106                .agent(107                    SessionCreateParams.Agent.builder()108                        .model("gpt-6-astra")109                        .instructions(110                            "Delegate each release to a separate subagent. Ask each to extract"111                                + " customer-visible changes and required migration steps using"112                                + " only its release notes. Wait for both results, then combine"113                                + " them into one release summary with release labels. Do not"114                                + " invent missing details.")115                        .multiAgent(116                            MultiAgentConfigParam.builder()117                                .enabled(true)118                                .maxConcurrentSubagents(2L)119                                .build())120                        .build())121                .environmentNone()122                .input(123                    "Release A: Search now supports filtering by date. Existing queries"124                        + " continue to work. Release B: The export endpoint now returns a"125                        + " download URL instead of file bytes. Update clients to fetch that"126                        + " URL.")127                .build())) {128  events.stream().forEach(System.out::println);129}130```131132```ruby133require "openai"134require "json"135136client = OpenAI::Client.new137138events = client.beta.agents.sessions.create_streaming(139  agent: {140    model: "gpt-6-astra",141    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.",142    multi_agent: {143      enabled: true,144      max_concurrent_subagents: 2145    }146  },147  environment: { type: "none" },148  input: "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."149)150begin151  events.each { |event| puts JSON.generate(event.to_h) }152ensure153  events.close154end155```156157```bash158curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \159  -H "OpenAI-Beta: agents=v1" \160  -H "Authorization: Bearer $OPENAI_API_KEY" \161  -H "Content-Type: application/json" \162  -d '{163    "agent": {164      "model": "gpt-6-astra",165      "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.",166      "multi_agent": { "enabled": true, "max_concurrent_subagents": 2 }167    },168    "environment": { "type": "none" },169    "input": "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.",170    "stream": true171  }'172```173174175With `environment.type: "none"`, include the initial `input` in the create request. Setting `stream: true` also streams the first turn. See [Session events and items](https://developers.openai.com/api/docs/guides/agents-api/sessions/events) for stream handling and recovery.176177### Concurrency settings178179`max_concurrent_subagents` limits how many subagents can run at once. The default is `6`, excluding the coordinator. Set a positive integer when delegation is enabled.180181To disable delegation, omit `multi_agent`, or set `enabled` to `false` and omit the limit. These settings apply at session creation. Changes to a stored agent apply to new sessions.182183## Use an environment184185When agents need files or command execution, [add an environment](https://developers.openai.com/api/docs/guides/agents-api/architecture). The coordinator and subagents share its filesystem. Creating a subagent does not create another environment.186187This example creates a session for work in your own environment:188189Enable delegation with your own environment190191```javascript192const result = await client.beta.agents.sessions.create({193  agent: {194    model: "gpt-6-astra",195    instructions:196      "Prepare release notes from the repository. Have one subagent identify customer-visible changes and another check migration guides and examples, then combine their findings.",197    multi_agent: {198      enabled: true,199      max_concurrent_subagents: 3,200    },201  },202  environment: {203    type: "self_hosted",204    workspace_directory: "/workspace",205  },206});207```208209```python210result = client.beta.agents.sessions.create(211    agent={212        "model": "gpt-6-astra",213        "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.",214        "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},215    },216    environment={"type": "self_hosted", "workspace_directory": "/workspace"},217)218```219220```go221result, err := client.Beta.Agents.Sessions.New(ctx,222	openai.BetaAgentSessionNewParams{223		Agent: openai.BetaAgentSessionNewParamsAgent{224			Model:        openai.String("gpt-6-astra"),225			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."),226			MultiAgent: openai.MultiAgentConfigParam{227				Enabled:                true,228				MaxConcurrentSubagents: openai.Int(3),229			},230		},231		Environment: openai.EnvironmentParamUnion{232			OfParamSelfHosted: &openai.EnvironmentParamSelfHosted{WorkspaceDirectory: "/workspace"},233		},234	})235if err != nil {236	panic(err)237}238```239240```java241var result =242    client243        .beta()244        .agents()245        .sessions()246        .create(247            SessionCreateParams.builder()248                .agent(249                    SessionCreateParams.Agent.builder()250                        .model("gpt-6-astra")251                        .instructions(252                            "Prepare release notes from the repository. Have one subagent"253                                + " identify customer-visible changes and another check"254                                + " migration guides and examples, then combine their"255                                + " findings.")256                        .multiAgent(257                            MultiAgentConfigParam.builder()258                                .enabled(true)259                                .maxConcurrentSubagents(3L)260                                .build())261                        .build())262                .environment(263                    EnvironmentParam.SelfHosted.builder()264                        .workspaceDirectory("/workspace")265                        .build())266                .build());267```268269```ruby270result = client.beta.agents.sessions.create(271  agent: {272    model: "gpt-6-astra",273    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.",274    multi_agent: {275      enabled: true,276      max_concurrent_subagents: 3277    }278  },279  environment: {280    type: "self_hosted",281    workspace_directory: "/workspace"282  }283)284```285286```bash287curl https://api.openai.com/v1/agents/sessions \288  -H "OpenAI-Beta: agents=v1" \289  -H "Authorization: Bearer $OPENAI_API_KEY" \290  -H "Content-Type: application/json" \291  -d '{292    "agent": {293      "model": "gpt-6-astra",294      "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.",295      "multi_agent": {296        "enabled": true,297        "max_concurrent_subagents": 3298      }299    },300    "environment": {301      "type": "self_hosted",302      "workspace_directory": "/workspace"303    }304  }'305```306307308Store the returned session and environment IDs in your application. [Connect the environment](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted), then [send input](https://developers.openai.com/api/docs/guides/agents-api/sessions#send-input) to start work.309310### Tools available to subagents311312Subagents inherit configured MCP tools, their credentials and allowed tools, and web search settings. They can also use the environment's files and command-line tools. Subagents do not support [function tools](https://developers.openai.com/api/docs/guides/agents-api/tools/functions).313314## Observe delegation315316The [session event stream](https://developers.openai.com/api/docs/guides/agents-api/sessions/events) reports subagent activity:317318- `agent.session.subagent.created` provides the new subagent's ID.319- `agent.session.turn.item.added` and `agent.session.turn.item.done` report coordination actions. Their item types include `create_subagent_call`, `send_subagent_input_call`, `wait_for_subagents_call`, and `interrupt_subagent_call`.320321The harness executes these actions. A completed create or wait action does not mean the subagent finished its task. On a create item, `agent_id` identifies the agent that requested the subagent.322323324325326Coordination items can omit message content. An `agent_message` item contains inter-agent text when available, but the stream does not provide a full conversation transcript.327328329330331Read the main agent's response for the combined result. Use [saved items and turns](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#fetch-items-and-turns) to inspect prior work, including each subagent's history.332333### Attribute commands334335Given a command item and its session ID, retrieve the command's turn to identify the agent that ran it. The turn's `subagent_id` is `null` for the main agent.336337Identify the agent that ran a command338339```javascript340// Use the saved session ID and command execution item from your application.341const turn = await client.beta.agents.sessions.turns.retrieve(342  command.turn_id,343  { session_id: sessionId }344);345console.log(turn.subagent_id);346```347348```python349# Use the saved session ID and command execution item from your application.350turn = client.beta.agents.sessions.turns.retrieve(351    command.turn_id, session_id=session_id352)353print(turn.subagent_id)354```355356```go357// Use the saved session ID and command execution item from your application.358turn, err := client.Beta.Agents.Sessions.Turns.Get(ctx, sessionID, item.TurnID)359if err != nil {360	panic(err)361}362fmt.Println(turn.SubagentID)363```364365```java366// Use the saved session ID and command execution item from your application.367var turn =368    client369        .beta()370        .agents()371        .sessions()372        .turns()373        .retrieve(374            TurnRetrieveParams.builder()375                .sessionId(sessionId)376                .turnId(command.turnId())377                .build());378System.out.println(turn.subagentId());379```380381```ruby382# Use the saved session ID and command execution item from your application.383turn = client.beta.agents.sessions.turns.retrieve(item.turn_id, session_id: session_id)384puts turn.subagent_id385```
Files main
Menu

Theme