o
    +i                  
   @   s   d Z ddlmZmZ ddlmZ ddlmZ ddlm	Z	 zddl
mZmZmZmZ W n ey= Z zdZeeedZ[ww G d	d
 d
eZdS )zAnthropic prompt caching middleware.

Requires:
    - langchain: For agent middleware framework
    - langchain-anthropic: For ChatAnthropic model (already a dependency)
    )	AwaitableCallable)Literal)warn)ChatAnthropic)AgentMiddlewareModelCallResultModelRequestModelResponsezAnthropicPromptCachingMiddleware requires 'langchain' to be installed. This middleware is designed for use with LangChain agents. Install it with: pip install langchainNc                   @   s   e Zd ZdZ				dded ded d	ed
ed ddf
ddZdedefddZ	dede
egef defddZdede
egee f defddZdS ) AnthropicPromptCachingMiddlewarea?  Prompt Caching Middleware.

    Optimizes API usage by caching conversation prefixes for Anthropic models.

    Requires both 'langchain' and 'langchain-anthropic' packages to be installed.

    Learn more about Anthropic prompt caching
    [here](https://docs.claude.com/en/docs/build-with-claude/prompt-caching).
    	ephemeral5mr   r   typettl)r   1hmin_messages_to_cacheunsupported_model_behavior)ignorer   raisereturnNc                 C   s   || _ || _|| _|| _dS )a  Initialize the middleware with cache control settings.

        Args:
            type: The type of cache to use, only "ephemeral" is supported.
            ttl: The time to live for the cache, only "5m" and "1h" are
                supported.
            min_messages_to_cache: The minimum number of messages until the
                cache is used, default is 0.
            unsupported_model_behavior: The behavior to take when an
                unsupported model is used. "ignore" will ignore the unsupported
                model and continue without caching. "warn" will warn the user
                and continue without caching. "raise" will raise an error and
                stop the agent.
        N)r   r   r   r   )selfr   r   r   r    r   j/var/www/html/psymed-ai/venv/lib/python3.10/site-packages/langchain_anthropic/middleware/prompt_caching.py__init__)   s   
z)AnthropicPromptCachingMiddleware.__init__requestc                 C   sp   t |jts$dt|j }| jdkrt|| jdkr"t|dd dS |jr.t|j	d nt|j	}|| j
kS )a.  Check if caching should be applied to the request.

        Args:
            request: The model request to check.

        Returns:
            True if caching should be applied, False otherwise.

        Raises:
            ValueError: If model is unsupported and behavior is set to "raise".
        zeAnthropicPromptCachingMiddleware caching middleware only supports Anthropic models, not instances of r   r      )
stacklevelF   )
isinstancemodelr   r   r   
ValueErrorr   system_promptlenmessagesr   )r   r   msgmessages_countr   r   r   _should_apply_cachingC   s   


z6AnthropicPromptCachingMiddleware._should_apply_cachinghandlerc                 C   sB   |  |s	||S |j}i |d| j| jdi}||j|dS )a  Modify the model request to add cache control blocks.

        Args:
            request: The model request to potentially modify.
            handler: The handler to execute the model request.

        Returns:
            The model response from the handler.
        cache_controlr   r   model_settingsr&   r+   r   r   overrider   r   r'   r+   new_model_settingsr   r   r   wrap_model_calla   s   
z0AnthropicPromptCachingMiddleware.wrap_model_callc                    sP   |  |s||I dH S |j}i |d| j| jdi}||j|dI dH S )a#  Modify the model request to add cache control blocks (async version).

        Args:
            request: The model request to potentially modify.
            handler: The async handler to execute the model request.

        Returns:
            The model response from the handler.
        Nr(   r)   r*   r,   r.   r   r   r   awrap_model_cally   s   
z1AnthropicPromptCachingMiddleware.awrap_model_call)r   r   r   r   )__name__
__module____qualname____doc__r   intr   r	   boolr&   r   r
   r   r0   r   r1   r   r   r   r   r      s@    

r   )r5   collections.abcr   r   typingr   warningsr   langchain_anthropic.chat_modelsr   !langchain.agents.middleware.typesr   r   r	   r
   ImportErrorer$   r   r   r   r   r   <module>   s    
	