
    Q
ir                     t   d dl mZ d dlmZmZmZmZmZmZm	Z	 d dl
mc mc mZ d dlZd dlmZmZmZmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZmZmZm Z m!Z! d d	l"m#Z# d d
l$m%Z%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z:  e2e;          Z< G d de          Z=dS )    )Path)AnyDictListMappingOptionalTypeUnionN)	BaseModel
ConfigDictFieldPrivateAttr)AggregateRequestAggregateResultReducer)ResponseError)ROUTE_VECTOR_FIELD_NAME)DistanceAggregationMethodRoute
RouteMatchRoutingConfigSemanticRouterIndexSchema)SearchIndex)FilterQueryVectorRangeQuery)Tag)RedisConnectionFactory)convert_byteshashify	make_dict)SyncRedisClient)
get_logger)deprecated_argumentmodel_to_dictscan_by_pattern)BaseVectorizer)HFTextVectorizerc                       e Zd ZU dZeed<   	 ee         ed<   	  ee	          Z
eed<   	  ee          Zeed<   	  e            Zeed<    ed	          Z ed
d          dddddi fdedee         dee         dee         dee         dededeeef         f fd            Ze	 	 dGdedee         dedd fd            Z ed
          	 	 	 	 dHdee         deded
efd            ZdefdZedee         fd            Zedeeee          f         fd            Z!defdZ"deeee          f         fdZ#e$dedededefd             Z%e$dededefd!            Z&dee         fd"Z'dedee         fd#Z(d$eeef         de)fd%Z*defd&Z+d'e,d(e-d)e.de/fd*Z0	 dId,ee          d(e-d)e.dee)         fd-Z1d,ee          d(e-de)fd.Z2d,ee          d)e.d(e-dee)         fd/Z3 ed0          	 	 	 	 dJd1ee         d,eee                   d(ee-         d0ee          de)f
d2            Z4 ed0          	 	 	 	 	 dKd1ee         d,eee                   d)ee.         d0ee          d(ee-         dee)         fd3            Z5deddfd4Z6dLd5Z7dLd6Z8ed7eeef         dd fd8            Z9deeef         fd9Z:ed:edd fd;            Z;dMd:ededdfd<Z<ded=e=eee         f         dee         fd>Z>e$d?ee         dee?         fd@            Z@dAg g fdedBee         dCee         deeeef                  fdDZAdAg g fdedBee         dCee         de.fdEZBdLdFZC xZDS )NSemanticRouterz8Semantic Router for managing and querying route vectors.nameroutes)default_factory
vectorizerrouting_config_indexT)arbitrary_types_alloweddtypeNredis://localhost:6379Fredis_client	redis_url	overwriteconnection_kwargsc	                 :   |	                     dd          }
|rLt          |t                    st          d          |
r%|j        |
k    rt          d|
 d|j                   n!|	}|
r |j        di d|
i t          dddi|}|t                      }t                      
                    ||||||            | j        |||fi | | j        j                                                            | j         d	d
|                                            dS )a_  Initialize the SemanticRouter.

        Args:
            name (str): The name of the semantic router.
            routes (List[Route]): List of Route objects.
            vectorizer (BaseVectorizer, optional): The vectorizer used to embed route references. Defaults to default HFTextVectorizer.
            routing_config (RoutingConfig, optional): Configuration for routing behavior. Defaults to the default RoutingConfig.
            redis_client (Optional[SyncRedisClient], optional): Redis client for connection. Defaults to None.
            redis_url (str, optional): The redis url. Defaults to redis://localhost:6379.
            overwrite (bool, optional): Whether to overwrite existing index. Defaults to False.
            connection_kwargs (Dict[str, Any]): The connection arguments
                for the redis client. Defaults to empty {}.
        r1   Nz.Must provide a valid redisvl.vectorizer class.zProvided dtype z! does not match vectorizer dtype modelz'sentence-transformers/all-mpnet-base-v2)r*   r+   r-   r.   r4   r3   :route_config. )pop
isinstancer&   	TypeErrorr1   
ValueErrorupdater'   r   super__init___initialize_indexr/   clientjsonsetr*   to_dict)selfr*   r+   r-   r.   r3   r4   r5   r6   kwargsr1   vectorizer_kwargs	__class__s               C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\redisvl/extensions/router/semantic.pyrB   zSemanticRouter.__init__0   s}   4 

