マルチエージェント機能を使うと、エージェントはサブエージェントにタスクを委任できます。各サブエージェントは独自のコンテキストを持ち、他のサブエージェントと並行して作業できます。メインエージェントは各サブエージェントの作業を調整し、結果をまとめます。
別々の文書をレビューする場合や、障害の原因の候補を個別に調査する場合など、互いに独立したタスクにはサブエージェントを使います。タスクごとに、答えてほしい問いと期待する結果を明示してください。
短時間で済むタスクや、前のステップの結果に依存する処理は、メインエージェントで実行します。複数のエージェントが同じファイルを編集する場合は、変更内容を互いに調整する必要があります。
セッションを作成する際に、agent.multi_agent.enabled を true に設定します。ハーネスには、サブエージェントの作成、メッセージの送信、待機、中断に使うツールが用意されています。これらのツールを自分で宣言する必要はありません。
この例では、ユーザー入力で 2 つのサブエージェントを明示的に要求します。それぞれが別のリリースノートをレビューし、メインエージェントがレビュー結果をまとめます。環境の用意やツールの設定は不要です。
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
}'
environment.type: "none" を指定する場合は、セッション作成リクエストに最初の input を含めてください。stream: true を設定すると、最初のターンもストリーミングされます。ストリームの処理と復旧については、セッションのイベントとアイテムを参照してください。
max_concurrent_subagents は、同時に実行できるサブエージェントの数を制限します。デフォルトは 6 で、作業を調整するメインエージェントはこの数に含まれません。委任を有効にする場合は、正の整数を指定してください。
委任を無効にするには、multi_agent を省略するか、enabled を false に設定して同時実行数の上限を省略します。これらの設定はセッションの作成時に適用されます。保存済みのエージェントに加えた変更は、新しいセッションに適用されます。
エージェントがファイルにアクセスしたりコマンドを実行したりする必要がある場合は、環境を追加してください。メインエージェントとサブエージェントは、その環境のファイルシステムを共有します。サブエージェントを作成しても、別の環境は作成されません。
この例では、独自の環境で作業するためのセッションを作成します。
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"
}
}'
返されたセッション ID と環境 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 です。
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