o
    ưiNh                     @   s  U d dl Z d dlZd dlmZmZ d dlmZmZ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 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 d dlm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ e$j,j-e&e$j.j-e(e$j/j-e)e$j0j-e*e$j1j-e'e$j2j-e+e$j3j-eiZ4e$j3j-eiZ5ee6e	e f e7d< dd Z8dd Z9e5:e9  e8 Z;e4:e; G dd dZ<G dd dZ=e= Z>dS )    N)datetimetimezone)AnyDictListOptionalTypecast)Router)verbose_proxy_logger)uuid)CustomGuardrail)
safe_dumps)GraySwanGuardrail)initialize_guardrail)get_instance_fn)PrismaClient)
get_secret)	GuardrailGuardrailEventHooksLakeraCategoryThresholdsLitellmParamsSupportedGuardrailIntegrations   )initialize_bedrockinitialize_hide_secretsinitialize_lakerainitialize_lakera_v2initialize_presidioinitialize_tool_permissionguardrail_class_registryc                  C   s  i } zt jt}t j|d}t j|std | W S t |D ]}t j||}t j	|r7|
dr8q#t j|d}t j|sFq#d| }zItd|  t|}t|dr}t|d}t|tr|| | td| d	t|   nt|d
rt|d
}	|	| |< td|  W q# ty }
 ztd| d	|
  W Y d}
~
q#d}
~
w ty }
 ztd| d	|
  W Y d}
~
q#d}
~
ww tdt|  dt|    W | S  ty }
 ztd|
  W Y d}
~
| S d}
~
ww )a  
    Get guardrail initializers by discovering them from the guardrail_hooks directory structure.

    Scans the guardrail_hooks directory for subdirectories containing __init__.py files
    with either guardrail_initializer_registry or initialize_guardrail functions.

    Returns:
        Dict[str, Callable]: A dictionary mapping guardrail types to their initializer functions
    guardrail_hooks#guardrail_hooks directory not found____init__.py)litellm.proxy.guardrails.guardrail_hooks.Discovering guardrails in: guardrail_initializer_registryz(Found guardrail_initializer_registry in : r   z'Found initialize_guardrail function in Could not import NError processing zDiscovered z guardrail initializers: *Error discovering guardrail initializers: )ospathdirname__file__joinexistsr   debuglistdirisdir
startswith	importlibimport_modulehasattrgetattr
isinstancedictupdatelistkeysImportErrorerror	Exceptionlen)Zdiscovered_initializerscurrent_dir	hooks_diritem	item_path	init_filemodule_pathmoduleregistryZinitialize_fne rL   b/home/app/Keep/.python/lib/python3.10/site-packages/litellm/proxy/guardrails/guardrail_registry.py$get_guardrail_initializer_from_hooks5   sf   









rN   c            
      C   s  	 i } zt jt}t j|d}t j|std | W S t |D ]}t j||}t j	|r8|
dr9q$t j|d}t j|sGq$d| }z#td|  t|}t|drnt|d}t|trn| | W q$ ty }	 ztd| d	|	  W Y d
}	~	q$d
}	~	w ty }	 ztd| d	|	  W Y d
}	~	q$d
}	~	ww W | S  ty }	 ztd|	  W Y d
}	~	| S d
}	~	ww )za
    Get guardrail classes by discovering them from the guardrail_hooks directory structure.
    r!   r"   r#   r$   r%   r&   r    r)   r(   Nr*   r+   )r,   r-   r.   r/   r0   r1   r   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r?   rA   	exceptionr@   )
Zdiscovered_classesrC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rL   rM   get_guardrail_class_from_hooks   sP   	






