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-05-22"\--header"content-type: application/json"\--data '{"model":"claude-opus-4-20250514","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_20250522","name":"code_execution"}]}'
{"role":"assistant","container":{"id":"container_011CPR5CNjB747bTd36fQLFk","expires_at":"2025-05-23T21:13:31.749448Z"},"content":[{"type":"text","text":"I'll calculate the mean and standard deviation for you."},{"type":"server_tool_use","id":"srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2","name":"code_execution","input":{"code":"import numpy as np\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nmean = np.mean(data)\nstd = np.std(data)\nprint(f\"Mean: {mean}\")\nprint(f\"Standard deviation: {std}\")"}},{"type":"code_execution_tool_result","tool_use_id":"srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2","content":{"type":"code_execution_result","stdout":"Mean: 5.5\nStandard deviation: 2.8722813232690143\n","stderr":"","return_code":0}},{"type":"text","text":"The mean of the dataset is 5.5 and the standard deviation is approximately 2.87."}],"id":"msg_01BqK2v4FnRs4xTjgL8EuZxz","model":"claude-opus-4-20250514","stop_reason":"end_turn","usage":{"input_tokens":45,"output_tokens":187,}}
{"type":"code_execution_tool_result","tool_use_id":"srvtoolu_01ABC123","content":{"type":"code_execution_result","stdout":"","stderr":"NameError: name 'undefined_variable' is not defined","return_code":1}}
import osfrom anthropic import Anthropic# 初始化客戶端client = Anthropic( api_key=os.getenv("ANTHROPIC_API_KEY"))# 第一個請求:建立包含隨機數字的檔案response1 = client.beta.messages.create( model="claude-opus-4-20250514", betas=["code-execution-2025-05-22"], 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_20250522","name":"code_execution"}])# 從第一個回應中提取容器 IDcontainer_id = response1.container.id# 第二個請求:重複使用容器來讀取檔案response2 = client.beta.messages.create( container=container_id,# 重複使用相同的容器 model="claude-opus-4-20250514", betas=["code-execution-2025-05-22"], max_tokens=4096, messages=[{"role":"user","content":"Read the number from '/tmp/number.txt' and calculate its square"}], tools=[{"type":"code_execution_20250522","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.