
    qi@                        d Z ddlZ ej                         5   ej                  d        ej                  ded       ddd       ddlZddl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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! ddl"m#Z#m$Z$  G d de      Z%e G d d             Z&e G d d             Z' G d de      Z(e G d de             Z) G d de$      Z* G d de#      Z+e G d d             Z,y# 1 sw Y   xY w)a  Context management for AWS Nova Sonic LLM service.

This module provides specialized context aggregators and message handling for AWS Nova Sonic,
including conversation history management and role-specific message processing.

.. deprecated:: 0.0.91
    AWS Nova Sonic no longer uses types from this module under the hood.
    It now uses ``LLMContext`` and ``LLMContextAggregatorPair``.
    Using the new patterns should allow you to not need types from this module.

    BEFORE::

        # Setup
        context = OpenAILLMContext(messages, tools)
        context_aggregator = llm.create_context_aggregator(context)

        # Context frame type
        frame: OpenAILLMContextFrame

        # Context type
        context: AWSNovaSonicLLMContext
        # or
        context: OpenAILLMContext

    AFTER::

        # Setup
        context = LLMContext(messages, tools)
        context_aggregator = LLMContextAggregatorPair(context)

        # Context frame type
        frame: LLMContextFrame

        # Context type
        context: LLMContext
    Nalwaysa  Types in pipecat.services.aws.nova_sonic.context (or pipecat.services.aws_nova_sonic.context) are deprecated. 
AWS Nova Sonic no longer uses types from this module under the hood. 
It now uses `LLMContext` and `LLMContextAggregatorPair`. 
Using the new patterns should allow you to not need types from this module.

BEFORE:
```
# Setup
context = OpenAILLMContext(messages, tools)
context_aggregator = llm.create_context_aggregator(context)

# Context frame type
frame: OpenAILLMContextFrame

# Context type
context: AWSNovaSonicLLMContext
# or
context: OpenAILLMContext

```

AFTER:
```
# Setup
context = LLMContext(messages, tools)
context_aggregator = LLMContextAggregatorPair(context)

# Context frame type
frame: LLMContextFrame

# Context type
context: LLMContext

```   )
stacklevel)	dataclassfield)Enum)logger)BotStoppedSpeakingFrame	DataFrameFrameFunctionCallResultFrameInterruptionFrameLLMFullResponseEndFrameLLMFullResponseStartFrameLLMMessagesAppendFrameLLMMessagesUpdateFrameLLMSetToolChoiceFrameLLMSetToolsFrame	TextFrameUserImageRawFrame)OpenAILLMContext)FrameDirection)#AWSNovaSonicFunctionCallResultFrame) OpenAIAssistantContextAggregatorOpenAIUserContextAggregatorc                        e Zd ZdZdZdZdZdZy)Rolea5  Roles supported in AWS Nova Sonic conversations.

    Parameters:
        SYSTEM: System-level messages (not used in conversation history).
        USER: Messages sent by the user.
        ASSISTANT: Messages sent by the assistant.
        TOOL: Messages sent by tools (not used in conversation history).
    SYSTEMUSER	ASSISTANTTOOLN)__name__
__module____qualname____doc__r   r   r    r!        Y/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/aws/nova_sonic/context.pyr   r   n   s     FDIDr'   r   c                   &    e Zd ZU dZeed<   eed<   y)&AWSNovaSonicConversationHistoryMessagezA single message in AWS Nova Sonic conversation history.

    Parameters:
        role: The role of the message sender (USER or ASSISTANT only).
        text: The text content of the message.
    roletextN)r"   r#   r$   r%   r   __annotations__strr&   r'   r(   r*   r*   ~   s     J
Ir'   r*   c                   B    e Zd ZU dZdZeed<    ee      Z	ee
   ed<   y)AWSNovaSonicConversationHistoryzComplete conversation history for AWS Nova Sonic initialization.

    Parameters:
        system_instruction: System-level instruction for the conversation.
        messages: List of conversation messages between user and assistant.
    Nsystem_instruction)default_factorymessages)r"   r#   r$   r%   r1   r.   r-   r   listr3   r*   r&   r'   r(   r0   r0      s*     #"=BSW=XHd9:Xr'   r0   c                        e Zd ZdZd fd	ZddefdZedededd fd       Z	de
