
    Ng)                    ,   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
 ddlmZmZ ddlmZ ddlmZ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 dd
lmZ ddl m!Z!  ej"        e#          Z$d#dZ%d$dZ& G d de!e          Z'd%dZ(d%dZ)d&dZ*d'd!Z+d'd"Z,dS )(z%Wrapper around YandexGPT chat models.    )annotationsN)AnyCallableDictListOptionalcast)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModel)	AIMessageBaseMessageHumanMessageSystemMessage)ChatGeneration
ChatResult)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponential)enforce_stop_tokens)_BaseYandexGPTrolestrtextreturnr   c                    | |dS )Nr   r    r   s     b/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/yandex.py_parse_messager"   "   s    $'''    historyList[BaseMessage]List[Dict[str, str]]c                   g }| D ]}t          t          |j                  }t          |t                    r#|                    t          d|                     t          |t                    r#|                    t          d|                     t          |t                    r#|                    t          d|                     |S )z`Parse a sequence of messages into history.

    Returns:
        A list of parsed messages.
    user	assistantsystem)	r	   r   content
isinstancer   appendr"   r   r   )r$   chat_historymessager+   s       r!   _parse_chat_historyr0   &   s     L C CsGO,,g|,, 	Avw ? ?@@@gy)) 	F{G D DEEEg}-- 	Cx A ABBBr#   c                  .    e Zd ZdZ	 	 dddZ	 	 dddZdS )ChatYandexGPTaD  YandexGPT large language models.

    There are two authentication options for the service account
    with the ``ai.languageModels.user`` role:
        - You can specify the token in a constructor parameter `iam_token`
        or in an environment variable `YC_IAM_TOKEN`.
        - You can specify the key in a constructor parameter `api_key`
        or in an environment variable `YC_API_KEY`.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatYandexGPT
            chat_model = ChatYandexGPT(iam_token="t1.9eu...")

    Nmessagesr%   stopOptional[List[str]]run_manager"Optional[CallbackManagerForLLMRun]kwargsr   r   r   c                    t          | |          }||nt          ||          }t          |          }t          t	          |          g          S )a  Generate next turn in the conversation.
        Args:
            messages: The history of the conversation as a list of messages.
            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.
        r3   Nr+   r/   generations)completion_with_retryr   r   r   r   selfr3   r4   r6   r8   r   r/   s          r!   	_generatezChatYandexGPT._generateJ   s]    & %TH===|tt)<T4)H)HD)))~g'F'F'F&GHHHHr#   'Optional[AsyncCallbackManagerForLLMRun]c                   K   t          | |           d{V }||nt          ||          }t          |          }t          t	          |          g          S )a  Async method to generate next turn in the conversation.

        Args:
            messages: The history of the conversation as a list of messages.
            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:   Nr;   r<   r=   )acompletion_with_retryr   r   r   r   r@   s          r!   
_ageneratezChatYandexGPT._agenerateb   ss      ( ,D8DDDDDDDDD|tt)<T4)H)HD)))~g'F'F'F&GHHHHr#   )NN)
r3   r%   r4   r5   r6   r7   r8   r   r   r   )
r3   r%   r4   r5   r6   rC   r8   r   r   r   )__name__
__module____qualname____doc__rB   rF   r    r#   r!   r2   r2   8   sl         ( %):>	I I I I I6 %)?C	I I I I I I Ir#   r2   rA   r3   c           	        	 dd l }ddlm}m} 	 ddlm}m ddlm} ddl	m
} n$# t          $ r ddlm}m ddlm} ddlm
} Y nw xY wn"# t          $ r}t          d          |d }~ww xY w|st!          d          t#          |          }	|                                }
|                    | j        |
          } || j         | || j                   || j                  	          fd
|	D                       } ||          }|                    || j                  }t5          |          d         j        d         j        j        S )Nr   DoubleValue
Int64ValueCompletionOptionsMessage)CompletionRequest)TextGenerationServiceStubkPlease install YandexCloud SDK  with `pip install yandexcloud`             or upgrade it to recent version.:You should provide at least one message to start the chat!valuetemperature
max_tokensc                     g | ]
} d i |S r    r    .0r/   rQ   s     r!   
<listcomp>z!_make_request.<locals>.<listcomp>   s)    DDD''$$G$$DDDr#   	model_uricompletion_optionsr3   metadata)grpcgoogle.protobuf.wrappers_pb2rM   rN   4yandex.cloud.ai.foundation_models.v1.text_common_pb2rP   rQ   Pyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2rR   Uyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpcrS   ModuleNotFoundError:yandex.cloud.ai.foundation_models.v1.foundation_models_pb2Byandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2Gyandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpcImportError
ValueErrorr0   ssl_channel_credentialssecure_channelurlra   rY   rZ   
Completiongrpc_metadatalistalternativesr/   r   )rA   r3   re   rM   rN   rP   rR   rS   emessage_historychannel_credentialschannelrequeststubresrQ   s                  @r!   _make_requestr~   |   si   HHHHHHHH	                   # 
	 
	 
	                   
	    .
 
 	
  WUVVV)(33O6688!!$(,?@@G.,,#$*:;;;!z888
 
 
 EDDDODDD  G %$W--D
//'D,>/
?
?C99Q<$Q'/44s7   A
 % A
 AA
 AA
 

A)A$$A)c           
       K   	 dd l }dd l}ddlm}m} 	 ddlm}m ddlm	}m
} ddlm}	 n&# t          $ r ddlm}m ddlm	}m
} ddlm}	 Y nw xY wddlm}
 ddlm} n"# t*          $ r}t+          d          |d }~ww xY w|st-          d	          t/          |          }d
}|                                }|j                            | j        |          4 d {V } || j         | || j                   || j                            fd|D                       } |	|          }|                    || j                    d {V }|j                            ||          4 d {V 	 } ||          }|j!        sU|"                    d           d {V   |
|j#                  }|$                    || j                    d {V }|j!        U	 d d d           d {V  n# 1 d {V swxY w Y    |            }|j%        &                    |           |j'        d         j(        j)        cd d d           d {V  S # 1 d {V swxY w Y   d S )Nr   rL   rO   )rR   CompletionResponse)TextGenerationAsyncServiceStub)GetOperationRequest)OperationServiceStubrT   rU   z"operation.api.cloud.yandex.net:443rV   rX   c                     g | ]
} d i |S r\   r    r]   s     r!   r_   z"_amake_request.<locals>.<listcomp>   s)    HHHWgg((((HHHr#   r`   rc      )operation_id)*asynciore   rf   rM   rN   rg   rP   rQ   rh   rR   r   ri   r   rj   rk   rl   rm   ,yandex.cloud.operation.operation_service_pb2r   1yandex.cloud.operation.operation_service_pb2_grpcr   rn   ro   r0   rp   aiorq   rr   ra   rY   rZ   rs   rt   donesleepidGetresponseUnpackrv   r/   r   )rA   r3   r   re   rM   rN   rP   rR   r   r   r   r   rw   rx   operation_api_urlry   rz   r{   r|   	operationoperation_channeloperation_stuboperation_requestcompletion_responserQ   s                           @r!   _amake_requestr      sO     &HHHHHHHH	                     # 	 	 	                     	 	UTTTTT	
 	
 	
 	
 	
 	
 	
    .
 
 	
  WUVVV)(33O<6688x&&tx1DEE @ @ @ @ @ @ @##n00'Kd.>???%:DO<<<      IHHHHHH
 
 
 .-g66//'D<N/OOOOOOOO	8**2
 
 
	 
	 
	 
	 
	 
	 
	 
	112CDDNn mmA&&&&&&&&&$7$7Y\$R$R$R!"0"4"4%!/ #5 # #      	  n  	
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 1022!!"5666"/2:?3@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @so   A  - A   AA  AA   
A?*A::A?BI6A(G1I1
G;	;I>G;	?=I
IIllmCallable[[Any], Any]c           
         ddl m} | j        }d}t          dt	          | j                  t          d||          t          |          t          t          t          j                            S )Nr   )RpcError<   Tr   )
multiplierminmax)reraiser4   waitr   before_sleep)re   r   sleep_intervalr   r   max_retriesr   r   r   loggerloggingWARNING)r   r   min_secondsmax_secondss       r!   _create_retry_decoratorr      st    $KK00MMM&22%fgo>>   r#   r8   r   c                N     t                     }|d fd            } |di |S )z*Use tenacity to retry the completion call._kwargsr   r   c                     t          fi | S N)r~   r   r   s    r!   _completion_with_retryz5completion_with_retry.<locals>._completion_with_retry  s    S,,G,,,r#   r   r   r   r   r    r   r   r8   retry_decoratorr   s   `   r!   r?   r?     sQ    -c22O- - - - - _- "!++F+++r#   c                ^    K   t                     }|d fd            } |di | d{V S )z0Use tenacity to retry the async completion call.r   r   r   c                 .   K   t          fi |  d {V S r   )r   r   s    r!   r   z6acompletion_with_retry.<locals>._completion_with_retry  s/      #C337333333333r#   Nr   r    r   r   s   `   r!   rE   rE     sg      -c22O4 4 4 4 4 _4 ('11&111111111r#   )r   r   r   r   r   r   )r$   r%   r   r&   )rA   r2   r3   r%   r   r   )r   r2   r   r   )r   r2   r8   r   r   r   )-rJ   
__future__r   r   typingr   r   r   r   r   r	   langchain_core.callbacksr
   r   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   langchain_core.outputsr   r   tenacityr   r   r   r   r   langchain_community.llms.utilsr   langchain_community.llms.yandexr   	getLoggerrG   r   r"   r0   r2   r~   r   r   r?   rE   r    r#   r!   <module>r      sD   + + " " " " " "  < < < < < < < < < < < < < < < <        E D D D D D            > = = = = = = =              ? > > > > > : : : : : :		8	$	$( ( ( (   $AI AI AI AI AINM AI AI AIH25 25 25 25jF@ F@ F@ F@R   , , , ,2 2 2 2 2 2r#   