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

# AutoAgentBuilder

> Generates a roster of agent configurations from a task using a single forced function call

## Overview

The `AutoAgentBuilder` class turns a plain-English task into a roster of agents. A single builder agent is forced to call one function, `build_agents`, and must answer with a list of agent configurations rather than prose.

Each generated agent carries exactly four fields — the minimum needed to construct an [`Agent`](/api/agent):

```
name, description, system_prompt, model_name
```

The builder designs the team and stops there. It does **not** choose a multi-agent architecture and it does **not** execute anything, so you decide what runs the roster.

<Note>
  Because the provider enforces the tool schema, there is no markdown fence to strip and no JSON to extract from a paragraph. This is the main behavioral difference from [`AutoSwarmBuilder`](/api/auto-swarm-builder), which uses structured output and also selects a `swarm_type` for you.
</Note>

## Class Definition

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

## Parameters

<ParamField path="name" type="str" default="auto-agent-builder">
  Name of this builder instance
</ParamField>

<ParamField path="description" type="str" default="Generates agent configurations from a task">
  What this builder is for
</ParamField>

<ParamField path="model_name" type="str" default="gpt-5.4">
  Model backing the builder agent itself. This is not the model given to the generated agents — the builder chooses those per agent. Must support function calling
</ParamField>

<ParamField path="max_agents" type="int" default="5">
  Upper bound on roster size. This is a **ceiling, not a target** — the builder is instructed to prefer the smallest roster that covers the task, so it will routinely return fewer. Must be >= 1
</ParamField>

<ParamField path="num_agents" type="Optional[int]" default="None">
  Exact number of agents to generate. When set, overrides `max_agents` and the builder's prefer-fewer guidance, and the count is verified on the result. Must be >= 1
</ParamField>

<ParamField path="system_prompt" type="str" default="AUTO_AGENT_BUILDER_SYSTEM_PROMPT">
  Instructions for the builder agent. Override to constrain the roster — force a model tier, require a specific role, or restrict the decomposition strategy
</ParamField>

<ParamField path="agent_kwargs" type="Optional[Dict[str, Any]]" default="None">
  Extra keyword arguments forwarded to every generated `Agent`, e.g. `max_loops` or `streaming_on`. Keys that collide with the four generated fields are ignored. Unused when `return_dict` is True, since no agent is constructed
</ParamField>

<ParamField path="return_dict" type="bool" default="False">
  When True, `run()` returns the raw configuration dicts instead of constructed `Agent` objects. Use this to inspect, serialize, or edit the roster before building anything from it
</ParamField>

<ParamField path="verbose" type="bool" default="False">
  Whether to log the generated roster
</ParamField>

**Raises:**

* `ValueError`: If `max_agents` or `num_agents` is less than 1

## Roster size: ceiling vs exact count

This is the setting most likely to surprise you.

| Parameter      | Meaning                                                               | Result for a 3-role task |
| -------------- | --------------------------------------------------------------------- | ------------------------ |
| `max_agents=5` | A ceiling. The builder picks the smallest roster that covers the task | 3 agents                 |
| `num_agents=5` | A hard requirement. Overrides the prefer-fewer guidance               | 5 agents                 |

The default system prompt actively pushes the count down — it states that "fewer is almost always better" and that "2–3 agents is the common, correct case for most tasks." So `max_agents=5` returning three agents is the builder working correctly, not a failure.

```python theme={null}
# Ceiling — the builder decides how many it needs
AutoAgentBuilder(max_agents=5).run(task)

# Exact — the builder must split the work to reach five
AutoAgentBuilder(num_agents=5).run(task)
```

<Warning>
  If the model returns fewer than `num_agents`, a warning is logged and the shorter roster is returned. Agents cannot be fabricated for a task that does not support them.
</Warning>

## Methods

### `run()`

```python theme={null}
def run(self, task: str) -> Union[List[Agent], List[Dict[str, str]]]
```

Generates the roster in the shape this builder was configured for.

**Parameters:**

<ParamField path="task" type="str" required>
  The task the generated team should be able to handle
</ParamField>

**Returns:**

<ResponseField name="result" type="Union[List[Agent], List[Dict[str, str]]]">
  Configuration dicts when `return_dict=True`, otherwise constructed `Agent` objects
</ResponseField>

**Raises:**

* `ValueError`: If `task` is empty, or the builder returns no usable agent configurations

***

### `build_agents()`

```python theme={null}
def build_agents(self, task: str) -> List[Agent]
```

Generates configurations and constructs the `Agent` objects. Ignores `return_dict` — this is the shape-specific entry point for callers that want agents regardless of how the builder was configured.

**Returns:**

<ResponseField name="agents" type="List[Agent]">
  Constructed agents, ready to run or hand to a multi-agent structure. `agent_kwargs` is applied to each
</ResponseField>

***

### `build_configs()`

```python theme={null}
def build_configs(self, task: str) -> List[Dict[str, str]]
```

Generates agent configurations for a task, always as dicts. Ignores `return_dict`.

**Returns:**

<ResponseField name="configs" type="List[Dict[str, str]]">
  One dict per agent with `name`, `description`, `system_prompt` and `model_name`. Truncated to `num_agents` or `max_agents`
</ResponseField>

***

### `__call__()`

```python theme={null}
def __call__(self, task: str) -> Union[List[Agent], List[Dict[str, str]]]
```

Alias for `run()`. Follows `return_dict`.

## Output shapes

