
    qi                        d Z ddlZddlZddlZddlZddlZddlZddlmZm	Z	 ddl
mZmZmZmZmZmZ ddl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 dd	lmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) dd
l*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z= ddl;m>Z>m?Z?m@Z@mAZA ddlBmCZC 	 ddlDm<Z<mEZEmFZFmGZG  G d de      ZLe G d de>             ZMe G d d             ZN G d de:      ZO G d d e4      ZP G d! d"e2      ZQ G d# d$e0      ZRy# eH$ r7ZI ej                  deI         ej                  d        eKdeI       dZI[Iww xY w)%zAnthropic AI service integration for Pipecat.

This module provides LLM services and context management for Anthropic's Claude models,
including support for function calling, vision, and prompt caching features.
    N)	dataclassfield)AnyDictListLiteralOptionalUnion)logger)Image)	BaseModelField)AnthropicLLMAdapterAnthropicLLMInvocationParams)FrameFunctionCallCancelFrameFunctionCallInProgressFrameFunctionCallResultFrameLLMContextFrameLLMEnablePromptCachingFrameLLMFullResponseEndFrameLLMFullResponseStartFrameLLMMessagesFrameLLMThoughtEndFrameLLMThoughtStartFrameLLMThoughtTextFrameUserImageRawFrame)LLMTokenUsage)
LLMContext)LLMAssistantAggregatorParamsLLMAssistantContextAggregatorLLMUserAggregatorParamsLLMUserContextAggregator)OpenAILLMContextOpenAILLMContextFrame)FrameDirection)FunctionCallFromLLM
LLMService	NOT_GIVEN)LLMSettings	_NotGiven_warn_deprecated_paramis_given)
traced_llm)r*   APITimeoutErrorAsyncAnthropicNotGivenzException: zKIn order to use Anthropic, you need to `pip install pipecat-ai[anthropic]`.zMissing module: c                   <    e Zd ZU dZed   ez  ed<   dZee	   ed<   y)AnthropicThinkingConfigaP  Configuration for extended thinking.

    Parameters:
        type: Type of thinking mode (currently only "enabled" or "disabled").
        budget_tokens: Maximum number of tokens for thinking.
            With today's models, the minimum is 1024.
            Currently required when type is "enabled", not allowed when "disabled".
    )enableddisabledtypeNbudget_tokens)
__name__
__module____qualname____doc__r   str__annotations__r8   r	   int     P/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/anthropic/llm.pyr4   r4   H   s*     '
(3
.. $(M8C='rA   r4   c                   v     e Zd ZU dZ ed       Zeez  ed<    ed       Z	e
ez  ed<   e fd       Z xZS )AnthropicLLMSettingszSettings for AnthropicLLMService.

    Parameters:
        enable_prompt_caching: Whether to enable prompt caching.
        thinking: Extended thinking configuration.
    c                      t         S N
_NOT_GIVENr@   rA   rB   <lambda>zAnthropicLLMSettings.<lambda>d   s    J rA   default_factoryenable_prompt_cachingc                      t         S rF   rG   r@   rA   rB   rI   zAnthropicLLMSettings.<lambda>e   s    R\ rA   thinkingc                     t         |   |      }t        |j                        r4t	        |j                  t
              rt        di |j                  |_        |S )zConvert a plain dict to settings, coercing thinking dicts.

        For backward compatibility, a ``thinking`` value that is a plain dict
        is converted to a :class:`AnthropicThinkingConfig`.
        r@   )superfrom_mappingr.   rN   
isinstancedictr4   )clssettingsinstance	__class__s      rB   rQ   z!AnthropicLLMSettings.from_mappingg   sL     7'1H%%&:h6G6G+N 7 L(:K:K LHrA   )r9   r:   r;   r<   r   rL   boolr,   r>   rN   r4   classmethodrQ   __classcell__rW   s   @rB   rD   rD   [   sH     /4DV.W4)+W49J\4]H%	1]	 	rA   rD   c                   6    e Zd ZU dZded<   ded<   d	dZd
dZy)AnthropicContextAggregatorPaira/  Pair of context aggregators for Anthropic conversations.

    Encapsulates both user and assistant context aggregators
    to manage conversation flow and message formatting.

    .. deprecated:: 0.0.99
        `AnthropicContextAggregatorPair` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.

    Parameters:
        _user: The user context aggregator.
        _assistant: The assistant context aggregator.
    AnthropicUserContextAggregator_user#AnthropicAssistantContextAggregator
_assistantc                     | j                   S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )r_   selfs    rB   userz#AnthropicContextAggregatorPair.user   s     zzrA   c                     | j                   S )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )ra   rc   s    rB   	assistantz(AnthropicContextAggregatorPair.assistant   s     rA   N)returnr^   )rh   r`   )r9   r:   r;   r<   r>   re   rg   r@   rA   rB   r]   r]   t   s      ,+55rA   r]   c                       e Zd ZU dZeZeed<   eZe	Z
 G d de      Zdddddddd	ed
ee   dee   dee   dee   dee   f fdZdefdZd Z	 	 d'deez  dee   dee   dee   fdZ e        e       ddedededefdZdeez  defdZedeez  fd       Zde de!f fdZ"d edefd!Z#d"ed#ed$ed%efd&Z$ xZ%S )(AnthropicLLMServicea  LLM service for Anthropic's Claude models.

    Provides inference capabilities with Claude models including support for
    function calling, vision processing, streaming responses, and prompt caching.
    Can use custom clients like AsyncAnthropicBedrock and AsyncAnthropicVertex.
    	_settingsc                   ,   e Zd ZU dZdZee   ed<   dZee   ed<    e	d d      Z
ee   ed<    e	d	 d
d      Zee   ed<    e	d d      Zee   ed<    e	d d
d      Zee   ed<    e	d       Zee   ed<    e	e      Zeeeef      ed<   d Zy)AnthropicLLMService.InputParamsa  Input parameters for Anthropic model inference.

        .. deprecated:: 0.0.105
            Use ``AnthropicLLMSettings`` instead. Pass settings directly via the
            ``settings`` parameter of :class:`AnthropicLLMService`.

        Parameters:
            enable_prompt_caching: Whether to enable the prompt caching feature.
            enable_prompt_caching_beta (deprecated): Whether to enable the beta prompt caching feature.

                .. deprecated:: 0.0.84
                    Use the `enable_prompt_caching` parameter instead.

            max_tokens: Maximum tokens to generate. Must be at least 1.
            temperature: Sampling temperature between 0.0 and 1.0.
            top_k: Top-k sampling parameter.
            top_p: Top-p sampling parameter between 0.0 and 1.0.
            thinking: Extended thinking configuration.
                Enabling extended thinking causes the model to spend more time "thinking" before responding.
                It also causes this service to emit LLMThinking*Frames during response generation.
                Extended thinking is disabled by default.
            extra: Additional parameters to pass to the API.
        NrL   enable_prompt_caching_betac                       y)N   r@   r@   rA   rB   rI   z(AnthropicLLMService.InputParams.<lambda>   s    rA      )rK   ge
max_tokensc                      t         S rF   r)   r@   rA   rB   rI   z(AnthropicLLMService.InputParams.<lambda>   s    Y rA   g        g      ?)rK   rr   letemperaturec                      t         S rF   r)   r@   rA   rB   rI   z(AnthropicLLMService.InputParams.<lambda>   s    Y rA   r   top_kc                      t         S rF   r)   r@   rA   rB   rI   z(AnthropicLLMService.InputParams.<lambda>   s    y rA   top_pc                      t         S rF   r)   r@   rA   rB   rI   z(AnthropicLLMService.InputParams.<lambda>   s    T] rA   rJ   rN   extrac                 x    | j                   .ddl}|j                  d       |j                  dt        d       yy)z4Post-initialization to handle deprecated parameters.Nr   alwaysLenable_prompt_caching_beta is deprecated. Use enable_prompt_caching instead.   
stacklevel)rn   warningssimplefilterwarnDeprecationWarning)rd   _InputParams__contextr   s      rB   model_post_initz/AnthropicLLMService.InputParams.model_post_init   s>    ..:%%h/b&   	 ;rA   )r9   r:   r;   r<   rL   r	   rX   r>   rn   r   rs   r?   rv   floatrx   rz   rN   r4   rS   r|   r   r=   r   r   r@   rA   rB   InputParamsrm      s    	0 15x~459"HTN9$),1$M
HSMM',=NSV[^'_Xe__$5F1Mx}M!&7HSUX!YxY6;L]6^(23^*/*ExS#X'E
	rA   r   Ng      @F)modelparamsrU   clientretry_timeout_secsretry_on_timeoutapi_keyr   r   rU   r   r   c                   t        ddddt        t        t        dddddt        i       }	|t        dt         d       ||	_        |	t        dt                |s|j                  |	_        |j
                  |	_        |j                  |	_        |j                  |	_        |j                  |	_        t        |j                  t              r|j                  |	_
        |j                  }
|j                  Tddl}|j                         5  |j!                  d	       |j#                  d
t$        d       ddd       |
|j                  }
|
xs d|	_        ||	j'                  |       t)        | T  dd|	i| |xs t-        |      | _        || _        || _        | j4                  j6                  r/t9        j:                  |  d| j4                  j6                          yy# 1 sw Y   xY w)a  Initialize the Anthropic LLM service.

        Args:
            api_key: Anthropic API key for authentication.
            model: Model name to use.

                .. deprecated:: 0.0.105
                    Use ``settings=AnthropicLLMSettings(model=...)`` instead.

            params: Optional model parameters for inference.

                .. deprecated:: 0.0.105
                    Use ``settings=AnthropicLLMSettings(...)`` instead.

            settings: Runtime-updatable settings for this service.  When both
                deprecated parameters and *settings* are provided, *settings*
                values take precedence.
            client: Optional custom Anthropic client instance.
            retry_timeout_secs: Request timeout in seconds for retry logic.
            retry_on_timeout: Whether to retry the request once if it times out.
            **kwargs: Additional arguments passed to parent LLMService.
        zclaude-sonnet-4-6Nrp   F)r   system_instructionrs   rL   rv   rx   rz   frequency_penaltypresence_penaltyseedfilter_incomplete_user_turnsuser_turn_completion_configrN   r|   r   r   r   r~   r   r   r   rU   )r   z: Using system instruction: r@   )rD   r*   r-   r   rs   rv   rx   rz   rN   rR   r|   rS   rL   rn   r   catch_warningsr   r   r   apply_updaterP   __init__r1   _client_retry_timeout_secs_retry_on_timeoutrk   r   r   debug)rd   r   r   r   rU   r   r   r   kwargsdefault_settingsrL   r   rW   s               rB   r   zAnthropicLLMService.__init__   s   F 0%#"'!"!).(,
$ "7,@'J%*" "8-AB.4.?.? +/5/A/A ,)/ &)/ &,2OO )fllD1-3\\$*(.(D(D%44@#!002  --h7 A.'(	 &  -4060Q0Q-9N9WRW 6 ))(3="2=f= 
"
 $6 !1>>,,LLD6!=dnn>_>_=`ab -- s   *GG'rh   c                      y)zCheck if this service can generate usage metrics.

        Returns:
            True, as Anthropic provides detailed token usage metrics.
        Tr@   rc   s    rB   can_generate_metricsz(AnthropicLLMService.can_generate_metrics;  s     rA   c                 F  K   | j                   r2	 t        j                   |di || j                         d{   }|S  |di | d{   }|S 7 # t        t        j
                  f$ r. t        j                  |  d        |di | d{  7  }|cY S w xY w7 Rw)zCreate message stream with optional timeout and retry.

        Args:
            api_call: The Anthropic API method to call.
            params: Parameters for the API call.

        Returns:
            Async stream of message events.
        )timeoutNz*: Retrying message creation due to timeoutr@   )r   asynciowait_forr   r0   TimeoutErrorr   r   )rd   api_callr   responses       rB   _create_message_streamz*AnthropicLLMService._create_message_streamC  s      !!	 !(!1!1&v&0H0H"    &///HO $W%9%9:  v%OPQ!)!3F!333	  0sP   B!*A AA  B!BB!A <BBBB!BB!contextrs   r   c                   K   g }t         }g }t        |t              rG| j                         }|j	                  || j
                  j                        }|d   }|d   }|d   }nBt        j                  |      }|j                  }t        |dt               }|j                  xs g }|$|r |t         urt        j                  |  d       |}| j
                  j                  ||n| j
                  j                  d| j
                  j                   | j
                  j"                  | j
                  j$                  |||dgd	
}	| j
                  j&                  r)| j
                  j&                  j)                  d
      |	d<   |	j+                  | j
                  j,                          | j.                  j0                  j                  j2                  di |	 d{   }
t5        d |
j6                  D        d      S 7 !w)aV  Run a one-shot, out-of-band (i.e. out-of-pipeline) inference with the given LLM context.

        Args:
            context: The LLM context containing conversation history.
            max_tokens: Optional maximum number of tokens to generate. If provided,
                overrides the service's default max_tokens setting.
            system_instruction: Optional system instruction to use for this inference.
                If provided, overrides any system instruction in the context.

        Returns:
            The LLM's response as a string, or None if no response is generated.
        rL   messagessystemtoolsN\: Both system_instruction and a system message in context are set. Using system_instruction.Finterleaved-thinking-2025-05-14)
r   rs   streamrv   rx   rz   r   r   r   betasTexclude_unsetrN   c              3   N   K   | ]  }t        |d       s|j                    yw)textN)hasattrr   ).0blocks     rB   	<genexpr>z4AnthropicLLMService.run_inference.<locals>.<genexpr>  s     XEPVAWUZZXs   %%r@   )r*   rR   r   get_llm_adapterget_llm_invocation_paramsrk   rL   AnthropicLLMContextupgrade_to_anthropicr   getattrr   r   warningr   rs   rv   rx   rz   rN   
model_dumpupdater|   r   betacreatenextcontent)rd   r   rs   r   r   r   r   adapterinvocation_paramsr   r   s              rB   run_inferencez!AnthropicLLMService.run_inference\  s    $ gz*+/+?+?+AG ' A At~~/S/S !B ! )4H&x0F%g.E)>>wGG''HWh	:FMM'RE )&	1f 1 1 (F ^^))(2(>*DNND]D]>>55^^))^^)) 78
 >>""!%!8!8!C!CRV!C!WF:dnn**+ ;**33::DVDDXX-=-=XZ^__ Es   GG=G;"G=)user_paramsassistant_paramsr   r   c                    |j                  | j                                t        |t              rt        j                  |      }t        ||      }t        ||      }t        ||      S )aE  Create Anthropic-specific context aggregators.

        Creates a pair of context aggregators optimized for Anthropic's message format,
        including support for function calls, tool usage, and image handling.

        Args:
            context: The LLM context.
            user_params: User aggregator parameters.
            assistant_params: Assistant aggregator parameters.

        Returns:
            A pair of context aggregators, one for the user and one for the assistant,
            encapsulated in an AnthropicContextAggregatorPair.

        .. deprecated:: 0.0.99
            `create_context_aggregator()` is deprecated and will be removed in a future version.
            Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
            See `OpenAILLMContext` docstring for migration guide.
        )r   )r_   ra   )	set_llm_adapterr   rR   r$   r   from_openai_contextr^   r`   r]   )rd   r   r   r   re   rg   s         rB   create_context_aggregatorz-AnthropicLLMService.create_context_aggregator  s^    4 	 4 4 67g/0)==gFG .gkJ7HXY	-DYOOrA   c                    t        |t              r| j                         }|j                  || j                  j
                        }| j                  j                  r<|d   t        urt        j                  |  d       | j                  j                  |d<   |S | j                  j
                  r|j                         n|j                  }t        |j                  ||j                  xs g       S )Nr   r   r   )r   r   r   )rR   r   r   r   rk   rL   r   r*   r   r   'get_messages_with_cache_control_markersr   r   r   r   )rd   r   r   r   r   s        rB   _get_llm_invocation_paramsz.AnthropicLLMService._get_llm_invocation_params  s     gz*+/+?+?+AG3:3T3Tt~~/S/S 4U 4F ~~00(#94NN& !: : $(>>#D#Dx M
 ~~33 ;;=!! 	
 ,>>--%2
 	
rA   c           	      "  K   d}d}d}d}d}d}	 | j                  t                      d {    | j                          d {    | j                  |      }t	        |t
              r$| j                         }	d}
|	j                  |      }nd}
|j                         }t        j                  |  d|
 d|d    d|        | j                          d {    | j                  j                  | j                  j                  d	| j                  j                  | j                  j                  | j                  j                   d
}| j                  j"                  r)| j                  j"                  j%                  d	      |d<   |j'                  |       |j'                  | j                  j(                         |j'                  ddgi       | j+                  | j,                  j.                  j0                  j2                  |       d {   }| j5                          d {    d }d}g }|2 3 d {   }|j6                  dk(  rgt9        |j:                  d      rW| j=                  |j:                  j>                         d {    || jA                  |j:                  j>                        z  }nt9        |j:                  d      rE|rC||j:                  jB                  z  }|| jA                  |j:                  jB                        z  }nt9        |j:                  d      r9| j                  tE        |j:                  j"                               d {    nht9        |j:                  d      rQ| j                  tG        |j:                  jH                               d {    n|j6                  dk(  r~|jJ                  j6                  dk(  r|jJ                  }d}n|jJ                  j6                  dk(  r| j                  tM        d	| j                         jN                               d {    n|j6                  dk(  r|t9        |j:                  d      rf|j:                  jP                  dk(  rM|rK|rtS        jT                  |      ni }|jW                  tY        ||jZ                  |j\                  |             t9        |d      rd|t9        |j^                  d      r|j^                  j`                  ndz  }|t9        |j^                  d      r|j^                  jb                  ndz  }t9        |d      st9        |jd                  d      s.|t9        |jd                  j^                  d      r |jd                  j^                  j`                  ndz  }|t9        |jd                  j^                  d      r |jd                  j^                  jb                  ndz  }|t9        |jd                  j^                  d       r@|jd                  j^                  jf                   |jd                  j^                  jf                  ndz  }t        j                  d!|        |t9        |jd                  j^                  d"      r@|jd                  j^                  jh                   |jd                  j^                  jh                  ndz  }t        j                  d#|        ||z   |z   }|d$k\  st9        |d%      s|xjj                  d&z  c_5        7 7 7 I7 7 7 7 7 7 7 6 | jm                  |       d {  7   nx# tn        jp                  $ r d	} tr        jt                  $ r | jw                  d'       d {  7   Y n4tx        $ r)}| j{                  d(| |)       d {  7   Y d }~nd }~ww xY w| j}                          d {  7   | j                  t                      d {  7   |s|n|}| j                  ||||*       d {  7   y # | j}                          d {  7   | j                  t                      d {  7   |s|n|}| j                  ||||*       d {  7   w xY ww)+Nr   F	universalzLLM-specificz: Generating chat from z
 context [r   z] | T)r   rs   r   rv   rx   rz   r   rN   r   r    content_block_deltar   partial_jsonr   	signature)r   content_block_starttool_use)append_to_contextllmmessage_deltastop_reason)r   tool_call_idfunction_name	argumentsusageinput_tokensoutput_tokensmessagecache_creation_input_tokenszCache creation input tokens: cache_read_input_tokenszCache read input tokens: i   turns_above_cache_thresholdrq   on_completion_timeoutzUnknown error occurred: )	error_msg	exception)prompt_tokenscompletion_tokensr   r   )A
push_framer   start_processing_metricsr   rR   r   r   get_messages_for_loggingr   r   start_ttfb_metricsrk   r   rs   rv   rx   rz   rN   r   r   r|   r   r   r   r   r   stop_ttfb_metricsr7   r   delta_push_llm_textr   _estimate_tokensr   r   r   r   content_blockr   id_for_llm_specific_messagesr   jsonloadsappendr'   idnamer   r   r   r   r   r   r   run_function_callsr   CancelledErrorhttpxTimeoutException_call_event_handler	Exception
push_errorstop_processing_metricsr   _report_usage_metrics)rd   r   r   r   completion_tokens_estimateuse_completion_tokens_estimater   r   params_from_contextr   context_type_for_loggingmessages_for_loggingr   r   tool_use_blockjson_accumulatorfunction_callseventargstotal_input_tokensecomp_tokenss                         rB   _process_contextz$AnthropicLLMService._process_context  s     %&").&&'#"#f	//";"=>>>//111"&"A"A'"J':...0+6('.'G'G'P$+9('.'G'G'I$LL&/0H/ITghpTqSrrv  xL  wM  N ))+++ --"nn77#~~99----F ~~&&%)^^%<%<%G%GVZ%G%[z" MM-.MM$..../
 MM7%F$GHI!889J9J9S9S9Z9Z\bccH((*** "N!N' XE XEe ::!66u{{F3"11%++2B2BCCC2d6K6KEKKL\L\6]]2 n=.(EKK,D,DD(2d6K6K!KK447 2 !j9"oo.Au{{G[G[.\]]] k:"oo.@5;;K`K`.abbbZZ#88**//:=).)<)<+-(,,11Z?"oo026$($8$8$:$W$W   JJ/1];//:=%?Otzz*:;UW&--/(/-;->->.<.A.A*.	 5'*!4;EKK4X00^_M &5<U[[/5Z11`a% UI.75=='3R!"5==#6#6G ++88M
 &"5==#6#6H ++99%
 0 $EMM$7$79VW % 3 3 O O [ ++GG
 / LL#@A\@]!^_+ $EMM$7$79RS % 3 3 K K W ++CC
 + LL#<=T<U!VW%(CCF]] ' *T1"#%B $??1D?U ?1 ,2 d*XE
 D ^b+  (t )).999%% 	 .2*%% 	D**+BCCC 	Y//.Fqc,JVW/XXX	Y ..000//"9";<<< 6 "/ 
 ,,+"-,G(?	 -    ..000//"9";<<< 6 "/ 
 ,,+"-,G(?	 -   s  b] \] \B] \D7] \"] &\%'] 3\77\(8\7;A] 
\+C] \.A] ,\1-B] :\4;D] 	] !F] 4] ] ] ] "] %] (\7+] .] 1] 4] 7] ]] `+ <_^_`+ __8^;9_>`+ _`+ b_!!b `#b$`'%b+b?a !b!a$"#bbbbframe	directionc                 T  K   t         |   ||       d{    d}t        |t              r t        j                  |j                        }nt        |t              r|j                  }nt        |t              r t        j                  |j                        }nit        |t              r?t        j                  d|j                   d       |j                  | j                  _        n| j#                  ||       d{    |r| j%                  |       d{    yy7 
7 $7 w)a,  Process incoming frames and route them appropriately.

        Handles various frame types including context frames, message frames,
        vision frames, and settings updates.

        Args:
            frame: The frame to process.
            direction: The direction of frame processing.
        Nz#Setting enable prompt caching to: [])rP   process_framerR   r%   r   r   r   r   r   from_messagesr   r   r   r   enablerk   rL   r   r  )rd   r  r  r   rW   s       rB   r  z!AnthropicLLMService.process_frame  s      g#E9555e23-@-U-UV[VcVc-dG/mmG/0 *77GG:;LL>u||nANO38<<DNN0//%333''000 # 	6 4 1s4   D(D!C'D(?D$ D(D&D($D(&D(r   c                 X    t        t        t        j                  d|            dz        S )Nz[^\w]+g?)r?   lenresplit)rd   r   s     rB   r   z$AnthropicLLMService._estimate_tokens  s"    3rxx	401C788rA   r   r   r   r   c                 z   K   |s|s|s|r-t        ||||||z         }| j                  |       d {    y y 7 w)N)r   r   r   r   total_tokens)r   start_llm_usage_metrics)rd   r   r   r   r   tokenss         rB   r  z)AnthropicLLMService._report_usage_metrics  sS       *&"+"3,G(?*->>F ..v666 ' 7s   0;9;)NN)&r9   r:   r;   r<   rD   Settingsr>   r   adapter_classr4   ThinkingConfigr   r   r=   r	   r   rX   r   r   r   r   r$   r?   r   r"   r    r]   r   r   r   r/   r  r   r&   r  r   r  rZ   r[   s   @rB   rj   rj      s    $H## (M -N,i ,d  $(,37.1+0`c `c }	`c
 %`c /0`c %UO`c #4.`cDd 8 %),0	A`..A` SMA` %SM	A`
 
#A`N 0G/H9U9W#P!#P -	#P
 7#P 
(#PJ
'*4
	%
< r.>.K r rh1 1> 1<9S 9S 977 7 &)	7
 "%7rA   rj   c                   D    e Zd ZdZ	 	 	 deddeee      deee      dee   dee	e
f   f fdZd	 Zed
edd fd       Zedefd       Zedee   dd fd       ZdefdZd Zd Zddde	deeef   dede	fdZd Zdee   fdZd Z fdZdeee	ef      fdZ  xZ!S )r   a  LLM context specialized for Anthropic's message format and features.

    Extends OpenAILLMContext to handle Anthropic-specific features like
    system messages, prompt caching, and message format conversions.
    Manages conversation state and message history formatting.

    .. deprecated:: 0.0.99
        `AnthropicLLMContext` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    N)r   r   r   tool_choicer   c                X    t         |   |||       | j                          || _        y)a  Initialize the Anthropic LLM context.

        Args:
            messages: Initial list of conversation messages.
            tools: Available function calling tools.
            tool_choice: Tool selection preference.
            system: System message content.
        r   r   r*  N)rP   r   !_AnthropicLLMContext__setup_localr   )rd   r   r   r*  r   rW   s        rB   r   zAnthropicLLMContext.__init__  s,    " 	(%[QrA   c                     d| _         y )Nr   )r   rc   s    rB   __setup_localz!AnthropicLLMContext.__setup_local  s    
 ,-(rA   objrh   c                     t        j                  d|         t        | t              r;t        | t              s+t        | _        | j                          | j                          | S )a  Upgrade an OpenAI context to Anthropic format.

        Converts message format and restructures content for Anthropic compatibility.

        Args:
            obj: The OpenAI context to upgrade.

        Returns:
            The upgraded Anthropic context.
        zUpgrading to Anthropic: )r   r   rR   r$   r   rW   r-  !_restructure_from_openai_messages)r0  s    rB   r   z(AnthropicLLMContext.upgrade_to_anthropic  sQ     	/u56c+,ZEX5Y/CM113
rA   openai_contextc                      | |j                   |j                  |j                        }|j                  |j	                                |j                          |S )zCreate Anthropic context from OpenAI context.

        Args:
            openai_context: The OpenAI context to convert.

        Returns:
            New Anthropic context with converted messages.
        r,  )r   r   r*  r   r   r2  )rT   r3  rd   s      rB   r   z'AnthropicLLMContext.from_openai_context  sS     #,, &&&22

 	^;;=>..0rA   c                 8     | |      }|j                          |S )zCreate context from a list of messages.

        Args:
            messages: List of conversation messages.

        Returns:
            New Anthropic context with the provided messages.
        )r   )r2  )rT   r   rd   s      rB   r  z!AnthropicLLMContext.from_messages  s     H%..0rA   c                 P    d| _         || j                  dd | j                          y)zzSet the messages list and reset cache tracking.

        Args:
            messages: New list of messages to set.
        r   N)r   	_messagesr2  )rd   r   s     rB   set_messagesz AnthropicLLMContext.set_messages-  s&     ,-($q..0rA   c           
      ,   |j                  d      }|j                  d      }|dk(  rt        |t              r
|d|dgdgS t        |t              rg }g }|D ]_  }|d   dk(  r|j	                  d|d   d       #|d   dk(  s,|j	                  d	|d
   |d   t        j                  |d         dd       a g }|r|j	                  ||d       |r|j	                  ||d       |S y|dk(  rt        |t              r
|d|dgdgS t        |t              rzg }g }|D ]F  }|d   dk(  r|j	                  d|d   d       #|d   dk(  s,|j	                  d|d   |d   d       H g }|r|j	                  ||d       |j                  |       |S yy)a  Convert Anthropic message format to standard structured format.

        Handles text content and function calls for both user and assistant messages.

        Args:
            obj: Message in Anthropic format.

        Returns:
            List of messages in standard format.

        Examples:
            Input Anthropic format::

                {
                    "role": "assistant",
                    "content": [
                        {"type": "text", "text": "Hello"},
                        {"type": "tool_use", "id": "123", "name": "search", "input": {"q": "test"}}
                    ]
                }

            Output standard format::

                [
                    {"role": "assistant", "content": [{"type": "text", "text": "Hello"}]},
                    {
                        "role": "assistant",
                        "tool_calls": [
                            {
                                "type": "function",
                                "id": "123",
                                "function": {"name": "search", "arguments": '{"q": "test"}'}
                            }
                        ]
                    }
                ]
        roler   rg   r   r7   r   r:  r   r7   r   functionr   r   input)r   r   )r7   r   r=  )r:  
tool_callsre   tool_resulttooltool_use_id)r:  r   r   N)getrR   r=   listr   r   dumpsextend)rd   r0  r:  r   
text_items
tool_itemsitemr   s           rB   to_standard_messagesz(AnthropicLLMContext.to_standard_messages7  s   P wwv'')$;'3'!%FG3T2UVWWGT*

# DF|v-"))64<*PQf3"))(2&*4j,0L15DM1J-"		 OOTj$IJOOT$LM- +. V^'3'!%FG3T2UVWWGT*

# 
DF|v-"))64<*PQf6"))(.04]0C+/	?	
 OOTj$IJ
+% + rA   c                    |d   dk(  rdd|d   |d   dgdS |j                  d	      rQ|d	   }d
g d}|D ]@  }|d   }t        j                  |d         }d|d   |d   |d}|d   j                  |       B |S |j                  d      }t	        |t
              r	|dk(  rd}|S t	        |t              r|D ]  }	|	d   dk(  s|	d   dk(  sd|	d<    |S )aH  Convert standard format message to Anthropic format.

        Handles conversion of text content, tool calls, and tool results.
        Empty text content is converted to "(empty)".

        Args:
            message: Message in standard format.

        Returns:
            Message in Anthropic format.

        Examples:
            Input standard format::

                {
                    "role": "assistant",
                    "tool_calls": [
                        {
                            "id": "123",
                            "function": {"name": "search", "arguments": '{"q": "test"}'}
                        }
                    ]
                }

            Output Anthropic format::

                {
                    "role": "assistant",
                    "content": [
                        {
                            "type": "tool_use",
                            "id": "123",
                            "name": "search",
                            "input": {"q": "test"}
                        }
                    ]
                }
        r:  rA  re   r@  r   r   r7   rB  r   r<  r?  rg   r=  r   r   r   r   r7   r   r   r>  r   (empty)r7   r   )rC  r   r   r   rR   r=   rD  )
rd   r   tcret	tool_callr=  r   new_tool_user   rI  s
             rB   from_standard_messagez)AnthropicLLMContext.from_standard_message  s/   P 6?f$ !.'.~'>#*9#5	 	 ;;|$&B&26C 	4	$Z0 JJx'<=	&#D/$V,&	  I%%l3	4 J++i(gs#"}#  & -<6)d6lb.@#,DL- rA   r   formatsizeimager   c                H   t        j                         }t        j                  |||      j	                  |d       t        j                  |j                               j                  d      }ddd|ddg}|r|j                  d	|d
       | j                  d|d       y)a  Add an image message to the context.

        Converts the image to base64 JPEG format and adds it as a user message
        with optional accompanying text.

        Args:
            format: The image format (e.g., 'RGB', 'RGBA').
            size: Image dimensions as (width, height).
            image: Raw image bytes.
            text: Optional text to accompany the image.
        JPEG)rT  zutf-8rV  base64z
image/jpeg)r7   
media_typedata)r7   sourcer   r;  re   r<  N)ioBytesIOr   	frombytessaverY  	b64encodegetvaluedecoder   add_message)rd   rT  rU  rV  r   bufferencoded_imager   s           rB   add_image_frame_messagez+AnthropicLLMContext.add_image_frame_message  s     e,11&1H(():;BB7K
  $".)	
 NNFD9:&W=>rA   c                 ,   	 | j                   r| j                   d   d   |d   k(  rt        | j                   d   d   t              r&d| j                   d   d   dg| j                   d   d<   t        |d   t              rd|d   dg|d<   | j                   d   d   j                  |d          y| j                   j	                  |       y| j                   j	                  |       y# t
        $ r"}t        j                  d|        Y d}~yd}~ww xY w)a  Add a message to the context, merging with previous message if same role.

        Anthropic requires alternating roles, so consecutive messages from the same
        role are merged together.

        Args:
            message: The message to add to the context.
        r:  r   r   r;  zError adding message: N)r   rR   r=   rF  r   r  r   error)rd   r   r  s      rB   rd  zAnthropicLLMContext.add_message   s   	7}} ==$V,? "$--"3I">D%+T]]25Fy5QR8b))4
 "')"4c:7=wyGY.Z-[	*MM"%i077	8JKMM((1$$W- 	7LL1!566	7s$   B-C( 0C( C( (	D1DDc                    	 t        j                  | j                        }| j                  dk\  rC|d   d   dk(  r8t	        |d   d   t
              rd|d   d   dg|d   d<   dd	i|d   d   d   d
<   | j                  dk\  rQt        |      dkD  rC|d   d   dk(  r8t	        |d   d   t
              rd|d   d   dg|d   d<   dd	i|d   d   d   d
<   |S # t        $ r.}t        j                  d|        | j                  cY d}~S d}~ww xY w)a  Get messages with prompt caching markers applied.

        Adds cache control markers to appropriate messages based on the
        number of turns above the cache threshold.

        Returns:
            List of messages with cache control markers added.
        rq   ri  r:  re   r   r   r;  r7   	ephemeralcache_controlr   z#Error adding cache control marker: N)
copydeepcopyr   r   rR   r=   r  r  r   rj  )rd   r   r  s      rB   r   z;AnthropicLLMContext.get_messages_with_cache_control_markers!  s8   	!}}T]]3H//14"f9MQW9Whrl95s;8>QSU^H_/`.aHRL+@F?TY'+O<00A5MA%RL(F2hrl95s;8>QSU^H_/`.aHRL+@F?TY'+O<O 	!LL>qcBC== 	!s   CC 	D#DDDc                 T   	 | j                   D cg c]  }| j                  |       c}| j                   d d  | j
                  rr| j
                  d   d   dk(  r]t        | j
                        dk(  rd| j
                  d   d<   n2| j
                  d   d   | _        | j
                  j                  d       d}|t        | j
                        dz
  k  r| j
                  |   }| j
                  |dz      }|d   |d   k(  rtt        |d   t              rd|d   d	g|d<   t        |d   t              rd|d   d	g|d<   |d   j                  |d          | j
                  j                  |dz          n|dz  }|t        | j
                        dz
  k  r| j
                  D ]R  }t        |d   t              r|d   d
k(  rd|d<   $t        |d   t              s8t        |d         dk(  sJddd	g|d<   T y c c}w # t        $ r#}t        j                  d|        Y d }~d }~ww xY w)NzError mapping messages: r   r:  r   rq   re   r   r   r;  r   rN  )r7  rS  r  r   rj  r   r  r   poprR   r=   rF  rD  )rd   mr  icurrent_messagenext_messager   s          rB   r2  z5AnthropicLLMContext._restructure_from_openai_messages=  s(   	9HL W1!;!;A!> WDNN1 ==T]]1-f5A4==!Q& ,2a ( #mmA.y9!!!$ #dmm$q(("mmA.O==Q/Lv&,v*>>oi8#>!'1KL2OI. l95s;8>U^H_/`.aL+	*11,y2IJ!!!a%(Q! #dmm$q((& }} 	KG'),c2wy7IR7O%.	"GI.5#gi>P:QUV:V/5y&I%J	"		KM !X 	9LL3A3788	9s'   G; G6G; 6G; ;	H'H""H'c                 z    t         |          }| j                  r|j                  dd| j                  d       |S )zGet messages formatted for persistent storage.

        Includes system message at the beginning if present.

        Returns:
            List of messages suitable for storage.
        r   r   r<  )rP   #get_messages_for_persistent_storager   insert)rd   r   rW   s     rB   rx  z7AnthropicLLMContext.get_messages_for_persistent_storagel  s5     7>@;;OOAT[[IJrA   c                     g }| j                   D ]Z  }t        j                  |      }d|v r.t        |d   t              r|d   D ]  }|d   dk(  sd|d   d<    |j                  |       \ |S )zGet messages formatted for logging with sensitive data redacted.

        Replaces image data with placeholder text for cleaner logs.

        Returns:
            List of messages in a format ready for logging.
        r   r7   rV  z...r\  r[  )r   ro  rp  rR   rD  r   )rd   msgsr   msgrI  s        rB   r   z,AnthropicLLMContext.get_messages_for_loggingy  s     }} 	G--(CCc)nd3 #I ;<725:DN62; KK	 rA   )NNN)"r9   r:   r;   r<   r*   r	   r   rS   r
   r=   r2   r   r-  staticmethodr$   r   rY   r   r  r8  rJ  rS  tupler?   bytesrg  rd  r   r2  rx  r   r   r   rZ   r[   s   @rB   r   r     s]   
 *.&*&*	 (14:& T
# d^	 c8m$* "2 7L  $ 1A  $ T$Z 4I  1T 1Y vK\ PT??$)#s(O?<A?IL?B7B!d !8-K^$tCH~*> rA   r   c                       e Zd ZdZy)r^   a  Anthropic-specific user context aggregator.

    Handles aggregation of user messages for Anthropic LLM services.
    Inherits all functionality from the base LLMUserContextAggregator.

    .. deprecated:: 0.0.99
        `AnthropicUserContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    N)r9   r:   r;   r<   r@   rA   rB   r^   r^     s    	 	rA   r^   c                   T    e Zd ZdZdefdZdefdZdefdZ	de
de
defd	Zdefd
Zy)r`   a  Context aggregator for assistant messages in Anthropic conversations.

    Handles function call lifecycle management including in-progress tracking,
    result handling, and cancellation for Anthropic's tool use format.

    .. deprecated:: 0.0.99
        `AnthropicAssistantContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    r  c                   K   dg d}|d   j                  d|j                  |j                  |j                  d       | j                  j                  |       | j                  j                  dd|j                  dd	gd       y
w)zHandle a function call that is starting.

        Creates tool use message and placeholder tool result for tracking.

        Args:
            frame: Frame containing function call details.
        rg   r<  r   r   rM  re   r@  IN_PROGRESSrL  N)r   r   r   r   _contextrd  )rd   r  assistant_messages      rB    handle_function_call_in_progresszDAnthropicAssistantContextAggregator.handle_function_call_in_progress  s      &1R@)$++"((++		
 	!!"34!! !.','9'9#0		
s   BBc                 (  K   |j                   rOt        j                  |j                         }| j                  |j                  |j
                  |       d{    y| j                  |j                  |j
                  d       d{    y7 57 w)zHandle the result of a completed function call.

        Updates the tool result with actual return value or completion status.

        Args:
            frame: Frame containing function call result.
        N	COMPLETED)resultr   rE  _update_function_call_resultr   r   )rd   r  r  s      rB   handle_function_call_resultz?AnthropicAssistantContextAggregator.handle_function_call_result  s}      <<ZZ-F33E4G4GI[I[]cddd33##U%7%7   es$   ABB/BB	BBc                 n   K   | j                  |j                  |j                  d       d{    y7 w)zHandle cancellation of a function call.

        Updates the tool result to indicate cancellation.

        Args:
            frame: Frame containing function call cancellation details.
        	CANCELLEDN)r  r   r   rd   r  s     rB   handle_function_call_cancelz?AnthropicAssistantContextAggregator.handle_function_call_cancel  s3      //!3!3[
 	
 	
s   +535r   r   r  c                    K   | j                   j                  D ]=  }|d   dk(  s|d   D ]*  }t        |t              s|d   dk(  s|d   |k(  s&||d<   , ? y w)Nr:  re   r   r7   r@  rB  )r  r   rR   rS   )rd   r   r   r  r   r   s         rB   r  z@AnthropicAssistantContextAggregator._update_function_call_result  sn      }}-- 	4Gv&(&y1 4G"7D1#FO}<#M2lB-3	*4	4s   "AAAA
Ac                 8  K   | j                  |j                  j                  |j                  j                  d       d{    | j                  j                  |j                  |j                  |j                  |j                  j                         y7 Vw)zHandle a user image frame with function call context.

        Marks the associated function call as completed and adds the image
        to the conversation context.

        Args:
            frame: User image frame with request context.
        r  N)rT  rU  rV  r   )
r  requestr   r   r  rg  rT  rU  rV  r   r  s     rB   handle_user_image_framez;AnthropicAssistantContextAggregator.handle_user_image_frame  s{      //MM'')C)C[
 	
 	
 	--<<++&&	 	. 	
	
s   ?BBABN)r9   r:   r;   r<   r   r  r   r  r   r  r=   r   r  r   r  r@   rA   rB   r`   r`     sX    	
<W 
>7N  

7N 

4 4034=@4
3D 
rA   r`   )Sr<   r   rY  ro  r]  r   r   dataclassesr   r   typingr   r   r   r   r	   r
   r  logurur   PILr   pydanticr   r   +pipecat.adapters.services.anthropic_adapterr   r   pipecat.frames.framesr   r   r   r   r   r   r   r   r   r   r   r   r   pipecat.metrics.metricsr   *pipecat.processors.aggregators.llm_contextr   +pipecat.processors.aggregators.llm_responser    r!   r"   r#   1pipecat.processors.aggregators.openai_llm_contextr$   r%   "pipecat.processors.frame_processorr&   pipecat.services.llm_servicer'   r(   pipecat.services.settingsr*   rH   r+   r,   r-   r.   (pipecat.utils.tracing.service_decoratorsr/   	anthropicr0   r1   r2   ModuleNotFoundErrorr  rj  r  r4   rD   r]   rj   r   r^   r`   r@   rA   rB   <module>r     sH      	  	 ( < <    %    2 A  > H = ^ ^ ?,NN(i (& ;  0 " " "Jr7* r7j{* {|	%= 	4g
*G g
K#  ,FLL;qc"#FLL^_
&qc*
++,s   8D E 2EE