Home / Articles / Practical notes: Loop Engineering with Agents

This article is published in English.

Practical notes: Loop Engineering with Agents

Operable walkthrough of Practical notes: Loop Engineering with Agents: contracts, checks, and drop-in code slots for teams shipping this pattern.

2945 words

Use this as an operator-facing rebuild of the ideas in “Loop Engineering with Agents”: clear stages, ordered code slots, and recovery notes that survive a handoff. The Overview stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Table of Contents

For the Table of Contents stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.

1. The Anatomy of an Agentic Loop

For the 1 The Anatomy of stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.

2. When to Use Loop Engineering

For the 2 When to Use stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness. For the 2 When to Use stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

3. Common Types of Loops

When working through the 3 Common Types of stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

   +-----------+      +-----------+
-->| Generate  |----->|  Verify   |----- pass -----> [ done ]
   +-----------+      +-----+-----+
        ^                   |
        +------- fail ------+
   +-----------+      +-----------+
-->| Generate  |----->|  Score    |--- good enough --> [ done ]
   +-----------+      +-----+-----+
        ^                   |
        +-- improve --------+
            (use the score)
   +-----------+      +-----------+
-->|   Plan    |----->|  Execute  |-- all steps done --> [ done ]
   +-----------+      +-----+-----+
        ^                   |
        +-- replan ---------+
            (hit a surprise)
   +-----------+     +-----------+     +-----------+
-->|   Wait    |---->|   Check   |---->|    Act    |---+
   | (timer /  |     +-----------+     +-----------+   |
   |  trigger) |                                       |
   +-----------+ <-------------------------------------+
        (no fixed end — keeps watching over time)

4. How to Build a Loop

When working through the 4 How to Build stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

                    +------------------+
  START ----------> |     Research     | <-------------+
                    | (draft / revise) |               |
                    +--------+---------+               |
                             |                         |
                             v                         | needs work
                    +------------------+               | (+ feedback)
                    |      Verify      |               |
                    |  (check claims)  |               |
                    +--------+---------+               |
                             |                         |
                             v                         |
                       +-----------+   needs work      |
                       |  Decide   |-------------------+
                       | (router)  |
                       +-----+-----+
                             | verified / out of tries
                             v
                          [ END ]
pip install langgraph==1.2.6 langchain-openai==1.3.3 pydantic==2.13.4
export OPENAI_API_KEY="your-key-here"
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field

# A model client on OpenAI's Responses API, with the built-in web-search tool
# bound on — so the model can search the web itself, no extra package needed.
# "gpt-5" is a reasoning model; swap it for any current model you have access to.
llm = ChatOpenAI(model="gpt-5", use_responses_api=True)
searcher = llm.bind_tools([{"type": "web_search"}])

MAX_ITERATIONS = 3         # a stop rule, decided up front

# STATE — the shared memory passed between every node
class ResearchState(TypedDict):
    question: str          # what we're answering
    draft: str             # the current best answer
    verdict: str           # "verified" or "needs_work"
    feedback: str          # what the verifier said to fix
    iterations: int        # how many times we've looped

# The verifier returns a typed result, so the router gets a clean
# "verified" / "needs_work" to branch on instead of parsing prose.
class Verdict(BaseModel):
    status: str = Field(description='"verified" or "needs_work"')
    feedback: str = Field(description="claims lacking support, if any")

# NODE 1 — the maker: search the web, then draft (or revise) the answer.
def research(state: ResearchState) -> dict:
    prompt = "Search the web, then answer the question. Back every claim with a source.\n"
    if state.get("feedback"):
        prompt += f"A reviewer flagged these gaps — fix them:\n{state['feedback']}\n"
    prompt += f"\nQuestion: {state['question']}"
    draft = searcher.invoke(prompt).text
    return {"draft": draft, "iterations": state["iterations"] + 1}

# NODE 2 — the checker: search for evidence, then critique the draft.
def verify(state: ResearchState) -> dict:
    evidence = searcher.invoke(
        f"Search the web for evidence to fact-check claims about: {state['question']}"
    ).text
    checker = llm.with_structured_output(Verdict)
    result = checker.invoke(
        "You are a fact-checker. Using the evidence below, reply 'verified' "
        "only if every claim in the answer is supported; otherwise 'needs_work' "
        "and list the unsupported claims as feedback.\n\n"
        f"Evidence:\n{evidence}\n\nAnswer:\n{state['draft']}"
    )
    return {"verdict": result.status, "feedback": result.feedback}

# ROUTER — the heart of the loop. Reads the verdict, picks the next step.
def decide(state: ResearchState) -> Literal["research", "__end__"]:
    if state["verdict"] == "verified":
        return "__end__"                      # success: goal met
    if state["iterations"] >= MAX_ITERATIONS:
        return "__end__"                      # surrender: out of tries
    return "research"                         # loop back and fix the gaps

# WIRE IT UP
graph = StateGraph(ResearchState)
graph.add_node("research", research)
graph.add_node("verify", verify)

graph.add_edge(START, "research")            # trigger
graph.add_edge("research", "verify")         # always verify a fresh draft
graph.add_conditional_edges("verify", decide, {
    "research": "research",                   # the backward arrow = the loop
    "__end__": END,
})

agent = graph.compile()

result = agent.invoke({
    "question": "What were the main causes of the 2008 financial crisis?",
    "draft": "", "verdict": "", "feedback": "", "iterations": 0,
})
print(result["draft"])

5. Failure Modes & Guardrails

When working through the 5 Failure Modes Guardrails stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node. When working through the 5 Failure Modes Guardrails stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

6. When NOT to Use Loop Engineering

The 6 When NOT to stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts.

Conclusion

The Conclusion stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts.

References

The References stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts. The References stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Operational checklist

When working through the Operational checklist stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest.

Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

Pin dependency versions and record the image digest that ran the demo. Reproducibility beats tribal knowledge.

Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.

Batch note for 5e9b984e8d8a: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.

The hardening note 0 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 0/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 1 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 1/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 2 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 2/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 3 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 3/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 4 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 4/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 5 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 5/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 6 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 6/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 7 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 7/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 8 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 8/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 9 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 9/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 10 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 10/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 11 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 11/884: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.