7D))  	j.99 R PQQQ )U22 `e``jN^``   !' =(!(<<GU+;<<<)  ?# J
 !*__N!)% 	 	
 	
 	
 	|Y	WWEVWWW!!%%&A&A&A4XXXXX    returnc                 T   |rt          j        dd|i|}n|rt          j        |           |t          d          |                                                    | d          }t          |t                    st          d| d|          |                     |||          S )	z3Return SemanticRouter instance from existing index.r4   NzOCreating Redis client failed. Please check the redis_url and connection_kwargs.r9   z!No valid router config found for z. Received: )r4   r3   r;   )	r   get_redis_connectionvalidate_sync_redisr?   rE   getr=   dict	from_dict)clsr*   r3   r4   rI   router_dicts         rL   from_existingzSemanticRouter.from_existingo   s      	E1F  # LL  	E"6|DDDa   #''))--.D.D.DEE+t,, 	UDUUkUU   }}9<  
 
 	
rM   float32c                 ,   t          j        | j        | j        j        | j        j                  }t          d|||d|| _        | j                                        }|sx|rvt          j	        | j        | j        j
                  }|j                                        | j        j                                        k    rt          d| j         d          | j                            |d           |r|r|                     | j                   dS dS )	z8Initialize the search index and handle Redis connection.)schemar3   r4   )r3   zExisting index z schema does not match the user provided schema for the semantic router. If you wish to overwrite the index schema, set overwrite=True during initialization.F)r5   dropNr;   )r   from_paramsr*   r-   dimsr1   r   r/   existsrW   rD   rZ   rG   r?   create_add_routesr+   )	rH   r3   r4   r5   r1   r6   rZ   existedexisting_indexs	            rL   rC   z SemanticRouter._initialize_index   sM    +6It+T_-B
 
 " 
%
 
  	
 
 +$$&& 	W 	(6	(:  N $,,..$+2D2L2L2N2NNN kdi k k k   	YU;;; 	*) 	*T[)))))	* 	*rM   c                 B    d| j         dt          | j                   dS )NzSemanticRouter(name=z	, routes=))r*   lenr+   rH   s    rL   __repr__zSemanticRouter.__repr__   s'    OdiOOC<L<LOOOOrM   c                 $    d | j         D             S )zcGet the list of route names.

        Returns:
            List[str]: List of route names.
        c                     g | ]	}|j         
S r;   r*   .0routes     rL   
<listcomp>z.SemanticRouter.route_names.<locals>.<listcomp>   s    444u
444rM   r+   rf   s    rL   route_nameszSemanticRouter.route_names   s     544444rM   c                 $    d | j         D             S )zGet the distance thresholds for each route.

        Returns:
            Dict[str, float]: Dictionary of route names and their distance thresholds.
        c                 (    i | ]}|j         |j        S r;   )r*   distance_thresholdrk   s     rL   
<dictcomp>z3SemanticRouter.route_thresholds.<locals>.<dictcomp>   s    NNN
E4NNNrM   ro   rf   s    rL   route_thresholdszSemanticRouter.route_thresholds   s     ON$+NNNNrM   c                     || _         dS )zUpdate the routing configuration.

        Args:
            routing_config (RoutingConfig): The new routing configuration.
        N)r.   )rH   r.   s     rL   update_routing_configz$SemanticRouter.update_routing_config   s     -rM   ru   c                 P    | j         D ]}|j        |v r||j                 |_        dS )zUpdate the distance thresholds for each route.

        Args:
            route_thresholds (Dict[str, float]): Dictionary of route names and their distance thresholds.
        N)r+   r*   rs   )rH   ru   rm   s      rL   update_route_thresholdsz&SemanticRouter.update_route_thresholds   sA     [ 	H 	HEz---+;EJ+G(	H 	HrM   index
route_namereference_hashc                     | j         }|r!| j        r| j                            |          n| j        }|r| | | | | S | | | S )zAGenerate the route reference key using the index's key_separator.key_separatorprefixrstrip)rz   r{   r|   sepr   s        rL   _route_ref_keyzSemanticRouter._route_ref_key   sr     !-0SU\S$$S)))u| 	8DcD:DsDNDDD 7#7~777rM   c                     | j         }|r!| j        r| j                            |          n| j        }|r| | | | dS | | dS )z/Generate a search pattern for route references.*r~   )rz   r{   r   r   s       rL   _route_patternzSemanticRouter._route_pattern   sn     !-0SU\S$$S)))u| 	)5c5:5s5555 (#((((rM   c           	         g }g }|D ]}| j                             d |j        D             d          }t          |j                  D ]m\  }}t	          |          }|                    ||j        |||         d           |                    |                     | j        |j        |                     n| 	                    |j                  s| j
                            |           | j                            ||           dS )zyAdd routes to the router and index.

        Args:
            routes (List[Route]): List of routes to be added.
        c                     g | ]}|S r;   r;   )rl   	references     rL   rn   z.SemanticRouter._add_routes.<locals>.<listcomp>   s    ===y===rM   T	as_bufferreference_idr{   r   vectorkeysN)r-   
embed_many
references	enumerater   appendr*   r   r/   rR   r+   load)	rH   r+   route_referencesr   rm   reference_vectorsir   r|   s	            rL   r`   zSemanticRouter._add_routes   s:    24 	* 	*E $ : :==E,<=== !; ! ! !*%*: ; ;  9!(!3!3 ''(6&+j%."3A"6	    ''UZPP   
 88EJ'' *""5))))55555rM   c                 F    t          fd| j        D             d          S )zGet a route by its name.

        Args:
            route_name (str): Name of the route.

        Returns:
            Optional[Route]: The selected Route object or None if not found.
        c              3   2   K   | ]}|j         k    |V  d S Nrj   rl   rm   r{   s     rL   	<genexpr>z%SemanticRouter.get.<locals>.<genexpr>  s/      PPuuzZ7O7OU7O7O7O7OPPrM   N)nextr+   )rH   r{   s    `rL   rR   zSemanticRouter.get  s-     PPPPPPPRVWWWrM   resultc                     t          t          |                    }t          |d         t          |d                             S )z-Process resulting route objects and metadata.r{   distance)r*   r   )r    r   r   float)rH   r   
route_dicts      rL   _process_routezSemanticRouter._process_route   sE    }V4455
L)E*Z:P4Q4Q
 
 
 	
rM   c                     d}t          | j                  D ](\  }}d|j         d|j         d}|dk    r|dz  }||z  })|S )z3Apply distance threshold on a route by route basis. z(@route_name == 'z' && @distance < rd   r   z || )r   r+   r*   rs   )rH   filterr   rm   
filter_strs        rL   _distance_threshold_filterz)SemanticRouter._distance_threshold_filter'  se    !$+.. 	! 	!HAueUZee%JbeeeJ1uu& j FFrM   vector_range_queryaggregation_methodmax_kc                    |t           j        k    rt          j        }n)|t           j        k    rt          j        }nt          j        }t          |                              d          d         }t          |                              d |d          	                    d                    
                    d|                              d          }|                                 }|                    |           |S )	z$Build the Redis aggregation request.z RETURNr   z@route_namevector_distancer   z	@distance)max   )r   minreducerssumavgstrsplitr   group_byaliassort_bydialectr   r   )rH   r   r   r   aggregation_funcaggregate_queryaggregate_requestr   s           rL   _build_aggregate_requestz'SemanticRouter._build_aggregate_request2  s     !:!>>>'|#<#@@@'|'|01177	BB1E_--X  !23399*EE  W[eW,,WQZZ 	 0022  (((  rM      r   c                     t          d  j        D                       }t          |t          t	          |          dg          }                     |||          }	  j                            ||j                  }n4# t          $ r'}dt          |          v rt          d          |d}~ww xY w fd|j        D             S )	z!Get route response from vector dbc              3   $   K   | ]}|j         V  d S r   )rs   rk   s     rL   r   z4SemanticRouter._get_route_matches.<locals>.<genexpr>]  s%       S Se!9 S S S S S SrM   r{   )r   vector_field_namers   return_fieldsr   z(VSS is not yet supported on FT.AGGREGATEzDSemantic routing is only available on Redis version 7.x.x or greaterNc                 :    g | ]}                     |          S r;   )r   )rl   route_matchrH   s     rL   rn   z5SemanticRouter._get_route_matches.<locals>.<listcomp>v  s4     
 
 
1<D,,
 
 
rM   )r   r+   r   r   r   r   r/   	aggregateparamsr   r   RuntimeErrorrows)	rH   r   r   r   rs   r   r   aggregation_resultes	   `        rL   _get_route_matchesz!SemanticRouter._get_route_matchesS  s    ! S St{ S S SSS-5$%788'.	
 
 
 !99 2% : 
 
		26+2G2G!#5#<3 3  	 	 	9SVVCC"Z   G	
 
 
 
@R@W
 
 
 	
s    B   
B1
"B,,B1c                     |                      ||          }|st                      S |d         }|j        |S t          |j         d| j         d          )z*Classify to a single route using a vector.r   N not a supported route for the  semantic router.)r   r   r*   r?   )rH   r   r   route_matchestop_route_matchs        rL   _classify_routezSemanticRouter._classify_routez  sr     //8JKK 	 << (*+"""'dd	ddd  rM   c                     |                      |||          }g }|r@|D ]=}|j        |                    |           t          |j         d| j         d          |S )z?Classify to multiple routes, up to max_k (int), using a vector.r   Nr   r   )r   r*   r   r?   )rH   r   r   r   r   top_route_matchesr   s          rL   _classify_multi_routez$SemanticRouter._classify_multi_route  s     //8JRW/XX /1 	,  #/%,,[9999$&+hhDIhhh   ! rM   rs   	statementc                     |s+|st          d          | j                            |          }|p| j        j        }|                     ||          }|S )a  Query the semantic router with a given statement or vector.

        Args:
            statement (Optional[str]): The input statement to be queried.
            vector (Optional[List[float]]): The input vector to be queried.
            distance_threshold (Optional[float]): The threshold for semantic distance.
            aggregation_method (Optional[DistanceAggregationMethod]): The aggregation method used for vector distances.

        Returns:
            RouteMatch: The matching route.
        0Must provide a vector or statement to the router)r?   r-   embedr.   r   r   )rH   r   r   r   rs   r   s         rL   __call__zSemanticRouter.__call__  sl    &  	6 U !STTT_**955F H$"5"H 	
 ..v7IJJrM   c                     |s+|st          d          | j                            |          }|p| j        j        }|p| j        j        }|                     |||          }|S )at  Query the semantic router with a given statement or vector for multiple matches.

        Args:
            statement (Optional[str]): The input statement to be queried.
            vector (Optional[List[float]]): The input vector to be queried.
            max_k (Optional[int]): The maximum number of top matches to return.
            distance_threshold (Optional[float]): The threshold for semantic distance.
            aggregation_method (Optional[DistanceAggregationMethod]): The aggregation method used for vector distances.

        Returns:
            List[RouteMatch]: The matching routes and their details.
        r   )r?   r-   r   r.   r   r   r   )rH   r   r   r   rs   r   r   s          rL   
