semantic-router

repository·main·Indexed 26 days ago

https://github.com/aurelio-labs/semantic-router

A high-speed decision-making layer for LLMs and agents that uses semantic vector space to route requests based on meaning. It provides a faster alternative to LLM generation for determining tool use or intent. Supports multiple encoders including OpenAI, Cohere, Hugging Face, and FastEmbed, and integrates with vector stores like Pinecone and Qdrant.

Tokens
69.8K
Snippets
213
Records
325
Agent score
81%

What's inside semantic-router

  1. Overview of Semantic Router Integrations

    main

    Semantic Router supports four main categories of integrations:

    1. Encoder Integrations: Provides embedding models for semantic similarity. Supports Cloud providers (Jina AI, OpenAI, Cohere, Voyage, Mistral, NVIDIA, Bedrock, Aurelio) and Local/Self-hosted options (Local sentence-transformers, Ollama, Hugging Face, FastEmbed). All encoders support synchronous and asynchronous operations.
    2. Index Integrations: Enables efficient vector storage and retrieval. Supports Pinecone, Qdrant, PostgreSQL (with pgvector), and a Local in-memory index. Supports CRUD operations and route isolation via namespaces/collections.
    3. LLM Integrations: Enables dynamic route generation and decision-making. Supported providers include OpenAI, Azure OpenAI, Mistral, Bedrock, and LiteLLM.
    4. Framework Integrations: Works with popular frameworks like Pydantic AI, LiteLLM, LangChain, and LlamaIndex.
  2. Introduction to Semantic Router

    main
    Semantic Router is a high-speed decision-making layer designed for LLMs and agents. It uses semantic vector space to route requests based on meaning, allowing for millisecond-level decisions instead of waiting for slow LLM generations. This helps reduce latency and costs by avoiding expensive LLM inference for simple routing tasks.
  3. Understand Semantic Router Core Components

    main

    Semantic Router operates using three primary components:

    1. Encoders: Transform inputs (text, images) into vector representations.
      • Dense Encoders: Generate continuous vectors (e.g., OpenAIEncoder, HuggingFaceEncoder, CLIPEncoder).
      • Sparse Encoders: Generate sparse vectors (e.g., BM25Encoder, TFIDFEncoder, AurelioSparseEncoder).
      • Multimodal Encoders: Handle both images and text (e.g., CLIPEncoder).
    2. Routes: Define the patterns to match. A Route consists of a name, a list of utterances (example inputs), and optional score_threshold, function_schemas, or metadata.
    3. Indexing Systems: Efficiently store and retrieve route vectors.
      • LocalIndex / HybridLocalIndex: In-memory storage.
      • Cloud/External Indexes: PineconeIndex, QdrantIndex, or PostgresIndex for scalable vector storage.
  4. Understand the difference between Static and Dynamic Routes

    main

    In semantic-router, there are two types of routes within the Route object:

    1. Static Routes: When triggered, they simply return the Route.name.
    2. Dynamic Routes: When triggered, they use an LLM call to extract parameter values from the user's input. These extracted values can be used to call an associated function.

    Dynamic routes require providing function_schemas (a list of schemas describing the functions) so the LLM knows how to map natural language to function arguments.

  5. Execution modes in Semantic Router

    main

    Semantic Router can be deployed in three different execution modes depending on your latency, cost, and privacy requirements:

    • Cloud-based: Uses API-based embeddings from providers like OpenAI or Cohere.
    • Hybrid: Combines local embeddings with API-based LLMs.
    • Fully local: Runs everything on your machine using local models like Llama or Mistral, ensuring no external API dependencies.
  6. Understand Semantic Routing Concepts

    main
    Semantic Routing directs inputs (text, images, or audio) to specific handlers based on their semantic meaning rather than exact keyword matching. It uses a high-dimensional mathematical space (semantic space) where similar concepts are represented by vectors that are geometrically close to one another. This allows the system to handle synonyms, paraphrases, and natural language variability gracefully.
  7. Quickstart: Define routes and use SemanticRouter

    main

    Semantic Router allows you to define decision paths using Route objects and then use a SemanticRouter to classify queries based on their semantic meaning.

    1. Define Routes: Create Route objects with a name and a list of utterances (example phrases).
    2. Initialize Encoder: Use an encoder like CohereEncoder or OpenAIEncoder (requires API keys in environment variables).
    3. Create Router: Initialize SemanticRouter with your encoder and routes.
    4. Route Queries: Call the router instance with a string. It returns a route object containing the .name of the matched route, or None if no match is found.
    from semantic_router import Route
    from semantic_router.encoders import OpenAIEncoder
    from semantic_router.routers import SemanticRouter
    import os
    
    # 1. Define routes
    politics = Route(
        name="politics",
        utterances=[
            "isn't politics the best thing ever",
            "why don't you tell me about your political opinions",
        ],
    )
    
    chitchat = Route(
        name="chitchat",
        utterances=[
            "how's the weather today?",
            "how are things going?",
        ],
    )
    
    routes = [politics, chitchat]
    
    # 2. Initialize encoder
    os.environ["OPENAI_API_KEY"] = "<YOUR_API_KEY>"
    encoder = OpenAIEncoder()
    
    # 3. Create router
    rl = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local")
    
    # 4. Use router
    print(rl("don't you love politics?").name)  # Output: 'politics'
    print(rl("how's the weather today?").name) # Output: 'chitchat'
    print(rl("I'm interested in learning about llama 2").name) # Output: None
  8. Install semantic-router

    main

    Install the core package using pip:

    pip install -qU semantic-router

    Optional Dependencies

    • Local Execution: To use a fully local version with HuggingFaceEncoder and LlamaCppLLM:
      pip install -qU "semantic-router[local]"
    • Hybrid Routing: To use the HybridRouteLayer:
      pip install -qU "semantic-router[hybrid]"
    pip install -qU semantic-router
  9. Use Dynamic Routes with function calling

    main

    Dynamic routes allow the router to perform function calling by providing function_schemas. You can generate these schemas using get_schema from semantic_router.utils.function_call.

    When a query matches a route with a schema, the SemanticRouter returns a RouteChoice containing the function_call arguments, which can be unpacked into your local Python function.

  10. Implement Guardrails with HybridRouter

    main

    Use HybridRouter to detect specific query types (e.g., allowed vs blocked) to control agent behavior. HybridRouter combines a dense encoder (like OpenAIEncoder) and a sparse encoder (like AurelioSparseEncoder) for higher accuracy in distinguishing similar queries with different keywords.

    from semantic_router import Route
    from semantic_router.routers import HybridRouter
    from semantic_router.encoders import OpenAIEncoder
    from semantic_router.encoders.aurelio import AurelioSparseEncoder
    
    # Define guardrail routes
    allowed = Route(
        name="allowed",
        utterances=["Tell me about the product", "What features does it have?"]
    )
    
    blocked = Route(
        name="blocked",
        utterances=["Can you give me a discount?", "I'll pay in bitcoin"]
    )
    
    # Initialize hybrid router for better accuracy
    encoder = OpenAIEncoder(name="text-embedding-3-small", score_threshold=0.3)
    sparse_encoder = AurelioSparseEncoder(name="bm25")
    
    router = HybridRouter(
        encoder=encoder,
        sparse_encoder=sparse_encoder,
        routes=[allowed, blocked],
        auto_sync="local"
    )