Ë
    uPêj#  ã                   óh   — d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZ  G d„ d«      Zy)	z†
Router utilities for Search API integration.

Handles search tool selection, load balancing, and fallback logic for search requests.
é    N)ÚCallable)Úpartial)ÚAnyÚFinal)Úverbose_router_loggerc                   óº   — e Zd ZdZedeeef   deedz  edz  f   fd„«       Z	edede
fd„«       Zeded	ede
fd
„«       Zededefd„«       Zedededefd„«       Zy)ÚSearchAPIRouterz¯
    Static utility class for routing search API calls through the LiteLLM router.

    Provides methods for search tool selection, load balancing, and fallback handling.
    Útool_litellm_paramsÚreturnNc                 óN   — | j                  d«      }| j                  d«      }||fS )aª  
        Resolve search provider credentials from tool configuration ONLY.

        Credentials are stored only in search_tool.litellm_params, never in team/key metadata.
        This ensures secrets are not exposed in team/key API responses.

        Args:
            tool_litellm_params: Search tool litellm_params with credentials

        Returns:
            Tuple of (api_key, api_base) from tool configuration
        Úapi_keyÚapi_base)Úget)r
   Úresolved_api_keyÚresolved_api_bases      úk/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/litellm/router_utils/search_api_router.pyÚ$_resolve_search_provider_credentialsz4SearchAPIRouter._resolve_search_provider_credentials   s3   € ð" /B×.EÑ.EÀiÓ.PÐØ/B×/FÑ/FÀzÓ/RÐàÐ!2Ð2Ð2ó    Úrouter_instanceÚsearch_toolsc              ƒ   ó²  K  — 	 ddl m} t        j                  dt	        |«      «       g }|D ]W  }|j                  d«      |j                  d«      |j                  di «      |j                  d«      dœ}|j                  |«       ŒY || _        t        j                  d	t	        |«      «       y# t        $ r}t        j                  d
