loop() helper runs a step for each item in a list, CSV, or text file — ideal for batch processing and data pipelines.
Quick Start
Choosing an Iteration Source
Pick the parameter that matches where your items live.API Reference
loop()
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
step | Any | required | Step to execute (function, Agent, Task) |
over | Optional[str] | None | Variable name containing list to iterate |
from_csv | Optional[str] | None | Path to CSV file |
from_file | Optional[str] | None | Path to text file |
var_name | str | "item" | Variable name for current item |
Context Variables
Inside the loop, these variables are available:| Variable | Type | Description |
|---|---|---|
item (or custom) | Any | Current item being processed |
loop_index | int | Current iteration index (0-based) |
Result Variables
After loop completion:| Variable | Type | Description |
|---|---|---|
loop_outputs | List[str] | All outputs from loop iterations |
Examples
Custom Variable Name
CSV with Headers
Givendata.csv:
With Agents
Chained Loops
Loop with Aggregation
Use Cases
| Use Case | Description |
|---|---|
| Batch Processing | Process files, records, or data items |
| Data Migration | Transform and migrate data row by row |
| Report Generation | Generate reports for each entity |
| Email Campaigns | Send personalized emails to list |
| API Calls | Call API for each item in list |
How It Works
| Phase | What happens |
|---|---|
| 1. Resolve | loop() reads the over variable (list, CSV, or text file) from ctx.variables |
| 2. Iterate | Handler is called once per item; ctx.variables["item"] holds the current value |
| 3. Collect | All StepResult objects are gathered; loop_index tracks the current position |
| 4. Return | AgentFlow returns after the last item completes |
Best Practices
Handle errors per item
Handle errors per item
Catch exceptions inside the loop body so one bad row does not stop the entire batch.
Log progress on large files
Log progress on large files
Enable verbose mode or custom logging when iterating thousands of records.
Chunk very large datasets
Chunk very large datasets
Split massive CSVs into batches to limit memory and simplify retries.
Clean up resources in finally blocks
Clean up resources in finally blocks
Close files and connections even when individual items fail.
Error Handling
Related
Workflow Patterns
Overview of routing, parallel, loop, and repeat patterns
Workflow Routing
Decision-based branching in workflows
Workflow Parallel
Run independent steps concurrently
Workflow Repeat
Repeat steps until a condition is met

