エージェント
エージェントは OpenAI Agents SDK の主要な構成要素です。 Agent は、次の設定を行った Large Language Model (LLM) です。
- Instructions – モデルに「自分は誰か」「どのように応答すべきか」を伝える system prompt
- 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-nano', // optional – falls back to the default model});このページでは、あらゆる Agent 機能を詳しく説明します。
エージェントの基本
Section titled “エージェントの基本”Agent コンストラクターは単一の設定オブジェクトを受け取ります。よく使われるプロパティは次のとおりです。
| Property | Required | Description |
|---|---|---|
name | yes | 短い人間可読の識別子 |
instructions | yes | System prompt(文字列 または 関数 – Dynamic instructions を参照) |
prompt | no | OpenAI Responses API のプロンプト設定。Prompt を参照 |
handoffDescription | no | このエージェントがハンドオフツールとして提供される際に使われる短い説明 |
model | no | モデル名 または カスタム Model 実装 |
modelSettings | no | 調整パラメーター(temperature、top_p など)。必要なプロパティがトップレベルにない場合は、providerData 配下に含めることができます |
tools | no | モデルが呼び出せる Tool インスタンスの配列 |
mcpServers | no | エージェントにツールを提供する MCP サーバー。MCP 連携 を参照 |
resetToolChoice | no | ツール呼び出し後に toolChoice をデフォルトにリセットします(デフォルト: true)。ツール使用のループを防止します。Forcing tool use を参照 |
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>)です。コンテキストは、あなたが作成して 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 を使用します。
構成パターン
Section titled “構成パターン”マルチエージェントの設計パターン
Section titled “マルチエージェントの設計パターン”エージェントを組み合わせる方法はさまざまです。プロダクション アプリでよく見られるパターンは次の 2 つです。
- Manager (agents as tools) – 中央のエージェントが会話を所有し、ツールとして公開された専門エージェントを呼び出す
- ハンドオフ – 最初のエージェントがユーザーのリクエストを特定したら、会話全体を専門家に委譲する
これらのアプローチは補完的です。マネージャー方式では、単一の場所でガードレールやレート制限を適用できます。一方、ハンドオフでは、各エージェントが会話の制御を保持せずに単一のタスクに集中できます。
Manager (agents as tools)
Section titled “Manager (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],});高度な設定と実行時制御
Section titled “高度な設定と実行時制御”Dynamic instructions
Section titled “Dynamic 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 “ライフサイクルフック”高度なユースケースでは、イベントをリッスンして 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-mini',});
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 はその特定のツールを呼び出す必要がある
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: 'auto' },});無限ループの防止
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 は function tools にのみ適用されます。組み込みツール(Hosted)は常にモデルに処理を戻します。