
    qi2                         d Z ddlZddlZddlZddlmZ ddl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 ddlmZ dd	lmZmZmZmZmZ  G d
 de      Z G d dee         Zy)z$AWS Bedrock LLM adapter for Pipecat.    N)	dataclass)AnyDictListOptional	TypedDict)logger)BaseLLMAdapter)FunctionSchema)ToolsSchema)
LLMContextLLMContextMessageLLMContextToolChoiceLLMSpecificMessageLLMStandardMessagec                   p    e Zd ZU dZeeeeef         e	d<   eeeef      e	d<   eeeef      e	d<   e
e	d<   y)AWSBedrockLLMInvocationParamsz<Context-based parameters for invoking AWS Bedrock's LLM API.systemmessagestoolstool_choiceN)__name__
__module____qualname____doc__r   r   dictstrr   __annotations__r        [/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/adapters/services/bedrock_adapter.pyr   r      sI    FT$sCx.)**4S>""S#X%%r    r   c                       e Zd ZdZedefd       ZdedefdZ	de
eeef      fdZe G d d             Zd	e
e   defd
Zdedeeef   fdZdedeeef   fdZededeeef   fd       Zdede
eeef      fdZy)AWSBedrockLLMAdapterzAdapter for AWS Bedrock LLM integration with Pipecat.

    Provides conversion utilities for transforming Pipecat function schemas
    into AWS Bedrock's expected tool format for function calling capabilities.
    returnc                      y)zHGet the identifier used in LLMSpecificMessage instances for AWS Bedrock.awsr   )selfs    r!   id_for_llm_specific_messagesz1AWSBedrockLLMAdapter.id_for_llm_specific_messages-   s     r    contextc                     | j                  | j                  |            }|j                  |j                  | j	                  |j
                        xs g |j                  dS )a	  Get AWS Bedrock-specific LLM invocation parameters from a universal LLM context.

        Args:
            context: The LLM context containing messages, tools, etc.

        Returns:
            Dictionary of parameters for invoking AWS Bedrock's LLM API.
        )r   r   r   r   ) _from_universal_context_messagesget_messagesr   r   from_standard_toolsr   r   )r'   r)   r   s      r!   get_llm_invocation_paramsz.AWSBedrockLLMAdapter.get_llm_invocation_params2   s[     889J9J79SToo ))--gmm<B #..	
 		
r    c                 4   | j                  | j                  |            j                  }g }|D ]f  }t        j                  |      }d|v r:t        |d   t              r'|d   D ]  }|j                  d      sd|d   d   d<   ! |j                  |       h |S )a^  Get messages from a universal LLM context in a format ready for logging about AWS Bedrock.

        Removes or truncates sensitive data like image content for safe logging.

        Args:
            context: The LLM context containing messages.

        Returns:
            List of messages in a format ready for logging about AWS Bedrock.
        contentimagez...sourcebytes)	r+   r,   r   copydeepcopy
isinstancelistgetappend)r'   r)   r   messages_for_loggingmessagemsgitems          r!   get_messages_for_loggingz-AWSBedrockLLMAdapter.get_messages_for_loggingG   s     889J9J79ST]]  " 	-G--(CCc)nd3 #I E88G,?DDM(3G<E !'',	- $#r    c                   <    e Zd ZU dZeeeef      ed<   e	e   ed<   y)&AWSBedrockLLMAdapter.ConvertedMessageszLContainer for Anthropic-formatted messages converted from universal context.r   r   N)
r   r   r   r   r   r   r   r   r   r   r   r    r!   ConvertedMessagesr@   a   s"    ZtCH~&&r    rA   universal_context_messagesc                 R   d }g }	 |D cg c]  }| j                  |       }}|r$|d   d   dk(  r|d   d   }|j	                  d       |D ]  }|d   dk(  sd|d<    d}|t        |      dz
  k  r||   }||dz      }	|d   |	d   k(  rjt        |d   t              rd|d   d	g|d<   t        |	d   t              rd|	d   d	g|	d<   |d   j                  |	d          |j	                  |dz          n|dz  }|t        |      dz
  k  r|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 | j                  ||      S c c}w # t        $ r#}t        j                  d|        Y d }~}d }~ww xY w)NzError mapping messages: r   roler   r0   user   text)typerG    (empty))r   r   )_from_universal_context_message	Exceptionr	   errorpoplenr6   r   extendr7   rA   )
