コンテンツにスキップ

エージェント

エージェントは OpenAI Agents SDK の主要な構成要素です。Agent は、次の設定を施した Large Language Model (LLM) です。

  • Instructions – モデルに「自分は何者か」「どのように応答すべきか」を伝える system prompt
  • Model – 呼び出す OpenAI モデルと、任意のモデル調整パラメーター
  • Tools – タスクを達成するために LLM が呼び出せる関数や API の一覧
基本的な Agent 定義
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Haiku Agent',
instructions: 'Always respond in haiku form.',
model: 'gpt-5-nano', // optional – falls back to the default model
});

このページでは、各 Agent 機能をより詳しく説明します。


Agent のコンストラクタは単一の設定オブジェクトを受け取ります。よく使われるプロパティは以下のとおりです。

PropertyRequiredDescription
nameyes短い人間可読の識別子
instructionsyesSystem prompt(文字列 または 関数。詳細は動的 instructions を参照)
promptnoOpenAI Responses API のプロンプト設定。詳しくはモデル を参照
handoffDescriptionnoこのエージェントがハンドオフツールとして提供される際に使われる短い説明
modelnoモデル名 または カスタム Model 実装
modelSettingsno調整パラメーター(temperature、top_p など)。必要なプロパティがトップレベルにない場合は、providerData 配下に含められます
toolsnoモデルが呼び出せる Tool インスタンスの配列
mcpServersnoエージェントにツールを提供する MCP サーバー。詳しくは MCP 連携 を参照
resetToolChoicenoツール呼び出し後にデフォルトへ toolChoice をリセット(デフォルト: true)。ツール使用ループを防ぎます。詳しくはツール使用の強制
handoffOutputTypeWarningEnablednoハンドオフの出力タイプが異なる場合に警告を出す(デフォルト: true
ツール付き Agent
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
const getWeather = tool({
name: 'get_weather',
description: 'Return the weather for a given city.',
parameters: z.object({ city: z.string() }),
async execute({ city }) {
return `The weather in ${city} is sunny.`;
},
});
const agent = new Agent({
name: 'Weather bot',
instructions: 'You are a helpful weather bot.',
model: 'gpt-4.1',
tools: [getWeather],
});

エージェントは自分のコンテキスト型に対して汎用的です(例: Agent<TContext, TOutput>)。コンテキストは、あなたが作成して Runner.run() に渡す依存性注入オブジェクトです。これはすべてのツール、ガードレール、ハンドオフなどに転送され、状態の保存や共通サービス(データベース接続、ユーザーメタデータ、機能フラグ など)を提供するのに役立ちます。

コンテキスト付き Agent
import { Agent } from '@openai/agents';
interface Purchase {
id: string;
uid: string;
deliveryStatus: string;
}
interface UserContext {
uid: string;
isProUser: boolean;
// this function can be used within tools
fetchPurchases(): Promise<Purchase[]>;
}
const agent = new Agent<UserContext>({
name: 'Personal shopper',
instructions: 'Recommend products the user will love.',
});
// Later
import { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', {
context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },
});

