Skip to content
Learn Agentic AI
Learn Agentic AI12 min read5 views

Building a Gemini Code Agent: Code Generation, Execution, and Debugging

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.

Gemini's Built-In Code Execution

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.

Enabling Code Execution

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.

Try Live Demo →

Inspecting Execution Results

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.

Building an Iterative Code Agent

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']}")

Combining Code Execution with Function Calling

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.

Test Generation Pattern

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."
)

FAQ

What Python libraries are available in the code execution sandbox?

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.

Is there a time limit for code execution?

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.

Can the code execution sandbox access files I upload?

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

Share

Try CallSphere AI Voice Agents

See how AI voice agents work for your industry. Live demo available -- no signup required.

Related Articles You May Like

Agentic AI

Multi-Agent Handoffs with the OpenAI Agents SDK: The Pattern That Actually Scales (2026)

Handoffs done right — when one agent should hand control to another, how to preserve context, and how to evaluate the handoff decision itself.

AI Strategy

AI Agent M&A Activity 2026: Aircall–Vogent, Meta–PlayAI, OpenAI's Six Deals

Q1 2026 saw a record acquisition wave: Aircall bought Vogent (May), Meta acquired Manus and PlayAI, OpenAI closed six deals. The voice AI consolidation phase has begun.

Agentic AI

Building Your First Agent with the OpenAI Agents SDK in 2026: A Hands-On Walkthrough

Step-by-step build of a working agent with the OpenAI Agents SDK — Agent class, tools, handoffs, tracing — plus an eval pipeline that catches regressions before merge.

Agentic AI

LangGraph Checkpointers in Production: Durable, Resumable Agents with Eval Replay

Use LangGraph's checkpointer to make agents resumable across crashes and human-in-the-loop pauses, then replay any checkpoint into your eval pipeline.

Agentic AI

LangGraph State-Machine Architecture: A Principal-Engineer Deep Dive (2026)

How LangGraph's StateGraph, channels, and reducers actually work — with a working multi-step agent, eval hooks at every node, and the patterns that survive production.

Agentic AI

LangGraph Supervisor Pattern: Orchestrating Multi-Agent Teams in 2026

The supervisor pattern in LangGraph for coordinating specialist agents, with full code, an eval pipeline that scores routing accuracy, and the failure modes to watch for.