nemoguardrails.utils

View as Markdown

Module Contents

Classes

NameDescription
CustomDumper-
EnhancedJsonEncoderCustom json encoder to handler dataclass and enum types

Functions

NameDescription
_add_modality_infoAdd modality related information to the action event
_has_property-
_update_action_propertiesUpdate action related even properties and ensure UMIM compliance (very basic)
camelcase_to_snakecaseConverts a CamelCase string to snake_case.
check_object_depthCheck if an object’s nesting depth exceeds the maximum allowed depths
compute_hashReturn the hash of the given text using MD5 if available,
ensure_valid_eventPerforms basic event validation and throws an AssertionError if any of the validators fail.
extract_error_jsonSafely extracts the JSON part from the exception message
get_data_pathHelper to get the path to the data directory.
get_examples_data_pathHelper to get the path to the examples data directory.
get_or_create_event_loopHelper to return the current asyncio loop.
get_railsignore_pathGet railsignore path.
get_railsignore_patternsRetrieve all specified patterns in railsignore.
init_random_seedInit random generator with seed.
is_ignored_by_railsignoreVerify if a filename should be ignored by a railsignore pattern
is_valid_eventPerforms a basic event validation and returns True if the event conforms.
new_event_dictHelper to create a generic event structure.
new_readable_uuidCreates a new uuid with a human readable prefix.
new_uuidHelper to generate new UUID v4.
new_var_uuidCreates a new uuid that is compatible with variable names.
safe_evalSafely evaluate a string to handle unescaped quotes or invalid syntax from the async generate_value action.
snake_to_camelcaseConverts a snake_case string to CamelCase.

Data

MAX_ERROR_MESSAGE_SIZE

MAX_JSON_SIZE

MAX_PARSING_DEPTH

Property

Validator

_ALL_CAP_PATTERN

_FIRST_CAP_PATTERN

_action_to_modality_info

_event_validators

console

secure_random

API

class nemoguardrails.utils.CustomDumper()

Bases: SafeDumper

nemoguardrails.utils.CustomDumper.ignore_aliases(
data
)
nemoguardrails.utils.CustomDumper.increase_indent(
flow = False,
indentless = False
)
nemoguardrails.utils.CustomDumper.represent_data(
data
)
class nemoguardrails.utils.EnhancedJsonEncoder()

Bases: JSONEncoder

Custom json encoder to handler dataclass and enum types

nemoguardrails.utils.EnhancedJsonEncoder.default(
o
)
nemoguardrails.utils._add_modality_info(
event_dict: typing.Dict[str, typing.Any]
) -> None

Add modality related information to the action event

nemoguardrails.utils._has_property(
e: typing.Dict[str, typing.Any],
p: nemoguardrails.utils.Property
) -> bool
nemoguardrails.utils._update_action_properties(
event_dict: typing.Dict[str, typing.Any]
) -> None

Update action related even properties and ensure UMIM compliance (very basic)

nemoguardrails.utils.camelcase_to_snakecase(
name: str
) -> str

Converts a CamelCase string to snake_case.

Parameters:

name
str

The CamelCase string to convert.

Returns: str

The converted snake_case string.

nemoguardrails.utils.check_object_depth(
obj: typing.Any,
current_depth: int = 0
) -> None

Check if an object’s nesting depth exceeds the maximum allowed depths

Parameters:

obj
Any

the object to check

current_depth
intDefaults to 0

current nesting depth

Raises:

  • ValueError: if the object is too deeply nested
nemoguardrails.utils.compute_hash(
text: str
) -> str

Return the hash of the given text using MD5 if available, otherwise use SHA256.

Parameters:

text
str

The input text to hash.

Returns: str

The hexadecimal digest of the hash.

nemoguardrails.utils.ensure_valid_event(
event: typing.Dict[str, typing.Any]
) -> None

Performs basic event validation and throws an AssertionError if any of the validators fail.

nemoguardrails.utils.extract_error_json(
error_message: str
) -> dict

