Skip to main content
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.

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

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 asks a model to pick the agent and runs it for you.

Next steps