route_manyzSemanticRouter.route_many  s    *  	6 U !STTT_**955F2,2H$"5"H 	
 !66E-
 
 ! rM   c                                                      t                              d d           dS  j                             fdj        D                        fd j        D              _        dS )zRemove a route and all references from the semantic router.

        Args:
            route_name (str): Name of the route to remove.
        NRoute z# is not found in the SemanticRouterc           	      l    g | ]0}                     j        j        t          |                    1S r;   )r   r/   r*   r   )rl   r   rm   rH   s     rL   rn   z/SemanticRouter.remove_route.<locals>.<listcomp>  sG       ! ''UZASASTT  rM   c                 *    g | ]}|j         k    |S r;   rj   r   s     rL   rn   z/SemanticRouter.remove_route.<locals>.<listcomp>  s%    VVVUUZ:=U=U5=U=U=UrM   )rR   loggerwarningr/   	drop_keysr   r+   )rH   r{   rm   s   ``@rL   remove_routezSemanticRouter.remove_route  s     $$=NNSJSSSTTTTTK!!    %*%5     WVVVdkVVVDKKKrM   c                 <    | j                             d           dS )z!Delete the semantic router index.T)r[   N)r/   deleterf   s    rL   r   zSemanticRouter.delete   s!    %%%%%rM   c                 F    | j                                          g | _        dS )z0Flush all routes from the semantic router index.N)r/   clearr+   rf   s    rL   r   zSemanticRouter.clear  s!    rM   datac                    ddl m} 	 |d         }|d         }|d         }|d         }n1# t          $ r$}t          dt	          |                     d}~ww xY w	  ||          }	n1# t
          $ r$}t          d	t	          |                     d}~ww xY w|	st          d	|           d
 |D             }
