ツール
ツールを使うと、エージェントは アクションを実行 できます。データの取得、外部 API の呼び出し、コードの実行、さらにはコンピューターの操作まで可能です。JavaScript/TypeScript SDK は 7 つのカテゴリーをサポートしています:
どのエージェントがタスクを担当すべきかが分かり、そのエージェントに機能を与えたい場合は、エージェントを読んだ後にこのページを読んでください。委譲パターンをまだ検討している場合は、エージェントオーケストレーションを参照してください。
- OpenAI がホストするツール – OpenAI サーバー上でモデルと並行して実行されます。(Web 検索、ファイル検索、Code Interpreter、画像生成、ツール検索)
- 組み込み実行ツール – モデルの外部で実行される、SDK が提供するツールです。(コンピュータ操作と apply_patch はローカルで実行されます。shell はローカルまたはホスト型コンテナーで実行できます)
- 関数ツール – 任意のローカル関数を JSON スキーマでラップし、LLM から呼び出せるようにします。
- Agents as tools – エージェント全体を呼び出し可能なツールとして公開します。
- MCP サーバー – Model Context Protocol サーバー(ローカルまたはリモート)を接続します。
- サンドボックス機能 – ワークスペーススコープの shell、filesystem、skills、memory、または compaction ツールを
SandboxAgentに接続します。 - 実験的: Codex ツール – Codex SDK を関数ツールとしてラップし、ワークスペースを認識するタスクを実行します。
ツールのカテゴリー
Section titled “ツールのカテゴリー”このガイドの残りでは、まず各ツールカテゴリーを説明し、その後、ツール選択とプロンプトに関する横断的な指針をまとめます。
1. 組み込みツール(Hosted)(OpenAI Responses API)
Section titled “1. 組み込みツール(Hosted)(OpenAI Responses API)”OpenAIResponsesModel を使用する場合、次の組み込みツールを追加できます:
| ツール | 型文字列 | 目的 |
|---|---|---|
| Web 検索 | 'web_search' | インターネット検索 |
| ファイル / 取得検索 | 'file_search' | OpenAI 上でホストされているベクトルストアへのクエリ |
| Code Interpreter | 'code_interpreter' | サンドボックス環境でコードを実行 |
| 画像生成 | 'image_generation' | テキストに基づく画像生成 |
| ツール検索 | 'tool_search' | 遅延読み込みされる関数ツール、名前空間、または検索可能な MCP ツールを実行時に読み込み |
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 は、組み込みツール(Hosted)の定義を返すヘルパー関数を提供しています:
| ヘルパー関数 | 備考 |
|---|---|
webSearchTool(options?) | searchContextSize、userLocation、filters.allowedDomains など、JS で扱いやすいオプション |
fileSearchTool(ids, options?) | 第 1 引数として 1 つ以上のベクトルストア ID を受け取り、maxNumResults、includeSearchResults、rankingOptions、フィルターなどのオプションも受け取ります |
codeInterpreterTool(options?) | container が指定されていない場合は、自動管理コンテナーがデフォルトになります |
imageGenerationTool(options?) | model、size、quality、background、inputFidelity、inputImageMask、moderation、outputCompression、partialImages、出力形式などの画像生成設定をサポートします |
toolSearchTool(options?) | 組み込みの tool_search ヘルパーを追加します。deferLoading: true を設定した遅延読み込み関数ツールまたはリモート MCP サーバーツールと組み合わせます。デフォルトのホスト型実行、または execution: 'client' と execute によるクライアント実行をサポートします |
これらのヘルパーは、JavaScript/TypeScript で扱いやすいオプション名を、基盤となる OpenAI Responses API のツールペイロードにマッピングします。完全なツールスキーマと、ランキングオプションやセマンティックフィルターなどの高度なオプションについては、公式の OpenAI ツールガイドを参照してください。また、現在の組み込みツール検索フローとモデルの利用可否については、公式のツール検索ガイドを参照してください。
2. 組み込み実行ツール
Section titled “2. 組み込み実行ツール”これらのツールは SDK に組み込まれていますが、実行はモデル応答そのものの外部で行われます:
- コンピュータ操作 –
Computerインターフェイスを実装し、computerTool()に渡します。これは、必ずユーザーが提供するローカルのComputer実装に対して実行されます。 - Shell – ローカルの
Shell実装を提供するか、shellTool({ environment })でホスト型コンテナー環境を設定します。 - Apply patch –
Editorインターフェイスを実装し、applyPatchTool()に渡します。これは、必ずユーザーが提供するローカルのEditor実装に対して実行されます。 - サンドボックスの shell および filesystem ツール – これらのアクションをサンドボックスワークスペース内で実行すべき場合は、
SandboxAgentでshell()、filesystem()、skills()、memory()、またはcompaction()を使用します。
ツール呼び出し自体は引き続きモデルがリクエストしますが、処理はアプリケーションまたは設定された実行環境が行います。
サンドボックス機能ツールは、プロセス全体の組み込みツールとは異なります。これらは、現在の SandboxAgent 実行におけるライブのサンドボックスセッションに紐づきます。ツールがアプリケーションプロセスではなく、エージェントの分離されたワークスペース上で動作すべき場合は、クイックスタートを使用してください。
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', model: 'gpt-5.4', tools: [ computerTool({ computer }), shellTool({ shell, needsApproval: true }), applyPatchTool({ editor, needsApproval: true }), ],});Computer ツールの詳細
Section titled “Computer ツールの詳細”computerTool() は次のいずれかを受け取ります:
- 具象的な
Computerインスタンス - 実行ごとに
Computerを作成する初期化関数 - 実行スコープのセットアップとティアダウンが必要な場合の
{ create, dispose }を持つプロバイダーオブジェクト
OpenAI の現在のコンピュータ操作パスを使用するには、gpt-5.4 などのコンピュータ操作対応モデルを設定してください。リクエストモデルが明示されている場合、SDK は GA の組み込み computer ツール形状を送信します。実効モデルが保存済みプロンプトや他の古い連携からまだ来ている場合、modelSettings.toolChoice: 'computer' で GA パスを明示的に選択しない限り、SDK は互換性のためにレガシーの computer_use_preview ワイヤー形状を維持します。
GA の computer 呼び出しでは、1 つの computer_call にバッチ化された actions[] を含めることができます。SDK はそれらを順に実行し、各アクションに対して needsApproval を評価し、最後のスクリーンショットをツール出力として返します。interruption.rawItem から承認 UI を構築する場合は、存在する場合は actions を読み取り、レガシープレビュー項目では action にフォールバックしてください。
影響の大きいコンピューターアクションでユーザーレビューのために一時停止すべき場合は needsApproval を使用し、computer 呼び出しに対して報告された保留中の安全性チェックを承認または拒否したい場合は onSafetyCheck を使用します。モデル側のガイダンスと移行の詳細については、公式の OpenAI コンピュータ操作ガイドとその移行ノートを参照してください。
Shell ツールの詳細
Section titled “Shell ツールの詳細”shellTool() には 2 つのモードがあります:
- ローカルモード:
shellを提供し、必要に応じてenvironment: { type: 'local', skills }、および自動承認処理のためのneedsApprovalとonApprovalを提供します。 - ホスト型コンテナーモード:
type: 'container_auto'またはtype: 'container_reference'を持つenvironmentを提供します。
ローカルモードでは、environment.skills により、name、description、ファイルシステム上の path でローカルスキルをマウントできます。
ホスト型コンテナーモードでは、次のいずれかを使って shellTool({ environment }) を設定します:
- 実行用の管理コンテナーを作成する
type: 'container_auto' containerIdで既存のコンテナーを再利用するtype: 'container_reference'
ホスト型の container_auto 環境は次をサポートします:
domainSecretsを含む許可リストなどのnetworkPolicy- アップロード済みファイルをマウントするための
fileIds - コンテナーサイズ指定のための
memoryLimit skill_referenceまたはインライン zip バンドルによるskills
ホスト型 shell 環境では、shell、needsApproval、onApproval は受け付けません。実行はローカルプロセスではなく、ホスト型コンテナー環境で行われるためです。
エンドツーエンドの使用方法については、examples/tools/local-shell.ts、examples/tools/container-shell-skill-ref.ts、examples/tools/container-shell-inline-skill.ts を参照してください。
Apply-patch ツールの詳細
Section titled “Apply-patch ツールの詳細”applyPatchTool() は、shellTool() のローカル承認フローを反映しています。ファイル編集の前に一時停止するには needsApproval を使用し、アプリレベルのコールバックで自動承認または拒否したい場合は onApproval を使用します。
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 |
customDataExtractor | いいえ | 発行される RunToolCallOutputItem.customData に SDK 専用メタデータを添付するためのコールバック (context) => Record<string, unknown> | null | undefined。このデータはモデルに送り返されません |
needsApproval | いいえ | 実行前に人間の承認を要求します。人間の介入(HITL)を参照してください |
isEnabled | いいえ | 実行ごとにツールを条件付きで公開します。boolean または述語を受け取ります |
inputGuardrails | いいえ | ツール実行前に動作するガードレールです。拒否または例外を投げることができます。ガードレールを参照してください |
outputGuardrails | いいえ | ツール実行後に動作するガードレールです。拒否または例外を投げることができます。ガードレールを参照してください |
SDK 専用のカスタムデータ
Section titled “SDK 専用のカスタムデータ”ツール結果にレンダラーのヒント、内部 ID、その他の JSON 互換メタデータを添付する必要がある場合は、customDataExtractor を使用します。このコールバックは、実行コンテキスト、ツール定義、モデルのツール呼び出し、解析済み入力、出力、クローンされた元の出力項目を受け取ります。返されたデータは RunToolCallOutputItem.customData と RunState に保存されますが、history とモデルのリプレイからは除外されます。
関数ツールのタイムアウト
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; },});ツール検索による遅延ツール読み込み
Section titled “ツール検索による遅延ツール読み込み”ツール検索を使うと、すべてのスキーマを事前に送信するのではなく、モデルが実行時に必要なツール定義だけを読み込めます。SDK では、遅延読み込みされるトップレベルの関数ツール、toolNamespace() グループ、deferLoading: true が設定されたリモート MCP サーバーツールを扱う方法がこれにあたります。
ツール検索は、Responses API でサポートされる GPT-5.4 以降のモデルリリースでのみ使用してください。
import { Agent, tool, toolNamespace, toolSearchTool } from '@openai/agents';import { z } from 'zod';
const customerIdParams = z.object({ customerId: z.string().describe('The customer identifier to look up.'),});
// Keep a standalone deferred tool at the top level when it represents a// single searchable capability that does not need a shared namespace.const shippingLookup = tool({ name: 'get_shipping_eta', description: 'Look up a shipment ETA by customer identifier.', parameters: customerIdParams, deferLoading: true, async execute({ customerId }) { return { customerId, eta: '2026-03-07', carrier: 'Priority Express', }; },});
// Group related tools into a namespace when one domain description should// cover several deferred tools and let tool search load them together.const crmTools = toolNamespace({ name: 'crm', description: 'CRM tools for customer profile lookups.', tools: [ tool({ name: 'get_customer_profile', description: 'Fetch a basic customer profile.', parameters: customerIdParams, deferLoading: true, async execute({ customerId }) { return { customerId, tier: 'enterprise', }; }, }), ],});
const agent = new Agent({ name: 'Operations assistant', model: 'gpt-5.4', // Mixing namespaced and top-level deferred tools in one request is supported. tools: [shippingLookup, ...crmTools, toolSearchTool()],});この例では、意図的に両方のスタイルを混在させています:
shippingLookupは単独の検索可能な機能であるため、トップレベルのままにしています。crmToolsは、関連する CRM ツールが 1 つの高レベルなラベルと説明を共有するため、toolNamespace()を使用します。- 同じリクエスト内で、名前空間化された遅延ツールとトップレベルの遅延ツールを混在させることがサポートされています。ツール検索は、
crmのような名前空間パスと、get_shipping_etaのようなトップレベルパスの両方を読み込めます。
ツール検索を使用する場合:
- 各遅延読み込み関数ツールに
deferLoading: trueを設定します。 - 複数の関連ツールが 1 つのドメイン説明を共有し、グループとして読み込まれるべき場合は、
toolNamespace({ name, description, tools })を使用します。 - それが単一の独立した機能であり、ツール名自体が良い検索対象である場合は、ツールをトップレベルのままにします。
- 遅延読み込み関数ツールまたはリモート MCP サーバーツールが
deferLoading: trueを使用する場合は、必ず同じtools配列にtoolSearchTool()を追加します。 modelSettings.toolChoiceは'auto'のままにします。SDK は、組み込みのtool_searchツールや遅延読み込み関数ツールを名前で強制指定することを拒否します。- ホスト型実行がデフォルトです。
toolSearchTool({ execution: 'client', execute })を設定した場合、標準のrun()ループは組み込みの{ paths: string[] }クライアントクエリ形状のみをサポートします。カスタムのクライアント側スキーマには、独自の Responses ループが必要です。 - 名前空間では、即時メンバーと遅延メンバーを混在させることができます。即時メンバーはツール検索なしで呼び出し可能なままで、同じ名前空間内の遅延メンバーは必要に応じて読み込まれます。
- 遅延読み込み関数ツールと
toolNamespace()は Responses 専用です。Chat Completions はそれらを拒否し、AI SDK アダプターは Responses の遅延ツール読み込みフローをサポートしません。
4. Agents as tools
Section titled “4. Agents as tools”会話を完全にハンドオフせずに、あるエージェントに別のエージェントを 支援 させたい場合があります。その場合は agent.asTool() を使用します:
agent.asTool() と handoff() のどちらを選ぶかまだ検討している場合は、エージェントとエージェントオーケストレーションでパターンを比較してください。
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 はデフォルト設定の runner を作成し、関数実行の中でその runner を使ってエージェントを実行します。runConfig または runOptions のプロパティを指定したい場合は、それらを asTool() メソッドに渡して runner の挙動をカスタマイズできます。
asTool() オプションを通じてエージェントツールに needsApproval と isEnabled を設定し、Human in the loop (人間の介入) フローや条件付きツール利用と統合することもできます。
customOutputExtractor の中では、現在の Agent.asTool() 呼び出しを調べるために result.agentToolInvocation を使用します。このコールバックでは結果は常に Agent.asTool() から来るため、agentToolInvocation は常に定義され、toolName、toolCallId、toolArguments を公開します。通常のアプリコンテキストと toolInput には result.runContext を使用します。このメタデータは現在のネストされた呼び出しにスコープされ、RunState にはシリアライズされません。
import { Agent } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing Agent', instructions: 'Handle billing questions and subscription changes.',});
const billingTool = billingAgent.asTool({ toolName: 'billing_agent', toolDescription: 'Handles customer billing questions.', customOutputExtractor(result) { console.log('tool', result.agentToolInvocation.toolName); // Direct invoke() calls may not have a model-generated tool call id. console.log('call', result.agentToolInvocation.toolCallId); console.log('args', result.agentToolInvocation.toolArguments);
return String(result.finalOutput ?? ''); },});
const orchestrator = new Agent({ name: 'Support Orchestrator', instructions: 'Delegate billing questions to the billing agent tool.', tools: [billingTool],});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(...)ハンドラーを提供すると、agent-as-tool は自動的にストリーミングモードで実行されます。提供しない場合は非ストリーミングのパスのままです。- ハンドラーは並列に呼び出されるため、遅い
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: 'pnpm exec mcp-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 にルーティングする関数ツールで、エージェントがワークスペーススコープのタスク(シェル、ファイル編集、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.4', networkAccessEnabled: true, webSearchEnabled: false, }, }), ],});知っておくべきこと:
- 認証:
CODEX_API_KEY(推奨)またはOPENAI_API_KEYを指定するか、codexOptions.apiKeyを渡します。 - 入力: strict スキーマです。
inputsには少なくとも 1 つの{ type: 'text', text }または{ type: 'local_image', path }を含める必要があります。 - 安全性:
sandboxModeはworkingDirectoryと組み合わせます。ディレクトリが Git リポジトリでない場合はskipGitRepoCheckを設定します。 - スレッド:
useRunContextThreadId: trueは最新のスレッド ID をrunContext.contextから読み取り、そこへ保存します。これはアプリ状態でターンをまたいで再利用する場合に便利です。 - スレッド ID の優先順位: ツール呼び出しの
threadId(スキーマに含まれている場合)が最優先で、その次に実行コンテキストのスレッド 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には descriptor、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.4', 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;ツール戦略とベストプラクティス
Section titled “ツール戦略とベストプラクティス”ツール使用の挙動
Section titled “ツール使用の挙動”モデルがいつ、どのようにツールを使用すべきか(modelSettings.toolChoice、toolUseBehavior など)を制御する方法については、エージェントを参照してください。
ベストプラクティス
Section titled “ベストプラクティス”- 短く明示的な説明 – ツールが 何を行うか と いつ使うべきか を説明します。
- 入力の検証 – 可能な場合は Zod スキーマを使用して厳密な JSON 検証を行います。
- エラーハンドラーでの副作用の回避 –
errorFunctionは例外を投げるのではなく、役立つ文字列を返すべきです。 - ツールごとに 1 つの責務 – 小さく組み合わせ可能なツールは、モデルの推論を向上させます。