エージェント
エージェントは、OpenAI Agents SDK の主要な構成要素です。エージェントとは、次のように設定された大規模言語モデル(LLM)です。
- 指示 – モデルに 自分が何者か、どのように応答すべきか を伝えるシステムプロンプト
- モデル – 呼び出す OpenAI モデルと、任意のモデル調整パラメーター
- ツール – タスクを達成するために LLM が呼び出せる関数や API の一覧
import { Agent } from '@openai/agents';
const agent = new Agent({ name: 'Haiku Agent', instructions: 'Always respond in haiku form.', model: 'gpt-5.4', // optional – falls back to the default model});単一の
Agentを定義またはカスタマイズする場合は、このページを使用してください。複数のエージェントをどのように連携させるか検討している場合は、エージェントオーケストレーションを参照してください。
次のガイドの選択
Section titled “次のガイドの選択”このページをエージェント定義のハブとして使用してください。次に行う必要がある判断に対応するガイドへ進んでください。
| 目的 | 次に読むガイド |
|---|---|
| モデルの選択または保存済みプロンプトの設定 | モデル |
| エージェントへの機能の追加 | ツール |
| エージェントへの隔離されたファイルシステムワークスペースの提供 | コンセプト |
| マネージャーとハンドオフの選択 | エージェントオーケストレーション |
| ハンドオフ動作の設定 | ハンドオフ |
| ターンの実行、イベントのストリーミング、状態の管理 | エージェントの実行 |
| 最終出力や実行項目の確認、または再開 | エージェントの実行結果 |
このページの以降のセクションでは、エージェントの各機能を詳しく説明します。
エージェントの基本
Section titled “エージェントの基本”Agent コンストラクターは、単一の設定オブジェクトを受け取ります。最もよく使用されるプロパティを以下に示します。
| プロパティ | 必須 | 説明 |
|---|---|---|
name | はい | 人間が判読しやすい短い識別子 |
instructions | はい | システムプロンプト(文字列 または 関数。詳しくは動的な指示を参照) |
prompt | いいえ | OpenAI Responses API のプロンプト設定。静的なプロンプトオブジェクトまたは関数を受け取ります。詳しくはプロンプトを参照してください |
handoffDescription | いいえ | このエージェントがハンドオフツールとして提示されるときに使用される短い説明 |
handoffs | いいえ | 会話を専門エージェントに委任します。詳しくは構成パターンとハンドオフを参照してください |
model | いいえ | モデル名 または カスタムの Model 実装 |
modelSettings | いいえ | 調整パラメーター(temperature、top_p など)。詳しくはモデルを参照してください。必要なプロパティがトップレベルにない場合は、providerData の下に含めることができます |
tools | いいえ | モデルが呼び出せる Tool インスタンスの配列。詳しくはツールを参照してください |
mcpServers | いいえ | エージェント用の MCP ベースのツール。詳しくは MCP 連携を参照してください |
mcpConfig | いいえ | 厳密なスキーマ、エラー処理、サーバー名を接頭辞に持つツール名など、ローカル MCP ツールのオプション。詳しくはエージェントレベルの MCP 設定を参照してください |
inputGuardrails | いいえ | このエージェントチェーンの最初のユーザー入力に適用されるガードレール。詳しくはガードレールを参照してください |
outputGuardrails | いいえ | このエージェントの最終出力に適用されるガードレール。詳しくはガードレールを参照してください |
outputType | いいえ | プレーンテキストではなく構造化された出力を返します。詳しくは出力型とエージェントの実行結果を参照してください |
toolUseBehavior | いいえ | 関数ツールの実行結果をモデルに戻すか、実行を終了するかを制御します。詳しくはツール使用の強制を参照してください |
resetToolChoice | いいえ | ツール使用のループを防ぐため、ツール呼び出し後に toolChoice をデフォルトへリセットします(デフォルト:true)。詳しくはツール使用の強制を参照してください |
handoffOutputTypeWarningEnabled | いいえ | ハンドオフの出力型が異なる場合に警告を出します(デフォルト:true)。詳しくはエージェントの実行結果を参照してください |
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],});コンテキスト
Section titled “コンテキスト”エージェントでは、コンテキスト型にジェネリクスを使用します。つまり、Agent<TContext, TOutput> です。コンテキスト は、自分で作成して Runner.run() に渡す依存性注入オブジェクトです。これはすべてのツール、ガードレール、ハンドオフなどに渡され、状態の保存や共有サービス(データベース接続、ユーザーメタデータ、機能フラグなど)の提供に役立ちます。
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.',});
// Laterimport { 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 は次の形式を受け付けます。
- Zod スキーマ(
z.object({...})) - JSON スキーマ互換の任意のオブジェクト
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を使用します。
OpenAI プラットフォームとの対応
Section titled “OpenAI プラットフォームとの対応”一部のエージェントのコンセプトは OpenAI プラットフォームのコンセプトに直接対応しますが、エージェントの定義時ではなく実行時に設定するものもあります。
| SDK のコンセプト | OpenAI ガイド | 使用する場面 |
|---|---|---|
outputType | Structured Outputs | エージェントがテキストではなく、型付き JSON または Zod で検証されたオブジェクトを返す必要がある場合 |
tools / 組み込みツール(Hosted) | ツールガイド | モデルに検索、取得、コード実行、または関数やツールの呼び出しを行わせる場合 |
conversationId / previousResponseId | 会話状態 | OpenAI にターン間の会話状態を保持または連結させる場合 |
conversationId と previousResponseId は実行時の制御項目であり、Agent コンストラクターのフィールドではありません。これらの SDK エントリーポイントが必要な場合は、エージェントの実行を参照してください。
構成パターン
Section titled “構成パターン”エージェントが大規模なワークフローに参加する場合、最もよく使用される SDK のエントリーポイントは次の 2 つです。
- マネージャー(agents as tools) – 中央のエージェントが会話を管理し、ツールとして公開された専門エージェントを呼び出します。
- ハンドオフ – 最初のエージェントがユーザーのリクエストを特定すると、会話全体を専門エージェントに委任します。
これらのアプローチは相互補完的です。マネージャーを使用すると、ガードレールやレート制限を 1 か所で適用できます。一方、ハンドオフでは各エージェントが会話の制御を保持せず、単一のタスクに集中できます。設計上のトレードオフと各パターンの選択基準については、エージェントオーケストレーションを参照してください。
マネージャー(agents as tools)
Section titled “マネージャー(agents as tools)”このパターンでは、マネージャーは制御を引き渡しません。LLM がツールを使用し、マネージャーが最終回答を要約します。詳しくはツールを参照してください。
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.', }), ],});ハンドオフでは、トリアージエージェントがリクエストを振り分けます。ただし、ハンドオフが行われると、専門エージェントが最終出力を生成するまで会話を管理します。これにより、プロンプトを短く保ち、各エージェントを個別に検討できます。詳しくはハンドオフを参照してください。
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 handoffsconst 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],});ハンドオフ先が異なる出力型を返す可能性がある場合は、new Agent(...) よりも Agent.create(...) を推奨します。これにより、TypeScript はハンドオフグラフ全体で考えられる finalOutput の型のユニオンを推論でき、handoffOutputTypeWarningEnabled で制御される実行時警告を回避できます。エンドツーエンドのコード例については、エージェントの実行結果を参照してください。
高度な設定と実行時制御
Section titled “高度な設定と実行時制御”instructions には、文字列の代わりに 関数 を指定できます。この関数は現在の RunContext とエージェントインスタンスを受け取り、文字列 または Promise<string> を返せます。
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 関数の両方がサポートされています。
動的プロンプト
Section titled “動的プロンプト”prompt は instructions と同じ形式のコールバックをサポートしますが、文字列ではなくプロンプト設定オブジェクトを返します。これは、プロンプト ID、バージョン、または変数が現在の実行コンテキストに依存する場合に便利です。
import { Agent, RunContext } from '@openai/agents';
interface PromptContext { customerTier: 'free' | 'pro';}
function buildPrompt(runContext: RunContext<PromptContext>) { return { promptId: 'pmpt_support_agent', version: '7', variables: { customer_tier: runContext.context.customerTier, }, };}
const agent = new Agent<PromptContext>({ name: 'Prompt-backed helper', prompt: buildPrompt,});これは OpenAI Responses API を使用する場合にのみサポートされます。同期関数と async 関数の両方がサポートされています。
ライフサイクルフック
Section titled “ライフサイクルフック”高度なユースケースでは、イベントをリッスンしてエージェントのライフサイクルを監視できます。
Agent インスタンスは、その特定のエージェントインスタンスに関するライフサイクルイベントを発行します。一方、Runner は実行全体を通じた単一のストリームとして、同じ名前のイベントを発行します。これは、ハンドオフやツール呼び出しを 1 か所で監視したいマルチエージェントワークフローで役立ちます。
共通のイベント名は次のとおりです。
| イベント | Agent フックの引数 | Runner フックの引数 |
|---|---|---|
agent_start | (context, agent, turnInput?) | (context, agent, turnInput?) |
agent_end | (context, output) | (context, agent, output) |
agent_handoff | (context, nextAgent) | (context, fromAgent, toAgent) |
agent_tool_start | (context, tool, { toolCall }) | (context, agent, tool, { toolCall }) |
agent_tool_end | (context, tool, result, { toolCall }) | (context, agent, tool, result, { toolCall }) |
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);});ガードレール
Section titled “ガードレール”ガードレールを使用すると、ユーザー入力とエージェント出力を検証または変換できます。これらは inputGuardrails 配列と outputGuardrails 配列で設定します。詳しくはガードレールを参照してください。
エージェントのクローン / コピー
Section titled “エージェントのクローン / コピー”既存のエージェントを少し変更したバージョンが必要ですか?完全に新しい Agent インスタンスを返す clone() メソッドを使用してください。
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({ name: 'Pirate', instructions: 'Respond like a pirate – lots of “Arrr!”', model: 'gpt-5.4',});
const robotAgent = pirateAgent.clone({ name: 'Robot', instructions: 'Respond like a robot – be precise and factual.',});ツール使用の強制
Section titled “ツール使用の強制”ツールを指定しても、LLM がそのいずれかを呼び出すとは限りません。modelSettings.toolChoice を使用すると、ツールの使用を 強制 できます。
'auto'(デフォルト)– ツールを使用するかどうかを LLM が判断します。'required'– LLM はツールを呼び出す必要があります(どのツールを使用するかは選択できます)。'none'– LLM はツールを呼び出しては なりません。'calculator'などの特定のツール名 – LLM はそのツールを呼び出す必要があります。
OpenAI Responses で利用可能なツールが computerTool() の場合、toolChoice: 'computer' には特別な意味があります。'computer' を単なる関数名として扱うのではなく、GA の組み込みコンピュータツールを強制的に使用します。SDK は以前の連携向けにプレビュー互換のコンピューターセレクターも受け付けますが、新しいコードでは 'computer' を推奨します。利用可能なコンピュータツールがない場合、この文字列はほかの関数ツール名と同様に動作します。
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: 'required' },});toolNamespace()、deferLoading: true を指定した関数ツール、または deferLoading: true を指定したホスト型 MCP ツールなど、遅延読み込みされる Responses ツールを使用する場合は、modelSettings.toolChoice を 'auto' のままにしてください。これらの定義をいつ読み込むかはモデルが判断する必要があるため、SDK は遅延ツールや組み込みの tool_search ヘルパーを名前で強制することを拒否します。ツール検索の完全な設定については、ツールを参照してください。
無限ループの防止
Section titled “無限ループの防止”ツール呼び出し後、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)は常にモデルに結果を返し、処理を継続します。
- モデルの選択、保存済みプロンプト、プロバイダー設定については、モデルを参照してください。
- 関数ツール、組み込みツール(Hosted)、MCP、
agent.asTool()については、ツールを参照してください。 - マネージャー、ハンドオフ、コード駆動のオーケストレーションの選択については、エージェントオーケストレーションを参照してください。
- 専門エージェントへの委任の設定については、ハンドオフを参照してください。
- ターンの実行、ストリーミング、会話状態については、エージェントの実行を参照してください。
finalOutput、実行項目、再開状態については、エージェントの実行結果を参照してください。- サイドバーの @openai/agents から、TypeDoc リファレンス全体を確認できます。