o
    i-*                     @   s   d 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
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 )z;OpenAI Realtime LLM context and aggregator implementations.    N)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.
    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   a/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/openai_realtime_beta/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_local5   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_idr7   r8   z1Unhandled message type in from_standard_message: N)getr&   listr   errorr   ConversationItemItemContent)r   r.   r*   ctcr   r   r   from_standard_messageN   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.   r/   z

   )indentr0   r1   )r   copydeepcopyr:   r   popr&   strr!   r;   lenrA   joinjsondumps)r   r   rB   r*   
intro_texttrailing_textr   r   r   %get_messages_for_initializing_historyq   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   r0   )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'   rA   rO   rS   __classcell__r   r   r   r   r   "   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 )#OpenAIRealtimeUserContextAggregatoraO  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.

    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_aggregation   s   	z4OpenAIRealtimeUserContextAggregator.push_aggregation)
rT   rU   rV   rW   r   
DOWNSTREAMr   r^   rb   rY   r   r   r   r   rZ      s    rZ   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 )(OpenAIRealtimeAssistantContextAggregatoraG  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.

    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^   ra   r   r   r   r^      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   rf     s
   zDOpenAIRealtimeAssistantContextAggregator.handle_function_call_result)
rT   rU   rV   rW   r   r   r^   r   rf   rY   r   r   r   r   rd      s    
rd   )rW   rE   rK   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   rZ   rd   r   r   r   r   <module>   s   $	 ,