Was this page helpful?
プログラマティックツール呼び出しにより、Claudeは各ツール呼び出しごとにモデルとのラウンドトリップを必要とせず、コード実行コンテナ内でプログラム的にツールを呼び出すコードを記述できます。これにより、マルチツールワークフローのレイテンシーが削減され、Claudeがモデルのコンテキストウィンドウに到達する前にデータをフィルタリングまたは処理できるため、トークン消費量が減少します。
この機能にはコード実行ツールが有効になっている必要があります。
This feature is not covered by Zero Data Retention (ZDR) arrangements. Data is retained according to the feature's standard retention policy.
プログラマティックツール呼び出しは以下のモデルで利用可能です:
| モデル | ツールバージョン |
|---|---|
Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825 |
Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825 |
Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825 |
プログラマティックツール呼び出しはClaude APIおよびMicrosoft Foundryを通じて利用可能です。
以下は、Claudeがプログラム的にデータベースを複数回クエリし、結果を集約する簡単な例です:
コード実行から呼び出し可能なツールを設定し、Claudeがそのツールを使用することを決定した場合:
tool_useブロックを返しますこのアプローチは特に以下の場合に有用です:
カスタムツールは並列ツール呼び出しをサポートするために非同期Python関数に変換されます。Claudeがツールを呼び出すコードを記述する際、awaitを使用し(例:result = await query_database("<sql>"))、適切な非同期ラッパー関数を自動的に含めます。
このドキュメントのコード例では、わかりやすさのために非同期ラッパーは省略されています。
allowed_callersフィールドallowed_callersフィールドは、どのコンテキストがツールを呼び出せるかを指定します:
{
"name": "query_database",
"description": "Execute a SQL query against the database",
"input_schema": {...},
"allowed_callers": ["code_execution_20250825"]
}指定可能な値:
["direct"] - Claudeのみがこのツールを直接呼び出せます(省略時のデフォルト)["code_execution_20250825"] - コード実行内からのみ呼び出し可能["direct", "code_execution_20250825"] - 直接およびコード実行の両方から呼び出し可能各ツールに対して、両方を有効にするのではなく、["direct"]または["code_execution_20250825"]のいずれかを選択することをお勧めします。これにより、Claudeがツールを最適に使用する方法についてより明確なガイダンスが提供されます。
callerフィールドすべてのツール使用ブロックには、どのように呼び出されたかを示すcallerフィールドが含まれます:
直接呼び出し(従来のツール使用):
{
"type": "tool_use",
"id": "toolu_abc123",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {"type": "direct"}
}プログラマティック呼び出し:
{
"type": "tool_use",
"id": "toolu_xyz789",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {
"type": "code_execution_20250825",
"tool_id": "srvtoolu_abc123"
}
}tool_idは、プログラマティック呼び出しを行ったコード実行ツールを参照します。
プログラマティックツール呼び出しはコード実行と同じコンテナを使用します:
containerフィールドを通じてレスポンスで返されますツールがプログラム的に呼び出され、コンテナがツール結果を待っている場合、コンテナが期限切れになる前に応答する必要があります。expires_atフィールドを監視してください。コンテナが期限切れになると、Claudeはツール呼び出しがタイムアウトしたとみなし、再試行する可能性があります。
プログラマティックツール呼び出しの完全なフローは以下のように動作します:
コード実行とプログラマティック呼び出しを許可するツールを含むリクエストを送信します。プログラマティック呼び出しを有効にするには、ツール定義にallowed_callersフィールドを追加します。
ツールの説明にツールの出力形式の詳細な説明を提供してください。ツールがJSONを返すことを指定すると、Claudeはコード内で結果をデシリアライズして処理しようとします。出力スキーマについてより詳細に提供するほど、Claudeはプログラム的にレスポンスをより適切に処理できます。
Claudeはツールを呼び出すコードを記述します。APIは一時停止して以下を返します:
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll query the purchase history and analyze the results."
},
{
"type": "server_tool_use",
"id": "srvtoolu_abc123",
"name": "code_execution",
"input": {
"code": "results = await query_database('<sql>')\ntop_customers = sorted(results, key=lambda x: x['revenue'], reverse=True)[:5]\nprint(f'Top 5 customers: {top_customers}')"
}
},
{
"type": "tool_use",
"id": "toolu_def456",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {
"type": "code_execution_20250825",
"tool_id": "srvtoolu_abc123"
}
}
],
"container": {
"id": "container_xyz789",
"expires_at": "2025-01-15T14:30:00Z"
},
"stop_reason": "tool_use"
}完全な会話履歴とツール結果を含めます:
コード実行が続行され、結果を処理します。追加のツール呼び出しが必要な場合は、すべてのツール呼び出しが満たされるまでステップ3を繰り返します。
コード実行が完了すると、Claudeは最終レスポンスを提供します:
{
"content": [
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_abc123",
"content": {
"type": "code_execution_result",
"stdout": "Top 5 customers by revenue:\n1. Customer C1: $45,000\n2. Customer C2: $38,000\n3. Customer C5: $32,000\n4. Customer C8: $28,500\n5. Customer C3: $24,000",
"stderr": "",
"return_code": 0,
"content": []
}
},
{
"type": "text",
"text": "I've analyzed the purchase history from last quarter. Your top 5 customers generated $167,500 in total revenue, with Customer C1 leading at $45,000."
}
],
"stop_reason": "end_turn"
}Claudeは複数のアイテムを効率的に処理するコードを記述できます:
# わかりやすさのために非同期ラッパーは省略
regions = ["West", "East", "Central", "North", "South"]
results = {}
for region in regions:
data = await query_database(f"<sql for {region}>")
results[region] = sum(row["revenue"] for row in data)
# 結果をプログラム的に処理
top_region = max(results.items(), key=lambda x: x[1])
print(f"Top region: {top_region[0]} with ${top_region[1]:,} in revenue")このパターンは:
Claudeは成功基準が満たされた時点で処理を停止できます:
# わかりやすさのために非同期ラッパーは省略
endpoints = ["us-east", "eu-west", "apac"]
for endpoint in endpoints:
status = await check_health(endpoint)
if status == "healthy":
print(f"Found healthy endpoint: {endpoint}")
break # 早期停止、残りはチェックしない# わかりやすさのために非同期ラッパーは省略
file_info = await get_file_info(path)
if file_info["size"] < 10000:
content = await read_full_file(path)
else:
content = await read_file_summary(path)
print(content)# わかりやすさのために非同期ラッパーは省略
logs = await fetch_logs(server_id)
errors = [log for log in logs if "ERROR" in log]
print(f"Found {len(errors)} errors")
for error in errors[-10:]: # 最後の10件のエラーのみ返す
print(error)コード実行がツールを呼び出す場合:
{
"type": "tool_use",
"id": "toolu_abc123",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {
"type": "code_execution_20250825",
"tool_id": "srvtoolu_xyz789"
}
}ツール結果は実行中のコードに渡されます:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "[{\"customer_id\": \"C1\", \"revenue\": 45000, \"orders\": 23}, {\"customer_id\": \"C2\", \"revenue\": 38000, \"orders\": 18}, ...]"
}
]
}すべてのツール呼び出しが満たされ、コードが完了した場合:
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_xyz789",
"content": {
"type": "code_execution_result",
"stdout": "Analysis complete. Top 5 customers identified from 847 total records.",
"stderr": "",
"return_code": 0,
"content": []
}
}| エラー | 説明 | 解決策 |
|---|---|---|
invalid_tool_input | ツール入力がスキーマと一致しない | ツールのinput_schemaを検証してください |
tool_not_allowed | ツールがリクエストされた呼び出し元タイプを許可していない | allowed_callersに正しいコンテキストが含まれているか確認してください |
missing_beta_header | 必要なベータヘッダーが提供されていない | リクエストに必要なベータヘッダーを追加してください |
ツールの応答に時間がかかりすぎると、コード実行はTimeoutErrorを受け取ります。Claudeはこれをstderrで確認し、通常は再試行します:
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_abc123",
"content": {
"type": "code_execution_result",
"stdout": "",
"stderr": "TimeoutError: Calling tool ['query_database'] timed out.",
"return_code": 0,
"content": []
}
}タイムアウトを防ぐには:
expires_atフィールドを監視するツールがエラーを返す場合:
# ツール結果にエラー情報を提供
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "Error: Query timeout - table lock exceeded 30 seconds",
}Claudeのコードはこのエラーを受け取り、適切に処理できます。
strict: trueのツールはプログラマティック呼び出しではサポートされていませんtool_choiceを通じて特定のツールのプログラマティック呼び出しを強制することはできませんdisable_parallel_tool_use: trueはプログラマティック呼び出しではサポートされていません以下のツールは現在プログラム的に呼び出すことができませんが、将来のリリースでサポートが追加される可能性があります:
プログラマティックツール呼び出しに応答する際、厳格なフォーマット要件があります:
ツール結果のみのレスポンス:結果を待っている保留中のプログラマティックツール呼び出しがある場合、レスポンスメッセージにはtool_resultブロックのみを含める必要があります。ツール結果の後であっても、テキストコンテンツを含めることはできません。
// ❌ 無効 - プログラマティックツール呼び出しへの応答時にテキストを含めることはできません
{
"role": "user",
"content": [
{"type": "tool_result", "tool_use_id": "toolu_01", "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"},
{"type": "text", "text": "What should I do next?"} // これはエラーを引き起こします
]
}
// ✅ 有効 - プログラマティックツール呼び出しへの応答時はツール結果のみ
{
"role": "user",
"content": [
{"type": "tool_result", "tool_use_id": "toolu_01", "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"}
]
}この制限はプログラマティック(コード実行)ツール呼び出しへの応答時にのみ適用されます。通常のクライアントサイドツール呼び出しの場合、ツール結果の後にテキストコンテンツを含めることができます。
プログラマティックツール呼び出しは、通常のツール呼び出しと同じレート制限の対象となります。コード実行からの各ツール呼び出しは、個別の呼び出しとしてカウントされます。
プログラム的に呼び出されるカスタムツールを実装する際:
プログラマティックツール呼び出しはトークン消費を大幅に削減できます:
例えば、10個のツールを直接呼び出すと、プログラム的に呼び出してサマリーを返す場合の約10倍のトークンを使用します。
プログラマティックツール呼び出しはコード実行と同じ料金体系を使用します。詳細はコード実行の料金をご覧ください。
プログラマティックツール呼び出しのトークンカウント:プログラマティック呼び出しからのツール結果は、入力/出力トークン使用量にカウントされません。最終的なコード実行結果とClaudeのレスポンスのみがカウントされます。
適した使用ケース:
あまり適さない使用ケース:
「Tool not allowed」エラー
"allowed_callers": ["code_execution_20250825"]が含まれていることを確認してくださいコンテナの期限切れ
expires_atフィールドを監視してくださいツール結果が正しくパースされない
callerフィールドをチェック**するClaudeのトレーニングにはコードへの広範な露出が含まれており、関数呼び出しの推論とチェーンに効果的です。ツールがコード実行環境内で呼び出し可能な関数として提示されると、Claudeはこの強みを活用して以下を行えます:
このアプローチにより、1Mトークンを超えるファイルの処理など、従来のツール使用では実用的でなかったワークフローが可能になります。すべてを会話コンテキストにロードするのではなく、Claudeがプログラム的にデータを操作できるようにすることで実現されます。
プログラマティックツール呼び出しは、Anthropicのマネージドコード実行の外部でも実装できる汎用的なパターンです。以下はアプローチの概要です:
Claudeにコード実行ツールを提供し、その環境で利用可能な関数を説明します。Claudeがコードでツールを呼び出すと、アプリケーションはそれらの関数が定義されているローカルで実行します。
利点:
欠点:
使用するタイミング: アプリケーションが任意のコードを安全に実行でき、シンプルなソリューションが必要で、Anthropicのマネージドオファリングがニーズに合わない場合。
Claudeの観点からは同じアプローチですが、コードはセキュリティ制限(例:ネットワークエグレスなし)を持つサンドボックスコンテナ内で実行されます。ツールが外部リソースを必要とする場合、サンドボックスの外でツール呼び出しを実行するためのプロトコルが必要です。
利点:
欠点:
使用するタイミング: セキュリティが重要で、Anthropicのマネージドソリューションが要件に合わない場合。
Anthropicのプログラマティックツール呼び出しは、Claude向けに最適化されたPython環境を備えたサンドボックス実行のマネージドバージョンです。Anthropicがコンテナ管理、コード実行、および安全なツール呼び出し通信を処理します。
利点:
Claude APIを使用している場合は、Anthropicのマネージドソリューションの使用をお勧めします。
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
}
],
"tools": [
{
"type": "code_execution_20250825",
"name": "code_execution"
},
{
"name": "query_database",
"description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
"input_schema": {
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "SQL query to execute"
}
},
"required": ["sql"]
},
"allowed_callers": ["code_execution_20250825"]
}
]
}'response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
}
],
tools=[
{"type": "code_execution_20250825", "name": "code_execution"},
{
"name": "query_database",
"description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
"input_schema": {...},
"allowed_callers": ["code_execution_20250825"],
},
],
)response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
container="container_xyz789", # コンテナを再利用
messages=[
{
"role": "user",
"content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll query the purchase history and analyze the results.",
},
{
"type": "server_tool_use",
"id": "srvtoolu_abc123",
"name": "code_execution",
"input": {"code": "..."},
},
{
"type": "tool_use",
"id": "toolu_def456",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {
"type": "code_execution_20250825",
"tool_id": "srvtoolu_abc123",
},
},
],
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_def456",
"content": '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]',
}
],
},
],
tools=[...],
)Claudeでのツール使用の基本を理解します。