La orquestación multiagente permite que un agente delegue tareas a subagentes. Cada subagente tiene su propio contexto y puede trabajar en paralelo con los demás. El agente principal coordina su trabajo y combina sus resultados.
Usa subagentes para tareas independientes, como revisar documentos por separado o investigar distintas causas de una falla. Para cada tarea, formula una pregunta clara y especifica el resultado esperado.
Deja las tareas breves y los pasos que dependen unos de otros a cargo del agente principal. Los agentes que editan los mismos archivos deben coordinar sus cambios.
Establece agent.multi_agent.enabled en true al crear una sesión. El arnés de ejecución proporciona herramientas para crear subagentes, enviarles mensajes, esperarlos e interrumpirlos. No tienes que declarar estas herramientas.
En este ejemplo, el usuario solicita explícitamente dos subagentes en su mensaje. Cada uno revisa un conjunto de notas de la versión y el agente principal reúne sus hallazgos. El ejemplo no requiere un entorno ni herramientas configuradas.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import 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();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18from 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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import (
"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())
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
42import 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());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25require "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
1
2
3
4
5
6
7
8
9
10
11
12
13
14curl --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
}'
Si usas environment.type: "none", incluye la entrada inicial en el campo input de la solicitud de creación. Si configuras stream: true, el primer turno también se transmite en tiempo real. Consulta Eventos y elementos de la sesión para saber cómo gestionar y recuperar el flujo de eventos.
max_concurrent_subagents limita la cantidad de subagentes que pueden ejecutarse al mismo tiempo. El valor predeterminado es 6, sin contar al coordinador. Si habilitas la delegación, especifica un número entero positivo.
Para deshabilitar la delegación, omite multi_agent o establece enabled en false y omite el límite. Esta configuración se aplica al crear la sesión. Los cambios que hagas en un agente guardado se aplican a las sesiones nuevas.
Cuando los agentes necesiten acceder a archivos o ejecutar comandos, agrega un entorno. El coordinador y los subagentes comparten el sistema de archivos del entorno. Al crear un subagente, no se crea otro entorno.
Este ejemplo crea una sesión para trabajar en tu propio entorno.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15const 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",
},
});
1
2
3
4
5
6
7
8result = 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"},
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17result, 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)
}
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
26var 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());
1
2
3
4
5
6
7
8
9
10
11
12
13
14result = 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"
}
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18curl 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"
}
}'
Guarda en tu aplicación los ID de sesión y de entorno que recibas. Conecta el entorno y luego envía la entrada para iniciar el trabajo.
Los subagentes heredan las herramientas MCP configuradas, sus credenciales, la lista de herramientas permitidas y la configuración de búsqueda web. También pueden usar los archivos y las herramientas de línea de comandos del entorno. Los subagentes no admiten herramientas de función.
El flujo de eventos de la sesión informa sobre la actividad de los subagentes:
agent.session.subagent.created proporciona el ID del nuevo subagente.
agent.session.turn.item.added y agent.session.turn.item.done informan sobre las acciones de coordinación. Entre los tipos de elementos de estos eventos se encuentran create_subagent_call, send_subagent_input_call, wait_for_subagents_call e interrupt_subagent_call.
El arnés de ejecución realiza estas acciones. Que termine una acción de creación o de espera no significa que el subagente haya terminado su tarea. En un elemento de creación, agent_id identifica al agente que solicitó el subagente.
Los elementos de coordinación pueden omitir el contenido de los mensajes. Un elemento agent_message contiene el texto intercambiado entre agentes cuando está disponible, pero el flujo de eventos no proporciona una transcripción completa de la conversación.
Lee la respuesta del agente principal para obtener el resultado combinado. Consulta los elementos y turnos guardados para revisar el trabajo anterior, incluido el historial de cada subagente.
Si tienes el elemento de un comando y su ID de sesión, recupera el turno del comando para identificar al agente que lo ejecutó. Para el agente principal, el campo subagent_id del turno tiene el valor null.
1
2
3
4
5
6// 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);
1
2
3
4
5# 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)
1
2
3
4
5
6// 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)
1
2
3
4
5
6
7
8
9
10
11
12
13// 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());
1
2
3# 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