コンテンツにスキップ

ツール

ツールはエージェントにアクションを実行させます。データの取得、外部 API の呼び出し、コードの実行、さらにはコンピュータの使用まで可能です。JavaScript / TypeScript SDK は次の 6 つのカテゴリーをサポートします。

  1. OpenAI がホストするツール – モデルと同一の OpenAI サーバー上で実行されます。(Web 検索、ファイル検索、Code Interpreter、画像生成)
  2. ローカル組み込みツール – あなたの環境で実行されます。(コンピュータ操作、shell、apply_patch)
  3. 関数ツール – 任意のローカル関数を JSON スキーマでラップし、LLM が呼び出せるようにします。
  4. Agents as tools – エージェント全体を呼び出し可能なツールとして公開します。
  5. MCP サーバー – Model Context Protocol サーバー(ローカルまたはリモート)を接続します。
  6. 実験的: Codex ツール – Codex SDK を関数ツールとしてラップし、ワークスペース対応タスクを実行します。

このガイドの残りでは、まず各ツールカテゴリーを説明し、その後で横断的なツール選定とプロンプト設計の指針をまとめます。

OpenAIResponsesModel を使うと、次の組み込みツールを追加できます。

ツール型文字列目的
Web 検索'web_search'インターネット検索
ファイル / 取得検索'file_search'OpenAI 上でホストされるベクトルストアのクエリ
Code Interpreter'code_interpreter'サンドボックス環境でコードを実行
画像生成'image_generation'テキストに基づく画像の生成
Hosted tools
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?)searchContextSizeuserLocationfilters.allowedDomains などの JS フレンドリーなオプションに対応
fileSearchTool(ids, options?)最初の引数として 1 つ以上のベクトルストア ID を受け取り、maxNumResultsincludeSearchResultsrankingOptions、各種フィルターなどのオプションを指定可能
codeInterpreterTool(options?)container を指定しない場合は自動管理コンテナがデフォルト
imageGenerationTool(options?)modelsizequalitybackgroundinputFidelityinputImageMaskmoderationoutputCompressionpartialImages、および出力形式など、画像生成の設定をサポート

これらのヘルパーは、JavaScript / TypeScript に適したオプション名を OpenAI Responses API のツールペイロードにマッピングします。完全なツールスキーマやランキングオプション、セマンティックフィルターなどの高度なオプションについては、OpenAI の公式ドキュメントを参照してください。


ローカル組み込みツールはあなたの環境で実行され、実装の提供が必要です。

  • コンピュータ操作Computer インターフェースを実装して computerTool() に渡す
  • Shell – ローカルの Shell 実装を提供するか、ホスト型コンテナ環境を構成する
  • Apply patchEditor インターフェースを実装して applyPatchTool() に渡す

Computer と apply‑patch ツールはローカルで実行され、OpenAI によってホストされるわけではありません。Shell ツールは、shellTool() の構成に応じてローカルまたはホスト型コンテナ環境で実行できます。 ツール呼び出し自体はモデルのレスポンスによって要求されますが、呼び出しの実行方法はあなたのアプリケーションが制御します。

Local built-in tools
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.tsexamples/tools/container-shell-inline-skill.ts を参照してください。


tool() ヘルパーを使うと、任意の関数をツールにできます。

