o
    ưi7                     @   s   d Z ddlmZmZmZmZmZ ddlZddlm	Z
 ddlmZmZmZ ddlmZ G dd deZG d	d
 d
eddZG dd deZdS )z
Calls Tavily's /search endpoint to search the web.

Tavily API Reference: https://docs.tavily.com/documentation/api-reference/endpoint/search
    )DictListOptional	TypedDictUnionN)Logging)BaseSearchConfigSearchResponseSearchResult)get_secret_strc                   @   s   e Zd ZU dZeed< dS )_TavilySearchRequestRequiredz.Required fields for Tavily Search API request.queryN)__name__
__module____qualname____doc__str__annotations__ r   r   `/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/tavily/search/transformation.pyr      s   
 r   c                   @   s   e Zd ZU dZeed< ee ed< ee ed< eed< eed< ee	ef ed< ee	ef ed< e	ed	< e	ed
< e	ed< eed< eed< eed< eed< dS )TavilySearchRequestz}
    Tavily Search API request format.
    Based on: https://docs.tavily.com/documentation/api-reference/endpoint/search
    max_resultsinclude_domainsZexclude_domainsZtopicZsearch_depthZinclude_answerZinclude_raw_contentZinclude_imagesZinclude_image_descriptionsZinclude_faviconZ
time_rangeZ
start_dateend_datecountryN)
r   r   r   r   intr   r   r   r   boolr   r   r   r   r      s    
 r   F)totalc                   @   s   e Zd ZdZedefddZ		ddedee dee defd	d
Z		ddee de
deeeee f  defddZdeeee f de
defddZdejdedefddZdS )TavilySearchConfigzhttps://api.tavily.comreturnc                   C   s   dS )NZTavilyr   r   r   r   r   ui_friendly_name0   s   z#TavilySearchConfig.ui_friendly_nameNheadersapi_keyapi_basec                 K   s2   |pt d}|stdd| |d< d|d< |S )z:
        Validate environment and return headers.
        ZTAVILY_API_KEYzETAVILY_API_KEY is not set. Set `TAVILY_API_KEY` environment variable.zBearer Authorizationzapplication/jsonzContent-Type)r   
ValueError)selfr!   r"   r#   kwargsr   r   r   validate_environment4   s   
z'TavilySearchConfig.validate_environmentoptional_paramsdatac                 K   s*   |pt dp| j}|ds| d}|S )z7
        Get complete URL for Search endpoint.
        TAVILY_API_BASEz/search)r   r+   endswith)r&   r#   r)   r*   r'   r   r   r   get_complete_urlE   s   


z#TavilySearchConfig.get_complete_urlr   c                 K   s   t |tr
d|}d|i}d|v r|d |d< d|v r"|d |d< d|v r.|d  |d< t|}| D ]\}}||  vrH||vrH|||< q6|S )a  
        Transform Search request to Tavily API format.
        
        Args:
            query: Search query (string or list of strings). Tavily only supports single string queries.
            optional_params: Optional parameters for the request
                - max_results: Maximum number of search results (0-20)
                - search_domain_filter: List of domains to include (max 300) -> maps to `include_domains`
                - exclude_domains: List of domains to exclude (max 150)
                - topic: Category of search ('general', 'news', 'finance')
                - search_depth: Depth of search ('basic', 'advanced')
                - include_answer: Include LLM-generated answer (bool or 'basic', 'advanced')
                - include_raw_content: Include raw HTML content (bool or 'markdown', 'text')
                - include_images: Perform image search (bool)
                - include_image_descriptions: Add descriptions for images (bool)
                - include_favicon: Include favicon URL (bool)
                - time_range: Time range filter ('day', 'week', 'month', 'year', 'd', 'w', 'm', 'y')
                - start_date: Start date filter (YYYY-MM-DD)
                - end_date: End date filter (YYYY-MM-DD)
                - country: Country code filter (e.g., 'US', 'GB', 'DE')
            
        Returns:
            Dict with typed request data following TavilySearchRequest spec
         r   r   Zsearch_domain_filterr   r   )
isinstancelistjoinlowerdictitemsZ(get_supported_perplexity_optional_params)r&   r   r)   r'   Zrequest_dataZresult_dataparamvaluer   r   r   transform_search_requestX   s    

z+TavilySearchConfig.transform_search_requestraw_responselogging_objc                 K   s^   |  }g }|dg D ]}t|dd|dd|ddddd}|| qt|dd	S )
u<  
        Transform Tavily API response to LiteLLM unified SearchResponse format.
        
        Tavily → LiteLLM mappings:
        - results[].title → SearchResult.title
        - results[].url → SearchResult.url
        - results[].content → SearchResult.snippet
        - No date/last_updated fields in Tavily response (set to None)
        
        Args:
            raw_response: Raw httpx response from Tavily API
            logging_obj: Logging object for tracking
            
        Returns:
            SearchResponse with standardized format
        resultstitle urlcontentN)r;   r=   snippetdateZlast_updatedsearch)r:   object)jsongetr
   appendr	   )r&   r8   r9   r'   Zresponse_jsonr:   resultZsearch_resultr   r   r   transform_search_response   s   


z,TavilySearchConfig.transform_search_response)NN)N)r   r   r   r+   staticmethodr   r    r   r   r(   r3   r   r   r-   r7   httpxResponseLiteLLMLoggingObjr	   rG   r   r   r   r   r   -   sN    


;r   )r   typingr   r   r   r   r   rI   Z*litellm.litellm_core_utils.litellm_loggingr   rK   Z+litellm.llms.base_llm.search.transformationr   r	   r
   Zlitellm.secret_managers.mainr   r   r   r   r   r   r   r   <module>   s    