Skip to main content

Overview

The AgentRouter is an embedding-based routing system that intelligently matches tasks to the most appropriate specialized agent using cosine similarity on embeddings. It uses LiteLLM’s embedding models to generate vector representations of both agents and tasks, enabling semantic matching for optimal agent selection. When a task is submitted, the router:
  1. Generates an embedding vector for the task
  2. Calculates cosine similarity between the task embedding and all agent embeddings
  3. Returns the agent with the highest similarity score
  4. Optionally updates agent embeddings with interaction history for improved matching over time

Installation

Class Definition

Attributes

str
default:"text-embedding-ada-002"
The embedding model to use for generating embeddings. Supports various models like text-embedding-3-small, text-embedding-3-large, cohere/embed-english-v3.0, huggingface/microsoft/codebert-base, etc.
int
default:"1"
Number of agents to return in queries (currently supports returning the best match)
Optional[str]
default:"None"
API key for the embedding service. If not provided, will use environment variables.
Optional[str]
default:"None"
Custom API base URL for the embedding service.
Optional[List[AgentType]]
default:"None"
List of agents to initialize the router with. Each agent should have name, description, and system_prompt attributes.

Methods

add_agent()

Add a single agent to the router. The agent will be embedded using its name, description, and system prompt.
Parameters:
  • agent (AgentType): The agent to add. Must have name, description, and system_prompt attributes.
Raises:
  • Exception: If there’s an error generating the embedding or adding the agent.

add_agents()

Add multiple agents to the router at once.
Parameters:
  • agents (List[Union[AgentType, Callable, Any]]): List of agents to add.

find_best_agent()

Find the best matching agent for a given task using cosine similarity on embeddings.
Parameters:
  • task (str): The task description to match against agents.
Returns: The best matching agent if found, None otherwise.

run()

Convenience method that calls find_best_agent. Run the agent router on a given task.
Parameters:
  • task (str): The task description to match against agents.
Returns: The best matching agent if found, None otherwise.

update_agent_history()

Update the agent’s embedding in the router with its interaction history. This allows the router to learn from past interactions and improve matching over time.
Parameters:
  • agent_name (str): The name of the agent to update.
This method updates the agent’s embedding to include its conversation history, which can improve future routing decisions based on what the agent has learned or discussed.

Usage Examples

Basic Medical Use Case

Finance Analysis Use Case

Custom Embedding Model

Dynamic Agent Addition

Best Practices

Agent Descriptions

Provide clear, specific descriptions for agents to improve matching accuracy:

Embedding Model Selection

Error Handling

Always handle cases where no agent is found:

Performance Considerations

  1. Embedding Generation: The first time agents are added, embeddings are generated which can take a few seconds per agent
  2. API Rate Limits: Be aware of rate limits when using embedding APIs, especially when adding many agents
  3. Caching: The router doesn’t cache task embeddings — consider caching results for repeated tasks
  4. Batch Processing: For processing multiple tasks, consider batching or using concurrent execution

Troubleshooting

No Agent Found

If find_best_agent returns None:
  1. Check that agents have been added: len(router.agents) > 0
  2. Verify agent descriptions are clear and specific
  3. Ensure the task description is detailed enough to match an agent
  4. Check logs for embedding generation errors

Low Similarity Scores

If agents are being matched but with low similarity:
  1. Improve agent descriptions to be more specific
  2. Enhance system prompts with more relevant keywords
  3. Consider using a different embedding model
  4. Update agent history after interactions to improve matching

Source Code

View the source code on GitHub