o
    ưi                      @   sV   d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
 G dd dZdS )z
Router utilities for Search API integration.

Handles search tool selection, load balancing, and fallback logic for search requests.
    N)partial)AnyCallable)verbose_router_loggerc                   @   sp   e Zd ZdZededefddZedededefdd	Z	eded
e
fddZededede
fddZdS )SearchAPIRouterz
    Static utility class for routing search API calls through the LiteLLM router.
    
    Provides methods for search tool selection, load balancing, and fallback handling.
    router_instancesearch_toolsc              
      s   zBddl m} tdt| d g }|D ]}|d|d|di |dd	}|| q|| _td
t| d W dS  t	y[ } zt
dt|  |d}~ww )aF  
        Update the router with search tools from the database.
        
        This method is called by a cron job to sync search tools from DB to router.
        
        Args:
            router_instance: The Router instance to update
            search_tools: List of search tool configurations from the database
        r   )SearchToolTypedDictzAdding z search tools to routersearch_tool_idsearch_tool_namelitellm_paramssearch_tool_info)r
   r   r   r   z!Successfully updated router with z search tool(s)z)Error updating router with search tools: N)Zlitellm.types.routerr	   r   debuglengetappendr   info	Exception	exceptionstr)r   r   r	   Zrouter_search_toolstoolZrouter_search_toole r   ]/home/app/Keep/.python/lib/python3.10/site-packages/litellm/router_utils/search_api_router.pyupdate_router_search_tools   s.   

z*SearchAPIRouter.update_router_search_toolsr   returnc                    s,    fdd| j D }|std  d|S )av  
        Get all search tools matching the given name.
        
        Args:
            router_instance: The Router instance
            search_tool_name: Name of the search tool to find
            
        Returns:
            List of matching search tool configurations
            
        Raises:
            ValueError: If no matching search tools are found
        c                    s   g | ]}| d  kr|qS r   r   .0r   r   r   r   
<listcomp>R   s
    z=SearchAPIRouter.get_matching_search_tools.<locals>.<listcomp>zSearch tool 'z"' not found in router.search_tools)r   
ValueError)r   r   matching_toolsr   r   r   get_matching_search_tools@   s   
z)SearchAPIRouter.get_matching_search_toolsoriginal_functionc                    s   zL| d| d}|std||d< ||d< ttj| d|d< | j||dd d	d
 | jD }td| d| d|  | j	di |I dH }|W S  t
yn } zddlm} t|| |t |d |d}~ww )a  
        Helper function to make a search API call through the router with load balancing and fallbacks.
        Reuses the router's retry/fallback infrastructure.
        
        Args:
            router_instance: The Router instance
            original_function: The original litellm.asearch function
            **kwargs: Search parameters including search_tool_name, query, etc.
            
        Returns:
            SearchResponse from the search API
        r   modelz:search_tool_name or model parameter is required for searchoriginal_generic_function)r   r$   Zlitellm_metadata)r%   kwargsZmetadata_variable_namec                 S   s   g | ]}| d qS r   r   r   r   r   r   r       s    z?SearchAPIRouter.async_search_with_fallbacks.<locals>.<listcomp>zIInside SearchAPIRouter.async_search_with_fallbacks() - search_tool_name: z, Available Search Tools: z
, kwargs: Nr   )send_llm_exception_alert)Zlitellm_router_instanceZrequest_kwargsZerror_traceback_strZoriginal_exceptionr   )r   r!   r   r   "async_search_with_fallbacks_helperZ_update_kwargs_before_fallbacksr   r   r   Zasync_function_with_fallbacksr   Z!litellm.router_utils.handle_errorr(   asynciocreate_task	traceback
format_exc)r   r$   r'   r   Zavailable_search_tool_namesresponser   r(   r   r   r   async_search_with_fallbacks\   sB   
z+SearchAPIRouter.async_search_with_fallbacksr%   r&   c              
      s   |}zDt j| |d}t|}|di }|d}|d}	|d}
|s/td| dtd|  |d||	|
d	|I d
H }|W S  tyb } zt	d| dt
|  |d
}~ww )a  
        Helper function for search API calls - selects a search tool and calls the original function.
        Called by async_function_with_fallbacks for each retry attempt.
        
        Args:
            router_instance: The Router instance
            model: The search tool name (passed as model for compatibility)
            original_generic_function: The original litellm.asearch function
            **kwargs: Search parameters
            
        Returns:
            SearchResponse from the selected search provider
        )r   r   r   search_providerapi_keyapi_basez=search_provider not found in litellm_params for search tool ''z$Selected search tool with provider: )r0   r1   r2   Nz@Error in SearchAPIRouter.async_search_with_fallbacks_helper for z: r   )r   r#   randomchoicer   r!   r   r   r   errorr   )r   r%   r&   r'   r   r"   Zselected_toolr   r0   r1   r2   r.   r   r   r   r   r)      s@   



z2SearchAPIRouter.async_search_with_fallbacks_helperN)__name__
__module____qualname____doc__staticmethodr   listr   r   r#   r   r/   r)   r   r   r   r   r      s4    (;r   )r:   r*   r4   r,   	functoolsr   typingr   r   Zlitellm._loggingr   r   r   r   r   r   <module>   s    