Claude 可以直接在 API 对话中分析数据、创建可视化图表、执行复杂计算、运行系统命令、创建和编辑文件以及处理上传的文件。 代码执行工具允许 Claude 在安全的沙盒环境中运行 Bash 命令和操作文件(包括编写代码)。
代码执行工具可在以下模型上使用:
| 模型 | 工具版本 |
|---|---|
Claude Opus 4.6 (claude-opus-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)也仍然可用。请参阅升级到最新工具版本了解迁移详情。
旧版工具不保证与新模型向后兼容。请始终使用与您的模型版本对应的工具版本。
以下是一个要求 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-08-25" \
--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 请求中添加代码执行工具时:
要求 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-08-25" \
--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 "anthropic-beta: code-execution-2025-08-25" \
--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 与代码执行一起使用需要两个 beta 头:"anthropic-beta": "code-execution-2025-08-25,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: code-execution-2025-08-25,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=["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"
}]
)
# 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: code-execution-2025-08-25,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:运行 shell 命令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 环境包含以下常用库:
您可以通过提供先前响应中的容器 ID,在多个 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.beta.messages.create(
model="claude-opus-4-6",
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"
}]
)
# Extract the container ID from the first response
container_id = response1.container.id
# Second request: Reuse the container to read the file
response2 = client.beta.messages.create(
container=container_id, # Reuse the same container
model="claude-opus-4-6",
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"
}]
)启用流式传输后,您将在代码执行事件发生时接收到它们:
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 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 1,550 free hours of usage with the code execution tool per month. Additional usage beyond the first 1,550 hours is billed at $0.05 per hour, per container.
通过升级到 code-execution-2025-08-25,您可以获得文件操作和 Bash 功能,包括多种语言的代码。价格没有差异。
| 组件 | 旧版 | 当前版本 |
|---|---|---|
| Beta 头 | 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 请求中进行以下更改:
更新 beta 头:
- "anthropic-beta": "code-execution-2025-05-22"
+ "anthropic-beta": "code-execution-2025-08-25"更新工具类型:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"检查响应处理(如果以编程方式解析响应):
代码执行工具支持编程式工具调用,允许 Claude 在执行容器内编写代码来以编程方式调用您的自定义工具。这使得高效的多工具工作流、在到达 Claude 上下文之前进行数据过滤以及复杂的条件逻辑成为可能。
# Enable programmatic calling for your tools
response = client.beta.messages.create(
model="claude-opus-4-6",
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"] # Enable programmatic calling
}
]
)在编程式工具调用文档中了解更多信息。
代码执行工具使 Claude 能够使用 Agent Skills。Skills 是由指令、脚本和资源组成的模块化功能,可扩展 Claude 的能力。
在 Agent Skills 文档和 Agent Skills API 指南中了解更多信息。
Was this page helpful?