Safely extracts the JSON part from the exception message

Parameters:

error_message
str

The exception message.

Returns: dict

The extracted JSON part as a dictionary, or an error dictionary if extraction fails.

nemoguardrails.utils.get_data_path(
package_name: str,
file_path: str
) -> str

Helper to get the path to the data directory.

nemoguardrails.utils.get_examples_data_path(
file_path: str
) -> str

Helper to get the path to the examples data directory.

nemoguardrails.utils.get_or_create_event_loop()

Helper to return the current asyncio loop.

If one does not exist, it will be created.

nemoguardrails.utils.get_railsignore_path(
path: typing.Optional[str] = None
) -> typing.Optional[pathlib.Path]

Get railsignore path.

Parameters:

path
Optional[str]Defaults to None

The starting path to search for the .railsignore file.

Returns: Optional[Path]

The .railsignore file path, if found.

Raises:

  • FileNotFoundError: If the .railsignore file is not found.
nemoguardrails.utils.get_railsignore_patterns(
railsignore_path: pathlib.Path
) -> typing.Set[str]

Retrieve all specified patterns in railsignore.

Returns: Set[str]

Set[str]: The set of filenames or glob patterns in railsignore

nemoguardrails.utils.init_random_seed(
seed: int
) -> None

Init random generator with seed.

nemoguardrails.utils.is_ignored_by_railsignore(
filename: str,
ignore_patterns: typing.Set[str]
) -> bool

Verify if a filename should be ignored by a railsignore pattern

nemoguardrails.utils.is_valid_event(
event: typing.Dict[str, typing.Any]
) -> bool

Performs a basic event validation and returns True if the event conforms.

nemoguardrails.utils.new_event_dict(
event_type: str,
payload = {}
) -> typing.Dict[str, typing.Any]

Helper to create a generic event structure.

nemoguardrails.utils.new_readable_uuid(
name: str
) -> str

Creates a new uuid with a human readable prefix.

nemoguardrails.utils.new_uuid() -> str

Helper to generate new UUID v4.

In testing mode, it will generate a predictable set of UUIDs to help debugging if random seed was set dependent on the environment variable DEBUG_MODE.

nemoguardrails.utils.new_var_uuid() -> str

Creates a new uuid that is compatible with variable names.

nemoguardrails.utils.safe_eval(
input_value: str
) -> str

Safely evaluate a string to handle unescaped quotes or invalid syntax from the async generate_value action.

Parameters:

input_value
str

The input string to evaluate.

Returns: str

The evaluated and properly formatted string.

Raises:

  • ValueError: If the input cannot be safely evaluated.
nemoguardrails.utils.snake_to_camelcase(
name: str
) -> str

Converts a snake_case string to CamelCase.

Parameters:

name
str

The snake_case string to convert.

Returns: str

The converted CamelCase string.

nemoguardrails.utils.MAX_ERROR_MESSAGE_SIZE = 400
nemoguardrails.utils.MAX_JSON_SIZE = 500
nemoguardrails.utils.MAX_PARSING_DEPTH = 2
nemoguardrails.utils.Property = namedtuple('Property', ['name', 'type'])
nemoguardrails.utils.Validator = namedtuple('Validator', ['description', 'function'])
nemoguardrails.utils._ALL_CAP_PATTERN = re.compile('([a-z0-9])([A-Z])')
nemoguardrails.utils._FIRST_CAP_PATTERN = re.compile('(.)([A-Z][a-z0-9]+)')
nemoguardrails.utils._action_to_modality_info: Dict[str, Tuple[str, str]] = {'UtteranceBotAction': ('bot_speech', 'replace'), 'UtteranceUserAction': ('user_...
nemoguardrails.utils._event_validators = [Validator("Events need to provide 'type'", lambda e: 'type' in e), Validator("E...
nemoguardrails.utils.console = Console()
nemoguardrails.utils.secure_random = random.SystemRandom()