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 ===
# 5050If 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 processingmatplotlib,seaborn— plottingscikit-learn— machine learningpillow— image processingsympy— symbolic math
Libraries that don't work (will throw import or connection errors):
requests,httpx,aiohttp— HTTP clientsselenium,playwright— browser automationflask,fastapi,django— web frameworkspsycopg2,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.998If 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-wayTwo 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.