Loops and graphs

A loop tries one change at a time against one check. A graph wires loops together. Some tasks run side by side, some create children of their own, some wait on another, and only the one that fails goes back. Make one change Check the score Try 1 Keep it Kept 0 of 0 Split the job Task 1 Task 2 2a 2b Task 3 Check Done Each task is its own loop Some run side by side Some create children Some wait on another Only what fails goes back

One change, one check, then keep it or put it back.

The pieces run side by side, and only what fails goes back.

Why I work this way

This is how I run AI agents at work and on this site. When a single AI session works on a big project for too long, it starts missing rules we agreed on earlier and approving its own shortcuts.

Loops and graphs keep that from happening. A loop repeats one focused job with an automated check each time, while a graph maps out which steps can run in parallel and which steps have to wait on others.

Start with one loop

The clearest loop to study is Andrej Karpathy's autoresearch. An agent edits one training script, runs training for five minutes, checks whether the validation score improved, and either keeps the edit or reverts it. At five minutes per attempt, one machine runs roughly 100 experiments overnight while you sleep.

Four rules make that loop reliable:

  • One fixed score: Progress is measured by a single metric, and the scoring script is off limits to the agent.
  • Automatic rollback: Every attempt can be undone; if the score stays flat or gets worse, the code resets immediately.
  • Same budget per try: Every experiment gets the exact same five minutes so results compare fairly.
  • One editable file: Limiting the agent to a single file keeps every change small enough to review quickly.
One loopA loop where each change is run and scored, then kept if the score got better or put back if it didn't, while the scoring code never changes.BetterSame or worseNext tryNext tryMake one changeRun itCheck the scoreKeep itPut it backThe score code(don't touch)Same budgetevery try
One change, one check, then keep it or put it back.

Write the goal down before you run anything

In autoresearch, you don't edit the Python code yourself; you write program.md, the instructions file the agent reads at startup. It specifies what the agent may change, what is off limits, how the score works, the five-minute time limit, how to log every try, and to keep running without stopping to ask permission.

My goal briefs for this site used those same parts: each one named the job, set a clear target, defined how a reviewer would check the output, and listed what not to touch. Write down what done looks like before starting a loop using a template like this (including one section autoresearch leaves out on purpose: when to stop and ask me).

A goal file

# Goal: ____ (one line: what you want to get better)

## What you can change
- ____ (the one file or setting the loop may edit)

