
    Ng8-                    d   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j*        e+          Z, G d de-          Z.d%dZ/d&dZ0d'dZ1d(dZ2d)d"Z3d)d#Z4 G d$ dee          Z5dS )*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dS )ChatGooglePalmErrorz!Error with the `Google PaLM` API.N)__name__
__module____qualname____doc__     g/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/google_palm.pyr    r    (   s        ++++r&   r    textstrstopOptional[List[str]]returnc                b    || S |D ]'}|                      |          }|dk    r
| d|         } (| S )z0Truncates text at the earliest stop token found.N)find)r(   r*   
stop_tokenstop_token_idxs       r'   _truncate_at_stop_tokensr2   ,   sM    
 | ) )
:..R(DKr&   responsegenai.types.ChatResponser   c           
     v   | j         st          d          g }| j         D ]	}|                    d          }|t          d|           t          |                    dd          |          }|t          d|           |dk    r3|                    t          |t          |	          
                     |dk    r3|                    t          |t          |	          
                     |                    t          |t          ||          
                     t          |          S )z9Converts a PaLM API response into a LangChain ChatResult.z.ChatResponse must have at least one candidate.authorNz"ChatResponse must have an author: content z"ChatResponse must have a content: ai)r7   )r(   messagehuman)roler7   )generations)

candidatesr    getr2   appendr   r   r   r   r   )r3   r*   r=   	candidater6   r7   s         r'   _response_to_resultrB   ;   s   
  T!"RSSS(*K(  	x((>%&V9&V&VWWW*9==B+G+GNN?%&V9&V&VWWWT>>GYw5O5O5OPPP    w (999       'VWEEE      +....r&   input_messagesList[BaseMessage]genai.types.MessagePromptDictc                   ddl m} d}g }g }t          t          |                     }|rE|                    d          \  }}t          |t                    r1|dk    rt          d          t          t          |j
                  }nt          |t                    r|j        r|rt          d          |                    d          \  }}	t          |	t                    r^|	j        rW|                    |j                            d|j
                  |j                            d|	j
                  g           n,t          d	          t          |t                    r|j        rt          d
          t          |t                    r5|                    |j                            d|j
                             nt          |t                    r5|                    |j                            d|j
                             n^t          |t$                    r:|                    |j                            |j        |j
                             nt          d          |E|j                            |||          S )zNConverts a list of LangChain messages into a PaLM API MessagePrompt structure.r   Nr8   z+System message must be first input message.z1Message examples must come before other messages.r;   )r6   r7   r9   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
   r)   r7   r   exampler   extendtypesMessageDictr@   r   r<   MessagePromptDict)