%rP   c                   @   s   e Zd ZdZdd Zdedee fddZde	d	e
fd
dZded	e
fddZdede	d	e
fddZed	e
dee	 fddZded	e
dee	 fddZded	e
dee	 fddZdS )GuardrailRegistryzi
    Registry for guardrails

    Handles adding, removing, and getting guardrails in DB + in memory
    c                 C   s   d S NrL   selfrL   rL   rM   __init__   s   zGuardrailRegistry.__init__guardrail_namereturnc                 C   s8   t jjtd}|D ]}t|tr|j|kr|  S q	dS )zW
        Returns the initialized guardrail callback for a given guardrail name
        )Zcallback_typeN)litellmlogging_callback_managerZget_custom_loggers_for_typer   r:   rV   )rT   rV   Zactive_guardrailsZactive_guardrailrL   rL   rM   "get_initialized_guardrail_callback   s   

z4GuardrailRegistry.get_initialized_guardrail_callback	guardrailprisma_clientc              
      s   zN| d}| di }t|dr| }n|rt|ni }t|}t| di }|jjj|||t	t
jt	t
jddI dH }t|}	|j|	d< |	W S  tyd }
 z	td	t|
 d}
~
ww )
z1
        Add a guardrail to the database
        rV   litellm_params
model_dumpguardrail_info)rV   r]   r_   
created_at
updated_at)dataNguardrail_idzError adding guardrail to DB: )getr8   r^   r;   r   dblitellm_guardrailstablecreater   nowr   utcrc   rA   str)rT   r[   r\   rV   litellm_params_objlitellm_params_dictr]   r_   Zcreated_guardrailZguardrail_dictrK   rL   rL   rM   add_guardrail_to_db   s2   





z%GuardrailRegistry.add_guardrail_to_dbrc   c              
      sZ   z|j jjd|idI dH  dd| diW S  ty, } z	tdt| d}~ww )z6
        Delete a guardrail from the database
        rc   whereNmessagez
Guardrail z deleted successfullyz"Error deleting guardrail from DB: )re   rf   deleterA   rj   )rT   rc   r\   rK   rL   rL   rM   delete_guardrail_from_db  s   z*GuardrailRegistry.delete_guardrail_from_dbc              
      s   zE| d}| di }t|dr| }n|rt|ni }t|}t| di }|jjjd|i|||t	t
jddI dH }	t|	W S  ty[ }
 z	td	t|
 d}
~
ww )
z4
        Update a guardrail in the database
        rV   r]   r^   r_   rc   )rV   r]   r_   ra   )ro   rb   Nz Error updating guardrail in DB: )rd   r8   r^   r;   r   re   rf   r<   r   rh   r   ri   rA   rj   )rT   rc   r[   r\   rV   rk   rl   r]   r_   Zupdated_guardrailrK   rL   rL   rM   update_guardrail_in_db"  s.   




