エージェント
エージェントは、OpenAI Agents SDK の主要な構成要素です。 エージェント とは、次の要素を設定した大規模言語モデル(LLM)です。
- Instructions – モデルに 自分が何者であるか、および どのように応答すべきか を伝えるシステムプロンプト
- Model – 呼び出す OpenAI モデルと、オプションのモデル調整パラメーター
- Tools – タスクを実行するために 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 | はい | システムプロンプト(文字列 または 関数。詳しくは動的な 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 | いいえ | SDK が関数ツールの実行結果をモデルに返すか、その実行結果を実行全体の最終出力として使用するかを制御します。ツール使用の強制を参照してください |
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({...})) - Standard JSON Schema 変換に対応した Standard Schema 値
- JSON Schema 互換の任意のオブジェクト
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 を使用します。
Zod および対応する Standard Schema 値は、解析済みの出力をローカルで検証し、推論された出力型を維持します。元の JSON Schema はモデルとの契約を記述しますが、解析済みの実行結果は unknown のままです。Standard Schema の例と対応する検証範囲については、スキーマ検証を参照してください。
OpenAI プラットフォームとの対応関係
Section titled “OpenAI プラットフォームとの対応関係”一部のエージェントのコンセプトは OpenAI プラットフォームのコンセプトに直接対応しますが、エージェントの定義時ではなく実行時に設定するものもあります。
| SDK のコンセプト | OpenAI ガイド | 使用する場面 |
|---|---|---|
outputType | Structured Outputs | エージェントがテキストではなく、型付き JSON またはスキーマ検証済みオブジェクトを返す必要がある場合 |
tools / 組み込みツール(Hosted) | ツールガイド | モデルが検索、取得、コード実行、または関数やツールの呼び出しを行う必要がある場合 |
conversationId / previousResponseId | 会話状態 | ターン間の会話状態を OpenAI に永続化または連結させる場合 |
conversationId と previousResponseId は実行時の制御項目であり、Agent コンストラクターのフィールドではありません。これらの SDK エントリーポイントが必要な場合は、エージェントの実行を参照してください。
構成パターン
Section titled “構成パターン”エージェントが大規模なワークフローに参加する場合、次の 2 つの SDK エントリーポイントが最もよく使用されます。
- マネージャー(agents as tools) – 中央のエージェントが会話を管理し、ツールとして公開された専門エージェントを呼び出します。
- ハンドオフ – 最初のエージェントがユーザーのリクエストを特定すると、会話全体を専門エージェントに委譲します。
これらのアプローチは相互に補完します。マネージャーではガードレールやレート制限を一元的に適用でき、ハンドオフでは会話の制御を保持せず、各エージェントを単一のタスクに集中させることができます。設計上のトレードオフと各パターンの選択基準については、エージェントオーケストレーションを参照してください。
マネージャー(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
Section titled “動的な instructions”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 は実行全体を通じた単一のストリームとして、同じ名前のイベントを発行します。これは、ハンドオフとツール呼び出しを一元的に監視したいマルチエージェントワークフローに便利です。
共通のイベント名は次のとおりです。
| イベント | エージェントフックの引数 | 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 “エージェントのクローン / コピー”既存のエージェントを少し変更したバージョンが必要な場合は、clone() メソッドを使用してください。このメソッドは、まったく新しい Agent インスタンスを返します。
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.',});clone() は、tools、handoffs、mcpServers、inputGuardrails、outputGuardrails などのリストプロパティをコピーしません。クローンの設定でこれらのプロパティのいずれかを省略すると、元のエージェントとクローンは同じ配列を共有するため、どちらかのエージェントを介して配列を変更すると両方に影響します。クローンに独自の配列を持たせるには、tools: [...agent.tools, extraTool] のような新しい配列を渡してください。ただし、その新しい配列内の各要素は、引き続き同じツールオブジェクトまたはハンドオフオブジェクトです。リストプロパティとして undefined を渡した場合は、そのプロパティが指定されたものと見なされ、元の配列を継承せず空のリストから開始します。
ツール使用の強制
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) => ...– 実行を終了するかどうかを返すカスタム関数
import { Agent, tool } from '@openai/agents';import { z } from 'zod';
const calculatorTool = tool({ name: 'calculator', description: 'Add two numbers.', parameters: z.object({ left: z.number(), right: z.number() }), execute: async ({ left, right }) => left + right,});
const agent = new Agent({ name: 'Calculator agent', instructions: 'Use the calculator tool to answer arithmetic questions.', tools: [calculatorTool], toolUseBehavior: 'stop_on_first_tool',});注:toolUseBehavior は 関数ツール にのみ適用されます。組み込みツール(Hosted)は、常に処理のためにモデルへ戻されます。
- モデルの選択、保存済みプロンプト、プロバイダー設定については、モデル
- 関数ツール、組み込みツール(Hosted)、MCP、
agent.asTool()については、ツール - マネージャー、ハンドオフ、コード主導のオーケストレーションの選択については、エージェントオーケストレーション
- 専門エージェントへの委譲の設定については、ハンドオフ
- ターンの実行、ストリーミング、会話状態については、エージェントの実行
finalOutput、実行項目、再開状態については、エージェントの実行結果- 完全な TypeDoc リファレンスは、サイドバーの @openai/agents を参照してください