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
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mZmZ e Z 				dde
e! de
e	e"  de
e! de
e" dee"ef f
ddZ#e								ddee"e	e" f de"de
e! de
e	e"  de
e! de
e" de
e" de
e" de
ee$ej%f  de
ee"ef  defddZ&e								ddee"e	e" f de"de
e! de
e	e"  de
e! de
e" de
e" de
e" de
ee$ej%f  de
ee"ef  deeeeeef f fddZ'dS )z#
Main Search function for LiteLLM.
    N)partial)Any	CoroutineDictListOptionalUnion)verbose_logger)request_timeout)Logging)BaseSearchConfigSearchResponse)BaseLLMHTTPHandler)SearchProviders)ProviderConfigManagerclientfilter_out_litellm_paramsmax_resultssearch_domain_filtermax_tokens_per_pagecountryreturnc                 C   sH   i }| dur
| |d< |dur||d< |dur||d< |dur"||d< |S )a  
    Helper function to build optional_params dict from Perplexity Search API parameters.
    
    Args:
        max_results: Maximum number of results (1-20)
        search_domain_filter: List of domains to filter (max 20)
        max_tokens_per_page: Max tokens per page
        country: Country code filter
        
    Returns:
        Dict with non-None optional parameters
    Nr   r   r   r    )r   r   r   r   optional_paramsr   r   J/home/app/Keep/.python/lib/python3.10/site-packages/litellm/search/main.py_build_search_optional_params   s   r   querysearch_providerapi_keyapi_basetimeoutextra_headersc
                    s   t  }zIt }d|
d< ttf| |||||||||	d
|
}t }t|j|}|d|I dH }t	|r>|I dH }n|}|du rKt
d| |W S  tyh } z| d}tj|||||
dd}~ww )a  
    Async Search function.
    
    Args:
        query: Search query (string or list of strings)
        search_provider: Provider name (e.g., "perplexity")
        max_results: Optional maximum number of results (1-20), default 10
        search_domain_filter: Optional list of domains to filter (max 20)
        max_tokens_per_page: Optional max tokens per page, default 1024
        country: Optional country code filter (e.g., 'US', 'GB', 'DE')
        api_key: Optional API key
        api_base: Optional API base URL
        timeout: Optional timeout
        extra_headers: Optional extra headers
        **kwargs: Additional parameters
        
    Returns:
        SearchResponse with results list following Perplexity format
        
    Example:
        ```python
        import litellm
        
        # Basic search
        response = await litellm.asearch(
            query="latest AI developments 2024",
            search_provider="perplexity"
        )
        
        # Search with options
        response = await litellm.asearch(
            query="AI developments",
            search_provider="perplexity",
            max_results=10,
            search_domain_filter=["arxiv.org", "nature.com"],
            max_tokens_per_page=1024,
            country="US"
        )
        
        # Access results
        for result in response.results:
            print(f"{result.title}: {result.url}")
            print(f"Snippet: {result.snippet}")
        ```
    Tasearch)
r   r   r   r   r   r   r   r   r    r!   Nz5Got an unexpected None response from the Search API: /searchmodelcustom_llm_providerZoriginal_exceptionZcompletion_kwargsextra_kwargs)localsasyncioget_event_loopr   searchcontextvarscopy_contextrunrun_in_executoriscoroutine
ValueError	Exceptionlitellmexception_type)r   r   r   r   r   r   r   r   r    r!   kwargs
local_varsloopfuncctxZfunc_with_contextZinit_responseresponsee
model_namer   r   r   r"   9   sV   ;

r"   c
                 K   s  t  }z|
d}|
dd}|
dddu }t| ttfs'tdt|  t| tr9tdd	 | D s9td
t	j
t|d}|du rLtd| td|  t||||d}t|
d}| D ]\}}||vrq|||< qetd|  |j|||	pi d}|j||d}| d}|j||||d|d tj| ||pt|||||||d
}|W S  ty } z| d}tj|||||
dd}~ww )a  
    Synchronous Search function.
    
    Args:
        query: Search query (string or list of strings)
        search_provider: Provider name (e.g., "perplexity")
        max_results: Optional maximum number of results (1-20), default 10
        search_domain_filter: Optional list of domains to filter (max 20)
        max_tokens_per_page: Optional max tokens per page, default 1024
        country: Optional country code filter (e.g., 'US', 'GB', 'DE')
        api_key: Optional API key
        api_base: Optional API base URL
        timeout: Optional timeout
        extra_headers: Optional extra headers
        **kwargs: Additional parameters
        
    Returns:
        SearchResponse with results list following Perplexity format
        
    Example:
        ```python
        import litellm
        
        # Basic search
        response = litellm.search(
            query="latest AI developments 2024",
            search_provider="perplexity"
        )
        
        # Search with options
        response = litellm.search(
            query="AI developments",
            search_provider="perplexity",
            max_results=10,
            search_domain_filter=["arxiv.org", "nature.com"],
            max_tokens_per_page=1024,
            country="US"
        )
        
        # Multi-query search
        response = litellm.search(
            query=["AI developments", "machine learning trends"],
            search_provider="perplexity"
        )
        
        # Access results
        for result in response.results:
            print(f"{result.title}: {result.url}")
            print(f"Snippet: {result.snippet}")
            if result.date:
                print(f"Date: {result.date}")
        ```
    litellm_logging_objlitellm_call_idNr"   FTz/query must be a string or list of strings, got c                 s   s    | ]}t |tV  qd S )N)
isinstancestr).0qr   r   r   	<genexpr>   s    zsearch.<locals>.<genexpr>z'All items in query list must be strings)providerz&Search is not supported for provider: zSearch call - provider: )r   r   r   r   )r5   zSearch optional_params: )r   r   headers)r   r   r#   )r>   r   )r%   r   Zlitellm_paramsr&   )
r   r   r    Zlogging_objr   r   r&   r"   rE   Zprovider_configr$   )r(   popgetr?   r@   listr1   typeallr   Zget_provider_search_configr   r	   debugr   r   itemsZvalidate_environmentZget_complete_urlZupdate_environment_variablesbase_llm_http_handlerr+   r
   r2   r3   r4   )r   r   r   r   r   r   r   r   r    r!   r5   r6   r=   r>   Z	_is_asyncZsearch_provider_configr   Zfiltered_kwargskeyvaluerE   Zcomplete_urlr<   r:   r;   r   r   r   r+      s   C



r+   )NNNN)NNNNNNNN)(__doc__r)   r,   	functoolsr   typingr   r   r   r   r   r   Zhttpxr3   Zlitellm._loggingr	   Zlitellm.constantsr
   Z*litellm.litellm_core_utils.litellm_loggingr   ZLiteLLMLoggingObjZ+litellm.llms.base_llm.search.transformationr   r   Z*litellm.llms.custom_httpx.llm_http_handlerr   Zlitellm.types.utilsr   Zlitellm.utilsr   r   r   rM   intr@   r   floatTimeoutr"   r+   r   r   r   r   <module>   s     


 
	
h
	
