Skip to content
,

Gemini Code Execution API in Python: Run Code, CSV Files and Charts

12โ€“17 minutes
Woman in a bright co-working space with plants holding a tablet with a CODE EXECUTION card, hook 30-second sandbox Gemini runs Python

Gemini can write Python, run it in a Google sandbox, read the result and then answer you. This guide shows how to switch on the code execution tool with the google-genai Python SDK and read every part it sends back.

We will also feed it a CSV file, get Matplotlib charts back as images, mix it with Google Search and your own functions, and work out what it really costs.

TLDR

  • Enable it: add types.Tool(code_execution=types.ToolCodeExecution()) to tools. With the Interactions API, pass {"type": "code_execution"}.
  • Read the output: loop over the parts and check text, executable_code.code and code_execution_result.output.
  • No extra fee: you pay normal token prices. Code and results count as tokens, and some are billed twice (as output, then as input).
  • Limits: Python only, 30 seconds per run, up to 5 automatic retries, no pip installs.
  • Files and charts: CSV and text files work best. Charts come back as inline PNG data, and only Matplotlib is supported.
  • Models: Gemini 4 Carbon, Neon and Hydrogen, Gemini 3.8 / 3.6 Flash and the Flash-Lite models support it. Gemini 4 Live does not.

What the Code Execution Tool Does

Language models are weak at exact maths and at counting rows in big tables. They guess. The code execution tool fixes this by letting Gemini write a Python script, run it, and use the real output.

The model can also loop. If the first script fails or the answer looks wrong, it can fix the code and run it again before it replies.

  • Exact maths: sums, statistics, equations and unit conversions.
  • Data work: read a CSV, group, filter and summarise it with pandas.
  • Charts: draw a Matplotlib graph and return it as an image.
  • Image inspection: on newer models, crop, zoom, rotate or annotate an image you send.
  • Text processing: count words, parse dates, clean up messy strings.

The code runs on Google’s side. You do not need your own sandbox, Docker or server. You just add the tool to the request.

Quick answer: add the code execution tool to your request, then loop over response.candidates[0].content.parts. Each part holds either text, executable_code (the script) or code_execution_result (what the script printed).

Which Gemini Models Support Code Execution

I checked each model page in the official docs on 4 December 2026. The table shows the current text models and their list prices on the paid tier.

Model Model ID Code execution Free tier Paid input / output (per 1M tokens)
Gemini 4 Carbon gemini-4-carbon Yes No $4.00 / $20.00
Gemini 4 Neon gemini-4-neon Yes No $3.00 / $15.00
Gemini 4 Hydrogen gemini-4-hydrogen Yes Yes $1.50 / $7.50
Gemini 3.8 Flash gemini-3.8-flash Yes Yes $0.75 / $3.75 (to 31 Dec 2026)
Gemini 3.6 Flash gemini-3.6-flash Yes Yes $0.75 / $3.75 (to 31 Dec 2026)
Gemini 3.5 Flash-Lite gemini-3.5-flash-lite Yes Yes $0.30 / $2.50
Gemini 3.1 Flash-Lite gemini-3.1-flash-lite Yes Yes $0.25 / $1.50
Gemini 4 Live gemini-4-live No Yes Not applicable

Warning: Gemini 3.8 Flash and 3.6 Flash double in price on 1 January 2027 ($1.50 input, $7.50 output). Also, gemini-4-argon is deprecated and routes to Gemini 4 Carbon (at Carbon prices) from 15 December 2026.

Code execution with images (crop, zoom, annotate) needs Gemini 3 Flash or newer, including Gemini 3.8 Flash and all Gemini 4 models. You turn it on by enabling both the code execution tool and thinking.

Setup Steps

You need Python 3.11 or newer, because the current SDK (google-genai 3.7.0, checked 4 December 2026) requires it. You also need a Gemini API key from Google AI Studio.

  1. Get an API key. Open Google AI Studio, click Get API key and create a key for your project. The free tier works for Hydrogen and the Flash models.
  2. Save the key as an environment variable. On macOS or Linux run export GEMINI_API_KEY="your-key". On Windows PowerShell run $env:GEMINI_API_KEY="your-key". The SDK reads it automatically.
  3. Install the SDK. Run pip install -U google-genai. For the chart example, also run pip install pillow.
  4. Pick a model. Start with gemini-4-hydrogen. It has a free tier and supports code execution, images and tool combos.
  5. Add the tool and run a test. Copy Example 1 below into test_code.py and run python test_code.py. You should see text, then code, then the printed result.

