Overview
TheAgentRearrange class enables complex workflows where multiple agents can work sequentially or concurrently based on a defined flow pattern. It supports both sequential execution (using ->) and concurrent execution (using ,) within the same workflow, providing maximum flexibility for agent orchestration.
Key Features
- Flexible Flow Syntax: Define sequential (
->) and concurrent (,) agent execution in one flow - Custom Flow Patterns: Mix sequential and concurrent execution patterns
- Team Awareness: Agents can be aware of their position in the workflow
- Memory System Support: Optional persistent memory across agent interactions
- Batch Processing: Process multiple tasks with the same flow
- Concurrent Execution: Run multiple tasks in parallel
- Async Support: Asynchronous execution for non-blocking operations
Installation
Class Definition
Earlier versions accepted
human_in_the_loop, custom_human_in_the_loop, and rules parameters (and an H token in the flow string for human review steps). These have been removed — AgentRearrange no longer supports inline human-in-the-loop steps or a rules argument.Parameters
str
default:"auto-generated"
Unique identifier for the agent rearrange system. Auto-generated if not provided.
str
default:"AgentRearrange"
Human-readable name for the system
str
default:"A swarm of agents for rearranging tasks."
Description of the system’s purpose
List[Union[Agent, Callable]]
required
List of agents to include in the system. Can be Agent objects or callable functions.
str
required
Flow pattern defining agent execution order. Uses
-> for sequential and , for concurrent execution.
Example: "agent1 -> agent2, agent3 -> agent4"int
default:"1"
Maximum number of execution loops. Must be greater than 0.
bool
default:"True"
Whether to enable verbose logging
Any
default:"None"
Optional memory system for persistence across interactions
OutputType
default:"all"
Format for output results. Options: “all”, “final”, “list”, “dict”
bool
default:"True"
Whether to automatically save execution data
bool
default:"False"
Whether agents should be aware of team structure and sequential flow
bool
default:"False"
Whether to track timestamps in conversations
bool
default:"False"
Whether to include message IDs in conversations
Flow Syntax
The flow pattern defines how agents execute:- Sequential:
agent1 -> agent2 -> agent3(agents run one after another) - Concurrent:
agent1, agent2, agent3(agents run simultaneously) - Mixed:
agent1 -> agent2, agent3 -> agent4(agent1 first, then agent2 and agent3 concurrently, then agent4)
Methods
run(task, img=None, *args, **kwargs)
Execute the agent rearrangement task.
str
required
The task to execute through the agent workflow
Optional[str]
default:"None"
Path to input image if required by any agents
Union[str, List[str], Dict[str, str]]
The processed output in the format specified by output_type
batch_run(tasks, img=None, batch_size=10, *args, **kwargs)
Process multiple tasks in batches.
List[str]
required
List of tasks to process through the agent workflow
Optional[List[str]]
default:"None"
Optional list of images corresponding to tasks
int
default:"10"
Number of tasks to process simultaneously in each batch
List[str]
List of results corresponding to input tasks
concurrent_run(tasks, img=None, max_workers=None, *args, **kwargs)
Process multiple tasks concurrently using ThreadPoolExecutor.
List[str]
required
List of tasks to process through the agent workflow
Optional[List[str]]
default:"None"
Optional list of images corresponding to tasks
Optional[int]
default:"None"
Maximum number of worker threads. Uses default ThreadPoolExecutor behavior if None.
List[str]
List of results corresponding to input tasks
run_async(task, img=None, *args, **kwargs)
Asynchronously execute a task.
str
required
The task to be executed through the agent workflow
Optional[str]
default:"None"
Optional image input for the task
Any
The result of the task execution
set_custom_flow(flow)
Set a custom flow pattern for agent execution.
str
required
The new flow pattern to use for agent execution
add_agent(agent)
Add an agent to the swarm.
Agent
required
The agent to be added
remove_agent(agent_name)
Remove an agent from the swarm.
str
required
The name of the agent to be removed
validate_flow()
Validate the flow pattern.
bool
True if the flow pattern is valid
ValueError: If the flow pattern is incorrectly formatted or contains unregistered agents
to_dict()
Convert all attributes to a dictionary for serialization.
Dict[str, Any]
Dictionary representation of all class attributes
Attributes
Usage Examples
Sequential Flow
Concurrent Flow
Mixed Sequential and Concurrent Flow
Batch Processing
Concurrent Task Execution
Async Execution
Dynamic Flow Modification
With Memory System
With Team Awareness
Different Output Types
Convenience Function
Therearrange() function provides a quick way to create and execute:
Error Handling
Best Practices
- Flow Design: Carefully design your flow to match your task requirements
- Team Awareness: Enable for complex flows where context matters
- Error Handling: Always wrap execution in try-except blocks
- Logging: Enable verbose mode during development
- Memory Systems: Use for tasks requiring persistent context
- Flow Validation: Always validate flows before production use
- Agent Naming: Use clear, descriptive agent names in flows
Common Flow Patterns
Fan-Out Pattern
Pipeline Pattern
Review Pattern
Ensemble Pattern
Related Classes
- SequentialWorkflow: For simple sequential execution
- ConcurrentWorkflow: For parallel agent execution
- GraphWorkflow: For complex DAG-based workflows
- Agent: The base agent class used in workflows