
    h8-                    z   d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZmZmZ dd
lmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z& erddl'm(Z)  ejT                  e+      Z, G d de-      Z.	 	 	 	 	 	 ddZ/	 	 	 	 	 	 ddZ0	 	 	 	 ddZ1ddZ2ddZ3ddZ4 G d dee      Z5y)z&Wrapper around Google's PaLM Chat API.    )annotationsN)TYPE_CHECKINGAnyCallableDictListOptionalcast)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModel)	AIMessageBaseMessageChatMessageHumanMessageSystemMessage)ChatGeneration
ChatResult)convert_to_secret_strget_from_dict_or_envpre_init)	BaseModel	SecretStr)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponentialc                      e Zd ZdZy)ChatGooglePalmErrorz!Error with the `Google PaLM` API.N)__name__
__module____qualname____doc__     i/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/chat_models/google_palm.pyr    r    (   s    +r&   r    c                T    || S |D ]  }| j                  |      }|dk7  s| d| }   | S )z0Truncates text at the earliest stop token found.N)find)textstop
stop_tokenstop_token_idxs       r'   _truncate_at_stop_tokensr/   ,   sF    
 | )
:.R(D) Kr&   c           
        | j                   st        d      g }| j                   D ]  }|j                  d      }|t        d|       t        |j                  dd      |      }|t        d|       |dk(  r'|j	                  t        |t        |      	             ||d
k(  r'|j	                  t        |t        |      	             |j	                  t        |t        ||      	              t        |      S )z9Converts a PaLM API response into a LangChain ChatResult.z.ChatResponse must have at least one candidate.authorz"ChatResponse must have an author: content z"ChatResponse must have a content: ai)r2   )r+   messagehuman)roler2   )generations)

candidatesr    getr/   appendr   r   r   r   r   )responser,   r8   	candidater1   r2   s         r'   _response_to_resultr>   ;   s	   
 !"RSS(*K(( 	x(>%(J9+&VWW*9==B+GN?%(J9+&VWWT>GYw5OP w (9  'VWE+8 +..r&   c                   ddl m} d}g }g }t        t        |             }|r(|j	                  d      \  }}t        |t              r,|dk7  rt        d      t        t        |j                        }nt        |t              r|j                  r|rt        d      |j	                  d      \  }}	t        |	t              rk|	j                  r_|j                  |j                  j!                  d|j                        |j                  j!                  d|	j                        g       nt        d	      t        |t              r|j                  rt        d
      t        |t              r7|j#                  |j                  j!                  d|j                               nt        |t              r7|j#                  |j                  j!                  d|j                               n\t        |t$              rA|j#                  |j                  j!                  |j&                  |j                               nt        d      |r(|j                  j)                  |||      S )zNConverts a list of LangChain messages into a PaLM API MessagePrompt structure.r   Nr3   z+System message must be first input message.z1Message examples must come before other messages.r6   )r1   r2   r4   zNHuman example message must be immediately followed by an  AI example response.zKAI example message must be immediately preceded by a Human example message.z<Messages without an explicit role not supported by PaLM API.)contextexamplesmessages)google.generativeaigenerativeailist	enumeratepop
isinstancer   r    r
   strr2   r   exampler   extendtypesMessageDictr;   r   r7   MessagePromptDict)
input_messagesgenair@   rA   rB   	remainingindexinput_message_next_input_messages
             r'   _messages_to_prompt_dictrV   c   s5    (G.0H.0HY~./I
(}}Q/}m]3z)*WXX3 5 56G|49N9N)G  %.MM!$4!A!,i8=O=W=W//#*M4I4I 0  //#'1C1K1K 0 		 *,  y1m6K6K%#  y1OO''t]=R=R'S |4OO''w@U@U'V {3OO''(--}7L7L (  &N c j ;;(( )  r&   c            
        ddl } d}d}d}d}t        dt        |      t        |||      t	        | j
                  j                  j                        t	        | j
                  j                  j                        z  t	        | j
                  j                  j                        z  t        t        t        j                        	      S )
zKReturns a tenacity retry decorator, preconfigured to handle PaLM exceptionsr   N      <   
   T)
multiplierminmax)reraiser,   waitr   before_sleep)google.api_core.exceptionsr   r   r   r   api_core
exceptionsResourceExhaustedServiceUnavailableGoogleAPIErrorr   loggerloggingWARNING)googler\   min_secondsmax_secondsmax_retriess        r'   _create_retry_decoratorro      s    %JKKK,+V#FOO$>$>$P$PQ%foo&@&@&S&STU%foo&@&@&O&OPQ &fgoo>
 
