GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
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-api277code-execution4troubleshooting82python104errors3

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-07-14
When Gemini's executed result and its prose disagree on a number — a gate that trusts only code_execution_result
Gemini Code Execution returns the value it actually computed and the sentence describing it as separate parts. Trust the prose and you can inherit a hallucinated number. Here is a verification gate, in working code, that extracts the executed result as the single source of truth and rejects prose that disagrees.
API / SDK2026-06-21
Gemini API Implicit Caching Not Working — Troubleshooting Guide by Root Cause
Troubleshoot Gemini API implicit caching issues: cache not hitting, unexpectedly high costs, or low cache hit rates. Covers token thresholds, prompt structure, model version consistency, TTL expiry, and multimodal caching with code examples.
API / SDK2026-06-14
When Gemini API Cuts Your Response Off Mid-Sentence — Detecting finish_reason: MAX_TOKENS and Stitching the Continuation
Long-form generation that ends mid-sentence is usually finish_reason: MAX_TOKENS. This failure arrives as a quiet HTTP 200, no exception. Here is how to detect it, stitch a continuation to recover the full text, and avoid the thinking-token trap that makes it worse on 3.x models.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →