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
 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 de
ZG dd deZdS )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                   @   s@   e Zd ZU dZee ed< eej	 ed< ee
eef  ed< dS )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    r   r   c/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/adapters/services/grok_realtime_adapter.pyr      s
   
 r   c                   @   s   e Zd ZdZedefddZdedefddZ	de
eeef  fdd	ZeG d
d dZde
e defddZdedejfddZededeeef fddZdede
eeef  fddZdS )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                 C   s   dS )zJGet the identifier used in LLMSpecificMessage instances for Grok Realtime.zgrok-realtimer   selfr   r   r   id_for_llm_specific_messages0   s   z3GrokRealtimeLLMAdapter.id_for_llm_specific_messagescontextc                 C   s,   |  | |}|j|j| |jp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   r   r   r   get_llm_invocation_params5   s
   	z0GrokRealtimeLLMAdapter.get_llm_invocation_paramsc                 C   s|   g }|  |D ]4}t|}d|v r6t|d tr6|d D ]}|ddkr*d|d< |ddkr5d|d< q|| q|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itemr   r   r   get_messages_for_loggingE   s   
z/GrokRealtimeLLMAdapter.get_messages_for_loggingc                   @   s0   e Zd ZU dZeej ed< dZe	e
 ed< dS )z(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   r   ConvertedMessages]   s   
 r6   universal_context_messagesc                 C   s   |s| j g dS t|}d}|d ddkr?|d}|d}t|tr*|}nt|tr6|d d}|s?| j g |dS t|d	kr[|d dd
kr[| j | 	|d g|dS d}d}| j t
jd
dt
jdd|tj|dd|gdgdg|d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.r2   
input_textz

   )indentr(   r:   r8   r(   r'   )r6   r+   r,   r/   popr-   r   r.   len_from_universal_context_messager   r   ItemContentjoinjsondumps)r    r7   r   r   r9   r'   
intro_texttrailing_textr   r   r   r#   d   sL   




z7GrokRealtimeLLMAdapter._from_universal_context_messagesr2   c                 C   s   | ddkrI| d}t|tr;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ro| dro| dd }tjd|d |d d |d d dS td|  dS )zConvert a single universal context message to Grok format.

        Args:
            message: Message in universal format.

        Returns:
            ConversationItem formatted for Grok Realtime API.
        r8   r<   r'    r(   r:    z+Unhandled content type in context message: z - r2   r=   r@   rA   	assistant
tool_callsr   function_callidfunctionname	arguments)r(   call_idrR   rS   z;Unhandled message type in _from_universal_context_message: N)	r/   r-   r.   r   errorstripr   r   rE   )r    r2   r'   text_contentctcr   r   r   rD      s2   



z6GrokRealtimeLLMAdapter._from_universal_context_messagerQ   c                 C   s   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.
        rQ   object)r(   
propertiesrequired)r(   rR   description
parameters)rR   r]   r[   r\   )rQ   r   r   r   _to_grok_function_format   s   z/GrokRealtimeLLMAdapter._to_grok_function_formattools_schemac                    s:   |j } fdd|D }g }|jr|jtjg }|| S )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.
        c                    s   g | ]}  |qS r   )r_   ).0funcr   r   r   
<listcomp>   s    zCGrokRealtimeLLMAdapter.to_provider_tools_format.<locals>.<listcomp>)standard_toolscustom_toolsr/   r   SHIM)r    r`   functions_schemard   shimmed_toolsr   r   r   to_provider_tools_format   s   z/GrokRealtimeLLMAdapter.to_provider_tools_formatN)r   r   r   r   propertyr   r!   r   r   r&   r   r   r   r5   r   r6   r   r#   r   r   rD   staticmethodr
   r_   r   ri   r   r   r   r   r   )   s*    
G
("r   )r   r+   rG   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   r   <module>   s   