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

# AgentRouter Guide

> Pick the best agent for each task by embedding similarity, then run it: build a router, route a queue of tickets, and refine routing with an agent's history

An `AgentRouter` picks the agent best suited to a task. When you add an agent, the router embeds its name, description and system prompt. When a task comes in, it embeds the task and returns the agent whose embedding is closest by cosine similarity. The router does not run the agent: `run()` returns the agent object, and you call its `run()` yourself.

Because routing uses embeddings, not a chat model, picking an agent is one cheap embedding call per task.

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

## 1. Route a task to the right agent

Give each agent a specific `agent_description` and `system_prompt`; they are what the router compares the task with. `AgentRouter` is imported from `swarms.structs.agent_router`.

```python theme={null}
from swarms import Agent
from swarms.structs.agent_router import AgentRouter

billing = Agent(
    agent_name="Billing-Agent",
    agent_description="Handles invoices, refunds, payment methods and subscription charges.",
    system_prompt="You answer billing questions: invoices, refunds, card payments and plan charges.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)
tech_support = Agent(
    agent_name="Tech-Support-Agent",
    agent_description="Fixes login problems, app crashes, error messages and sync issues.",
    system_prompt="You troubleshoot software problems step by step.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)
shipping = Agent(
    agent_name="Shipping-Agent",
    agent_description="Tracks orders, delivery dates, lost parcels and returns shipping.",
    system_prompt="You answer questions about order tracking, delivery and returns shipping.",
    model_name="gpt-5.4-mini",
    max_loops=1,
)

router = AgentRouter(agents=[billing, tech_support, shipping])

question = "I was charged twice for my monthly plan. Can I get one charge refunded?"
best_agent = router.run(question)

print(f"Routed to: {best_agent.agent_name}")
print(best_agent.run(question))
```

```text theme={null}
Routed to: Billing-Agent
I can help with that. In many cases, duplicate monthly plan charges can be reviewed ...
```

The router logs the winning score, for example `Found best matching agent: Billing-Agent (similarity: 0.7915)`. The default `embedding_model` is `"text-embedding-ada-002"`, which uses your `OPENAI_API_KEY`.

## 2. Route a queue of tasks

Here a second router uses another embedding model and gets its agents one at a time with `add_agent()`. A router with no agents returns `None`, so check the result before you call it. `find_best_agent()` is the same call as `run()`. This block reuses the agents from section 1:

```python theme={null}
small_router = AgentRouter(embedding_model="text-embedding-3-small")
print(small_router.run("Where is my parcel?"))

for agent in [billing, tech_support, shipping]:
    small_router.add_agent(agent)

tickets = [
    "The app logs me out every time I open it on my phone.",
    "My order was due Tuesday and the tracking page has not moved since Friday.",
    "How do I change the card my subscription is billed to?",
]

for ticket in tickets:
    agent = small_router.find_best_agent(ticket)
    print(f"{agent.agent_name:<20} <- {ticket}")
```

```text theme={null}
None
Tech-Support-Agent   <- The app logs me out every time I open it on my phone.
Shipping-Agent       <- My order was due Tuesday and the tracking page has not moved since Friday.
Billing-Agent        <- How do I change the card my subscription is billed to?
```

Any LiteLLM embedding model works, such as `"text-embedding-3-large"` or `"cohere/embed-english-v3.0"`. Pass `api_key` and `api_base` to use a key or endpoint other than the environment's. Use one embedding model per router: every agent and task must be embedded by the same model to be compared.

## 3. Learn from what an agent has handled

`update_agent_history(agent_name)` embeds the agent again, this time with its conversation history added to its name, description and system prompt. Tasks like the ones it has already answered then score closer to it. After the Billing-Agent answered the question in section 1:

```python theme={null}
before = router.agent_metadata[0]["text"]
router.update_agent_history("Billing-Agent")
after = router.agent_metadata[0]["text"]

print(len(before), "->", len(after))
print(router.run("I see two identical charges on my card statement.").agent_name)
```

```text theme={null}
163 -> 866
Billing-Agent
```

`agent_metadata` holds the text the router embedded for each agent, in the order they were added. An unknown name logs a warning and changes nothing.

## Reading the output

| Call | Returns |
| - | - |
| `router.run(task)`, `router.find_best_agent(task)` | The best-matching agent object, or `None` if the router has no agents |
| `best_agent.run(task)` | That agent's output, shaped by the agent's own `output_type` |
| `router.agents` | The routed agents, in the order they were added |
| `router.agent_metadata` | One `{"name", "text"}` dict per agent: the text that was embedded |

The router always returns its closest agent, however low the score. If some tasks should go to nobody, screen them before routing.

## Tips

* **Write distinct descriptions.** Agents with similar descriptions and prompts get similar embeddings, and the router will mix them up.
* **Expect retries.** `add_agent()` and `find_best_agent()` retry up to three times with a 4 to 10 second backoff. When every attempt fails, they raise `tenacity.RetryError`.
* **Embed once.** Adding agents is the slow part, one embedding call each. Build the router once and reuse it for every task.
* **Want an LLM to choose instead?** [MultiAgentRouter](https://docs.swarms.world/api/multi-agent-router.md) asks a model to pick the agent and runs it for you.

## Next steps

* [AgentRouter reference](https://docs.swarms.world/api/agent-router.md)
* [ModelRouter guide](https://docs.swarms.world/examples/multi-agent/model-router-example.md), to route tasks to models instead of agents
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/agent_router_examples)


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