Skip to content

feat(rails): declare and validate rail dependencies - #2195

Open
Pouyanpi wants to merge 9 commits into
developfrom
pouyanpi/rail-library-requirements
Open

feat(rails): declare and validate rail dependencies#2195
Pouyanpi wants to merge 9 commits into
developfrom
pouyanpi/rail-library-requirements

Conversation

@Pouyanpi

@Pouyanpi Pouyanpi commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Description

Make rail runtime dependencies explicit in manifests and validate the requirements
of configured rails without importing optional packages or contacting services.

Add typed Python package declarations, structured validation results, dependency
errors, and nemoguardrails rails validate. Static validation checks installed
distribution versions, environment markers, and required environment-variable
names; --runtime additionally verifies declared imports. Service and model
requirements remain declared but unverified.

Migrate built-in rail manifests and lazy runtime imports to the new contract.
Remove rail-specific installation extras so users install each rail's packages
directly. Add the lightweight packaging core dependency for standards-compliant
PEP 440 version and PEP 508 marker validation.

Adds

uv run nemoguardrails rails validate --config=./examples/configs/nemoguards
content_safety:
  [OK] python_package: fast-langdetect>=1 (installed (1.0.1))
jailbreak_detection:
  [WARNING] python_package: transformers>=4.35 (not installed)
  [WARNING] python_package: torch>=2 (not installed)
  [OK] python_package: huggingface-hub (installed (1.16.1))
  [OK] environment_variable: NVIDIA_API_KEY (set)
  [OK] environment_variable: HF_TOKEN (set)
  [INFO] environment_variable: HF_HOME (optional and not set)
  [INFO] environment_variable: HF_HUB_OFFLINE (optional and not set)
  [INFO] environment_variable: JAILBREAK_CHECK_DEVICE (optional and not set)
  [INFO] environment_variable: EMBEDDING_CLASSIFIER_PATH (optional and not set)
  [INFO] service: NVIDIA NIM (declared; not verified)
topic_safety:
  [INFO] model: topic_control (declared; not verified)
Install missing or incompatible packages with: pip install 'torch>=2' 'transformers>=4.35'
uv run nemoguardrails rails validate --config=./examples/configs/gliner
gliner:
  [OK] environment_variable: NVIDIA_API_KEY (set)
  [INFO] service: GLiNER endpoint (declared; not verified)

Impact

  • Configured rails report missing or incompatible dependencies before execution.
  • Optional dependencies remain lazily imported and static validation has no
    provider, model, or network side effects.
  • Missing required rail packages raise actionable RailDependencyError messages.
  • Rail-specific packages no longer become part of the aggregate all extra.

Verification

AI Assistance

  • No AI tools were used.
  • AI tools were used; a human reviewed and can explain every change (tool: ___).

Checklist

  • I've read the CONTRIBUTING guidelines.
  • This PR links to a triaged issue assigned to me.
  • My PR title follows the project commit convention.
  • I've updated the documentation if applicable.
  • I've added tests if applicable.
  • I've noted any verification beyond CI and any checks I couldn't run.
  • I did not update generated changelog files manually.
  • I addressed all CodeRabbit, Greptile, and other review comments, or replied with why no change is needed.
  • @mentions of the person or team responsible for reviewing proposed changes.

Summary by CodeRabbit

  • New Features

    • Added rails validate CLI command to check configured rail dependencies, environment variables, and runtime imports.
    • Validation now reports clear statuses and installation guidance for required and optional packages.
    • Rail-owned action results are excluded from generated conversation history.
  • Documentation

    • Updated installation guidance, optional extras, rail-specific dependencies, and validation instructions.
    • Refreshed setup steps and supported versions for integrations including Presidio, Cleanlab, GCP moderation, jailbreak detection, and content safety.
  • Bug Fixes

    • Improved error messages and handling when optional rail dependencies are missing or incompatible.

@Pouyanpi Pouyanpi added this to the v0.24.0 milestone Jul 21, 2026
@Pouyanpi Pouyanpi self-assigned this Jul 21, 2026
@github-actions github-actions Bot added status: needs triage New issues that have not yet been reviewed or categorized. size: L labels Jul 21, 2026
@Pouyanpi Pouyanpi removed the status: needs triage New issues that have not yet been reviewed or categorized. label Jul 21, 2026
@Pouyanpi Pouyanpi added the status: triaged Triaged by a maintainer; eligible for automated review (CodeRabbit/Greptile). label Jul 21, 2026
@greptile-apps

