Claudeは、API会話内で直接、データの分析、可視化の作成、複雑な計算の実行、システムコマンドの実行、ファイルの作成と編集、アップロードされたファイルの処理を行うことができます。コード実行ツールにより、Claudeは安全でサンドボックス化された環境で、Bashコマンドの実行や、コードの記述を含むファイルの操作を行うことができます。
コード実行は、web検索またはwebフェッチ(web_search_20260209、web_fetch_20260209、またはそれ以降)と併用する場合は無料です。 これらのツールのいずれかがリクエストに含まれている場合、そのリクエストにおけるコード実行に対して、標準のトークンコスト以外の追加料金は発生しません。これは、動的フィルタリングの背後にあるコード実行と、Claudeが直接実行するコードの両方を対象とします。これらが含まれていない場合は、標準のコード実行料金が適用されます。
コード実行は、web検索およびwebフェッチツールの動的フィルタリングも支えています。Claudeは、結果がコンテキストウィンドウに到達する前に、コード実行環境内で結果をフィルタリングします。動的フィルタリングが実行されると、APIはリクエストに必要なコード実行を自動的にプロビジョニングするため、そのためにコード実行ツールをリクエストに追加する必要はありません。
この機能に関するフィードバックは、フィードバックフォームからお寄せください。
この機能は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 Sonnet 5 (claude-sonnet-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、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.1 (claude-opus-4-1-20250805) (非推奨) | code_execution_20250825 |
各ツールバージョンは、前のバージョンを基盤として構築されています。
code_execution_20250825は、Bashコマンドとファイル操作をサポートし、表内のすべてのモデルで利用できます。code_execution_20260120は、REPL状態の永続化と、サンドボックス内からのプログラマティックツール呼び出しを追加します。Claude Haiku 4.5はcode_execution_20260120およびcode_execution_20260521のツールタイプを受け付けますが、プログラマティックツール呼び出しと、それに依存するREPL状態の永続化は利用できないため、これらの新しいバージョンはcode_execution_20250825と同様に動作します。code_execution_20260521は、code_execution_20260120と同じランタイムです。違いは、ツールの説明がプログラマティックツール呼び出しにおける各Pythonセルの90秒の実時間(wall-clock)制限についてClaudeに伝えるため、Claudeが長時間実行されるセルの時間配分を計画できる点です。制限を超えたセルは、ゼロ以外のreturn_codeと、出力内のdetection_timeoutステータスメッセージを含む通常のコード実行結果を返します。これは、ツール呼び出し全体が最大実行時間を超えた場合にAPIが返すexecution_time_exceededエラーコードとは別のものです。3つのツールバージョンはすべて一般提供されており、anthropic-betaヘッダーは必要ありません。従来のコード実行ベータヘッダーは、引き続き有効なオプトインとして機能します。
このページの例では、表内のすべてのモデルがサポートしているため、code_execution_20250825を使用しています。現在のweb検索およびwebフェッチツール(web_search_20260209、web_fetch_20260209、およびそれ以降)は、コード実行バージョンとしてcode_execution_20260120以降を必要とします。
従来のcode_execution_20250522(Pythonのみ)をまだ使用している場合は、最新のツールバージョンへのアップグレードを参照して移行してください。
古いツールバージョンは、新しいモデルとの後方互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
コード実行は以下で利用できます。
コード実行は現在、Amazon BedrockおよびGoogle Cloudでは利用できません。
Claude Mythos Previewの場合、コード実行はClaude APIとMicrosoft Foundryでのみサポートされています。Amazon Bedrock、Google Cloud、またはClaude Platform on AWS上のMythos Previewでは利用できません。
Claudeに計算を実行させる簡単な例を以下に示します。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Use the code execution tool to 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.to_json())レスポンスでは、server_tool_useブロック(Claudeが実行したコマンド)とそのツール結果ブロックが交互に配置され、その後にClaudeのテキストが続きます。トップレベルにはcontainerオブジェクトも含まれており、そのidをリクエスト間で再利用できます。ブロックの形式については、レスポンス形式を参照してください。
コード実行ツールをAPIリクエストに追加すると、次のようになります。
tool_resultブロックを送り返したりする必要はありません。例外は、Claudeがコード実行と並行してクライアントツールのいずれかを呼び出す場合です。この場合、APIはコード実行の呼び出しを結果なしで返します。結果は、クライアントツールのtool_resultブロックを送り返した後、後続のレスポンスで届きますコンテナにはPythonがプリインストールされています。Claudeはファイル操作サブツールでPythonを記述し、Bashコマンドで実行します。code_execution_20260120以降とプログラマティックツール呼び出しを使用すると、Pythonインタープリタの状態(変数バインディングなど)も、コンテナを再利用するリクエスト間で永続化されます。
Claudeは、リクエストが計算やファイル処理から恩恵を受ける場合にコードを実行します。
Claudeは、以下の場合はコードを実行せずに直接回答します。
境界線上のリクエストでClaudeにコードを実行させたい場合は、明示的に依頼してください(例:「コードを実行してこれを検証して」)。
独自のデータファイル(CSV、Excel、画像など)を分析するには、Files APIを通じてアップロードし、リクエスト内で参照します。
Files APIをコード実行と併用するには、Files APIベータヘッダーが必要です: "anthropic-beta": "files-api-2025-04-14"
Python環境は、Files APIを通じてアップロードされたさまざまなファイルタイプを処理できます。以下が含まれます。
container_uploadコンテンツブロックを使用して、メッセージ内でファイルを参照しますclient = anthropic.Anthropic()
# ファイルをアップロードします
file_object = client.beta.files.upload(file=Path("data.csv"))
# 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.to_json())Claudeがコード実行中にファイルを作成すると、作成された各ファイルのIDがコード実行のツール結果に表示され、Files APIでダウンロードできます。
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: BetaMessage) -> list[str]:
file_ids: list[str] = []
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 output_block in content_item.content:
file_ids.append(output_block.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}")コード実行ツールには追加のパラメータは必要ありません。
{
"type": "code_execution_20250825",
"name": "code_execution"
}両方のフィールドは固定です。typeはツールバージョンを選択し、nameはcode_executionでなければなりません。
このツールが提供されると、Claudeは自動的に2つのサブツールにアクセスできるようになります。
bash_code_execution: シェルコマンドを実行text_editor_code_execution: コードの記述を含む、ファイルの表示、作成、編集Claudeがコードを実行すると、レスポンスにはコンテナのidとexpires_atタイムスタンプを持つトップレベルのcontainerオブジェクトも含まれます。同じコンテナを使い続けるには、そのIDをトップレベルのcontainerリクエストパラメータで渡し返します。コンテナの再利用を参照してください。
コード実行ツールは、操作に応じて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,
"content": []
}
}ファイルの表示:
{
"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_view_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"num_lines": 4,
"start_line": 1,
"total_lines": 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_create_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_str_replace_result",
"old_start": 3,
"old_lines": 1,
"new_start": 3,
"new_lines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}Bashコマンドの結果(bash_code_execution_result)には以下が含まれます。
stdout: 実行が成功した場合の出力stderr: 実行が失敗した場合のエラーメッセージreturn_code: 成功の場合は0、失敗の場合はゼロ以外content: コマンドが作成した各ファイルのエントリを含むリスト。各エントリには、Files APIでファイルを取得するためのfile_idが含まれますファイル操作の結果には、それぞれ独自のフィールドがあります。
text_editor_code_execution_view_result): file_type、content、num_lines、start_line、total_linestext_editor_code_execution_create_result): is_file_update(ファイルがすでに存在していたかどうか)text_editor_code_execution_str_replace_result): old_start、old_lines、new_start、new_lines、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 | ツール呼び出しが最大実行時間を超えました |
| すべてのツール | invalid_tool_input | ツールに無効なパラメータが提供されました |
| すべてのツール | too_many_requests | ツール使用のレート制限を超えました |
| bash | output_file_too_large | コマンド出力が最大サイズを超えました |
| text_editor | file_not_found | ファイルが存在しません(表示/編集操作の場合) |
期限切れのコンテナは再利用できません。それを参照するリクエストは、復元する代わりにエラーを返します。新しいコンテナを取得するには、containerパラメータなしでリクエストを再送信してください。
pause_turn停止理由レスポンスにはpause_turn停止理由が含まれることがあります。これは、APIが長時間実行されているターンを一時停止したことを示します。レスポンスをそのまま後続のリクエストで返してClaudeにターンを続行させることも、会話を中断したい場合はコンテンツを変更することもできます。
コード実行ツールは、コード実行専用に設計された安全なコンテナ化環境で実行され、特にPythonに重点を置いています。
execution_time_exceededエラーを返します。プログラマティックツール呼び出しでは、各REPLセルにも90秒の実時間制限がありますサンドボックス化されたPython環境には、以下のよく使用されるライブラリが含まれています。
コンテナには、unzip、unrar、7zip、bc、rg(ripgrep)、fd、sqliteなどのコマンドラインツールも含まれています。
コンテナにはインターネットアクセスがないため、Claudeは実行時に追加のパッケージをダウンロードまたはインストールできません。プリインストールされたライブラリのみが利用可能です。
以前のレスポンスのコンテナIDを提供することで、複数のAPIリクエストにわたって既存のコンテナを再利用できます。これにより、リクエスト間で作成されたファイルを維持できます。code_execution_20260120以降とプログラマティックツール呼び出しを使用すると、Pythonインタープリタの状態も永続化されます。
コンテナは作成から30日後に期限切れになります。約5分間の非アクティブ状態の後、コンテナはチェックポイントされ、30日間のウィンドウ内でそのIDを含むリクエストを送信すると復元されます。レスポンスのcontainerオブジェクト内のexpires_atタイムスタンプは、より短いローリング値であり、30日間の制限を示すものではありません。期限切れになったコンテナは再利用できません。新しいコンテナを取得するには、containerパラメータなしでリクエストを再送信してください。
client = anthropic.Anthropic()
# 最初のリクエスト:新しいコンテナにランダムな数値を含むファイルを作成
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"}],
)
# 2番目のリクエスト:コンテナIDを渡してClaudeに同じコンテナを再利用させる
response2 = client.messages.create(
container=response1.container.id,
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.to_json())コードを実行するクライアント提供のツール(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これは、コード実行を自動的に有効にするweb検索またはwebフェッチとコード実行を組み合わせる場合に特に重要です。アプリケーションがすでにクライアントサイドのシェルツールを提供している場合、自動的なコード実行により、Claudeが区別する必要のある2つ目の実行環境が作成されます。
Claudeがコード実行と並行してクライアントツールのいずれかを呼び出すと、APIはコード実行の呼び出しを結果なしで返します。結果は、クライアントツールのtool_resultブロックを送り返した後、後続のレスポンスで届きます。
ストリーミングを有効にすると("stream": true)、コード実行イベントを発生時に受信できます。サブツールの入力はinput_json_deltaイベントとしてストリーミングされ、各結果ブロックは単一のcontent_block_startイベントで丸ごと届きます。
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "bash_code_execution"}}
// Tool input streamed as partial JSON
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"python analyze.py\"}"}}
// Pause while the command runs
// Execution result delivered as a complete block
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "bash_code_execution_result", "stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": "", "return_code": 0, "content": []}}}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_20260521です。現在の3つのバージョン間を移行するには、リクエスト内のtype文字列を更新します。3つすべてがレスポンス形式に記載されているレスポンスブロックを返します。各バージョンが追加する機能と、それをサポートするモデルについては、モデルの互換性を参照してください。
このセクションの残りの部分では、従来のPython専用のcode_execution_20250522から現在のツールバージョンへの移行について説明します。
| コンポーネント | 従来 | 現在 |
|---|---|---|
| ベータヘッダー | code-execution-2025-05-22 | 不要 |
| ツールタイプ | 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とデータ保持を参照してください。
より高速なエグゼキューターモデルと、生成中に戦略的なガイダンスを提供する、より高い知能を持つアドバイザーモデルを組み合わせます。
コード実行コンテナ内で実行されるコードから、独自のツールを呼び出します。
分析用のファイルをアップロードし、コード実行が作成したファイルをダウンロードします。
Agent Skillsを使用してAPIを通じてClaudeの機能を拡張する方法を学びます。
Was this page helpful?