Im Multi-Agenten-Modus kann ein Agent Aufgaben an Subagenten delegieren. Jeder Subagent hat einen eigenen Kontext und kann parallel zu den anderen arbeiten. Der Hauptagent koordiniert ihre Arbeit und führt ihre Ergebnisse zusammen.
Setze Subagenten für voneinander unabhängige Aufgaben ein, etwa um verschiedene Dokumente zu prüfen oder unterschiedliche Ursachen für einen Fehler zu untersuchen. Formuliere für jede Aufgabe eine klare Frage und gib an, welches Ergebnis du erwartest.
Lass den Hauptagenten kurze Aufgaben und voneinander abhängige Schritte selbst ausführen. Agenten, die dieselben Dateien bearbeiten, müssen ihre Änderungen aufeinander abstimmen.
Setze agent.multi_agent.enabled beim Erstellen einer Sitzung auf true. Der Harness stellt Tools bereit, mit denen der Agent Subagenten erstellen, ihnen Nachrichten senden, auf sie warten und sie unterbrechen kann. Du musst diese Tools nicht selbst deklarieren.
In diesem Beispiel fordert die Nutzereingabe ausdrücklich zwei Subagenten an. Jeder prüft einen eigenen Satz von Versionshinweisen. Der Hauptagent führt die Ergebnisse zusammen. Das Beispiel kommt ohne Umgebung und ohne konfigurierte Tools aus.
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
}'
Wenn du environment.type: "none" verwendest, übergib die erste Eingabe als input in der Anfrage zum Erstellen der Sitzung. Mit stream: true wird auch der erste Turn gestreamt. Wie du den Stream verarbeitest und nach einer Unterbrechung wiederherstellst, erfährst du im Abschnitt Sitzungsereignisse und -elemente.
max_concurrent_subagents begrenzt die Anzahl der Subagenten, die gleichzeitig laufen können. Der Standardwert ist 6. Der koordinierende Hauptagent zählt dabei nicht mit. Gib bei aktivierter Delegation eine positive ganze Zahl an.
Um die Delegation zu deaktivieren, lass multi_agent weg oder setze enabled auf false und lass die Obergrenze weg. Diese Einstellungen gelten beim Erstellen der Sitzung. Änderungen an einem gespeicherten Agenten gelten für neue Sitzungen.
Wenn Agenten auf Dateien zugreifen oder Befehle ausführen müssen, füge eine Umgebung hinzu. Der Hauptagent und die Subagenten nutzen das Dateisystem der Umgebung gemeinsam. Beim Erstellen eines Subagenten entsteht keine weitere Umgebung.
Dieses Beispiel erstellt eine Sitzung für die Arbeit in deiner eigenen Umgebung.
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"
}
}'
Speichere die zurückgegebenen IDs der Sitzung und der Umgebung in deiner Anwendung. Verbinde die Umgebung und sende dann eine Eingabe, um die Arbeit zu starten.
Subagenten übernehmen die konfigurierten MCP-Tools samt Zugangsdaten und Freigaben für einzelne Tools sowie die Einstellungen für die Websuche. Sie können auch die Dateien und Kommandozeilentools der Umgebung nutzen. Subagenten unterstützen keine Funktionstools.
Der Ereignisstream der Sitzung meldet die Aktivitäten der Subagenten.
agent.session.subagent.created liefert die ID des neuen Subagenten.
agent.session.turn.item.added und agent.session.turn.item.done melden Koordinationsaktionen. Zu den zugehörigen Elementtypen gehören create_subagent_call, send_subagent_input_call, wait_for_subagents_call und interrupt_subagent_call.
Der Harness führt diese Aktionen aus. Auch wenn die Aktion zum Erstellen oder Warten abgeschlossen ist, kann der Subagent noch an seiner Aufgabe arbeiten. Im Element für die Erstellung bezeichnet agent_id den Agenten, der den Subagenten angefordert hat.
Koordinationselemente können den Nachrichteninhalt auslassen. Ein Element vom Typ agent_message enthält den zwischen Agenten ausgetauschten Text, sofern er verfügbar ist. Der Stream liefert jedoch kein vollständiges Gesprächsprotokoll.
Das zusammengeführte Ergebnis findest du in der Antwort des Hauptagenten. Über die gespeicherten Elemente und Turns kannst du frühere Arbeitsschritte einsehen, einschließlich des Verlaufs jedes Subagenten.
Wenn dir ein Befehlselement und seine Sitzungs-ID vorliegen, rufe den zugehörigen Turn ab. So erkennst du, welcher Agent den Befehl ausgeführt hat. Beim Hauptagenten hat subagent_id im Turn den Wert 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