o
    Zht                     @   s   d dl Z d dlZd dlmZmZmZmZmZ d dlZd dl	m
Z
 d dl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 d d	lmZ e eZd
edefddZe
dddG dd deZ dS )    N)AnyDictListMappingOptional)
deprecated)CallbackManagerForLLMRun)BaseChatModel)	AIMessageBaseMessageChatMessageHumanMessage)ChatGeneration
ChatResultget_from_dict_or_env)model_validatormessagereturnc                 C   s^   t | tr| j| jd}|S t | trd| jd}|S t | tr(d| jd}|S td|  )N)rolecontentuserZ	assistantzGot unknown type )
isinstancer   r   r   r   r
   
ValueError)r   Zmessage_dict r   \/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/chat_models/ernie.py_convert_message_to_dict   s   


r   z0.0.13z3langchain_community.chat_models.QianfanChatEndpoint)Zsincealternativec                   @   sr  e Zd ZU dZdZee ed< 	 dZee ed< 	 dZ	ee ed< 	 dZ
ee ed< 	 dZeed< 	 dZee ed	< 	 d
Zee ed< 	 dZee ed< 	 dZee ed< dZee ed< dZee ed< e ZeddededefddZdedefddZd*ddZ 		d+de!e" d ee!e  d!ee# d"ede$f
d#d$Z%d%e&eef de$fd&d'Z'e(defd(d)Z)dS ),ErnieBotChata#  `ERNIE-Bot` large language model.

    ERNIE-Bot is a large language model developed by Baidu,
    covering a huge amount of Chinese data.

    To use, you should have the `ernie_client_id` and `ernie_client_secret` set,
    or set the environment variable `ERNIE_CLIENT_ID` and `ERNIE_CLIENT_SECRET`.

    Note:
    access_token will be automatically generated based on client_id and client_secret,
    and will be regenerated after expiration (30 days).

    Default model is `ERNIE-Bot-turbo`,
    currently supported models are `ERNIE-Bot-turbo`, `ERNIE-Bot`, `ERNIE-Bot-8K`,
    `ERNIE-Bot-4`, `ERNIE-Bot-turbo-AI`.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ErnieBotChat
            chat = ErnieBotChat(model_name='ERNIE-Bot')


    Deprecated Note:
    Please use `QianfanChatEndpoint` instead of this class.
    `QianfanChatEndpoint` is a more suitable choice for production.

    Always test your code after changing to `QianfanChatEndpoint`.

    Example of `QianfanChatEndpoint`:
        .. code-block:: python

            from langchain_community.chat_models import QianfanChatEndpoint
            qianfan_chat = QianfanChatEndpoint(model="ERNIE-Bot",
                endpoint="your_endpoint", qianfan_ak="your_ak", qianfan_sk="your_sk")

    Nernie_api_baseernie_client_idernie_client_secretaccess_tokenERNIE-Bot-turbo
model_namesystem<   request_timeoutF	streamingg?top_pgffffff?temperature   penalty_scorebefore)modevaluesr   c                 C   s6   t |ddd|d< t |dd|d< t |dd|d< |S )Nr   ZERNIE_API_BASEzhttps://aip.baidubce.comr    ZERNIE_CLIENT_IDr!   ZERNIE_CLIENT_SECRETr   )clsr/   r   r   r   validate_environmento   s   z!ErnieBotChat.validate_environmentpayloadc              
   C   s|   | j  d}dddddddd	d
d	}| j|v r"| d|| j  }ntd| j tj|| jddid| ji|d}| S )Nz)/rpc/2.0/ai_custom/v1/wenxinworkshop/chatz
eb-instantZcompletionsZernie_bot_8kZcompletions_proZai_apaasZ
bloomz_7b1Z
llama_2_7bZllama_2_13bZllama_2_70b)	r#   z	ERNIE-BotzERNIE-Bot-8KzERNIE-Bot-4zERNIE-Bot-turbo-AIz	BLOOMZ-7BzLlama-2-7b-chatzLlama-2-13b-chatzLlama-2-70b-chat/zGot unknown model_name Content-Typeapplication/jsonr"   )timeoutheadersparamsjson)r   r$   r   requestspostr'   r"   r9   )selfr2   base_urlZmodel_pathsurlrespr   r   r   _chat   s.   
	zErnieBotChat._chatc              	   C   sz   | j 0 td | j d}tj|ddddd| j| jdd}t|	 
d	| _W d    d S 1 s6w   Y  d S )
NzRefreshing access tokenz/oauth/2.0/token
   r5   )r4   AcceptZclient_credentials)Z
grant_typeZ	client_idZclient_secret)r6   r7   r8   r"   )_lockloggerdebugr   r:   r;   r    r!   strr9   getr"   )r<   r=   r?   r   r   r   _refresh_access_token_with_lock   s    
"z,ErnieBotChat._refresh_access_token_with_lockmessagesstoprun_managerkwargsc                 K   s   | j rtd| js|   dd |D | j| j| j| jd|}t	d|  | 
|}|drP|ddkrIt	d |   | 
|}ntd	| | |S )
Nz)`streaming` option currently unsupported.c                 S   s   g | ]}t |qS r   )r   ).0mr   r   r   
<listcomp>   s    z*ErnieBotChat._generate.<locals>.<listcomp>)rI   r)   r*   r,   r%   zPayload for ernie api is Z
error_codeo   z access_token expired, refresh itz#Error from ErnieChat api response: )r(   r   r"   rH   r)   r*   r,   r%   rD   rE   r@   rG   _create_chat_result)r<   rI   rJ   rK   rL   r2   r?   r   r   r   	_generate   s*   



zErnieBotChat._generateresponsec                 C   sf   d|v rdt |di i}ni }tt|ddi |ddg}|di }|| jd}t||dS )	NZfunction_callresult )r   additional_kwargs)r   usage)token_usager$   )generations
llm_output)dictrG   r   r
   r$   r   )r<   rS   rV   rY   rX   rZ   r   r   r   rQ      s   
z ErnieBotChat._create_chat_resultc                 C   s   dS )Nzernie-bot-chatr   )r<   r   r   r   	_llm_type   s   zErnieBotChat._llm_type)r   N)NN)*__name__
__module____qualname____doc__r   r   rF   __annotations__r    r!   r"   r$   r%   r'   intr(   boolr)   floatr*   r,   	threadingLockrC   r   classmethodr   r   r1   objectr[   r@   rH   r   r   r   r   rR   r   rQ   propertyr\   r   r   r   r   r   "   sV   
 &


r   )!loggingre   typingr   r   r   r   r   r:   Zlangchain_core._api.deprecationr   Zlangchain_core.callbacksr   Z*langchain_core.language_models.chat_modelsr	   Zlangchain_core.messagesr
   r   r   r   Zlangchain_core.outputsr   r   Zlangchain_core.utilsr   Zpydanticr   	getLoggerr]   rD   r[   r   r   r   r   r   r   <module>   s$    
