GyaanStack. Blog

Articles / agentspython

Build a self-correcting code assistant in Python: generate, test, retry

A Python loop that writes code with a local model, runs it against tests with a timeout, feeds the failure back and retries. Measured pass rates, real traces.

By Raghunath · · 18 min read

A self-correcting code assistant asks a model for code, runs that code against tests, and if the tests fail it sends the failure output back to the model and asks again. It stops when the tests pass or when it runs out of attempts. The whole idea fits in a 30-line function. The work is in the parts around it: running untrusted code without hanging your machine, deciding what counts as a pass, and checking whether the retries helped or only taught the model to satisfy one test file.

This post builds that loop in standard-library Python, points it at a local model through Ollama, and measures it. Six small tasks, three seeds each, one attempt versus up to three. On visible tests, retries lifted the pass rate from 10/18 to 12/18. On hidden tests the model never saw, the numbers were 6/18 and 8/18. Visible tests passed several solutions that the hidden tests then failed, and most of this post is about that gap.

This is a narrower build than Build an AI coding agent in Python, which gives a model tools to read and edit a repo and only lets it stop when the suite passes. Here there are no tools and no repo. The model writes one module from a spec, and the test runner is the only feedback it gets. If you want the version that edits real code, read that post. For the design at scale, see Design an AI coding agent.