t          di |} | d||
|	|d|S )a  Create a SemanticRouter from a dictionary.

        Args:
            data (Dict[str, Any]): The dictionary containing the semantic router data.

        Returns:
            SemanticRouter: The semantic router instance.

        Raises:
            ValueError: If required data is missing or invalid.

        .. code-block:: python

            from redisvl.extensions.router import SemanticRouter
            router_data = {
                "name": "example_router",
                "routes": [{"name": "route1", "references": ["ref1"], "distance_threshold": 0.5}],
                "vectorizer": {"type": "openai", "model": "text-embedding-ada-002"},
            }
            router = SemanticRouter.from_dict(router_data)
        r   )vectorizer_from_dictr*   r+   r-   r.   z*Unable to load semantic router from dict: NzUnable to load vectorizer: c                 &    g | ]}t          d i |S )r;   )r   rk   s     rL   rn   z,SemanticRouter.from_dict.<locals>.<listcomp>6  s"    :::U%..%..:::rM   r*   r+   r-   r.   r;   )redisvl.utils.vectorizer   KeyErrorr?   r   	Exceptionr   )rU   r   rI   r   r*   routes_datavectorizer_datarouting_config_datar   r-   r+   r.   s               rL   rT   zSemanticRouter.from_dict	  s]   6 	A@@@@@	T<Dx.K"<0O"&'7"8 	T 	T 	TR#a&&RRSSS	T	E--o>>JJ 	E 	E 	EC3q66CCDDD	E  	NL?LLMMM::k:::&==)<==s 