fdZ fd	Zdefd
Zd ZdefdZd Zd Z xZS )AWSNovaSonicLLMContexta  Specialized LLM context for AWS Nova Sonic service.

    Extends OpenAI context with Nova Sonic-specific message handling,
    conversation history management, and text buffering capabilities.

    .. deprecated:: 0.0.99
        `AWSNovaSonicLLMContext` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    c                 J    t        |   d||d| | j                          y)zInitialize AWS Nova Sonic LLM context.

        Args:
            messages: Initial messages for the context.
            tools: Available tools for the context.
            **kwargs: Additional arguments passed to parent class.
        )r3   toolsNr&   )super__init__$_AWSNovaSonicLLMContext__setup_local)selfr3   r8   kwargs	__class__s       r(   r:   zAWSNovaSonicLLMContext.__init__   s(     	B(%B6Br'   r1   c                 .    d| _         d| _        || _        y )N )_assistant_text
_user_text_system_instruction)r<   r1   s     r(   __setup_localz$AWSNovaSonicLLMContext.__setup_local   s    !#5 r'   objreturnc                 ~    t        | t              r,t        | t              st        | _        | j	                  |       | S )a  Upgrade an OpenAI context to AWS Nova Sonic context.

        Args:
            obj: The OpenAI context to upgrade.
            system_instruction: System instruction for the context.

        Returns:
            The upgraded AWS Nova Sonic context.
        )
isinstancer   r6   r>   r;   )rE   r1   s     r(   upgrade_to_nova_sonicz,AWSNovaSonicLLMContext.upgrade_to_nova_sonic   s4     c+,ZE[5\2CM01
r'   c                 &   t        | j                        }| j                  s|S t        j                  | j                        }|d   j                  d      dk(  r|j                  d      }|j                  d      }t        |t              r||_	        n)t        |t              r|d   j                  d      |_	        |j                  r|j                  | _        |D ]1  }| j                  |      }|s|j                  j                  |       3 |S )a;  Get conversation history for initializing AWS Nova Sonic session.

        Processes stored messages and extracts system instruction and conversation
        history in the format expected by AWS Nova Sonic.

        Returns:
            Formatted conversation history with system instruction and messages.
        )r1   r   r+   systemcontentr,   )r0   rC   r3   copydeepcopygetpoprH   r.   r1   r4   from_standard_messageappend)r<   historyr3   rK   rL   messagehistory_messages          r(   %get_messages_for_initializing_historyz<AWSNovaSonicLLMContext.get_messages_for_initializing_history   s     2TE]E]^ }}N==/ A;??6"h.\\!_Fjj+G'3'-4*GT*-4QZ^^F-C*))+2+E+E(   	9G"88AO  ''8	9
 r'   c                     t         |          }| j                  r8|r|d   j                  d      dk(  s|j	                  dd| j                  d       |S )zGet messages formatted for persistent storage.

        Returns:
            List of messages including system instruction if present.
        r   r+   rK   r+   rL   )r9   #get_messages_for_persistent_storagerC   rO   insert)r<   r3   r>   s     r(   rY   z:AWSNovaSonicLLMContext.get_messages_for_persistent_storage   sP     7>@##X(1+//&:QU]:]OOAT=U=UVWr'   c                    |j                  d      }|j                  d      dk(  s|j                  d      dk(  r|j                  d      }t        |j                  d      t              rnd}|j                  d      D ]X  }|j                  d      dk(  r|d|j                  d      z   z  }/t        j                  d	|j                  d       d
