# pip install anthropic e2b-code-interpreter
from anthropic import Anthropic
from e2b_code_interpreter import Sandbox
client = 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 tool
response = client.messages.create(
model=model,
max_tokens=1024,
tools=tools,
messages=messages
)
messages.append({"role": "assistant", "content": response.content})
# Execute the tool if called
if 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)