
    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)zGrok Realtime LLM adapter for Pipecat.

Converts Pipecat's tool schemas and context into the format required by
Grok's Voice Agent API.
    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)GrokRealtimeLLMInvocationParamsa7  Context-based parameters for invoking Grok Realtime API.

    Attributes:
        system_instruction: System prompt/instructions for the session.
        messages: List of conversation items formatted for Grok Realtime.
        tools: List of tool definitions (function, web_search, x_search, file_search).
    system_instructionmessagestoolsN)__name__
__module____qualname____doc__r   str__annotations__r   r   ConversationItemr   r        a/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/adapters/services/grok_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)GrokRealtimeLLMAdapterzLLM adapter for Grok Voice Agent API.

    Converts Pipecat's universal context and tool schemas into the specific
    format required by Grok's Voice Agent Realtime API.
    returnc                      y)zJGet the identifier used in LLMSpecificMessage instances for Grok Realtime.zgrok-realtimer   )selfs    r   id_for_llm_specific_messagesz3GrokRealtimeLLMAdapter.id_for_llm_specific_messages0   s     r   contextc                     | j                  | j                  |            }|j                  |j                  | j	                  |j
                        xs g dS )a  Get Grok Realtime-specific LLM invocation parameters from a universal LLM context.

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

        Returns:
            Dictionary of parameters for invoking Grok's Voice Agent API.
        )r   r   r   ) _from_universal_context_messagesget_messagesr   r   from_standard_toolsr   )r$   r&   r   s      r   get_llm_invocation_paramsz0GrokRealtimeLLMAdapter.get_llm_invocation_params5   sR     889J9J79ST"*"="= ))--gmm<B
 	
r   c                 *   g }| j                  |      D ]|  }t        j                  |      }d|v rPt        |d   t              r=|d   D ]5  }|j                  d      dk(  rd|d<   |j                  d      dk(  s1d|d<   7 |j                  |       ~ |S )a  Get messages from context in a format safe for logging.

        Removes or truncates sensitive data like audio content.

        Args:
            context: The LLM context containing messages.

        Returns:
            List of messages with sensitive data redacted.
        contenttypeinput_audioz...audio)r)   copydeepcopy
isinstancelistgetappend)r$   r&   msgsmessagemsgitems         r   get_messages_for_loggingz/GrokRealtimeLLMAdapter.get_messages_for_loggingE   s     ((1 		G--(CCc)nd3 #I 288F+}<,1DM88F+w6,1DM	2
 KK		 r   c                   J    e Zd ZU dZeej                     ed<   dZe	e
   ed<   y)(GrokRealtimeLLMAdapter.ConvertedMessageszGContainer for Grok-formatted messages converted from universal context.r   Nr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   ConvertedMessagesr=   ]   s%    Uv..//,0HSM0r   r>   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                  t        j                  d
dt        j                  ddj                  |t        j                  |d      |g            g      g|      S )a  Convert universal context messages to Grok Realtime format.

        Similar to OpenAI Realtime, we pack conversation history into a single
        user message since the realtime API doesn't support loading long histories.

        Args:
            universal_context_messages: List of messages in universal format.

        Returns:
            ConvertedMessages with Grok-formatted messages and system instruction.
        )r   Nr   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, simply say that you
        are ready to continue the conversation.r8   
input_textz

   )indentr.   rC   rA   r.   r-   )r>   r1   r2   r5   popr3   r   r4   len_from_universal_context_messager   r   ItemContentjoinjsondumps)r$   r?   r   r   rB   r-   
intro_texttrailing_texts           r   r(   z7GrokRealtimeLLMAdapter._from_universal_context_messagesd   s|    *))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 %%''"**!-!'$.$(JJx$B$1!""	$  2' & 
 	
r   r8   c                    |j                  d      dk(  r|j                  d      }t        |t              rod}|D ]X  }|j                  d      dk(  r|d|j                  d      z   z  }/t        j                  d|j                  d       d	|        Z |j                         }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 single universal context message to Grok format.

        Args:
            message: Message in universal format.

        Returns:
            ConversationItem formatted for Grok Realtime API.
        rA   rE   r-    r.   rC    z+Unhandled content type in context message: z - r8   rF   rI   rJ   	assistant
tool_callsr   function_callidfunctionname	arguments)r.   call_idr\   r]   z;Unhandled message type in _from_universal_context_message: N)	r5   r3   r4   r	   errorstripr   r   rN   )r$   r8   r-   text_contentctcs         r   rM   z6GrokRealtimeLLMAdapter._from_universal_context_message   sJ    ;;v&(kk),G'4(!  AuuV}.$aeeFm(;;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 Grok Realtime function format.

        Args:
            function: The function schema to convert.

        Returns:
            Dictionary in Grok Realtime function format.
        r[   object)r.   
propertiesrequired)r.   r\   description
parameters)r\   rh   rf   rg   )r[   s    r   _to_grok_function_formatz/GrokRealtimeLLMAdapter._to_grok_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 )aU  Convert tool schemas to Grok Realtime format.

        Supports both standard function tools and Grok-specific tools
        (web_search, x_search, file_search).

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

        Returns:
            List of tool definitions in Grok Realtime format.
        )standard_toolsrj   custom_toolsr5   r   SHIM)r$   rk   functions_schemafuncrm   shimmed_toolss         r   to_provider_tools_formatz/GrokRealtimeLLMAdapter.to_provider_tools_format   sm     (66JZ[$$77=[[ $$(5599+:J:JBOM-- \s   A(N)r   r   r   r   propertyr   r%   r   r   r+   r   r   r   r;   r   r>   r   r(   r   r   rM   staticmethodr   rj   r   rs   r   r   r   r!   r!   )   s     c  
 
@_ 
 4S#X3G 0 1 1 1E
*./@*AE
	E
N&^(&^		 	 &^P 
> 
d38n 
 
(.[ .T$sTWx.EY .r   r!   )r   r1   rP   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.grok.realtimer   r   r!   r   r   r   <module>r~      sG      ! 7 7  < C J T 1 i  T.^ T.r   