Skip to main content

Overview

The AgentRearrange 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
  • 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 via generate_id("agent-rearrange") if not provided, producing agent-rearrange-<32 hex chars>.
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"
Number of times the whole flow runs per run() call. Values below 1 are treated as 1.
bool
default:"False"
Whether to enable verbose logging
Any
default:"None"
Accepted for backwards compatibility. The value is stored on the instance and is not read by the workflow. Configure memory on the individual agents with persistent_memory instead.
OutputType
default:"all"
Format of the returned conversation. One of "list", "dict", "dictionary", "str", "string", "all", "final", "last", "json", "yaml", "dict-all-except-first", "str-all-except-first", "dict-final", "list-final". The default "all" returns the transcript as "role: content" text. Any other value raises ValueError at construction.
bool
default:"True"
Whether to automatically save execution data
bool
default:"False"
If True, the step-by-step flow structure (see get_sequential_flow_structure()) is added to the shared conversation as a system message at the start of each run. Agents in single-agent steps always receive the names of the agents ahead and behind them as a system turn, whether or not this is set.
str
Guidance prepended to every agent’s messages as a system turn for the duration of the run. It is not written to the shared conversation, so other agents never see it, and the caller’s Agent objects are not modified. SequentialWorkflow passes its collaboration preamble through this parameter.
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. Each call starts a fresh shared conversation, so a reused instance does not carry the previous task’s transcript. Every agent’s final answer, not its whole transcript, is added to that conversation. The flow is not validated up front: a step that names an unregistered agent raises ValueError when it is reached, after earlier steps have run.
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. Batches run one after another; the tasks inside a batch run concurrently. Each task runs on an isolated clone with a fresh conversation and deep-copied agents (falling back to the original agent when it cannot be copied).
List[str]
required
List of tasks to process through the agent workflow
Optional[List[str]]
default:"None"
Optional list of images corresponding to tasks. Must be the same length as tasks, or ValueError is raised.
int
default:"10"
Number of tasks to process simultaneously in each batch. Must be positive, or ValueError is raised.
List[str]
List of results in the same order as the input tasks

concurrent_run(tasks, img=None, max_workers=None, *args, **kwargs)

Process multiple tasks concurrently on a thread pool. Each task runs on an isolated clone with a fresh conversation, so concurrent tasks never share history.
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. Defaults to os.cpu_count() when None.
List[str]
List of results in the same order as the 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. The new flow is validated immediately; if it is empty or names an unregistered agent, ValueError is raised and the previous flow is kept.
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

add_agents(agents)

Add multiple agents to the swarm at once.
List[Agent]
required
A list of Agent objects to be added

remove_agent(agent_name)

Remove an agent from the swarm. Raises ValueError if no agent has that name.
str
required
The name of the agent to be removed

explain(return_str=False)

Print (or return) the resolved execution plan for the current flow, listing every step in order and marking each as sequential or parallel. Does not invoke any agents or LLMs. Validates the flow first and raises if it is invalid.
bool
default:"False"
When True, returns the plan as a string instead of printing it
Optional[str]
The plan string if return_str=True; otherwise None

get_agent_sequential_awareness(agent_name)

Get the sequential awareness information (agents immediately ahead/behind) for a specific agent in the current flow.
str
required
The name of the agent to get awareness for
str
A string describing the agents ahead and behind in the sequence

get_sequential_flow_structure()

Get a string describing the complete sequential flow structure (step-by-step breakdown of the flow).
str
A string describing the overall sequential flow structure

run_stream(task=None, img=None, with_events=False, **kwargs)

Sync generator that streams tokens from each agent in flow order as they are generated. Sequential segments stream one agent at a time; parallel (comma) segments interleave tokens fairly across concurrent agents.
str
default:"None"
Initial task fed into the first agent in the flow
Optional[str]
default:"None"
Optional image input forwarded to every agent
bool
default:"False"
When False, yields (agent_name, token) tuples. When True, yields structured event dicts (agent_start, token, agent_end)
Not yet supported in streaming mode: max_loops > 1, custom_tasks. Use run() for those.

arun_stream(task=None, img=None, with_events=False, **kwargs)

Async generator version of run_stream, with the same parameters and yield semantics.

validate_flow()

Validate the flow pattern.
bool
True if the flow pattern is valid
Raises:
  • 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 Team Awareness

Different Output Types

Convenience Function

The rearrange() function provides a quick way to create and execute:

Error Handling

Best Practices

  1. Flow Design: Carefully design your flow to match your task requirements
  2. Team Awareness: Enable for complex flows where context matters
  3. Error Handling: Always wrap execution in try-except blocks
  4. Logging: Enable verbose mode during development
  5. Memory: memory_system is not read; set persistent_memory=True on individual agents for context that survives restarts
  6. Flow Validation: Call validate_flow() or explain() before production use, since construction does not check agent names
  7. Agent Naming: Use clear, descriptive agent names in flows

Common Flow Patterns

Fan-Out Pattern

Pipeline Pattern

Review Pattern

Ensemble Pattern