LogoFreestyle

Gemini Python SDK

Code execution for Gemini in Python

Install the required dependencies

pip install google-genai freestyle

Get your Freestyle API Key from the Freestyle Dashboard

Set up the Code Executor

The simplest code executor looks like this:

import os
import freestyle.gemini
 
definition, runner = freestyle.gemini.execute_tool(
    os.environ.get("FREESTYLE_API_KEY"),
)

Adding Node Modules

When you want your AI code execution to have access to specific node modules, you can pass them in through the configuration parameter:

import os
import freestyle.gemini
import freestyle
 
definition, runner = freestyle.gemini.execute_tool(
    os.environ.get("FREESTYLE_API_KEY"),
    freestyle.FreestyleExecuteScriptParamsConfiguration(
        nodeModules={"mathjs": "14.3.1"}
    ),
  )

Adding Environment Variables

You can also pass in environment variables that your AI code execution will have access to:

import os
import freestyle.gemini
import freestyle
 
definition, runner = freestyle.gemini.execute_tool(
    os.environ.get("FREESTYLE_API_KEY"),
    freestyle.FreestyleExecuteScriptParamsConfiguration(
        envVars={"RESEND_API_KEY": os.environ.get("RESEND_API_KEY")},
        nodeModules={"resend": "4.1.2"}
    ),
  )

Other Configuration Options

  • timeout: The maximum time in seconds that the code execution is allowed to run.
  • networkPermissions: A list of URLs that the code execution is allowed to access.
  • peerDependencyResolution: Configure if peer dependencies should be resolved — do not use this unless you know what you are doing.

Set up the Gemini Python SDK

import google.genai as genai
from google.genai import types
import os
import freestyle.gemini
 
client = genai.Client(api_key=os.environ.get("GENERATIVEAI_API_KEY"))
 
definition, runner = freestyle.gemini.execute_tool(
    os.environ.get("FREESTYLE_API_KEY"),
)
 
chat = client.chats.create(
    model="gemini-2.0-flash",
    config=types.GenerateContentConfigDict(
        tools=[definition],
    ),
    history=[],
)
 
response = chat.send_message(
    "What is the sum of every number from 50 to 65 divided by 17"
).candidates[0]
 
tool_result = runner(response.content)
print("Answer: ", tool_result)
The definition and runner variables are from the code executor setup. The runner is a function that takes in a Gemini model response and returns the output of the code execution if there is one. Runner is made to be called on every response from the Gemini model, if there is no code execution then it returns None and does nothing.

On this page