
    qi[&                         d Z ddlmZ ddl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 dd	lmZ dd
lmZmZmZ ddlmZ e G d d             Ze G d de             Z G d de      Zy)zGrok LLM service implementation using OpenAI-compatible interface.

This module provides a service for interacting with Grok's API through an
OpenAI-compatible interface, including specialized token usage tracking
and context aggregation functionality.
    )	dataclass)Optional)logger)LLMTokenUsage)
LLMContext)LLMAssistantAggregatorParamsLLMUserAggregatorParams)OpenAILLMContext)OpenAILLMSettings) OpenAIAssistantContextAggregatorOpenAILLMServiceOpenAIUserContextAggregator)_warn_deprecated_paramc                   >    e Zd ZU dZeed<   eed<   defdZdefdZy)GrokContextAggregatorPairaT  Pair of context aggregators for user and assistant interactions.

    Provides a convenient container for managing both user and assistant
    context aggregators together for Grok LLM interactions.

    .. deprecated:: 0.0.99
        `GrokContextAggregatorPair` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.

    Parameters:
        _user: The user context aggregator instance.
        _assistant: The assistant context aggregator instance.
    _user
_assistantreturnc                     | j                   S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )r   selfs    K/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/grok/llm.pyuserzGrokContextAggregatorPair.user8   s     zz    c                     | j                   S )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )r   r   s    r   	assistantz#GrokContextAggregatorPair.assistant@   s     r   N)	__name__
__module____qualname____doc__r   __annotations__r   r   r    r   r   r   r   #   s/      '&001 ; r   r   c                       e Zd ZdZy)GrokLLMSettingszSettings for GrokLLMService.N)r   r   r   r    r"   r   r   r$   r$   I   s    &r   r$   c            
            e Zd ZU dZeZeed<   dddddededee   d	ee   f fd