Function tool with Zod parameters
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.`;
},
});
フィールド必須説明
nameいいえ関数名(例: get_weather)がデフォルト
descriptionはいLLM に提示する、明確で人間が読める説明
parametersはいZod スキーマまたは元の JSON スキーマオブジェクトのいずれか。Zod のパラメーターは自動的に strict モードを有効化
strictいいえtrue(デフォルト)の場合、引数が検証に失敗すると SDK はモデルエラーを返す。あいまいな一致を許すには false に設定
executeはい(args, context, details) => string | unknown | Promise<...> – ビジネスロジック。文字列以外の出力はモデル向けにシリアライズ。context は任意の RunContextdetails には toolCallresumeStatesignal などのメタデータを含む
errorFunctionいいえ内部エラーをユーザー向けの文字列に変換するカスタムハンドラー (context, error) => string
timeoutMsいいえ呼び出し単位のタイムアウト(ミリ秒)。0 より大きく 2147483647 以下である必要あり
timeoutBehaviorいいえタイムアウト時の動作: デフォルトの error_as_result はモデル向けのタイムアウトメッセージを返し、raise_exceptionToolTimeoutError を送出
timeoutErrorFunctionいいえtimeoutBehaviorerror_as_result のときのタイムアウト出力をカスタマイズするハンドラー (context, timeoutError) => string
needsApprovalいいえ実行前に人間の承認を必須にする。詳しくは 人間の介入(HITL) を参照
isEnabledいいえ実行ごとに条件付きでツールを公開。真偽値または述語を受け付ける
inputGuardrailsいいえ実行前に走るガードレール。拒否や例外送出が可能。詳細は ガードレール を参照
outputGuardrailsいいえ実行後に走るガードレール。拒否や例外送出が可能。詳細は ガードレール を参照

各関数ツール呼び出しの上限を設定するには timeoutMs を使用します。

  • timeoutBehavior: 'error_as_result'(デフォルト)はモデルに Tool '<name>' timed out after <timeoutMs>ms. を返す
  • timeoutBehavior: 'raise_exception'ToolTimeoutError を送出し、実行時の例外 の一部として捕捉可能
  • timeoutErrorFunction により、error_as_result モードでのタイムアウト文言をカスタマイズ可能
  • タイムアウトは details.signal を中断するため、長時間実行のツールもキャンセル待受で速やかに停止可能

関数ツールを直接呼び出す場合は、通常のエージェント実行と同じタイムアウト動作を強制するために invokeFunctionTool を使用してください。

無効または不完全な入力をモデルに推測させる必要がある場合は、元の JSON スキーマ使用時に strict モードを無効化できます。

Non-strict JSON schema tools
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;
},
});

会話を完全に引き継がずに、あるエージェントに別のエージェントを補助させたい場合があります。agent.asTool() を使用します。

Agents as tools
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 はデフォルト設定でランナーを作成し、関数実行内でそのエージェントを実行します。runConfigrunOptions の任意のプロパティを指定したい場合は、asTool() に渡してランナーの動作をカスタマイズできます。

また、asTool() のオプションでエージェントツールに needsApprovalisEnabled を設定し、Human in the loop (人間の介入) のフローやツールの条件付き有効化に統合できます。

agent.asTool() の高度な構造化入力オプション:

  • inputBuilder: 構造化ツール引数を入れ子のエージェント入力ペイロードへマッピング
  • includeInputSchema: 入れ子の実行に入力 JSON スキーマを含め、スキーマ認識を強化
  • resumeState: シリアライズされた入れ子の RunState を再開する際のコンテキスト整合戦略を制御。'merge'(デフォルト)はライブの承認 / コンテキスト状態をシリアライズ状態にマージ、'replace' は現在の実行コンテキストを使用、'preferSerialized' はシリアライズ済みコンテキストを変更せずに再開

エージェントツールからのストリーミングイベント

Section titled “エージェントツールからのストリーミングイベント”

エージェントツールは入れ子の全実行イベントをアプリへストリーミングできます。ツールの組み立て方に合うフックスタイルを選びます。

Streaming agent tools
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_eventrun_item_stream_eventagent_updated_stream_event
  • onStream は最も簡単な「総受け」で、ツールをインラインで宣言する場合(tools: [agent.asTool({ onStream })])に適している。個別のイベント振り分けが不要な場合に使用
  • on(eventName, handler) は選択的に(または '*' で)購読でき、より細かい制御が必要な場合や作成後にリスナーを取り付けたい場合に最適
  • onStream またはいずれかの on(...) ハンドラーを提供すると、自動的にストリーミングモードで実行。指定しない場合は非ストリーミング経路のまま
  • ハンドラーは並列に呼び出されるため、遅い onStream コールバックが on(...) ハンドラーをブロックすることはない(その逆も同様)
  • toolCallId は、ツールがモデルのツールコール経由で呼び出された場合に提供される。invoke() の直接呼び出しやプロバイダー依存の挙動では省略されることがある

Model Context Protocol (MCP) サーバー経由でツールを公開し、エージェントに接続できます。 たとえば、MCPServerStdio を使って stdio MCP サーバーを起動して接続できます。

Local MCP server
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 連携 を参照してください。 複数サーバーの管理(または一部障害)時には、connectMcpServersMCP 連携 のライフサイクル指針を使用してください。


@openai/agents-extensions/experimental/codexcodexTool() を提供します。これは、モデルのツールコールを Codex SDK にルーティングする関数ツールで、エージェントがワークスペース範囲のタスク(shell、ファイル編集、MCP ツール)を自律的に実行できるようにします。本機能は実験的であり、変更される可能性があります。

まず依存関係をインストールします。

Terminal window
npm install @openai/agents-extensions @openai/codex-sdk

クイックスタート:

Experimental Codex tool
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 } を含む必要がある
  • セーフティ: sandboxModeworkingDirectory と組み合わせる。ディレクトリが Git リポジトリでない場合は skipGitRepoCheck を設定
  • スレッディング: useRunContextThreadId: true は最新の thread id を runContext.context に読み書きし、アプリ状態でのターン間再利用に有用
  • Thread ID の優先順位: ツールコールの threadId(スキーマに含めた場合)が最優先、次に実行コンテキストの thread id、最後に codexTool({ threadId })
  • 実行コンテキストキー: name: 'codex' の場合はデフォルトで codexThreadIdname: 'engineer' のような名前では codexThreadId_<suffix>(正規化後は codex_engineer
  • 変更可能なコンテキスト要件: useRunContextThreadId 有効時は、run(..., { context }) に変更可能なオブジェクトまたは Map を渡す
  • 命名: ツール名は codex 名前空間へ正規化され(engineercodex_engineer になる)、エージェント内での Codex ツール名の重複は拒否される
  • ストリーミング: onStream は Codex のイベント(推論、コマンド実行、MCP ツールコール、ファイル変更、Web 検索)を反映するため、進捗のログやトレースが可能
  • 出力: ツール結果には responseusagethreadId が含まれ、Codex のトークン使用量は RunContext に記録される
  • 構造: outputSchema はディスクリプタ、JSON スキーマオブジェクト、または Zod オブジェクトを指定可能。JSON オブジェクトスキーマでは additionalPropertiesfalse が必要

実行コンテキストのスレッド再利用例:

Codex run-context thread reuse
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 “ツール戦略とベストプラクティス”

モデルがいつどのようにツールを使用すべきかの制御については、エージェント を参照してください(modelSettings.toolChoicetoolUseBehavior など)。


  • 短く明示的な説明 – ツールが何をするのか、いつ使うのかを記述
  • 入力の検証 – 可能なら Zod スキーマで厳密な JSON 検証を行う
  • エラーハンドラーで副作用を避けるerrorFunction は有用な文字列を返し、例外は投げない
  • ツールごとに単一責務 – 小さく合成しやすいツールは、モデルの推論を改善する