{
  "id": "router",
  "title": "Semantic Router",
  "url": "https://redis.io/docs/latest/develop/ai/redisvl/0.10.0/api/router/",
  "summary": "",
  "content": "\n\n\u003ca id=\"semantic-router-api\"\u003e\u003c/a\u003e\n\n## Semantic Router\n\n### `class SemanticRouter(name, routes, vectorizer=None, routing_config=None, redis_client=None, redis_url='redis://localhost:6379', overwrite=False, connection_kwargs={})`\n\nSemantic Router for managing and querying route vectors.\n\nInitialize the SemanticRouter.\n\n* **Parameters:**\n  * **name** (*str*) – The name of the semantic router.\n  * **routes** (*List* *[*[Route](#route) *]*) – List of Route objects.\n  * **vectorizer** (*BaseVectorizer* *,* *optional*) – The vectorizer used to embed route references. Defaults to default HFTextVectorizer.\n  * **routing_config** ([RoutingConfig](#routingconfig) *,* *optional*) – Configuration for routing behavior. Defaults to the default RoutingConfig.\n  * **redis_client** (*Optional* *[* *SyncRedisClient* *]* *,* *optional*) – Redis client for connection. Defaults to None.\n  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.\n  * **overwrite** (*bool* *,* *optional*) – Whether to overwrite existing index. Defaults to False.\n  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments\n    for the redis client. Defaults to empty {}.\n\n#### `add_route_references(route_name, references)`\n\nAdd a reference(s) to an existing route.\n\n* **Parameters:**\n  * **router_name** (*str*) – The name of the router.\n  * **references** (*Union* *[* *str* *,* *List* *[* *str* *]* *]*) – The reference or list of references to add.\n  * **route_name** (*str*)\n* **Returns:**\n  The list of added references keys.\n* **Return type:**\n  List[str]\n\n#### `clear()`\n\nFlush all routes from the semantic router index.\n\n* **Return type:**\n  None\n\n#### `delete()`\n\nDelete the semantic router index.\n\n* **Return type:**\n  None\n\n#### `delete_route_references(route_name='', reference_ids=[], keys=[])`\n\nGet references for an existing semantic router route.\n\n* **Parameters:**\n  * **Optional** (*keys*) – The name of the router.\n  * **Optional** – The reference or list of references to delete.\n  * **Optional** – List of fully qualified keys (prefix:router:reference_id) to delete.\n  * **route_name** (*str*)\n  * **reference_ids** (*List* *[* *str* *]*)\n  * **keys** (*List* *[* *str* *]*)\n* **Returns:**\n  Number of objects deleted\n* **Return type:**\n  int\n\n#### `classmethod from_dict(data, **kwargs)`\n\nCreate a SemanticRouter from a dictionary.\n\n* **Parameters:**\n  **data** (*Dict* *[* *str* *,* *Any* *]*) – The dictionary containing the semantic router data.\n* **Returns:**\n  The semantic router instance.\n* **Return type:**\n  [SemanticRouter](#semanticrouter)\n* **Raises:**\n  **ValueError** – If required data is missing or invalid.\n\n```python\nfrom redisvl.extensions.router import SemanticRouter\nrouter_data = {\n    \"name\": \"example_router\",\n    \"routes\": [{\"name\": \"route1\", \"references\": [\"ref1\"], \"distance_threshold\": 0.5}],\n    \"vectorizer\": {\"type\": \"openai\", \"model\": \"text-embedding-ada-002\"},\n}\nrouter = SemanticRouter.from_dict(router_data)\n```\n\n#### `classmethod from_existing(name, redis_client=None, redis_url='redis://localhost:6379', **kwargs)`\n\nReturn SemanticRouter instance from existing index.\n\n* **Parameters:**\n  * **name** (*str*)\n  * **redis_client** (*Redis* *|* *RedisCluster* *|* *None*)\n  * **redis_url** (*str*)\n* **Return type:**\n  [SemanticRouter](#semanticrouter)\n\n#### `classmethod from_yaml(file_path, **kwargs)`\n\nCreate a SemanticRouter from a YAML file.\n\n* **Parameters:**\n  **file_path** (*str*) – The path to the YAML file.\n* **Returns:**\n  The semantic router instance.\n* **Return type:**\n  [SemanticRouter](#semanticrouter)\n* **Raises:**\n  * **ValueError** – If the file path is invalid.\n  * **FileNotFoundError** – If the file does not exist.\n\n```python\nfrom redisvl.extensions.router import SemanticRouter\nrouter = SemanticRouter.from_yaml(\"router.yaml\", redis_url=\"redis://localhost:6379\")\n```\n\n#### `get(route_name)`\n\nGet a route by its name.\n\n* **Parameters:**\n  **route_name** (*str*) – Name of the route.\n* **Returns:**\n  The selected Route object or None if not found.\n* **Return type:**\n  Optional[[Route](#route)]\n\n#### `get_route_references(route_name='', reference_ids=[], keys=[])`\n\nGet references for an existing route route.\n\n* **Parameters:**\n  * **router_name** (*str*) – The name of the router.\n  * **references** (*Union* *[* *str* *,* *List* *[* *str* *]* *]*) – The reference or list of references to add.\n  * **route_name** (*str*)\n  * **reference_ids** (*List* *[* *str* *]*)\n  * **keys** (*List* *[* *str* *]*)\n* **Returns:**\n  Reference objects stored\n* **Return type:**\n  List[Dict[str, Any]]]\n\n#### `model_post_init(context, /)`\n\nThis function is meant to behave like a BaseModel method to initialise private attributes.\n\nIt takes context as an argument since that’s what pydantic-core passes when calling it.\n\n* **Parameters:**\n  * **self** (*BaseModel*) – The BaseModel instance.\n  * **context** (*Any*) – The context.\n* **Return type:**\n  None\n\n#### `remove_route(route_name)`\n\nRemove a route and all references from the semantic router.\n\n* **Parameters:**\n  **route_name** (*str*) – Name of the route to remove.\n* **Return type:**\n  None\n\n#### `route_many(statement=None, vector=None, max_k=None, distance_threshold=None, aggregation_method=None)`\n\nQuery the semantic router with a given statement or vector for multiple matches.\n\n* **Parameters:**\n  * **statement** (*Optional* *[* *str* *]*) – The input statement to be queried.\n  * **vector** (*Optional* *[* *List* *[* *float* *]* *]*) – The input vector to be queried.\n  * **max_k** (*Optional* *[* *int* *]*) – The maximum number of top matches to return.\n  * **distance_threshold** (*Optional* *[* *float* *]*) – The threshold for semantic distance.\n  * **aggregation_method** (*Optional* *[*[DistanceAggregationMethod](#distanceaggregationmethod) *]*) – The aggregation method used for vector distances.\n* **Returns:**\n  The matching routes and their details.\n* **Return type:**\n  List[[RouteMatch](#routematch)]\n\n#### `to_dict()`\n\nConvert the SemanticRouter instance to a dictionary.\n\n* **Returns:**\n  The dictionary representation of the SemanticRouter.\n* **Return type:**\n  Dict[str, Any]\n\n```python\nfrom redisvl.extensions.router import SemanticRouter\nrouter = SemanticRouter(name=\"example_router\", routes=[], redis_url=\"redis://localhost:6379\")\nrouter_dict = router.to_dict()\n```\n\n#### `to_yaml(file_path, overwrite=True)`\n\nWrite the semantic router to a YAML file.\n\n* **Parameters:**\n  * **file_path** (*str*) – The path to the YAML file.\n  * **overwrite** (*bool*) – Whether to overwrite the file if it already exists.\n* **Raises:**\n  **FileExistsError** – If the file already exists and overwrite is False.\n* **Return type:**\n  None\n\n```python\nfrom redisvl.extensions.router import SemanticRouter\nrouter = SemanticRouter(\n    name=\"example_router\",\n    routes=[],\n    redis_url=\"redis://localhost:6379\"\n)\nrouter.to_yaml(\"router.yaml\")\n```\n\n#### `update_route_thresholds(route_thresholds)`\n\nUpdate the distance thresholds for each route.\n\n* **Parameters:**\n  **route_thresholds** (*Dict* *[* *str* *,* *float* *]*) – Dictionary of route names and their distance thresholds.\n\n#### `update_routing_config(routing_config)`\n\nUpdate the routing configuration.\n\n* **Parameters:**\n  **routing_config** ([RoutingConfig](#routingconfig)) – The new routing configuration.\n\n#### `model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}`\n\nConfiguration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].\n\n#### `name: str`\n\nThe name of the semantic router.\n\n#### `property route_names: List[str]`\n\nGet the list of route names.\n\n* **Returns:**\n  List of route names.\n* **Return type:**\n  List[str]\n\n#### `property route_thresholds: Dict[str, float | None]`\n\nGet the distance thresholds for each route.\n\n* **Returns:**\n  Dictionary of route names and their distance thresholds.\n* **Return type:**\n  Dict[str, float]\n\n#### `routes: `List[[Route](#route)]\n\nList of Route objects.\n\n#### `routing_config: `[RoutingConfig](#routingconfig)\n\nConfiguration for routing behavior.\n\n#### `vectorizer: BaseVectorizer`\n\nThe vectorizer used to embed route references.\n\n## Routing Config\n\n### `class RoutingConfig(*, max_k=1, aggregation_method=DistanceAggregationMethod.avg)`\n\nConfiguration for routing behavior.\n\nCreate a new model by parsing and validating input data from keyword arguments.\n\nRaises [ValidationError][pydantic_core.ValidationError] if the input data cannot be\nvalidated to form a valid model.\n\nself is explicitly positional-only to allow self as a field name.\n\n* **Parameters:**\n  * **max_k** (*Annotated* *[* *int* *,* *FieldInfo* *(* *annotation=NoneType* *,* *required=True* *,* *metadata=* *[* *Strict* *(* *strict=True* *)* *,* *Gt* *(* *gt=0* *)* *]* *)* *]*)\n  * **aggregation_method** ([DistanceAggregationMethod](#distanceaggregationmethod))\n\n#### `max_k: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Gt(gt=0)])]`\n\nAggregation method to use to classify queries.\n\n#### `model_config: ClassVar[ConfigDict] = {'extra': 'ignore'}`\n\nConfiguration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].\n\n## Route\n\n### `class Route(*, name, references, metadata={}, distance_threshold=0.5)`\n\nModel representing a routing path with associated metadata and thresholds.\n\nCreate a new model by parsing and validating input data from keyword arguments.\n\nRaises [ValidationError][pydantic_core.ValidationError] if the input data cannot be\nvalidated to form a valid model.\n\nself is explicitly positional-only to allow self as a field name.\n\n* **Parameters:**\n  * **name** (*str*)\n  * **references** (*List* *[* *str* *]*)\n  * **metadata** (*Dict* *[* *str* *,* *Any* *]*)\n  * **distance_threshold** (*Annotated* *[* *float* *,* *FieldInfo* *(* *annotation=NoneType* *,* *required=True* *,* *metadata=* *[* *Strict* *(* *strict=True* *)* *,* *Gt* *(* *gt=0* *)* *,* *Le* *(* *le=2* *)* *]* *)* *]*)\n\n#### `distance_threshold: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Gt(gt=0), Le(le=2)])]`\n\nDistance threshold for matching the route.\n\n#### `metadata: Dict[str, Any]`\n\nMetadata associated with the route.\n\n#### `model_config: ClassVar[ConfigDict] = {}`\n\nConfiguration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].\n\n#### `name: str`\n\nThe name of the route.\n\n#### `references: List[str]`\n\nList of reference phrases for the route.\n\n## Route Match\n\n### `class RouteMatch(*, name=None, distance=None)`\n\nModel representing a matched route with distance information.\n\nCreate a new model by parsing and validating input data from keyword arguments.\n\nRaises [ValidationError][pydantic_core.ValidationError] if the input data cannot be\nvalidated to form a valid model.\n\nself is explicitly positional-only to allow self as a field name.\n\n* **Parameters:**\n  * **name** (*str* *|* *None*)\n  * **distance** (*float* *|* *None*)\n\n#### `distance: float | None`\n\nThe vector distance between the statement and the matched route.\n\n#### `model_config: ClassVar[ConfigDict] = {}`\n\nConfiguration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].\n\n#### `name: str | None`\n\nThe matched route name.\n\n## Distance Aggregation Method\n\n### `class DistanceAggregationMethod(value, names=\u003cnot given\u003e, *values, module=None, qualname=None, type=None, start=1, boundary=None)`\n\nEnumeration for distance aggregation methods.\n\n#### `avg = 'avg'`\n\nCompute the average of the vector distances.\n\n#### `min = 'min'`\n\nCompute the minimum of the vector distances.\n\n#### `sum = 'sum'`\n\nCompute the sum of the vector distances.\n",
  "tags": [],
  "last_updated": "2026-04-01T08:10:08-05:00"
}