New to the SDK? My Gemini API Python tutorial covers clients, models and streaming from scratch.

Example 1: Enable Code Execution and Read the Parts

This is the classic generate_content call. The only new thing is the tools list in the config.

Official Gemini API docs showing the Python generate_content call with tools set to types.Tool(code_execution=types.ToolCodeExecution) on gemini-4-hydrogen
Official Gemini API code execution docs, generateContent tab (checked 4 Dec 2026).
from google import genai
from google.genai import types

client = genai.Client()  # reads GEMINI_API_KEY

response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents=(
        "What is the sum of the first 50 prime numbers? "
        "Generate and run code for the calculation, and make sure you get all 50."
    ),
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution())]
    ),
)

for part in response.candidates[0].content.parts:
    if part.text is not None:
        print("TEXT:", part.text)
    if part.executable_code is not None:
        print("CODE:")
        print(part.executable_code.code)
    if part.code_execution_result is not None:
        print("RESULT:", part.code_execution_result.outcome)
        print(part.code_execution_result.output)

The official sample answer for this prompt is 5117, worked out by real Python code, not a guess.

The part types

Python field REST (JSON) name What it holds
part.text text The model’s explanation and final answer.
part.executable_code executableCode The script: code, language (always PYTHON) and an id.
part.code_execution_result codeExecutionResult What ran: output (stdout or the error), outcome and an id.
part.inline_data inlineData Image output, such as a Matplotlib chart (PNG bytes).

The outcome field is an enum. In SDK 3.7.0 the values are OUTCOME_OK, OUTCOME_FAILED, OUTCOME_DEADLINE_EXCEEDED and OUTCOME_UNSPECIFIED.

Tip: response.text only joins the text parts. If you want to show users the code too, always loop over the parts as above.

Example 2: Analyse a CSV and Save the Charts

Code execution accepts file input and returns graphs. The docs say it works best with text and CSV files. You can send the file inline or upload it with the Files API.

from google import genai
from google.genai import types

client = genai.Client()

# Option A: upload with the Files API (kept for 48 hours)
csv_file = client.files.upload(
    file="sales.csv",
    config=types.UploadFileConfig(mime_type="text/csv"),
)

# Option B (small files): send the bytes inline instead
# csv_file = types.Part.from_bytes(
#     data=open("sales.csv", "rb").read(), mime_type="text/csv"
# )

response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents=[
        csv_file,
        "Using code, find total revenue per month and the top 3 products. "
        "Then draw a bar chart of revenue per month with matplotlib.",
    ],
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution())]
    ),
)

chart_count = 0
for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    if part.executable_code is not None:
        print("--- code ---")
        print(part.executable_code.code)
    if part.code_execution_result is not None:
        print("--- output ---")
        print(part.code_execution_result.output)
    if part.inline_data is not None:
        chart_count += 1
        name = f"chart_{chart_count}.png"
        with open(name, "wb") as f:
            f.write(part.inline_data.data)
        print("Saved", name, part.inline_data.mime_type)

Output files always come back as inline data, so you never download anything from a URL. The SDK also has part.as_image(), which the official image example uses to open the picture with Pillow.

File size rules

  • Context limit: the file must fit in the model’s token window. Too big and the API returns an error.
  • AI Studio: the maximum input file is 1 million tokens, roughly 2 MB for text files.
  • Files API: up to 2 GB per file and 20 GB per project. Files are deleted after 48 hours.
  • Inline data: use the Files API when the whole request is larger than 100 MB.

Note: only Matplotlib is supported for chart rendering. Seaborn is installed, but ask for plain Matplotlib if a chart does not appear.

Code execution works inside a chat, and it can be combined with Grounding with Google Search. That lets the model look up fresh numbers and then calculate with them.

from google import genai
from google.genai import types

client = genai.Client()

chat = client.chats.create(
    model="gemini-4-hydrogen",
    config=types.GenerateContentConfig(
        tools=[
            types.Tool(code_execution=types.ToolCodeExecution()),
            types.Tool(google_search=types.GoogleSearch()),
        ]
    ),
)

r1 = chat.send_message("I want to compare loan repayments.")
print(r1.text)

r2 = chat.send_message(
    "Search for the current average 30-year US mortgage rate. "
    "Then use code to work out the monthly payment and total interest "
    "on a 250,000 dollar loan at that rate."
)
for part in r2.candidates[0].content.parts:
    if part.executable_code is not None:
        print(part.executable_code.code)
    if part.code_execution_result is not None:
        print(part.code_execution_result.output)
    if part.text is not None:
        print(part.text)

