Claudeは、API会話内で直接、データの分析、視覚化の作成、複雑な計算の実行、システムコマンドの実行、ファイルの作成と編集、アップロードされたファイルの処理を行うことができます。コード実行ツールにより、Claudeは安全なサンドボックス環境でBashコマンドを実行し、コードの記述を含むファイル操作を行うことができます。
コード実行は、ウェブ検索またはウェブフェッチと併用する場合は無料です。 リクエストにweb_search_20260209(またはそれ以降)またはweb_fetch_20260209(またはそれ以降)が含まれている場合、標準の入力および出力トークンコスト以外に、コード実行ツール呼び出しに対する追加料金は発生しません。これらのツールが含まれていない場合は、標準のコード実行料金が適用されます。
コード実行は、高性能なエージェントを構築するための中核的なプリミティブです。ウェブ検索およびウェブフェッチツールでの動的フィルタリングを可能にし、Claudeが結果をコンテキストウィンドウに到達する前に処理できるようにすることで、トークン消費を削減しながら精度を向上させます。
この機能に関するフィードバックは、フィードバックフォームからお寄せください。
この機能はZero Data Retention (ZDR)の対象外です。データは、この機能の標準的な保持ポリシーに従って保持されます。
コード実行ツールは、以下のモデルで利用可能です。
| モデル | ツールバージョン |
|---|---|
| Claude Fable 5 (claude-fable-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Mythos 5 (claude-mythos-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.8 (claude-opus-4-8) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.7 (claude-opus-4-7) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
| Claude Opus 4.1 (claude-opus-4-1-20250805)(非推奨) | code_execution_20250825 |
code_execution_20250825はBashコマンドとファイル操作をサポートし、表内のすべてのモデルで利用可能です。code_execution_20260120はREPL状態の永続化とサンドボックス内からのプログラマティックツール呼び出しを追加し、Claude Fable 5、Claude Mythos 5、Opus 4.5以降、Sonnet 4.5以降でのみ利用可能です。code_execution_20260521は_20260120と同じランタイムですが、ツールの説明にセルごとの実行時間制限が明記されているため、Claudeは長時間実行されるセルに応じて時間配分を計画できます。各セルには90秒の実時間制限があり、これを超えるコードはdetection_timeoutの結果を返します。レガシーのcode_execution_20250522(Pythonのみ)をまだ使用している場合は、最新のツールバージョンへのアップグレードを参照して移行してください。
古いツールバージョンは、新しいモデルとの後方互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
コード実行は以下で利用可能です。
コード実行は現在、Amazon BedrockおよびVertex AIでは利用できません。
Claude Mythos Previewでは、コード実行はClaude APIおよびMicrosoft Foundryでのみサポートされています。Amazon Bedrock、Vertex AI、Claude Platform on AWSのMythos Previewでは利用できません。
Claudeに計算を実行させる簡単な例を以下に示します。
APIリクエストにコード実行ツールを追加すると、以下のように動作します。
Claudeは、リクエストが計算やファイル処理によって恩恵を受ける場合にコードを実行します。
以下の場合、Claudeはコードを実行せずに直接回答します。
判断が難しいリクエストでClaudeにコードを実行させたい場合は、明示的に依頼してください(例:「コードを実行してこれを検証してください」)。
コード実行を、同じくコードを実行するクライアント提供ツール(bashツールやカスタムREPLなど)と併せて提供する場合、Claudeはマルチコンピュータ環境で動作していることになります。コード実行ツールはAnthropicのサンドボックス化されたコンテナで実行され、クライアント提供ツールはユーザーが管理する別の環境で実行されます。Claudeはこれらの環境を混同し、誤ったツールを使用しようとしたり、環境間で状態が共有されていると想定したりすることがあります。
これを避けるには、システムプロンプトに区別を明確にする指示を追加してください。
When multiple code execution environments are available, be aware that:
- Variables, files, and state do NOT persist between different execution environments
- Use the code_execution tool for general-purpose computation in Anthropic's sandboxed environment
- Use client-provided execution tools (e.g., bash) when you need access to the user's local system, files, or data
- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared stateこれは、コード実行を自動的に有効にするウェブ検索やウェブフェッチと組み合わせる場合に特に重要です。アプリケーションがすでにクライアント側のシェルツールを提供している場合、自動コード実行により2つ目の実行環境が作成され、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(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リクエストと同じ料金で課金されます。
コード実行は、ウェブ検索またはウェブ取得と併用する場合は無料です。 APIリクエストに web_search_20260209(またはそれ以降)もしくは web_fetch_20260209(またはそれ以降)が含まれている場合、標準の入力および出力トークンコスト以外に、コード実行ツール呼び出しに対する追加料金は発生しません。
これらのツールを使用せずにコード実行を利用する場合、トークン使用量とは別に追跡される実行時間に基づいて課金されます。
コード実行の使用状況はレスポンスで追跡されます。
{
"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を使用できるようになります。スキルは、Claudeの機能を拡張する指示、スクリプト、リソースで構成されるモジュール式の機能です。
詳細については、Agent SkillsおよびAPIでのAgent Skillsの使用を参照してください。
Was this page helpful?
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
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()
# ファイルをアップロード
file_object = client.beta.files.upload(
file=open("data.csv", "rb"),
)
# コード実行でfile_idを使用
response = client.beta.messages.create(
model="claude-opus-4-8",
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)# クライアントを初期化
client = Anthropic()
# ファイルを作成するコード実行をリクエスト
response = client.beta.messages.create(
model="claude-opus-4-8",
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":
# 具象型のリスト: List[BashCodeExecutionOutputBlock]
for file in content_item.content:
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}")| text_editor |
file_not_found |
| ファイルが存在しません(表示/編集操作の場合) |
| text_editor | string_not_found | ファイル内にold_strが見つかりません(str_replaceの場合) |
# 最初のリクエスト:ランダムな数値を含むファイルを作成
response1 = client.messages.create(
model="claude-opus-4-8",
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, # Reuse the same container
model="claude-opus-4-8",
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)