o
    Zh                     @   s  d dl mZmZmZmZmZmZ d dlmZ d dl	m
Z
mZ d dlmZmZmZ d dlmZmZmZmZmZmZ d dlmZmZmZ d dlmZ d dlmZ d	ed
efddZ dddee deeeeef   ded
eeef fddZ!eddddG dd deeZ"dS )    )AnyAsyncIteratorDictIteratorListOptional)
deprecated)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModelagenerate_from_streamgenerate_from_stream)	AIMessageAIMessageChunkBaseMessageChatMessageHumanMessageSystemMessage)ChatGenerationChatGenerationChunk
ChatResult)
ConfigDict)
BaseCoheremessagereturnc                 C   sB   t | ts
t | trdS t | trdS t | trdS td|  )zGet the role of the message.

    Args:
        message: The message.

    Returns:
        The role of the message.

    Raises:
        ValueError: If the message is of an unknown type.
    ZUserZChatbotSystemzGot unknown type )
isinstancer   r   r   r   
ValueErrorr    r   ]/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/chat_models/cohere.pyget_role   s   

r!   N)
connectorsmessagesr"   kwargsc                K   s   d|vrdn
dd t |d D }|dd |du r|nd}|dus'|dur)dnd}| d jdd | dd D |||d|}d	d
 | D S )zGet the request for the Cohere chat API.

    Args:
        messages: The messages.
        connectors: The connectors.
        **kwargs: The keyword arguments.

    Returns:
        The request for the Cohere chat API.
    Zsource_documentsNc                 S   s2   g | ]\}}|j |jd pdt| dqS )idzdoc-)Zsnippetr%   )Zpage_contentmetadatagetstr).0idocr   r   r    
<listcomp>D   s    z+get_cohere_chat_request.<locals>.<listcomp>ZAUTOc                 S   s   g | ]
}t ||jd qS ))Zroler   )r!   content)r)   xr   r   r    r,   W   s    )r   Zchat_history	documentsr"   prompt_truncationc                 S   s   i | ]\}}|d ur||qS )Nr   )r)   kvr   r   r    
<dictcomp>`   s    z+get_cohere_chat_request.<locals>.<dictcomp>)	enumeratepopr.   items)r#   r"   r$   r0   Zmaybe_connectorsr1   reqr   r   r    get_cohere_chat_request1   s*   

r9   z0.0.30z1.0zlangchain_cohere.ChatCohere)ZsinceZremovalZalternative_importc                   @   sf  e Zd ZdZedddZedefddZede	ee
f fddZede	ee
f fd	d
Z		ddee deee  dee de
dee f
ddZ		ddee deee  dee de
dee f
ddZde
de	ee
f fddZ		ddee deee  dee de
def
ddZ		ddee deee  dee de
def
ddZdedefddZdS )
ChatCohereaA  `Cohere` chat large language models.

    To use, you should have the ``cohere`` python package installed, and the
    environment variable ``COHERE_API_KEY`` set with your API key, or pass
    it as a named parameter to the constructor.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatCohere
            from langchain_core.messages import HumanMessage

            chat = ChatCohere(max_tokens=256, temperature=0.75)

            messages = [HumanMessage(content="knock knock")]
            chat.invoke(messages)
    T)Zpopulate_by_nameZarbitrary_types_allowedr   c                 C   s   dS )zReturn type of chat model.zcohere-chatr   selfr   r   r    	_llm_type~   s   zChatCohere._llm_typec                 C   s
   d| j iS )z2Get the default parameters for calling Cohere API.temperature)r>   r;   r   r   r    _default_params   s   zChatCohere._default_paramsc                 C   s   i d| j i| jS )zGet the identifying parameters.model)r@   r?   r;   r   r   r    _identifying_params   s   zChatCohere._identifying_paramsNr#   stoprun_managerr$   c           
      k   s    t |fi | j|}t| jdr| jjdi |}n| jjdi |ddi}|D ]}|jdkrI|j}tt	|dd}	|rF|j
||	d |	V  q+d S 	Nchat_streamstreamTztext-generationr.   r   )chunkr   )r9   r?   hasattrclientrE   chat
event_typetextr   r   on_llm_new_token
r<   r#   rB   rC   r$   requestrF   datadeltarH   r   r   r    _stream   s   
zChatCohere._streamc           
      K  s   t |fi | j|}t| jdr| jjdi |I d H }n| jjdi |ddiI d H }|2 z%3 d H W }|jdkrV|j}tt	|dd}	|rS|j
||	dI d H  |	V  q16 d S rD   )r9   r?   rI   Zasync_clientrE   rK   rL   rM   r   r   rN   rO   r   r   r    _astream   s    
zChatCohere._astreamresponsec                 C   s   |j |j|j|j|jdS )z1Get the generation info from cohere API response.r0   Z	citationsZsearch_resultsZsearch_queriesZtoken_countrV   )r<   rU   r   r   r    _get_generation_info   s   zChatCohere._get_generation_infoc           
      K   s   | j r| j|f||d|}t|S t|fi | j|}| jjdi |}t|jd}d }	t	|dr9| 
|}	tt||	dgdS N)rB   rC   rG   r0   )r   generation_info)Zgenerationsr   )	streamingrS   r   r9   r?   rJ   rK   r   rM   rI   rW   r   r   
r<   r#   rB   rC   r$   Zstream_iterrP   rU   r   rY   r   r   r    	_generate   s&   


zChatCohere._generatec           
         s   | j r| j|f||d|}t|I d H S t|fi | j|}| jjdi |}t|jd}d }	t	|dr=| 
|}	tt||	dgdS rX   )rZ   rT   r   r9   r?   rJ   rK   r   rM   rI   rW   r   r   r[   r   r   r    
_agenerate   s(   


zChatCohere._ageneraterM   c                 C   s   t | jj|djS )zCalculate number of tokens.)rM   )lenrJ   tokenizetokens)r<   rM   r   r   r    get_num_tokens   s   zChatCohere.get_num_tokens)NN)__name__
__module____qualname____doc__r   Zmodel_configpropertyr(   r=   r   r   r?   rA   r   r   r   r
   r   r   rS   r	   r   rT   rW   r   r\   r]   intra   r   r   r   r    r:   c   s    







r:   )#typingr   r   r   r   r   r   Zlangchain_core._api.deprecationr   Zlangchain_core.callbacksr	   r
   Z*langchain_core.language_models.chat_modelsr   r   r   Zlangchain_core.messagesr   r   r   r   r   r   Zlangchain_core.outputsr   r   r   Zpydanticr   Zlangchain_community.llms.coherer   r(   r!   r9   r:   r   r   r   r    <module>   s.      

2