o
    Zh)                     @  s  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Z%d+ddZ&G dd de!eZ'd,ddZ(d,ddZ)d-d"d#Z*d.d&d'Z+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rolestrtextreturnr   c                 C  s
   | |dS )Nr   r    r   r   r   ]/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/chat_models/yandex.py_parse_message"   s   
r    historyList[BaseMessage]List[Dict[str, str]]c                 C  sl   g }| D ]/}t t|j}t|tr|td| t|tr&|td| t|tr3|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                   @  s0   e Zd ZdZ		ddddZ		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...")

    Nmessagesr"   stopOptional[List[str]]run_manager"Optional[CallbackManagerForLLMRun]kwargsr   r   r   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/   r1   r   r)   r   r   r   	_generateJ   s   
zChatYandexGPT._generate'Optional[AsyncCallbackManagerForLLMRun]c                   sF   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.
        r2   Nr3   r4   r5   )acompletion_with_retryr   r   r   r   r7   r   r   r   
_agenerateb   s
   
zChatYandexGPT._agenerate)NN)
r,   r"   r-   r.   r/   r0   r1   r   r   r   )
r,   r"   r-   r.   r/   r:   r1   r   r   r   )__name__
__module____qualname____doc__r9   r<   r   r   r   r   r+   8   s    r+   r8   r,   c              
     s6  zBd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w W n tyS } ztd|d }~ww |sZt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                      g | ]	} d i |qS r   r   .0r)   rF   r   r   
<listcomp>       z!_make_request.<locals>.<listcomp>	model_uriZcompletion_optionsr,   metadata)grpcgoogle.protobuf.wrappers_pb2rB   rC   4yandex.cloud.ai.foundation_models.v1.text_common_pb2rE   rF   Pyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2rG   Uyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpcrH   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urlrX   rN   rO   
Completiongrpc_metadatalistalternativesr)   r   )r8   r,   r[   rB   rC   rE   rG   rH   emessage_historychannel_credentialschannelrequeststubresr   rT   r   _make_request|   sJ   

rt   c              
     s8  zVdd l }dd l}ddlm}m} zddlm}m  ddlm	}m
} ddlm}	 W n tyI   ddlm}m  ddlm	}m
} ddlm}	 Y nw ddlm}
 ddlm} W n tyh } ztd|d }~ww |sot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 }|j!rW d   I d H  n1 I d H sw   Y  | }|j%&| |j'd j(j)W  d   I d H  S 1 I d H sw   Y  d S )Nr   rA   rD   )rG   CompletionResponse)TextGenerationAsyncServiceStub)GetOperationRequest)OperationServiceStubrI   rJ   z"operation.api.cloud.yandex.net:443rK   rM   c                   rP   rQ   r   rR   rT   r   r   rU      rV   z"_amake_request.<locals>.<listcomp>rW   rY      )Zoperation_id)*asyncior[   r\   rB   rC   r]   rE   rF   r^   rG   ru   r_   rv   r`   ra   rb   rc   Z,yandex.cloud.operation.operation_service_pb2rw   Z1yandex.cloud.operation.operation_service_pb2_grpcrx   rd   re   r*   rf   Zaiorg   rh   rX   rN   rO   ri   rj   donesleepidZGetresponseZUnpackrl   r)   r   )r8   r,   rz   r[   rB   rC   rE   rG   ru   rv   rw   rx   rm   rn   Zoperation_api_urlro   rp   rq   rr   Z	operationZoperation_channelZoperation_stubZoperation_requestZcompletion_responser   rT   r   _amake_request   st   

(2r   llmCallable[[Any], Any]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<   Try   )
multiplierminmax)reraiser-   waitr   before_sleep)r[   r   Zsleep_intervalr   r   max_retriesr   r   r   loggerloggingWARNING)r   r   Zmin_secondsZmax_secondsr   r   r   _create_retry_decorator   s   
r   r1   r   c                   s(   t  }|d fdd}|di |S )	z*Use tenacity to retry the completion call._kwargsr   r   c                    s   t  fi | S N)rt   r   r   r   r   _completion_with_retry  s   z5completion_with_retry.<locals>._completion_with_retryNr   r   r   r   r   r   r   r1   Zretry_decoratorr   r   r   r   r6     s   r6   c                   s0   t  }|d fdd}|di |I dH S )	z0Use tenacity to retry the async completion call.r   r   r   c                    s   t  fi | I d H S r   )r   r   r   r   r   r     s   z6acompletion_with_retry.<locals>._completion_with_retryNr   r   r   r   r   r   r   r;     s
   r;   )r   r   r   r   r   r   )r!   r"   r   r#   )r8   r+   r,   r"   r   r   )r   r+   r   r   )r   r+   r1   r   r   r   )-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   	getLoggerr=   r   r    r*   r+   rt   r   r   r6   r;   r   r   r   r   <module>   s(     



D
5
I
