liveBook · Manning

Loop

As explained in Build an AI Agent (From Scratch)

A loop workflow repeatedly runs one or more agents across iterations until a stopping condition is met or an iteration limit is reached.

A loop workflow runs a fixed sequence of agents repeatedly until a stop condition is met or an iteration limit is reached. It suits work that can improve through repeated evaluation, such as drafting and reviewing writing or generating code and running tests. Unlike an LLM-directed agent loop, the developer defines which agents run and in what order; the stop condition decides when that sequence ends. section 9.3 section 9.3.4 section 1.3.2

The implementation has two levels of control:

  • An outer loop counts iterations, bounded by max_iterations; an inner loop runs the agents in order on each iteration. section 9.3.4
  • Only the first agent on the first iteration receives user_input. Later executions inherit the context, allowing revisions to build on earlier results. section 9.3.4
  • After each iteration, stop_condition receives the current result and iteration count. It returns whether to terminate; max_iterations prevents an unbounded run. section 9.3.4

Draft, review, revise

A writer drafts marketing copy, then a reviewer returns a score and feedback. A score of 60 triggers another pass; a score of at least 80 ends the workflow. The threshold is a project-specific quality bar, not a guarantee of quality. Other stop conditions can check for an approval keyword or require both a minimum number of iterations and sufficient output length. section 9.3.4

from pydantic import BaseModel

class Review(BaseModel):
    content: str
    score: int  # 0-100
    feedback: str

writer = Agent(
    model=model,
    name="writer",
    instructions="Write content or improve it based on feedback."
)
reviewer = Agent(
    model=model,
    name="reviewer",
    instructions="Evaluate the writing and provide a score (0-100) with feedback.",
    output_type=Review
)

def quality_reached(result: AgentResult, iteration: int) -> bool:
    """Stop if score is 80 or higher"""
    if isinstance(result.output, Review):
        return result.output.score >= 80
    return False

workflow = LoopWorkflow(
    agents=[writer, reviewer],
    stop_condition=quality_reached,
    max_iterations=5,
)
result = await workflow.run("Write marketing copy")

The Python example defines a structured Review result, checks its score in quality_reached, and runs writer and reviewer with a five-iteration limit. section 9.3.4

A loop workflow can also be one stage of a larger pipeline. Because workflows share the Agent run() interface, a sequential pipeline can place research and parallel analysis before a write–review loop, then pass its result to an editor. This keeps the overall order explicit while allowing one stage to iterate. section 9.3.5

How Build an AI Agent (From Scratch) covers it

How deep it goes
Implements nested iteration, context propagation, a result-based stop condition, and an iteration cap.
Examples
Demonstrates scored writing review, keyword and length checks, and a write–review stage inside a larger pipeline.
What it assumes
Assumes familiarity with agents, results, execution context, and Python callables; shows how those pieces form a loop.
What you can do after
Build it from scratch with ordered agents, a stop-condition callback, and a maximum iteration count.
How it connects
Connects stop conditions and execution context to sequential workflows, parallel workflows, and LLM-directed agent loops.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build an AI Agent (From Scratch). The section links point to the parts of the book it draws on.