!)	
 

 
 
 	
s,    ) 
AAAA' '
B1BBc                     | j         d | j        D             | j        j        | j        j        dt          | j                  dS )a  Convert the SemanticRouter instance to a dictionary.

        Returns:
            Dict[str, Any]: The dictionary representation of the SemanticRouter.

        .. code-block:: python

            from redisvl.extensions.router import SemanticRouter
            router = SemanticRouter(name="example_router", routes=[], redis_url="redis://localhost:6379")
            router_dict = router.to_dict()
        c                 ,    g | ]}t          |          S r;   )r$   rk   s     rL   rn   z*SemanticRouter.to_dict.<locals>.<listcomp>O  s     EEE}U++EEErM   )typer8   r   )r*   r+   r-   r   r8   r$   r.   rf   s    rL   rG   zSemanticRouter.to_dictA  sU     IEEEEE,.  ,D,?@@
 
 	
rM   	file_pathc                 x   	 t          |                                          }n%# t          $ r}t          d|           |d}~ww xY w|                                st          d| d          t          |d          5 }t          j        |          } | j	        |fi |cddd           S # 1 swxY w Y   dS )a	  Create a SemanticRouter from a YAML file.

        Args:
            file_path (str): The path to the YAML file.

        Returns:
            SemanticRouter: The semantic router instance.

        Raises:
            ValueError: If the file path is invalid.
            FileNotFoundError: If the file does not exist.

        .. code-block:: python

            from redisvl.extensions.router import SemanticRouter
            router = SemanticRouter.from_yaml("router.yaml", redis_url="redis://localhost:6379")
        zInvalid file path: NzFile z does not existr)
