コンテンツにスキップ

エージェント

エージェントは OpenAI Agents SDK の主要な構成要素です。Agent は、次の要素で設定された Large Language Model (LLM) です:

  • Instructions – モデルに 自分が何者かどう応答すべきか を伝えるシステムプロンプト
  • Model – 呼び出す OpenAI モデルと、任意のモデル調整パラメーター
  • Tools – タスク達成のために LLM が呼び出せる関数や API のリスト
Basic Agent definition
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 機能をより詳しく説明します。


Agent コンストラクターは単一の設定オブジェクトを受け取ります。最もよく使われるプロパティは次のとおりです。

プロパティ必須説明
nameyes人が読める短い識別子
instructionsyesシステムプロンプト(文字列 or 関数 - 動的 Instructions を参照)
promptnoOpenAI Responses API のプロンプト設定。静的なプロンプトオブジェクトまたは関数を受け取ります。Prompt を参照
handoffDescriptionnoこのエージェントをハンドオフツールとして提示する際に使う短い説明
handoffsno会話を専門エージェントへ委譲します。構成パターンハンドオフガイド を参照
modelnoモデル名 or カスタム Model 実装
modelSettingsno調整パラメーター(temperature、top_p など)。モデル を参照。必要なプロパティがトップレベルにない場合は providerData 配下に含められます
toolsnoモデルが呼び出せる Tool インスタンスの配列。ツール を参照
mcpServersnoエージェント向けの MCP ベースツール。MCP 連携ガイド を参照
inputGuardrailsnoこのエージェントチェーンの最初のユーザー入力に適用されるガードレール。ガードレール を参照
outputGuardrailsnoこのエージェントの最終出力に適用されるガードレール。ガードレール を参照
outputTypenoプレーンテキストではなく構造化出力を返します。出力タイプエージェントの実行結果 を参照
toolUseBehaviorno関数ツールの結果をモデルにループバックするか、実行を終了するかを制御します。ツール使用の強制 を参照
resetToolChoicenoツール呼び出し後に toolChoice をデフォルトにリセットします(既定: true)。ツール使用ループの防止に役立ちます。ツール使用の強制 を参照
handoffOutputTypeWarningEnablednoハンドオフ間で出力タイプが異なる場合に警告を出します(既定: true)。エージェントの実行結果 を参照
Agent with tools
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() に渡します。これはすべてのツール、ガードレール、ハンドオフなどに渡され、状態保存や共有サービス(データベース接続、ユーザーメタデータ、機能フラグなど)の提供に役立ちます。

Agent with context
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 () => [] },
});

デフォルトでは Agent は プレーンテキストstring)を返します。モデルに構造化オブジェクトを返させたい場合は、outputType プロパティを指定できます。SDK は次を受け付けます。

  1. Zod スキーマ(z.object({...})
  2. JSON schema 互換の任意オブジェクト
Structured output with 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 toolsTools guideモデルで検索、取得、コード実行、または独自関数/ツール呼び出しを行う場合
conversationId / previousResponseIdConversation stateターン間の会話状態を OpenAI 側に永続化または連結したい場合

conversationIdpreviousResponseId は実行時の制御であり、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.',
}),
],
});

ハンドオフではトリアージエージェントがリクエストを振り分けますが、ハンドオフが発生すると専門エージェントが最終出力を生成するまで会話を担当します。これによりプロンプトを短く保て、各エージェントを独立して考えやすくなります。詳しくは ハンドオフガイド を参照してください。

Agent with handoffs
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 形状の union を推論でき、handoffOutputTypeWarningEnabled で制御される実行時警告も回避できます。エンドツーエンドの例は エージェントの実行結果ガイド を参照してください。


instructions には文字列ではなく 関数 を指定できます。この関数は現在の RunContext と Agent インスタンスを受け取り、文字列 または Promise<string> を返せます。

Agent with dynamic 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 と同じコールバック形式をサポートしますが、文字列ではなくプロンプト設定オブジェクトを返します。プロンプト ID、バージョン、変数が現在の実行コンテキストに依存する場合に有用です。

Agent with dynamic 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 のライフサイクルを観測できます。

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

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

EventAgent hook argumentsRunner 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 })
Agent with lifecycle hooks
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 配列で設定します。詳細は ガードレールガイド を参照してください。


既存エージェントを少し変更した版が必要ですか?clone() メソッドを使うと、まったく新しい Agent インスタンスを返します。

Cloning Agents
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 の組み込みコンピュータツールを強制します。SDK は古い連携向けに preview 互換のコンピュータセレクターも受け付けますが、新規コードでは 'computer' を推奨します。コンピュータツールが利用できない場合、この文字列は他の関数ツール名と同様に振る舞います。

Forcing tool use
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() のような deferred Responses ツール、deferLoading: true の関数ツール、または deferLoading: true の hosted MCP ツールを使う場合は、modelSettings.toolChoice'auto' のままにしてください。これらの定義をいつ読み込むかはモデルが判断する必要があるため、SDK は deferred ツールや組み込み 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 が適用されるのは function tools のみです。Hosted tools は常に処理のためモデルに戻されます。