Loops
Loops allow a workflow to repeat a step or group of steps until a condition is met. They are useful for iterative processing but must have a clear exit condition to avoid infinite loops.
6 min•By Priygop Team•Updated 2026
Safe Loop Design
- Always define a maximum iteration count — never loop without a stop condition
- Loop exit conditions: goal achieved, max iterations reached, user input received, time limit exceeded
- Track iteration count in state and check it at the start of each iteration
- Log every iteration with its input and output for debugging
- Prefer bounded loops (process each item in a list) over open-ended loops
Loop Node Pattern
Loop Node Pattern
# Workflow loop: retry a step until success or max attempts
def retry_loop_node(state: dict, max_attempts: int = 3) -> str:
"""
Try an operation up to max_attempts times.
Exits on success or when attempts are exhausted.
"""
attempt = state["data"].get("attempt", 0) + 1
state["data"]["attempt"] = attempt
print(f" Attempt {attempt}/{max_attempts}")
# Simulate a flaky operation (fails first 2 times)
if attempt < 2:
state["data"]["last_error"] = "Temporary failure"
return "retry" if attempt < max_attempts else "exhausted"
# Success on attempt 2+
state["data"]["result"] = f"Succeeded on attempt {attempt}"
return "success"
# Process all items in a list with a loop
def process_item_node(state: dict) -> str:
"""Process the next item in the input list."""
items = state["input"].get("items", [])
processed = state["data"].get("processed", [])
index = len(processed)
if index >= len(items):
return "all_done" # Exit the loop
item = items[index]
processed.append(f"processed_{item}")
state["data"]["processed"] = processed
print(f" Processed item {index+1}/{len(items)}: {item}")
return "next" # Loop back for next item
state = {"input": {"items": ["A", "B", "C"]}, "data": {}}
for _ in range(5): # Run up to 5 iterations
condition = process_item_node(state)
if condition == "all_done":
break
print("All processed:", state["data"]["processed"])Key Takeaways
- Loops allow a workflow to repeat a step or group of steps until a condition is met.
- Always define a maximum iteration count — never loop without a stop condition
- Loop exit conditions: goal achieved, max iterations reached, user input received, time limit exceeded
- Track iteration count in state and check it at the start of each iteration