
    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 )CohereRerankera  
    The CohereReranker class uses Cohere's API to rerank documents based on an
    input query.

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

    .. code-block:: python

        from redisvl.utils.rerank import CohereReranker

        # set up the Cohere reranker with some configuration
        reranker = CohereReranker(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_aclientrerank-english-v3.0N   Tmodelrank_bylimitreturn_score
api_configc                 n    t                                          ||||            | j        |fi | dS )a  
        Initialize the CohereReranker with specified model, ranking criteria,
        and API configuration.

        Parameters:
            model (str): The identifier for the Cohere model used for reranking.
                Defaults to 'rerank-english-v3.0'.
            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 cohere 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/cohere.pyr   zCohereReranker.__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d|| _         |d
|dd|| _	        d	S )zi
        Setup the Cohere clients using the provided API key or an
        environment variable.
        r   )AsyncClientClientziCohere reranker requires the cohere library.                     Please install with `pip install cohere`api_keyCOHERE_API_KEYzdCohere API key is required. Provide it in api_config or set the COHERE_API_KEY environment variable.redisvl)r"   client_nameN )
coherer    r!   ImportErrorgetosgetenv
ValueErrorr   r   )r   r   r   r    r!   r"   s         r   r   z"CohereReranker._initialize_clientsM   s    	222222222 	 	 	>  	 *4TJNN9%%%CS9T9T 	  	[   vOg9OOOO#UGUUfUUs    %querydocsc                    |                     d| j                  }|                     d| j                  }|                     d          }|                     d| j                  pg }t	          |t
                    r|gn|}| j        ||||d}t          d |D                       r|r||d<   nt          d          ||fS )	zo
        Prepare and validate reranking config based on provided input and
        optional overrides.
        r   r   max_chunks_per_docr   )r   r-   top_n	documentsr0   c              3   @   K   | ]}t          |t                    V  d S )N)
isinstancedict).0docs     r   	<genexpr>z-CohereReranker._preprocess.<locals>.<genexpr>|   s,      55z#t$$555555r   rank_fieldszLIf reranking dictionary-like docs, you must provide a list of rank_by fields)	r)   r   r   r   r4   strr   allr,   )	r   r-   r.   r   r   r   r0   r   reranker_kwargss	            r   _preprocesszCohereReranker._preprocessg   s     

7DJ//zz.$2CDD#ZZ(<==**Y55;)'377D7))W Z"4
 
 5555555 	 18.. @  
 ,,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.   r>   reranked_docsscoresitems        r   _postprocesszCohereReranker._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 Cohere 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   rerankrH   	r   r-   r.   r   r<   r   r>   rE   rF   s	            r   rankzCohereReranker.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 )rJ   Nr&   )r=   r   rK   rH   rL   s	            r   arankzCohereReranker.arank   s      $ )9(8(O(O(O(O%--@@@@@@@@@@ $ 1 1$ A Av 	) &((r   )r   Nr   TN)__name__
__module____qualname____doc__r	   r   r   __annotations__r   r:   r   r   intboolr   r   r   r   r=   staticmethodr   floatrH   rM   rO   __classcell__)r   s   @r   r   r   	   s         8 ;==GS   KMMHc!!! +'+!%)"7 "7"7 $s)$"7 	"7
 "7 TN"7 "7 "7 "7 "7 "7HVhtn V V V V4-- %d4S>&:DI&E F- - - -@ %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   