o
    i@7                     @   s   d Z ddlZe  ed ed W d   n1 sw   Y  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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 d
dlmZmZ G dd deZG dd deZG dd deZdS )a)  OpenAI Realtime LLM context and aggregator implementations.

.. deprecated:: 0.0.92
    OpenAI Realtime 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 aggregator type
        context_aggregator: OpenAIContextAggregatorPair

        # Context frame type
        frame: OpenAILLMContextFrame

        # Context type
        context: OpenAIRealtimeLLMContext
        # or
        context: OpenAILLMContext

    AFTER::

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

        # Context aggregator type
        context_aggregator: LLMContextAggregatorPair

        # Context frame type
        frame: LLMContextFrame

        # Context type
        context: LLMContext
    Nalwaysa  Types in pipecat.services.openai.realtime.llm (or pipecat.services.openai_realtime.llm) are deprecated. 
OpenAI Realtime 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 aggregator type
context_aggregator: OpenAIContextAggregatorPair

# Context frame type
frame: OpenAILLMContextFrame

# Context type
context: OpenAIRealtimeLLMContext
# or
context: OpenAILLMContext

```

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

# Context aggregator type
context_aggregator: LLMContextAggregatorPair

# Context frame type
frame: LLMContextFrame

# Context type
context: LLMContext

```
)logger)FrameFunctionCallResultFrameInterimTranscriptionFrameLLMMessagesUpdateFrameLLMSetToolsFrameLLMTextFrameTranscriptionFrame)OpenAILLMContext)FrameDirection) OpenAIAssistantContextAggregatorOpenAIUserContextAggregator   )events)RealtimeFunctionCallResultFrameRealtimeMessagesUpdateFramec                       sX   e Zd ZdZd fdd	Zdd Zededd fd	d
Zdd Z	dd Z
dd Z  ZS )OpenAIRealtimeLLMContexta  OpenAI Realtime LLM context with session management and message conversion.

    Extends the standard OpenAI LLM context to support real-time session properties,
    instruction management, and conversion between standard message formats and
    realtime conversation items.

    .. deprecated:: 0.0.99
        `OpenAIRealtimeLLMContext` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    Nc                    s$   t  jd||d| |   dS )a  Initialize the OpenAIRealtimeLLMContext.

        Args:
            messages: Initial conversation messages. Defaults to None.
            tools: Available function tools. Defaults to None.
            **kwargs: Additional arguments passed to parent OpenAILLMContext.
        )messagestoolsN )super__init__&_OpenAIRealtimeLLMContext__setup_local)selfr   r   kwargs	__class__r   \/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/openai/realtime/context.pyr   {   s   	z!OpenAIRealtimeLLMContext.__init__c                 C   s   d| _ d| _d| _d S )NT )llm_needs_settings_updatellm_needs_initial_messages_session_instructionsr   r   r   r   __setup_local   s   z&OpenAIRealtimeLLMContext.__setup_localobjreturnc                 C   s&   t | trt | tst| _|   | S )zUpgrade a standard OpenAI LLM context to a realtime context.

        Args:
            obj: The OpenAILLMContext instance to upgrade.

        Returns:
            The upgraded OpenAIRealtimeLLMContext instance.
        )
isinstancer   r   r   r   )r%   r   r   r   upgrade_to_realtime   s   
z,OpenAIRealtimeLLMContext.upgrade_to_realtimec                 C   s   | ddkrK| d}t| dtr=d}| dD ]!}| ddkr.|d| d 7 }qtd| d d	|  qtjdd
tjd|dgdS | ddkrq| drq| dd }tjd|d |d d |d d dS td|  dS )zConvert a standard message format to a realtime conversation item.

        Args:
            message: The standard message dictionary to convert.

        Returns:
            A ConversationItem instance for the realtime API.
        roleusercontentr   typetext z+Unhandled content type in context message: z - message
input_textr,   r-   r)   r,   r+   	assistant
tool_callsr   function_callidfunctionname	arguments)r,   call_idr8   r9   z1Unhandled message type in from_standard_message: N)getr'   listr   errorr   ConversationItemItemContent)r   r/   r+   ctcr   r   r   from_standard_message   s0   	


z.OpenAIRealtimeLLMContext.from_standard_messagec              
   C   s   | j sg S t| j }|d ddkr;d| _|d}|d}t|tr*|| _nt|t	r7|d d| _|s;g S t
