Claude dapat menganalisis data, membuat visualisasi, melakukan kalkulasi kompleks, menjalankan perintah sistem, membuat dan mengedit file, serta memproses file yang diunggah langsung dalam percakapan API. Tool eksekusi kode memungkinkan Claude menjalankan perintah Bash dan memanipulasi file, termasuk menulis kode, dalam lingkungan sandbox yang aman.

Tool eksekusi kode saat ini dalam beta publik.

Untuk menggunakan fitur ini, tambahkan beta header "code-execution-2025-08-25" ke permintaan API Anda.

Kami baru-baru ini meningkatkan tool eksekusi kode untuk mendukung perintah Bash dan manipulasi file langsung. Untuk instruksi upgrade ke versi tool terbaru, lihat Upgrade ke versi tool terbaru.

Model yang didukung

Tool eksekusi kode tersedia pada:

  • Claude Opus 4.1 (claude-opus-4-1-20250805)
  • 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)

Mulai cepat

Berikut contoh sederhana yang meminta Claude melakukan kalkulasi:

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-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [
            {
                "role": "user",
                "content": "Hitung rata-rata dan standar deviasi dari [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
            }
        ],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

Cara kerja eksekusi kode

Ketika Anda menambahkan tool eksekusi kode ke permintaan API Anda:

  1. Claude mengevaluasi apakah eksekusi kode akan membantu menjawab pertanyaan Anda
  2. Tool secara otomatis menyediakan Claude dengan kemampuan berikut:
    • Perintah Bash: Menjalankan perintah shell untuk operasi sistem dan manajemen paket
    • Operasi file: Membuat, melihat, dan mengedit file secara langsung, termasuk menulis kode
  3. Claude dapat menggunakan kombinasi kemampuan ini dalam satu permintaan
  4. Semua operasi berjalan dalam lingkungan sandbox yang aman
  5. Claude menyediakan hasil dengan grafik, kalkulasi, atau analisis yang dihasilkan

Cara menggunakan tool

Menjalankan perintah Bash

Minta Claude untuk memeriksa informasi sistem dan menginstal paket:

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-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": "Periksa versi Python dan daftar paket yang terinstal"
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

Membuat dan mengedit file secara langsung

Claude dapat membuat, melihat, dan mengedit file secara langsung dalam sandbox menggunakan kemampuan manipulasi file:

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-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": "Buat file config.yaml dengan pengaturan database, lalu perbarui port dari 5432 ke 3306"
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

Mengunggah dan menganalisis file Anda sendiri

Untuk menganalisis file data Anda sendiri (CSV, Excel, gambar, dll.), unggah melalui Files API dan referensikan dalam permintaan Anda:

Menggunakan Files API dengan Code Execution memerlukan dua beta header: "anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14"

Lingkungan Python dapat memproses berbagai jenis file yang diunggah melalui Files API, termasuk:

  • CSV
  • Excel (.xlsx, .xls)
  • JSON
  • XML
  • Gambar (JPEG, PNG, GIF, WebP)
  • File teks (.txt, .md, .py, dll)

Mengunggah dan menganalisis file

  1. Unggah file Anda menggunakan Files API
  2. Referensikan file dalam pesan Anda menggunakan blok konten container_upload
  3. Sertakan tool eksekusi kode dalam permintaan API Anda
# Pertama, unggah file
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"' \

# Kemudian gunakan file_id dengan eksekusi kode
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-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": [
                {"type": "text", "text": "Analisis data CSV ini"},
                {"type": "container_upload", "file_id": "file_abc123"}
            ]
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

Mengambil file yang dihasilkan

Ketika Claude membuat file selama eksekusi kode, Anda dapat mengambil file-file ini menggunakan Files API:

from anthropic import Anthropic

# Inisialisasi client
client = Anthropic()

# Permintaan eksekusi kode yang membuat file
response = client.beta.messages.create(
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25", "files-api-2025-04-14"],
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Buat visualisasi matplotlib dan simpan sebagai output.png"
    }],
    tools=[{
        "type": "code_execution_20250825",
        "name": "code_execution"
    }]
)

