# Aurelio Docs (/docs) Welcome to the Aurelio documentation. Choose a library to get started: * [Semantic Router](/docs/semantic-router) — superfast decision-making layer for LLMs and agents. * [Semantic Chunkers](/docs/semantic-chunkers) — chunk documents by meaning for better retrieval. * [GraphAI](/docs/graphai) — build async, graph-based AI workflows and agents. # Semantic Router v1 (/docs/semantic-router/v1) Superfast decision-making layer for LLMs and agents. ## Sections [#sections] * [Get Started](/docs/semantic-router/v1/get-started/introduction) * [Client Reference](/docs/semantic-router/v1/client-reference/calibration) * [User Guide](/docs/semantic-router/v1/user-guide/changelog) # Introduction (/docs/semantic-router/v1/get-started/introduction) Semantic Router is a superfast decision layer for LLMs and agents. Most tools make routing decisions by asking an LLM and waiting for it to answer. That's slow. Semantic Router decides in milliseconds: it compares the *meaning* of an input against your routes in vector space, or asks a small decision model that answers in a single fast call. The payoff is simple. Decisions land in milliseconds, not seconds. You skip an LLM call, so you cut cost. And because routes are explicit, you stay in control of what happens next. ## How it works [#how-it-works] You define routes: the decisions your app can make. Each one has a few example phrases and, if you like, a plain description. A router scores every route for an incoming request and hands back the best one, with a confidence. There are a few kinds of router, and they all behave the same way: * **`IndexedRouter`** embeds your example utterances once, up front. At runtime it matches each request to the closest route by meaning. Give it a sparse encoder as well and it becomes a hybrid router that also weighs exact keywords. * **`DecisionRouter`** asks a decision model which route applies: TypeSafe's Jev, or any model that speaks the same API. It needs no index and no embeddings, because it reads your route descriptions. * **`Chain`** and **`Merge`** are routers made of routers. A Chain tries a fast router first and only falls through to a slower one when the fast one isn't sure. A Merge asks several routers at once and averages their answers. ## Confidence you can act on [#confidence-you-can-act-on] Every router returns a `confidence` with its choice. Call `fit()` with a few dozen labelled example queries and the router learns to turn its raw scores into probabilities. After that, a confidence of 0.85 means the route is right about 85% of the time. So you can set a threshold from a policy ("only act when you're 90% sure") instead of guessing at similarity scores. ## What you can build [#what-you-can-build] * **Intent routing** for chatbots and agents: send each message to the right tool, prompt or team. * **Guardrails**: catch off-topic, unsafe or out-of-scope requests before they reach an LLM. * **Multi-modal routing**: route on images as well as text. * **Production scale**: keep your routes in Pinecone, Qdrant or Postgres, and share one index between many routers. It works with the encoders you already use: OpenAI, Cohere, Hugging Face, FastEmbed, and more. With a local encoder like FastEmbed, routing runs entirely on your machine. ## Start here [#start-here] New to Semantic Router? The [quickstart](quickstart) gets you routing in a few minutes, with no API keys. Upgrading from 0.x? Version 1 is a breaking release. The [migration guide](../user-guide/guides/migration-to-v1) covers every change, with before and after code. The 0.x docs stay online: see [versions](versions). ## Resources [#resources] * [GitHub repository](https://github.com/aurelio-labs/semantic-router) * [Online course](https://www.aurelio.ai/course/semantic-router) # Quickstart (/docs/semantic-router/v1/get-started/quickstart) Semantic Router sends text to the right handler based on *meaning*, not keywords. That makes it a good fit for chatbots, intent classification and guardrails: anything that needs to understand what a user is actually asking. This quickstart runs entirely on your machine. It uses a small local embedding model through FastEmbed, so you don't need any API keys. ```bash pip install -qU "semantic-router[fastembed]>=1.0.0" ``` ## Define your routes [#define-your-routes] A `Route` is a decision you want the router to make. You describe it with example utterances: a few phrases a user might say. Those examples become the route's reference point in semantic space. Let's start with two: one for *politics*, one for *chitchat*. ```python from semantic_router import Route # use this to steer a chatbot away from political conversation politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "they're going to destroy this country!", "they will save the country!", ], ) # and this to switch the chatbot into a more conversational mode chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` ## Pick an encoder [#pick-an-encoder] An encoder turns text into a vector, so the router can measure how close two pieces of text are in meaning. We'll use a small local model. The first call downloads it (about 70 MB). ```python from semantic_router.encoders import FastEmbedEncoder encoder = FastEmbedEncoder(name="BAAI/bge-small-en-v1.5") ``` Semantic Router supports plenty of others: OpenAI, Cohere, Hugging Face, and more. The [encoders guide](../user-guide/components/encoders) has the full list. ## Create the router [#create-the-router] An `IndexedRouter` embeds every utterance once, stores them in an index, and matches each query against them. Hand it your encoder and routes: ```python from semantic_router import IndexedRouter router = IndexedRouter(encoder=encoder, routes=routes) ``` With no index given, it keeps the vectors in memory. The [indexes guide](../user-guide/components/indexes) shows how to use Pinecone, Qdrant or Postgres instead. ## Route a query [#route-a-query] Call the router with a query. It embeds the query and scores it against every route. ```python router("don't you love politics?") ``` ``` [Out]: RouteChoice(name='politics', confidence=0.6717691933713713, calibrated=False) ``` You get back a `RouteChoice`: the route's `name`, a `confidence`, and `calibrated`, which says whether that confidence is a probability. Right now it isn't: it's the raw similarity between the query and the route's utterances. ```python router("how's the weather today?") ``` ``` [Out]: RouteChoice(name='chitchat', confidence=0.8048876076635829, calibrated=False) ``` Both correct, even though neither query matches an utterance word for word. ## When nothing should match [#when-nothing-should-match] Now send something unrelated: ```python router("I'm interested in learning about llama 2") ``` ``` [Out]: RouteChoice(name='politics', confidence=0.46913750545106614, calibrated=False) ``` It picked a route anyway. That's the default: **with no threshold set, the best route always wins**, however weak the match. To let the router say "none of these", give it a bar to clear. You could set a raw similarity bar by hand, but the right number depends on the encoder, the routes and your data. Calibration finds it for you. ## Calibrate the confidence [#calibrate-the-confidence] `fit()` takes some labelled example queries and learns to turn the router's raw scores into probabilities. Use queries the router hasn't seen, *not* the utterances you gave the routes. Label the ones that shouldn't match any route with `None`. ```python X = [ "who should I vote for in the election?", "what do you think of the prime minister?", "is the government doing a good job?", "tell me your opinion on the new tax law", "are you left wing or right wing?", "the opposition party is a joke", "nice day out, isn't it?", "it's freezing outside", "how was your weekend?", "fancy grabbing some fish and chips?", "what a lovely sunny afternoon", "how have you been?", "how do I reset my password?", "what's the capital of australia?", "write me a python function to sort a list", "what is the boiling point of water?", "recommend a good sci-fi book", "how many legs does a spider have?", ] y = ["politics"] * 6 + ["chitchat"] * 6 + [None] * 6 router.fit(X=X, y=y) ``` ``` [Out]: FitReport(method='platt', n=18, accuracy=0.9166666666666666, ece=0.23736602563869935) ``` The report gives the top-route accuracy on your examples and the calibration error (`ece`, lower is better). Eighteen examples is enough to see it work. For a real app, use a few dozen per route. Now confidences are probabilities: ```python router("don't you love politics?") ``` ``` [Out]: RouteChoice(name='politics', confidence=0.9295308430490237, calibrated=True) ``` ## Set a threshold [#set-a-threshold] Set a `confidence_threshold`, and a route only wins if its confidence clears it. Because the router is calibrated, 0.5 means "only answer when it's more likely right than wrong". ```python router.confidence_threshold = 0.5 router("I'm interested in learning about llama 2") ``` ``` [Out]: RouteChoice(name=None, confidence=None, calibrated=True) ``` No route cleared the bar, so `name` is `None`. Treat that as your fallback signal: pass the query through, send it to a default handler, whatever fits your app. The on-topic queries still route: ```python router("how's the weather today?") ``` ``` [Out]: RouteChoice(name='chitchat', confidence=0.9937006111667317, calibrated=True) ``` You can also pass `confidence_threshold=` when you build the router, and give any single route its own bar with `Route(confidence_threshold=...)`. The [calibration guide](../user-guide/features/calibration) covers both. ## Next steps [#next-steps] * [Routes](../user-guide/components/routes) and [routers](../user-guide/components/routers): every option, including hybrid search. * [Calibration](../user-guide/features/calibration): how `fit()` works, and choosing between Platt and isotonic. * [Decision models](../user-guide/features/decision-models) and [Chain and Merge](../user-guide/features/composition): when an embedding match isn't enough. * Coming from 0.x? Read the [migration guide](../user-guide/guides/migration-to-v1). # Versions (/docs/semantic-router/v1/get-started/versions) Semantic Router has two release lines. Pick the one that matches the version you have installed, and use the version switcher to read the matching docs. ## v1: the 1.x line [#v1-the-1x-line] You're reading the v1 docs. Version 1 rebuilds the routing layer around three ideas: * **Calibrated confidence.** `fit()` turns raw scores into probabilities, so a threshold means what it says. * **More than one kind of router.** `IndexedRouter` matches by embedding, `DecisionRouter` asks a decision model, and every router follows the same contract. * **Composition.** `Chain` and `Merge` build routers out of routers. It's a breaking release: the router classes, thresholds and sync all change, and dynamic routes are gone. The [migration guide](../user-guide/guides/migration-to-v1) covers every change, with before and after code. ```bash pip install -qU "semantic-router>=1,<2" ``` The 1.x source lives on the [`main` branch](https://github.com/aurelio-labs/semantic-router). ## v0: the 0.x line [#v0-the-0x-line] The 0.x releases are the library as it shipped from 2023 to 2026: `SemanticRouter`, `HybridRouter`, `score_threshold`, dynamic routes and index sync. The final feature release of this line is **0.3.0**. From then on it gets bug fixes only, on the [`v0` branch](https://github.com/aurelio-labs/semantic-router/tree/v0). Install it with an upper bound, so an upgrade never moves you to 1.x by accident: ```bash pip install -qU "semantic-router<1" ``` The [v0 docs](../../v0/get-started/introduction) stay online. ## Which one should I use? [#which-one-should-i-use] * **Starting something new?** Use 1.x. * **Running 0.x in production?** Nothing changes until you choose to upgrade. Pin `semantic-router<1`, keep using the v0 docs, and move over with the [migration guide](../user-guide/guides/migration-to-v1) when you're ready. * **Contributing?** Fixes for 0.x go to `v0`; everything else goes to `main`. See [Contributing](https://github.com/aurelio-labs/semantic-router/blob/main/CONTRIBUTING.md). # semantic_router.calibration (/docs/semantic-router/v1/client-reference/calibration) turn a raw router score into P(route is correct). monotonic, so ranking never changes. ## Calibrator Objects [#calibrator-objects] ```python class Calibrator() ``` a fitted score -> probability map. build one with `Calibrator.fit`. #### ece [#ece] ```python def ece(probs: np.ndarray, correct: np.ndarray, bins: int = 10) -> float ``` expected calibration error: bin-weighted gap between stated confidence and observed accuracy. # semantic_router.config (/docs/semantic-router/v1/client-reference/config) save a router to a yaml or json file and load it back. `router_type` picks the shape. keys and secrets are never written: a loaded router reads them from the environment (`OPENAI_API_KEY`, `JEV_API_KEY`, `PINECONE_API_KEY`...), as it would if built in code. a decision router's model is saved like an index: its type, and its non-default params. an indexed router on a remote index (pinecone, postgres, a qdrant server) is saved without its routes: the index holds them and stays the single source of truth, so the file only names the index. an in-memory index keeps nothing between runs, so its file carries routes. #### to\_config [#to_config] ```python def to_config(router: BaseRouter) -> RouterConfig ``` describe a router as a config, the shape a file holds. keys and secrets are left out. #### from\_config [#from_config] ```python def from_config(config: RouterConfig | dict[str, Any]) -> BaseRouter ``` build the router a config describes. keys and secrets come from the environment. #### save\_router [#save_router] ```python def save_router(router: BaseRouter, path: str | Path, format: Format | None = None) -> None ``` write a router to a file; the format follows the extension unless given. #### load\_router [#load_router] ```python def load_router(path: str | Path) -> BaseRouter ``` build a router from a yaml or json file written by `to_yaml` or `to_json`. the file's `router_type` picks the class: IndexedRouter, DecisionRouter, Chain or Merge. # semantic_router.linear (/docs/semantic-router/v1/client-reference/linear) #### similarity\_matrix [#similarity_matrix] ```python def similarity_matrix(xq: np.ndarray, index: np.ndarray) -> np.ndarray ``` Compute the similarity scores between a query vector and a set of vectors. **Arguments**: * `xq`: A query vector (1d ndarray) * `index`: A set of vectors. **Returns**: `np.ndarray`: The similarity between the query vector and the set of vectors. #### top\_scores [#top_scores] ```python def top_scores(sim: np.ndarray, top_k: int = 5) -> Tuple[np.ndarray, np.ndarray] ``` Get the top scores and indices from a similarity matrix. **Arguments**: * `sim`: A similarity matrix. * `top_k`: The number of top scores to get. **Returns**: `Tuple[np.ndarray, np.ndarray]`: The top scores and indices. # semantic_router.route (/docs/semantic-router/v1/client-reference/route) ## Route Objects [#route-objects] ```python class Route(BaseModel) ``` A route: one decision a router can make, and what tells it when to make it. **Arguments**: * `name` (`str`): The name of the route. * `utterances` (`List[Any]`): Example queries for the route. Indexed routers embed these; a decision router only reads them when the route has no description. * `description` (`Optional[str]`): What the route covers, stated literally. Decision routers read it. * `confidence_threshold` (`Optional[float]`): The confidence a router needs before it returns this route. It overrides the router's own confidence\_threshold. * `metadata` (`Dict[str, Any]`): Anything else to keep with the route. #### to\_dict [#to_dict] ```python def to_dict() -> Dict[str, Any] ``` Convert the route to a dictionary. **Returns**: `Dict[str, Any]`: The dictionary representation of the route. #### from\_dict [#from_dict] ```python @classmethod def from_dict(cls, data: Dict[str, Any]) -> "Route" ``` Create a Route object from a dictionary. **Arguments**: * `data` (`Dict[str, Any]`): The dictionary to create the route from. **Returns**: `Route`: The created route. # semantic_router.schema (/docs/semantic-router/v1/client-reference/schema) ## EncoderType Objects [#encodertype-objects] ```python class EncoderType(Enum) ``` The type of encoder. ## EncoderInfo Objects [#encoderinfo-objects] ```python class EncoderInfo(BaseModel) ``` Information about an encoder. ## RouteChoice Objects [#routechoice-objects] ```python class RouteChoice(BaseModel) ``` A route choice output by the routers. ## Utterance Objects [#utterance-objects] ```python class Utterance(BaseModel) ``` One record in an index: a route name, one of its utterances, and the record's metadata (the route's own metadata plus the reserved `sr_` keys). ## Metric Objects [#metric-objects] ```python class Metric(Enum) ``` The metric to use in vector-based similarity search indexes. ## SparseEmbedding Objects [#sparseembedding-objects] ```python class SparseEmbedding(BaseModel) ``` Sparse embedding interface. Primarily uses numpy operations for faster operations. #### from\_compact\_array [#from_compact_array] ```python @classmethod def from_compact_array(cls, array: np.ndarray) ``` Create a SparseEmbedding object from a compact array. **Arguments**: * `array` (`np.ndarray`): A compact array. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_vector [#from_vector] ```python @classmethod def from_vector(cls, vector: np.ndarray) ``` Consumes an array of sparse vectors containing zero-values. **Arguments**: * `vector` (`np.ndarray`): A sparse vector. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_aurelio [#from_aurelio] ```python @classmethod def from_aurelio(cls, embedding: "BM25SparseEmbedding") ``` Create a SparseEmbedding object from an AurelioSparseEmbedding object. **Arguments**: * `embedding` (`BM25SparseEmbedding`): An AurelioSparseEmbedding object. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_dict [#from_dict] ```python @classmethod def from_dict(cls, sparse_dict: dict) ``` Create a SparseEmbedding object from a dictionary. **Arguments**: * `sparse_dict` (`dict`): A dictionary of sparse values. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_pinecone\_dict [#from_pinecone_dict] ```python @classmethod def from_pinecone_dict(cls, sparse_dict: dict) ``` Create a SparseEmbedding object from a Pinecone dictionary. **Arguments**: * `sparse_dict` (`dict`): A Pinecone dictionary. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### to\_dict [#to_dict] ```python def to_dict() ``` Convert a SparseEmbedding object to a dictionary. **Returns**: `dict`: A dictionary of sparse values. #### to\_pinecone [#to_pinecone] ```python def to_pinecone() ``` Convert a SparseEmbedding object to a Pinecone dictionary. **Returns**: `dict`: A Pinecone dictionary. #### items [#items] ```python def items() ``` Return a list of (index, value) tuples from the SparseEmbedding object. **Returns**: `list`: A list of (index, value) tuples. # semantic_router.tokenizers (/docs/semantic-router/v1/client-reference/tokenizers) ## BaseTokenizer Objects [#basetokenizer-objects] ```python class BaseTokenizer() ``` Abstract Tokenizer class #### vocab\_size [#vocab_size] ```python @property def vocab_size() -> int ``` Returns the vocabulary size of the tokenizer **Returns**: `int`: Vocabulary size of tokenizer #### config [#config] ```python @property def config() -> dict ``` The tokenizer config **Returns**: `dict`: dictionary of tokenizer config #### save [#save] ```python def save(path: str | Path) -> None ``` Saves the configuration of the tokenizer Saves these files: * tokenizer.json: saved configuration of the tokenizer **Arguments**: * `path` (`str, :class:`pathlib.Path\`\`): Path to save the tokenizer to #### load [#load] ```python @classmethod def load(cls, path: str | Path) -> "BaseTokenizer" ``` Returns a :class:`bm25_engine.tokenizer.BaseTokenizer` object from saved configuration Requires these files: * tokenizer.json: saved configuration of the tokenizer **Arguments**: * `path` (`str, :class:`pathlib.Path\`\`): Path to load the tokenizer from **Returns**: `BaseTokenizer`: Configured BaseTokenizer ## PretrainedTokenizer Objects [#pretrainedtokenizer-objects] ```python class PretrainedTokenizer(BaseTokenizer) ``` Wrapper for HuggingFace tokenizers, representing a pretrained tokenizer (i.e. bert-base-uncased). Extends the :class:`semantic_router.tokenizers.BaseTokenizer` class. **Arguments**: * `tokenizer` (`class:`tokenizers.Tokenizer\`\`): Binding for HuggingFace Rust tokenizers * `add_special_tokens` (`bool`): Whether to accept special tokens from the tokenizer (i.e. `[PAD]`) * `pad` (`bool`): Whether to pad the input to a consistent length (using `[PAD]` tokens) * `tokenizer`0 (`tokenizer`1): HuggingFace ID of the model (i.e. `tokenizer`2) #### \_\_init\_\_ [#__init__] ```python def __init__(model_ident: str, custom_normalizer: Any = None, add_special_tokens: bool = False, pad: bool = True) -> None ``` Constructor method #### vocab\_size [#vocab_size-1] ```python @property def vocab_size() ``` Returns the vocabulary size of the tokenizer **Returns**: `int`: Vocabulary size of tokenizer #### config [#config-1] ```python @property def config() -> dict ``` The tokenizer config **Returns**: `dict`: dictionary of tokenizer config #### tokenize [#tokenize] ```python def tokenize(texts: str | list[str], pad: bool = True) -> np.ndarray ``` Tokenizes a string or list of strings into a 2D :class:`numpy.ndarray` of token ids **Arguments**: * `texts` (`str, list`): Texts to be tokenized * `pad` (`bool`): unused here (configured in the constructor) **Returns**: `class:`numpy.ndarray\`\`: 2D numpy array representing token ids ## TokenizerFactory Objects [#tokenizerfactory-objects] ```python class TokenizerFactory() ``` Tokenizer factory class #### get [#get] ```python @staticmethod def get(type_: str, **tokenizer_kwargs) -> BaseTokenizer ``` Get a configured :class:`bm25_engine.tokenizer.BaseTokenizer` **Arguments**: * `type_` (`str`): Tokenizer type to instantiate * `\**kwargs`: kwargs to be passed to Tokenizer constructor **Returns**: `bm25_engine.tokenizer.BaseTokenizer`: Tokenizer # semantic_router.decision_models.base (/docs/semantic-router/v1/client-reference/decision_models/base) the decision-model contract: answer typed questions about a state, with probabilities. a decision model is to DecisionRouter what an encoder is to IndexedRouter. the router turns its routes into one choice question; the model answers it. #### choice [#choice] ```python def choice(instructions: str, options: dict[str, str]) -> Question ``` which one of several named options applies. `options` maps a name to its meaning. #### noul [#noul] ```python def noul(instructions: str, yes: str = "yes", no: str = "no") -> Question ``` a yes/no question, answered with the probability of yes. #### score [#score] ```python def score(instructions: str, levels: Sequence[str]) -> Question ``` where the state sits on an ordered scale. `levels` go lowest first. ## DecisionModel Objects [#decisionmodel-objects] ```python class DecisionModel(BaseModel) ``` answers typed questions (choice, noul, score) about a state. questions and answers use the /v1/systemone shapes, whatever runs the model: a model over HTTP sends them as they are, a local model maps them onto its own API. #### aask [#aask] ```python async def aask(state: object, questions: dict[str, Question]) -> dict[str, Answer] ``` answer every question about one state, keyed by the question names. #### aask\_many [#aask_many] ```python async def aask_many(states: Sequence[object], questions: dict[str, Question]) -> list[dict[str, Answer]] ``` answer the same questions about many states, one result per state. #### aclose [#aclose] ```python async def aclose() -> None ``` release sessions or weights. a no-op unless the model holds any. #### close [#close] ```python def close() -> None ``` release sessions or weights from sync code. # semantic_router.decision_models.gliner2 (/docs/semantic-router/v1/client-reference/decision_models/gliner2) GLiNER2 decision models, run locally: fastino/GLiNER2.5-Decide by default. ## GLiNER2DecisionModel Objects [#gliner2decisionmodel-objects] ```python class GLiNER2DecisionModel(DecisionModel) ``` A GLiNER2 decision model run in-process with the gliner2 library. Answers choice, noul and score questions locally, with no network calls and no key. Requires the `local` extra: `pip install "semantic-router[local]"`. **Arguments**: * `name`: The model on the Hugging Face Hub, or a local directory. * `device`: `"cuda"`, `"mps"` or `"cpu"`. Left out, the first available. * `batch_size`: States per forward pass when answering many at once. * `classifier`: A loaded `gliner2.classification.Classifier` to use instead of loading `name`, e.g. one with a fine-tuned adapter. #### ask\_many [#ask_many] ```python def ask_many(states: Sequence[object], questions: dict[str, Question]) -> list[dict[str, Answer]] ``` answer the same questions about many states in batched forward passes. #### ask [#ask] ```python def ask(state: object, questions: dict[str, Question]) -> dict[str, Answer] ``` answer every question about one state in one forward pass. # semantic_router.decision_models.systemone (/docs/semantic-router/v1/client-reference/decision_models/systemone) decision models served over HTTP at /v1/systemone (TypeSafe's Jev, and servers that copy it). ## SystemOneDecisionModel Objects [#systemonedecisionmodel-objects] ```python class SystemOneDecisionModel(DecisionModel) ``` any server that speaks /v1/systemone: Jev, Laya, Von, or one of your own. **Arguments**: * `name`: The model id sent with every request. * `base_url`: The server; requests go to `{base_url}/v1/systemone`. * `api_key`: Sent as a Bearer token. Read from `api_key_env` when not given; a server that needs no key gets no Authorization header. * `timeout`: Seconds per request. * `retries`: Retries on rate limits (429, 529), server errors and timeouts. * `concurrency`: Requests in flight when answering many states at once. With one request per state, this caps a batch's throughput. * `session`: An aiohttp session to use instead of the model's own (tests). #### aask [#aask] ```python async def aask(state: object, questions: dict[str, Question]) -> dict[str, Answer] ``` answer several typed questions about one state in a single request. ## TypeSafeDecisionModel Objects [#typesafedecisionmodel-objects] ```python class TypeSafeDecisionModel(SystemOneDecisionModel) ``` TypeSafe's Jev over its API. Reads `JEV_API_KEY` when no key is passed. **Arguments**: * `name`: The Jev model to call. # semantic_router.encoders.aurelio (/docs/semantic-router/v1/client-reference/encoders/aurelio) ## AurelioSparseEncoder Objects [#aureliosparseencoder-objects] ```python class AurelioSparseEncoder(SparseEncoder, AsymmetricSparseMixin) ``` Sparse encoder using Aurelio Platform's embedding API. Requires an API key from [https://platform.aurelio.ai](https://platform.aurelio.ai) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: Optional[str] = None) ``` Initialize the AurelioSparseEncoder. **Arguments**: * `name` (`str | None`): The name of the model to use. * `api_key` (`str | None`): The API key to use. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[str]) -> list[SparseEmbedding] ``` Encode a list of queries using the Aurelio Platform embedding API. Documents must be strings, sparse encoders do not support other types. #### acall [#acall] ```python async def acall(docs: list[str]) -> list[SparseEmbedding] ``` Asynchronously encode a list of documents using the Aurelio Platform embedding API. Documents must be strings, sparse encoders do not support other types. :param docs: The documents to encode. :type docs: list\[str] :param input\_type: :type semantic\_router.encoders.encode\_input\_type.EncodeInputType :return: The encoded documents. :rtype: list\[SparseEmbedding] #### fit [#fit] ```python def fit(docs: List[str]) ``` Fit the encoder to a list of documents. AurelioSparseEncoder does not support fit yet. **Arguments**: * `docs` (`list[str]`): The documents to fit the encoder to. # semantic_router.encoders.azure_openai (/docs/semantic-router/v1/client-reference/encoders/azure_openai) ## AzureOpenAIEncoder Objects [#azureopenaiencoder-objects] ```python class AzureOpenAIEncoder(DenseEncoder) ``` Encoder for Azure OpenAI API. This class provides functionality to encode text documents using the Azure OpenAI API. #### \_\_init\_\_ [#__init__] ```python def __init__( name: Optional[str] = None, azure_endpoint: str | None = None, api_version: str | None = None, api_key: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: Callable[[], str] | None = None, http_client_options: Optional[Dict[str, Any]] = None, deployment_name: str = EncoderDefault.AZURE.value["deployment_name"], dimensions: Union[int, NotGiven] = NotGiven(), max_retries: int = 3) ``` Initialize the AzureOpenAIEncoder. **Arguments**: * `azure_endpoint` (`str, optional`): The endpoint for the Azure OpenAI API. Example: `"https://accountname.openai.azure.com"` * `api_version` (`str, optional`): The version of the API to use. Example: `"2025-02-01-preview"` * `api_key` (`str, optional`): The API key for the Azure OpenAI API. * `azure_ad_token` (`str, optional`): The Azure AD/Entra ID token for authentication. [https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) * `str, optional`0 (`str, optional`1): A callable function that returns an Azure AD/Entra ID token. * `str, optional`2 (`str, optional`3): Dictionary of options to configure httpx client Example: `str, optional`4 * `str, optional`5 (`str, optional`): The name of the model deployment to use. * `str, optional`7 (`str, optional`8): The number of dimensions for the embeddings. If not given, it defaults to the model's default setting. * `str, optional`9 (`str, optional`8): The maximum number of retries for API calls in case of failures. Default is `"https://accountname.openai.azure.com"`1. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Encode a list of documents into embeddings using the Azure OpenAI API. **Arguments**: * `docs` (`List[str]`): The documents to encode. **Returns**: `List[List[float]]`: The embeddings for the documents. #### acall [#acall] ```python async def acall(docs: List[str]) -> List[List[float]] ``` Encode a list of documents into embeddings using the Azure OpenAI API asynchronously. **Arguments**: * `docs` (`List[str]`): The documents to encode. **Returns**: `List[List[float]]`: The embeddings for the documents. # semantic_router.encoders.base (/docs/semantic-router/v1/client-reference/encoders/base) ## DenseEncoder Objects [#denseencoder-objects] ```python class DenseEncoder(BaseModel) ``` #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Any]) -> List[List[float]] ``` Encode a list of documents. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[List[float]]`: The encoded documents. #### acall [#acall] ```python async def acall(docs: List[Any]) -> List[List[float]] ``` Encode a list of documents asynchronously. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[List[float]]`: The encoded documents. ## SparseEncoder Objects [#sparseencoder-objects] ```python class SparseEncoder(BaseModel) ``` An encoder that encodes documents into a sparse format. #### \_\_call\_\_ [#__call__-1] ```python def __call__(docs: List[str]) -> List[SparseEmbedding] ``` Sparsely encode a list of documents. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[SparseEmbedding]`: The encoded documents. #### acall [#acall-1] ```python async def acall(docs: List[Any]) -> List[SparseEmbedding] ``` Encode a list of documents asynchronously. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[SparseEmbedding]`: The encoded documents. ## AsymmetricDenseMixin Objects [#asymmetricdensemixin-objects] ```python class AsymmetricDenseMixin() ``` #### encode\_queries [#encode_queries] ```python def encode_queries(docs: List[str]) -> List[List[float]] ``` Convert query texts to dense embeddings optimized for querying #### encode\_documents [#encode_documents] ```python def encode_documents(docs: List[str]) -> List[List[float]] ``` Convert document texts to dense embeddings optimized for storage #### aencode\_queries [#aencode_queries] ```python async def aencode_queries(docs: List[str]) -> List[List[float]] ``` Async version of encode\_queries #### aencode\_documents [#aencode_documents] ```python async def aencode_documents(docs: List[str]) -> List[List[float]] ``` Async version of encode\_documents ## AsymmetricSparseMixin Objects [#asymmetricsparsemixin-objects] ```python class AsymmetricSparseMixin() ``` #### encode\_queries [#encode_queries-1] ```python def encode_queries(docs: List[str]) -> List[SparseEmbedding] ``` Convert query texts to dense embeddings optimized for querying #### encode\_documents [#encode_documents-1] ```python def encode_documents(docs: List[str]) -> List[SparseEmbedding] ``` Convert document texts to dense embeddings optimized for storage #### aencode\_queries [#aencode_queries-1] ```python async def aencode_queries(docs: List[str]) -> List[SparseEmbedding] ``` Async version of encode\_queries #### aencode\_documents [#aencode_documents-1] ```python async def aencode_documents(docs: List[str]) -> List[SparseEmbedding] ``` Async version of encode\_documents # semantic_router.encoders.bedrock (/docs/semantic-router/v1/client-reference/encoders/bedrock) This module provides the BedrockEncoder class for generating embeddings using Amazon's Bedrock Platform. The BedrockEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Amazon's Bedrock Platform to generate embeddings for given documents. It requires an AWS Access Key ID and AWS Secret Access Key and supports customization of the pre-trained model and region. Example usage: ``` from semantic_router.encoders.bedrock_encoder import BedrockEncoder encoder = BedrockEncoder(access_key_id="your-access-key-id", secret_access_key="your-secret-key", region="your-region") embeddings = encoder(["document1", "document2"]) ``` Classes: BedrockEncoder: A class for generating embeddings using the Bedrock Platform. ## BedrockEncoder Objects [#bedrockencoder-objects] ```python class BedrockEncoder(DenseEncoder) ``` Dense encoder using Amazon Bedrock embedding API. Requires an AWS Access Key ID and AWS Secret Access Key. The BedrockEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Amazon's Bedrock Platform to generate embeddings for given documents. It supports customization of the pre-trained model and region. Example usage: ```python from semantic_router.encoders.bedrock_encoder import BedrockEncoder encoder = BedrockEncoder( access_key_id="your-access-key-id", secret_access_key="your-secret-key", region="your-region" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_init\_\_ [#__init__] ```python def __init__(name: str = EncoderDefault.BEDROCK.value["embedding_model"], input_type: Optional[str] = "search_query", client: Optional[Any] = None, access_key_id: Optional[str] = None, secret_access_key: Optional[str] = None, session_token: Optional[str] = None, region: Optional[str] = None) ``` Initializes the BedrockEncoder. **Arguments**: * `name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `input_type` (`str`): The type of input to use for the embedding. If not provided, the default input type specified in EncoderDefault will be used. * `access_key_id` (`str`): The AWS access key id for an IAM principle. If not provided, it will be retrieved from the access\_key\_id environment variable. * `secret_access_key` (`str`): The secret access key for an IAM principle. If not provided, it will be retrieved from the AWS\_SECRET\_KEY environment variable. * `session_token`: The session token for an IAM principle. If not provided, it will be retrieved from the AWS\_SESSION\_TOKEN environment variable. * `region` (`str`): The location of the Bedrock resources. If not provided, it will be retrieved from the AWS\_REGION environment variable, defaulting to "us-west-1" **Raises**: * `str`1: If the Bedrock Platform client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Union[str, Dict]], model_kwargs: Optional[Dict] = None) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`list[str]`): A list of strings representing the documents to embed. * `model_kwargs` (`dict`): A dictionary of model-specific inference parameters. **Raises**: * `ValueError`: If the Bedrock Platform client is not initialized or if the API call fails. **Returns**: `list[list[float]]`: A list of lists, where each inner list contains the embedding values for a document. #### chunk\_strings [#chunk_strings] ```python def chunk_strings(strings, MAX_WORDS=20) ``` Breaks up a list of strings into smaller chunks. **Arguments**: * `strings` (`list`): A list of strings to be chunked. * `max_chunk_size` (`int`): The maximum size of each chunk. Default is 20. **Returns**: `list[list[str]]`: A list of lists, where each inner list contains a chunk of strings. #### get\_env\_variable [#get_env_variable] ```python @staticmethod def get_env_variable(var_name, provided_value, default=None) ``` Retrieves environment variable or uses a provided value. **Arguments**: * `var_name` (`str`): The name of the environment variable. * `provided_value` (`Optional[str]`): The provided value to use if not None. * `default` (`Optional[str]`): The default value if the environment variable is not set. **Raises**: * `ValueError`: If no value is provided and the environment variable is not set. **Returns**: `str`: The value of the environment variable or the provided/default value. # semantic_router.encoders.bm25 (/docs/semantic-router/v1/client-reference/encoders/bm25) ## BM25Encoder Objects [#bm25encoder-objects] ```python class BM25Encoder(SparseEncoder, FittableMixin, AsymmetricSparseMixin) ``` BM25Encoder, running a vectorized version of ATIRE BM25 algorithm Concept: * BM25 uses scoring between queries & corpus to retrieve the most relevant documents ∈ corpus * most vector databases (VDB) store embedded documents and score them versus received queries for retrieval * we need to break up the BM25 formula into `encode_queries` and `encode_documents`, with the latter to be stored in VDB * dot product of `encode_queries(q)` and `encode_documents([D_0, D_1, ...])` is the BM25 score of the documents `[D_0, D_1, ...]` for the given query `q` * we train a BM25 encoder's normalization parameters on a sufficiently large corpus to capture target language distribution * these trained parameter allow us to balance TF & IDF of query & documents for retrieval (read more on how BM25 fixes issues with TF-IDF) The reference formula is section 4.1 of the ATIRE paper: ``` RSV_d = Σ_{t ∈ q} log(N / df_t) · (k1 + 1) · tf_td / (k1 · ((1 - b) + b · L_d / L_avg) + tf_td) ``` ## Deviations from the paper [#deviations-from-the-paper] This implementation is faithful to the formula above on the document side, but deviates from it in three documented ways. Each is deliberate; see the inline comments at the point of use for the details. 1. IDF smoothing. We compute `log((N + 1) / (df_t + 0.5))` rather than `log(N / df_t)`, to avoid a division by zero for unseen terms. This preserves the strictly-positive IDF that the ATIRE variant exists for. 2. Query weight normalization. The paper produces an unbounded relevance score, which is fine for a search engine that only ranks within a single query. A router instead compares scores against a fixed threshold, so scores must be comparable *across* queries. We therefore L1-normalize the query weights and scale them by `1 / (k1 + 1)`, which bounds the query·document dot product to \[0, 1] -- the same range as the cosine similarity returned by the dense encoders, so the two can be blended in a hybrid `encode_documents`0 and thresholded alike. This is ranking-neutral within a query (it is a single positive constant per query) but it does discard cross-query IDF magnitude: two queries with different total IDF mass can produce the same score. 3. Parameter defaults. We default to `encode_documents`1 rather than the paper's `encode_documents`2. See the `encode_documents`3 and `encode_documents`4 parameter docs below. ATIRE Paper: [https://www.cs.otago.ac.nz/research/student-publications/atire-opensource.pdf](https://www.cs.otago.ac.nz/research/student-publications/atire-opensource.pdf) Pinecone Implementation: [https://github.com/pinecone-io/pinecone-text/blob/8399f9ff28c4652766c35165c0db9b0eff309077/pinecone\_text/sparse/bm25\_encoder.py](https://github.com/pinecone-io/pinecone-text/blob/8399f9ff28c4652766c35165c0db9b0eff309077/pinecone_text/sparse/bm25_encoder.py) **Arguments**: * `encode_documents`3 (`encode_documents`6): normalizer parameter that limits how much a single query term `encode_documents`7 can affect score for document `encode_documents`8. Defaults to 1.5, the standard Robertson value, *not* the 0.9 reported in the ATIRE paper. The paper's value was trained on the INEX 2008 Wikipedia collection, whose documents average 878 words (paper table 5), whereas this encoder is fitted on route utterances averaging on the order of ten tokens. Transferring the paper's parameters to utterance-length text is not obviously more correct, and changing the default would silently shift the scores that existing thresholds were tuned against. * `encode_documents`4 (`encode_documents`6): normalizer parameter that balances the effect of a single document length compared to the average document length. Defaults to 0.75 rather than the paper's 0.4, for the same reason as `encode_documents`3. Note that `encode_documents`4 is considerably more influential on short text: over utterances spanning 0.3x to 2.2x the average length, `encode_queries(q)`3 spreads the document factor by \~2.2x versus \~1.4x for `encode_queries(q)`4. Lower it towards the paper's value if length is over-weighted for your route set. * `encode_queries(q)`5 (`encode_queries(q)`6): number of documents in the trained corpus * `encode_queries(q)`7 (`encode_queries(q)`8): float representing the average document length in the trained corpus * `encode_queries(q)`9 (`encode_documents([D_0, D_1, ...])`0numpy.ndarray`encode_documents([D_0, D_1, ...])`1): (1, tokenizer.vocab\_size) shaped array, denoting how many documents contain `encode_documents([D_0, D_1, ...])`2 #### fit [#fit] ```python def fit(routes: List[Route]) -> "BM25Encoder" ``` Trains the encoder weights on the provided routes. **Arguments**: * `routes` (`List[Route]`): List of routes to train the encoder on. #### encode\_queries [#encode_queries] ```python def encode_queries(queries: list[str]) -> list[SparseEmbedding] ``` Returns BM25 scores for queries using precomputed corpus scores. **Arguments**: * `queries` (`list`): List of queries to encode **Returns**: `list[SparseEmbedding]`: BM25 scores for each query against the corpus #### encode\_documents [#encode_documents] ```python def encode_documents(documents: list[str], batch_size: int | None = None) -> list[SparseEmbedding] ``` Returns document term frequency normed by itself & average trained corpus length (This is the right-hand side of the BM25 equation, which gets matmul-ed with the query IDF component) LaTeX: $\frac{(k_1 + 1) \times f(d_i, D)}{f(d_i, D) + k_1 \times (1 - b + b \times \frac{|D|}{avgdl})}$ where: f(d\_i, D) is frequency of term `d_i ∈ D` |D| is the document length avgdl is average document length in trained corpus **Arguments**: * `documents` (`list`): List of queries to encode **Returns**: `list[SparseEmbedding]`: Encoded queries (as either sparse or dict) #### model [#model] ```python def model(docs: List[str]) -> list[SparseEmbedding] ``` Encode documents using BM25, with different encoding for queries vs documents to be indexed. **Arguments**: * `docs`: List of documents to encode * `is_query`: If True, use query encoding, else use document encoding **Returns**: List of sparse embeddings # semantic_router.encoders.clip (/docs/semantic-router/v1/client-reference/encoders/clip) ## CLIPEncoder Objects [#clipencoder-objects] ```python class CLIPEncoder(DenseEncoder) ``` Multi-modal dense encoder for text and images using CLIP-type models via HuggingFace. **Arguments**: * `name` (`str`): The name of the model to use. * `tokenizer_kwargs` (`Dict`): Keyword arguments for the tokenizer. * `processor_kwargs` (`Dict`): Keyword arguments for the processor. * `model_kwargs` (`Dict`): Keyword arguments for the model. * `device` (`Optional[str]`): The device to use for the model. * `str`0 (`str`1): The tokenizer for the model. * `str`2 (`str`1): The processor for the model. * `str`4 (`str`1): The model. * `str`6 (`str`1): The torch library. * `str`8 (`str`1): The PIL library. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize the CLIPEncoder. **Arguments**: * `**data` (`Dict`): Keyword arguments for the encoder. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Any], batch_size: int = 32, normalize_embeddings: bool = True) -> List[List[float]] ``` Encode a list of documents. Can handle both text and images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. * `batch_size` (`int`): The batch size for the encoding. * `normalize_embeddings` (`bool`): Whether to normalize the embeddings. **Returns**: `List[List[float]]`: A list of embeddings. # semantic_router.encoders.cohere (/docs/semantic-router/v1/client-reference/encoders/cohere) #### docs2cohere\_embed\_input [#docs2cohere_embed_input] ```python def docs2cohere_embed_input(docs: list[str]) -> list[dict[str, Any]] ``` Convert a list of texts into Cohere's `inputs` format. The Cohere `embed` endpoint expects one `EmbedInput` per embedding, each holding its own `content` array, so a list of N texts becomes N inputs. **Arguments**: * `docs` (`list[str]`): The texts to embed. **Returns**: \`\`0: One embed input per text. #### batch\_docs [#batch_docs] ```python def batch_docs(docs: list[str], size: int = COHERE_MAX_EMBED_BATCH) -> list[list[str]] ``` Split texts into chunks that fit Cohere's per-request input limit. **Arguments**: * `docs` (`list[str]`): The texts to embed. * `size` (`int`): Maximum number of texts per request. **Returns**: `list[list[str]]`: The texts split into consecutive chunks of at most `size`. ## CohereEncoder Objects [#cohereencoder-objects] ```python class CohereEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Dense encoder that uses Cohere API and SDK to embed documents. Supports text only. Requires a Cohere API key from [https://dashboard.cohere.com/api-keys](https://dashboard.cohere.com/api-keys). #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, cohere_api_key: str | None = None) ``` Initialize the Cohere encoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "embed-english-v3.0" or "embed-multilingual-v3.0". * `cohere_api_key` (`str`): The API key for the Cohere client, can also be set via the COHERE\_API\_KEY environment variable. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Cohere. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Cohere asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.fastembed (/docs/semantic-router/v1/client-reference/encoders/fastembed) ## FastEmbedEncoder Objects [#fastembedencoder-objects] ```python class FastEmbedEncoder(DenseEncoder) ``` Dense encoder that uses local FastEmbed to embed documents. Supports text only. Requires the fastembed package which can be installed with `pip install 'semantic-router[fastembed]'` **Arguments**: * `name`: The name of the embedding model to use. * `max_length`: The maximum length of the input text. * `cache_dir`: The directory to cache the embedding model. * `threads`: The number of threads to use for the embedding. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize the FastEmbed encoder. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Embed a list of documents. Supports text only. **Arguments**: * `docs` (`List[str]`): The documents to embed. **Raises**: * `ValueError`: If the embedding fails. **Returns**: `List[List[float]]`: The vector embeddings of the documents. #### acall [#acall] ```python async def acall(docs: List[str]) -> List[List[float]] ``` Embed a list of documents asynchronously. Supports text only. FastEmbed itself is synchronous, so this offloads the embedding call to a thread to avoid blocking the event loop. **Arguments**: * `docs` (`List[str]`): The documents to embed. **Raises**: * `ValueError`: If the embedding fails. **Returns**: `List[List[float]]`: The vector embeddings of the documents. # semantic_router.encoders.google (/docs/semantic-router/v1/client-reference/encoders/google) ## GoogleEncoder Objects [#googleencoder-objects] ```python class GoogleEncoder(DenseEncoder) ``` GoogleEncoder class for generating embeddings using Google's AI Platform. The GoogleEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Google AI Platform to generate embeddings for given documents. It requires a Google Cloud project ID and supports customization of the pre-trained model, location, and API endpoint. Example usage: ```python from semantic_router.encoders.google_encoder import GoogleEncoder encoder = GoogleEncoder(project_id="your-project-id") embeddings = encoder(["document1", "document2"]) ``` **Attributes**: * `client` - An instance of the TextEmbeddingModel client. * `type` - The type of the encoder, which is "google". #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, project_id: Optional[str] = None, location: Optional[str] = None, api_endpoint: Optional[str] = None) ``` Initializes the GoogleEncoder. **Arguments**: * `model_name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `project_id` (`str`): The Google Cloud project ID. If not provided, it will be retrieved from the GOOGLE\_PROJECT\_ID environment variable. * `location` (`str`): The location of the AI Platform resources. If not provided, it will be retrieved from the GOOGLE\_LOCATION environment variable, defaulting to "us-central1". * `api_endpoint` (`str`): The API endpoint for the AI Platform. If not provided, it will be retrieved from the GOOGLE\_API\_ENDPOINT environment variable. **Raises**: * `ValueError`: If the Google Project ID is not provided or if the AI Platform client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`List[str]`): A list of strings representing the documents to embed. **Raises**: * `ValueError`: If the Google AI Platform client is not initialized or if the API call fails. **Returns**: `List[List[float]]`: A list of lists, where each inner list contains the embedding values for a document. # semantic_router.encoders.huggingface (/docs/semantic-router/v1/client-reference/encoders/huggingface) This module provides the HFEndpointEncoder class to embeddings models using Huggingface's endpoint. The HFEndpointEncoder class is a subclass of DenseEncoder and utilizes a specified Huggingface endpoint to generate embeddings for given documents. It requires the URL of the Huggingface API endpoint and an API key for authentication. Example usage: ``` from semantic_router.encoders.hfendpointencoder import HFEndpointEncoder encoder = HFEndpointEncoder( huggingface_url="https://api-inference.huggingface.co/models/BAAI/bge-large-en-v1.5", huggingface_api_key="your-hugging-face-api-key" ) embeddings = encoder(["document1", "document2"]) ``` Classes: HFEndpointEncoder: A class for generating embeddings using a Huggingface endpoint. ## HuggingFaceEncoder Objects [#huggingfaceencoder-objects] ```python class HuggingFaceEncoder(DenseEncoder) ``` HuggingFace encoder class for local embedding models. Models can be trained and loaded from private repositories, or from the Huggingface Hub. Example usage: ```python from semantic_router.encoders import HuggingFaceEncoder encoder = HuggingFaceEncoder( name="sentence-transformers/all-MiniLM-L6-v2", device="cuda" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str], batch_size: int = 32, normalize_embeddings: bool = True, pooling_strategy: str = "mean") -> List[List[float]] ``` Encode a list of documents into embeddings using the local Hugging Face model. **Arguments**: * `docs` (`List[str]`): A list of documents to encode. * `batch_size`: The batch size for encoding. ## HFEndpointEncoder Objects [#hfendpointencoder-objects] ```python class HFEndpointEncoder(DenseEncoder) ``` HFEndpointEncoder class to embeddings models using Huggingface's inference endpoints. The HFEndpointEncoder class is a subclass of DenseEncoder and utilizes a specified Huggingface endpoint to generate embeddings for given documents. It requires the URL of the Huggingface API endpoint and an API key for authentication. Example usage: ```python from semantic_router.encoders import HFEndpointEncoder encoder = HFEndpointEncoder( huggingface_url="https://api-inference.huggingface.co/models/BAAI/bge-large-en-v1.5", huggingface_api_key="your-hugging-face-api-key" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = "hugging_face_custom_endpoint", huggingface_url: Optional[str] = None, huggingface_api_key: Optional[str] = None) ``` Initializes the HFEndpointEncoder with the specified parameters. **Arguments**: * `name` (`str`): The name of the encoder. * `huggingface_url` (`str`): The URL of the Hugging Face API endpoint. * `huggingface_api_key` (`str`): The API key for the Hugging Face API. **Raises**: * `ValueError`: If either `huggingface_url` or `huggingface_api_key` is None. #### \_\_call\_\_ [#__call__-1] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Encodes a list of documents into embeddings using the Hugging Face API. **Arguments**: * `docs` (`List[str]`): A list of documents to encode. **Raises**: * `ValueError`: If no embeddings are returned for a document. **Returns**: `List[List[float]]`: A list of embeddings for the given documents. #### query [#query] ```python def query(payload, max_retries=3, retry_interval=5) ``` Sends a query to the Hugging Face API and returns the response. **Arguments**: * `payload` (`dict`): The payload to send in the request. **Raises**: * `ValueError`: If the query fails or the response status is not 200. **Returns**: `dict`: The response from the Hugging Face API. # semantic_router.encoders.jina (/docs/semantic-router/v1/client-reference/encoders/jina) This file contains the JinaEncoder class which is used to encode text using Jina #### jina\_to\_list [#jina_to_list] ```python def jina_to_list(embeds: CreateEmbeddingResponse) -> list[list[float]] ``` Convert a Jina embedding response to a list of embeddings. **Arguments**: * `embeds` (`CreateEmbeddingResponse`): The embedding response returned by the Jina API. **Returns**: `list[list[float]]`: One embedding per input document. ## JinaEncoder Objects [#jinaencoder-objects] ```python class JinaEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Jina. Requires a Jina API key from [https://jina.ai/api-keys/](https://jina.ai/api-keys/) Jina exposes an OpenAI-compatible embeddings endpoint, so this encoder drives it with the OpenAI SDK pointed at `https://api.jina.ai/v1` rather than depending on LiteLLM. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None, base_url: str | None = None) ``` Initialize the JinaEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "jina-embeddings-v3". * `api_key` (`str`): The Jina API key, can also be set via the JINA\_API\_KEY or JINA\_AI\_API\_KEY environment variable. * `base_url` (`str`): Override the Jina API base URL, can also be set via the JINA\_BASE\_URL or JINA\_AI\_API\_BASE environment variable. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Jina. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Jina asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.litellm (/docs/semantic-router/v1/client-reference/encoders/litellm) #### litellm\_to\_list [#litellm_to_list] ```python def litellm_to_list(embeds: "litellm.EmbeddingResponse") -> list[list[float]] ``` Convert a LiteLLM embedding response to a list of embeddings. **Arguments**: * `embeds`: The LiteLLM embedding response. **Returns**: A list of embeddings. ## LiteLLMEncoder Objects [#litellmencoder-objects] ```python class LiteLLMEncoder(DenseEncoder, AsymmetricDenseMixin) ``` LiteLLM encoder class for generating embeddings using LiteLLM. The LiteLLMEncoder class is a subclass of DenseEncoder and utilizes the LiteLLM SDK to generate embeddings for given documents. It supports all encoders supported by LiteLLM. litellm is an optional dependency: install it with `pip install "semantic-router[litellm]"`. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None) ``` Initialize the LiteLLMEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use. Must use LiteLLM naming convention (e.g. "openai/text-embedding-3-small" or "mistral/mistral-embed"). **Raises**: * `ImportError`: If litellm is not installed. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using LiteLLM. **Arguments**: * `docs`: List of text documents to encode. **Returns**: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of documents into embeddings using LiteLLM asynchronously. **Arguments**: * `docs`: List of documents to encode. **Returns**: List of embeddings for each document. # semantic_router.encoders.local (/docs/semantic-router/v1/client-reference/encoders/local) ## LocalEncoder Objects [#localencoder-objects] ```python class LocalEncoder(DenseEncoder) ``` Local encoder using sentence-transformers for efficient local embeddings. ## LocalSparseEncoder Objects [#localsparseencoder-objects] ```python class LocalSparseEncoder(SparseEncoder) ``` Local sparse encoder using sentence-transformers' SparseEncoder (e.g., SPLADE, CSR) for efficient local sparse embeddings. # semantic_router.encoders.mistral (/docs/semantic-router/v1/client-reference/encoders/mistral) This file contains the MistralEncoder class which is used to encode text using MistralAI #### mistral\_to\_list [#mistral_to_list] ```python def mistral_to_list(embeds: EmbeddingResponse) -> list[list[float]] ``` Convert a Mistral embedding response to a list of embeddings. **Arguments**: * `embeds` (`EmbeddingResponse`): The Mistral embedding response. **Returns**: `list[list[float]]`: One embedding per input document. ## MistralEncoder Objects [#mistralencoder-objects] ```python class MistralEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using MistralAI and SDK. Requires a MistralAI API key from [https://console.mistral.ai/api-keys/](https://console.mistral.ai/api-keys/) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, mistralai_api_key: str | None = None) ``` Initialize the MistralEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "mistral-embed". * `mistralai_api_key` (`str`): The MistralAI API key. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using MistralAI. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using MistralAI asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.nvidia_nim (/docs/semantic-router/v1/client-reference/encoders/nvidia_nim) This file contains the NimEncoder class which is used to encode text using Nim #### nim\_to\_list [#nim_to_list] ```python def nim_to_list(embeds: CreateEmbeddingResponse) -> list[list[float]] ``` Convert a NVIDIA NIM embedding response to a list of embeddings. **Arguments**: * `embeds` (`CreateEmbeddingResponse`): The embedding response returned by the NIM API. **Returns**: `list[list[float]]`: One embedding per input document. ## NimEncoder Objects [#nimencoder-objects] ```python class NimEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Nvidia NIM. Requires a Nim API key from [https://build.nvidia.com/](https://build.nvidia.com/) NVIDIA NIM exposes an OpenAI-compatible embeddings endpoint, so this encoder drives it with the OpenAI SDK pointed at `https://integrate.api.nvidia.com/v1` rather than depending on LiteLLM. Point `base_url` at your own host to use a self-hosted NIM. NVIDIA's `nv-embedqa` models are asymmetric: queries must be embedded with `input_type="query"` and stored documents with `input_type="passage"`, so :meth:`0 and :meth:`1 differ accordingly. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None, base_url: str | None = None) ``` Initialize the NimEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "nvidia/nv-embedqa-mistral-7b-v2". * `api_key` (`str`): The Nim API key, can also be set via the NVIDIA\_NIM\_API\_KEY environment variable. * `base_url` (`str`): Override the NIM API base URL, can also be set via the NVIDIA\_NIM\_API\_BASE environment variable. Use this to target a self-hosted NIM container. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using NVIDIA NIM. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using NVIDIA NIM asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.ollama (/docs/semantic-router/v1/client-reference/encoders/ollama) ## OllamaEncoder Objects [#ollamaencoder-objects] ```python class OllamaEncoder(DenseEncoder) ``` OllamaEncoder class for generating embeddings using OLLAMA. [https://ollama.com/search?c=embedding](https://ollama.com/search?c=embedding) Example usage: ```python from semantic_router.encoders.ollama import OllamaEncoder encoder = OllamaEncoder(base_url="http://localhost:11434") embeddings = encoder(["document1", "document2"]) ``` **Attributes**: * `client` - An instance of the TextEmbeddingModel client. * `type` - The type of the encoder, which is "ollama". #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, base_url: str | None = None) ``` Initializes the OllamaEncoder. **Arguments**: * `name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `base_url` (`str`): The API endpoint for OLLAMA. If not provided, it will be retrieved from the `OLLAMA_BASE_URL` environment variable. **Raises**: * `ValueError`: If the hosted base url is not provided properly or if the ollama client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`List[str]`): A list of strings representing the documents to embed. **Raises**: * `ValueError`: If the Google AI Platform client is not initialized or if the API call fails. **Returns**: `List[List[float]]`: A list of lists, where each inner list contains the embedding values for a document. # semantic_router.encoders.openai (/docs/semantic-router/v1/client-reference/encoders/openai) ## OpenAIEncoder Objects [#openaiencoder-objects] ```python class OpenAIEncoder(DenseEncoder) ``` OpenAI encoder class for generating embeddings using OpenAI API. The OpenAIEncoder class is a subclass of DenseEncoder and utilizes the OpenAI API to generate embeddings for given documents. It requires an OpenAI API key. #### token\_limit [#token_limit] default value, should be replaced by config #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, openai_base_url: Optional[str] = None, openai_api_key: Optional[str] = None, openai_org_id: Optional[str] = None, dimensions: Union[int, NotGiven] = NotGiven(), max_retries: int = 3) ``` Initialize the OpenAIEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use. * `openai_base_url` (`str`): The base URL for the OpenAI API. * `openai_api_key` (`str`): The OpenAI API key. * `openai_org_id` (`str`): The OpenAI organization ID. * `dimensions` (`int`): The dimensions of the embeddings. * `str`0 (`int`): The maximum number of retries for the OpenAI API call. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str], truncate: bool = True) -> List[List[float]] ``` Encode a list of text documents into embeddings using OpenAI API. **Arguments**: * `docs`: List of text documents to encode. * `truncate`: Whether to truncate the documents to token limit. If False and a document exceeds the token limit, an error will be raised. **Returns**: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: List[str], truncate: bool = True) -> List[List[float]] ``` Encode a list of text documents into embeddings using OpenAI API asynchronously. **Arguments**: * `docs`: List of text documents to encode. * `truncate`: Whether to truncate the documents to token limit. If False and a document exceeds the token limit, an error will be raised. **Returns**: List of embeddings for each document. # semantic_router.encoders.tfidf (/docs/semantic-router/v1/client-reference/encoders/tfidf) ## TfidfEncoder Objects [#tfidfencoder-objects] ```python class TfidfEncoder(SparseEncoder, FittableMixin) ``` #### fit [#fit] ```python def fit(routes: List[Route]) ``` Trains the encoder weights on the provided routes. **Arguments**: * `routes` (`List[Route]`): List of routes to train the encoder on. # semantic_router.encoders.vit (/docs/semantic-router/v1/client-reference/encoders/vit) ## VitEncoder Objects [#vitencoder-objects] ```python class VitEncoder(DenseEncoder) ``` Encoder for Vision Transformer models. This class provides functionality to encode images using a Vision Transformer model via Hugging Face. It supports various image processing and model initialization options. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize the VitEncoder. **Arguments**: * `**data` (`dict`): Additional keyword arguments for the encoder. #### \_\_call\_\_ [#__call__] ```python def __call__(imgs: List[Any], batch_size: int = 32) -> List[List[float]] ``` Encode a list of images into embeddings using the Vision Transformer model. **Arguments**: * `imgs` (`List[Any]`): The images to encode. * `batch_size` (`int`): The batch size for encoding. **Returns**: `List[List[float]]`: The embeddings for the images. # semantic_router.encoders.voyage (/docs/semantic-router/v1/client-reference/encoders/voyage) This file contains the VoyageEncoder class which is used to encode text using Voyage ## VoyageEncoder Objects [#voyageencoder-objects] ```python class VoyageEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Voyage and VoyageAI SDK. Requires a Voyage API key from [https://voyageai.com/api-keys/](https://voyageai.com/api-keys/) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None) ``` Initialize the VoyageEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "voyage-3-lite". * `api_key` (`str`): The Voyage API key, can also be set via the VOYAGE\_API\_KEY environment variable. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Voyage. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Voyage asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.index.base (/docs/semantic-router/v1/client-reference/index/base) ## BaseIndex Objects [#baseindex-objects] ```python class BaseIndex(BaseModel) ``` Base class for indices using Pydantic's BaseModel. This class outlines the expected interface for index classes. Actual method implementations should be provided in subclasses. The index is the single source of truth for routes. Each record is one (route, utterance) pair with a deterministic id, so adding the same pair again replaces the record instead of duplicating it. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Upsert records into the index, one per (route, utterance) pair. This method should be implemented by subclasses. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of route names, one per embedding. * `utterances` (`List[str]`): List of utterances, one per embedding. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata dicts, one per embedding. Holds the route's own metadata and the reserved `sr_description` and `sr_confidence_threshold` keys. * `List[List[float]]`2 (`List[List[float]]`3): List of sparse embeddings, one per embedding. Only hybrid indexes store them. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Upsert records into the index asynchronously. This method should be implemented by subclasses. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of route names, one per embedding. * `utterances` (`List[str]`): List of utterances, one per embedding. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata dicts, one per embedding. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): List of sparse embeddings, one per embedding. #### get\_utterances [#get_utterances] ```python def get_utterances() -> List[Utterance] ``` Gets every record stored in the index as an Utterance. **Returns**: `List[Utterance]`: A list of Utterance objects. #### aget\_utterances [#aget_utterances] ```python async def aget_utterances() -> List[Utterance] ``` Gets every record stored in the index as an Utterance, asynchronously. **Returns**: `List[Utterance]`: A list of Utterance objects. #### get\_routes [#get_routes] ```python def get_routes() -> List[Route] ``` Rebuilds the routes stored in the index from its records. **Returns**: `List[Route]`: A list of Route objects. #### aget\_routes [#aget_routes] ```python async def aget_routes() -> List[Route] ``` Rebuilds the routes stored in the index from its records, asynchronously. **Returns**: `List[Route]`: A list of Route objects. #### delete [#delete] ```python def delete(route_name: str) ``` Deletes route by route name. This method should be implemented by subclasses. **Arguments**: * `route_name` (`str`): Name of the route to delete. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. This method should be implemented by subclasses. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### describe [#describe] ```python def describe() -> IndexConfig ``` Returns an IndexConfig object with index details such as type, dimensions, and total vector count. This method should be implemented by subclasses. **Returns**: `IndexConfig`: An IndexConfig object. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. This method should be implemented by subclasses. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. This method should be implemented by subclasses. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query\_vector and return top\_k results. This method should be implemented by subclasses. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query\_vector and return top\_k results. This method should be implemented by subclasses. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the index. This method should be implemented by subclasses. **Raises**: * `NotImplementedError`: If the method is not implemented by the subclass. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes or resets the index. This method should be implemented by subclasses. **Raises**: * `NotImplementedError`: If the method is not implemented by the subclass. #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Deletes or resets the index asynchronously. This method should be implemented by subclasses. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. Default implementation just calls the sync version. **Returns**: `int`: The total number of vectors. #### check\_records [#check_records] ```python def check_records( embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]] ``` Checks the lists passed to `add` line up, and returns one metadata dict per record (a copy, so an index never mutates the caller's dicts). **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings. * `routes` (`List[str]`): List of route names. * `utterances` (`List[Any]`): List of utterances. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata dicts, or None for empty metadata. **Returns**: \`\`0: One metadata dict per record. #### to\_utterance [#to_utterance] ```python def to_utterance(record: Dict[str, Any]) -> Utterance ``` Builds an Utterance from a record's metadata, which holds the `sr_route` and `sr_utterance` keys next to the rest of the record's metadata. **Arguments**: * `record` (`Dict[str, Any]`): The record's metadata. **Returns**: `Utterance`: An Utterance object. #### to\_routes [#to_routes] ```python def to_routes(utterances: List[Utterance]) -> List[Route] ``` Rebuilds routes from index records, in the order each route is first seen. The route-level fields come from the reserved `sr_` keys of the route's first record, and every `sr_` key is stripped from the route's metadata. **Arguments**: * `utterances` (`List[Utterance]`): The records, as returned by `get_utterances`. **Returns**: `List[Route]`: A list of Route objects. # semantic_router.index.hybrid_local (/docs/semantic-router/v1/client-reference/index/hybrid_local) ## HybridLocalIndex Objects [#hybridlocalindex-objects] ```python class HybridLocalIndex(LocalIndex) ``` #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Upsert records into the index, one per (route, utterance) pair. A pair that is already stored has its embeddings and metadata replaced. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata to add to the index. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): List of sparse embeddings to add to the index. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float]`): The sparse vector to search for, must be provided. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. This method calls the sync `query` method as everything uses numpy computations which is CPU-bound and so no benefit can be gained from making this async. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float]`): The sparse vector to search for, must be provided. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes the index, effectively clearing it and setting it to None. **Returns**: `None`: None # semantic_router.index.local (/docs/semantic-router/v1/client-reference/index/local) ## LocalIndex Objects [#localindex-objects] ```python class LocalIndex(BaseIndex) ``` #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Upsert records into the index, one per (route, utterance) pair. A pair that is already stored has its embedding and metadata replaced. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata to add to the index. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): Not supported, use HybridLocalIndex. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Upsert records into the index. Note that this just points to the sync add method as async makes no difference for the local computations of the LocalIndex. #### get\_utterances [#get_utterances] ```python def get_utterances() -> List[Utterance] ``` Gets every record stored in the index as an Utterance. **Returns**: `List[Utterance]`: A list of Utterance objects. #### aget\_utterances [#aget_utterances] ```python async def aget_utterances() -> List[Utterance] ``` Gets every record stored in the index as an Utterance. Note that this just points to the sync get\_utterances method. **Returns**: `List[Utterance]`: A list of Utterance objects. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: An IndexConfig object. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. Note that this just points to the sync query method, the computation is local and CPU-bound. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### delete [#delete] ```python def delete(route_name: str) ``` Delete all records of a specific route from the index. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### adelete [#adelete] ```python async def adelete(route_name: str) ``` Delete all records of a specific route from the index. Note that this just points to the sync delete method as async makes no difference for the local computations of the LocalIndex. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes the index, effectively clearing it and setting it to None. **Returns**: `None`: None #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the index. **Returns**: `None`: None #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Deletes the index, effectively clearing it and setting it to None. Note that this just points to the sync delete\_index method as async makes no difference for the local computations of the LocalIndex. **Returns**: `None`: None # semantic_router.index.mongodb (/docs/semantic-router/v1/client-reference/index/mongodb) MongoDB Atlas Vector Search index. Records are MongoDB documents, searched with the `$vectorSearch` aggregation stage. Works with MongoDB Atlas, and with the `mongodb/mongodb-atlas-local` image (MongoDB with search) that the integration tests run against. ## MongoDbIndex Objects [#mongodbindex-objects] ```python class MongoDbIndex(BaseIndex) ``` MongoDB Atlas Vector Search index. The first `add` creates the collection and its vector search index, with `sr_route`, `namespace` and `_id` as filter fields, and waits until the index is queryable. Atlas indexes new documents asynchronously, so `add` also waits (up to `sync_timeout` seconds) until its records are searchable, so a query straight after an add sees them. Scores are on the same scale as the other indexes: Atlas reports cosine and dot product scores as `(1 + similarity) / 2`, which this index maps back to the raw similarity. Euclidean scores are Atlas's `1 / (1 + distance)`. One pymongo client serves everything. The async methods run it in a worker thread, so the index works from any event loop and keeps a single connection pool. **Arguments**: * \`\`6: The collection that holds the records. * \`\`7: The database the collection lives in. * \`\`8: The name of the collection's vector search index. * `9: The MongoDB connection string. Read from `MONGO\_CONNECTION\_URI\`\` when not given, and never written to a file. * \`\`2: Scopes every record, query and delete to one tenant. * `3: Seconds `add\`\` waits for new records to become searchable; 0 returns as soon as they are written. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = 200, **kwargs) ``` Upsert one document per (route, utterance), then wait until they are searchable. **Arguments**: * `embeddings`: The dense vectors. * `routes`: The route of each record. * `utterances`: The utterance of each record. * `metadata_list`: Each record's metadata, including the reserved `sr_` route-level keys. * `sparse_embeddings`: Not supported: MongoDbIndex stores dense vectors only. * `batch_size`: Documents per bulk write. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = 200, **kwargs) ``` Async :meth:`add`. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index with `$vectorSearch`. **Arguments**: * `vector`: The query vector. * `top_k`: The number of results to return. * `route_filter`: Only search these routes. * `sparse_vector`: Not used: MongoDbIndex is dense only. **Returns**: The scores and route names of the top\_k results. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Async :meth:`query`. #### delete [#delete] ```python def delete(route_name: str) -> list[str] ``` Delete every record of one route. Returns the deleted record ids. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Async :meth:`delete`. #### delete\_all [#delete_all] ```python def delete_all() -> None ``` Delete every record in this namespace, keeping the collection. #### delete\_index [#delete_index] ```python def delete_index() -> None ``` Drop the collection, and its vector search index with it. #### adelete\_index [#adelete_index] ```python async def adelete_index() -> None ``` Async :meth:`delete_index`. #### describe [#describe] ```python def describe() -> IndexConfig ``` The index type, its dimensions and how many records it holds. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Whether the vector search index exists and is queryable. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Async :meth:`is_ready`. # semantic_router.index.pinecone (/docs/semantic-router/v1/client-reference/index/pinecone) #### build\_records [#build_records] ```python def build_records( embeddings: List[List[float]], routes: List[str], utterances: List[str], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None ) -> List[Dict] ``` Build records for Pinecone upsert. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata to upsert. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): List of sparse embeddings to upsert. **Returns**: `List[List[float]]`0: List of records to upsert. ## PineconeRecord Objects [#pineconerecord-objects] ```python class PineconeRecord(BaseModel) ``` #### metadata [#metadata] Additional metadata dictionary #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize PineconeRecord. **Arguments**: * `**data` (`dict`): Keyword arguments to pass to the BaseModel constructor. #### to\_dict [#to_dict] ```python def to_dict() ``` Convert PineconeRecord to a dictionary. **Returns**: `dict`: Dictionary representation of the PineconeRecord. ## PineconeIndex Objects [#pineconeindex-objects] ```python class PineconeIndex(BaseIndex) ``` #### \_\_init\_\_ [#__init__-1] ```python def __init__(api_key: Optional[str] = None, index_name: str = "index", dimensions: Optional[int] = None, metric: str = "dotproduct", cloud: str = "aws", region: str = "us-east-1", host: str = "", namespace: Optional[str] = "", base_url: Optional[str] = "https://api.pinecone.io", init_async_index: bool = False) ``` Initialize PineconeIndex. **Arguments**: * `api_key` (`Optional[str]`): Pinecone API key. * `index_name` (`str`): Name of the index. * `dimensions` (`Optional[int]`): Dimensions of the index. * `metric` (`str`): Metric of the index. * `cloud` (`str`): Cloud provider of the index. * `Optional[str]`0 (`str`): Region of the index. * `Optional[str]`2 (`str`): Host of the index. * `Optional[str]`4 (`Optional[str]`): Namespace of the index. * `Optional[str]`6 (`Optional[str]`): Base URL of the Pinecone API. * `Optional[str]`8 (`Optional[str]`9): Whether to initialize the index asynchronously. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = 100, **kwargs) ``` Upsert vectors into Pinecone in batches, one per (route, utterance) pair. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata to upsert. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): List of sparse embeddings to upsert. * `List[List[float]]`0 (`List[List[float]]`1): Number of vectors to upsert in a single batch. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = 100, **kwargs) ``` Upsert vectors into Pinecone in batches, one per (route, utterance) pair. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): List of metadata to upsert. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): List of sparse embeddings to upsert. * `List[List[float]]`0 (`List[List[float]]`1): Number of vectors to upsert in a single batch. #### delete [#delete] ```python def delete(route_name: str) -> list[str] ``` Delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### delete\_all [#delete_all] ```python def delete_all() ``` Delete all routes from index if it exists. **Returns**: `None`: None #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: IndexConfig #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`Optional[SparseEmbedding]`): An optional sparse vector to include in the query. * `kwargs` (`Any`): Additional keyword arguments for the query, including sparse\_vector. **Raises**: * `np.ndarray`0: If the index is not populated. **Returns**: `np.ndarray`1: A tuple containing an array of scores and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `kwargs` (`Any`): Additional keyword arguments for the query, including sparse\_vector. * `sparse_vector` (`Optional[dict]`): An optional sparse vector to include in the query. **Raises**: * `np.ndarray`0: If the index is not populated. **Returns**: `np.ndarray`1: A tuple containing an array of scores and a list of route names. #### delete\_index [#delete_index] ```python def delete_index() ``` Delete the index. **Returns**: `None`: None #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Asynchronously delete the index. #### ais\_ready [#ais_ready] ```python async def ais_ready(client_only: bool = False) -> bool ``` Checks if class attributes exist to be used for async operations. **Arguments**: * `client_only` (`bool, optional`): Whether to check only the client attributes. If False attributes will be checked for both client and index operations. If True only attributes for client operations will be checked. Defaults to False. **Returns**: `bool`: True if the class attributes exist, False otherwise. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. If the index is not initialized, initializes it first or returns 0. **Returns**: `int`: The total number of vectors. # semantic_router.index.postgres (/docs/semantic-router/v1/client-reference/index/postgres) ## MetricPgVecOperatorMap Objects [#metricpgvecoperatormap-objects] ```python class MetricPgVecOperatorMap(Enum) ``` Enum to map the metric to PostgreSQL vector operators. #### dotproduct [#dotproduct] inner product #### euclidean [#euclidean] L2 distance #### manhattan [#manhattan] L1 distance #### parse\_vector [#parse_vector] ```python def parse_vector(vector_str: Union[str, Any]) -> List[float] ``` Parses a vector from a string or other representation. **Arguments**: * `vector_str` (`Union[str, Any]`): The string or object representation of a vector. **Returns**: `List[float]`: A list of floats representing the vector. #### clean\_route\_name [#clean_route_name] ```python def clean_route_name(route_name: str) -> str ``` Cleans and formats the route name by stripping spaces and replacing them with hyphens. **Arguments**: * `route_name` (`str`): The original route name. **Returns**: `str`: The cleaned and formatted route name. ## PostgresIndexRecord Objects [#postgresindexrecord-objects] ```python class PostgresIndexRecord(BaseModel) ``` Model to represent a record in the Postgres index. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) -> None ``` Initializes a new Postgres index record with given data. **Arguments**: * `data` (`dict`): Field values for the record. #### to\_dict [#to_dict] ```python def to_dict() -> Dict ``` Converts the record to a dictionary. **Returns**: `Dict`: A dictionary representation of the record. ## PostgresIndex Objects [#postgresindex-objects] ```python class PostgresIndex(BaseIndex) ``` Postgres implementation of Index. #### \_\_init\_\_ [#__init__-1] ```python def __init__(connection_string: Optional[str] = None, index_prefix: str = "semantic_router_", index_name: str = "index", metric: Metric = Metric.COSINE, namespace: Optional[str] = "", dimensions: int | None = None, init_async_index: bool = False) ``` Initializes the Postgres index with the specified parameters. **Arguments**: * `connection_string` (`Optional[str]`): The connection string for the PostgreSQL database. * `index_prefix` (`str`): The prefix for the index table name. * `index_name` (`str`): The name of the index table. * `dimensions` (`int`): The number of dimensions for the vectors. * `metric` (`Metric`): The metric used for vector comparisons. * `Optional[str]`0 (`Optional[str]`): An optional namespace for the index. * `Optional[str]`2 (`Optional[str]`3): Whether to initialize the index asynchronously. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) -> None ``` Upserts records into the index, one per (route, utterance) pair. The table is created on first use. **Arguments**: * `embeddings` (`List[List[float]]`): A list of vector embeddings to add. * `routes` (`List[str]`): A list of route names corresponding to the embeddings. * `utterances` (`List[Any]`): A list of utterances corresponding to the embeddings. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): A list of metadata corresponding to the embeddings. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): Not supported, PostgresIndex is dense only. **Raises**: * `List[List[float]]`0: If the vector embeddings being added do not match the expected dimensions. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = 100, **kwargs) -> None ``` Asynchronously upserts records into the index in batches, one per (route, utterance) pair. The table is created on first use. **Arguments**: * `embeddings`: A list of vector embeddings to add. * `routes`: A list of route names corresponding to the embeddings. * `utterances`: A list of utterances corresponding to the embeddings. * `metadata_list`: (Optional) List of metadata dictionaries. * `sparse_embeddings`: Not supported, PostgresIndex is dense only. * `batch_size`: Number of records per batch insert. **Raises**: * `ValueError`: If the vector embeddings don't match expected dimensions. #### delete [#delete] ```python def delete(route_name: str) -> None ``` Deletes records with the specified route name. **Arguments**: * `route_name` (`str`): The name of the route to delete records for. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describes the index by returning its type, dimensions, and total vector count. **Returns**: `IndexConfig`: An IndexConfig object containing the index's type, dimensions, and total vector count. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Searches the index for the query vector and returns the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector. * `top_k` (`int`): The number of top results to return. * `route_filter` (`Optional[List[str]]`): Optional list of routes to filter the results by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): Not used, PostgresIndex is dense only. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the scores and routes of the top\_k results. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): Not used, PostgresIndex is dense only. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing an array of scores and a list of route names. #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the Postgres index. #### delete\_index [#delete_index] ```python def delete_index() -> None ``` Deletes the entire table for the index. #### adelete\_index [#adelete_index] ```python async def adelete_index() -> None ``` Asynchronously delete the entire table for the index. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index, 0 if the table does not exist yet. **Returns**: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. **Returns**: `int`: The total number of vectors. #### close [#close] ```python def close() ``` Closes the psycopg connection if it exists. #### has\_connection [#has_connection] ```python def has_connection() -> bool ``` Returns True if there is an active and valid psycopg connection, otherwise False. # semantic_router.index.qdrant (/docs/semantic-router/v1/client-reference/index/qdrant) ## QdrantIndex Objects [#qdrantindex-objects] ```python class QdrantIndex(BaseIndex) ``` The name of the collection to use #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Upsert records into the index, one point per (route, utterance) pair. **Arguments**: * `embeddings` (`List[List[float]]`): The embeddings to add. * `routes` (`List[str]`): The routes to add. * `utterances` (`List[str]`): The utterances to add. * `metadata_list` (`Optional[List[Dict[str, Any]]]`): The metadata to add. * `sparse_embeddings` (`Optional[List[SparseEmbedding]]`): Not supported, QdrantIndex is dense only. * `List[List[float]]`0 (`List[List[float]]`1): The batch size to use for the upload. #### delete [#delete] ```python def delete(route_name: str) ``` Delete records from the index. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: The index configuration. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to query. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to query. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### delete\_index [#delete_index] ```python def delete_index() ``` Delete the index. **Returns**: `None`: None #### convert\_metric [#convert_metric] ```python def convert_metric(metric: Metric) ``` Convert the metric to a Qdrant distance metric. **Arguments**: * `metric` (`Metric`): The metric to convert. **Returns**: `Distance`: The converted metric. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete records from the index by route name. **Arguments**: * `route_name` (`str`): The name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted (empty list, as Qdrant does not return IDs). #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Asynchronously delete the index (collection) from Qdrant. **Returns**: `None`: None #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[Any], metadata_list: Optional[List[Dict[str, Any]]] = None, sparse_embeddings: Optional[List[SparseEmbedding]] = None, batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Asynchronously upsert records into the index, one point per (route, utterance) pair. # semantic_router.routers.base (/docs/semantic-router/v1/client-reference/routers/base) the routing contract. a router scores every route for a query; everything else is shared. #### run [#run] ```python def run(coro: Coroutine[object, object, T]) -> T ``` run a coroutine from sync code, including from inside a running loop (notebooks). every sync call shares one background loop, so pooled connections survive between calls instead of being torn down with a fresh `asyncio.run` each time. #### in\_sync\_call [#in_sync_call] ```python def in_sync_call() -> bool ``` true while a sync method's coroutine runs on the shared background loop. routers use their clients' sync APIs there: an async client used on that loop binds to it, and then fails when the caller later awaits on a loop of their own. ## FitReport Objects [#fitreport-objects] ```python @dataclass(frozen=True) class FitReport() ``` #### accuracy [#accuracy] top-1 accuracy on queries that have a route, before any threshold #### ece [#ece] calibration error of the stated confidences ## BaseRouter Objects [#baserouter-objects] ```python class BaseRouter(ABC) ``` #### concurrency [#concurrency] cap on in-flight requests when scoring many queries #### afit [#afit] ```python async def afit(X: Sequence[str], y: Sequence[str | None], method: Method = "platt") -> FitReport ``` calibrate on labelled queries. a label of None means no route should match. #### aevaluate [#aevaluate] ```python async def aevaluate(X: Sequence[str], y: Sequence[str | None]) -> float ``` end-to-end accuracy with the threshold applied; None labels are right when nothing passes. #### to\_yaml [#to_yaml] ```python def to_yaml(path: str | Path) -> None ``` save the router to a yaml file; `load_router` reads it back. keys are never written. #### to\_json [#to_json] ```python def to_json(path: str | Path) -> None ``` save the router to a json file; `load_router` reads it back. keys are never written. # semantic_router.routers.compose (/docs/semantic-router/v1/client-reference/routers/compose) compose routers: fall through a chain, or merge several opinions into one. ## Chain Objects [#chain-objects] ```python class Chain(BaseRouter) ``` try routers in order; the first whose best confidence clears its bar answers. ## Merge Objects [#merge-objects] ```python class Merge(BaseRouter) ``` ask every router at once and take a weighted mean of their confidences per route. # semantic_router.routers.decision (/docs/semantic-router/v1/client-reference/routers/decision) a router that asks a decision model which route applies. one call answers many questions. ## DecisionRouter Objects [#decisionrouter-objects] ```python class DecisionRouter(BaseRouter) ``` routes by asking a decision model one choice question: which route applies. **Arguments**: * `model`: The decision model that answers, e.g. `GLiNER2DecisionModel()` locally or `TypeSafeDecisionModel()` over HTTP. * `routes`: The routes to choose between. * `instructions`: The question asked about each query. * `confidence_threshold`: The confidence a route needs, unless it sets its own. * `calibrator`: A fitted score -> probability map; `fit()` makes one. #### route\_question [#route_question] ```python def route_question() -> Question ``` the choice question for the current route set; descriptions beat utterance samples #### aask [#aask] ```python async def aask(state: object, questions: dict[str, Question]) -> dict[str, Answer] ``` answer several typed questions about one state in a single model pass. # semantic_router.routers.indexed (/docs/semantic-router/v1/client-reference/routers/indexed) a router that scores by similarity between the query and stored example utterances. ## IndexedRouter Objects [#indexedrouter-objects] ```python class IndexedRouter(BaseRouter) ``` #### routes [#routes] ```python @property def routes() -> list[Route] ``` the routes in the index, as last read from it. the index is the only place routes are written, and this view is only ever filled from it: on build, after this router's add / remove, on refresh(), and per call once the cache is older than refresh\_interval. a route another router wrote shows up here after a refresh, but a query finds it in the index straight away. #### refresh [#refresh] ```python def refresh() -> None ``` re-read the routes from the index, picking up other writers' changes. #### arefresh [#arefresh] ```python async def arefresh() -> None ``` re-read the routes from the index, picking up other writers' changes. # semantic_router.utils.defaults (/docs/semantic-router/v1/client-reference/utils/defaults) ## EncoderDefault Objects [#encoderdefault-objects] ```python class EncoderDefault(Enum) ``` Default model names for each encoder type. # semantic_router.utils.logger (/docs/semantic-router/v1/client-reference/utils/logger) ## CustomFormatter Objects [#customformatter-objects] ```python class CustomFormatter(colorlog.ColoredFormatter) ``` Custom formatter for the logger. #### add\_coloured\_handler [#add_coloured_handler] ```python def add_coloured_handler(logger) ``` Add a coloured handler to the logger. #### setup\_custom\_logger [#setup_custom_logger] ```python def setup_custom_logger(name) ``` Setup a custom logger. # Changelog (/docs/semantic-router/v1/user-guide/changelog) ### v1.1.2 [#v112] `1.1.2` fixes bugs in five encoders, in loading encoders from router files, and in calibration. Code and files written for `1.1.1` work unchanged. #### Fixes [#fixes] * `CohereEncoder` sends at most 96 texts per request, Cohere's limit for one embed call, and returns the embeddings in input order. A router with more than 96 utterances used to fail to encode them. * `BedrockEncoder` with a Cohere model returns one embedding per document. It used to return one per 20-word chunk, so it gave back more embeddings than documents. Each document is now sent whole, up to 96 per request. Embed v3 takes at most 2,048 characters per text, so a longer document is cut to fit following `truncate` in `model_kwargs`. `END`, the default, keeps the start; `START` keeps the end; and `NONE` raises a `ValueError` before any call. Embed v4 texts are sent uncut. ([#824](https://github.com/aurelio-labs/semantic-router/issues/824)) * `OpenAIEncoder` raises a clear `ValueError` before any call for an empty list, an empty string, or an item that isn't a string. It used to retry, then fail with `$.input is invalid`. Whitespace-only strings are still sent. ([#530](https://github.com/aurelio-labs/semantic-router/issues/530)) * `OpenAIEncoder` accepts models that tiktoken doesn't know, such as `nomic-embed-text` on an OpenAI-compatible server. It counts tokens with `cl100k_base` for them, where it used to raise `KeyError`. * `HFEndpointEncoder` stops resending a request once it succeeds. It used to send a successful request again until its retries ran out, three times by default. When an endpoint still answers 503 after the retries, it raises a `ValueError`; it used to return the error body as embeddings. * `GoogleEncoder` defaults to `text-embedding-005`, because Google retired the old default, `textembedding-gecko@003`. Both give 768-dimensional embeddings. `GOOGLE_EMBEDDING_MODEL` still overrides it. * An encoder block in a router file can leave out `name`, and the encoder then uses its default model. `AutoEncoder` does the same when passed `name=None`. This used to fail validation for `FastEmbedEncoder`, `HuggingFaceEncoder`, `VitEncoder`, `CLIPEncoder`, `BedrockEncoder` and `LocalEncoder`. * `fit` and `afit` raise a clear `ValueError` when a query scores no route, as on a router with no routes. They used to fail with `max() iterable argument is empty`. ([#806](https://github.com/aurelio-labs/semantic-router/issues/806)) ### v1.1.1 [#v111] #### Security [#security] * **LiteLLM 1.107.0 is excluded.** That PyPI release contained malware (a supply-chain attack, live on PyPI on 21 October 2026 from 11:39 to 13:23 UTC), and the `litellm` extra allowed it. The extra is now `litellm>=1.84.0,!=1.107.0`. PyPI has removed 1.107.0, but a private mirror may still serve it. If you installed `semantic-router[litellm]` or `[all]` without a lockfile in that window, check without starting Python in that environment: any Python start, `pip` included, runs the malware again. Look at your lockfile or deployment records, or search the environment from a shell, for example `find -name 'litellm-1.107.0.dist-info' -o -name cook.pth -o -name sitecustomize.py`. `pip show litellm` is safe only in an environment you know is clean, such as one you've just rebuilt. If 1.107.0 was installed, follow [LiteLLM's incident guidance](https://docs.litellm.ai/blog/security-incident-oct-21-2026#what-to-do-if-you-are-affected): isolate the host, rebuild the environment rather than reinstalling into it, and rotate every credential it could reach, from a clean machine. Finding nothing doesn't prove the environment was never exposed. * **certifi 2026.10.19 in the lockfile.** It removes the `emSign ECC Root CA - G3` root, which compromised eMudhra intermediate keys chain to ([advisory](https://github.com/advisories/GHSA-6q48-6c7w-9gw2)). semantic-router doesn't pin certifi, so `pip install -U certifi` updates the bundle in an existing environment; images and vendored bundles need rebuilding. Connections to Postgres or MongoDB over TLS may use your operating system's trust store or a CA bundle you configured instead of certifi: update whichever one they use. ### v1.1.0 [#v110] `1.1.0` adds a MongoDB Atlas index and fixes four bugs. Code and files written for `1.0.2` work unchanged, apart from the `QdrantIndex.ais_ready()` change below. #### Feature: MongoDB Atlas Vector Search [#feature-mongodb-atlas-vector-search] * `MongoDbIndex` stores routes in MongoDB and searches them with Atlas Vector Search: `pip install "semantic-router[mongodb]"`. * The first `add` creates the collection and its vector search index, so there's nothing to set up in Atlas first. Atlas makes new records searchable a moment after they're written, so `add` waits until they are (up to `sync_timeout`, 30 seconds by default). * Cosine and dot product scores are the raw similarity, the same scale as the other indexes. `namespace` keeps tenants apart in one collection. * The connection string comes from `connection_uri` or `MONGO_CONNECTION_URI`, and is never written to a file. Files save the rest, so a router on it saves and loads like any other. #### Fixes [#fixes-1] * `BedrockEncoder` now retries a failed call (throttling, an expired session token), making up to three attempts with backoff. It used to raise on the first error. * `PineconeIndex.aquery()` accepts a sparse vector as a dict, as `query()` does. * `QdrantIndex.ais_ready()` falls back to the sync check for an in-memory index, so it agrees with `is_ready()`. * `QdrantIndex.ais_ready()` now raises when the check itself fails (Qdrant unreachable), as `is_ready()` does. It used to log a warning and return `False`. **If you call it yourself, handle the exception** where you used to treat `False` as "not ready". ### v1.0.2 [#v102] `1.0.2` adds a decision model that runs locally. Code and files written for `1.0.1` work unchanged. #### Feature: GLiNER2.5-Decide, a local decision model [#feature-gliner25-decide-a-local-decision-model] * `GLiNER2DecisionModel` runs fastino/GLiNER2.5-Decide in-process, so `DecisionRouter(model=GLiNER2DecisionModel(), routes=routes)` routes with no network call and no API key. * It answers `choice`, `noul` and `score` questions like the HTTP models, batches states (`batch_size`, default 8) and runs off the event loop. It uses CUDA, then MPS, then CPU, unless you pass `device`. * `classifier=` takes a `gliner2` classifier you loaded yourself, such as one with a fine-tuned adapter. * It needs the `local` extra, which now includes `gliner2` (Python \< 3.13, like the other torch-based models): `pip install "semantic-router[local]"`. * Files save it as `model: {type: gliner2, name: fastino/GLiNER2.5-Decide}`, plus `device` and `batch_size` when you set them. ### v1.0.1 [#v101] `1.0.1` makes the decision model a component you pass to `DecisionRouter`, the way you pass an encoder to `IndexedRouter`. It changes `DecisionRouter`'s arguments, so code and files written for `1.0.0` need a small edit. #### Breaking: decision models are a component [#breaking-decision-models-are-a-component] * `DecisionRouter(model=TypeSafeDecisionModel(), routes=routes)` replaces `DecisionRouter(routes=routes)`. The connection settings move to the model: `api_key`, `base_url`, `timeout`, `retries` and `concurrency`, and `model` becomes the model's `name`. * `SystemOneDecisionModel(name=..., base_url=...)` talks to any `/v1/systemone` server (Laya, Von or your own) and sends a key only if you pass one. `TypeSafeDecisionModel` is the same with TypeSafe's defaults, and reads `JEV_API_KEY`. * Subclass `DecisionModel` and implement `aask` to route with another kind of model. * `choice`, `noul` and `score` move to `semantic_router.decision_models`. * Files save the model as a block, `model: {type: typesafe, name: jev-latest}`. A `1.0.0` file, which wrote `model: jev-latest`, fails to load with an error that shows the new form. ### v1.0.0 [#v100] The `1.0.0` release rebuilds the routing layer. A router is now anything that scores every route; the base class turns scores into calibrated confidence, and routers compose. It's a breaking release: the [migration guide](guides/migration-to-v1) covers every change, with before and after code. #### Feature: Router types [#feature-router-types] * `IndexedRouter` replaces `SemanticRouter`. Passing a `sparse_encoder` makes it hybrid, which replaces `HybridRouter`. The hybrid `alpha` (the weight on the dense score) defaults to 0.7, not 0.3, and now weights the dense side on `HybridLocalIndex` too. * `DecisionRouter` routes with a decision model over TypeSafe's `/v1/systemone` API (Jev, Laya, Von), and `aask()` answers several `choice`, `noul` and `score` questions about one message in a single call. * `Chain` falls through from a fast router to a slower one when the fast one isn't confident. `Merge` takes a weighted average of several routers. * Subclass `BaseRouter` and implement one async method, `_scores`, to build your own router. * `DecisionRouter(concurrency=8)` sets how many requests a batch keeps in flight. #### Feature: Calibration [#feature-calibration] * `fit()` learns a map from raw score to the probability that the top route is right (Platt or isotonic), and returns a `FitReport` with accuracy and calibration error. It replaces the random threshold search. * `confidence_threshold` replaces `score_threshold`, on the router and on each route. A per-call `threshold=` overrides both. * `RouteChoice` is now `name`, `confidence` and `calibrated`. #### Feature: The index is the source of truth [#feature-the-index-is-the-source-of-truth] * `router.routes` is a cached view of the index, filled on build and after the router's own `add`/`remove`. `refresh()` / `arefresh()` re-read it, and `refresh_interval` re-reads it during calls once it's that many seconds old. A query always searches the index itself. * An `IndexedRouter` can open an index that 0.x filled: `IndexedRouter(encoder=..., index=...)` with no routes reads them back. #### Feature: Config files [#feature-config-files] * `router.to_yaml(path=)`, `router.to_json(path=)` and `load_router(path=)` save and load any router type, keyed on `router_type`, with the calibrator and without secrets. #### Removed [#removed] * Index sync: `auto_sync`, `sync()`, `is_synced()`, `get_utterance_diff()`, and the hash, lock and config records. The index is the single source of truth. * Dynamic routes and the `semantic_router.llms` package, `function_schemas`, `RouteChoice.function_call` and `similarity_score`. * `route_filter`, `vector=` and `simulate_static=` on router calls. * The default `OpenAIEncoder()`: the encoder is now required. * `score_threshold` on encoders, and `llama-cpp-python` from the `[local]` extra. * Default thresholds: with no `confidence_threshold`, the best route always wins. *** ### v0.1.12 [#v0112] The `0.1.12` release brings Pinecone v7 support and AWS Bedrock boto3 client integration, improving compatibility and expanding cloud deployment options. #### Feature: Pinecone v7 Upgrade [#feature-pinecone-v7-upgrade] Semantic Router now supports Pinecone Python SDK v7, providing: * Improved data plane performance and reliability * Enhanced async support for high-throughput applications * Simplified API structure for better developer experience * Better error handling and retry logic The upgrade is backward compatible - existing code continues to work without changes. For shared index deployments, set `PINECONE_INDEX_NAME` to reuse existing indexes and avoid quota limits. Semantic Router automatically isolates data using namespaces. #### Feature: Bedrock boto3 Client Support [#feature-bedrock-boto3-client-support] Added support for custom boto3 clients in the `BedrockEncoder`, enabling: * Advanced AWS credential management (IAM roles, cross-account access) * Custom retry policies and timeout configurations * VPC endpoint support for private deployments * Better integration with existing AWS infrastructure This provides greater flexibility for enterprise AWS deployments while maintaining backward compatibility with the existing credential-based approach. #### Chore: Relaxed OpenAI SDK Dependency [#chore-relaxed-openai-sdk-dependency] Updated OpenAI SDK dependency constraints from `<2.0.0` to `<3.0.0`, allowing compatibility with OpenAI SDK v2.x releases. This provides access to newer OpenAI features and improvements while maintaining stability through the v2 major version. *** ### v0.1.11 [#v0111] The `0.1.11` release introduces new encoder options for local and self-hosted deployments, alongside sparse encoding improvements and CI/CD enhancements. #### Feature: Local Encoder [#feature-local-encoder] Added `LocalEncoder` for fully local embedding generation using sentence-transformers: * No API keys or internet connection required * Automatic device selection (CUDA, MPS, CPU) * Support for any sentence-transformers model * Privacy-first design - all data stays on your machine Perfect for offline deployments, privacy-sensitive applications, or development environments. #### Feature: Local Sparse Encoder [#feature-local-sparse-encoder] Added sparse encoder support using sentence transformers with `LocalSparseEncoder`. * Same offline advantages as the Local Encoder above. * Better handling of sentence boundaries * Improved BM25 and TF-IDF implementations * Enhanced compatibility with `HybridRouter` #### Feature: Ollama Encoder [#feature-ollama-encoder] Introduced `OllamaEncoder` for using Ollama-hosted embedding models: * Works with any Ollama embedding model (nomic-embed-text, mxbai-embed-large, etc.) * Full control over model versions and hosting * Low latency with local Ollama instances * Both sync and async support Ideal for organizations wanting to self-host embedding models while maintaining API-like convenience. #### Feature: Dagger CI [#feature-dagger-ci] Implemented Dagger for CI/CD pipeline, providing: * Faster, more reliable builds * Better caching and parallelization * Consistent local and remote execution * Improved developer experience #### Chore: Torch Dependency Optimization [#chore-torch-dependency-optimization] Removed torch from main dependencies to reduce installation size. PyTorch is now only installed when needed via `semantic-router[local]` extras, reducing default installation from \~2GB to \<100MB. *** ### v0.1.10 [#v0110] The `0.1.10` release was primarily focused on expanding async support for `QdrantIndex`, `PostgresIndex`, and `HybridRouter`, alongside many synchronization and testing improvements. #### Feature: Expanded Async Support [#feature-expanded-async-support] * **QdrantIndex**: Async methods have been brought inline with our other indexes, ensuring consistent behavior. * **PostgresIndex**: Async methods have been added to the `PostgresIndex` for improved performance in async environments. * **HybridRouter**: Async support for the `HybridRouter` is now aligned with the `SemanticRouter`, providing a more consistent experience. #### Fixes and Optimizations [#fixes-and-optimizations] * **LocalIndex Bug Fix**: Added a `metadata` attribute to the local index. This fixes a bug where `LocalIndex` embeddings would always be recomputed, as reported in [issue #585](https://github.com/aurelio-labs/semantic-router/issues/585). * Various other bug fixes and optimizations have been included in this release. * The `urllib3` library has been upgraded. * Test compatibility and synchronization have been optimized. *** ### v0.1.9 [#v019] The `0.1.9` update focuses on improving support for our local deployment options. We have standardized the `PostgresIndex` to bring it in line with other index options and prepare it for future feature releases. For `local` extras (including `transformers` and `llama_cpp` support) and `postgres` extras we have resolved issues making those extras unusable with Python 3.13. Continue reading below for more detail. #### Feature: Improvements to `postgres` Support [#feature-improvements-to-postgres-support] * **Upgrade from psycopg2 to v3 (psycopg)**: We've upgraded our PostgreSQL driver from psycopg2 to the newer psycopg v3, which provides better performance and modern Python compatibility. * **Standardization of sync methods**: The `PostgresIndex` class now has standardized synchronous methods that integrate seamlessly into our standard pytest test suite, ensuring better testing coverage and reliability. * **Addition of IndexType support**: We've introduced `IndexType` which includes `FLAT`, `IVFFLAT`, and `HNSW` index types. Both `FLAT` and `IVFFLAT` map to the `IVFFLAT` index in pgvector (pgvector does not currently support `FLAT` and so `IVFFLAT` is the closest approximation - but our other indexes do). `FLAT` is now the default index type. We recommend `HNSW` for high-scale use cases with many millions of utterances due to its higher memory requirements and complexity. #### Feature: Configurable Logging [#feature-configurable-logging] * **Environment variable log level control**: Logger now supports configurable log levels via environment variables. Set `SEMANTIC_ROUTER_LOG_LEVEL` or `LOG_LEVEL` to control logging verbosity (e.g., `DEBUG`, `INFO`, `WARNING`, `ERROR`). Defaults to `INFO` if not specified. #### Fix: Local Installation for Python 3.13 and up [#fix-local-installation-for-python-313-and-up] Python 3.13 and up had originally been incompatible with our local installations due to the lack of compatability with PyTorch and the (then) new version of Python. We have now added the following version support for `local` libraries: ```python local = [ "torch>=2.6.0 ; python_version >= '3.13'", "transformers>=4.50.0 ; python_version >= '3.13'", "tokenizer>=0.20.2 ; python_version >= '3.13'", "llama-cpp-python>=0.3.0 ; python_version >= '3.13'", ] ``` #### Fix: Consistent Index Length Behavior [#fix-consistent-index-length-behavior] * **Standardized `__len__` method across all index implementations**: All index types now consistently return `0` when uninitialized, preventing potential `AttributeError` exceptions that could occur in `PineconeIndex` and `QdrantIndex` when checking the length of uninitialized indexes. #### Chore: Broader and More Useful Tests [#chore-broader-and-more-useful-tests] We have broken our tests apart into strict unit and integration test directories. Now, when incoming PRs are raised we will no longer trigger integration tests that require API keys to successfully run. To ensure we're still covering all components of the library we have broadened our testing suite to extensively test `LocalIndex`, `PineconeIndex` (via Pinecone Local), `PostgresIndex`, and `QdrantIndex` within those unit tests. # Overview (/docs/semantic-router/v1/user-guide/concepts/overview) Semantic routing sends an input — text, an image, audio — to the right handler based on what it *means*, not on keywords or hand-written rules. People say the same thing a hundred different ways. Semantic routing handles that variety without you enumerating every phrasing. ## Semantic space [#semantic-space] Here's the core idea. Imagine a huge coordinate system where every point is a concept. "I need help with my password" sits right next to "Can't log in to my account", and far from "What's the weather forecast?". That's semantic space. Meaning becomes geometry, and similarity becomes a distance you can measure. * Each point (a vector) represents the meaning of some content. * Distance between points is semantic difference. * Similar meanings cluster together, whatever the exact wording. So synonyms, paraphrases, and related ideas all land close to each other — and you never program the variations by hand. ### Encoders [#encoders] To put content into semantic space, you *encode* it into a vector. That's the job of an encoder (you'll also hear "embedding model" or "bi-encoder"). An encoder takes the input, analyzes its features, and outputs a fixed-size vector of numbers — usually hundreds or thousands of dimensions. "How's the weather today?" might become `[0.12, -0.34, 0.56, ...]`. "What's the temperature outside?" becomes a different but nearby vector, because the meanings are close. Semantic Router supports two families: * **Dense encoders** (`OpenAIEncoder`, `HuggingFaceEncoder`, …) fill every dimension. They capture rich semantic relationships. * **Sparse encoders** (`AurelioSparseEncoder`, `BM25Encoder`, …) leave most dimensions at zero. They excel at exact keywords and term frequency. ### Multimodal routing [#multimodal-routing] Text is the common case, but anything you can encode, you can route: * **Images.** `CLIPEncoder` and `VitEncoder` place images in the same space as text, so you can compare across modalities. * **Audio.** Speech or sound, routed on content or tone. * **Mixed content.** Text and images together, encoded jointly or separately. That's what lets you route on what's *in* an image, or on the combined meaning of text plus a picture. ### Making the decision [#making-the-decision] Once everything is a vector, routing is a similarity calculation. The usual measures: * **Cosine similarity**: cos(θ) = (A·B)/(||A||·||B||) * **Euclidean distance**: d(A,B) = √(Σ(Aᵢ-Bᵢ)²) * **Dot product**: A·B = Σ(Aᵢ·Bᵢ) An `IndexedRouter` compares the incoming query against every route's example utterances and gives each route a score. Raw similarities are hard to act on, though: 0.8 means something different for every encoder and every set of routes. So the router can be *calibrated*. Fit it on some labelled queries and it learns to turn a score into the probability that the route is right. Then a threshold like 0.9 means "act only when you're 90% sure", and the best route above it wins. ### When similarity isn't enough [#when-similarity-isnt-enough] Some decisions depend on instructions, not resemblance: "refunds, but not pricing questions before a purchase". A `DecisionRouter` hands those to a small, fast decision model that reads your route descriptions and returns a probability for each route. You can chain the two, so the embedding router answers the easy queries in milliseconds and only the ambiguous ones go to the model. To learn what decision models are and where they fit, read [Understanding Jev and Where It Fits in the AI Stack](https://jamesbriggs.io/understanding-jev) or watch [I Tested Jev AI Against LLMs and Open Source](https://youtu.be/P-t4F_UlxkI). ## The workflow [#the-workflow] 1. **Define routes**: example utterances for each decision, and a description if a decision model will read it. 2. **Pick an encoder**: based on content type and performance needs. 3. **Build the router**: connect the encoder, routes and an index. 4. **Calibrate it**: fit on labelled queries the router hasn't seen, then set a threshold. 5. **Write handlers**: the logic for each route, and a fallback for "no route". 6. **Route inputs**: encode, score, decide, dispatch. Semantic Router handles the vector math, the scoring, the calibration and the decision. You focus on defining good routes and writing the handlers. # Architecture (/docs/semantic-router/v1/user-guide/concepts/architecture) ## System overview [#system-overview] Every router does one thing: given a query, it scores every route. Everything after that is shared. The base class turns the scores into confidences (calibrated, if you've fitted it), applies the thresholds, and hands back a `RouteChoice`. Routers differ only in how they score: * **`IndexedRouter`** scores by embedding similarity: an encoder plus an index. * **`DecisionRouter`** scores by asking a decision model, with one HTTP call. * **`Chain`** and **`Merge`** score by asking other routers. A router of your own is one more subclass: implement `_scores` and the rest comes free. See [routers](../components/routers#build-your-own-router). ## Core components [#core-components] ### Routes [#routes] A route is one decision a router can make. The same `Route` works with every router type. `IndexedRouter` embeds the `utterances`; `DecisionRouter` reads the `description`. See [routes](../components/routes). ### Encoders [#encoders] Encoders map inputs into semantic space. `IndexedRouter` uses them; `DecisionRouter` doesn't. * **Dense encoders** produce continuous vectors (OpenAI, FastEmbed, Hugging Face, ...). * **Sparse encoders** produce mostly-zero vectors keyed on terms (BM25, TF-IDF, ...). Add one to an `IndexedRouter` for hybrid search. * **Asymmetric encoders** embed queries and documents differently; the router calls the right side for each. See [encoders](../components/encoders). ### Indexes [#indexes] Indexes store utterance vectors and search them. The index is the single source of truth for an `IndexedRouter`'s routes: building a router writes to it, and `router.routes` is a cached view of it, which `refresh()` re-reads. See [indexes](../components/indexes). ### Calibrator [#calibrator] A `Calibrator` maps a raw score to the probability that the top route is right. `fit()` builds one from labelled queries, with Platt scaling or isotonic regression. Both are monotone, so calibration never changes which route ranks first, only the number attached to it. See [calibration](../features/calibration). ## Data flow [#data-flow] An `IndexedRouter` call: A `Chain` of an `IndexedRouter` and a `DecisionRouter`: ## Sync and async [#sync-and-async] The router logic is async all the way down. Every sync method (`__call__`, `fit`, `add`, ...) runs its async twin on one background event loop that all routers share. That keeps HTTP connections pooled between calls, so repeated calls to a remote encoder, index or decision model don't pay to reconnect. It also means sync calls work inside notebooks, which already run a loop. In async code, use the `a`-methods with `await`. ## Performance notes [#performance-notes] * **Encoding dominates.** For an `IndexedRouter`, nearly all of a call's time is embedding the query. A local encoder or a fast embedding API matters more than the index. * **Batch where you can.** `fit()` and `evaluate()` embed all their queries in one encoder call. * **A Chain pays only when it must.** Confident queries stop at the first router; only ambiguous ones pay for the decision model too. * **Warm up remote models.** The first call to a decision model can be much slower than the rest. Make one call at startup. # Benchmarks (/docs/semantic-router/v1/user-guide/concepts/benchmarks) How the router types compare on one task, all measured the same way by [`benchmarks/accuracy.py`](https://github.com/aurelio-labs/semantic-router/blob/main/benchmarks/accuracy.py). The raw results are in [`benchmarks/results/accuracy.json`](https://github.com/aurelio-labs/semantic-router/blob/main/benchmarks/results/accuracy.json). ## The task [#the-task] [CLINC150](https://github.com/clinc/oos-eval) is an intent dataset with an out-of-scope class: queries that match none of the intents, which a router should turn away. * **Routes:** 15 intents picked at random (seed 0). Each route gets 10 of the intent's training utterances and a one-line description written from the intent's name alone. * **Fitting:** every router is [calibrated](../features/calibration) on 400 validation queries, 300 in scope and 100 out of scope. * **Testing:** 600 held-out test queries, 450 in scope and 150 out of scope. A router answers when its calibrated confidence is at least 0.5, and returns no route otherwise. The intents are book\_hotel, direct\_deposit, ingredient\_substitution, maybe, mpg, nutrition\_info, pto\_used, report\_fraud, restaurant\_suggestion, routing, timer, tire\_change, transactions, transfer and yes. ## Accuracy and calibration [#accuracy-and-calibration] | Router | Top-1 | End-to-end | In scope | Out of scope turned away | Calibration error | | ------------------------------------------------ | ----- | ---------- | -------- | ------------------------ | ----------------- | | `IndexedRouter`, OpenAI `text-embedding-3-small` | 97.3% | 94.5% | 96.4% | 88.7% | 0.033 | | `IndexedRouter`, FastEmbed `bge-small-en-v1.5` | 97.3% | 92.0% | 95.3% | 82.0% | 0.042 | | `IndexedRouter`, hybrid (OpenAI and TF-IDF) | 94.9% | 89.3% | 91.1% | 84.0% | 0.055 | | `DecisionRouter`, Jev | 99.3% | 97.8% | 98.7% | 95.3% | 0.017 | | `DecisionRouter`, GLiNER2.5-Decide (local) | 97.6% | 93.8% | 92.7% | 97.3% | 0.029 | | `Chain`: OpenAI index, then Jev | 98.0% | 96.2% | 97.6% | 92.0% | 0.005 | | `Merge`: OpenAI index and Jev | 99.3% | 98.3% | 98.9% | 96.7% | 0.011 | | `Chain`: FastEmbed index, then Jev | 98.2% | 95.8% | 98.0% | 89.3% | 0.013 | | `Merge`: FastEmbed index and Jev | 99.3% | 98.3% | 98.9% | 96.7% | 0.018 | * **Top-1:** of the in-scope queries, how often the highest-scoring route is the right one, before any threshold. * **End-to-end:** of all 600 test queries, how often the router does the right thing at the 0.5 bar: the right route for an in-scope query, and no route for an out-of-scope one. * **In scope:** end-to-end on the 450 in-scope queries alone. * **Out of scope turned away:** of the 150 out-of-scope queries, how many get no route. * **Calibration error:** the expected calibration error (ECE) after `fit()`: the average gap between the confidence a router states and how often it's right. 0 is perfect. Before `fit()`, the single routers' raw scores are much further off: | Router | Calibration error before `fit()` | | ---------------------------------- | -------------------------------- | | `IndexedRouter`, OpenAI | 0.314 | | `IndexedRouter`, FastEmbed | 0.222 | | `IndexedRouter`, hybrid | 0.327 | | `DecisionRouter`, Jev | 0.150 | | `DecisionRouter`, GLiNER2.5-Decide | 0.221 | A `Chain` or `Merge` is built from routers that are already fitted. ## Latency [#latency] | Router | p50 | p95 | Throughput | | ---------------------------------- | ------ | ------ | ------------- | | `IndexedRouter`, OpenAI | 394 ms | 608 ms | 35 queries/s | | `IndexedRouter`, FastEmbed | 3 ms | 3 ms | 978 queries/s | | `IndexedRouter`, hybrid | 340 ms | 451 ms | 43 queries/s | | `DecisionRouter`, Jev | 257 ms | 434 ms | 26 queries/s | | `Chain`: OpenAI index, then Jev | 454 ms | 793 ms | 25 queries/s | | `Merge`: OpenAI index and Jev | 345 ms | 577 ms | 25 queries/s | | `Chain`: FastEmbed index, then Jev | 3 ms | 336 ms | 52 queries/s | | `Merge`: FastEmbed index and Jev | 263 ms | 538 ms | 29 queries/s | p50 and p95 are over 30 single queries, after two warm-up calls. Throughput is a batch of 50 queries scored at once. These were timed on 15 October 2026 on a quiet 32-core Linux machine, against the live OpenAI and Jev APIs, so the API-backed numbers include that machine's network round trip. Yours will differ. The OpenAI chain answered 66.8% of the test queries from the index alone (87.6% of the in-scope ones) and sent the rest to Jev. GLiNER2.5-Decide was timed separately, on an Apple M4 Max on 17 October 2026: | Setup | p50 | Throughput | | ---------------------------------------- | ------ | ------------ | | MPS, the benchmark's 15 described routes | 211 ms | 5 queries/s | | MPS, 2 short routes | 50 ms | 47 queries/s | | CPU, the benchmark's 15 described routes | 328 ms | 2 queries/s | Its latency grows with the number of routes and the length of their descriptions, because every route goes through the model in one pass with the query. ## Reading the results [#reading-the-results] * **Most accurate:** Jev, alone or merged with an index. Jev gets 99.3% top-1, and the merges reach 98.3% end-to-end. * **Fastest:** a FastEmbed index answers in 3 ms, with the same top-1 as OpenAI embeddings (97.3%). It turns away fewer out-of-scope queries, though (82.0% against 88.7%). * **Fast and accurate:** a `Chain` answers most queries from the index and pays for Jev only on the rest. The FastEmbed chain has a 3 ms p50 and 95.8% end-to-end. * **Local decision model:** GLiNER2.5-Decide gets 97.6% top-1 with no API key, and turns away the most out-of-scope queries (97.3%). It also turns away more in-scope ones (92.7%) at the 0.5 bar. A bar of 0.3, picked on the validation set, lifts its end-to-end to 95.0%. * **Hybrid:** adding TF-IDF lowers accuracy here, because none of these routes hinge on exact keywords. See [routers](../components/routers) for when sparse helps. * **Calibration:** every router's raw scores are off by 0.15 to 0.33. After `fit()`, all of them are within 0.06. Fit before you set a threshold. ## Run it yourself [#run-it-yourself] ```bash uv run python benchmarks/accuracy.py --dry-run # prints the API budget, then stops uv run python benchmarks/accuracy.py ``` It needs `OPENAI_API_KEY` and `JEV_API_KEY`. Jev's answers are cached in `benchmarks/.cache/`, keyed on the whole request, so a rerun only spends Jev calls on latency. `--latency none` measures accuracy alone, and `--latency decision_jev,chain` re-times only those routers. GLiNER2.5-Decide needs the `local` extra, so run it on Python 3.12: ```bash uv run --python 3.12 --extra local --extra fastembed python benchmarks/accuracy.py ``` # Routes (/docs/semantic-router/v1/user-guide/components/routes) A `Route` is one decision a router can make: "this is a billing question", "this is small talk", "this needs a human". Every router type takes the same `Route` objects, so you can define your routes once and use them with an `IndexedRouter`, a `DecisionRouter`, or both. ## Fields [#fields] ```python from semantic_router import Route billing = Route( name="billing", utterances=[ "i want a refund", "why was i charged twice?", "where can I find my invoice?", ], description="Money already paid or owed: refunds, charges, invoices.", confidence_threshold=0.9, metadata={"team": "payments"}, ) ``` | Field | What it's for | Read by | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `name` | The route's identifier. It's what the router returns. | every router | | `utterances` | Example queries that belong to the route. | `IndexedRouter` embeds them; `DecisionRouter` reads the first five when there's no description | | `description` | What the route covers, stated literally. | `DecisionRouter` | | `confidence_threshold` | The confidence this route needs before a router returns it. Overrides the router's own threshold. | every router | | `metadata` | Anything else you want to keep with the route, such as an owner or a handler name. Stored with the route in the index. | you | Only `name` is required. An `IndexedRouter` needs utterances to match against; a `DecisionRouter` works from a description alone. ## Utterances [#utterances] Utterances are examples, not keywords. Write them the way your users actually talk, and cover the different ways people ask for the same thing. Five to twenty per route is a good start. More helps when a route is broad or its neighbours are close. Keep the queries you use to *test* or *calibrate* a router separate from the utterances. A router always matches its own utterances well, so testing on them tells you nothing. See [calibration](../features/calibration). ## Descriptions [#descriptions] A decision model reads the description and nothing else, so say exactly what belongs in the route. These models take you literally and don't fill in gaps: ```python # vague: the model has to guess where the edges are Route(name="billing", description="Billing stuff.") # literal: says what's in, and what's next door Route( name="billing", description="Money already paid or owed: refunds, charges, invoices. Not pricing questions before a purchase.", ) ``` `IndexedRouter` doesn't embed the description. Descriptions aren't phrased like user queries, so mixing them in with the utterances would skew the scores. It does store the description with the route, so a router that reads the routes back from the index gets it too. ## Thresholds [#thresholds] A route's `confidence_threshold` is the bar its confidence must clear before a router returns it. When a route doesn't set one, the router's `confidence_threshold` applies. When neither is set, there's no bar, and the best route always wins. Use a route-level bar when some decisions are costlier to get wrong than others: ```python routes = [ # cheap to be wrong Route(name="flag_possible_bug", utterances=["this looks like a bug", "is this an off-by-one?"], confidence_threshold=0.6), # costly to be wrong Route(name="refund_customer", utterances=["refund this customer", "give them their money back"], confidence_threshold=0.95), ] ``` These numbers mean most once the router is calibrated: then 0.95 means "right at least 95% of the time". See [calibration](../features/calibration). ## What a router returns [#what-a-router-returns] A router call returns a `RouteChoice`: ```python class RouteChoice(BaseModel): name: Optional[str] = None # the route, or None if nothing cleared its bar confidence: Optional[float] = None calibrated: bool = False # True when confidence is a probability ``` `confidence` is a probability when `calibrated` is `True`: after `fit()`, or from a router like `DecisionRouter` whose scores are already probabilities. Otherwise it's the router's raw score, such as a cosine similarity. ## Saving routes [#saving-routes] `Route.to_dict()` and `Route.from_dict()` round-trip a route through a plain dict. To save a whole router, routes included, see [save and load](../guides/save-load-from-file). # Routers (/docs/semantic-router/v1/user-guide/components/routers) A router takes a query, scores every route, and hands back a decision. Version 1 has several kinds of router, and they all share one contract: each scores the routes its own way, and the base class does the rest. Thresholds, calibration, evaluation, sync and async calling, and adding and removing routes all work the same on every router. For how they compare on accuracy, calibration and latency, see the [benchmarks](../concepts/benchmarks). ```python from semantic_router import Chain, DecisionRouter, IndexedRouter, Merge ``` | Router | Scores routes by | Needs | | ----------------------------------- | -------------------------------------------------------- | -------------------------------------------------- | | [`IndexedRouter`](#indexedrouter) | similarity between the query and each route's utterances | an encoder; an index (in memory by default) | | [`DecisionRouter`](#decisionrouter) | asking a decision model which route applies | a Jev API key (or another model with the same API) | | [`Chain`](#chain-and-merge) | trying routers in order until one is confident | other routers | | [`Merge`](#chain-and-merge) | averaging several routers' confidences | other routers | ## IndexedRouter [#indexedrouter] The `IndexedRouter` embeds every route's utterances once, stores them in an index, and at query time finds the stored utterances closest to the query. It's fast, it runs locally if your encoder does, and it's what most apps start with. ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import FastEmbedEncoder routes = [ Route(name="weather", utterances=["how's the weather?", "is it raining?", "will it be sunny tomorrow?"]), Route(name="politics", utterances=["tell me about politics", "who's the president?", "what do you think of the election?"]), ] router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes, ) router("what's the weather like today?").name ``` ``` [Out]: 'weather' ``` The constructor embeds the utterances and writes them to the index before it returns, so the router is ready to call. | Argument | Default | What it does | | ---------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `encoder` | required | The dense encoder that embeds utterances and queries. | | `routes` | none | Routes to write to the index. Leave it out to use the routes already in the index. | | `refresh_interval` | `None` | Seconds before the router re-reads its routes from the index on the next call, to see other writers' changes. `None` never re-reads; call `refresh()` instead. See [sharing an index](indexes#sharing-an-index). | | `index` | in memory | Where the vectors live: `LocalIndex`, `PineconeIndex`, `QdrantIndex`, `PostgresIndex`, ... See [indexes](indexes). | | `sparse_encoder` | `None` | Set it to make the router hybrid (below). | | `alpha` | `0.7` | Hybrid only: the weight on the dense score; the sparse score gets `1 - alpha`. | | `top_k` | `5` | How many stored utterances to fetch per query. | | `aggregation` | `"mean"` | How a route's hits combine into its score: `"mean"`, `"max"` or `"sum"`. | | `confidence_threshold` | `None` | The router's default bar. See [thresholds](#thresholds). | | `calibrator` | `None` | A fitted `Calibrator`. Usually you call `fit()` instead. | A route's score is the aggregate of its utterances among the `top_k` hits, and a route with no hits scores 0. If you ask for several routes with `limit`, raise `top_k` so that more routes get a chance to appear. ### Hybrid search [#hybrid-search] Pass a sparse encoder as well, and the router weighs exact keywords alongside meaning. That helps when queries carry terms that must match: product codes, names, jargon. ```python from semantic_router.encoders import BM25Encoder, FastEmbedEncoder hybrid = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), sparse_encoder=BM25Encoder(), routes=routes, alpha=0.7, ) ``` Without an `index`, a hybrid router uses a `HybridLocalIndex`. The only remote index that stores sparse vectors is `PineconeIndex`; the dense-only indexes raise an error if you pair them with a `sparse_encoder`. `alpha` sets the balance: 1.0 is dense only, 0.0 is sparse only. The default, 0.7, keeps meaning in charge and uses keywords as a boost. Top-1 accuracy with a local FastEmbed model (`bge-small-en-v1.5`) on `HybridLocalIndex`: | Queries | Sparse encoder | 0.0 | 0.3 | 0.5 | 0.7 | 0.9 | 1.0 | | ----------------------------- | -------------- | --- | --- | --- | ------- | --- | --- | | notebook 06, 59 queries | BM25 | .69 | .76 | .88 | **.93** | .95 | .95 | | notebook 06, 59 queries | TF-IDF | .51 | .51 | .56 | **.64** | .83 | .92 | | support benchmark, 15 queries | BM25 | .93 | 1.0 | 1.0 | **1.0** | 1.0 | 1.0 | | support benchmark, 15 queries | TF-IDF | .87 | .80 | .80 | **.87** | .93 | .93 | The dense encoder alone scores .95 and 1.0 on these sets, which have no keyword-heavy routes. Sparse earns its place when queries hinge on exact terms like product codes and names. Measure on your own queries with [`evaluate()`](../features/calibration#measure-it) before you lower `alpha`. A *fitted* sparse encoder such as `BM25Encoder` learns its vocabulary from your utterances, so `add()` refits it and rebuilds the index. ## DecisionRouter [#decisionrouter] The `DecisionRouter` asks a decision model which route a query belongs to. You pass it the model, as you pass an encoder to an `IndexedRouter`. It needs no encoder and no index: the model reads each route's `description` and returns a probability for every route, so its confidences are calibrated from the start. ```python from semantic_router import DecisionRouter, Route from semantic_router.decision_models import TypeSafeDecisionModel routes = [ Route(name="billing", description="Money already paid or owed: refunds, charges, invoices."), Route(name="technical", description="Something in the product is broken or not working."), ] router = DecisionRouter(model=TypeSafeDecisionModel(), routes=routes) # reads JEV_API_KEY router("why was I charged twice this month?") ``` ``` [Out]: RouteChoice(name='billing', confidence=1.0, calibrated=True) ``` It's slower than an `IndexedRouter` (a network call of a few hundred milliseconds) but it understands instructions and edge cases that example utterances can't capture. It can also answer several questions about one message in a single call. See [decision models](../features/decision-models), and for background on the models themselves, [Understanding Jev](https://jamesbriggs.io/understanding-jev) and [the video](https://youtu.be/P-t4F_UlxkI). ## Chain and Merge [#chain-and-merge] `Chain` and `Merge` are routers made of routers. * **`Chain(routers=[fast, smart])`** tries `fast` first. If its best route clears its bar, that's the answer and `smart` never runs. Otherwise it moves on to `smart`. Easy queries cost only the fast router. * **`Merge(routers=[a, b], weights=[1, 2])`** asks every router at once and averages their confidences per route. Every query gets a second opinion. Both are routers themselves, so they nest, and you can `fit()` them. See [Chain and Merge](../features/composition). ## Calling a router [#calling-a-router] ```python router("what's the weather like today?") # the best route, as a RouteChoice router("what's the weather like today?", limit=2) # up to 2 routes, best first router("what's the weather like today?", limit=None) # every route that clears its bar router("what's the weather like today?", threshold=0.8) # a bar for this call only ``` With `limit=1` (the default) you get one `RouteChoice`, with `name=None` when nothing clears the bar. With any other `limit` you get a list, which is empty when nothing clears it. Every method has an async twin: ```python choice = await router.acall("what's the weather like today?") ``` The sync methods run their async twin on one shared background event loop. That keeps HTTP connections pooled between calls, and it works inside notebooks. Inside your own async code, use the `a`-methods with `await`: a sync call from code running on that shared loop raises an error instead of deadlocking. ## Thresholds [#thresholds] A route is returned only when its confidence clears its bar. The bar is, in order: 1. the `threshold=` you pass to the call, if any 2. the route's own `confidence_threshold`, if set 3. the router's `confidence_threshold`, if set 4. otherwise no bar: the best route always wins Until you calibrate, a router's confidence is its raw score, so a bar is a raw similarity. After `fit()` it's a probability. The [calibration guide](../features/calibration) shows how. ## Managing routes [#managing-routes] ```python router.add(routes=Route(name="greetings", utterances=["hello there", "hi, how are you?"])) router.remove(name="greetings") [r.name for r in router.routes] ``` `add()` takes one route or a list. On an `IndexedRouter`, `add()` embeds and writes the new utterances, and `remove()` deletes the route's records from the index. To change a route, remove it and add the new version. If you've calibrated the router, `add()` and `remove()` refit it on the labelled queries you last gave `fit()`. A new route with no labelled queries gets a warning: call `fit()` again with some. ## Build your own router [#build-your-own-router] A router is anything that scores every route. Subclass `BaseRouter` and implement one async method, `_scores`, which returns a raw score per route (higher means more likely). You get calling, `limit`, thresholds, calibration, `evaluate()`, `add()`/`remove()` and composition for free. ```python from semantic_router import Route from semantic_router.routers import BaseRouter class KeywordRouter(BaseRouter): async def _scores(self, query: str) -> dict[str, float]: q = query.lower() return { r.name: float(any(str(u) in q for u in r.utterances)) for r in self.routes } keyword_router = KeywordRouter( routes=[ Route(name="refund", utterances=["refund", "money back"]), Route(name="cancel", utterances=["cancel", "unsubscribe"]), ], confidence_threshold=0.5, ) keyword_router("can I get my money back?") ``` ``` [Out]: RouteChoice(name='refund', confidence=1.0, calibrated=False) ``` | Hook | Override when | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `_scores(query)` | Always: the raw score for every route. | | `_scores_many(queries)` | You can score a batch more cheaply than one at a time (`IndexedRouter` embeds a whole batch in one call). The default runs `_scores` concurrently, eight at a time. | | `_on_add(routes)` / `_on_remove(name)` | You keep per-route state, such as an index. | | `probabilistic = True` | Your raw scores are already probabilities, so results report `calibrated=True` without a fit. | # Encoders (/docs/semantic-router/v1/user-guide/components/encoders) An encoder turns text (or images, or other data) into a vector — a list of numbers that captures meaning. Those vectors are what let Semantic Router measure how similar two inputs are. An `IndexedRouter` needs one; a `DecisionRouter` doesn't use them at all. ## What an encoder does [#what-an-encoder-does] An encoder does two jobs: 1. **At setup**, it embeds the example utterances in your routes. 2. **At runtime**, it embeds each incoming query. The router compares the two and picks the closest route — even when the wording is completely different. ## Dense vs. sparse [#dense-vs-sparse] Semantic Router supports two kinds of encoder. They see text very differently, and each has its strengths. ### Dense encoders [#dense-encoders] Dense encoders fill every dimension of the vector. They: * Produce fixed-size vectors (1536 dimensions for OpenAI's `text-embedding-3-small`, for example). * Capture rich semantic relationships. * Do well when context and meaning matter more than exact words. ```python import os from semantic_router.encoders import OpenAIEncoder os.environ["OPENAI_API_KEY"] = "your-api-key" encoder = OpenAIEncoder() embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ### Sparse encoders [#sparse-encoders] Sparse encoders leave most dimensions at zero, with only a few non-zero values. They: * Key off specific words and tokens. * Excel at exact keyword matching and term frequency. * Are more interpretable — a non-zero dimension usually maps to a specific word. ```python import os from semantic_router.encoders import AurelioSparseEncoder os.environ["AURELIO_API_KEY"] = "your-api-key" encoder = AurelioSparseEncoder() embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ## Using both: hybrid routing [#using-both-hybrid-routing] You don't have to choose. Give an `IndexedRouter` a sparse encoder as well as a dense one, and you get semantic understanding *and* keyword precision. The `alpha` parameter sets the balance: it's the weight on the dense score, and the sparse score gets the rest. ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import BM25Encoder, FastEmbedEncoder routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), sparse_encoder=BM25Encoder(), routes=routes, alpha=0.7, # 1.0 = dense only, 0.0 = sparse only ) ``` ## Supported encoders [#supported-encoders] Most encoders ship with the base install. The ones that run models locally need an extra: `[fastembed]` for FastEmbed, and `[local]` for Hugging Face and sentence-transformers models. ```bash pip install -qU "semantic-router[fastembed]" pip install -qU "semantic-router[local]" ``` ### Dense encoders [#dense-encoders-1] | Encoder | What it uses | Install | | ------------------------------------------------------------------ | -------------------------------------------------- | ----------- | | [OpenAIEncoder](../../client-reference/encoders/openai) | OpenAI embedding models | base | | [AzureOpenAIEncoder](../../client-reference/encoders/azure_openai) | Azure OpenAI embedding models | base | | [CohereEncoder](../../client-reference/encoders/cohere) | Cohere embedding models | base | | [MistralEncoder](../../client-reference/encoders/mistral) | Mistral embedding models | base | | [GoogleEncoder](../../client-reference/encoders/google) | Google embedding models | base | | [BedrockEncoder](../../client-reference/encoders/bedrock) | AWS Bedrock embedding models | base | | [JinaEncoder](../../client-reference/encoders/jina) | Jina embedding models | base | | [VoyageEncoder](../../client-reference/encoders/voyage) | Voyage embedding models | base | | [NimEncoder](../../client-reference/encoders/nvidia_nim) | NVIDIA NIM embedding models | base | | [LiteLLMEncoder](../../client-reference/encoders/litellm) | Any provider supported by LiteLLM | base | | [OllamaEncoder](../../client-reference/encoders/ollama) | Embedding models served by a local Ollama instance | base | | [HFEndpointEncoder](../../client-reference/encoders/huggingface) | Hugging Face Inference API | base | | [HuggingFaceEncoder](../../client-reference/encoders/huggingface) | Hugging Face models, run locally | `local` | | [LocalEncoder](../../client-reference/encoders/local) | Any sentence-transformers model, run locally | `local` | | [FastEmbedEncoder](../../client-reference/encoders/fastembed) | FastEmbed models, run locally on CPU | `fastembed` | | [VitEncoder](../../client-reference/encoders/vit) | Vision Transformer, for image embeddings | `vision` | | [CLIPEncoder](../../client-reference/encoders/clip) | CLIP, for image and text embeddings | `vision` | ### Sparse encoders [#sparse-encoders-1] | Encoder | What it uses | Install | | --------------------------------------------------------------- | ------------------------------------------------------------------------- | ------- | | [BM25Encoder](../../client-reference/encoders/bm25) | BM25 | base | | [TfidfEncoder](../../client-reference/encoders/tfidf) | TF-IDF | base | | [AurelioSparseEncoder](../../client-reference/encoders/aurelio) | Aurelio's API for BM25 sparse embeddings | base | | [LocalSparseEncoder](../../client-reference/encoders/local) | Neural sparse models (SPLADE, CSR) via sentence-transformers, run locally | `local` | `LocalSparseEncoder` is worth a closer look if you want sparse vectors without an API. It uses the sentence-transformers `SparseEncoder` API (v5+), runs on CPU, CUDA, or MPS, and works with any compatible model from the Hugging Face Hub: ```python from semantic_router.encoders import LocalSparseEncoder encoder = LocalSparseEncoder(name="naver/splade-v3") embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ## AutoEncoder [#autoencoder] If you'd rather pick an encoder by name at runtime, `AutoEncoder` resolves the right class for you: ```python from semantic_router.encoders import AutoEncoder from semantic_router.schema import EncoderType encoder = AutoEncoder(type=EncoderType.OPENAI.value, name="text-embedding-3-small").model embeddings = encoder(["How can I help you today?"]) ``` ## Choosing an encoder [#choosing-an-encoder] A few questions to ask: 1. **Accuracy.** Dense encoders understand meaning better but can miss exact keywords. Sparse encoders are the reverse. 2. **Speed.** Local encoders avoid network round-trips, though cloud models are often more accurate. 3. **Cost.** Cloud encoders (OpenAI, Cohere, Aurelio) bill per call. Local ones don't. 4. **Privacy.** Local encoders keep your data on your machine. `FastEmbedEncoder` is the lightest way to start: a small model that runs on CPU, with no API key. 5. **Both?** When you're unsure, a hybrid setup often gives the best balance. Each encoder's reference page covers its specific options. # Indexes (/docs/semantic-router/v1/user-guide/components/indexes) An index is where an `IndexedRouter` stores the vectors of your route utterances and searches them. It's the search backend behind every decision the router makes. (A `DecisionRouter` doesn't use one.) ## What an index does [#what-an-index-does] 1. **Stores** the embedding of every utterance, with its route. 2. **Searches** for the stored vectors closest to each query. 3. **Persists** your routes across restarts, if it's a remote index. 4. **Scales** to large numbers of routes and utterances. ## The index is the source of truth [#the-index-is-the-source-of-truth] In version 1 the index holds your routes, and the router is a client of it: * **Building a router writes its routes to the index.** Each record's id comes from its route and utterance, so writing the same routes again changes nothing. Two processes can start up with the same routes and the index ends up the same. * **Passing `routes=` adds or updates, and never deletes.** Routes already in the index that aren't in your list stay there. Remove one with `router.remove(name=...)`. * **`router.routes` is a view of the index.** The router fills it from the index when it's built, after its own `add()` and `remove()`, and whenever you refresh it. It never writes routes anywhere else. See [sharing an index](#sharing-an-index). There is no sync step, and no `auto_sync`: there's only one copy of your routes to keep right. (0.x kept a second copy in the router and reconciled the two. The [migration guide](../guides/migration-to-v1#sync-is-gone) covers moving off it.) ## Local indexes [#local-indexes] A local index keeps the vectors in memory. It's fast and needs no setup, but it's gone when your process exits. It's the default when you don't pass an index, and ideal for development, tests and small route sets. ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import FastEmbedEncoder from semantic_router.index import LocalIndex routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes, index=LocalIndex(), ) router("What's the weather like today?").name ``` ``` [Out]: 'weather' ``` ## Remote indexes [#remote-indexes] A remote index stores the vectors in a vector database. Your routes persist, many processes can share them, and you can scale to millions of vectors. This is what you want in production. Here's Pinecone: ```python import os from semantic_router import IndexedRouter from semantic_router.encoders import OpenAIEncoder from semantic_router.index import PineconeIndex os.environ["OPENAI_API_KEY"] = "" os.environ["PINECONE_API_KEY"] = "" index = PineconeIndex( index_name="semantic-router", dimensions=1536, # must match your encoder ) router = IndexedRouter( encoder=OpenAIEncoder(), routes=routes, index=index, ) ``` Qdrant can run in memory, which is handy for trying a remote-style index without a server: ```python from semantic_router.index import QdrantIndex router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes, index=QdrantIndex(index_name="routes", location=":memory:"), ) ``` Postgres works through pgvector: ```python from semantic_router.index import PostgresIndex index = PostgresIndex( connection_string="postgresql://user:password@localhost:5432/routes", index_name="routes", dimensions=384, # must match your encoder ) ``` MongoDB Atlas works through Atlas Vector Search. The index creates its collection and vector search index on the first `add`, so there's nothing to set up in Atlas first: ```python from semantic_router.index import MongoDbIndex index = MongoDbIndex( connection_uri="mongodb+srv://user:password@cluster.mongodb.net/", # or set MONGO_CONNECTION_URI database_name="semantic_router", index_name="routes", ) ``` Atlas makes new records searchable a moment after they're written, so `add` waits until they are (up to `sync_timeout`, 30 seconds by default). For local development, the `mongodb/mongodb-atlas-local` Docker image supports the same vector search. ## Sharing an index [#sharing-an-index] Because the index holds the routes, several routers can share one. To connect to an index that's already filled, pass it without `routes`: the router reads them from the index. ```python shared = QdrantIndex(index_name="support", location=":memory:") encoder = FastEmbedEncoder(name="BAAI/bge-small-en-v1.5") writer = IndexedRouter(encoder=encoder, routes=routes, index=shared) reader = IndexedRouter(encoder=encoder, index=shared) sorted(r.name for r in reader.routes) ``` ``` [Out]: ['politics', 'weather'] ``` Each router keeps its own cached copy of the route list, so routing a query never re-reads every route from the index. That read grows with the number of utterances, and on Pinecone it can take seconds. The cache fills when the router is built and after its own `add()` and `remove()`. Changes another router writes show up when you refresh: ```python writer.add(routes=Route(name="greetings", utterances=["hello there", "hi, how are you?"])) reader.refresh() sorted(r.name for r in reader.routes) ``` ``` [Out]: ['greetings', 'politics', 'weather'] ``` Use `await router.arefresh()` in async code. To pick up other writers' changes without calling it yourself, set `refresh_interval`, in seconds. When the cache is older than that, the next call re-reads the routes while it embeds the query: ```python reader = IndexedRouter(encoder=encoder, index=shared, refresh_interval=60) ``` With the default, `refresh_interval=None`, a call never reads routes from the index. The search itself always runs against the index, so a stale cache never hides a route: if another writer adds a route, the reader returns it for a matching query even before it refreshes. What the cache holds is the route list (`router.routes`) and each route's settings. Until a refresh, a route the reader hasn't cached is held to the router's `confidence_threshold`, because its own isn't known yet. So refresh after another writer changes routes' settings, such as a route's threshold. Every router on a shared index must use the same encoder: the stored vectors only mean something to the model that made them. ## Hybrid indexes [#hybrid-indexes] For [hybrid search](routers#hybrid-search), the index has to store sparse vectors as well as dense ones. Two do: * `HybridLocalIndex`, in memory. A hybrid `IndexedRouter` uses it when you don't pass an index. * `PineconeIndex`, remote. `LocalIndex`, `QdrantIndex`, `PostgresIndex` and `MongoDbIndex` are dense only: give a router one of them along with a `sparse_encoder` and it raises an error. ## Supported indexes [#supported-indexes] | Index | What it is | Hybrid | Install | | ------------------------------------------------------------- | -------------------------------------- | ------ | --------------------------------------------- | | [LocalIndex](../../client-reference/index/local) | In memory, for development and testing | no | base | | [HybridLocalIndex](../../client-reference/index/hybrid_local) | In memory, dense and sparse | yes | base | | [PineconeIndex](../../client-reference/index/pinecone) | Pinecone vector database | yes | `pip install -qU "semantic-router[pinecone]"` | | [QdrantIndex](../../client-reference/index/qdrant) | Qdrant vector database | no | `pip install -qU "semantic-router[qdrant]"` | | [PostgresIndex](../../client-reference/index/postgres) | PostgreSQL with pgvector | no | `pip install -qU "semantic-router[postgres]"` | | [MongoDbIndex](../../client-reference/index/mongodb) | MongoDB Atlas Vector Search | no | `pip install -qU "semantic-router[mongodb]"` | ## Choosing an index [#choosing-an-index] 1. **Persistence.** Local indexes vanish on restart. Remote ones don't. 2. **Sharing.** Only a remote index can be shared between processes. 3. **Scale.** Local is bounded by memory. Remote handles millions of vectors. 4. **Latency.** Local is fastest. Remote adds a network hop to every query. 5. **Setup and cost.** Local needs nothing and costs nothing. Remote needs a service. 6. **Hybrid search.** Only `HybridLocalIndex` and `PineconeIndex` store sparse vectors. ## Index methods [#index-methods] You rarely call an index directly; the router does it for you. Every index implements: * `add()` and `aadd()`: write records. * `query()` and `aquery()`: find the stored vectors closest to a query. * `delete()` and `adelete()`: remove a route's records. * `get_routes()` and `aget_routes()`: rebuild the routes from the stored records. * `delete_index()`: drop everything. Each index's reference page covers its own options. # Calibration and thresholds (/docs/semantic-router/v1/user-guide/features/calibration) A raw similarity of 0.8 means something different for every encoder, every set of routes and every kind of query. So a threshold set on raw scores is a guess, and it breaks when you change the encoder. Calibration fixes that. `fit()` takes labelled example queries and learns a curve from a router's raw score to the probability that its top route is right. After that, a confidence of 0.85 means the route is right about 85% of the time, and a threshold is a policy you can reason about: "act when you're 90% sure, otherwise ask a human". ## Fit a router [#fit-a-router] You need some labelled queries the router hasn't seen. Label the ones that shouldn't match any route with `None`. ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import FastEmbedEncoder routes = [ Route(name="billing", utterances=["i want a refund", "why was i charged twice?", "where can I find my invoice?", "cancel my subscription and refund me", "you overcharged me"]), Route(name="technical", utterances=["the app keeps crashing", "I can't log in", "the page won't load", "I get an error when I upload a file", "sync isn't working"]), Route(name="chitchat", utterances=["how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy"]), ] router = IndexedRouter(encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes) X_train = [ "can I get my money back?", "there's a double charge on my card", "send me last month's receipt", "I was billed the wrong amount", "the screen goes blank when I open settings", "password reset email never arrives", "the export button does nothing", "it says error 500", "nice day out, isn't it?", "how was your weekend?", "it's freezing outside", "how have you been?", "what's the capital of australia?", "write me a poem about cats", "recommend a good sci-fi book", "how many legs does a spider have?", ] y_train = ["billing"] * 4 + ["technical"] * 4 + ["chitchat"] * 4 + [None] * 4 router.fit(X=X_train, y=y_train) ``` ``` [Out]: FitReport(method='platt', n=16, accuracy=1.0, ece=0.13265465825903883) ``` `fit()` returns a `FitReport`: | Field | Meaning | | ---------- | ------------------------------------------------------------------------------------------------------------------------- | | `method` | `"platt"` or `"isotonic"` | | `n` | how many labelled queries it fitted on | | `accuracy` | how often the top route was right, over the queries that have a route (before any threshold) | | `ece` | expected calibration error: the average gap between stated confidence and actual accuracy. Lower is better; 0 is perfect. | From now on, every result has `calibrated=True` and its `confidence` is a probability. ## Never fit on the stored utterances [#never-fit-on-the-stored-utterances] Use queries the router has never seen: paraphrases, real traffic, anything that isn't in the routes' `utterances`. A stored utterance always finds itself in the index, at a similarity near 1.0, which real queries never reach. Fit on those, and the calibrator learns that only near-perfect scores are trustworthy, so real queries come out unsure. If you chain routers, too many of them then fall through to the slow one. `IndexedRouter.fit()` warns when it sees stored utterances among your queries: ``` WARNING semantic_router 15/19 training queries are stored utterances; they match themselves at ~1.0, so the calibrator will under-rate real queries, which score lower. fit on held-out queries. ``` ## Set thresholds [#set-thresholds] A threshold is the confidence a route must reach before the router returns it. With none set, the best route always wins, however weak, so set one before you rely on `name=None` as a fallback. ```python router.confidence_threshold = 0.5 router("who won the football?") ``` ``` [Out]: RouteChoice(name=None, confidence=None, calibrated=True) ``` Thresholds live in up to three places. The first one that's set wins: 1. **The call:** `router(query, threshold=0.8)` for a one-off bar. 2. **The route:** `Route(confidence_threshold=0.95)` for a decision that's costlier to get wrong. 3. **The router:** `IndexedRouter(confidence_threshold=0.5)`, or `router.confidence_threshold = 0.5`, as the default. ```python review_routes = [ # cheap to be wrong Route(name="flag_possible_bug", utterances=["this looks like a bug", "is this an off-by-one?"], confidence_threshold=0.6), # costly to be wrong Route(name="refund_customer", utterances=["refund this customer", "give them their money back"], confidence_threshold=0.95), ] review_router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=review_routes, confidence_threshold=0.8, # for routes without their own bar ) ``` A router has one calibrator, fitted across all its routes, so a 0.95 bar on one route is only as honest as the calibration is on that route. Give every route some labelled queries. ## Measure it [#measure-it] `evaluate()` runs labelled queries through the router, thresholds and all, and returns the accuracy. A `None` label counts as right when no route clears its bar. Use a test set you didn't fit on. ```python X_test = ["refund my order please", "why is my bill so high?", "the app froze again", "I can't upload my photo", "lovely sunny afternoon", "fancy a chat?", "who won the football?", "translate hello into french"] y_test = ["billing", "billing", "technical", "technical", "chitchat", "chitchat", None, None] router.confidence_threshold = None router.evaluate(X=X_test, y=y_test) ``` ``` [Out]: 0.75 ``` With no threshold, the two off-topic queries still get a route, so they count as wrong. With a bar: ```python router.confidence_threshold = 0.5 router.evaluate(X=X_test, y=y_test) ``` ``` [Out]: 0.875 ``` Raising the threshold trades coverage for precision: more queries fall back to "no route", and the ones that do route are more often right. Try a few values against your test set, and pick the one whose mistakes you can live with. ## Platt or isotonic [#platt-or-isotonic] `fit()` takes `method="platt"` (the default) or `method="isotonic"`. ```python router.fit(X=X_train, y=y_train, method="isotonic") ``` ``` [Out]: FitReport(method='isotonic', n=16, accuracy=1.0, ece=0.05555555555555549) ``` **Platt scaling** fits an S-curve with two numbers, *a* and *b*: P(right | s) = 1 / (1 + e^-(a·s + b)) *a* sets how steep the curve is and *b* where it crosses 50%. They're chosen to minimise log-loss on your (score, right?) pairs, with the targets softened slightly so a small class can't pin the curve at exactly 0 or 1. **Isotonic regression** assumes only that a higher score is never worse. It sorts the scores and merges neighbouring blocks wherever accuracy drops (pool adjacent violators), so the curve is a staircase of observed accuracies. | | Platt | Isotonic | | -------- | ------------------------ | -------------------------------------------------- | | Assumes | an S-shape | only "a higher score is never worse" | | Learns | 2 numbers | one step per block, up to one per example | | Needs | tens of labelled queries | hundreds, or it overfits into flat steps | | Use when | by default | you have lots of data and the curve isn't S-shaped | Don't read too much into a low `ece` on the data you fitted on: isotonic can follow small samples almost exactly. Check it with `evaluate()` on a held-out set. Both methods are monotone, so calibration never changes which route ranks first. It only changes the number attached to it. ## When routes change [#when-routes-change] `add()` and `remove()` refit the calibrator on the labelled queries you last passed to `fit()`. Labels for a removed route become `None`. A new route has no labelled queries yet, so the router warns you to call `fit()` again with some. A calibrator you passed in yourself, or loaded from a file, has no labelled queries to refit on. When the routes change, it's dropped with a warning, and confidences are raw again until you call `fit()`. ## Routers that are already calibrated [#routers-that-are-already-calibrated] A `DecisionRouter` returns probabilities straight from its model, so its results say `calibrated=True` without a fit. You can still `fit()` one to correct a model that's systematically over- or under-confident on your traffic. The [calibrated probability](https://youtu.be/P-t4F_UlxkI?t=395) chapter of the Jev video shows what that means in practice, and [Understanding Jev](https://jamesbriggs.io/understanding-jev) measures the calibration error of Jev and the open models it compares. A `Chain` or `Merge` is calibrated only when every router in it is. Calibrate the parts first, so their confidences are on the same scale; otherwise a threshold or an average mixes raw similarities with probabilities. # Decision models (/docs/semantic-router/v1/user-guide/features/decision-models) Some routing decisions depend on instructions rather than resemblance: "refunds and charges, but not pricing questions before a purchase". Example utterances struggle to draw lines like that. A decision model can: it's a small, fast model trained to answer typed questions about a piece of text, with a probability for every answer. `DecisionRouter` routes with one. The model is a component you pass in, the way you pass an encoder to an `IndexedRouter`. The models that ship speak the `/v1/systemone` API that TypeSafe's **Jev** introduced, which **Laya** and **Von** also implement. ## Learn about decision models [#learn-about-decision-models] New to decision models? Two walkthroughs by James Briggs explain what they are and where they fit: * **Article:** [Understanding Jev and Where It Fits in the AI Stack](https://jamesbriggs.io/understanding-jev) covers what a decision model is and how it differs from an LLM, what a calibrated probability gives you, where to use one and where not to, and how open models such as GLiNER2.5 compare, with benchmarks. * **Video:** [I Tested Jev AI Against LLMs and Open Source](https://youtu.be/P-t4F_UlxkI) (34 min) covers the same ground with live tests. Jump to [the three types of decision](https://youtu.be/P-t4F_UlxkI?t=266), [calibrated probability](https://youtu.be/P-t4F_UlxkI?t=395), [open-source alternatives](https://youtu.be/P-t4F_UlxkI?t=999) or [GLiNER](https://youtu.be/P-t4F_UlxkI?t=1228). ## Route with a decision model [#route-with-a-decision-model] ```python from semantic_router import DecisionRouter, Route from semantic_router.decision_models import TypeSafeDecisionModel routes = [ Route(name="billing", description="Money already paid or owed: refunds, charges, invoices."), Route(name="technical", description="Something in the product is broken or not working."), ] router = DecisionRouter(model=TypeSafeDecisionModel(), routes=routes) # reads JEV_API_KEY router("why was I charged twice this month?") ``` ``` [Out]: RouteChoice(name='billing', confidence=1.0, calibrated=True) ``` There's no encoder and no index. The router turns your routes into one multiple-choice question, sends it with the query, and gets back a probability for every route. Those are already probabilities, so results say `calibrated=True` without a `fit()`. The router takes: | Argument | Default | What it does | | ---------------------- | -------------------------------------------------- | --------------------------------------------- | | `model` | required | The decision model that answers. | | `routes` | `()` | The routes to choose between. | | `instructions` | `"Which route does the user's message belong to?"` | The question asked about each query. | | `confidence_threshold` | `None` | The router's default bar, as on every router. | The model holds the connection settings: | Argument | Default | What it does | | ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `"jev-latest"` | The model to ask. | | `api_key` | `JEV_API_KEY` | Your API key. | | `base_url` | `"https://api.typesafe.ai"` | The server; requests go to `{base_url}/v1/systemone`. | | `timeout` | `10.0` | Seconds per request. | | `retries` | `3` | Retries on rate limits (429, 529), server errors and timeouts, with exponential backoff and jitter. | | `concurrency` | `8` | Requests in flight when scoring a batch (`fit`, `evaluate`, `Chain`, `Merge`). Each query is one request, so this caps a batch's throughput: raise it as far as your rate limit allows. | ## Use another server [#use-another-server] `TypeSafeDecisionModel` is TypeSafe's Jev with its defaults filled in. For a Laya or Von deployment, or a server of your own that speaks `/v1/systemone`, use `SystemOneDecisionModel` and say where it is: ```python from semantic_router.decision_models import SystemOneDecisionModel model = SystemOneDecisionModel(name="my-model", base_url="http://localhost:8080") router = DecisionRouter(model=model, routes=routes) ``` It sends a key only if you pass `api_key`, so a local server needs none. To plug in a different kind of model, subclass `DecisionModel` and implement `aask(state, questions)`, which returns an answer for each question. ## Run a decision model locally [#run-a-decision-model-locally] `GLiNER2DecisionModel` runs [GLiNER2.5-Decide](https://huggingface.co/fastino/GLiNER2.5-Decide), Fastino's open decision model, in your own process. Your queries never leave your infrastructure, and there's no API key. ```bash pip install "semantic-router[local]" # Python 3.10 to 3.12 ``` ```python from semantic_router import DecisionRouter from semantic_router.decision_models import GLiNER2DecisionModel router = DecisionRouter(model=GLiNER2DecisionModel(), routes=routes) router.fit(X=held_out_queries, y=held_out_labels) router("why was I charged twice this month?") ``` The first time it loads, it downloads the weights from Hugging Face (about 1.8 GB). It answers the same `choice`, `noul` and `score` questions as Jev, so `aask()` works the same way. | Argument | Default | What it does | | ------------ | ---------------------------- | ------------------------------------------------------------------------------------ | | `name` | `"fastino/GLiNER2.5-Decide"` | The model on the Hugging Face Hub, or a local directory. | | `device` | the first available | `"cuda"`, `"mps"` or `"cpu"`. | | `batch_size` | `8` | Queries per forward pass when scoring a batch (`fit`, `evaluate`, `Chain`, `Merge`). | | `classifier` | `None` | A `gliner2` classifier you loaded yourself, such as one with a fine-tuned adapter. | On the [benchmark](../concepts/benchmarks) (CLINC150, 15 routes), it comes close to Jev: | | Jev | GLiNER2.5-Decide | | ----------------------------------------- | ------------- | ---------------- | | Top-1 accuracy | 99.3% | 97.6% | | End-to-end, at a 0.5 bar | 97.8% | 93.8% | | Out-of-scope queries turned away | 95.3% | 97.3% | | Calibration error, before / after `fit()` | 0.150 / 0.017 | 0.221 / 0.029 | Three things to know: * **Fit it before you set a threshold.** Its raw scores rank the routes well, but they aren't calibrated: a 0.8 isn't right 80% of the time. [`fit()`](calibration) on held-out queries fixes that. * **Its speed depends on your routes.** Every route's name and description go through the model in one pass with the query, so more routes and longer descriptions take longer. On an Apple M4 Max (MPS), a query takes about 50 ms with two short routes and about 210 ms with the benchmark's 15 described routes; on CPU, about 330 ms. Keep descriptions short, or put an `IndexedRouter` in front of it with a [Chain](composition). * **It needs Python 3.12 or earlier**, like the other models in the `local` extra. The [GLiNER chapter](https://youtu.be/P-t4F_UlxkI?t=1228) of the Jev video covers how it works and how it compares. ## Write literal descriptions [#write-literal-descriptions] The model reads each route's `description`, and it takes you at your word. Say what belongs in the route and, where it helps, what doesn't: ```python Route( name="billing", description="Money already paid or owed: refunds, charges, invoices. Not pricing questions before a purchase.", ) ``` A route with no description falls back to its first five utterances, joined together. That works, but a written description is usually better. ## Ask several questions in one call [#ask-several-questions-in-one-call] A decision model can answer several questions about the same message in one pass, for about the cost of one. `aask()` sends the message (the `state`) once, with a dict of named questions, and returns an answer for each. ```python from semantic_router.decision_models import choice, noul, score answers = await router.aask( state="my card was charged twice and I need it fixed today or I'm cancelling", questions={ "route": router.route_question(), "urgent": noul(instructions="Is this time-sensitive?", yes="needs action now", no="can wait"), "mood": score(instructions="How upset is the user?", levels=["calm", "annoyed", "angry"]), }, ) answers["route"]["choice"], answers["urgent"]["noul"], answers["mood"]["score"] ``` There are three kinds of question: | Helper | Asks | Answer | | --------------------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `choice(instructions=, options=)` | which one of several options applies. `options` maps each option's name to a description. | `choice`, `confidence`, and `probabilities` per option | | `noul(instructions=, yes=, no=)` | a yes/no question. `yes` and `no` describe what each answer means. | `noul`: the probability of yes | | `score(instructions=, levels=)` | where the message sits on an ordered scale, lowest first. | `score` (the expected level, 0-based), `confidence`, `probabilities` per level, and a `legend` | `router.route_question()` is the `choice` question the router asks for routing, built from your routes. The answers above look like this: ```json { "route": {"type": "choice", "choice": "billing", "confidence": 1.0, "probabilities": {"billing": 1.0, "technical": 0.0}}, "urgent": {"type": "noul", "noul": 0.96}, "mood": {"type": "score", "score": 1.92, "confidence": 0.88, "legend": {"0": "calm", "1": "annoyed", "2": "angry"}, "probabilities": {"0": 0.0, "1": 0.08, "2": 0.92}} } ``` *Noul* is TypeSafe's name for a yes/no question, short for *Bernoulli*: one trial, two outcomes. The answer is the probability of yes, so you choose the cut-off. So one call can route a message, check it against a guardrail and score its urgency, where 0.x needed a separate router for each. `aask()` is async only. In a notebook you can `await` it directly; in a script, run it with `asyncio.run()`. ## Latency [#latency] A decision model is a network call. Measured against Jev (p50, after warm-up): | Call | p50 | | --------------------------------------- | -------- | | one question | 351 ms | | three questions in one `aask()` | 327 ms | | three separate calls, one after another | 1,012 ms | * **Batch questions** into one `aask()` rather than fanning out calls. * **Warm up at startup.** The first call to a model can take many seconds; later ones take a few hundred milliseconds. Make one call when your app starts, never on a user's first request. * **Put a fast router in front.** A [Chain](composition) answers confident queries from an `IndexedRouter` in milliseconds and only sends the ambiguous ones to the decision model. ## Close the session [#close-the-session] A `DecisionRouter`'s model keeps a pooled HTTP session, so repeated calls reuse the connection. Close it when you're done. After async calls (`acall`, `aask`), prefer: ```python await router.aclose() ``` From sync code, `router.close()` does the same. A sync `close()` from inside a running event loop raises an error that tells you to `await router.aclose()` instead. # Chain and Merge (/docs/semantic-router/v1/user-guide/features/composition) `Chain` and `Merge` are routers made of other routers. They take the same routes, return the same `RouteChoice`, and can be fitted, evaluated and nested like any other router. * **`Chain`** is sequential. It asks each router in turn and stops at the first one that's confident. Use it to answer easy queries cheaply and spend more only on hard ones. * **`Merge`** is parallel. It asks every router at once and averages their confidences. Use it to get a second opinion on every query. ## Chain: fast first, smart when unsure [#chain-fast-first-smart-when-unsure] The classic pairing is an `IndexedRouter`, which answers in milliseconds, in front of a `DecisionRouter`, which is slower but follows instructions: ```python from semantic_router import Chain, DecisionRouter, IndexedRouter, Route from semantic_router.decision_models import TypeSafeDecisionModel from semantic_router.encoders import FastEmbedEncoder routes = [ Route( name="billing", utterances=["i want a refund", "why was i charged twice?", "where can I find my invoice?"], description="Money already paid or owed: refunds, charges, invoices.", ), Route( name="technical", utterances=["the app keeps crashing", "I can't log in", "the page won't load"], description="Something in the product is broken or not working.", ), ] fast = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes, confidence_threshold=0.85, ) fast.fit(X=held_out_queries, y=held_out_labels) # so 0.85 means 85% smart = DecisionRouter(model=TypeSafeDecisionModel(), routes=routes) router = Chain(routers=[fast, smart]) router("I was billed for a plan I cancelled") ``` For each query, the Chain: 1. Asks `fast` to score the routes. 2. Takes `fast`'s top route and compares its confidence to that route's bar: the route's `confidence_threshold`, else `fast`'s, else the Chain's own. 3. If it clears the bar, answers from `fast`. `smart` never runs. 4. Otherwise moves on to `smart`. The last router always answers. Measured with an OpenAI encoder and Jev, a confident query that stopped at the index took 265 ms at p50; an ambiguous one that fell through to Jev took 610 ms. Only the traffic that needs the decision model pays for it. The same fast-then-slow split, with a decision model making the quick calls and an LLM setting the strategy, is the [thinking fast and slow](https://youtu.be/P-t4F_UlxkI?t=1542) chapter of the Jev video. Two things to get right: * **Give the first router a bar.** A router with no threshold (and no threshold on the Chain) always answers, so the routers after it never run. * **Calibrate the first router.** Its bar is only meaningful if its confidence is a probability. If you fit it on its own stored utterances, real queries look unsure and nearly everything falls through. See [calibration](calibration#never-fit-on-the-stored-utterances). ## Merge: a second opinion on every query [#merge-a-second-opinion-on-every-query] ```python from semantic_router import Merge router = Merge(routers=[fast, smart], weights=[1, 2]) router("I was billed for a plan I cancelled") ``` Merge runs every router at the same time and returns, for each route, the weighted mean of their confidences: `(1 × fast + 2 × smart) / 3` here. Without `weights`, every router counts equally. A call always takes as long as the slowest router. Average only like with like. A raw cosine similarity and a probability are different units, so calibrate every router before you merge them. ## Chain or Merge? [#chain-or-merge] | | Chain | Merge | | --------- | ------------------------------------------------------------------- | -------------------------------------- | | Runs | one router after another, stopping early | every router, at once | | Costs | the fast router for confident queries; all of them only when unsure | the slowest router, every time | | Answer | one router's answer | a blend of all of them | | Use it to | save time and money on easy queries | improve accuracy with a second opinion | A Chain can't do what a Merge does: it never combines answers. And a Merge never saves you a call. ## Thresholds, calibration and nesting [#thresholds-calibration-and-nesting] `Chain` and `Merge` take a `confidence_threshold` like any router. It applies to the final answer, and in a Chain it's also the fallback bar for routers without one of their own. A Chain or Merge reports `calibrated=True` only when every router in it is calibrated. You can also `fit()` the whole composition on labelled queries, like any router. Both are routers, so they nest. Here, queries the fast router is unsure about get a blended answer from a hybrid router and the decision model: ```python from semantic_router.encoders import BM25Encoder hybrid = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), sparse_encoder=BM25Encoder(), routes=routes, ) hybrid.fit(X=held_out_queries, y=held_out_labels) router = Chain(routers=[fast, Merge(routers=[hybrid, smart])]) ``` Their routes are the routes of the first router you pass in. Give every router in a composition the same routes. # Migrating from 0.x to 1.0 (/docs/semantic-router/v1/user-guide/guides/migration-to-v1) Semantic Router 1.0 is a breaking release. The routing layer was rebuilt around calibrated confidence and composable routers, and a lot of 0.x machinery is gone: index sync, dynamic routes and the LLM classes. This guide walks through every change, each with the 0.x code and its 1.0 replacement. Most apps need only the first few sections: the router class, thresholds and `fit()`. Not ready to move? Pin `semantic-router<1`. The 0.x line gets bug fixes on the [`v0` branch](https://github.com/aurelio-labs/semantic-router/tree/v0), and its docs stay online under [v0](../../get-started/versions). ## At a glance [#at-a-glance] | 0.x | 1.0 | | -------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `SemanticRouter` | `IndexedRouter` | | `HybridRouter` | `IndexedRouter(sparse_encoder=..., alpha=...)`; `alpha` defaults to 0.7, not 0.3 | | `encoder` defaults to `OpenAIEncoder()` | `encoder` is required | | a default `score_threshold` on every encoder | removed: no threshold unless you set one | | `score_threshold` (route and router) | `confidence_threshold` (route and router) | | `fit()` searches for thresholds, returns `None` | `fit()` calibrates confidence, returns a `FitReport` | | `RouteChoice.similarity_score` | `RouteChoice.confidence`, plus `RouteChoice.calibrated` | | `RouteChoice.function_call` | removed, along with dynamic routes | | `auto_sync`, `sync()`, `is_synced()`, `get_utterance_diff()` | removed: the index is the source of truth | | `Route(function_schemas=..., llm=...)`, `semantic_router.llms` | removed | | `router(..., route_filter=[...])` | removed: filter the ranked results | | `router(vector=...)`, `simulate_static=` | removed | | `router.delete(route_name=...)` | `router.remove(name=...)` | | `router.get(...)`, `list_route_names()`, `update()` | read `router.routes`; `remove()` then `add()` | | `to_yaml(file_path)`, `from_yaml()`, `RouterConfig` | `to_yaml(path=)`, `load_router(path=)` | | Python 3.9+ | Python 3.10+ | New in 1.0, with no 0.x equivalent: [`DecisionRouter`](../features/decision-models), [`Chain` and `Merge`](../features/composition), and [calibration](../features/calibration). ## Install [#install] ```bash pip install -qU "semantic-router>=1,<2" ``` The extras are unchanged, except that `[local]` no longer installs `llama-cpp-python`, because the LLM classes are gone. FastEmbed has its own extra, `[fastembed]`. ## SemanticRouter is now IndexedRouter [#semanticrouter-is-now-indexedrouter] The router that embeds your utterances and searches an index is now called `IndexedRouter`, because it's one kind of router among several. It takes the same core arguments. **0.x** ```python # 0.x from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder router = SemanticRouter( encoder=OpenAIEncoder(), routes=routes, auto_sync="local", ) choice = router("why was I charged twice?") choice.name, choice.similarity_score ``` **1.0** ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import OpenAIEncoder router = IndexedRouter( encoder=OpenAIEncoder(), routes=routes, ) choice = router("why was I charged twice?") choice.name, choice.confidence, choice.calibrated ``` The constructor embeds every utterance and writes it to the index straight away, so the router is ready when it returns. `index`, `top_k` and `aggregation` work as before. ## HybridRouter is a flag, not a class [#hybridrouter-is-a-flag-not-a-class] Pass a `sparse_encoder` to `IndexedRouter` and it becomes a hybrid router. Without an index, it uses a `HybridLocalIndex`. **0.x** ```python # 0.x from semantic_router.routers import HybridRouter from semantic_router.encoders import BM25Encoder, OpenAIEncoder router = HybridRouter( encoder=OpenAIEncoder(), sparse_encoder=BM25Encoder(), routes=routes, alpha=0.3, ) ``` **1.0** ```python from semantic_router import IndexedRouter from semantic_router.encoders import BM25Encoder, OpenAIEncoder router = IndexedRouter( encoder=OpenAIEncoder(), sparse_encoder=BM25Encoder(), routes=routes, alpha=0.7, ) ``` `alpha` is still the weight on the dense score, with the rest on the sparse score. Three things changed: * **The default is 0.7, not 0.3**, so meaning leads and keywords boost. On our test sets, 0.7 beat 0.3 by up to 17 points of top-1 accuracy (BM25: .93 against .76). The full table is on the [routers page](../components/routers#hybrid-search). * **On `HybridLocalIndex`, `alpha` now weights the dense side too.** In 0.x that index normalised the query vector, which cancelled `alpha` on the dense score, so only the sparse score was scaled. Expect hybrid scores to move. * **On Pinecone, `alpha` already weighted both sides.** To keep 0.x's weighting there, pass `alpha=0.3`. What's gone is the threshold rescaling: `HybridRouter` multiplied its threshold by `alpha`, and 1.0 doesn't. Calibration absorbs the difference, so refit after you upgrade. A *fitted* sparse encoder such as `BM25Encoder` changes its vocabulary whenever the routes change. So `add()` on a hybrid router refits the sparse encoder and rebuilds the whole index. On Pinecone, rebuilding deletes and recreates the remote index. ## The encoder is required [#the-encoder-is-required] 0.x quietly built an `OpenAIEncoder()` when you didn't pass one. 1.0 makes you choose. **0.x** ```python # 0.x router = SemanticRouter(routes=routes) # OpenAI, from OPENAI_API_KEY ``` **1.0** ```python from semantic_router.encoders import OpenAIEncoder router = IndexedRouter(encoder=OpenAIEncoder(), routes=routes) ``` ## There's no default threshold [#theres-no-default-threshold] This is the change most likely to surprise you. In 0.x, every encoder came with a default `score_threshold` (0.3 for OpenAI, 0.5 for FastEmbed, and so on), so an off-topic query usually came back with `name=None`. In 1.0, a router has **no threshold unless you set one**, and the best route always wins, however weak the match. The encoders no longer take a `score_threshold` at all. **0.x** ```python # 0.x router = SemanticRouter(encoder=encoder, routes=routes) router("what's the capital of australia?").name # None: under the encoder's default ``` **1.0** ```python router = IndexedRouter(encoder=encoder, routes=routes) router("what's the capital of australia?").name # the closest route, however weak # calibrate, then set a bar to get None back for off-topic queries router.fit(X=held_out_queries, y=labels) router.confidence_threshold = 0.5 router("what's the capital of australia?").name # None ``` If you depended on `name=None` for a fallback path, add a `confidence_threshold` before you ship. ## score\_threshold is now confidence\_threshold [#score_threshold-is-now-confidence_threshold] Thresholds sit in the same two places as before, the router and the route, under a new name. A route's own threshold wins over the router's. **0.x** ```python # 0.x billing = Route(name="billing", utterances=billing_utterances, score_threshold=0.82) router = SemanticRouter(encoder=encoder, routes=[billing, chitchat], score_threshold=0.75) router.set_threshold(threshold=0.8, route_name="billing") router.get_thresholds() ``` **1.0** ```python billing = Route(name="billing", utterances=billing_utterances, confidence_threshold=0.9) router = IndexedRouter(encoder=encoder, routes=[billing, chitchat], confidence_threshold=0.75) router.confidence_threshold = 0.8 # the router's default bar {r.name: r.confidence_threshold for r in router.routes} ``` The name changed because the number changed. Until you call `fit()`, the bar applies to raw similarity, as in 0.x. After `fit()`, it applies to a calibrated probability: 0.9 means "the route is right at least 90% of the time". So **don't copy your old `score_threshold` values across.** Fit first, then pick a bar from how often you can afford to be wrong. You can also pass a one-off bar per call with `router(query, threshold=0.6)`. It wins over both the route's and the router's. ## fit() calibrates instead of searching [#fit-calibrates-instead-of-searching] In 0.x, `fit()` ran a random search over per-route thresholds and returned nothing. In 1.0 it learns a curve from raw score to the probability that the top route is right, and returns a report. **0.x** ```python # 0.x router.fit(X=queries, y=labels, max_iter=500) # -> None accuracy = router.evaluate(X=test_queries, y=test_labels) ``` **1.0** ```python report = router.fit(X=held_out_queries, y=labels, method="platt") # FitReport(method='platt', n=150, accuracy=0.93, ece=0.03) accuracy = router.evaluate(X=test_queries, y=test_labels) ``` * **Fit on held-out queries, never on the utterances you gave the routes.** A stored utterance matches itself at a similarity near 1.0, so the calibrator learns that only near-perfect scores are trustworthy, and real queries look unsure. `IndexedRouter` warns if it sees stored utterances in `X`. * A label of `None` still means "no route should match". * `batch_size`, `max_iter` and `local_execution` are gone. `method` is `"platt"` (the default) or `"isotonic"`. * `evaluate()` is unchanged: end-to-end accuracy with your thresholds applied. The [calibration guide](../features/calibration) explains both methods and how much data each needs. ## RouteChoice has three fields [#routechoice-has-three-fields] **0.x** ```python # 0.x class RouteChoice(BaseModel): name: Optional[str] = None function_call: Optional[List[Dict]] = None similarity_score: Optional[float] = None ``` **1.0** ```python class RouteChoice(BaseModel): name: Optional[str] = None confidence: Optional[float] = None calibrated: bool = False ``` * `similarity_score` becomes `confidence`. Before `fit()` it's the raw score, as before; after, it's a probability. * `calibrated` tells you which of the two you're looking at. * `function_call` is gone with dynamic routes. `limit` works as before: `limit=1` returns one `RouteChoice` (with `name=None` when nothing clears the bar), and `limit=None` returns every route that clears it, best first. ## Sync is gone [#sync-is-gone] 0.x kept a copy of your routes in the router and another in the index, and the `auto_sync` modes reconciled the two. 1.0 drops all of it. **The index is the single source of truth**: the router writes routes to it, and `router.routes` reads them back. Each record's id comes from its route and utterance, so writing the same routes twice changes nothing. Removed: `auto_sync`, `sync()`, `async_sync()`, `is_synced()`, `get_utterance_diff()`, the index hash, lock and config records, and `SyncMode`, `UtteranceDiff` and `ConfigParameter` from `semantic_router.schema`. **0.x** ```python # 0.x router = SemanticRouter( encoder=encoder, routes=routes, index=PineconeIndex(index_name="routes", dimensions=1536), auto_sync="local", ) if not router.is_synced(): router.sync("merge-force-local") ``` **1.0** ```python router = IndexedRouter( encoder=encoder, routes=routes, index=PineconeIndex(index_name="routes", dimensions=1536), ) ``` Passing `routes=` adds or updates; it never deletes. Routes that are in the index but not in your list stay there, unlike `auto_sync="local"`. Remove a route with `router.remove(name=...)`. To connect to an index that's already filled, leave `routes` out: `IndexedRouter(encoder=encoder, index=index)` reads the routes from the index, which replaces `auto_sync="remote"`. To see routes that other processes add later, call `router.refresh()` or set `refresh_interval`; see [sharing an index](../components/indexes#sharing-an-index). Upgrading a remote index that 0.x filled? The cleanest path is to point 1.0 at a new index (or a new namespace) and let the router fill it from your routes. Reusing the old one also works: * Record ids use the same scheme as 0.x, so adding your routes again updates the old records rather than duplicating them. * 1.0 ignores the old sync records (the `sr_config` namespace on Pinecone, the `sr_config` collection on Qdrant). They're harmless, and you can delete them by hand. * Routes read back without a description or threshold until you add them again. * **Postgres:** rows written by 0.x's async `aadd()` have random ids, so they don't dedupe. If you used it, start a new table. The [indexes guide](../components/indexes) covers sharing one index between routers. ## Managing routes [#managing-routes] **0.x** ```python # 0.x router.add(Route(name="greetings", utterances=["hello there", "hi, how are you?"])) router.delete(route_name="greetings") router.get("billing") router.list_route_names() router.update(name="billing", utterances=new_utterances) ``` **1.0** ```python router.add(routes=Route(name="greetings", utterances=["hello there", "hi, how are you?"])) router.remove(name="greetings") next(r for r in router.routes if r.name == "billing") [r.name for r in router.routes] # to change a route, replace it router.remove(name="billing") router.add(routes=Route(name="billing", utterances=new_utterances)) ``` `add()` takes one route or a list. If the router is calibrated, `add()` and `remove()` refit it on the labelled queries you last passed to `fit()`, and warn you when a new route has no labelled queries yet. ## Dynamic routes and the LLM classes are gone [#dynamic-routes-and-the-llm-classes-are-gone] 1.0 is a decision layer: it tells you *which* route applies, and your code decides what happens next. Dynamic routes, which generated function arguments with an LLM, are removed along with everything that supported them: * `Route(function_schemas=..., llm=...)`, `Route.from_dynamic_route()`, and calling a `Route` directly * the `llm` argument on routers, and `RouteChoice.function_call` * the whole `semantic_router.llms` package: `BaseLLM`, `OpenAILLM`, `AzureOpenAILLM`, `CohereLLM`, `MistralAILLM`, `OllamaLLM`, `OpenRouterLLM` and `LlamaCppLLM` * `semantic_router.utils.function_call` (`get_schema`, `get_schemas_openai`) and the `Message` schema Route first, then call the tool with whatever LLM client you already use. **0.x** ```python # 0.x from semantic_router.llms import OpenAILLM from semantic_router.utils.function_call import get_schemas_openai time_route = Route( name="get_time", utterances=["what time is it in rome?", "what's the time in new york?"], function_schemas=get_schemas_openai([get_time]), ) router = SemanticRouter(encoder=encoder, routes=[time_route], llm=OpenAILLM()) choice = router("what's the time in tokyo?") get_time(**choice.function_call[0]["arguments"]) ``` **1.0** ```python from openai import OpenAI time_route = Route( name="get_time", utterances=["what time is it in rome?", "what's the time in new york?"], ) router = IndexedRouter(encoder=encoder, routes=[time_route], confidence_threshold=0.5) query = "what's the time in tokyo?" if router(query).name == "get_time": # the router picked the tool; your LLM fills in its arguments response = OpenAI().chat.completions.create( model="gpt-4.1-mini", messages=[{"role": "user", "content": query}], tools=[{"type": "function", "function": get_time_schema}], tool_choice={"type": "function", "function": {"name": "get_time"}}, ) ``` Routing still saves you the expensive part: the LLM only runs when a tool is actually needed, and it never has to choose between tools. ## route\_filter is gone [#route_filter-is-gone] `limit=None` returns every route that clears its bar, best first, so you can filter the ranked list yourself. **0.x** ```python # 0.x router("how's the weather?", route_filter=["chitchat", "weather"]) ``` **1.0** ```python allowed = {"chitchat", "weather"} picks = [c for c in router("how's the weather?", limit=None) if c.name in allowed] choice = picks[0] if picks else None ``` If you always route over the same subset, build a second router with only those routes. Routers can share one index. ## Other call arguments [#other-call-arguments] A router call is now `router(query, limit=1, threshold=None)`. * `vector=` is gone: routers take the text and embed it themselves. * `simulate_static=` is gone with dynamic routes. * `text=` is now the first positional argument, `query`. **0.x** ```python # 0.x router(text="hello", simulate_static=True) ``` **1.0** ```python router("hello") ``` ## Saving and loading [#saving-and-loading] A config file now says which kind of router it describes, in a `router_type` field, so one loader can rebuild any router: an `IndexedRouter`, a `DecisionRouter`, a `Chain` or a `Merge`. A fitted calibrator is saved too, so a loaded router is calibrated straight away. **0.x** ```python # 0.x router.to_yaml("router.yaml") router = SemanticRouter.from_yaml("router.yaml") from semantic_router import RouterConfig config = RouterConfig.from_file("router.yaml") ``` **1.0** ```python from semantic_router import load_router router.to_yaml(path="router.yaml") router = load_router(path="router.yaml") ``` 0.x files have no `router_type`, so `load_router` won't read them. Rebuild the routes from an old file in a few lines, then save in the new format: ```python import yaml from semantic_router import IndexedRouter, Route with open("old_router.yaml") as f: old = yaml.safe_load(f) routes = [ Route( name=r["name"], utterances=r["utterances"], description=r.get("description"), metadata=r.get("metadata") or {}, ) for r in old["routes"] ] router = IndexedRouter(encoder=encoder, routes=routes) router.to_yaml(path="router.yaml") ``` Leave `score_threshold` behind and calibrate instead (see above). The [save and load guide](save-load-from-file) shows the new format. ## Async [#async] The async methods keep their shape and gain the new ones: `acall`, `aadd`, `aremove`, `afit` and `aevaluate`. **0.x** ```python # 0.x choice = await router.acall(text="hello") await router.aadd(new_route) await router.adelete(route_name="greetings") ``` **1.0** ```python choice = await router.acall("hello") await router.aadd(routes=new_route) await router.aremove(name="greetings") report = await router.afit(X=held_out_queries, y=labels) ``` Every sync method runs its async twin on one shared background event loop. That keeps HTTP connections pooled between calls and works inside notebooks. Inside your own async code, use the `a`-methods with `await`. ## Keyword arguments [#keyword-arguments] Every example in these docs passes arguments by keyword, `IndexedRouter(encoder=encoder, routes=routes)` and `Chain(routers=[fast, smart])`, and we recommend you do the same. The query is the one exception: `router("...")`. ## Building on 1.0 [#building-on-10] A router is now anything that scores every route. Subclass `BaseRouter`, implement one async method, and you get calling, thresholds, calibration, evaluation and composition for free. See [routers](../components/routers#build-your-own-router). # Save and load routers (/docs/semantic-router/v1/user-guide/guides/save-load-from-file) You can save a router to a file and load it back later. That's useful for shipping the same routes and settings between environments, keeping them in version control, or skipping a refit every time you start up. One loader handles every kind of router. Each file says what it describes in a `router_type` field: `indexed`, `decision`, `chain` or `merge`. ## Save a router [#save-a-router] ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import FastEmbedEncoder routes = [ Route( name="politics", utterances=["isn't politics the best thing ever", "why don't you tell me about your political opinions"], ), Route( name="chitchat", utterances=["how's the weather today?", "how are things going?"], description="Small talk.", confidence_threshold=0.9, ), ] router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), routes=routes, confidence_threshold=0.5, ) router.fit( X=["who should I vote for?", "nice day isn't it", "what's 2+2?", "the election is rigged", "how have you been?", "translate cat to french"], y=["politics", "chitchat", None, "politics", "chitchat", None], ) router.to_yaml(path="router.yaml") ``` `router.to_json(path="router.json")` writes the same thing as JSON. Here's the YAML: ```yaml router_type: indexed encoder: type: fastembed name: BAAI/bge-small-en-v1.5 sparse_encoder: null alpha: 0.7 top_k: 5 aggregation: mean index: type: local confidence_threshold: 0.5 calibrator: method: platt params: a: - 9.789179445243244 b: - -4.871250211949403 refresh_interval: null routes: - name: politics utterances: - isn't politics the best thing ever - why don't you tell me about your political opinions description: null confidence_threshold: null metadata: {} - name: chitchat utterances: - how's the weather today? - how are things going? description: Small talk. confidence_threshold: 0.9 metadata: {} ``` The encoder is saved by type and model name, and the index by type and its settings. The fitted calibrator is saved too. The routes are in the file because this router's index is in memory, so the file is the only place they can come back from. ## Load it back [#load-it-back] ```python from semantic_router import load_router router = load_router(path="router.yaml") router("don't you love politics?") ``` ``` [Out]: RouteChoice(name='politics', confidence=0.8947431378911611, calibrated=True) ``` `load_router` returns the class the file's `router_type` names: an `IndexedRouter`, a `DecisionRouter`, a `Chain` or a `Merge`. It rebuilds the encoder and the index, writes the routes to the index, and restores the calibrator, so the loaded router routes exactly like the one you saved, with no refit. ## Routers on a remote index [#routers-on-a-remote-index] A remote index (Pinecone, Qdrant, Postgres) already holds the routes, and it's their single source of truth. So the file names the index and leaves the routes out: ```yaml router_type: indexed encoder: type: fastembed name: BAAI/bge-small-en-v1.5 sparse_encoder: null alpha: 0.7 top_k: 5 aggregation: mean index: type: qdrant dimensions: 384 index_name: support-routes location: null url: http://localhost:6333 confidence_threshold: null calibrator: null refresh_interval: null ``` `load_router` connects to that index and reads the routes from it, so a loaded router always routes over what's stored now, not what was there when you saved. A loaded calibrator doesn't come with the labelled queries it was fitted on. If you `add()` or `remove()` a route on a loaded router, the calibrator is dropped with a warning: call `fit()` again. ## No secrets in files [#no-secrets-in-files] Files never hold API keys or connection strings. Encoders are saved as their type and model name, and indexes keep only settings that aren't secret, such as `index_name`, `namespace` and `metric`. When you load a file, the encoder, index and decision model read their keys from the environment, as they do when you build them in code: `OPENAI_API_KEY`, `PINECONE_API_KEY`, `JEV_API_KEY` and so on. `load_router` refuses a file with an `api_key` written into it. ## Other router types [#other-router-types] A `DecisionRouter` saves its model as a block, the way an `IndexedRouter` saves its encoder, and its routes. The block always has the model's `type` and `name`; other settings appear only when you changed them from their defaults: ```yaml router_type: decision model: type: typesafe name: jev-latest instructions: Which route does the user's message belong to? confidence_threshold: null calibrator: null routes: - name: billing utterances: - i want a refund description: 'Money already paid or owed: refunds, charges, invoices.' confidence_threshold: null metadata: {} ``` A `Chain` or `Merge` nests the routers it's made of, under `routers`, each with its own `router_type`. A `Merge` adds its `weights`. Trimmed, a Chain looks like this: ```yaml router_type: chain confidence_threshold: null calibrator: null routers: - router_type: indexed encoder: type: fastembed name: BAAI/bge-small-en-v1.5 index: type: local confidence_threshold: 0.85 routes: [...] - router_type: decision model: type: typesafe name: jev-latest routes: [...] ``` ## What can't be saved [#what-cant-be-saved] Saving fails straight away, rather than on load, for anything the loader couldn't rebuild: a custom router or index, and encoders that can't be rebuilt from a type and a name (your own encoder classes, `HFEndpointEncoder`, `LocalSparseEncoder`). For those, build the router in code. Unknown fields are errors, so a typo in a hand-edited file fails loudly instead of being ignored. ## Files from 0.x [#files-from-0x] 0.x files have no `router_type`, so `load_router` rejects them with an error that links the [migration guide](migration-to-v1#saving-and-loading). The guide shows how to rebuild the routes from an old file in a few lines and save them in the new format. # Local execution (/docs/semantic-router/v1/user-guide/guides/local-execution) There are plenty of reasons to keep routing on your own hardware: cost, latency, privacy, compliance, or just working offline. An `IndexedRouter` with a local encoder and a local index makes no network calls at all once the model is downloaded. ## Pick a local encoder [#pick-a-local-encoder] | Encoder | Install | Good for | | -------------------- | ---------------------------------------------- | ------------------------------------------------------------------ | | `FastEmbedEncoder` | `pip install -qU "semantic-router[fastembed]"` | The lightest start: small ONNX models that run fast on CPU. | | `HuggingFaceEncoder` | `pip install -qU "semantic-router[local]"` | Any Hugging Face embedding model, on CPU, CUDA or Apple silicon. | | `LocalEncoder` | `pip install -qU "semantic-router[local]"` | Any sentence-transformers model. | | `TfidfEncoder` | base install | A sparse encoder fitted on your own utterances, for hybrid search. | | `LocalSparseEncoder` | `pip install -qU "semantic-router[local]"` | Neural sparse models such as SPLADE. | ## A fully local router [#a-fully-local-router] FastEmbed for meaning, TF-IDF for keywords, and the default in-memory index: ```python from semantic_router import IndexedRouter, Route from semantic_router.encoders import FastEmbedEncoder, TfidfEncoder routes = [ Route( name="get_time", utterances=["what time is it in rome?", "what's the time in new york?", "tell me the time in tokyo", "current time in london"], ), Route( name="weather", utterances=["how's the weather today?", "is it going to rain?", "what's the forecast for tomorrow?", "is it cold outside?"], ), ] router = IndexedRouter( encoder=FastEmbedEncoder(name="BAAI/bge-small-en-v1.5"), sparse_encoder=TfidfEncoder(), routes=routes, alpha=0.7, # mostly meaning, some keywords ) router("what's the time in sydney right now?").name ``` ``` [Out]: 'get_time' ``` The first `FastEmbedEncoder` call downloads the model (about 70 MB) and caches it. After that, nothing leaves your machine. Calibrate it the same way as any router, with labelled queries it hasn't seen, and save it to a file so the next start-up skips the refit. See [calibration](../features/calibration) and [save and load](save-load-from-file). ## Hugging Face models [#hugging-face-models] `HuggingFaceEncoder` runs any embedding model from the Hugging Face Hub with PyTorch, on whatever hardware you have: ```python from semantic_router.encoders import HuggingFaceEncoder encoder = HuggingFaceEncoder(name="sentence-transformers/all-MiniLM-L6-v2") ``` Bigger models are usually more accurate and slower. Since every query is embedded on the hot path, start small and move up only if your [evaluation](../features/calibration#measure-it) says you need to. ## A local decision model [#a-local-decision-model] A `DecisionRouter` can run locally too: `GLiNER2DecisionModel` runs the open GLiNER2.5-Decide model in-process, from the same `local` extra. It reads your route descriptions instead of embedding utterances. See [run a decision model locally](../features/decision-models#run-a-decision-model-locally). ## Pairing with a local LLM [#pairing-with-a-local-llm] Semantic Router doesn't run LLMs any more: it decides, and your code acts. To pair it with a local model, route first, then call the model only when a route needs one. With [Ollama](https://ollama.com), for example: ```python from datetime import datetime from zoneinfo import ZoneInfo import ollama def get_time(timezone: str) -> str: """Get the current time in an IANA timezone, such as "Australia/Sydney".""" return datetime.now(ZoneInfo(timezone)).strftime("%H:%M") query = "what's the time in sydney right now?" choice = router(query) if choice.name == "get_time": # the router picked the tool; the local LLM fills in its arguments reply = ollama.chat(model="llama3.2", messages=[{"role": "user", "content": query}], tools=[get_time]) ``` The LLM never has to choose between tools, and it doesn't run at all for queries that don't need it. # Configuration (/docs/semantic-router/v1/user-guide/guides/configuration) ## Logging [#logging] Semantic Router uses Python's standard `logging` module. You control how much it says with an environment variable. ### Setting the log level [#setting-the-log-level] Two variables work. Set the library-specific one if you can: ```bash export SEMANTIC_ROUTER_LOG_LEVEL=DEBUG ``` Or use the general one, which other libraries may share: ```bash export LOG_LEVEL=WARNING ``` `SEMANTIC_ROUTER_LOG_LEVEL` wins if both are set. If neither is, the level is `INFO`. ### Levels [#levels] * `DEBUG` — detailed diagnostics. * `INFO` — general progress (the default). * `WARNING` — something looks off but still works. * `ERROR` — something failed. * `CRITICAL` — something failed badly. ### From Python [#from-python] Set the variable *before* importing the library: ```python import os os.environ["SEMANTIC_ROUTER_LOG_LEVEL"] = "DEBUG" from semantic_router import IndexedRouter, Route # debug logs now show ``` Turn on `DEBUG` when you're chasing an encoder or index problem, want to see what a router is doing on each call, or need to understand what the library is doing under the hood. # Semantic Router v0 (/docs/semantic-router/v0) Superfast decision-making layer for LLMs and agents. ## Sections [#sections] * [Get Started](/docs/semantic-router/v0/get-started/introduction) * [Client Reference](/docs/semantic-router/v0/client-reference/linear) * [User Guide](/docs/semantic-router/v0/user-guide/changelog) # Introduction (/docs/semantic-router/v0/get-started/introduction) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/get-started/introduction), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. Semantic Router is a superfast decision layer for LLMs and agents. Most tools make routing decisions by asking an LLM and waiting for it to answer. That's slow. Semantic Router skips the wait — it compares the *meaning* of an input against your routes in vector space and picks a match in milliseconds. The payoff is simple. Decisions land in milliseconds, not seconds. You skip an LLM call, so you cut cost. And because routes are explicit, you stay in control of what happens next. ## How it works [#how-it-works] You define routes, each one a handful of example phrases. Semantic Router embeds those examples once, up front. At runtime it embeds the incoming request and matches it to the closest route by meaning. No keyword matching, and no LLM in the hot path. From there you can: * **Trigger functions.** Dynamic routes extract parameters and call your code. * **Go multi-modal.** Route on images, not just text. * **Scale it.** Persist routes in Pinecone, Qdrant, or Postgres. * **Run it anywhere.** Cloud APIs, fully local, or a mix of both. It works with the encoders you already use — OpenAI, Cohere, Hugging Face, FastEmbed, and more. ## Running local or in the cloud [#running-local-or-in-the-cloud] You choose how much runs on your machine: * **Cloud.** Embeddings from OpenAI, Cohere, or another API. * **Hybrid.** Local embeddings, API-based LLMs. * **Fully local.** Everything on your hardware, with models like Llama and Mistral. No external calls. ## Start here [#start-here] New to Semantic Router? The [quickstart](quickstart) gets you routing in a few minutes. Upgrading from a 0.0.x release? v0.1 introduced breaking changes — the [migration guide](../user-guide/guides/migration-to-v0-1) walks you through them. ## Resources [#resources] * [GitHub repository](https://github.com/aurelio-labs/semantic-router) * [Online course](https://www.aurelio.ai/course/semantic-router) # Quickstart (/docs/semantic-router/v0/get-started/quickstart) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/get-started/quickstart), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. Semantic Router sends text to the right handler based on *meaning*, not keywords. That makes it a good fit for chatbots, intent classification, guardrails — anything that needs to understand what a user is actually asking. Install it: ```bash pip install -qU semantic-router ``` Want everything to run locally, with no API calls? Install the `local` extra and use `HuggingFaceEncoder` with `LlamaCppLLM`. The [local execution guide](../user-guide/guides/local-execution) walks through it. ```bash pip install -qU "semantic-router[local]" ``` ## Define your routes [#define-your-routes] A `Route` is a topic or intent you want to detect. You describe it with example utterances — a few phrases a user might say. Those examples become the route's semantic reference point. Let's start with two: one for *politics*, one for *chitchat*. ```python from semantic_router import Route # use this to steer a chatbot away from political conversation politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "they're going to destroy this country!", "they will save the country!", ], ) # and this to switch the chatbot into a more conversational mode chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` ## Pick an encoder [#pick-an-encoder] An encoder turns text into a vector, so we can measure how similar two pieces of text are. Semantic Router supports a lot of them — OpenAI, Cohere, Hugging Face, FastEmbed, and more. The [encoders guide](../user-guide/components/encoders) has the full list. We'll use Cohere or OpenAI here: ```python import os from semantic_router.encoders import CohereEncoder, OpenAIEncoder # Cohere os.environ["COHERE_API_KEY"] = "" encoder = CohereEncoder() # or OpenAI os.environ["OPENAI_API_KEY"] = "" encoder = OpenAIEncoder() ``` ## Create the router [#create-the-router] The `SemanticRouter` is the decision engine. Hand it your encoder and routes: ```python from semantic_router import SemanticRouter sr = SemanticRouter(encoder=encoder, routes=routes) ``` ## Route a query [#route-a-query] Now call it. Under the hood, the router embeds your query and finds the closest route. ```python sr("don't you love politics?").name ``` ``` [Out]: 'politics' ``` Right answer. One more: ```python sr("how's the weather today?").name ``` ``` [Out]: 'chitchat' ``` Both correct. Notice the queries don't match any utterance word for word — they just mean the same thing. That's the whole point. ## When nothing matches [#when-nothing-matches] Send something unrelated: ```python sr("I'm interested in learning about llama 2").name ``` ``` [Out]: ``` No route was close enough, so the router returns `None`. Treat that as your fallback signal: pass the query through, hand it to a default handler, whatever fits your app. # Versions (/docs/semantic-router/v0/get-started/versions) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/get-started/versions), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. Semantic Router has two release lines. Pick the one that matches the version you have installed, and use the version switcher at the top of the sidebar to read the matching docs. ## v0: the 0.x line [#v0-the-0x-line] The 0.x releases are the library as it has shipped since 2023: `SemanticRouter`, `HybridRouter`, utterance-based routes, `score_threshold`, and index synchronisation. The final feature release of this line is **0.3.0**. After that it receives bug fixes only. Install it with an upper bound so an upgrade never moves you to 1.x by accident: ```bash pip install "semantic-router<1" ``` The 0.x source lives on the [`v0` branch](https://github.com/aurelio-labs/semantic-router/tree/v0). Bug reports and fixes for 0.x should target that branch. ## v1: the 1.x line [#v1-the-1x-line] The 1.x line rebuilds the routing layer around calibrated confidence, decision-model backends, and composable routers. It shipped as **1.0.0** from the [`main` branch](https://github.com/aurelio-labs/semantic-router). It is a breaking change: route definitions, thresholds, and the router classes all move. The [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) covers every change, with before and after code. ```bash pip install -qU "semantic-router>=1,<2" ``` ## Which one should I use? [#which-one-should-i-use] * **Starting something new?** Use 1.x, and read the [v1 docs](https://docs.aurelio.ai/docs/semantic-router/v1/get-started/introduction). * **Running 0.x in production?** Nothing changes until you choose to migrate. Pin `semantic-router<1` and stay on these docs until then. * **Contributing?** Fixes for 0.x go to `v0`; everything else goes to `main`. See [Contributing](https://github.com/aurelio-labs/semantic-router/blob/main/CONTRIBUTING.md). # semantic_router.linear (/docs/semantic-router/v0/client-reference/linear) #### similarity\_matrix [#similarity_matrix] ```python def similarity_matrix(xq: np.ndarray, index: np.ndarray) -> np.ndarray ``` Compute the similarity scores between a query vector and a set of vectors. **Arguments**: * `xq`: A query vector (1d ndarray) * `index`: A set of vectors. **Returns**: `np.ndarray`: The similarity between the query vector and the set of vectors. #### top\_scores [#top_scores] ```python def top_scores(sim: np.ndarray, top_k: int = 5) -> Tuple[np.ndarray, np.ndarray] ``` Get the top scores and indices from a similarity matrix. **Arguments**: * `sim`: A similarity matrix. * `top_k`: The number of top scores to get. **Returns**: `Tuple[np.ndarray, np.ndarray]`: The top scores and indices. # semantic_router.route (/docs/semantic-router/v0/client-reference/route) #### is\_valid [#is_valid] ```python def is_valid(route_config: str) -> bool ``` Check if the route config is valid. **Arguments**: * `route_config` (`str`): The route config to check. **Returns**: `bool`: Whether the route config is valid. ## Route Objects [#route-objects] ```python class Route(BaseModel) ``` A route for the semantic router. **Arguments**: * `name` (`str`): The name of the route. * `utterances` (`Union[List[str], List[Any]]`): The utterances of the route. * `description` (`Optional[str]`): The description of the route. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas of the route. * `llm` (`Optional[BaseLLM]`): The LLM to use. * `str`0 (`str`1): The score threshold of the route. * `str`2 (`str`3): The metadata of the route. #### \_\_call\_\_ [#__call__] ```python def __call__(query: Optional[str] = None) -> RouteChoice ``` Call the route. If dynamic routes have been provided the query must have been provided and the llm attribute must be set. **Arguments**: * `query` (`Optional[str]`): The query to pass to the route. **Returns**: `RouteChoice`: The route choice. #### acall [#acall] ```python async def acall(query: Optional[str] = None) -> RouteChoice ``` Asynchronous call the route. If dynamic routes have been provided the query must have been provided and the llm attribute must be set. **Arguments**: * `query` (`Optional[str]`): The query to pass to the route. **Returns**: `RouteChoice`: The route choice. #### to\_dict [#to_dict] ```python def to_dict() -> Dict[str, Any] ``` Convert the route to a dictionary. **Returns**: `Dict[str, Any]`: The dictionary representation of the route. #### from\_dict [#from_dict] ```python @classmethod def from_dict(cls, data: Dict[str, Any]) ``` Create a Route object from a dictionary. **Arguments**: * `data` (`Dict[str, Any]`): The dictionary to create the route from. **Returns**: `Route`: The created route. #### from\_dynamic\_route [#from_dynamic_route] ```python @classmethod def from_dynamic_route(cls, llm: BaseLLM, entities: List[Union[BaseModel, Callable]], route_name: str) ``` Generate a dynamic Route object from a list of functions or Pydantic models using an LLM. **Arguments**: * `llm` (`BaseLLM`): The LLM to use. * `entities` (`List[Union[BaseModel, Callable]]`): The entities to use. * `route_name`: The name of the route. # semantic_router.schema (/docs/semantic-router/v0/client-reference/schema) ## EncoderType Objects [#encodertype-objects] ```python class EncoderType(Enum) ``` The type of encoder. ## EncoderInfo Objects [#encoderinfo-objects] ```python class EncoderInfo(BaseModel) ``` Information about an encoder. ## RouteChoice Objects [#routechoice-objects] ```python class RouteChoice(BaseModel) ``` A route choice typically output by the routers. ## Message Objects [#message-objects] ```python class Message(BaseModel) ``` A message in a conversation, includes the role and content fields. #### to\_openai [#to_openai] ```python def to_openai() ``` Convert the message to an OpenAI-compatible format. #### to\_cohere [#to_cohere] ```python def to_cohere() ``` Convert the message to a Cohere-compatible format. #### to\_llamacpp [#to_llamacpp] ```python def to_llamacpp() ``` Convert the message to a LlamaCPP-compatible format. #### to\_mistral [#to_mistral] ```python def to_mistral() ``` Convert the message to a Mistral-compatible format. #### to\_voyage [#to_voyage] ```python def to_voyage() ``` Convert the message to a Voyage-compatible format. #### to\_jina [#to_jina] ```python def to_jina() ``` Convert the message to a Jina-compatible format. #### \_\_str\_\_ [#__str__] ```python def __str__() ``` Convert the message to a string. ## ConfigParameter Objects [#configparameter-objects] ```python class ConfigParameter(BaseModel) ``` A configuration parameter for a route. Used for remote router metadata such as router hashes, sync locks, etc. #### to\_pinecone [#to_pinecone] ```python def to_pinecone(dimensions: int) ``` Convert the configuration parameter to a Pinecone-compatible format. Should be used when upserting configuration parameters to a separate config namespace within your Pinecone index. **Arguments**: * `dimensions` (`int`): The dimensions of the Pinecone index. **Returns**: `dict`: A Pinecone-compatible configuration parameter. ## Utterance Objects [#utterance-objects] ```python class Utterance(BaseModel) ``` An utterance in a conversation, includes the route, utterance, function schemas, metadata, and diff tag. #### from\_tuple [#from_tuple] ```python @classmethod def from_tuple(cls, tuple_obj: Tuple) ``` Create an Utterance object from a tuple. The tuple must contain route and utterance as the first two elements. Then optionally function schemas and metadata as the third and fourth elements respectively. If this order is not followed an invalid Utterance object will be returned. **Arguments**: * `tuple_obj` (`Tuple`): A tuple containing route, utterance, function schemas and metadata. **Returns**: `Utterance`: An Utterance object. #### to\_tuple [#to_tuple] ```python def to_tuple() ``` Convert an Utterance object to a tuple. **Returns**: `Tuple`: A tuple containing (route, utterance, function schemas, metadata). #### to\_str [#to_str] ```python def to_str(include_metadata: bool = False) ``` Convert an Utterance object to a string. Used for comparisons during sync check operations. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the string. **Returns**: `str`: A string representation of the Utterance object. ## SyncMode Objects [#syncmode-objects] ```python class SyncMode(Enum) ``` Synchronization modes for local (route layer) and remote (index) instances. ## UtteranceDiff Objects [#utterancediff-objects] ```python class UtteranceDiff(BaseModel) ``` A list of Utterance objects that represent the differences between local and remote utterances. #### from\_utterances [#from_utterances] ```python @classmethod def from_utterances(cls, local_utterances: List[Utterance], remote_utterances: List[Utterance]) ``` Create a UtteranceDiff object from two lists of Utterance objects. **Arguments**: * `local_utterances` (`List[Utterance]`): A list of Utterance objects. * `remote_utterances` (`List[Utterance]`): A list of Utterance objects. #### to\_utterance\_str [#to_utterance_str] ```python def to_utterance_str(include_metadata: bool = False) -> List[str] ``` Outputs the utterance diff as a list of diff strings. Returns a list of strings showing what is different in the remote when compared to the local. For example: \[" route1: utterance1", " route1: utterance2", "- route2: utterance3", "- route2: utterance4"] Tells us that the remote is missing "route2: utterance3" and "route2: utterance4", which do exist locally. If we see: \[" route1: utterance1", " route1: utterance2", "+ route2: utterance3", "+ route2: utterance4"] This diff tells us that the remote has "route2: utterance3" and "route2: utterance4", which do not exist locally. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the string. **Returns**: `List[str]`: A list of diff strings. #### get\_tag [#get_tag] ```python def get_tag(diff_tag: str) -> List[Utterance] ``` Get all utterances with a given diff tag. **Arguments**: * `diff_tag` (`str`): The diff tag to filter by. Must be one of "+", "-", or " ". **Returns**: `List[Utterance]`: A list of Utterance objects. #### get\_sync\_strategy [#get_sync_strategy] ```python def get_sync_strategy(sync_mode: str) -> dict ``` Generates the optimal synchronization plan for local and remote instances. **Arguments**: * `sync_mode` (`str`): The mode to sync the routes with the remote index. **Returns**: `dict`: A dictionary describing the synchronization strategy. ## Metric Objects [#metric-objects] ```python class Metric(Enum) ``` The metric to use in vector-based similarity search indexes. ## SparseEmbedding Objects [#sparseembedding-objects] ```python class SparseEmbedding(BaseModel) ``` Sparse embedding interface. Primarily uses numpy operations for faster operations. #### from\_compact\_array [#from_compact_array] ```python @classmethod def from_compact_array(cls, array: np.ndarray) ``` Create a SparseEmbedding object from a compact array. **Arguments**: * `array` (`np.ndarray`): A compact array. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_vector [#from_vector] ```python @classmethod def from_vector(cls, vector: np.ndarray) ``` Consumes an array of sparse vectors containing zero-values. **Arguments**: * `vector` (`np.ndarray`): A sparse vector. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_aurelio [#from_aurelio] ```python @classmethod def from_aurelio(cls, embedding: BM25SparseEmbedding) ``` Create a SparseEmbedding object from an AurelioSparseEmbedding object. **Arguments**: * `embedding` (`BM25SparseEmbedding`): An AurelioSparseEmbedding object. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_dict [#from_dict] ```python @classmethod def from_dict(cls, sparse_dict: dict) ``` Create a SparseEmbedding object from a dictionary. **Arguments**: * `sparse_dict` (`dict`): A dictionary of sparse values. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### from\_pinecone\_dict [#from_pinecone_dict] ```python @classmethod def from_pinecone_dict(cls, sparse_dict: dict) ``` Create a SparseEmbedding object from a Pinecone dictionary. **Arguments**: * `sparse_dict` (`dict`): A Pinecone dictionary. **Returns**: `SparseEmbedding`: A SparseEmbedding object. #### to\_dict [#to_dict] ```python def to_dict() ``` Convert a SparseEmbedding object to a dictionary. **Returns**: `dict`: A dictionary of sparse values. #### to\_pinecone [#to_pinecone-1] ```python def to_pinecone() ``` Convert a SparseEmbedding object to a Pinecone dictionary. **Returns**: `dict`: A Pinecone dictionary. #### items [#items] ```python def items() ``` Return a list of (index, value) tuples from the SparseEmbedding object. **Returns**: `list`: A list of (index, value) tuples. # semantic_router.tokenizers (/docs/semantic-router/v0/client-reference/tokenizers) ## BaseTokenizer Objects [#basetokenizer-objects] ```python class BaseTokenizer() ``` Abstract Tokenizer class #### vocab\_size [#vocab_size] ```python @property def vocab_size() -> int ``` Returns the vocabulary size of the tokenizer **Returns**: `int`: Vocabulary size of tokenizer #### config [#config] ```python @property def config() -> dict ``` The tokenizer config **Returns**: `dict`: dictionary of tokenizer config #### save [#save] ```python def save(path: str | Path) -> None ``` Saves the configuration of the tokenizer Saves these files: * tokenizer.json: saved configuration of the tokenizer **Arguments**: * `path` (`str, :class:`pathlib.Path\`\`): Path to save the tokenizer to #### load [#load] ```python @classmethod def load(cls, path: str | Path) -> "BaseTokenizer" ``` Returns a :class:`bm25_engine.tokenizer.BaseTokenizer` object from saved configuration Requires these files: * tokenizer.json: saved configuration of the tokenizer **Arguments**: * `path` (`str, :class:`pathlib.Path\`\`): Path to load the tokenizer from **Returns**: `BaseTokenizer`: Configured BaseTokenizer ## PretrainedTokenizer Objects [#pretrainedtokenizer-objects] ```python class PretrainedTokenizer(BaseTokenizer) ``` Wrapper for HuggingFace tokenizers, representing a pretrained tokenizer (i.e. bert-base-uncased). Extends the :class:`semantic_router.tokenizers.BaseTokenizer` class. **Arguments**: * `tokenizer` (`class:`tokenizers.Tokenizer\`\`): Binding for HuggingFace Rust tokenizers * `add_special_tokens` (`bool`): Whether to accept special tokens from the tokenizer (i.e. `[PAD]`) * `pad` (`bool`): Whether to pad the input to a consistent length (using `[PAD]` tokens) * `tokenizer`0 (`tokenizer`1): HuggingFace ID of the model (i.e. `tokenizer`2) #### \_\_init\_\_ [#__init__] ```python def __init__(model_ident: str, custom_normalizer: Any = None, add_special_tokens: bool = False, pad: bool = True) -> None ``` Constructor method #### vocab\_size [#vocab_size-1] ```python @property def vocab_size() ``` Returns the vocabulary size of the tokenizer **Returns**: `int`: Vocabulary size of tokenizer #### config [#config-1] ```python @property def config() -> dict ``` The tokenizer config **Returns**: `dict`: dictionary of tokenizer config #### tokenize [#tokenize] ```python def tokenize(texts: str | list[str], pad: bool = True) -> np.ndarray ``` Tokenizes a string or list of strings into a 2D :class:`numpy.ndarray` of token ids **Arguments**: * `texts` (`str, list`): Texts to be tokenized * `pad` (`bool`): unused here (configured in the constructor) **Returns**: `class:`numpy.ndarray\`\`: 2D numpy array representing token ids ## TokenizerFactory Objects [#tokenizerfactory-objects] ```python class TokenizerFactory() ``` Tokenizer factory class #### get [#get] ```python @staticmethod def get(type_: str, **tokenizer_kwargs) -> BaseTokenizer ``` Get a configured :class:`bm25_engine.tokenizer.BaseTokenizer` **Arguments**: * `type_` (`str`): Tokenizer type to instantiate * `\**kwargs`: kwargs to be passed to Tokenizer constructor **Returns**: `bm25_engine.tokenizer.BaseTokenizer`: Tokenizer # semantic_router.encoders.aurelio (/docs/semantic-router/v0/client-reference/encoders/aurelio) ## AurelioSparseEncoder Objects [#aureliosparseencoder-objects] ```python class AurelioSparseEncoder(SparseEncoder, AsymmetricSparseMixin) ``` Sparse encoder using Aurelio Platform's embedding API. Requires an API key from [https://platform.aurelio.ai](https://platform.aurelio.ai) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: Optional[str] = None) ``` Initialize the AurelioSparseEncoder. **Arguments**: * `name` (`str | None`): The name of the model to use. * `api_key` (`str | None`): The API key to use. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[str]) -> list[SparseEmbedding] ``` Encode a list of queries using the Aurelio Platform embedding API. Documents must be strings, sparse encoders do not support other types. #### acall [#acall] ```python async def acall(docs: list[str]) -> list[SparseEmbedding] ``` Asynchronously encode a list of documents using the Aurelio Platform embedding API. Documents must be strings, sparse encoders do not support other types. :param docs: The documents to encode. :type docs: list\[str] :param input\_type: :type semantic\_router.encoders.encode\_input\_type.EncodeInputType :return: The encoded documents. :rtype: list\[SparseEmbedding] #### fit [#fit] ```python def fit(docs: List[str]) ``` Fit the encoder to a list of documents. AurelioSparseEncoder does not support fit yet. **Arguments**: * `docs` (`list[str]`): The documents to fit the encoder to. # semantic_router.encoders.azure_openai (/docs/semantic-router/v0/client-reference/encoders/azure_openai) ## AzureOpenAIEncoder Objects [#azureopenaiencoder-objects] ```python class AzureOpenAIEncoder(DenseEncoder) ``` Encoder for Azure OpenAI API. This class provides functionality to encode text documents using the Azure OpenAI API. It supports customization of the score threshold for filtering or processing the embeddings. #### \_\_init\_\_ [#__init__] ```python def __init__( name: Optional[str] = None, azure_endpoint: str | None = None, api_version: str | None = None, api_key: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: Callable[[], str] | None = None, http_client_options: Optional[Dict[str, Any]] = None, deployment_name: str = EncoderDefault.AZURE.value["deployment_name"], score_threshold: float = 0.82, dimensions: Union[int, NotGiven] = NotGiven(), max_retries: int = 3) ``` Initialize the AzureOpenAIEncoder. **Arguments**: * `azure_endpoint` (`str, optional`): The endpoint for the Azure OpenAI API. Example: `"https://accountname.openai.azure.com"` * `api_version` (`str, optional`): The version of the API to use. Example: `"2025-02-01-preview"` * `api_key` (`str, optional`): The API key for the Azure OpenAI API. * `azure_ad_token` (`str, optional`): The Azure AD/Entra ID token for authentication. [https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) * `str, optional`0 (`str, optional`1): A callable function that returns an Azure AD/Entra ID token. * `str, optional`2 (`str, optional`3): Dictionary of options to configure httpx client Example: `str, optional`4 * `str, optional`5 (`str, optional`): The name of the model deployment to use. * `str, optional`7 (`str, optional`8): The score threshold for filtering embeddings. Default is `str, optional`9. * `"https://accountname.openai.azure.com"`0 (`"https://accountname.openai.azure.com"`1): The number of dimensions for the embeddings. If not given, it defaults to the model's default setting. * `"https://accountname.openai.azure.com"`2 (`"https://accountname.openai.azure.com"`1): The maximum number of retries for API calls in case of failures. Default is `"https://accountname.openai.azure.com"`4. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Encode a list of documents into embeddings using the Azure OpenAI API. **Arguments**: * `docs` (`List[str]`): The documents to encode. **Returns**: `List[List[float]]`: The embeddings for the documents. #### acall [#acall] ```python async def acall(docs: List[str]) -> List[List[float]] ``` Encode a list of documents into embeddings using the Azure OpenAI API asynchronously. **Arguments**: * `docs` (`List[str]`): The documents to encode. **Returns**: `List[List[float]]`: The embeddings for the documents. # semantic_router.encoders.base (/docs/semantic-router/v0/client-reference/encoders/base) ## DenseEncoder Objects [#denseencoder-objects] ```python class DenseEncoder(BaseModel) ``` #### set\_score\_threshold [#set_score_threshold] ```python @field_validator("score_threshold") def set_score_threshold(cls, v: float | None) -> float | None ``` Set the score threshold. If None, the score threshold is not used. **Arguments**: * `v` (`float | None`): The score threshold. **Returns**: `float | None`: The score threshold. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Any]) -> List[List[float]] ``` Encode a list of documents. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[List[float]]`: The encoded documents. #### acall [#acall] ```python async def acall(docs: List[Any]) -> List[List[float]] ``` Encode a list of documents asynchronously. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[List[float]]`: The encoded documents. ## SparseEncoder Objects [#sparseencoder-objects] ```python class SparseEncoder(BaseModel) ``` An encoder that encodes documents into a sparse format. #### \_\_call\_\_ [#__call__-1] ```python def __call__(docs: List[str]) -> List[SparseEmbedding] ``` Sparsely encode a list of documents. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[SparseEmbedding]`: The encoded documents. #### acall [#acall-1] ```python async def acall(docs: List[Any]) -> List[SparseEmbedding] ``` Encode a list of documents asynchronously. Documents can be any type, but the encoder must be built to handle that data type. Typically, these types are strings or arrays representing images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. **Returns**: `List[SparseEmbedding]`: The encoded documents. ## AsymmetricDenseMixin Objects [#asymmetricdensemixin-objects] ```python class AsymmetricDenseMixin() ``` #### encode\_queries [#encode_queries] ```python def encode_queries(docs: List[str]) -> List[List[float]] ``` Convert query texts to dense embeddings optimized for querying #### encode\_documents [#encode_documents] ```python def encode_documents(docs: List[str]) -> List[List[float]] ``` Convert document texts to dense embeddings optimized for storage #### aencode\_queries [#aencode_queries] ```python async def aencode_queries(docs: List[str]) -> List[List[float]] ``` Async version of encode\_queries #### aencode\_documents [#aencode_documents] ```python async def aencode_documents(docs: List[str]) -> List[List[float]] ``` Async version of encode\_documents ## AsymmetricSparseMixin Objects [#asymmetricsparsemixin-objects] ```python class AsymmetricSparseMixin() ``` #### encode\_queries [#encode_queries-1] ```python def encode_queries(docs: List[str]) -> List[SparseEmbedding] ``` Convert query texts to dense embeddings optimized for querying #### encode\_documents [#encode_documents-1] ```python def encode_documents(docs: List[str]) -> List[SparseEmbedding] ``` Convert document texts to dense embeddings optimized for storage #### aencode\_queries [#aencode_queries-1] ```python async def aencode_queries(docs: List[str]) -> List[SparseEmbedding] ``` Async version of encode\_queries #### aencode\_documents [#aencode_documents-1] ```python async def aencode_documents(docs: List[str]) -> List[SparseEmbedding] ``` Async version of encode\_documents # semantic_router.encoders.bedrock (/docs/semantic-router/v0/client-reference/encoders/bedrock) This module provides the BedrockEncoder class for generating embeddings using Amazon's Bedrock Platform. The BedrockEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Amazon's Bedrock Platform to generate embeddings for given documents. It requires an AWS Access Key ID and AWS Secret Access Key and supports customization of the pre-trained model, score threshold, and region. Example usage: ``` from semantic_router.encoders.bedrock_encoder import BedrockEncoder encoder = BedrockEncoder(access_key_id="your-access-key-id", secret_access_key="your-secret-key", region="your-region") embeddings = encoder(["document1", "document2"]) ``` Classes: BedrockEncoder: A class for generating embeddings using the Bedrock Platform. ## BedrockEncoder Objects [#bedrockencoder-objects] ```python class BedrockEncoder(DenseEncoder) ``` Dense encoder using Amazon Bedrock embedding API. Requires an AWS Access Key ID and AWS Secret Access Key. The BedrockEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Amazon's Bedrock Platform to generate embeddings for given documents. It supports customization of the pre-trained model, score threshold, and region. Example usage: ```python from semantic_router.encoders.bedrock_encoder import BedrockEncoder encoder = BedrockEncoder( access_key_id="your-access-key-id", secret_access_key="your-secret-key", region="your-region" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_init\_\_ [#__init__] ```python def __init__(name: str = EncoderDefault.BEDROCK.value["embedding_model"], input_type: Optional[str] = "search_query", score_threshold: float = 0.3, client: Optional[Any] = None, access_key_id: Optional[str] = None, secret_access_key: Optional[str] = None, session_token: Optional[str] = None, region: Optional[str] = None) ``` Initializes the BedrockEncoder. **Arguments**: * `name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `input_type` (`str`): The type of input to use for the embedding. If not provided, the default input type specified in EncoderDefault will be used. * `score_threshold` (`float`): The threshold for similarity scores. * `access_key_id` (`str`): The AWS access key id for an IAM principle. If not provided, it will be retrieved from the access\_key\_id environment variable. * `secret_access_key` (`str`): The secret access key for an IAM principle. If not provided, it will be retrieved from the AWS\_SECRET\_KEY environment variable. * `str`0: The session token for an IAM principle. If not provided, it will be retrieved from the AWS\_SESSION\_TOKEN environment variable. * `str`1 (`str`): The location of the Bedrock resources. If not provided, it will be retrieved from the AWS\_REGION environment variable, defaulting to "us-west-1" **Raises**: * `str`3: If the Bedrock Platform client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Union[str, Dict]], model_kwargs: Optional[Dict] = None) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`list[str]`): A list of strings representing the documents to embed. * `model_kwargs` (`dict`): A dictionary of model-specific inference parameters. **Raises**: * `ValueError`: If the Bedrock Platform client is not initialized or if the API call fails. **Returns**: `list[list[float]]`: A list of lists, where each inner list contains the embedding values for a document. #### chunk\_strings [#chunk_strings] ```python def chunk_strings(strings, MAX_WORDS=20) ``` Breaks up a list of strings into smaller chunks. **Arguments**: * `strings` (`list`): A list of strings to be chunked. * `max_chunk_size` (`int`): The maximum size of each chunk. Default is 20. **Returns**: `list[list[str]]`: A list of lists, where each inner list contains a chunk of strings. #### get\_env\_variable [#get_env_variable] ```python @staticmethod def get_env_variable(var_name, provided_value, default=None) ``` Retrieves environment variable or uses a provided value. **Arguments**: * `var_name` (`str`): The name of the environment variable. * `provided_value` (`Optional[str]`): The provided value to use if not None. * `default` (`Optional[str]`): The default value if the environment variable is not set. **Raises**: * `ValueError`: If no value is provided and the environment variable is not set. **Returns**: `str`: The value of the environment variable or the provided/default value. # semantic_router.encoders.bm25 (/docs/semantic-router/v0/client-reference/encoders/bm25) ## BM25Encoder Objects [#bm25encoder-objects] ```python class BM25Encoder(SparseEncoder, FittableMixin, AsymmetricSparseMixin) ``` BM25Encoder, running a vectorized version of ATIRE BM25 algorithm Concept: * BM25 uses scoring between queries & corpus to retrieve the most relevant documents ∈ corpus * most vector databases (VDB) store embedded documents and score them versus received queries for retrieval * we need to break up the BM25 formula into `encode_queries` and `encode_documents`, with the latter to be stored in VDB * dot product of `encode_queries(q)` and `encode_documents([D_0, D_1, ...])` is the BM25 score of the documents `[D_0, D_1, ...]` for the given query `q` * we train a BM25 encoder's normalization parameters on a sufficiently large corpus to capture target language distribution * these trained parameter allow us to balance TF & IDF of query & documents for retrieval (read more on how BM25 fixes issues with TF-IDF) The reference formula is section 4.1 of the ATIRE paper: ``` RSV_d = Σ_{t ∈ q} log(N / df_t) · (k1 + 1) · tf_td / (k1 · ((1 - b) + b · L_d / L_avg) + tf_td) ``` ## Deviations from the paper [#deviations-from-the-paper] This implementation is faithful to the formula above on the document side, but deviates from it in three documented ways. Each is deliberate; see the inline comments at the point of use for the details. 1. IDF smoothing. We compute `log((N + 1) / (df_t + 0.5))` rather than `log(N / df_t)`, to avoid a division by zero for unseen terms. This preserves the strictly-positive IDF that the ATIRE variant exists for. 2. Query weight normalization. The paper produces an unbounded relevance score, which is fine for a search engine that only ranks within a single query. A router instead compares scores against a fixed `score_threshold`, so scores must be comparable *across* queries. We therefore L1-normalize the query weights and scale them by `1 / (k1 + 1)`, which bounds the query·document dot product to \[0, 1] -- the same range as the cosine similarity returned by the dense encoders, so the two can be blended in `encode_documents`0 and thresholded alike. This is ranking-neutral within a query (it is a single positive constant per query) but it does discard cross-query IDF magnitude: two queries with different total IDF mass can produce the same score. 3. Parameter defaults. We default to `encode_documents`1 rather than the paper's `encode_documents`2. See the `encode_documents`3 and `encode_documents`4 parameter docs below. ATIRE Paper: [https://www.cs.otago.ac.nz/research/student-publications/atire-opensource.pdf](https://www.cs.otago.ac.nz/research/student-publications/atire-opensource.pdf) Pinecone Implementation: [https://github.com/pinecone-io/pinecone-text/blob/8399f9ff28c4652766c35165c0db9b0eff309077/pinecone\_text/sparse/bm25\_encoder.py](https://github.com/pinecone-io/pinecone-text/blob/8399f9ff28c4652766c35165c0db9b0eff309077/pinecone_text/sparse/bm25_encoder.py) **Arguments**: * `encode_documents`3 (`encode_documents`6): normalizer parameter that limits how much a single query term `encode_documents`7 can affect score for document `encode_documents`8. Defaults to 1.5, the standard Robertson value, *not* the 0.9 reported in the ATIRE paper. The paper's value was trained on the INEX 2008 Wikipedia collection, whose documents average 878 words (paper table 5), whereas this encoder is fitted on route utterances averaging on the order of ten tokens. Transferring the paper's parameters to utterance-length text is not obviously more correct, and changing the default would silently shift the scores that existing `score_threshold` values were tuned against. * `encode_documents`4 (`encode_documents`6): normalizer parameter that balances the effect of a single document length compared to the average document length. Defaults to 0.75 rather than the paper's 0.4, for the same reason as `encode_documents`3. Note that `encode_documents`4 is considerably more influential on short text: over utterances spanning 0.3x to 2.2x the average length, `encode_queries(q)`4 spreads the document factor by \~2.2x versus \~1.4x for `encode_queries(q)`5. Lower it towards the paper's value if length is over-weighted for your route set. * `encode_queries(q)`6 (`encode_queries(q)`7): number of documents in the trained corpus * `encode_queries(q)`8 (`encode_queries(q)`9): float representing the average document length in the trained corpus * `encode_documents([D_0, D_1, ...])`0 (`encode_documents([D_0, D_1, ...])`1numpy.ndarray`encode_documents([D_0, D_1, ...])`2): (1, tokenizer.vocab\_size) shaped array, denoting how many documents contain `encode_documents([D_0, D_1, ...])`3 #### fit [#fit] ```python def fit(routes: List[Route]) -> "BM25Encoder" ``` Trains the encoder weights on the provided routes. **Arguments**: * `routes` (`List[Route]`): List of routes to train the encoder on. #### encode\_queries [#encode_queries] ```python def encode_queries(queries: list[str]) -> list[SparseEmbedding] ``` Returns BM25 scores for queries using precomputed corpus scores. **Arguments**: * `queries` (`list`): List of queries to encode **Returns**: `list[SparseEmbedding]`: BM25 scores for each query against the corpus #### encode\_documents [#encode_documents] ```python def encode_documents(documents: list[str], batch_size: int | None = None) -> list[SparseEmbedding] ``` Returns document term frequency normed by itself & average trained corpus length (This is the right-hand side of the BM25 equation, which gets matmul-ed with the query IDF component) LaTeX: $\frac{(k_1 + 1) \times f(d_i, D)}{f(d_i, D) + k_1 \times (1 - b + b \times \frac{|D|}{avgdl})}$ where: f(d\_i, D) is frequency of term `d_i ∈ D` |D| is the document length avgdl is average document length in trained corpus **Arguments**: * `documents` (`list`): List of queries to encode **Returns**: `list[SparseEmbedding]`: Encoded queries (as either sparse or dict) #### model [#model] ```python def model(docs: List[str]) -> list[SparseEmbedding] ``` Encode documents using BM25, with different encoding for queries vs documents to be indexed. **Arguments**: * `docs`: List of documents to encode * `is_query`: If True, use query encoding, else use document encoding **Returns**: List of sparse embeddings # semantic_router.encoders.clip (/docs/semantic-router/v0/client-reference/encoders/clip) ## CLIPEncoder Objects [#clipencoder-objects] ```python class CLIPEncoder(DenseEncoder) ``` Multi-modal dense encoder for text and images using CLIP-type models via HuggingFace. **Arguments**: * `name` (`str`): The name of the model to use. * `tokenizer_kwargs` (`Dict`): Keyword arguments for the tokenizer. * `processor_kwargs` (`Dict`): Keyword arguments for the processor. * `model_kwargs` (`Dict`): Keyword arguments for the model. * `device` (`Optional[str]`): The device to use for the model. * `str`0 (`str`1): The tokenizer for the model. * `str`2 (`str`1): The processor for the model. * `str`4 (`str`1): The model. * `str`6 (`str`1): The torch library. * `str`8 (`str`1): The PIL library. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize the CLIPEncoder. **Arguments**: * `**data` (`Dict`): Keyword arguments for the encoder. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[Any], batch_size: int = 32, normalize_embeddings: bool = True) -> List[List[float]] ``` Encode a list of documents. Can handle both text and images. **Arguments**: * `docs` (`List[Any]`): The documents to encode. * `batch_size` (`int`): The batch size for the encoding. * `normalize_embeddings` (`bool`): Whether to normalize the embeddings. **Returns**: `List[List[float]]`: A list of embeddings. # semantic_router.encoders.cohere (/docs/semantic-router/v0/client-reference/encoders/cohere) #### docs2cohere\_embed\_input [#docs2cohere_embed_input] ```python def docs2cohere_embed_input(docs: list[str]) -> list[dict[str, Any]] ``` Convert a list of texts into Cohere's `inputs` format. The Cohere `embed` endpoint expects one `EmbedInput` per embedding, each holding its own `content` array, so a list of N texts becomes N inputs. **Arguments**: * `docs` (`list[str]`): The texts to embed. **Returns**: \`\`0: One embed input per text. ## CohereEncoder Objects [#cohereencoder-objects] ```python class CohereEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Dense encoder that uses Cohere API and SDK to embed documents. Supports text only. Requires a Cohere API key from [https://dashboard.cohere.com/api-keys](https://dashboard.cohere.com/api-keys). #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, cohere_api_key: str | None = None, score_threshold: float = 0.3) ``` Initialize the Cohere encoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "embed-english-v3.0" or "embed-multilingual-v3.0". * `cohere_api_key` (`str`): The API key for the Cohere client, can also be set via the COHERE\_API\_KEY environment variable. * `score_threshold` (`float`): The threshold for the score of the embedding. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Cohere. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Cohere asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.fastembed (/docs/semantic-router/v0/client-reference/encoders/fastembed) ## FastEmbedEncoder Objects [#fastembedencoder-objects] ```python class FastEmbedEncoder(DenseEncoder) ``` Dense encoder that uses local FastEmbed to embed documents. Supports text only. Requires the fastembed package which can be installed with `pip install 'semantic-router[fastembed]'` **Arguments**: * `name`: The name of the embedding model to use. * `max_length`: The maximum length of the input text. * `cache_dir`: The directory to cache the embedding model. * `threads`: The number of threads to use for the embedding. #### \_\_init\_\_ [#__init__] ```python def __init__(score_threshold: float = 0.5, **data) ``` Initialize the FastEmbed encoder. **Arguments**: * `score_threshold` (`float`): The threshold for the score of the embedding. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Embed a list of documents. Supports text only. **Arguments**: * `docs` (`List[str]`): The documents to embed. **Raises**: * `ValueError`: If the embedding fails. **Returns**: `List[List[float]]`: The vector embeddings of the documents. #### acall [#acall] ```python async def acall(docs: List[str]) -> List[List[float]] ``` Embed a list of documents asynchronously. Supports text only. FastEmbed itself is synchronous, so this offloads the embedding call to a thread to avoid blocking the event loop. **Arguments**: * `docs` (`List[str]`): The documents to embed. **Raises**: * `ValueError`: If the embedding fails. **Returns**: `List[List[float]]`: The vector embeddings of the documents. # semantic_router.encoders.google (/docs/semantic-router/v0/client-reference/encoders/google) ## GoogleEncoder Objects [#googleencoder-objects] ```python class GoogleEncoder(DenseEncoder) ``` GoogleEncoder class for generating embeddings using Google's AI Platform. The GoogleEncoder class is a subclass of DenseEncoder and utilizes the TextEmbeddingModel from the Google AI Platform to generate embeddings for given documents. It requires a Google Cloud project ID and supports customization of the pre-trained model, score threshold, location, and API endpoint. Example usage: ```python from semantic_router.encoders.google_encoder import GoogleEncoder encoder = GoogleEncoder(project_id="your-project-id") embeddings = encoder(["document1", "document2"]) ``` **Attributes**: * `client` - An instance of the TextEmbeddingModel client. * `type` - The type of the encoder, which is "google". #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, score_threshold: float = 0.75, project_id: Optional[str] = None, location: Optional[str] = None, api_endpoint: Optional[str] = None) ``` Initializes the GoogleEncoder. **Arguments**: * `model_name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `score_threshold` (`float`): The threshold for similarity scores. * `project_id` (`str`): The Google Cloud project ID. If not provided, it will be retrieved from the GOOGLE\_PROJECT\_ID environment variable. * `location` (`str`): The location of the AI Platform resources. If not provided, it will be retrieved from the GOOGLE\_LOCATION environment variable, defaulting to "us-central1". * `api_endpoint` (`str`): The API endpoint for the AI Platform. If not provided, it will be retrieved from the GOOGLE\_API\_ENDPOINT environment variable. **Raises**: * `str`0: If the Google Project ID is not provided or if the AI Platform client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`List[str]`): A list of strings representing the documents to embed. **Raises**: * `ValueError`: If the Google AI Platform client is not initialized or if the API call fails. **Returns**: `List[List[float]]`: A list of lists, where each inner list contains the embedding values for a document. # semantic_router.encoders.huggingface (/docs/semantic-router/v0/client-reference/encoders/huggingface) This module provides the HFEndpointEncoder class to embeddings models using Huggingface's endpoint. The HFEndpointEncoder class is a subclass of DenseEncoder and utilizes a specified Huggingface endpoint to generate embeddings for given documents. It requires the URL of the Huggingface API endpoint and an API key for authentication. The class supports customization of the score threshold for filtering or processing the embeddings. Example usage: ``` from semantic_router.encoders.hfendpointencoder import HFEndpointEncoder encoder = HFEndpointEncoder( huggingface_url="https://api-inference.huggingface.co/models/BAAI/bge-large-en-v1.5", huggingface_api_key="your-hugging-face-api-key" ) embeddings = encoder(["document1", "document2"]) ``` Classes: HFEndpointEncoder: A class for generating embeddings using a Huggingface endpoint. ## HuggingFaceEncoder Objects [#huggingfaceencoder-objects] ```python class HuggingFaceEncoder(DenseEncoder) ``` HuggingFace encoder class for local embedding models. Models can be trained and loaded from private repositories, or from the Huggingface Hub. The class supports customization of the score threshold for filtering or processing the embeddings. Example usage: ```python from semantic_router.encoders import HuggingFaceEncoder encoder = HuggingFaceEncoder( name="sentence-transformers/all-MiniLM-L6-v2", device="cuda" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str], batch_size: int = 32, normalize_embeddings: bool = True, pooling_strategy: str = "mean") -> List[List[float]] ``` Encode a list of documents into embeddings using the local Hugging Face model. **Arguments**: * `docs` (`List[str]`): A list of documents to encode. * `batch_size`: The batch size for encoding. ## HFEndpointEncoder Objects [#hfendpointencoder-objects] ```python class HFEndpointEncoder(DenseEncoder) ``` HFEndpointEncoder class to embeddings models using Huggingface's inference endpoints. The HFEndpointEncoder class is a subclass of DenseEncoder and utilizes a specified Huggingface endpoint to generate embeddings for given documents. It requires the URL of the Huggingface API endpoint and an API key for authentication. The class supports customization of the score threshold for filtering or processing the embeddings. Example usage: ```python from semantic_router.encoders import HFEndpointEncoder encoder = HFEndpointEncoder( huggingface_url="https://api-inference.huggingface.co/models/BAAI/bge-large-en-v1.5", huggingface_api_key="your-hugging-face-api-key" ) embeddings = encoder(["document1", "document2"]) ``` #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = "hugging_face_custom_endpoint", huggingface_url: Optional[str] = None, huggingface_api_key: Optional[str] = None, score_threshold: float = 0.8) ``` Initializes the HFEndpointEncoder with the specified parameters. **Arguments**: * `name` (`str`): The name of the encoder. * `huggingface_url` (`str`): The URL of the Hugging Face API endpoint. * `huggingface_api_key` (`str`): The API key for the Hugging Face API. * `score_threshold` (`float`): A threshold for processing the embeddings. **Raises**: * `ValueError`: If either `huggingface_url` or `huggingface_api_key` is None. #### \_\_call\_\_ [#__call__-1] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Encodes a list of documents into embeddings using the Hugging Face API. **Arguments**: * `docs` (`List[str]`): A list of documents to encode. **Raises**: * `ValueError`: If no embeddings are returned for a document. **Returns**: `List[List[float]]`: A list of embeddings for the given documents. #### query [#query] ```python def query(payload, max_retries=3, retry_interval=5) ``` Sends a query to the Hugging Face API and returns the response. **Arguments**: * `payload` (`dict`): The payload to send in the request. **Raises**: * `ValueError`: If the query fails or the response status is not 200. **Returns**: `dict`: The response from the Hugging Face API. # semantic_router.encoders.jina (/docs/semantic-router/v0/client-reference/encoders/jina) This file contains the JinaEncoder class which is used to encode text using Jina #### jina\_to\_list [#jina_to_list] ```python def jina_to_list(embeds: CreateEmbeddingResponse) -> list[list[float]] ``` Convert a Jina embedding response to a list of embeddings. **Arguments**: * `embeds` (`CreateEmbeddingResponse`): The embedding response returned by the Jina API. **Returns**: `list[list[float]]`: One embedding per input document. ## JinaEncoder Objects [#jinaencoder-objects] ```python class JinaEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Jina. Requires a Jina API key from [https://jina.ai/api-keys/](https://jina.ai/api-keys/) Jina exposes an OpenAI-compatible embeddings endpoint, so this encoder drives it with the OpenAI SDK pointed at `https://api.jina.ai/v1` rather than depending on LiteLLM. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None, score_threshold: float = 0.4, base_url: str | None = None) ``` Initialize the JinaEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "jina-embeddings-v3". * `api_key` (`str`): The Jina API key, can also be set via the JINA\_API\_KEY or JINA\_AI\_API\_KEY environment variable. * `score_threshold` (`float`): The score threshold for the embeddings. * `base_url` (`str`): Override the Jina API base URL, can also be set via the JINA\_BASE\_URL or JINA\_AI\_API\_BASE environment variable. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Jina. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Jina asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.litellm (/docs/semantic-router/v0/client-reference/encoders/litellm) #### litellm\_to\_list [#litellm_to_list] ```python def litellm_to_list(embeds: "litellm.EmbeddingResponse") -> list[list[float]] ``` Convert a LiteLLM embedding response to a list of embeddings. **Arguments**: * `embeds`: The LiteLLM embedding response. **Returns**: A list of embeddings. ## LiteLLMEncoder Objects [#litellmencoder-objects] ```python class LiteLLMEncoder(DenseEncoder, AsymmetricDenseMixin) ``` LiteLLM encoder class for generating embeddings using LiteLLM. The LiteLLMEncoder class is a subclass of DenseEncoder and utilizes the LiteLLM SDK to generate embeddings for given documents. It supports all encoders supported by LiteLLM and supports customization of the score threshold for filtering or processing the embeddings. litellm is an optional dependency: install it with `pip install "semantic-router[litellm]"`. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, score_threshold: float | None = None, api_key: str | None = None) ``` Initialize the LiteLLMEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use. Must use LiteLLM naming convention (e.g. "openai/text-embedding-3-small" or "mistral/mistral-embed"). * `score_threshold` (`float`): The score threshold for the embeddings. **Raises**: * `ImportError`: If litellm is not installed. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using LiteLLM. **Arguments**: * `docs`: List of text documents to encode. **Returns**: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of documents into embeddings using LiteLLM asynchronously. **Arguments**: * `docs`: List of documents to encode. **Returns**: List of embeddings for each document. # semantic_router.encoders.local (/docs/semantic-router/v0/client-reference/encoders/local) ## LocalEncoder Objects [#localencoder-objects] ```python class LocalEncoder(DenseEncoder) ``` Local encoder using sentence-transformers for efficient local embeddings. ## LocalSparseEncoder Objects [#localsparseencoder-objects] ```python class LocalSparseEncoder(SparseEncoder) ``` Local sparse encoder using sentence-transformers' SparseEncoder (e.g., SPLADE, CSR) for efficient local sparse embeddings. # semantic_router.encoders.mistral (/docs/semantic-router/v0/client-reference/encoders/mistral) This file contains the MistralEncoder class which is used to encode text using MistralAI #### mistral\_to\_list [#mistral_to_list] ```python def mistral_to_list(embeds: EmbeddingResponse) -> list[list[float]] ``` Convert a Mistral embedding response to a list of embeddings. **Arguments**: * `embeds` (`EmbeddingResponse`): The Mistral embedding response. **Returns**: `list[list[float]]`: One embedding per input document. ## MistralEncoder Objects [#mistralencoder-objects] ```python class MistralEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using MistralAI and SDK. Requires a MistralAI API key from [https://console.mistral.ai/api-keys/](https://console.mistral.ai/api-keys/) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, mistralai_api_key: str | None = None, score_threshold: float = 0.4) ``` Initialize the MistralEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "mistral-embed". * `mistralai_api_key` (`str`): The MistralAI API key. * `score_threshold`: The score threshold for the embeddings. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using MistralAI. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using MistralAI asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.nvidia_nim (/docs/semantic-router/v0/client-reference/encoders/nvidia_nim) This file contains the NimEncoder class which is used to encode text using Nim #### nim\_to\_list [#nim_to_list] ```python def nim_to_list(embeds: CreateEmbeddingResponse) -> list[list[float]] ``` Convert a NVIDIA NIM embedding response to a list of embeddings. **Arguments**: * `embeds` (`CreateEmbeddingResponse`): The embedding response returned by the NIM API. **Returns**: `list[list[float]]`: One embedding per input document. ## NimEncoder Objects [#nimencoder-objects] ```python class NimEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Nvidia NIM. Requires a Nim API key from [https://build.nvidia.com/](https://build.nvidia.com/) NVIDIA NIM exposes an OpenAI-compatible embeddings endpoint, so this encoder drives it with the OpenAI SDK pointed at `https://integrate.api.nvidia.com/v1` rather than depending on LiteLLM. Point `base_url` at your own host to use a self-hosted NIM. NVIDIA's `nv-embedqa` models are asymmetric: queries must be embedded with `input_type="query"` and stored documents with `input_type="passage"`, so :meth:`0 and :meth:`1 differ accordingly. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None, score_threshold: float = 0.4, base_url: str | None = None) ``` Initialize the NimEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "nvidia/nv-embedqa-e5-v5". * `api_key` (`str`): The Nim API key, can also be set via the NVIDIA\_NIM\_API\_KEY environment variable. * `score_threshold` (`float`): The score threshold for the embeddings. * `base_url` (`str`): Override the NIM API base URL, can also be set via the NVIDIA\_NIM\_API\_BASE environment variable. Use this to target a self-hosted NIM container. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using NVIDIA NIM. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using NVIDIA NIM asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.encoders.ollama (/docs/semantic-router/v0/client-reference/encoders/ollama) ## OllamaEncoder Objects [#ollamaencoder-objects] ```python class OllamaEncoder(DenseEncoder) ``` OllamaEncoder class for generating embeddings using OLLAMA. [https://ollama.com/search?c=embedding](https://ollama.com/search?c=embedding) Example usage: ```python from semantic_router.encoders.ollama import OllamaEncoder encoder = OllamaEncoder(base_url="http://localhost:11434") embeddings = encoder(["document1", "document2"]) ``` **Attributes**: * `client` - An instance of the TextEmbeddingModel client. * `type` - The type of the encoder, which is "ollama". #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, score_threshold: float = 0.5, base_url: str | None = None) ``` Initializes the OllamaEncoder. **Arguments**: * `name` (`str`): The name of the pre-trained model to use for embedding. If not provided, the default model specified in EncoderDefault will be used. * `score_threshold` (`float`): The threshold for similarity scores. * `base_url` (`str`): The API endpoint for OLLAMA. If not provided, it will be retrieved from the `OLLAMA_BASE_URL` environment variable. **Raises**: * `ValueError`: If the hosted base url is not provided properly or if the ollama client fails to initialize. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str]) -> List[List[float]] ``` Generates embeddings for the given documents. **Arguments**: * `docs` (`List[str]`): A list of strings representing the documents to embed. **Raises**: * `ValueError`: If the Google AI Platform client is not initialized or if the API call fails. **Returns**: `List[List[float]]`: A list of lists, where each inner list contains the embedding values for a document. # semantic_router.encoders.openai (/docs/semantic-router/v0/client-reference/encoders/openai) ## OpenAIEncoder Objects [#openaiencoder-objects] ```python class OpenAIEncoder(DenseEncoder) ``` OpenAI encoder class for generating embeddings using OpenAI API. The OpenAIEncoder class is a subclass of DenseEncoder and utilizes the OpenAI API to generate embeddings for given documents. It requires an OpenAI API key and supports customization of the score threshold for filtering or processing the embeddings. #### token\_limit [#token_limit] default value, should be replaced by config #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, openai_base_url: Optional[str] = None, openai_api_key: Optional[str] = None, openai_org_id: Optional[str] = None, score_threshold: Optional[float] = None, dimensions: Union[int, NotGiven] = NotGiven(), max_retries: int = 3) ``` Initialize the OpenAIEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use. * `openai_base_url` (`str`): The base URL for the OpenAI API. * `openai_api_key` (`str`): The OpenAI API key. * `openai_org_id` (`str`): The OpenAI organization ID. * `score_threshold` (`float`): The score threshold for the embeddings. * `str`0 (`str`1): The dimensions of the embeddings. * `str`2 (`str`1): The maximum number of retries for the OpenAI API call. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: List[str], truncate: bool = True) -> List[List[float]] ``` Encode a list of text documents into embeddings using OpenAI API. **Arguments**: * `docs`: List of text documents to encode. * `truncate`: Whether to truncate the documents to token limit. If False and a document exceeds the token limit, an error will be raised. **Returns**: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: List[str], truncate: bool = True) -> List[List[float]] ``` Encode a list of text documents into embeddings using OpenAI API asynchronously. **Arguments**: * `docs`: List of text documents to encode. * `truncate`: Whether to truncate the documents to token limit. If False and a document exceeds the token limit, an error will be raised. **Returns**: List of embeddings for each document. # semantic_router.encoders.tfidf (/docs/semantic-router/v0/client-reference/encoders/tfidf) ## TfidfEncoder Objects [#tfidfencoder-objects] ```python class TfidfEncoder(SparseEncoder, FittableMixin) ``` #### fit [#fit] ```python def fit(routes: List[Route]) ``` Trains the encoder weights on the provided routes. **Arguments**: * `routes` (`List[Route]`): List of routes to train the encoder on. # semantic_router.encoders.vit (/docs/semantic-router/v0/client-reference/encoders/vit) ## VitEncoder Objects [#vitencoder-objects] ```python class VitEncoder(DenseEncoder) ``` Encoder for Vision Transformer models. This class provides functionality to encode images using a Vision Transformer model via Hugging Face. It supports various image processing and model initialization options. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize the VitEncoder. **Arguments**: * `**data` (`dict`): Additional keyword arguments for the encoder. #### \_\_call\_\_ [#__call__] ```python def __call__(imgs: List[Any], batch_size: int = 32) -> List[List[float]] ``` Encode a list of images into embeddings using the Vision Transformer model. **Arguments**: * `imgs` (`List[Any]`): The images to encode. * `batch_size` (`int`): The batch size for encoding. **Returns**: `List[List[float]]`: The embeddings for the images. # semantic_router.encoders.voyage (/docs/semantic-router/v0/client-reference/encoders/voyage) This file contains the VoyageEncoder class which is used to encode text using Voyage ## VoyageEncoder Objects [#voyageencoder-objects] ```python class VoyageEncoder(DenseEncoder, AsymmetricDenseMixin) ``` Class to encode text using Voyage and VoyageAI SDK. Requires a Voyage API key from [https://voyageai.com/api-keys/](https://voyageai.com/api-keys/) #### \_\_init\_\_ [#__init__] ```python def __init__(name: str | None = None, api_key: str | None = None, score_threshold: float = 0.4) ``` Initialize the VoyageEncoder. **Arguments**: * `name` (`str`): The name of the embedding model to use such as "voyage-3-lite". * `api_key` (`str`): The Voyage API key, can also be set via the VOYAGE\_API\_KEY environment variable. * `score_threshold` (`float`): The score threshold for the embeddings. **Raises**: * `ValueError`: If no API key is provided or found in the environment. #### \_\_call\_\_ [#__call__] ```python def __call__(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Voyage. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. #### acall [#acall] ```python async def acall(docs: list[Any], **kwargs) -> list[list[float]] ``` Encode a list of text documents into embeddings using Voyage asynchronously. **Arguments**: * `docs` (`list[Any]`): List of text documents to encode. **Returns**: `list[list[float]]`: List of embeddings for each document. # semantic_router.index.base (/docs/semantic-router/v0/client-reference/index/base) ## BaseIndex Objects [#baseindex-objects] ```python class BaseIndex(BaseModel) ``` Base class for indices using Pydantic's BaseModel. This class outlines the expected interface for index classes. Actual method implementations should be provided in subclasses. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[Any], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], **kwargs) ``` Add embeddings to the index. This method should be implemented by subclasses. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to add to the index. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to add to the index. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[Optional[List[Dict[str, Any]]]] = None, metadata_list: List[Dict[str, Any]] = [], **kwargs) ``` Add vectors to the index asynchronously. This method should be implemented by subclasses. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to add to the index. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to add to the index. #### get\_utterances [#get_utterances] ```python def get_utterances(include_metadata: bool = False) -> List[Utterance] ``` Gets a list of route and utterance objects currently stored in the index, including additional metadata. **Arguments**: * `include_metadata` (`bool`): Whether to include function schemas and metadata in the returned Utterance objects. **Returns**: `List[Utterance]`: A list of Utterance objects. #### aget\_utterances [#aget_utterances] ```python async def aget_utterances(include_metadata: bool = False) -> List[Utterance] ``` Gets a list of route and utterance objects currently stored in the index, including additional metadata. **Arguments**: * `include_metadata` (`bool`): Whether to include function schemas and metadata in the returned Utterance objects. **Returns**: `List[Utterance]`: A list of Utterance objects. #### get\_routes [#get_routes] ```python def get_routes() -> List[Route] ``` Gets a list of route objects currently stored in the index. **Returns**: `List[Route]`: A list of Route objects. #### delete [#delete] ```python def delete(route_name: str) ``` Deletes route by route name. This method should be implemented by subclasses. **Arguments**: * `route_name` (`str`): Name of the route to delete. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. This method should be implemented by subclasses. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### describe [#describe] ```python def describe() -> IndexConfig ``` Returns an IndexConfig object with index details such as type, dimensions, and total vector count. This method should be implemented by subclasses. **Returns**: `IndexConfig`: An IndexConfig object. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. This method should be implemented by subclasses. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. This method should be implemented by subclasses. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query\_vector and return top\_k results. This method should be implemented by subclasses. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query\_vector and return top\_k results. This method should be implemented by subclasses. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aget\_routes [#aget_routes] ```python def aget_routes() ``` Asynchronously get a list of route and utterance objects currently stored in the index. This method should be implemented by subclasses. **Raises**: * `NotImplementedError`: If the method is not implemented by the subclass. **Returns**: `list[tuple]`: A list of tuples, each containing a route name and an associated utterance. #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the index. This method should be implemented by subclasses. **Raises**: * `NotImplementedError`: If the method is not implemented by the subclass. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes or resets the index. This method should be implemented by subclasses. **Raises**: * `NotImplementedError`: If the method is not implemented by the subclass. #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Deletes or resets the index asynchronously. This method should be implemented by subclasses. #### lock [#lock] ```python def lock(value: bool, wait: int = 0, scope: str | None = None) -> ConfigParameter ``` Lock/unlock the index for a given scope (if applicable). If index already locked/unlocked, raises ValueError. **Arguments**: * `scope` (`str | None`): The scope to lock. * `wait` (`int`): The number of seconds to wait for the index to be unlocked, if set to 0, will raise an error if index is already locked/unlocked. **Returns**: `ConfigParameter`: The config parameter that was locked. #### alock [#alock] ```python async def alock(value: bool, wait: int = 0, scope: str | None = None) -> ConfigParameter ``` Lock/unlock the index for a given scope (if applicable). If index already locked/unlocked, raises ValueError. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. Default implementation just calls the sync version. **Returns**: `int`: The total number of vectors. #### parse\_route\_info [#parse_route_info] ```python def parse_route_info(metadata: List[Dict[str, Any]]) -> List[Tuple] ``` Parses metadata from index to extract route, utterance, function schema and additional metadata. **Arguments**: * `metadata` (`List[Dict[str, Any]]`): List of metadata dictionaries. **Returns**: `List[Tuple]`: A list of tuples, each containing route, utterance, function schema and additional metadata. # semantic_router.index.hybrid_local (/docs/semantic-router/v0/client-reference/index/hybrid_local) ## HybridLocalIndex Objects [#hybridlocalindex-objects] ```python class HybridLocalIndex(LocalIndex) ``` #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Add embeddings to the index. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to add to the index. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to add to the index. * `List[List[float]]`0 (`List[List[float]]`1): List of sparse embeddings to add to the index. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], sparse_embeddings: Optional[List[SparseEmbedding]] = None, **kwargs) ``` Add embeddings to the index - note that this is not truly async as it is a local index and there is no sense to make this method async. Instead, it will call the sync `add` method. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to add to the index. * `metadata_list` (`embeddings`0): List of metadata to add to the index. * `embeddings`1 (`embeddings`2): List of sparse embeddings to add to the index. #### get\_utterances [#get_utterances] ```python def get_utterances(include_metadata: bool = False) -> List[Utterance] ``` Gets a list of route and utterance objects currently stored in the index. **Arguments**: * `include_metadata` (`bool`): Whether to include function schemas and metadata in the returned Utterance objects - HybridLocalIndex doesn't include metadata so this parameter is ignored. **Returns**: `List[Utterance]`: A list of Utterance objects. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float]`): The sparse vector to search for, must be provided. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. This method calls the sync `query` method as everything uses numpy computations which is CPU-bound and so no benefit can be gained from making this async. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float]`): The sparse vector to search for, must be provided. #### aget\_routes [#aget_routes] ```python def aget_routes() ``` Get all routes from the index. **Returns**: `List[str]`: A list of routes. #### delete [#delete] ```python def delete(route_name: str) ``` Delete all records of a specific route from the index. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes the index, effectively clearing it and setting it to None. **Returns**: `None`: None # semantic_router.index.local (/docs/semantic-router/v0/client-reference/index/local) ## LocalIndex Objects [#localindex-objects] ```python class LocalIndex(BaseIndex) ``` #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], **kwargs) ``` Add embeddings to the index. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to add to the index. * `routes` (`List[str]`): List of routes to add to the index. * `utterances` (`List[str]`): List of utterances to add to the index. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to add to the index. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to add to the index. #### get\_utterances [#get_utterances] ```python def get_utterances(include_metadata: bool = False) -> List[Utterance] ``` Gets a list of route and utterance objects currently stored in the index. **Arguments**: * `include_metadata`: Whether to include function schemas and metadata in the returned Utterance objects - LocalIndex now includes metadata if present. **Returns**: `List[Utterance]`: A list of Utterance objects. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: An IndexConfig object. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query and return top\_k results. **Arguments**: * `vector` (`np.ndarray`): The vector to search for. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The routes to filter the search by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to search for. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the query vector and a list of route names. #### aget\_routes [#aget_routes] ```python async def aget_routes() ``` Get all routes from the index. **Returns**: `List[str]`: A list of routes. #### delete [#delete] ```python def delete(route_name: str) ``` Delete all records of a specific route from the index. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### adelete [#adelete] ```python async def adelete(route_name: str) ``` Delete all records of a specific route from the index. Note that this just points to the sync delete method as async makes no difference for the local computations of the LocalIndex. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### delete\_index [#delete_index] ```python def delete_index() ``` Deletes the index, effectively clearing it and setting it to None. **Returns**: `None`: None #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Deletes the index, effectively clearing it and setting it to None. Note that this just points to the sync delete\_index method as async makes no difference for the local computations of the LocalIndex. **Returns**: `None`: None # semantic_router.index.pinecone (/docs/semantic-router/v0/client-reference/index/pinecone) #### build\_records [#build_records] ```python def build_records( embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[Optional[List[Dict[str, Any]]]] = None, metadata_list: List[Dict[str, Any]] = [], sparse_embeddings: Optional[Optional[List[SparseEmbedding]]] = None ) -> List[Dict] ``` Build records for Pinecone upsert. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to upsert. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to upsert. * `List[List[float]]`0 (`List[List[float]]`1): List of sparse embeddings to upsert. **Returns**: `List[List[float]]`2: List of records to upsert. ## PineconeRecord Objects [#pineconerecord-objects] ```python class PineconeRecord(BaseModel) ``` #### metadata [#metadata] Additional metadata dictionary #### \_\_init\_\_ [#__init__] ```python def __init__(**data) ``` Initialize PineconeRecord. **Arguments**: * `**data` (`dict`): Keyword arguments to pass to the BaseModel constructor. #### to\_dict [#to_dict] ```python def to_dict() ``` Convert PineconeRecord to a dictionary. **Returns**: `dict`: Dictionary representation of the PineconeRecord. ## PineconeIndex Objects [#pineconeindex-objects] ```python class PineconeIndex(BaseIndex) ``` #### \_\_init\_\_ [#__init__-1] ```python def __init__(api_key: Optional[str] = None, index_name: str = "index", dimensions: Optional[int] = None, metric: str = "dotproduct", cloud: str = "aws", region: str = "us-east-1", host: str = "", namespace: Optional[str] = "", base_url: Optional[str] = "https://api.pinecone.io", init_async_index: bool = False) ``` Initialize PineconeIndex. **Arguments**: * `api_key` (`Optional[str]`): Pinecone API key. * `index_name` (`str`): Name of the index. * `dimensions` (`Optional[int]`): Dimensions of the index. * `metric` (`str`): Metric of the index. * `cloud` (`str`): Cloud provider of the index. * `Optional[str]`0 (`str`): Region of the index. * `Optional[str]`2 (`str`): Host of the index. * `Optional[str]`4 (`Optional[str]`): Namespace of the index. * `Optional[str]`6 (`Optional[str]`): Base URL of the Pinecone API. * `Optional[str]`8 (`Optional[str]`9): Whether to initialize the index asynchronously. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[Optional[List[Dict[str, Any]]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = 100, sparse_embeddings: Optional[Optional[List[SparseEmbedding]]] = None, **kwargs) ``` Add vectors to Pinecone in batches. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to upsert. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to upsert. * `List[List[float]]`0 (`List[List[float]]`1): Number of vectors to upsert in a single batch. * `List[List[float]]`2 (`List[List[float]]`3): List of sparse embeddings to upsert. #### aadd [#aadd] ```python async def aadd( embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[Optional[List[Dict[str, Any]]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = 100, sparse_embeddings: Optional[Optional[List[SparseEmbedding]]] = None, **kwargs) ``` Add vectors to Pinecone in batches. **Arguments**: * `embeddings` (`List[List[float]]`): List of embeddings to upsert. * `routes` (`List[str]`): List of routes to upsert. * `utterances` (`List[str]`): List of utterances to upsert. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): List of function schemas to upsert. * `metadata_list` (`List[Dict[str, Any]]`): List of metadata to upsert. * `List[List[float]]`0 (`List[List[float]]`1): Number of vectors to upsert in a single batch. * `List[List[float]]`2 (`List[List[float]]`3): List of sparse embeddings to upsert. #### delete [#delete] ```python def delete(route_name: str) -> list[str] ``` Delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### delete\_all [#delete_all] ```python def delete_all() ``` Delete all routes from index if it exists. **Returns**: `None`: None #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: IndexConfig #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`Optional[SparseEmbedding]`): An optional sparse vector to include in the query. * `kwargs` (`Any`): Additional keyword arguments for the query, including sparse\_vector. **Raises**: * `np.ndarray`0: If the index is not populated. **Returns**: `np.ndarray`1: A tuple containing an array of scores and a list of route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `kwargs` (`Any`): Additional keyword arguments for the query, including sparse\_vector. * `sparse_vector` (`Optional[dict]`): An optional sparse vector to include in the query. **Raises**: * `np.ndarray`0: If the index is not populated. **Returns**: `np.ndarray`1: A tuple containing an array of scores and a list of route names. #### aget\_routes [#aget_routes] ```python async def aget_routes() -> list[tuple] ``` Asynchronously get a list of route and utterance objects currently stored in the index. **Returns**: `List[Tuple]`: A list of (route\_name, utterance) objects. #### delete\_index [#delete_index] ```python def delete_index() ``` Delete the index. **Returns**: `None`: None #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Asynchronously delete the index. #### ais\_ready [#ais_ready] ```python async def ais_ready(client_only: bool = False) -> bool ``` Checks if class attributes exist to be used for async operations. **Arguments**: * `client_only` (`bool, optional`): Whether to check only the client attributes. If False attributes will be checked for both client and index operations. If True only attributes for client operations will be checked. Defaults to False. **Returns**: `bool`: True if the class attributes exist, False otherwise. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. If the index is not initialized, initializes it first or returns 0. **Returns**: `int`: The total number of vectors. # semantic_router.index.postgres (/docs/semantic-router/v0/client-reference/index/postgres) ## MetricPgVecOperatorMap Objects [#metricpgvecoperatormap-objects] ```python class MetricPgVecOperatorMap(Enum) ``` Enum to map the metric to PostgreSQL vector operators. #### dotproduct [#dotproduct] inner product #### euclidean [#euclidean] L2 distance #### manhattan [#manhattan] L1 distance #### parse\_vector [#parse_vector] ```python def parse_vector(vector_str: Union[str, Any]) -> List[float] ``` Parses a vector from a string or other representation. **Arguments**: * `vector_str` (`Union[str, Any]`): The string or object representation of a vector. **Returns**: `List[float]`: A list of floats representing the vector. #### clean\_route\_name [#clean_route_name] ```python def clean_route_name(route_name: str) -> str ``` Cleans and formats the route name by stripping spaces and replacing them with hyphens. **Arguments**: * `route_name` (`str`): The original route name. **Returns**: `str`: The cleaned and formatted route name. ## PostgresIndexRecord Objects [#postgresindexrecord-objects] ```python class PostgresIndexRecord(BaseModel) ``` Model to represent a record in the Postgres index. #### \_\_init\_\_ [#__init__] ```python def __init__(**data) -> None ``` Initializes a new Postgres index record with given data. **Arguments**: * `data` (`dict`): Field values for the record. #### to\_dict [#to_dict] ```python def to_dict() -> Dict ``` Converts the record to a dictionary. **Returns**: `Dict`: A dictionary representation of the record. ## PostgresIndex Objects [#postgresindex-objects] ```python class PostgresIndex(BaseIndex) ``` Postgres implementation of Index. #### \_\_init\_\_ [#__init__-1] ```python def __init__(connection_string: Optional[str] = None, index_prefix: str = "semantic_router_", index_name: str = "index", metric: Metric = Metric.COSINE, namespace: Optional[str] = "", dimensions: int | None = None, init_async_index: bool = False) ``` Initializes the Postgres index with the specified parameters. **Arguments**: * `connection_string` (`Optional[str]`): The connection string for the PostgreSQL database. * `index_prefix` (`str`): The prefix for the index table name. * `index_name` (`str`): The name of the index table. * `dimensions` (`int`): The number of dimensions for the vectors. * `metric` (`Metric`): The metric used for vector comparisons. * `Optional[str]`0 (`Optional[str]`): An optional namespace for the index. * `Optional[str]`2 (`Optional[str]`3): Whether to initialize the index asynchronously. #### setup\_index [#setup_index] ```python @deprecated( "Use _init_index or sync methods such as `auto_sync` (read more " "https://docs.aurelio.ai/semantic-router/user-guide/features/sync). " "This method will be removed in 0.2.0") def setup_index() -> None ``` Sets up the index by creating the table and vector extension if they do not exist. **Raises**: * `ValueError`: If the existing table's vector dimensions do not match the expected dimensions. * `TypeError`: If the database connection is not established. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], **kwargs) -> None ``` Adds records to the index. **Arguments**: * `embeddings` (`List[List[float]]`): A list of vector embeddings to add. * `routes` (`List[str]`): A list of route names corresponding to the embeddings. * `utterances` (`List[Any]`): A list of utterances corresponding to the embeddings. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): A list of function schemas corresponding to the embeddings. * `metadata_list` (`List[Dict[str, Any]]`): A list of metadata corresponding to the embeddings. **Raises**: * `List[List[float]]`0: If the vector embeddings being added do not match the expected dimensions. * `List[List[float]]`1: If the database connection is not established. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = 100, **kwargs) -> None ``` Asynchronously adds records to the index in batches. **Arguments**: * `embeddings`: A list of vector embeddings to add. * `routes`: A list of route names corresponding to the embeddings. * `utterances`: A list of utterances corresponding to the embeddings. * `function_schemas`: (Optional) List of function schemas. * `metadata_list`: (Optional) List of metadata dictionaries. * `batch_size`: Number of records per batch insert. **Raises**: * `ValueError`: If the vector embeddings don't match expected dimensions. * `TypeError`: If connection is not an async Postgres connection. #### delete [#delete] ```python def delete(route_name: str) -> None ``` Deletes records with the specified route name. **Arguments**: * `route_name` (`str`): The name of the route to delete records for. **Raises**: * `TypeError`: If the database connection is not established. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete specified route from index if it exists. Returns the IDs of the vectors deleted. **Arguments**: * `route_name` (`str`): Name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describes the index by returning its type, dimensions, and total vector count. **Returns**: `IndexConfig`: An IndexConfig object containing the index's type, dimensions, and total vector count. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Searches the index for the query vector and returns the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector. * `top_k` (`int`): The number of top results to return. * `route_filter` (`Optional[List[str]]`): Optional list of routes to filter the results by. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): Optional sparse vector to filter the results by. **Raises**: * `TypeError`: If the database connection is not established. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing the scores and routes of the top\_k results. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously search the index for the query vector and return the top\_k results. **Arguments**: * `vector` (`np.ndarray`): The query vector to search for. * `top_k` (`int, optional`): The number of top results to return, defaults to 5. * `route_filter` (`Optional[List[str]], optional`): A list of route names to filter the search results, defaults to None. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): An optional sparse vector to include in the query. **Raises**: * `TypeError`: If the database connection is not established. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple containing an array of scores and a list of route names. #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the Postgres index. **Raises**: * `TypeError`: If the database connection is not established. #### delete\_index [#delete_index] ```python def delete_index() -> None ``` Deletes the entire table for the index. **Raises**: * `TypeError`: If the database connection is not established. #### adelete\_index [#adelete_index] ```python async def adelete_index() -> None ``` Asynchronously delete the entire table for the index. **Raises**: * `TypeError`: If the async database connection is not established. #### aget\_routes [#aget_routes] ```python async def aget_routes() -> list[tuple] ``` Asynchronously get a list of route and utterance objects currently stored in the index. **Raises**: * `TypeError`: If the database connection is not established. **Returns**: `List[Tuple]`: A list of (route\_name, utterance) objects. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. **Returns**: `int`: The total number of vectors. #### close [#close] ```python def close() ``` Closes the psycopg connection if it exists. #### has\_connection [#has_connection] ```python def has_connection() -> bool ``` Returns True if there is an active and valid psycopg connection, otherwise False. # semantic_router.index.qdrant (/docs/semantic-router/v0/client-reference/index/qdrant) ## QdrantIndex Objects [#qdrantindex-objects] ```python class QdrantIndex(BaseIndex) ``` The name of the collection to use #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Add records to the index. **Arguments**: * `embeddings` (`List[List[float]]`): The embeddings to add. * `routes` (`List[str]`): The routes to add. * `utterances` (`List[str]`): The utterances to add. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas to add. * `metadata_list` (`List[Dict[str, Any]]`): The metadata to add. * `List[List[float]]`0 (`List[List[float]]`1): The batch size to use for the upload. #### get\_utterances [#get_utterances] ```python def get_utterances(include_metadata: bool = False) -> List[Utterance] ``` Gets a list of route and utterance objects currently stored in the index. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the returned Utterance objects. **Returns**: `List[Utterance]`: A list of Utterance objects. #### delete [#delete] ```python def delete(route_name: str) ``` Delete records from the index. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: The index configuration. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to query. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to query. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### get\_routes\_tuples [#get_routes_tuples] ```python def get_routes_tuples() -> list[tuple] ``` Synchronously get route and utterance objects as tuples. **Returns**: `list[tuple]`: A list of (route\_name, utterance, function\_schemas, metadata) tuples. #### aget\_routes [#aget_routes] ```python async def aget_routes() -> list[tuple] ``` Asynchronously get a list of route and utterance objects currently stored in the index. **Returns**: `list[tuple]`: A list of (route\_name, utterance, function\_schemas, metadata) tuples. #### delete\_index [#delete_index] ```python def delete_index() ``` Delete the index. **Returns**: `None`: None #### convert\_metric [#convert_metric] ```python def convert_metric(metric: Metric) ``` Convert the metric to a Qdrant distance metric. **Arguments**: * `metric` (`Metric`): The metric to convert. **Returns**: `Distance`: The converted metric. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete records from the index by route name. **Arguments**: * `route_name` (`str`): The name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted (empty list, as Qdrant does not return IDs). #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Asynchronously delete the index (collection) from Qdrant. **Returns**: `None`: None #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Asynchronously add records to the index, including metadata in the payload. #### aget\_utterances [#aget_utterances] ```python async def aget_utterances(include_metadata: bool = False) -> List[Utterance] ``` Asynchronously gets a list of route and utterance objects currently stored in the index. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the returned Utterance objects. **Returns**: `List[Utterance]`: A list of Utterance objects. # semantic_router.index.redis (/docs/semantic-router/v0/client-reference/index/redis) ## RedisIndex Objects [#redisindex-objects] ```python class RedisIndex(BaseIndex) ``` Redis implementation of Index, backed by RediSearch vector search. Requires a Redis server with the RediSearch module (e.g. Redis Stack, or Redis 8+, which bundles it by default). Plain open-source Redis without the module cannot be used, since it has no vector index type. #### add [#add] ```python def add(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Add records to the index. **Arguments**: * `embeddings` (`List[List[float]]`): The embeddings to add. * `routes` (`List[str]`): The routes to add. * `utterances` (`List[str]`): The utterances to add. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas to add. * `metadata_list` (`List[Dict[str, Any]]`): The metadata to add. * `List[List[float]]`0 (`List[List[float]]`1): The batch size to use for the upload. #### aadd [#aadd] ```python async def aadd(embeddings: List[List[float]], routes: List[str], utterances: List[str], function_schemas: Optional[List[Dict[str, Any]]] = None, metadata_list: List[Dict[str, Any]] = [], batch_size: int = DEFAULT_UPLOAD_BATCH_SIZE, **kwargs) ``` Asynchronously add records to the index. **Arguments**: * `embeddings` (`List[List[float]]`): The embeddings to add. * `routes` (`List[str]`): The routes to add. * `utterances` (`List[str]`): The utterances to add. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas to add. * `metadata_list` (`List[Dict[str, Any]]`): The metadata to add. * `List[List[float]]`0 (`List[List[float]]`1): The batch size to use for the upload. #### query [#query] ```python def query( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): Unused; RedisIndex does not support hybrid search. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### aquery [#aquery] ```python async def aquery( vector: np.ndarray, top_k: int = 5, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> Tuple[np.ndarray, List[str]] ``` Asynchronously query the index. **Arguments**: * `vector` (`np.ndarray`): The vector to query. * `top_k` (`int`): The number of results to return. * `route_filter` (`Optional[List[str]]`): The route filter to apply. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): Unused; RedisIndex does not support hybrid search. **Returns**: `Tuple[np.ndarray, List[str]]`: A tuple of the scores and route names. #### aget\_routes [#aget_routes] ```python async def aget_routes() -> list[tuple] ``` Asynchronously get a list of route and utterance objects currently stored in the index. **Returns**: `list[tuple]`: A list of (route\_name, utterance, function\_schemas, metadata) tuples. #### delete [#delete] ```python def delete(route_name: str) ``` Delete records from the index by route name. **Arguments**: * `route_name` (`str`): The name of the route to delete. #### adelete [#adelete] ```python async def adelete(route_name: str) -> list[str] ``` Asynchronously delete records from the index by route name. **Arguments**: * `route_name` (`str`): The name of the route to delete. **Returns**: `list[str]`: List of IDs of the vectors deleted. #### delete\_all [#delete_all] ```python def delete_all() ``` Deletes all records from the index (but keeps the index/schema). #### delete\_index [#delete_index] ```python def delete_index() ``` Delete the RediSearch index, all of its documents and its config (every namespace's sync hash and lock). #### adelete\_index [#adelete_index] ```python async def adelete_index() ``` Asynchronously delete the RediSearch index, all of its documents and its config (every namespace's sync hash and lock). #### describe [#describe] ```python def describe() -> IndexConfig ``` Describe the index. **Returns**: `IndexConfig`: The index configuration. #### is\_ready [#is_ready] ```python def is_ready() -> bool ``` Checks if the index is ready to be used. **Returns**: `bool`: True if the index is ready, False otherwise. #### ais\_ready [#ais_ready] ```python async def ais_ready() -> bool ``` Checks if the index is ready to be used asynchronously. **Returns**: `bool`: True if the index is ready, False otherwise. #### \_\_len\_\_ [#__len__] ```python def __len__() ``` Returns the total number of vectors in the index. If the index is not initialized returns 0. **Returns**: `int`: The total number of vectors. #### alen [#alen] ```python async def alen() ``` Async version of **len**. Returns the total number of vectors in the index. **Returns**: `int`: The total number of vectors. #### close [#close] ```python def close() ``` Closes the Redis client connections if they exist. # semantic_router.llms.atlascloud (/docs/semantic-router/v0/client-reference/llms/atlascloud) ## AtlasCloudLLM Objects [#atlascloudllm-objects] ```python class AtlasCloudLLM(OpenAICompatibleLLM) ``` LLM for Atlas Cloud, a preset of OpenAICompatibleLLM pointing at the Atlas Cloud gateway ([https://api.atlascloud.ai/v1](https://api.atlascloud.ai/v1)) and reading the API key from ATLASCLOUD\_API\_KEY. See [https://docs.atlascloud.ai/](https://docs.atlascloud.ai/) for more information. Limits inherited from semantic-router 0.x: * Dynamic routes extract function inputs only when called synchronously; an async call returns the route with function\_call=None. * A router config file saves only the class and model name. Reloading one uses the default base\_url and ATLASCLOUD\_API\_KEY, so a custom base\_url or a key passed in code is lost. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, atlascloud_api_key: Optional[str] = None, base_url: str = "https://api.atlascloud.ai/v1", temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the AtlasCloudLLM. **Arguments**: * `name` (`Optional[str]`): The name of the Atlas Cloud model to use. Defaults to the ATLASCLOUD\_CHAT\_MODEL\_NAME environment variable or deepseek-ai/deepseek-v4-flash. * `atlascloud_api_key` (`Optional[str]`): The Atlas Cloud API key. Defaults to the ATLASCLOUD\_API\_KEY environment variable. * `base_url` (`str`): The base URL for the Atlas Cloud API. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. # semantic_router.llms.base (/docs/semantic-router/v0/client-reference/llms/base) ## BaseLLM Objects [#basellm-objects] ```python class BaseLLM(BaseModel) ``` Base class for LLMs typically used by dynamic routes. This class provides a base implementation for LLMs. It defines the common configuration and methods for all LLM classes. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str, **kwargs) ``` Initialize the BaseLLM. **Arguments**: * `name` (`str`): The name of the LLM. * `**kwargs` (`dict`): Additional keyword arguments for the LLM. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> Optional[str] ``` Call the LLM. Must be implemented by subclasses. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the LLM. **Returns**: `Optional[str]`: The response from the LLM. #### extract\_function\_inputs [#extract_function_inputs] ```python def extract_function_inputs( query: str, function_schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]] ``` Extract the function inputs from the query. **Arguments**: * `query` (`str`): The query to extract the function inputs from. * `function_schemas` (`List[Dict[str, Any]]`): The function schemas to extract the function inputs from. **Returns**: `List[Dict[str, Any]]`: The function inputs. # semantic_router.llms.cohere (/docs/semantic-router/v0/client-reference/llms/cohere) ## CohereLLM Objects [#coherellm-objects] ```python class CohereLLM(BaseLLM) ``` LLM for Cohere. Requires a Cohere API key from [https://dashboard.cohere.com/api-keys](https://dashboard.cohere.com/api-keys). This class provides functionality to interact with the Cohere API for generating text responses. It extends the BaseLLM class and implements the **call** method to generate text responses. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, cohere_api_key: Optional[str] = None) ``` Initialize the CohereLLM. **Arguments**: * `name` (`Optional[str]`): The name of the Cohere model to use can also be set via the COHERE\_CHAT\_MODEL\_NAME environment variable. * `cohere_api_key` (`Optional[str]`): The API key for the Cohere client. Can also be set via the COHERE\_API\_KEY environment variable. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the Cohere client. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the Cohere client. **Returns**: `str`: The response from the Cohere client. # semantic_router.llms.llamacpp (/docs/semantic-router/v0/client-reference/llms/llamacpp) ## LlamaCppLLM Objects [#llamacppllm-objects] ```python class LlamaCppLLM(BaseLLM) ``` LLM for LlamaCPP. Enables fully local LLM use, helpful for local implementation of dynamic routes. #### \_\_init\_\_ [#__init__] ```python def __init__(llm: Any, name: str = "llama.cpp", temperature: float = 0.2, max_tokens: Optional[int] = 200, grammar: Optional[Any] = None) ``` Initialize the LlamaCPPLLM. **Arguments**: * `llm` (`Any`): The LLM to use. * `name` (`str`): The name of the LLM. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`Optional[int]`): The maximum number of tokens to generate. * `grammar` (`Optional[Any]`): The grammar to use. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the LlamaCPPLLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the LlamaCPPLLM. **Returns**: `str`: The response from the LlamaCPPLLM. #### extract\_function\_inputs [#extract_function_inputs] ```python def extract_function_inputs( query: str, function_schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]] ``` Extract the function inputs from the query. **Arguments**: * `query` (`str`): The query to extract the function inputs from. * `function_schemas` (`List[Dict[str, Any]]`): The function schemas to extract the function inputs from. **Returns**: `List[Dict[str, Any]]`: The function inputs. # semantic_router.llms.minimax (/docs/semantic-router/v0/client-reference/llms/minimax) ## MiniMaxLLM Objects [#minimaxllm-objects] ```python class MiniMaxLLM(OpenAICompatibleLLM) ``` LLM for MiniMax, a preset of OpenAICompatibleLLM pointing at MiniMax's OpenAI-compatible API ([https://api.minimax.io/v1](https://api.minimax.io/v1)) and reading the API key from MINIMAX\_API\_KEY. Create a key at [https://platform.minimax.io](https://platform.minimax.io). MiniMax's models think before they answer. MiniMax-M3 puts its thinking in \ tags inside the reply, which are stripped from the output, and MiniMax-M3.1-Flash returns it in a separate field, which is ignored. Thinking counts towards max\_tokens, so the default leaves room for it. Current MiniMax models ignore temperature. It is still clamped to (0.0, 1.0], the range older MiniMax models required. Limits inherited from semantic-router 0.x: * Dynamic routes extract function inputs only when called synchronously; an async call returns the route with function\_call=None. MiniMaxLLM.acall itself works, but routes don't use it for extraction. * A router config file saves only the class and model name. Reloading one uses the default base\_url and MINIMAX\_API\_KEY, so a custom base\_url or a key passed in code is lost. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, minimax_api_key: Optional[str] = None, base_url: str = "https://api.minimax.io/v1", temperature: float = 0.01, max_tokens: int = 4096) ``` Initialize the MiniMaxLLM. **Arguments**: * `name` (`Optional[str]`): The name of the MiniMax model to use. Defaults to the MINIMAX\_CHAT\_MODEL\_NAME environment variable or MiniMax-M3.1-Flash. * `minimax_api_key` (`Optional[str]`): The MiniMax API key. Defaults to the MINIMAX\_API\_KEY environment variable. * `base_url` (`str`): The base URL for the MiniMax API. * `temperature` (`float`): The temperature of the LLM, clamped to (0.0, 1.0]. * `max_tokens` (`int`): The maximum number of tokens to generate, thinking included. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the MiniMaxLLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the MiniMaxLLM. **Returns**: `str`: The response from the MiniMaxLLM, without its thinking. #### acall [#acall] ```python async def acall(messages: List[Message]) -> str ``` Call the MiniMaxLLM asynchronously. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the MiniMaxLLM. **Returns**: `str`: The response from the MiniMaxLLM, without its thinking. # semantic_router.llms.mistral (/docs/semantic-router/v0/client-reference/llms/mistral) ## MistralAILLM Objects [#mistralaillm-objects] ```python class MistralAILLM(BaseLLM) ``` LLM for MistralAI. Requires a MistralAI API key from [https://console.mistral.ai/api-keys/](https://console.mistral.ai/api-keys/) #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, mistralai_api_key: Optional[str] = None, temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the MistralAILLM. **Arguments**: * `name` (`Optional[str]`): The name of the MistralAI model to use. * `mistralai_api_key` (`Optional[str]`): The MistralAI API key. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the MistralAILLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the MistralAILLM. **Returns**: `str`: The response from the MistralAILLM. # semantic_router.llms.ollama (/docs/semantic-router/v0/client-reference/llms/ollama) ## OllamaLLM Objects [#ollamallm-objects] ```python class OllamaLLM(BaseLLM) ``` LLM for Ollama. Enables fully local LLM use, helpful for local implementation of dynamic routes. #### \_\_init\_\_ [#__init__] ```python def __init__(name: str = "openhermes", temperature: float = 0.2, max_tokens: Optional[int] = 200, stream: bool = False) ``` Initialize the OllamaLLM. **Arguments**: * `name` (`str`): The name of the Ollama model to use. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`Optional[int]`): The maximum number of tokens to generate. * `stream` (`bool`): Whether to stream the response. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message], temperature: Optional[float] = None, name: Optional[str] = None, max_tokens: Optional[int] = None, stream: Optional[bool] = None) -> str ``` Call the OllamaLLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the OllamaLLM. * `temperature` (`Optional[float]`): The temperature of the LLM. * `name` (`Optional[str]`): The name of the Ollama model to use. * `max_tokens` (`Optional[int]`): The maximum number of tokens to generate. * `stream` (`Optional[bool]`): Whether to stream the response. # semantic_router.llms.openai (/docs/semantic-router/v0/client-reference/llms/openai) ## OpenAILLM Objects [#openaillm-objects] ```python class OpenAILLM(BaseLLM) ``` LLM for OpenAI. Requires an OpenAI API key from [https://platform.openai.com/api-keys](https://platform.openai.com/api-keys). #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, openai_api_key: Optional[str] = None, temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the OpenAILLM. **Arguments**: * `name` (`Optional[str]`): The name of the OpenAI model to use. * `openai_api_key` (`Optional[str]`): The OpenAI API key. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. #### async\_extract\_tool\_calls\_info [#async_extract_tool_calls_info] ```python async def async_extract_tool_calls_info( tool_calls: List[ChatCompletionMessageToolCall] ) -> List[Dict[str, Any]] ``` Extract the tool calls information from the tool calls. **Arguments**: * `tool_calls` (`List[ChatCompletionMessageToolCall]`): The tool calls to extract the information from. **Returns**: `List[Dict[str, Any]]`: The tool calls information. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message], function_schemas: Optional[List[Dict[str, Any]]] = None) -> str ``` Call the OpenAILLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the OpenAILLM. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas to pass to the OpenAILLM. **Returns**: `str`: The response from the OpenAILLM. #### acall [#acall] ```python async def acall( messages: List[Message], function_schemas: Optional[List[Dict[str, Any]]] = None) -> str ``` Call the OpenAILLM asynchronously. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the OpenAILLM. * `function_schemas` (`Optional[List[Dict[str, Any]]]`): The function schemas to pass to the OpenAILLM. **Returns**: `str`: The response from the OpenAILLM. #### extract\_function\_inputs [#extract_function_inputs] ```python def extract_function_inputs( query: str, function_schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]] ``` Extract the function inputs from the query. **Arguments**: * `query` (`str`): The query to extract the function inputs from. * `function_schemas` (`List[Dict[str, Any]]`): The function schemas to extract the function inputs from. **Returns**: `List[Dict[str, Any]]`: The function inputs. #### async\_extract\_function\_inputs [#async_extract_function_inputs] ```python async def async_extract_function_inputs( query: str, function_schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]] ``` Extract the function inputs from the query asynchronously. **Arguments**: * `query` (`str`): The query to extract the function inputs from. * `function_schemas` (`List[Dict[str, Any]]`): The function schemas to extract the function inputs from. **Returns**: `List[Dict[str, Any]]`: The function inputs. #### get\_schemas\_openai [#get_schemas_openai] ```python def get_schemas_openai(items: List[Callable]) -> List[Dict[str, Any]] ``` Get function schemas for the OpenAI LLM from a list of functions. **Arguments**: * `items` (`List[Callable]`): The functions to get function schemas for. **Returns**: `List[Dict[str, Any]]`: The schemas for the OpenAI LLM. # semantic_router.llms.openai_compatible (/docs/semantic-router/v0/client-reference/llms/openai_compatible) ## OpenAICompatibleLLM Objects [#openaicompatiblellm-objects] ```python class OpenAICompatibleLLM(BaseLLM) ``` LLM for any OpenAI compatible chat completions endpoint, such as LLM routers and proxies. Configure the base URL and the name of the environment variable that holds the API key, for example OpenAICompatibleLLM(name="provider/model", base\_url="[https://api.example.com/v1](https://api.example.com/v1)", api\_key\_var\_name="EXAMPLE\_API\_KEY"). Limits inherited from semantic-router 0.x: * Dynamic routes extract function inputs only when called synchronously. BaseLLM has no async extraction, so an async call returns the route with function\_call=None and logs an error. * A router config file saves only the LLM's class and model name, so a router using OpenAICompatibleLLM can't be reloaded from one: reloading raises, because there is no base\_url. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, base_url: Optional[str] = None, api_key: Optional[str] = None, api_key_var_name: Optional[str] = None, temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the OpenAICompatibleLLM. **Arguments**: * `name` (`Optional[str]`): The name of the model to use. * `base_url` (`Optional[str]`): The base URL of the OpenAI compatible API. * `api_key` (`Optional[str]`): The API key. Takes precedence over api\_key\_var\_name. * `api_key_var_name` (`Optional[str]`): The name of the environment variable holding the API key, used when api\_key is not provided. * `temperature` (`float`): The temperature of the LLM. * `Optional[str]`0 (`Optional[str]`1): The maximum number of tokens to generate. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the OpenAICompatibleLLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the OpenAICompatibleLLM. **Returns**: `str`: The response from the OpenAICompatibleLLM. # semantic_router.llms.openrouter (/docs/semantic-router/v0/client-reference/llms/openrouter) ## OpenRouterLLM Objects [#openrouterllm-objects] ```python class OpenRouterLLM(BaseLLM) ``` LLM for OpenRouter. Requires an OpenRouter API key, see here for more information [https://openrouter.ai/docs/api-reference/authentication#using-an-api-key](https://openrouter.ai/docs/api-reference/authentication#using-an-api-key) #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, openrouter_api_key: Optional[str] = None, base_url: str = "https://openrouter.ai/api/v1", temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the OpenRouterLLM. **Arguments**: * `name` (`Optional[str]`): The name of the OpenRouter model to use. * `openrouter_api_key` (`Optional[str]`): The OpenRouter API key. * `base_url` (`str`): The base URL for the OpenRouter API. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the OpenRouterLLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the OpenRouterLLM. **Returns**: `str`: The response from the OpenRouterLLM. # semantic_router.llms.orcarouter (/docs/semantic-router/v0/client-reference/llms/orcarouter) ## OrcaRouterLLM Objects [#orcarouterllm-objects] ```python class OrcaRouterLLM(OpenAICompatibleLLM) ``` LLM for OrcaRouter, a preset of OpenAICompatibleLLM pointing at the OrcaRouter gateway ([https://api.orcarouter.ai/v1](https://api.orcarouter.ai/v1)) and reading the API key from ORCAROUTER\_API\_KEY. See [https://www.orcarouter.ai](https://www.orcarouter.ai) for more information. Limits inherited from semantic-router 0.x: * Dynamic routes extract function inputs only when called synchronously; an async call returns the route with function\_call=None. * A router config file saves only the class and model name. Reloading one uses the default base\_url and ORCAROUTER\_API\_KEY, so a custom base\_url or a key passed in code is lost. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, orcarouter_api_key: Optional[str] = None, base_url: str = "https://api.orcarouter.ai/v1", temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the OrcaRouterLLM. **Arguments**: * `name` (`Optional[str]`): The name of the OrcaRouter model to use. Defaults to the ORCAROUTER\_CHAT\_MODEL\_NAME environment variable or orcarouter/auto. * `orcarouter_api_key` (`Optional[str]`): The OrcaRouter API key. Defaults to the ORCAROUTER\_API\_KEY environment variable. * `base_url` (`str`): The base URL for the OrcaRouter API. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. # semantic_router.llms.requesty (/docs/semantic-router/v0/client-reference/llms/requesty) ## RequestyLLM Objects [#requestyllm-objects] ```python class RequestyLLM(OpenAICompatibleLLM) ``` LLM for Requesty, a preset of OpenAICompatibleLLM pointing at the Requesty router ([https://router.requesty.ai/v1](https://router.requesty.ai/v1)) and reading the API key from REQUESTY\_API\_KEY. See [https://docs.requesty.ai](https://docs.requesty.ai) for more information and [https://app.requesty.ai/api-keys](https://app.requesty.ai/api-keys) to create a key. Limits inherited from semantic-router 0.x: * Dynamic routes extract function inputs only when called synchronously; an async call returns the route with function\_call=None. * A router config file saves only the class and model name. Reloading one uses the default base\_url and REQUESTY\_API\_KEY, so a custom base\_url or a key passed in code is lost. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, requesty_api_key: Optional[str] = None, base_url: str = "https://router.requesty.ai/v1", temperature: float = 0.01, max_tokens: int = 200) ``` Initialize the RequestyLLM. **Arguments**: * `name` (`Optional[str]`): The name of the Requesty model to use. Defaults to the REQUESTY\_CHAT\_MODEL\_NAME environment variable or openai/gpt-4o-mini. * `requesty_api_key` (`Optional[str]`): The Requesty API key. Defaults to the REQUESTY\_API\_KEY environment variable. * `base_url` (`str`): The base URL for the Requesty API. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. # semantic_router.llms.zure (/docs/semantic-router/v0/client-reference/llms/zure) ## AzureOpenAILLM Objects [#azureopenaillm-objects] ```python class AzureOpenAILLM(BaseLLM) ``` LLM for Azure OpenAI. Requires an Azure OpenAI API key. #### \_\_init\_\_ [#__init__] ```python def __init__(name: Optional[str] = None, openai_api_key: Optional[str] = None, azure_endpoint: Optional[str] = None, temperature: float = 0.01, max_tokens: int = 200, api_version="2023-07-01-preview") ``` Initialize the AzureOpenAILLM. **Arguments**: * `name` (`Optional[str]`): The name of the Azure OpenAI model to use. * `openai_api_key` (`Optional[str]`): The Azure OpenAI API key. * `azure_endpoint` (`Optional[str]`): The Azure OpenAI endpoint. * `temperature` (`float`): The temperature of the LLM. * `max_tokens` (`int`): The maximum number of tokens to generate. * `Optional[str]`0 (`Optional[str]`1): The API version to use. #### \_\_call\_\_ [#__call__] ```python def __call__(messages: List[Message]) -> str ``` Call the AzureOpenAILLM. **Arguments**: * `messages` (`List[Message]`): The messages to pass to the AzureOpenAILLM. **Returns**: `str`: The response from the AzureOpenAILLM. # semantic_router.routers.base (/docs/semantic-router/v0/client-reference/routers/base) #### is\_valid [#is_valid] ```python def is_valid(layer_config: str) -> bool ``` Make sure the given string is json format and contains the 3 keys: \["encoder\_name", "encoder\_type", "routes"] ## RouterConfig Objects [#routerconfig-objects] ```python class RouterConfig() ``` Generates a RouterConfig object that can be used for initializing routers. #### \_\_init\_\_ [#__init__] ```python def __init__(routes: List[Route] = [], encoder_type: str = "openai", encoder_name: Optional[str] = None) ``` Initialize a RouterConfig object. **Arguments**: * `routes` (`List[Route]`): A list of routes. * `encoder_type` (`str`): The type of encoder to use. * `encoder_name` (`Optional[str]`): The name of the encoder to use. #### from\_file [#from_file] ```python @classmethod def from_file(cls, path: str) -> "RouterConfig" ``` Initialize a RouterConfig from a file. Expects a JSON or YAML file with file extension .json, .yaml, or .yml. **Arguments**: * `path` (`str`): The path to the file to load the RouterConfig from. #### from\_tuples [#from_tuples] ```python @classmethod def from_tuples(cls, route_tuples: List[Tuple[str, str, Optional[List[Dict[str, Any]]], Dict[str, Any]]], encoder_type: str = "openai", encoder_name: Optional[str] = None) ``` Initialize a RouterConfig from a list of tuples of routes and utterances. **Arguments**: * `route_tuples` (`List[Tuple[str, str]]`): A list of tuples, each containing a route name and an associated utterance. * `encoder_type` (`str, optional`): The type of encoder to use, defaults to "openai". * `encoder_name` (`Optional[str], optional`): The name of the encoder to use, defaults to None. #### from\_index [#from_index] ```python @classmethod def from_index(cls, index: BaseIndex, encoder_type: str = "openai", encoder_name: Optional[str] = None) ``` Initialize a RouterConfig from a BaseIndex object. **Arguments**: * `index` (`BaseIndex`): The index to initialize the RouterConfig from. * `encoder_type` (`str, optional`): The type of encoder to use, defaults to "openai". * `encoder_name` (`Optional[str], optional`): The name of the encoder to use, defaults to None. #### to\_dict [#to_dict] ```python def to_dict() -> Dict[str, Any] ``` Convert the RouterConfig to a dictionary. **Returns**: `Dict[str, Any]`: A dictionary representation of the RouterConfig. #### to\_file [#to_file] ```python def to_file(path: str) ``` Save the routes to a file in JSON or YAML format. **Arguments**: * `path` (`str`): The path to save the RouterConfig to. #### to\_utterances [#to_utterances] ```python def to_utterances() -> List[Utterance] ``` Convert the routes to a list of Utterance objects. **Returns**: `List[Utterance]`: A list of Utterance objects. #### add [#add] ```python def add(route: Route) ``` Add a route to the RouterConfig. **Arguments**: * `route` (`Route`): The route to add. #### get [#get] ```python def get(name: str) -> Optional[Route] ``` Get a route from the RouterConfig by name. **Arguments**: * `name` (`str`): The name of the route to get. **Returns**: `Optional[Route]`: The route if found, otherwise None. #### remove [#remove] ```python def remove(name: str) ``` Remove a route from the RouterConfig by name. **Arguments**: * `name` (`str`): The name of the route to remove. #### get\_hash [#get_hash] ```python def get_hash() -> ConfigParameter ``` Get the hash of the RouterConfig. Used for syncing. **Returns**: `ConfigParameter`: The hash of the RouterConfig. #### xq\_reshape [#xq_reshape] ```python def xq_reshape(xq: List[float] | np.ndarray) -> np.ndarray ``` Reshape the query vector to be a 2D numpy array. **Arguments**: * `xq` (`List[float] | np.ndarray`): The query vector. **Returns**: `np.ndarray`: The reshaped query vector. ## BaseRouter Objects [#baserouter-objects] ```python class BaseRouter(BaseModel) ``` Base class for all routers. #### \_\_init\_\_ [#__init__-1] ```python def __init__(encoder: Optional[DenseEncoder] = None, sparse_encoder: Optional[SparseEncoder] = None, llm: Optional[BaseLLM] = None, routes: Optional[List[Route]] = None, index: Optional[BaseIndex] = None, top_k: int = 5, aggregation: str = "mean", auto_sync: Optional[str] = None, init_async_index: bool = False) ``` Initialize a BaseRouter object. Expected to be used as a base class only, not directly instantiated. **Arguments**: * `encoder` (`Optional[DenseEncoder]`): The encoder to use. * `sparse_encoder` (`Optional[SparseEncoder]`): The sparse encoder to use. * `llm` (`Optional[BaseLLM]`): The LLM to use. * `routes` (`Optional[List[Route]]`): The routes to use. * `index` (`Optional[BaseIndex]`): The index to use. * `Optional[DenseEncoder]`0 (`Optional[DenseEncoder]`1): The number of routes to return. * `Optional[DenseEncoder]`2 (`Optional[DenseEncoder]`3): The aggregation method to use. * `Optional[DenseEncoder]`4 (`Optional[DenseEncoder]`5): The auto sync mode to use. #### check\_for\_matching\_routes [#check_for_matching_routes] ```python def check_for_matching_routes(top_class: str) -> Optional[Route] ``` Check for a matching route in the routes list. **Arguments**: * `top_class` (`str`): The top class to check for. **Returns**: `Optional[Route]`: The matching route if found, otherwise None. #### \_\_call\_\_ [#__call__] ```python def __call__(text: Optional[str] = None, vector: Optional[List[float] | np.ndarray] = None, simulate_static: bool = False, route_filter: Optional[List[str]] = None, limit: int | None = 1) -> RouteChoice | List[RouteChoice] ``` Call the router to get a route choice. **Arguments**: * `text` (`Optional[str]`): The text to route. * `vector` (`Optional[List[float] | np.ndarray]`): The vector to route. * `simulate_static` (`bool`): Whether to simulate a static route. * `route_filter` (`Optional[List[str]]`): The route filter to use. * `limit` (`int | None`): The number of routes to return, defaults to 1. If set to None, no limit is applied and all routes are returned. **Returns**: `Optional[str]`0: The route choice. #### acall [#acall] ```python async def acall( text: Optional[str] = None, vector: Optional[List[float] | np.ndarray] = None, limit: int | None = 1, simulate_static: bool = False, route_filter: Optional[List[str]] = None ) -> RouteChoice | list[RouteChoice] ``` Asynchronously call the router to get a route choice. **Arguments**: * `text` (`Optional[str]`): The text to route. * `vector` (`Optional[List[float] | np.ndarray]`): The vector to route. * `simulate_static` (`bool`): Whether to simulate a static route (ie avoid dynamic route LLM calls during fit or evaluate). * `route_filter` (`Optional[List[str]]`): The route filter to use. **Returns**: `RouteChoice`: The route choice. #### sync [#sync] ```python def sync(sync_mode: str, force: bool = False, wait: int = 0) -> List[str] ``` Runs a sync of the local routes with the remote index. **Arguments**: * `sync_mode` (`str`): The mode to sync the routes with the remote index. * `force` (`bool, optional`): Whether to force the sync even if the local and remote hashes already match. Defaults to False. * `wait` (`int`): The number of seconds to wait for the index to be unlocked before proceeding with the sync. If set to 0, will raise an error if index is already locked/unlocked. **Returns**: `List[str]`: A list of diffs describing the addressed differences between the local and remote route layers. #### async\_sync [#async_sync] ```python async def async_sync(sync_mode: str, force: bool = False, wait: int = 0) -> List[str] ``` Runs a sync of the local routes with the remote index. **Arguments**: * `sync_mode` (`str`): The mode to sync the routes with the remote index. * `force` (`bool, optional`): Whether to force the sync even if the local and remote hashes already match. Defaults to False. * `wait` (`int`): The number of seconds to wait for the index to be unlocked before proceeding with the sync. If set to 0, will raise an error if index is already locked/unlocked. **Returns**: `List[str]`: A list of diffs describing the addressed differences between the local and remote route layers. #### from\_json [#from_json] ```python @classmethod def from_json(cls, file_path: str) ``` Load a RouterConfig from a JSON file. **Arguments**: * `file_path` (`str`): The path to the JSON file. **Returns**: `RouterConfig`: The RouterConfig object. #### from\_yaml [#from_yaml] ```python @classmethod def from_yaml(cls, file_path: str) ``` Load a RouterConfig from a YAML file. **Arguments**: * `file_path` (`str`): The path to the YAML file. **Returns**: `RouterConfig`: The RouterConfig object. #### from\_config [#from_config] ```python @classmethod def from_config(cls, config: RouterConfig, index: Optional[BaseIndex] = None) ``` Create a Router from a RouterConfig object. **Arguments**: * `config` (`RouterConfig`): The RouterConfig object. * `index` (`Optional[BaseIndex]`): The index to use. #### add [#add-1] ```python def add(routes: List[Route] | Route) ``` Add a route to the local SemanticRouter and index. **Arguments**: * `route` (`Route`): The route to add. #### aadd [#aadd] ```python async def aadd(routes: List[Route] | Route) ``` Add a route to the local SemanticRouter and index asynchronously. **Arguments**: * `route` (`Route`): The route to add. #### update [#update] ```python def update(name: str, threshold: Optional[float] = None, utterances: Optional[List[str]] = None) ``` Updates the route specified in name. Allows the update of threshold and/or utterances. If no values are provided via the threshold or utterances parameters, those fields are not updated. If neither field is provided raises a ValueError. The name must exist within the local SemanticRouter, if not a KeyError will be raised. **Arguments**: * `name` (`str`): The name of the route to update. * `threshold` (`Optional[float]`): The threshold to update. * `utterances` (`Optional[List[str]]`): The utterances to update. #### delete [#delete] ```python def delete(route_name: str) ``` Deletes a route given a specific route name. **Arguments**: * `route_name`: the name of the route to be deleted #### adelete [#adelete] ```python async def adelete(route_name: str) ``` Deletes a route given a specific route name asynchronously. **Arguments**: * `route_name`: the name of the route to be deleted #### is\_synced [#is_synced] ```python def is_synced() -> bool ``` Check if the local and remote route layer instances are synchronized. **Returns**: `bool`: True if the local and remote route layers are synchronized, False otherwise. #### async\_is\_synced [#async_is_synced] ```python async def async_is_synced() -> bool ``` Check if the local and remote route layer instances are synchronized asynchronously. **Returns**: `bool`: True if the local and remote route layers are synchronized, False otherwise. #### get\_utterance\_diff [#get_utterance_diff] ```python def get_utterance_diff(include_metadata: bool = False) -> List[str] ``` Get the difference between the local and remote utterances. Returns a list of strings showing what is different in the remote when compared to the local. For example: \[" route1: utterance1", " route1: utterance2", "- route2: utterance3", "- route2: utterance4"] Tells us that the remote is missing "route2: utterance3" and "route2: utterance4", which do exist locally. If we see: \[" route1: utterance1", " route1: utterance2", "+ route2: utterance3", "+ route2: utterance4"] This diff tells us that the remote has "route2: utterance3" and "route2: utterance4", which do not exist locally. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the diff. **Returns**: `List[str]`: A list of strings showing the difference between the local and remote utterances. #### aget\_utterance\_diff [#aget_utterance_diff] ```python async def aget_utterance_diff(include_metadata: bool = False) -> List[str] ``` Get the difference between the local and remote utterances asynchronously. Returns a list of strings showing what is different in the remote when compared to the local. For example: \[" route1: utterance1", " route1: utterance2", "- route2: utterance3", "- route2: utterance4"] Tells us that the remote is missing "route2: utterance3" and "route2: utterance4", which do exist locally. If we see: \[" route1: utterance1", " route1: utterance2", "+ route2: utterance3", "+ route2: utterance4"] This diff tells us that the remote has "route2: utterance3" and "route2: utterance4", which do not exist locally. **Arguments**: * `include_metadata` (`bool`): Whether to include metadata in the diff. **Returns**: `List[str]`: A list of strings showing the difference between the local and remote utterances. #### get [#get-1] ```python def get(name: str) -> Optional[Route] ``` Get a route by name. **Arguments**: * `name` (`str`): The name of the route to get. **Returns**: `Optional[Route]`: The route. #### group\_scores\_by\_class [#group_scores_by_class] ```python def group_scores_by_class(query_results: List[Dict]) -> Dict[str, List[float]] ``` Group the scores by class. **Arguments**: * `query_results` (`List[Dict]`): The query results to group. Expected format is a list of dictionaries with "route" and "score" keys. **Returns**: `Dict[str, List[float]]`: A dictionary of route names and their associated scores. #### set\_threshold [#set_threshold] ```python def set_threshold(threshold: float, route_name: str | None = None) ``` Set the score threshold for a specific route or all routes. A `threshold` of 0.0 will mean that the route will be returned no matter how low it scores whereas a threshold of 1.0 will mean that a route must contain an exact utterance match to be returned. **Arguments**: * `threshold` (`float`): The threshold to set. * `route_name` (`str | None`): The name of the route to set the threshold for. If None, the threshold will be set for all routes. #### to\_config [#to_config] ```python def to_config() -> RouterConfig ``` Convert the router to a RouterConfig object. **Returns**: `RouterConfig`: The RouterConfig object. #### to\_json [#to_json] ```python def to_json(file_path: str) ``` Convert the router to a JSON file. **Arguments**: * `file_path` (`str`): The path to the JSON file. #### to\_yaml [#to_yaml] ```python def to_yaml(file_path: str) ``` Convert the router to a YAML file. **Arguments**: * `file_path` (`str`): The path to the YAML file. #### get\_thresholds [#get_thresholds] ```python def get_thresholds() -> Dict[str, float] ``` Get the score thresholds for each route. **Returns**: `Dict[str, float]`: A dictionary of route names and their associated thresholds. #### fit [#fit] ```python def fit(X: List[str], y: List[str], batch_size: int = 500, max_iter: int = 500, local_execution: bool = False) ``` Fit the router to the data. Works best with a large number of examples for each route and with many `None` utterances. **Arguments**: * `X` (`List[str]`): The input data. * `y` (`List[str]`): The output data. * `batch_size` (`int`): The batch size to use for fitting. * `max_iter` (`int`): The maximum number of iterations to use for fitting. * `local_execution` (`X`0): Whether to execute the fitting locally. #### evaluate [#evaluate] ```python def evaluate(X: List[str], y: List[str], batch_size: int = 500) -> float ``` Evaluate the accuracy of the route selection. **Arguments**: * `X` (`List[str]`): The input data. * `y` (`List[str]`): The output data. * `batch_size` (`int`): The batch size to use for evaluation. **Returns**: `float`: The accuracy of the route selection. #### threshold\_random\_search [#threshold_random_search] ```python def threshold_random_search( route_layer: BaseRouter, search_range: Union[int, float]) -> Dict[str, float] ``` Performs a random search iteration given a route layer and a search range. **Arguments**: * `route_layer` (`BaseRouter`): The route layer to search. * `search_range` (`Union[int, float]`): The search range to use. **Returns**: `Dict[str, float]`: A dictionary of route names and their associated thresholds. # semantic_router.routers.hybrid (/docs/semantic-router/v0/client-reference/routers/hybrid) ## HybridRouter Objects [#hybridrouter-objects] ```python class HybridRouter(BaseRouter) ``` A hybrid layer that uses both dense and sparse embeddings to classify routes. #### \_\_init\_\_ [#__init__] ```python def __init__(encoder: DenseEncoder, sparse_encoder: Optional[SparseEncoder] = None, llm: Optional[BaseLLM] = None, routes: Optional[List[Route]] = None, index: Optional[HybridLocalIndex] = None, top_k: int = 5, aggregation: str = "mean", auto_sync: Optional[str] = None, alpha: float = 0.3, init_async_index: bool = False) ``` Initialize the HybridRouter. **Arguments**: * `encoder` (`DenseEncoder`): The dense encoder to use. * `sparse_encoder` (`Optional[SparseEncoder]`): The sparse encoder to use. #### add [#add] ```python def add(routes: List[Route] | Route) ``` Add a route to the local HybridRouter and index. **Arguments**: * `route` (`Route`): The route to add. #### aadd [#aadd] ```python async def aadd(routes: List[Route] | Route) ``` Add a route to the local HybridRouter and index asynchronously. **Arguments**: * `routes` (`List[Route] | Route`): The route(s) to add. #### \_\_call\_\_ [#__call__] ```python def __call__( text: Optional[str] = None, vector: Optional[List[float] | np.ndarray] = None, simulate_static: bool = False, route_filter: Optional[List[str]] = None, limit: int | None = 1, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> RouteChoice | list[RouteChoice] ``` Call the HybridRouter. **Arguments**: * `text` (`Optional[str]`): The text to encode. * `vector` (`Optional[List[float] | np.ndarray]`): The vector to encode. * `simulate_static` (`bool`): Whether to simulate a static route. * `route_filter` (`Optional[List[str]]`): The route filter to use. * `limit` (`int | None`): The number of routes to return, defaults to 1. If set to None, no limit is applied and all routes are returned. * `Optional[str]`0 (`Optional[str]`1): The sparse vector to use. **Returns**: `Optional[str]`2: A RouteChoice or a list of RouteChoices. #### acall [#acall] ```python async def acall( text: Optional[str] = None, vector: Optional[List[float] | np.ndarray] = None, limit: int | None = 1, simulate_static: bool = False, route_filter: Optional[List[str]] = None, sparse_vector: dict[int, float] | SparseEmbedding | None = None ) -> RouteChoice | list[RouteChoice] ``` Asynchronously call the router to get a route choice. **Arguments**: * `text` (`Optional[str]`): The text to route. * `vector` (`Optional[List[float] | np.ndarray]`): The vector to route. * `simulate_static` (`bool`): Whether to simulate a static route (ie avoid dynamic route LLM calls during fit or evaluate). * `route_filter` (`Optional[List[str]]`): The route filter to use. * `sparse_vector` (`dict[int, float] | SparseEmbedding | None`): The sparse vector to use. **Returns**: `Optional[str]`0: The route choice. #### fit [#fit] ```python def fit(X: List[str], y: List[str], batch_size: int = 500, max_iter: int = 500, local_execution: bool = False) ``` Fit the HybridRouter. **Arguments**: * `X` (`List[str]`): The input data. * `y` (`List[str]`): The output data. * `batch_size` (`int`): The batch size to use for fitting. * `max_iter` (`int`): The maximum number of iterations to use for fitting. * `local_execution` (`bool`): Whether to execute the fitting locally. #### evaluate [#evaluate] ```python def evaluate(X: List[str], y: List[str], batch_size: int = 500) -> float ``` Evaluate the accuracy of the route selection. **Arguments**: * `X` (`List[str]`): The input data. * `y` (`List[str]`): The output data. * `batch_size` (`int`): The batch size to use for evaluation. **Returns**: `float`: The accuracy of the route selection. # semantic_router.routers.semantic (/docs/semantic-router/v0/client-reference/routers/semantic) ## SemanticRouter Objects [#semanticrouter-objects] ```python class SemanticRouter(BaseRouter) ``` A router that uses a dense encoder to encode routes and utterances. #### add [#add] ```python def add(routes: List[Route] | Route) ``` Add a route to the local SemanticRouter and index. **Arguments**: * `route` (`Route`): The route to add. #### aadd [#aadd] ```python async def aadd(routes: List[Route] | Route) ``` Asynchronously add a route to the local SemanticRouter and index. **Arguments**: * `routes` (`List[Route] | Route`): The route(s) to add. # semantic_router.utils.defaults (/docs/semantic-router/v0/client-reference/utils/defaults) ## EncoderDefault Objects [#encoderdefault-objects] ```python class EncoderDefault(Enum) ``` Default model names for each encoder type. # semantic_router.utils.function_call (/docs/semantic-router/v0/client-reference/utils/function_call) ## Parameter Objects [#parameter-objects] ```python class Parameter(BaseModel) ``` Parameter for a function. **Arguments**: * `name` (`str`): The name of the parameter. * `description` (`Optional[str]`): The description of the parameter. * `type` (`str`): The type of the parameter. * `default` (`Any`): The default value of the parameter. * `required` (`bool`): Whether the parameter is required. #### to\_ollama [#to_ollama] ```python def to_ollama() ``` Convert the parameter to a dictionary for an Ollama-compatible function schema. **Returns**: `Dict[str, Any]`: The parameter in dictionary format. ## FunctionSchema Objects [#functionschema-objects] ```python class FunctionSchema() ``` Class that consumes a function and can return a schema required by different LLMs for function calling. #### \_\_init\_\_ [#__init__] ```python def __init__(function: Union[Callable, BaseModel]) ``` Initialize the FunctionSchema. **Arguments**: * `function` (`Union[Callable, BaseModel]`): The function to consume. #### to\_ollama [#to_ollama-1] ```python def to_ollama() ``` Convert the FunctionSchema to an Ollama-compatible function schema dictionary. **Returns**: `Dict[str, Any]`: The function schema in dictionary format. #### get\_schema\_list [#get_schema_list] ```python def get_schema_list( items: List[Union[BaseModel, Callable]]) -> List[Dict[str, Any]] ``` Get a list of function schemas from a list of functions or Pydantic BaseModels. **Arguments**: * `items` (`List[Union[BaseModel, Callable]]`): The functions or BaseModels to get the schemas for. **Returns**: `List[Dict[str, Any]]`: A list of function schemas. #### get\_schema [#get_schema] ```python def get_schema(item: Union[BaseModel, Callable]) -> Dict[str, Any] ``` Get a function schema from a function or Pydantic BaseModel. **Arguments**: * `item` (`Union[BaseModel, Callable]`): The function or BaseModel to get the schema for. **Returns**: `Dict[str, Any]`: The function schema. #### convert\_python\_type\_to\_json\_type [#convert_python_type_to_json_type] ```python def convert_python_type_to_json_type(param_type: str) -> str ``` Convert a Python type to a JSON type. **Arguments**: * `param_type` (`str`): The type of the parameter. **Returns**: `str`: The JSON type. #### route\_and\_execute [#route_and_execute] ```python async def route_and_execute(query: str, llm: BaseLLM, functions: List[Callable], layer) -> Any ``` Route and execute a function. **Arguments**: * `query` (`str`): The query to route and execute. * `llm` (`BaseLLM`): The LLM to use. * `functions` (`List[Callable]`): The functions to execute. * `layer` (`Layer`): The layer to use. **Returns**: `Any`: The result of the function. # semantic_router.utils.logger (/docs/semantic-router/v0/client-reference/utils/logger) ## CustomFormatter Objects [#customformatter-objects] ```python class CustomFormatter(colorlog.ColoredFormatter) ``` Custom formatter for the logger. #### add\_coloured\_handler [#add_coloured_handler] ```python def add_coloured_handler(logger) ``` Add a coloured handler to the logger. #### setup\_custom\_logger [#setup_custom_logger] ```python def setup_custom_logger(name) ``` Setup a custom logger. # Changelog (/docs/semantic-router/v0/user-guide/changelog) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/changelog), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. ### v0.3.4 [#v034] #### Fixes [#fixes] * Dynamic routes reject function inputs in which the LLM sets a required argument to `null`. They raise `ValueError("Invalid inputs")`, as they already did for a missing argument, instead of returning `None` for it in `function_call`. Optional arguments may still be `None`. This applies to every LLM except `OpenAILLM`, which checks its tool calls separately. ([#686](https://github.com/aurelio-labs/semantic-router/issues/686)) ### v0.3.3 [#v033] #### Security [#security] * **LiteLLM 1.107.0 is excluded.** That PyPI release contained malware (a supply-chain attack, live on PyPI on 21 October 2026 from 11:39 to 13:23 UTC), and the `litellm` extra allowed it. The extra is now `litellm>=1.84.0,!=1.107.0`. PyPI has removed 1.107.0, but a private mirror may still serve it. If you installed `semantic-router[litellm]` or `[all]` without a lockfile in that window, check without starting Python in that environment: any Python start, `pip` included, runs the malware again. Look at your lockfile or deployment records, or search the environment from a shell, for example `find -name 'litellm-1.107.0.dist-info' -o -name cook.pth -o -name sitecustomize.py`. `pip show litellm` is safe only in an environment you know is clean, such as one you've just rebuilt. If 1.107.0 was installed, follow [LiteLLM's incident guidance](https://docs.litellm.ai/blog/security-incident-oct-21-2026#what-to-do-if-you-are-affected): isolate the host, rebuild the environment rather than reinstalling into it, and rotate every credential it could reach, from a clean machine. Finding nothing doesn't prove the environment was never exposed. * **certifi 2026.10.19 in the lockfile.** It removes the `emSign ECC Root CA - G3` root, which compromised eMudhra intermediate keys chain to ([advisory](https://github.com/advisories/GHSA-6q48-6c7w-9gw2)). semantic-router doesn't pin certifi, so `pip install -U certifi` updates the bundle in an existing environment; images and vendored bundles need rebuilding. Connections to Redis or Postgres over TLS may use your operating system's trust store or a CA bundle you configured instead of certifi: update whichever one they use. ### v0.3.2 [#v032] #### Fixes [#fixes-1] * `RedisIndex` reads every record past RediSearch's `MAXSEARCHRESULTS` limit (10,000 on Redis Stack). `get_utterances` and the lookups behind `delete` and `delete_all` used to stop at the limit without an error, so an index with more records than that synced from an incomplete list and left records behind on delete. Queries are unchanged. * `RedisIndex` doesn't support open-source Redis Cluster, because it talks to a single endpoint. When the server allows `INFO`, `RedisIndex` now detects cluster mode and raises a clear `ValueError` before it writes anything; it used to fail with a `MovedError` after some writes had landed. If an ACL denies `INFO`, the check is skipped, and Cluster is still unsupported. * The [Redis guide](https://github.com/aurelio-labs/semantic-router/blob/v0/docs/integrations/redis.md) covers TLS: a `rediss://` connection string with `ssl_ca_certs` (and a client certificate and key, if the server needs them) for a private CA. `ssl=True` with `host` and `port` trusts only the system's CAs. ### v0.3.1 [#v031] #### Fixes [#fixes-2] * Dynamic routes read function inputs that the LLM wraps in a Markdown code block (` ```json … ``` `), alone or after a line of text, instead of failing with a `JSONDecodeError`. This affects every LLM that asks for the inputs as JSON: `OpenAICompatibleLLM` and its presets, `AzureOpenAILLM`, `CohereLLM`, `MistralAILLM`, `OllamaLLM` and `OpenRouterLLM`. `OpenAILLM` uses tool calls and is unaffected. Plain JSON is read as before, including backticks inside its strings. ### v0.3.0 [#v030] `0.3.0` brings in the features from pull requests that were already open when `0.2.0` shipped, as a one-off exception. It is now the last feature release of the 0.x line: from here, 0.x gets bug fixes only, and new work goes into 1.x. Releases also follow strict [semantic versioning](https://semver.org) from now on: new features raise the minor version, and fixes raise the patch version. These are the changes since `0.2.0`, and none of them is breaking. #### Features [#features] * **`RedisIndex`** stores routes in Redis with RediSearch vector search, sync and async. It needs a server with the search module, such as Redis Stack, Redis 8 or Redis Cloud. Install `semantic-router[redis]`, and see the [Redis guide](https://github.com/aurelio-labs/semantic-router/blob/v0/docs/integrations/redis.md). * **`OpenAICompatibleLLM`** calls any OpenAI-compatible chat completions API. Pass its `base_url`, and either `api_key` or the name of the environment variable holding the key (`api_key_var_name`). * **Presets** built on `OpenAICompatibleLLM`, each with its own default `base_url`: | LLM | Key variable | Default model | | --------------- | -------------------- | ------------------------------- | | `RequestyLLM` | `REQUESTY_API_KEY` | `openai/gpt-4o-mini` | | `OrcaRouterLLM` | `ORCAROUTER_API_KEY` | `orcarouter/auto` | | `AtlasCloudLLM` | `ATLASCLOUD_API_KEY` | `deepseek-ai/deepseek-v4-flash` | | `MiniMaxLLM` | `MINIMAX_API_KEY` | `MiniMax-M3.1-Flash` | A preset reads its model from `_CHAT_MODEL_NAME` (`REQUESTY_CHAT_MODEL_NAME`, for example) when you don't pass `name`. `MiniMaxLLM` strips MiniMax-M3's `` blocks from its replies, and its default `max_tokens` is 4096 to leave room for thinking. #### Limits [#limits] **`RedisIndex` on Redis 8 with search workers.** With the query engine's worker threads on, Redis 8 can return incomplete results while it re-indexes a key. Redis 8.10 turns them on by default (`search-workers 16`); 8.0 and 8.2 leave them off. A query that runs while the same keys are being rewritten can miss routes, and so can the scans behind `sync` and `delete`. `RedisIndex` waits for a new or reopened index to finish indexing the keys already in the database (up to `index_ready_timeout`, 60 seconds by default), but it can't guard against concurrent updates. If routes are updated while the router serves queries, use Redis Stack 7.4 or set `search-workers 0`. On Redis 8.2 with workers on, a search can also return a record without its score, and `RedisIndex` raises an error rather than return incomplete results. `OpenAICompatibleLLM` and its presets have two limits in 0.x: * Dynamic routes extract function inputs only when called synchronously. `BaseLLM` has no async extraction, so an async call returns the matched route with `function_call=None` and logs an error. * A router config file saves only each LLM's class and model name. A router using `OpenAICompatibleLLM` can't be reloaded from one, because it needs a `base_url`. A preset reloads with its default `base_url` and reads its key from its environment variable, so a custom `base_url` or a key passed in code is lost. ### v0.2.0 [#v020] `0.2.0` is the last feature release of the 0.x line: from here, 0.x gets bug fixes only, and new work goes into 1.x (see the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1)). These are the changes since `0.1.16`. #### Breaking changes [#breaking-changes] * **Python 3.10 or later.** Python 3.9 is no longer supported, and dependency floors are raised to patched versions. * **`litellm` is optional.** Install `semantic-router[litellm]` to use `LiteLLMEncoder`. `CohereEncoder`, `MistralEncoder`, `VoyageEncoder`, `JinaEncoder` and `NimEncoder` call their providers directly and no longer need LiteLLM. * **`BM25Encoder` scores change.** The ATIRE BM25 formula is corrected: document length normalisation, the `(k1 + 1)` numerator, query IDF weighted by term frequency, and query weights scaled to `[0, 1]`. Both the document and the query weights change, so vectors stored by 0.1.x don't match queries encoded by 0.2.0: re-encode your documents and rebuild any sparse or hybrid index, then re-check the thresholds you tuned. #### Feature [#feature] * `FastEmbedEncoder` supports async calls. #### Fixes [#fixes-3] * `OpenAIEncoder` rejects an empty list, an empty string, non-string items and a bare `str` with a clear `ValueError` before calling the API. It used to retry the API's 400 before failing. Other input is sent unchanged. * `LocalIndex` returns no results for a route filter that matches no routes, like the other indexes, instead of raising. * `LocalIndex.add` checks that `metadata_list` is as long as the other inputs. * `PostgresIndex.aadd` uses deterministic record ids, as `add` does, so adding a stored utterance again doesn't duplicate it. * `PostgresIndex` no longer fails when two connections create the `vector` extension at the same moment. * `PineconeIndex` retries reading the stats of a freshly created index while its host comes up. * `QdrantIndex`: a failed scroll raises instead of reading as an empty index. * `NimEncoder` embeds queries with `input_type="query"` instead of `"passage"`. * `CLIPEncoder` and `VitEncoder` work with transformers 5. ### v0.1.12 [#v0112] The `0.1.12` release brings Pinecone v7 support and AWS Bedrock boto3 client integration, improving compatibility and expanding cloud deployment options. #### Feature: Pinecone v7 Upgrade [#feature-pinecone-v7-upgrade] Semantic Router now supports Pinecone Python SDK v7, providing: * Improved data plane performance and reliability * Enhanced async support for high-throughput applications * Simplified API structure for better developer experience * Better error handling and retry logic The upgrade is backward compatible - existing code continues to work without changes. For shared index deployments, set `PINECONE_INDEX_NAME` to reuse existing indexes and avoid quota limits. Semantic Router automatically isolates data using namespaces. #### Feature: Bedrock boto3 Client Support [#feature-bedrock-boto3-client-support] Added support for custom boto3 clients in the `BedrockEncoder`, enabling: * Advanced AWS credential management (IAM roles, cross-account access) * Custom retry policies and timeout configurations * VPC endpoint support for private deployments * Better integration with existing AWS infrastructure This provides greater flexibility for enterprise AWS deployments while maintaining backward compatibility with the existing credential-based approach. #### Chore: Relaxed OpenAI SDK Dependency [#chore-relaxed-openai-sdk-dependency] Updated OpenAI SDK dependency constraints from `<2.0.0` to `<3.0.0`, allowing compatibility with OpenAI SDK v2.x releases. This provides access to newer OpenAI features and improvements while maintaining stability through the v2 major version. *** ### v0.1.11 [#v0111] The `0.1.11` release introduces new encoder options for local and self-hosted deployments, alongside sparse encoding improvements and CI/CD enhancements. #### Feature: Local Encoder [#feature-local-encoder] Added `LocalEncoder` for fully local embedding generation using sentence-transformers: * No API keys or internet connection required * Automatic device selection (CUDA, MPS, CPU) * Support for any sentence-transformers model * Privacy-first design - all data stays on your machine Perfect for offline deployments, privacy-sensitive applications, or development environments. #### Feature: Local Sparse Encoder [#feature-local-sparse-encoder] Added sparse encoder support using sentence transformers with `LocalSparseEncoder`. * Same offline advantages as the Local Encoder above. * Better handling of sentence boundaries * Improved BM25 and TF-IDF implementations * Enhanced compatibility with `HybridRouter` #### Feature: Ollama Encoder [#feature-ollama-encoder] Introduced `OllamaEncoder` for using Ollama-hosted embedding models: * Works with any Ollama embedding model (nomic-embed-text, mxbai-embed-large, etc.) * Full control over model versions and hosting * Low latency with local Ollama instances * Both sync and async support Ideal for organizations wanting to self-host embedding models while maintaining API-like convenience. #### Feature: Dagger CI [#feature-dagger-ci] Implemented Dagger for CI/CD pipeline, providing: * Faster, more reliable builds * Better caching and parallelization * Consistent local and remote execution * Improved developer experience #### Chore: Torch Dependency Optimization [#chore-torch-dependency-optimization] Removed torch from main dependencies to reduce installation size. PyTorch is now only installed when needed via `semantic-router[local]` extras, reducing default installation from \~2GB to \<100MB. *** ### v0.1.10 [#v0110] The `0.1.10` release was primarily focused on expanding async support for `QdrantIndex`, `PostgresIndex`, and `HybridRouter`, alongside many synchronization and testing improvements. #### Feature: Expanded Async Support [#feature-expanded-async-support] * **QdrantIndex**: Async methods have been brought inline with our other indexes, ensuring consistent behavior. * **PostgresIndex**: Async methods have been added to the `PostgresIndex` for improved performance in async environments. * **HybridRouter**: Async support for the `HybridRouter` is now aligned with the `SemanticRouter`, providing a more consistent experience. #### Fixes and Optimizations [#fixes-and-optimizations] * **LocalIndex Bug Fix**: Added a `metadata` attribute to the local index. This fixes a bug where `LocalIndex` embeddings would always be recomputed, as reported in [issue #585](https://github.com/aurelio-labs/semantic-router/issues/585). * Various other bug fixes and optimizations have been included in this release. * The `urllib3` library has been upgraded. * Test compatibility and synchronization have been optimized. *** ### v0.1.9 [#v019] The `0.1.9` update focuses on improving support for our local deployment options. We have standardized the `PostgresIndex` to bring it in line with other index options and prepare it for future feature releases. For `local` extras (including `transformers` and `llama_cpp` support) and `postgres` extras we have resolved issues making those extras unusable with Python 3.13. Continue reading below for more detail. #### Feature: Improvements to `postgres` Support [#feature-improvements-to-postgres-support] * **Upgrade from psycopg2 to v3 (psycopg)**: We've upgraded our PostgreSQL driver from psycopg2 to the newer psycopg v3, which provides better performance and modern Python compatibility. * **Standardization of sync methods**: The `PostgresIndex` class now has standardized synchronous methods that integrate seamlessly into our standard pytest test suite, ensuring better testing coverage and reliability. * **Addition of IndexType support**: We've introduced `IndexType` which includes `FLAT`, `IVFFLAT`, and `HNSW` index types. Both `FLAT` and `IVFFLAT` map to the `IVFFLAT` index in pgvector (pgvector does not currently support `FLAT` and so `IVFFLAT` is the closest approximation - but our other indexes do). `FLAT` is now the default index type. We recommend `HNSW` for high-scale use cases with many millions of utterances due to its higher memory requirements and complexity. #### Feature: Configurable Logging [#feature-configurable-logging] * **Environment variable log level control**: Logger now supports configurable log levels via environment variables. Set `SEMANTIC_ROUTER_LOG_LEVEL` or `LOG_LEVEL` to control logging verbosity (e.g., `DEBUG`, `INFO`, `WARNING`, `ERROR`). Defaults to `INFO` if not specified. #### Fix: Local Installation for Python 3.13 and up [#fix-local-installation-for-python-313-and-up] Python 3.13 and up had originally been incompatible with our local installations due to the lack of compatability with PyTorch and the (then) new version of Python. We have now added the following version support for `local` libraries: ```python local = [ "torch>=2.6.0 ; python_version >= '3.13'", "transformers>=4.50.0 ; python_version >= '3.13'", "tokenizer>=0.20.2 ; python_version >= '3.13'", "llama-cpp-python>=0.3.0 ; python_version >= '3.13'", ] ``` #### Fix: Consistent Index Length Behavior [#fix-consistent-index-length-behavior] * **Standardized `__len__` method across all index implementations**: All index types now consistently return `0` when uninitialized, preventing potential `AttributeError` exceptions that could occur in `PineconeIndex` and `QdrantIndex` when checking the length of uninitialized indexes. #### Chore: Broader and More Useful Tests [#chore-broader-and-more-useful-tests] We have broken our tests apart into strict unit and integration test directories. Now, when incoming PRs are raised we will no longer trigger integration tests that require API keys to successfully run. To ensure we're still covering all components of the library we have broadened our testing suite to extensively test `LocalIndex`, `PineconeIndex` (via Pinecone Local), `PostgresIndex`, and `QdrantIndex` within those unit tests. # Encoders (/docs/semantic-router/v0/user-guide/components/encoders) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/components/encoders), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. An encoder turns text (or images, or other data) into a vector — a list of numbers that captures meaning. Those vectors are what let Semantic Router measure how similar two inputs are. Every routing decision starts here. ## What an encoder does [#what-an-encoder-does] An encoder does two jobs: 1. **At setup**, it embeds the example utterances in your routes. 2. **At runtime**, it embeds each incoming query. The router compares the two and picks the closest route — even when the wording is completely different. ## Dense vs. sparse [#dense-vs-sparse] Semantic Router supports two kinds of encoder. They see text very differently, and each has its strengths. ### Dense encoders [#dense-encoders] Dense encoders fill every dimension of the vector. They: * Produce fixed-size vectors (1536 dimensions for OpenAI's `text-embedding-3-small`, for example). * Capture rich semantic relationships. * Do well when context and meaning matter more than exact words. ```python import os from semantic_router.encoders import OpenAIEncoder os.environ["OPENAI_API_KEY"] = "your-api-key" encoder = OpenAIEncoder() embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ### Sparse encoders [#sparse-encoders] Sparse encoders leave most dimensions at zero, with only a few non-zero values. They: * Key off specific words and tokens. * Excel at exact keyword matching and term frequency. * Are more interpretable — a non-zero dimension usually maps to a specific word. ```python import os from semantic_router.encoders import AurelioSparseEncoder os.environ["AURELIO_API_KEY"] = "your-api-key" encoder = AurelioSparseEncoder() embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ## Using both: hybrid routing [#using-both-hybrid-routing] You don't have to choose. The `HybridRouter` takes a dense and a sparse encoder together, so you get semantic understanding *and* keyword precision. The `alpha` parameter sets the balance. ```python import os from semantic_router import Route from semantic_router.routers import HybridRouter from semantic_router.encoders import OpenAIEncoder, AurelioSparseEncoder os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["AURELIO_API_KEY"] = "your-aurelio-api-key" routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = HybridRouter( encoder=OpenAIEncoder(), sparse_encoder=AurelioSparseEncoder(), routes=routes, alpha=0.5, # 0 = all dense, 1 = all sparse ) ``` ## Supported encoders [#supported-encoders] Most encoders ship with the base install. The ones that run models locally need the `local` extra: ```bash pip install -qU "semantic-router[local]" ``` ### Dense encoders [#dense-encoders-1] | Encoder | What it uses | Install | | ------------------------------------------------------------------ | -------------------------------------------------- | ------- | | [OpenAIEncoder](../../client-reference/encoders/openai) | OpenAI embedding models | base | | [AzureOpenAIEncoder](../../client-reference/encoders/azure_openai) | Azure OpenAI embedding models | base | | [CohereEncoder](../../client-reference/encoders/cohere) | Cohere embedding models | base | | [MistralEncoder](../../client-reference/encoders/mistral) | Mistral embedding models | base | | [GoogleEncoder](../../client-reference/encoders/google) | Google embedding models | base | | [BedrockEncoder](../../client-reference/encoders/bedrock) | AWS Bedrock embedding models | base | | [JinaEncoder](../../client-reference/encoders/jina) | Jina embedding models | base | | [VoyageEncoder](../../client-reference/encoders/voyage) | Voyage embedding models | base | | [NimEncoder](../../client-reference/encoders/nvidia_nim) | NVIDIA NIM embedding models | base | | [LiteLLMEncoder](../../client-reference/encoders/litellm) | Any provider supported by LiteLLM | base | | [OllamaEncoder](../../client-reference/encoders/ollama) | Embedding models served by a local Ollama instance | base | | [HFEndpointEncoder](../../client-reference/encoders/huggingface) | Hugging Face Inference API | base | | [HuggingFaceEncoder](../../client-reference/encoders/huggingface) | Hugging Face models, run locally | `local` | | [LocalEncoder](../../client-reference/encoders/local) | Any sentence-transformers model, run locally | `local` | | [FastEmbedEncoder](../../client-reference/encoders/fastembed) | FastEmbed models, run locally | `local` | | [VitEncoder](../../client-reference/encoders/vit) | Vision Transformer, for image embeddings | `local` | | [CLIPEncoder](../../client-reference/encoders/clip) | CLIP, for image and text embeddings | `local` | ### Sparse encoders [#sparse-encoders-1] | Encoder | What it uses | Install | | --------------------------------------------------------------- | ------------------------------------------------------------------------- | ------- | | [BM25Encoder](../../client-reference/encoders/bm25) | BM25 | base | | [TfidfEncoder](../../client-reference/encoders/tfidf) | TF-IDF | base | | [AurelioSparseEncoder](../../client-reference/encoders/aurelio) | Aurelio's API for BM25 sparse embeddings | base | | [LocalSparseEncoder](../../client-reference/encoders/local) | Neural sparse models (SPLADE, CSR) via sentence-transformers, run locally | `local` | `LocalSparseEncoder` is worth a closer look if you want sparse vectors without an API. It uses the sentence-transformers `SparseEncoder` API (v5+), runs on CPU, CUDA, or MPS, and works with any compatible model from the Hugging Face Hub: ```python from semantic_router.encoders import LocalSparseEncoder encoder = LocalSparseEncoder(name="naver/splade-v3") embeddings = encoder(["How's the weather today?", "Tell me about politics"]) ``` ## AutoEncoder [#autoencoder] If you'd rather pick an encoder by name at runtime, `AutoEncoder` resolves the right class for you: ```python from semantic_router.encoders import AutoEncoder from semantic_router.schema import EncoderType encoder = AutoEncoder(type=EncoderType.OPENAI.value, name="text-embedding-3-small").model embeddings = encoder(["How can I help you today?"]) ``` ## Choosing an encoder [#choosing-an-encoder] A few questions to ask: 1. **Accuracy.** Dense encoders understand meaning better but can miss exact keywords. Sparse encoders are the reverse. 2. **Speed.** Local encoders avoid network round-trips, though cloud models are often more accurate. 3. **Cost.** Cloud encoders (OpenAI, Cohere, Aurelio) bill per call. Local ones don't. 4. **Privacy.** Local encoders keep your data on your machine. 5. **Both?** When you're unsure, a hybrid setup often gives the best balance. Each encoder's reference page covers its specific options. # Indexes (/docs/semantic-router/v0/user-guide/components/indexes) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/components/indexes), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. An index is where Semantic Router stores your route embeddings and searches them. It's the search backend behind every routing decision. ## What an index does [#what-an-index-does] An index handles four things: 1. **Stores** the embeddings of your route utterances. 2. **Searches** for the most similar vectors when a query comes in. 3. **Persists** your routes across sessions (remote indexes only). 4. **Scales** to large numbers of routes and utterances. Your choice of index shapes performance, scale, and whether your routes survive a restart. ## Local vs. remote [#local-vs-remote] ### Local indexes [#local-indexes] A local index keeps embeddings in memory. It's fast and needs zero setup, but it's gone when your process exits. Ideal for development, testing, and small route sets. ```python import os from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder from semantic_router.index import LocalIndex os.environ["OPENAI_API_KEY"] = "your-api-key" routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = SemanticRouter( encoder=OpenAIEncoder(), routes=routes, index=LocalIndex(), ) result = router("What's the weather like today?") print(result.name) # "weather" ``` ### Remote indexes [#remote-indexes] A remote index stores embeddings in a vector database. Your routes persist, and you can scale to millions of vectors. This is what you want in production. Here's Pinecone: ```python import os from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder from semantic_router.index import PineconeIndex os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["PINECONE_API_KEY"] = "your-pinecone-api-key" routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] index = PineconeIndex( index_name="semantic-router", dimensions=1536, # must match your encoder ) router = SemanticRouter( encoder=OpenAIEncoder(), routes=routes, index=index, auto_sync="remote", # push local routes to the remote index ) result = router("What's the weather like today?") print(result.name) # "weather" ``` ## Hybrid indexes [#hybrid-indexes] For hybrid routing, you need an index that stores both dense and sparse vectors. `HybridLocalIndex` does that in memory: ```python import os from semantic_router.routers import HybridRouter from semantic_router.encoders import OpenAIEncoder, AurelioSparseEncoder from semantic_router.index import HybridLocalIndex os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["AURELIO_API_KEY"] = "your-aurelio-api-key" router = HybridRouter( encoder=OpenAIEncoder(), sparse_encoder=AurelioSparseEncoder(), routes=routes, index=HybridLocalIndex(), alpha=0.5, # 0 = all dense, 1 = all sparse ) ``` ## Supported indexes [#supported-indexes] | Index | What it is | Install | | ------------------------------------------------------------- | -------------------------------------- | --------------------------------------------- | | [LocalIndex](../../client-reference/index/local) | In-memory, for development and testing | base | | [HybridLocalIndex](../../client-reference/index/hybrid_local) | In-memory, dense and sparse | base | | [PineconeIndex](../../client-reference/index/pinecone) | Pinecone vector database | `pip install -qU "semantic-router[pinecone]"` | | [QdrantIndex](../../client-reference/index/qdrant) | Qdrant vector database | `pip install -qU "semantic-router[qdrant]"` | | [PostgresIndex](../../client-reference/index/postgres) | PostgreSQL with pgvector | `pip install -qU "semantic-router[postgres]"` | | [RedisIndex](../../client-reference/index/redis) | Redis with RediSearch vector search | `pip install -qU "semantic-router[redis]"` | ## Keeping local and remote in sync [#keeping-local-and-remote-in-sync] With a remote index, your in-memory routes and the stored ones can drift. The `auto_sync` parameter tells the router how to reconcile them at startup: ```python router = SemanticRouter( encoder=encoder, routes=routes, index=remote_index, auto_sync="remote", # "local", "remote", or None ) # adding a route syncs it automatically router.add(Route(name="greetings", utterances=["Hello there", "Hi, how are you?"])) ``` * `"local"` — local is the source of truth; push it to remote. * `"remote"` — remote is the source of truth; pull it into local. * `None` — don't sync. There are more strategies, including merges. The [sync guide](../features/sync) covers them all. ## Choosing an index [#choosing-an-index] 1. **Persistence.** Local indexes vanish on restart. Remote ones don't. 2. **Scale.** Local is bounded by memory. Remote handles millions of vectors. 3. **Latency.** Local is fastest. Remote adds a network hop. 4. **Setup.** Local needs nothing. Remote needs an account and config. 5. **Cost.** Local is free. Remote may bill for usage. 6. **Hybrid search.** Only some indexes store both dense and sparse vectors. ## Index methods [#index-methods] Every index inherits from `BaseIndex` and implements: * `add()` — add embeddings. * `query()` — search for similar vectors. * `delete()` — remove a route. * `describe()` — get index info. * `is_ready()` — check it's initialized. Each index's reference page covers its configuration options. # Routers (/docs/semantic-router/v0/user-guide/components/routers) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/components/routers), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. The router is the part you actually talk to. It takes a query, finds the best-matching route, and hands back a decision. Under the hood it wires together an encoder, an index, and your routes. ## What a router does [#what-a-router-does] 1. **Encodes** incoming queries. 2. **Matches** them to routes by similarity. 3. **Decides** which handler should run. 4. **Manages** routes — add, look up, list. 5. **Reports** a confidence score with each decision. ## Router types [#router-types] ### SemanticRouter [#semanticrouter] The standard router. It uses dense embeddings and is what most people reach for first. ```python import os from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder from semantic_router.index import LocalIndex os.environ["OPENAI_API_KEY"] = "your-api-key" routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = SemanticRouter( encoder=OpenAIEncoder(), routes=routes, index=LocalIndex(), ) result = router("What's the weather like today?") print(result.name) # "weather" print(result.score) # e.g. 0.92 ``` ### HybridRouter [#hybridrouter] The `HybridRouter` combines dense and sparse embeddings — semantic understanding plus keyword matching. It often wins when your queries carry specific terms that need to match exactly. ```python import os from semantic_router import Route from semantic_router.routers import HybridRouter from semantic_router.encoders import OpenAIEncoder, AurelioSparseEncoder from semantic_router.index import HybridLocalIndex os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["AURELIO_API_KEY"] = "your-aurelio-api-key" routes = [ Route(name="weather", utterances=["How's the weather?", "Is it raining?"]), Route(name="politics", utterances=["Tell me about politics", "Who's the president?"]), ] router = HybridRouter( encoder=OpenAIEncoder(), sparse_encoder=AurelioSparseEncoder(), routes=routes, index=HybridLocalIndex(), alpha=0.3, # 0 = all dense, 1 = all sparse ) result = router("What's the weather like today?") print(result.name) # "weather" ``` ## Working with routes [#working-with-routes] Add, fetch, and list routes on a live router: ```python router.add(Route(name="greetings", utterances=["Hello there", "Hi, how are you?"])) greeting_route = router.get("greetings") route_names = router.list_route_names() ``` ## Thresholds [#thresholds] A route only matches when its similarity score clears a threshold. Set one for the whole router, or per route: ```python # one threshold for every route router = SemanticRouter( encoder=OpenAIEncoder(), routes=routes, score_threshold=0.75, ) # a stricter threshold on one route weather_route = Route( name="weather", utterances=["How's the weather?", "Is it raining?"], score_threshold=0.8, ) ``` Picking thresholds by hand is tedious. The [threshold optimization guide](../features/threshold-optimization) shows how to fit them from examples in seconds. ## Async [#async] Both routers work in async code: ```python result = await router.acall("What's the weather like today?") await router.aadd(new_route) ``` ## Loading from config [#loading-from-config] Load a router from a file or a config object — handy for shipping the same routes across environments: ```python # from YAML router = SemanticRouter.from_yaml("router_config.yaml") # from a RouterConfig from semantic_router.routers import RouterConfig config = RouterConfig(routes=routes, encoder_type="openai") router = SemanticRouter.from_config(config) ``` ## Syncing with a remote index [#syncing-with-a-remote-index] With a remote index, `auto_sync` controls how local and stored routes are reconciled: ```python router = SemanticRouter( encoder=encoder, routes=routes, index=remote_index, auto_sync="remote", # "local", "remote", or None ) ``` The [sync guide](../features/sync) covers every strategy. ## Tuning hybrid alpha [#tuning-hybrid-alpha] `alpha` sets the dense/sparse balance in a `HybridRouter`: ```python alpha=0.2 # lean semantic (80% dense, 20% sparse) alpha=0.5 # even split alpha=0.8 # lean keywords (20% dense, 80% sparse) ``` ## What a router returns [#what-a-router-returns] Calling a router gives you a `RouteChoice` with: * `name` — the matched route, or `None` if nothing matched. * `score` — the confidence of the match. * `function_call` — for dynamic routes, the function(s) to call and their arguments. * `metadata` — any metadata attached to the route. ## SemanticRouter or HybridRouter? [#semanticrouter-or-hybridrouter] * **HybridRouter** usually scores higher, because it matches on meaning *and* keywords. * **SemanticRouter** is lighter and faster. * If your queries contain specific terms that must match exactly — product codes, names, jargon — go hybrid. * Hybrid needs a sparse encoder too, so check you have the API keys or local models it needs. The API reference has the full detail on every option. # Architecture (/docs/semantic-router/v0/user-guide/concepts/architecture) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/concepts/architecture), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. # Semantic Router: Technical Architecture [#semantic-router-technical-architecture] ## System overview [#system-overview] Three components do the work. An **encoder** turns the input into a vector. An **index** stores your route vectors. A **router** compares the two and picks a match. ## Core components [#core-components] ### 1. Encoders [#1-encoders] Encoders map inputs into semantic space. * **Dense encoders** produce continuous vectors (OpenAI, Hugging Face, …). * **Sparse encoders** produce mostly-zero vectors (BM25, TF-IDF, AurelioSparse, …). * **Multimodal encoders** handle images as well as text (CLIP, ViT). ### 2. Routes [#2-routes] A route is a pattern to match, defined by example inputs that should trigger it. * **name** — the route's identifier. * **utterances** — example inputs that should match. * **function\_schemas** — optional. Set this and the route becomes *dynamic*, able to call functions. * **score\_threshold** — the minimum similarity needed to match. ### 3. Indexes [#3-indexes] Indexes store route vectors and search them efficiently. * **LocalIndex** — in-memory, dense vectors. * **HybridLocalIndex** — in-memory, dense *and* sparse. * **PineconeIndex / QdrantIndex** — cloud vector databases. * **PostgresIndex** — SQL storage via pgvector. ## Data flow [#data-flow] 1. An input arrives (text, an image). 2. The encoder turns it into a vector. 3. The router searches the index for similar route vectors. 4. The best match above threshold is selected. 5. The matched route comes back, ready for your handler. ## Router types [#router-types] * **SemanticRouter** — dense embeddings, pure semantic matching. * **HybridRouter** — dense *and* sparse, for better accuracy when exact keywords matter. ## Putting it together [#putting-it-together] ```python from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder # 1. Define routes weather_route = Route(name="weather", utterances=["What's the weather like?"]) greeting_route = Route(name="greeting", utterances=["Hello there!", "Hi!"]) # 2. Pick an encoder encoder = OpenAIEncoder() # 3. Build the router router = SemanticRouter(encoder=encoder, routes=[weather_route, greeting_route]) # 4. Route a query result = router("What's the forecast for tomorrow?") print(result.name) # "weather" ``` ## Performance notes [#performance-notes] * **In-memory vs. vector DB** — pick by scale and latency needs. * **Encoder choice** — trade accuracy against speed for your use case. * **Batching** — use the batch methods for higher throughput. * **Async** — available for high-concurrency and network-heavy workloads. # Overview (/docs/semantic-router/v0/user-guide/concepts/overview) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/concepts/overview), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. Semantic routing sends an input — text, an image, audio — to the right handler based on what it *means*, not on keywords or hand-written rules. People say the same thing a hundred different ways. Semantic routing handles that variety without you enumerating every phrasing. ## Semantic space [#semantic-space] Here's the core idea. Imagine a huge coordinate system where every point is a concept. "I need help with my password" sits right next to "Can't log in to my account", and far from "What's the weather forecast?". That's semantic space. Meaning becomes geometry, and similarity becomes a distance you can measure. * Each point (a vector) represents the meaning of some content. * Distance between points is semantic difference. * Similar meanings cluster together, whatever the exact wording. So synonyms, paraphrases, and related ideas all land close to each other — and you never program the variations by hand. ### Encoders [#encoders] To put content into semantic space, you *encode* it into a vector. That's the job of an encoder (you'll also hear "embedding model" or "bi-encoder"). An encoder takes the input, analyzes its features, and outputs a fixed-size vector of numbers — usually hundreds or thousands of dimensions. "How's the weather today?" might become `[0.12, -0.34, 0.56, ...]`. "What's the temperature outside?" becomes a different but nearby vector, because the meanings are close. Semantic Router supports two families: * **Dense encoders** (`OpenAIEncoder`, `HuggingFaceEncoder`, …) fill every dimension. They capture rich semantic relationships. * **Sparse encoders** (`AurelioSparseEncoder`, `BM25Encoder`, …) leave most dimensions at zero. They excel at exact keywords and term frequency. ### Multimodal routing [#multimodal-routing] Text is the common case, but anything you can encode, you can route: * **Images.** `CLIPEncoder` and `VitEncoder` place images in the same space as text, so you can compare across modalities. * **Audio.** Speech or sound, routed on content or tone. * **Mixed content.** Text and images together, encoded jointly or separately. That's what lets you route on what's *in* an image, or on the combined meaning of text plus a picture. ### Making the decision [#making-the-decision] Once everything is a vector, routing is a similarity calculation. The usual measures: * **Cosine similarity**: cos(θ) = (A·B)/(||A||·||B||) * **Euclidean distance**: d(A,B) = √(Σ(Aᵢ-Bᵢ)²) * **Dot product**: A·B = Σ(Aᵢ·Bᵢ) Semantic Router compares the incoming query against every route, where each route is represented by its example utterances. The route with the highest score above a configurable threshold wins. ## The workflow [#the-workflow] 1. **Define routes** — example utterances for each category. 2. **Pick an encoder** — based on content type and performance needs. 3. **Configure the router** — connect encoder, routes, and an index. 4. **Write handlers** — the logic for each route. 5. **Route inputs** — encode, compare, dispatch. Semantic Router handles the vector math, the similarity scoring, and the decision. You focus on defining good routes and writing the handlers. # Dynamic Routes (/docs/semantic-router/v0/user-guide/features/dynamic-routes) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 removes dynamic routes. The [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1#dynamic-routes-and-the-llm-classes-are-gone) shows what to do instead. There are two kinds of route. A *static* route tells you which route matched — you get back its name, like `"math"`. A *dynamic* route does that too, but it also pulls the details out of the query and hands them to a function. Say you have a route with utterances like these: ```python "what is x to the power of y?" "what is 9 to the power of 4?" "calculate the result of base x and exponent y" "return x to the power of y" ``` and you attach a function to it: ```python def power(base: float, exponent: float) -> float: """Raise base to the power of exponent. Args: base (float): The base number. exponent (float): The exponent to which the base is raised. Returns: float: The result of base raised to the power of exponent. """ return base ** exponent ``` Now ask "What is 2 to the power of 3?". The route matches on meaning, same as any route. Then an LLM reads the query and works out that `base=2` and `exponent=3`, in a shape you can pass straight to `power()`. That's the whole idea: natural language in, a ready-to-call function out. To make a route dynamic, give it `function_schemas` — a list describing each function so the LLM knows what it does and what it needs. The rest of this page walks through it. ## Full example [#full-example] [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/02-dynamic-routes.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/02-dynamic-routes.ipynb) ```python !pip install tzdata !pip install -qU semantic-router>=0.1.5 ``` > **Prefer to run this locally?** There's a fully local version of dynamic routes in [05-local-execution.ipynb](https://github.com/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb). It tends to outperform the OpenAI version shown here, so it's worth a try. ### Start with static routes [#start-with-static-routes] Dynamic routes sit alongside static ones, so let's build a router with two static routes first. ```python from semantic_router import Route politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` Pick an encoder. Any will do — `CohereEncoder`, `OpenAIEncoder`, or a local one like `FastEmbedEncoder`. ```python import os from semantic_router import SemanticRouter from semantic_router.encoders import OpenAIEncoder # platform.openai.com os.environ["OPENAI_API_KEY"] = "" encoder = OpenAIEncoder() sr = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") ``` Check it works with static routes only: ```python sr("how's the weather today?") ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` ### Add a dynamic route [#add-a-dynamic-route] Here's the function we want the route to call — it returns the current time in a timezone. The docstring matters: the LLM reads it to learn what the `timezone` argument should look like. ```python from datetime import datetime from zoneinfo import ZoneInfo def get_time(timezone: str) -> str: """Finds the current time in a specific timezone. :param timezone: The timezone to find the current time in, should be a valid timezone from the IANA Time Zone Database like "America/New_York" or "Europe/London". Do NOT put the place name itself like "rome", or "new york", you must provide the IANA format. :type timezone: str :return: The current time in the specified timezone.""" now = datetime.now(ZoneInfo(timezone)) return now.strftime("%H:%M") ``` ```python get_time("America/New_York") ``` ``` '17:57' ``` Generate the schema from the function with `get_schemas_openai`: ```python from semantic_router.llms.openai import get_schemas_openai schemas = get_schemas_openai([get_time]) schemas ``` Then define the route, passing the schema in: ```python time_route = Route( name="get_time", utterances=[ "what is the time in new york city?", "what is the time in london?", "I live in Rome, what time is it?", ], function_schemas=schemas, ) ``` Add it to the router: ```python sr.add(time_route) ``` Now ask a time question: ```python response = sr("what is the time in new york city?") response ``` ``` RouteChoice(name='get_time', function_call=[{'function_name': 'get_time', 'arguments': {'timezone': 'America/New_York'}}], similarity_score=None) ``` The route matched *and* the LLM filled in the arguments. `function_call` holds everything you need to run it: ```python for call in response.function_call: if call["function_name"] == "get_time": result = get_time(**call["arguments"]) print(result) ``` ``` 17:57 ``` ### One route, several functions [#one-route-several-functions] A route can carry more than one function. When it matches, the LLM decides which functions the query needs — and it can call several at once if the query asks for several things. Let's give one route three timezone tools: ```python from datetime import datetime, timedelta from zoneinfo import ZoneInfo def get_time(timezone: str) -> str: """Finds the current time in a specific timezone. :param timezone: The timezone to find the current time in, should be a valid timezone from the IANA Time Zone Database like "America/New_York" or "Europe/London". Do NOT put the place name itself like "rome", or "new york", you must provide the IANA format. :type timezone: str :return: The current time in the specified timezone.""" now = datetime.now(ZoneInfo(timezone)) return now.strftime("%H:%M") def get_time_difference(timezone1: str, timezone2: str) -> str: """Calculates the time difference between two timezones. :param timezone1: The first timezone, should be a valid timezone from the IANA Time Zone Database like "America/New_York" or "Europe/London". :param timezone2: The second timezone, should be a valid timezone from the IANA Time Zone Database like "America/New_York" or "Europe/London". :type timezone1: str :type timezone2: str :return: The time difference in hours between the two timezones.""" now_utc = datetime.utcnow().replace(tzinfo=ZoneInfo("UTC")) tz1_time = now_utc.astimezone(ZoneInfo(timezone1)) tz2_time = now_utc.astimezone(ZoneInfo(timezone2)) tz1_offset = tz1_time.utcoffset().total_seconds() tz2_offset = tz2_time.utcoffset().total_seconds() hours_difference = (tz2_offset - tz1_offset) / 3600 return f"The time difference between {timezone1} and {timezone2} is {hours_difference} hours." def convert_time(time: str, from_timezone: str, to_timezone: str) -> str: """Converts a specific time from one timezone to another. :param time: The time to convert in HH:MM format. :param from_timezone: The original timezone of the time, should be a valid IANA timezone. :param to_timezone: The target timezone for the time, should be a valid IANA timezone. :type time: str :type from_timezone: str :type to_timezone: str :return: The converted time in the target timezone. :raises ValueError: If the time format or timezone strings are invalid. Example: convert_time("12:30", "America/New_York", "Asia/Tokyo") -> "03:30" """ try: # use today's date to avoid historical timezone issues today = datetime.now().date() datetime_string = f"{today} {time}" time_obj = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M").replace( tzinfo=ZoneInfo(from_timezone) ) converted_time = time_obj.astimezone(ZoneInfo(to_timezone)) return converted_time.strftime("%H:%M") except Exception as e: raise ValueError(f"Error converting time: {e}") ``` Generate schemas for all three and build the route. Give it utterances that cover each function, plus a couple that hit several at once: ```python from semantic_router.llms.openai import get_schemas_openai functions = [get_time, get_time_difference, convert_time] schemas = get_schemas_openai(functions) multi_function_route = Route( name="timezone_management", utterances=[ # get_time "what is the time in New York?", "current time in Berlin?", "tell me the time in Moscow right now", "can you show me the current time in Tokyo?", "please provide the current time in London", # get_time_difference "how many hours ahead is Tokyo from London?", "time difference between Sydney and Cairo", "what's the time gap between Los Angeles and New York?", "how much time difference is there between Paris and Sydney?", "calculate the time difference between Dubai and Toronto", # convert_time "convert 15:00 from New York time to Berlin time", "change 09:00 from Paris time to Moscow time", "adjust 20:00 from Rome time to London time", "convert 12:00 from Madrid time to Chicago time", "change 18:00 from Beijing time to Los Angeles time", # all three "What is the time in Seattle? What is the time difference between Mumbai and Tokyo? What is 5:53 Toronto time in Sydney time?", ], function_schemas=schemas, ) routes = [politics, chitchat, multi_function_route] sr2 = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") ``` A small dispatcher runs whatever the router asks for: ```python def parse_response(response): for call in response.function_call: args = call["arguments"] if call["function_name"] == "get_time": print(get_time(**args)) if call["function_name"] == "get_time_difference": print(get_time_difference(**args)) if call["function_name"] == "convert_time": print(convert_time(**args)) ``` Now ask for three things in one go: ```python response = sr2( """ What is the time in Prague? What is the time difference between Frankfurt and Beijing? What is 5:53 Lisbon time in Bangkok time? """ ) response ``` ``` RouteChoice(name='timezone_management', function_call=[{'function_name': 'get_time', 'arguments': {'timezone': 'Europe/Prague'}}, {'function_name': 'get_time_difference', 'arguments': {'timezone1': 'Europe/Berlin', 'timezone2': 'Asia/Shanghai'}}, {'function_name': 'convert_time', 'arguments': {'time': '05:53', 'from_timezone': 'Europe/Lisbon', 'to_timezone': 'Asia/Bangkok'}}], similarity_score=None) ``` All three functions, each with the right arguments. Run them: ```python parse_response(response) ``` ``` 23:58 The time difference between Europe/Berlin and Asia/Shanghai is 6.0 hours. 11:53 ``` # Route Filter (/docs/semantic-router/v0/user-guide/features/route-filter) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 removes `route_filter`. The [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1#route_filter-is-gone) shows what to do instead. Sometimes you only want the router to consider *some* of its routes. Maybe context tells you the user is mid-conversation about one topic, or a certain route shouldn't fire in this part of your app. `route_filter` lets you narrow the field per call. Say your router has `politics`, `weather`, and `chitchat`. To consider only `chitchat` for one query: ```python sr("don't you love politics?", route_filter=["chitchat"]) ``` The router ignores every route not in the list. ## Full example [#full-example] [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/09-route-filter.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/09-route-filter.ipynb) ```python !pip install -qU semantic-router ``` Two routes to work with: ```python from semantic_router import Route politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` An encoder: ```python import os from getpass import getpass from semantic_router.encoders import CohereEncoder, OpenAIEncoder os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass( "Enter Cohere API Key: " ) # os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass( # "Enter OpenAI API Key: " # ) encoder = CohereEncoder() # encoder = OpenAIEncoder() ``` And the router: ```python from semantic_router import SemanticRouter sr = SemanticRouter(encoder=encoder, routes=routes) ``` Without a filter it behaves as usual: ```python sr("don't you love politics?") ``` ``` RouteChoice(name='politics', function_call=None, similarity_score=None) ``` ```python sr("how's the weather today?") ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` And an unrelated query returns `None`: ```python sr("I'm interested in learning about llama 2") ``` ``` RouteChoice(name=None, function_call=None, similarity_score=None) ``` ## Filtering [#filtering] Now restrict the router to `chitchat` and send it a political query: ```python sr("don't you love politics?", route_filter=["chitchat"]) ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` It comes back as `chitchat` — the query would normally match `politics`, but that route wasn't allowed, and `chitchat` still cleared its threshold. The other way round: ```python sr("how's the weather today?", route_filter=["politics"]) ``` ``` RouteChoice(name=None, function_call=None, similarity_score=None) ``` `None` this time. The weather query is nowhere near `politics`, so nothing passed the threshold. A filter narrows the candidates; it doesn't force a match. # Sync (/docs/semantic-router/v0/user-guide/features/sync) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 removes sync: the index is the single source of truth. The [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1#sync-is-gone) covers the change, and [indexes](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/components/indexes) how it works now. When you use a remote index like `PineconeIndex` or `QdrantIndex`, there are two copies of your routes: the ones in your `SemanticRouter` object, and the ones stored in the index. They can drift. Sync strategies decide which copy wins when they do. Getting this right matters most in distributed setups, where several processes share one index. Pick the right strategy and you avoid both wasted startup time and subtle routing bugs. ## The strategies [#the-strategies] * **`error`** — raise if local and remote differ. Use this when drift should never happen silently. * **`remote`** — remote is the source of truth. Overwrite local to match. * **`local`** — local is the source of truth. Overwrite remote to match. * **`merge-force-local`** — merge, with local winning. Remote utterances survive only if their route also exists locally; everything else is dropped. Where a route exists on both sides with different `function_schemas` or `metadata`, local's version wins and is written to remote. * **`merge-force-remote`** — the mirror image. Remote wins; local utterances survive only if their route exists remotely. * **`merge`** — merge both, combining utterances where a route name appears on both sides. On a conflict in `function_schemas` or `metadata`, local wins. You can apply a strategy two ways: automatically at startup with `auto_sync`, or on demand with `SemanticRouter.sync`. ## `auto_sync` at startup [#auto_sync-at-startup] Pass `auto_sync` when you create the router, and it reconciles with the index immediately. Note this adds to initialization time, since it has to compare and possibly write. ```python import os from semantic_router import Route, SemanticRouter from semantic_router.encoders import OpenAIEncoder from semantic_router.index import PineconeIndex os.environ["OPENAI_API_KEY"] = "" os.environ["PINECONE_API_KEY"] = "" politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] encoder = OpenAIEncoder() pc_index = PineconeIndex( region="us-east-1", index_name="sync-example", ) # make sure the index exists before the router tries to sync with it pc_index.index = pc_index._init_index(force_create=True) sr = SemanticRouter( encoder=encoder, routes=routes, index=pc_index, auto_sync="local", ) ``` Confirm the two sides agree: ```python sr.is_synced() ``` ## Checking sync [#checking-sync] `is_synced()` compares the routes, utterances, and metadata in your router against what's in the index. It works in two passes. **The fast check** hashes your local router — built from the encoder type and name, plus each route's name, utterances, description, function schemas, LLM, score threshold, and metadata — and compares it to the hash stored in the index. Matching hashes mean you're in sync, and it returns `True` straight away. **The slow check** only runs if the hashes differ. It rebuilds a `LayerConfig` from the remote index and compares it to the local one field by field. If those match, you're in sync after all. If not, something has genuinely drifted. To fix drift on demand, call `sync` with a strategy. It does exactly what `auto_sync` would do at startup. If your local router holds the ground truth, push it to the index: ```python sr.sync(sync_mode="local") ``` Run `sr.is_synced()` again and it should now return `True`. ## Seeing what drifted [#seeing-what-drifted] Often you'll want to know *why* things diverged before you overwrite anything. `get_utterance_diff` gives you a readable diff: ```python diff = sr.get_utterance_diff() ``` ```python ["- politics: don't you just hate the president", "- politics: don't you just love the president", "- politics: isn't politics the best thing ever", '- politics: they will save the country!', "- politics: they're going to destroy this country!", "- politics: why don't you tell me about your political opinions", '+ chitchat: how\'s the weather today?', '+ chitchat: how are things going?', '+ chitchat: lovely weather today', '+ chitchat: the weather is horrendous', '+ chitchat: let\'s go to the chippy'] ``` It lists every route in the remote index and compares it against your local routes. Anything that differs shows up here. For finer control, build an `UtteranceDiff` object from the two sets of utterances: ```python local_utterances = sr.to_config().to_utterances() remote_utterances = sr.index.get_utterances() diff = UtteranceDiff.from_utterances( local_utterances=local_utterances, remote_utterances=remote_utterances ) ``` Every `Utterance` in `diff.diff` carries a `diff_tag`: * `'+'` — exists in remote only. * `'-'` — exists in local only. * `' '` — exists in both. Pull out whichever set you want to inspect: ```python diff.get_tag("+") # remote only diff.get_tag("-") # local only diff.get_tag(" ") # both ``` Once you understand the drift and know which side should win, apply a strategy: ```python sr._execute_sync_strategy(sync_mode="local") ``` Then confirm: ```python sr.is_synced() ``` `True` means the two sides match again. # Threshold Optimization (/docs/semantic-router/v0/user-guide/features/threshold-optimization) > **You're reading the docs for Semantic Router 0.x.** Threshold optimization is now calibration in version 1.0: read [the v1 page](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/features/calibration), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. A route matches only if its similarity score beats its `score_threshold`. Score above it and the route is chosen. Fall below and either another route wins, or nothing does. That one number decides a lot, so it's worth getting right — but tuning it by hand is slow and fiddly. Instead, hand the router a few *(utterance, target route)* examples and let `fit` find the thresholds for you. It usually takes seconds and the improvement can be dramatic. `evaluate` tells you how well you're doing before and after. ## Full example [#full-example] [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/06-threshold-optimization.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/06-threshold-optimization) ```python !pip install -qU "semantic-router>=0.1.5" ``` ## Set up the router [#set-up-the-router] A `SemanticRouter` needs `routes` and an `encoder`. (If you use dynamic routes you'll also want an `llm`, or the OpenAI default.) Four routes to start: *politics*, *chitchat*, *mathematics*, and *biology*. ```python from semantic_router import Route # steer a chatbot away from politics politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) # switch to a more conversational prompt chitchat = Route( name="chitchat", utterances=[ "Did you watch the game last night?", "what's your favorite type of music?", "Have you read any good books lately?", "nice weather we're having", "Do you have any plans for the weekend?", ], ) # hand off to an agent with math tools mathematics = Route( name="mathematics", utterances=[ "can you explain the concept of a derivative?", "What is the formula for the area of a triangle?", "how do you solve a system of linear equations?", "What is the concept of a prime number?", "Can you explain the Pythagorean theorem?", ], ) # hand off to an agent with biology knowledge biology = Route( name="biology", utterances=[ "what is the process of osmosis?", "can you explain the structure of a cell?", "What is the role of RNA?", "What is genetic mutation?", "Can you explain the process of photosynthesis?", ], ) routes = [politics, chitchat, mathematics, biology] ``` We'll use the local `HuggingFaceEncoder`. `CohereEncoder`, `FastEmbedEncoder`, `OpenAIEncoder`, and `AzureOpenAIEncoder` all work too. ```python from semantic_router.encoders import HuggingFaceEncoder encoder = HuggingFaceEncoder() ``` ```python from semantic_router import SemanticRouter sr = SemanticRouter(encoder=encoder, routes=routes) ``` Out of the box it does reasonably well: ```python for utterance in [ "don't you love politics?", "how's the weather today?", "What's DNA?", "I'm interested in learning about llama 2", ]: print(f"{utterance} -> {sr(utterance).name}") ``` ``` don't you love politics? -> politics how's the weather today? -> chitchat What's DNA? -> biology I'm interested in learning about llama 2 -> None ``` ## Measure it [#measure-it] `evaluate` takes a list of utterances and their target routes and returns an accuracy: ```python test_data = [ ("don't you love politics?", "politics"), ("how's the weather today?", "chitchat"), ("What's DNA?", "biology"), ("I'm interested in learning about llama 2", None), ] X, y = zip(*test_data) accuracy = sr.evaluate(X=X, y=y) print(f"Accuracy: {accuracy*100:.2f}%") ``` ``` Generating embeddings: 100%|██████████| 1/1 [00:00<00:00, 76.91it/s] Accuracy: 100.00% ``` Perfect — on four examples. That's not a real test. Let's try a bigger, harder set. *Tip: an LLM is a quick way to generate test examples for your own routes. The more realistic they are, the more your accuracy number will reflect real-world performance.* ```python test_data = [ # politics ("What's your opinion on the current government?", "politics"), ("Who do you think will win the next election?", "politics"), ("What are your thoughts on the new policy?", "politics"), ("How do you feel about the political situation?", "politics"), ("Do you agree with the president's actions?", "politics"), ("What's your stance on the political debate?", "politics"), ("How do you see the future of our country?", "politics"), ("What do you think about the opposition party?", "politics"), ("Do you believe the government is doing enough?", "politics"), ("What's your opinion on the political scandal?", "politics"), ("Do you think the new law will make a difference?", "politics"), ("What are your thoughts on the political reform?", "politics"), ("Do you agree with the government's foreign policy?", "politics"), # chitchat ("What's the weather like?", "chitchat"), ("It's a beautiful day today.", "chitchat"), ("How's your day going?", "chitchat"), ("It's raining cats and dogs.", "chitchat"), ("Let's grab a coffee.", "chitchat"), ("What's up?", "chitchat"), ("It's a bit chilly today.", "chitchat"), ("How's it going?", "chitchat"), ("Nice weather we're having.", "chitchat"), ("It's a bit windy today.", "chitchat"), ("Let's go for a walk.", "chitchat"), ("How's your week been?", "chitchat"), ("It's quite sunny today.", "chitchat"), ("How are you feeling?", "chitchat"), ("It's a bit cloudy today.", "chitchat"), # mathematics ("What is the Pythagorean theorem?", "mathematics"), ("Can you solve this quadratic equation?", "mathematics"), ("What is the derivative of x squared?", "mathematics"), ("Explain the concept of integration.", "mathematics"), ("What is the area of a circle?", "mathematics"), ("How do you calculate the volume of a sphere?", "mathematics"), ("What is the difference between a vector and a scalar?", "mathematics"), ("Explain the concept of a matrix.", "mathematics"), ("What is the Fibonacci sequence?", "mathematics"), ("How do you calculate permutations?", "mathematics"), ("What is the concept of probability?", "mathematics"), ("Explain the binomial theorem.", "mathematics"), ("What is the difference between discrete and continuous data?", "mathematics"), ("What is a complex number?", "mathematics"), ("Explain the concept of limits.", "mathematics"), # biology ("What is photosynthesis?", "biology"), ("Explain the process of cell division.", "biology"), ("What is the function of mitochondria?", "biology"), ("What is DNA?", "biology"), ("What is the difference between prokaryotic and eukaryotic cells?", "biology"), ("What is an ecosystem?", "biology"), ("Explain the theory of evolution.", "biology"), ("What is a species?", "biology"), ("What is the role of enzymes?", "biology"), ("What is the circulatory system?", "biology"), ("Explain the process of respiration.", "biology"), ("What is a gene?", "biology"), ("What is the function of the nervous system?", "biology"), ("What is homeostasis?", "biology"), ("What is the difference between a virus and a bacteria?", "biology"), ("What is the role of the immune system?", "biology"), # some None examples, so thresholds don't collapse to zero ("What is the capital of France?", None), ("how many people live in the US?", None), ("when is the best time to visit Bali?", None), ("how do I learn a language", None), ("tell me an interesting fact", None), ("what is the best programming language?", None), ("I'm interested in learning about llama 2", None), ] ``` ```python X, y = zip(*test_data) accuracy = sr.evaluate(X=X, y=y) print(f"Accuracy: {accuracy*100:.2f}%") ``` ``` Generating embeddings: 100%|██████████| 1/1 [00:00<00:00, 9.23it/s] Accuracy: 34.85% ``` Ouch. The good news: this is easy to fix. ## Optimize the thresholds [#optimize-the-thresholds] Optimization finds the best `score_threshold` for each route. First, look at the defaults: ```python route_thresholds = sr.get_thresholds() print("Default route thresholds:", route_thresholds) ``` ``` Default route thresholds: {'politics': 0.5, 'chitchat': 0.5, 'mathematics': 0.5, 'biology': 0.5} ``` Every route sits at 0.5. Now call `fit` with your training utterances `X` and labels `y`: ```python sr.fit(X=X, y=y) ``` ``` Generating embeddings: 100%|██████████| 1/1 [00:00<00:00, 9.21it/s] Training: 100%|██████████| 500/500 [00:01<00:00, 419.45it/s, acc=0.89] ``` The thresholds have moved a lot: ```python route_thresholds = sr.get_thresholds() print("Updated route thresholds:", route_thresholds) ``` ``` Updated route thresholds: {'politics': 0.05050505050505051, 'chitchat': 0.32323232323232326, 'mathematics': 0.18181818181818182, 'biology': 0.21212121212121213} ``` Don't read too much into the absolute values. The right thresholds depend heavily on the encoder — OpenAI's `text-embedding-ada-002`, for instance, tends to land in the `0.5` to `0.8` range with this library. That's exactly why fitting beats guessing. The result: ```python accuracy = sr.evaluate(X=X, y=y) print(f"Accuracy: {accuracy*100:.2f}%") ``` ``` Generating embeddings: 100%|██████████| 1/1 [00:00<00:00, 8.89it/s] Accuracy: 89.39% ``` From 35% to 89%, in about a second. To push further, the next lever is your routes themselves: add more utterances, look at *which* examples still fail, and reshape the routes around them. That's more hands-on than `fit`, but it's how you squeeze out the last few points. # Configuration (/docs/semantic-router/v0/user-guide/guides/configuration) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/configuration), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. # Configuration [#configuration] ## Logging [#logging] Semantic Router uses Python's standard `logging` module. You control how much it says with an environment variable. ### Setting the log level [#setting-the-log-level] Two variables work. Set the library-specific one if you can: ```bash export SEMANTIC_ROUTER_LOG_LEVEL=DEBUG ``` Or use the general one, which other libraries may share: ```bash export LOG_LEVEL=WARNING ``` `SEMANTIC_ROUTER_LOG_LEVEL` wins if both are set. If neither is, the level is `INFO`. ### Levels [#levels] * `DEBUG` — detailed diagnostics. * `INFO` — general progress (the default). * `WARNING` — something looks off but still works. * `ERROR` — something failed. * `CRITICAL` — something failed badly. ### From Python [#from-python] Set the variable *before* importing the library: ```python import os os.environ["SEMANTIC_ROUTER_LOG_LEVEL"] = "DEBUG" from semantic_router import Route, SemanticRouter # debug logs now show ``` Turn on `DEBUG` when you're chasing an encoder or index problem, want to see why a query matched the route it did, or need to understand what the library is doing under the hood. # Local Execution (/docs/semantic-router/v0/user-guide/guides/local-execution) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/local-execution), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. Plenty of reasons to run your own LLM instead of calling an API — cost, privacy, compliance. Semantic Router supports local LLMs through `llama.cpp`. `llama.cpp` also runs quantized GGUF models, which shrink memory use enough that even a 13B-parameter model runs with hardware acceleration on an Apple M1 Pro. ## Full example [#full-example] [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb) We'll use **Mistral-7B-Instruct**, quantized to 4-bit to keep the memory footprint small. ## Install [#install] > For hardware acceleration (BLAS, CUDA, Metal, and so on), see the [llama-cpp-python README](https://github.com/abetlen/llama-cpp-python#installation-with-specific-hardware-acceleration-blas-cuda-metal-etc). ```python pip install -qU "semantic-router[local]" ``` On Apple silicon, compile with Metal acceleration: ```bash CMAKE_ARGS="-DLLAMA_METAL=on" pip install -qU "semantic-router[local]" ``` ## Download the model [#download-the-model] Mistral 7B Instruct as a 4-bit GGUF is a good balance of quality and consumer-hardware friendliness: ```python !curl -L "https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_0.gguf?download=true" -o ./mistral-7b-instruct-v0.2.Q4_0.gguf !ls mistral-7b-instruct-v0.2.Q4_0.gguf ``` ## Define the routes [#define-the-routes] We'll include a dynamic route so the local LLM has some function calling to do: ```python from datetime import datetime from zoneinfo import ZoneInfo from semantic_router import Route from semantic_router.utils.function_call import get_schema def get_time(timezone: str) -> str: """Finds the current time in a specific timezone. :param timezone: The timezone to find the current time in, should be a valid timezone from the IANA Time Zone Database like "America/New_York" or "Europe/London". Do NOT put the place name itself like "rome", or "new york", you must provide the IANA format. :type timezone: str :return: The current time in the specified timezone.""" now = datetime.now(ZoneInfo(timezone)) return now.strftime("%H:%M") time_schema = get_schema(get_time) time = Route( name="get_time", utterances=[ "what is the time in new york city?", "what is the time in london?", "I live in Rome, what time is it?", ], function_schemas=[time_schema], ) politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat, time] ``` ## Encoder [#encoder] To stay fully local we'll use `HuggingFaceEncoder`, which defaults to `sentence-transformers/all-MiniLM-L6-v2`: ```python from semantic_router.encoders import HuggingFaceEncoder encoder = HuggingFaceEncoder() ``` ## The `llama.cpp` LLM [#the-llamacpp-llm] Create a `llama_cpp.Llama` and wrap it in `LlamaCppLLM`. Three parameters worth knowing: * `n_gpu_layers` — how many layers to offload to the GPU. `-1` for the whole model, `0` for CPU only. * `n_ctx` — the context window. Capped by the model's own limit (8000 tokens for Mistral-7B-Instruct). * `verbose` — set `False` to quiet `llama.cpp`'s output. > The [llama-cpp-python API reference](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/) covers the rest. ```python from semantic_router import SemanticRouter from llama_cpp import Llama from semantic_router.llms.llamacpp import LlamaCppLLM enable_gpu = True # offload to GPU (the model must fit in memory) _llm = Llama( model_path="./mistral-7b-instruct-v0.2.Q4_0.gguf", n_gpu_layers=-1 if enable_gpu else 0, n_ctx=2048, ) _llm.verbose = False llm = LlamaCppLLM(name="Mistral-7B-v0.2-Instruct", llm=_llm, max_tokens=None) router = SemanticRouter(encoder=encoder, routes=routes, llm=llm) ``` ## Try it [#try-it] A static route first: ```python router("how's the weather today?") ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` Now a time question, which triggers the dynamic route and the local LLM: ```python out = router("what's the time in New York right now?") print(out) get_time(**out.function_call[0]) ``` ``` name='get_time' function_call=[{'timezone': 'America/New_York'}] similarity_score=None '07:50' ``` A couple more: ```python out = router("what's the time in Rome right now?") print(out) get_time(**out.function_call[0]) ``` ``` name='get_time' function_call=[{'timezone': 'Europe/Rome'}] similarity_score=None '13:51' ``` ```python out = router("what's the time in Bangkok right now?") print(out) get_time(**out.function_call[0]) ``` ``` name='get_time' function_call=[{'timezone': 'Asia/Bangkok'}] similarity_score=None '18:51' ``` All local, no API calls. ## Cleanup [#cleanup] Delete the model when you're done: ```bash rm ./mistral-7b-instruct-v0.2.Q4_0.gguf ``` # Migration to v0 1 (/docs/semantic-router/v0/user-guide/guides/migration-to-v0-1) > **You're reading the docs for Semantic Router 0.x.** This guide covers 0.0.x to 0.1. The [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) covers upgrading from 0.x to 1.0. v0.1 reworked the API and added new capabilities. Some of those changes are breaking. This guide covers what moved, what got renamed, and how to update your code. ## Key API changes [#key-api-changes] ### `RouteLayer` is now `SemanticRouter` [#routelayer-is-now-semanticrouter] ```python # before from semantic_router import RouteLayer # after from semantic_router.routers import SemanticRouter ``` The class was renamed and moved into the `routers` module. Same job, clearer name, and it fits the modular layout alongside `HybridRouter`. ### `add` takes a list [#add-takes-a-list] `add` now accepts a list of routes. A single route still works. ```python # before route_layer = RouteLayer(encoder=encoder) route_layer.add(route1) route_layer.add(route2) # after semantic_router = SemanticRouter(encoder=encoder) semantic_router.add([route1, route2]) # several at once semantic_router.add(route3) # one still works ``` ### `retrieve_multiple_routes` is gone — use `limit` [#retrieve_multiple_routes-is-gone--use-limit] To get more than one route back, call the router with a `limit`: ```python # before (v0.0.x) route_layer = RouteLayer(encoder=encoder, routes=routes) multiple_routes = route_layer.retrieve_multiple_routes(query_text) # transitional (v0.1.0–0.1.2) — deprecated, not recommended semantic_router = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") query_results = semantic_router._query(query_text) multiple_routes = semantic_router._semantic_classify_multiple_routes(query_results) # after (v0.1.3+, 0.1.5+ recommended) semantic_router = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") all_routes = semantic_router(query_text, limit=None) # every route that passes its threshold top_routes = semantic_router(query_text, limit=3) # the top 3 that pass # to score every route regardless of threshold semantic_router.set_threshold(threshold=0.0) all_route_scores = semantic_router(query_text, limit=None) ``` With `limit=1` (the default) you get a single `RouteChoice`. With `limit=None` or `limit > 1` you get a list. > **Watch `top_k`.** It defaults to 5 and caps how many routes come back, independently of `limit`. If you use `limit > 1`, raise `top_k` — 100 or more is reasonable. If you use `limit=None` to get everything, set `top_k` to at least the total number of utterances across all your routes. > > ```python > semantic_router = SemanticRouter(encoder=encoder, routes=routes, top_k=100) > all_routes = semantic_router(query_text, limit=None) > ``` ### Sync is now explicit [#sync-is-now-explicit] If you expect local and remote routes to sync at startup, say so with `auto_sync`: ```python semantic_router = SemanticRouter( encoder=encoder, routes=routes, index=PineconeIndex(...), auto_sync="local", # push local routes to the remote index ) ``` The modes: * `error` — raise if local and remote differ. * `remote` — remote wins; update local. * `local` — local wins; update remote. * `merge-force-local` — merge, local takes priority. * `merge-force-remote` — merge, remote takes priority. * `merge` — merge, local wins on conflicts. The [sync guide](../features/sync) explains each in depth. ## Other changes [#other-changes] ### `RouterConfig` replaces `LayerConfig` [#routerconfig-replaces-layerconfig] ```python from semantic_router.routers import RouterConfig config = RouterConfig( routes=[route1, route2], encoder_type="openai", encoder_name="text-embedding-3-small", ) semantic_router = SemanticRouter.from_config(config) ``` ### More router types [#more-router-types] The modular layout exposes: * `SemanticRouter` — the standard router (the old `RouteLayer`). * `HybridRouter` — dense plus sparse embeddings. * `BaseRouter` — an abstract base for your own routers. ## Before and after [#before-and-after] ```python # before (v0.0.x) from semantic_router import RouteLayer, Route from semantic_router.encoders import OpenAIEncoder route = Route(name="example", utterances=["sample utterance"]) layer = RouteLayer(encoder=OpenAIEncoder()) layer.add(route) result = layer("query text") # after (v0.1.x) from semantic_router import Route from semantic_router.routers import SemanticRouter from semantic_router.encoders import OpenAIEncoder route = Route(name="example", utterances=["sample utterance"]) router = SemanticRouter(encoder=OpenAIEncoder()) router.add(route) result = router("query text") ``` # Save Load from File (/docs/semantic-router/v0/user-guide/guides/save-load-from-file) > **You're reading the docs for Semantic Router 0.x.** Version 1.0 is out: read [this page for v1](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/save-load-from-file), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. You can save a router to a file and load it back later — useful for shipping the same routes between environments, or just for not rebuilding them every time. JSON and YAML both work. ```python # JSON router.to_json("router.json") new_router = SemanticRouter.from_json("router.json") # YAML router.to_yaml("router.yaml") new_router = SemanticRouter.from_yaml("router.yaml") ``` The file holds everything needed to recreate the router. If you use a remote index, the [sync features](../features/sync) keep the loaded router and the index in step. ## Full example [#full-example] [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/01-save-load-from-file.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/01-save-load-from-file.ipynb) ```bash !pip install -qU semantic-router ``` ## Build a router [#build-a-router] ```python from semantic_router import Route politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` ```python import os from getpass import getpass from semantic_router import SemanticRouter from semantic_router.encoders import CohereEncoder # dashboard.cohere.ai os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass( "Enter Cohere API Key: " ) encoder = CohereEncoder() router = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") ``` Quick check that it works: ```python router("isn't politics the best thing ever") ``` ``` RouteChoice(name='politics', function_call=None, similarity_score=None) ``` ```python router("how's the weather today?") ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` ## Save it [#save-it] ```python router.to_json("router.json") ``` ## Load it [#load-it] Have a look at what got saved: ```python import json with open("router.json", "r") as f: router_json = json.load(f) print(router_json) ``` Encoder type, encoder name, and the routes — everything a new router needs. Load it with `from_json`: ```python router = SemanticRouter.from_json("router.json") ``` Confirm it came back intact: ```python print( f"""{router.encoder.type=} {router.encoder.name=} {router.routes=}""" ) ``` And that it still routes: ```python router("isn't politics the best thing ever") ``` ``` RouteChoice(name='politics', function_call=None, similarity_score=None) ``` ```python router("how's the weather today?") ``` ``` RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` # Semantic Router (/docs/semantic-router/v0/user-guide/guides/semantic-router) > **You're reading the docs for Semantic Router 0.x.** `SemanticRouter` is now `IndexedRouter` in version 1.0: read [the v1 page](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/components/routers), or the [migration guide](https://docs.aurelio.ai/docs/semantic-router/v1/user-guide/guides/migration-to-v1) to upgrade. The `SemanticRouter` is the heart of the library. Give it a query and it decides which route to take. It's built from three things: an `encoder`, an `index`, and a list of `routes`. If any of your routes are dynamic (they produce function calls), it also holds an `llm`. ## Routes [#routes] Start with some routes: ```python from semantic_router import Route politics = Route( name="politics", utterances=[ "isn't politics the best thing ever", "why don't you tell me about your political opinions", "don't you just love the president", "don't you just hate the president", "they're going to destroy this country!", "they will save the country!", ], ) chitchat = Route( name="chitchat", utterances=[ "how's the weather today?", "how are things going?", "lovely weather today", "the weather is horrendous", "let's go to the chippy", ], ) routes = [politics, chitchat] ``` ## Encoder [#encoder] There are plenty of encoders to choose from, local and API-based. We'll use `OpenAIEncoder` here: ```python import os from semantic_router.encoders import OpenAIEncoder os.environ["OPENAI_API_KEY"] = "" encoder = OpenAIEncoder() ``` ## The router [#the-router] Pass in the encoder and routes. When you call the router with a query, it returns the `Route` the query belongs to. ```python from semantic_router import SemanticRouter sr = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") ``` ```python sr("don't you love politics?") ``` ``` [Out]: RouteChoice(name='politics', function_call=None, similarity_score=None) ``` You get back a `RouteChoice`. It holds the route name, any function call (for dynamic routes), and the similarity score that triggered the match. ```python sr("how's the weather today?") ``` ``` [Out]: RouteChoice(name='chitchat', function_call=None, similarity_score=None) ``` Both right. Now something that matches neither route: ```python sr("I'm interested in learning about llama 3") ``` ``` [Out]: RouteChoice(name=None, function_call=None, similarity_score=None) ``` No route cleared its threshold, so `name` is `None`. ## Getting more than one route [#getting-more-than-one-route] By default the router returns the single best match. Pass `limit` to get several, each with its score. `limit=None` returns every route that passes its threshold; `limit=3` returns the top three. ```python sr("Hi! How are you doing in politics??", limit=None) ``` ``` [Out]: [RouteChoice(name='politics', function_call=None, similarity_score=0.859), RouteChoice(name='chitchat', function_call=None, similarity_score=0.835)] ``` If nothing passes, you get an empty list: ```python sr("I'm interested in learning about llama 3", limit=None) ``` ``` [Out]: [] ``` > One thing to watch: `top_k` (default 5) caps how many routes are considered, independently of `limit`. If you're using `limit > 1` or `limit=None`, raise `top_k` — for example `SemanticRouter(..., top_k=100)`. The [introductory notebook](https://github.com/aurelio-labs/semantic-router/blob/main/docs/00-introduction.ipynb) walks through all of this end to end. # Semantic Chunkers (/docs/semantic-chunkers) Chunk documents by meaning for better retrieval. ## Sections [#sections] * [Get Started](/docs/semantic-chunkers/get-started/encoders) # Encoders (/docs/semantic-chunkers/get-started/encoders) An encoder turns text into vectors. The chunkers compare those vectors to decide where to split, and that is the only thing they ask of an encoder: ```python class MyEncoder: def __call__(self, docs): ... # one vector per document async def acall(self, docs): ... # the same, without blocking ``` Anything with those two methods works. There is nothing to inherit from. ## OpenAI [#openai] `OpenAIEncoder` ships with the library — no extra to install, and no `openai` package: ```python import os from semantic_chunkers import OpenAIEncoder, StatisticalChunker os.environ["OPENAI_API_KEY"] = "" encoder = OpenAIEncoder() # text-embedding-3-small chunker = StatisticalChunker(encoder=encoder) ``` The key comes from `api_key=` or `OPENAI_API_KEY`. Requests go out in batches of 100 documents, and a rate limit or a server fault is retried, waiting as long as the `Retry-After` header asks for. ### Azure and OpenAI-compatible endpoints [#azure-and-openai-compatible-endpoints] Point `base_url` at any service that speaks the `/embeddings` API — Azure OpenAI, vLLM, Ollama, a gateway of your own. It also reads `OPENAI_BASE_URL`: ```python encoder = OpenAIEncoder( name="text-embedding-3-large", base_url="https://my-resource.openai.azure.com/openai/v1", dimensions=256, ) ``` ## A local model [#a-local-model] `LocalEncoder` runs sentence-transformers on your machine, so there is no key and no per-call cost. It is behind an extra because torch and the weights are around 2 GB: ```bash pip install -qU "semantic-chunkers[local]" ``` ```python from semantic_chunkers import LocalEncoder, StatisticalChunker chunker = StatisticalChunker(encoder=LocalEncoder("all-MiniLM-L6-v2")) ``` ## Anything else [#anything-else] If you already have a function that embeds a list of strings, wrap it. `CallableEncoder` supplies the async path by running your function in a worker thread: ```python from semantic_chunkers import CallableEncoder, StatisticalChunker encoder = CallableEncoder(lambda docs: my_model.embed(docs), name="my-model") chunker = StatisticalChunker(encoder=encoder) ``` Encoders from other libraries, including Semantic Router's, already have `__call__` and `acall`, so they plug straight in: ```python from semantic_router.encoders import CohereEncoder # pip install semantic-router chunker = StatisticalChunker(encoder=CohereEncoder()) ``` ## When the async path is missing [#when-the-async-path-is-missing] Not every encoder has one. If yours has no `acall`, `chunker.acall(...)` raises `EncoderError` naming it, rather than failing somewhere inside the chunker: ```python chunks = await chunker.acall(docs=[...]) # EncoderError: MyEncoder has no usable acall(), so this chunker cannot run # asynchronously. Give it an `async def acall(self, docs)`, call the chunker # synchronously, or wrap it: CallableEncoder(encoder) runs the synchronous # call in a thread. ``` # Introduction (/docs/semantic-chunkers/get-started/introduction) Semantic Chunkers splits text into chunks based on *meaning*. Instead of cutting every N characters or at every newline, it uses an embedding model to find the places where the topic actually shifts — and splits there. That matters most for retrieval. A chunk that starts mid-thought and ends mid-thought is a bad search result. A chunk that holds one coherent idea is a good one. Better chunks mean better RAG. ## How it works [#how-it-works] The library splits a document into sentences, embeds them, and looks at how similar each sentence is to its neighbours. Where similarity drops, a new chunk begins. You choose how that decision gets made: * **`StatisticalChunker`** — the most robust option and the one to start with. It sets the similarity threshold dynamically per document, so it adapts to the text instead of relying on a fixed number. Text only. * **`ConsecutiveChunker`** — the simplest. Groups consecutive sentences while they stay above a fixed similarity threshold. Works on more than just text. * **`CumulativeChunker`** — accumulates sentences and compares each new one against everything gathered so far. More stable and noise-resistant, but the most expensive in time and, with API encoders, money. * **`RegexChunker`** — no embeddings at all. Splits on delimiters up to a token budget. Fast and free, for when semantics don't matter. The semantic chunkers take any [encoder](encoders) — the OpenAI one that ships with the library, a local sentence-transformers model, an embedding function of your own, or an encoder from another library such as [Semantic Router](../../semantic-router). ## Start here [#start-here] The [quickstart](quickstart) chunks a document in a few lines and compares the strategies. ## Resources [#resources] * [GitHub repository](https://github.com/aurelio-labs/semantic-chunkers) # Quickstart (/docs/semantic-chunkers/get-started/quickstart) Install the library: ```bash pip install -qU semantic-chunkers ``` That is the whole install. The OpenAI encoder comes with it. ## Pick an encoder and a chunker [#pick-an-encoder-and-a-chunker] The encoder turns sentences into vectors. The chunker uses those vectors to decide where to split. We'll use OpenAI for the encoder and `StatisticalChunker` — the best default for text. ```python import os from semantic_chunkers import OpenAIEncoder, StatisticalChunker os.environ["OPENAI_API_KEY"] = "" encoder = OpenAIEncoder() chunker = StatisticalChunker(encoder=encoder) ``` Prefer a local model, another provider, or a function of your own? See [encoders](encoders). Anything with `__call__(docs)` and `acall(docs)` works, so encoders from other libraries — Semantic Router's included — plug in unchanged. ## Chunk a document [#chunk-a-document] Pass a list of documents. You get back a list of chunks for each one: ```python chunks = chunker(docs=["your long document text goes here..."]) ``` `chunks[0]` is the list of `Chunk` objects for the first document. Each holds its `splits` (the sentences it contains), a `token_count`, and — for the semantic chunkers — the `triggered_score` that caused the split. To see them at a glance: ```python chunker.print(chunks[0]) ``` ## Find a chunk in the document [#find-a-chunk-in-the-document] `content` is the document's own text, whitespace and all, and `start` and `end` are where that text sits in it: ```python doc = "Alpha one.\n\n Alpha two. Beta one." chunks = chunker(docs=[doc])[0] first = chunks[0] first.content # the document from first.start to first.end doc[first.start : first.end] == first.content # True "".join(chunk.content for chunk in chunks) == doc # True ``` Because the chunks of a document join back into that document, you can highlight a chunk where it was found, or store an offset instead of a copy of the text. The `splits` stay stripped, so use `content` when you want the layout and `splits` when you want the sentences. A chunk the library could not place in a document — one you built yourself, or one whose splits are video frames rather than text — has `content`, `start` and `end` set to `None`. ## Go async [#go-async] Chunking embeds a lot of sentences, so the async path is dramatically faster when you're calling an API. Every chunker has `acall`: ```python chunks = await chunker.acall(docs=["your long document text goes here..."]) ``` The [async notebook](https://github.com/aurelio-labs/semantic-chunkers/blob/main/docs/02-chunkers-async.ipynb) shows it running around 40× faster. ## The strategies [#the-strategies] Four chunkers, each a different way of deciding where to split. ```python from semantic_chunkers import ( StatisticalChunker, ConsecutiveChunker, CumulativeChunker, RegexChunker, ) # adaptive threshold per document; the recommended default for text chunker = StatisticalChunker(encoder=encoder) # fixed similarity threshold between neighbouring sentences chunker = ConsecutiveChunker(encoder=encoder, score_threshold=0.45) # compares each new sentence to the whole chunk so far; stable but expensive chunker = CumulativeChunker(encoder=encoder, score_threshold=0.45) # no encoder; splits on delimiters up to a token budget chunker = RegexChunker(max_chunk_tokens=300) ``` **Statistical** is where to start. It picks its threshold from the document itself, so you rarely need to tune it. Its most useful knobs are `min_split_tokens` (default 100) and `max_split_tokens` (default 300), which bound chunk size. **Consecutive** is the simplest and cheapest semantic option, and unlike Statistical it can work on more than text. Lower `score_threshold` for bigger chunks, raise it for smaller ones. The default is 0.45. **Cumulative** is the most stable on noisy text, because each decision considers the whole chunk so far — but that means far more embedding calls. Reach for it when quality matters more than cost. **Regex** skips embeddings entirely. Use it when you just need size-bounded splits and don't care about semantics, or as a fast first pass. ## Next steps [#next-steps] Try each strategy on your own documents and compare the chunks. The [intro notebook](https://github.com/aurelio-labs/semantic-chunkers/blob/main/docs/00-chunkers-intro.ipynb) runs all of them side by side. # GraphAI (/docs/graphai) Build async, graph-based AI workflows and agents. ## Sections [#sections] * [Get Started](/docs/graphai/get-started/introduction) * [Client Reference](/docs/graphai/client-reference/callback) * [User Guide](/docs/graphai/user-guide/faqs) # Introduction (/docs/graphai/get-started/introduction) GraphAI is a minimal "AI framework" that tries hard not to be one. It gives you a small, flexible graph runtime — nodes, edges, routers, state, streaming — and then gets out of the way. You build the agent, the LLM wrapper, the memory, exactly how you want them. ## What you get [#what-you-get] GraphAI is built around a computational graph. It provides: 1. A **graph-based architecture** for wiring components into a workflow. 2. An **async-first design**, so waiting on API calls doesn't waste compute. 3. **Minimal abstractions** — no baked-in notion of "LLM" or "Agent" to fight against. 4. **Callbacks** for streaming and communication between components. Other libraries ship their own idea of what an LLM, an agent, or a tool should look like. GraphAI doesn't. It hands you the primitives and lets you define those concepts yourself. ## Why [#why] Most AI frameworks impose a shape on your application. That shape becomes a local minimum: fine right up until you need something the framework didn't anticipate. GraphAI takes the opposite stance. * **Bring your own components.** Any LLM provider, any agent design, any telemetry. * **Build the workflow you actually need**, not the one the framework assumes. * **Think in flow, not framework.** Focus on how data moves through your app. ## The core ideas [#the-core-ideas] **Async-first.** AI apps spend most of their time waiting on APIs. GraphAI is async from the ground up, so your code stays busy while responses are in flight. **A graph of nodes.** Nodes do the work. Edges say where data flows next. Routers are nodes that choose the next path. Complex workflows stay readable because the structure *is* the diagram. **Only what you need.** A `Graph` to orchestrate, `@node` and `@router` to define steps, a callback for streaming, and a state dict for context. That's the whole surface. ## When to reach for it [#when-to-reach-for-it] GraphAI fits when: * You want full control over your architecture. * Existing frameworks feel too opinionated. * You're mixing components from different ecosystems. * You prefer explicit code over magic. * You're building something that doesn't fit the usual patterns. Ready? The [quickstart](quickstart) builds a working agent in a few minutes. # Quickstart (/docs/graphai/get-started/quickstart) Let's build a small LLM-powered agent with GraphAI and the OpenAI API. By the end you'll have an agent that: 1. Decides whether to search for information or pull it from memory. 2. Runs the chosen action. 3. Writes a response to the user. ## Prerequisites [#prerequisites] * Python 3.10+ * An OpenAI API key * Some familiarity with async Python ## Install [#install] ```bash pip install graphai-lib semantic-router ``` This example uses semantic-router's `OpenAILLM` for the LLM calls. GraphAI itself doesn't depend on it — swap in any client you like. ## Set up [#set-up] ```python import os from getpass import getpass import ast from graphai import router, node, Graph from semantic_router.llms import OpenAILLM from semantic_router.schema import Message from pydantic import BaseModel, Field import openai os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass("Enter OpenAI API Key: ") llm = OpenAILLM(name="gpt-4o-2024-08-06") # use your preferred model ``` ## Describe the tools [#describe-the-tools] Two Pydantic models describe the agent's options. The LLM will pick one. ```python class Search(BaseModel): query: str = Field(description="Search query for internet information") class Memory(BaseModel): query: str = Field(description="Self-directed query to search information from your long-term memory") ``` ## Define the nodes [#define-the-nodes] Everything in GraphAI is a node: an async function that takes some input and returns a dict. A quick word on how data moves, because it shapes every node you write: The dict you pass to `graph.execute()` *is* the graph's state. Each node receives only the parameters it declares, looked up by name from that state. So a node with an `input` parameter gets `state["input"]`, and a node with an `output` parameter gets `state["output"]`. Whatever a node returns is merged back into the state. We'll keep the user's request under an `input` key throughout. ```python @node(start=True) async def node_start(input: dict): """Entry point for our graph.""" return {"input": input} @router async def node_router(input: dict): """Routes the query to either search or memory.""" query = input["query"] messages = [ Message( role="system", content="You are a helpful assistant. Select the best route to answer the user query. ONLY choose one function.", ), Message(role="user", content=query), ] response = llm( messages=messages, function_schemas=[ openai.pydantic_function_tool(Search), openai.pydantic_function_tool(Memory), ], ) choice = ast.literal_eval(response)[0] return { "choice": choice["function_name"].lower(), "input": {**input, **choice["arguments"]}, } @node async def memory(input: dict): """Retrieves information from memory.""" # a real implementation would query a vector database return {"input": {"text": "The user is in Bali right now.", **input}} @node async def search(input: dict): """Searches for information.""" # a real implementation would call a search API return { "input": { "text": "The most famous photo spot in Bali is the Uluwatu Temple.", **input, } } @node async def llm_node(input: dict): """Generates a response using the retrieved information.""" chat_history = [ Message(role=message["role"], content=message["content"]) for message in input["chat_history"] ] messages = [ Message(role="system", content="You are a helpful assistant."), *chat_history, Message( role="user", content=( f"Response to the following query from the user: {input['query']}\n" "Here is additional context. You can use it to answer the user query. " f"But do not directly reference it: {input.get('text', '')}." ), ), ] response = llm(messages=messages) return {"output": response} @node(end=True) async def node_end(output: str): """Exit point for our graph.""" return {"output": output} ``` Notice the router. It returns a `"choice"` — the name of the node to run next — alongside the updated `input`. That's all a router needs to do. And notice `node_end` declares `output`, not `input`, because the value it wants lives at `state["output"]` (that's what `llm_node` returned). ## Wire up the graph [#wire-up-the-graph] ```python graph = Graph() graph.add_node(node_start) graph.add_node(node_router) graph.add_node(memory) graph.add_node(search) graph.add_node(llm_node) graph.add_node(node_end) graph.add_edge(node_start, node_router) # start -> router graph.add_edge(search, llm_node) # search -> llm graph.add_edge(memory, llm_node) # memory -> llm graph.add_edge(llm_node, node_end) # llm -> end # the router needs no outgoing edges: its "choice" picks the next node ``` ## Run it [#run-it] ```python import asyncio async def run_agent(): input_data = { "query": "What's the best photo spot in Bali?", "chat_history": [ {"role": "user", "content": "I'm planning a trip to Bali."}, {"role": "assistant", "content": "That's wonderful! Bali is a beautiful destination with rich culture, stunning beaches, and vibrant scenery. How can I help with your trip planning?"}, ], } result = await graph.execute(input={"input": input_data}) print(result["output"]) asyncio.run(run_agent()) ``` ## What just happened [#what-just-happened] 1. `node_start` took the request and stored it under `input`. 2. `node_router` asked the LLM whether to search or use memory, and returned that as its `choice`. 3. The chosen node — `search` or `memory` — added context to `input`. 4. `llm_node` wrote a response and stored it under `output`. 5. `node_end` returned it. Swap out any node and the rest of the graph doesn't care. That's the point: change what a step does without changing the shape of the whole thing. # graphai.callback (/docs/graphai/client-reference/callback) ## GraphEvent Objects [#graphevent-objects] ```python @dataclass class GraphEvent() ``` A graph event emitted for specific graph events such as start node or end node, and used by the callback to emit user-defined events. **Arguments**: * `type` (`GraphEventType | str`): The type of event, can be start\_node, end\_node, callback, or a custom str. * `identifier` (`str`): The identifier of the event, this is set typically by a callback handler and can be used to distinguish between different events. For example, a conversation/session ID could be used. * `token` (`str | None`): The token associated with the event, such as LLM streamed output. * `params` (`dict[str, Any] | None`): The parameters associated with the event, such as tool call parameters or event metadata. #### encode [#encode] ```python def encode(charset: str = "utf-8") -> bytes ``` Encodes the event as a JSON string, important for compatability with FastAPI and starlette. **Arguments**: * `charset` (`str`): The character set to use for encoding the event. ## CallbackProtocol Objects [#callbackprotocol-objects] ```python @runtime_checkable class CallbackProtocol(Protocol) ``` Protocol defining the interface for callback handlers. ## Callback Objects [#callback-objects] ```python class Callback() ``` The original callback handler class. Outputs a stream of structured text tokens. It is recommended to use the newer `EventCallback` handler instead. #### aiter [#aiter] ```python async def aiter() -> AsyncIterator[str] ``` Used by receiver to get the tokens from the stream queue. Creates a generator that yields tokens from the queue until the END token is received. #### start\_node [#start_node] ```python async def start_node(node_name: str, active: bool = True) ``` Starts a new node and emits the start token. #### end\_node [#end_node] ```python async def end_node(node_name: str) ``` Emits the end token for the current node. #### close [#close] ```python async def close() ``` Close the stream and prevent further tokens from being added. This will send an END token and set the done flag to True. ## EventCallback Objects [#eventcallback-objects] ```python class EventCallback() ``` The event callback handler class. Outputs a stream of structured text tokens. It is recommended to use the newer `EventCallback` handler instead. #### \_\_call\_\_ [#__call__] ```python def __call__(token: str | None = None, type: GraphEventType | str = GraphEventType.CALLBACK, identifier: str | None = None, params: dict[str, Any] | None = None) ``` Builds a GraphEvent object and adds it to the queue. #### acall [#acall] ```python async def acall(token: str | None = None, type: GraphEventType | str = GraphEventType.CALLBACK, identifier: str | None = None, params: dict[str, Any] | None = None) ``` Builds a GraphEvent object and adds it to the queue. #### aiter [#aiter-1] ```python async def aiter() -> AsyncIterator[GraphEvent] ``` Used by receiver to get the tokens from the stream queue. Creates a generator that yields tokens from the queue until the END token is received. #### start\_node [#start_node-1] ```python async def start_node(node_name: str, active: bool = True) ``` Starts a new node and emits the start token. #### end\_node [#end_node-1] ```python async def end_node(node_name: str) ``` Emits the end token for the current node. #### close [#close-1] ```python async def close() ``` Close the stream and prevent further tokens from being added. This will send an END token and set the done flag to True. # graphai.graph (/docs/graphai/client-reference/graph) ## MaxStepsError Objects [#maxstepserror-objects] ```python class MaxStepsError(GraphError) ``` Raised when a run exceeds the graph's `max_steps` before reaching an end node. ## NodeProtocol Objects [#nodeprotocol-objects] ```python class NodeProtocol(Protocol) ``` Protocol defining the interface of a decorated node. ## BranchError Objects [#brancherror-objects] ```python @dataclass class BranchError() ``` A failure inside a branch pipeline, recorded instead of raised so the main path is never taken down by a side pipeline. ## Graph Objects [#graph-objects] ```python class Graph() ``` #### get\_state [#get_state] ```python def get_state() -> dict[str, Any] ``` Get the current graph state. **Returns**: The current graph state. #### set\_state [#set_state] ```python def set_state(state: dict[str, Any]) -> Graph ``` Set the graph state. **Arguments**: * `state` - The new state to set for the graph. **Returns**: The graph instance. #### update\_state [#update_state] ```python def update_state(values: dict[str, Any]) -> Graph ``` Update the graph state with new values. **Arguments**: * `values` - The new values to update the graph state with. **Returns**: The graph instance. #### reset\_state [#reset_state] ```python def reset_state() -> Graph ``` Reset the graph state to an empty dict. #### add\_node [#add_node] ```python def add_node(node: NodeProtocol) -> Graph ``` Adds a node to the graph. **Arguments**: * `node` - The node to add to the graph. **Raises**: * `Exception` - If a node with the same name already exists in the graph. #### add\_edge [#add_edge] ```python def add_edge(source: NodeProtocol | str, destination: NodeProtocol | str) -> Graph ``` Adds an edge between two nodes that already exist in the graph. **Arguments**: * `source` - The source node or its name. * `destination` - The destination node or its name. #### add\_branch [#add_branch] ```python def add_branch(source: NodeProtocol | str, destination: NodeProtocol | str, *, condition: BranchCondition | None = None, wait: bool = True) -> Graph ``` Adds a branch edge: a side pipeline that starts at `destination` once `source` has run, without becoming a fork of the main path. Regular edges out of a node with two or more successors fork the main path and expect a join. A branch edge instead runs `destination` and whatever regular edges follow it as an isolated pipeline: it needs no join and no end node, it stops at the first node with no successors (or one whose output has `success: False`), and an exception inside it is recorded in `branch_errors` rather than raised. Branches may themselves have branches. **Arguments**: * `source` - The node whose completion starts the branch. * `destination` - The first node of the branch pipeline. * `condition` - Optional callable `(output, state) -> bool` (may be async) evaluated with the source node's output; the branch is skipped when it returns a falsy value. * `wait` - When True (default) the main path waits for the branch to finish before moving on. When False the branch runs as a detached task; `source`0 still waits for all detached branches before returning. #### add\_router [#add_router] ```python def add_router(sources: list[NodeProtocol], router: NodeProtocol, destinations: list[NodeProtocol]) -> Graph ``` Adds a router node, allowing for a decision to be made on which branch to follow based on the `choice` output of the router node. **Arguments**: * `sources` - The list of source nodes for the router. * `router` - The router node. * `destinations` - The list of destination nodes for the router. #### compile [#compile] ```python def compile(*, strict: bool = False) -> Graph ``` Validate the graph: * exactly one start node present (or Graph.start\_node set) * at least one end node present * all edges reference known nodes * all nodes reachable from the start (optional) **no cycles** when strict=True Returns self on success; raises GraphCompileError otherwise. #### wait\_for\_branches [#wait_for_branches] ```python async def wait_for_branches() -> None ``` Wait for every detached branch pipeline started by this graph. Called by execute() before it returns; exposed for callers that drive `_execute_branch` themselves. #### execute\_many [#execute_many] ```python async def execute_many(inputs: Iterable[dict[str, Any]], *, concurrency: int = 5) -> list[Any] ``` Execute the graph on many inputs concurrently. **Arguments**: * `inputs` (`Iterable[dict]`): An iterable of input dicts to feed into the graph. * `concurrency` (`int`): Maximum number of graph executions to run at once. * `state` (`Optional[Any]`): Optional shared state to pass to each execution. If you want isolated state per execution, pass None and the graph's normal semantics will apply. **Returns**: `list[Any]`: The list of results in the same order as `inputs`. #### get\_callback [#get_callback] ```python def get_callback() ``` Get a new instance of the callback class. **Returns**: `Callback`: A new instance of the callback class. #### set\_callback [#set_callback] ```python def set_callback(callback_class: type[Callback]) -> "Graph" ``` Set the callback class that is returned by the `get_callback` method and used as the default callback when no callback is passed to the `execute` method. **Arguments**: * `callback_class` (`type[Callback]`): The callback class to use as the default callback. #### add\_parallel [#add_parallel] ```python def add_parallel(source: NodeProtocol | str, destinations: list[NodeProtocol | str]) ``` Add multiple outgoing edges from a single source node to be executed in parallel. **Arguments**: * `source` - The source node for the parallel branches. * `destinations` - The list of destination nodes for the parallel branches. #### add\_join [#add_join] ```python def add_join(sources: list[NodeProtocol | str], destination: NodeProtocol | str) ``` Joins multiple parallel branches into a single branch. **Arguments**: * `sources` - The list of source nodes for the join. * `destination` - The destination node for the join. #### visualize [#visualize] ```python def visualize(*, save_path: str | None = None) ``` Render the current graph. If matplotlib is not installed, raise a helpful error telling users to install the viz extra. Optionally save to a file via `save_path`. ## BranchEdge Objects [#branchedge-objects] ```python class BranchEdge() ``` Side edge from `source` to the first node of an isolated pipeline. See `Graph.add_branch`. # graphai.utils (/docs/graphai/client-reference/utils) ## StrEnum Objects [#strenum-objects] ```python class StrEnum(str, Enum) ``` Backport of StrEnum for Python \< 3.11 ## ColoredFormatter Objects [#coloredformatter-objects] ```python class ColoredFormatter(logging.Formatter) ``` Custom colored formatter for the logger using ANSI escape codes. #### add\_coloured\_handler [#add_coloured_handler] ```python def add_coloured_handler(logger) ``` Add a coloured handler to the logger. #### setup\_custom\_logger [#setup_custom_logger] ```python def setup_custom_logger(name) ``` Setup a custom logger. ## Parameter Objects [#parameter-objects] ```python class Parameter(BaseModel) ``` Parameter for a function. **Arguments**: * `name` (`str`): The name of the parameter. * `description` (`str | None`): The description of the parameter. * `type` (`str`): The type of the parameter. * `default` (`Any`): The default value of the parameter. * `required` (`bool`): Whether the parameter is required. #### to\_dict [#to_dict] ```python def to_dict() -> dict[str, Any] ``` Convert the parameter to a dictionary for an standard dictionary-based function schema. This is the most common format used by LLM providers, including OpenAI, Ollama, and others. **Returns**: `dict[str, Any]`: The parameter in dictionary format. ## FunctionSchema Objects [#functionschema-objects] ```python class FunctionSchema(BaseModel) ``` Class that consumes a function and can return a schema required by different LLMs for function calling. #### from\_callable [#from_callable] ```python @classmethod def from_callable(cls, function: Callable) -> "FunctionSchema" ``` Initialize the FunctionSchema. **Arguments**: * `function` (`Callable`): The function to consume. #### from\_pydantic [#from_pydantic] ```python @classmethod def from_pydantic(cls, model: type[BaseModel]) -> "FunctionSchema" ``` Create a FunctionSchema from a Pydantic model class. **Arguments**: * `model` (`type[BaseModel]`): The Pydantic model class to convert **Returns**: `FunctionSchema`: FunctionSchema instance #### to\_openai [#to_openai] ```python def to_openai(api: OpenAIAPI = OpenAIAPI.COMPLETIONS) -> dict[str, Any] ``` Convert the function schema into OpenAI-compatible formats. Supports both completions and responses APIs. **Arguments**: * `api` (`OpenAIAPI`): The API to convert to. **Returns**: `dict`: The function schema in OpenAI-compatible format. # FAQs (/docs/graphai/user-guide/faqs) ## TypeError: object dict can't be used in 'await' expression [#typeerror-object-dict-cant-be-used-in-await-expression] Every node in GraphAI must be an `async` function — the runtime awaits each one. Define a node with a plain `def` and you'll hit this: ``` Traceback (most recent call last): File "/app/.venv/lib/python3.13/site-packages/graphai/graph.py", line 351, in execute output = await current_node.invoke(input=state, state=self.state) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.13/site-packages/graphai/nodes/base.py", line 152, in invoke out = await instance.execute(**input) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3.13/site-packages/graphai/nodes/base.py", line 74, in execute return await func(**params_dict) # Pass only the necessary arguments ^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: object dict can't be used in 'await' expression ``` The fix is one word: ```python # wrong @node def my_node(input: dict) -> dict: return {"output": "Hello, world!"} # right @node async def my_node(input: dict) -> dict: return {"output": "Hello, world!"} ``` # Release Notes (/docs/graphai/user-guide/release-notes) See below for all notable changes to the GraphAI library. ## \[0.0.12] - 2026-09-08 [#0012---2026-09-08] ### Fixed [#fixed] * `max_steps` is now enforced for router-driven graphs: a router returning a single `choice` and a parallel fan-out through a join both skipped the step counter, so loops such as `router -> tool -> router` were never bounded * A parallel layer counts as one step, matching the budget of a sequential `router -> tool` transition ### Added [#added] * `MaxStepsError` (a `GraphError`) raised when the limit is hit, exported from the package root, with the limit on `.max_steps` ## \[0.0.11] - 2026-09-03 [#0011---2026-09-03] ### Added [#added-1] * Branch edges via `add_branch(source, destination, *, condition=None, wait=True)` * A side pipeline that runs after `source` completes without forking the main path * Follows regular edges from `destination` to the first node with no successors; needs no join or end node * Stops after a step returns `success: False`; failures are recorded in `graph.branch_errors` instead of raised * Optional sync or async `condition` callable and detached mode (`wait=False`), awaited by `execute()` before it returns * `upstream` entry in every node's local state (`{"node", "output"}` of the node that just ran), readable by declaring an `upstream` parameter * `BranchError` exported from the package root * Docs: [Branches](components/branches.md) and [Parallel Execution vs Branching](components/parallel-vs-branching.md) ### Changed [#changed] * `compile()` follows branch edges for reachability and no longer errors on join edges * `visualize()` draws branch edges dashed * `FunctionSchema.from_callable()` accepts union annotations such as `dict | None` ## \[0.0.10] - TBD [#0010---tbd] ### Added [#added-2] * Direct Starlette support for `GraphEvent` and `EventCallback` objects * Parallel node execution for graphs with multiple outgoing edges from a single node * Automatic concurrent execution when a node has multiple successors * State merging from parallel branches * Configurable through standard `add_edge()` calls * New `add_join()` method for explicit convergence of parallel branches * Synchronizes multiple parallel branches to a single destination node * Ensures convergence node executes only once with merged state * Prevents duplicate execution of downstream nodes * New `add_parallel()` convenience method for creating parallel branches * Syntactic sugar for adding multiple edges from one source to multiple destinations * Parallel execution support for router nodes with multiple choices by returning `choices: list[str]` rather than `choice: str` ### Changed [#changed-1] * Enhanced `EventCallback.__call__()` and `EventCallback.acall()` method signatures * Removed legacy `node_name` parameter for cleaner API * Added `type` parameter to specify event type directly (defaults to `GraphEventType.CALLBACK`) * Added `identifier` parameter for custom event identification * Added `params` parameter for event metadata * Improved flexibility for custom event handling and streaming ## \[0.0.9] - 2025-09-05 [#009---2025-09-05] ### Added [#added-3] * Enhanced `FunctionSchema.from_pydantic()` method with full Pydantic v2 support * Correctly extracts field types, descriptions, and default values from Pydantic models * Handles `Optional` types and complex type annotations * Properly identifies required vs optional fields using `PydanticUndefined` * New `to_openai()` method on FunctionSchema for OpenAI API format support * Supports both `completions` and `responses` API endpoints * Export schemas for either nested or flat format structures * New `EventCallback` class for object-based callback handling * Outputs structured `GraphEvent` objects instead of formatted strings * Provides `GraphEventType` enum for event type identification * Better structured data with `type`, `identifier`, `token`, and `params` fields * Maintains backward compatibility with existing callback interface * Comprehensive graph compilation validation * Stricter validation of node connections and dependencies * Better error messages for graph construction issues * Cycle detection with clear `GraphCompileError` reporting * New `execute_many()` method for concurrent graph execution * Execute the graph on multiple inputs concurrently * Configurable concurrency level to control parallel execution * Preserves input order in results for predictable output ### Changed [#changed-2] * Graph compilation now validates execution order at compile time * Graphs with cycles now raise `GraphCompileError` during compilation to ensure predictable execution order ### Deprecated [#deprecated] * `Callback` class is deprecated and will be removed in v0.1.0 - use `EventCallback` instead * `special_token_format` and `token_format` parameters in `EventCallback` exist for backwards compatibility but are deprecated and will be removed in v0.1.0 ### Fixed [#fixed-1] * Added Python 3.10 compatibility for `StrEnum` with fallback implementation * Fixed type annotation issues with `default_factory` in Pydantic field definitions * Improved type extraction for complex Pydantic field types including `Union` and `Optional` ## \[0.0.8] - 2025-08-16 [#008---2025-08-16] ### Added [#added-4] * Graph constructor methods \[`add_node`, `add_router`, `add_edge`, `set_callback`, `set_state`, `update_state`, `reset_state`, `set_start_node`, `set_end_node`, `compile`] can now be chained * Moved `Callback` class to top-level import, you can now import it with `from graphai import Callback` * Environment variable `GRAPHAI_LOG_LEVEL` for controlling log output level (DEBUG, INFO, WARNING, ERROR, CRITICAL) ### Changed [#changed-3] * Dropped `networkx`, `matplotlib`, and `colorlog` dependencies (note if using `Graph.visualize` one of `networkx` or `matplotlib` must be installed) * Updated documentation notebooks to use new callback pattern * Updated old type annotations to use Python 3.10+ syntax, e.g., `List[str]` -> `list[str]` and `Optional[list]` -> `list | None` ## [0.0.7] - Removed [#007---removed] ## [0.0.6] - 2025-05-28 [#006---2025-05-28] ### Added [#added-5] * Explicit callback parameter in `execute()` method for better control over callback instances * `NodeProtocol` type definition for improved type safety and IDE support * Enhanced documentation examples demonstrating proper parallel execution patterns * New `set_callback()` method for customizing default callback class ### Changed [#changed-4] * **BREAKING**: Refactored callback handling to eliminate shared state between parallel executions * Modified `execute()` method signature to accept optional `callback` parameter * Removed internal `self.callback` attribute * Updated all documentation notebooks to use new callback pattern * Improved type hints throughout codebase using `Type[Callback]` ### Fixed [#fixed-2] * **Critical**: Fixed callback stream contamination when multiple graphs executed in parallel * Resolved race conditions in multi-threaded environments * Fixed inconsistent streaming behavior in concurrent scenarios * Improved memory management and reduced callback-related memory leaks * Better cleanup of callback resources after execution ### Security [#security] * Enhanced thread-safety for parallel graph execution * Eliminated shared state vulnerabilities in callback handling ### Migration Guide [#migration-guide] For basic usage, no changes required - the API remains backwards compatible. For custom callbacks, update from: ```python # Before (v0.0.5) cb = graph.get_callback() graph.callback = cb result = await graph.execute(input=data) ``` To: ```python # After (v0.0.6) cb = graph.get_callback() result = await graph.execute(input=data, callback=cb) ``` ## [0.0.5] - 2025-03-30 [#005---2025-03-30] ### Added [#added-6] * New function schema functionality for generating standardized function schemas compatible with various LLM providers * Built-in colored logger with support for different log levels and custom formatting * Support for generating function schemas from Pydantic models ### Changed [#changed-5] * Removed dependency on semantic router library * Improved type mapping for function parameters in schemas * Enhanced documentation and code organization ### Fixed [#fixed-3] * Various bug fixes and improvements ### Security [#security-1] * No security-related changes in this release [0.0.7]: https://github.com/aurelio-labs/graphai/compare/v0.0.6...v0.0.7 [0.0.6]: https://github.com/aurelio-labs/graphai/compare/v0.0.5...v0.0.6 [0.0.5]: https://github.com/aurelio-labs/graphai/compare/v0.0.4...v0.0.5 [0.0.4]: https://github.com/aurelio-labs/graphai/compare/v0.0.3...v0.0.4 [0.0.3]: https://github.com/aurelio-labs/graphai/compare/v0.0.2...v0.0.3 [0.0.2]: https://github.com/aurelio-labs/graphai/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/aurelio-labs/graphai/releases/tag/v0.0.1 # Branches (/docs/graphai/user-guide/components/branches) Branches let a node start a side pipeline when it finishes, without changing where the main path goes next. Use them for work that should happen *because* a node ran, such as logging a result or writing rows to a table. ## Adding a Branch [#adding-a-branch] Create a branch with `add_branch()`. The destination runs after the source completes; the main path continues along its regular edges as if the branch were not there: ```python from graphai import Graph, node @node(start=True) async def start(input: dict): return {} @node async def main(input: dict): return {"main": True} @node async def side(input: dict): return {"side": True} @node(end=True) async def end(input: dict): return {} g = Graph() g.add_node(start).add_node(main).add_node(side).add_node(end) g.add_edge(start, main) g.add_edge(main, end) g.add_branch(main, side) # side runs after main, off the main path result = await g.execute(input={"input": {}}) # result contains: {"main": True} # "side" is not in result: a branch never writes into the main path ``` A branch needs no join and no end node. It stops at the first node with no outgoing edges. ## Multi-Step Branches [#multi-step-branches] The branch target can lead to further nodes through ordinary edges. Together they form a pipeline that runs to its last step: ```python g.add_branch(main, shape) # pipeline starts here g.add_edge(shape, validate) # ordinary edges between steps g.add_edge(validate, write) # write has no successors, so the pipeline ends there ``` If a step returns `{"success": False}`, the steps after it do not run. ## Reading the Previous Node [#reading-the-previous-node] Every node can declare an `upstream` parameter. It holds the name and output of the node that ran just before it, so a pipeline step can read what it was given: ```python @node async def shape(input: dict, upstream: dict | None = None): rows = upstream["output"]["rows"] # the previous node returned {"rows": [...]} return {"rows": [r | {"source": "api"} for r in rows]} ``` `upstream` is available on the main path too, and nodes that do not declare it are unaffected. ## Conditions [#conditions] Pass a `condition` to decide at run time whether the branch runs. It receives the source node's output and the graph state and may be sync or async: ```python def only_on_success(output: dict, state: dict) -> bool: return output.get("success") is True g.add_branch(main, side, condition=only_on_success) ``` ## Detached Branches [#detached-branches] By default the main path waits for a branch to finish before moving on. Pass `wait=False` to let it continue immediately: ```python g.add_branch(main, side, wait=False) ``` `execute()` still waits for every detached branch before it returns, so nothing is left running when a run is reported complete. ## Errors [#errors] An exception inside a branch never reaches the main path. It is logged and recorded on the graph: ```python await g.execute(input={"input": {}}) for err in g.branch_errors: print(err.source, "->", err.destination, err.error) ``` `branch_errors` is cleared at the start of each `execute()`. ## Branches on Routers and Loops [#branches-on-routers-and-loops] A branch can hang off any node, including a node inside a router loop. The loop is unaffected because a branch is not one of the node's successors: ```python g.add_edge(brain, tool) g.add_edge(tool, brain) # the loop g.add_branch(tool, log) # log runs each time tool runs ``` ## Next Steps [#next-steps] * Compare branches with forks in [Parallel Execution vs Branching](parallel-vs-branching.md) * Learn how forks and joins work in [Parallel Execution](parallel-execution.md) * See how outputs flow between nodes in [State](state.md) # Callbacks (/docs/graphai/user-guide/components/callbacks) Callbacks are how a graph streams while it runs. A node can push tokens out as it produces them — an LLM's partial response, progress updates — and something outside the graph can consume them live. That's what makes streaming chat UIs and real-time endpoints possible. ## Use `EventCallback` [#use-eventcallback] `EventCallback` emits structured `GraphEvent` objects instead of formatted strings, which makes the stream much easier to consume. > `Callback`, the original string-based class, is deprecated and will be removed in v0.1.0. It still works, but new code should use `EventCallback`. A `Graph` still creates the deprecated `Callback` by default, so tell it to use `EventCallback`: ```python from graphai import Graph from graphai.callback import EventCallback graph = Graph() graph.set_callback(EventCallback) ``` From then on, `graph.get_callback()` returns an `EventCallback`, and it's the default whenever `execute()` runs without one. ## Streaming from a node [#streaming-from-a-node] Mark a node with `stream=True` and give it a `callback` parameter. GraphAI injects the callback for you. ```python from graphai import node @node(stream=True) async def streaming_node(input: dict, callback): for chunk in process_chunks(input["data"]): await callback.acall(chunk) return {"result": "streaming complete"} ``` Two rules. `stream=True` tells GraphAI to inject the callback, and the node must declare a `callback` parameter to receive it. ### Streaming an LLM response [#streaming-an-llm-response] The common case: ```python @node(stream=True) async def llm_node(input: dict, callback): from openai import AsyncOpenAI client = AsyncOpenAI() stream = await client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": input["query"]}, ], stream=True, ) response_text = "" async for chunk in stream: content = chunk.choices[0].delta.content if content: response_text += content await callback.acall(content) return {"response": response_text} ``` ## Events [#events] Everything that flows through the callback is a `GraphEvent`: * `type` — what happened. One of `GraphEventType.START`, `END`, `START_NODE`, `END_NODE`, or `CALLBACK` (a streamed token). * `identifier` — who emitted it. Defaults to `"graphai"`. * `token` — the streamed content, for `CALLBACK` events. * `params` — optional extra metadata. Node boundaries and the end of the run are emitted as events too, so a consumer always knows where it is in the execution. ## Emitting events [#emitting-events] ```python # async (preferred) await callback.acall(token="chunk of text") # sync, for non-async contexts callback(token="chunk of text") ``` Both also take `type`, `identifier`, and `params`, so you can emit something other than a plain token: ```python await callback.acall( token="search finished", type="tool_done", # a GraphEventType, or your own string params={"tool": "search"}, ) ``` You can mark node boundaries and close the stream yourself as well: ```python await callback.start_node(node_name="my_node") await callback.end_node(node_name="my_node") await callback.close() ``` ## Consuming the stream [#consuming-the-stream] `aiter()` is an async iterator over events. Start the graph as a background task, then read from the callback: ```python import asyncio cb = graph.get_callback() task = asyncio.create_task(graph.execute(input={"input": {"query": "hello"}}, callback=cb)) async for event in cb.aiter(): if event.type == "callback": print(event.token, end="", flush=True) await task ``` Two things worth knowing. Pass the callback into `execute()` explicitly — that's what ties the stream to *that* run, and it keeps concurrent runs from bleeding into each other. And `aiter()` finishes when the stream closes, which happens when execution ends. ## Example: a streaming endpoint [#example-a-streaming-endpoint] `GraphEvent` objects play nicely with Starlette and FastAPI streaming responses, so a streaming API stays short: ```python import asyncio from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse from graphai import Graph, node from graphai.callback import EventCallback app = FastAPI() @node(start=True, stream=True) async def llm_stream(input: dict, callback): async for chunk in get_llm_response(input["query"]): await callback.acall(chunk) return {"status": "complete"} @node(end=True) async def final_node(input: dict): return {"status": "success"} graph = Graph() graph.set_callback(EventCallback) graph.add_node(llm_stream).add_node(final_node) graph.add_edge(llm_stream, final_node) @app.post("/stream") async def stream_endpoint(request: Request): data = await request.json() cb = graph.get_callback() asyncio.create_task( graph.execute(input={"input": {"query": data["query"]}}, callback=cb) ) async def events(): async for event in cb.aiter(): if event.token: yield event.token return StreamingResponse(events(), media_type="text/event-stream") ``` ## Good habits [#good-habits] 1. **Stay async.** The callback is built on `asyncio`; prefer `acall` over the sync form. 2. **Pass the callback to `execute()`.** Don't share one instance across runs. 3. **Stream small chunks.** Tokens, not whole documents. 4. **Branch on `event.type`.** Handle node boundaries and the end event, not only tokens. ## Next steps [#next-steps] * [Graphs](graphs.md) — orchestrating execution * [Nodes](nodes.md) — processing logic * [State](state.md) — context across nodes # Function Schema (/docs/graphai/user-guide/components/function-schema) Most LLM providers accept "function schemas" — a JSON description of a function's name, what it does, and what arguments it takes. Writing those by hand is tedious and easy to get wrong. `FunctionSchema` generates them from your Python functions. ## What it extracts [#what-it-extracts] Given a function, `FunctionSchema` pulls out: * Its name. * Its description, from the docstring. * Its signature and return type. * Each parameter: type, default, and whether it's required. ## Basic usage [#basic-usage] ```python from graphai.utils import FunctionSchema def scrape_webpage(url: str, name: str = "test") -> str: """Provides access to web scraping. You can use this tool to scrape a webpage. Many webpages may return no information due to JS or adblock issues, if this happens, you must use a different URL. """ return "hello there" schema = FunctionSchema.from_callable(scrape_webpage) schema_dict = schema.to_dict() ``` ## The output [#the-output] `to_dict()` produces the common shape most providers accept: ```python { "type": "function", "function": { "name": "function_name", "description": "function_description", "parameters": { "type": "object", "properties": { "param_name": { "description": "param_description", "type": "param_type" } }, "required": ["required_param1", "required_param2"] } } } ``` For OpenAI specifically, `to_openai()` targets either the Chat Completions or the Responses API: ```python from graphai.utils import OpenAIAPI schema.to_openai() # Chat Completions (the default) schema.to_openai(api=OpenAIAPI.RESPONSES) # Responses API ``` ## Type mapping [#type-mapping] Python types become JSON schema types: * `int`, `float` → `number` * `str` → `string` * `bool` → `boolean` * anything else → `object` ## Several functions at once [#several-functions-at-once] `get_schemas` builds a list of schemas in one call: ```python from graphai.utils import get_schemas def function1(x: int) -> str: """First function""" return str(x) def function2(y: str, z: bool = False) -> int: """Second function""" return len(y) schemas = get_schemas([function1, function2]) ``` ## From a Pydantic model [#from-a-pydantic-model] Schemas can come from Pydantic models too. Field types, descriptions, and defaults all carry over: ```python from pydantic import BaseModel from graphai.utils import FunctionSchema class SearchQuery(BaseModel): """A search query model""" query: str max_results: int = 10 schema = FunctionSchema.from_pydantic(SearchQuery) ``` ## Getting good schemas [#getting-good-schemas] 1. **Write docstrings.** They become the description the LLM reads to decide when to call your function. 2. **Add type hints** on every parameter and the return value, so types map correctly. 3. **Use defaults** for optional parameters. A parameter with no default is marked required. The output works with OpenAI, LiteLLM, Ollama, and any other provider that uses the standard function-calling format. # Graphs (/docs/graphai/user-guide/components/graphs) The `Graph` is what ties everything together. It holds your nodes and routers, connects them with edges, and runs them in order. ## The pieces [#the-pieces] * **Nodes** do the work. * **Edges** say which node runs next. * **State** is the shared dict that carries data through the run. ## Creating a graph [#creating-a-graph] ```python from graphai import Graph graph = Graph() # or with a step limit and some starting state graph = Graph(max_steps=20, initial_state={"history": []}) ``` * `max_steps` (default `10`) caps how many steps a run can take, so a loop can't run forever. Hitting the cap raises `MaxStepsError`. * `initial_state` seeds the state dict. ## Adding nodes [#adding-nodes] Add each node you've defined. Constructor methods return the graph, so you can chain them. ```python graph.add_node(my_node) graph.add_node(node_a).add_node(node_b).add_node(node_c) ``` A node is one of: * **Start node** — the entry point. Exactly one per graph. * **End node** — an exit point. As many as you need. * **Regular node** — a processing step. * **Router** — a node that decides where to go next. ## Connecting nodes [#connecting-nodes] Edges define the flow. You can pass node objects or their names: ```python graph.add_edge(source_node, destination_node) graph.add_edge("node_a", "node_b") ``` A straight-line workflow is just a chain of edges: ```python graph.add_edge(node_a, node_b) graph.add_edge(node_b, node_c) ``` Give one node several outgoing edges and the successors run concurrently — see [Parallel Execution](parallel-execution.md). For side work that shouldn't affect the main path, use [Branches](branches.md). ## Routers [#routers] A router picks the next node at run time. Register it with the nodes that lead into it and the nodes it can send to: ```python graph.add_router( sources=[node_a], router=my_router, destinations=[node_b, node_c], ) ``` The router returns a `"choice"` naming the next node: ```python @router async def my_router(input: dict): if some_condition: return {"choice": "node_b", "data": processed_data} return {"choice": "node_c", "data": processed_data} ``` Return `"choices"` (a list) instead to run several destinations in parallel. ## Running the graph [#running-the-graph] ```python import asyncio async def run_graph(): result = await graph.execute(input={"input": {"query": "Hello, world!"}}) return result result = asyncio.run(run_graph()) ``` Here's the one thing to really understand: **the dict you pass to `execute()` becomes the state**, and each node receives only the parameters it declares, looked up by name from that state. A node with an `input` parameter gets `state["input"]`. That's why the request goes under an `input` key above. `execute()` returns the final state. ### What happens during a run [#what-happens-during-a-run] 1. Execution starts at the start node. 2. Each node gets its declared parameters from the state, runs, and returns a dict. 3. That dict is merged into the state. 4. At a router, the `"choice"` decides the next node. 5. It continues until an end node runs — or `max_steps` is hit. ### Many inputs at once [#many-inputs-at-once] `execute_many` runs the graph over several inputs concurrently: ```python results = await graph.execute_many( [{"input": {"query": "one"}}, {"input": {"query": "two"}}], concurrency=5, ) ``` Results come back in input order. ## State [#state] The graph keeps a state dict for the whole run: ```python state = graph.get_state() graph.set_state({"history": [], "context": "some context"}) # replace graph.update_state({"new_key": "new_value"}) # merge graph.reset_state() # clear ``` A node can read the state by declaring a `state` parameter. Changes persist either way — mutate it in place, or return the keys you want merged: ```python @node async def my_node(input: dict, state: dict): history = state.get("history", []) return {"output": result, "history": history + [result]} ``` [State](state.md) goes into more detail. ## Validating the graph [#validating-the-graph] `compile()` checks the graph before you run it, and raises `GraphCompileError` if something's wrong: ```python graph.compile() # also reject cycles graph.compile(strict=True) ``` It checks for a start node, at least one end node, and that every node is reachable. Cycles — like a router that loops back to itself through a tool — are allowed by default, because they're how agents iterate. Pass `strict=True` to forbid them. ## Visualizing [#visualizing] ```python graph.visualize() ``` Draws the graph, with branch edges dashed. You'll need `networkx` or `matplotlib` installed. ## Next steps [#next-steps] * [Nodes](nodes.md) — building processing steps * [Parallel Execution](parallel-execution.md) — forks and joins * [Branches](branches.md) — side pipelines off the main path * [State](state.md) — carrying context through a run * [Callbacks](callbacks.md) — streaming # Nodes (/docs/graphai/user-guide/components/nodes) Nodes are the units of work in GraphAI. Each one is an async function that takes some input and returns a dict. You connect them into a graph. ## Defining a node [#defining-a-node] Decorate an async function with `@node`: ```python from graphai import node @node async def process_data(input: dict): result = do_something(input["data"]) return {"output": result} ``` Every node must be `async`, and must return a dict. ## How a node gets its arguments [#how-a-node-gets-its-arguments] This is the most important thing to understand about nodes, so it's worth spelling out. The graph keeps a state dict. When a node runs, GraphAI looks at the node's signature and passes **only the parameters it declares, pulled from the state by name**. Nothing else. So this node receives `state["input"]`: ```python @node async def my_node(input: dict): ... ``` And this one receives `state["query"]` and `state["metadata"]`, ignoring everything else in the state: ```python @node async def selective(query: str, metadata: dict = None): return {"result": process(query, metadata)} ``` A parameter with no default is required. If it isn't in the state, the run fails with a clear error. ## What a node returns [#what-a-node-returns] The dict a node returns is merged into the state, where later nodes can read it: ```python @node async def my_node(input: dict): result = process(input["data"]) return { "processed_data": result, "metadata": {"timestamp": time.time()}, } ``` ## Kinds of node [#kinds-of-node] ### Start and end [#start-and-end] One start node marks the entry point. Any number of end nodes mark exits. ```python @node(start=True) async def entry(input: dict): return {"initialized_data": input} @node(end=True) async def exit(input: dict): return {"final_result": processed_result} ``` ### Streaming [#streaming] Set `stream=True` and declare a `callback` parameter to stream tokens out while the node runs: ```python @node(stream=True) async def streaming_node(input: dict, callback): for chunk in process_chunks(input["data"]): await callback.acall(chunk) return {"result": "streaming complete"} ``` [Callbacks](callbacks.md) covers this in depth. ### Routers [#routers] A router decides which node runs next. It returns a `"choice"` with the next node's name: ```python from graphai import router @router async def route_on_content(input: dict): if "question" in input["query"].lower(): return {"choice": "question_node", "query": input["query"]} return {"choice": "statement_node", "statement": input["query"]} ``` Return `"choices"` (a list of names) to run several nodes in parallel instead. Routers are often driven by an LLM — the [quickstart](../../get-started/quickstart.md) builds one that picks between tools. ## Reading state and the previous node [#reading-state-and-the-previous-node] Declare a `state` parameter to read the shared state. You can change it in place, or return keys to merge — both persist: ```python @node async def stateful(input: dict, state: dict): history = state.get("history", []) result = process_with_history(input["data"], history) return {"result": result, "history": history + [result]} ``` Declare `upstream` to see the node that ran just before this one — its name and its output: ```python @node async def shape(input: dict, upstream: dict | None = None): rows = upstream["output"]["rows"] return {"rows": rows} ``` ## Naming nodes [#naming-nodes] A node's name defaults to the function name. Set it explicitly when a router needs to refer to it: ```python @node(name="data_processor") async def process_data(input: dict): return {"processed": result} ``` ## Next steps [#next-steps] * [Graphs](graphs.md) — connecting nodes * [State](state.md) — carrying context through a run * [Callbacks](callbacks.md) — streaming responses # Parallel Execution (/docs/graphai/user-guide/components/parallel-execution) Parallel execution lets independent parts of your graph run at the same time. When several tools can work on a request at once, there's no reason to wait for them one by one. GraphAI runs things in parallel in two situations: 1. **Forks** — a node has several outgoing edges, so all of its successors run concurrently. 2. **Router fan-out** — a router returns several `choices`, so all of them run concurrently. ## Forking with edges [#forking-with-edges] Give one node more than one outgoing edge and the destinations run in parallel. ```python from graphai import Graph, node @node(start=True) async def start(input: dict): return {} @node async def branch_a(input: dict): return {"a": 1} @node async def branch_b(input: dict): return {"b": 2} @node(end=True) async def end(input: dict): return {} g = Graph() g.add_node(start).add_node(branch_a).add_node(branch_b).add_node(end) # fork from start g.add_edge(start, branch_a) g.add_edge(start, branch_b) # both lead to end g.add_edge(branch_a, end) g.add_edge(branch_b, end) result = await g.execute(input={"input": {}}) # result contains: {"a": 1, "b": 2} ``` `branch_a` and `branch_b` run concurrently once `start` finishes, and their outputs are merged into the state. `add_parallel()` is shorthand for the same fork: ```python g.add_parallel(start, [branch_a, branch_b]) g.add_edge(branch_a, end) g.add_edge(branch_b, end) ``` ## Joining the branches [#joining-the-branches] Here's the catch. When parallel branches converge on the same node, that node runs **once per incoming branch** by default. Usually you want it to run once, after everything has finished. That's what `add_join()` is for. Without a join, `end` runs twice: ```python @node(start=True) async def start(input: dict, state: dict): state["history"] = ["start"] return {} @node async def branch_a(input: dict, state: dict): state["history"].append("branch_a") return {} @node async def branch_b(input: dict, state: dict): state["history"].append("branch_b") return {} @node(end=True) async def end(input: dict, state: dict): state["history"].append("end") return {} g = Graph() g.add_node(start).add_node(branch_a).add_node(branch_b).add_node(end) g.add_edge(start, branch_a) g.add_edge(start, branch_b) g.add_edge(branch_a, end) g.add_edge(branch_b, end) await g.execute(input={"input": {}}) state = g.get_state() # state["history"] has TWO "end" entries ``` With a join, it runs once: ```python g = Graph() g.add_node(start).add_node(branch_a).add_node(branch_b).add_node(end) g.add_edge(start, branch_a) g.add_edge(start, branch_b) g.add_join([branch_a, branch_b], end) await g.execute(input={"input": {}}) state = g.get_state() # state["history"] has ONE "end" entry ``` `add_join()` guarantees that every listed branch finishes first, the destination runs exactly once, and the branches' state is merged before it continues. ## Nesting forks [#nesting-forks] Forks can happen at any depth: ```python @node(start=True) async def start(input: dict): return {} @node async def mid(input: dict): return {"mid": True} @node async def branch_a(input: dict): return {"a": 1} @node async def branch_b(input: dict): return {"b": 2} @node(end=True) async def end(input: dict): return {} g = Graph() g.add_node(start).add_node(mid).add_node(branch_a).add_node(branch_b).add_node(end) g.add_edge(start, mid) # linear g.add_edge(mid, branch_a) # then mid forks g.add_edge(mid, branch_b) g.add_join([branch_a, branch_b], end) result = await g.execute(input={"input": {}}) # result contains: {"mid": True, "a": 1, "b": 2} ``` ## Router fan-out [#router-fan-out] A router normally picks one path: ```python from graphai import router @router async def single_router(input: dict): return {"choice": "tool_a"} # only tool_a runs ``` Return `choices` (a list) instead and every listed node runs in parallel: ```python @router async def parallel_router(input: dict): return {"choices": ["tool_a", "tool_b"]} # both run ``` A full example: ```python from graphai import Graph, node, router @node(start=True) async def start(input: dict): return {} @router async def parallel_router(input: dict): return {"choices": ["tool_a", "tool_b"]} @node(name="tool_a") async def tool_a(input: dict): return {"a_result": 1} @node(name="tool_b") async def tool_b(input: dict): return {"b_result": 2} @node(name="tool_c") async def tool_c(input: dict): return {"c_result": 3} @node(end=True) async def end(input: dict): return {} g = Graph() g.add_node(start).add_node(parallel_router).add_node(tool_a).add_node(tool_b).add_node(tool_c).add_node(end) g.add_edge(start, parallel_router) g.add_edge(parallel_router, tool_a) g.add_edge(parallel_router, tool_b) g.add_edge(parallel_router, tool_c) # has an edge, but isn't in choices g.add_join([tool_a, tool_b], end) result = await g.execute({"input": {}}) assert result["a_result"] == 1 assert result["b_result"] == 2 assert "c_result" not in result # tool_c never ran ``` Only nodes named in `choices` run. `tool_c` has an edge from the router, but the router didn't choose it, so it's skipped. ### Looping back through a join [#looping-back-through-a-join] Join the parallel branches back into the router and you get an iterative loop — run tools, look at the results, decide whether to go again: ```python @node(start=True) async def start(input: dict): return {} @router(name="parallel_router") async def parallel_router(input: dict, state: dict): iteration = state.get("iteration", 0) if iteration > 0: return {"choice": "end"} # second time through: finish state["iteration"] = iteration + 1 return {"choices": ["tool_a", "tool_b"]} @node(name="tool_a") async def tool_a(input: dict): return {"a_result": 1} @node(name="tool_b") async def tool_b(input: dict): return {"b_result": 2} @node(end=True) async def end(input: dict): return {"final": "done"} g = Graph() g.add_node(start).add_node(parallel_router).add_node(tool_a).add_node(tool_b).add_node(end) g.add_edge(start, parallel_router) g.add_edge(parallel_router, tool_a) g.add_edge(parallel_router, tool_b) g.add_join([tool_a, tool_b], parallel_router) # back to the router g.add_edge(parallel_router, end) result = await g.execute({"input": {}}) # the router runs twice: first it fans out, then it chooses end ``` This is the shape of a tool-calling agent that can fire several tools at once, gather the results, and decide what to do next. Keep an eye on `max_steps` — each parallel layer counts as one step, and the loop is bounded by it. ## How state merges [#how-state-merges] When parallel branches finish, their outputs are merged into the state. If two branches return the same key, the last one to finish wins. ```python result = await g.execute({"input": {}}) result["a_result"] # from tool_a result["b_result"] # from tool_b ``` ## Good habits [#good-habits] 1. **Join where branches converge.** Otherwise downstream nodes run once per branch. 2. **Keep branches independent.** They run concurrently on copied state — don't assume one can see another's changes. 3. **Loop through a join, not through return values.** Routing back to the router with `add_join()` keeps the control flow in the graph structure. 4. **Name router destinations explicitly.** The names in `choices` must match the nodes. ## Next steps [#next-steps] * [Graphs](graphs.md) — general graph construction * [State](state.md) — how state flows through parallel branches * [Callbacks](callbacks.md) — watching parallel progress * [Parallel Execution vs Branching](parallel-vs-branching.md) — forks vs. side pipelines # Parallel Vs Branching (/docs/graphai/user-guide/components/parallel-vs-branching) GraphAI has two ways for one node to lead to more than one node. A **fork** (two or more regular edges) runs successors concurrently as part of the main path. A **branch** runs a side pipeline that stays out of the main path. They look similar on a diagram and behave very differently. ## The Same Nodes, Two Wirings [#the-same-nodes-two-wirings] ```python from graphai import Graph, node @node(start=True) async def start(input: dict): return {} @node async def a(input: dict): return {"a": 1} @node async def b(input: dict): return {"b": 2} @node(end=True) async def end(input: dict): return {} ``` ### As a fork [#as-a-fork] ```python g = Graph() g.add_node(start).add_node(a).add_node(b).add_node(end) g.add_edge(start, a) g.add_edge(start, b) # second edge out of start: a fork g.add_join([a, b], end) # forks converge with a join result = await g.execute(input={"input": {}}) # result contains: {"a": 1, "b": 2} ``` ### As a branch [#as-a-branch] ```python g = Graph() g.add_node(start).add_node(a).add_node(b).add_node(end) g.add_edge(start, a) g.add_edge(a, end) # the main path g.add_branch(start, b) # b is a side pipeline off start result = await g.execute(input={"input": {}}) # result contains: {"a": 1} ``` ## What Differs [#what-differs] | | Fork | Branch | | ------------ | -------------------------------------- | ---------------------------------------------------------- | | Created with | two or more `add_edge()` calls | `add_branch()` | | Runs | all successors concurrently | the branch after the source completes | | Must end | at a join or an end node | wherever the pipeline runs out of edges | | Result | outputs of every path merged | main path only | | On error | the first exception aborts `execute()` | recorded in `branch_errors`, run continues | | Waiting | until every path finishes | until the branch finishes, or not at all with `wait=False` | | Conditional | no | optional `condition` callable | ## Choosing [#choosing] Use a **fork** when the paths are parts of one result and the graph needs all of them before it can continue, such as running several tools at once and then deciding what to do with the combined output. Use a **branch** when the work is a consequence of a node running and the main path should not depend on it, such as writing a log row, notifying another system, or syncing data after a tool call. ## Inside a Router Loop [#inside-a-router-loop] The difference matters most in a loop. Here a router repeatedly calls a tool and the tool returns to the router: ```python g.add_edge(brain, tool) g.add_edge(tool, brain) ``` Adding a fork off the tool changes how the loop terminates, because the router path is now one arm of a fork that expects to join. Adding a branch does not: ```python g.add_branch(tool, log) # log runs after each tool call; the loop is unchanged ``` ## Mixing Them [#mixing-them] A branch's pipeline may itself fork and join, and a node inside a pipeline may have branches of its own: ```python g.add_branch(main, shape) g.add_edge(shape, write) g.add_edge(shape, notify) # a fork inside the pipeline g.add_join([write, notify], done) ``` ## Next Steps [#next-steps] * Full details in [Branches](branches.md) * Forks, joins and router choices in [Parallel Execution](parallel-execution.md) # State (/docs/graphai/user-guide/components/state) State is the dict that carries data through a run. It's how a node knows what earlier nodes did. ## The basics [#the-basics] The state dict: 1. Starts as whatever you pass to `execute()` — or `initial_state`, if you set one. 2. Lives for the whole run. 3. Is readable by any node that asks for it. 4. Grows as nodes return values. ## Seeding state [#seeding-state] Set an initial state when you create the graph: ```python from graphai import Graph graph = Graph(initial_state={ "history": [], "context": "initial context", "metadata": { "user_id": "user123", "session_start": 1625097600, }, }) ``` Leave it out and the state starts empty. ## The state methods [#the-state-methods] ```python current = graph.get_state() graph.set_state({"new_state": "value"}) # replace graph.update_state({"additional": "data"}) # merge graph.reset_state() # clear ``` ## Reading state in a node [#reading-state-in-a-node] Declare a `state` parameter and GraphAI passes it in: ```python from graphai import node @node async def stateful_node(input: dict, state: dict): history = state.get("history", []) context = state.get("context", "") processed = process_with_context(input["data"], context) return {"result": processed} ``` ## Changing state [#changing-state] Two ways, and both persist. **Return it.** Any key in the returned dict is merged into the state. This is the clearest way to hand data to the next node: ```python @node async def update_history(input: dict, state: dict): history = state.get("history", []) return { "result": process(input["query"]), "history": history + [input["query"]], } ``` **Mutate it.** The `state` a node receives is the graph's actual state object, so in-place changes stick: ```python @node async def append_history(input: dict, state: dict): state.setdefault("history", []).append(input["query"]) return {} ``` Returning keys is usually the better habit — it's explicit, and it's easy to see what a node contributes. Mutation is handy for accumulating into an existing list or dict. ## State vs. input [#state-vs-input] There's no separate "input" mechanism. The dict you pass to `execute()` *is* the initial state, and each node receives whichever keys it declares as parameters. By convention the request goes under an `input` key, which is why so many nodes declare `input: dict` — but that's just a key like any other. ```python @node async def process_with_both(input: dict, state: dict): query = input["query"] # state["input"]["query"] history = state.get("history", []) # the whole state result = process_with_history(query, history) return {"result": result, "history": history + [query]} ``` ## Persisting across runs [#persisting-across-runs] State lives as long as the graph object. To carry it between runs, save and restore it: ```python result = await graph.execute(input={"input": input_data}) saved = graph.get_state() store_state(saved) # later graph.set_state(load_state()) ``` ## Scope [#scope] State belongs to a graph instance. Two graphs never share it: ```python graph1 = Graph(initial_state={"id": "graph1"}) graph2 = Graph(initial_state={"id": "graph2"}) graph1.update_state({"value": 1}) graph2.update_state({"value": 2}) ``` ## Good habits [#good-habits] 1. **Keep it serializable** — dicts, lists, strings, numbers — so you can save it. 2. **Be selective.** Only put things in state that later nodes actually need. 3. **Write down the shape.** A documented state structure saves everyone time. 4. **Watch the size.** Don't let it grow without bound in long-running apps. ## Next steps [#next-steps] * [Graphs](graphs.md) — orchestrating a run * [Nodes](nodes.md) — processing logic * [Callbacks](callbacks.md) — streaming