o
    ưir'                     @   s   d Z ddlmZmZmZmZ ddlZddl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 ddlmZ ddlmZ G dd deZdS )zW
Translate from OpenAI's `/v1/chat/completions` to Perplexity's `/v1/chat/completions`
    )AnyListOptionalTupleN)verbose_loggerget_secret_str)AllMessageValues)UsagePromptTokensDetailsWrapper)Logging)OpenAIGPTConfig)ModelResponse)ChatCompletionAnnotation)#ChatCompletionAnnotationURLCitationc                       s   e Zd Zedee fddZdee dee deee ee f fddZdede	fd	d
Z
		ddedejdedededee dedededee dee def fddZdededdfddZdededdfddZ  ZS )PerplexityChatConfigreturnc                 C   s   dS )NZ
perplexity )selfr   r   b/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/perplexity/chat/transformation.pycustom_llm_provider   s   z(PerplexityChatConfig.custom_llm_providerapi_baseapi_keyc                 C   s,   |pt dpd}|pt dpt d}||fS )NZPERPLEXITY_API_BASEzhttps://api.perplexity.aiZPERPLEXITYAI_API_KEYZPERPLEXITY_API_KEYr   )r   r   r   Zdynamic_api_keyr   r   r   $_get_openai_compatible_provider_info   s   z9PerplexityChatConfig._get_openai_compatible_provider_infomodelc              
   C   s   g d}zt j|| jdr|d W n ty- } ztd|  W Y d}~nd}~ww zt j|| jdr?|d W |S W |S  ty\ } ztd|  W Y d}~|S d}~ww )z
        Perplexity supports a subset of OpenAI params

        Ref: https://docs.perplexity.ai/api-reference/chat-completions

        Eg. Perplexity does not support tools, tool_choice, function_call, functions, etc.
        )
Zfrequency_penaltyZ
max_tokensZmax_completion_tokensZpresence_penaltyZresponse_formatstreamZtemperatureZtop_pmax_retriesextra_headers)r   r   Zreasoning_effortz,Error checking if model supports reasoning: NZweb_search_optionsz-Error checking if model supports web search: )litellmZsupports_reasoningr   append	Exceptionr   debugZsupports_web_search)r   r   Zbase_openai_paramser   r   r   get_supported_openai_params$   s0   
z0PerplexityChatConfig.get_supported_openai_paramsNraw_responsemodel_responselogging_objrequest_datamessagesoptional_paramslitellm_paramsencoding	json_modec                    s   t  j|||||||||	|
|d}z| }| || | || W |S  ty? } ztd|  W Y d }~|S d }~ww )N)r   r$   r%   r&   r'   r(   r)   r*   r+   r   r,   z3Error extracting Perplexity-specific usage fields: )supertransform_responsejson%_enhance_usage_with_perplexity_fields_add_citations_as_annotationsr    r   r!   )r   r   r$   r%   r&   r'   r(   r)   r*   r+   r   r,   raw_response_jsonr"   	__class__r   r   r.   K   s2   z'PerplexityChatConfig.transform_responser2   c           	      C   s  t |dr
|jdu rtdddd|_|j}|dg }d}|r3tdd |D }|dkr3td|d	 }|di }|d
}|du rG|d
}|du rP|d}|du rY|d}|dkse|dur|dkr|jdu rnt |_|dkrxt|d| |dur|dkr||j_	dS dS dS dS dS )z
        Extract citation tokens and search queries from Perplexity API response
        and add them to the usage object using standard LiteLLM fields.
        usageNr   )Zprompt_tokensZcompletion_tokensZtotal_tokens	citationsc                 s   s     | ]}|rt t|V  qd S )N)lenstr).0citationr   r   r   	<genexpr>   s    

zMPerplexityChatConfig._enhance_usage_with_perplexity_fields.<locals>.<genexpr>      num_search_queriesZsearch_queriescitation_tokens)
hasattrr5   r
   getsummaxZprompt_tokens_detailsr   setattrZweb_search_requests)	r   r%   r2   r5   r6   r?   Ztotal_citation_charsZperplexity_usager>   r   r   r   r0   t   sB   





z:PerplexityChatConfig._enhance_usage_with_perplexity_fieldsc                 C   s  |j sdS |j d }t|dr|jdu rdS |j}g }|dg }|dg }i }|D ]}	t|	trBd|	v rBd|	v rB|	d ||	d < q+t|dd	}
|
sMdS ddl}d
}t|	||
}i }t
|D ]\}}t|trp|||d < qa|D ],}t|d}||v r|| }||d	}||| | d}d|d}|| qs|rt|dr|jdu rg |_|j| |rt|d| |rt|d| dS dS )z
        Extract citations and search_results from Perplexity API response
        and add them as ChatCompletionAnnotation objects to the message.
        Nr   messager6   search_resultsurltitlecontent z	\[(\d+)\]r<   )rG   rH   start_indexZ	end_indexurl_citation)typerL   annotations)choicesr@   rE   rA   
isinstancedictgetattrrelistfinditer	enumerater8   intgroupstartendr   rN   extendrD   )r   r%   r2   choicerE   rN   r6   rF   Zurl_to_titleresultrI   rS   Zcitation_patternZcitation_matchesZcitation_number_to_urlir:   matchZcitation_numberrG   rH   rL   
annotationr   r   r   r1      sb   


z2PerplexityChatConfig._add_citations_as_annotations)NN)__name__
__module____qualname__propertyr   r8   r   r   r   rT   r#   httpxResponser   LiteLLMLoggingObjrQ   r   r	   r   boolr.   r0   r1   __classcell__r   r   r3   r   r      sh    
2	
)
:r   )__doc__typingr   r   r   r   re   r   Zlitellm._loggingr   Zlitellm.secret_managers.mainr   Zlitellm.types.llms.openair	   Zlitellm.types.utilsr
   r   Z*litellm.litellm_core_utils.litellm_loggingr   rg   Z+litellm.llms.openai.chat.gpt_transformationr   r   r   r   r   r   r   r   r   <module>   s    