> ## 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.

# AutoSwarmBuilder Guide

> Describe a task and let a boss model design the agents and pick the swarm architecture, then review the design or run it in one call

`AutoSwarmBuilder` designs a multi-agent team for you. You describe the task; a boss model replies with a spec: the agents, each with a name, description, system prompt and model, plus the architecture to run them in, such as `SequentialWorkflow`. You can stop at the spec and review it, turn it into `Agent` objects, or have the builder run it through a [SwarmRouter](https://docs.swarms.world/api/swarm-router.md) straight away.

Reference: [AutoSwarmBuilder](https://docs.swarms.world/api/auto-swarm-builder.md).

## What run() returns

`run(task)` returns one of four things:

| Setting | Returns |
| - | - |
| `swarm_type="return-agents"` (the default) | `{"agents": [...]}`, one spec dict per agent |
| `swarm_type="return-swarm-router-config"` | The full spec: `name`, `description`, `agents`, `swarm_type`, `rearrange_flow`, `rules`, `multi_agent_collab_prompt` and `task` |
| `swarm_type="return-agents-objects"` | A list of built `Agent` objects that have not run |
| `auto_execute=True`, or `run(task, execute=True)` | The team is built and run. Returns `name`, `description`, `agents`, `swarm_type`, `task` and `output` |

Here `swarm_type` picks what the builder returns, not the architecture. The boss model picks the architecture.

The boss's reply is parsed as JSON and checked against a schema. A bad reply is sent back to the boss with the error, up to `max_json_repair_attempts` times (1 by default), before `run()` raises `ValueError`.

## 1. Design a team

```python theme={null}
from swarms import AutoSwarmBuilder

builder = AutoSwarmBuilder(
    name="launch-team-designer",
    model_name="gpt-5.4-mini",
)

specs = builder.run(
    "Plan the launch of a budget electric scooter: pricing, a marketing "
    "plan and a risk review. Use at most three agents."
)

for spec in specs["agents"]:
    print(f"{spec['agent_name']} ({spec['model_name']}): {spec['description']}")
```

Output from one run, shortened:

```
MarketAnalystScout (gpt-4o-mini): Owns market positioning, customer segmentation, competitive pricing logic, ...
GrowthCampaignPlanner (gpt-4o-mini): Designs the launch marketing plan, including messaging, channels, ...
LaunchRiskReviewer (gpt-4o-mini): Performs a structured risk review covering product, supply chain, ...
```

`model_name` on the builder sets the boss model only. The boss chooses a `model_name` for each agent it designs, here `gpt-4o-mini`. A spec without one gets `gpt-5.4`. Each spec also has `system_prompt`, `max_tokens`, `temperature`, `max_loops`, `role`, `goal` and `auto_generate_prompt`.

## 2. Get the full swarm spec

`"return-swarm-router-config"` adds the architecture and the team's name to the agents:

```python theme={null}
from swarms import AutoSwarmBuilder

builder = AutoSwarmBuilder(
    model_name="gpt-5.4-mini",
    swarm_type="return-swarm-router-config",
)

config = builder.run(
    "Write a short product FAQ for a smart thermostat: one agent drafts "
    "the questions, one answers them, one edits. Use exactly three agents."
)

print(config["name"], "|", config["swarm_type"])
print("flow:", config["rearrange_flow"])
print("agents:", [agent["agent_name"] for agent in config["agents"]])
print("task:", config["task"])
```

Output:

```
Smart Thermostat FAQ Team | SequentialWorkflow
flow: None
agents: ['FAQ_Question_Drafter', 'FAQ_Answer_Writer', 'FAQ_Editor']
task: Write a short product FAQ for a smart thermostat: one agent drafts the questions, one answers them, one edits. Use exactly three agents.
```

* `swarm_type` is any [SwarmType](https://docs.swarms.world/api/swarm-router.md) except `"AutoSwarmBuilder"` and `"auto"`. A spec naming either is rejected.
* `rearrange_flow` is set only when the boss picks `AgentRearrange`.
* `task` is always your exact task string, not the boss's copy of it.
* Two agents with the same name raise `ValueError`.

## 3. Design and run in one call

With `auto_execute=True`, `run()` builds the agents from the spec and runs them through a `SwarmRouter`. Pass `execute=True` or `execute=False` to `run()` to override it for one call.

```python theme={null}
from swarms import AutoSwarmBuilder

builder = AutoSwarmBuilder(
    name="haiku-team",
    model_name="gpt-5.4-mini",
    auto_execute=True,
)

result = builder.run(
    "Write one haiku about autumn rain. Use two agents: a poet and an editor."
)

print(result["name"], "|", result["swarm_type"], "|", result["agents"])
for message in result["output"]:
    print(f"{message['role']}: {message['content']}")

print("tokens:", builder.usage["total_tokens"])
```

Output from one run, with each haiku cut to its first line:

```
Autumn Rain Haiku Team | SequentialWorkflow | ['Poet', 'Editor']
User: Write one haiku about autumn rain. Use two agents: a poet and an editor.
Poet: Whispers through the trees, ...
Editor: Whispers through the trees, ...
tokens: 3094
```

* `agents` lists the names of the agents that actually ran, built from the same spec that is reported back.
* The router runs with `output_type="dict"`, so `output` is the conversation as a list of messages, each with `role`, `content`, `timestamp` and `message_id`.
* The router gets the builder's `max_loops`.
* The spec's `rules` and `multi_agent_collab_prompt` are not applied. `SwarmRouter` logs that it ignored `rules`.
* `builder.usage` adds up the boss calls and every agent in every router the builder ran.

## 4. Review and edit the spec before running

To change the design before anything runs, take the spec, edit it, then build the agents and the router yourself. Here every agent is pinned to one model:

```python theme={null}
from swarms import AutoSwarmBuilder, SwarmRouter

builder = AutoSwarmBuilder(
    model_name="gpt-5.4-mini",
    swarm_type="return-swarm-router-config",
)

config = builder.run(
    "Write a two-paragraph welcome email for new customers of a bike "
    "repair shop. Use two agents: a writer and a proofreader."
)

# Pin every generated agent to one model before anything runs.
for spec in config["agents"]:
    spec["model_name"] = "gpt-5.4-mini"

agents = builder.create_agents_from_specs(config)

router = SwarmRouter(
    name=config["name"],
    swarm_type=config["swarm_type"],
    rearrange_flow=config["rearrange_flow"],
    agents=agents,
    output_type="final",
)

print([(agent.agent_name, agent.model_name) for agent in agents])
print(router.run(config["task"]))
```

This prints `[('Writer', 'gpt-5.4-mini'), ('Proofreader', 'gpt-5.4-mini')]`, then the proofread email. `create_agents_from_specs()` turns each spec's `description` into the agent's `agent_description` and raises `ValueError` on a repeated name.

## 5. Get ready-made Agent objects

`"return-agents-objects"` designs the team and builds the agents, but leaves running them to you:

```python theme={null}
from swarms import AutoSwarmBuilder

builder = AutoSwarmBuilder(
    model_name="gpt-5.4-mini",
    swarm_type="return-agents-objects",
)

reviewers = builder.run(
    "Create two code reviewers: one checks security, one checks readability. "
    "Use exactly two agents, each on gpt-5.4-mini."
)

snippet = "def load(path): return eval(open(path).read())"

for reviewer in reviewers:
    reviewer.print_on = False
    print(f"{reviewer.agent_name} ({reviewer.model_name}):")
    print(reviewer.run(f"Review this Python in two sentences:\n{snippet}"), "\n")
```

The boss followed the model named in the task, and the run printed `SecurityReviewer (gpt-5.4-mini):` and `ReadabilityReviewer (gpt-5.4-mini):`, each with a short review.

## 6. Pick an architecture for agents you already have

`initialize_swarm_router()` takes your own agents and asks the boss only to choose the architecture. The boss is told your agents' names and descriptions, and the router runs your agents, not new ones.

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

agents = [
    Agent(
        agent_name=name,
        agent_description=description,
        system_prompt=f"You are the {name}. {description} Keep answers short.",
        model_name="gpt-5.4-mini",
        max_loops=1,
        print_on=False,
    )
    for name, description in [
        ("Researcher", "Lists the key facts about a topic."),
        ("Writer", "Turns facts into one clear paragraph."),
    ]
]

builder = AutoSwarmBuilder(model_name="gpt-5.4-mini")
output = builder.initialize_swarm_router(
    agents=agents,
    task="Explain why the sky is blue to a ten-year-old.",
)

for message in output:
    print(f"{message['role']}: {message['content']}\n")
```

The boss chose `SequentialWorkflow` here, so the output shows the task, then the Researcher's facts, then the Writer's paragraph. The router uses `output_type="dict"` and the builder's `max_loops`.

## 7. Limit the team size and the repair retries

`max_agents` and `max_json_repair_attempts` are attributes, not constructor arguments. Set them after construction, then call `reliability_check()` to validate them.

```python theme={null}
from swarms import AutoSwarmBuilder

builder = AutoSwarmBuilder(model_name="gpt-5.4-mini")
builder.max_agents = 2
builder.max_json_repair_attempts = 2
builder.reliability_check()

try:
    builder.run("Build a team of five specialists to plan a music festival. Use exactly five agents.")
except ValueError as error:
    print(error)
```

Output:

```
Boss agent generated 5 agents, exceeding max_agents=2.
```

The boss is not told about `max_agents`; the limit is checked after it replies. Say how many agents you want in the task as well, as the earlier examples do.

## Tips

* **Start with the spec.** Run `"return-agents"` or `"return-swarm-router-config"` first, read what the boss designed, then execute.
* **Name the team size and models in the task.** The boss follows them, and it keeps runs small.
* **Use a different boss prompt** with `system_prompt`, and pass extra arguments to the boss model with `additional_llm_args`.
* **`batch_run(tasks)`** calls `run()` on each task in turn and returns a list of results.

## Next steps

* [AutoSwarmBuilder reference](https://docs.swarms.world/api/auto-swarm-builder.md)
* [SwarmRouter](https://docs.swarms.world/api/swarm-router.md), which runs the generated team


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