a
    bg)                     @  sJ  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"e#Z$ddddddZ%dddddZ&G dd de!eZ'ddddddZ(ddddddZ)ddddd Z*dd!d!d"d#d$Z+dd!d!d"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strr   )roletextreturnc                 C  s
   | |dS )Nr   r    r   r   r   t/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/chat_models/yandex.py_parse_message"   s    r    List[BaseMessage]zList[Dict[str, str]])historyr   c                 C  sl   g }| D ]^}t t|j}t|tr2|td| t|trL|td| t|tr|td| q|S )z`Parse a sequence of messages into history.

    Returns:
        A list of parsed messages.
    userZ	assistantsystem)	r   r   content
isinstancer   appendr    r   r   )r"   Zchat_historymessager%   r   r   r   _parse_chat_history&   s    


r)   c                   @  s@   e Zd ZdZdddddddd	d
Zdddddd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...")

    Nr!   zOptional[List[str]]z"Optional[CallbackManagerForLLMRun]r   r   )messagesstoprun_managerkwargsr   c                 K  s>   t | |d}|du r|nt||}t|d}tt|dgd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.
        r+   Nr%   r(   Zgenerations)completion_with_retryr   r   r   r   selfr+   r,   r-   r.   r   r(   r   r   r   	_generateJ   s    
zChatYandexGPT._generatez'Optional[AsyncCallbackManagerForLLMRun]c                   sD   t | |dI dH }|du r|nt||}t|d}tt|dgd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/   Nr0   r1   r2   )acompletion_with_retryr   r   r   r   r4   r   r   r   
_agenerateb   s    
zChatYandexGPT._agenerate)NN)NN)__name__
__module____qualname____doc__r6   r8   r   r   r   r   r*   8   s       r*   )r5   r+   r   c              
     sB  zdd l }ddlm}m} z,ddlm}m  ddlm} ddl	m
} W n: ty   ddlm}m  ddlm} ddlm
} Y n0 W n. ty } ztd|W Y d }~n
d }~0 0 |stdt|}	| }
|| j|
}|| j||| jd|| jdd	 fd
d|	D d}||}|j|| jd}t|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                   s   g | ]} f i |qS r   r   .0r(   rB   r   r   
<listcomp>       z!_make_request.<locals>.<listcomp>	model_uriZcompletion_optionsr+   metadata)grpcgoogle.protobuf.wrappers_pb2r>   r?   4yandex.cloud.ai.foundation_models.v1.text_common_pb2rA   rB   Pyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2rC   Uyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpcrD   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
ValueErrorr)   ssl_channel_credentialssecure_channelurlrR   rJ   rK   
Completiongrpc_metadatalistalternativesr(   r   )r5   r+   rU   r>   r?   rA   rC   rD   emessage_historychannel_credentialschannelrequeststubresr   rN   r   _make_request|   sB    

rn   c              
     sH  zdd l }dd l}ddlm}m} z0ddlm}m  ddlm	}m
} ddlm}	 W n> ty   ddlm}m  ddlm	}m
} ddlm}	 Y n0 ddlm}
 ddlm} W n. ty } ztd|W Y d }~n
d }~0 0 |std	t|}d
}| }|j| j|4 I d H }|| j||| jd|| jdd fdd|D d}|	|}|j|| j dI d H }|j||4 I d H ^}||}|j!s|"dI d H  |
|j#d}|j$|| j dI d H }qW d   I d H  q1 I d H s0    Y  | }|j%&| |j'd j(j)W  d   I d H  S 1 I d H s:0    Y  d S )Nr   r=   r@   )rC   CompletionResponse)TextGenerationAsyncServiceStub)GetOperationRequest)OperationServiceStubrE   rF   z"operation.api.cloud.yandex.net:443rG   rI   c                   s   g | ]} f i |qS r   r   rL   rN   r   r   rO      rP   z"_amake_request.<locals>.<listcomp>rQ   rS      )Zoperation_id)*asynciorU   rV   r>   r?   rW   rA   rB   rX   rC   ro   rY   rp   rZ   r[   r\   r]   Z,yandex.cloud.operation.operation_service_pb2rq   Z1yandex.cloud.operation.operation_service_pb2_grpcrr   r^   r_   r)   r`   Zaiora   rb   rR   rJ   rK   rc   rd   donesleepidZGetresponseZUnpackrf   r(   r   )r5   r+   rt   rU   r>   r?   rA   rC   ro   rp   rq   rr   rg   rh   Zoperation_api_urlri   rj   rk   rl   Z	operationZoperation_channelZoperation_stubZoperation_requestZcompletion_responser   rN   r   _amake_request   sf    

>ry   zCallable[[Any], Any])llmr   c                 C  sD   ddl m} | j}d}tdt| jtd||dt|tt	t
jdS )Nr   )RpcError<   Trs   )
multiplierminmax)reraiser,   waitr   before_sleep)rU   r{   Zsleep_intervalr   r   max_retriesr   r   r   loggerloggingWARNING)rz   r{   Zmin_secondsZmax_secondsr   r   r   _create_retry_decorator   s    
r   r   )rz   r.   r   c                   s.   t  }|ddd fdd}|f i |S )z*Use tenacity to retry the completion call.r   _kwargsr   c                    s   t  fi | S N)rn   r   rz   r   r   _completion_with_retry  s    z5completion_with_retry.<locals>._completion_with_retryr   rz   r.   Zretry_decoratorr   r   r   r   r3     s    r3   c                   s4   t  }|ddd fdd}|f i |I dH S )z0Use tenacity to retry the async completion call.r   r   c                    s   t  fi | I d H S r   )ry   r   r   r   r   r     s    z6acompletion_with_retry.<locals>._completion_with_retryNr   r   r   r   r   r7     s    r7   )-r<   
__future__r   r   typingr   r   r   r   r   r   Zlangchain_core.callbacksr	   r
   Z*langchain_core.language_models.chat_modelsr   Zlangchain_core.messagesr   r   r   r   Zlangchain_core.outputsr   r   tenacityr   r   r   r   r   Zlangchain_community.llms.utilsr   Zlangchain_community.llms.yandexr   	getLoggerr9   r   r    r)   r*   rn   ry   r   r3   r7   r   r   r   r   <module>   s&    
D5I