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":"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"}]}'
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":"Check the Python version and list installed packages"}],"tools":[{"type":"code_execution_20250825","name":"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"\--header"content-type: application/json"\--data '{"model":"claude-opus-4-1-20250805","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"}]}'
{"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}}
import osfrom anthropic import Anthropic# 初始化客户端client = Anthropic( api_key=os.getenv("ANTHROPIC_API_KEY"))# 第一个请求:创建一个包含随机数的文件response1 = client.beta.messages.create( model="claude-opus-4-1-20250805", 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"}])# 从第一个响应中提取容器IDcontainer_id = response1.container.id# 第二个请求:重用容器来读取文件response2 = client.beta.messages.create( container=container_id,# 重用相同的容器 model="claude-opus-4-1-20250805", 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"}])
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.