o
    Zh4                     @   s   d dl Z d dlmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZmZ d d	lmZ erDd d
lmZ erLd d
lmZ G dd deZdS )    N)TYPE_CHECKINGAnyOptionalSequence)
exceptions)Credentials)	Callbacks)Document)BaseDocumentCompressor)
ConfigDictField)get_client_infodiscoveryengine_v1alphac                
       sV  e Zd ZU dZeddZeed< eddZeed< eddZ	eed< ed	dZ
eed
< eddZeed< eddZeed< eddZee ed< eddZee ed< eddZee ed< eddZee ed< dZeed< def fddZd%ddZdedee dee fddZ	d&dee dedee dee fd d!Zed"d#d$Z  Z S )'VertexAIRanka  
    Initializes the Vertex AI Ranker with configurable parameters.

    Inherits from BaseDocumentCompressor for document processing
    and validation features, respectively.

    Attributes:
        project_id (str): Google Cloud project ID
        location_id (str): Location ID for the ranking service.
        ranking_config (str):
            Required. The  name of the rank service config, such as default_config.
            It is set to default_config by default if unspecified.
        model (str):
            The identifier of the model to use. It is one of:

            - ``semantic-ranker-512@latest``: Semantic ranking model
              with maximum input token size 512.

            It is set to ``semantic-ranker-512@latest`` by default if unspecified.
        top_n (int):
            The number of results to return. If this is
            unset or no bigger than zero, returns all
            results.
        ignore_record_details_in_response (bool):
            If true, the response will contain only
            record ID and score. By default, it is false,
            the response will contain record details.
        id_field (Optional[str]): Specifies a unique document metadata field
        to use as an id.
        title_field (Optional[str]): Specifies the document metadata field
        to use as title.
        credentials (Optional[Credentials]): Google Cloud credentials object.
        credentials_path (Optional[str]): Path to the Google Cloud service
        account credentials file.
    N)default
project_idgloballocation_idZdefault_configranking_configzsemantic-ranker-512@latestmodel
   top_nF!ignore_record_details_in_responseid_fieldtitle_fieldcredentialscredentials_pathclientkwargsc                    s6   t  jdi | |d| _| js|  | _dS dS )z
        Constructor for VertexAIRanker, allowing for specification of
        ranking configuration and initialization of Google Cloud services.

        The parameters accepted are the same as the attributes listed above.
        r   N )super__init__getr   _get_rank_service_client)selfr   	__class__r    ]/var/www/html/lang_env/lib/python3.10/site-packages/langchain_google_community/vertex_rank.pyr"   E   s
   zVertexAIRank.__init__return)discoveryengine_v1alpha.RankServiceClientc              
   C   s`   zddl m} W n ty } ztd|d}~ww |j| jr(| jp't| jndtdddS )z
        Returns a RankServiceClient instance for making API calls to the
        Vertex AI Ranking service.

        Returns:
            A RankServiceClient instance.
        r   r   zCould not import google-cloud-discoveryengine python package. Please, install vertexaisearch dependency group: `pip install langchain-google-community[vertexaisearch]`Nzvertex-ai-search)module)r   Zclient_info)	google.cloudr   ImportErrorZRankServiceClientr   r   r   Zfrom_service_account_filer   )r%   r   excr    r    r(   r$   Q   s$   
z%VertexAIRank._get_rank_service_clientquery	documentsc              
      s   ddl m  z fddt|D }W n ty'   tdj d Y nw dj dj d	j	 } j
|j||jjd
}z	jj|d}W n  tjym } ztdt|  tdt| |d}~ww fdd|jD S )z
        Reranks documents based on the provided query.

        Args:
            query: The query to use for reranking.
            documents: The list of documents to rerank.

        Returns:
            A list of reranked documents.
        r   r   c              	      sr   g | ]5\}}|j sjr|jjr jdjr |jjnt||j d jr3d|jjini qS ))idcontenttitler    )page_contentr   metadatar#   ZRankingRecordr   str).0idxdocr   r%   r    r(   
<listcomp>{   s"    
z2VertexAIRank._rerank_documents.<locals>.<listcomp>z
id_field 'z!' not found in document metadata.z	projects/z/locations/z/rankingConfigs/)r   r   r/   recordsr   r   )requestz%Error in Vertex AI Ranking API call: Nc                    sD   g | ]}t  js|jnd |j|jd jr j|jini dqS ) )r1   Zrelevance_score)r4   r5   )r	   r   r2   r1   Zscorer   r3   )r7   record)r%   r    r(   r;      s    )r,   r   	enumerateKeyErrorwarningswarnr   r   r   r   ZRankRequestr   r   r   r   Zrankcore_exceptionsZGoogleAPICallErrorprintr6   RuntimeErrorr<   )r%   r/   r0   r<   Zranking_config_pathr=   responseer    r:   r(   _rerank_documentsk   s<   

	
zVertexAIRank._rerank_documents	callbacksc                 C   s   |  ||S )ap  
        Compresses documents using Vertex AI's rerank API.

        Args:
            documents: List of Document instances to compress.
            query: Query string to use for compressing the documents.
            callbacks: Callbacks to execute during compression (not used here).

        Returns:
            A list of Document instances, compressed.
        )rI   )r%   r0   r/   rJ   r    r    r(   compress_documents   s   zVertexAIRank.compress_documentsignoreT)extraZarbitrary_types_allowed)r)   r*   )N)!__name__
__module____qualname____doc__r   r   r6   __annotations__r   r   r   r   intr   boolr   r   r   r   r   r   r   r   r"   r$   r   r	   rI   r   rK   r   Zmodel_config__classcell__r    r    r&   r(   r      sH   
 $

G
r   )rB   typingr   r   r   r   Zgoogle.api_corer   rD   Zgoogle.auth.credentialsr   Zlangchain_core.callbacksr   Zlangchain_core.documentsr	   Z#langchain_core.documents.compressorr
   Zpydanticr   r   Z!langchain_google_community._utilsr   r,   r   r   r    r    r    r(   <module>   s    