r   resolveOSErrorr?   r^   FileNotFoundErroropenyaml	safe_loadrT   )rU   r   rI   fpr   f	yaml_datas          rL   	from_yamlzSemanticRouter.from_yamlW  s)   .	Gi((**BB 	G 	G 	G>9>>??QF	G yy{{ 	H#$FI$F$F$FGGG"c]] 	aq))I 3=  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s&   !$ 
AAA "B//B36B3c                 B   t          |                                          }|                                r|st          d| d          t	          |d          5 }|                                 }t          j        ||d           ddd           dS # 1 swxY w Y   dS )a`  Write the semantic router to a YAML file.

        Args:
            file_path (str): The path to the YAML file.
            overwrite (bool): Whether to overwrite the file if it already exists.

        Raises:
            FileExistsError: If the file already exists and overwrite is False.

        .. code-block:: python

            from redisvl.extensions.router import SemanticRouter
            router = SemanticRouter(
                name="example_router",
                routes=[],
                redis_url="redis://localhost:6379"
            )
            router.to_yaml("router.yaml")
        zSchema file z already exists.wF)	sort_keysN)r   r   r^   FileExistsErrorr   rG   r   dump)rH   r   r5   r  r  r  s         rL   to_yamlzSemanticRouter.to_yaml}  s    ( )__$$&&99;; 	Ny 	N!"L"L"L"LMMM"c]] 	5aIIie4444	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5s   ,BBBr   c                 D   t          |t                    r|g}g }g }| j                            |d          }t	          |          D ]c\  }}t          |          }|                    |||||         d           |                    |                     | j        ||                     d| j        	                    ||          }| 
                    |          }	|	st          d| d          |	j                            |           |                                  |S )a  Add a reference(s) to an existing route.

        Args:
            router_name (str): The name of the router.
            references (Union[str, List[str]]): The reference or list of references to add.

        Returns:
            List[str]: The list of added references keys.
        Tr   r   r   r     not found in the SemanticRouter)r=   r   r-   r   r   r   r   r   r/   r   rR   r?   r   extend_update_router_state)
rH   r{   r   r   r   r   r   r   r|   rm   s
             rL   add_route_referencesz#SemanticRouter.add_route_references  sL    j#&& 	&$J13 !O66zT6RR &j11 	V 	VLAy$Y//N##$2",!*/2	    KK++DK^TTUUUU{ 0t<<$$ 	TRjRRRSSS
+++!!###rM   idsc                     g }| D ]=}t          d          |k    }t          g d|          }|                    |           >|S )z(Create a filter query for the given ids.r   )r   r{   r   )r   filter_expression)r   r   r   )r  queriesidfefqs        rL   _make_filter_queriesz#SemanticRouter._make_filter_queries  sf      	 	B^$$*BIII"$  B NN2rM   r   reference_idsr   c                    |r|                      |          }n|rr|s5|                     | j        |          }t          | j        j        |          }| j        j        |                      fdt          |          D                       }nt          d          | j                            |          }d |D             S )a$  Get references for an existing route route.

        Args:
            router_name (str): The name of the router.
            references (Union[str, List[str]]): The reference or list of references to add.

        Returns:
            List[Dict[str, Any]]]: Reference objects stored
        c                 F    g | ]}|                               d          S ))r   )rl   keyr   s     rL   rn   z7SemanticRouter.get_route_references.<locals>.<listcomp>  s(    CCC3#CCCrM   zCMust provide a route name, reference ids, or keys to get referencesc                 D    g | ]}t          |          d k    |d          S )r   re   rl   r   s     rL   rn   z7SemanticRouter.get_route_references.<locals>.<listcomp>  s'    000SVVaZZ!ZZZrM   )	r  r   r/   r%   rD   r   r   r?   batch_query)rH   r{   r  r   r  patternresr   s          @rL   get_route_referencesz#SemanticRouter.get_route_references  s       	//>>GG 	 D--dk:FF&t{'97CC++C//CCCC}T/B/BCCC GG U   k%%g..00c0000rM   c           	         |r>|s<|                      |          }| j                            |          }d |D             }n7|s5|                     | j        |          }t	          | j        j        |          }|st          d|           g }|D ]^}|                    d          d         }|                    |t          | j        j        
                    |                    f           _| j                            |          }	|D ]O\  }}
|                     |          }|st          d| d          |j                            |
d                    P|                                  |	S )a  Get references for an existing semantic router route.

        Args:
            router_name Optional(str): The name of the router.
            reference_ids Optional(List[str]]): The reference or list of references to delete.
            keys Optional(List[str]]): List of fully qualified keys (prefix:router:reference_id) to delete.

        Returns:
            int: Number of objects deleted
        c                 P    g | ]#}t          |          d k    |d          d         $S )r   r  r  r  s     rL   rn   z:SemanticRouter.delete_route_references.<locals>.<listcomp>  s+    :::1s1vvzzAaDJzzzrM   zNo references found for route :r   r  r   )r  r/   r   r   r%   rD   r?   r   r   r   hgetallr   rR   r   remover  )rH   r{   r  r   r  r"  r!  to_be_deletedr  deletedr   rm   s               rL   delete_route_referencesz&SemanticRouter.delete_route_references  s   "  	@ 	@//>>G+))'22C:::::DD 	@))$+zBBG"4;#5w??D 	LJjJJKKK 	 	C3+J  ]4;+=+E+Ec+J+JKKL    +''--"/ 	9 	9JHHZ((E X !V*!V!V!VWWW##F;$78888!!###rM   c                     | j         j                                                            | j         dd|                                            dS )z)Update the router configuration in Redis.r9   r:   N)r/   rD   rE   rF   r*   rG   rf   s    rL   r  z#SemanticRouter._update_router_state,  sD    !!%%&A&A&A4XXXXXrM   )Nr2   )Nr2   FrX   )r   )NNNN)NNNNN)rN   N)T)E__name__
