
    Q
i                     b    d dl Z d dlmZmZmZmZmZmZ d dlm	Z	 d dl
mZ  G d de          ZdS )    N)AnyDictListOptionalTupleUnion)PrivateAttr)BaseRerankerc                       e Zd ZU dZ e            Zeed<    e            Zeed<   	 	 	 	 dde	de
ee	                  d	ed
ede
e         f
 fdZde
e         fdZde	deeee	ef                  ee	         f         fdZedeeee	ef                  ee	         f         dee         deee         ee         f         fd            Zde	deeee	ef                  ee	         f         deeeee	ef                  ee         f         eee	ef                  f         fdZde	deeee	ef                  ee	         f         deeeee	ef                  ee         f         eee	ef                  f         fdZ xZS )VoyageAIRerankera#  
    The VoyageAIReranker class uses VoyageAI's API to rerank documents based on an
    input query.

    This reranker is designed to interact with VoyageAI's /rerank API,
    requiring an API key for authentication. The key can be provided
    directly in the `api_config` dictionary or through the `VOYAGE_API_KEY`
    environment variable. User must obtain an API key from VoyageAI's website
    (https://dash.voyageai.com/). Additionally, the `voyageai` python
    client must be installed with `pip install voyageai`.

    .. code-block:: python

        from redisvl.utils.rerank import VoyageAIReranker

        # set up the VoyageAI reranker with some configuration
        reranker = VoyageAIReranker(rank_by=["content"], limit=2)
        # rerank raw search results based on user input/query
        results = reranker.rank(
            query="your input query text here",
            docs=[
                {"content": "document 1"},
                {"content": "document 2"},
                {"content": "document 3"}
            ]
        )
    _client_aclientN   Tmodelrank_bylimitreturn_score
api_configc                 n    t                                          ||||            | j        |fi | dS )a  
        Initialize the VoyageAIReranker with specified model, ranking criteria,
        and API configuration.

        Parameters:
            model (str): The identifier for the VoyageAI model used for reranking.
            rank_by (Optional[List[str]]): Optional list of keys specifying the
                attributes in the documents that should be considered for
                ranking. None means ranking will rely on the model's default
                behavior.
            limit (int): The maximum number of results to return after
                reranking. Must be a positive integer.
            return_score (bool): Whether to return scores alongside the
                reranked results.
            api_config (Optional[Dict], optional): Dictionary containing the API key.
                Defaults to None.

        Raises:
            ImportError: If the voyageai library is not installed.
            ValueError: If the API key is not provided.
        )r   r   r   r   N)super__init___initialize_clients)selfr   r   r   r   r   kwargs	__class__s          C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\redisvl/utils/rerank/voyageai.pyr   zVoyageAIReranker.__init__)   sR    < 	L 	 	
 	
 	
 	! 66v66666    c                    	 ddl m}m} n# t          $ r t          d          w xY w|r|                    d          nt          j        d          }|st          d           |dd|i|| _         |dd|i|| _	        dS )	zk
        Setup the VoyageAI clients using the provided API key or an
        environment variable.
        r   )AsyncClientClientzoVoyageAI reranker requires the voyageai library.                     Please install with `pip install voyageai`api_keyVOYAGE_API_KEYzfVoyageAI API key is required. Provide it in api_config or set the VOYAGE_API_KEY environment variable.N )