|dkrR|d ddkrR| |d gS d	}d
}dddd|tj|dd|gdgdgS )a@  Get conversation items for initializing the realtime session history.

        Converts the context's messages to a format suitable for the realtime API,
        handling system instructions and conversation history packaging.

        Returns:
            List of conversation items for session initialization.
        r   r)   systemTr+   r-   r   r*   z
        This is a previously saved conversation. Please treat this conversation history as a
        starting point for the current conversation.aS  
        This is the end of the previously saved conversation. Please continue the conversation
        from here. If the last message is a user instruction or question, act on that instruction
        or answer the question. If the last message is an assistant response, simple say that you
        are ready to continue the conversation.r/   r0   z

   )indentr1   r2   )r   copydeepcopyr;   r    popr'   strr"   r<   lenrB   joinjsondumps)r   r   rC   r+   
intro_texttrailing_textr   r   r   %get_messages_for_initializing_history   s6   



z>OpenAIRealtimeLLMContext.get_messages_for_initializing_historyc                 C   s(   dd|j d jdgd}| | dS )zAdd a user content item as a standard message to the context.

        Args:
            item: The conversation item to add as a user message.
        r*   r-   r   r1   )r)   r+   N)r+   
transcriptadd_message)r   itemr/   r   r   r    add_user_content_item_as_message  s   z9OpenAIRealtimeLLMContext.add_user_content_item_as_message)NN)__name__
__module____qualname____doc__r   r   staticmethodr   r(   rB   rP   rT   __classcell__r   r   r   r   r   n   s    #>r   c                       s8   e Zd ZdZejfdedef fddZdd Z  Z	S )#OpenAIRealtimeUserContextAggregatora]  User context aggregator for OpenAI Realtime API.

    Handles user input frames and generates appropriate context updates
    for the realtime conversation, including message updates and tool settings.

    .. deprecated:: 0.0.99
        `OpenAIRealtimeUserContextAggregator` 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 OpenAI realtime LLM context.
        **kwargs: Additional arguments passed to parent aggregator.
    frame	directionc                    s\   t  ||I dH  t|tr| t| jdI dH  t|tr,| ||I dH  dS dS )zProcess incoming frames and handle realtime-specific frame types.

        Args:
            frame: The frame to process.
            direction: The direction of frame flow in the pipeline.
        N)context)r   process_framer'   r   
push_framer   _contextr   r   r\   r]   r   r   r   r_      s   	

z1OpenAIRealtimeUserContextAggregator.process_framec                    s   dS )zPush user input aggregation.

        Currently ignores all user input coming into the pipeline as realtime
        audio input is handled directly by the service.
        Nr   r#   r   r   r   push_aggregation5  s   	z4OpenAIRealtimeUserContextAggregator.push_aggregation)
rU   rV   rW   rX   r   
DOWNSTREAMr   r_   rc   rZ   r   r   r   r   r[     s    r[   c                       s<   e Zd ZdZdedef fddZdef fddZ  Z	S )(OpenAIRealtimeAssistantContextAggregatoraZ  Assistant context aggregator for OpenAI Realtime API.

    Handles assistant output frames from the realtime service, filtering
    out duplicate text frames and managing function call results.

    .. deprecated:: 0.0.99
        `OpenAIRealtimeAssistantContextAggregator` 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 OpenAI realtime LLM context.
        **kwargs: Additional arguments passed to parent aggregator.
    r\   r]   c                    s.   t |tttfst ||I dH  dS dS )zProcess assistant frames, filtering out duplicate text content.

        Args:
            frame: The frame to process.
            direction: The direction of frame flow in the pipeline.
        N)r'   r	   r
   r   r   r_   rb   r   r   r   r_   Y  s   z6OpenAIRealtimeAssistantContextAggregator.process_framec                    s2   t  |I dH  | t|dtjI dH  dS )zHandle function call result and notify the realtime service.

        Args:
            frame: The function call result frame to handle.
        N)result_frame)r   handle_function_call_resultr`   r   r   UPSTREAM)r   r\   r   r   r   rg   c  s
   zDOpenAIRealtimeAssistantContextAggregator.handle_function_call_result)
rU   rV   rW   rX   r   r   r_   r   rg   rZ   r   r   r   r   re   A  s    
re   ) rX   warningscatch_warningssimplefilterwarnrF   rL   logurur   pipecat.frames.framesr   r   r   r   r   r	   r
   1pipecat.processors.aggregators.openai_llm_contextr   "pipecat.processors.frame_processorr   pipecat.services.openai.llmr   r   r   r   framesr   r   r   r[   re   r   r   r   r   <module>   s*   (

$$	 !3