__module____qualname____doc__r   __annotations__r   r   r   r'   r-   r&   r   r.   r   r/   r   r   model_configr#   r   r!   boolr   r   rB   classmethodrW   rC   rg   propertyrp   r   ru   rw   ry   staticmethodr   r   r`   rR   r   r   r   r   r   intr   r   r   r   r   r   r   r   r   r   rT   rG   r  r
  r
   r  r   r  r#  r,  r  __classcell__)rK   s   @rL   r)   r)       s        BB
III*K !&7G!H!H!HJHHH8$)E-$H$H$HNMHHH-%+--FK''':d;;;L,//
 0426261,.<Y <Y<Y U<Y ^,	<Y
 !/<Y /<Y <Y <Y  S><Y <Y <Y <Y <Y 0/<Y|  371	
 

 /
 	
 

 
 
 [
< !! 371$* $*/$* $* 	$*
 $* $* $* "!$*LP# P P P P 5T#Y 5 5 5 X5 O$sHUO';"< O O O XO-M - - - -HS(5/=Q8R H H H H 8k 8s 8C 8TW 8 8 8 \8 )k )s )s ) ) ) \)!6$u+ !6 !6 !6 !6F	Xc 	Xhuo 	X 	X 	X 	X
T#s(^ 

 
 
 
 
	C 	 	 	 	!,! 6! 	!
 
! ! ! !J 	%
 %
U%
 6%
 	%

 
j	%
 %
 %
 %
NU 6 
	   .!U! ! 6	!
 
j	! ! ! !. -.. $((,BF.2 C= e% %%>?	
 %UO 
   /.> -.. $((,#.2BF#! #!C=#! e%#! }	#!
 %UO#! %%>?#! 
j	#! #! #! /.#!JWs Wt W W W W$& & & &   
 5
38n5
 
	5
 5
 5
 [5
n
c3h 
 
 
 
, ## 
	# # # [#J5 5 5 5 5 5 5 5:-- #tCy.)- 
c	- - - -^ $s) [0A    \" #%	"1 "1"1 Cy"1 3i	"1
 
d38n	"1 "1 "1 "1L #%	- -- Cy- 3i	-
 
- - - -^Y Y Y Y Y Y Y YrM   r)   )>pathlibr   typingr   r   r   r   r   r	   r
   redis.commands.search.reducerscommandssearchr   r   pydanticr   r   r   r   !redis.commands.search.aggregationr   r   r   redis.exceptionsr   redisvl.extensions.constantsr    redisvl.extensions.router.schemar   r   r   r   r   redisvl.indexr   redisvl.queryr   r   redisvl.query.filterr   redisvl.redis.connectionr   redisvl.redis.utilsr   r   r    redisvl.typesr!   redisvl.utils.logr"   redisvl.utils.utilsr#   r$   r%   redisvl.utils.vectorize.baser&   (redisvl.utils.vectorize.text.huggingfacer'   r.  r   r)   r;   rM   rL   <module>rN     sQ         B B B B B B B B B B B B B B B B B B 1 1 1 1 1 1 1 1 1 1 1 1  > > > > > > > > > > > > X X X X X X X X X X * * * * * * @ @ @ @ @ @              & % % % % % 7 7 7 7 7 7 7 7 $ $ $ $ $ $ ; ; ; ; ; ; A A A A A A A A A A ) ) ) ) ) ) ( ( ( ( ( ( S S S S S S S S S S 7 7 7 7 7 7 E E E E E E	H		NY NY NY NY NYY NY NY NY NY NYrM   