voyageair   r    ImportErrorgetosgetenv
ValueErrorr   r   )r   r   r   r   r    r!   s         r   r   z$VoyageAIReranker._initialize_clientsL   s    	444444444 	 	 	@  	 *4TJNN9%%%CS9T9T 	  	[   v88g888#>>G>v>>s    %querydocsc                 r   |                     d| j                  }|                     d| j                  }|                     d          }t          |t                    st          d          t          d |D                       rd |D             }nd |D             }||| j        |d}|||d<   ||fS )	zo
        Prepare and validate reranking config based on provided input and
        optional overrides.
        r   r   
truncationz6Docs to rerank should either be a list of str or dict.c              3   H   K   | ]}t          |t                    od |v V  dS )contentN)
isinstancedict.0docs     r   	<genexpr>z/VoyageAIReranker._preprocess.<locals>.<genexpr>t   s6      JJcz#t$$9c)9JJJJJJr   c                 j    g | ]0}t          |t                    rd |v t          |d                    1S )r/   )r0   r1   strr2   s     r   
<listcomp>z0VoyageAIReranker._preprocess.<locals>.<listcomp>u   sM       c4(( .7#-=-= C	N##-=-=-=r   c                 ,    g | ]}t          |          S r#   )r7   r2   s     r   r8   z0VoyageAIReranker._preprocess.<locals>.<listcomp>{   s    ...#SXX...r   )r*   	documentsr   top_k)r&   r   r   r0   listr)   allr   )	r   r*   r+   r   r   r   r-   textsreranker_kwargss	            r   _preprocesszVoyageAIReranker._preprocessf   s     

7DJ//zz.$2CDDZZ--
$%% 	WUVVVJJTJJJJJ 	/   EE /....E Z	
 
 !,6OL),,r   rankingsreturnc                     g g }}|j         D ]<}|                    |j                   |                    | |j                            =||fS )zm
        Post-process the initial list of documents to include ranking scores,
        if specified.
        )resultsappendrelevance_scoreindex)r+   rA   reranked_docsscoresitems        r   _postprocesszVoyageAIReranker._postprocess   s]     !#Bv$ 	3 	3DMM$.///  dj!12222f$$r   c                      | j         ||fi |\  }} | j        j        di |}|                     ||          \  }}|r||fS |S )  
        Rerank documents based on the provided query using the VoyageAI rerank API.

        This method processes the user's query and the provided documents to
        rerank them in a manner that is potentially more relevant to the
        query's context.

        Parameters:
            query (str): The user's search query.
            docs (Union[List[Dict[str, Any]], List[str]]): The list of documents
                to be ranked, either as dictionaries or strings.

        Returns:
            Union[Tuple[Union[List[Dict[str, Any]], List[str]], float], List[Dict[str, Any]]]: The reranked list of documents and optionally associated scores.
        r#   )r@   r   rerankrK   	r   r*   r+   r   r?   r   rA   rH   rI   s	            r   rankzVoyageAIReranker.rank   sr    $ )9(8(O(O(O(O%&4<&9999 $ 1 1$ A Av 	) &((r   c                    K    | j         ||fi |\  }} | j        j        di | d{V }|                     ||          \  }}|r||fS |S )rM   Nr#   )r@   r   rN   rK   rO   s	            r   arankzVoyageAIReranker.arank   s      $ )9(8(O(O(O(O%--@@@@@@@@@@ $ 1 1$ A Av 	) &((r   )Nr   TN)__name__
__module____qualname____doc__r	   r   r   __annotations__r   r7   r   r   intboolr   r   r   r   r@   staticmethodr   floatrK   rP   rR   __classcell__)r   s   @r   r   r   	   s         8 ;==GS   KMMHc!!!
 (,!%)!7 !7!7 $s)$!7 	!7
 !7 TN!7 !7 !7 !7 !7 !7F?htn ? ? ? ?4 - - %d4S>&:DI&E F -  -  -  -D %Dc3h($s)34%s)% 
tCy$u+%	&% % % \% %d4S>&:DI&E F	uT$sCx.)4;67d38n9MM	N   2 %d4S>&:DI&E F	uT$sCx.)4;67d38n9MM	N       r   r   )r'   typingr   r   r   r   r   r   pydanticr	   redisvl.utils.rerank.baser
   r   r#   r   r   <module>r`      s    				 : : : : : : : : : : : : : : : :             2 2 2 2 2 2~ ~ ~ ~ ~| ~ ~ ~ ~ ~r   