Chapter 79
Intro to Generating and Executing Python Code with Gemini 3
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.Intro to Generating and Executing Python Code with Gemini 3
| Author |
|---|
| Kristopher Overholt |
Overview
This notebook introduces the code execution capabilities of the Gemini 3 Flash model, a new multimodal generative AI model from Google DeepMind. Gemini 3 Flash offers improvements in speed, quality, and advanced reasoning capabilities including enhanced understanding, coding, and instruction following.
Code Execution
A key feature of this model is code execution, which is the ability to generate and execute Python code directly within the API. If you want the API to generate and run Python code and return the results, you can use code execution as demonstrated in this notebook.
This code execution capability enables the model to generate code, execute and observe the results, correct the code if needed, and learn iteratively from the results until it produces a final output. This is particularly useful for applications that involve code-based reasoning such as solving mathematical equations or processing text.
Objectives
In this tutorial, you will learn how to generate and execute code using the Gemini API in Vertex AI and the Google Gen AI SDK for Python with the Gemini 3 Flash model.
You will complete the following tasks:
- Generating and running sample Python code from text prompts
- Exploring data using code execution in multi-turn chats
- Using code execution in streaming sessions
Getting started
Install Google Gen AI SDK for Python
%pip install --upgrade --quiet google-genaiAuthenticate your notebook environment (Colab only)
If you're running this notebook on Google Colab, run the cell below to authenticate your environment.
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()Import libraries
import os
from IPython.display import Markdown, display
from google import genai
from google.genai.types import GenerateContentConfig, Tool, ToolCodeExecutionConnect to a generative AI API service
Google Gen AI APIs and models including Gemini are available in the following two API services:
- Google AI for Developers: Experiment, prototype, and deploy small projects.
- Vertex AI: Build enterprise-ready projects on Google Cloud. The Google Gen AI SDK provides a unified interface to these two API services.
This notebook shows how to use the Google Gen AI SDK with the Gemini API in Vertex AI.
Set Google Cloud project information and create client
To get started using Vertex AI, you must have an existing Google Cloud project and enable the Vertex AI API.
Learn more about setting up a project and a development environment.
# fmt: off
PROJECT_ID = "[your-project-id]" # @param {type: "string", placeholder: "[your-project-id]", isTemplate: true}
# fmt: on
if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
PROJECT_ID = str(os.environ.get("GOOGLE_CLOUD_PROJECT"))
LOCATION = os.environ.get("GOOGLE_CLOUD_REGION", "global")client = genai.Client(enterprise=True, project=PROJECT_ID, location=LOCATION)Working with code execution in Gemini 3
Load the Gemini model
The following code loads the Gemini 3 Flash model. You can learn about all Gemini models on Vertex AI by visiting the documentation:
MODEL_ID = "gemini-3.6-flash" # @param {type: "string"}Define the code execution tool
The following code initializes the code execution tool by passing code_execution in a Tool definition.
Later we'll register this tool with the model that it can use to generate and run Python code:
code_execution_tool = Tool(code_execution=ToolCodeExecution())Generate and execute code
The following code sends a prompt to the Gemini model, asking it to generate and execute Python code to calculate the sum of the first 50 prime numbers. The code execution tool is passed in so the model can generate and run the code:
PROMPT = """What is the sum of the first 50 prime numbers?
Generate and run code for the calculation."""
response = client.models.generate_content(
model=MODEL_ID,
contents=PROMPT,
config=GenerateContentConfig(
tools=[code_execution_tool],
),
)View the generated code
The following code iterates through the response and displays any generated Python code by checking for part.executable_code in the response parts:
for part in response.candidates[0].content.parts:
if part.executable_code:
display(
Markdown(
f"""
```py
{part.executable_code.code}
```
"""
)
)Output
<IPython.core.display.Markdown object>
View the code execution results
The following code iterates through the response and displays the execution result and outcome by checking for part.code_execution_result in the response parts:
for part in response.candidates[0].content.parts:
if part.code_execution_result:
display(Markdown(f"`{part.code_execution_result.output}`"))
print("\nOutcome:", part.code_execution_result.outcome)Output
<IPython.core.display.Markdown object>
Outcome: Outcome.OUTCOME_OK
Great! Now you have the answer (5117) as well as the generated (and verified via execution!) Python code.
At this point in your application, you would save the output code, result, or outcome and display it to the end-user or use it downstream in your application.
Code execution in a chat session
This section shows how to use code execution in an interactive chat with history using the Gemini API.
You can use client.chats.create to create a chat session and passes in the code execution tool, enabling the model to generate and run code:
chat = client.chats.create(
model=MODEL_ID,
config=GenerateContentConfig(
tools=[code_execution_tool],
),
)You'll start the chat by asking the model to generate sample time series data with noise and then output a sample of 10 data points:
PROMPT = """Generate and run code to create sample time series data of temperature vs. time in a test furnace.
Add noise to the data. Output a sample of 10 data points from the time series data."""
response = chat.send_message(PROMPT)Now you can iterate through the response to display any generated Python code and execution results by checking for part.executable_code and part.code_execution_result in the response parts:
for part in response.candidates[0].content.parts:
if part.executable_code:
display(
Markdown(
f"""
```py
{part.executable_code.code}
```
"""
)
)
if part.code_execution_result:
display(Markdown(f"`{part.code_execution_result.output}`"))
print("\nOutcome:", part.code_execution_result.outcome)Output
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
Outcome: Outcome.OUTCOME_OK
Now you can ask the model to add a smoothed data series to the time series data:
PROMPT = "Rewrite the code to add a data series that smooths the sample data."
response = chat.send_message(PROMPT)And then display the generated Python code and execution results:
for part in response.candidates[0].content.parts:
if part.executable_code:
display(
Markdown(
f"""
```py
{part.executable_code.code}
```
"""
)
)
if part.code_execution_result:
display(Markdown(f"`{part.code_execution_result.output}`"))
print("\nOutcome:", part.code_execution_result.outcome)Output
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
Outcome: Outcome.OUTCOME_OK
Finally, you can ask the model to generate descriptive statistics for the time series data:
PROMPT = "Rewrite the code to generate and output descriptive statistics on the time series data."
response = chat.send_message(PROMPT)And then display the generated Python code and execution results:
for part in response.candidates[0].content.parts:
if part.executable_code:
display(
Markdown(
f"""
```py
{part.executable_code.code}
```
"""
)
)
if part.code_execution_result:
display(Markdown(f"`{part.code_execution_result.output}`"))
print("\nOutcome:", part.code_execution_result.outcome)Output
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
Outcome: Outcome.OUTCOME_OK
This chat example demonstrates how you can use the Gemini API with code execution as a powerful tool for exploratory data analysis and more. Go forth and adapt this approach to your own projects and use cases!
Code execution in a streaming session
You can also use the code execution functionality with streaming output from the Gemini API.
The following code demonstrates how the Gemini API can generate and execute code while streaming the results:
PROMPT = """Generate and run code to create a list of 20 random names, then
create a new list with just the names containing the letter 'a', then output the
number of names that contain 'a', and finally show me that new list."""
for chunk in client.models.generate_content_stream(
model=MODEL_ID,
contents=PROMPT,
config=GenerateContentConfig(
tools=[code_execution_tool],
),
):
if chunk.candidates and chunk.candidates[0].content:
if chunk.candidates[0].content.parts is not None:
for part in chunk.candidates[0].content.parts:
if part.text:
display(Markdown("#### Natural language stream"))
display(Markdown(part.text))
display(Markdown("---"))
if part.executable_code:
display(Markdown("#### Code stream"))
display(
Markdown(
f"""
```py
{part.executable_code.code}
```
"""
)
)
display(Markdown("---"))
if part.code_execution_result:
display(Markdown("#### Code result"))
display(
Markdown(
f"""
```
{part.code_execution_result.output}
```
"""
)
)
display(Markdown("---"))Output
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
This streaming example demonstrated how the Gemini API can generate, execute code, and provide results within a streaming session.
Summary
Refer to the documentation for more details about code execution, and in particular, the recommendations regarding differences between code execution and function calling.
Next steps
- See the Google Gen AI SDK reference docs
- Explore other notebooks in the Google Cloud Generative AI GitHub repository
- Explore AI models in Model Garden
