エージェント
エージェントは OpenAI Agents SDK の主要な構成要素です。Agent は、次のように設定された Large Language Model (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 “次のガイドの選択”このページはエージェント定義のハブとして利用できます。次に判断したい内容に応じて、対応する関連ガイドへ進んでください。
| If you want to… | Read next |
|---|---|
| モデルを選ぶ、または保存済みプロンプトを設定する | モデル |
| エージェントに機能を追加する | ツール |
| マネージャーとハンドオフのどちらにするか決める | エージェントオーケストレーション |
| ハンドオフの動作を設定する | ハンドオフ |
| ターンを実行する、イベントをストリーミングする、または状態を管理する | エージェントの実行 |
| 最終出力、実行項目、または再開を確認する | エージェントの実行結果 |
このページの残りでは、Agent の各機能をさらに詳しく説明します。
エージェントの基礎
Section titled “エージェントの基礎”Agent コンストラクターは 1 つの設定オブジェクトを受け取ります。最もよく使われるプロパティを以下に示します。
| Property | Required | Description |
|---|---|---|
name | yes | 人間が読める短い識別子 |
instructions | yes | システムプロンプト(文字列 または 関数。詳細は 動的 instructions を参照) |
prompt | no | OpenAI Responses API のプロンプト設定です。静的なプロンプトオブジェクトまたは関数を受け取ります。Prompt を参照してください |
handoffDescription | no | このエージェントがハンドオフツールとして提供される際に使われる短い説明 |
handoffs | no | 会話を専門エージェントに委譲します。構成パターン および ハンドオフ ガイド を参照してください |
model | no | モデル名 または カスタム Model 実装 |
modelSettings | no | 調整パラメーター(temperature、top_p など)。モデル を参照してください。必要なプロパティがトップレベルにない場合は、providerData 配下に含められます |
tools | no | モデルが呼び出せる Tool インスタンスの配列です。ツール を参照してください |
mcpServers | no | エージェント向けの MCP ベースのツールです。MCP 連携 を参照してください |
inputGuardrails | no | このエージェントチェーンの最初のユーザー入力に適用されるガードレールです。ガードレール を参照してください |
outputGuardrails | no | このエージェントの最終出力に適用されるガードレールです。ガードレール を参照してください |
outputType | no | プレーンテキストの代わりに structured outputs を返します。出力型 および エージェントの実行結果 を参照してください |
toolUseBehavior | no | 関数ツールの結果をモデルに戻すか、実行を終了するかを制御します。ツール使用の強制 を参照してください |
resetToolChoice | no | ツール呼び出し後に toolChoice をデフォルトにリセットします(デフォルト: true)。ツール使用ループを防ぐためです。ツール使用の強制 を参照してください |
handoffOutputTypeWarningEnabled | no | ハンドオフ先で出力型が異なる場合に警告を出します(デフォルト: 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> です。context は依存性注入用のオブジェクトであり、これを作成して 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 () => [] },});デフォルトでは、Agent は プレーンテキスト(string)を返します。モデルに構造化オブジェクトを返させたい場合は、outputType プロパティを指定できます。SDK が受け付けるのは次のいずれかです。
- Zod スキーマ(
z.object({...})) - 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 を使用します。
OpenAI プラットフォームとの対応
Section titled “OpenAI プラットフォームとの対応”一部のエージェントの概念は OpenAI プラットフォームの概念に直接対応していますが、他はエージェント定義時ではなく実行時に設定されます。
| SDK concept | OpenAI guide | When it matters |
|---|---|---|
outputType | Structured Outputs | エージェントがテキストの代わりに型付き JSON または Zod で検証されたオブジェクトを返す必要がある場合 |
tools / hosted tools | Tools guide | モデルに検索、取得、コード実行、または関数 / ツール呼び出しをさせたい場合 |
conversationId / previousResponseId | Conversation state | OpenAI にターン間の会話状態を永続化または連結させたい場合 |
conversationId と previousResponseId は実行時の制御であり、Agent コンストラクターのフィールドではありません。これらの SDK エントリーポイントが必要な場合は エージェントの実行 を利用してください。
構成パターン
Section titled “構成パターン”エージェントがより大きなワークフローに参加する場合、最もよく使われる SDK のエントリーポイントは 2 つあります。
- Manager(Agents as tools) – 中央のエージェントが会話を管理し、ツールとして公開された専門エージェントを呼び出します
- ハンドオフ – 最初のエージェントが、ユーザーの要求を特定した時点で会話全体を専門エージェントに委譲します
これらのアプローチは相補的です。Manager はガードレールやレート制限を一元的に適用する場所を提供し、ハンドオフは各エージェントが会話の制御を保持せずに単一のタスクに集中できるようにします。設計上のトレードオフや、どのパターンを選ぶべきかについては、エージェントオーケストレーション を参照してください。
Manager(Agents as tools)
Section titled “Manager(Agents as tools)”このパターンでは Manager は制御を渡しません。LLM がツールを使用し、Manager が最終回答を要約します。詳しくは ツール ガイド を参照してください。
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 の形の union を推論でき、handoffOutputTypeWarningEnabled で制御される実行時警告も回避できます。エンドツーエンドの例については エージェントの実行結果 ガイド を参照してください。
高度な設定と実行時制御
Section titled “高度な設定と実行時制御”動的 instructions
Section titled “動的 instructions”instructions は文字列ではなく 関数 にすることもできます。この関数は現在の RunContext と Agent インスタンスを受け取り、文字列 または 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 のライフサイクルを観察できます。
Agent インスタンスはその特定のエージェントインスタンスに対するライフサイクルイベントを発行し、Runner は同じイベント名を実行全体にわたる単一のストリームとして発行します。これは、ハンドオフやツール呼び出しを 1 か所で観察したいマルチエージェントワークフローで役立ちます。
共通のイベント名は次のとおりです。
| Event | Agent hook arguments | Runner hook arguments |
|---|---|---|
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.',});ツール使用の強制
Section titled “ツール使用の強制”ツールを渡しても、LLM が必ずそれを呼び出すとは限りません。modelSettings.toolChoice を使うと、ツール使用を 強制 できます。
'auto'(デフォルト)– ツールを使うかどうかを LLM が判断します'required'– LLM は必ずツールを呼び出さなければなりません(どれを使うかは選べます)'none'– LLM はツールを呼び出しては いけません- 特定のツール名(例:
'calculator')– LLM はその特定のツールを呼び出さなければなりません
利用可能なツールが OpenAI Responses の computerTool() の場合、toolChoice: 'computer' は特別です。'computer' を通常の関数名として扱うのではなく、GA の組み込みコンピュータツールを強制します。SDK は古い統合向けに preview 互換のコンピュータセレクターも受け付けますが、新しいコードでは '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() のような遅延 Responses ツール、deferLoading: true を持つ関数ツール、または deferLoading: true を持つ hosted MCP ツールを使う場合は、modelSettings.toolChoice を 'auto' のままにしてください。SDK は、遅延ツールや組み込みの tool_search ヘルパーを名前で強制することを拒否します。これらの定義をいつ読み込むかはモデルが判断する必要があるためです。完全な 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 tool は常に処理のためにモデルへ戻されます。
- モデル選択、保存済みプロンプト、プロバイダー設定については モデル
- 関数ツール、hosted tools、MCP、
agent.asTool()については ツール - Manager、ハンドオフ、コード主導のオーケストレーションの選び方については エージェントオーケストレーション
- 専門エージェントへの委譲設定については ハンドオフ
- ターン実行、ストリーミング、会話状態については エージェントの実行
finalOutput、実行項目、再開状態については エージェントの実行結果- サイドバーの @openai/agents 配下にある完全な TypeDoc リファレンスも参照してください