Skip to main content
Run steps repeatedly until an end condition is met or max iterations reached.
from definable.agent import Agent
from definable.agent.workflow import Workflow, Loop, Step

generator = Agent(model="gpt-4o", instructions="Generate content based on feedback.")
evaluator = Agent(model="gpt-4o", instructions="Evaluate quality. Say APPROVED if it meets standards.")

workflow = Workflow(
    name="refinement",
    steps=[
        Loop(
            name="improve",
            steps=[
                Step(name="generate", agent=generator),
                Step(name="evaluate", agent=evaluator),
            ],
            end_condition=lambda outputs: any(
                "APPROVED" in (o.content or "") for o in outputs
            ),
            max_iterations=5,
        ),
    ],
)

How It Works

  1. generate and evaluate steps execute sequentially.
  2. After each iteration, end_condition receives all step outputs from that iteration.
  3. If it returns True, the loop stops.
  4. If max_iterations is reached, the loop stops regardless.

Parameters

end_condition
Callable[[List[StepOutput]], bool]
Called after each iteration. Return True to stop. Supports sync and async.
max_iterations
int
default:"3"
Maximum iterations before stopping.

Tracking Iterations

Use the LoopIterationEvent to monitor progress:
from definable.agent.workflow import LoopIterationEvent

workflow.events.on(LoopIterationEvent, lambda e: print(f"Iteration {e.iteration}/{e.max_iterations}"))