Source code for langchain_community.utilities.opaqueprompts

from typing import Dict, Union


[docs]def sanitize( input: Union[str, Dict[str, str]], ) -> Dict[str, Union[str, Dict[str, str]]]: """对输入字符串或字符串字典进行清理,将敏感数据替换为占位符。 它返回清理后的输入字符串或字符串字典,以及作为字典的安全上下文,格式如下: { "sanitized_input": <清理后的输入字符串或字符串字典>, "secure_context": <安全上下文> } 安全上下文是一个字节对象,需要用于从LLM的响应中去除清理。 参数: input: 输入字符串或字符串字典。 返回: 清理后的输入字符串或字符串字典,以及作为字典的安全上下文,格式如下: { "sanitized_input": <清理后的输入字符串或字符串字典>, "secure_context": <安全上下文> } 需要将`secure_context`传递给`desanitize`函数。 抛出: ValueError: 如果输入不是字符串或字符串字典。 ImportError: 如果未安装`opaqueprompts` Python包。 """ try: import opaqueprompts as op except ImportError: raise ImportError( "Could not import the `opaqueprompts` Python package, " "please install it with `pip install opaqueprompts`." ) if isinstance(input, str): # the input could be a string, so we sanitize the string sanitize_response: op.SanitizeResponse = op.sanitize([input]) return { "sanitized_input": sanitize_response.sanitized_texts[0], "secure_context": sanitize_response.secure_context, } if isinstance(input, dict): # the input could be a dict[string, string], so we sanitize the values values = list() # get the values from the dict for key in input: values.append(input[key]) # sanitize the values sanitize_values_response: op.SanitizeResponse = op.sanitize(values) # reconstruct the dict with the sanitized values sanitized_input_values = sanitize_values_response.sanitized_texts idx = 0 sanitized_input = dict() for key in input: sanitized_input[key] = sanitized_input_values[idx] idx += 1 return { "sanitized_input": sanitized_input, "secure_context": sanitize_values_response.secure_context, } raise ValueError(f"Unexpected input type {type(input)}")
[docs]def desanitize(sanitized_text: str, secure_context: bytes) -> str: """从经过处理的文本中恢复原始的敏感数据。 参数: sanitized_text: 经过处理的文本。 secure_context: `sanitize` 函数返回的安全上下文。 返回: 反处理后的文本。 """ try: import opaqueprompts as op except ImportError: raise ImportError( "Could not import the `opaqueprompts` Python package, " "please install it with `pip install opaqueprompts`." ) desanitize_response: op.DesanitizeResponse = op.desanitize( sanitized_text, secure_context ) return desanitize_response.desanitized_text