Claude はデータの分析、ビジュアライゼーションの作成、複雑な計算の実行、システムコマンドの実行、ファイルの作成と編集、および API 会話内でアップロードされたファイルの処理を直接行うことができます。
コード実行ツールにより、Claude は安全なサンドボックス環境でコードを含む Bash コマンドとファイル操作を実行できます。
コード実行ツールは現在パブリックベータ版です。この機能を使用するには、API リクエストに "code-execution-2025-08-25" ベータヘッダー を追加してください。
モデルの互換性
コード実行ツールは以下のモデルで利用可能です:
| モデル | ツールバージョン |
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.5 (claude-sonnet-4-5-20250929) | 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 のみ) も利用可能です。移行の詳細については 最新ツールバージョンへのアップグレード を参照してください。
古いツールバージョンは新しいモデルとの後方互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
クイックスタート
Claude に計算を実行するよう求める簡単な例を次に示します:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: code-execution-2025-08-25" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-4-5",
"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"
}]
}'
コード実行の仕組み
API リクエストにコード実行ツールを追加すると:
- Claude は質問に答えるためにコード実行が役立つかどうかを評価します
- ツールは自動的に Claude に以下の機能を提供します:
- Bash コマンド: システム操作とパッケージ管理のためのシェルコマンドを実行します
- ファイル操作: コードを含むファイルを直接作成、表示、編集します
- Claude は単一のリクエストでこれらの機能の任意の組み合わせを使用できます
- すべての操作は安全なサンドボックス環境で実行されます
- Claude は生成されたチャート、計算、または分析を含む結果を提供します
ツールの使用方法
Bash コマンドを実行する
Claude にシステム情報を確認してパッケージをインストールするよう求めます:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: code-execution-2025-08-25" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-4-5",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": "Check the Python version and list installed packages"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'
ファイルを直接作成および編集する
Claude はサンドボックス内のファイル操作機能を使用してファイルを直接作成、表示、編集できます:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: code-execution-2025-08-25" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-4-5",
"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"
}]
}'
独自のファイルをアップロードして分析する
独自のデータファイル (CSV、Excel、画像など) を分析するには、Files API を使用してアップロードし、リクエストで参照します:
Files API でコード実行を使用するには、2 つのベータヘッダーが必要です: "anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14"
Python 環境は Files API を通じてアップロードされた様々なファイルタイプを処理できます:
- CSV
- Excel (.xlsx, .xls)
- JSON
- XML
- 画像 (JPEG, PNG, GIF, WebP)
- テキストファイル (.txt, .md, .py など)
ファイルをアップロードして分析する
- Files API を使用してファイルをアップロードします
container_upload コンテンツブロックを使用してメッセージ内でファイルを参照します
- API リクエストにコード実行ツールを含めます
# まずファイルをアップロードします
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"' \
# その後、ファイル ID をコード実行で使用します
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: code-execution-2025-08-25,files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-4-5",
"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"
}]
}'
生成されたファイルを取得する
Claude がコード実行中にファイルを作成する場合、Files API を使用してこれらのファイルを取得できます:
from anthropic import Anthropic
# クライアントを初期化します
client = Anthropic()
# ファイルを作成するコード実行をリクエストします
response = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25", "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
# ファイル 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: code-execution-2025-08-25,files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-4-5",
"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"
}]
}'
ツール定義
コード実行ツールは追加のパラメータを必要としません:
{
"type": "code_execution_20250825",
"name": "code_execution"
}
このツールが提供されると、Claude は自動的に 2 つのサブツールにアクセスできます:
bash_code_execution: シェルコマンドを実行します
text_editor_code_execution: ファイルを表示、作成、編集します (コードを含む)
レスポンス形式
コード実行ツールは操作に応じて 2 つのタイプの結果を返すことができます:
Bash コマンドレスポンス
{
"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、totalLines
- 作成:
is_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 | ツール使用のレート制限を超過しました |
| text_editor | file_not_found | ファイルが存在しません (表示/編集操作の場合) |
| text_editor | string_not_found | old_str がファイルに見つかりません (str_replace の場合) |
pause_turn 停止理由
レスポンスに pause_turn 停止理由が含まれる場合があります。これは API が長時間実行されるターンを一時停止したことを示します。レスポンスをそのまま後続のリクエストで提供して Claude にターンを続行させるか、会話を中断したい場合はコンテンツを変更できます。
コンテナ
コード実行ツールは、コード実行用に特別に設計された安全でコンテナ化された環境で実行され、Python に高い焦点を当てています。
ランタイム環境
- Python バージョン: 3.11.12
- オペレーティングシステム: Linux ベースのコンテナ
- アーキテクチャ: x86_64 (AMD64)
リソース制限
- メモリ: 5GiB RAM
- ディスク容量: 5GiB ワークスペースストレージ
- CPU: 1 CPU
ネットワークとセキュリティ
- インターネットアクセス: セキュリティのため完全に無効化されています
- 外部接続: 送信ネットワークリクエストは許可されていません
- サンドボックス分離: ホストシステムおよび他のコンテナからの完全な分離
- ファイルアクセス: ワークスペースディレクトリのみに制限されています
- ワークスペーススコープ: Files と同様に、コンテナは API キーのワークスペースにスコープされます
- 有効期限: コンテナは作成から 30 日後に期限切れになります
プリインストールされたライブラリ
サンドボックス化された Python 環境には、これらの一般的に使用されるライブラリが含まれています:
- データサイエンス: pandas、numpy、scipy、scikit-learn、statsmodels
- ビジュアライゼーション: matplotlib、seaborn
- ファイル処理: pyarrow、openpyxl、xlsxwriter、xlrd、pillow、python-pptx、python-docx、pypdf、pdfplumber、pypdfium2、pdf2image、pdfkit、tabula-py、reportlab[pycairo]、Img2pdf
- 数学と計算: sympy、mpmath
- ユーティリティ: tqdm、python-dateutil、pytz、joblib、unzip、unrar、7zip、bc、rg (ripgrep)、fd、sqlite
コンテナの再利用
前のレスポンスからコンテナ ID を提供することで、複数の API リクエスト間で既存のコンテナを再利用できます。
これにより、リクエスト間で作成されたファイルを保持できます。
import os
from anthropic import Anthropic
# クライアントを初期化します
client = Anthropic(
api_key=os.getenv("ANTHROPIC_API_KEY")
)
# 最初のリクエスト: ランダムな数字を含むファイルを作成します
response1 = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25"],
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.beta.messages.create(
container=container_id, # 同じコンテナを再利用します
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25"],
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"
}]
)
ストリーミング
ストリーミングが有効な場合、コード実行イベントが発生時に受け取ります:
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 tool usage is tracked separately from token usage. Execution time has a minimum of 5 minutes.
If files are included in the request, execution time is billed even if the tool is not used due to files being preloaded onto the container.
Each organization receives 50 free hours of usage with the code execution tool per day. Additional usage beyond the first 50 hours is billed at $0.05 per hour, per container.
最新ツールバージョンへのアップグレード
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 |
後方互換性
- 既存のすべての Python コード実行は以前と同じように機能し続けます
- 既存の Python のみのワークフローに変更は必要ありません
アップグレード手順
アップグレードするには、API リクエストで以下の変更を行う必要があります:
-
ベータヘッダーを更新します:
- "anthropic-beta": "code-execution-2025-05-22"
+ "anthropic-beta": "code-execution-2025-08-25"
-
ツールタイプを更新します:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"
-
レスポンス処理を確認します (プログラムでレスポンスを解析する場合):
- Python 実行レスポンスの前のブロックは送信されなくなります
- 代わりに、Bash とファイル操作の新しいレスポンスタイプが送信されます (レスポンス形式セクションを参照)
Agent Skills でコード実行を使用する
コード実行ツールにより、Claude は Agent Skills を使用できます。Skills は、Claude の機能を拡張する命令、スクリプト、リソースで構成されたモジュール機能です。
詳細については、Agent Skills ドキュメント および Agent Skills API ガイド を参照してください。