
    Ng8                       d Z ddlmZ ddlZddlZddlZddlmZmZ ddl	m
Z
mZmZmZmZmZmZmZ ddlmZ ddlZddlmZ ddlmZmZ dd	lmZmZ dd
lmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ e
rddl0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6  ej7        e8          Z9e G d d                      Z:d+dZ;d,dZ<d-dZ=d.d!Z>d/d$Z? ed%d&d'(           G d) d*e*e                      Z@dS )0z1Wrapper around Google VertexAI chat-based models.    )annotationsN)	dataclassfield)TYPE_CHECKINGAnyDictIteratorListOptionalUnioncast)urlparse)
deprecated)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModelgenerate_from_stream)	AIMessageAIMessageChunkBaseMessageHumanMessageSystemMessage)ChatGenerationChatGenerationChunk
ChatResult)pre_init)_VertexAICommonis_codey_modelis_gemini_model)load_image_from_gcsraise_vertex_import_error)ChatMessageChatSessionCodeChatSessionInputOutputTextPair)Contentc                  D    e Zd ZU dZ ee          Zded<   dZded<   dS )_ChatHistoryz/Represents a context and a history of messages.)default_factoryzList['ChatMessage']historyNOptional[str]context)	__name__
__module____qualname____doc__r   listr*   __annotations__r,        d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/vertexai.pyr(   r(   6   sG         99#(5#>#>#>G>>>>!G!!!!!!r4   r(   r*   List[BaseMessage]returnc                   ddl m} g d}}t          |           D ]\  }}t          t          |j                  }|dk    rt          |t                    r|}=t          |t                    r( ||j        d          }|	                    |           zt          |t                    r( ||j        d          }|	                    |           t          dt          |           d| d	          t          ||
          }|S )a  Parse a sequence of messages into history.

    Args:
        history: The list of messages to re-create the history of the chat.
    Returns:
        A parsed chat history.
    Raises:
        ValueError: If a sequence of message has a SystemMessage not at the
        first place.
    r   )r"   Nbot)contentauthoruserUnexpected message with type  at the position .)r,   r*   )vertexai.language_modelsr"   	enumerater   strr:   
isinstancer   r   appendr   
ValueErrortyper(   )	r*   r"   vertex_messagesr,   imessager:   vertex_messagechat_historys	            r5   _parse_chat_historyrL   >   s0    544444!4WO((  
7sGO,,66j-886GG++ 		([OOON"">2222.. 	([PPPN"">2222TWTTPQTTT    IIILr4   srB   boolc                    	 t          |           }t          |j        |j        g          S # t          $ r(}t
                              d|            Y d }~dS d }~ww xY w)NzUnable to parse URL: F)r   allschemenetloc	Exceptionloggerdebug)rM   resultes      r5   _is_urlrX   ^   sp    !FM6=1222   0Q00111uuuuus   ), 
AAAprojectr+   List['Content']c                  
 ddl m}m
m d
fdg }t	          |           D ]\  }}|dk    r$t          |t                    rt          d          t          |t                    rd	}n;t          |t                    rd
}n#t          dt          |           d| d          |j        }t          |t                    r|g}fd|D             } |||          }	|                    |	           |S )Nr   )r&   ImagePartpartUnion[str, Dict]r7   r]   c                   t          | t                    r                    |           S t          | t                    s t	          dt          |            d          | d         dk    r                    | d                   S | d         dk    r| d         d         }|                    d          rt          |          }n|                    d	          rdt          j	        d
|          }|r|
                    d          }nt	          d                              t          j        |                    }nwt          |          rCt          j        |          }|                                                     |j                  }n%                    |          }nt	          d                              |          S )Nz0Message's content is expected to be a dict, got !rF   text	image_urlurlzgs://)pathrY   zdata:image/zdata:image/\w{2,4};base64,(.*)   zdInvalid image uri. It should be in the format data:image/<image_type>;base64,<base64_encoded_image>.z,Only text and image_url types are supported!)rC   rB   	from_textr   rE   rF   