# Ekstrak file ID dari respons
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.get('type') == 'code_execution_result':
                for file in content_item.get('content', []):
                    file_ids.append(file['file_id'])
    return file_ids

# Unduh file yang dibuat
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"Diunduh: {file_metadata.filename}")

Menggabungkan operasi

Alur kerja kompleks menggunakan semua kemampuan:

# Pertama, unggah file
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

# Ekstrak file_id (menggunakan jq)
FILE_ID=$(jq -r '.id' file_response.json)

# Kemudian gunakan dengan eksekusi kode
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-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": [
                {
                    "type": "text", 
                    "text": "Analisis data CSV ini: buat laporan ringkasan, simpan visualisasi, dan buat README dengan temuan"
                },
                {
                    "type": "container_upload", 
                    "file_id": "'$FILE_ID'"
                }
            ]
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

Definisi tool

Tool eksekusi kode tidak memerlukan parameter tambahan:

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

Ketika tool ini disediakan, Claude secara otomatis mendapatkan akses ke dua sub-tool:

  • bash_code_execution: Menjalankan perintah shell
  • text_editor_code_execution: Melihat, membuat, dan mengedit file, termasuk menulis k

Format respons

Tool eksekusi kode dapat mengembalikan dua jenis hasil tergantung pada operasi:

Respons perintah 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
  }
}

Respons operasi file

Lihat file:

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

Buat file:

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

Edit file (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"]
  }
}

Hasil

Semua hasil eksekusi mencakup:

  • stdout: Output dari eksekusi yang berhasil
  • stderr: Pesan error jika eksekusi gagal
  • return_code: 0 untuk sukses, bukan nol untuk gagal

Field tambahan untuk operasi file:

  • View: file_type, content, numLines, startLine, totalLines
  • Create: is_file_update (apakah file sudah ada)
  • Edit: oldStart, oldLines, newStart, newLines, lines (format diff)

Error

Setiap jenis tool dapat mengembalikan error spesifik:

Error umum (semua tool):

{
  "type": "bash_code_execution_tool_result",
  "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
  "content": {
    "type": "bash_code_execution_tool_result_error",
    "error_code": "unavailable"
  }
}

Kode error berdasarkan jenis tool:

ToolKode ErrorDeskripsi
Semua toolunavailableTool sementara tidak tersedia
Semua toolexecution_time_exceededEksekusi melebihi batas waktu maksimum
Semua toolcontainer_expiredContainer kedaluwarsa dan tidak lagi tersedia
Semua toolinvalid_tool_inputParameter tidak valid diberikan ke tool
Semua tooltoo_many_requestsBatas rate terlampaui untuk penggunaan tool
text_editorfile_not_foundFile tidak ada (untuk operasi view/edit)
text_editorstring_not_foundold_str tidak ditemukan dalam file (untuk str_replace)

Alasan stop pause_turn

Respons mungkin mencakup alasan stop pause_turn, yang menunjukkan bahwa API menjeda turn yang berjalan lama. Anda dapat memberikan respons kembali apa adanya dalam permintaan berikutnya untuk membiarkan Claude melanjutkan turn-nya, atau memodifikasi konten jika Anda ingin mengganggu percakapan.

Container

Tool eksekusi kode berjalan dalam lingkungan container yang aman, dirancang khusus untuk eksekusi kode, dengan fokus lebih tinggi pada Python.

Lingkungan runtime

  • Versi Python: 3.11.12
  • Sistem operasi: Container berbasis Linux
  • Arsitektur: x86_64 (AMD64)

Batas sumber daya

  • Memori: 1GiB RAM
  • Ruang disk: 5GiB penyimpanan workspace
  • CPU: 1 CPU

Jaringan dan keamanan

  • Akses internet: Sepenuhnya dinonaktifkan untuk keamanan
  • Koneksi eksternal: Tidak ada permintaan jaringan keluar yang diizinkan
  • Isolasi sandbox: Isolasi penuh dari sistem host dan container lain
  • Akses file: Terbatas pada direktori workspace saja
  • Scoping workspace: Seperti Files, container dicakup ke workspace dari API key
  • Kedaluwarsa: Container kedaluwarsa 1 jam setelah dibuat

