
    h                         d dl mZmZmZmZ d dlmZmZmZm	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 d dlmZmZ d d	lmZ d d
lmZmZ  e       Z eddg      Zdeeef   fdZej?                  de ee      g      d        Z ejC                  ddg ee      g      de	fd       Z"deee#f   fdZ$ej?                  d ee      g      d        Z%ejC                  ddg ee      g      d        Z&y)    )AnyDictListTuple)	APIRouterDependsHTTPExceptionRequestN)verbose_proxy_logger)
RedisCache)
safe_dumps)SensitiveDataMasker)ProxyErrorTypesProxyException)user_api_key_auth)CachePingResponseHealthCheckCacheParamsz/cachecaching)prefixtagsreturnc                  P   t         j                  i S 	 t        t         j                  j                        } | rt        di | j	                         ni }t
        j                  |      S # t        t        f$ r-}t        j                  dt        |              i cY d}~S d}~ww xY w)a  
    Safely extracts and cleans cache parameters.

    The health check UI needs to display specific cache parameters, to show users how they set up their cache.

    eg.
        {
            "host": "localhost",
            "port": 6379,
            "redis_kwargs": {"db": 0},
            "namespace": "test",
        }

    Returns:
        Dict containing cleaned and masked cache parameters
    NzError extracting cache params:  )litellmcachevarsr   
model_dumpmasker	mask_dictAttributeError	TypeErrorr   debugstr)cache_paramscleaned_paramses      X/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/proxy/caching_routes.py_extract_cache_paramsr(      s    " }}	GMM//0CO"2\2==?UW 	 //I& ""%DSVH#MN	s   AA) )B%8"B B% B%z/ping)response_modeldependenciesc            	        K   i } i }	 t         j                  t        dd      t        j	                  t        t         j                              } | j                  dd       t               }t         j                  j                  dk(  rt         j                  j                          d{   }t        j                  dt        |      z          t         j                  j                  dd	d
ddg       d{    t        j                  d       t        dt        t         j                  j                        ddt        |       |      S t        dt        t         j                  j                        t        |             S 7 7 # t         $ rc}ddl}dt        |       dt        |       t        |      |j%                         d}t'        t        |      t(        j*                  dd      d}~ww xY ww)z6
    Endpoint for checking if cache can be pinged
    N  ,Cache not initialized. litellm.cache is Nonestatus_codedetailr   redisz/cache/ping: ping_response: test_keyz
test-modeluserztest from litellm)rolecontent)resultmodelmessagesz"/cache/ping: done with set_cache()healthyTsuccess)status
cache_typeping_responseset_cache_responselitellm_cache_paramshealth_check_cache_params)r;   r<   r?   r   Service Unhealthy ())messager?   r@   	traceback
cache_ping)rC   typeparamcode)r   r   r	   r   r   r   popr(   rF   pingr   r"   r#   async_add_cacher   r   	ExceptionrD   
format_excr   r   cache_ping_error)r?   cleaned_cache_paramsr=   r&   rD   error_messages         r'   rE   rE   4   s     ,.+-3
== (V   &//W]]0CD  $/46==(")--"4"4"66M &&.]1CC --//!"#)6IJK 0   
 !&&'KL$ w}}112"#,%/0D%E*>  % w}}112%/0D%E + 7
*  
 -SVHA6$./C$D)34H)I"--/	
 }- 11	
 	

s\   G:B#F +F,AF :F	;AF G:7F G:F 	F 	G7AG22G77G:z/delete)r   r*   requestc                   K   	 t         j                  t        dd      | j                          d{   }|j	                  dd      }t         j                  j
                  dk(  r,t         j                  j                  |       d{    dd	iS t        d
dt         j                  j
                   d      7 7 3# t        $ r}t        d
dt        |       d      d}~ww xY ww)a  
    Endpoint for deleting a key from the cache. All responses from litellm proxy have `x-litellm-cache-key` in the headers

    Parameters:
    - **keys**: *Optional[List[str]]* - A list of keys to delete from the cache. Example {"keys": ["key1", "key2"]}

    ```shell
    curl -X POST "http://0.0.0.0:4000/cache/delete"     -H "Authorization: Bearer sk-1234"     -d '{"keys": ["key1", "key2"]}'
    ```

    Nr,   r-   r.   keysr1   )rS   r;   r:     Cache type z; does not support deleting a key. only `redis` is supportedzCache Delete Failed(rB   )	r   r   r	   jsongetrF   delete_cache_keysrL   r#   )rQ   request_datarS   r&   s       r'   cache_deleterZ   u   s     &
