Skip to main content
LLMs like Google’s Gemini are good at writing code, but can’t execute code. Fortunately, Gemini understands this and allows you to supplement its functionality with external “tools”. In this guide we’ll hook up the Riza Code Interpreter API as a tool for Gemini to use when it wants to execute code. Using Riza as the code execution environment keeps your local machine safe in case the code written by Gemini does something unexpected. We’ll run Python, but Riza can execute JavaScript, PHP, and Ruby too.

Example code

Get the full code for this example in our GitHub.

Getting started

To generate Python with Gemini, you’ll need an API key from the Google. 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:
In this guide we’ll use the Gemini and Riza Python API client libraries.

Python environment setup

Create a virtualenv and activate it:
Install the google-generativeai and rizaio packages with pip:

Scenario

We’ll create a message for Gemini that requires code execution to answer. Here, we ask Gemini to base32 encode the message “purple monkey dishwasher.”
Sending this message to Gemini without offering any additional tools results in unexpected hallucinated output:
Response
The correct result is OB2XE4DMMUQG233ONNSXSIDENFZWQ53BONUGK4Q=. For a correct result, we can offer Gemini a tool to execute Python.

Step 1: Import required libraries

First we import and initialize required libraries from Google and Riza.

Step 2: Define a code execution tool

Before sending the message to Gemini 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 Code API to run the code. So first, we define an execute_python helper function in our script. This function uses Riza to execute arbitrary Python:
We’ll use this function in the next step.

Step 3: Call Gemini with Riza as a tool

Now, we can make execute_python() function available to Gemini as a tool, and call Gemini with our query:
Here, we enable the enable_automatic_function_calling setting to allow Gemini to call any function without us having to explicitly handle the tool use. If you’d like to explicitly handle the tool use, you can disable this setting. Finally, let’s print out the full chat history so we can see the function call:
See the full example in GitHub.