コード実行ツールは、Claudeが安全なサンドボックス環境でPythonコードを実行することを可能にします。 Claudeは、データの分析、視覚化の作成、複雑な計算の実行、およびアップロードされたファイルの処理を API会話内で直接行うことができます。

コード実行ツールは現在ベータ版です。

この機能にはベータヘッダーが必要です:"anthropic-beta": "code-execution-2025-05-22"

サポートされているモデル

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

  • Claude Opus 4 (claude-opus-4-20250514)
  • Claude Sonnet 4 (claude-sonnet-4-20250514)
  • Claude Sonnet 3.7 (claude-3-7-sonnet-20250219)
  • Claude Haiku 3.5 (claude-3-5-haiku-latest)

クイックスタート

以下は、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-05-22" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "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_20250522",
            "name": "code_execution"
        }]
    }'

コード実行の仕組み

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

  1. Claudeは、コード実行があなたの質問に答えるのに役立つかどうかを評価します
  2. Claudeは安全なサンドボックス環境でPythonコードを書いて実行します
  3. コード実行は単一のリクエスト中に複数回発生する可能性があります
  4. Claudeは生成されたチャート、計算、または分析とともに結果を提供します

ツール定義

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

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

レスポンス形式

以下はコード実行を含むレスポンスの例です:

{
  "role": "assistant",
  "container": {
    "id": "container_011CPR5CNjB747bTd36fQLFk",
    "expires_at": "2025-05-23T21:13:31.749448Z"
  },
  "content": [
    {
      "type": "text",
      "text": "I'll calculate the mean and standard deviation for you."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "name": "code_execution",
      "input": {
        "code": "import numpy as np\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nmean = np.mean(data)\nstd = np.std(data)\nprint(f\"Mean: {mean}\")\nprint(f\"Standard deviation: {std}\")"
      }
    },
    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "content": {
        "type": "code_execution_result",
        "stdout": "Mean: 5.5\nStandard deviation: 2.8722813232690143\n",
        "stderr": "",
        "return_code": 0
      }
    },
    {
      "type": "text",
      "text": "The mean of the dataset is 5.5 and the standard deviation is approximately 2.87."
    }
  ],
  "id": "msg_01BqK2v4FnRs4xTjgL8EuZxz",
  "model": "claude-opus-4-20250514",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 45,
    "output_tokens": 187,
  }
}

結果

コード実行結果には以下が含まれます:

  • stdout:print文と成功した実行からの出力
  • stderr:コード実行が失敗した場合のエラーメッセージ
  • return_code(成功の場合は0、失敗の場合は非ゼロ)
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01ABC123",
  "content": {
    "type": "code_execution_result",
    "stdout": "",
    "stderr": "NameError: name 'undefined_variable' is not defined",
    "return_code": 1
  }
}

エラー

ツールの使用でエラーが発生した場合、code_execution_tool_result_errorが表示されます

{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
  "content": {
    "type": "code_execution_tool_result_error",
    "error_code": "unavailable"
  }
}

可能なエラーには以下が含まれます

  • unavailable:コード実行ツールが利用できません
  • code_execution_exceeded:実行時間が最大許可時間を超えました
  • container_expired:コンテナが期限切れで利用できません

pause_turn停止理由

レスポンスにはpause_turn停止理由が含まれる場合があり、これはAPIが長時間実行されるターンを一時停止したことを示します。後続のリクエストでレスポンスをそのまま提供してClaudeにターンを続行させるか、会話を中断したい場合はコンテンツを変更することができます。

コード実行でのファイルの操作

コード実行は、CSVファイル、Excelファイル、その他のデータ形式など、Files APIを介してアップロードされたファイルを分析できます。 これにより、Claudeはあなたのデータを読み取り、処理し、洞察を生成できます。リクエストごとに複数のファイルを渡すことができます。

コード実行でFiles APIを使用するには、2つのベータヘッダーが必要です:"anthropic-beta": "code-execution-2025-05-22,files-api-2025-04-14"

