# pip install anthropic e2b-code-interpreterfrom anthropic import Anthropicfrom e2b_code_interpreter import Sandboxclient = Anthropic()response = client.messages.create( model="claude-sonnet-4-5-20250929", max_tokens=1024, system="You are a helpful assistant that writes Python code. Only respond with the code to execute, no backticks or explanations.", messages=[{"role": "user", "content": "Calculate the first 10 Fibonacci numbers"}])code = response.content[0].textwith Sandbox() as sandbox: execution = sandbox.run_code(code) print(execution.text)
Claude’s tool use lets the model decide when to execute code.
# pip install anthropic e2b-code-interpreterfrom anthropic import Anthropicfrom e2b_code_interpreter import Sandboxclient = Anthropic()model = "claude-sonnet-4-5-20250929"tools = [{ "name": "execute_python", "description": "Execute Python code in a Jupyter notebook cell and return the result", "input_schema": { "type": "object", "properties": { "code": { "type": "string", "description": "The Python code to execute" } }, "required": ["code"] }}]messages = [{"role": "user", "content": "What's the sum of the first 100 prime numbers?"}]# First API call - Claude decides to use the toolresponse = client.messages.create( model=model, max_tokens=1024, tools=tools, messages=messages)messages.append({"role": "assistant", "content": response.content})# Execute the tool if calledif response.stop_reason == "tool_use": tool_use = next(block for block in response.content if block.type == "tool_use") with Sandbox() as sandbox: execution = sandbox.run_code(tool_use.input["code"]) result = execution.text messages.append({ "role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": result }] }) # Second API call - Claude provides the final answer final_response = client.messages.create( model=model, max_tokens=1024, tools=tools, messages=messages ) print(final_response.content[0].text)