ツール
ツールはエージェントにアクションを実行させます。データの取得、外部 API の呼び出し、コードの実行、さらにはコンピュータの使用まで可能です。JavaScript / TypeScript SDK は次の 6 つのカテゴリーをサポートします。
- OpenAI がホストするツール – モデルと同一の OpenAI サーバー上で実行されます。(Web 検索、ファイル検索、Code Interpreter、画像生成)
- ローカル組み込みツール – あなたの環境で実行されます。(コンピュータ操作、shell、apply_patch)
- 関数ツール – 任意のローカル関数を JSON スキーマでラップし、LLM が呼び出せるようにします。
- Agents as tools – エージェント全体を呼び出し可能なツールとして公開します。
- MCP サーバー – Model Context Protocol サーバー(ローカルまたはリモート)を接続します。
- 実験的: Codex ツール – Codex SDK を関数ツールとしてラップし、ワークスペース対応タスクを実行します。
ツールのカテゴリー
Section titled “ツールのカテゴリー”このガイドの残りでは、まず各ツールカテゴリーを説明し、その後で横断的なツール選定とプロンプト設計の指針をまとめます。
1. Hosted tools (OpenAI Responses API)
Section titled “1. Hosted tools (OpenAI Responses API)”OpenAIResponsesModel を使うと、次の組み込みツールを追加できます。
| ツール | 型文字列 | 目的 |
|---|---|---|
| Web 検索 | 'web_search' | インターネット検索 |
| ファイル / 取得検索 | 'file_search' | OpenAI 上でホストされるベクトルストアのクエリ |
| Code Interpreter | 'code_interpreter' | サンドボックス環境でコードを実行 |
| 画像生成 | 'image_generation' | テキストに基づく画像の生成 |
import { Agent, codeInterpreterTool, fileSearchTool, imageGenerationTool, webSearchTool,} from '@openai/agents';
const agent = new Agent({ name: 'Travel assistant', tools: [ webSearchTool({ searchContextSize: 'medium' }), fileSearchTool('VS_ID', { maxNumResults: 3 }), codeInterpreterTool(), imageGenerationTool({ size: '1024x1024' }), ],});SDK は、ホスト型ツール定義を返すヘルパー関数を提供します。
| ヘルパー関数 | メモ |
|---|---|
webSearchTool(options?) | searchContextSize、userLocation、filters.allowedDomains などの JS フレンドリーなオプションに対応 |
fileSearchTool(ids, options?) | 最初の引数として 1 つ以上のベクトルストア ID を受け取り、maxNumResults、includeSearchResults、rankingOptions、各種フィルターなどのオプションを指定可能 |
codeInterpreterTool(options?) | container を指定しない場合は自動管理コンテナがデフォルト |
imageGenerationTool(options?) | model、size、quality、background、inputFidelity、inputImageMask、moderation、outputCompression、partialImages、および出力形式など、画像生成の設定をサポート |
これらのヘルパーは、JavaScript / TypeScript に適したオプション名を OpenAI Responses API のツールペイロードにマッピングします。完全なツールスキーマやランキングオプション、セマンティックフィルターなどの高度なオプションについては、OpenAI の公式ドキュメントを参照してください。
2. ローカル組み込みツール
Section titled “2. ローカル組み込みツール”ローカル組み込みツールはあなたの環境で実行され、実装の提供が必要です。
- コンピュータ操作 –
Computerインターフェースを実装してcomputerTool()に渡す - Shell – ローカルの
Shell実装を提供するか、ホスト型コンテナ環境を構成する - Apply patch –
Editorインターフェースを実装してapplyPatchTool()に渡す
Computer と apply‑patch ツールはローカルで実行され、OpenAI によってホストされるわけではありません。Shell ツールは、shellTool() の構成に応じてローカルまたはホスト型コンテナ環境で実行できます。
ツール呼び出し自体はモデルのレスポンスによって要求されますが、呼び出しの実行方法はあなたのアプリケーションが制御します。
import { Agent, applyPatchTool, computerTool, shellTool, Computer, Editor, Shell,} from '@openai/agents';
const computer: Computer = { environment: 'browser', dimensions: [1024, 768], screenshot: async () => '', click: async () => {}, doubleClick: async () => {}, scroll: async () => {}, type: async () => {}, wait: async () => {}, move: async () => {}, keypress: async () => {}, drag: async () => {},};
const shell: Shell = { run: async () => ({ output: [ { stdout: '', stderr: '', outcome: { type: 'exit', exitCode: 0 }, }, ], }),};
const editor: Editor = { createFile: async () => ({ status: 'completed' }), updateFile: async () => ({ status: 'completed' }), deleteFile: async () => ({ status: 'completed' }),};
const agent = new Agent({ name: 'Local tools agent', tools: [ computerTool({ computer }), shellTool({ shell, needsApproval: true }), applyPatchTool({ editor, needsApproval: true }), ],});
void agent;ホスト型 shell 環境では、shellTool({ environment }) を次のいずれかで構成します。
type: 'container_auto'実行ごとに管理コンテナを作成(ネットワークポリシー、メモリ制限、スキルに対応)type: 'container_reference'既存のコンテナをcontainerIdで再利用
エンドツーエンドの使用例は examples/tools/container-shell-skill-ref.ts と examples/tools/container-shell-inline-skill.ts を参照してください。
3. 関数ツール
Section titled “3. 関数ツール”tool() ヘルパーを使うと、任意の関数をツールにできます。
import { tool } from '@openai/agents';import { z } from 'zod';
const getWeatherTool = tool({ name: 'get_weather', description: 'Get the weather for a given city', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});オプションリファレンス
Section titled “オプションリファレンス”| フィールド | 必須 | 説明 |
|---|---|---|
name | いいえ | 関数名(例: get_weather)がデフォルト |
description | はい | LLM に提示する、明確で人間が読める説明 |
parameters | はい | Zod スキーマまたは元の JSON スキーマオブジェクトのいずれか。Zod のパラメーターは自動的に strict モードを有効化 |
strict | いいえ | true(デフォルト)の場合、引数が検証に失敗すると SDK はモデルエラーを返す。あいまいな一致を許すには false に設定 |
execute | はい | (args, context, details) => string | unknown | Promise<...> – ビジネスロジック。文字列以外の出力はモデル向けにシリアライズ。context は任意の RunContext、details には toolCall、resumeState、signal などのメタデータを含む |
errorFunction | いいえ | 内部エラーをユーザー向けの文字列に変換するカスタムハンドラー (context, error) => string |
timeoutMs | いいえ | 呼び出し単位のタイムアウト(ミリ秒)。0 より大きく 2147483647 以下である必要あり |
timeoutBehavior | いいえ | タイムアウト時の動作: デフォルトの error_as_result はモデル向けのタイムアウトメッセージを返し、raise_exception は ToolTimeoutError を送出 |
timeoutErrorFunction | いいえ | timeoutBehavior が error_as_result のときのタイムアウト出力をカスタマイズするハンドラー (context, timeoutError) => string |
needsApproval | いいえ | 実行前に人間の承認を必須にする。詳しくは 人間の介入(HITL) を参照 |
isEnabled | いいえ | 実行ごとに条件付きでツールを公開。真偽値または述語を受け付ける |
inputGuardrails | いいえ | 実行前に走るガードレール。拒否や例外送出が可能。詳細は ガードレール を参照 |
outputGuardrails | いいえ | 実行後に走るガードレール。拒否や例外送出が可能。詳細は ガードレール を参照 |
関数ツールのタイムアウト
Section titled “関数ツールのタイムアウト”各関数ツール呼び出しの上限を設定するには timeoutMs を使用します。
timeoutBehavior: 'error_as_result'(デフォルト)はモデルにTool '<name>' timed out after <timeoutMs>ms.を返すtimeoutBehavior: 'raise_exception'はToolTimeoutErrorを送出し、実行時の例外 の一部として捕捉可能timeoutErrorFunctionにより、error_as_resultモードでのタイムアウト文言をカスタマイズ可能- タイムアウトは
details.signalを中断するため、長時間実行のツールもキャンセル待受で速やかに停止可能
関数ツールを直接呼び出す場合は、通常のエージェント実行と同じタイムアウト動作を強制するために invokeFunctionTool を使用してください。
非 strict な JSON スキーマツール
Section titled “非 strict な JSON スキーマツール”無効または不完全な入力をモデルに推測させる必要がある場合は、元の JSON スキーマ使用時に strict モードを無効化できます。
import { tool } from '@openai/agents';
interface LooseToolInput { text: string;}
const looseTool = tool({ description: 'Echo input; be forgiving about typos', strict: false, parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: true, }, execute: async (input) => { // because strict is false we need to do our own verification if (typeof input !== 'object' || input === null || !('text' in input)) { return 'Invalid input. Please try again'; } return (input as LooseToolInput).text; },});4. Agents as tools
Section titled “4. Agents as tools”会話を完全に引き継がずに、あるエージェントに別のエージェントを補助させたい場合があります。agent.asTool() を使用します。
import { Agent } from '@openai/agents';
const summarizer = new Agent({ name: 'Summarizer', instructions: 'Generate a concise summary of the supplied text.',});
const summarizerTool = summarizer.asTool({ toolName: 'summarize_text', toolDescription: 'Generate a concise summary of the supplied text.',});
const mainAgent = new Agent({ name: 'Research assistant', tools: [summarizerTool],});内部的に SDK は次を行います。
- 単一の
inputパラメーターを持つ関数ツールを作成 - ツール呼び出し時にサブエージェントをその入力で実行
- 最後のメッセージ、または
customOutputExtractorで抽出した出力を返す
エージェントをツールとして実行すると、Agents SDK はデフォルト設定でランナーを作成し、関数実行内でそのエージェントを実行します。runConfig や runOptions の任意のプロパティを指定したい場合は、asTool() に渡してランナーの動作をカスタマイズできます。
また、asTool() のオプションでエージェントツールに needsApproval と isEnabled を設定し、Human in the loop (人間の介入) のフローやツールの条件付き有効化に統合できます。
agent.asTool() の高度な構造化入力オプション:
inputBuilder: 構造化ツール引数を入れ子のエージェント入力ペイロードへマッピングincludeInputSchema: 入れ子の実行に入力 JSON スキーマを含め、スキーマ認識を強化resumeState: シリアライズされた入れ子のRunStateを再開する際のコンテキスト整合戦略を制御。'merge'(デフォルト)はライブの承認 / コンテキスト状態をシリアライズ状態にマージ、'replace'は現在の実行コンテキストを使用、'preferSerialized'はシリアライズ済みコンテキストを変更せずに再開
エージェントツールからのストリーミングイベント
Section titled “エージェントツールからのストリーミングイベント”エージェントツールは入れ子の全実行イベントをアプリへストリーミングできます。ツールの組み立て方に合うフックスタイルを選びます。
import { Agent } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing Agent', instructions: 'Answer billing questions and compute simple charges.',});
const billingTool = billingAgent.asTool({ toolName: 'billing_agent', toolDescription: 'Handles customer billing questions.', // onStream: simplest catch-all when you define the tool inline. onStream: (event) => { console.log(`[onStream] ${event.event.type}`, event); },});
// on(eventName) lets you subscribe selectively (or use '*' for all).billingTool.on('run_item_stream_event', (event) => { console.log('[on run_item_stream_event]', event);});billingTool.on('raw_model_stream_event', (event) => { console.log('[on raw_model_stream_event]', event);});
const orchestrator = new Agent({ name: 'Support Orchestrator', instructions: 'Delegate billing questions to the billing agent tool.', tools: [billingTool],});- イベント型は
RunStreamEvent['type']に一致:raw_model_stream_event、run_item_stream_event、agent_updated_stream_event onStreamは最も簡単な「総受け」で、ツールをインラインで宣言する場合(tools: [agent.asTool({ onStream })])に適している。個別のイベント振り分けが不要な場合に使用on(eventName, handler)は選択的に(または'*'で)購読でき、より細かい制御が必要な場合や作成後にリスナーを取り付けたい場合に最適onStreamまたはいずれかのon(...)ハンドラーを提供すると、自動的にストリーミングモードで実行。指定しない場合は非ストリーミング経路のまま- ハンドラーは並列に呼び出されるため、遅い
onStreamコールバックがon(...)ハンドラーをブロックすることはない(その逆も同様) toolCallIdは、ツールがモデルのツールコール経由で呼び出された場合に提供される。invoke()の直接呼び出しやプロバイダー依存の挙動では省略されることがある
5. MCP サーバー
Section titled “5. MCP サーバー”Model Context Protocol (MCP) サーバー経由でツールを公開し、エージェントに接続できます。
たとえば、MCPServerStdio を使って stdio MCP サーバーを起動して接続できます。
import { Agent, MCPServerStdio } from '@openai/agents';
const server = new MCPServerStdio({ fullCommand: 'npx -y @modelcontextprotocol/server-filesystem ./sample_files',});
await server.connect();
const agent = new Agent({ name: 'Assistant', mcpServers: [server],});完全な例は filesystem-example.ts を参照してください。MCP サーバーツール統合に関する総合的なガイドを探している場合は、MCP 連携 を参照してください。
複数サーバーの管理(または一部障害)時には、connectMcpServers と MCP 連携 のライフサイクル指針を使用してください。
6. 実験的: Codex ツール
Section titled “6. 実験的: Codex ツール”@openai/agents-extensions/experimental/codex は codexTool() を提供します。これは、モデルのツールコールを Codex SDK にルーティングする関数ツールで、エージェントがワークスペース範囲のタスク(shell、ファイル編集、MCP ツール)を自律的に実行できるようにします。本機能は実験的であり、変更される可能性があります。
まず依存関係をインストールします。
npm install @openai/agents-extensions @openai/codex-sdkクイックスタート:
import { Agent } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
export const codexAgent = new Agent({ name: 'Codex Agent', instructions: 'Use the codex tool to inspect the workspace and answer the question. When skill names, which usually start with `$`, are mentioned, you must rely on the codex tool to use the skill and answer the question.', tools: [ codexTool({ sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.2-codex', networkAccessEnabled: true, webSearchEnabled: false, }, }), ],});知っておくべきこと:
- 認証:
CODEX_API_KEY(推奨)またはOPENAI_API_KEYを指定、あるいはcodexOptions.apiKeyを渡す - 入力: 厳密なスキーマ —
inputsは少なくとも 1 つの{ type: 'text', text }または{ type: 'local_image', path }を含む必要がある - セーフティ:
sandboxModeをworkingDirectoryと組み合わせる。ディレクトリが Git リポジトリでない場合はskipGitRepoCheckを設定 - スレッディング:
useRunContextThreadId: trueは最新の thread id をrunContext.contextに読み書きし、アプリ状態でのターン間再利用に有用 - Thread ID の優先順位: ツールコールの
threadId(スキーマに含めた場合)が最優先、次に実行コンテキストの thread id、最後にcodexTool({ threadId }) - 実行コンテキストキー:
name: 'codex'の場合はデフォルトでcodexThreadId、name: 'engineer'のような名前ではcodexThreadId_<suffix>(正規化後はcodex_engineer) - 変更可能なコンテキスト要件:
useRunContextThreadId有効時は、run(..., { context })に変更可能なオブジェクトまたはMapを渡す - 命名: ツール名は
codex名前空間へ正規化され(engineerはcodex_engineerになる)、エージェント内での Codex ツール名の重複は拒否される - ストリーミング:
onStreamは Codex のイベント(推論、コマンド実行、MCP ツールコール、ファイル変更、Web 検索)を反映するため、進捗のログやトレースが可能 - 出力: ツール結果には
response、usage、threadIdが含まれ、Codex のトークン使用量はRunContextに記録される - 構造:
outputSchemaはディスクリプタ、JSON スキーマオブジェクト、または Zod オブジェクトを指定可能。JSON オブジェクトスキーマではadditionalPropertiesはfalseが必要
実行コンテキストのスレッド再利用例:
import { Agent, run } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
// Derived from codexTool({ name: 'engineer' }) when runContextThreadIdKey is omitted.type ExampleContext = { codexThreadId_engineer?: string;};
const agent = new Agent<ExampleContext>({ name: 'Codex assistant', instructions: 'Use the codex tool for workspace tasks.', tools: [ codexTool({ // `name` is optional for a single Codex tool. // We set it so the run-context key is tool-specific and to avoid collisions when adding more Codex tools. name: 'engineer', // Reuse the same Codex thread across runs that share this context object. useRunContextThreadId: true, sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.2-codex', approvalPolicy: 'never', }, }), ],});
// The default key for useRunContextThreadId with name=engineer is codexThreadId_engineer.const context: ExampleContext = {};
// First turn creates (or resumes) a Codex thread and stores the thread ID in context.await run(agent, 'Inspect src/tool.ts and summarize it.', { context });// Second turn reuses the same thread because it shares the same context object.await run(agent, 'Now list refactoring opportunities.', { context });
const threadId = context.codexThreadId_engineer;
void threadId;ツール戦略とベストプラクティス
Section titled “ツール戦略とベストプラクティス”ツール使用の挙動
Section titled “ツール使用の挙動”モデルがいつどのようにツールを使用すべきかの制御については、エージェント を参照してください(modelSettings.toolChoice、toolUseBehavior など)。
ベストプラクティス
Section titled “ベストプラクティス”- 短く明示的な説明 – ツールが何をするのか、いつ使うのかを記述
- 入力の検証 – 可能なら Zod スキーマで厳密な JSON 検証を行う
- エラーハンドラーで副作用を避ける –
errorFunctionは有用な文字列を返し、例外は投げない - ツールごとに単一責務 – 小さく合成しやすいツールは、モデルの推論を改善する