Was this page helpful?
Claudeは、APIの会話内で直接、データの分析、ビジュアライゼーションの作成、複雑な計算の実行、システムコマンドの実行、ファイルの作成・編集、アップロードされたファイルの処理を行うことができます。コード実行ツールにより、Claudeは安全なサンドボックス環境でBashコマンドを実行し、コードの記述を含むファイル操作を行うことができます。
コード実行は、ウェブ検索またはウェブフェッチと組み合わせて使用する場合は無料です。 リクエストに web_search_20260209 または web_fetch_20260209 が含まれている場合、標準の入出力トークンコスト以外にコード実行ツール呼び出しの追加料金はかかりません。これらのツールが含まれていない場合は、標準のコード実行料金が適用されます。
コード実行は、高性能なエージェントを構築するためのコアプリミティブです。ウェブ検索およびウェブフェッチツールでの動的フィルタリングを可能にし、Claudeがコンテキストウィンドウに到達する前に結果を処理できるようにすることで、トークン消費を削減しながら精度を向上させます。
この機能に関するフィードバックは、フィードバックフォームからお寄せください。
This feature is not eligible for Zero Data Retention (ZDR). 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 Opus 4.1 (claude-opus-4-1-20250805) | code_execution_20250825 |
Claude Opus 4 (claude-opus-4-20250514) | code_execution_20250825 |
Claude Sonnet 4 (claude-sonnet-4-20250514) | code_execution_20250825 |
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219) (非推奨) | code_execution_20250825 |
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
Claude Haiku 3.5 (claude-3-5-haiku-latest) (非推奨) | code_execution_20250825 |
現在のバージョン code_execution_20250825 はBashコマンドとファイル操作をサポートしています。レガシーバージョン code_execution_20250522(Pythonのみ)も利用可能です。移行の詳細については、最新ツールバージョンへのアップグレードを参照してください。
古いツールバージョンは、新しいモデルとの後方互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
コード実行は以下で利用可能です:
コード実行は現在、Amazon BedrockまたはGoogle Vertex AIでは利用できません。
Claudeに計算を実行させる簡単な例を示します:
APIリクエストにコード実行ツールを追加すると:
コード実行を、コードを実行するクライアント提供のツール(bashツールやカスタムREPLなど)と一緒に提供する場合、Claudeはマルチコンピュータ環境で動作しています。コード実行ツールはAnthropicのサンドボックスコンテナで実行され、クライアント提供のツールはあなたが制御する別の環境で実行されます。Claudeはこれらの環境を混同し、誤ったツールを使用しようとしたり、状態が共有されていると仮定したりすることがあります。
これを避けるために、区別を明確にするシステムプロンプトへの指示を追加してください:
複数のコード実行環境が利用可能な場合、以下の点に注意してください:
- 変数、ファイル、状態は異なる実行環境間で持続しません
- Anthropicのサンドボックス環境での汎用計算にはcode_executionツールを使用してください
- ユーザーのローカルシステム、ファイル、またはデータへのアクセスが必要な場合は、クライアント提供の実行ツール(例:bash)を使用してください
- 環境間で結果を渡す必要がある場合は、共有状態を仮定するのではなく、後続のツール呼び出しに出力を明示的に含めてくださいこれは、コード実行をウェブ検索やウェブフェッチと組み合わせる場合に特に重要です。これらはコード実行を自動的に有効にします。アプリケーションがすでにクライアント側のシェルツールを提供している場合、自動コード実行によって2番目の実行環境が作成され、Claudeはそれらを区別する必要があります。
Claudeにシステム情報の確認とパッケージのインストールを依頼します:
Claudeはファイル操作機能を使用して、サンドボックス内でファイルを直接作成、表示、編集できます:
独自のデータファイル(CSV、Excel、画像など)を分析するには、Files APIを使用してアップロードし、リクエストで参照します:
Files APIをコード実行と組み合わせて使用するには、Files APIベータヘッダーが必要です:"anthropic-beta": "files-api-2025-04-14"
Pythonの環境は、Files APIを通じてアップロードされた様々なファイルタイプを処理できます:
container_uploadコンテンツブロックを使用してメッセージ内でファイルを参照しますClaudeがコード実行中にファイルを作成した場合、Files APIを使用してこれらのファイルを取得できます:
すべての機能を使用した複雑なワークフロー:
コード実行ツールには追加のパラメータは必要ありません:
{
"type": "code_execution_20250825",
"name": "code_execution"
}このツールが提供されると、Claudeは自動的に2つのサブツールへのアクセスを取得します:
bash_code_execution:シェルコマンドを実行text_editor_code_execution:コードの記述を含む、ファイルの表示・作成・編集コード実行ツールは、操作に応じて2種類の結果を返すことができます:
{
"type": "server_tool_use",
"id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"name": "bash_code_execution",
"input": {
"command": "ls -la | head -5"
}
},
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"content": {
"type": "bash_code_execution_result",
"stdout": "total 24\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 11:00 ..\n-rw-r--r-- 1 user user 220 Jan 1 12:00 data.csv\n-rw-r--r-- 1 user user 180 Jan 1 12:00 config.json",
"stderr": "",
"return_code": 0
}
}ファイルの表示:
{
"type": "server_tool_use",
"id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"name": "text_editor_code_execution",
"input": {
"command": "view",
"path": "config.json"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": {
"type": "text_editor_code_execution_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"numLines": 4,
"startLine": 1,
"totalLines": 4
}
}ファイルの作成:
{
"type": "server_tool_use",
"id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"name": "text_editor_code_execution",
"input": {
"command": "create",
"path": "new_file.txt",
"file_text": "Hello, World!"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"content": {
"type": "text_editor_code_execution_result",
"is_file_update": false
}
}ファイルの編集(str_replace):
{
"type": "server_tool_use",
"id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"name": "text_editor_code_execution",
"input": {
"command": "str_replace",
"path": "config.json",
"old_str": "\"debug\": true",
"new_str": "\"debug\": false"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"content": {
"type": "text_editor_code_execution_result",
"oldStart": 3,
"oldLines": 1,
"newStart": 3,
"newLines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}すべての実行結果には以下が含まれます:
stdout:実行成功時の出力stderr:実行失敗時のエラーメッセージreturn_code:成功の場合は0、失敗の場合は0以外ファイル操作の追加フィールド:
file_type、content、numLines、startLine、totalLinesis_file_update(ファイルが既に存在していたかどうか)oldStart、oldLines、newStart、newLines、lines(差分形式)各ツールタイプは特定のエラーを返すことができます:
共通エラー(すべてのツール):
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
"content": {
"type": "bash_code_execution_tool_result_error",
"error_code": "unavailable"
}
}ツールタイプ別のエラーコード:
| ツール | エラーコード | 説明 |
|---|---|---|
| すべてのツール | unavailable | ツールが一時的に利用できない |
| すべてのツール | execution_time_exceeded | 実行が最大時間制限を超えた |
| すべてのツール | container_expired | コンテナが期限切れになり、利用できなくなった |
| すべてのツール | invalid_tool_input | ツールに無効なパラメータが提供された |
| すべてのツール | too_many_requests | ツール使用のレート制限を超えた |
| text_editor | file_not_found | ファイルが存在しない(表示/編集操作の場合) |
pause_turn 停止理由レスポンスには pause_turn 停止理由が含まれる場合があります。これはAPIが長時間実行されているターンを一時停止したことを示します。Claudeがターンを継続できるように、後続のリクエストでレスポンスをそのまま提供するか、会話を中断したい場合はコンテンツを変更することができます。
コード実行ツールは、コード実行専用に設計された安全なコンテナ化された環境で実行され、Pythonに重点を置いています。
サンドボックスのPython環境には、よく使用される以下のライブラリが含まれています:
前のレスポンスからコンテナIDを提供することで、複数のAPIリクエスト間で既存のコンテナを再利用できます。これにより、リクエスト間で作成されたファイルを維持することができます。
ストリーミングを有効にすると、コード実行イベントが発生するたびに受信します:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}
// コード実行がストリーミングされます
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"code\":\"import pandas as pd\\ndf = pd.read_csv('data.csv')\\nprint(df.head())\"}"}}
// コードが実行される間、一時停止します
// 実行結果がストリーミングされます
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": ""}}}Messages Batches APIにコード実行ツールを含めることができます。Messages Batches APIを通じたコード実行ツール呼び出しは、通常のMessages APIリクエストと同じ料金が適用されます。
Code execution is free when used with web search or web fetch. When web_search_20260209 or web_fetch_20260209 is included in your API request, there are no additional charges for code execution tool calls beyond the standard input and output token costs.
When used without these tools, code execution is billed by execution time, tracked separately from token usage:
Code execution usage is tracked in the response:
"usage": {
"input_tokens": 105,
"output_tokens": 239,
"server_tool_use": {
"code_execution_requests": 1
}
}code-execution-2025-08-25にアップグレードすることで、複数の言語でのコードを含む、ファイル操作とBash機能へのアクセスが得られます。価格差はありません。
| コンポーネント | レガシー | 現在 |
|---|---|---|
| ベータヘッダー | code-execution-2025-05-22 | code-execution-2025-08-25 |
| ツールタイプ | code_execution_20250522 | code_execution_20250825 |
| 機能 | Pythonのみ | Bashコマンド、ファイル操作 |
| レスポンスタイプ | code_execution_result | bash_code_execution_result、text_editor_code_execution_result |
アップグレードするには、APIリクエストのツールタイプを更新します:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"レスポンス処理の確認(プログラムでレスポンスを解析する場合):
コード実行ツールはプログラムによるツール呼び出しを強化します。これにより、Claudeは実行コンテナ内でカスタムツールをプログラムで呼び出すコードを記述できます。これにより、効率的なマルチツールワークフロー、Claudeのコンテキストに到達する前のデータフィルタリング、複雑な条件ロジックが可能になります。
# ツールのプログラムによる呼び出しを有効にします
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
messages=[
{"role": "user", "content": "Get weather for 5 cities and find the warmest"}
],
tools=[
{"type": "code_execution_20250825", "name": "code_execution"},
{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {...},
"allowed_callers": [
"code_execution_20250825"
], # プログラムによる呼び出しを有効にします
},
],
)詳細については、プログラムによるツール呼び出しのドキュメントを参照してください。
コード実行はサーバーサイドのサンドボックスコンテナで実行されます。実行アーティファクト、アップロードされたファイル、出力を含むコンテナデータは、最大30日間保持されます。この保持期間は、コンテナ環境内で処理されるすべてのデータに適用されます。
すべての機能にわたるZDRの適格性については、APIとデータ保持を参照してください。
コード実行ツールにより、ClaudeはAgent Skillsを使用できます。Skillsは、Claudeの機能を拡張する命令、スクリプト、およびリソースで構成されるモジュール型の機能です。
詳細については、Agent SkillsドキュメントおよびAgent Skills APIガイドを参照してください。
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": "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
}
],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'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": "Check the Python version and list installed packages"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'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": "Create a config.yaml file with database settings, then update the port from 5432 to 3306"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'# まず、ファイルをアップロードします
curl https://api.anthropic.com/v1/files \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--form 'file=@"data.csv"' \
# 次に、file_idをコード実行と一緒に使用します
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this CSV data"},
{"type": "container_upload", "file_id": "file_abc123"}
]
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'from anthropic import Anthropic
# クライアントを初期化します
client = Anthropic()
# ファイルを作成するコード実行をリクエストします
response = client.beta.messages.create(
model="claude-opus-4-6",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Create a matplotlib visualization and save it as output.png",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# レスポンスからファイルIDを抽出します
def extract_file_ids(response):
file_ids = []
for item in response.content:
if item.type == "bash_code_execution_tool_result":
content_item = item.content
if content_item.type == "bash_code_execution_result":
for file in content_item.content:
if hasattr(file, "file_id"):
file_ids.append(file.file_id)
return file_ids
# 作成されたファイルをダウンロードします
for file_id in extract_file_ids(response):
file_metadata = client.beta.files.retrieve_metadata(file_id)
file_content = client.beta.files.download(file_id)
file_content.write_to_file(file_metadata.filename)
print(f"Downloaded: {file_metadata.filename}")# まず、ファイルをアップロードします
curl https://api.anthropic.com/v1/files \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--form 'file=@"data.csv"' \
> file_response.json
# file_idを抽出します(jqを使用)
FILE_ID=$(jq -r '.id' file_response.json)
# コード実行と一緒に使用します
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this CSV data: create a summary report, save visualizations, and create a README with the findings"
},
{
"type": "container_upload",
"file_id": "'$FILE_ID'"
}
]
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'| text_editor |
string_not_found |
ファイル内に old_str が見つからない(str_replaceの場合) |
import os
from anthropic import Anthropic
# クライアントを初期化します
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
# 最初のリクエスト:乱数を含むファイルを作成します
response1 = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Write a file with a random number and save it to '/tmp/number.txt'",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# 最初のレスポンスからコンテナIDを抽出します
container_id = response1.container.id
# 2番目のリクエスト:コンテナを再利用してファイルを読み取ります
response2 = client.messages.create(
container=container_id, # 同じコンテナを再利用します
model="claude-opus-4-6",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Read the number from '/tmp/number.txt' and calculate its square",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)