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.7 (claude-opus-4-7) | code_execution_20250825, code_execution_20260120 |
Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825, code_execution_20260120 |
Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825, code_execution_20260120 |
Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825, code_execution_20260120 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825, code_execution_20260120 |
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | 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 3.5 (claude-3-5-haiku-latest) (非推奨) | code_execution_20250825 |
code_execution_20250825はBashコマンドとファイル操作をサポートし、上記のすべてのモデルで利用可能です。code_execution_20260120はREPL状態の永続化とプログラマティックツール呼び出しをサンドボックス内から追加し、Opus 4.5以上とSonnet 4.5以上でのみ利用可能です。レガシーバージョンcode_execution_20250522(Pythonのみ)もcode_execution_20250825と同じモデルで利用可能です。最新ツールバージョンへのアップグレードを参照して、それから移行してください。
古いツールバージョンは、新しいモデルとの下位互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
コード実行は以下で利用可能です:
コード実行は現在Amazon BedrockまたはGoogle Vertex AIでは利用できません。
Claude Mythos Previewの場合、コード実行はClaude APIおよびMicrosoft Foundryでサポートされています。Amazon BedrockまたはGoogle Vertex AIのMythos Previewでは利用できません。
Claudeに計算を実行するよう求める簡単な例を次に示します:
APIリクエストにコード実行ツールを追加する場合:
コード実行をコードも実行するクライアント提供ツール(bashツールやカスタムREPLなど)と一緒に提供する場合、Claudeはマルチコンピュータ環境で動作しています。コード実行ツールはAnthropicのサンドボックス化されたコンテナで実行され、クライアント提供ツールはあなたが制御する別の環境で実行されます。Claudeはこれらの環境を混同することがあり、間違ったツールを使用しようとしたり、状態が共有されていると仮定したりすることがあります。
これを回避するには、システムプロンプトに環境の区別を明確にする指示を追加してください:
複数のコード実行環境が利用可能な場合は、以下に注意してください:
- 変数、ファイル、状態は異なる実行環境間で永続化されません
- Anthropicのサンドボックス環境での汎用計算にはcode_executionツールを使用してください
- ユーザーのローカルシステム、ファイル、またはデータへのアクセスが必要な場合は、クライアント提供の実行ツール(例:bash)を使用してください
- 環境間で結果を渡す必要がある場合は、共有状態を仮定するのではなく、後続のツール呼び出しに明示的に出力を含めてくださいこれは特にウェブ検索またはウェブフェッチとコード実行を組み合わせる場合に重要です。これらはコード実行を自動的に有効にします。アプリケーションがすでにクライアント側シェルツールを提供している場合、自動コード実行は2番目の実行環境を作成し、Claudeが区別する必要があります。
独自のデータファイル(CSV、Excel、画像など)を分析するには、Files APIを使用してアップロードし、リクエストで参照します:
Code Executionで 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 (diff形式)各ツールタイプは特定のエラーを返すことができます:
共通エラー (すべてのツール):
{
"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 | ツール使用のレート制限を超過しました |
| bash | output_file_too_large | コマンド出力が最大サイズを超過しました |
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"}}
// Code execution streamed
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())\"}"}}
// Pause while code executes
// Execution results streamed
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"レスポンス処理の確認(プログラムでレスポンスを解析する場合):
コード実行コンテナ内でツールを実行するには、プログラマティックツール呼び出しを参照してください。
コード実行はサーバー側のサンドボックスコンテナで実行されます。実行アーティファクト、アップロードされたファイル、出力を含むコンテナデータは最大30日間保持されます。この保持はコンテナ環境内で処理されるすべてのデータに適用されます。コード実行がFiles APIに作成するファイル(client.beta.files.download()経由で取得可能)は、明示的に削除されるまで保持されます。
すべての機能にわたるZDR適格性については、API とデータ保持を参照してください。
コード実行ツールにより、ClaudeはAgent Skillsを使用できます。Skillsは、Claudeの機能を拡張する指示、スクリプト、リソースで構成されるモジュール機能です。
詳細については、Agent SkillsドキュメントとAgent Skills APIガイドを参照してください。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-7",
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"}],
)
print(response)client = anthropic.Anthropic()
# Upload a file
file_object = client.beta.files.upload(
file=open("data.csv", "rb"),
)
# Use the file_id with code execution
response = client.beta.messages.create(
model="claude-opus-4-7",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this CSV data"},
{"type": "container_upload", "file_id": file_object.id},
],
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response)# Initialize the client
client = Anthropic()
# Request code execution that creates files
response = client.beta.messages.create(
model="claude-opus-4-7",
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"}],
)
# Extract file IDs from the response
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":
# concrete-typed list: List[BashCodeExecutionOutputBlock]
for file in content_item.content:
file_ids.append(file.file_id)
return file_ids
# Download the created files
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}")| text_editor |
file_not_found |
| ファイルが存在しません (表示/編集操作の場合) |
| text_editor | string_not_found | old_str がファイルに見つかりません (str_replaceの場合) |
# First request: Create a file with a random number
response1 = client.messages.create(
model="claude-opus-4-7",
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"}],
)
# Extract the container ID from the first response
container_id = response1.container.id
# Second request: Reuse the container to read the file
response2 = client.messages.create(
container=container_id, # Reuse the same container
model="claude-opus-4-7",
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"}],
)
print(response2)