デフォルトでは、エージェントはプレーンテキスト(string)を返します。モデルに構造化オブジェクトを返させたい場合は、outputType プロパティを指定します。SDK は次を受け付けます。

  1. Zod スキーマ(z.object({...})
  2. JSON Schema 互換の任意のオブジェクト
Zod を使った構造化出力
import { Agent } from '@openai/agents';
import { z } from 'zod';
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const extractor = new Agent({
name: 'Calendar extractor',
instructions: 'Extract calendar events from the supplied text.',
outputType: CalendarEvent,
});

outputType が指定されると、SDK はプレーンテキストではなく structured outputs を自動的に使用します。


マルチエージェントのシステム設計パターン

Section titled “マルチエージェントのシステム設計パターン”

エージェントを組み合わせる方法は多数あります。プロダクションアプリでよく見られる 2 つのパターンは次のとおりです。

  1. Manager (agents as tools) – 中央のエージェントが会話を管理し、ツールとして公開された専門エージェントを呼び出します
  2. Handoffs – 最初のエージェントがユーザーの要求を特定したら、会話全体を専門エージェントに委譲します

これらのアプローチは補完的です。マネージャーはガードレールやレート制限を一元的に適用でき、ハンドオフは各エージェントが会話の制御を保持せずに単一タスクに集中できます。

このパターンでは、マネージャーは制御を渡しません。LLM がツールを使い、マネージャーが最終回答を要約します。詳しくはツール ガイドを参照してください。

Agents as tools
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({
name: 'Booking expert',
instructions: 'Answer booking questions and modify reservations.',
});
const refundAgent = new Agent({
name: 'Refund expert',
instructions: 'Help customers process refunds and credits.',
});
const customerFacingAgent = new Agent({
name: 'Customer-facing agent',
instructions:
'Talk to the user directly. When they need booking or refund help, call the matching tool.',
tools: [
bookingAgent.asTool({
toolName: 'booking_expert',
toolDescription: 'Handles booking questions and requests.',
}),
refundAgent.asTool({
toolName: 'refund_expert',
toolDescription: 'Handles refund questions and requests.',
}),
],
});

ハンドオフでは、トリアージエージェントがリクエストをルーティングしますが、ハンドオフが発生すると、専門エージェントが最終出力を生成するまで会話を管理します。これによりプロンプトを短く保ち、各エージェントを個別に考えやすくなります。詳しくはハンドオフ ガイドを参照してください。

ハンドオフ付き Agent
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({
name: 'Booking Agent',
instructions: 'Help users with booking requests.',
});
const refundAgent = new Agent({
name: 'Refund Agent',
instructions: 'Process refund requests politely and efficiently.',
});
// Use Agent.create method to ensure the finalOutput type considers handoffs
const triageAgent = Agent.create({
name: 'Triage Agent',
instructions: `Help the user with their questions.
If the user asks about booking, hand off to the booking agent.
If the user asks about refunds, hand off to the refund agent.`.trimStart(),
handoffs: [bookingAgent, refundAgent],
});

instructions は文字列の代わりに関数にできます。関数は現在の RunContext と Agent インスタンスを受け取り、文字列 または Promise<string> を返せます。

動的 instructions を使う Agent
import { Agent, RunContext } from '@openai/agents';
interface UserContext {
name: string;
}
function buildInstructions(runContext: RunContext<UserContext>) {
return `The user's name is ${runContext.context.name}. Be extra friendly!`;
}
const agent = new Agent<UserContext>({
name: 'Personalized helper',
instructions: buildInstructions,
});

同期関数と async 関数の両方をサポートします。


高度なユースケースでは、イベントをリッスンして Agent のライフサイクルを監視できます。利用可能な項目は、こちら に列挙されたエージェントフックのイベント名を参照してください。

ライフサイクルフック付き Agent
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Verbose agent',
instructions: 'Explain things thoroughly.',
});
agent.on('agent_start', (ctx, agent) => {
console.log(`[${agent.name}] started`);
});
agent.on('agent_end', (ctx, output) => {
console.log(`[agent] produced:`, output);
});

ガードレールは、ユーザー入力とエージェント出力を検証または変換できます。inputGuardrailsoutputGuardrails 配列で設定します。詳細はガードレール ガイドを参照してください。


エージェントのクローン/コピー

Section titled “エージェントのクローン/コピー”

既存エージェントの少しだけ変更した版が必要ですか?clone() メソッドを使うと、完全に新しい Agent インスタンスが返されます。

エージェントのクローン
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({
name: 'Pirate',
instructions: 'Respond like a pirate – lots of “Arrr!”',
model: 'gpt-5-mini',
});
const robotAgent = pirateAgent.clone({
name: 'Robot',
instructions: 'Respond like a robot – be precise and factual.',
});

ツールを提供しても、LLM が必ず呼び出すとは限りません。modelSettings.toolChoice でツール使用を強制できます。

  1. 'auto'(デフォルト)– ツールを使うかどうかを LLM が判断
  2. 'required' – LLM はツールを呼び出す 必要がある(どれを使うかは選べる)
  3. 'none' – LLM はツールを呼び出しては ならない
  4. 特定のツール名(例: 'calculator')– LLM はその特定ツールを呼び出す必要がある
ツール使用の強制
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
const calculatorTool = tool({
name: 'Calculator',
description: 'Use this tool to answer questions about math problems.',
parameters: z.object({ question: z.string() }),
execute: async (input) => {
throw new Error('TODO: implement this');
},
});
const agent = new Agent({
name: 'Strict tool user',
instructions: 'Always answer using the calculator tool.',
tools: [calculatorTool],
modelSettings: { toolChoice: 'auto' },
});

ツール呼び出し後、SDK は自動的に toolChoice'auto' にリセットします。これにより、モデルがツール呼び出しを繰り返す無限ループに入るのを防ぎます。この挙動は、resetToolChoice フラグで上書きするか、toolUseBehavior を設定して変更できます。

  • 'run_llm_again'(デフォルト)– ツール結果を使って LLM を再実行
  • 'stop_on_first_tool' – 最初のツール結果を最終回答として扱う
  • { stopAtToolNames: ['my_tool'] } – 指定ツールが呼ばれたら停止
  • (context, toolResults) => ... – 実行を終了すべきかを返すカスタム関数
const agent = new Agent({
...,
toolUseBehavior: 'stop_on_first_tool',
});

注: toolUseBehavior関数ツール にのみ適用されます。組み込みツール(Hosted)は常にモデルに処理を戻します。