> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# AgentRearrange Guide

> Write the order your agents run in as a flow string, mix sequential and parallel steps, read the shared conversation, and run many tasks at once

`AgentRearrange` runs agents in the order a flow string gives. An arrow `->` separates steps that run one after another. A comma `,` puts several agents in the same step, where they run at the same time. Every agent reads one shared conversation: the task, then each earlier agent's answer under its name. When the flow ends, `run()` returns that conversation in the format `output_type` names.

Reference: [AgentRearrange](https://docs.swarms.world/api/agent-rearrange.md).

## 1. A sequential pipeline

Name each agent, then refer to it by `agent_name` in the flow. Here a researcher, a writer and an editor run one after another, and each one builds on the answers before it.

```python theme={null}
from swarms import Agent, AgentRearrange

researcher = Agent(
    agent_name="Researcher",
    system_prompt="You list the key facts about a topic as five short bullets.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)
writer = Agent(
    agent_name="Writer",
    system_prompt="You turn research notes into one clear paragraph of under 120 words.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)
editor = Agent(
    agent_name="Editor",
    system_prompt="You tighten a paragraph and fix any errors. Return only the edited paragraph.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)

pipeline = AgentRearrange(
    name="Blog-Pipeline",
    agents=[researcher, writer, editor],
    flow="Researcher -> Writer -> Editor",
)

result = pipeline.run("Explain why solid-state batteries matter for electric cars.")
print(result)
```

The default `output_type="all"` returns the whole conversation as text, one timestamped line per message:

```text theme={null}
[2026-12-02T13:41:19.328417] User: Explain why solid-state batteries matter for electric cars.

[2026-12-02T13:41:21.383039] Researcher: - They can store more energy, which could mean longer driving range.
...
[2026-12-02T13:41:24.180248] Editor: Solid-state batteries matter for electric cars because ...
```

Each `run()` starts a fresh conversation, so reusing the same `AgentRearrange` for a new task does not carry the old transcript.

## 2. Run agents in parallel with a comma

Agents in the same step run at the same time and see the same conversation. The next step sees all of their answers. Call `explain()` to print the plan without calling any model.

```python theme={null}
from swarms import Agent, AgentRearrange


def make_agent(name: str, system_prompt: str) -> Agent:
    """Build a one-loop agent on a small model."""
    return Agent(
        agent_name=name,
        system_prompt=system_prompt,
        model_name="gpt-5.4-mini",
        max_loops=1,
    )


planner = make_agent("Planner", "Restate the decision to make and list three criteria for it.")
optimist = make_agent("Optimist", "You always make the strongest case FOR the proposal, in under 80 words.")
skeptic = make_agent("Skeptic", "You always make the strongest case AGAINST the proposal, in under 80 words.")
judge = make_agent("Judge", "Weigh both sides against the criteria and give a one-line verdict.")

review = AgentRearrange(
    name="Proposal-Review",
    agents=[planner, optimist, skeptic, judge],
    flow="Planner -> Optimist, Skeptic -> Judge",
    output_type="final",
)

review.explain()

verdict = review.run("Should our 12-person design team switch to a four-day work week?")
print(verdict)
```

`explain()` prints:

```text theme={null}
Flow: Planner -> Optimist, Skeptic -> Judge

Step 1: Planner            [sequential]
Step 2: Optimist, Skeptic  [parallel, 2 agents]
Step 3: Judge              [sequential]

3 steps, 4 agent invocations across 1 loop(s).
```

With `output_type="final"`, `run()` returns only the Judge's answer as a string.

> [!NOTE]
>
> Steps run by name, so two different agents with the same `agent_name` raise `ValueError` when you build the `AgentRearrange`. The same agent can still appear in more than one step.

## 3. Read the output

`output_type` decides what `run()` returns. With `"list"`, you get one dict per message, with `role` and `content`, in the order the messages were added:

```python theme={null}
review = AgentRearrange(
    name="Proposal-Review",
    agents=[planner, optimist, skeptic, judge],
    flow="Planner -> Optimist, Skeptic -> Judge",
    output_type="list",
)

messages = review.run("Should our 12-person design team switch to a four-day work week?")

for message in messages:
    print(f"{message['role']}: {message['content'][:60]}...")
```

```text theme={null}
User: Should our 12-person design team switch to a four-day work w...
Planner: Decision to make: whether your 12-person design team should ...
Optimist: Yes ...
Skeptic: Probably not. A four-day week risks compressing the same wor...
Judge: Probably yes ...
```

The values you will use most:

| `output_type` | `run()` returns |
| - | - |
| `"all"` (default), `"str"`, `"string"` | The whole conversation as one string |
| `"final"`, `"last"` | The last agent's answer as a string |
| `"list"` | A list of `{"role", "content"}` dicts, one per message |
| `"dict"`, `"dictionary"` | A list of message dicts that also carry each message's timestamp and id |
| `"str-all-except-first"` | Every answer after the task, one per line, without speaker names |
| `"json"`, `"yaml"` | The conversation serialized |

Any other value raises `ValueError` when you build the `AgentRearrange`. After a run, `review.conversation` still holds the full conversation as a `Conversation`.

## 4. Tell agents where they sit in the flow

`team_awareness=True` adds the flow structure to the start of the conversation as a system message, and tells each agent in a single-agent step which agents come before and after it. `collab_prompt` is a system message given to every agent but kept out of the shared conversation. This block reuses the agents from section 1:

```python theme={null}
aware_pipeline = AgentRearrange(
    name="Aware-Pipeline",
    agents=[researcher, writer, editor],
    flow="Researcher -> Writer -> Editor",
    team_awareness=True,
    collab_prompt="Keep every reply under 100 words and build on the previous step.",
    output_type="final",
)

print(aware_pipeline.get_sequential_flow_structure())
print(aware_pipeline.get_agent_sequential_awareness("Writer"))

print(aware_pipeline.run("Explain how heat pumps heat a home in winter."))
```

The two helper methods show what the agents are told:

```text theme={null}
Sequential Flow Structure:
Step 1: Researcher (leads to: Writer)
Step 2: Writer (follows: Researcher) (leads to: Editor)
Step 3: Editor (follows: Writer)
Sequential awareness: Agent ahead: Researcher | Agent behind: Editor
```

## 5. Run many tasks with batch\_run

`batch_run()` sends each task through the whole flow and returns the results in the same order as the tasks. Each task runs on its own copy of the swarm, with copied agents and a fresh conversation, so tasks never share history. `batch_size` caps how many tasks run at once.

```python theme={null}
pipeline = AgentRearrange(
    name="Blog-Pipeline",
    agents=[researcher, writer, editor],
    flow="Researcher -> Writer -> Editor",
    output_type="final",
)

topics = [
    "Explain why solid-state batteries matter for electric cars.",
    "Explain how heat pumps heat a home in winter.",
    "Explain what a smart grid does.",
]

paragraphs = pipeline.batch_run(topics, batch_size=2)

for topic, paragraph in zip(topics, paragraphs):
    print(f"=== {topic}\n{paragraph}\n")
```

`concurrent_run(tasks, max_workers=None)` does the same with a thread limit you choose; by default every task gets its own thread.

## 6. Change the flow between runs

`set_custom_flow()` replaces the flow and checks it right away. A flow that names an unknown agent raises `ValueError`, and the old flow stays in place. `steps` shows the parsed flow, one list of names per step.

```python theme={null}
pipeline.set_custom_flow("Researcher -> Editor")
print(pipeline.steps)

try:
    pipeline.set_custom_flow("Researcher -> Translator")
except ValueError as error:
    print(f"Rejected: {error}")

print(pipeline.flow)
print(pipeline.run("Explain what a smart grid does."))
```

```text theme={null}
[['Researcher'], ['Editor']]
Rejected: Agent 'Translator' is not registered.
Researcher -> Editor
```

`run()` also checks the flow before any agent runs, so a bad flow fails fast instead of after the first steps have spent tokens.

> [!WARNING]
>
> `run()` accepts a `custom_tasks` keyword that is meant to splice an extra step in front of an agent. On the current release it only works for the first agent in a flow written without spaces around `->`, and its value is read as an agent name, not as task text. Use `set_custom_flow()` to change which agents run.

## 7. Stream tokens as agents write

`run_stream()` yields output while each agent is still writing. With `with_events=True` it yields dicts: `agent_start`, then one `token` event per chunk, then `agent_end` with the agent's whole output. Agents in a parallel step stream at the same time, so their tokens interleave.

```python theme={null}
streaming = AgentRearrange(
    name="Streaming-Pipeline",
    agents=[researcher, writer],
    flow="Researcher -> Writer",
)

for event in streaming.run_stream("Explain what a smart grid does.", with_events=True):
    if event["type"] == "agent_start":
        print(f"\n--- {event['agent']} ---")
    elif event["type"] == "token":
        print(event["token"], end="", flush=True)
print()
```

Without `with_events`, each item is an `(agent_name, token)` tuple. Streaming runs the flow once, whatever `max_loops` is. Inside async code, use `async for event in streaming.arun_stream(...)`.

## Tips

* **Match names exactly.** The flow refers to agents by `agent_name`, and spaces around `->` and `,` are ignored.
* **Check before you spend.** `explain()` and `validate_flow()` check the flow without calling a model.
* **Use `max_loops` for rounds.** `max_loops=2` runs the whole flow twice on the same conversation, so the second pass sees the first.
* **Nest whole swarms.** A `ConcurrentWorkflow`, `SequentialWorkflow` or another `AgentRearrange` with a `name` can be a step of the flow. See [Nested Swarms](https://docs.swarms.world/api/agent-rearrange.md#nested-swarms).

## Next steps

* [AgentRearrange reference](https://docs.swarms.world/api/agent-rearrange.md)
* [GraphWorkflow guide](https://docs.swarms.world/examples/multi-agent/graph-workflow-example.md), for dependency graphs that a flow string cannot express
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/agent_rearrange_examples)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.