
    3fi                         d Z ddlZ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mZ ddlmZ  ed      Z ej"                  e      Z G d d	e      Z G d
 de      Zy)a  
Langchain Runnables to screen user prompt and/or model response using Google
Cloud Model Armor.

Prerequisites
-------------

Before using Model Armor Runnables, ensure the following steps are completed:

- Select or create a Google Cloud Platform project.
    - You can do this at: https://console.cloud.google.com/project

- Enable billing for your project.
    - Instructions: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project

- Enable the Model Armor API in your GCP project.
    - See: https://cloud.google.com/security-command-center/docs/get-started-model-armor

- Grant the `modelarmor.user` IAM role to any user or service account that will use
    the Model Armor runnables.

- Authentication:
    - Your application or environment must be authenticated and have the necessary
        permissions to access the Model Armor service.
    - You can authenticate using several methods described here: https://googleapis.dev/python/google-api-core/latest/auth.html

- Create Model Armor Template:
    - You must create a Model Armor template for prompt and response sanitization. You
        may use a single template for both, or separate templates as needed.
    - Refer to the guide: Create and manage Model Armor templates (https://cloud.google.com/security-command-center/docs/get-started-model-armor)
    - The Template IDs must be provided when initializing the respective runnables.
    - To manage Model Armor templates, the `modelarmor.admin` IAM role is required.
    N)AnyOptionalTypeVarcast)DataItemModelArmorClientSanitizeModelResponseRequestSanitizeUserPromptRequest)RunnableConfig)ModelArmorSanitizeBaseRunnableTc                   >    e Zd ZdZ	 	 d	dedee   dee   dedef
dZ	y)
 ModelArmorSanitizePromptRunnablez6`Runnable` to sanitize user prompts using Model Armor.Ninputconfig	fail_openkwargsreturnc                 t   | j                  |      }t        j                  d| j                         t	        t
        | j                        j                  t        t        j                  t	        t        | j                        t	        t        | j                        t	        t        | j                              t        |                  }|j                  }||n| j                  }| j!                  |||      s:|r-t        j                  d|       t        j#                  d       |S t%        d      |S )	ad  Sanitize a user prompt using Model Armor.

        Args:
            input: The user prompt to sanitize. Can be `str`, `BaseMessage`,
                `BasePromptTemplate`, list of messages, or any object with
                string conversion.
            config: A config to use when invoking the `Runnable`.
            fail_open: If `True`, allows unsafe prompts to pass through.

        Returns:
            Same type as input (original input is always returned).

        Raises:
            ValueError: If the prompt is flagged as unsafe by Model Armor and
                `fail_open` is `False`.
        z8Starting prompt sanitization request with template id %stext)nameuser_prompt_datarequestr   z;Found following unsafe prompt findings from Model Armor: %sz6Continuing for unsafe prompt as fail_open flag is truez(Prompt flagged as unsafe by Model Armor.)_extract_inputloggerinfotemplate_idr   r   clientsanitize_user_promptr
   template_pathstrprojectlocationr   sanitization_resultr   evaluatewarning
ValueError)	selfr   r   r   r   contentresultsanitization_findingseffective_fail_opens	            m/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_google_community/model_armor/runnable.pyinvokez'ModelArmorSanitizePromptRunnable.invoke:   s   . %%e,F	

 &4II-%33dll+dmm,d../
 "*w!7 J 	
 !' : : ,5+@idnn}}W&;F}K"Q) WX  !!KLL    NN
__name__
__module____qualname____doc__r   r   r   boolr   r1    r2   r0   r   r   7   sK    @
 ,0$(	77 (7 D>	7
 7 
7r2   r   c                   >    e Zd ZdZ	 	 d	dedee   dee   dedef
dZ	y)
"ModelArmorSanitizeResponseRunnablez7`Runnable` to sanitize LLM responses using Model Armor.Nr   r   r   r   r   c                 h   | j                  |      }t        j                  d| j                         t	        t
        | j                        j                  t        t        j                  t	        t        | j                        t	        t        | j                        t	        t        | j                              t        |                  }|j                  }| j                  |||      sD| j                   r-t        j                  d|       t        j#                  d       |S t%        d      |S )	aG  Sanitize an LLM response using Model Armor.

        Args:
            input: The model response to sanitize. Can be `str`, `BaseMessage`,
                list of messages, or any object with string conversion.
            config: A config to use when invoking the `Runnable`.
            fail_open: If `True`, allows unsafe responses to pass through.

        Returns:
            Same type as input (original input is always returned).

        Raises:
            ValueError: If the response is flagged as unsafe by Model Armor
                and `fail_open` is `False`.
        z@Starting model response sanitization request with template id %sr   )r   model_response_datar   r   z=Found following unsafe response findings from Model Armor: %sz8Continuing for unsafe response as fail open flag is truez*Response flagged as unsafe by Model Armor.)r   r   r   r    r   r   r!   sanitize_model_responser	   r#   r$   r%   r&   r   r'   r(   r   r)   r*   )r+   r   r   r   r   r,   r-   r.   s           r0   r1   z)ModelArmorSanitizeResponseRunnable.invokew   s   , %%e,N	

 &4LL0%33dll+dmm,d../
 %-'$: M 	
 !' : :}}W&;F}K~~S) N  !!MNNr2   r3   r4   r:   r2   r0   r<   r<   t   sK    A
 ,0$(	55 (5 D>	5
 5 
5r2   r<   )r8   loggingtypingr   r   r   r   google.cloud.modelarmor_v1r   r   r	   r
   langchain_core.runnables.configr   4langchain_google_community.model_armor.base_runnabler   r   	getLoggerr5   r   r   r<   r:   r2   r0   <module>rF      sb    D  / /  ; CL			8	$:'E :z8)G 8r2   