◉GEMINI LABJP
●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…
Articles/API / SDK
◈ API / SDK/2026-05-14Intermediate

3 Gemini Code Execution Errors and How to Fix Them — Import Errors, Timeouts, and Empty Outputs

Fix the most common Gemini API Code Execution issues: missing tool configuration, unsupported library imports, and timeout errors. Includes working code examples for each fix.

gemini-api286code-execution4troubleshooting87python108errors3

When you first start using Gemini API's Code Execution feature, the most disorienting problem is when the model writes code — but never actually runs it.

As an indie developer with over a decade of building apps, I've learned to read error messages pretty quickly. But Code Execution threw me off at first because some failure modes produce no error messages at all — just a silent, empty response. I ran into this while experimenting with Code Execution for image color analysis in one of my wallpaper apps, and spent a good 30 minutes staring at empty output before I figured out the pattern.

This article covers the three most common failure modes, with working code examples for each fix.

Code Execution Isn't Enabled (The Most Common Problem)

The most frequent cause of "code runs but produces no result" is a missing tools configuration. Without it, Gemini will happily generate code, but it won't execute it.

# ❌ Gemini writes code but doesn't run it
import google.generativeai as genai
 
model = genai.GenerativeModel("gemini-2.5-flash")
response = model.generate_content("Calculate the sum of numbers 1 to 100 in Python")
print(response.text)
# Output: "Here's Python code to calculate the sum: ..."  (no execution result)
# ✅ Pass tools="code_execution" to actually run the code
import google.generativeai as genai
 
model = genai.GenerativeModel(
    model_name="gemini-2.5-flash",
    tools="code_execution",  # This is required
)
response = model.generate_content("Calculate the sum of numbers 1 to 100 in Python")
 
# Iterate over parts to get both code and execution result
for part in response.candidates[0].content.parts:
    if hasattr(part, "executable_code"):
        print("=== Code Executed ===")
        print(part.executable_code.code)
    elif hasattr(part, "code_execution_result"):
        print("=== Execution Result ===")
        print(part.code_execution_result.output)
# Output:
# === Code Executed ===
# total = sum(range(1, 101))
# print(total)
# === Execution Result ===
# 5050

If you're only reading response.text, the execution result can disappear — it lives in specific parts of the response alongside the executable_code. Always iterate through parts when using Code Execution.

Import Errors — Unsupported Libraries in the Sandbox

Code Execution runs inside a sandboxed environment, which means not every Python library is available. Anything requiring network access or external system dependencies will fail.

# ❌ This will fail — no network access in the sandbox
model = genai.GenerativeModel(
    model_name="gemini-2.5-flash",
    tools="code_execution",
)
response = model.generate_content(
    "Use the requests library to fetch and parse https://example.com"
)
 
# code_execution_result will contain something like:
# ModuleNotFoundError: No module named 'requests'

Libraries that work in the sandbox:

  • numpy, pandas, scipy — numerical computation and data processing
  • matplotlib, seaborn — plotting
  • scikit-learn — machine learning
  • pillow — image processing
  • sympy — symbolic math

Libraries that don't work (will throw import or connection errors):

  • requests, httpx, aiohttp — HTTP clients
  • selenium, playwright — browser automation
  • flask, fastapi, django — web frameworks
  • psycopg2, pymongo — database drivers
# ✅ This works — NumPy is available in the sandbox
model = genai.GenerativeModel(
    model_name="gemini-2.5-flash",
    tools="code_execution",
)
response = model.generate_content(
    "Generate 100 random numbers from a normal distribution using NumPy, "
    "then calculate the mean and standard deviation"
)
 
for part in response.candidates[0].content.parts:
    if hasattr(part, "code_execution_result"):
        print(part.code_execution_result.output)
# Example output:
# Mean: 0.023
# Std dev: 0.998

If you're unsure whether a library is available, run a simple import test first — it's the fastest way to find out.

Timeouts — Heavy Processing Gets Cut Off

The sandbox has execution time limits. The official documentation doesn't specify exact numbers, but in practice, anything that takes more than a few seconds is at risk of being cut short.

This is exactly what happened with my color analysis batch job — I passed a large dataset directly and the response just stopped partway through.

