Claude dapat menganalisis data, membuat visualisasi, melakukan perhitungan kompleks, menjalankan perintah sistem, membuat dan mengedit file, serta memproses file yang diunggah langsung dalam percakapan API. Alat eksekusi kode memungkinkan Claude menjalankan perintah Bash dan memanipulasi file, termasuk menulis kode, dalam lingkungan sandbox yang aman.
Alat eksekusi kode saat ini dalam beta publik.
Untuk menggunakan fitur ini, tambahkan header beta "code-execution-2025-08-25" ke permintaan API Anda.
Alat eksekusi kode tersedia pada model berikut:
| Model | Versi Alat |
|---|---|
Claude Opus 4.5 (claude-opus-4-5-20251101) | 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.5 (claude-sonnet-4-5-20250929) | code_execution_20250825 |
Claude Sonnet 4 (claude-sonnet-4-20250514) | code_execution_20250825 |
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219) (tidak direkomendasikan) | code_execution_20250825 |
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
Claude Haiku 3.5 (claude-3-5-haiku-latest) | code_execution_20250825 |
Versi saat ini code_execution_20250825 mendukung perintah Bash dan operasi file. Versi lama code_execution_20250522 (hanya Python) juga tersedia. Lihat Tingkatkan ke versi alat terbaru untuk detail migrasi.
Versi alat yang lebih lama tidak dijamin kompatibel mundur dengan model yang lebih baru. Selalu gunakan versi alat yang sesuai dengan versi model Anda.
Berikut adalah contoh sederhana yang meminta Claude melakukan perhitungan:
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-sonnet-4-5",
"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"
}]
}'Ketika Anda menambahkan alat eksekusi kode ke permintaan API Anda:
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-sonnet-4-5",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": "Check the Python version and list installed packages"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'Claude dapat membuat, melihat, dan mengedit file secara langsung di 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-sonnet-4-5",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": "Create a config.yaml file with database settings, then update the port from 5432 to 3306"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'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 header beta: "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:
container_upload# 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-sonnet-4-5",
"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_20250825",
"name": "code_execution"
}]
}'Ketika Claude membuat file selama eksekusi kode, Anda dapat mengambil file ini menggunakan Files API:
from anthropic import Anthropic
# Inisialisasi klien
client = Anthropic()
# Minta eksekusi kode yang membuat file
response = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25", "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"
}]
)
# Ekstrak ID file 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.type == 'bash_code_execution_result':
for file in content_item.content:
if hasattr(file, 'file_id'):
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"Downloaded: {file_metadata.filename}")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-sonnet-4-5",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this CSV data: create a summary report, save visualizations, and create a README with the findings"
},
{
"type": "container_upload",
"file_id": "'$FILE_ID'"
}
]
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'Alat eksekusi kode tidak memerlukan parameter tambahan:
{
"type": "code_execution_20250825",
"name": "code_execution"
}Ketika alat ini disediakan, Claude secara otomatis mendapatkan akses ke dua sub-alat:
bash_code_execution: Jalankan perintah shelltext_editor_code_execution: Lihat, buat, dan edit file, termasuk menulis kodeAlat eksekusi kode dapat mengembalikan dua jenis hasil tergantung pada operasi:
{
"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
}
}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"]
}
}Semua hasil eksekusi mencakup:
stdout: Output dari eksekusi yang berhasilstderr: Pesan kesalahan jika eksekusi gagalreturn_code: 0 untuk sukses, non-nol untuk kegagalanBidang tambahan untuk operasi file:
file_type, content, numLines, startLine, totalLinesis_file_update (apakah file sudah ada)oldStart, oldLines, newStart, newLines, lines (format diff)Setiap jenis alat dapat mengembalikan kesalahan spesifik:
Kesalahan umum (semua alat):
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
"content": {
"type": "bash_code_execution_tool_result_error",
"error_code": "unavailable"
}
}Kode kesalahan menurut jenis alat:
| Alat | Kode Kesalahan | Deskripsi |
|---|---|---|
| Semua alat | unavailable | Alat tidak tersedia sementara |
| Semua alat | execution_time_exceeded | Eksekusi melampaui batas waktu maksimum |
| Semua alat | container_expired | Kontainer kedaluwarsa dan tidak lagi tersedia |
| Semua alat | invalid_tool_input | Parameter tidak valid diberikan ke alat |
| Semua alat | too_many_requests | Batas laju terlampaui untuk penggunaan alat |
| text_editor | file_not_found | File tidak ada (untuk operasi lihat/edit) |
| text_editor | string_not_found | old_str tidak ditemukan dalam file (untuk str_replace) |
pause_turnRespons mungkin menyertakan alasan penghentian pause_turn, yang menunjukkan bahwa API menjeda giliran yang berjalan lama. Anda dapat memberikan respons kembali apa adanya dalam permintaan berikutnya untuk membiarkan Claude melanjutkan gilirannya, atau memodifikasi konten jika Anda ingin mengganggu percakapan.
Alat eksekusi kode berjalan dalam lingkungan yang terkontainer dan aman yang dirancang khusus untuk eksekusi kode, dengan fokus yang lebih tinggi pada Python.
Lingkungan Python sandbox mencakup perpustakaan yang umum digunakan ini:
Anda dapat menggunakan kembali kontainer yang ada di beberapa permintaan API dengan menyediakan ID kontainer dari respons sebelumnya. Ini memungkinkan Anda mempertahankan file yang dibuat antar permintaan.
import os
from anthropic import Anthropic
# Inisialisasi klien
client = Anthropic(
api_key=os.getenv("ANTHROPIC_API_KEY")
)
# Permintaan pertama: Buat file dengan angka acak
response1 = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25"],
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"
}]
)
# Ekstrak ID kontainer dari respons pertama
container_id = response1.container.id
# Permintaan kedua: Gunakan kembali kontainer untuk membaca file
response2 = client.beta.messages.create(
container=container_id, # Gunakan kembali kontainer yang sama
model="claude-sonnet-4-5",
betas=["code-execution-2025-08-25"],
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"
}]
)Dengan streaming diaktifkan, Anda akan menerima peristiwa 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-streaming
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 dijalankan
// Hasil eksekusi di-streaming
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": ""}}}Anda dapat menyertakan alat eksekusi kode dalam Messages Batches API. Panggilan alat eksekusi kode melalui Messages Batches API dihargai sama dengan yang ada di permintaan Messages API reguler.
Code execution tool usage is tracked separately from token usage. Execution time has 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.
Each organization receives 50 free hours of usage with the code execution tool per day. Additional usage beyond the first 50 hours is billed at $0.05 per hour, per container.
Dengan meningkatkan ke code-execution-2025-08-25, Anda mendapatkan akses ke manipulasi file dan kemampuan Bash, termasuk kode dalam berbagai bahasa. Tidak ada perbedaan harga.
| Komponen | Lama | Saat Ini |
|---|---|---|
| Header beta | code-execution-2025-05-22 | code-execution-2025-08-25 |
| Jenis alat | code_execution_20250522 | code_execution_20250825 |
| Kemampuan | Hanya Python | Perintah Bash, operasi file |
| Jenis respons | code_execution_result | bash_code_execution_result, text_editor_code_execution_result |
Untuk upgrade, Anda perlu membuat perubahan berikut dalam permintaan API Anda:
Perbarui header beta:
- "anthropic-beta": "code-execution-2025-05-22"
+ "anthropic-beta": "code-execution-2025-08-25"Perbarui jenis alat:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"Tinjau penanganan respons (jika mengurai respons secara terprogram):
Alat eksekusi kode memberdayakan pemanggilan alat terprogram, yang memungkinkan Claude menulis kode yang memanggil alat kustom Anda secara terprogram dalam kontainer eksekusi. Ini memungkinkan alur kerja multi-alat yang efisien, penyaringan data sebelum mencapai konteks Claude, dan logika bersyarat yang kompleks.
# Aktifkan pemanggilan terprogram untuk alat Anda
response = client.beta.messages.create(
model="claude-sonnet-4-5",
betas=["advanced-tool-use-2025-11-20"],
max_tokens=4096,
messages=[{
"role": "user",
"content": "Get weather for 5 cities and find the warmest"
}],
tools=[
{
"type": "code_execution_20250825",
"name": "code_execution"
},
{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {...},
"allowed_callers": ["code_execution_20250825"] # Aktifkan pemanggilan terprogram
}
]
)Pelajari lebih lanjut dalam dokumentasi pemanggilan alat terprogram.
Alat eksekusi kode memungkinkan Claude menggunakan Agent Skills. Skills adalah kemampuan modular yang terdiri dari instruksi, skrip, dan sumber daya yang memperluas fungsionalitas Claude.
Pelajari lebih lanjut dalam dokumentasi Agent Skills dan panduan API Agent Skills.