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 repeatedly runs one or more agents until a stop condition is met or an iteration limit is reached. It is useful when output can be evaluated and improved through repeated passes, such as writing and reviewing. section 9.3 section 9.3.4

The developer defines the agent order. An outer loop controls iterations, while an inner loop runs the agents sequentially. Only the first agent in the first iteration receives the original user input; subsequent executions inherit context. After each iteration, a stop condition examines the current result and iteration count. A maximum iteration count prevents the workflow from running indefinitely, but it can also end the loop before the quality target is reached. section 9.3.4

Writer and reviewer

A writer drafts marketing copy and a reviewer scores it for clarity, persuasiveness, and grammar. If the score is 60, the workflow continues so the writer can improve the draft using feedback. It stops when the score reaches 80 or the iteration limit is reached. The threshold is a project-specific quality bar. 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")

Inspect the writer, structured review, score-based stop condition, and five-iteration limit. section 9.3.4

Stop conditions can also check for a keyword or combine a minimum iteration count with an output-length requirement. Choose a condition that reflects the result you need, and retain a maximum iteration limit as a safeguard. section 9.3.4

A loop can be one stage in a larger workflow. For example, a sequential pipeline can run research, parallel analysis, a writer-reviewer loop, and final editing. The loop shares the same run interface as an agent, allowing it to be nested in the pipeline. section 9.3.5

A developer-defined loop differs from an LLM-directed agent loop. In the former, code sets the order and stop condition; in the latter, the model assesses state, chooses actions and tools, observes results, and decides when to stop. section 1.3.2 section 9.3.4

How Build an AI Agent (From Scratch) covers it

How deep it goes
Explains nested execution, context passing, stop-condition checks, and iteration limits with a concrete implementation.
Examples
Uses scored marketing-copy reviews, keyword checks, and minimum-iteration content-length checks.
What you can do after
Build it from scratch by defining an agent sequence, a stop condition, and a maximum iteration count.
How it connects
Connects loop workflows to sequential workflows, parallel workflows, agent composition, and LLM-directed tool use.

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.