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.6 (claude-opus-4-6) | code_execution_20250825 |
Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825 |
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 (claude-sonnet-4-20250514) | code_execution_20250825 |
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219) (устарела) | 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 |
Текущая версия code_execution_20250825 поддерживает команды Bash и операции с файлами. Также доступна устаревшая версия code_execution_20250522 (только Python). Подробности о миграции см. в разделе Обновление до последней версии инструмента.
Обратная совместимость старых версий инструментов с более новыми моделями не гарантируется. Всегда используйте версию инструмента, соответствующую версии вашей модели.
Выполнение кода доступно на:
Выполнение кода в настоящее время недоступно на Amazon Bedrock или Google Vertex AI.
Вот простой пример, в котором Claude просят выполнить вычисление:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"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"
}]
}'Когда вы добавляете инструмент выполнения кода в свой API-запрос:
Когда вы предоставляете выполнение кода вместе с клиентскими инструментами, которые также запускают код (например, инструмент 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Это особенно важно при совмещении выполнения кода с веб-поиском или веб-запросами, которые автоматически включают выполнение кода. Если ваше приложение уже предоставляет клиентский инструмент оболочки, автоматическое выполнение кода создаёт вторую среду выполнения, между которыми Claude должен различать.
Попросите Claude проверить системную информацию и установить пакеты:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": "Check the Python version and list installed packages"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'Claude может создавать, просматривать и редактировать файлы непосредственно в песочнице, используя возможности работы с файлами:
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"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"
}]
}'Чтобы анализировать собственные файлы данных (CSV, Excel, изображения и т.д.), загрузите их через Files API и укажите на них в своём запросе:
Использование Files API с выполнением кода требует бета-заголовка Files API: "anthropic-beta": "files-api-2025-04-14"
Среда Python может обрабатывать различные типы файлов, загруженных через Files API, включая:
container_upload# First, upload a 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"' \
# Then use the file_id with code execution
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"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"
}]
}'Когда Claude создаёт файлы во время выполнения кода, вы можете получить эти файлы с помощью Files API:
from anthropic import Anthropic
# Initialize the client
client = Anthropic()
# Request code execution that creates files
response = client.beta.messages.create(
model="claude-opus-4-6",
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":
for file in content_item.content:
if hasattr(file, "file_id"):
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}")Сложный рабочий процесс с использованием всех возможностей:
# First, upload a 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
# Extract file_id (using jq)
FILE_ID=$(jq -r '.id' file_response.json)
# Then use it with code execution
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: files-api-2025-04-14" \
--header "content-type: application/json" \
--data '{
"model": "claude-opus-4-6",
"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"
}]
}'Инструмент выполнения кода не требует дополнительных параметров:
{
"type": "code_execution_20250825",
"name": "code_execution"
}Когда этот инструмент предоставлен, Claude автоматически получает доступ к двум подинструментам:
bash_code_execution: Запуск команд оболочкиtext_editor_code_execution: Просмотр, создание и редактирование файлов, включая написание кодаИнструмент выполнения кода может возвращать два типа результатов в зависимости от операции:
{
"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
}
}Просмотр файла:
{
"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
}
}Создание файла:
{
"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):
{
"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 при успехе, ненулевое значение при сбоеДополнительные поля для операций с файлами:
file_type, content, numLines, startLine, totalLinesis_file_update (существовал ли файл ранее)oldStart, oldLines, newStart, newLines, 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 | Выполнение превысило максимальный лимит времени |
| Все инструменты | container_expired | Контейнер истёк и больше недоступен |
| Все инструменты | invalid_tool_input | Переданы недопустимые параметры инструменту |
| Все инструменты | too_many_requests | Превышен лимит запросов для использования инструмента |
| text_editor | file_not_found | Файл не существует (для операций просмотра/редактирования) |
| text_editor | string_not_found | old_str не найден в файле (для str_replace) |
pause_turnОтвет может включать причину остановки pause_turn, которая указывает на то, что API приостановил длительный ход. Вы можете передать ответ как есть в последующем запросе, чтобы позволить Claude продолжить свой ход, или изменить содержимое, если хотите прервать разговор.
Инструмент выполнения кода работает в безопасной контейнеризированной среде, специально разработанной для выполнения кода, с повышенным акцентом на Python.
Изолированная среда Python включает следующие часто используемые библиотеки:
Вы можете повторно использовать существующий контейнер в нескольких API-запросах, указав идентификатор контейнера из предыдущего ответа. Это позволяет сохранять созданные файлы между запросами.
import os
from anthropic import Anthropic
# Initialize the client
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
# First request: Create a file with a random number
response1 = client.messages.create(
model="claude-opus-4-6",
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-6",
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"}],
)При включённой потоковой передаче вы будете получать события выполнения кода по мере их возникновения:
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:
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-22 | code-execution-2025-08-25 |
| Тип инструмента | 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"Проверьте обработку ответов (если вы программно разбираете ответы):
Инструмент выполнения кода обеспечивает работу программного вызова инструментов, который позволяет Claude писать код, вызывающий ваши пользовательские инструменты программно внутри контейнера выполнения. Это обеспечивает эффективные рабочие процессы с несколькими инструментами, фильтрацию данных до того, как они достигнут контекста Claude, и сложную условную логику.
# Enable programmatic calling for your tools
response = client.messages.create(
model="claude-opus-4-6",
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"
], # Enable programmatic calling
},
],
)Узнайте больше в документации по программному вызову инструментов.
Выполнение кода происходит в серверных изолированных контейнерах. Данные контейнера, включая артефакты выполнения, загруженные файлы и результаты, хранятся до 30 дней. Это правило хранения распространяется на все данные, обрабатываемые в среде контейнера.
Для получения информации о праве на ZDR для всех функций см. API и хранение данных.
Инструмент выполнения кода позволяет Claude использовать Agent Skills. Skills — это модульные возможности, состоящие из инструкций, скриптов и ресурсов, расширяющих функциональность Claude.
Подробнее см. в документации по Agent Skills и руководстве по API Agent Skills.
Was this page helpful?