startswithr    researchgroup
from_bytesbase64	b64decoderX   requestsgetraise_for_statusr:   load_from_file
from_image)r^   re   imageencodedresponser\   r]   rY   s        r5   _convert_to_promptz6_parse_chat_history_gemini.<locals>._convert_to_promptl   s   dC   	(>>$'''$%% 	P4::PPP   <6!!>>$v,///&\[(($U+Dw'' 3+wGGG// 3!y)JDQQ %mmA..GG$Q   (()9')B)BCC 3#<--))+++(()9::,,T22KLLLu%%%r4   z%SystemMessages are not yet supported!modelr<   r=   r>   r?   c                &    g | ]} |          S r3   r3   ).0r^   rw   s     r5   
<listcomp>z._parse_chat_history_gemini.<locals>.<listcomp>   s%    BBBd##D))BBBr4   )roleparts)r^   r_   r7   r]   )"vertexai.preview.generative_modelsr&   r\   r]   rA   rC   r   rE   r   r   rF   r:   rB   rD   )r*   rY   r&   rG   rH   rI   r|   raw_contentr}   rJ   r\   r]   rw   s    `        @@@r5   _parse_chat_history_geminir   g   se    HGGGGGGGGG!& !& !& !& !& !& !& !&F O(( / /
766j-886DEEE++ 	DD.. 	DDTWTTPQTTT   ok3'' 	(&-KBBBBkBBB d%888~....r4   examplesList['InputOutputTextPair']c                   ddl m} t          |           dz  dk    r t          dt          |            d          g }d }t	          |           D ]\  }}|dz  dk    r?t          |t                    s#t          dt          |           d| d          |j        }|dz  d	k    r_t          |t                    s#t          d
t          |           d| d           |||j                  }|
                    |           |S )Nr   )r%      z8Expect examples to have an even amount of messages, got r?   z;Expected the first message in a part to be from human, got z	 for the zth message.rf   z9Expected the second message in a part to be from AI, got )
input_textoutput_text)r@   r%   lenrE   rA   rC   r   rF   r:   r   rD   )r   r%   example_pairsr   rH   examplepairs          r5   _parse_examplesr      ss   <<<<<<
8}}qAWs8}}WWW
 
 	
 MJ)) ' '
7q5A::g|44  >G}}> >/0> > >   !Jq5A::gy11  >G}}> >/0> > >   '&%7?  D   &&&r4   messagesr   c                    | st          d          | d         }t          |t                    st          d|j         d          |S )zMGet the human message at the end of a list of input messages to a chat model.z:You should provide at least one message to start the chat!z3Last message in the list should be from human, got r?   )rE   rC   r   rF   )r   questions     r5   _get_questionr      s^     WUVVV|Hh-- 
R(-RRR
 
 	
 Or4   z0.0.12z1.0z&langchain_google_vertexai.ChatVertexAI)sinceremovalalternative_importc                      e Zd ZU dZdZded<   	 dZded<   ed$d
            Zed%d            Z	e
d&d            Z	 	 	 d'd(dZ	 	 d)d*dZ	 	 d)d+dZd,d#ZdS )-ChatVertexAIz+`Vertex AI` Chat large language models API.z
chat-bisonrB   
model_nameNzOptional[List[BaseMessage]]r   r7   rN   c                    dS )NTr3   )selfs    r5   is_lc_serializablezChatVertexAI.is_lc_serializable   s    tr4   	List[str]c                
    g dS )z*Get the namespace of the langchain object.)	langchainchat_modelsvertexair3   )clss    r5   get_lc_namespacezChatVertexAI.get_lc_namespace   s     8777r4   valuesr   c                Z   t          |d                   }|                     |           	 ddlm}m} |rddlm} n# t          $ r t                       Y nw xY w|r ||d                   |d<   n8t          |d                   r|}n|}|
                    |d                   |d<   |S )z7Validate that the python package exists in environment.r   r   )	ChatModelCodeChatModel)GenerativeModel)r   client)r   _try_init_vertexair@   r   r   r~   r   ImportErrorr!   r   from_pretrained)r   r   	is_geminir   r   r   	model_clss          r5   validate_environmentz!ChatVertexAI.validate_environment   s    $F<$899	v&&&	(IIIIIIII        	( 	( 	(%'''''	( 	O.&:NOOOF8f\233 &)		%	(889MNNF8s   = AAr   r6   stopOptional[List[str]]run_manager"Optional[CallbackManagerForLLMRun]streamOptional[bool]kwargsr   r   c                   ||n| j         }|r  | j        |f||d|}t          |          S t          |          } | j        d|dd|}	i }
d|	v r|	                    d          |
d<   | j        r]t          || j                  }|                                }| j	        
                    |          }|                    ||	          }nht          |dd	                   }|                    d
          p| j        }|rt          |          |	d
<    | j        |fi |	} |j        |j        fi |
}d |j        D             }t'          |          S )a>  Generate next turn in the conversation.

        Args:
            messages: The history of the conversation as a list of messages. Code chat
                does not support context.
            stop: The list of stop words (optional).
            run_manager: The CallbackManager for LLM run, it's not used at the moment.
            stream: Whether to use the streaming endpoint.

        Returns:
            The ChatResult that contains outputs generated by the model.

        Raises:
            ValueError: if the last message in the list is not from human.
        N)r   r   Fr   r   candidate_countrY   r*   generation_configr   r   c                T    g | ]%}t          t          |j                             &S r:   rI   r   r   rb   rz   rs     r5   r{   z*ChatVertexAI._generate.<locals>.<listcomp>,  @     
 
 
 9QV#<#<#<===
 
 
r4   generationsr3   )	streaming_streamr   r   _prepare_paramspop_is_gemini_modelr   rY   r   
start_chatsend_messagerL   rp   r   r   _start_chatr:   
candidatesr   )r   r   r   r   r   r   should_streamstream_iterr   params
msg_paramshistory_geminirI   chatrv   r*   r   r   s                     r5   	_generatezChatVertexAI._generate   s   . #)"4$. 	5&$,# @F K (444 **%%H4HHHH
&&,2JJ7H,I,IJ()  	I7$,WWWN$((**G;)).)AAD((F(KKHH)(3B3-88Gzz*-->H ?%4X%>%>z"#4#G66v66D(t()9HHZHHH
 
(
 
 
 k2222r4   'Optional[AsyncCallbackManagerForLLMRun]c                  K   d|v r/|                     d           t                              d            | j        dd|i|}i }d|v r|                     d          |d<   | j        rct          || j                  }|                                 }| j                            |          }	|		                    ||           d{V }
nwt          |          }t          |dd	                   }|                    d
d          }|rt          |          |d
<    | j        |fi |}	 |	j	        |j        fi | d{V }
d |
j        D             }t#          |          S )a  Asynchronously generate next turn in the conversation.

        Args:
            messages: The history of the conversation as a list of messages. Code chat
                does not support context.
            stop: The list of stop words (optional).
            run_manager: The CallbackManager for LLM run, it's not used at the moment.

        Returns:
            The ChatResult that contains outputs generated by the model.

        Raises:
            ValueError: if the last message in the list is not from human.
        r   z8ChatVertexAI does not currently support async streaming.r   r   r   r   r   Nr   r   c                T    g | ]%}t          t          |j                             &S r   r   r   s     r5   r{   z+ChatVertexAI._agenerate.<locals>.<listcomp>^  r   r4   r   r3   )r   rT   warningr   r   r   rY   r   r   send_message_asyncr   rL   rp   r   r   r:   r   r   )r   r   r   r   r   r   r   r   rI   r   rv   r   r*   r   r   s                  r5   