Search grounding on Gemini 3 and newer has its own fee: 5,000 free searches a month, then $14 per 1,000. My Gemini grounding tutorial explains the citation data.

Example 4: The Interactions API Way

Google’s docs now lead with the newer Interactions API. The tool is the same, but the shape of the response is different: you get steps, not parts.

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What is the sum of the first 50 prime numbers? "
          "Generate and run code for the calculation, and make sure you get all 50.",
    tools=[{"type": "code_execution"}],
)

for step in interaction.steps:
    if step.type == "model_output":
        for block in step.content:
            if block.type == "text":
                print(block.text)
    elif step.type == "code_execution_call":
        print(step.arguments.code)
    elif step.type == "code_execution_result":
        print(step.result)

# Follow-up turn keeps the context on Google's side
follow_up = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=interaction.id,
    input="Now do the same for the first 100 primes.",
    tools=[{"type": "code_execution"}],
)
print(follow_up.output_text)

The step types are code_execution_call and code_execution_result. Image output arrives as a content block with type == "image" and base64 data. See the Interactions API tutorial for the full model.

Combining Code Execution With Function Calling

Gemini 4 and Gemini 3 models can mix built-in tools (code execution, Google Search, URL context, Maps, File Search) with your own functions in one request. This feature is still marked Preview.

  1. Declare both tools. Put code_execution and your function_declarations in tools.
  2. Turn on context circulation. Set tool_config=types.ToolConfig(include_server_side_tool_invocations=True).
  3. Run your function. When a function_call part arrives, call your code and note its id.
  4. Send everything back. Append response.candidates[0].content unchanged, then your function_response with the same id.
get_rate = {
    "name": "get_exchange_rate",
    "description": "Returns today's exchange rate between two currencies.",
    "parameters": {
        "type": "object",
        "properties": {
            "base": {"type": "string"},
            "quote": {"type": "string"},
        },
        "required": ["base", "quote"],
    },
}

config = types.GenerateContentConfig(
    tools=[
        types.Tool(code_execution=types.ToolCodeExecution()),
        types.Tool(function_declarations=[get_rate]),
    ],
    tool_config=types.ToolConfig(include_server_side_tool_invocations=True),
)

Warning: you must return every part with its id and thought_signature fields. If you drop the thought signatures, the model errors out on the next turn. Do not rebuild the parts by hand.

For the full function loop, see my Gemini function calling tutorial.

Quick curl Test

This calls the REST endpoint directly. The tool is just an empty code_execution object.

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tools": [{"code_execution": {}}],
    "contents": [{
      "parts": [{"text": "Use code to find the 20th Fibonacci number."}]
    }]
  }'

In the JSON reply, look for parts named executableCode and codeExecutionResult.

Supported Libraries in the Sandbox

The sandbox comes with a fixed list of Python libraries. You cannot install your own, so plan your prompts around these.

Use Libraries
Data and maths numpy, pandas, scipy, sympy, mpmath, scikit-learn, tensorflow, joblib, toolz
Charts and images matplotlib, seaborn, contourpy, pillow, opencv-python, imageio
Maps and geo geopandas
Office and PDF files openpyxl, xlrd, python-docx, python-pptx, PyPDF2, reportlab, fpdf, pylatex, striprtf
Text and parsing lxml, jinja2, tabulate, pyparsing, python-dateutil, jsonschema, jsonschema-specifications
Other attrs, chess, packaging, protobuf, six

Even though python-docx and reportlab are installed, the tool cannot return media files like DOCX or PDF. Only charts come back, as inline images.

Limits and Run Time

Gemini API docs I/O details: 30 second maximum runtime, up to 5 automatic code regenerations, 1 million token file limit in AI Studio
I/O limits from the official Gemini API code execution page (checked 4 Dec 2026).
Limit Value
Language Python only (it can write other languages but not run them)
Max run time per execution 30 seconds
Automatic retries after an error Up to 5 regenerations
Input file size Limited by the model’s context window (1M tokens, about 2 MB text, in AI Studio)
Best input types Text and CSV
Output files Inline images only (Matplotlib charts)
Custom packages Not allowed
Images as input Gemini 3 Flash and newer, with thinking enabled

The docs also warn that turning on code execution can sometimes make other output worse, such as story writing. So only add the tool to requests that need it.

