U
    h!                     @  s0  d dl mZ d dlZd dl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 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 d dlm Z  e!e"Z#dddddZ$ddddddZ%ddddddZ&e
ddddG dd deZ'e
ddddG d d dee'Z(dS )!    )annotationsN)AnyCallableDictListOptional)
deprecated)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)LLM)Serializable)Field	SecretStr)convert_to_secret_strget_from_dict_or_envpre_init)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponential)enforce_stop_tokensintzCallable[[Any], Any])max_retriesreturnc                 C  sV   dd l }t|drt|jjntt}d}d}tdt| td||d|t	t
tjdS )	Nr   error   
   T   )Z
multiplierminmax)reraisestopwaitr   Zbefore_sleep)coherehasattrr   r   ZCohereError	Exceptionr   r   r   r   loggerloggingWARNING)r   r$   Zretry_conditionsZmin_secondsZmax_seconds r*   C/tmp/pip-unpacked-wheel-9gdii04g/langchain_community/llms/cohere.py_create_retry_decorator   s    
r,   Coherer   )llmkwargsr   c                   s,   t  j}|ddd fdd}|f |S )*Use tenacity to retry the completion call.r   r/   r   c                    s    j jf | S N)clientgenerater/   r.   r*   r+   _completion_with_retry7   s    z5completion_with_retry.<locals>._completion_with_retryr,   r   r.   r/   Zretry_decoratorr7   r*   r6   r+   completion_with_retry3   s    
r:   c                   s,   t  j}|ddd fdd}|f |S )r0   r   r1   c                    s    j jf | I d H S r2   )async_clientr4   r5   r6   r*   r+   r7   B   s    z6acompletion_with_retry.<locals>._completion_with_retryr8   r9   r*   r6   r+   acompletion_with_retry>   s    
r<   z0.0.30z1.0zlangchain_cohere.BaseCohere)ZsinceZremovalZalternative_importc                   @  s   e Zd ZU dZded< ded< eddZded< d	Zd
ed< dZded< dZ	ded< eddZ
ded< dZded< edddddZdS )
BaseCoherezBase class for Cohere models.r   r3   r;   N)defaultOptional[str]modelg      ?floattemperaturezOptional[SecretStr]cohere_api_keyOptional[List[str]]r"   Fbool	streamingZ	langchainstr
user_agentr   )valuesr   c                 C  s~   zddl }W n tk
r(   tdY nRX tt|dd|d< |d }|j|d  |d|d< |j|d  |d|d	< |S )
z?Validate that api key and python package exists in environment.r   NzTCould not import cohere python package. Please install it with `pip install cohere`.rC   COHERE_API_KEYrH   )Zapi_keyclient_namer3   r;   )r$   ImportErrorr   r   ZClientZget_secret_valueZAsyncClient)clsrI   r$   rK   r*   r*   r+   validate_environmentb   s&    





zBaseCohere.validate_environment)__name__
__module____qualname____doc____annotations__r   r@   rB   rC   r"   rF   rH   r   rN   r*   r*   r*   r+   r=   I   s   
r=   z0.1.14zlangchain_cohere.Coherec                   @  s  e Zd ZU dZdZded< dZded< dZded< d	Zd
ed< d	Z	d
ed< dZ
ded< dZded< G dd dZeddddZeddddZeddddZeddddZd d!d"d#d$d%Zd!d dd&d'd(Zd0dd d)d!dd*d+d,Zd1dd d-d!dd*d.d/ZdS )2r-   a  Cohere 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.llms import Cohere

            cohere = Cohere(model="gptd-instruct-tft", cohere_api_key="my-api-key")
       r   
max_tokensr   kr   pg        rA   frequency_penaltypresence_penaltyNr?   truncater   r   c                   @  s   e Zd ZdZdS )zCohere.ConfigZforbidN)rO   rP   rQ   extrar*   r*   r*   r+   Config   s   r\   zDict[str, Any])r   c                 C  s"   | j | j| j| j| j| j| jdS )z2Get the default parameters for calling Cohere API.rU   rB   rV   rW   rX   rY   rZ   r]   selfr*   r*   r+   _default_params   s    zCohere._default_paramszDict[str, str]c                 C  s   ddiS )NrC   rJ   r*   r^   r*   r*   r+   
lc_secrets   s    zCohere.lc_secretsc                 C  s   d| j i| jS )zGet the identifying parameters.r@   )r@   r`   r^   r*   r*   r+   _identifying_params   s    zCohere._identifying_paramsrG   c                 C  s   dS )zReturn type of llm.r$   r*   r^   r*   r*   r+   	_llm_type   s    zCohere._llm_typerD   r   dict)r"   r/   r   c                 K  sH   | j }| jd k	r"|d k	r"tdn| jd k	r8| j|d< n||d< ||S )Nz2`stop` found in both the input and default params.stop_sequences)r`   r"   
ValueError)r_   r"   r/   paramsr*   r*   r+   _invocation_params   s    

zCohere._invocation_params)responser"   r   c                 C  s   |j d j}|rt||}|S )Nr   )Zgenerationstextr   )r_   ri   r"   rj   r*   r*   r+   _process_response   s    
zCohere._process_responsez"Optional[CallbackManagerForLLMRun])promptr"   run_managerr/   r   c                 K  s<   | j |f|}t| f| j|d|}|d}| ||S )ah  Call out to Cohere's generate endpoint.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.

        Returns:
            The string generated by the model.

        Example:
            .. code-block:: python

                response = cohere("Tell me a joke.")
        r@   rl   re   )rh   r:   r@   getrk   r_   rl   r"   rm   r/   rg   ri   _stopr*   r*   r+   _call   s     
zCohere._callz'Optional[AsyncCallbackManagerForLLMRun]c                   sB   | j |f|}t| f| j|d|I dH }|d}| ||S )at  Async call out to Cohere's generate endpoint.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.

        Returns:
            The string generated by the model.

        Example:
            .. code-block:: python

                response = await cohere("Tell me a joke.")
        rn   Nre   )rh   r<   r@   ro   rk   rp   r*   r*   r+   _acall   s     
zCohere._acall)NN)NN)rO   rP   rQ   rR   rU   rS   rV   rW   rX   rY   rZ   r   r\   propertyr`   ra   rb   rc   rh   rk   rr   rs   r*   r*   r*   r+   r-   |   s2   

    ))
__future__r   r(   typingr   r   r   r   r   Zlangchain_core._api.deprecationr   Zlangchain_core.callbacksr	   r
   Z#langchain_core.language_models.llmsr   Z langchain_core.load.serializabler   Zlangchain_core.pydantic_v1r   r   Zlangchain_core.utilsr   r   r   Ztenacityr   r   r   r   r   Zlangchain_community.llms.utilsr   	getLoggerrO   r'   r,   r:   r<   r=   r-   r*   r*   r*   r+   <module>   s,   
  0