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

# SubagentRegistry Guide

> Run agents in the background, track each task by id, retry and cancel tasks, limit how deep sub-tasks go, and let an autonomous agent delegate to sub-agents

A `SubagentRegistry` runs agent tasks in the background on a thread pool. `spawn()` hands an agent a task and returns a task id at once; the agent keeps working while your code moves on. Later you wait with `gather()` and read each task's status, result or error by id. The registry also handles retries, cancels queued tasks and enforces a depth limit for tasks that spawn more tasks.

An `Agent` running with `max_loops="auto"` uses the same registry when it creates sub-agents and assigns them work. The last section shows that.

Reference: [SubagentRegistry](https://docs.swarms.world/api/async-subagent.md).

## 1. Fan out and gather

Three researchers each get one question. Keep the id that `spawn()` returns for each task, so you can match results to tasks later.

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

topics = ["solar power", "wind power", "geothermal power"]

researchers = [
    Agent(
        agent_name=f"Researcher-{i}",
        system_prompt="Answer in one sentence.",
        model_name="gpt-5.4-mini",
        max_loops=1,
        print_on=False,
    )
    for i in range(1, len(topics) + 1)
]

registry = SubagentRegistry(max_workers=3)

task_ids = {
    topic: registry.spawn(agent, f"What is the main drawback of {topic}?")
    for agent, topic in zip(researchers, topics)
}

registry.gather()

for topic, task_id in task_ids.items():
    task = registry.get_task(task_id)
    print(f"{task_id} {task.status.value} {topic}: {task.result}")
```

This prints one line per topic, such as `task-5005430c completed wind power: The main drawback of wind power is that it is intermittent, ...`.

`gather()` blocks until the tasks finish and returns their results as a list. The list is not keyed by task and its order is not guaranteed, so read results with `get_task(task_id)` as above.

> [!WARNING]
>
> Give each task its own agent. The registry runs the object you pass, as it is. An `Agent` keeps its conversation between runs, so one agent spawned for several tasks mixes their histories into its answers, and running it on two threads at once mixes them further.

## 2. Inspect the tasks

Every task is a `SubagentTask` record. Continuing from step 1:

```python theme={null}
for task_id, task in registry.tasks.items():
    seconds = task.completed_at - task.created_at
    print(task_id, task.agent.agent_name, task.status.value, f"{seconds:.1f}s")

results = registry.get_results()
print(len(results), "results, keyed by task id")

registry.shutdown()
```

Output:

```
task-d3a85539 Researcher-1 completed 2.2s
task-5005430c Researcher-2 completed 1.7s
task-313713e5 Researcher-3 completed 1.9s
3 results, keyed by task id
```

| Field | What it holds |
| - | - |
| `id`, `agent`, `task_str` | The task id, the agent object and the task text |
| `status` | A `TaskStatus`: `running` from the moment it is spawned, then `completed`, `failed` or `cancelled` |
| `result`, `error` | The agent's return value, or the exception that ended the task |
| `retries`, `max_retries` | Retries used and allowed |
| `parent_id`, `depth` | Where the task sits in a tree of tasks |
| `created_at`, `completed_at` | Unix timestamps |

`registry.tasks` is a copy of every task, keyed by id. `get_results()` maps the id of each completed task to its result, and of each failed task to its exception; it does not wait. `shutdown()` stops the pool from taking new tasks without waiting for running ones.

## 3. Retry some errors and record failures

`max_retries` reruns a task that raised. `retry_on` limits retries to the listed exception types; leave it out to retry any exception. With `fail_fast=False` a failed task stores its error and returns `None` instead of raising in its thread.

Any object with a `run(task)` method can be spawned; its `agent_name`, if it has one, is used in the logs. This stand-in times out once, then answers. The second task uses a model that does not exist, so it fails with an error that is not on the retry list:

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


class FlakyAgent:
    """Times out on its first call, then answers."""

    agent_name = "Flaky"

    def __init__(self) -> None:
        self.calls = 0

    def run(self, task: str) -> str:
        """Fail the first call with a timeout and answer after that."""
        self.calls += 1
        if self.calls == 1:
            raise TimeoutError("the first call timed out")
        return f"answered on call {self.calls}"


broken = Agent(
    agent_name="Broken",
    model_name="openai/no-such-model",
    max_loops=1,
    print_on=False,
)

registry = SubagentRegistry()

flaky_id = registry.spawn(
    FlakyAgent(),
    "Say hello.",
    max_retries=2,
    retry_on=[TimeoutError],
    fail_fast=False,
)
broken_id = registry.spawn(
    broken,
    "Say hello.",
    max_retries=2,
    retry_on=[TimeoutError],
    fail_fast=False,
)

registry.gather()

for task_id in (flaky_id, broken_id):
    task = registry.get_task(task_id)
    print(task.agent.agent_name, task.status.value, f"retries={task.retries}")
    print("  result:", task.result)
    print("  error:", type(task.error).__name__ if task.error else None)

registry.shutdown()
```

Output, after the model error is logged:

```
Flaky completed retries=1
  result: answered on call 2
  error: None
Broken failed retries=0
  result: None
  error: AgentLLMError
```

The flaky task succeeded on its first retry. The broken agent raised `AgentLLMError`, which is not in `retry_on`, so it failed at once with no retries.

Either way a failed task ends with `status` `failed` and its exception in `error`. `fail_fast` only changes what `gather()` returns for a task that fails while it waits: with `fail_fast=True` (the default) the list holds the exception, and with `fail_fast=False` it holds `None`.

## 4. Take the first result and cancel queued work

`gather(strategy="wait_first")` returns as soon as one more task finishes. Tasks still running are left out of that list and keep going. `cancel()` stops a task that is still waiting for a free thread; a task that has started cannot be cancelled.

With one worker thread, tasks run one at a time, so the later ones wait in the queue:

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


def tagline_writer(product: str) -> Agent:
    """Build a fresh agent for one product."""
    return Agent(
        agent_name=f"{product.title()}-Writer",
        system_prompt="Reply with one short tagline only.",
        model_name="gpt-5.4-mini",
        max_loops=1,
        print_on=False,
    )


# One worker thread, so later tasks wait in the queue.
registry = SubagentRegistry(max_workers=1)

task_ids = [
    registry.spawn(tagline_writer(product), f"Write a tagline for a {product}.")
    for product in ("bakery", "bike shop", "bookstore")
]

first = registry.gather(strategy="wait_first")
print("wait_first returned:", first)

cancelled = registry.cancel(task_ids[2])
print("cancelled the bookstore task:", cancelled)

everything = registry.gather()
print("wait_all returned:", everything)

for task_id in task_ids:
    task = registry.get_task(task_id)
    print(task.agent.agent_name, task.status.value)

registry.shutdown()
```

Output:

```
wait_first returned: ['Freshly baked happiness, every day.']
cancelled the bookstore task: True
wait_all returned: ['Freshly baked happiness, every day.', CancelledError(), 'Ride farther, ride happier.']
Bakery-Writer completed
Bike Shop-Writer completed
Bookstore-Writer cancelled
```

Each `gather()` call covers every task in the registry. Tasks that had already finished come first, then the ones that finished during the wait, in no set order. A cancelled task shows up as a `CancelledError`. Pass `timeout` in seconds to stop waiting; tasks still running then are left out.

## 5. Build a tree of tasks with a depth limit

A task can lead to more tasks. Record the link with `parent_id` and `depth` when you spawn. The registry does not work out the depth itself; it stores what you pass and refuses any `depth` above `max_depth`.

A planner splits a topic, then one writer per subtopic works at depth 1:

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


def worker(name: str, system_prompt: str) -> Agent:
    """Build a quiet one-loop agent."""
    return Agent(
        agent_name=name,
        system_prompt=system_prompt,
        model_name="gpt-5.4-mini",
        max_loops=1,
        print_on=False,
    )


registry = SubagentRegistry(max_depth=1)

planner = worker("Planner", "Reply with exactly two subtopics, one per line, no numbering.")
root_id = registry.spawn(planner, "Split the topic 'home energy savings' into subtopics.")
registry.gather()

plan = registry.get_task(root_id).result
subtopics = [line.strip("-* ") for line in plan.splitlines() if line.strip()]

child_ids = [
    registry.spawn(
        worker(f"Writer-{i}", "Reply with one sentence."),
        f"Give one tip about {subtopic}.",
        parent_id=root_id,
        depth=1,
    )
    for i, subtopic in enumerate(subtopics, 1)
]
registry.gather()

for task in registry.tasks.values():
    print(f"depth={task.depth} parent={task.parent_id} {task.agent.agent_name}: {task.result}\n")

try:
    registry.spawn(worker("Too-Deep", "Reply briefly."), "Go one level deeper.", parent_id=child_ids[0], depth=2)
except ValueError as error:
    print(error)

registry.shutdown()
```

Output from one run:

```
depth=0 parent=None Planner: Heating and cooling efficiency
Lighting and appliance energy reduction

depth=1 parent=task-f263fc47 Writer-1: Seal gaps around doors and windows to reduce air leaks, ...

depth=1 parent=task-f263fc47 Writer-2: Switch to LED bulbs and turn off lights and unplug appliances when they’re not in use ...

Subagent depth 2 exceeds max_depth 1
```

The refused spawn raises before a task is created, so nothing is left in the registry. The default `max_depth` is 3.

## 6. Let an autonomous agent delegate

An `Agent` with `max_loops="auto"` has four sub-agent tools:

| Tool | What it does |
| - | - |
| `create_sub_agent` | Builds sub-agents from a name, a description and an optional system prompt, and stores them on `agent.sub_agents` under ids such as `sub-agent-c775cf12` |
| `assign_task` | Spawns each assignment on the agent's own `SubagentRegistry`, with `fail_fast=False` and no retries. By default it waits for every task and returns each result or error |
| `check_sub_agent_status` | Reports each of a sub-agent's tasks: status, depth, retries and duration |
| `cancel_sub_agent_tasks` | Cancels a sub-agent's queued tasks |

`selected_tools` limits the autonomous tools to the ones you list. This lead agent gets the planning tools and the sub-agent tools, and nothing else:

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

lead = Agent(
    agent_name="Research-Lead",
    system_prompt=(
        "You lead a small research team. Create sub-agents with "
        "create_sub_agent, give each one a task with assign_task, then "
        "combine their answers."
    ),
    model_name="gpt-5.4-mini",
    max_loops="auto",
    selected_tools=[
        "create_plan",
        "subtask_done",
        "complete_task",
        "create_sub_agent",
        "assign_task",
        "check_sub_agent_status",
    ],
    print_on=False,
)

answer = lead.run(
    "Create two sub-agents: one that knows electric cars and one that knows "
    "hydrogen cars. Ask each for the single biggest obstacle to adoption, "
    "in one sentence, then compare the two answers in three sentences."
)
print(answer)

for sub_agent_id, entry in lead.sub_agents.items():
    sub_agent = entry["agent"]
    print(sub_agent_id, entry["name"], sub_agent.model_name, sub_agent.max_loops)
```

The answer includes both sub-agents' one-sentence replies and the comparison. The loop then prints the sub-agents the lead made:

```
sub-agent-c775cf12 electric_cars_expert gpt-5.4-mini 1
sub-agent-67d47ddd hydrogen_cars_expert gpt-5.4-mini 1
```

How sub-agents are built:

* They use the lead's `model_name` and get the lead's `tools`.
* A sub-agent with tools gets `max_loops=5`, and one without gets `max_loops=1`, as here. Sub-agents never run in `"auto"` mode, so they cannot start sub-agents of their own.
* The lead's registry is created on first use with `max_depth=3`.

See [Autonomous mode](https://docs.swarms.world/agents/autonomous-mode.md) for the rest of the autonomous tools.

## Tips

* **Keep the ids from `spawn()`.** They are the only way to tie a result to its task.
* **Size the pool with `max_workers`.** The default comes from Python's `ThreadPoolExecutor`. One agent call holds a thread for its whole run.
* **Call `shutdown()`** when you are done. Spawning after `shutdown()` raises `RuntimeError`.

## Next steps

* [SubagentRegistry reference](https://docs.swarms.world/api/async-subagent.md)
* [Autonomous mode](https://docs.swarms.world/agents/autonomous-mode.md)
* [Multi-agent execution utilities](https://docs.swarms.world/api/multi-agent-execution-utilities.md), to run agents in parallel and wait for all of them in one call


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