Source code for langchain_community.utilities.opaqueprompts
fromtypingimportDict,Union
[docs]defsanitize(input:Union[str,Dict[str,str]],)->Dict[str,Union[str,Dict[str,str]]]:""" Sanitize input string or dict of strings by replacing sensitive data with placeholders. It returns the sanitized input string or dict of strings and the secure context as a dict following the format: { "sanitized_input": <sanitized input string or dict of strings>, "secure_context": <secure context> } The secure context is a bytes object that is needed to de-sanitize the response from the LLM. Args: input: Input string or dict of strings. Returns: Sanitized input string or dict of strings and the secure context as a dict following the format: { "sanitized_input": <sanitized input string or dict of strings>, "secure_context": <secure context> } The `secure_context` needs to be passed to the `desanitize` function. Raises: ValueError: If the input is not a string or dict of strings. ImportError: If the `opaqueprompts` Python package is not installed. """try:importopaquepromptsasopexceptImportError:raiseImportError("Could not import the `opaqueprompts` Python package, ""please install it with `pip install opaqueprompts`.")ifisinstance(input,str):# the input could be a string, so we sanitize the stringsanitize_response:op.SanitizeResponse=op.sanitize([input])return{"sanitized_input":sanitize_response.sanitized_texts[0],"secure_context":sanitize_response.secure_context,}ifisinstance(input,dict):# the input could be a dict[string, string], so we sanitize the valuesvalues=list()# get the values from the dictforkeyininput:values.append(input[key])# sanitize the valuessanitize_values_response:op.SanitizeResponse=op.sanitize(values)# reconstruct the dict with the sanitized valuessanitized_input_values=sanitize_values_response.sanitized_textsidx=0sanitized_input=dict()forkeyininput:sanitized_input[key]=sanitized_input_values[idx]idx+=1return{"sanitized_input":sanitized_input,"secure_context":sanitize_values_response.secure_context,}raiseValueError(f"Unexpected input type {type(input)}")
[docs]defdesanitize(sanitized_text:str,secure_context:bytes)->str:""" Restore the original sensitive data from the sanitized text. Args: sanitized_text: Sanitized text. secure_context: Secure context returned by the `sanitize` function. Returns: De-sanitized text. """try:importopaquepromptsasopexceptImportError:raiseImportError("Could not import the `opaqueprompts` Python package, ""please install it with `pip install opaqueprompts`.")desanitize_response:op.DesanitizeResponse=op.desanitize(sanitized_text,secure_context)returndesanitize_response.desanitized_text