> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nemo/guardrails/llms.txt.
> For full documentation content, see https://docs.nvidia.com/nemo/guardrails/llms-full.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.nvidia.com/nemo/guardrails/_mcp/server.

# nemoguardrails.utils

## Module Contents

### Classes

| Name                                                               | Description                                             |
| ------------------------------------------------------------------ | ------------------------------------------------------- |
| [`CustomDumper`](#nemoguardrails-utils-CustomDumper)               | -                                                       |
| [`EnhancedJsonEncoder`](#nemoguardrails-utils-EnhancedJsonEncoder) | Custom json encoder to handler dataclass and enum types |

### Functions

| Name                                                                           | Description                                                                                                  |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| [`_add_modality_info`](#nemoguardrails-utils-_add_modality_info)               | Add modality related information to the action event                                                         |
| [`_has_property`](#nemoguardrails-utils-_has_property)                         | -                                                                                                            |
| [`_update_action_properties`](#nemoguardrails-utils-_update_action_properties) | Update action related even properties and ensure UMIM compliance (very basic)                                |
| [`camelcase_to_snakecase`](#nemoguardrails-utils-camelcase_to_snakecase)       | Converts a CamelCase string to snake\_case.                                                                  |
| [`check_object_depth`](#nemoguardrails-utils-check_object_depth)               | Check if an object's nesting depth exceeds the maximum allowed depths                                        |
| [`compute_hash`](#nemoguardrails-utils-compute_hash)                           | Return the hash of the given text using MD5 if available,                                                    |
| [`ensure_valid_event`](#nemoguardrails-utils-ensure_valid_event)               | Performs basic event validation and throws an AssertionError if any of the validators fail.                  |
| [`extract_error_json`](#nemoguardrails-utils-extract_error_json)               | Safely extracts the JSON part from the exception message                                                     |
| [`get_data_path`](#nemoguardrails-utils-get_data_path)                         | Helper to get the path to the data directory.                                                                |
| [`get_examples_data_path`](#nemoguardrails-utils-get_examples_data_path)       | Helper to get the path to the examples data directory.                                                       |
| [`get_or_create_event_loop`](#nemoguardrails-utils-get_or_create_event_loop)   | Helper to return the current asyncio loop.                                                                   |
| [`get_railsignore_path`](#nemoguardrails-utils-get_railsignore_path)           | Get railsignore path.                                                                                        |
| [`get_railsignore_patterns`](#nemoguardrails-utils-get_railsignore_patterns)   | Retrieve all specified patterns in railsignore.                                                              |
| [`init_random_seed`](#nemoguardrails-utils-init_random_seed)                   | Init random generator with seed.                                                                             |
| [`is_ignored_by_railsignore`](#nemoguardrails-utils-is_ignored_by_railsignore) | Verify if a filename should be ignored by a railsignore pattern                                              |
| [`is_valid_event`](#nemoguardrails-utils-is_valid_event)                       | Performs a basic event validation and returns True if the event conforms.                                    |
| [`new_event_dict`](#nemoguardrails-utils-new_event_dict)                       | Helper to create a generic event structure.                                                                  |
| [`new_readable_uuid`](#nemoguardrails-utils-new_readable_uuid)                 | Creates a new uuid with a human readable prefix.                                                             |
| [`new_uuid`](#nemoguardrails-utils-new_uuid)                                   | Helper to generate new UUID v4.                                                                              |
| [`new_var_uuid`](#nemoguardrails-utils-new_var_uuid)                           | Creates a new uuid that is compatible with variable names.                                                   |
| [`safe_eval`](#nemoguardrails-utils-safe_eval)                                 | Safely evaluate a string to handle unescaped quotes or invalid syntax from the async generate\_value action. |
| [`snake_to_camelcase`](#nemoguardrails-utils-snake_to_camelcase)               | Converts a snake\_case string to CamelCase.                                                                  |

### Data

[`MAX_ERROR_MESSAGE_SIZE`](#nemoguardrails-utils-MAX_ERROR_MESSAGE_SIZE)

[`MAX_JSON_SIZE`](#nemoguardrails-utils-MAX_JSON_SIZE)

[`MAX_PARSING_DEPTH`](#nemoguardrails-utils-MAX_PARSING_DEPTH)

[`Property`](#nemoguardrails-utils-Property)

[`Validator`](#nemoguardrails-utils-Validator)

[`_ALL_CAP_PATTERN`](#nemoguardrails-utils-_ALL_CAP_PATTERN)

[`_FIRST_CAP_PATTERN`](#nemoguardrails-utils-_FIRST_CAP_PATTERN)

[`_action_to_modality_info`](#nemoguardrails-utils-_action_to_modality_info)

[`_event_validators`](#nemoguardrails-utils-_event_validators)

[`console`](#nemoguardrails-utils-console)

[`secure_random`](#nemoguardrails-utils-secure_random)

### API

```python
class nemoguardrails.utils.CustomDumper()
```

**Bases:** `SafeDumper`

```python
nemoguardrails.utils.CustomDumper.ignore_aliases(
    data
)
```

```python
nemoguardrails.utils.CustomDumper.increase_indent(
    flow = False,
    indentless = False
)
```

```python
nemoguardrails.utils.CustomDumper.represent_data(
    data
)
```

```python
class nemoguardrails.utils.EnhancedJsonEncoder()
```

**Bases:** `JSONEncoder`

Custom json encoder to handler dataclass and enum types

```python
nemoguardrails.utils.EnhancedJsonEncoder.default(
    o
)
```

```python
nemoguardrails.utils._add_modality_info(
    event_dict: typing.Dict[str, typing.Any]
) -> None
```

Add modality related information to the action event

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

```python
nemoguardrails.utils._update_action_properties(
    event_dict: typing.Dict[str, typing.Any]
) -> None
```

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

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

Converts a CamelCase string to snake\_case.

**Parameters:**

The CamelCase string to convert.

**Returns:** `str`

The converted snake\_case string.

```python
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:**

the object to check

current nesting depth

**Raises:**

* `ValueError`: if the object is too deeply nested

```python
nemoguardrails.utils.compute_hash(
    text: str
) -> str
```

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

**Parameters:**

The input text to hash.

**Returns:** `str`

The hexadecimal digest of the hash.

```python
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.

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

Safely extracts the JSON part from the exception message

**Parameters:**

The exception message.

**Returns:** `dict`

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

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

Helper to get the path to the data directory.

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

Helper to get the path to the examples data directory.

```python
nemoguardrails.utils.get_or_create_event_loop()
```

Helper to return the current asyncio loop.

If one does not exist, it will be created.

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

Get railsignore path.

**Parameters:**

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.

```python
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

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

Init random generator with seed.

```python
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

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

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

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

Helper to create a generic event structure.

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

Creates a new uuid with a human readable prefix.

```python
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.

```python
nemoguardrails.utils.new_var_uuid() -> str
```

Creates a new uuid that is compatible with variable names.

```python
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:**

The input string to evaluate.

**Returns:** `str`

The evaluated and properly formatted string.

**Raises:**

* `ValueError`: If the input cannot be safely evaluated.

```python
nemoguardrails.utils.snake_to_camelcase(
    name: str
) -> str
```

Converts a snake\_case string to CamelCase.

**Parameters:**

The snake\_case string to convert.

**Returns:** `str`

The converted CamelCase string.

```python
nemoguardrails.utils.MAX_ERROR_MESSAGE_SIZE = 400
```

```python
nemoguardrails.utils.MAX_JSON_SIZE = 500
```

```python
nemoguardrails.utils.MAX_PARSING_DEPTH = 2
```

```python
nemoguardrails.utils.Property = namedtuple('Property', ['name', 'type'])
```

```python
nemoguardrails.utils.Validator = namedtuple('Validator', ['description', 'function'])
```

```python
nemoguardrails.utils._ALL_CAP_PATTERN = re.compile('([a-z0-9])([A-Z])')
```

```python
nemoguardrails.utils._FIRST_CAP_PATTERN = re.compile('(.)([A-Z][a-z0-9]+)')
```

```python
nemoguardrails.utils._action_to_modality_info: Dict[str, Tuple[str, str]] = {'UtteranceBotAction': ('bot_speech', 'replace'), 'UtteranceUserAction': ('user_...
```

```python
nemoguardrails.utils._event_validators = [Validator("Events need to provide 'type'", lambda e: 'type' in e), Validator("E...
```

```python
nemoguardrails.utils.console = Console()
```

```python
nemoguardrails.utils.secure_random = random.SystemRandom()
```