U
    h                     @   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 eedd	d
Zddee eeeeef   eeeef d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)
BaseCohere)messagereturnc                 C   sF   t | tst | trdS t | tr&dS t | tr4dS td|  dS )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 N)
isinstancer   r   r   r   
ValueErrorr    r   J/tmp/pip-unpacked-wheel-9gdii04g/langchain_community/chat_models/cohere.pyget_role   s    

r    N)
connectors)messagesr!   kwargsr   c                K   s   d|krdndd t |d D }|dd |dkr:|nd}|dk	sN|dk	rRd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>C   s   z+get_cohere_chat_request.<locals>.<listcomp>ZAUTOc                 S   s   g | ]}t ||jd qS ))roler   )r    content)r(   xr   r   r   r+   V   s    )r   Zchat_history	documentsr!   prompt_truncationc                 S   s   i | ]\}}|d k	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_request0   s*    

r9   z0.0.30z1.0zlangchain_cohere.ChatCohere)ZsinceZremovalZalternative_importc                   @   s4  e Zd ZdZG dd dZeedddZeeee	f dddZ
eeee	f dd	d
Zdee eee  ee e	ee dddZdee eee  ee e	ee dddZe	eee	f dddZdee eee  ee e	edddZdee eee  ee e	edddZeed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)
    c                   @   s   e Zd ZdZdZdS )zChatCohere.ConfigTN)__name__
__module____qualname__Zallow_population_by_field_nameZarbitrary_types_allowedr   r   r   r   Configx   s   r>   )r   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)rB   r?   r   r   r   _default_params   s     zChatCohere._default_paramsc                 C   s   d| j i| jS )zGet the identifying parameters.model)rD   rC   r?   r   r   r   _identifying_params   s    zChatCohere._identifying_paramsN)r"   stoprun_managerr#   r   c           
      k   s   t |f| j|}t| jdr.| jjf |}n| jjf |ddi}|D ]<}|jdkrH|j}tt	|dd}	|r~|j
||	d |	V  qHd S Nchat_streamstreamTztext-generationr.   r   )chunk)r9   rC   hasattrclientrI   chat
event_typetextr   r   on_llm_new_token
r@   r"   rF   rG   r#   requestrJ   datadeltarL   r   r   r   _stream   s    
zChatCohere._streamc           
      K  s   t |f| j|}t| jdr4| jjf |I d H }n| jjf |ddiI d H }|2 zJ3 d H W }|jdkrT|j}tt	|dd}	|r|j
||	dI d H  |	V  qT6 d S rH   )r9   rC   rM   Zasync_clientrI   rO   rP   rQ   r   r   rR   rS   r   r   r   _astream   s    
zChatCohere._astream)responser   c                 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_countrZ   )r@   rY   r   r   r   _get_generation_info   s    zChatCohere._get_generation_infoc           
      K   s~   | j r&| j|f||d|}t|S t|f| j|}| jjf |}t|jd}d }	t	|drj| 
|}	tt||	dgdS N)rF   rG   rK   r0   )r   generation_info)Zgenerations)	streamingrW   r   r9   rC   rN   rO   r   rQ   rM   r[   r   r   
r@   r"   rF   rG   r#   Zstream_iterrT   rY   r   r]   r   r   r   	_generate   s(     


zChatCohere._generatec           
         s   | j r,| j|f||d|}t|I d H S t|f| j|}| jjf |}t|jd}d }	t	|drp| 
|}	tt||	dgdS r\   )r^   rX   r   r9   rC   rN   rO   r   rQ   rM   r[   r   r   r_   r   r   r   
_agenerate   s(     


zChatCohere._agenerate)rQ   r   c                 C   s   t | jj|djS )zCalculate number of tokens.)rQ   )lenrN   tokenizetokens)r@   rQ   r   r   r   get_num_tokens   s    zChatCohere.get_num_tokens)NN)NN)NN)NN)r;   r<   r=   __doc__r>   propertyr'   rA   r   r   rC   rE   r   r   r   r
   r   r   rW   r	   r   rX   r[   r   r`   ra   intre   r   r   r   r   r:   b   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langchain_community.llms.coherer   r'   r    r9   r:   r   r   r   r   <module>   s(     
2  