z(GuardrailRegistry.update_guardrail_in_dbc              
      sz   z&| j jjddiddidI dH }g }|D ]}|tdi t| q|W S  ty< } z	tdt| d}~ww )	z
        Get all active guardrails from the database.
        Only rows with status == "active" are returned (pending_review and rejected are excluded).
        statusactiver`   Zdesc)ro   orderNz"Error getting guardrails from DB: rL   )re   rf   Z	find_manyappendr   r;   rA   rj   )r\   Zguardrails_from_dbZ
guardrailsr[   rK   rL   rL   rM   get_all_guardrails_from_dbE  s   
z,GuardrailRegistry.get_all_guardrails_from_dbc              
      f   z|j jjd|idI dH }|sW dS tdi t|W S  ty2 } z	tdt| d}~ww )z=
        Get a guardrail by its ID from the database
        rc   rn   N!Error getting guardrail from DB: rL   re   rf   Zfind_uniquer   r;   rA   rj   )rT   rc   r\   r[   rK   rL   rL   rM   get_guardrail_by_id_from_db]     z-GuardrailRegistry.get_guardrail_by_id_from_dbc              
      ry   )z?
        Get a guardrail by its name from the database
        rV   rn   Nrz   rL   r{   )rT   rV   r\   r[   rK   rL   rL   rM   get_guardrail_by_name_from_dbo  r}   z/GuardrailRegistry.get_guardrail_by_name_from_dbN)__name__
__module____qualname____doc__rU   rj   r   r   rZ   r   r   rm   rr   rs   staticmethodr   rx   r|   r~   rL   rL   rL   rM   rQ      sZ    

&

#
rQ   c                   @   s  e Zd ZdZdd Z		d dedee ded d	ee fd
dZ	d!de	dede
dee d	ee f
ddZdeded	dfddZded	dfddZd	ee fddZded	ee fddZdeded	efddZ	d!dedee d	ee fddZ	d!dedee d	ee fddZdS )"InMemoryGuardrailHandlerz[
    Class that handles initializing guardrails and adding them to the CallbackManager
    c                 C   s   i | _ 	 i | _d S rR   )IN_MEMORY_GUARDRAILS guardrail_id_to_custom_guardrailrS   rL   rL   rM   rU     s   z!InMemoryGuardrailHandler.__init__Nr[   config_file_path
llm_routerr
   rW   c                 C   s  | dp
tt }||d< || jv rtd | j| S d}|d }td| t|tr7t	di |}n|}d|v rM|d rMt
di |d }||_|jr^|jdr^tt|j|_|jro|jdrott|j|_|j}	|	du rztdt |	}
|
rd	dl}||
}d
|jv r|
|||}n#|
||}nt|	trd|	v r| jtt||	||d}ntd|	 t| d|d |d}|| j|< || j|< |S )z
        Initialize a guardrail from a dictionary and add it to the litellm callback manager

        Returns a Guardrail object if the guardrail is initialized successfully
        rc   z3guardrail_id already exists in IN_MEMORY_GUARDRAILSNr]   zlitellm_params= %scategory_thresholdszos.environ/zguardrail_type is requiredr   r   .)r[   guardrail_typer]   r   zUnsupported guardrail: rV   )rc   rV   r]   rL   )rd   rj   r   uuid4r   r   r2   r:   r;   r   r   r   Zapi_keyr5   r   Zapi_baser[   
ValueErrorr'   inspect	signature
parametersinitialize_custom_guardrailr	   r   r   )rT   r[   r   r   rc   custom_guardrail_callbackZlitellm_params_datar]   Zlakera_category_thresholdsr   Zinitializerr   sigZparsed_guardrailrL   rL   rM   r     sl   







z-InMemoryGuardrailHandler.initialize_guardrailr   r]   c                 C   s   |st dtd| t||d}|j}|du r&td| ddt |j}t	|dr5|j
d	d
}n|r;t|ni }dD ]}	||	d q?|d|d ||d|}
tj|
 |
S )z
        Initialize a Custom Guardrail from a python file or module path

        This initializes it by adding it to the litellm callback manager
        zTGuardrailsAIException - Please pass the config_file_path to initialize_guardrails_v2z!Initializing custom guardrail: %s)r   Nzmode is required for guardrail z* please set mode to one of the following: z, r^   T)Zexclude_none)r[   mode
default_onrV   )rV   Z
event_hookr   rL   )rA   r   r2   r   r   r   r0   r   r   r8   r^   r;   poprX   rY   Zadd_litellm_callback)rT   r[   r   r]   r   Z_guardrail_classr   r   Zextra_paramskeyZ_guardrail_callbackrL   rL   rM   r     s:   
z4InMemoryGuardrailHandler.initialize_custom_guardrailrc   c                 C   s@   || j |< | j|}|rtt|di }|j|d dS dS )z
        Update a guardrail in memory

        - updates the guardrail in memory
        - updates the guardrail params in litellm.callback_manager
        r]   )r]   N)r   r   rd   r	   r   Zupdate_in_memory_litellm_params)rT   rc   r[   r   Zupdated_litellm_paramsrL   rL   rM   update_in_memory_guardrail  s   
	
z3InMemoryGuardrailHandler.update_in_memory_guardrailc                 C   s<   | j |d | j|d}|rtjjtj|dd dS dS )zQ
        Delete a guardrail in memory and remove from litellm callbacks.
        NF)Zcallback_listobjZrequire_self)r   r   r   rX   rY   Z#remove_callback_from_list_by_object	callbacks)rT   rc   r   rL   rL   rM   delete_in_memory_guardrail3  s   
z3InMemoryGuardrailHandler.delete_in_memory_guardrailc                 C   s   t | j S )z/
        List all guardrails in memory
        )r=   r   valuesrS   rL   rL   rM   list_in_memory_guardrailsE  s   z2InMemoryGuardrailHandler.list_in_memory_guardrailsc                 C   s   | j |S )z7
        Get a guardrail by its ID from memory
        )r   rd   )rT   rc   rL   rL   rM   get_guardrail_by_idK  s   z,InMemoryGuardrailHandler.get_guardrail_by_idnew_guardrailc                 C   s  | j |}|du rdS |d|dkrdS |d}|d}t|tr+| n|}t|tr6| n|}i }|duri|durit| t| B }	|	D ]}
||
}||
}||krg||d||
< qPn||krtd||di}|r~td|  t	|dkS )z
        Check if guardrail params or name have changed compared to in-memory version.
        Returns True if params/name changed or guardrail doesn't exist in memory.
        NTrV   r]   )oldnewz'Guardrail params changed. Differences: r   )
r   rd   r:   r   r^   setr>   r   r2   rB   )rT   rc   r   existingZexisting_params
new_paramsZexisting_dictZnew_dictZchanged_fieldsall_keysr   old_valnew_valrL   rL   rM   _has_guardrail_params_changedQ  s@   





z6InMemoryGuardrailHandler._has_guardrail_params_changedc                 C   s>   | d}|std dS || jv r| | | j||dS )z
        Force re-initialization of a guardrail even if it exists in memory.
        Removes old callback from litellm.callbacks and creates fresh instance.
        rc   z2Cannot reinitialize guardrail without guardrail_idNr[   r   )rd   r   r@   r   r   r   )rT   r[   r   rc   rL   rL   rM   reinitialize_guardrail  s   


z/InMemoryGuardrailHandler.reinitialize_guardrailc                 C   sf   | d}|std dS | ||r-| dd}td| d| d | j||d	S | j |S )
z
        Sync a guardrail from DB - initializes if new, re-initializes if changed.
        This is the method to call during DB polling.
        rc   z*Cannot sync guardrail without guardrail_idNrV   UnknownzGuardrail 'z' (ID: z$) params changed, re-initializing...r   )rd   r   r@   r   infor   r   )rT   r[   r   rc   rV   rL   rL   rM   sync_guardrail_from_db  s   

z/InMemoryGuardrailHandler.sync_guardrail_from_db)NNrR   )r   r   r   r   rU   r   r   rj   r   r   r   r   r   r   r   r   r   r   boolr   r   r   rL   rL   rL   rM   r     sv    
Z
6

5
r   )?r6   r,   r   r   typingr   r   r   r   r   r	   rX   r
   Zlitellm._loggingr   Zlitellm._uuidr   Z%litellm.integrations.custom_guardrailr   Z*litellm.litellm_core_utils.safe_json_dumpsr   Z1litellm.proxy.guardrails.guardrail_hooks.grayswanr   r   Zinitialize_grayswanZlitellm.proxy.types_utils.utilsr   Zlitellm.proxy.utilsr   Zlitellm.secret_managers.mainr   Zlitellm.types.guardrailsr   r   r   r   r   Zguardrail_initializersr   r   r   r   r   r   ZBEDROCKvalueZLAKERAZ	LAKERA_V2ZPRESIDIOZHIDE_SECRETSZTOOL_PERMISSIONZGRAYSWANr'   r    rj   __annotations__rN   rP   r<   Z_discovered_initializersrQ   r   ZIN_MEMORY_GUARDRAIL_HANDLERrL   rL   rL   rM   <module>   sL   
  
LA
 8  
7