
    3fi&                         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
eedf         Zy)    )TYPE_CHECKINGAnyDictListOptional)
exceptions)Credentials)Document)RunnableConfigRunnableSerializable)	BaseModel
ConfigDictField)get_client_infodiscoveryengine_v1alphac                       e Zd ZU dZ ed      Zeed<    ed      Zeed<    ed      Z	eed<    ed	      Z
ee   ed
<   dZeed<    ed      Zee   ed<    ed      Zee   ed<    G d de      Zdef fdZ	 	 ddZ	 d dedee   defdZdee   dee   fdZdeeeef      defdZedee   fd       Zedefd       Z  e!dd      Z" x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: Google Cloud project ID
        location_id: Location ID for the ranking service.
        grounding_config: 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: 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_iddefault_grounding_configgrounding_configg333333?citation_thresholdclientcredentialscredentials_pathc                   f    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<   y)4VertexAICheckGroundingWrapper.CheckGroundingResponseg        support_scorecited_chunksclaims answer_with_citationsN)__name__
__module____qualname__r!   float__annotations__r"   r   r   strr   r#   r%        o/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_google_community/vertex_check_grounding.pyCheckGroundingResponser    3   sE    "u"-/d4S>*/')T#s(^$)%'s'r-   r/   kwargsc                     t        |   di | |j                  d      | _        | j                  s| j	                         | _        yy)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)selfr0   	__class__s     r.   r3   z&VertexAICheckGroundingWrapper.__init__9   sA     	"6"jj*{{BBDDK r-   returnc                     	 ddl m}  |j                  | j                  xs- | j
                  rt        j                  | j
                        ndt        d            S # t        $ r}t        d      |d}~ww xY w)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   client_info)	google.cloudr   ImportErrorGroundedGenerationServiceClientr   r   r	   from_service_account_filer   )r6   r   excs      r.   r5   zAVertexAICheckGroundingWrapper._get_check_grounding_service_clientD   s    	< G&FF    ,,  99$:O:OP (/AB

 
	
  	K 		s   A 	A9(A44A9inputconfigc                 Z   ddl m} |}| j                  |      } |j                  | j                        }|D 	cg c]b  }|j
                  rT |j                  |j
                  |j                  xs i j                         D 	ci c]  \  }}	|dvr|	||	 c}	}      d }
}}}	|
st        d       |j                  d| j                   d	| j                   d
| j                   ||
|      }| j                  t        d      	 | j                  j                  |      }|j(                  }|j*                  D cg c]'  }|j,                  |t/        |j0                           d) }}|j2                  D cg c]:  }|j4                  |j6                  |j8                  t;        |j<                        d< }}| j?                  |      }| jA                  ||||      S c c}	}w c c}	}}w # t         j"                  $ r}t%        dt'        |             |d}~ww xY wc c}w c c}w )av  
        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:
            input: The candidate answer to be evaluated for grounding.
            config: Runnable configuration containing documents in
                `config["configurable"]["documents"]`. The documents are used as
                grounding facts and will be converted to
                `google.cloud.discoveryengine_v1alpha.types.GroundingFact` objects.
                Supports 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   )idrelevance_scoreN)	fact_text
attributesz*No valid documents provided for grounding.z	projects/z/locations/z/groundingConfigs/)r   answer_candidatefactsgrounding_speczClient not initialized.)requestz-Error in Vertex AI Check Grounding API call: )
chunk_textsource)	start_posend_pos
claim_textcitation_indices)r!   r"   r#   r%   )!r<   r   extract_documentsCheckGroundingSpecr   page_contentGroundingFactmetadataitems
ValueErrorCheckGroundingRequestr   r   r   r   check_groundingcore_exceptionsGoogleAPICallErrorRuntimeErrorr+   r!   r"   rL   intrM   r#   rN   rO   rP   listrQ   combine_claims_with_citationsr/   )r6   rA   rB   r   rH   	documentsrJ   dockeyvaluerI   rK   responseer!   chunkr"   claimr#   r%   s                       r.   invokez$VertexAICheckGroundingWrapper.invokeb   sl   R 	9 **62	C0CC#66
 !
 
  2#11** *eg	"U ";;@Q	 J	
 
 IJJ?)??((9TEUEUDVVhimi~i~h  A-)	
 ;;677	{{2272CH !.. "..

  $..#C$56
 
 "
  #__ ==#..$()?)?$@	
 
 !% B B6 J**'%"7	 + 
 	
e
: 11 	?AxH	

s<   A	G)G#G)
G0  ,H#<?H(#G)0H HH c                     |st        d      |j                  di       j                  dg       }t        |t              rt	        d |D              st        d      |st        d      |S )NzConfiguration is required.configurablera   c              3   <   K   | ]  }t        |t                y wN)
isinstancer
   ).0rb   s     r.   	<genexpr>zBVertexAICheckGroundingWrapper.extract_documents.<locals>.<genexpr>   s      @
*-JsH%@
s   z8Invalid documents. Each must be an instance of Document.z/This wrapper requires documents for processing.)rX   r4   rn   r_   all)r6   rB   potential_documentss      r.   rR   z/VertexAICheckGroundingWrapper.extract_documents   ss    9::$jj<@@bQ-t4C @
1D@
 =
 WXX"NOO""r-   r#   c           	         t        |d       }g }|D ]M  }|d   r0dj                  |d   D cg c]  }d| d
 c}      }|d    | }n|d   }|j                  |       O dj                  |      j                         S c c}w )	Nc                     | d   S )NrN   r,   )xs    r.   <lambda>zMVertexAICheckGroundingWrapper.combine_claims_with_citations.<locals>.<lambda>   s
    Q{^ r-   )rc   rQ   r$   []rP    )sortedjoinappendstrip)r6   r#   sorted_claimsresultrh   idx	citationsrP   s           r.   r`   z;VertexAICheckGroundingWrapper.combine_claims_with_citations   s    v+CD" 	&E'(GG5AS;T$UCqQZ$UV	 %l 34YK@
"<0
MM*%	& xx%%'' %Vs   B
c                 
    g dS )N)	langchain	utilitiesrZ   r,   clss    r.   get_lc_namespacez.VertexAICheckGroundingWrapper.get_lc_namespace   s    <<r-   c                      y)NFr,   r   s    r.   is_lc_serializablez0VertexAICheckGroundingWrapper.is_lc_serializable   s    r-   ignoreT)extraarbitrary_types_allowed)r8   z7discoveryengine_v1alpha.GroundedGenerationServiceClientrm   )$r&   r'   r(   __doc__r   r   r+   r*   r   r   r   r   r)   r   r   r   r	   r   r   r/   r3   r5   r   ri   r   r
   rR   r   r`   classmethodr   boolr   r   model_config__classcell__)r7   s   @r.   r   r      s[   2 D)J)X.K.!*DEcE*/*<<FC).t)<K+&<&+D&9hsm9( (	E 	E
	B
> >Bl
l
"*>":l
	l
\#(@ #T(^ #
(Dc3h4H 
(S 
( =c = = 4    $Lr-   r   r    N)typingr   r   r   r   r   google.api_corer   r[   google.auth.credentialsr	   langchain_core.documentsr
   langchain_core.runnablesr   r   pydanticr   r   r   !langchain_google_community._utilsr   r<   r   r+   r   r,   r-   r.   <module>r      s@    ; ; 9 / - I 1 1 =4gTTUgr-   