What you are building#

  task spec ---> model.complete(messages) ---> extract ```python block
                       ^                                |
                       |                                v
                       |                      run_tests(code, visible tests)
                       |                       temp dir, child process,
                       |                       5 s wall clock, 5 s CPU,
                       |                       kill whole process group
                       |                                |
                       |          fail / timeout        |  pass
                       +---- append test output <-------+---------> stop
                             (up to max_attempts)            |
                                                             v
                                            score separately on hidden tests
File Job
tasks.py Six task specs, each with visible tests (sent back on failure) and hidden tests (scoring only)
sandbox.py Runs code against tests in a child process with a timeout and resource limits
model.py One complete(messages) method: an Ollama client and a scripted stub
loop.py Generate, test, feed back, retry
run_eval.py Runs every task with three seeds and prints pass rates
demo_failures.py Replays failure modes with the scripted stub

Everything ran on Python 3.15.2 on macOS with Ollama 0.40.16 and qwen2.5:7b. There are no pip installs. If you have no GPU, the scripted stub runs every part except the measurement.

Step 1: tasks with two sets of tests#

Each task has a prompt, a tests suite the model sees in failure output, and a hidden suite it never sees. Without the hidden suite you cannot tell a correct function from one that fits the three visible asserts.

"""Small tasks. 'tests' are shown to the model on failure; 'hidden' are only used for scoring."""
HEAD = "import unittest\nfrom solution import *\n\nclass T(unittest.TestCase):\n"
TAIL = "\nif __name__ == '__main__':\n    unittest.main()\n"


def suite(*cases):
    body = "".join(f"    def test_{i}(self):\n        {c}\n" for i, c in enumerate(cases))
    return HEAD + body + TAIL


TASKS = [
    {
        "name": "merge_intervals",
        "prompt": "Write merge_intervals(pairs) that takes a list of [start, end] integer pairs in any "
                  "order and returns a new sorted list of merged [start, end] lists. Intervals that "
                  "touch (end == next start) are merged. Do not modify the input list.",
        "tests": suite(
            "self.assertEqual(merge_intervals([[5,7],[1,3],[2,4]]), [[1,4],[5,7]])",
            "self.assertEqual(merge_intervals([[1,2],[2,3]]), [[1,3]])",
            "self.assertEqual(merge_intervals([]), [])",
        ),
        "hidden": suite(
            "x = [[3,4],[1,2]]; merge_intervals(x); self.assertEqual(x, [[3,4],[1,2]])",
            "self.assertEqual(merge_intervals([[1,10],[2,3],[4,5]]), [[1,10]])",
            "self.assertEqual(merge_intervals([[1,1]]), [[1,1]])",
        ),
    },
    # ... parse_duration, rle, wrap, business_days, version_cmp follow the same shape
]

The other five tasks are parse_duration('1h30m') -> 5400 with strict unit order, run-length encode and decode with multi-digit counts, word wrap without textwrap, Monday-to-Friday counts between two dates with the end excluded, and dotted version comparison where '1.0' equals '1'. Every prompt states the edge cases the hidden tests check. A hidden test that checks something the spec never mentions measures luck, not correctness.

Before trusting any number below, run a reference solution through both suites. Mine passed all 12. If your reference fails a test, the test is wrong, and every pass rate built on it is too.

Step 2: the test runner#

The runner writes solution.py and test_solution.py into a fresh temp directory and runs python -m unittest there in a child process.

"""Run candidate code against tests in a child process with limits. NOT a security sandbox."""
import os, re, signal, subprocess, sys, tempfile, time
from pathlib import Path

MAX_OUTPUT = 3_000  # characters of test output kept (the tail)


def _limits():
    # Runs in the child just before exec (POSIX only).
    import resource
    resource.setrlimit(resource.RLIMIT_CPU, (5, 5))                 # 5 s of CPU time
    resource.setrlimit(resource.RLIMIT_FSIZE, (1_000_000, 1_000_000))  # no file over 1 MB


def run_tests(code, test_code, timeout=5):
    """Write solution.py and test_solution.py to a fresh temp dir and run unittest there."""
    expected = test_code.count("def test_")
    with tempfile.TemporaryDirectory() as tmp:
        tmp = os.path.realpath(tmp)  # /var -> /private/var on macOS, so the replace() below works
        Path(tmp, "solution.py").write_text(code)
        Path(tmp, "test_solution.py").write_text(test_code)
        start = time.monotonic()
        proc = subprocess.Popen(
            [sys.executable, "-m", "unittest", "-q", "test_solution"],
            cwd=tmp,
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
            env={"PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"},
            start_new_session=True,   # own process group, so we can kill children too
            preexec_fn=_limits,
        )
        try:
            out, _ = proc.communicate(timeout=timeout)
            ran = re.search(r"^Ran (\d+) tests?", out, re.M)
            ok = (proc.returncode == 0 and ran and int(ran.group(1)) == expected
                  and re.search(r"^OK", out, re.M))
            status = "pass" if ok else "fail"
            if proc.returncode == 0 and not ok:
                out += f"\nREJECTED: exit code 0 but unittest did not report {expected} tests OK"
        except subprocess.TimeoutExpired:
            os.killpg(proc.pid, signal.SIGKILL)
            out, _ = proc.communicate()
            status = "timeout"
            out += f"\nTIMEOUT: tests did not finish in {timeout}s (infinite loop?)"
        return {
            "status": status,
            "seconds": round(time.monotonic() - start, 2),
            "output": out.replace(tmp, ".")[-MAX_OUTPUT:],
        }

Each line here is there because of a specific failure:

  • Two clocks. communicate(timeout=5) is wall time, and it catches time.sleep and blocked reads. RLIMIT_CPU is CPU time, and the kernel sends SIGXCPU when a busy loop uses it up, even if the parent is stuck. You want both.
  • Kill the group, not the process. The subprocess docs say a timeout does not kill the child for you. If the generated code forks, killing only the parent leaves orphans running. start_new_session=True puts the child in its own process group, and os.killpg takes the whole group down.
  • Exit code 0 is not proof. A module that calls os._exit(0) at import time ends the run before unittest prints anything, and the exit code is still 0. The runner counts Ran N tests and requires OK with the expected N.
  • A stripped environment. env= drops your API keys and tokens from the child's environment. That is the only real protection on this list, and it is a small one.
  • Clean, short output. Replacing the temp path with . and keeping the last 3,000 characters gives the model the traceback and assertion diff without paths or noise it might fixate on.

One caveat from the docs: preexec_fn is not safe when the parent has threads. This script is single-threaded. In a threaded server, set limits in a small wrapper script instead, or use a container.

Step 3: the model behind one method#

The loop only needs complete(messages) -> str. OllamaModel posts to Ollama's /api/chat endpoint with urllib, so there is no client library to install. ScriptedModel returns canned replies, which is how the failure demos later run without a GPU.

"""The code model sits behind one method: complete(messages) -> str."""
import json, re, urllib.request


class OllamaModel:
    """A local model through Ollama's /api/chat endpoint. No API key."""

    def __init__(self, model="qwen2.5:7b", temperature=0.7, seed=None,
                 url="http://localhost:11434/api/chat"):
        self.model, self.url = model, url
        self.options = {"temperature": temperature, "num_predict": 800}
        if seed is not None:
            self.options["seed"] = seed

    def complete(self, messages):
        body = json.dumps({"model": self.model, "messages": messages,
                           "stream": False, "options": self.options}).encode()
        req = urllib.request.Request(self.url, body, {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.load(r)["message"]["content"]


class ScriptedModel:
    """Returns canned replies in order. Used to show failure modes without a GPU."""

    def __init__(self, replies):
        self.replies = list(replies)

    def complete(self, messages):
        return self.replies.pop(0)


def extract_code(reply):
    """Take the first ```python block if there is one, else the whole reply."""
    m = re.search(r"```(?:python|py)?\s*\n(.*?)```", reply, re.S)
    return (m.group(1) if m else reply).strip() + "\n"

To use a hosted model, add a class with the same complete method that calls that provider's SDK. The coding agent post has a Claude adapter you can adapt. If you reach for LangChain instead, note that langchain_community.llms.Ollama is marked deprecated since 0.3.1 in favour of OllamaLLM from the langchain-ollama package (I checked the decorator in the langchain-community source, version 0.4.2).

A reasoning model can be a poor fit for this loop: a first run with qwen3:1.7b hit the 120-second request timeout on its very first call. qwen2.5:7b averaged about 20 seconds per call on a shared GPU, test runs included.

Asking for a fenced block and extracting it is more reliable than "return only code". Models add a sentence of prose often enough that a parser has to cope with it either way.

Step 4: the loop#

"""Generate, test, feed the failure back, retry."""
from model import extract_code
from sandbox import run_tests

SYSTEM = (
    "You write one Python module named solution.py. Reply with a single ```python code block "
    "and nothing else. Standard library only. No input(), no printing, no example usage."
)

FIX = (
    "Your code failed the tests. Test output:\n\n{output}\n\n"
    "Find the cause, then reply with the complete corrected solution.py in one ```python block."
)


def solve(task, model, max_attempts=3):
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": task["prompt"]},
    ]
    trace = []
    for attempt in range(1, max_attempts + 1):
        reply = model.complete(messages)
        code = extract_code(reply)
        result = run_tests(code, task["tests"])
        trace.append({"attempt": attempt, "code": code, **result})
        if result["status"] == "pass":
            break
        messages += [
            {"role": "assistant", "content": reply},
            {"role": "user", "content": FIX.format(output=result["output"])},
        ]
    return trace

The model sees the whole conversation on each retry: its own earlier code and every test report since. That costs tokens, but without it the model repeats mistakes it already made. The function returns the trace, not only the final code, because the trace is what you debug from.

A real retry trace#

version_cmp, seed 3, qwen2.5:7b. Attempt 1 compared part by part and then treated the longer version as bigger:

    # Check for remaining parts in either version string
    if len(a_parts) > len(b_parts):
        return 1

The runner sent this back (trimmed to the failing test):

FAIL: test_1 (test_solution.T.test_1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./test_solution.py", line 8, in test_1
    self.assertEqual(compare_versions('1.0', '1'), 0)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1 != 0

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1)

Attempt 2 padded both lists with zeros to the same length and passed all three visible tests, then both hidden ones. The model got a concrete assertion diff and made a targeted fix.

Seed 2 on the same task shows the other side. Attempt 1 crashed with TypeError: unsupported operand type(s) for +: 'map' and 'list'. Attempt 2 sent back the exact same code. Attempt 3 fixed the crash but reintroduced the "longer is bigger" bug and failed '1.0' vs '1'. Across all 18 runs, 3 retries were byte-for-byte copies of the previous attempt, each one a wasted call.

Step 5: measure 1 attempt against up to 3#

run_eval.py runs every task with seeds 1, 2 and 3, max_attempts=3, and records whether attempt 1 passed and whether the final attempt passed. The 1-attempt numbers come from attempt 1 of the same runs, so both columns share the same first draft. Then it re-runs the passing code against the hidden suite.

SEEDS = [1, 2, 3]
rows = []
for task in TASKS:
    for seed in SEEDS:
        trace = solve(task, OllamaModel(MODEL, seed=seed), max_attempts=3)
        first, last = trace[0], trace[-1]
        rows.append({
            "task": task["name"], "seed": seed, "attempts": len(trace),
            "statuses": [t["status"] for t in trace],
            "pass_1": first["status"] == "pass",
            "pass_3": last["status"] == "pass",
            "hidden_1": first["status"] == "pass" and run_tests(first["code"], task["hidden"])["status"] == "pass",
            "hidden_3": last["status"] == "pass" and run_tests(last["code"], task["hidden"])["status"] == "pass",
            "trace": trace,
        })

Output from python3 run_eval.py qwen2.5:7b:

parse_duration   seed=1 fail -> fail -> fail         hidden@3=False
parse_duration   seed=2 fail -> fail -> fail         hidden@3=False
parse_duration   seed=3 fail -> fail -> fail         hidden@3=False
merge_intervals  seed=1 pass                         hidden@3=False
merge_intervals  seed=2 pass                         hidden@3=False
merge_intervals  seed=3 pass                         hidden@3=False
rle              seed=1 pass                         hidden@3=True
rle              seed=2 pass                         hidden@3=True
rle              seed=3 pass                         hidden@3=True
wrap             seed=1 pass                         hidden@3=False
wrap             seed=2 fail -> fail -> fail         hidden@3=False
wrap             seed=3 fail -> fail -> fail         hidden@3=False
business_days    seed=1 pass                         hidden@3=True
business_days    seed=2 fail -> pass                 hidden@3=True
business_days    seed=3 pass                         hidden@3=True
version_cmp      seed=1 pass                         hidden@3=True
version_cmp      seed=2 fail -> fail -> fail         hidden@3=False
version_cmp      seed=3 fail -> pass                 hidden@3=True
pass_1    10/18 = 56%
pass_3    12/18 = 67%
hidden_1  6/18 = 33%
hidden_3  8/18 = 44%
model calls: 32

Per task:

Task Visible, 1 attempt Visible, up to 3 Hidden, up to 3 Model calls
parse_duration 0/3 0/3 0/3 9
merge_intervals 3/3 3/3 0/3 3
rle 3/3 3/3 3/3 3
wrap 1/3 1/3 0/3 7
business_days 2/3 3/3 3/3 4
version_cmp 1/3 2/3 2/3 6

What the numbers say:

  • Retries helped where the failure was local. Both rescues (business_days seed 2, version_cmp seed 3) came on the second attempt, and the fixed code also passed the hidden tests. In business_days the model dropped a broken week-arithmetic formula, which returned 10 instead of 5, for a plain day-by-day loop.
  • Retries did not help where the first idea was wrong. No parse_duration attempt passed. Each seed locked onto its own parsing approach (splitting on spaces, checking every character against the unit table, splitting off the last character) and raised ValueError on valid input such as '1h30m' or '45s' in all three attempts. Nine calls, zero passes, and in seeds 2 and 3 the error message did not change once. When a third attempt fails the same way as the first, a fourth will too.
  • Visible passes overstate quality. All three merge_intervals solutions passed the visible tests and broke the "do not modify the input" rule by calling pairs.sort() in place. The spec said it, the visible tests did not check it, and the model ignored it every time. The one wrap solution that passed visible tests failed hidden ones: it never filled a line to exactly width, so 'a b' at width 3 came out as ['a', 'b', 'c'].
  • Small samples move. An earlier run, identical except that the feedback text contained a mangled temp path, rescued version_cmp seed 2 and scored 13/18 visible. With 18 runs, one flip is 6 points. Report counts, not just percentages, and run more seeds before you believe a 10-point difference.
  • Cost. 32 model calls for 18 runs, against 18 with no retries. A 78% increase in calls bought 2 extra passes. The extra calls all went to runs that failed attempt 1, which is the right place, but 12 of the 14 extra calls landed on runs that never recovered.

That last point suggests a cheap stop rule: end the run early when the model resubmits identical code, or when the failing test names and messages match the previous attempt. On this run, that would have saved at least the 3 duplicate calls.

Step 6: failure modes, replayed with the stub#

demo_failures.py feeds the loop scripted replies so each failure is repeatable:

# 1. An infinite loop on the first try, a fix on the second.
hang = "```python\ndef compare_versions(a, b):\n    while True:\n        pass\n```"
for t in solve(version, ScriptedModel([hang, good])):
    print(t["attempt"], t["status"], t["seconds"], "s |", t["output"].strip().splitlines()[-1])

# 2. Gaming the tests: special-case the visible inputs.
gamed = """```python
def compare_versions(a, b):
    known = {('1.10.0', '1.9'): 1, ('1.0', '1'): 0, ('2.0.1', '2.1'): -1}
    return known.get((a, b), 0)
```"""
t = solve(version, ScriptedModel([gamed]), max_attempts=1)[-1]
print("gamed, visible:", t["status"], "| hidden:", run_tests(t["code"], version["hidden"])["status"])

# 3. Editing the test run itself: exit 0 before unittest reports.
exit_hack = "```python\nimport os\nos._exit(0)\n```"
t = solve(version, ScriptedModel([exit_hack]), max_attempts=1)[-1]
print("os._exit(0):", t["status"], "|", t["output"].strip())

# 4. What the child can still see.
peek = "```python\nimport os\nprint('home readable:', os.path.isdir(os.path.expanduser('~/.ssh')))\n```"
print(run_tests(extract_code(peek), "import solution")["output"].strip())

good is the zero-padding solution from the trace above. Output:

1 timeout 5.07 s | TIMEOUT: tests did not finish in 5s (infinite loop?)
2 pass 2.99 s | OK
gamed, visible: pass | hidden: fail
os._exit(0): fail | REJECTED: exit code 0 but unittest did not report 3 tests OK
----------------------------------------------------------------------
Ran 0 tests in 0.000s

NO TESTS RAN
home readable: True

The hang costs 5 seconds and comes back as a readable message the model can act on. The lookup table passes every visible test and fails the hidden ones, which is why the hidden suite exists. No real model in my 18 runs tried a lookup table on these tasks, but the risk grows when the visible tests are few and the model is told to make them pass at any cost. The os._exit(0) trick is caught only because the runner checks unittest's own summary. Before that check existed, the same script reported it as a pass.

The last line shows that code running under this runner can read your home directory, including ~/.ssh.

A subprocess is not a sandbox#

Everything in sandbox.py limits how long code runs and how much it writes. None of it limits what the code can reach. The child runs as your user, with your file permissions and your network. Generated code can read ~/.ssh, upload files, delete anything you can delete, or start a process that outlives the run. A with tempfile.TemporaryDirectory() working directory changes where relative paths point and nothing else. The resource limits are per process, and this runner sets no memory limit at all, so code that builds a huge list can still push your machine into swap.

For code from a model, the minimum is a disposable container with no network and no home directory mounted, for example docker run --rm --network none with the temp directory as the only volume (see Docker's none network driver). For hostile input, add a stronger boundary such as gVisor or a microVM. How to dockerize an AI agent covers the container side, and the coding agent design post covers OS sandboxes like Seatbelt and bubblewrap. Keep run_tests as the single function that executes code, and swap its body for the container call when you move off your laptop.

Where to take it next#

  • Hidden tests as the gate, visible tests as the hint. Send only visible failures back, but accept a solution only when the hidden suite also passes. Hold out a third set if you tune prompts against the hidden one.
  • A repeat guard. Stop when the code or the failure signature repeats. Here that would have saved 3 calls without losing a pass.
  • A bigger task set. Six tasks is a demo. The HumanEval paper reports pass@k and gives an unbiased way to estimate it from n samples per problem. Use that estimator and a few hundred problems before you compare models. Evaluating an AI agent in Python shows how to structure the eval code.
  • Reflection before rewrite. Reflexion and Self-Refine both have the model write a critique of its failure before the new attempt. That is a one-line change to FIX, and the eval above is how you would find out whether it helps on your tasks.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.