# ❌ Heavy computation risks timeout
response = model.generate_content(
    "Find all prime numbers up to 10 million"
)
 
# code_execution_result may contain:
# TimeoutError, or output that stops mid-way

Two approaches work well here:

① Reduce the scope of what you're asking Code Execution to do

# ✅ Scope it down
response = model.generate_content(
    "Find all prime numbers up to 1000, print the count and the largest one"
)

② Do the heavy lifting locally, pass results to Gemini for analysis

This is where Code Execution shines in real applications — not as a general compute engine, but as an analysis layer over data you've already prepared.

import pandas as pd
import google.generativeai as genai
 
# Preprocess locally
df = pd.read_csv("sales_data.csv")
summary_stats = df.describe().to_string()
 
model = genai.GenerativeModel(
    model_name="gemini-2.5-flash",
    tools="code_execution",
)
 
# Pass the pre-aggregated data for analysis
response = model.generate_content(
    f"Analyze these sales statistics and identify any notable trends:\n\n{summary_stats}"
)
 
for part in response.candidates[0].content.parts:
    if hasattr(part, "code_execution_result"):
        print(part.code_execution_result.output)
    elif part.text:
        print(part.text)

Reading Execution Status with the outcome Field

Every Code Execution response includes an outcome field that tells you whether execution succeeded or failed. Building this check in from the start saves a lot of debugging time.

import google.generativeai as genai
 
model = genai.GenerativeModel(
    model_name="gemini-2.5-flash",
    tools="code_execution",
)
 
def run_with_code_execution(prompt: str) -> dict:
    """Run a prompt with Code Execution and return structured results."""
    response = model.generate_content(prompt)
 
    result = {
        "code": None,
        "output": None,
        "outcome": None,
        "text": [],
    }
 
    for part in response.candidates[0].content.parts:
        if hasattr(part, "executable_code"):
            result["code"] = part.executable_code.code
        elif hasattr(part, "code_execution_result"):
            result["outcome"] = part.code_execution_result.outcome.name
            result["output"] = part.code_execution_result.output
        elif part.text:
            result["text"].append(part.text)
 
    # outcome values: OUTCOME_OK, OUTCOME_FAILED, OUTCOME_DEADLINE_EXCEEDED
    if result["outcome"] == "OUTCOME_FAILED":
        print(f"⚠️ Execution error: {result['output']}")
    elif result["outcome"] == "OUTCOME_DEADLINE_EXCEEDED":
        print("⏱️ Timeout: try splitting the task or reducing scope")
 
    return result
 
# Example usage
result = run_with_code_execution("Compute the first 20 Fibonacci numbers")
print(f"Result: {result['output']}")
print(f"Status: {result['outcome']}")

The outcome field is the clearest signal about what went wrong — especially useful when the output itself gives no indication of failure.

Next Steps

Most Code Execution issues fall into one of these three buckets: missing tools config, unsupported library, or scope that's too large. Checking outcome as a first step makes diagnosing any of these much faster.

Code Execution is a good fit for lightweight computation, statistical analysis, and mathematical tasks — keep the scope tight and it's a genuinely useful tool. For the fundamentals, see the Gemini Code Execution API guide. If you're hitting authentication issues before you even get to execution, API authentication error solutions covers those separately.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ API / SDK2026-10-16
The Day /models Returns 200 but generateContent Returns 403 — Decide Your Triage Order Before It Happens
A triage order for the case where listing models succeeds with 200 but generation fails with 403 permission_denied. Includes a small diagnostic script that checks key, project, and billing in turn, why you should not retry a 403, and how to assemble what support needs.
◈ API / SDK2026-05-17
Diagnosing INVALID_ARGUMENT Errors in Gemini API Batch Image Analysis
When using the Gemini API to analyze multiple images at once, INVALID_ARGUMENT errors can be surprisingly hard to diagnose. This guide covers the three root causes—MIME type mismatches, inline data size limits, and contents structure errors—with code to fix each one.
◈ API / SDK2026-09-04
Screen Loop Seam Clicks With Numbers Before You Hand the Audio to Gemini
An ambient loop that clicks only at the wrap point. Here is the numeric prescreen I run before sending anything to audio understanding, why an absolute threshold fails, and how AAC encoding quietly rebuilt the seam I had just repaired.