サポートされているファイルタイプ

Python環境は以下のファイルタイプを操作できますが、これらに限定されません

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

コード実行用のファイルの読み込み

  1. ファイルをアップロードFiles APIを使用してファイルをアップロードします
  2. ファイルを参照container_uploadコンテンツブロックを使用してメッセージでファイルを参照します
  3. コード実行ツールを含める: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"' \

# 次に、file_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-05-22,files-api-2025-04-14" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "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_20250522",
            "name": "code_execution"
        }]
    }'

コード実行で作成されたファイルの取得

Claudeがコード実行中にファイルを作成した場合(例:matplotlibプロットの保存、CSVの生成)、Files APIを使用してこれらのファイルを取得できます:

from anthropic import Anthropic

# クライアントを初期化します
client = Anthropic()

# ファイルを作成するコード実行をリクエストします
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    betas=["code-execution-2025-05-22", "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_20250522",
        "name": "code_execution"
    }]
)

# レスポンスからfile_idを抽出します
def extract_file_ids(response):
    file_ids = []
    for item in response.content:
        if item.type == 'code_execution_tool_result':
            content_item = item.content
            if content_item.get('type') == 'code_execution_result':
                for file in content_item.get('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}")

コンテナ

コード実行ツールは、Pythonコード実行専用に設計された安全なコンテナ化環境で実行されます。

ランタイム環境

  • Pythonバージョン:3.11.12
  • オペレーティングシステム:Linuxベースのコンテナ
  • アーキテクチャ:x86_64 (AMD64)

リソース制限

  • メモリ:1GiB RAM
  • ディスク容量:5GiBワークスペースストレージ
  • CPU:1 CPU

ネットワークとセキュリティ

  • インターネットアクセス:セキュリティのため完全に無効
  • 外部接続:アウトバウンドネットワークリクエストは許可されません
  • サンドボックス分離:ホストシステムと他のコンテナからの完全な分離
  • ファイルアクセス:ワークスペースディレクトリのみに制限
  • ワークスペーススコープFilesと同様に、コンテナはAPIキーのワークスペースにスコープされます
  • 有効期限:コンテナは作成から1時間後に期限切れになります

プリインストールライブラリ

サンドボックス化されたPython環境には、これらの一般的に使用されるライブラリが含まれています:

  • データサイエンス:pandas、numpy、scipy、scikit-learn、statsmodels
  • 視覚化:matplotlib
  • ファイル処理:pyarrow、openpyxl、xlrd、pillow
  • 数学・計算:sympy、mpmath
  • ユーティリティ:tqdm、python-dateutil、pytz、joblib

コンテナの再利用

以前のレスポンスからコンテナIDを提供することで、複数のAPIリクエスト間で既存のコンテナを再利用できます。 これにより、リクエスト間で作成されたファイルを維持できます。

import os
from anthropic import Anthropic

# クライアントを初期化します
client = Anthropic(
    api_key=os.getenv("ANTHROPIC_API_KEY")
)

# 最初のリクエスト:ランダムな数値でファイルを作成します
response1 = client.beta.messages.create(
    model="claude-opus-4-20250514",
    betas=["code-execution-2025-05-22"],
    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_20250522",
        "name": "code_execution"
    }]
)

# 最初のレスポンスからコンテナIDを抽出します
container_id = response1.container.id

# 2番目のリクエスト:コンテナを再利用してファイルを読み取ります
response2 = client.beta.messages.create(
    container=container_id,  # 同じコンテナを再利用します
    model="claude-opus-4-20250514",
    betas=["code-execution-2025-05-22"],
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Read the number from '/tmp/number.txt' and calculate its square"
    }],
    tools=[{
        "type": "code_execution_20250522",
        "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リクエストと同じ価格で提供されます。

使用方法と価格

The code execution tool usage is tracked separately from token usage. Execution time is 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.

Pricing: $0.05 per session-hour.