_ageneratezChatVertexAI._agenerate2  s     * vJJx   NNUVVV%%::4:6::
&&,2JJ7H,I,IJ()  	U7$,WWWN$((**G;)).)AAD!44WPV4WWWWWWWWHH$X..H)(3B3-88Gzz*d33H ?%4X%>%>z"#4#G66v66D4T4X5ETTTTTTTTTTH
 
(
 
 
 k2222r4   Iterator[ChatGenerationChunk]c              +  j  K    | j         d|dd|}| j        r^t          || j                  }|                                }| j                            |          }|                    |d|          }	nqt          |          }
t          |d d                   }|
                    dd           }|rt          |          |d<    | j        |fi |} |j        |
j        fi |}	|	D ]G}t          t!          |j                  	          }|r|                    |j        |
           |V  Hd S )NTr   r   r   )r   r   r   r   r   r   )chunkr3   )r   r   r   rY   r   r   r   r   r   rL   rp   r   r   send_message_streamingr:   r   r   rb   on_llm_new_token)r   r   r   r   r   r   r   rI   r   	responsesr   r*   r   rv   r   s                  r5   r   zChatVertexAI._streamd  s      &%G4GGGG  	P7$,WWWN$((**G;)).)AAD)) *  II %X..H)(3B3-88Gzz*d33H ?%4X%>%>z"#4#G66v66D33H4DOOOOI! 	 	H'x}0U0U0UVVVE I,,X]%,HHHKKKK		 	r4   r*   r(   #Union[ChatSession, CodeChatSession]c                    | j         s | j        j        d|j        |j        d|S  | j        j        dd|j        i|S )N)r,   message_historyr   r3   )r   r   r   r,   r*   )r   r*   r   s      r5   r   zChatVertexAI._start_chat  sh     " 	U)4;)  LR   *4;)TT'/TVTTTr4   )r7   rN   )r7   r   )r   r   r7   r   )NNN)r   r6   r   r   r   r   r   r   r   r   r7   r   )NN)
r   r6   r   r   r   r   r   r   r7   r   )
r   r6   r   r   r   r   r   r   r7   r   )r*   r(   r   r   r7   r   )r-   r.   r/   r0   r   r2   r   classmethodr   r   r   r   r   r   r   r   r3   r4   r5   r   r      s#         65"J"""",0H0000   [ 8 8 8 [8    X4 %):>!%43 43 43 43 43r %)?C	03 03 03 03 03j %):>	    :U U U U U Ur4   r   )r*   r6   r7   r(   )rM   rB   r7   rN   )r*   r6   rY   r+   r7   rZ   )r   r6   r7   r   )r   r6   r7   r   )Ar0   
__future__r   rm   loggingri   dataclassesr   r   typingr   r   r   r	   r
   r   r   r   urllib.parser   ro   langchain_core._api.deprecationr   langchain_core.callbacksr   r   *langchain_core.language_models.chat_modelsr   r   langchain_core.messagesr   r   r   r   r   langchain_core.outputsr   r   r   langchain_core.utilsr   !langchain_community.llms.vertexair   r   r   &langchain_community.utilities.vertexair    r!   r@   r"   r#   r$   r%   r~   r&   	getLoggerr-   rT   r(   rL   rX   r   r   r   r   r3   r4   r5   <module>r      sU   7 7 " " " " " "   				 ( ( ( ( ( ( ( ( R R R R R R R R R R R R R R R R R R R R ! ! ! ! ! !  6 6 6 6 6 6                            S R R R R R R R R R ) ) ) ) ) )         
       
  ;            ;:::::		8	$	$ " " " " " " " "   @   ; ; ; ;|   <	 	 	 	 
?  
uU uU uU uU uU?M uU uU 
uU uU uUr4   