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

# ForestSwarm Guide

> Group specialist agents into trees and send each task to the one agent whose system prompt matches it

A `ForestSwarm` holds trees of agents. Each `Tree` groups the agents for one domain, such as tax or investing. When a task comes in, the forest walks its trees in order and hands the task to the first agent that matches it. No model makes the choice: matching uses keywords taken from each agent's system prompt, then the embedding similarity between the task and that prompt. One agent answers each task.

`ForestSwarm`, `Tree` and `TreeAgent` are not exported from the top-level `swarms` package. Import them from `swarms.structs.tree_swarm`.

Reference: [ForestSwarm](https://docs.swarms.world/api/forest-swarm.md).

## How an agent is picked

| Step | What happens |
| - | - |
| Build a `TreeAgent` | It embeds its system prompt once and keeps the five most frequent words of the prompt as keywords. One-letter words and common stop words are dropped. |
| Build a `Tree` | It gives each agent a distance to the agent listed before it, then sorts its agents by that distance. |
| Run a task | The forest checks its trees in the order you gave, and each tree's agents in sorted order. An agent matches when one of its keywords appears as a word in the task. If none does, the task is embedded and the agent matches when the cosine similarity is 0.7 or more. |
| Answer | The first agent that matches runs the task on a fresh conversation, and its output is returned. |

## 1. Build a forest and run a task

Each specialist is a `TreeAgent`: a regular `Agent` with an embedding model for its system prompt. Put the domain words you want to match at the start of the prompt and repeat the most important one. The keywords are the five most frequent words, and ties go to the word that comes first.

```python theme={null}
from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent


def specialist(name: str, system_prompt: str) -> TreeAgent:
    """Build a one-loop tree agent that embeds its prompt with text-embedding-3-small."""
    return TreeAgent(
        agent_name=name,
        system_prompt=system_prompt,
        model_name="gpt-5.4-mini",
        embedding_model_name="text-embedding-3-small",
        max_loops=1,
    )


tax_tree = Tree(
    tree_name="Tax",
    agents=[
        specialist(
            "Corporate-Tax-Advisor",
            "Corporate tax advisor. Corporate tax filing, Delaware "
            "corporations, deductions, quarterly estimated tax.",
        ),
        specialist(
            "Personal-Tax-Advisor",
            "Personal tax advisor. Income tax returns, tax credits, "
            "filing status, refunds for individuals.",
        ),
    ],
)

investing_tree = Tree(
    tree_name="Investing",
    agents=[
        specialist(
            "Stock-Analyst",
            "Stock analyst. Stocks, earnings, valuation, sectors, market trends.",
        ),
        specialist(
            "Retirement-Planner",
            "Retirement planner. Retirement savings, 401k, Roth IRA, "
            "pension, withdrawal plans.",
        ),
    ],
)

forest = ForestSwarm(
    name="Finance-Forest",
    description="Routes finance questions to one specialist",
    trees=[tax_tree, investing_tree],
)

answer = forest.run(
    "How should a small Delaware corporation plan its quarterly estimated tax payments?"
)
print(answer)
```

The task contains `tax` and `delaware`, two of the Corporate-Tax-Advisor's keywords, so that agent answers.

> [!WARNING]
>
> The default embedding model is `text-embedding-ada-002`. In our tests it scored unrelated text above 0.7, so the first agent in the first tree matched almost every task, including a question about stocks and one about retirement accounts. `text-embedding-3-small` scores unrelated text far lower, so routing follows the keywords and the embedding check passes only on a close match. Set `embedding_model_name` on every agent.

## 2. Check the routing before you run

`find_relevant_tree()` and `Tree.find_relevant_agent()` run the same matching as `run()` without calling the language model. Use them to test your system prompts. They do call the embedding model for any agent whose keywords miss.

```python theme={null}
for tree in forest.trees:
    for agent in tree.agents:
        print(tree.tree_name, agent.agent_name, agent.relevant_keywords)

tasks = [
    "Should I move my 401k into a Roth IRA before I retire?",
    "Which sectors drove the latest earnings season?",
    "What is a good recipe for banana bread?",
]

for task in tasks:
    tree = forest.find_relevant_tree(task)
    agent = tree.find_relevant_agent(task) if tree else None
    print(task)
    print("  tree:", tree.tree_name if tree else None)
    print("  agent:", agent.agent_name if agent else None)
```

The keywords print as, for example, `['retirement', 'planner', 'savings', '401k', 'roth']`. The first task goes to Retirement-Planner through `401k` and `roth`, and the second to Stock-Analyst through `earnings`. Nothing matches the banana bread question, so both lookups return `None`.

## 3. Run several tasks

`batched_run()` calls `run()` once per task and returns the results in task order.

```python theme={null}
results = forest.batched_run(tasks)

for task, result in zip(tasks, results):
    print(f"=== {task}\n{result[:300]}\n")
```

The banana bread task returns the string `"No relevant agent found to handle this task."` instead of an answer.

> [!WARNING]
>
> `batched_run()` also accepts `max_workers` to run tasks in threads. Leave it unset when two tasks can reach the same agent. A `TreeAgent` has one conversation, and in our test two tasks that ran at the same time on the same agent came back with the same answer.

## Reading the output

* **One answer per task.** `run()` returns the selected agent's output, shaped by that agent's `output_type` (the `Agent` default is `"str-all-except-first"`). The agent is reset before each task, so the output covers only this task.
* **No match.** `run()` returns `"No relevant agent found to handle this task."`
* **Errors.** `run()` never raises. If routing or the agent fails, it returns `None`. Pass `verbose=True` to the forest to see the error in the log.
* **No shared history.** The forest's `conversation` is not updated by `run()`. Keep your own record of which agent answered, using `find_relevant_tree()` as in step 2.
* **Token usage.** `forest.usage` sums the provider token usage of every agent in every tree.

## Tips

* **Order matters.** The first match wins and agents are not ranked against each other. Put the most specific trees first.
* **Keep keywords specific.** A keyword such as `advisor` or `planner` matches any task that uses the word. Name agents and write prompts so the frequent words are domain terms.
* **Building costs one embedding call per agent.** Build the forest once and reuse it.

## Next steps

* [ForestSwarm reference](https://docs.swarms.world/api/forest-swarm.md)
* [SwarmRouter guide](https://docs.swarms.world/examples/swarm-router-example.md) for routing with a model instead of keywords
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/forest_swarm_examples)


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