|«       |‚d}~ww xY w­w)a6  
        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 %s search tools to routerÚsearch_tool_idÚsearch_tool_nameÚlitellm_paramsÚsearch_tool_info)r   r   r   r   z2Successfully updated router with %s search tool(s)z+Error updating router with search tools: %sN)Úlitellm.types.routerr   r   ÚdebugÚlenr   Úappendr   ÚinfoÚ	ExceptionÚ	exception)r   r   r   Úrouter_search_toolsÚtoolÚrouter_search_toolÚes          r   Úupdate_router_search_toolsz*SearchAPIRouter.update_router_search_tools.   sÕ   è ø€ ð	Ý@ä!×'Ñ'Ð(JÌCÐP\ÓL]Ô^ð 02ÐØ$ò ?�ð '+§h¡hÐ/?Ó&@Ø(,¯©Ð1CÓ(DØ&*§h¡hÐ/?ÀÓ&DØ(,¯©Ð1CÓ(Dñ	;Ð"ð $×*Ñ*Ð+=Õ>ð?ð ,?ˆOÔ(ä!×&Ñ&Ð'[Ô]`ÐatÓ]uÕvøäò 	Ü!×+Ñ+Ð,YÐ[\Ô]ØˆGûð	üs)   ‚C„B)B. Â-CÂ.	CÂ7CÃCÃCr   c                 óŽ   — | j                   D �cg c]  }|j                  d«      |k(  sŒ|‘Œ }}|st        d|› d�«      ‚|S c c}w )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
        r   zSearch tool 'z"' not found in router.search_tools)r   r   Ú
ValueError)r   r   r%   Úmatching_toolss       r   Úget_matching_search_toolsz)SearchAPIRouter.get_matching_search_toolsS   s]   € ð& -×9Ñ9ö!
Ø¸T¿X¹XÐFXÓ=YÐ]mÓ=mŠDð!
ˆð !
ñ Ü˜}Ð-=Ð,>Ð>`ÐaÓbÐbàÐùò!
s
   �A©AÚoriginal_functionc           	   ‹   ó:  K  — 	 |j                  d|j                  d«      «      }|st        d«      ‚||d<   ||d<   t        t        j                  | ¬«      |d<   | j                  ||d¬«       | j                  D �cg c]  }|j                  d«      ‘Œ }}t        j                  d	|||«        | j                  di |¤Žƒ d
{  –—† }|S c c}w 7 Œ# t        $ r>}ddlm} t        j                   || |t        j                   «       |¬«      «       |‚d
}~ww xY 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-   Úlitellm_metadata)r/   ÚkwargsÚmetadata_variable_namezsInside SearchAPIRouter.async_search_with_fallbacks() - search_tool_name: %s, Available Search Tools: %s, kwargs: %sNr   )Úsend_llm_exception_alert)Úlitellm_router_instanceÚrequest_kwargsÚerror_traceback_strÚoriginal_exception© )r   r*   r   r	   Ú"async_search_with_fallbacks_helperÚ_update_kwargs_before_fallbacksr   r   r   Úasync_function_with_fallbacksr"   Ú!litellm.router_utils.handle_errorr4   ÚasyncioÚcreate_taskÚ	tracebackÚ
format_exc)	r   r-   r2   r   r%   Úavailable_search_tool_namesÚresponser'   r4   s	            r   Úasync_search_with_fallbacksz+SearchAPIRouter.async_search_with_fallbacksn   s?  è ø€ ð$-	Ø&,§j¡jÐ1CÀVÇZÁZÐPWÓEXÓ&YÐá#Ü Ð!]Ó^Ð^ð /ˆF�7‰OØ2CˆFÐ.Ñ/ä*1Ü×BÑBØ /ô+ˆFÐ&Ñ'ð ×;Ñ;Ø&ØØ'9ð <ô ð \k×[wÑ[wÖ1xÐSW°$·(±(Ð;MÕ2NÐ1xÐ'Ð1xÜ!×'Ñ'ð FØ Ø+Øô	ð %R O×$QÑ$QÑ$[ÐTZÑ$[×[ˆHØˆOùò 2yð \ùô ò 	ÝRä×ÑÙ(Ø,;Ø#)Ü(1×(<Ñ(<Ó(>Ø'(ô	ôð ˆGûð	üsG   ‚D„A8C Á<C
Â/C ÃCÃC Ã	DÃ
C Ã	DÃ9DÄDÄDr/   r0   c              ‹   ó²  K  — |}	 t         j                  | |¬«      }t        j                  |«      }|j	                  di «      }|j	                  d«      }|st        d|› d�«      ‚t         j                  |¬«      \  }	}
t        j                  d|«        |d||	|
dœ|¤Žƒ d	{  –—† }|S 7 Œ# t        $ r}t        j                  d
||«       |‚d	}~ww xY 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_providerz=search_provider not found in litellm_params for search tool 'ú')r
   z&Selected search tool with provider: %s)rF   r   r   NzFError in SearchAPIRouter.async_search_with_fallbacks_helper for %s: %sr9   )r	   r,   ÚrandomÚchoicer   r*   r   r   r   r"   Úerror)r   r/   r0   r2   r   r+   Úselected_toolr   rF   r   r   rC   r'   s                r   r:   z2SearchAPIRouter.async_search_with_fallbacks_helper¯   s  è ø€ ð( #(Ðð%	ä$3×$MÑ$MØ /Ø!1ð %Nó %ˆNô $*§=¡=°Ó#@ˆMð %2×$5Ñ$5Ð6FÈÓ$KˆNØ%3×%7Ñ%7Ð8IÓ%JˆOÙ"Ü Ð#`ÐaqÐ`rÐrsÐ!tÓuÐuä /× TÑ TØ$2ð !Uó !ÑˆG�Xô "×'Ñ'Ð(PÐRaÔbñ %>ð %Ø /ØØ!ñ%ð ñ	%÷ ˆHð ˆOðùô ò 	Ü!×'Ñ'ØXÐZjÐlmôð ˆGûð		üs;   ‚C†BB- Â$B+Â%B- Â*CÂ+B- Â-	CÂ6CÃCÃC)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚstaticmethodÚdictÚstrr   Útupler   Úlistr(   r,   r   rD   r:   r9   r   r   r	   r	      së   „ ñð ð3à! # s (™^ð3ð 
ˆs�T‰z˜3 ™:Ð%Ñ	&ò3ó ð3ð* ð"¸#ð "ÈTò "ó ð"ðH ðØðàðð 
òó ðð4 ð>Øð>à#ò>ó ð>ð@ ð:Øð:àð:ð $,ò:ó ñ:r   r	   )rO   r>   rH   r@   Úcollections.abcr   Ú	functoolsr   Útypingr   r   Úlitellm._loggingr   r	   r9   r   r   ú<module>rY      s-   ðñó Û Û Ý $Ý ß å 2÷Yò Yr   