```python theme={null}
AutoAgentBuilder().run(task)                  # -> [Agent, Agent, ...]
AutoAgentBuilder(return_dict=True).run(task)  # -> [{...}, {...}, ...]

builder.build_agents(task)                    # always Agent objects
builder.build_configs(task)                   # always configuration dicts
```

## One LLM call per method

Every public method triggers a fresh call, and the builder is not deterministic. Calling `build_configs()` and then `build_agents()` designs **two different rosters** — so what you printed may not be what you ran.

Generate once and reuse the result:

```python theme={null}
configs = builder.build_configs(task)

agents = [
    Agent(
        agent_name=c["name"],
        agent_description=c["description"],
        system_prompt=c["system_prompt"],
        model_name=c["model_name"],
        max_loops=1,
    )
    for c in configs
]
```

## Validation behavior

The builder filters the model's output before returning it:

| Condition                            | Behavior                                                                                                         |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| Entry missing any of the four fields | Dropped, warning logged                                                                                          |
| Duplicate `name`                     | Dropped, warning logged. `Agent` memory is keyed on `agent_name`, so duplicates would corrupt each other's state |
| More agents than the limit           | Truncated to `num_agents` or `max_agents`, warning logged                                                        |
| Fewer than `num_agents`              | Returned as-is, warning logged                                                                                   |
| No usable entries at all             | Raises `ValueError`                                                                                              |
| Malformed or non-JSON tool output    | Raises `ValueError`                                                                                              |

Tool calls are parsed from all shapes providers return: a plain dict, a list-wrapped dict, or an attribute-style object such as litellm's `ChatCompletionMessageToolCall`.

## Usage Examples

### Inspect the roster before building

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

builder = AutoAgentBuilder(model_name="gpt-5.4", max_agents=3, return_dict=True)

for config in builder.run("Analyze why SaaS churn increased last quarter."):
    print(f"{config['name']} [{config['model_name']}]")
    print(f"  {config['description']}")
```

### Build and run in sequence

```python theme={null}
from swarms import AutoAgentBuilder, SequentialWorkflow

agents = AutoAgentBuilder(num_agents=3, agent_kwargs={"max_loops": 1}).run(task)

result = SequentialWorkflow(agents=agents, max_loops=1).run(task)
```

### Compose with SwarmRouter

The builder answers *who is on the team*; [`SwarmRouter`](/api/swarm-router) answers *how they run*.

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

agents = AutoAgentBuilder(max_agents=4).run(task)

router = SwarmRouter(agents=agents, swarm_type="ConcurrentWorkflow", max_loops=1)
result = router.run(task)
```

Since the roster is just a list of agents, it also drops into `MixtureOfAgents`, `HierarchicalSwarm`, `GroupChat`, or anything else that accepts one.

### Constrain the roster with a custom prompt

```python theme={null}
from swarms.prompts.auto_agent_builder_prompt import (
    AUTO_AGENT_BUILDER_SYSTEM_PROMPT,
)

CONSTRAINED = AUTO_AGENT_BUILDER_SYSTEM_PROMPT + """

ADDITIONAL CONSTRAINTS:
- Every agent must use model_name "gpt-5.4-mini".
- Include exactly one agent whose sole job is to verify the others' output.
"""

builder = AutoAgentBuilder(system_prompt=CONSTRAINED, num_agents=4)
```

## The builder system prompt

The default prompt is exported and can be imported, extended, or replaced:

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

It instructs the builder to:

| Area                      | Guidance                                                                                                                                                                                    |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Decomposition**         | Split by stage, domain, source, or perspective — and pick one seam rather than mixing them                                                                                                  |
| **Sizing**                | Prefer the smallest roster; a single agent is a valid answer. An explicit exact count overrides this                                                                                        |
| **Merge test**            | Merge any two agents where one competent specialist could do both jobs                                                                                                                      |
| **Coverage test**         | Confirm every part of the task has an owner; gaps are worse than redundancy                                                                                                                 |
| **`system_prompt` field** | Several paragraphs covering identity, responsibility, method, output, and standards — the generated agent never sees the builder prompt or its teammates' prompts, so each must stand alone |
| **`model_name` field**    | Match the model to cognitive load, not to the agent's importance. Mixing tiers is a sign of good design                                                                                     |

## Comparison with AutoSwarmBuilder

|                          | `AutoAgentBuilder`   | [`AutoSwarmBuilder`](/api/auto-swarm-builder)        |
| ------------------------ | -------------------- | ---------------------------------------------------- |
| Output                   | Agent roster only    | Roster plus `swarm_type` and optional execution      |
| Structured output method | Forced function call | `response_format`                                    |
| Fields per agent         | 4                    | 10+ (`max_tokens`, `temperature`, `role`, `goal`, …) |
| Picks architecture       | No                   | Yes                                                  |
| Executes the task        | No                   | Optionally                                           |

Use `AutoAgentBuilder` when you want the roster and full control over what runs it. Use `AutoSwarmBuilder` when you want the whole pipeline decided for you.

## Requirements

The builder needs a model that supports function calling, plus a provider key:

```bash theme={null}
export OPENAI_API_KEY=sk-...
```

Generated agents may name a different provider than the builder — it chooses a model per agent and deliberately mixes tiers. If a roster references a provider you have no key for, set that key or edit `model_name` on the configs before constructing.

## Source Code

* [`swarms/structs/auto_agent_builder.py`](https://github.com/kyegomez/swarms/blob/master/swarms/structs/auto_agent_builder.py)
* [`swarms/prompts/auto_agent_builder_prompt.py`](https://github.com/kyegomez/swarms/blob/master/swarms/prompts/auto_agent_builder_prompt.py)
* [Examples](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/auto_agent_builder_examples)