|        Z |r"t        t        |j                            |      S yy)zConvert standard message format to Nova Sonic format.

        Args:
            message: Standard message dictionary to convert.

        Returns:
            Nova Sonic conversation history message, or None if not convertible.
        r+   user	assistantrL   r@   typer,    z+Unhandled content type in context message: z - )r+   r,   N)rO   rH   r4   r	   errorr*   r   upper)r<   rT   r+   rL   cs        r(   rQ   z,AWSNovaSonicLLMContext.from_standard_message   s     {{6";;v&(GKK,?;,Nkk),G'++i0$7 Y/ AuuV}.3v#66I!%%PV-X[\c[de	 =4

CU\cdd  -Or'   c                 `    | xj                   | j                   rd| z  c_         y|z  c_         y)znBuffer user text for later flushing to context.

        Args:
            text: User text to buffer.
        r_   N)rB   r<   r,   s     r(   buffer_user_textz'AWSNovaSonicLLMContext.buffer_user_text  s%     	Qtf:BdBr'   c                 z    | j                   sy| j                   }dd|dgd}d| _         | j                  |       |S )zFlush buffered user text to context as a complete message.

        Returns:
            The flushed user text, or empty string if no text was buffered.
        r@   r\   r,   r^   r,   rX   )rB   add_message)r<   	user_textrT   s      r(   flush_aggregated_user_textz1AWSNovaSonicLLMContext.flush_aggregated_user_text  sI     OO	!';<
 !r'   c                 .    | xj                   |z  c_         y)zxBuffer assistant text for later flushing to context.

        Args:
            text: Assistant text to buffer.
        N)rA   rd   s     r(   buffer_assistant_textz,AWSNovaSonicLLMContext.buffer_assistant_text1  s     	$r'   c                 t    | j                   sydd| j                   dgd}d| _         | j                  |       y)z?Flush buffered assistant text to context as a complete message.Nr]   r,   rg   rX   r@   )rA   rh   )r<   rT   s     r(   flush_aggregated_assistant_textz6AWSNovaSonicLLMContext.flush_aggregated_assistant_text:  sA    ##!'1E1EFG
  "!r'   )NN)r@   )r"   r#   r$   r%   r:   r.   r;   staticmethodr   rI   r0   rV   rY   r*   rQ   re   rj   rl   rn   __classcell__r>   s   @r(   r6   r6      s    	
6 6
 36	! $#7V #J
e0V e:CC $%	"r'   r6   c                       e Zd ZU dZeed<   y)AWSNovaSonicMessagesUpdateFramezFrame containing updated AWS Nova Sonic context.

    Parameters:
        context: The updated AWS Nova Sonic LLM context.
    contextN)r"   r#   r$   r%   r6   r-   r&   r'   r(   rs   rs   G  s     $#r'   rs   c                   D     e Zd ZdZej
                  fdedef fdZ xZS )!AWSNovaSonicUserContextAggregatora  Context aggregator for user messages in AWS Nova Sonic conversations.

    Extends the OpenAI user context aggregator to emit Nova Sonic-specific
    context update frames.

    .. deprecated:: 0.0.99
        `AWSNovaSonicUserContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    frame	directionc                    K   t         |   ||       d{    t        |t              r.| j	                  t        | j                               d{    yy7 C7 w)zProcess frames and emit Nova Sonic-specific context updates.

        Args:
            frame: The frame to process.
            direction: The direction the frame is traveling.
        N)rt   )r9   process_framerH   r   
push_framers   _contextr<   rw   rx   r>   s      r(   rz   z/AWSNovaSonicUserContextAggregator.process_frame`  sX      g#E9555 e34//"A$--"XYYY 5 	6 Zs!   AA<AAAA)	r"   r#   r$   r%   r   
DOWNSTREAMr   rz   rp   rq   s   @r(   rv   rv   R  s2    	 9G8Q8QZZ'5Z Zr'   rv   c                   <     e Zd ZdZdedef fdZdef fdZ xZ	S )&AWSNovaSonicAssistantContextAggregatora  Context aggregator for assistant messages in AWS Nova Sonic conversations.

    Provides specialized handling for assistant responses and function calls
    in AWS Nova Sonic context, with custom frame processing logic.

    .. deprecated:: 0.0.99
        `AWSNovaSonicAssistantContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    rw   rx   c                    K   t        |t        t        t        t        t
        t        t        t        t        t        f
      r| j                  ||       d{    yt        | 5  ||       d{    y7 7 w)zProcess frames with Nova Sonic-specific logic.

        Args:
            frame: The frame to process.
            direction: The direction the frame is traveling.
        N)rH   r   r   r   r   r   r   r   r   r   r
   r{   r9   rz   r}   s      r(   rz   z4AWSNovaSonicAssistantContextAggregator.process_frame~  sk      !)'&& %!'
 //%333''y999 49s$   AA:A6A:0A81A:8A:c                    K   t         |   |       d{    | j                  t        |      t        j
                         d{    y7 77 w)zHandle function call results for AWS Nova Sonic.

        Args:
            frame: The function call result frame to handle.
        N)result_frame)r9   handle_function_call_resultr{   r   r   UPSTREAM)r<   rw   r>   s     r(   r   zBAWSNovaSonicAssistantContextAggregator.handle_function_call_result  sO      g1%888
 oo/UC^E\E\
 	
 	
 	9
	
s!   AA1AA	AA)
r"   r#   r$   r%   r   r   rz   r   r   rp   rq   s   @r(   r   r   p  s-    	: :> :<
7N 
 
r'   r   c                   >    e Zd ZU dZeed<   eed<   defdZdefdZy)!AWSNovaSonicContextAggregatorPaira  Pair of user and assistant context aggregators for AWS Nova Sonic.

    .. deprecated:: 0.0.99
        `AWSNovaSonicContextAggregatorPair` 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.
    _user
_assistantrF   c                     | j                   S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )r   r<   s    r(   r\   z&AWSNovaSonicContextAggregatorPair.user  s     zzr'   c                     | j                   S )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )r   r   s    r(   r]   z+AWSNovaSonicContextAggregatorPair.assistant  s     r'   N)	r"   r#   r$   r%   rv   r-   r   r\   r]   r&   r'   r(   r   r     s/    
 -,667 A r'   r   )-r%   warningscatch_warningssimplefilterwarnDeprecationWarningrM   dataclassesr   r   enumr   logurur	   pipecat.frames.framesr
   r   r   r   r   r   r   r   r   r   r   r   r   1pipecat.processors.aggregators.openai_llm_contextr   "pipecat.processors.frame_processorr   &pipecat.services.aws.nova_sonic.framesr   pipecat.services.openai.llmr   r   r   r*   r0   r6   rs   rv   r   r   r&   r'   r(   <module>r      s5  #J X  H(#HMM	6 	; D  (      O = V4   	 	 	 	Y 	Y 	Yk"- k"^ $i $ $Z(C Z<9
-M 9
x      s   (DD