Loop or graph: which should you build your AI agent on?
Loop or graph: which should you build your AI agent on?
You have a task you want an agent to handle. Do you give it tools and let it loop until it is done, or do you draw the steps as a graph and let the model fill in only the parts that need judgment? The loop engineering and graph engineering posts in this series explain each idea. This one is about choosing, with a small runnable example of each.
Both examples are plain Python 3 with no framework and no API key. The "model" is a stub function that returns canned answers, so you can see the control flow without paying for tokens. I ran both on Python 3.12 and the outputs below are copied from that run. To use a real model, replace the stub with a call to any chat API or a local model.
The one question that decides it
Can you draw the steps before the task starts?
- Yes: a graph. You know the shape (classify, then check, then reply, maybe escalate). Code should route the work and the model should only make the calls that need judgment.
- No: a loop. The next step depends on what the agent just found (debugging, research, exploring an unfamiliar codebase). Give it tools, a way to check its work and a budget.
This is the line LangChain draws in its post on three years of LangGraph: graphs for predictable structure such as classify-then-route or approval before an external action, and an agent loop for open-ended work such as deep research, which they moved off a graph and onto a looping agent.
Animation: the same budget spent two ways: a loop that circles a goal until a check passes, and a graph that walks fixed nodes with one conditional branch.
Example 1: an engineered loop
The task: produce an add function that passes three tests. The stub model guesses wrong twice, then right. What makes it loop engineering rather than a bare loop is the four parts around the model call: a deterministic verifier, state saved to a file, a budget and a clear exit.
python"""A minimal engineered loop: a stub "model" proposes a fix, a deterministic verifier checks it, state lives in a file, and the loop stops on success or budget. Pure Python, no API key. The stub stands in for an LLM call.""" import json, pathlib STATE = pathlib.Path("loop_state.json") # memory outside the conversation MAX_TRIES = 5 # budget: hard stop TESTS = [((2, 3), 5), ((-1, 1), 0), ((0, 0), 0)] # set point: all pass def stub_model(attempt, last_error): """Pretend LLM: returns candidate code. Gets better when shown the error.""" candidates = [ "def add(a, b): return a - b", # wrong "def add(a, b): return a * b", # still wrong "def add(a, b): return a + b", # right ] return candidates[min(attempt, len(candidates) - 1)] def verify(code): """Sensor: deterministic check, no model involved.""" env = {} exec(code, env) fails = [(args, want, env["add"](*args)) for args, want in TESTS if env["add"](*args) != want] return fails def run(): state = json.loads(STATE.read_text()) if STATE.exists() else {"attempt": 0, "log": []} last_error = None while state["attempt"] < MAX_TRIES: code = stub_model(state["attempt"], last_error) fails = verify(code) state["attempt"] += 1 state["log"].append({"try": state["attempt"], "code": code, "failures": len(fails)}) STATE.write_text(json.dumps(state, indent=1)) print(f"try {state['attempt']}: {code!r} -> {len(fails)} failing test(s)") if not fails: print("stop: verifier passed") return code last_error = fails[0] print("stop: budget spent, escalate to a human") if __name__ == "__main__": STATE.unlink(missing_ok=True) run()
Output:
texttry 1: 'def add(a, b): return a - b' -> 2 failing test(s) try 2: 'def add(a, b): return a * b' -> 2 failing test(s) try 3: 'def add(a, b): return a + b' -> 0 failing test(s) stop: verifier passed
Two details are worth copying into real code. The verifier is plain code, not another model call, which matches Kyle Mistele's advice in his AI Engineer talk on loops that you should not send an agent to do deterministic code's job. And the state file means a crashed or rescheduled run can pick up where it left off, because the conversation is not where progress lives.
Notice also what the loop does not know: it has no idea how many tries it will need or what the fixes will look like. That uncertainty is exactly why a loop fits.
Example 2: an engineered graph
The task: handle a customer support ticket. The shape is known in advance. Classify the ticket. For a refund, check the policy in code. If allowed, draft a reply and lint it, redrafting at most three times. Anything else goes to a human.
python"""A minimal engineered graph: nodes do work, edges route a shared state dict. One conditional edge, one bounded retry cycle, one human-escalation exit. Pure Python, no framework, no API key. stub_llm stands in for a model call.""" def stub_llm(prompt): """Pretend LLM. First draft is too long; second draft is fine.""" if prompt.startswith("classify"): return "refund" if "refund" in prompt else "question" if prompt.startswith("draft"): return "Sure! " * 30 if "attempt 1" in prompt else "Your refund of $40 is approved." return "" # ---- nodes: each takes state, returns updated state ---- def classify(s): s["kind"] = stub_llm(f"classify: {s['ticket']}"); return s def check_policy(s): # deterministic code, no model s["allowed"] = s["amount"] <= 50; return s def draft_reply(s): s["attempts"] += 1 s["reply"] = stub_llm(f"draft attempt {s['attempts']}: {s['ticket']}"); return s def lint_reply(s): # deterministic check s["ok"] = len(s["reply"]) <= 80; return s def escalate(s): s["reply"] = "Sent to a human reviewer."; return s def answer_question(s): s["reply"] = "Here is how to reset your password."; return s NODES = {f.__name__: f for f in [classify, check_policy, draft_reply, lint_reply, escalate, answer_question]} # ---- edges: fixed or conditional, decided by code ---- def next_node(name, s): if name == "classify": return "check_policy" if s["kind"] == "refund" else "answer_question" if name == "check_policy": return "draft_reply" if s["allowed"] else "escalate" if name == "draft_reply": return "lint_reply" if name == "lint_reply": if s["ok"]: return "END" return "draft_reply" if s["attempts"] < 3 else "escalate" # bounded cycle return "END" def run(ticket, amount): s = {"ticket": ticket, "amount": amount, "attempts": 0} node, path = "classify", [] while node != "END": path.append(node) s = NODES[node](s) node = next_node(node, s) print(" -> ".join(path)) print("reply:", s["reply"][:60]) if __name__ == "__main__": run("I want a refund for order 1182", 40) print() run("I want a refund for order 1183", 400) print() run("How do I reset my password?", 0)
Output:
textclassify -> check_policy -> draft_reply -> lint_reply -> draft_reply -> lint_reply reply: Your refund of $40 is approved. classify -> check_policy -> escalate reply: Sent to a human reviewer. classify -> answer_question reply: Here is how to reset your password.
The printed path is the payoff. Every run tells you exactly which steps happened, and the model could never skip the policy check or approve a $400 refund, because that branch is decided by code. This is the predictability and auditability Zachary Blumenfeld describes in his AI Engineer talk on graph engineering, where two free-running agent runs of the same task took paths of different lengths.
Notice too that the graph has a cycle (draft, lint, draft again). As LangChain puts it, agent graphs are usually not DAGs, and loops are simple graphs.
Side by side
| Question | Loop | Graph |
|---|---|---|
| Who picks the next step? | The model | Your code, along edges you drew |
| Best when | The path depends on what the agent finds | The steps are known in advance |
| Typical tasks | Debugging, research, migrations driven by a check | Triage, approvals, form-like workflows |
| How it stops | A verifier passes, or the budget runs out | It reaches an end node |
| How you debug it | Read the run log and state file | Read the path each run took |
| Main risk | Burns tokens, repeats bad habits at scale | Breaks on cases nobody drew |
You will usually want both
Real systems mix them. LangChain's 2026 update is that a graph node can now be a whole agent with its own loop. Mistele's migration loop is, in practice, a small graph run on a schedule: sensor, then controller, then actuator, then a gate that skips the run if the last pull request is still open. A good default:
- Draw the parts you understand as a graph, with deterministic checks on the edges.
- Put a looping agent inside the one or two nodes that need open-ended work.
- Give every loop a budget, and every graph an exit to a human.
To build the real versions with an API, start with the agent loop lesson and the ReAct vs plan-and-execute lesson in the Build an AI Agent in Python course.
Sources
- Sydney Runkle and Harrison Chase, "3 Years of Graph Engineering with LangGraph", LangChain, July 2026: https://www.langchain.com/blog/3-years-of-graph-engineering-with-langgraph
- Kyle Mistele (HumanLayer), "Loop Engineering from First Principles", AI Engineer, July 2026. Video: https://www.youtube.com/watch?v=xIt_mTQp6mY
- Zachary Blumenfeld (Neo4j), "Make Your AI Agents Predictable With Graph Engineering", AI Engineer, November 2026. Video: https://www.youtube.com/watch?v=g_NgCLTibiM
- Addy Osmani, "Practical Loop Engineering", August 2026: https://addyosmani.com/blog/practical-loop-engineering/
