Example code
Get the full code for this example in our GitHub.Getting started
To generate Python with Anthropic’s models, you’ll need an API key from the Anthropic Console. To execute Python using Riza’s Code Interpreter API, you’ll need an API key from the Riza Dashboard. Make these API keys available in your shell environment:Python environment setup
Create a virtualenv and activate it:anthropic
and rizaio
packages with pip
:
Scenario
We’ll create a message for Claude that requires code execution to answer. Here, we ask Claude to base32 encode the message “purple monkey dishwasher.”Response 1
Response 2
OB2XE4DMMUQG233ONNSXSIDENFZWQ53BONUGK4Q=
).
For a correct result, we can offer Claude a tool to execute Python.
Step 1: Import required libraries
First we import and initialize required libraries from Anthropic and Riza.Step 2: Define a code execution tool
Before sending the message to Claude, we’ll describe the Riza Code Interpreter as a tool using a tool definition that Claude understands. In this example, we will use Riza’s Execute Function API to run the code. So we define a tool that takes in the required inputs of the Execute Function API:execute_function()
helper, which we’ll use to handle any tool use calls. This function uses Riza to safely execute code.
Step 3: Call Claude and handle tool use
Now we can send the message and tool definition to Claude.execute_python_function
tool to execute Python code, the response will
include a tool_use
block with the execute_python_function
name.
This block will have a set of input parameters corresponding to the input properties
we specified in our tool definition. In this case, the parameters we care about are
code
and input
.
We take the code that Claude wants to run and execute it using Riza:
tool_result
message to send back.
This step is optional, as the code execution output might be all you need.
Step 4: (optional) Call Claude with the tool use result for a final answer
We send the updated list of messages back to Claude to get a final answer incorporating the code execution output:Response
Step 5: (optional) Let Claude decide when to stop
In our example so far, we make either 1 or 2 calls to Claude: one call with our prompt, and a possible second call with the result of theexecute_python_function
tool.
But what happens if Claude’s first attempt at writing code results in an error? In our example so far, we don’t give Claude the chance to recover from that mistake.
Here’s one way to address this problem: we’ll adjust our script to keep calling Claude until Claude decides it no longer wants to use a tool. This solution is only appropriate because our prompt requires Claude to use a tool to produce a correct answer.
Here’s our revised script, which introduces a while loop. Notice that if execute_python_function
results in an error, we now pass the error to Claude, and Claude can respond to it. (Ideally, Claude would try calling the tool again with a different piece of code.)