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


























