o
    Zh&                     @   s   d dl mZ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mZ d dlmZmZmZ d dlmZ er@d dlmZ G d	d
 d
eedf ZdS )    )TYPE_CHECKINGAnyDictListOptional)
exceptions)Credentials)Document)RunnableConfigRunnableSerializable)	BaseModel
ConfigDictField)get_client_infodiscoveryengine_v1alphac                       sT  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 ed
< dZeed< eddZee ed< eddZee ed< G dd deZdef fddZ		d'ddZ	d(dedee defddZdee dee fddZdeeeef  defddZedee fd d!Zedefd"d#Z e!d$d%d&Z"  Z#S ))VertexAICheckGroundingWrappera  
    Initializes the Vertex AI CheckGroundingOutputParser with configurable parameters.

    Calls the Check Grounding API to validate the response against a given set of
    documents and returns back citations that support the claims along with the cited
    chunks. Output is of the type CheckGroundingResponse.

    Attributes:
        project_id (str): Google Cloud project ID
        location_id (str): Location ID for the ranking service.
        grounding_config (str):
            Required. The resource name of the grounding config, such as
            ``default_grounding_config``.
            It is set to ``default_grounding_config`` by default if unspecified
        citation_threshold (float):
            The threshold (in [0,1]) used for determining whether a fact
            must be cited for a claim in the answer candidate. Choosing
            a higher threshold will lead to fewer but very strong
            citations, while choosing a lower threshold may lead to more
            but somewhat weaker citations. If unset, the threshold will
            default to 0.6.
        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_grounding_configgrounding_configg333333?citation_thresholdclientcredentialscredentials_pathc                   @   sV   e Zd ZU dZeed< g Zeee	e
f  ed< g Zeee	e
f  ed< dZe	ed< dS )4VertexAICheckGroundingWrapper.CheckGroundingResponseg        support_scorecited_chunksclaims answer_with_citationsN)__name__
__module____qualname__r   float__annotations__r   r   r   strr   r   r!    r(   r(   h/var/www/html/lang_env/lib/python3.10/site-packages/langchain_google_community/vertex_check_grounding.pyCheckGroundingResponse4   s
   
 r*   kwargsc                    s6   t  jdi | |d| _| js|  | _dS dS )z
        Constructor for CheckGroundingOutputParser.
        Initializes the grounding check service client with necessary credentials
        and configurations.
        r   Nr(   )super__init__getr   #_get_check_grounding_service_client)selfr+   	__class__r(   r)   r-   :   s
   z&VertexAICheckGroundingWrapper.__init__return7discoveryengine_v1alpha.GroundedGenerationServiceClientc              
   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 GroundedGenerationServiceClient instance using provided credentials.
        Raises ImportError if necessary packages are not installed.

        Returns:
            A GroundedGenerationServiceClient 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GroundedGenerationServiceClientr   r   r   Zfrom_service_account_filer   )r0   r   excr(   r(   r)   r/   E   s$   

zAVertexAICheckGroundingWrapper._get_check_grounding_service_clientinputconfigc              
      s
  ddl m  |}| | j| jd} fddD }|s#td jd| j d| j d	| j	 |||d
}| j
du rAtdz	| j
j|d}W n tjya } z
tdt| |d}~ww |j}	fdd|jD }
dd |jD }| |}| j|	|
||dS )a  
        Calls the Vertex Check Grounding API for a given answer candidate and a list
        of documents (claims) to validate whether the set of claims support the 
        answer candidate.

        Args:
            answer_candidate (str): The candidate answer to be evaluated for grounding.
            documents (List[Document]): The documents against which grounding is
            checked. This will be converted to facts:
                facts (MutableSequence[google.cloud.discoveryengine_v1alpha.types.                    GroundingFact]):
                List of facts for the grounding check.
                We support up to 200 facts.
        Returns:
            Response of the type CheckGroundingResponse

            Attributes:
            support_score (float):
                The support score for the input answer
                candidate. Higher the score, higher is the
                fraction of claims that are supported by the
                provided facts. This is always set when a
                response is returned.

            cited_chunks (MutableSequence[google.cloud.discoveryengine_v1alpha.types.                FactChunk]):
                List of facts cited across all claims in the
                answer candidate. These are derived from the
                facts supplied in the request.

            claims (MutableSequence[google.cloud.discoveryengine_v1alpha.types.                CheckGroundingResponse.Claim]):
                Claim texts and citation info across all
                claims in the answer candidate.
            
            answer_with_citations (str):
                Complete formed answer formatted with inline citations
        r   r   )r   c                    s6   g | ]}|j r j|j d d |jpi  D dqS )c                 S   s&   i | ]\}}|d vr|dur||qS ))idZrelevance_scoreNr(   ).0keyvaluer(   r(   r)   
<dictcomp>   s
    zCVertexAICheckGroundingWrapper.invoke.<locals>.<listcomp>.<dictcomp>)Z	fact_text
