By Sagar Shankaran, Founder of CallSphere
Build a code agent with Gemini that generates Python code, executes it in a sandboxed environment, analyzes results, and iteratively debugs failures. Includes the code execution API and test generation patterns.
Key takeaways
One of Gemini's most powerful features for agent development is native code execution. Instead of generating code and hoping it works, Gemini can write Python code, run it in a sandboxed environment, observe the output, and iterate if something goes wrong — all within a single API call.
This creates a true code agent loop: generate, execute, analyze, fix. The model does not just suggest code — it verifies that the code actually works.
Code execution is enabled as a tool, similar to function calling:
flowchart LR
INPUT(["User intent"])
PARSE["Parse plus<br/>classify"]
PLAN["Plan and tool<br/>selection"]
AGENT["Agent loop<br/>LLM plus tools"]
GUARD{"Guardrails<br/>and policy"}
EXEC["Execute and<br/>verify result"]
OBS[("Trace and metrics")]
OUT(["Outcome plus<br/>next action"])
INPUT --> PARSE --> PLAN --> AGENT --> GUARD
GUARD -->|Pass| EXEC --> OUT
GUARD -->|Fail| AGENT
AGENT --> OBS
style AGENT fill:#4f46e5,stroke:#4338ca,color:#fff
style GUARD fill:#f59e0b,stroke:#d97706,color:#1f2937
style OBS fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
style OUT fill:#059669,stroke:#047857,color:#fff
import google.generativeai as genai
import os
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools="code_execution",
)
response = model.generate_content(
"Calculate the first 20 Fibonacci numbers and show them as a formatted table."
)
print(response.text)
When code execution is enabled, Gemini writes Python code, executes it server-side in a sandboxed environment, and incorporates the actual output into its response. You see both the code and its real results.
Hear it before you finish reading
Talk to a live CallSphere AI voice agent in your browser — 60 seconds, no signup.
The response contains structured parts that separate code from output:
response = model.generate_content(
"Generate a random dataset of 100 points and calculate basic statistics."
)
for part in response.candidates[0].content.parts:
if part.text:
print(f"TEXT: {part.text[:200]}")
if part.executable_code:
print(f"CODE:\n{part.executable_code.code}")
if part.code_execution_result:
print(f"OUTPUT:\n{part.code_execution_result.output}")
print(f"OUTCOME: {part.code_execution_result.outcome}")
The outcome field tells you whether execution succeeded or failed. On failure, Gemini automatically attempts to fix the code and re-execute — you get the full debugging cycle in the response.
Here is a code agent that handles complex multi-step programming tasks:
import google.generativeai as genai
import os
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
class CodeAgent:
def __init__(self):
self.model = genai.GenerativeModel(
"gemini-2.0-flash",
tools="code_execution",
system_instruction="""You are a Python programming agent.
When given a task:
1. Break it into steps
2. Write code for each step
3. Execute and verify each step works
4. If any step fails, debug and fix before continuing
5. Always validate your final output""",
)
self.chat = self.model.start_chat()
def solve(self, task: str) -> dict:
response = self.chat.send_message(task)
code_blocks = []
outputs = []
explanation = []
for part in response.candidates[0].content.parts:
if part.executable_code:
code_blocks.append(part.executable_code.code)
if part.code_execution_result:
outputs.append({
"output": part.code_execution_result.output,
"success": part.code_execution_result.outcome.name == "OUTCOME_OK",
})
if part.text:
explanation.append(part.text)
return {
"explanation": "\n".join(explanation),
"code_blocks": code_blocks,
"outputs": outputs,
"all_succeeded": all(o["success"] for o in outputs),
}
agent = CodeAgent()
result = agent.solve(
"Read a CSV string with columns name, age, salary. "
"Find the average salary by age group (20-29, 30-39, 40+). "
"Format the results as a markdown table."
)
print(result["explanation"])
print(f"All code executed successfully: {result['all_succeeded']}")
The code execution tool works alongside custom function calling. This lets the agent both run ad-hoc code and access external systems:
def query_database(sql: str) -> list:
"""Execute a SQL query against the analytics database.
Args:
sql: The SQL query to execute.
"""
# In production, connect to your real database
return [
{"month": "Jan", "revenue": 150000},
{"month": "Feb", "revenue": 175000},
{"month": "Mar", "revenue": 162000},
]
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools=["code_execution", query_database],
)
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message(
"Query the monthly revenue data, then calculate the trend line "
"and predict next month's revenue using linear regression."
)
In this pattern, the agent calls your database function to get data, then uses code execution to run the statistical analysis. Each tool handles what it does best.
Still reading? Stop comparing — try CallSphere live.
CallSphere ships complete AI voice agents per industry — 14 tools for healthcare, 10 agents for real estate, 4 specialists for salons. See how it actually handles a call before you book a demo.
A practical application is generating and running tests for existing code:
agent = CodeAgent()
source_code = """
def parse_duration(text: str) -> int:
parts = text.strip().split()
total_seconds = 0
i = 0
while i < len(parts) - 1:
value = int(parts[i])
unit = parts[i + 1].lower().rstrip('s')
if unit == 'hour':
total_seconds += value * 3600
elif unit == 'minute':
total_seconds += value * 60
elif unit == 'second':
total_seconds += value
i += 2
return total_seconds
"""
result = agent.solve(
f"Here is a Python function:\n\n{source_code}\n\n"
"Write comprehensive unit tests for this function including edge cases. "
"Execute all tests and report which pass and which fail."
)
The sandbox includes NumPy, Pandas, Matplotlib, and the Python standard library. It does not have network access or the ability to install additional packages. For tasks requiring other libraries, generate the code for local execution instead.
Yes. Code execution has a timeout of approximately 30 seconds. Long-running computations will be terminated. Design your code agent prompts to break large tasks into smaller, faster steps.
No. The code execution environment is separate from the Files API. If you need to process uploaded files with code, extract the content as text and pass it as part of the prompt, or use function calling to bridge the gap.
#GoogleGemini #CodeGeneration #AIAgents #Python #Debugging #AgenticAI #LearnAI #AIEngineering

Written by
Sagar Shankaran· Founder, CallSphere
LinkedInSagar Shankaran is the founder of CallSphere, where he builds production AI voice and chat agents deployed across healthcare, hospitality, real estate, and home services. He writes about agentic AI, LLM engineering, and shipping voice agents that handle real calls in production.
See how AI voice agents work for your industry. Live demo available -- no signup required.
A founder's guide to the personal AI assistant market: best AI assistant apps, business-grade options, and how CallSphere's voice agent fits in.
A founder's guide to free AI agents, low-code AI agent builders, and how to know when you should pay for a real platform like CallSphere.
Graphiti is the open-source temporal knowledge graph for AI agents in 2026. Learn how bi-temporal memory beats vector RAG for voice agents and long-running LLMs.
Chatbot app vs ChatGPT in 2026: a founder's clear take on the difference, when to use which, and how a real AI chatbot app development works.
How we built a fault-tolerant HVAC emergency triage and tech-dispatch platform on Kubernetes — three-tier CQRS, 11 micro-agents on the OpenAI Agents SDK + LangGraph, NATS JetStream, DTMF/SMS/WebSocket acceptance, circuit breakers, and an evaluation pipeline that catches regressions before they wake a tech at 3 AM.
Head-to-head: OpenAI Frontier and Anthropic's managed agent stack — strengths, fit, and what each means for enterprise AI voice and chat deployment.
© 2026 CallSphere Inc. All rights reserved.
Made within San Francisco
Watch how CallSphere handles real customer calls, schedules appointments, and processes payments — live.