Library yang sudah terinstal

Lingkungan Python sandbox mencakup library yang umum digunakan ini:

  • Data Science: pandas, numpy, scipy, scikit-learn, statsmodels
  • Visualisasi: matplotlib, seaborn
  • Pemrosesan File: pyarrow, openpyxl, xlrd, pillow, python-pptx, python-docx, pypdf, pdfplumber, pypdfium2, pdf2image, pdfkit, tabula-py, reportlab[pycairo], Img2pdf
  • Math & Computing: sympy, mpmath
  • Utilitas: tqdm, python-dateutil, pytz, joblib, unzip, unrar, 7zip, bc, rg (ripgrep), fd, sqlite

Penggunaan ulang container

Anda dapat menggunakan ulang container yang ada di beberapa permintaan API dengan menyediakan ID container dari respons sebelumnya. Ini memungkinkan Anda mempertahankan file yang dibuat antar permintaan.

Contoh

import os
from anthropic import Anthropic

# Inisialisasi client
client = Anthropic(
    api_key=os.getenv("ANTHROPIC_API_KEY")
)

# Permintaan pertama: Buat file dengan angka acak
response1 = client.beta.messages.create(
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25"],
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Tulis file dengan angka acak dan simpan ke '/tmp/number.txt'"
    }],
    tools=[{
        "type": "code_execution_20250825",
        "name": "code_execution"
    }]
)

# Ekstrak ID container dari respons pertama
container_id = response1.container.id

# Permintaan kedua: Gunakan ulang container untuk membaca file
response2 = client.beta.messages.create(
    container=container_id,  # Gunakan ulang container yang sama
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25"],
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Baca angka dari '/tmp/number.txt' dan hitung kuadratnya"
    }],
    tools=[{
        "type": "code_execution_20250825",
        "name": "code_execution"
    }]
)

Streaming

Dengan streaming diaktifkan, Anda akan menerima event eksekusi kode saat terjadi:

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}

// Eksekusi kode di-stream
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())\"}"}}

// Jeda saat kode dieksekusi

// Hasil eksekusi di-stream
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": ""}}}

Permintaan batch

Anda dapat menyertakan tool eksekusi kode dalam Messages Batches API. Panggilan tool eksekusi kode melalui Messages Batches API dikenakan harga yang sama dengan yang ada di permintaan Messages API reguler.

Penggunaan dan harga

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.

Upgrade ke versi tool terbaru

Dengan upgrade ke code-execution-2025-08-25, Anda mendapatkan akses ke manipulasi file dan kemampuan Bash, termasuk kode dalam berbagai bahasa. Tidak ada perbedaan harga.

Yang berubah

KomponenLegacySaat ini
Beta headercode-execution-2025-05-22code-execution-2025-08-25
Jenis toolcode_execution_20250522code_execution_20250825
KemampuanHanya PythonPerintah Bash, operasi file
Jenis responscode_execution_resultbash_code_execution_result, text_editor_code_execution_result

Kompatibilitas mundur

  • Semua eksekusi kode Python yang ada terus bekerja persis seperti sebelumnya
  • Tidak ada perubahan yang diperlukan untuk alur kerja khusus Python

Langkah upgrade

Untuk upgrade, Anda perlu membuat perubahan berikut dalam permintaan API Anda:

  1. Perbarui beta header:

    - "anthropic-beta": "code-execution-2025-05-22"
    + "anthropic-beta": "code-execution-2025-08-25"
    
  2. Perbarui jenis tool:

    - "type": "code_execution_20250522"
    + "type": "code_execution_20250825"
    
  3. Tinjau penanganan respons (jika mem-parsing respons secara programatis):

    • Blok sebelumnya untuk respons eksekusi Python tidak akan lagi dikirim
    • Sebagai gantinya, jenis respons baru untuk operasi Bash dan file akan dikirim (lihat bagian Format Respons)