
    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
 ddlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZmZ dd
lmZ  G d de
      Z G d de      Zy)z(OpenAI Realtime LLM adapter for Pipecat.    N)	dataclass)AnyDictListOptional	TypedDict)logger)BaseLLMAdapter)FunctionSchema)AdapterTypeToolsSchema)
LLMContextLLMContextMessage)eventsc                   `    e Zd ZU dZee   ed<   eej                     ed<   ee
eef      ed<   y)!OpenAIRealtimeLLMInvocationParamszContext-based parameters for invoking OpenAI Realtime API.

    This is a placeholder until support for universal LLMContext machinery is added for OpenAI Realtime.
    system_instructionmessagestoolsN)__name__
__module____qualname____doc__r   str__annotations__r   r   ConversationItemr   r        d/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/adapters/services/open_ai_realtime_adapter.pyr   r      s7    
 !%6**++S#Xr   r   c                       e Zd ZdZedefd       ZdedefdZ	de
eeef      fdZe G d d             Zd	e
e   defd
Zdedej&                  fdZededeeef   fd       Zdede
eeef      fdZy)OpenAIRealtimeLLMAdapterzLLM adapter for OpenAI Realtime API function calling.

    Converts Pipecat's tool schemas into the specific format required by
    OpenAI's Realtime API for function calling capabilities.
    returnc                      y)zLGet the identifier used in LLMSpecificMessage instances for OpenAI Realtime.zopenai-realtimer   )selfs    r   id_for_llm_specific_messagesz5OpenAIRealtimeLLMAdapter.id_for_llm_specific_messages)   s     !r   contextc                     | j                  | j                  |            }|j                  |j                  | j	                  |j
                        xs g dS )a{  Get OpenAI Realtime-specific LLM invocation parameters from a universal LLM context.

        This is a placeholder until support for universal LLMContext machinery is added for OpenAI Realtime.

        Args:
            context: The LLM context containing messages, tools, etc.

        Returns:
            Dictionary of parameters for invoking OpenAI Realtime's API.
        )r   r   r   ) _from_universal_context_messagesget_messagesr   r   from_standard_toolsr   )r$   r&   r   s      r   get_llm_invocation_paramsz2OpenAIRealtimeLLMAdapter.get_llm_invocation_params.   sR     889J9J79ST"*"="= ))--gmm<B	
 	
r   c                 n   g }| j                  |      D ]  }t        j                  |      }d|v rUt        |d   t              rB|d   D ]:  }|d   dk(  r|d   d   j                  d      rd|d   d<   |d   dk(  s3d|d   d	<   < d
|v r|d
   j                  d      rd|d	<   |j                  |        |S )a  Get messages from a universal LLM context in a format ready for logging about OpenAI Realtime.

        Removes or truncates sensitive data like image content for safe logging.

        This is a placeholder until support for universal LLMContext machinery is added for OpenAI Realtime.

        Args:
            context: The LLM context containing messages.

        Returns:
            List of messages in a format ready for logging about OpenAI Realtime.
        contenttype	image_urlurlzdata:image/zdata:image/...input_audioz...data	mime_typezimage/)r)   copydeepcopy
isinstancelist
startswithappend)r$   r&   msgsmessagemsgitems         r   get_messages_for_loggingz1OpenAIRealtimeLLMAdapter.get_messages_for_loggingA   s    " ((1 	G--(CCc)nd3 #I @<;6#K07BB=Q;K[ 1% 8<=8:?D/7@ c!c+&6&A&A(&K#FKK	 r   c                   J    e Zd ZU dZeej                     ed<   dZe	e
   ed<   y)*OpenAIRealtimeLLMAdapter.ConvertedMessageszIContainer for OpenAI-formatted messages converted from universal context.r   Nr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   ConvertedMessagesr@   b   s%    Wv..//,0HSM0r   rA   universal_context_messagesc                    |s| j                  g       S t        j                  |      }d }|d   j                  d      dk(  rn|j	                  d      }|j                  d      }t        |t              r|}n$t        |t              r|d   j                  d      }|s| j                  g |      S t        |      dk(  r=|d   j                  d      d	k(  r&| j                  | j                  |d         g|      S d
}d}| j                  d	dddj                  |t        j                  |d      |g      dgdg|      S )N)r   r   rolesystemr-   text)r   r      userz
        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;   
input_textz

   )indentr.   rF   rD   r.   r-   )rA   r4   r5   getpopr6   r   r7   len_from_universal_context_messagejoinjsondumps)r$   rB   r   r   rE   r-   
intro_texttrailing_texts           r   r(   z9OpenAIRealtimeLLMAdapter._from_universal_context_messagesi   sj    *))2)66==!;<! A;??6"h.\\!_Fjj+G'3'%,"GT*%,QZ^^F%;"--rN`-aa x=A(1+//&"9V"C))>>x{KL#5 *  8
3 %% #% %1$*KK!+TZZ-K] [%   2 & 
 	
r   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 )NrD   rH   r-    r.   rF    z+Unhandled content type in context message: z - r;   rI   rL   rM   	assistant
tool_callsr   function_callidfunctionname	arguments)r.   call_idr_   r`   z;Unhandled message type in _from_universal_context_message: )rN   r6   r7   r	   errorr   r   ItemContent)r$   r;   r-   ctcs        r   rQ   z8OpenAIRealtimeLLMAdapter._from_universal_context_message   sN    ;;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	  	RSZR[\]r   r^   c                 h    d| j                   | j                  d| j                  | j                  ddS )zConvert a function schema to OpenAI Realtime format.

        Args:
            function: The function schema to convert.

        Returns:
            Dictionary in OpenAI Realtime function format.
        r^   object)r.   
propertiesrequired)r.   r_   description
parameters)r_   rj   rh   ri   )r^   s    r   #_to_openai_realtime_function_formatz<OpenAIRealtimeLLMAdapter._to_openai_realtime_function_format   s;     MM#// &11$--		
 		
r   tools_schemac                     |j                   }|D cg c]  }| j                  |       }}g }|j                  r*|j                  j                  t        j
                  g       }||z   S c c}w )zConvert tool schemas to OpenAI Realtime function-calling format.

        Args:
            tools_schema: The tools schema containing functions to convert.

        Returns:
            List of function definitions in OpenAI Realtime format.
        )standard_toolsrl   custom_toolsrN   r   SHIM)r$   rm   functions_schemafuncro   shimmed_toolss         r   to_provider_tools_formatz1OpenAIRealtimeLLMAdapter.to_provider_tools_format   ss     (66GW
?CD44T:
 
 $$(5599+:J:JBOM--
s   A(N)r   r   r   r   propertyr   r%   r   r   r+   r   r   r   r>   r   rA   r   r(   r   r   rQ   staticmethodr   rl   r   ru   r   r   r   r!   r!   "   s     !c ! !
 
@a 
&4S#X3G B 1 1 1=
*./@*A=
	=
~^(^		 	 ^: 
n 
cSVh 
 
(.[ .T$sTWx.EY .r   r!   )r   r4   rS   dataclassesr   typingr   r   r   r   r   logurur	   !pipecat.adapters.base_llm_adapterr
   (pipecat.adapters.schemas.function_schemar   %pipecat.adapters.schemas.tools_schemar   r   *pipecat.processors.aggregators.llm_contextr   r    pipecat.services.openai.realtimer   r   r!   r   r   r   <module>r      sE    /   ! 7 7  < C J T 3 	  P.~ P.r   