greptile-apps Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes rail runtime dependencies explicit by introducing a typed PythonPackage model with PEP 440/508 validation, wiring manifests for all built-in rails, and adding a nemoguardrails rails validate CLI command that reports package, environment-variable, service, and model requirements without importing optional packages or contacting services.

  • PythonPackage + RailRequirements: new structured declarations with SpecifierSet/Marker field validators, a uniqueness guard, and required flag that drives ERROR vs WARNING status in reports.
  • manifests/validation.py: static validation reads distribution metadata only; --runtime additionally calls importlib.import_module; require_python_package and raise_for_missing_package replace bare try/except ImportError blocks across all library action files.
  • pyproject.toml: rail-specific extras (sdd, gcp, jailbreak, multilingual) are removed; packaging>=23.0 is promoted to a core dependency.

Confidence Score: 5/5

Safe to merge; the new validation path is purely additive and all existing lazy-import patterns are replaced consistently.

The core logic in validation.py is straightforward and well-covered by the new test suite. The library action migrations are mechanical replacements of try/except blocks with typed helpers. The only finding is a minor normalization gap in the duplicate-package detector that does not affect the built-in rails or runtime behavior.

nemoguardrails/manifests/manifest.py — the _python_packages_must_be_unique validator normalization logic.

Important Files Changed

Filename Overview
nemoguardrails/manifests/manifest.py Adds PythonPackage model with PEP 440/508 validators and integrates it into RailRequirements; uniqueness normalization misses dot-separated package names.
nemoguardrails/manifests/validation.py New validation module; static/runtime package checks, env-var checks, and report aggregation are correctly implemented with appropriate status distinctions.
nemoguardrails/cli/rails.py New CLI sub-command wiring validated rail results to stdout with correct exit-code semantics.
nemoguardrails/manifests/catalog.py Adds config-owner index built during catalog construction; owner_for_config_key lookup is consistent with existing flow-owner pattern.
nemoguardrails/library/sensitive_data_detection/actions.py Migrates presidio/spacy lazy imports to require_python_package; _load_presidio caching is correct and None-guard removals are clean.
nemoguardrails/library/injection_detection/actions.py Replaces module-level yara sentinel with lru_cache'd _load_yara(); stale _check_yara_available() fully removed.
nemoguardrails/library/jailbreak_detection/actions.py Converts silent ImportError suppression into actionable RailDependencyError; removes jailbreak_result=False fallback for missing deps.
nemoguardrails/library/hf_classifier/backends.py Switches pipeline loading to require_python_package + raise_for_missing_package for torch.
tests/rails/llm/test_rail_requirements.py Comprehensive test coverage for static/runtime validation, env-var checks, transitive import failures, and configured-manifest selection.
pyproject.toml Adds packaging>=23.0 as core dependency; removes rail-specific extras and cleans them from the all aggregate.

Reviews (7): Last reviewed commit: "test(rails): isolate unknown validator e..." | Re-trigger Greptile

Comment thread nemoguardrails/library/guardrails_ai/actions.py
Comment thread nemoguardrails/manifests/validation.py Outdated
Comment thread nemoguardrails/manifests/validation.py
@Pouyanpi
Pouyanpi force-pushed the pouyanpi/rail-library-stack-5-lazy-actions branch from 29e08df to 08d9c5c Compare July 22, 2026 07:13
@Pouyanpi
Pouyanpi force-pushed the pouyanpi/rail-library-requirements branch 2 times, most recently from b233b7d to 7eed276 Compare July 22, 2026 08:16
@Pouyanpi
Pouyanpi force-pushed the pouyanpi/rail-library-stack-5-lazy-actions branch 2 times, most recently from fe1b46c to 7e708b4 Compare July 22, 2026 13:39
@Pouyanpi
Pouyanpi force-pushed the pouyanpi/rail-library-requirements branch from 7eed276 to 02e7a2a Compare July 22, 2026 13:39
Base automatically changed from pouyanpi/rail-library-stack-5-lazy-actions to develop July 23, 2026 10:01
Pouyanpi added 9 commits July 23, 2026 12:13
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
Signed-off-by: Pouyanpi <13303554+Pouyanpi@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds declarative rail dependency modeling and validation, migrates catalog rails to structured package requirements, introduces rails validate, enables lazy manifest action loading, marks rail action events, and filters them from history. Documentation, packaging metadata, and tests are updated accordingly.

Changes

Rail requirements and manifest integration

