o
    +i;                     @  s   d Z ddlmZ ddlZddlZddlmZmZmZm	Z	 ddl
mZ ddlZddlmZmZ ddlmZmZ ddlm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 ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% G dd deZ&G dd dee&Z'dS )z;Anthropic LLM wrapper. Chat models are in `chat_models.py`.    )annotationsN)AsyncIteratorCallableIteratorMapping)Any)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseLanguageModelLangSmithParams)LLM)GenerationChunk)PromptValue)get_pydantic_field_names)_build_model_kwargsfrom_envsecret_from_env)
ConfigDictField	SecretStrmodel_validator)Selfc                   @  sl  e Zd ZU dZded< dZded< edddZded	< 	 ed
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< 	 dZded< 	 ededdddZded< 	 ed ed!d"ddZd#ed$< 	 dZded%< dZded&< dZd'ed(< eed)Zd*ed+< ed,d-edAd1d2Zed3d-dBd5d6ZedCd8d9ZedCd:d;ZdDdEd?d@ZdS )F_AnthropicCommonNr   clientasync_clientzclaude-sonnet-4-5
model_name)defaultaliasstrmodeli   max_tokens_to_sampleint
max_tokenszfloat | Nonetemperaturez
int | Nonetop_ktop_pFbool	streamingdefault_request_timeout   max_retriesbase_urlANTHROPIC_API_URLzhttps://api.anthropic.com)r   )r   default_factoryz
str | Noneanthropic_api_urlapi_keyANTHROPIC_API_KEY r   anthropic_api_keyHUMAN_PROMPT	AI_PROMPTzCallable[[str], int] | Nonecount_tokens)r-   dict[str, Any]model_kwargsbeforemodevaluesdictreturnc                 C  s   t | }t||S N)r   r   )clsr;   all_required_field_names rA   U/var/www/html/psymed-ai/venv/lib/python3.10/site-packages/langchain_anthropic/llms.pybuild_extraR   s   
z_AnthropicCommon.build_extraafterr   c                 C  s`   t j| j| j | j| jd| _t j| j| j | j| jd| _	t
t dd| _t
t dd| _| S )z?Validate that api key and python package exists in environment.)r+   r/   timeoutr*   r3   Nr4   )	anthropic	Anthropicr.   r2   get_secret_valuer(   r*   r   AsyncAnthropicr   getattrr3   r4   selfrA   rA   rB   validate_environmentX   s   z%_AnthropicCommon.validate_environmentMapping[str, Any]c                 C  sX   | j | jd}| jdur| j|d< | jdur| j|d< | jdur%| j|d< i || jS )z5Get the default parameters for calling Anthropic API.)r"   r   Nr#   r$   r%   )r"   r   r#   r$   r%   r7   )rL   drA   rA   rB   _default_paramsl   s   





z _AnthropicCommon._default_paramsc                 C  s
   i | j S )Get the identifying parameters.)rP   rK   rA   rA   rB   _identifying_params{   s   
z$_AnthropicCommon._identifying_paramsstoplist[str] | None	list[str]c                 C  s   |d u rg }|S r>   rA   )rL   rS   rA   rA   rB   _get_anthropic_stop   s   z$_AnthropicCommon._get_anthropic_stopr;   r<   r=   r   )r=   r   )r=   rN   r>   )rS   rT   r=   rU   ) __name__
__module____qualname__r   __annotations__r   r   r   r"   r#   r$   r%   r'   r(   r*   r   r.   r   r2   r3   r4   r5   r<   r7   r   classmethodrC   rM   propertyrP   rR   rV   rA   rA   rA   rB   r      s\   
 
r   c                      s   e Zd ZdZedddZedded7d
dZe	d8ddZ
e	d9ddZed:ddZe	d;ddZ	d<d= fddZd>d!d"Z		d?d@d%d&ZdAd(d)Z		d?dBd+d,Z		d?dCd.d/Z		d?dDd1d2ZdEd5d6Z  ZS )FAnthropicLLMat  Anthropic text completion large language model (legacy LLM).

    To use, you should have the environment variable `ANTHROPIC_API_KEY`
    set with your API key, or pass it as a named parameter to the constructor.

    Example:
        ```python
        from langchain_anthropic import AnthropicLLM

        model = AnthropicLLM(model="claude-sonnet-4-5")
        ```
    T)populate_by_namearbitrary_types_allowedr8   r9   r;   r<   r=   r   c                 C  s   t jddd |S )z,Raise warning that this class is deprecated.zdThis Anthropic LLM is deprecated. Please use `from langchain_anthropic import ChatAnthropic` insteadr)   )
stacklevel)warningswarn)r?   r;   rA   rA   rB   raise_warning   s
   zAnthropicLLM.raise_warningr   c                 C     dS )zReturn type of llm.zanthropic-llmrA   rK   rA   rA   rB   	_llm_type      zAnthropicLLM._llm_typedict[str, str]c                 C  s   ddiS )z9Return a mapping of secret keys to environment variables.r2   r0   rA   rK   rA   rA   rB   
lc_secrets   s   zAnthropicLLM.lc_secretsr&   c                 C  re   )z2Whether this class can be serialized by langchain.TrA   )r?   rA   rA   rB   is_lc_serializable   rg   zAnthropicLLM.is_lc_serializabler6   c              
   C  s*   | j | j| j| j| j| j| j| j| jd	S )rQ   	r   r"   r#   r$   r%   r7   r'   r(   r*   rk   rK   rA   rA   rB   rR      s   z AnthropicLLM._identifying_paramsNrS   rT   kwargsr   c                   s>   t  jdd|i|}| j}|d|d }r||d< |S )z Get standard params for tracing.rS   r"   ls_max_tokensNrA   )super_get_ls_paramsrR   get)rL   rS   rl   paramsidentifying_paramsr"   	__class__rA   rB   ro      s   zAnthropicLLM._get_ls_paramspromptlist[dict[str, str]]c           	      C  s
  g }| j r[| j |v r[|| j }t|D ]E\}}| sq| jrK| j|v rK|| jd\}}| r<|d| d | rJ|d| d q| rY|d| d qntdd|}tdd|}| rw|d| d |sd| pddg}|S )	z&Convert prompt to Messages API format.   user)rolecontent	assistantz^\n*Human:\s*r1   z\n*Assistant:\s*.*$Hello)r3   split	enumeratestripr4   appendresub)	rL   ru   messagesparts_part
human_partassistant_partrz   rA   rA   rB   _format_messages   s4   zAnthropicLLM._format_messagesrun_managerCallbackManagerForLLMRun | Nonec           	      K  s   | j rd}| jd|||d|D ]}||j7 }q|S | |}i | j|}dd | D }| jjjd| 	||r=|ndd|}|j
d jS )	aj  Call out to Anthropic's completion endpoint.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: Optional callback manager for LLM run.
            kwargs: Additional keyword arguments to pass to the model.

        Returns:
            The string generated by the model.

        Example:
            ```python
            prompt = "What are the biggest risks facing humanity?"
            prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
            response = model.invoke(prompt)
            ```
        r1   ru   rS   r   c                 S     i | ]\}}|d kr||qS r    rA   .0kvrA   rA   rB   
<dictcomp>!      z&AnthropicLLM._call.<locals>.<dictcomp>Nr   stop_sequencesr   rA   )r'   _streamtextrV   rP   itemsr   r   creater   rz   	rL   ru   rS   r   rl   
completionchunkrq   responserA   rA   rB   _call   s*   



zAnthropicLLM._callr   c                 C  s   |  S )z$Convert a `PromptValue` to a string.)	to_string)rL   ru   rA   rA   rB   convert_prompt*  s   zAnthropicLLM.convert_prompt$AsyncCallbackManagerForLLMRun | Nonec           	        s   | j r!d}| jd|||d|2 z3 dH W }||j7 }q6 |S | |}i | j|}dd | D }| jjjd| 	||rC|ndd|I dH }|j
d jS )	z;Call out to Anthropic's completion endpoint asynchronously.r1   r   Nc                 S  r   r   rA   r   rA   rA   rB   r   E  r   z'AnthropicLLM._acall.<locals>.<dictcomp>r   r   rA   )r'   _astreamr   rV   rP   r   r   r   r   r   rz   r   rA   rA   rB   _acall.  s.   


zAnthropicLLM._acallIterator[GenerationChunk]c           	      k  s    |  |}i | j|}dd | D }| jjjd	| ||r#|ndd|-}|D ]!}|jdkrNt|j	drNt
|j	jd}|rK|j|j|d |V  q-W d   dS 1 sZw   Y  dS )
  Call Anthropic completion_stream and return the resulting generator.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: Optional callback manager for LLM run.
            kwargs: Additional keyword arguments to pass to the model.

        Returns:
            A generator representing the stream of tokens from Anthropic.

        Example:
            ```python
            prompt = "Write a poem about a stream."
            prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
            generator = anthropic.stream(prompt)
            for token in generator:
                yield token
            ```
        c                 S  r   r   rA   r   rA   rA   rB   r   m  r   z(AnthropicLLM._stream.<locals>.<dictcomp>Nr   content_block_deltar   r   r   rA   )rV   rP   r   r   r   streamr   typehasattrdeltar   r   on_llm_new_token	rL   ru   rS   r   rl   rq   r   eventr   rA   rA   rB   r   N  s(   


"zAnthropicLLM._streamAsyncIterator[GenerationChunk]c           	   	   K s   |  |}i | j|}dd | D }| jjjd	| ||r#|ndd|4 I dH 8}|2 z(3 dH W }|jdkrYt|j	drYt
|j	jd}|rV|j|j|dI dH  |V  q16 W d  I dH  dS 1 I dH slw   Y  dS )
r   c                 S  r   r   rA   r   rA   rA   rB   r     r   z)AnthropicLLM._astream.<locals>.<dictcomp>Nr   r   r   r   r   rA   )rV   rP   r   r   r   r   r   r   r   r   r   r   r   r   rA   rA   rB   r   {  s(   


.zAnthropicLLM._astreamr   r!   c                 C  s   d}t |)zCalculate number of tokens.zAnthropic's legacy count_tokens method was removed in anthropic 0.39.0 and langchain-anthropic 0.3.0. Please use ChatAnthropic.get_num_tokens_from_messages instead.)NotImplementedError)rL   r   msgrA   rA   rB   get_num_tokens  s
   zAnthropicLLM.get_num_tokensrW   )r=   r   )r=   rh   )r=   r&   )r=   r6   r>   )rS   rT   rl   r   r=   r   )ru   r   r=   rv   )NN)
ru   r   rS   rT   r   r   rl   r   r=   r   )ru   r   r=   r   )
ru   r   rS   rT   r   r   rl   r   r=   r   )
ru   r   rS   rT   r   r   rl   r   r=   r   )
ru   r   rS   rT   r   r   rl   r   r=   r   )r   r   r=   r!   )rX   rY   rZ   __doc__r   model_configr   r\   rd   r]   rf   ri   rj   rR   ro   r   r   r   r   r   r   r   __classcell__rA   rA   rs   rB   r^      sD    

*
1#0-r^   )(r   
__future__r   r   rb   collections.abcr   r   r   r   typingr   rF   langchain_core.callbacksr   r	   langchain_core.language_modelsr
   r   #langchain_core.language_models.llmsr   langchain_core.outputsr   langchain_core.prompt_valuesr   langchain_core.utilsr   langchain_core.utils.utilsr   r   r   pydanticr   r   r   r   typing_extensionsr   r   r^   rA   rA   rA   rB   <module>   s$    m