
    qif                        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Zddlm	Z	m
Z
 ddlmZmZ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 dd	l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*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; 	 ddl<Z<ddl=m>Z> ddl?m@Z@ e	 G d de7             ZEe	 G d d             ZF G d de/      ZG G d de-      ZH G d d e+      ZI G d! d"e4      ZJy# eA$ r7ZB ej                  deB         ej                  d        eDdeB       dZB[Bww xY w)#zAWS Bedrock integration for Large Language Model services.

This module provides AWS Bedrock LLM service implementation with support for
Amazon Nova and Anthropic Claude models, including vision capabilities and
function calling.
    N)	dataclassfield)AnyDictListOptional)logger)Image)	BaseModelField)AWSBedrockLLMAdapterAWSBedrockLLMInvocationParams)
FrameFunctionCallCancelFrameFunctionCallFromLLMFunctionCallInProgressFrameFunctionCallResultFrameLLMContextFrameLLMFullResponseEndFrameLLMFullResponseStartFrameLLMMessagesFrameUserImageRawFrame)LLMTokenUsage)
LLMContext)LLMAssistantAggregatorParamsLLMAssistantContextAggregatorLLMUserAggregatorParamsLLMUserContextAggregator)OpenAILLMContextOpenAILLMContextFrame)FrameDirection)
LLMService)	NOT_GIVENLLMSettings	_NotGiven_warn_deprecated_param)
traced_llm)Config)ReadTimeoutErrorzException: zIn order to use AWS services, you need to `pip install pipecat-ai[aws]`. Also, remember to set `AWS_SECRET_ACCESS_KEY`, `AWS_ACCESS_KEY_ID`, and `AWS_REGION` environment variable.zMissing module: c                       e Zd ZU dZ ed       Zee   dz  ez  e	d<    ed       Z
eez  e	d<    ed       Zeeef   ez  e	d	<   y)
AWSBedrockLLMSettingsa  Settings for AWSBedrockLLMService.

    Parameters:
        stop_sequences: List of strings that stop generation.
        latency: Performance mode - "standard" or "optimized".
        additional_model_request_fields: Additional model-specific parameters.
    c                      t         S Nr#        J/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/aws/llm.py<lambda>zAWSBedrockLLMSettings.<lambda>S   s    QZ r0   default_factoryNstop_sequencesc                      t         S r-   r.   r/   r0   r1   r2   zAWSBedrockLLMSettings.<lambda>T   s    Y r0   latencyc                      t         S r-   r.   r/   r0   r1   r2   zAWSBedrockLLMSettings.<lambda>V   s    	 r0   additional_model_request_fields)__name__
__module____qualname____doc__r   r5   r   strr%   __annotations__r7   r9   r   r   r/   r0   r1   r+   r+   I   s^     49IZ3[NDI$y0[$5FGGS9_GBG)C#T#s(^i%? r0   r+   c                   6    e Zd ZU dZded<   ded<   d	dZd
dZy)AWSBedrockContextAggregatorPaira5  Container for AWS Bedrock context aggregators.

    Provides convenient access to both user and assistant context aggregators
    for AWS Bedrock LLM operations.

    .. deprecated:: 0.0.99
        `AWSBedrockContextAggregatorPair` 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 instance.
        _assistant: The assistant context aggregator instance.
    AWSBedrockUserContextAggregator_user$AWSBedrockAssistantContextAggregator
_assistantc                     | j                   S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )rC   selfs    r1   userz$AWSBedrockContextAggregatorPair.usero   s     zzr0   c                     | j                   S )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )rE   rG   s    r1   	assistantz)AWSBedrockContextAggregatorPair.assistantw   s     r0   N)returnrB   )rL   rD   )r:   r;   r<   r=   r?   rI   rK   r/   r0   r1   rA   rA   Z   s      -,66r0   rA   c                   .    e Zd ZdZ	 	 	 ddddeee      deee      dee   dee   f f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 Zd Z fdZd
eeeef      fdZ xZS )AWSBedrockLLMContexta  AWS Bedrock-specific LLM context implementation.

    Extends OpenAI LLM context to handle AWS Bedrock's specific message format
    and system message handling. Manages conversion between OpenAI and Bedrock
    message formats.

    .. deprecated:: 0.0.99
        `AWSBedrockLLMContext` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    N)systemmessagestoolstool_choicerO   c                8    t         |   |||       || _        y)aD  Initialize AWS Bedrock LLM context.

        Args:
            messages: List of conversation messages in OpenAI format.
            tools: List of available function calling tools.
            tool_choice: Tool selection strategy or specific tool choice.
            system: System message content for AWS Bedrock.
        rP   rQ   rR   N)super__init__rO   )rH   rP   rQ   rR   rO   	__class__s        r1   rV   zAWSBedrockLLMContext.__init__   s     " 	(%[Qr0   objrL   c                     t        j                  d|         t        | t              r-t        | t              st        | _        | j                          | S | j                          | S )zUpgrade an OpenAI LLM context to AWS Bedrock format.

        Args:
            obj: The OpenAI LLM context to upgrade.

        Returns:
            The upgraded AWS Bedrock LLM context.
        zUpgrading to AWS Bedrock: )r	   debug
isinstancer   rN   rW   !_restructure_from_openai_messages"_restructure_from_bedrock_messages)rX   s    r1   upgrade_to_bedrockz'AWSBedrockLLMContext.upgrade_to_bedrock   sZ     	1#78c+,ZEY5Z0CM113 
 224
r0   openai_contextc                      | |j                   |j                  |j                        }|j                  |j	                                |j                          |S )zCreate AWS Bedrock context from OpenAI context.

        Args:
            openai_context: The OpenAI LLM context to convert.

        Returns:
            New AWS Bedrock LLM context instance.
        rT   )rP   rQ   rR   set_llm_adapterget_llm_adapterr\   )clsr_   rH   s      r1   from_openai_contextz(AWSBedrockLLMContext.from_openai_context   sS     #,, &&&22

 	^;;=>..0r0   c                 8     | |      }|j                          |S )zCreate AWS Bedrock context from message list.

        Args:
            messages: List of messages in OpenAI format.

        Returns:
            New AWS Bedrock LLM context instance.
        )rP   )r\   )rc   rP   rH   s      r1   from_messagesz"AWSBedrockLLMContext.from_messages   s     H%..0r0   c                 B    || j                   dd | j                          y)zSet the messages list and restructure for Bedrock format.

        Args:
            messages: List of messages to set.
        N)	_messagesr\   )rH   rP   s     r1   set_messagesz!AWSBedrockLLMContext.set_messages   s     %q..0r0   c           
         |j                  d      }|j                  d      }|dk(  rt        |t              r
|d|dgdgS t        |t              rg }g }|D ]\  }d|v r|j	                  d|d   d       d|v s$|d   }|j	                  d|d	   |d
   t        j                  |d         dd       ^ g }|r|j	                  ||d       |r|j	                  ||d       |S y|dk(  rt        |t              r
|d|dgdgS t        |t              rg }g }|D ]  }d|v r|j	                  d|d   d       d|v s$|d   }	d}
t        |	d   t              r2|	d   D ])  }d|v r|d   }
d|v st        j                  |d         }
+ n|	d   }
|j	                  d|	d	   |
d        g }|r|j	                  ||d       |j                  |       |S yy)a  Convert AWS Bedrock message format to standard structured format.

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

        Args:
            obj: Message in AWS Bedrock format.

        Returns:
            List of messages in standard format.

        Examples:
            AWS Bedrock format input::

                {
                    "role": "assistant",
                    "content": [
                        {"text": "Hello"},
                        {"toolUse": {"toolUseId": "123", "name": "search", "input": {"q": "test"}}}
                    ]
                }

            Standard format output::

                [
                    {"role": "assistant", "content": [{"type": "text", "text": "Hello"}]},
                    {
                        "role": "assistant",
                        "tool_calls": [
                            {
                                "type": "function",
                                "id": "123",
                                "function": {"name": "search", "arguments": '{"q": "test"}'}
                            }
                        ]
                    }
                ]
        rolecontentrK   texttyperm   rk   rl   toolUsefunction	toolUseIdnameinput)rt   	arguments)ro   idrr   )rk   
tool_callsrI   
toolResult jsontool)rk   tool_call_idrl   N)getr[   r>   listappendr{   dumpsextend)rH   rX   rk   rl   
text_items
tool_itemsitemtool_userP   tool_resultresult_contentcontent_items               r1   to_standard_messagesz)AWSBedrockLLMContext.to_standard_messages   sE   L wwv'')$;'3'!%FG3T2UVWWGT*

# D~"))64<*PQ"d*#'	?"))(2&.{&;,4V,<15HW<M1N-"	 OOTj$IJOOT$LM/ +0 V^'3'!%FG3T2UVWWGT*

# D~"))64<*PQ%-&*<&8)+%k)&<dC0;I0F V#)\#95A&5IN%+|%;59ZZV@T5UN	V .9-CN"))(.0;K0H+9!. OOTj$IJ
+= + r0   c           	         |d   dk(  ry	 |d   j                         j                  d      r@|d   j                         j                  d      rt        j                  |d         }d|ig}nd|d   ig}dd	|d
   |digdS |j                  d      rR|d   }dg d}|D ]A  }|d   }t        j                  |d         }d|d   |d   |di}	|d   j                  |	       C |S |j                  d      }
t        |
t              r|
dk(  r|d   ddigdS |d   d|
igdS t        |
t              rg }|
D ]  }|j                  dd      dk(  r"|d   dk7  r|d   nd}|j                  d|i       |d   dk(  sCdddt        j                  |d   d   j                  d      d         idi}|j                  |        t!        |      D cg c]  \  }}d|v s| }}}t!        |      D cg c]  \  }}d|v s| }}}t#        |      dk(  r4|r2|d    }|d    }||kD  r|j%                  |      }|j'                  |       |d   |dS |S # t        j
                  t        t        f$ r d|d   ig}Y w xY wc c}}w c c}}w )!ax  Convert standard format message to AWS Bedrock 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 AWS Bedrock format.

        Examples:
            Standard format input::

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

            AWS Bedrock format output::

                {
                    "role": "assistant",
                    "content": [
                        {
                            "toolUse": {
                                "toolUseId": "123",
                                "name": "search",
                                "input": {"q": "test"}
                            }
                        }
                    ]
                }
        rk   r|   rl   {}r{   rm   rI   ry   r}   rs   rl   rp   rx   rK   rr   rv   rq   rw   rt   rs   rt   ru   rz   (empty)ro   	image_urlimagejpegbytesurl,   )formatsourcer   )strip
startswithendswithr{   loadsJSONDecodeError
ValueErrorAttributeErrorr~   r   r[   r>   r   base64	b64decodesplit	enumeratelenpopinsert)rH   messagecontent_jsontool_result_contenttcret	tool_callrr   rv   new_tool_userl   new_contentr   text_contentnew_itemiimage_indicestext_indicesimg_idxfirst_txt_idx
image_items                        r1   from_standard_messagez*AWSBedrockLLMContext.from_standard_messageD  s*   P 6?f$	E9%++-88='C%'((3-C( $(::gi.@#AL,2L+A*B',2GI4F+G*H'
  %)0)@':'
 
 ;;|$&B&26C 
4	$Z0 JJx'<=	%.t_ ( 0!*   I%%l3
4 J ++i(gs#"} 'fi=P<QRR 'fg=N<OPP&K 188FB'6137<23E4<9L&&'=><;.&, ')9)9${:KE:R:X:XY\:]^_:`)a'" H  &&x01& /8.DX71dSWQXMX-6{-CV'!TvQU~AVLV=!Q&<'* ,Q]*!,!9J""=*=#FODDM ((*nE E(.	0B'C&D#Ev YVs*   A*I I=I=0J=J&I:9I:)rm   r   sizer   rm   c                D   t        j                         }t        j                  |||      j	                  |d       t        j                  |j                               j                  d      }ddd|idg}|r|j                  d|i       | j                  d	|d
       y)a  Add an image message to the context.

        Args:
            format: The image format (e.g., 'RGB', 'RGBA').
            size: The image dimensions as (width, height).
            image: The raw image data as bytes.
            text: Optional text to accompany the image.
        JPEG)r   zutf-8r   r   r   )ro   r   r   rm   rI   rp   N)ioBytesIOr
   	frombytessaver   	b64encodegetvaluedecoder   add_message)rH   r   r   r   rm   bufferencoded_imagerl   s           r1   add_image_frame_messagez,AWSBedrockLLMContext.add_image_frame_message  s     e,11&1H(():;BB7K $v'=AYZ[NNFD>*&W=>r0   c                 (   	 | j                   r| j                   d   d   |d   k(  rt        | j                   d   d   t              r%d| j                   d   d   ig| j                   d   d<   t        |d   t              rd|d   i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.

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

        Args:
            message: The message to add to the context.
        rk   rl   rm   zError adding message: N)rP   r[   r>   r   r   	Exceptionr	   error)rH   r   es      r1   r   z AWSBedrockLLMContext.add_message  s   	7}} ==$V,? "$--"3I">D9?rARS\A]8^7_b))4 "')"4c:/5wy7I.J-K	*MM"%i077	8JKMM((1$$W- 	7LL1!566	7s$   B+C& .C& 
C& &	D/DDc                    | j                   r| j                   d   d   dk(  rt        | j                         dk(  rd| j                   d   d<   n| j                   j                  d      d   }t        |t              rd|ig}| j
                  rJt        | j
                  t              rd| j
                  ig| _        | j
                  j                  |       n|| _        | j                   D ]  }t        |d   t              rd|d   ig|d<   "|d   s	ddig|d<   0t        |d   t              sDt        |d         D ]H  \  }}t        |t              rd|v r|d   d	k(  rd|d<   (t        |t              s9|d	k(  s?ddi|d   |<   J  g }| j                   D ]>  }|r)|d
   d   |d   k(  r|d
   d   j                  |d          .|j                  |       @ | j                   j                          | j                   j                  |       y)zRestructure messages in AWS Bedrock format.

        Handles system messages, merging consecutive messages with the same role,
        and ensuring proper content formatting.
        r   rk   rO   r   rI   rl   rm   r   rz   r   N)rP   r   r   r[   r>   rO   r   r   r   dictr   clear)rH   system_contentmsgidxr   merged_messagess         r1   r]   z7AWSBedrockLLMContext._restructure_from_bedrock_messages  s    ==T]]1-f5A4==!Q&+1a (!%!2!21!5i!@nc2'-~&>%?N;;!$++s3(.'<&=KK&&~6"0DK == 
	BC#i.#.#)3y>":!;I^#)9"5!6IC	ND1!*3y>!: BIC!$-&D.T&\UWEW'0V#D#.42:/5y.AIs+	B
	B == 	,C?2#6v#>#f+#M#I.55c)nE&&s+		, 	_-r0   c                    	 | j                   D cg c]  }| j                  |       c}| j                   d d  | j
                  rG| j
                  d   d   dk(  r2| 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   rk   rO   rl   r   rm   rn   rz   r   )rh   r   r   r	   r   rP   rO   r   r   r[   r>   r   r   )rH   mr   r   current_messagenext_messager   s          r1   r\   z6AWSBedrockLLMContext._restructure_from_openai_messages!  s   	9HL W1!;!;A!> WDNN1 ==T]]1-f5A--*95DKMMa  #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? !X 	9LL3A3788	9s'   G GG G 	G<G77G<c                 z    t         |          }| j                  r|j                  dd| j                  d       |S )zGet messages formatted for persistent storage.

        Returns:
            List of messages including system message if present.
        r   rO   rp   )rU   #get_messages_for_persistent_storagerO   r   )rH   rP   rW   s     r1   r   z8AWSBedrockLLMContext.get_messages_for_persistent_storageI  s5     7>@;;OOAT[[IJr0   c                     g }| j                   D ]f  }t        j                  |      }d|v r:t        |d   t              r'|d   D ]  }|j                  d      sd|d   d   d<   ! |j                  |       h |S )zGet messages formatted for logging with sensitive data redacted.

        Returns:
            List of messages in a format ready for logging.
        rl   r   z...r   r   )rP   copydeepcopyr[   r   r~   r   )rH   msgsr   r   r   s        r1   get_messages_for_loggingz-AWSBedrockLLMContext.get_messages_for_loggingT  s     }} 	G--(CCc)nd3 #I E88G,?DDM(3G<E KK	 r0   )NNN)r:   r;   r<   r=   r   r   r   r>   rV   staticmethodr   r^   classmethodrd   rf   ri   r   r   tupleintr   r   r   r]   r\   r   r   r   r   __classcell__rW   s   @r1   rN   rN      sH   
 *.&*&*	 !%4:& T
# d^	 (  0 5K  " 1A  $ T$Z 4J  1T 1e Nxv PT??$)#s(O?<A?IL?*7@,.\&KP	$tCH~*> r0   rN   c                       e Zd ZdZy)rB   a_  User context aggregator for AWS Bedrock LLM service.

    Handles aggregation of user messages and frames for AWS Bedrock format.
    Inherits all functionality from the base LLM user context aggregator.

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

    Args:
        context: The LLM context to aggregate messages into.
        params: Configuration parameters for the aggregator.
    N)r:   r;   r<   r=   r/   r0   r1   rB   rB   f  s      	r0   rB   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)rD   a^  Assistant context aggregator for AWS Bedrock LLM service.

    Handles aggregation of assistant responses and function calls for AWS Bedrock
    format, including tool use and tool result handling.

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

    Args:
        context: The LLM context to aggregate messages into.
        params: Configuration parameters for the aggregator.
    framec                   K   | j                   j                  dd|j                  |j                  |j                  r|j                  ni digd       | j                   j                  dd|j                  ddigd	igd       y
w)zHandle function call in progress frame.

        Args:
            frame: The function call in progress frame to handle.
        rK   rq   r   rp   rI   ry   rm   IN_PROGRESSr   N)_contextr   r}   function_namerv   rH   r   s     r1    handle_function_call_in_progresszEAWSBedrockAssistantContextAggregator.handle_function_call_in_progress  s      	!!# ").););$)$7$78=U__R$	
 	!! %).););)/(?'@'
	
s   BBc                 (  K   |j                   rOt        j                  |j                         }| j                  |j                  |j
                  |       d{    y| j                  |j                  |j
                  d       d{    y7 57 w)zwHandle function call result frame.

        Args:
            frame: The function call result frame to handle.
        N	COMPLETED)resultr{   r   _update_function_call_resultr   r}   )rH   r   r   s      r1   handle_function_call_resultz@AWSBedrockAssistantContextAggregator.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)zwHandle function call cancel frame.

        Args:
            frame: The function call cancel frame to handle.
        	CANCELLEDN)r   r   r}   r   s     r1   handle_function_call_cancelz@AWSBedrockAssistantContextAggregator.handle_function_call_cancel  s3      //!3!3[
 	
 	
s   +535r   r}   r   c                    K   | j                   j                  D ]O  }|d   dk(  s|d   D ]<  }t        |t              s|j	                  d      s&|d   d   |k(  s2d|ig|d   d<   > Q y w)Nrk   rI   rl   ry   rs   rm   )r   rP   r[   r   r~   )rH   r   r}   r   r   rl   s         r1   r   zAAWSBedrockAssistantContextAggregator._update_function_call_result  s      }}-- 	NGv&(&y1 NG"7D1#KK5#L1+>,N=CV<L;M-i8N	Ns   "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)zcHandle user image frame.

        Args:
            frame: The user image frame to handle.
        r   N)r   r   r   rm   )
r   requestr   r}   r   r   r   r   r   contextr   s     r1   handle_user_image_framez<AWSBedrockAssistantContextAggregator.handle_user_image_frame  s{      //MM'')C)C[
 	
 	
 	--<<++&&	 	. 	
	
s   ?BBABN)r:   r;   r<   r=   r   r   r   r   r   r   r>   r   r   r   r   r/   r0   r1   rD   rD   z  s]    "!
<W !
F7N 
7N 
N N03N=@N
3D 
r0   rD   c                       e Zd ZU dZeZeed<   eZ G d de	      Z
ddddddddddddd	ee   d
ee   dee   dee   dee   dee
   dee   deee      dee   dee   dee   f fdZdefdZdeeef   fdZ	 	 d.deez  dee   dee   dee   fdZd Z e        e       ddedededefd Z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 )/AWSBedrockLLMServicezAWS Bedrock Large Language Model service implementation.

    Provides inference capabilities for AWS Bedrock models including Amazon Nova
    and Anthropic Claude. Supports streaming responses, function calling, and
    vision capabilities.
    	_settingsc                       e Zd ZU dZ edd      Zee   ed<    eddd      Z	ee
   ed	<    eddd      Zee
   ed
<    ed       Zeee      ed<    ed      Zee   ed<    ee      Zeeeef      ed<   y) AWSBedrockLLMService.InputParamsa  Input parameters for AWS Bedrock LLM service.

        .. deprecated:: 0.0.105
            Use ``AWSBedrockLLMSettings`` instead. Pass settings directly via the
            ``settings`` parameter of :class:`AWSBedrockLLMService`.

        Parameters:
            max_tokens: Maximum number of tokens to generate.
            temperature: Sampling temperature between 0.0 and 1.0.
            top_p: Nucleus sampling parameter between 0.0 and 1.0.
            stop_sequences: List of strings that stop generation.
            latency: Performance mode - "standard" or "optimized".
            additional_model_request_fields: Additional model-specific parameters.
        Nr   )defaultge
max_tokensg        g      ?)r   r   letemperaturetop_pc                      g S r-   r/   r/   r0   r1   r2   z)AWSBedrockLLMService.InputParams.<lambda>  s    B r0   r3   r5   )r   r7   r9   )r:   r;   r<   r=   r   r  r   r   r?   r  floatr  r5   r   r>   r7   r   r9   r   r   r/   r0   r1   InputParamsr     s    	 %*$1$=
HSM=',Tcc'JXe_J!&t!DxD.3J.Oc+O!&t!4#4DIZ^D_'$sCx.)A_r0   r  Ng      @F)modelaws_access_keyaws_secret_keyaws_session_token
aws_regionparamssettingsr5   client_configretry_timeout_secsretry_on_timeoutr  r	  r
  r  r  r  r  r5   r  r  r  c                P   t        dddddddddddddi       }|t        dt         d       ||_        |t        dt         d       ||_        |t        dt                |s|j                  |_        |j
                  |_        |j                  |_        |j                  r|j                  |_        |j                  |_        t        |j                  t              r|j                  |_	        ||j                  |       t        | 4  dd|i| |	st        d	d	d
di      }	t        j                          | _        |xs t%        j&                  d      |xs t%        j&                  d      |xs t%        j&                  d      |xs t%        j&                  dd      |	d| _        |
| _        || _        t/        j0                  d| j2                  j                          | j2                  j4                  r/t/        j6                  |  d| j2                  j4                          yy)az  Initialize the AWS Bedrock LLM service.

        Args:
            model: The AWS Bedrock model identifier to use.

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

            aws_access_key: AWS access key ID. If None, uses default credentials.
            aws_secret_key: AWS secret access key. If None, uses default credentials.
            aws_session_token: AWS session token for temporary credentials.
            aws_region: AWS region for the Bedrock service.
            params: Model parameters and configuration.

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

            settings: Runtime-updatable settings for this service.  When both
                deprecated parameters and *settings* are provided, *settings*
                values take precedence.
            stop_sequences: List of strings that stop generation.

                .. deprecated:: 0.0.105
                    Use ``settings=AWSBedrockLLMSettings(stop_sequences=...)`` instead.

            client_config: Custom boto3 client configuration.
            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us.amazon.nova-lite-v1:0NF)r  system_instructionr  r  r  top_kfrequency_penaltypresence_penaltyseedfilter_incomplete_user_turnsuser_turn_completion_configr5   r7   r9   r  r5   r  r  i,  max_attempts   )connect_timeoutread_timeoutretriesAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN
AWS_REGIONz	us-east-1)aws_access_key_idaws_secret_access_keyr  region_nameconfigzUsing AWS Bedrock model: z: Using system instruction: r/   )r+   r&   r  r5   r  r  r  r7   r[   r9   r   apply_updaterU   rV   r(   aioboto3Session_aws_sessionosgetenv_aws_params_retry_timeout_secs_retry_on_timeoutr	   infor   r  rZ   )rH   r  r	  r
  r  r  r  r  r5   r  r  r  kwargsdefault_settingsrW   s                 r1   rV   zAWSBedrockLLMService.__init__
  s   ^ 1,#"!).(,,.
$ "7,A7K%*"%"#35JL\].<+ "8-BC.4.?.? +/5/A/A ,)/ &((6<6K6K$3+1>> (fDDdK>> %D
 ))(3="2=f= " # '+M %,,. "0!Q299=P3Q%3%YryyAX7Y!2!Tbii@S6T%M<)M#
 $6 !1/0D0D/EFG>>,,LLD6!=dnn>_>_=`ab -r0   rL   c                      y)zCheck if the service can generate usage metrics.

        Returns:
            True if metrics generation is supported.
        Tr/   rG   s    r1   can_generate_metricsz)AWSBedrockLLMService.can_generate_metrics  s     r0   c                    i }| j                   j                  | j                   j                  |d<   | j                   j                  | j                   j                  |d<   | j                   j                  | j                   j                  |d<   | j                   j                  r| j                   j                  |d<   |S )aO  Build inference config with only the parameters that are set.

        This prevents conflicts with models (e.g., Claude Sonnet 4.5) that don't
        allow certain parameter combinations like temperature and top_p together.

        Returns:
            Dictionary containing only the inference parameters that are not None.
        	maxTokensr  topPstopSequences)r   r  r  r  r5   )rH   inference_configs     r1   _build_inference_configz,AWSBedrockLLMService._build_inference_config  s     >>$$0,0NN,E,E[)>>%%1.2nn.H.H]+>>+'+~~';';V$>>((040M0M_-r0   r   r  r  c                   K   g }g }t        |t              r,| j                         }|j                  |      }|d   }|d   }n.t        j                  |      }|j                  }t        |dd      }||rt        j                  |  d       d|ig}| j                         }|||d<   | j                  j                  || j                  j                  d}	|r||	d<   |r||	d<    | j                  j                  dd	d
i| j                   4 d{   }
 |
j"                  di |	 d{   }d|v rd|d   v ryd|d   d   v ro|d   d   d   }t        |t$              r1|D ]+  }|j'                  d      s|d   c cddd      d{    S  n#t        |t(              r|cddd      d{    S 	 ddd      d{    y7 7 7 @7 7 # 1 d{  7  sw Y   yxY w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.
        rP   rO   N\: Both system_instruction and a system message in context are set. Using system_instruction.rm   r6  modelIdrP   additionalModelRequestFieldsinferenceConfigservice_namebedrock-runtimeoutputr   rl   r/   )r[   r   rb   get_llm_invocation_paramsrN   r^   rP   getattrr	   warningr:  r   r  r9   r*  clientr-  converser   r~   r>   )rH   r   r  r  rP   rO   adapterr  r9  request_paramsrG  responserl   r   s                 r1   run_inferencez"AWSBedrockLLMService.run_inference  s9    $ gz*,0,@,@,BG4;4U4UV]4^Fj)HH%F*==gFG''HWh5F )f 1 1 123F  779 !,6[) ~~++ ,0NN,Z,Z
 0@N,-'-N8$+4$$++ 
*
.2.>.>
 	 	,V__>~>>H H$(!33(!3I!>>"8,Y7	Bgt, ' 088F+#'</!	 	 	0  -"%	 	 	( )	 	 	 ?		 	 	 	 	 	s   DG%GG%G+G,A
G7G=G%	G

G%G"G%.G/G%4G5G% GG%G
G%G%G%G"GG"G%c                   K   | j                   r<	 t        j                   |j                  di || j                         d{   }|S  |j                  di | d{   }|S 7 "# t
        t        j                  f$ r?}t        j                  |  d        |j                  di | d{  7  }|cY d}~S d}~ww xY w7 cw)a  Create converse stream with optional timeout and retry.

        Args:
            client: The AWS Bedrock client instance.
            request_params: Parameters for the converse_stream call.

        Returns:
            Async stream of response events.
        )timeoutNz): Retrying converse_stream due to timeoutr/   )	r/  asynciowait_forconverse_streamr.  r)   TimeoutErrorr	   rZ   )rH   rG  rJ  rK  r   s        r1   _create_converse_streamz,AWSBedrockLLMService._create_converse_stream  s      !!	 !(!1!1*F**<^<dF^F^"    4V33EnEEHO %g&:&:;  v%NOP!7!7!7!I.!III	  Fs^   C4A) A'A) 
C C!C'A) )C-B</B20B<6C7C<CC)user_paramsassistant_paramsrT  rU  c                    |j                  | j                                t        |t              rt        j                  |      }t        ||      }t        ||      }t        ||      S )a  Create AWS Bedrock-specific context aggregators.

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

        Args:
            context: The LLM context to create aggregators for.
            user_params: Parameters for user message aggregation.
            assistant_params: Parameters for assistant message aggregation.

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

        .. 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  )rC   rE   )	ra   rb   r[   r   rN   rd   rB   rD   rA   )rH   r   rT  rU  rI   rK   s         r1   create_context_aggregatorz.AWSBedrockLLMService.create_context_aggregator  s^    6 	 4 4 67g/0*>>wGG /w{K8IYZ	.TiPPr0   c                     dddddi g didiS )ag  Create a no-operation tool for AWS Bedrock when tool content exists but no tools are defined.

        This is required because AWS Bedrock doesn't allow empty tool configurations after tools were
        previously set. Other LLM vendors allow NOT_GIVEN or empty tool configurations,
        but AWS Bedrock requires at least one tool to be defined.
        toolSpecno_operationz9Internal placeholder function. Do not call this function.r{   object)ro   
propertiesrequired)rt   descriptioninputSchemar/   rG   s    r1   _create_no_op_toolz'AWSBedrockLLMService._create_no_op_tool,  s,     &Z &Y[(\]
 	
r0   c                 ~   t        |t              rr| j                         }|j                  |      }| j                  j
                  r9|d   rt        j                  |  d       d| j                  j
                  ig|d<   |S t        t        |dd       |j                  |j                  xs g |j                        S )NrO   r<  rm   )rO   rP   rQ   rR   )r[   r   rb   rD  r   r  r	   rF  r   rE  rP   rQ   rR   )rH   r   rI  r  s       r1   _get_llm_invocation_paramsz/AWSBedrockLLMService._get_llm_invocation_params;  s     gz*,0,@,@,BG4;4U4UV]4^F~~00(#NN& !: : &,T^^-N-N$O#Px M -7Hd3%%--%2++	
 	
r0   c           
        K   d}d}d}d}d}d}d}	 | j                  t                      d {    | j                          d {    | j                          d {    | j	                  |      }	|	d   }
|	d   }|	d   }|	d   }| j                         }| j                  j                  |
| j                  j                  d}|r||d<   |r||d<   d}|
D ];  }t        |j                  d	      t              r|d	   D ]  }d
|v sd|v sd} n |s; n |r|s| j                         g}d}|rCd|i}|s8|r6|dk(  rdi i|d<   n)|dk(  rn#t        |t              rd|v rdd|d   d   ii|d<   ||d<   | j                  j                  dv rd| j                  j                  i|d<   t        |t              r$| j!                         }d}|j#                  |      }nd}|j#                         }t%        j&                  |  d| d| d|         | j(                  j*                  d9ddi| j,                  4 d {   }| j/                  ||       d {   }| j1                          d {    d }d}g }|d   2 3 d {   }d |v rq|d    d!   }d"|v r4| j3                  |d"          d {    || j5                  |d"         z  }nd
|v rd#|d
   v r||d
   d#   z  }|| j5                  |d
   d#         z  }nd$|v r:|d$   d%   }d
|v r|d
   j                  d&d      |d
   j                  dd      d'}d}nnd(|v rjd)|d(   v rc|d(   d)   d*k(  rX|rV	 |rt7        j8                  |      ni }|s%|j;                  t=        ||d+   |d   |,             nt%        j&                  d-       d/|v s0d0|d/   v s9|d/   d0   } || j                  d1d      z  }|| j                  d2d      z  }|| j                  d3d      z  }|| j                  d4d      z  }7 7 7 7 7 7 7 7 |# t6        j>                  $ r t%        j@                  d.|        Y w xY w6 d d d       d {  7   n# 1 d {  7  sw Y   nxY w| jC                         d {  7   n~# tD        jF                  $ r d} tH        tD        jJ                  f$ r | jM                  d5       d {  7   Y n4tN        $ r)}!| jQ                  d6|! |!7       d {  7   Y d }!~!nd }!~!ww xY w| jS                          d {  7   | j                  tU                      d {  7   |s|n|}"| jW                  ||"||8       d {  7   y # | jS                          d {  7   | j                  tU                      d {  7   |s|n|}"| jW                  ||"||8       d {  7   w xY ww):Nr   FrP   rO   rQ   rR   r=  r@  rl   rq   ry   Tauto
toolChoicenonerr   r|   rt   
toolConfig)standard	optimizedr7   performanceConfig	universalzLLM-specificz: Generating chat from z
 context [z] | rA  rB  rz   streamcontentBlockDeltadeltarm   ru   contentBlockStartstartrs   )rw   rt   messageStop
stopReasonr   rw   )r   r}   r   rv   zIgnoring no_operation tool callz Failed to parse tool arguments: metadatausageinputTokensoutputTokenscacheReadInputTokenscacheWriteInputTokenson_completion_timeoutzUnknown error occurred: )	error_msg	exception)prompt_tokenscompletion_tokenscache_read_input_tokenscache_creation_input_tokensr/   ),
push_framer   start_processing_metricsstart_ttfb_metricsrb  r:  r   r  r9   r[   r~   r   r`  r   r7   r   rb   r   r	   rZ   r*  rG  r-  rS  stop_ttfb_metrics_push_llm_text_estimate_tokensr{   r   r   r   r   r   run_function_callsrO  CancelledErrorr)   rR  _call_event_handlerr   
push_errorstop_processing_metricsr   _report_usage_metrics)#rH   r   r|  r}  completion_tokens_estimater~  r  use_completion_tokens_estimateusing_noop_toolparams_from_contextrP   rO   rQ   rR   r9  rJ  has_tool_contentr   r   tool_configrI  context_type_for_loggingmessages_for_loggingrG  rK  tool_use_blockjson_accumulatorfunction_callseventrn  content_block_startrv   rt  r   comp_tokenss#                                      r1   _process_contextz%AWSBedrockLLMService._process_contextS  s     %&""#&'#).&j	//";"=>>>//111))+++"&"A"A'"J*:6H(2F'0E-m<K  $;;=  >>//$040^0^N  4D01 +1x(  %# gkk)4d;(/	(: "$48T/3,!" $  0023"&&. ';"f,5;RLL1$.#K6:;T"V[-DV-L$M5L1 0;|, ~~%%)BB7@$..BXBX6Y23 ':...0+6('.'G'G'P$+9('.'G'G'I$LL&/0H/ITZS[[_`t_uv 0t((// .262B2B A] A]!%!=!=fn!UU,,... "&#% !##+H#5 3] 3]%*e3 %&9 :7 C!U?"&"5"5eFm"DDD6$:O:OPUV\P]:^^6&%/GuY?O4O,i0@0II,6$:O:O %i 0 9; 6
 -5.34G.H.Q+$(;;&9)&D&H&HVX&Y(;I(F(J(J6SU(V.N 02, '%/LE-DX4X /=KP^dL\DJJ7G,Hbd	 (7$2$9$9(;4;9G9M:H:P6?	)*%& %+LL1R$S
 "U*w%
:K/K %j 1' :%=!)DD)UYY~q-II)/599=SUV3WW/3uyyAXZ[7\\3_ ?1+VA] V.3]
 EJ $(#7#7 d &/OP`Oa-b cdU $6A] A] A] A] A]F )).999%% 	 .2* '"6"67 	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  WR PR PR PB+R R D$R 7P8R ;Q,PQ,)P*Q,9Q=P">Q(Q,)P%*B#Q,AP(#Q,)Q,2AQ,R R R R Q,Q,"Q%Q,(+QQ,QQ,R %Q(&R ,Q>2Q53Q>:R RR U: ATS!T$U: &T.TT
TU: TU: W-T0.!WU#W3U64W:WV!W0V31#WWWWr   	directionc                   K   t         |   ||       d{    d}t        |t              rt        j                  |j                        }t        |t              r|j                  }nJt        |t              r t        j                  |j                        }n| j                  ||       d{    |r| j                  |       d{    yy7 7 #7 
w)zProcess incoming frames and handle LLM-specific frame types.

        Args:
            frame: The frame to process.
            direction: The direction of frame processing.
        N)rU   process_framer[   r    rN   r^   r   r   r   rf   rP   r  r  )rH   r   r  r   rW   s       r1   r  z"AWSBedrockLLMService.process_frame  s      g#E9555e23*==emmLGe_-mmG/0 +88HG//%333''000  	6 4 1s4   CCBC/C0C
CCCCrm   c                 X    t        t        t        j                  d|            dz        S )Nz[^\w]+g?)r   r   rer   )rH   rm   s     r1   r  z%AWSBedrockLLMService._estimate_tokens#  s"    3rxx	401C788r0   r|  r}  r~  r  c                 r   K   |s|r-t        ||||z   ||      }| j                  |       d {    y y 7 w)N)r|  r}  total_tokensr~  r  )r   start_llm_usage_metrics)rH   r|  r}  r~  r  tokenss         r1   r  z*AWSBedrockLLMService._report_usage_metrics&  sM      -"+"3*->>(?,GF ..v666 . 7s   ,757)NN)+r:   r;   r<   r=   r+   Settingsr?   r   adapter_classr   r  r   r>   r   r(   r  boolrV   r4  r   r   r:  r   r   r   rL  rS  r   r   rA   rW  r`  r   rb  r'   rN   r  r   r!   r  r  r  r   r   s   @r1   r   r     sS    %H$$ )M`i `4  $(,(,+/$((,48.2*..1+0uc }uc !	uc
 !uc $C=uc SMuc %uc 01uc !c+uc  'uc %UOuc #4.ucnd  c3h  . %),0	N..N SMN %SM	N
 
#N`: 0G/H9U9W$Q!$Q -	$Q
 7$Q 
)$QL

'*4
	&
0 u.BZ.O u un1 1> 109S 9S 977 7 "%	7
 &)7r0   r   )Kr=   rO  r   r   r   r{   r+  r  dataclassesr   r   typingr   r   r   r   logurur	   PILr
   pydanticr   r   )pipecat.adapters.services.bedrock_adapterr   r   pipecat.frames.framesr   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"   pipecat.services.settingsr#   r$   r%   r&   (pipecat.utils.tracing.service_decoratorsr'   r(  botocore.configr(   botocore.exceptionsr)   ModuleNotFoundErrorr   r   r   r+   rA   rN   rB   rD   r   r/   r0   r1   <module>r     s>      	  	 	 ( , ,   %   2 A  > 3 _ _ ?	,&4 K    " " "Jc+ cL	&> 	(h
+H h
VP	7: P	7I  ,FLL;qc"#FLL 	~ &qc*
++,s   &D D>2D99D>