Layer / File(s) Summary
Requirement model and validation API
nemoguardrails/manifests/*, tests/manifests/*, tests/rails/llm/*
Adds PythonPackage, validation reports, dependency errors, configured-manifest discovery, package checks, environment checks, and duplicate requirement validation with comprehensive tests.
Rail manifests and runtime dependency loading
nemoguardrails/library/*, docs/configure-rails/*, tests/test_*
Moves rail-specific dependencies into structured manifest requirements and loads optional integrations lazily through shared dependency helpers.
Lazy action dispatch and history metadata
nemoguardrails/actions/*, nemoguardrails/colang/*, nemoguardrails/llm/filters.py, tests/test_action_dispatcher.py, tests/v2_x/*
Adds manifest-aware lazy action resolution, propagates is_rail_action through action events, and excludes rail-action results from generated history.
Validation CLI, packaging, and usage documentation
nemoguardrails/cli/*, docs/getting-started/*, docs/reference/cli/*, pyproject.toml, CONTRIBUTING.md, tests/cli/*, tests/test_rail_packaging.py
Registers rails validate, documents static and runtime validation, updates optional extras, and verifies rail packages are not packaged as extras.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant RailsConfig
  participant RailCatalog
  participant validate_rail_requirements
  participant RailValidationReport
  CLI->>RailsConfig: load --config
  CLI->>RailCatalog: resolve configured rail manifests
  CLI->>validate_rail_requirements: validate static or runtime requirements
  validate_rail_requirements->>RailValidationReport: aggregate checks and install guidance
  RailValidationReport-->>CLI: print statuses and exit code
Loading
sequenceDiagram
  participant RuntimeV2_x
  participant ActionDispatcher
  participant ActionFinished
  participant co_v2
  RuntimeV2_x->>ActionDispatcher: resolve and execute manifest action
  ActionDispatcher-->>RuntimeV2_x: action result and ownership status
  RuntimeV2_x->>ActionFinished: add is_rail_action marker
  ActionFinished->>co_v2: process event
  co_v2-->>RuntimeV2_x: omit rail-action output from history
Loading

Possibly related PRs

Suggested reviewers: tgasser-nv

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.61% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Results For Major Changes ⚠️ Warning Major new CLI/validation/refactor PR, but the description leaves the Verification section empty and gives no actual test results or testing notes. Add a brief Verification section with test run results or what was tested (unit/docs/manual), plus any checks that could not be run.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main change: declaring rail dependencies and adding validation support.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pouyanpi/rail-library-requirements

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
nemoguardrails/manifests/manifest.py (1)

333-339: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Use packaging.utils.canonicalize_name for the duplicate check.

The manual normalization (lower().replace("_", "-")) doesn't fully implement PEP 503: it misses dots, so distributions like ruamel.yaml vs ruamel-yaml would not be flagged as duplicates. packaging is already a dependency here.

♻️ Proposed fix
+from packaging.utils import canonicalize_name
+
 `@model_validator`(mode="after")
 def _python_packages_must_be_unique(self) -> "RailRequirements":
-    normalized = [package.distribution.lower().replace("_", "-") for package in self.python_packages]
+    normalized = [canonicalize_name(package.distribution) for package in self.python_packages]
     duplicates = sorted({name for name in normalized if normalized.count(name) > 1})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nemoguardrails/manifests/manifest.py` around lines 333 - 339, Update
RailRequirements._python_packages_must_be_unique to normalize each distribution
with packaging.utils.canonicalize_name instead of the manual
lower().replace("_", "-") logic, preserving the existing duplicate detection and
error behavior.
nemoguardrails/manifests/validation.py (1)

90-104: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

RailDependencyError message omits the environment marker; duplicates _package_requirement.

RailDependencyError.__init__ re-implements the distribution+version string without the marker suffix that _package_requirement (defined just below) already produces. This can suggest an install command that ignores a package's actual applicability constraint (e.g. python_version < '3.13'), and duplicates logic that should be shared.

♻️ Proposed fix
 class RailDependencyError(ImportError):
     def __init__(self, rail_name: str, requirement: PythonPackage) -> None:
         self.rail_name = rail_name
         self.requirement = requirement
-        package = requirement.distribution + (requirement.version or "")
+        package = _package_requirement(requirement)
         super().__init__(
             f"Rail {rail_name!r} requires Python package {package!r}. Install it with: pip install '{package}'"
         )
+
+
+def _package_requirement(requirement: PythonPackage) -> str:
+    package = requirement.distribution + (requirement.version or "")
+    if requirement.marker is not None:
+        package = f"{package}; {Marker(requirement.marker)}"
+    return package

(Move _package_requirement above RailDependencyError, or forward-declare, to call it from __init__.)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nemoguardrails/manifests/validation.py` around lines 90 - 104, Update
RailDependencyError.__init__ to build the package string via
_package_requirement(requirement), ensuring the exception message and install
command include any environment marker. Move or otherwise make
_package_requirement available before RailDependencyError uses it, and remove
the duplicated distribution/version formatting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/getting-started/installation-guide.mdx`:
- Line 117: Update the catalog rails installation note in the installation guide
to replace “NeMo Guardrails extras” with the canonical wording “extras for the
NVIDIA NeMo Guardrails library,” while preserving the existing guidance about
installing rail-specific Python packages directly.

In `@tests/test_guardrails_ai_e2e_actions.py`:
- Around line 253-255: Configure the patched _load_guard_class in the
validate_guardrails_ai test to raise the expected lookup error via side_effect,
ensuring the unknown validator path still raises GuardrailsAIValidationError.
Keep the existing pytest.raises assertion and validation arguments unchanged.

---

Nitpick comments:
In `@nemoguardrails/manifests/manifest.py`:
- Around line 333-339: Update RailRequirements._python_packages_must_be_unique
to normalize each distribution with packaging.utils.canonicalize_name instead of
the manual lower().replace("_", "-") logic, preserving the existing duplicate
detection and error behavior.

In `@nemoguardrails/manifests/validation.py`:
- Around line 90-104: Update RailDependencyError.__init__ to build the package
string via _package_requirement(requirement), ensuring the exception message and
install command include any environment marker. Move or otherwise make
_package_requirement available before RailDependencyError uses it, and remove
the duplicated distribution/version formatting.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 24a61993-561b-4731-827f-e7a6fd1eb5b2

📥 Commits

Reviewing files that changed from the base of the PR and between 936cb9c and 02e7a2a.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (48)
  • CONTRIBUTING.md
  • docs/configure-rails/guardrail-catalog/agentic-security.mdx
  • docs/configure-rails/guardrail-catalog/community/cleanlab.mdx
  • docs/configure-rails/guardrail-catalog/community/gcp-text-moderations.mdx
  • docs/configure-rails/guardrail-catalog/community/presidio.mdx
  • docs/configure-rails/guardrail-catalog/content-safety.mdx
  • docs/configure-rails/guardrail-catalog/jailbreak-protection.mdx
  • docs/getting-started/installation-guide.mdx
  • docs/getting-started/tutorials/jailbreak-detection-heuristics.mdx
  • docs/reference/cli/index.mdx
  • nemoguardrails/actions/action_dispatcher.py
  • nemoguardrails/cli/__init__.py
  • nemoguardrails/cli/rails.py
  • nemoguardrails/colang/runtime.py
  • nemoguardrails/colang/v2_x/runtime/runtime.py
  • nemoguardrails/library/cleanlab/actions.py
  • nemoguardrails/library/cleanlab/rail.py
  • nemoguardrails/library/content_safety/rail.py
  • nemoguardrails/library/gcp_moderate_text/actions.py
  • nemoguardrails/library/gcp_moderate_text/rail.py
  • nemoguardrails/library/guardrails_ai/actions.py
  • nemoguardrails/library/guardrails_ai/rail.py
  • nemoguardrails/library/hf_classifier/backends.py
  • nemoguardrails/library/hf_classifier/rail.py
  • nemoguardrails/library/injection_detection/actions.py
  • nemoguardrails/library/injection_detection/rail.py
  • nemoguardrails/library/jailbreak_detection/actions.py
  • nemoguardrails/library/jailbreak_detection/rail.py
  • nemoguardrails/library/sensitive_data_detection/actions.py
  • nemoguardrails/library/sensitive_data_detection/rail.py
  • nemoguardrails/llm/filters.py
  • nemoguardrails/manifests/__init__.py
  • nemoguardrails/manifests/catalog.py
  • nemoguardrails/manifests/manifest.py
  • nemoguardrails/manifests/validation.py
  • pyproject.toml
  • tests/cli/test_cli_main.py
  • tests/manifests/test_manifest.py
  • tests/rails/llm/test_rail_requirements.py
  • tests/test_action_dispatcher.py
  • tests/test_filters.py
  • tests/test_guardrails_ai_actions.py
  • tests/test_guardrails_ai_e2e_actions.py
  • tests/test_injection_detection.py
  • tests/test_jailbreak_actions.py
  • tests/test_jailbreak_nim.py
  • tests/test_rail_packaging.py
  • tests/v2_x/test_run_actions.py


### Rail Dependencies

Catalog rails declare their own Python package, model, service, and environment-variable requirements. Rail-specific Python packages are not included in the NeMo Guardrails extras. Install them directly by following the setup instructions in the [Guardrail Catalog](/configure-guardrails/guardrail-catalog).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the canonical package name.

Replace “NeMo Guardrails extras” with wording that refers to “the NVIDIA NeMo Guardrails library,” for example: “Rail-specific Python packages are not included in extras for the NVIDIA NeMo Guardrails library.”

As per coding guidelines, “Refer to this package as ‘the NVIDIA NeMo Guardrails library’.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/getting-started/installation-guide.mdx` at line 117, Update the catalog
rails installation note in the installation guide to replace “NeMo Guardrails
extras” with the canonical wording “extras for the NVIDIA NeMo Guardrails
library,” while preserving the existing guidance about installing rail-specific
Python packages directly.

Source: Coding guidelines

Comment on lines +253 to +255
with patch("nemoguardrails.library.guardrails_ai.actions._load_guard_class"):
with pytest.raises(GuardrailsAIValidationError) as exc_info:
validate_guardrails_ai(validator_name="completely_unknown_validator", text="Test text")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Make the patched loader fail.

Line 253 replaces the unknown-validator failure with a callable MagicMock, so validate_guardrails_ai() can complete instead of raising. Configure side_effect with a lookup error.

Proposed fix
-        with patch("nemoguardrails.library.guardrails_ai.actions._load_guard_class"):
+        with patch(
+            "nemoguardrails.library.guardrails_ai.actions._load_guard_class",
+            side_effect=LookupError("unknown validator"),
+        ):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with patch("nemoguardrails.library.guardrails_ai.actions._load_guard_class"):
with pytest.raises(GuardrailsAIValidationError) as exc_info:
validate_guardrails_ai(validator_name="completely_unknown_validator", text="Test text")
with patch(
"nemoguardrails.library.guardrails_ai.actions._load_guard_class",
side_effect=LookupError("unknown validator"),
):
with pytest.raises(GuardrailsAIValidationError) as exc_info:
validate_guardrails_ai(validator_name="completely_unknown_validator", text="Test text")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_guardrails_ai_e2e_actions.py` around lines 253 - 255, Configure
the patched _load_guard_class in the validate_guardrails_ai test to raise the
expected lookup error via side_effect, ensuring the unknown validator path still
raises GuardrailsAIValidationError. Keep the existing pytest.raises assertion
and validation arguments unchanged.

@Pouyanpi
Pouyanpi force-pushed the pouyanpi/rail-library-requirements branch from 02e7a2a to f545de8 Compare July 23, 2026 10:18
@github-actions

Copy link
Copy Markdown
Contributor

@tgasser-nv tgasser-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach doesn't feel user-friendly, and is a regression on the current experience. I think we need to rethink how this works.

The only advantage is we're reducing the size of the install, but it's a weak argument since removing half a dozen packages from all whose total size if only around 3MB isn't much of a saving. Users would reasonably expect to use Nvidia-vended rails like multilingual Content-safety (using fast-langdetect) or yara regex rules after installing Guardrails.

The disadvantage is that it requires learning a whole new flow around nemoguardrails validate where you have to validate every possible rail you'd use in a Guardrails install/environment. Then copy-paste pip commands for each of these in sequence. These pip commands are less likely to work than a single uv install, since it can't jointly solve all package versions and can silently corrupt the uv core installation. Every time you do a uv sync these will be lost. The uv add command would be better than pip install.

The tension is that the Manifest approach does discovery dynamically by walking the library directories, whereas the package installation has to be from a static file. We can iterate over the rail manifests to create a dependency list for each. Then use tomlkit to write a new section for each rail, and an all-rails which combines all of them into the pyproject.toml:

[project.optional-dependencies]
tracing = [...]        # hand-written, untouched
server  = [...]
# >>> generated rail extras — run `make gen-rail-extras`; do not edit >>>
content-safety-rail      = ["fast-langdetect>=1"]
injection-detection-rail = ["yara-python>=4.5.1,<5"]
sensitive-data-detection-rail = ["presidio-analyzer>=2.2; python_version < '3.13'", "presidio-anonymizer>=2.2; python_version < '3.13'", "spacy>=3.4.4,<4,!=3.7.0; python_version < '3.13'"]
# ... one per rail ...
all-rails = [ ...union of every rail's packages... ]
# <<< generated rail extras <<<

Then if any rail isn't installed the error message would be to run uv add nemoguardrails[<rail-name>]

@@ -144,12 +160,6 @@ async def jailbreak_detection_model(
except RuntimeError as e:
log.error(f"Jailbreak detection model not available: {e}")
jailbreak_result = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without an except clause here, it'll just raise a ModuleNotFoundError without helping the user solve the problem. We need to give them guidance on what to do to remedy the failure, using the manifest to give the missing modules

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size: L status: triaged Triaged by a maintainer; eligible for automated review (CodeRabbit/Greptile).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants