o
    i2                     @   s   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 deZG dd dee ZdS )z$AWS Bedrock LLM adapter for Pipecat.    N)	dataclass)AnyDictListOptional	TypedDict)logger)BaseLLMAdapter)FunctionSchema)ToolsSchema)
LLMContextLLMContextMessageLLMContextToolChoiceLLMSpecificMessageLLMStandardMessagec                   @   sZ   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< dS )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    r   r   ]/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/adapters/services/bedrock_adapter.pyr      s   
 r   c                   @   s   e Zd ZdZedefddZdedefddZ	de
eeef  fdd	ZeG d
d dZde
e defddZdedeeef fddZdedeeef fddZededeeef fddZdede
eeef  fddZdS )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                 C   s   dS )zHGet the identifier used in LLMSpecificMessage instances for AWS Bedrock.awsr   selfr   r   r   id_for_llm_specific_messages-   s   z1AWSBedrockLLMAdapter.id_for_llm_specific_messagescontextc                 C   s0   |  | |}|j|j| |jp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   r   r   r   get_llm_invocation_params2   s   	z.AWSBedrockLLMAdapter.get_llm_invocation_paramsc                 C   sv   |  | |j}g }|D ]+}t|}d|v r3t|d tr3|d D ]}|dr2d|d d d< q#|| q|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itemr   r   r   get_messages_for_loggingG   s   

z-AWSBedrockLLMAdapter.get_messages_for_loggingc                   @   s2   e Zd ZU dZeeeef  ed< e	e ed< dS )z&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   r   ConvertedMessagesa   s   
 r9   universal_context_messagesc           	   
      s  d }g }z fdd|D }W n t y) } ztd|  W Y d }~nd }~ww |r?|d d dkr?|d d }|d |D ]}|d dkrMd|d< qAd}|t|d	 k r|| }||d	  }|d |d krt|d tr{d
|d dg|d< t|d trd
|d dg|d< |d |d  ||d	  n|d	7 }|t|d	 k sX|D ]+}t|d tr|d dkrd|d< qt|d trt|d dkrd
ddg|d< q j	||dS )Nc                       g | ]}  |qS r   )_from_universal_context_message).0mr"   r   r   
<listcomp>p       zIAWSBedrockLLMAdapter._from_universal_context_messages.<locals>.<listcomp>zError mapping messages: r   roler   r*   user   text)typerD    (empty))r   r   )
	Exceptionr   errorpoplenr0   r   extendr1   r9   )	r#   r:   r   r   er5   icurrent_messagenext_messager   r"   r   r&   h   sH   

z5AWSBedrockLLMAdapter._from_universal_context_messagesr5   c                 C   s    t |trt|jS | |S )N)r0   r   r.   r/   r5   _from_standard_message)r#   r5   r   r   r   r<      s   

z4AWSBedrockLLMAdapter._from_universal_context_messagec              
   C   s  t |}|d dkrUz(|d  dr+|d  dr+t|d }d|ig}nd|d ig}W n tjtt	fyG   d|d ig}Y nw dd	|d
 |digdS |
dr|d }dg d}|D ] }|d }t|d }d|d |d |di}	|d |	 qe|S |
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 ]l}|
dddkr|d dkr|d nd}|d|i |d dkr |d d dr|d d }|dd dd }|dd }d |d!t|d"d id#i}|| q|d d }td$|  qd%d& t|D }d'd& t|D }t|dkrU|rU|d }|d }||krO||}||| |d |dS |S )(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"}
                            }
                        }
                    ]
                }
        rA   toolr*   {}jsonrD   rB   
toolResulttool_call_id)	toolUseIdr*   )rA   r*   
tool_calls	assistantfunction	argumentstoolUseidname)rX   r_   inputrF   rG   rE   	image_urlurlzdata::rC   ;r   /r+   r-   ,)formatr,   zUnsupported 'image_url': c                 S      g | ]
\}}d |v r|qS )r+   r   r=   rN   r7   r   r   r   r?         z?AWSBedrockLLMAdapter._from_standard_message.<locals>.<listcomp>c                 S   rh   )rD   r   ri   r   r   r   r?     rj   )r.   r/   strip
startswithendswithrU   loadsJSONDecodeError
ValueErrorAttributeErrorr2   r3   r0   r   r1   splitbase64	b64decoder   warning	enumeraterK   rJ   insert)r#   r5   content_jsontool_result_contenttcret	tool_callr[   r\   new_tool_user*   new_contentr7   text_contentrb   	mime_typeimage_formatnew_itemimage_indicestext_indicesimg_idxfirst_txt_idx
image_itemr   r   r   rQ      s   
(






z+AWSBedrockLLMAdapter._from_standard_messager[   c                 C   s$   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.
        toolSpecrU   object)rE   
propertiesrequired)r_   descriptioninputSchema)r_   r   r   r   )r[   r   r   r   _to_bedrock_function_format$  s   z0AWSBedrockLLMAdapter._to_bedrock_function_formattools_schemac                    s   |j } fdd|D S )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.
        c                    r;   r   )r   )r=   funcr"   r   r   r?   F  r@   zAAWSBedrockLLMAdapter.to_provider_tools_format.<locals>.<listcomp>)standard_tools)r#   r   functions_schemar   r"   r   to_provider_tools_format<  s   	z-AWSBedrockLLMAdapter.to_provider_tools_formatN)r   r   r   r   propertyr   r$   r   r   r)   r   r   r   r8   r   r9   r   r&   r   r<   r   rQ   staticmethodr
   r   r   r   r   r   r   r   r   &   s&    
4 "r   )r   rs   r.   rU   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   r   <module>   s   		