
    dh8                       S r SSKJr  SSKrSSKrSSKrSSKJrJr  SSK	J
r
JrJrJrJrJrJrJr  SSKJr  SSKrSSKJr  SSKJrJr  SS	KJrJr  SS
KJrJrJ r J!r!J"r"  SSK#J$r$J%r%J&r&  SSK'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.J/r/  \
(       a  SSK0J1r1J2r2J3r3J4r4  SSK5J6r6  \Rn                  " \85      r9\ " S S5      5       r:SS jr;SS jr<      S S jr=S!S jr>S"S jr?\" SSSS9 " S S\*\5      5       r@g)#z1Wrapper 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                  >    \ rS rSr% Sr\" \S9rS\S'   Sr	S\S'   S	r
g)
_ChatHistory6   z/Represents a context and a history of messages.)default_factoryzList['ChatMessage']historyNOptional[str]context )__name__
__module____qualname____firstlineno____doc__r   listr+   __annotations__r-   __static_attributes__r.       `/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/chat_models/vertexai.pyr(   r(   6   s    9#(#>G >!G]!r7   r(   c                   SSK Jn  / Sp2[        U 5       H  u  pE[        [        UR
                  5      nUS:X  a  [        U[        5      (       a  UnM>  [        U[        5      (       a$  U" UR
                  SS9nUR                  U5        Mw  [        U[        5      (       a$  U" UR
                  SS9nUR                  U5        M  [        S[        U5       SU S	35      e   [        X2S
9nU$ )zParse 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	            r8   _parse_chat_historyrM   >   s     5!4W(
sGOO,6j-88G++(ON"">2..(PN"">2/W>OPQsRST  )  ILr7   c                     [        U 5      n[        UR                  UR                  /5      $ ! [         a"  n[
        R                  SU 35         S nAgS nAff = f)NzUnable to parse URL: F)r   allschemenetloc	Exceptionloggerdebug)sresultes      r8   _is_urlrX   ^   sO    !FMM6==122 ,QC01s   +. 
AAAc                  ^^^ SSK JnJmJm  SUUU4S jjn/ n[	        U 5       H  u  pVUS:X  a   [        U[        5      (       a  [        S5      e[        U[        5      (       a  SnO3[        U[        5      (       a  SnO[        S[        U5       SU S	35      eUR                  n[        U[        5      (       a  U/nU V	s/ sH
  o" U	5      PM     n
n	U" XzS
9nUR                  U5        M     U$ s  sn	f )Nr   )r&   ImagePartc                8  > [        U [        5      (       a  TR                  U 5      $ [        U [        5      (       d  [	        S[        U 5       S35      eU S   S:X  a  TR                  U S   5      $ U S   S:X  Ga  U S   S   nUR                  S5      (       a  [        UTS9nOUR                  S	5      (       aa  [        R                  " S
U5      nU(       a  UR                  S5      nO[	        S5      eTR                  [        R                  " U5      5      nOo[        U5      (       aB  [        R                   " U5      nUR#                  5         TR                  UR$                  5      nOTR'                  U5      nO[	        S5      eTR)                  U5      $ )Nz0Message's content is expected to be a dict, got !rG   text	image_urlurlzgs://)pathprojectz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!)rD   rC   	from_textr   rF   rG   
startswithr    researchgroup
from_bytesbase64	b64decoderX   requestsgetraise_for_statusr;   load_from_file
from_image)partra   imageencodedresponserZ   r[   rb   s        r8   _convert_to_prompt6_parse_chat_history_gemini.<locals>._convert_to_promptl   se   dC  >>$''$%%B4:,aP  <6!>>$v,//&\[($U+Dw''+wG//!yy)JDQ%mmA.G$Q  (()9)9')BC#<<-))+(()9)9:,,T2KLLu%%r7   z%SystemMessages are not yet supported!modelr=   r>   r?   r@   )roleparts)rq   zUnion[str, Dict]returnr[   )"vertexai.preview.generative_modelsr&   rZ   r[   rB   rD   r   rF   r   r   rG   r;   rC   rE   )r+   rb   r&   ru   rH   rI   rJ   rx   raw_contentrq   ry   rK   rZ   r[   s    `          @@r8   _parse_chat_history_geminir}   g   s     HG!& !&F O(
6j-88DEE++D..D/W>OPQsRST  ook3''&-K6ABkd#D)kB d8~.# )$  Cs   C2c                   SSK Jn  [        U 5      S-  S:w  a  [        S[        U 5       S35      e/ nS n[	        U 5       H  u  pEUS-  S:X  a<  [        U[        5      (       d  [        S[        U5       SU S35      eUR                  nUS-  S	:X  d  MU  [        U[        5      (       d  [        S
[        U5       SU S35      eU" X5R                  S9nUR                  U5        M     U$ )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.rc   z9Expected the second message in a part to be from AI, got )
input_textoutput_text)rA   r%   lenrF   rB   rD   r   rG   r;   r   rE   )examplesr%   example_pairsr   rI   examplepairs          r8   _parse_examplesr      s   <
8}qAFs8}oUVW
 	
 MJ)