== (V  %\\^+-==(--11t1<<<)   $W]]%7%7$88st  , =  
)#a&3
 	

sK   C,0C B=AC B?C C,*C ?C 	C)
C$$C))C,c                     	 | j                         }|t        |      fS # t        $ r0}t        j                  dt        |              dgdfcY d}~S d}~ww xY w)z
    Helper function to safely get Redis client list information.

    Returns:
        tuple: (client_list, num_clients) where num_clients is -1 if CLIENT LIST is unavailable
    zACLIENT LIST command failed (likely restricted on managed Redis): z8CLIENT LIST command not available on this Redis instanceN)client_listlenrL   r   warningr#   )cache_instancer]   r&   s      r'   _get_redis_client_infora      sh    P$002C,,, P$$OPSTUPVxX	
 KKROO	Ps    	A%AAAz/redis/info)r*   c                     K   	 t         j                  t        dd      t         j                  j                  dk(  r(t	        t         j                  j                  t
              s)t        ddt         j                  j                   d      t        t         j                  j                        \  } }t         j                  j                  j                         }|| |d	S # t        $ r}t        dd
t        |       d      d}~ww xY ww)z*
    Endpoint for getting /redis/info
    Nr,   r-   r.   r1   rT   rU   z does not support redis info)num_clientsclientsinforA   rB   )
r   r   r	   rF   
isinstancer   ra   re   rL   r#   )r]   rc   
redis_infor&   s       r'   cache_redis_inforh      s     
== (V 
 MM')7==..
;$W]]%7%7$88TU  $:'--:M:M#N [ ]]((--/
 '"
 	

  
(Q2
 	

s)   DCC# "D#	D,DDDz	/flushallc                    K   	 t         j                  t        dd      t         j                  j                  dk(  rTt	        t         j                  j                  t
              r,t         j                  j                  j                          ddiS t        dd	t         j                  j                   d
      # t        $ r} t        ddt        |        d      d} ~ ww xY ww)a  
    A function to flush all items from the cache. (All items will be deleted from the cache with this)
    Raises HTTPException if the cache is not initialized or if the cache type does not support flushing.
    Returns a dictionary with the status of the operation.

    Usage:
    ```
    curl -X POST http://0.0.0.0:4000/cache/flushall -H "Authorization: Bearer sk-1234"
    ```
    Nr,   r-   r.   r1   r;   r:   rT   rU   z does not support flushingrA   rB   )	r   r   r	   rF   rf   r   flushallrL   r#   )r&   s    r'   cache_flushallrk      s      
== (V  ==(ZMM.
 MM((*)   $W]]%7%7$88RS   
(Q2
 	

s/   C&BB; C&)B; ;	C#CC##C&)'typingr   r   r   r   fastapir   r   r	   r
   r   litellm._loggingr   litellm.caching.cachingr   *litellm.litellm_core_utils.safe_json_dumpsr   0litellm.litellm_core_utils.sensitive_data_maskerr   litellm.proxy._typesr   r   $litellm.proxy.auth.user_api_key_authr   litellm.types.cachingr   r   r   routerr#   r(   rW   rE   postrZ   intra   rh   rk   r       r'   <module>ry      sI   ) ) > >  1 . A P @ B K			

tCH~ < $+,-  
9

9
x 
+,-  
%
 %

%
PPeD#I.> P" +,-  "
	"
J 
+,-  
 

 
rx   