Z	d fd	Z
deez  f fdZdefdZ e        e       ddedededefdZ xZS )GrokLLMServiceam  A service for interacting with Grok's API using the OpenAI-compatible interface.

    This service extends OpenAILLMService to connect to Grok's API endpoint while
    maintaining full compatibility with OpenAI's interface and functionality.
    Includes specialized token usage tracking that accumulates metrics during
    processing and reports final totals.
    	_settingszhttps://api.x.ai/v1N)base_urlmodelsettingsapi_keyr(   r)   r*   c                    t        d      }|t        dt         d       ||_        ||j                  |       t	        |   d|||d| d| _        d| _        d| _        d| _	        d| _
        y)	a  Initialize the GrokLLMService with API key and model.

        Args:
            api_key: The API key for accessing Grok's API.
            base_url: The base URL for Grok API. Defaults to "https://api.x.ai/v1".
            model: The model identifier to use. Defaults to "grok-3-beta".

                .. deprecated:: 0.0.105
                    Use ``settings=OpenAILLMSettings(model=...)`` instead.

            settings: Runtime-updatable settings. When provided alongside deprecated
                parameters, ``settings`` values take precedence.
            **kwargs: Additional keyword arguments passed to OpenAILLMService.
        zgrok-3-beta)r)   Nr)   )r+   r(   r*   r   Fr"   )r$   r   r)   apply_updatesuper__init___prompt_tokens_completion_tokens_total_tokens_has_reported_prompt_tokens_is_processing)r   r+   r(   r)   r*   kwargsdefault_settings	__class__s          r   r/   zGrokLLMService.__init__\   s    0 +? "7OWE%*"
 ))(3a8FVaZ`a"#+0(#r   c                 V    t        j                  d|        t        |   ||fi |S )as  Create OpenAI-compatible client for Grok API endpoint.

        Args:
            api_key: The API key to use. If None, uses instance default.
            base_url: The base URL to use. If None, uses instance default.
            **kwargs: Additional arguments passed to client creation.

        Returns:
            The configured client instance for Grok API.
        zCreating Grok client with api )r   debugr.   create_client)r   r+   r(   r5   r7   s       r   r:   zGrokLLMService.create_client   s0     	5hZ@Aw$WhA&AAr   contextc           	      (  K   d| _         d| _        d| _        d| _        d| _        d| _        d| _        	 t        | !  |       d{    d| _        | j                   dkD  s| j                  dkD  rx| j                   | j                  z   | _        t        | j                   | j                  | j                  | j                  | j                        }t        | )  |       d{    yy7 7 # d| _        | j                   dkD  s| j                  dkD  ry| j                   | j                  z   | _        t        | j                   | j                  | j                  | j                  | j                        }t        | )  |       d{  7   w w xY ww)a  Process a context through the LLM and accumulate token usage metrics.

        This method overrides the parent class implementation to handle Grok's
        incremental token reporting style, accumulating the counts and reporting
        them once at the end of processing.

        Args:
            context: The context to process, containing messages and other
                information needed for the LLM interaction.
        r   NFT)prompt_tokenscompletion_tokenstotal_tokenscache_read_input_tokensreasoning_tokens)r0   r1   r2   _cache_read_input_tokens_reasoning_tokensr3   r4   r.   _process_contextr   start_llm_usage_metrics)r   r;   tokensr7   s      r   rD   zGrokLLMService._process_context   s      "#(,%!%+0("	>'*7333"'D""Q&$*A*AA*E%)%8%84;R;R%R"&"&"5"5&*&=&=!%!3!3,0,I,I%)%;%; g5f=== +F	 4 > #(D""Q&$*A*AA*E%)%8%84;R;R%R"&"&"5"5&*&=&=!%!3!3,0,I,I%)%;%; g5f=== +FsN   2FC/ C+	C/ BF$C-%F+C/ -F/BFF
FFrF   c                 V  K   | j                   sy| j                  s'|j                  dkD  r|j                  | _        d| _        |j                  | j
                  kD  r|j                  | _        |j                  |j                  | _        |j                  |j                  | _	        yyw)a  Accumulate token usage metrics during processing.

        This method intercepts the incremental token updates from Grok's API
        and accumulates them instead of passing each update to the metrics system.
        The final accumulated totals are reported at the end of processing.

        Args:
            tokens: The token usage metrics for the current chunk of processing,
                containing prompt_tokens, completion_tokens, and optional cached/reasoning tokens.
        Nr   T)
r4   r3   r=   r0   r>   r1   r@   rB   rA   rC   )r   rF   s     r   rE   z&GrokLLMService.start_llm_usage_metrics   s      "" //F4H4H14L"("6"6D/3D, ##d&=&==&,&>&>D# ))5,2,J,JD)"".%+%<%<D" /s   B'B))user_paramsassistant_paramsrH   rI   r   c                    |j                  | j                                t        ||      }t        ||      }t	        ||      S )a  Create an instance of GrokContextAggregatorPair from an OpenAILLMContext.

        Constructor keyword arguments for both the user and assistant aggregators
        can be provided.

        Args:
            context: The LLM context to create aggregators for.
            user_params: Parameters for configuring the user aggregator.
            assistant_params: Parameters for configuring the assistant aggregator.

        Returns:
            GrokContextAggregatorPair: A pair of context aggregators, one for
            the user and one for the assistant, encapsulated in an
            GrokContextAggregatorPair.

        .. deprecated:: 0.0.99
            `create_context_aggregator()` is deprecated and will be removed in a future version.
            Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
            See `OpenAILLMContext` docstring for migration guide.
        )params)r   r   )set_llm_adapterget_llm_adapterr   r   r   )r   r;   rH   rI   r   r   s         r   create_context_aggregatorz(GrokLLMService.create_context_aggregator   sC    6 	 4 4 67 +7;G4WEUV	(t	JJr   )NN)r   r   r   r    r$   Settingsr!   strr   r/   r:   r
   r   rD   r   rE   r	   r   r   rN   __classcell__)r7   s   @r   r&   r&   P   s     H .#.2+$ +$ 	+$
 }+$ ?++$ZB">.>.K ">H=M =F 0G/H9U9W!K!!K -	!K
 7!K 
#!Kr   r&   N)r    dataclassesr   typingr   logurur   pipecat.metrics.metricsr   *pipecat.processors.aggregators.llm_contextr   +pipecat.processors.aggregators.llm_responser   r	   1pipecat.processors.aggregators.openai_llm_contextr
    pipecat.services.openai.base_llmr   pipecat.services.openai.llmr   r   r   pipecat.services.settingsr   r   r$   r&   r"   r   r   <module>r\      s    "   1 A O > 
 = " " "J 	' 	 	kK% kKr   