
    qi-*                         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e      Z G d de      Z G d de      Zy)z;OpenAI Realtime LLM context and aggregator implementations.    N)logger)FrameFunctionCallResultFrameInterimTranscriptionFrameLLMMessagesUpdateFrameLLMSetToolsFrameLLMTextFrameTranscriptionFrame)OpenAILLMContext)FrameDirection) OpenAIAssistantContextAggregatorOpenAIUserContextAggregator   )events)RealtimeFunctionCallResultFrameRealtimeMessagesUpdateFramec                   V     e Zd ZdZd
 fd	Zd Zededd fd       Zd Z	d Z
d	 Z x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.
    c                 J    t        |   d||d| | j                          y)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__s       _/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/openai_realtime_beta/context.pyr   z!OpenAIRealtimeLLMContext.__init__*   s(     	B(%B6B    c                 .    d| _         d| _        d| _        y )NT )llm_needs_settings_updatellm_needs_initial_messages_session_instructionsr   s    r   __setup_localz&OpenAIRealtimeLLMContext.__setup_local5   s    )-&*.'%'"r    objreturnc                 |    t        | t              r+t        | t              st        | _        | j	                          | 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(   s    r   upgrade_to_realtimez,OpenAIRealtimeLLMContext.upgrade_to_realtime<   s1     c+,ZE]5^4CM
r    c                    |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 t        j                  dd
t        j                  d|      g      S |j                  d      dk(  rM|j                  d      r<|j                  d      d   }t        j                  d|d   |d   d   |d   d         S t        j                  d|        y)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r1   r2   r.   r1   r0   	assistant
tool_callsr   function_callidfunctionname	arguments)r1   call_idr=   r>   z1Unhandled message type in from_standard_message: N)getr+   listr   errorr   ConversationItemItemContent)r   r4   r0   ctcs        r   from_standard_messagez.OpenAIRealtimeLLMContext.from_standard_messageN   sL    ;;v&(kk),G'++i0$7 Y/ AuuV}.3v#66I!%%PV-X[\c[de	 **++GLM 
 ;;v+-'++l2K\*1-B**$4
^F+Z.5	  	H	RSr    c           
      F   | j                   sg S t        j                  | j                         }|d   j                  d      dk(  rnd| _        |j                  d      }|j                  d      }t        |t              r|| _        n)t        |t              r|d   j                  d      | _        |sg S t        |      dk(  r,|d   j                  d      dk(  r| j                  |d         gS d	}d
}ddddj                  |t        j                  |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.   systemTr0   r2   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.r4   r5   z

   )indentr6   r7   )r   copydeepcopyr@   r#   popr+   strr%   rA   lenrG   joinjsondumps)r   r   rI   r0   
intro_texttrailing_texts         r   %get_messages_for_initializing_historyz>OpenAIRealtimeLLMContext.get_messages_for_initializing_historyq   s$    }}I==/ A;??6"h.-1D*\\!_Fjj+G'3'-4*GT*-4QZ^^F-C*	 x=A(1+//&"9V"C..x{;<<8
3 ! !- &'HQ)GW!
 	
r    c                 f    dd|j                   d   j                  dgd}| j                  |       y)zAdd a user content item as a standard message to the context.

        Args:
            item: The conversation item to add as a user message.
        r/   r2   r   r6   )r.   r0   N)r0   
transcriptadd_message)r   itemr4   s      r    add_user_content_item_as_messagez9OpenAIRealtimeLLMContext.add_user_content_item_as_message   s7     !'a1K1KLM
 	!r    )NN)__name__
__module____qualname____doc__r   r   staticmethodr   r,   rG   rV   r[   __classcell__r   s   @r   r   r   "   sH    	 !1 6P  "!TF<
|
"r    r   c                   J     e Zd ZdZej
                  fdedef fdZd Z x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                   K   t         |   ||       d{    t        |t              r-| j	                  t        | j                               d{    t        |t              r| j	                  ||       d{    yy7 m7 27 
w)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   re   rf   r   s      r   ri   z1OpenAIRealtimeUserContextAggregator.process_frame   s      g#E9555
 e34//"=dmm"TUUU e-.//%333 / 	6 V 4s3   BB<BB)B>B	?BB	Bc                    K   yw)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&   s    r   push_aggregationz4OpenAIRealtimeUserContextAggregator.push_aggregation   s      	s   )
r\   r]   r^   r_   r   
DOWNSTREAMr   ri   rn   ra   rb   s   @r   rd   rd      s.     9G8Q8Q44'54*	r    rd   c                   <     e Zd ZdZdedef fdZdef fdZ x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.
    re   rf   c                 z   K   t        |t        t        t        f      st        |   ||       d{    yy7 w)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   ri   rl   s      r   ri   z6OpenAIRealtimeAssistantContextAggregator.process_frame   s:      %,0BD]!^_''y999 `9s   /;9;c                    K   t         |   |       d{    | j                  t        |      t        j
                         d{    y7 77 w)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_resultrj   r   r   UPSTREAM)r   re   r   s     r   ru   zDOpenAIRealtimeAssistantContextAggregator.handle_function_call_result  sO      g1%888
 oo+?AXAX
 	
 	
 	9
	
s!   AA1AA	AA)
r\   r]   r^   r_   r   r   ri   r   ru   ra   rb   s   @r   rq   rq      s-     : :> :
7N 
 
r    rq   )r_   rL   rR   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   rd   rq   r   r    r   <module>r}      sd    B      O =
  PW"/ W"t)*E )X(
/O (
r    