The bug-fixing agent: an AI that repairs crashing Python functions
Give it a Python function and some inputs. If the function crashes, the agent asks OpenAI's GPT to rewrite it, loads the new version, and runs it again, up to 3 times. You'll see every line explained, a real trace of one request moving through the graph, and exercises for your learners.
What it does, in one minute
💡 The story
You have this function, and someone calls it with b = 0:
def divide_two_numbers(a, b):
return a / b # divide_two_numbers(10, 0) -> ZeroDivisionError 💥
The agent:
- Runs it → it crashes with
ZeroDivisionError: division by zero. - Asks GPT: "here's the code, the inputs, and the error: rewrite it to handle the error gracefully".
- Loads GPT's new version into Python.
- Runs it again → returns
"Error: cannot divide by zero"instead of crashing. Done.
If the new version still crashes, it loops back to step 2 with the newest code, at most 3 times.
🔧 Analogy: the mechanic's test drive
A mechanic test-drives a car (run). Strange noise? They fix it (ask GPT) and test-drive again. Still noisy? Fix again. After 3 failed attempts they stop and call the customer, instead of working on it forever. That "fix → re-test → stop after N tries" loop is the heart of almost every coding agent, from Copilot's agent mode to Claude Code.
The big picture: a graph with two nodes and a loop
💡 The 4 parts of any agent, and where they live in this code
| Agent part | In plain words | In this code |
|---|---|---|
| Brain | Decides what to do / writes new code | OpenAI GPT via ChatOpenAI, used in code_fix_node |
| Hands (tools) | Acts in the world | Running the function and loading code with exec() |
| Memory | Remembers what happened so far | The State object |
| Loop + brakes | Keeps going until done, but not forever | LangGraph edges + error_router + MAX_FIX_ATTEMPTS |
🏭 Analogy: a car service centre
Nodes are workstations. Edges are the paths the car moves along. The router is the supervisor who looks at the job card and decides "back to repairs" or "ready for delivery". The State is the job card every workstation reads and writes on.
How to run it
⌨️ Setup (5 minutes)
- Put these files in one folder:
agentic_bug_fixing_openai.py,requirements.txt,.env.example. - Install:
pip install -r requirements.txt(Python 3.10+). - Copy
.env.exampleto.envand paste your key:OPENAI_API_KEY=sk-... - Terminal demo:
python agentic_bug_fixing_openai.py - Browser app:
python agentic_bug_fixing_openai.py --ui→ open the link it prints (usually http://127.0.0.1:7860).
The model is set in one place at the top of the file: MODEL_NAME = "gpt-5-mini". Change that line to use a different OpenAI model.
What the terminal demo prints (GPT writes the fix fresh each time, so your wording will differ slightly):
=== 1) The ORIGINAL function, called directly ===
Crashed as expected: ZeroDivisionError: division by zero
=== 2) The SAME call, through the bug-fixing agent ===
[run] divide_two_numbers(10, 0)
[run] crashed -> ZeroDivisionError: division by zero
[fix] attempt 1/3: asking gpt-5-mini to fix it
[fix] new version loaded, running it again
[run] divide_two_numbers(10, 0)
[run] ok -> 'Error: Cannot divide by zero.'
--- Fixed code written by GPT ---
def divide_two_numbers(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Cannot divide by zero."
--- Final answer ---
'Error: Cannot divide by zero.'The browser app after clicking "Run Agent & Show Diff" on the first example:
Red line = removed, green lines = added by the agent.
What changed from the original Groq version, and why
Same design, same graph, same Gradio app. Here's everything that's different.
| # | Original | Now | Why |
|---|---|---|---|
| 1 | from langchain_groq import ChatGroqChatGroq(model="llama-3.3-70b-versatile") | from langchain_openai import ChatOpenAIChatOpenAI(model="gpt-5-mini") | The OpenAI switch. The key is read from OPENAI_API_KEY in your .env; the model is set once in MODEL_NAME. |
| 2 | from langchain.schema import HumanMessage | Removed. The prompt is piped into the model: FIX_PROMPT | llm | That import no longer exists in LangChain 1.x. On a fresh install the original crashes at line 3 with ModuleNotFoundError. |
| 3 | No limit on fix attempts | attempts counter + MAX_FIX_ATTEMPTS = 3 | A fix that keeps failing would loop until LangGraph's recursion limit, burning money on every lap. |
| 4 | Fix node ran the new function itself | Fix node only loads it; the loop re-runs it in code_execution_node | If GPT's fix still crashed, the original fix node raised an exception and killed the whole program. |
| 5 | Every retry sent the original code to GPT | Sends the latest version | So attempt 2 improves on attempt 1 instead of starting over. |
| 6 | GPT's reply was exec'd as-is | clean_llm_code() strips ```python fences and extra indentation | LLMs often add markdown fences even when told not to → SyntaxError. |
| 7 | inspect.getsource() used directly | Wrapped in textwrap.dedent() | A function defined inside another block comes back indented, and indented code can't be exec'd. |
| 8 | Error text: str(e) | f"{type(e).__name__}: {e}" | For a missing coupon, str(e) is just 'INVALID'. Now GPT sees KeyError: 'INVALID', which is far clearer. |
| 9 | Prompt had code + error | Prompt also has the arguments | GPT can see exactly which input broke the code. |
| 10 | Function ran again after the graph finished (twice more in total) | Result is saved in state.result | No wasted re-runs, and no surprises if the function has side effects (e.g. sends an email). |
| 11 | UI picked the "first callable" in the code | Uses ast to find the first def | More reliable when the pasted code has imports or classes. |
| 12 | Script ended with answer_2 = divide_two_numbers(10, 0) | Wrapped in try/except, prints both results | The original always ended with a crash traceback, and printed nothing. |
| 13 | App launch commented out | --ui flag | Run the terminal demo or the app without editing code. |
| 14 | API/network errors crashed the UI | Caught and shown in red | A wrong key now shows a readable message instead of a stack trace. |
The code, step by step
The file is split into STEP 0–6 comments. Each block below is copied straight from the file, with its line numbers, so you can follow along in your editor.
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: never ask GPT more than 3 times for one function
💡 What to notice
- Standard-library tools (
ast,difflib,inspect,textwrap…) do the "plumbing". Each has a one-line comment saying why it's needed. - The only provider-specific line is
from langchain_openai import ChatOpenAI. Swapping providers in LangChain is usually a 2-line change. load_dotenv()reads your.envfile into environment variables, so the API key never has to be written in the code.MODEL_NAMEis the OpenAI model that writes the fixes.MAX_FIX_ATTEMPTS = 3is the safety brake. Every agent needs one.
The State: the shared job card
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 result: Any = None # what the function returned on its last good run
💡 In simple words
The State is everything the agent knows right now. LangGraph passes it to each node; each node returns the fields it changed; LangGraph merges those changes in.
functionis the real, callable Python function.function_stringis its text. We need both: Python runs the object, GPT reads the text.error/error_description: what happened on the last run.new_function_string: GPT's latest fix (empty if none needed).attempts: how many times we've asked GPT. The router uses it as the brake.result: the answer from the last successful run.
Why Pydantic (BaseModel)? It's like a printed form with fixed boxes: every field has a name, a type and a default, so a typo like state.erorr fails loudly instead of silently.
The prompt we send to GPT
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." )
💡 In simple words
A fill-in-the-blanks letter. {function_string}, {arguments} and {error_description} are blanks filled in at run time. Here is the exact prompt GPT received for the division example:
You are fixing a Python function that crashed.
Function:
def divide_two_numbers(a, b):
return a / b
It was called with these arguments: [10, 0]
It raised this error: ZeroDivisionError: division by zero
Rewrite the function so it handles this error gracefully by returning an error message (a string) instead of crashing.
Rules:
- Use the exact same function name and parameters.
- Return only the function definition: no explanation, no markdown, no ``` fences.
⚠️ Teaching point: prompts are part of your code
"Same name and parameters" matters because the code looks the function up by name afterwards. "No markdown" is a request, not a guarantee, which is why STEP 3 still strips fences. Always defend against what the LLM might do.
Helper functions: turning LLM text into running code
3a. clean_llm_code: tidy up GPT's reply
def clean_llm_code(text: str) -> str: """GPT sometimes wraps code in ```python ... ``` even when told not to. Remove that.""" text = text.strip() fenced = re.search(r"```(?:python|py)?[ \t]*\n(.*?)```", text, re.DOTALL) if fenced: text = fenced.group(1) # dedent: if the code arrives indented, exec() would fail with "unexpected indent" return textwrap.dedent(text).strip()
If the reply contains ```python … ```, keep only what's inside. Then dedent removes shared leading spaces. Example: "Sure! ```python\ndef f(): ...```" → "def f(): ...".
3b. first_function_name: find the def
def first_function_name(code: str) -> str: """Return the name of the first `def` in a piece of code, e.g. 'divide_two_numbers'.""" tree = ast.parse(code) for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): return node.name raise ValueError("No function definition (def ...) found in the code.")
ast.parse reads code the way Python does (as a tree) without running it. We walk the top level and return the first function's name. The UI uses this to know which function the user pasted.
3c. load_function_from_code: text → callable function
def load_function_from_code(code: str, function_name: str | None = None) -> Callable: """Turn code TEXT into a real function OBJECT we can call. exec() runs the text as Python. The `def` inside it creates the function and stores it in the `namespace` dictionary, from where we pick it up by name. """ namespace: dict = {} exec(code, namespace) # <-- runs GPT-written code: see the SAFETY NOTE at the top name = function_name or first_function_name(code) function = namespace.get(name) if not callable(function): raise ValueError(f"The code does not define a function called '{name}'.") return function
🔧 Analogy for exec()
It's like pasting code into a Python console and pressing Enter, except your program does it. Running a def doesn't call the function; it creates it and stores it in the namespace dictionary. We then take it out by name: namespace["divide_two_numbers"].
The Agent: two nodes, one router, one graph
4a. __init__: connect to OpenAI and build the graph
def __init__(self, model_name: str = MODEL_NAME): self.llm = ChatOpenAI(model=model_name) # <-- the swap: was ChatGroq(model=...) self.fix_chain = FIX_PROMPT | self.llm # "pipe" = fill the prompt, then send it to GPT self.graph = self.build_graph()
ChatOpenAI(model=...)connects to OpenAI. It readsOPENAI_API_KEYautomatically (loaded from.envin STEP 0).FIX_PROMPT | self.llmis LangChain's "pipe": fill the template, then send it to the model. Like a Unix pipe, the output of the left side flows into the right side.
4b. Node 1: code_execution_node (run it)
def code_execution_node(self, state: State) -> dict: print(f"[run] {state.function.__name__}{tuple(state.arguments)}") try: result = state.function(*state.arguments) except Exception as e: # Keep the error TYPE too: "KeyError: 'INVALID'" tells GPT far more than "'INVALID'" description = f"{type(e).__name__}: {e}" print(f"[run] crashed -> {description}") return {"error": True, "error_description": description} print(f"[run] ok -> {result!r}") return {"error": False, "error_description": "", "result": result}
Calls the function with the arguments (*state.arguments unpacks [10, 0] into (10, 0)). Crash? Return error=True plus a description that includes the error type. Success? Return error=False and the result. Notice it returns only the changed fields; LangGraph merges them into the State.
4c. Node 2: code_fix_node (ask GPT)
def code_fix_node(self, state: State) -> dict: attempt = state.attempts + 1 print(f"[fix] attempt {attempt}/{MAX_FIX_ATTEMPTS}: asking {self.llm.model_name} to fix it") # If an earlier fix still crashed, send the LATEST code, not the original one. code_to_fix = state.new_function_string or state.function_string reply = self.fix_chain.invoke({ "function_string": code_to_fix, "arguments": json.dumps(state.arguments, default=str), "error_description": state.error_description, }) new_code = clean_llm_code(reply.content) try: new_function = load_function_from_code(new_code, state.function.__name__) except Exception as e: # GPT wrote code that doesn't even load. Count the attempt and keep the # previous version; the loop will run it, see the same crash, and try again. print(f"[fix] the new code could not be loaded ({type(e).__name__}: {e})") return {"attempts": attempt} print("[fix] new version loaded, running it again") return {"attempts": attempt, "function": new_function, "new_function_string": new_code}
- Count this attempt.
- Pick the code to fix: the latest fix if there is one, otherwise the original.
- Fill the prompt and call GPT (
self.fix_chain.invoke). This is the only line that costs money. - Clean the reply (
reply.contentis GPT's text) and load it as a real function. - If the reply won't load (bad syntax), keep the old version and just count the attempt. The loop will try again.
- Otherwise, return the new function and its code.
4d. The router: error_router (where next?)
def error_router(self, state: State) -> str: if not state.error: return END # it worked, we're done if state.attempts >= MAX_FIX_ATTEMPTS: print(f"[stop] still failing after {state.attempts} fix attempts, giving up") return END # safety brake return "code_fix_node" # crashed: go fix it
Three possibilities, checked in order: worked → END; out of attempts → END (the brake); otherwise → code_fix_node. The router only decides; it never changes the State.
4e. build_graph: wire it up
def build_graph(self): builder = StateGraph(State) builder.add_node("code_execution_node", self.code_execution_node) builder.add_node("code_fix_node", self.code_fix_node) builder.set_entry_point("code_execution_node") # always start by running it builder.add_conditional_edges("code_execution_node", self.error_router) # then ask the router builder.add_edge("code_fix_node", "code_execution_node") # after a fix, run again return builder.compile()
| Line | Meaning |
|---|---|
StateGraph(State) | "This graph passes a State around." |
add_node(name, function) | Register a workstation. |
set_entry_point(...) | Always start by running the code. |
add_conditional_edges(node, router) | After running, ask the router where to go. |
add_edge(fix, execution) | After every fix, always re-run. This creates the loop. |
compile() | Check the wiring and produce a runnable graph. |
4f. run and execute: easy entry points
def run(self, function: Callable, arguments: list, function_string: str | None = None) -> dict: """Run the whole loop. Returns the final State as a dictionary.""" state = State( function=function, function_string=function_string or textwrap.dedent(inspect.getsource(function)), arguments=arguments, ) return self.graph.invoke(state)
def execute(self, function: Callable, arguments: list): """Same as the original execute(): give back the function's answer.""" final_state = self.run(function, arguments) if final_state.get("error"): return (f"Could not fix the function after {final_state.get('attempts', 0)} attempt(s). " f"Last error: {final_state.get('error_description')}") return final_state.get("result")
run() builds the starting State (getting the function's source text automatically) and invokes the graph. It returns the final State as a dictionary. execute() keeps the original file's behaviour: it just returns the function's answer, or a readable message if fixing failed.
The Gradio app: paste code, see the fix as a diff
5a. The button handler
def run_agent_and_show_diff(self, code_string: str, arguments_str: str): """Button handler. Returns 4 things: original code, fixed code, diff HTML, result text.""" # 5a. Read the arguments the user typed, e.g. [10, 0] try: arguments = json.loads(arguments_str) if not isinstance(arguments, list): arguments = [arguments] # a single value becomes a 1-item list except json.JSONDecodeError: return code_string, "Error parsing arguments", self._error_html("Invalid JSON format for arguments"), "Error: Invalid arguments" # 5b. Turn the code text into a real function try: function = load_function_from_code(code_string) except Exception as e: return code_string, f"Error: {e}", self._error_html(f"Error loading code: {e}"), f"Error: {e}" # 5c. Run the agent loop self.original_code = code_string try: final_state = self.agent.run(function, arguments, function_string=code_string) except Exception as e: # e.g. wrong API key, no internet return code_string, "Agent failed", self._error_html(f"Agent failed: {e}"), f"Error: {e}" # 5d. Build the outputs self.fixed_code = final_state.get("new_function_string", "") if self.fixed_code: diff = self._generate_colored_diff_html(self.original_code, self.fixed_code) else: diff = ('<pre style="font-family: monospace; background-color: var(--dkb-f6f8fa, #f6f8fa); padding: 10px; ' 'border-radius: 5px; color: #1a7f37;">No errors detected - code executed successfully!</pre>') if final_state.get("error"): result = (f"Still failing after {final_state.get('attempts', 0)} fix attempt(s): " f"{final_state.get('error_description')}") else: result = repr(final_state.get("result")) return self.original_code, self.fixed_code or "No fix needed", diff, result
- 5a: read the arguments as JSON (
[10, 0],[null]…). A single value becomes a 1-item list. - 5b: turn the pasted text into a function (STEP 3 helpers).
- 5c: run the agent. API problems (wrong key, no internet) are caught and shown.
- 5d: build the 4 outputs: original code, fixed code, a coloured diff, and the result.
5b. The diff (like git diff)
def _generate_diff(self, original: str, fixed: str) -> str: """Unified diff, like `git diff`: '-' = removed line, '+' = added line.""" diff = difflib.unified_diff( original.splitlines(), fixed.splitlines(), fromfile="original", tofile="fixed", lineterm="", ) return "\n".join(diff)
difflib.unified_diff compares the two versions line by line: lines starting with - were removed, + were added. _generate_colored_diff_html then paints them red and green, and html.escape makes sure code like < can't break the page.
Show the UI code (launch), mostly Gradio boilerplate
def launch(self): import gradio as gr # Ready-made buggy functions to try (name -> code + arguments as JSON) examples = { "Division by Zero": { "code": "def divide_two_numbers(a, b):\n return a / b", "args": "[10, 0]", }, "E-commerce: 100% Discount Price": { "code": ( "def calculate_total_price(items, discount_percent):\n" " subtotal = sum(item['price'] * item['quantity'] for item in items)\n" " discount_amount = subtotal * (discount_percent / 100)\n" " margin = subtotal / (subtotal - discount_amount)\n" " final_price = subtotal - discount_amount\n" " return final_price" ), "args": '[[{"price": 10, "quantity": 2}], 100]', }, "Invalid Coupon Code": { "code": ( "def apply_coupon_code(cart_total, coupon_code):\n" " coupons = {\n" " 'SAVE10': 0.10,\n" " 'SAVE20': 0.20,\n" " 'BLACKFRIDAY': 0.50\n" " }\n" " discount = coupons[coupon_code]\n" " return cart_total * (1 - discount)" ), "args": '[100, "INVALID"]', }, "Product Index Out of Range": { "code": "def get_product_price(products, product_id):\n return products[product_id]['price']", "args": '[[{"price": 10}, {"price": 20}], 5]', }, "Bulk Discount - Zero Quantity": { "code": ( "def calculate_bulk_discount(quantity, unit_price):\n" " avg_discount = 100 / quantity\n" " if quantity >= 100:\n" " discount = 0.20\n" " elif quantity >= 50:\n" " discount = 0.10\n" " elif quantity >= 10:\n" " discount = 0.05\n" " else:\n" " discount = 0.0\n" " return quantity * unit_price * (1 - discount)" ), "args": "[0, 10.99]", }, "Format Price - None Value": { "code": 'def format_price_display(price):\n return f"${price:.2f}"', "args": "[null]", }, # This one does NOT crash: .get() quietly returns None. The agent only fixes # crashes, so it reports "no errors". Good discussion point about silent bugs! "Inventory - Missing SKU (silent bug)": { "code": "def get_inventory_count(inventory, sku):\n return inventory.get(sku)", "args": '[{"ABC123": 10}, "XYZ999"]', }, } first = "Division by Zero" def load_example(example_name): if example_name in examples: return examples[example_name]["code"], examples[example_name]["args"] return "", "[]" with gr.Blocks(title="Agentic Bug Fixing - Code Diff Viewer") as demo: gr.Markdown("# Agentic Bug Fixing - Code Diff Viewer") gr.Markdown("Enter a Python function and its arguments. If it crashes, the agent asks " f"OpenAI (`{self.agent.llm.model_name}`) to fix it.") example_dropdown = gr.Dropdown(choices=list(examples.keys()), label="Load Example", value=first) with gr.Row(): with gr.Column(scale=2): gr.Markdown("### Python Function Code") code_input = gr.Code(value=examples[first]["code"], language="python", label="", lines=12) with gr.Column(scale=1): gr.Markdown("### Function Arguments") arguments_input = gr.Textbox(value=examples[first]["args"], label="Arguments (JSON format)", placeholder='[10, 0] or {"key": "value"}', lines=2) run_btn = gr.Button("Run Agent & Show Diff", variant="primary", size="lg") gr.Markdown("### Git-Style Diff") diff_output = gr.HTML(label="") with gr.Row(): with gr.Column(): gr.Markdown("### Original Code") original_output = gr.Code(language="python", label="") with gr.Column(): gr.Markdown("### Fixed Code") fixed_output = gr.Code(language="python", label="") gr.Markdown("### Execution Result") result_output = gr.Textbox(label="", lines=3) example_dropdown.change(fn=load_example, inputs=[example_dropdown], outputs=[code_input, arguments_input]) run_btn.click(fn=self.run_agent_and_show_diff, inputs=[code_input, arguments_input], outputs=[original_output, fixed_output, diff_output, result_output]) demo.launch()
💡 Gradio in one breath
gr.Blocks is the page. gr.Row/gr.Column arrange things. gr.Code, gr.Textbox and gr.HTML are the widgets. run_btn.click(fn=..., inputs=[...], outputs=[...]) says: "when clicked, call this Python function with these widget values and put its return values into those widgets". That's the whole mental model.
The terminal demo and the entry point
def demo_in_terminal(): agent = Agent() def divide_two_numbers(a, b): return a / b print("\n=== 1) The ORIGINAL function, called directly ===") try: divide_two_numbers(10, 0) except ZeroDivisionError as e: print(f"Crashed as expected: ZeroDivisionError: {e}") # (The original script did `answer_2 = divide_two_numbers(10, 0)` without try/except, # so the whole program died with a traceback at the very end.) print("\n=== 2) The SAME call, through the bug-fixing agent ===") final_state = agent.run(divide_two_numbers, [10, 0]) print("\n--- Fixed code written by GPT ---") print(final_state.get("new_function_string") or "(no fix was needed)") print("\n--- Final answer ---") if final_state.get("error"): print(f"Still failing: {final_state.get('error_description')}") else: print(repr(final_state.get("result")))
if __name__ == "__main__": if "--ui" in sys.argv: App().launch() else: demo_in_terminal()
It first calls the original function directly (crashes, caught and printed), then runs the same call through the agent and prints the fixed code and the final answer. --ui on the command line starts the browser app instead.
Watching the agent think
One request, step by step through the graph
agent.graph.stream(state, stream_mode="updates") prints what each node returned. Try it in class.
[run] divide_two_numbers(10, 0)
[run] crashed -> ZeroDivisionError: division by zero
### STEP 1: code_execution_node returned -> {'error': True, 'error_description': 'ZeroDivisionError: division by zero'}
[fix] attempt 1/3: asking gpt-5-mini to fix it
[fix] new version loaded, running it again
### STEP 2: code_fix_node returned -> {'attempts': 1, 'function': '<function divide_two_numbers> (the NEW version)', 'new_function_string': 'def divide_two_numbers(a, b):\n try:\n return a / b\n except ZeroDivisionError:\n return "Error: Cannot divide by zero."'}
[run] divide_two_numbers(10, 0)
[run] ok -> 'Error: Cannot divide by zero.'
### STEP 3: code_execution_node returned -> {'error': False, 'error_description': '', 'result': 'Error: Cannot divide by zero.'}| Moment | error | attempts | function | result | Router says |
|---|---|---|---|---|---|
| Start | False | 0 | original (a / b) | None | – |
| After code_execution_node | True | 0 | original | None | → code_fix_node |
| After code_fix_node | True | 1 | new version (try/except) | None | (always → run again) |
| After code_execution_node | False | 1 | new version | "Error: Cannot divide by zero." | → END |
💡 Read it like this
3 node runs, 1 LLM call. If GPT's first fix had still crashed, you'd see two more steps (fix → run) with attempts=2, and at most up to attempts=3.
The 7 built-in examples: what breaks and what a good fix does
| Example | Arguments | Crash | A good fix… |
|---|---|---|---|
| Division by Zero | [10, 0] | ZeroDivisionError | catches it and returns an error message |
| E-commerce: 100% discount | one item, 100% off | ZeroDivisionError in the (unused!) margin line | guards the division. A sharp fix also notices margin is never used. |
| Invalid Coupon Code | [100, "INVALID"] | KeyError: 'INVALID' | checks the coupon exists first |
| Product Index Out of Range | 2 products, id 5 | IndexError | checks the index is within range |
| Bulk Discount: zero quantity | [0, 10.99] | ZeroDivisionError in unused avg_discount | rejects quantity ≤ 0 |
| Format Price: None | [null] | TypeError (can't format None) | handles a missing price |
| Inventory: missing SKU | SKU not in dict | No crash! Returns None | nothing: the agent sees no error |
⚠️ The best class discussion: the silent bug
The last example returns None instead of a stock count, which is wrong, but nothing crashes, so the agent reports "no errors". This agent can only fix bugs that raise exceptions. To catch silent bugs you need expected outputs (tests). That's exercise 3 below, and it's exactly why real coding agents run test suites, not just the code.
⚠️ Second discussion: "fixed" isn't always "correct"
The prompt asks GPT to return an error message instead of crashing. So the fixed function now returns a string where callers expected a number. That's fine for a demo, but in real code, would you rather raise a clear custom error, return None, or log and alert? Agents do what the prompt says, so the prompt encodes your engineering decisions.
Connecting it to the lecture
How this agent connects to the inference-optimization lecture
| Lecture idea | Where it shows up in this agent |
|---|---|
| Cost per request (slides 5–7) | Each fix attempt = 1 LLM call. Worst case = 3 calls per function. That's why the brake matters. |
| Retries are hidden cost (slide 6) | MAX_FIX_ATTEMPTS caps the bill. The original code had no cap. |
| Model choice / the triangle (slide 2) | Fixing a 5-line function doesn't need the biggest model. Change MODEL_NAME to a smaller or larger model and compare quality vs speed. |
| Agent latency ≠ model latency (slide 10) | User-visible time = run + LLM call + load + run again (+ more if it retries). |
| Response caching (slide 22) | The same broken code + same error → the same fix. Cache it with key = hash(code + error). See exercise 1. |
| TTFT and streaming (slide 9) | The UI waits for the whole fix. Streaming GPT's reply into the "Fixed Code" box would feel faster. See exercise 4. |
| Self-hosting with vLLM (slide 17) | Add OPENAI_BASE_URL=http://localhost:8000/v1 to .env (ChatOpenAI reads it) and set MODEL_NAME to your model. |
Exercises for learners (easy → hard)
- Cache the fixes. Before calling GPT in
code_fix_node, computehashlib.sha256((code + error).encode())and look it up in a dict. Count how many LLM calls you save when you click the same example twice. - Log tokens and cost. The reply has
reply.usage_metadata(input/output tokens). Add them to the State and print the cost of each fix using the formula from slide 7. - Catch silent bugs. Add
expected: Any = Noneto the State. Incode_execution_node, treat "result ≠ expected" as an error. Now the inventory example gets fixed too. - Stream the fix. Use
self.fix_chain.stream(...)and print chunks as they arrive. Measure the TTFT. - Test many inputs. Change
argumentsto a list of test cases. A fix only "passes" if all cases run. - Sandbox it. Run the function in a
subprocesswith a timeout (sowhile True:can't freeze the app), or inside Docker. - Draw the graph.
print(agent.graph.get_graph().draw_mermaid()), then paste the output into mermaid.live.
Safety note: this runs AI-written code
⚠️ Say this out loud in class
exec() runs whatever text it's given with your permissions: it could delete files, read your .env, or call the internet. In a classroom demo with toy functions that's acceptable. In any real product, AI-written code must run in a sandbox (a container or isolated VM with no secrets, no network and a time limit). The same applies to the Gradio app: anyone who can open it can run code on your machine, so don't share its link publicly.
Glossary
- Agent
- An LLM in a loop with tools and memory, that keeps acting until a goal is met (or a limit is hit).
- LangGraph
- A library for building agents as graphs of steps (nodes) and paths (edges) that share a State.
- State
- The shared data every node reads and updates. Here a Pydantic model.
- Node
- One step in the graph: a Python function that takes the State and returns changes.
- Edge
- A fixed path from one node to the next.
- Conditional edge / router
- A function that looks at the State and picks the next node.
- END
- LangGraph's special "stop here" destination.
- ChatOpenAI
- LangChain's wrapper around OpenAI chat models.
- ChatPromptTemplate
- A prompt with {blanks} filled in at run time.
- Pipe ( | )
- LangChain syntax for "feed the output of the left into the right".
- exec()
- Python built-in that runs a string as code.
- ast
- Python's module for reading code as a tree without running it.
- Pydantic
- A library for data classes with type-checked fields.
- Gradio
- A library that builds a web UI from Python functions.
- Unified diff
- The "- removed / + added" format used by git.
Full source
agentic_bug_fixing_openai.py (complete file)
""" Agentic Bug Fixing - OpenAI version ===================================== Author: Shivank Agarwal WHAT THIS PROGRAM DOES (one line) It runs a Python function. If the function crashes, OpenAI GPT rewrites the function so it handles the error, then the new version is run again. HOW IT WORKS (the "agent loop") START | v +----------------------+ no error / too many tries +-----+ | code_execution_node | -----------------------------> | END | | (run the function) | +-----+ +----------------------+ | it crashed v +----------------------+ | code_fix_node | asks GPT to rewrite the function, | (ask GPT to fix it) | then loads the new code +----------------------+ | +------> back to code_execution_node (run the NEW version) HOW TO RUN 1. pip install -r requirements.txt 2. Create a file called .env next to this file with one line: OPENAI_API_KEY=sk-...your key... 3. python agentic_bug_fixing_openai.py -> quick demo in the terminal python agentic_bug_fixing_openai.py --ui -> browser app (Gradio) with a diff viewer SAFETY NOTE This program runs (exec) code that GPT wrote, on your own machine. That is fine for a classroom demo. In a real product, run it inside a sandbox (a Docker container, E2B, a locked-down VM...) so bad code can't hurt anything. """ # --------------------------------------------------------------------------- # 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: never ask GPT more than 3 times for one function # --------------------------------------------------------------------------- # STEP 1: The State = the "job card" every node reads from and writes into # --------------------------------------------------------------------------- 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 result: Any = None # what the function returned on its last good run # --------------------------------------------------------------------------- # STEP 2: The prompt we send to GPT # --------------------------------------------------------------------------- # Words inside {curly braces} are blanks that get filled in at run time. 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." ) # --------------------------------------------------------------------------- # STEP 3: Small helper functions # --------------------------------------------------------------------------- def clean_llm_code(text: str) -> str: """GPT sometimes wraps code in ```python ... ``` even when told not to. Remove that.""" text = text.strip() fenced = re.search(r"```(?:python|py)?[ \t]*\n(.*?)```", text, re.DOTALL) if fenced: text = fenced.group(1) # dedent: if the code arrives indented, exec() would fail with "unexpected indent" return textwrap.dedent(text).strip() def first_function_name(code: str) -> str: """Return the name of the first `def` in a piece of code, e.g. 'divide_two_numbers'.""" tree = ast.parse(code) for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): return node.name raise ValueError("No function definition (def ...) found in the code.") def load_function_from_code(code: str, function_name: str | None = None) -> Callable: """Turn code TEXT into a real function OBJECT we can call. exec() runs the text as Python. The `def` inside it creates the function and stores it in the `namespace` dictionary, from where we pick it up by name. """ namespace: dict = {} exec(code, namespace) # <-- runs GPT-written code: see the SAFETY NOTE at the top name = function_name or first_function_name(code) function = namespace.get(name) if not callable(function): raise ValueError(f"The code does not define a function called '{name}'.") return function # --------------------------------------------------------------------------- # STEP 4: The Agent = two nodes + one router, wired into a LangGraph graph # --------------------------------------------------------------------------- class Agent: def __init__(self, model_name: str = MODEL_NAME): self.llm = ChatOpenAI(model=model_name) # <-- the swap: was ChatGroq(model=...) self.fix_chain = FIX_PROMPT | self.llm # "pipe" = fill the prompt, then send it to GPT self.graph = self.build_graph() # ---- Node 1: run the function and record what happened ----------------- def code_execution_node(self, state: State) -> dict: print(f"[run] {state.function.__name__}{tuple(state.arguments)}") try: result = state.function(*state.arguments) except Exception as e: # Keep the error TYPE too: "KeyError: 'INVALID'" tells GPT far more than "'INVALID'" description = f"{type(e).__name__}: {e}" print(f"[run] crashed -> {description}") return {"error": True, "error_description": description} print(f"[run] ok -> {result!r}") return {"error": False, "error_description": "", "result": result} # A node returns ONLY the fields it changed. LangGraph merges them into the State. # ---- Node 2: ask GPT to fix the function -------------------------------- def code_fix_node(self, state: State) -> dict: attempt = state.attempts + 1 print(f"[fix] attempt {attempt}/{MAX_FIX_ATTEMPTS}: asking {self.llm.model_name} to fix it") # If an earlier fix still crashed, send the LATEST code, not the original one. code_to_fix = state.new_function_string or state.function_string reply = self.fix_chain.invoke({ "function_string": code_to_fix, "arguments": json.dumps(state.arguments, default=str), "error_description": state.error_description, }) new_code = clean_llm_code(reply.content) try: new_function = load_function_from_code(new_code, state.function.__name__) except Exception as e: # GPT wrote code that doesn't even load. Count the attempt and keep the # previous version; the loop will run it, see the same crash, and try again. print(f"[fix] the new code could not be loaded ({type(e).__name__}: {e})") return {"attempts": attempt} print("[fix] new version loaded, running it again") return {"attempts": attempt, "function": new_function, "new_function_string": new_code} # ---- Router: after each run, decide where to go next --------------------- def error_router(self, state: State) -> str: if not state.error: return END # it worked, we're done if state.attempts >= MAX_FIX_ATTEMPTS: print(f"[stop] still failing after {state.attempts} fix attempts, giving up") return END # safety brake return "code_fix_node" # crashed: go fix it # ---- Wire the nodes together --------------------------------------------- def build_graph(self): builder = StateGraph(State) builder.add_node("code_execution_node", self.code_execution_node) builder.add_node("code_fix_node", self.code_fix_node) builder.set_entry_point("code_execution_node") # always start by running it builder.add_conditional_edges("code_execution_node", self.error_router) # then ask the router builder.add_edge("code_fix_node", "code_execution_node") # after a fix, run again return builder.compile() # ---- Easy entry points ---------------------------------------------------- def run(self, function: Callable, arguments: list, function_string: str | None = None) -> dict: """Run the whole loop. Returns the final State as a dictionary.""" state = State( function=function, function_string=function_string or textwrap.dedent(inspect.getsource(function)), arguments=arguments, ) return self.graph.invoke(state) def execute(self, function: Callable, arguments: list): """Same as the original execute(): give back the function's answer.""" final_state = self.run(function, arguments) if final_state.get("error"): return (f"Could not fix the function after {final_state.get('attempts', 0)} attempt(s). " f"Last error: {final_state.get('error_description')}") return final_state.get("result") # --------------------------------------------------------------------------- # STEP 5: The browser app (Gradio) - type code + arguments, see the fix as a diff # --------------------------------------------------------------------------- class App: def __init__(self): self.agent = Agent() self.original_code = "" self.fixed_code = "" def run_agent_and_show_diff(self, code_string: str, arguments_str: str): """Button handler. Returns 4 things: original code, fixed code, diff HTML, result text.""" # 5a. Read the arguments the user typed, e.g. [10, 0] try: arguments = json.loads(arguments_str) if not isinstance(arguments, list): arguments = [arguments] # a single value becomes a 1-item list except json.JSONDecodeError: return code_string, "Error parsing arguments", self._error_html("Invalid JSON format for arguments"), "Error: Invalid arguments" # 5b. Turn the code text into a real function try: function = load_function_from_code(code_string) except Exception as e: return code_string, f"Error: {e}", self._error_html(f"Error loading code: {e}"), f"Error: {e}" # 5c. Run the agent loop self.original_code = code_string try: final_state = self.agent.run(function, arguments, function_string=code_string) except Exception as e: # e.g. wrong API key, no internet return code_string, "Agent failed", self._error_html(f"Agent failed: {e}"), f"Error: {e}" # 5d. Build the outputs self.fixed_code = final_state.get("new_function_string", "") if self.fixed_code: diff = self._generate_colored_diff_html(self.original_code, self.fixed_code) else: diff = ('<pre style="font-family: monospace; background-color: var(--dkb-f6f8fa, #f6f8fa); padding: 10px; ' 'border-radius: 5px; color: #1a7f37;">No errors detected - code executed successfully!</pre>') if final_state.get("error"): result = (f"Still failing after {final_state.get('attempts', 0)} fix attempt(s): " f"{final_state.get('error_description')}") else: result = repr(final_state.get("result")) return self.original_code, self.fixed_code or "No fix needed", diff, result @staticmethod def _error_html(message: str) -> str: return f'<pre style="color: red;">{html.escape(message)}</pre>' def _generate_diff(self, original: str, fixed: str) -> str: """Unified diff, like `git diff`: '-' = removed line, '+' = added line.""" diff = difflib.unified_diff( original.splitlines(), fixed.splitlines(), fromfile="original", tofile="fixed", lineterm="", ) return "\n".join(diff) def _generate_colored_diff_html(self, original: str, fixed: str) -> str: """Same diff, coloured red/green like GitHub.""" diff_text = self._generate_diff(original, fixed) if not diff_text: return ('<pre style="font-family: monospace; background-color: var(--dkb-f6f8fa, #f6f8fa); padding: 10px; ' 'border-radius: 5px;">No differences found</pre>') html_lines = [] for line in diff_text.split("\n"): escaped = html.escape(line) if line.startswith("---") or line.startswith("+++"): html_lines.append(f'<div style="font-weight: bold;">{escaped}</div>') # file headers elif line.startswith("@@"): html_lines.append(f'<div style="color: var(--dkf-0969da, #0969da);">{escaped}</div>') # line numbers elif line.startswith("-"): html_lines.append(f'<div style="background-color: var(--dkb-ffebe9, #ffebe9); color: var(--dkf-cf222e, #cf222e);">{escaped}</div>') # removed elif line.startswith("+"): html_lines.append(f'<div style="background-color: var(--dkb-dafbe1, #dafbe1); color: var(--dkf-1a7f37, #1a7f37);">{escaped}</div>') # added else: html_lines.append(f"<div>{escaped}</div>") # unchanged return ('<pre style="font-family: monospace; background-color: var(--dkb-f6f8fa, #f6f8fa); padding: 10px; ' f'border-radius: 5px; overflow-x: auto;">{"".join(html_lines)}</pre>') def launch(self): import gradio as gr # Ready-made buggy functions to try (name -> code + arguments as JSON) examples = { "Division by Zero": { "code": "def divide_two_numbers(a, b):\n return a / b", "args": "[10, 0]", }, "E-commerce: 100% Discount Price": { "code": ( "def calculate_total_price(items, discount_percent):\n" " subtotal = sum(item['price'] * item['quantity'] for item in items)\n" " discount_amount = subtotal * (discount_percent / 100)\n" " margin = subtotal / (subtotal - discount_amount)\n" " final_price = subtotal - discount_amount\n" " return final_price" ), "args": '[[{"price": 10, "quantity": 2}], 100]', }, "Invalid Coupon Code": { "code": ( "def apply_coupon_code(cart_total, coupon_code):\n" " coupons = {\n" " 'SAVE10': 0.10,\n" " 'SAVE20': 0.20,\n" " 'BLACKFRIDAY': 0.50\n" " }\n" " discount = coupons[coupon_code]\n" " return cart_total * (1 - discount)" ), "args": '[100, "INVALID"]', }, "Product Index Out of Range": { "code": "def get_product_price(products, product_id):\n return products[product_id]['price']", "args": '[[{"price": 10}, {"price": 20}], 5]', }, "Bulk Discount - Zero Quantity": { "code": ( "def calculate_bulk_discount(quantity, unit_price):\n" " avg_discount = 100 / quantity\n" " if quantity >= 100:\n" " discount = 0.20\n" " elif quantity >= 50:\n" " discount = 0.10\n" " elif quantity >= 10:\n" " discount = 0.05\n" " else:\n" " discount = 0.0\n" " return quantity * unit_price * (1 - discount)" ), "args": "[0, 10.99]", }, "Format Price - None Value": { "code": 'def format_price_display(price):\n return f"${price:.2f}"', "args": "[null]", }, # This one does NOT crash: .get() quietly returns None. The agent only fixes # crashes, so it reports "no errors". Good discussion point about silent bugs! "Inventory - Missing SKU (silent bug)": { "code": "def get_inventory_count(inventory, sku):\n return inventory.get(sku)", "args": '[{"ABC123": 10}, "XYZ999"]', }, } first = "Division by Zero" def load_example(example_name): if example_name in examples: return examples[example_name]["code"], examples[example_name]["args"] return "", "[]" with gr.Blocks(title="Agentic Bug Fixing - Code Diff Viewer") as demo: gr.Markdown("# Agentic Bug Fixing - Code Diff Viewer") gr.Markdown("Enter a Python function and its arguments. If it crashes, the agent asks " f"OpenAI (`{self.agent.llm.model_name}`) to fix it.") example_dropdown = gr.Dropdown(choices=list(examples.keys()), label="Load Example", value=first) with gr.Row(): with gr.Column(scale=2): gr.Markdown("### Python Function Code") code_input = gr.Code(value=examples[first]["code"], language="python", label="", lines=12) with gr.Column(scale=1): gr.Markdown("### Function Arguments") arguments_input = gr.Textbox(value=examples[first]["args"], label="Arguments (JSON format)", placeholder='[10, 0] or {"key": "value"}', lines=2) run_btn = gr.Button("Run Agent & Show Diff", variant="primary", size="lg") gr.Markdown("### Git-Style Diff") diff_output = gr.HTML(label="") with gr.Row(): with gr.Column(): gr.Markdown("### Original Code") original_output = gr.Code(language="python", label="") with gr.Column(): gr.Markdown("### Fixed Code") fixed_output = gr.Code(language="python", label="") gr.Markdown("### Execution Result") result_output = gr.Textbox(label="", lines=3) example_dropdown.change(fn=load_example, inputs=[example_dropdown], outputs=[code_input, arguments_input]) run_btn.click(fn=self.run_agent_and_show_diff, inputs=[code_input, arguments_input], outputs=[original_output, fixed_output, diff_output, result_output]) demo.launch() # --------------------------------------------------------------------------- # STEP 6: Terminal demo (what runs when you type: python agentic_bug_fixing_openai.py) # --------------------------------------------------------------------------- def demo_in_terminal(): agent = Agent() def divide_two_numbers(a, b): return a / b print("\n=== 1) The ORIGINAL function, called directly ===") try: divide_two_numbers(10, 0) except ZeroDivisionError as e: print(f"Crashed as expected: ZeroDivisionError: {e}") # (The original script did `answer_2 = divide_two_numbers(10, 0)` without try/except, # so the whole program died with a traceback at the very end.) print("\n=== 2) The SAME call, through the bug-fixing agent ===") final_state = agent.run(divide_two_numbers, [10, 0]) print("\n--- Fixed code written by GPT ---") print(final_state.get("new_function_string") or "(no fix was needed)") print("\n--- Final answer ---") if final_state.get("error"): print(f"Still failing: {final_state.get('error_description')}") else: print(repr(final_state.get("result"))) if __name__ == "__main__": if "--ui" in sys.argv: App().launch() else: demo_in_terminal()