Loading...
  • ビルド
  • 管理
  • モデルと料金
  • クライアントSDK
  • APIリファレンス
Search...
⌘K
Log in
コード実行ツール
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
ビルド/ツール

コード実行ツール

サンドボックス化されたコンテナでPythonとbashコードを実行して、データを分析し、ファイルを生成し、ソリューションを反復処理します。

Was this page helpful?

  • Bashコマンドレスポンス
  • Agent Skillsでのコード実行の使用

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と同じモデルで利用可能です。最新ツールバージョンへのアップグレードを参照して、それから移行してください。

古いツールバージョンは、新しいモデルとの下位互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。

プラットフォーム可用性

コード実行は以下で利用可能です:

  • Claude API(Anthropic)
  • Microsoft Azure AI Foundry

コード実行は現在Amazon BedrockまたはGoogle Vertex AIでは利用できません。

Claude Mythos Previewの場合、コード実行はClaude APIおよびMicrosoft Foundryでサポートされています。Amazon BedrockまたはGoogle Vertex AIのMythos Previewでは利用できません。

クイックスタート

Claudeに計算を実行するよう求める簡単な例を次に示します:

コード実行の仕組み

APIリクエストにコード実行ツールを追加する場合:

  1. Claudeは質問に答えるのにコード実行が役立つかどうかを評価します
  2. ツールは自動的にClaudeに以下の機能を提供します:
    • Bashコマンド:システム操作とパッケージ管理のためのシェルコマンドを実行します
    • ファイル操作:コードの記述を含め、ファイルを直接作成、表示、編集します
  3. Claudeは単一のリクエスト内でこれらの機能の任意の組み合わせを使用できます
  4. すべての操作はセキュアなサンドボックス環境で実行されます
  5. Claudeは生成されたチャート、計算、または分析を含む結果を提供します

他の実行ツールでのコード実行の使用

コード実行をコードも実行するクライアント提供ツール(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を使用してアップロードされた様々なファイルタイプを処理できます:

  • CSV
  • Excel (.xlsx, .xls)
  • JSON
  • XML
  • 画像 (JPEG, PNG, GIF, WebP)
  • テキストファイル (.txt, .md, .py など)

ファイルをアップロードして分析する

  1. ファイルをアップロードする Files APIを使用
  2. ファイルを参照する container_upload コンテンツブロックを使用してメッセージ内で
  3. コード実行ツールを含める APIリクエストに

生成されたファイルを取得する

Claudeがコード実行中にファイルを作成する場合、Files APIを使用してこれらのファイルを取得できます:

ツール定義

コード実行ツールは追加のパラメータを必要としません:

JSON
{
  "type": "code_execution_20250825",
  "name": "code_execution"
}

このツールが提供されると、Claudeは自動的に2つのサブツールにアクセスできるようになります:

  • bash_code_execution: シェルコマンドを実行
  • text_editor_code_execution: ファイルを表示、作成、編集し、コードを書き込む

レスポンス形式

コード実行ツールは、操作に応じて2つのタイプの結果を返すことができます:

Bashコマンドレスポンス

Output
{
  "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
  }
}

ファイル操作レスポンス

ファイルを表示:

Output
{
  "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
  }
}

ファイルを作成:

Output
{
  "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):

Output
{
  "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形式)

エラー

各ツールタイプは特定のエラーを返すことができます:

共通エラー (すべてのツール):

Output
{
  "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ツール使用のレート制限を超過しました
bashoutput_file_too_largeコマンド出力が最大サイズを超過しました

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リクエスト間で既存のコンテナを再利用できます。これにより、リクエスト間で作成されたファイルを保持できます。

例

ストリーミング

ストリーミングを有効にすると、コード実行イベントが発生時に受け取られます:

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:

  • Execution time has a minimum of 5 minutes
  • Each organization receives 1,550 free hours of usage per month
  • Additional usage beyond 1,550 hours is billed at $0.05 per hour, per container
  • If files are included in the request, execution time is billed even if the tool is not invoked, due to files being preloaded onto the container

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-22code-execution-2025-08-25
ツールタイプcode_execution_20250522code_execution_20250825
機能PythonのみBashコマンド、ファイル操作
レスポンスタイプcode_execution_resultbash_code_execution_result、text_editor_code_execution_result

後方互換性

  • 既存のすべてのPythonコード実行は以前と同じように機能します
  • 既存のPythonのみのワークフローに変更は不要です

アップグレード手順

アップグレードするには、APIリクエストのツールタイプを更新します:

- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"

レスポンス処理の確認(プログラムでレスポンスを解析する場合):

  • Python実行レスポンスの以前のブロックは送信されなくなります
  • 代わりに、Bashとファイル操作の新しいレスポンスタイプが送信されます(レスポンス形式セクションを参照)

プログラマティックツール呼び出し

コード実行コンテナ内でツールを実行するには、プログラマティックツール呼び出しを参照してください。

データ保持

コード実行はサーバー側のサンドボックスコンテナで実行されます。実行アーティファクト、アップロードされたファイル、出力を含むコンテナデータは最大30日間保持されます。この保持はコンテナ環境内で処理されるすべてのデータに適用されます。コード実行がFiles APIに作成するファイル(client.beta.files.download()経由で取得可能)は、明示的に削除されるまで保持されます。

すべての機能にわたるZDR適格性については、API とデータ保持を参照してください。

Agent Skillsでのコード実行の使用

コード実行ツールにより、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_editorstring_not_foundold_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)