r'   rB   r   r   mer;   icurrent_messagenext_messages
             r!   r+   z5AWSBedrockLLMAdapter._from_universal_context_messagesh   s    	9IcdA<<Q?dHd
 F+x7a[+FLLO   	)Gv(*"(	)
 #h-!##&qkO#AE?Lv&,v*>>oi8#>!'1KL2OI. l95s;8>U^H_/`.aL+	*11,y2IJQU#Q! #h-!##&   	KG'),c2wy7IR7O%.	"GI.5#gi>P:QUV:V/5y&I%J	"		K %%x%GGU e 	9LL3A3788	9s'   E: E5E: 5E: :	F&F!!F&r;   c                     t        |t              rt        j                  |j                        S | j                  |      S )N)r6   r   r4   r5   r;   _from_standard_message)r'   r;   s     r!   rK   z4AWSBedrockLLMAdapter._from_universal_context_message   s1    g12==11**733r    c           	      $   t        j                  |      }|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              rg }|
D ]  }|j                  dd      dk(  r"|d   dk7  r|d   nd}|j                  d|i       |d   dk(  sC|d   d   j                  d      r|d   d   }|j                  d      d   j                  d      d   }|j                  d      d   }d |d!t!        j"                  |j                  d"      d         id#i}|j                  |       |d   d   }t%        j&                  d$|         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 yw 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"}
                            }
                        }
                    ]
                }
        rD   toolr0   {}jsonrG   rE   
toolResulttool_call_id)	toolUseIdr0   )rD   r0   
tool_calls	assistantfunction	argumentstoolUseidname)r_   rf   inputrI   rJ   rH   	image_urlurlzdata::rF   ;r   /r1   r3   ,)formatr2   zUnsupported 'image_url': )r4   r5   strip
startswithendswithr\   loadsJSONDecodeError
ValueErrorAttributeErrorr8   r9   r6   r   r7   splitbase64	b64decoder	   warning	enumeraterO   rN   insert)r'   r;   content_jsontool_result_contenttcret	tool_callrb   rc   new_tool_user0   new_contentr=   text_contentri   	mime_typeimage_formatnew_itemrS   image_indicestext_indicesimg_idxfirst_txt_idx
image_items                           r!   rW   z+AWSBedrockLLMAdapter._from_standard_message   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 J88FB'6137<23E4<9L&&'=><;.K(/::7C";/6$'IIcN1$5$;$;C$@$C	'0s';A'>#*6+2F4D4DSYYs^TUEV4W*X&$ $**84";/6)B3%'HI-J6 /8.DX71dSWQXMX-6{-CV'!TvQU~AVLV=!Q&<'* ,Q]*!,!9J""=*=#FODD] ((*nE E(.	0B'C&D#EF YVs*   A*K L$L9LL&LLrb   c                 n    d| j                   | j                  dd| j                  | j                  didiS )zConvert a function schema to Bedrock's tool format.

        Args:
            function: The function schema to convert.

        Returns:
            Dictionary formatted for Bedrock's tool specification.
        toolSpecr\   object)rH   
propertiesrequired)rf   descriptioninputSchema)rf   r   r   r   )rb   s    r!   _to_bedrock_function_formatz0AWSBedrockLLMAdapter._to_bedrock_function_format$  sH      '33 (&.&9&9$,$5$5 

 	
r    tools_schemac                 b    |j                   }|D cg c]  }| j                  |       c}S c c}w )zConvert function schemas to Bedrock's function-calling format.

        Args:
            tools_schema: The tools schema containing functions to convert.

        Returns:
            List of Bedrock formatted function call definitions.
        )standard_toolsr   )r'   r   functions_schemafuncs       r!   to_provider_tools_formatz-AWSBedrockLLMAdapter.to_provider_tools_format<  s/     (66CST4006TTTs   ,N)r   r   r   r   propertyr   r(   r   r   r.   r   r   r   r>   r   rA   r   r+   r   rK   r   rW   staticmethodr   r   r   r   r   r    r!   r#   r#   &   s    c  
 
@] 
*$4S#X3G $4   2H*./@*A2H	2Hh47H 4TRUWZRZ^ 4
A.@ AT#s(^ AF 
n 
c3h 
 
.
U[ 
UT$sTWx.EY 
Ur    r#   )r   rw   r4   r\   dataclassesr   typingr   r   r   r   r   logurur	   !pipecat.adapters.base_llm_adapterr
   (pipecat.adapters.schemas.function_schemar   %pipecat.adapters.schemas.tools_schemar   *pipecat.processors.aggregators.llm_contextr   r   r   r   r   r   r#   r   r    r!   <module>r      sT    +    ! 7 7  < C = &I &`U>*GH `Ur    