04. Agentic Bug Fixing#
A fast, conceptual revision guide for 04-agentic-bug-fixing. Focused on how a self-healing coding agent works in LangGraph — the execute–fix–retest loop, shared Pydantic state, defensive handling of LLM-generated code, diff visualization, silent bugs, sandboxing, and inference-cost trade-offs — without boilerplate code clutter.
The Self-Healing Agent Loop & LangGraph Architecture#
Revision Notes#
Reference files: agentic-bug-fixing-code/agentic_bug_fixing_openai.py, agentic-bug-fixing-notes/agentic_bug_fixing_code_explainer.html
Concept#
An agentic bug fixer runs a Python function with given inputs, catches any runtime crash, asks an LLM to rewrite the function so it handles the error, dynamically loads the rewritten version, and re-runs it — repeating until it succeeds or hits a retry cap. This "test → fix → re-test → stop after N tries" loop is the core pattern behind modern coding agents.
How the Graph Works#
LangGraph orchestrates autonomous debugging as a bounded cycle: code_execution_node runs the target function and error_router exits immediately on success or MAX_FIX_ATTEMPTS=3, while crashes route through code_fix_node and always loop back for re-verification.
Key Mental Models#
- The four anatomy parts of any agent:
- Brain: The LLM (
ChatOpenAI(model="gpt-5-mini")) insidecode_fix_nodethat diagnoses the crash and writes replacement code. - Hands (tools): Executing the target function and dynamically loading code with
exec(). - Memory: The shared
Stateobject passed between nodes. - Loop + brakes: LangGraph edges (
add_edge,add_conditional_edges),error_router, andMAX_FIX_ATTEMPTS = 3.
- Brain: The LLM (
- The car service centre analogy:
- Nodes are workstations (
code_execution_nodetest-drives the car;code_fix_noderepairs it). - State is the shared job card each workstation reads from and writes updates to.
- Conditional edge (
error_router) is the supervisor who inspects the job card and routes either toENDor back to repairs — without mutating the state itself. - Fixed edge (
code_fix_node→code_execution_node) guarantees every proposed fix is verified before finishing.
- Nodes are workstations (
- Observing a single trace: Using
agent.graph.stream(state, stream_mode="updates"), a one-shot fix takes 3 node runs and 1 LLM call:code_execution_node(crashes) →code_fix_node(attempts=1, loads new function) →code_execution_node(succeeds, savesresult) →END.
Code Reference#
# ---------------------------------------------------------------------------
# STEP 0: Imports and settings
# ---------------------------------------------------------------------------
import ast # reads Python code as a tree, so we can find the "def" name
import difflib # makes a git-style "before vs after" diff
import html # escapes text so it is safe to show inside HTML
import inspect # gets the source code (text) of a Python function
import json # parses the arguments the user types in the UI, e.g. [10, 0]
import re # regex, used to strip ```python fences from GPT's reply
import sys # reads the --ui command-line flag
import textwrap # removes extra indentation from code
from typing import Any, Callable
from dotenv import load_dotenv # loads OPENAI_API_KEY from the .env file
from langchain_core.prompts import ChatPromptTemplate # a prompt with {blanks} to fill
from langchain_openai import ChatOpenAI # <-- the OpenAI chat model (was ChatGroq)
from langgraph.graph import StateGraph, END # builds the agent's flowchart
from pydantic import BaseModel # defines the shape of our "State"
load_dotenv()
MODEL_NAME = "gpt-5-mini" # the OpenAI model that writes the fixes
MAX_FIX_ATTEMPTS = 3 # safety brake: bounds retries so a bad fix cannot loop forever
# ---------------------------------------------------------------------------
# STEP 1: The State = the "job card" every node reads from and writes into
# ---------------------------------------------------------------------------
# Using a Pydantic BaseModel (instead of a plain dict) gives LangGraph typed,
# validated fields with safe defaults across the execute -> fix -> re-test loop.
class State(BaseModel):
function: Callable # the actual Python function object we will run
function_string: str # the ORIGINAL source code, as text
arguments: list # inputs to call the function with, e.g. [10, 0]
error: bool = False # did the last run crash?
error_description: str = "" # the crash message, e.g. "ZeroDivisionError: division by zero"
new_function_string: str = "" # the fixed code written by GPT ("" = no fix needed)
attempts: int = 0 # how many times we have asked GPT to fix it (checked against MAX_FIX_ATTEMPTS)
result: Any = None # what the function returned on its last good run
# -> Example State after Attempt 0 crash:
# State(function=<fn divide>, arguments=[10, 0], error=True,
# error_description='ZeroDivisionError: division by zero',
# new_function_string='', attempts=0, result=None)
# ---------------------------------------------------------------------------
# STEP 2: The prompt we send to GPT
# ---------------------------------------------------------------------------
# Words inside {curly braces} are placeholders populated from `State` at run time.
# Explicit formatting rules ("exact same function name", "no ``` fences") keep
# the LLM output directly parseable by `ast.parse()` and `exec()`.
FIX_PROMPT = ChatPromptTemplate.from_template(
"You are fixing a Python function that crashed.\n\n"
"Function:\n{function_string}\n\n"
"It was called with these arguments: {arguments}\n"
"It raised this error: {error_description}\n\n"
"Rewrite the function so it handles this error gracefully by returning an "
"error message (a string) instead of crashing.\n"
"Rules:\n"
"- Use the exact same function name and parameters.\n"
"- Return only the function definition: no explanation, no markdown, no ``` fences."
)
# -> ChatPromptTemplate(input_variables=['arguments', 'error_description',
# 'function_string']); when invoked on Attempt 1, renders a HumanMessage with
# divide(a, b), args [10, 0], and 'ZeroDivisionError: division by zero'.
# ---------------------------------------------------------------------------
# STEP 3: Small helper functions
# ... (see full file: agentic_bug_fixing_openai.py)
$ python agentic_bug_fixing_openai.py
[Attempt 0] Running divide(10, 0)...
✗ Crashed: ZeroDivisionError: division by zero
[Attempt 1] Asking gpt-5-mini to patch `divide`...
✓ Re-running patched `divide(10, 0)` -> 'Error: Cannot divide by zero.'
--- original
+++ fixed
@@ -1,2 +1,4 @@
def divide(a, b):
+ if b == 0:
+ return "Error: Cannot divide by zero."
return a / b
Final result: Error: Cannot divide by zero. (fixed in 1 attempt)
Prompting & Defensive Code Loading#
Revision Notes#
Reference files: agentic-bug-fixing-code/agentic_bug_fixing_openai.py, agentic-bug-fixing-notes/agentic_bug_fixing_code_explainer.html
Concept#
FIX_PROMPT is a ChatPromptTemplate piped into the model via LangChain's LCEL syntax (FIX_PROMPT | self.llm). Because LLMs are probabilistic text generators, prompt instructions are requests, not guarantees — the host program must defensively sanitize, parse, and load whatever text the model returns.
How Text Becomes a Callable Function#
Prompt rules are requests rather than guarantees: the host pipeline strips markdown fences, normalizes indentation, validates syntax via AST, and compiles the replacement inside an isolated namespace — recovering gracefully if generated code fails to load.
Key Mental Models#
- Prompts are part of your code contract:
- Instructing GPT to keep the exact same function name and parameters is essential because
load_function_from_code()looks up the new function by its original name (state.function.__name__).
- Instructing GPT to keep the exact same function name and parameters is essential because
- Defensive output cleaning (
clean_llm_code):- Even when told "no markdown, no ```
```` fences", LLMs frequently wrap code in fenced blocks or indent it. - Regex extraction strips fences and
textwrap.dedent()removes shared leading indentation (which would otherwise causeIndentationErrorinsideexec()).
- Even when told "no markdown, no ```
- AST parsing (
first_function_name) beats naive inspection:ast.parse(code)reads Python syntax as a tree without executing it, reliably finding the first top-leveldef/async defeven when pasted code contains imports or helper classes.
- Recovering from unloadable LLM output:
- If
exec()fails (e.g., syntax error or renamed function),code_fix_nodecatches the exception, incrementsattempts, and keeps the previous function so the loop can retry cleanly up toMAX_FIX_ATTEMPTS.
- If
Interactive Diff Viewer & Failure Modes (Silent Bugs vs. Crashes)#
Revision Notes#
Reference files: agentic-bug-fixing-code/agentic_bug_fixing_openai.py, agentic-bug-fixing-notes/agentic_bug_fixing_code_explainer.html
Concept#
The script supports both a quick terminal demo and a Gradio browser app (--ui flag) where users paste code and JSON arguments, run the agent, and inspect a GitHub-style red/green unified diff (difflib.unified_diff + html.escape) alongside original code, fixed code, and execution result. The 7 built-in examples illustrate both what exception-driven agents excel at and where they fundamentally fail.
Key Mental Models#
- What the 7 built-in examples test:
- Crashing bugs (6 examples):
ZeroDivisionError(direct division, unusedmarginon 100% discount, unusedavg_discounton zero quantity),KeyError(invalid coupon),IndexError(out-of-range product ID), andTypeError(formattingNoneprice). All raise exceptions, so the agent detects and patches them. - Silent bug (1 example —
get_inventory_count): Looking up a missing SKU withdict.get(sku)returnsNonewithout raising an exception. The agent reports "No errors detected".
- Crashing bugs (6 examples):
- Silent bugs require test assertions, not just crash detection:
- An agent that only watches for exceptions cannot catch wrong return values or logic bugs.
- Detecting silent bugs requires expected outputs / test suites (e.g., checking
result != expectedor running multiple test cases). This is why production coding agents run automated test suites rather than just executing code.
- "Fixed" is not always "correct":
- Because
FIX_PROMPTtells GPT to return an error string instead of crashing, a numeric function likedivide_two_numbersnow returns astron failure. - Downstream callers expecting a
floatmay now break elsewhere. In real engineering, you must decide whether to raise a typed domain exception, return a sentinel/None, or log and alert — your prompt encodes your architectural contract.
- Because
Production Readiness: Safety, Sandboxing & Inference Optimization#
Revision Notes#
Reference files: agentic-bug-fixing-code/agentic_bug_fixing_openai.py, agentic-bug-fixing-notes/agentic_bug_fixing_code_explainer.html, agentic-bug-fixing-code/.env.example
Concept#
Running LLM-written code with exec() on a developer's machine works for a classroom demo, but shipping a real self-healing agent requires execution sandboxing, provider portability, and cost/latency engineering.
Safety & Sandboxing Pitfalls#
exec()runs with full host permissions: Untrusted or hallucinated AI-generated code can delete files, exfiltrate.envsecrets, make outbound network calls, or hang forever (while True:).- Never expose the Gradio UI publicly: Anyone with access to the UI can execute arbitrary Python on the host machine.
- Production requirement: Execute AI-generated code inside an isolated sandbox (Docker container, E2B, locked-down VM, or timeout-bounded subprocess) with no secrets, no network access, and strict CPU/time limits.
Provider Portability & Inference Optimization#
- Provider swap in two lines: Only
ChatOpenAIis OpenAI-specific; switching from Groq (ChatGroq) to OpenAI or a self-hosted vLLM server (by settingOPENAI_BASE_URLin.env) leaves the graph, state, and UI untouched. - Cost per request & hidden retry costs: Every fix attempt is 1 LLM call (up to
MAX_FIX_ATTEMPTS = 3calls per function). Trackingreply.usage_metadataexposes true token spend; retry caps protect your budget. - Model choice trade-off: Patching small Python functions rarely needs a frontier flagship model — smaller models (
gpt-5-mini) optimize the quality/speed/cost triangle. - Agent latency vs. model latency: User-visible latency is the sum of execution + LLM call + code load + re-execution, multiplied across retries.
- Caching & streaming:
- Response caching: Hashing
(code + error)(sha256) avoids repeat LLM calls for identical crashes. - Streaming & TTFT: Streaming via
self.fix_chain.stream(...)improves perceived responsiveness (Time To First Token) in the UI instead of blocking until the full rewrite completes.
- Response caching: Hashing
Moving a self-healing coding agent to production requires replacing host-level exec() and crash-only checks with isolated sandboxes, test-suite assertions that catch silent logic bugs, and SHA-256 caching to bound latency and token spend.
How All Building Blocks Connect#
Revision Notes#
Every piece of 04-agentic-bug-fixing fits into one cohesive self-healing architecture:
- Configuration & Model (
ChatOpenAI+.env): Supplies a swappable LLM brain with secrets kept outside source code. - Typed Memory (
State(BaseModel)): Tracks the live callable, original and latest source strings, inputs, exception type/message, attempt counter, and final result. - Cyclic Graph (
StateGraph): Connectscode_execution_node→error_router→code_fix_node→code_execution_nodewithMAX_FIX_ATTEMPTS = 3as the safety brake. - Defensive Code Pipeline (
FIX_PROMPT | self.llm→clean_llm_code→ast.parse→exec): Bridges probabilistic LLM text back into executable Python without crashing the agent loop on malformed output. - Observability & UX (Terminal trace + Gradio diff viewer): Surfaces exactly what changed (
difflib.unified_diff) and highlights the boundary between crash-fixing and test-driven verification. - Production Guardrails (Sandboxing + Inference Optimization): Identifies what must be hardened — isolated execution, test suites, caching, streaming, and token/retry budgets — before deploying beyond a demo.
Quick Self-Check Questions#
Self-Check Questions#
Why does State store both function (callable) and function_string (text)?
Python needs the live callable object to execute the function, while GPT needs the source text to read and rewrite it (and the UI needs the original text to compute the diff).
Why should code_fix_node only load the new function instead of executing it directly?
If the new function still crashes, letting code_execution_node run it keeps error handling, state updates, and retry routing cleanly inside the LangGraph loop instead of crashing code_fix_node.
On retry attempt 2, should the agent send the original code or the latest failed fix to GPT?
The latest failed fix (state.new_function_string or state.function_string), so the model iterates on its previous attempt instead of repeating the same mistake from scratch.
Why does code_execution_node record f"{type(e).__name__}: {e}" instead of str(e)?
Some exceptions have minimal messages (e.g., str(KeyError('INVALID')) is just 'INVALID'). Including the exception class name (KeyError: 'INVALID') gives the LLM far clearer diagnostic signal.
Why does the agent report "No errors detected" on the get_inventory_count missing-SKU example?
dict.get(sku) quietly returns None without raising an exception. Crash-driven agents cannot detect silent bugs; catching them requires assertions or test suites with expected outputs.
Why is "fixed" not always the same as "correct" in this demo?
The prompt instructs GPT to return an error string on failure, which changes the function's return type (e.g., returning str instead of float) and can break downstream callers expecting a number.
Why is running exec() directly on the host unsafe in production, and how should it be hardened?
exec() runs AI-written code with the host process's full permissions (file access, .env secrets, network, infinite loops). Production systems must execute generated code in an isolated sandbox (container/VM/subprocess) with no secrets, no network, and a strict timeout.