コンテンツにスキップ

エージェント

エージェントは OpenAI Agents SDK の主要な構成要素です。 エージェント は、次のように設定された大規模言語モデル (LLM) です。

  • Instructions – モデルに 何者であるかどのように応答すべきか を伝えるシステムプロンプト
  • モデル – 呼び出す 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はいシステムプロンプト(文字列 または 関数 – 動的 instructions を参照)
promptいいえOpenAI Responses API の prompt 設定。静的な prompt オブジェクトまたは関数を受け付けます。プロンプト を参照
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],
});

エージェントは コンテキスト型でジェネリック です。つまり 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. 任意の 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 を自動的に使用します。


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

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

一部のエージェント概念は OpenAI プラットフォームの概念に直接対応しますが、その他はエージェント定義時ではなく実行時に設定します。

SDK の概念OpenAI ガイド必要になる場面
outputTypeStructured Outputsエージェントがテキストではなく、型付き JSON または Zod で検証されたオブジェクトを返す必要がある場合
tools / 組み込みツール(Hosted)ツールガイドモデルで検索、取得、コード実行、または独自の関数 / ツール呼び出しを行う必要がある場合
conversationId / previousResponseId会話状態ターン間で会話状態を OpenAI に永続化または連鎖させたい場合

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


エージェントがより大きなワークフローに参加するとき、最もよく使われる SDK エントリーポイントは 2 つあります。

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

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

このパターンでは、マネージャーは制御を引き渡しません。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 は文字列ではなく 関数 にできます。この関数は現在の RunContextAgent インスタンスを受け取り、文字列 または Promise<string> を返せます。

動的 instructions 付きエージェント
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 関数の両方に対応しています。


promptinstructions と同じコールバック形式に対応しますが、文字列ではなく prompt 設定オブジェクトを返します。これは、プロンプト ID、バージョン、または変数が現在の実行コンテキストに依存する場合に便利です。

動的 prompt 付きエージェント
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 は実行全体をまたぐ単一のストリームとして、同じイベント名を発行します。これは、ハンドオフやツール呼び出しを 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);
});

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


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

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.',
});

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

  1. 'auto'(デフォルト)– ツールを使用するかどうかを LLM が判断します
  2. 'required' – LLM はツールを呼び出す 必要があります(どれを呼び出すかは選べます)
  3. 'none' – LLM はツールを 呼び出してはいけません
  4. 特定のツール名(例: 'calculator')– LLM はその特定のツールを呼び出す必要があります

OpenAI Responses で利用可能なツールが computerTool() の場合、toolChoice: 'computer' は特別です。'computer' を通常の関数名として扱うのではなく、GA の組み込み computer ツールを強制します。SDK は古い連携向けの preview 互換 computer セレクターも受け付けますが、新しいコードでは 'computer' を推奨します。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 のリモート MCP サーバーツールを使用する場合は、modelSettings.toolChoice'auto' のままにしてください。モデルがそれらの定義をいつロードするか判断する必要があるため、SDK は遅延ツールや組み込みの tool_search ヘルパーを名前で強制することを拒否します。完全な tool-search セットアップについては、ツール を参照してください。

ツール呼び出しの後、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 リファレンスも参照してください。