Source code for langchain.utilities.opaqueprompts
from typing import Dict, Union
[docs]def sanitize(
    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.
    """
    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):