# Loops and graphs

```text
LOOP: Make one change -> Check the score -> Keep it, or Put it back
  Try 1, Try 2, Try 3, Try 4, Try 5: Kept 2 of 5
  One change, one check, then keep it or put it back.

GRAPH: Split the job -> Task 1 and Task 2
  Task 2 creates 2a and 2b, and waits for them
  Task 3 waits on Task 1 and Task 2 -> Check
  Task 3 fails the check -> back to 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.
  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.

```text
Make one change -> Run it -> Check the score
   Better?         yes -> keep it        -> back to the top
                   no  -> put it back    -> back to the top
The score code never changes. Every try gets the same budget.
```

## 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**

```markdown
# 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**

```python
"""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.

```text
Which pieces?
  -> Draft the words  -+
  -> Build the page   -+-> Check -> Done
  -> Shoot the frames -+     |
          ^                  |
          +-- too dark: send back just this one
The three pieces run side by side. 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**

```python
"""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**

```python
"""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))
```

```text
The work (what changed, from what)
  first room -> darker blue rug -> rug and lamps together
  first room -> warmer lamps (stopped)

What's true (and where it came from)
  first screen -> must stay under -> 450 KB   [source: the goal for the site]
  rug -> looks faded at -> dusk               [source: review of frame 12]
  lamps -> should be -> cooler                [no source: refused]
```

## 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](/about/#how) and in [my note on how I organized the agents that built this site](/notes/the-lead-the-desk-and-the-judges/).

## Further reading

- [autoresearch (README)](https://github.com/karpathy/autoresearch), Andrej Karpathy. A small, practical optimization loop: one editable file, one fixed score, and a five-minute budget per run.
- [autoresearch (program.md)](https://github.com/karpathy/autoresearch/blob/master/program.md), Andrej Karpathy. The plain-text instructions file that drives that loop, useful to read before writing your own goal file.
- [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents), Erik Schluntz and Barry Zhang, Anthropic Engineering. The core patterns (chains, routing, parallel steps, and worker-checker loops) and when each one makes sense.
- [Knowledge Graph Construction with Claude](https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/knowledge_graph/guide.ipynb), Anthropic claude-cookbooks. How to build a graph of facts where every edge stores its source document, plus how to score it against a reference set.
- [Loop Engineering vs. Graph Engineering: The Architecture Shift Quietly Reshaping AI Agents](https://medium.com/@neuraldev/loop-engineering-vs-graph-engineering-the-architecture-shift-quietly-reshaping-ai-agents-c83488435d23), Uday Sharma. A clear comparison of single-context loops versus multi-step graphs with routing and targeted retries.
- [Prompts. Then Loops. Now Graphs. The Engineering Progression Every AI Builder Needs to Understand](https://medium.com/the-programmer/andrej-karpathy-built-a-loop-that-ran-700-experiments-e98949aedb17), Pramod Chandrayan. An overview of moving from single prompts to bounded loops and stateful graphs (Medium member article).