rC   genairG   rH   rI   	remainingindexinput_message_next_input_messages
             r'   _messages_to_prompt_dictr[   c   s    ('''''G.0H.0HY~..//I
 3(}}Q//}m]33 0	zz)*WXXX3 566GG|44 ,	9N ,	 )G   %.MM!$4$4!A!,i88 =O=W //#*M4I 0   //#'1C1K 0  		 	 	 	 *,   y11 	m6K 	%#   y11 	OO''t]=R'SS    |44 	OO''w@U'VV    {33 		OO''(-}7L (      &N  c  3j ;(( )   r&   Callable[[Any], Any]c            
     j   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)googlerb   min_secondsmax_secondsmax_retriess        r'   _create_retry_decoratorru      s    %%%%JKKK,,+VVV#FO$>$PQQ%fo&@&STTU%fo&@&OPPQ &fgo>>
 
 
 
r&   llmChatGooglePalmkwargsr   c                L     t                      }|d fd            } |di |S )z*Use tenacity to retry the completion call.rx   r   r,   c                 (     j         j        di | S Nr%   )clientchatrx   rv   s    r'   _chat_with_retryz)chat_with_retry.<locals>._chat_with_retry   s    sz(((((r&   rx   r   r,   r   r%   ru   )rv   rx   retry_decoratorr   s   `   r'   chat_with_retryr      sO    -//O) ) ) ) ) _) %%f%%%r&   c                \    K   t                      }|d fd            } |di | d{V S )z0Use tenacity to retry the async completion call.rx   r   r,   c                 8   K    j         j        di |  d {V S r{   )r|   
chat_asyncr~   s    r'   _achat_with_retryz+achat_with_retry.<locals>._achat_with_retry   s6       +SZ*44V444444444r&   Nr   r%   r   )rv   rx   r   r   s   `   r'   achat_with_retryr      se      -//O5 5 5 5 5 _5 #",,V,,,,,,,,,r&   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.d0d&Zed1d(            Zed2d)            ZdS )3rw   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   r|   zmodels/chat-bison-001r)   
model_nameNzOptional[SecretStr]google_api_keyzOptional[float]temperaturetop_pzOptional[int]top_kr_   intnr,   Dict[str, str]c                
    ddiS )Nr   GOOGLE_API_KEYr%   selfs    r'   
lc_secretszChatGooglePalm.lc_secrets   s     "233r&   boolc                    dS )NTr%   r   s    r'   is_lc_serializablez!ChatGooglePalm.is_lc_serializable   s    tr&   	List[str]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&   valuesr   c                   t          t          |dd                    }	 ddlm}  |j        |                                           n# t          $ r t          d          w xY w||d<   |d         $d|d         cxk    rd	k    sn t          d
          |d         $d|d         cxk    rd	k    sn t          d          |d         |d         dk    rt          d          |S )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`r|   r   r_   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   rJ   rK   	configureget_secret_valueImportErrorr    
ValueError)r   r   r   rU   s       r'   validate_environmentz#ChatGooglePalm.validate_environment  sC    / )9;KLL
 
	//////EON$C$C$E$EFFFFF 	 	 	%K  	 !x- ,Q&:O5T5T5T5TST5T5T5T5TJKKK'?&qF7O/H/H/H/Hq/H/H/H/HDEEE'?&6'?a+?+?5666s   )A
 
A$rI   rD   r*   r+   run_manager"Optional[CallbackManagerForLLMRun]rx   r   c           
         t          |          }t          | f| j        || j        | j        | j        | j        d|}t          ||          S N)modelpromptr   r   r   candidate_count)r[   r   r   r   r   r   r   rB   r   rI   r*   r   rx   r   r3   s          r'   	_generatezChatGooglePalm._generate%  sf     *(33-<	.
/(** F	.
 	.
 	.
 	.
 #8T222r&   'Optional[AsyncCallbackManagerForLLMRun]c           	        K   t          |          }t          | | j        || j        | j        | j        | j                   d {V }t          ||          S r   )r[   r   r   r   r   r   r   rB   r   s          r'   
_ageneratezChatGooglePalm._agenerate;  sy       *(333C/(** F4
 4
 4
 .
 .
 .
 .
 .
 .
 #8T222r&   Dict[str, Any]c                D    | 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  s-     /+ZZ
 
 	
r&   c                    dS )Nzgoogle-palm-chatr%   r   s    r'   	_llm_typezChatGooglePalm._llm_type[  s    !!r&   )r,   r   )r,   r   )r,   r   )r   r   r,   r   )NN)
rI   rD   r*   r+   r   r   rx   r   r,   r   )
rI   rD   r*   r+   r   r   rx   r   r,   r   )r,   r   )r,   r)   )r!   r"   r#   r$   __annotations__r   r   r   r   r   r   propertyr   classmethodr   r   r   r   r   r   r   r   r%   r&   r'   rw   rw      s         " KKK-J----*.N....#'K''''!E!!!!XEAJJJJI 4 4 4 X4    [ ; ; ; [;    X> %):>	3 3 3 3 32 %)?C	3 3 3 3 3* 
 
 
 X
 " " " X" " "r&   )r(   r)   r*   r+   r,   r)   )r3   r4   r*   r+   r,   r   )rC   rD   r,   rE   )r,   r\   )rv   rw   rx   r   r,   r   )6r$   
__future__r   ro   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   rJ   rK   rU   	getLoggerr!   rn   	Exceptionr    r2   rB   r[   ru   r   r   rw   r%   r&   r'   <module>r      s   , , " " " " " "  K K K K K K K K K K K K K K K K K K        E D D D D D                     W V V V V V V V V V ) ) ) ) ) ) ) )               (''''''		8	$	$, , , , ,) , , ,   %/ %/ %/ %/PE E E EP   ,& & & &	- 	- 	- 	-E" E" E" E" E"]I E" E" E" E" E"r&   