Pricing and a Worked Cost Example

There is no extra charge for the tool. Google bills normal input and output tokens for the model, and no fee is charged for sandbox run time.

  • Output tokens: the generated code, the execution output, thinking tokens and the final summary.
  • Input tokens: your prompt. When the model loops, the prompt, code and result are fed back as “intermediate” tokens and billed again as input.
  • Where to see it: check response.usage_metadata. The tool_use_prompt_token_count field shows the extra tool tokens.

Worked example on Gemini 4 Hydrogen

Say you send a 2,000-token prompt with a 20,000-token CSV. The model runs one script. These numbers are an illustration, not a measurement.

Item Tokens Rate (per 1M) Cost
First pass input (prompt + CSV) 22,000 $1.50 $0.0330
Intermediate input (prompt + CSV + code + result) 22,700 $1.50 $0.0341
Output (code 400 + result 300 + thinking 1,000 + summary 300) 2,000 $7.50 $0.0150
Total 46,700 about $0.08

The big CSV is paid for twice because the model reads it again after running code. On Gemini 3.8 Flash (December price) the same job is about half that. Batch API cuts token prices by 50% for non-urgent jobs.

Tip: send a trimmed CSV with only the columns you need. Fewer input tokens is the easiest saving. The Gemini API pricing guide lists every model and the free tier.

Code Execution vs Function Calling

Both are tools, but they run in different places. Code execution runs in Google’s sandbox. Function calling asks your app to run something and send the result back.

Code execution Function calling
Where code runs Google’s sandbox (server side) Your app (client side)
Who writes the code The model, on the fly You, in advance
Round trips One request; the model loops by itself You send the result back in a new turn
Internet, databases, your APIs No access Anything your code can reach
Libraries Fixed list Any you install
Best for Maths, data analysis, charts Live data, actions, business logic

Use code execution when the answer can be computed from what you sent. Use function calling when the model needs your systems. On Gemini 3 and 4 models you can use both at once.

Troubleshooting: Common Problems and Fixes

Problem or error Likely cause Fix
No executable_code parts, only text The model decided code was not needed Say “Generate and run code for this” in the prompt.
outcome is OUTCOME_DEADLINE_EXCEEDED The script ran longer than 30 seconds Ask for a faster method, sample the data or split the job.
outcome is OUTCOME_FAILED with ModuleNotFoundError The code imported a library that is not installed Name an installed library in the prompt, such as pandas or numpy.
No chart in the response The model used another plotting library, or only described the chart Ask for “a matplotlib chart” and check part.inline_data.
400 invalid_request Bad tool JSON or a file larger than the context window Check the tools shape and trim the file.
Error on turn 2 when mixing tools Missing thought_signature or id fields Append response.candidates[0].content as is.
404 model_not_found Old or misspelled model ID Use a current ID like gemini-4-hydrogen.
429 rate_limit_exceeded / quota_exceeded Too many requests or daily quota used Retry with exponential backoff, or upgrade your tier.
503 service_unavailable The service is overloaded Retry with backoff after a few seconds.
pip installs an old SDK or finds no matching version Python older than 3.11 Upgrade Python, then reinstall google-genai.

More fixes for status codes are in my Gemini API errors guide.

Frequently Asked Questions

Is the Gemini code execution tool free?

There is no extra fee for the tool itself. You pay the model’s normal token prices, and on free-tier models like Gemini 4 Hydrogen the tokens are free within the rate limits.

Can Gemini code execution run JavaScript or other languages?

No. It only runs Python. The model can still write code in other languages, but it cannot execute it with this tool.

Can I install extra Python packages?

No. You are limited to the built-in list, which includes pandas, numpy, scipy, scikit-learn, matplotlib, tensorflow and more.

How long can the code run?

Each execution can run for up to 30 seconds. If the code errors, the model may rewrite and rerun it up to 5 times.

Can it access the internet from the sandbox?

The docs do not offer network access from the sandbox. To use live data, combine code execution with Google Search grounding or your own function calls.

Can it return Excel or PDF files?

No. The only output files are inline images, such as Matplotlib charts. Ask for the data as text or CSV in the reply and save it yourself.

Does it work with the Interactions API?

Yes. Pass {"type": "code_execution"} in tools and read the code_execution_call and code_execution_result steps.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a bright co-working space with plants holding a tablet with a CODE EXECUTION card, hook 30-second sandbox Gemini runs Python