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


