r&   ChatGooglePalmc                >     t               }|d fd       } |di |S )z*Use tenacity to retry the completion call.c                 <     j                   j                  di | S Nr%   )clientchatkwargsllms    r'   _chat_with_retryz)chat_with_retry.<locals>._chat_with_retry   s    szz(((r&   rw   r   returnr   r%   ro   )rx   rw   retry_decoratorry   s   `   r'   chat_with_retryr~      s-    -/O) ) %f%%r&   c                Z    K   t               }|d fd       } |di | d{   S 7 w)z0Use tenacity to retry the async completion call.c                 X   K    j                   j                  di |  d {   S 7 wrs   )rt   
chat_asyncrv   s    r'   _achat_with_retryz+achat_with_retry.<locals>._achat_with_retry   s)      +SZZ**4V4444s    *(*Nrz   r%   r|   )rx   rw   r}   r   s   `   r'   achat_with_retryr      s7     -/O5 5 #,V,,,,s   !+)+c                  &   e Zd ZU dZded<   dZded<   	 dZded	<   dZd
ed<   	 dZd
ed<   	 dZ	ded<   	 dZ
ded<   	 edd       Zedd       Zedd       Zedd       Z	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 d dZed!d       Zed"d       Zy)#rp   a  `Google PaLM` Chat models API.

    To use you must have the google.generativeai Python package installed and
    either:

        1. The ``GOOGLE_API_KEY`` environment variable set with your API key, or
        2. Pass your API key using the google_api_key kwarg to the ChatGoogle
           constructor.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatGooglePalm
            chat = ChatGooglePalm()

    r   rt   zmodels/chat-bison-001rI   
model_nameNzOptional[SecretStr]google_api_keyzOptional[float]temperaturetop_pzOptional[int]top_krY   intnc                
    ddiS )Nr   GOOGLE_API_KEYr%   selfs    r'   
lc_secretszChatGooglePalm.lc_secrets   s     "233r&   c                     y)NTr%   r   s    r'   is_lc_serializablez!ChatGooglePalm.is_lc_serializable   s    r&   c                
    g dS )z*Get the namespace of the langchain object.)	langchainchat_modelsgoogle_palmr%   )clss    r'   get_lc_namespacezChatGooglePalm.get_lc_namespace  s
     ;:r&   c                   t        t        |dd            }	 ddlm}  |j                  |j                                ||d<   |d   %d|d   cxk  rd	k  st        d
       t        d
      |d   %d|d   cxk  rd	k  st        d       t        d      |d   |d   dk  rt        d      |S # t        $ r t        d      w xY w)zGValidate api key, python package exists, temperature, top_p, and top_k.r   r   r   N)api_keyzmCould not import google.generativeai python package. Please install it with `pip install google-generativeai`rt   r   rY   z+temperature must be in the range [0.0, 1.0]r   z%top_p must be in the range [0.0, 1.0]r   ztop_k must be positive)	r   r   rC   rD   	configureget_secret_valueImportErrorr    
ValueError)r   valuesr   rP   s       r'   validate_environmentz#ChatGooglePalm.validate_environment  s    / )9;KL
	/EOON$C$C$EF !x- ,Q&:O5TST5TJKK 6UJKK'?&qF7O/Hq/HDEE 0IDEE'?&6'?a+?566#  	%K 	s   'B2 2Cc           
         t        |      }t        | f| j                  || j                  | j                  | j
                  | j                  d|}t        ||      S N)modelpromptr   r   r   candidate_count)rV   r~   r   r   r   r   r   r>   r   rB   r,   run_managerrw   r   r<   s          r'   	_generatezChatGooglePalm._generate%  sa     *(3-<	.
//((**** FF	.
 	.
 #8T22r&   c           	        K   t        |      }t        | | j                  || j                  | j                  | j
                  | j                         d {   }t        ||      S 7 wr   )rV   r   r   r   r   r   r   r>   r   s          r'   
_ageneratezChatGooglePalm._agenerate;  s`      *(33C//((**** FF4
 .
 #8T22.
s   AA(A&A(c                v    | j                   | j                  | j                  | j                  | j                  dS )zGet the identifying parameters.r   r   r   r   r   r   r   s    r'   _identifying_paramsz"ChatGooglePalm._identifying_paramsP  s3     //++ZZZZ
 	
r&   c                     y)Nzgoogle-palm-chatr%   r   s    r'   	_llm_typezChatGooglePalm._llm_type[  s    !r&   )r{   zDict[str, str])r{   bool)r{   z	List[str])r   r   r{   r   )NN)
rB   List[BaseMessage]r,   Optional[List[str]]r   z"Optional[CallbackManagerForLLMRun]rw   r   r{   r   )
rB   r   r,   r   r   z'Optional[AsyncCallbackManagerForLLMRun]rw   r   r{   r   )r{   zDict[str, Any])r{   rI   )r!   r"   r#   r$   __annotations__r   r   r   r   r   r   propertyr   classmethodr   r   r   r   r   r   r   r   r%   r&   r'   rp   rp      sU   " K-J-*.N'.#'K'!E?!XE=AsJI 4 4   ; ;  > %):>	3#3 "3 8	3
 3 
32 %)?C	3#3 "3 =	3
 3 
3* 
 
 " "r&   )r+   rI   r,   r   r{   rI   )r<   zgenai.types.ChatResponser,   r   r{   r   )rO   r   r{   zgenai.types.MessagePromptDict)r{   zCallable[[Any], Any])rx   rp   rw   r   r{   r   )6r$   
__future__r   ri   typingr   r   r   r   r   r	   r
   langchain_core.callbacksr   r   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   r   langchain_core.outputsr   r   langchain_core.utilsr   r   r   pydanticr   r   tenacityr   r   r   r   r   rC   rD   rP   	getLoggerr!   rh   	Exceptionr    r/   r>   rV   ro   r~   r   rp   r%   r&   r'   <module>r      s    , "  K K K E  W V )  '			8	$,) ,

 	%/&%/
%/ %/PE%E"EP,&	-E"]I E"r&   