
    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 ddlmZ dd	lmZ dd
lmZ e G d de             Z G d de      Zy)a  Perplexity LLM service implementation.

This module provides a service for interacting with Perplexity's API using
an OpenAI-compatible interface. It handles Perplexity's unique token usage
reporting patterns while maintaining compatibility with the Pipecat framework.
    )	dataclass)Optional)OpenAILLMInvocationParams)LLMTokenUsage)
LLMContext)OpenAILLMContext)OpenAILLMSettings)OpenAILLMService)_warn_deprecated_paramc                       e Zd ZdZy)PerplexityLLMSettingsz"Settings for PerplexityLLMService.N)__name__
__module____qualname____doc__     Q/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/perplexity/llm.pyr   r      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e
defdZdeez  f fdZdefdZ xZS )PerplexityLLMServiceaD  A service for interacting with Perplexity's API.

    This service extends OpenAILLMService to work with Perplexity's API while maintaining
    compatibility with the OpenAI-style interface. It specifically handles the difference
    in token usage reporting between Perplexity (incremental) and OpenAI (final summary).
    	_settingszhttps://api.perplexity.aiN)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 Perplexity LLM service.

        Args:
            api_key: The API key for accessing Perplexity's API.
            base_url: The base URL for Perplexity's API. Defaults to "https://api.perplexity.ai".
            model: The model identifier to use. Defaults to "sonar".

                .. 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.
        sonar)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)selfr   r   r   r   kwargsdefault_settings	__class__s          r   r    zPerplexityLLMService.__init__,   s    0 1w? "7,A7K%*"
 ))(3a8FVaZ`a"#+0(#r   params_from_contextreturnc                    | j                   j                  d|d   d}| j                   j                  | j                   j                  |d<   | j                   j                  | j                   j                  |d<   | j                   j                  | j                   j                  |d<   | j                   j
                  | j                   j
                  |d<   | j                   j                  | j                   j                  |d<   | j                   j                  r2|j                  dg       }d	| j                   j                  d
g|z   |d<   |S )a  Build parameters for Perplexity chat completion request.

        Perplexity uses a subset of OpenAI parameters and doesn't support tools.

        Args:
            params_from_context: Parameters, derived from the LLM context, to
                use for the chat completion. Contains messages, tools, and tool
                choice.

        Returns:
            Dictionary of parameters for the chat completion request.
        Tmessages)r   streamr-   frequency_penaltypresence_penaltytemperaturetop_p
max_tokenssystem)rolecontent)	r   r   r/   r0   r1   r2   r3   system_instructionget)r&   r*   paramsr-   s       r   build_chat_completion_paramsz1PerplexityLLMService.build_chat_completion_paramsY   s&    ^^))+J7
 >>++7*...*J*JF&'>>**6)-)H)HF%&>>%%1$(NN$>$>F=!>>+"nn22F7O>>$$0#'>>#<#<F<  >>,,zz*b1H!dnn.O.OP""F: r   contextc                   K   d| _         d| _        d| _        d| _        d| _        	 t
        |   |       d{    d| _        | j                   dkD  s| j                  dkD  rb| j                   | j                  z   | _        t        | j                   | j                  | j                        }t
        | !  |       d{    yy7 7 # d| _        | j                   dkD  s| j                  dkD  rc| j                   | j                  z   | _        t        | 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
        Perplexity'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   FTN)prompt_tokenscompletion_tokenstotal_tokens)	r!   r"   r#   r$   r%   r   _process_contextr   start_llm_usage_metrics)r&   r;   tokensr)   s      r   r@   z%PerplexityLLMService._process_context   sO      "#+0("	>'*7333"'D""Q&$*A*AA*E%)%8%84;R;R%R"&"&"5"5&*&=&=!%!3!3
 g5f=== +F	 4 > #(D""Q&$*A*AA*E%)%8%84;R;R%R"&"&"5"5&*&=&=!%!3!3
 g5f=== +FsK   $EC CC BE C	EC 	EBEEEErB   c                    K   | j                   sy| j                  s'|j                  dkD  r|j                  | _        d| _        |j                  | j
                  kD  r|j                  | _        yyw)aR  Accumulate token usage metrics during processing.

        Perplexity reports token usage incrementally during streaming,
        unlike OpenAI which provides a final summary. We accumulate the
        counts and report the total at the end of processing.

        Args:
            tokens: Token usage information to accumulate.
        Nr   T)r%   r$   r=   r!   r>   r"   )r&   rB   s     r   rA   z,PerplexityLLMService.start_llm_usage_metrics   sk      "" //F4H4H14L"("6"6D/3D, ##d&=&==&,&>&>D# >s   A-A/)r   r   r   r   r   Settings__annotations__strr   r    r   dictr:   r   r   r@   r   rA   __classcell__)r)   s   @r   r   r   !   s     %H$$ 4#48+$ +$ 	+$
 }+$ 01+$Z&@Y &^b &P>.>.K >@?M ?r   r   N)r   dataclassesr   typingr   )pipecat.adapters.services.open_ai_adapterr   pipecat.metrics.metricsr   *pipecat.processors.aggregators.llm_contextr   1pipecat.processors.aggregators.openai_llm_contextr    pipecat.services.openai.base_llmr	   pipecat.services.openai.llmr
   pipecat.services.settingsr   r   r   r   r   r   <module>rR      sR    "  O 1 A N > 8 < 	- 	 	T?+ T?r   