## What you can't touch
- ____ (the scoring code, the test data, anything else that's off limits)

## How we measure it
- Score: ____ (the one number, and whether lower or higher is better)
- Command: ____ (how to run one try and print the score)

## Budget
- Each try: ____ (minutes)
- Whole run: ____ (tries, minutes or dollars, whichever comes first)

## Keep or put it back
- Keep a change only if the score gets better.
- If it's the same or worse, put it back.
- Write every try down: what changed, the score, kept or put back.

## When to stop
- ____ (the budget runs out, or the score hits ____)

## When to ask me
- ____ (anything that needs a file outside "What you can change", or costs more than ____)

Try one loop yourself

Here is a small loop you can run right now with standard Python and nothing to install. It searches for three target numbers against a fixed score function, with one marked comment showing where an LLM call would go. Because it uses a fixed random seed, running it drops the error from 14.000 to 0.011 in 71 tries every time, keeping 15 changes and putting 56 back.

The loop

"""One loop: make one change, check it, keep it or put it back."""
import random

random.seed(7)
TARGET = [3.0, -1.0, 2.0]          # the answer the loop doesn't know


def score(guess):
    # The check. Lower is better. It never changes during the run.
    return sum((g - t) ** 2 for g, t in zip(guess, TARGET))


def propose_change(guess, history):
    # A model call would go here: show it the guess and the recent
    # history, and ask for one small change. This stand-in nudges one number.
    i = random.randrange(len(guess))
    new = list(guess)
    new[i] += random.choice([-1, 1]) * random.uniform(0.1, 1.0)
    return new, "nudge number %d" % (i + 1)


best = [0.0, 0.0, 0.0]
best_score = score(best)
history = [("start", round(best_score, 3), "keep")]
for attempt in range(1, 201):                      # the budget: 200 tries
    guess, what = propose_change(best, history[-5:])
    s = score(guess)
    kept = s < best_score                          # keep only if it got better
    if kept:
        best, best_score = guess, s                # otherwise the old one stays
    history.append((what, round(s, 3), "keep" if kept else "put back"))
    if best_score < 0.05:                          # the stop rule
        break

kept_count = sum(1 for h in history[1:] if h[2] == "keep")
print("tries: %d, kept: %d, put back: %d" % (len(history) - 1, kept_count, len(history) - 1 - kept_count))
print("score went from %.3f to %.3f" % (history[0][1], best_score))
print("best guess:", [round(x, 2) for x in best], "target:", TARGET)

When one loop isn't enough

A single loop plans, edits, checks the score, and tries again inside one long conversation. The downside is that every failed attempt stays in that same transcript, which makes it easy for the model to repeat ideas that already failed.

A graph splits the process into explicit steps. Each node handles one job (a specialized agent, a tool call, a routing rule, or a merge check) and reads and writes shared state rather than relying on chat history. Anthropic's Building effective agents guide draws a clear distinction here between workflows, where code defines the order of steps, and agents, which choose their own actions inside a step.

Graphs still use loops, except each retry arrow is scoped to send back only the specific step that failed. Independent steps run in parallel, and automated checks (gates) stop broken work from moving forward. That is how we built this site: parallel sessions built separate parts while one integration session merged everything and sent only failed pieces back.

A small graph with a checkA router sends a request to three pieces that run at the same time, one check looks at all three, and only the piece that failed is sent back to run again.Which pieces?Side by sideDraft thewordsBuild thepageShoot theframesCheckPassesDoneToo dark:send backjust this
The pieces run side by side, and only what fails goes back.

Here is a small graph you can run in plain Python. A router picks which pieces a request needs, independent pieces run side by side, one check inspects all of them, and retries run only what failed. Writing a new post runs three pieces at once, catches dark frames on round one, re-runs only the frames on round two, and passes; fixing a typo runs only the words; and if the retry limit runs out, it stops and asks me.

A graph with a router, a check and a retry

"""A small graph: a router picks the pieces, the pieces run side by side,
a check looks at all of them, and only what failed goes back."""
from concurrent.futures import ThreadPoolExecutor
from graphlib import TopologicalSorter

attempts = {}


def route(request):
    # A decision point. A model call could make this choice; plain rules work here.
    if request == "fix a typo":
        return ["draft the words"]
    return ["draft the words", "build the page", "shoot the frames"]


def work(piece):
    # A model call (or a whole session) would go here. This stand-in makes
    # the frames come out too dark the first time.
    attempts[piece] = attempts.get(piece, 0) + 1
    if piece == "shoot the frames" and attempts[piece] == 1:
        return piece, False, "too dark"
    return piece, True, ""


def run(request, max_rounds=2):
    attempts.clear()
    pieces = route(request)
    waits_on = {piece: ["route"] for piece in pieces}    # every piece waits on the router
    waits_on["check"] = pieces                          # the check waits on all of them
    graph, steps = TopologicalSorter(waits_on), []
    graph.prepare()
    while graph.is_active():                            # group what can run at the same time
        ready = graph.get_ready()
        steps.append(" + ".join(ready))
        graph.done(*ready)
    print("%s: %s" % (request, " -> ".join(steps)))
    results, todo = {}, pieces
    for round_number in range(1, max_rounds + 1):
        with ThreadPoolExecutor() as pool:              # the pieces run side by side
            for piece, ok, why in pool.map(work, todo):
                results[piece] = (ok, why)
        failed = [p for p, (ok, why) in results.items() if not ok]
        print("  round %d: ran %s; failed: %s" % (round_number, ", ".join(todo),
              ", ".join("%s (%s)" % (p, results[p][1]) for p in failed) or "nothing"))
        if not failed:
            print("  passed the check after %d round(s)" % round_number)
            return
        todo = failed                                   # the retry edge: only what failed goes back
    print("  still failing after %d round(s), so it stops and asks me" % max_rounds)


run("write a new post")
run("fix a typo")
run("write a new post", max_rounds=1)

Keep two graphs apart

On a real project, keep your change history separate from your verified facts. One graph tracks the work: what changed and which earlier version it was built on. For example, autoresearch saves every winning change as a Git commit and logs every attempt in a results file marked keep, discard, or crash.

The second graph tracks what is true and where each fact came from. In Anthropic's knowledge graph cookbook, every relationship stores its source document so you can verify where any claim originated. On this site, my dated file of exact words served as that primary source for every session. In the example below, any finding without a source is rejected, and you can trace any change back to where it started.

Two graphs, kept apart

"""Two graphs, kept apart. The work graph says what changed and from what.
The knowledge graph says what's true and where it came from."""

work = {}         # change -> the change it was built on
knowledge = []    # (thing, how it relates, other thing, source)


def record_change(change, built_on=None):
    work[change] = built_on


def add_finding(thing, relation, other, source=None):
    # A finding without a source is refused. That's the whole rule.
    if not source:
        print("REFUSED (no source):", thing, relation, other)
        return
    knowledge.append((thing, relation, other, source))
    print("added:", thing, relation, other, "(source: %s)" % source)


def path_to(change):
    # Walk back through what each change was built on.
    steps = []
    while change:
        steps.append(change)
        change = work[change]
    return " <- ".join(steps)


record_change("first room")
record_change("darker blue rug", built_on="first room")
record_change("warmer lamps", built_on="first room")
record_change("rug and lamps together", built_on="darker blue rug")

add_finding("first screen", "must stay under", "450 KB", source="the goal for the site")
add_finding("rug", "looks faded at", "dusk", source="review of frame 12")
add_finding("lamps", "should be", "cooler")

print("how we got here:", path_to("rug and lamps together"))
print("findings kept: %d, every one with a source" % len(knowledge))
Two graphs, kept apartTwo separate maps: one shows each change and what it was built on, the other shows facts joined by labeled lines, each tagged with its source, and one line with no source crossed out.The workrug and lamps togetherdarker blue rugfirst roomwarmer lampsWhat's truemust stay underfirst screen450 KBsource: the goal for the sitelooks faded atrugdusksource: review of frame 12should belampscoolerno source: refused
What changed on one side, what's true on the other.

When to use which

Start with the simplest option that solves the problem, which often means plain code and no AI agent at all. Use a fixed sequence of steps when the task breaks down the same way every time. Use a loop with an automated check when you have clear grading criteria and extra passes measurably improve the result. Always set a hard limit on tries, time, or cost so an agent knows when to stop.

How I built this site with it

I steered almost the entire build of this site over a few days from the Claude app on my iPhone. One master Python script builds the 3D room from scratch by calling nine modular scripts, so separate builders could work on separate parts of the room in parallel. Builders never reviewed their own output; separate read-only sessions checked every frame without permission to edit files.

You can read more in How I work and in my note on how I organized the agents that built this site.

Further reading