
    qi@7                     j   d Z ddlZ ej                         5   ej                  d        ej                  d       ddd       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# 1 sw Y   mxY w)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                   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.

    .. 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.
    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       Z/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/openai/realtime/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_local   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r2   r3   r/   r2   r1   	assistant
tool_callsr   function_callidfunctionname	arguments)r2   call_idr>   r?   z1Unhandled message type in from_standard_message: N)getr,   listr   errorr   ConversationItemItemContent)r   r5   r1   ctcs        r    from_standard_messagez.OpenAIRealtimeLLMContext.from_standard_message   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/   systemTr1   r3   r   r0   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.r5   r6   z

   )indentr7   r8   )r   copydeepcopyrA   r$   popr,   strr&   rB   lenrH   joinjsondumps)r   r   rJ   r1   
intro_texttrailing_texts         r    %get_messages_for_initializing_historyz>OpenAIRealtimeLLMContext.get_messages_for_initializing_history   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.
        r0   r3   r   r7   )r/   r1   N)r1   
transcriptadd_message)r   itemr5   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-   rH   rW   r\   __classcell__r   s   @r    r   r   n   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 )#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                   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   rf   rg   r   s      r    rj   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_aggregation5  s      	s   )
r]   r^   r_   r`   r   
DOWNSTREAMr   rj   ro   rb   rc   s   @r    re   re     s.    $ 9G8Q8Q44'54*	r!   re   c                   <     e Zd ZdZdedef fdZdef fdZ x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.
    rf   rg   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   rj   rm   s      r    rj   z6OpenAIRealtimeAssistantContextAggregator.process_frameY  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_resultrk   r   r   UPSTREAM)r   rf   r   s     r    rv   zDOpenAIRealtimeAssistantContextAggregator.handle_function_call_resultc  sO      g1%888
 oo+?AXAX
 	
 	
 	9
	
s!   AA1AA	AA)
r]   r^   r_   r`   r   r   rj   r   rv   rb   rc   s   @r    rr   rr   A  s-    .: :> :
7N 
 
r!   rr   ) r`   warningscatch_warningssimplefilterwarnrM   rS   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   re   rr   r   r!   r    <module>r      s   &P X "H(#HMM	 "H      O =
  P]"/ ]"@0*E 0f/
/O /
a" "s   %B))B2