attributes)Zpage_contentZGroundingFactmetadataitemsr<   docr   r(   r)   
<listcomp>   s    z8VertexAICheckGroundingWrapper.invoke.<locals>.<listcomp>z*No valid documents provided for grounding.z	projects/z/locations/z/groundingConfigs/)r   answer_candidatefactsgrounding_specNzClient not initialized.)requestz-Error in Vertex AI Check Grounding API call: c                    s"   g | ]}|j  t|j d qS ))
chunk_textsource)rJ   intrK   )r<   chunk)	documentsr(   r)   rE      s    c                 S   s&   g | ]}|j |j|jt|jd qS ))	start_posend_pos
claim_textcitation_indices)rO   rP   rQ   listrR   )r<   claimr(   r(   r)   rE      s    )r   r   r   r!   )r6   r   extract_documentsZCheckGroundingSpecr   
ValueErrorZCheckGroundingRequestr   r   r   r   check_groundingcore_exceptionsZGoogleAPICallErrorRuntimeErrorr'   r   r   r   combine_claims_with_citationsr*   )r0   r9   r:   rF   rH   rG   rI   responseer   r   r   r!   r(   )r   rN   r)   invokea   sV   )





z$VertexAICheckGroundingWrapper.invokec                 C   sT   |st d|di dg }t|trtdd |D s"t d|s(t d|S )NzConfiguration is required.ZconfigurablerN   c                 s   s    | ]}t |tV  qd S N)
isinstancer	   rC   r(   r(   r)   	<genexpr>   s    

zBVertexAICheckGroundingWrapper.extract_documents.<locals>.<genexpr>z8Invalid documents. Each must be an instance of Document.z/This wrapper requires documents for processing.)rV   r.   r_   rS   all)r0   r:   Zpotential_documentsr(   r(   r)   rU      s   z/VertexAICheckGroundingWrapper.extract_documentsr   c                 C   sp   t |dd d}g }|D ]$}|d r'ddd |d D }|d  | }n|d }|| qd	| S )
Nc                 S   s   | d S )NrO   r(   )xr(   r(   r)   <lambda>   s    zMVertexAICheckGroundingWrapper.combine_claims_with_citations.<locals>.<lambda>)r=   rR   r    c                 S   s   g | ]}d | dqS )[]r(   )r<   idxr(   r(   r)   rE      s    zOVertexAICheckGroundingWrapper.combine_claims_with_citations.<locals>.<listcomp>rQ    )sortedjoinappendstrip)r0   r   Zsorted_claimsresultrT   Z	citationsrQ   r(   r(   r)   rZ      s   z;VertexAICheckGroundingWrapper.combine_claims_with_citationsc                 C   s   g dS )N)Z	langchainZ	utilitiesrW   r(   clsr(   r(   r)   get_lc_namespace   s   z.VertexAICheckGroundingWrapper.get_lc_namespacec                 C   s   dS )NFr(   rm   r(   r(   r)   is_lc_serializable   s   z0VertexAICheckGroundingWrapper.is_lc_serializableignoreT)extraZarbitrary_types_allowed)r3   r4   r^   )$r"   r#   r$   __doc__r   r   r'   r&   r   r   r   r   r%   r   r   r   r   r   r   r*   r-   r/   r
   r]   r   r	   rU   r   rZ   classmethodro   boolrp   r   Zmodel_config__classcell__r(   r(   r1   r)   r      s@   
 

nr   r   N)typingr   r   r   r   r   Zgoogle.api_corer   rX   Zgoogle.auth.credentialsr   Zlangchain_core.documentsr	   Zlangchain_core.runnablesr
   r   Zpydanticr   r   r   Z!langchain_google_community._utilsr   r6   r   r'   r   r(   r(   r(   r)   <module>   s    