q5A:g|44 QG}oYqc>  !Jq5A:gy11 OG}oYqc>  '%??D   &# *$ r7   c                    U (       d  [        S5      eU S   n[        U[        5      (       d  [        SUR                   S35      eU$ )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@   )rF   rD   r   rG   )messagesquestions     r8   _get_questionr      sL    UVV|Hh--A(--PQR
 	
 Or7   z0.0.12z1.0z&langchain_google_vertexai.ChatVertexAI)sinceremovalalternative_importc                      \ rS rSr% SrSrS\S'    SrS\S'   \SS	 j5       r	\SS
 j5       r
\SS j5       r   S           SS jjr  S         SS jjr  S         SS jjr      SS jrSrg)ChatVertexAI   z+`Vertex AI` Chat large language models API.z
chat-bisonrC   
model_nameNzOptional[List[BaseMessage]]r   c                    g)NTr.   )selfs    r8   is_lc_serializableChatVertexAI.is_lc_serializable   s    r7   c                
    / SQ$ )z*Get the namespace of the langchain object.)	langchainchat_modelsvertexair.   )clss    r8   get_lc_namespaceChatVertexAI.get_lc_namespace   s
     87r7   c                ,   [        US   5      nU R                  U5         SSKJnJn  U(       a  SSKJn  U(       a  W" US   S9US'   U$ [        US   5      (       a  WnOWnUR                  US   5      US'   U$ ! [         a    [        5          N\f = f)z7Validate that the python package exists in environment.r   r   )	ChatModelCodeChatModel)GenerativeModel)r   client)r   _try_init_vertexairA   r   r   r{   r   ImportErrorr!   r   from_pretrained)r   values	is_geminir   r   r   	model_clss          r8   validate_environment!ChatVertexAI.validate_environment   s     $F<$89	v&	(I
 .&:NOF8  f\233)	%	(889MNF8  	(%'	(s   A< <BBc           	        Ub  UOU R                   nU(       a   U R                  " U4X#S.UD6n[        U5      $ [        U5      nU R                  " SUSS.UD6n	0 n
SU	;   a  U	R                  S5      U
S'   U R                  (       aL  [        XR                  S9nUR                  5       nU R                  R                  US9nUR                  XS9nOw[        USS	 5      nUR                  S
5      =(       d    U R                  nU(       a  [        U5      U	S
'   U R                   " U40 U	D6nUR                  " UR"                  40 U
D6nUR$                   Vs/ sH  n['        [)        UR*                  S9S9PM     nn[-        US9$ s  snf )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)stoprun_managerFr   streamcandidate_countrb   r+   generation_configr   r   r;   rJ   generationsr.   )	streaming_streamr   r   _prepare_paramspop_is_gemini_modelr}   rb   r   
start_chatsend_messagerM   rm   r   r   _start_chatr;   
candidatesr   r   r^   r   )r   r   r   r   r   kwargsshould_streamstream_iterr   params
msg_paramshistory_geminirJ   chatrt   r+   r   rr   s                      r8   	_generateChatVertexAI._generate   s   . #)"4$..,,#@FK (44 *%%H4HH
&,2JJ7H,IJ()  7,,WN$((*G;;)).)AD(((KH)(3B-8Gzz*->H%4X%>z"##G6v6D(()9)9HZHH ((
( 9QVV#<=( 	 
 k22	
s   #Fc           	       #    SU;   a&  UR                  S5        [        R                  S5        U R                  " SSU0UD6n0 nSU;   a  UR                  S5      US'   U R                  (       aT  [        XR                  S9nUR                  5       nU R                  R                  US9n	U	R                  XS9I Sh  vN n
Ox[        U5      n[        USS	 5      nUR                  S
S5      nU(       a  [        U5      US
'   U R                  " U40 UD6n	U	R                  " UR                  40 UD6I Sh  vN n
U
R                    Vs/ sH  n[#        [%        UR&                  S9S9PM     nn[)        US9$  N NBs  snf 7f)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   r   r   r   r.   )r   rS   warningr   r   r}   rb   r   r   send_message_asyncr   rM   rm   r   r   r;   r   r   r   r^   r   )r   r   r   r   r   r   r   r   rJ   r   rt   r   r+   r   r   r   s                   r8   
_agenerateChatVertexAI._agenerate2  sw    * vJJx NNUV%%:4:6:
&,2JJ7H,IJ()  7,,WN$((*G;;)).)AD!44W4WWH$X.H)(3B-8Gzz*d3H%4X%>z"##G6v6D!44X5E5ETTTH ((
( 9QVV#<=( 	 
 k22 X U
s7   B<F>E8?A8F7E:8F
#E<-F:F<Fc              +  d  #    U R                   " SUSS.UD6nU R                  (       aN  [        XR                  S9nUR	                  5       nU R
                  R                  US9nUR                  USUS9n	Op[        U5      n
[        US S 5      nUR                  SS 5      nU(       a  [        U5      US'   U R                  " U40 UD6nUR                  " U
R                  40 UD6n	U	 HB  n[        [!        UR"                  S9S	9nU(       a  UR%                  UR"                  US
9  Uv   MD     g 7f)NTr   r   r   )r   r   r   r   r   r   )chunkr.   )r   r   r}   rb   r   r   r   r   r   rM   rm   r   r   send_message_streamingr;   r   r   r^   on_llm_new_token)r   r   r   r   r   r   r   rJ   r   	responsesr   r+   r   rt   r   s                  r8   r   ChatVertexAI._streamd  s#     %%G4GG  7,,WN$((*G;;)).)AD)) * I %X.H)(3B-8Gzz*d3H%4X%>z"##G6v6D33H4D4DOOI!H'x}}0UVE,,X]]%,HK	 "s   D.D0c                    U R                   (       d3  U R                  R                  " SUR                  UR                  S.UD6$ U R                  R                  " SSUR                  0UD6$ )N)r-   message_historyr   r.   )r   r   r   r-   r+   )r   r+   r   s      r8   r   ChatVertexAI._start_chat  sa     "";;)) LR  ;;))T'//TVTTr7   r.   )rz   bool)rz   z	List[str])r   r   rz   r   )NNN)r   List[BaseMessage]r   Optional[List[str]]r   "Optional[CallbackManagerForLLMRun]r   zOptional[bool]r   r   rz   r   )NN)
r   r   r   r   r   z'Optional[AsyncCallbackManagerForLLMRun]r   r   rz   r   )
r   r   r   r   r   r   r   r   rz   zIterator[ChatGenerationChunk])r+   r(   r   r   rz   z#Union[ChatSession, CodeChatSession])r/   r0   r1   r2   r3   r   r5   r   classmethodr   r   r   r   r   r   r   r   r6   r.   r7   r8   r   r      s@    6"J",0H)0  8 8  4 %):>!%43#43 "43 8	43
 43 43 
43r %)?C	03#03 "03 =	03
 03 
03j %):>	# " 8	
  
':U#U/2U	,Ur7   r   )r+   r   rz   r(   )rU   rC   rz   r   )r+   r   rb   r,   rz   zList['Content'])r   r   rz   zList['InputOutputTextPair'])r   r   rz   r   )Ar3   
__future__r   rj   loggingrf   dataclassesr   r   typingr   r   r   r	   r
   r   r   r   urllib.parser   rl   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!   rA   r"   r#   r$   r%   r{   r&   	getLoggerr/   rS   r(   rM   rX   r}   r   r   r   r.   r7   r8   <module>r      s    7 "   	 ( R R R !  6  S R ) 

   ;			8	$ " " "@;;)6;;|<	 
?
uU?M uU
uUr7   