コンテンツにスキップ

エージェント

エージェントは、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 を定義またはカスタマイズする場合は、このページを参照してください。複数のエージェントをどのように連携させるかを検討している場合は、エージェントオーケストレーションを参照してください。

このページをエージェント定義のハブとして活用してください。次に決める必要があることに応じて、関連するガイドに進んでください。

目的次に読むガイド
モデルの選択や保存済みプロンプトの設定モデル
エージェントへの機能の追加ツール
構造化データ用の検証ライブラリの選択スキーマ検証
エージェントへの隔離されたファイルシステムワークスペースの提供コンセプト
マネージャーとハンドオフの選択エージェントオーケストレーション
ハンドオフの動作の設定ハンドオフ
ターンの実行、イベントのストリーミング、状態の管理エージェントの実行
実際のサービスを使わないエージェントワークフローのテストテスト
最終出力や実行アイテムの確認、実行の再開エージェントの実行結果

このページの以降のセクションでは、エージェントの各機能を詳しく説明します。


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いいえ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],
});

エージェントは コンテキストの型をジェネリック型パラメーターとして受け取ります 。つまり、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.',
});
// 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. Standard JSON Schema への変換に対応した、サポート対象の Standard Schema 値。
  3. 任意の 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 を自動的に使用します。

Zod とサポート対象の Standard Schema 値は、パースされた出力をローカルで検証し、推論された出力型を保持します。元の JSON Schema はモデルが従う仕様を記述しますが、パース結果は unknown のままです。Standard Schema の例とサポートされる検証範囲については、スキーマ検証を参照してください。


OpenAI プラットフォームとの対応関係

Section titled “OpenAI プラットフォームとの対応関係”

エージェントの概念の中には、OpenAI プラットフォームの概念に直接対応するものもあれば、エージェントの定義時ではなく実行時に設定するものもあります。

SDK の概念OpenAI のガイド関連する場面
outputTypeStructured Outputsエージェントからテキストではなく、型付きの JSON やスキーマ検証済みのオブジェクトを返したい場合。
tools / 組み込みツール(Hosted)ツールガイドモデルに検索、情報取得、コード実行、独自の関数やツールの呼び出しを行わせたい場合。
conversationId / previousResponseId会話の状態OpenAI に会話の状態を永続化させたり、ターン間でつなげたりしたい場合。

conversationId と previousResponseId は実行時の制御項目であり、Agent コンストラクターのフィールドではありません。これらの SDK エントリーポイントが必要な場合は、エージェントの実行を参照してください。


エージェントがより大きなワークフローに参加する際によく使われる SDK のエントリーポイントは、次の 2 つです。

  1. マネージャー(agents as tools) – 中央のエージェントが会話を管理し、ツールとして公開された専門エージェントを呼び出します。
  2. ハンドオフ – 最初のエージェントがユーザーのリクエストを特定すると、会話全体を専門エージェントに委譲します。

これらのアプローチは相互補完的です。マネージャーでは、ガードレールやレート制限を一か所で適用できます。一方、ハンドオフでは、会話の制御を保持し続けることなく、各エージェントが単一のタスクに集中できます。設計上のトレードオフと各パターンを選ぶタイミングについては、エージェントオーケストレーションを参照してください。

このパターンでは、マネージャーが制御を渡すことはありません。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.',
}),
],
});

ハンドオフでは、トリアージエージェントがリクエストを振り分けますが、ハンドオフが発生すると、専門エージェントが最終出力を生成するまで会話を管理します。これによりプロンプトを短く保ち、各エージェントについて個別に検討できます。詳しくは、ハンドオフを参照してください。

ハンドオフを持つエージェント
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],
});

ハンドオフ先が異なる出力型を返す可能性がある場合は、new Agent(...) よりも Agent.create(...) を優先してください。これにより、TypeScript がハンドオフグラフ全体で取り得る finalOutput の形式のユニオン型を推論でき、handoffOutputTypeWarningEnabled で制御される実行時警告も回避できます。一連の処理を示す例については、エージェントの実行結果を参照してください。


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 関数の両方がサポートされています。


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 関数の両方がサポートされています。


高度なユースケースでは、イベントをリッスンすることでエージェントのライフサイクルを監視できます。

Agent インスタンスは、そのエージェントインスタンス固有のライフサイクルイベントを発行します。一方、Runner は同じイベント名のイベントを、実行全体にわたる単一のストリームとして発行します。これは、ハンドオフやツール呼び出しを一か所で監視したいマルチエージェントワークフローで便利です。

共通のイベント名は次のとおりです。

イベント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);
});

ガードレールを使用すると、ユーザー入力とエージェント出力を検証または変換できます。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.',
});

clone() は、tools、handoffs、mcpServers、inputGuardrails、outputGuardrails などのリスト型プロパティをコピーしません。クローンの設定でこれらのプロパティを省略すると、元のエージェントとクローンは同じ配列を共有するため、どちらかのエージェントを通じて配列を変更すると、両方のエージェントに影響します。クローンに独自の配列を持たせるには、tools: [...agent.tools, extraTool] のように新しい配列を渡してください。ただし、新しい配列内の要素は、引き続き同じツールやハンドオフのオブジェクトです。リスト型プロパティに undefined を渡した場合は、そのプロパティを指定したものと見なされ、元の配列を継承せず、空のリストとして初期化されます。


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

  1. 'auto'(デフォルト)– LLM がツールを使用するかどうかを判断します。
  2. 'required' – LLM は 必ず ツールを呼び出します(どのツールを呼び出すかは選択できます)。
  3. 'none' – LLM はツールを 呼び出してはいけません 。
  4. '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 ヘルパーを名前で指定して強制することを拒否します。ツール検索の設定全体については、ツールを参照してください。

ツール呼び出し後、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)の結果は、常にモデルに返されて処理されます。