Skip to content

Add NeMo Guardrails policy middleware - #2006

Merged
rapids-bot[bot] merged 9 commits into
NVIDIA:release/1.8from
ericevans-nv:feature/nemo-guardrails-integration
Jun 6, 2026
Merged

rapids-bot[bot] merged 9 commits into
NVIDIA:release/1.8from
ericevans-nv:feature/nemo-guardrails-integration

Conversation

@ericevans-nv

@ericevans-nv ericevans-nv commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds first-class NeMo Guardrails support to the NeMo Agent Toolkit and
consolidates all safety/security middleware into the nvidia-nat-security plugin.

New: NeMo Guardrails middleware (_type: guardrails)

  • Adds GuardrailsMiddleware, which applies NeMo Guardrails rails (content safety,
    jailbreak detection, PII masking, output verification, etc.) at a function's
    input and output boundaries via the dynamic middleware system.
  • Schema-driven field selection: rather than JSONPath text extraction, operators
    declare which string fields to guard using dotted attribute paths against the
    function's Pydantic input/output schema (GuardrailFunctionFields,
    e.g. reviews.review). List paths fan out and are concatenated into a single rail
    call; a field with no subpath guards the whole value. When no selection is given
    (e.g. the <workflow> boundary, whose value is a plain string), the entire value
    is guarded.
  • Supports pass / modify / block outcomes driven by the Colang policy: modified
    text is written back to the input/output, blocks short-circuit the call and return
    the rail's message (on_post_invoke_blocked / PostInvokeBlockedError are
    overridable).

Refactor / packaging

  • Moves the defense middleware (pii_defense, content_safety_guard,
    output_verifier, pre_tool_verifier) and the red-teaming middleware out of
    nvidia-nat-core and into the nvidia-nat-security plugin (renames preserve history).
  • Reworks extras accordingly:
    • Removes the pii-defense extra from nvidia-nat-core.
    • Adds defense and guardrails extras to nvidia-nat-security (and surfaces them
      on the umbrella nvidia-nat package). guardrails pulls in nemoguardrails.
  • Updates lockfiles across the repo and ci/.nim_models_used.json to reflect the
    extras restructuring and the new example's NIM models.

Breaking change (migration): Python imports of the defense/red-teaming
middleware move from nat.middleware.* to
nat.plugins.security.middleware.*, and nvidia-nat[pii-defense] is replaced by
nvidia-nat[defense] (provided by nvidia-nat-security). The registered _type
values are unchanged. See the updated migration guide.

Config loading

  • YAML config loading now uses ${VAR}-style environment interpolation
    (surrounded_vars_only=True) and interpolates recursively after parse, so
    ${VAR:-default} resolves consistently in nested config structures.

Example & documentation

  • Adds a guardrails walkthrough to the retail agent example:
    config-with-guardrails.yml, red-teaming-with-guardrails.yml, and a
    verifier_redirect.co Colang policy.
  • Documents installation (including the en_core_web_lg spaCy model and the
    transformers[torch,accelerate] requirement for the jailbreak-heuristics rail),
    how to run with guardrails, how guardrails evaluate content (pass/modify/block),
    and red-teaming results with a comparison chart.
  • Fixes example config paths/links and updates examples/README.md and the
    workflow-configuration / installation / migration-guide docs.

Tests

  • Adds unit tests for the guardrails middleware and policy-path resolution.
  • Relocates the existing defense/red-teaming test suites alongside the moved code.

Closes

By Submitting this PR I confirm:

  • I am familiar with the Contributing Guidelines.
  • We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
    • Any contribution which contains commits that are not Signed-Off will not be accepted.
  • When the PR is ready for review, new or existing tests cover these changes.
  • When the PR is ready for review, the documentation is up to date with these changes.

Summary by CodeRabbit

  • New Features

    • NeMo Guardrails middleware added for policy-driven input/output protection and content blocking.
    • Dynamic middleware enhanced to allow selective workflow-function interception/registration.
    • New retail-agent guardrails and red‑teaming example configurations and workflows.
  • Documentation

    • Clarified environment-variable interpolation (use ${VAR} / ${VAR:-default}; bare $VAR unsupported) and migration guidance.
    • Expanded installation/docs for defense, guardrails, and red‑teaming.
  • Chores

    • Packaging/extras reorganized (security/defense/guardrails); removed prior pii-defense extra.
    • LLM configuration entries updated.
  • Tests

    • Extensive unit tests added for dynamic middleware, YAML interpolation, and guardrails behavior.

Add a GuardrailsMiddleware (`_type: guardrails`) that applies NeMo
Guardrails rails at function input/output boundaries, with schema-driven
dotted-path field selection for choosing which string fields to guard.

- Move defense and red-teaming middleware from nvidia-nat-core into the
  nvidia-nat-security plugin; expose a `guardrails` extra (nemoguardrails).
- Add the retail agent guardrails example and README docs/results.
- Support ${VAR}-style environment interpolation in YAML config loading.

Signed-off-by: Eric Evans <[email protected]>
@ericevans-nv ericevans-nv self-assigned this Jun 5, 2026
@ericevans-nv
ericevans-nv requested review from a team as code owners June 5, 2026 07:48
@ericevans-nv ericevans-nv added feature request New feature or request non-breaking Non-breaking change labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Complex PR? Review this PR in Change Stack to move by importance, not file order.

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds NeMo Guardrails middleware, guardrails configs and tests; changes YAML loading to braced ${VAR} expansion with recursive post-parse interpolation; extends dynamic middleware workflow-function targeting and late group discovery; migrates security middleware into plugin namespaces; updates retail examples, docs, packaging, and CI metadata.

Changes

Guardrails and YAML Interpolation

Layer / File(s) Summary
YAML braced variable interpolation
packages/nvidia_nat_core/src/nat/utils/io/yaml_tools.py, packages/nvidia_nat_core/tests/nat/utils/test_yaml_tools.py
YAML loading now expands braced ${VAR} expressions on the raw text and then recursively interpolates parsed values; tests confirm ${VAR} expansion while preserving bare $ sequences and $model=... strings.
Dynamic middleware workflow-function targeting
packages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_middleware_config.py, packages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_function_middleware.py, packages/nvidia_nat_core/tests/nat/middleware/test_dynamic_middleware.py
Added workflow_functions config field and _should_intercept_function; discovery/register flows respect allow-lists, support register-all mode, avoid duplicate registrations, and patch builder.add_function_group to discover late-added groups.
Guardrails exceptions, config, and runtime
packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/exceptions.py, packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py, packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py, packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/register.py
New Guardrails middleware package: GuardrailsMiddleware applies NeMo Guardrails input/output rails at function boundaries, supports field-path selection and list fan-out, binds LLMs to rail actions once, buffers streams for post-invoke evaluation, and exposes on_post_invoke_blocked hook; config types validate mutual-exclusive policy sources and Colang 1.0.
Guardrails middleware tests and validation
packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py, packages/nvidia_nat_security/tests/middleware/guardrails/test_resolve_guardrails_policy_path.py
Comprehensive tests for pre/post-invoke rewrites, in-place field masking, list-element fan-out calls, blocking/refusal behaviors (including message-list fallbacks), and config/policy-path validation.

Security Namespace Migration and Retail Example

Layer / File(s) Summary
Middleware core registry and namespace alignment
packages/nvidia_nat_core/src/nat/middleware/__init__.py, packages/nvidia_nat_core/src/nat/middleware/register.py, packages/nvidia_nat_security/src/nat/plugins/security/register.py
Removed RedTeamingMiddleware from core exports and updated registration/imports to use nat.plugins.security.middleware.* plugin namespace.
Defense and red-teaming module migration
packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/*.py, packages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/register.py, packages/nvidia_nat_security/tests/middleware/defense/*, packages/nvidia_nat_security/tests/middleware/red_teaming/*
Repointed defense and red-teaming imports to the plugin namespace; tests updated import paths and logger patch targets to the new module locations.
Retail guardrails configurations
examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.yml, examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.yml, examples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.co, examples/safety_and_security/retail_agent/pyproject.toml
Adds full guardrails policies for retail example (PII/content-safety/jailbreak/self-check rails), judge LLMs and red-teaming scenarios with guardrails, verifier redirect flow, and example package extras updated to include defense and guardrails.
Retail example documentation
examples/safety_and_security/retail_agent/README.md, examples/README.md
README updated with Guardrails run instructions, prerequisites, nat run/nat red-team examples, defended red-team guidance, TOC changes, and results chart reference.
Installation, packaging, and CI alignment
docs/source/get-started/installation.md, docs/source/resources/migration-guide.md, docs/source/build-workflows/workflow-configuration.md, packages/nvidia_nat_core/pyproject.toml, packages/nvidia_nat_security/pyproject.toml, pyproject.toml, ci/.nim_models_used.json, test_data/azure_openai_e2e.yaml, ci/scripts/path_checks.py, ci/vale/styles/config/vocabularies/nat/accept.txt
Docs now require braced ${VAR} interpolation and add migration notes; pii-defense extras removed, new defense/guardrails extras added in pyproject(s); CI model catalog updated model counts and content-safety entries; e2e test data switched to ${AZURE_OPENAI_ENDPOINT}; path/vocab checks adjusted.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@ericevans-nv ericevans-nv added breaking Breaking change and removed non-breaking Non-breaking change labels Jun 5, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 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 `@examples/safety_and_security/retail_agent/README.md`:
- Around line 27-58: The Table of Contents list under the "Table of Contents" /
"NeMo Agent Toolkit Safety and Security" section has inconsistent indentation
causing MD005 warnings; edit the README.md TOC so all sibling list items use the
same number of leading spaces (e.g., two spaces or a single tab) and align
nested subitems consistently—update the block containing entries like
"Demonstrated Through Retail Agent Example", "Introduction", "Why We Need Safety
and Security" and its subitems (e.g., "The Problem", "The Solution", "How It
Works", "Red Teaming Flow", "Defense Flow") so each sibling uses the same indent
level and nested entries are uniformly indented.

In
`@examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.yml`:
- Line 22: Remove the TODO placeholder from the comment on the LLM
configurations line by deleting the substring "`#TODO` EE: TO BE REMOVED" or
replacing it with a finalized comment; specifically update the comment that
currently reads "LLM configurations - scenarios reference these by name `#TODO`
EE: TO BE REMOVED" to a clean, final phrase such as "LLM configurations -
scenarios reference these by name" or an appropriate descriptive note so no
TODO/FIXME text remains in red-teaming-with-guardrails.yml.

In
`@examples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.co`:
- Around line 1-5: Add the standard SPDX Apache-2.0 header comment to the top of
this new source file: insert the Apache-2.0 SPDX identifier and full license
header as a comment before the existing "define flow self check input redirect"
declaration so the file is properly licensed; ensure the header appears above
any code (before the define flow line) and retains the existing flow and
variables ($allowed, execute self_check_input, $user_message) unchanged.

In `@packages/nvidia_nat_security/pyproject.toml`:
- Around line 65-69: The optional-dependencies list named defense contains
unpinned packages; update the entries "presidio-analyzer" and
"presidio-anonymizer" to include explicit version constraints per project policy
(e.g., use a compatible range like >=X.Y.Z,<A.B.C or an exact pin) so they match
the versioned "spacy>=3.7" style; modify the defense array to replace the
unversioned "presidio-analyzer" and "presidio-anonymizer" strings with
appropriate versioned specifiers.

In
`@packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py`:
- Around line 355-359: The blocked-path logic currently calls
_handle_modified_rail_response(response, fallback=text) which can return the
original unsafe text and then assigns context.output = result_text when blocked
is true; change this so blocked calls use a non-echoing fallback (e.g. empty
string or a safe replacement) or explicitly set context.output to a safe value
when blocked and result_text == text. Update the block branch around the
variables blocked, result_text, text and the function
_handle_modified_rail_response so that blocked responses never fall back to
echoing the original input but instead return a sanitized/empty replacement
before assigning context.output.

In
`@packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py`:
- Line 301: The pytest.raises call using match="Colang 2.0 is not supported"
treats the string as a regex and tripping RUF043 because the dot is a
metacharacter; update the assertion to escape the dot or use a raw/escaped regex
(e.g. change match="Colang 2.0 is not supported" to match=r"Colang 2\.0 is not
supported" or construct the pattern with re.escape) in the pytest.raises(...)
invocation so Ruff no longer flags the unescaped metacharacter.
🪄 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: b77622c8-9b37-4794-96e7-79f266e3ec7a

📥 Commits

Reviewing files that changed from the base of the PR and between feb90a6 and a6f96ba.

⛔ Files ignored due to path filters (84)
  • examples/A2A/math_assistant_a2a/uv.lock is excluded by !**/*.lock
  • examples/A2A/math_assistant_a2a_protected/uv.lock is excluded by !**/*.lock
  • examples/HITL/por_to_jiratickets/uv.lock is excluded by !**/*.lock
  • examples/HITL/simple_calculator_hitl/uv.lock is excluded by !**/*.lock
  • examples/MCP/service_account_auth_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_auth_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_fastmcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_fastmcp_protected/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_mcp_protected/uv.lock is excluded by !**/*.lock
  • examples/RAG/simple_rag/uv.lock is excluded by !**/*.lock
  • examples/a365_example/uv.lock is excluded by !**/*.lock
  • examples/advanced_agents/alert_triage_agent/uv.lock is excluded by !**/*.lock
  • examples/agents/uv.lock is excluded by !**/*.lock
  • examples/control_flow/hybrid_control_flow/uv.lock is excluded by !**/*.lock
  • examples/control_flow/parallel_executor/uv.lock is excluded by !**/*.lock
  • examples/control_flow/router_agent/uv.lock is excluded by !**/*.lock
  • examples/control_flow/sequential_executor/uv.lock is excluded by !**/*.lock
  • examples/custom_functions/automated_description_generation/uv.lock is excluded by !**/*.lock
  • examples/custom_functions/plot_charts/uv.lock is excluded by !**/*.lock
  • examples/documentation_guides/uv.lock is excluded by !**/*.lock
  • examples/documentation_guides/workflows/text_file_ingest/uv.lock is excluded by !**/*.lock
  • examples/dynamo_integration/latency_sensitivity_demo/uv.lock is excluded by !**/*.lock
  • examples/dynamo_integration/react_benchmark_agent/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/email_phishing_analyzer/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/simple_calculator_eval/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/simple_web_query_eval/uv.lock is excluded by !**/*.lock
  • examples/finetuning/dpo_tic_tac_toe/uv.lock is excluded by !**/*.lock
  • examples/finetuning/rl_with_openpipe_art/uv.lock is excluded by !**/*.lock
  • examples/frameworks/adk_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/agno_personal_finance/uv.lock is excluded by !**/*.lock
  • examples/frameworks/haystack_deep_research_agent/uv.lock is excluded by !**/*.lock
  • examples/frameworks/multi_frameworks/uv.lock is excluded by !**/*.lock
  • examples/frameworks/nat_autogen_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/semantic_kernel_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/strands_demo/uv.lock is excluded by !**/*.lock
  • examples/front_ends/per_user_workflow/uv.lock is excluded by !**/*.lock
  • examples/front_ends/simple_auth/uv.lock is excluded by !**/*.lock
  • examples/front_ends/simple_calculator_custom_routes/uv.lock is excluded by !**/*.lock
  • examples/getting_started/simple_calculator/uv.lock is excluded by !**/*.lock
  • examples/getting_started/simple_web_query/uv.lock is excluded by !**/*.lock
  • examples/memory/redis/uv.lock is excluded by !**/*.lock
  • examples/notebooks/uv.lock is excluded by !**/*.lock
  • examples/object_store/user_report/uv.lock is excluded by !**/*.lock
  • examples/observability/simple_calculator_observability/uv.lock is excluded by !**/*.lock
  • examples/prompt_from_file/uv.lock is excluded by !**/*.lock
  • examples/safety_and_security/retail_agent/assets/guardrails-score.png is excluded by !**/*.png
  • examples/safety_and_security/retail_agent/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_a2a/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_a365/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_adk/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_agno/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_app/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_atif/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_autogen/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_config_optimizer/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_core/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_crewai/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_data_flywheel/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_eval/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_fastmcp/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_langchain/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_llama_index/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_mcp/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_mem0ai/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_memmachine/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_mysql/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_nemo_customizer/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_openpipe_art/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_opentelemetry/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_phoenix/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_profiler/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_rag/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_ragaai/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_ragas/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_redis/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_s3/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_security/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_semantic_kernel/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_strands/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_test/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_weave/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_zep_cloud/uv.lock is excluded by !**/*.lock
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (53)
  • ci/.nim_models_used.json
  • docs/source/build-workflows/workflow-configuration.md
  • docs/source/get-started/installation.md
  • docs/source/resources/migration-guide.md
  • examples/README.md
  • examples/safety_and_security/retail_agent/README.md
  • examples/safety_and_security/retail_agent/pyproject.toml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-defenses.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.co
  • packages/nvidia_nat_core/pyproject.toml
  • packages/nvidia_nat_core/src/nat/middleware/__init__.py
  • packages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_function_middleware.py
  • packages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_middleware_config.py
  • packages/nvidia_nat_core/src/nat/middleware/register.py
  • packages/nvidia_nat_core/src/nat/utils/io/yaml_tools.py
  • packages/nvidia_nat_core/tests/nat/middleware/test_dynamic_middleware.py
  • packages/nvidia_nat_core/tests/nat/utils/test_yaml_tools.py
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/eval/runners/red_teaming_runner/config.py
  • packages/nvidia_nat_security/src/nat/plugins/security/eval/runners/red_teaming_runner/runner.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/__init__.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_content_guard.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_data_models.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_output_verifier.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_pii.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_pre_tool_verifier.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/register.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/__init__.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/exceptions.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/register.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/__init__.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/red_teaming_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/red_teaming_middleware_config.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/register.py
  • packages/nvidia_nat_security/src/nat/plugins/security/register.py
  • packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_config.py
  • packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py
  • packages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware.py
  • packages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_content_guard.py
  • packages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_output_verifier.py
  • packages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_pii.py
  • packages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_pre_tool_verifier.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_resolve_guardrails_policy_path.py
  • packages/nvidia_nat_security/tests/middleware/red_teaming/test_red_teaming_middleware.py
  • pyproject.toml
  • test_data/azure_openai_e2e.yaml
💤 Files with no reviewable changes (3)
  • packages/nvidia_nat_core/pyproject.toml
  • packages/nvidia_nat_core/src/nat/middleware/register.py
  • packages/nvidia_nat_core/src/nat/middleware/init.py

Comment thread pyproject.toml Resolved
Refine field-selection handling in the Guardrails middleware, clarify
configuration, and update the retail agent example, docs, and tests.

Signed-off-by: Eric Evans <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py (1)

421-423: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Blocked input path can still return unsafe original text.

On Line 422, blocked input uses _handle_modified_rail_response(..., fallback=text), so a blocked response without extractable text can echo the original guarded input back to users. Use the blocked handler in this branch.

Suggested fix
-            if self._rail_blocked(response):
-                context.output = self._handle_modified_rail_response(response, fallback=text)
+            if self._rail_blocked(response):
+                context.output = self._handle_blocked_rail_response(response)
                 return context
🤖 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
`@packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py`
around lines 421 - 423, The branch that checks self._rail_blocked(response)
currently sets context.output by calling
self._handle_modified_rail_response(response, fallback=text), which can echo the
original input when no safe text is extractable; change this branch to call the
blocked-response handler instead (i.e., replace the
_handle_modified_rail_response(..., fallback=text) call with the appropriate
blocked handler method used elsewhere in this class) so context.output is set
via the blocked handler when _rail_blocked(response) is True, ensuring blocked
inputs never return the original text.
🤖 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 `@ci/scripts/path_checks.py`:
- Around line 177-182: The listed allowlist strings ending with a literal dot
(e.g., "Copyright/Trademark/Plagiarism.", "Fraud/Deception.",
"Immoral/Unethical.", "PII/Privacy.", "Planning/Confessions.",
"Political/Misinformation/Conspiracy.") are being injected raw into a regex
union and their trailing '.' acts as a wildcard; fix by escaping those dots (or
better, escape each whole entry with re.escape) when building the regex in the
code that constructs the union (e.g., the ALLOWLIST/allowlist entries or the
function that builds ALLOWLIST_REGEX/regex_union), so replace raw join logic
with escaped_entry = re.escape(entry) (or explicitly replace trailing '.' with
'\.') before joining into the union.

In
`@packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py`:
- Around line 232-239: The current loop over configured paths in
_iter_guard_targets/_iter_targets_at_path silently skips guardrail evaluation
when a dotted path resolves to no string leaves; change the logic so that if
paths is non-empty but iterating all paths yields no targets, you fall back to
yielding the whole_setter text (same as the fallback in the no-paths branch).
Concretely, inside the method using variables paths, value and whole_setter,
collect whether any yield occurred from self._iter_targets_at_path(value, path)
(or buffer results), and if after the loop no targets were produced, compute
text = getattr(value, "input_message", None) or (value if isinstance(value, str)
else str(value)) and yield text, whole_setter.

---

Duplicate comments:
In
`@packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py`:
- Around line 421-423: The branch that checks self._rail_blocked(response)
currently sets context.output by calling
self._handle_modified_rail_response(response, fallback=text), which can echo the
original input when no safe text is extractable; change this branch to call the
blocked-response handler instead (i.e., replace the
_handle_modified_rail_response(..., fallback=text) call with the appropriate
blocked handler method used elsewhere in this class) so context.output is set
via the blocked handler when _rail_blocked(response) is True, ensuring blocked
inputs never return the original text.
🪄 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: fe953798-adcf-42e6-a4a2-2b7b09b7ec3e

📥 Commits

Reviewing files that changed from the base of the PR and between a6f96ba and 8a61989.

⛔ Files ignored due to path filters (8)
  • examples/experimental/claude_code_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/codex_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/cursor_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/hermes_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/openclaw_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/safety_and_security/retail_agent/uv.lock is excluded by !**/*.lock
  • packages/nvidia_nat_security/uv.lock is excluded by !**/*.lock
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • ci/scripts/path_checks.py
  • ci/vale/styles/config/vocabularies/nat/accept.txt
  • docs/source/get-started/installation.md
  • examples/safety_and_security/retail_agent/README.md
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.co
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_resolve_guardrails_policy_path.py
💤 Files with no reviewable changes (2)
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.yml
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.yml
✅ Files skipped from review due to trivial changes (3)
  • ci/vale/styles/config/vocabularies/nat/accept.txt
  • docs/source/get-started/installation.md
  • examples/safety_and_security/retail_agent/README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • examples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.co

Comment thread ci/scripts/path_checks.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@examples/safety_and_security/retail_agent/README.md`:
- Around line 443-445: Fix the blockquote break in the README's blockquoted
section that starts with "**Attach one guardrails middleware per function.**":
remove the blank line inside the blockquote or prefix that separator/blank line
with ">" so the blockquote remains continuous (ensuring the paragraph that
follows stays part of the same blockquote and avoids the MD028 lint failure).
- Line 396: Replace possessive "'s" phrasing in the README prose around the
pii_guardrails middleware and mask_sensitive_data action: change "NeMo's
`mask_sensitive_data` action" to "the `mask_sensitive_data` action in NeMo" (and
similarly convert other possessive uses like "function's" to "the input of the
function" or "the X in Y") for the occurrences that reference NeMo,
`mask_sensitive_data`, spaCy, and `en_core_web_lg`; keep the technical
identifiers and meaning unchanged while removing possessive "'s" constructions.
🪄 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: 9bcdd654-f1c3-4538-9098-92e014accf27

📥 Commits

Reviewing files that changed from the base of the PR and between 8a61989 and feb4b7e.

⛔ Files ignored due to path filters (53)
  • examples/A2A/math_assistant_a2a/uv.lock is excluded by !**/*.lock
  • examples/A2A/math_assistant_a2a_protected/uv.lock is excluded by !**/*.lock
  • examples/HITL/por_to_jiratickets/uv.lock is excluded by !**/*.lock
  • examples/HITL/simple_calculator_hitl/uv.lock is excluded by !**/*.lock
  • examples/MCP/service_account_auth_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_auth_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_fastmcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_fastmcp_protected/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_mcp/uv.lock is excluded by !**/*.lock
  • examples/MCP/simple_calculator_mcp_protected/uv.lock is excluded by !**/*.lock
  • examples/RAG/simple_rag/uv.lock is excluded by !**/*.lock
  • examples/a365_example/uv.lock is excluded by !**/*.lock
  • examples/advanced_agents/alert_triage_agent/uv.lock is excluded by !**/*.lock
  • examples/agents/uv.lock is excluded by !**/*.lock
  • examples/control_flow/hybrid_control_flow/uv.lock is excluded by !**/*.lock
  • examples/control_flow/parallel_executor/uv.lock is excluded by !**/*.lock
  • examples/control_flow/router_agent/uv.lock is excluded by !**/*.lock
  • examples/control_flow/sequential_executor/uv.lock is excluded by !**/*.lock
  • examples/custom_functions/automated_description_generation/uv.lock is excluded by !**/*.lock
  • examples/custom_functions/plot_charts/uv.lock is excluded by !**/*.lock
  • examples/documentation_guides/uv.lock is excluded by !**/*.lock
  • examples/documentation_guides/workflows/text_file_ingest/uv.lock is excluded by !**/*.lock
  • examples/dynamo_integration/latency_sensitivity_demo/uv.lock is excluded by !**/*.lock
  • examples/dynamo_integration/react_benchmark_agent/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/email_phishing_analyzer/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/simple_calculator_eval/uv.lock is excluded by !**/*.lock
  • examples/evaluation_and_profiling/simple_web_query_eval/uv.lock is excluded by !**/*.lock
  • examples/experimental/claude_code_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/codex_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/cursor_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/hermes_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/experimental/openclaw_agent_adapter/uv.lock is excluded by !**/*.lock
  • examples/finetuning/dpo_tic_tac_toe/uv.lock is excluded by !**/*.lock
  • examples/finetuning/rl_with_openpipe_art/uv.lock is excluded by !**/*.lock
  • examples/frameworks/adk_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/agno_personal_finance/uv.lock is excluded by !**/*.lock
  • examples/frameworks/haystack_deep_research_agent/uv.lock is excluded by !**/*.lock
  • examples/frameworks/multi_frameworks/uv.lock is excluded by !**/*.lock
  • examples/frameworks/nat_autogen_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/semantic_kernel_demo/uv.lock is excluded by !**/*.lock
  • examples/frameworks/strands_demo/uv.lock is excluded by !**/*.lock
  • examples/front_ends/per_user_workflow/uv.lock is excluded by !**/*.lock
  • examples/front_ends/simple_auth/uv.lock is excluded by !**/*.lock
  • examples/front_ends/simple_calculator_custom_routes/uv.lock is excluded by !**/*.lock
  • examples/getting_started/simple_calculator/uv.lock is excluded by !**/*.lock
  • examples/getting_started/simple_web_query/uv.lock is excluded by !**/*.lock
  • examples/memory/redis/uv.lock is excluded by !**/*.lock
  • examples/notebooks/uv.lock is excluded by !**/*.lock
  • examples/object_store/user_report/uv.lock is excluded by !**/*.lock
  • examples/observability/simple_calculator_observability/uv.lock is excluded by !**/*.lock
  • examples/prompt_from_file/uv.lock is excluded by !**/*.lock
  • examples/safety_and_security/retail_agent/uv.lock is excluded by !**/*.lock
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • docs/source/build-workflows/advanced/middleware.md
  • docs/source/resources/migration-guide.md
  • examples/safety_and_security/retail_agent/README.md
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py
  • pyproject.toml
✅ Files skipped from review due to trivial changes (1)
  • docs/source/resources/migration-guide.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • pyproject.toml
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py (1)

50-56: ⚡ Quick win

Consider adding type hints for better type safety.

The new empty_function registration is missing type hints for the async generator return value and the inner function's parameters. While this is test code, the guidelines require type hints on parameters and return values.

📝 Suggested type hints
+from collections.abc import AsyncGenerator, Callable
+from typing import Any
+
 `@register_function`(config_type=EmptyFunctionConfig)
-async def empty_function(config: EmptyFunctionConfig, builder: Builder):
+async def empty_function(config: EmptyFunctionConfig, builder: Builder) -> AsyncGenerator[Callable[..., None], None]:
+    """Register an empty function for testing."""
 
-    async def inner(*args, **kwargs):
+    async def inner(*args: Any, **kwargs: Any) -> None:
         return None
 
     yield inner

As per coding guidelines: "All public APIs require Python 3.11+ type hints on parameters and return values" and "Python methods should use type hints for all parameters and return values."

🤖 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
`@packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py`
around lines 50 - 56, The test's registered async generator `empty_function` and
its inner callable lack type hints; update `empty_function(config:
EmptyFunctionConfig, builder: Builder)` to declare its return as an
AsyncGenerator of a callable (e.g., -> AsyncGenerator[Callable[...,
Awaitable[None]], None]) and type `inner` as a callable with typed params and
return (e.g., async def inner(*args: Any, **kwargs: Any) -> None) and add the
necessary imports (Any, AsyncGenerator, Callable, Awaitable) so the signatures
for `empty_function` and `inner` comply with the project's public-API typing
rules.
🤖 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.

Nitpick comments:
In
`@packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py`:
- Around line 50-56: The test's registered async generator `empty_function` and
its inner callable lack type hints; update `empty_function(config:
EmptyFunctionConfig, builder: Builder)` to declare its return as an
AsyncGenerator of a callable (e.g., -> AsyncGenerator[Callable[...,
Awaitable[None]], None]) and type `inner` as a callable with typed params and
return (e.g., async def inner(*args: Any, **kwargs: Any) -> None) and add the
necessary imports (Any, AsyncGenerator, Callable, Awaitable) so the signatures
for `empty_function` and `inner` comply with the project's public-API typing
rules.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: c7718cf7-3e30-4537-82a2-babf6f861d1f

📥 Commits

Reviewing files that changed from the base of the PR and between feb4b7e and 27b6ce9.

📒 Files selected for processing (7)
  • docs/source/build-workflows/advanced/middleware.md
  • examples/safety_and_security/retail_agent/README.md
  • packages/nvidia_nat_security/pyproject.toml
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py
  • packages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.py
💤 Files with no reviewable changes (1)
  • packages/nvidia_nat_security/pyproject.toml
✅ Files skipped from review due to trivial changes (1)
  • docs/source/build-workflows/advanced/middleware.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.py
  • examples/safety_and_security/retail_agent/README.md
  • packages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.py

@ericevans-nv
ericevans-nv changed the base branch from develop to release/1.8 June 5, 2026 22:26

@Salonijain27 Salonijain27 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.

Approved from a dependency point of view

@AjayThorve

AjayThorve commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

I ran the documented retail guardrails workflow and hit a bad happy-path outcome.

Input used:

Email From: [email protected]
Content: What garden trowels do you have?

This is the same benign query shown in the README's Run with Guardrails section for config-with-guardrails.yml.

Observed behavior: the configured workflow_guardrails middleware guards the whole workflow input, so the PII rail rewrites the operational email before the agent runs. The workflow then continues with <EMAIL_ADDRESS> instead of the real sender/recipient. The agent calls send_email using the masked placeholder, and the final workflow output is a refusal.

Relevant log snippets:

user_message: '<PERSON> From: <EMAIL_ADDRESS>
Content: What garden trowels do you have?'
Agent input: <PERSON> From: <EMAIL_ADDRESS>
Content: What garden trowels do you have?
Action: retail_tools__send_email
Action Input: {'recipient_email': '<EMAIL_ADDRESS>', ...}
Workflow Result: I'm sorry, I can't respond to that.

I think this is probably a retail example/config issue rather than a core middleware issue. The README/config do document that Guardrails can modify pre-invoke content, but for this retail happy path the whole-workflow input-side PII mutation removes operational identity before tool execution. From an end-user POV, the documented benign guardrails command should still complete the product lookup/email flow; any PII masking should not make the workflow send to a placeholder or end in a refusal.

@ericevans-nv
ericevans-nv force-pushed the feature/nemo-guardrails-integration branch from 00d6be7 to e53cd6b Compare June 6, 2026 04:25
@ericevans-nv

Copy link
Copy Markdown
Contributor Author

/merge

@rapids-bot
rapids-bot Bot merged commit d12f2d3 into NVIDIA:release/1.8 Jun 6, 2026
12 checks passed
@AjayThorve

Copy link
Copy Markdown
Contributor

Follow-up: I reinstalled/reran the retail guardrails example on the latest PR head (e53cd6b9) and this fixes the issue I saw earlier.

The documented benign input now stays intact through workflow input rails:

Agent input: Email From: [email protected]\nContent: What garden trowels do you have?

The agent then completes the expected product lookup / email flow and calls send_email with the real operational recipient:

Tool's input: {'recipient_email': '[email protected]', ...}
success=True message='Email sent successfully'

The final workflow result is successful, with PII masked only in the returned output:

Workflow Result:
{"success": true, "message": "<PERSON> sent successfully", "email_details": {"to": "<EMAIL_ADDRESS>", ...}}

So the blocker from my earlier comment appears resolved. Only minor polish note: output masking turns "Email sent successfully" into "<PERSON> sent successfully", which is a little odd for the demo, but it no longer breaks the end-user workflow.

yifei-gpt pushed a commit to yifei-gpt/NeMo-Agent-Toolkit that referenced this pull request Sep 13, 2026
This PR adds first-class **NeMo Guardrails** support to the NeMo Agent Toolkit and
consolidates all safety/security middleware into the `nvidia-nat-security` plugin.

### New: NeMo Guardrails middleware (`_type: guardrails`)
- Adds `GuardrailsMiddleware`, which applies NeMo Guardrails rails (content safety,
  jailbreak detection, PII masking, output verification, etc.) at a function's
  **input and output boundaries** via the dynamic middleware system.
- **Schema-driven field selection:** rather than JSONPath text extraction, operators
  declare which string fields to guard using dotted attribute paths against the
  function's Pydantic input/output schema (`GuardrailFunctionFields`,
  e.g. `reviews.review`). List paths fan out and are concatenated into a single rail
  call; a field with no subpath guards the whole value. When no selection is given
  (e.g. the `<workflow>` boundary, whose value is a plain string), the entire value
  is guarded.
- Supports **pass / modify / block** outcomes driven by the Colang policy: modified
  text is written back to the input/output, blocks short-circuit the call and return
  the rail's message (`on_post_invoke_blocked` / `PostInvokeBlockedError` are
  overridable).

### Refactor / packaging
- **Moves the defense middleware** (`pii_defense`, `content_safety_guard`,
  `output_verifier`, `pre_tool_verifier`) and the **red-teaming middleware** out of
  `nvidia-nat-core` and into the `nvidia-nat-security` plugin (renames preserve history).
- Reworks extras accordingly:
  - Removes the `pii-defense` extra from `nvidia-nat-core`.
  - Adds `defense` and `guardrails` extras to `nvidia-nat-security` (and surfaces them
    on the umbrella `nvidia-nat` package). `guardrails` pulls in `nemoguardrails`.
- Updates lockfiles across the repo and `ci/.nim_models_used.json` to reflect the
  extras restructuring and the new example's NIM models.

> **Breaking change (migration):** Python imports of the defense/red-teaming
> middleware move from `nat.middleware.*` to
> `nat.plugins.security.middleware.*`, and `nvidia-nat[pii-defense]` is replaced by
> `nvidia-nat[defense]` (provided by `nvidia-nat-security`). The registered `_type`
> values are unchanged. See the updated migration guide.

### Config loading
- YAML config loading now uses `${VAR}`-style environment interpolation
  (`surrounded_vars_only=True`) and interpolates recursively after parse, so
  `${VAR:-default}` resolves consistently in nested config structures.

### Example & documentation
- Adds a guardrails walkthrough to the **retail agent** example:
  `config-with-guardrails.yml`, `red-teaming-with-guardrails.yml`, and a
  `verifier_redirect.co` Colang policy.
- Documents installation (including the `en_core_web_lg` spaCy model and the
  `transformers[torch,accelerate]` requirement for the jailbreak-heuristics rail),
  how to run with guardrails, how guardrails evaluate content (pass/modify/block),
  and red-teaming results with a comparison chart.
- Fixes example config paths/links and updates `examples/README.md` and the
  workflow-configuration / installation / migration-guide docs.

### Tests
- Adds unit tests for the guardrails middleware and policy-path resolution.
- Relocates the existing defense/red-teaming test suites alongside the moved code.


Closes

## By Submitting this PR I confirm:
- I am familiar with the [Contributing Guidelines](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/docs/source/resources/contributing/index.md).
- We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
  - Any contribution which contains commits that are not Signed-Off will not be accepted.
- When the PR is ready for review, new or existing tests cover these changes.
- When the PR is ready for review, the documentation is up to date with these changes.


## Summary by CodeRabbit

* **New Features**
  * NeMo Guardrails middleware added for policy-driven input/output protection and content blocking.
  * Dynamic middleware enhanced to allow selective workflow-function interception/registration.
  * New retail-agent guardrails and red‑teaming example configurations and workflows.

* **Documentation**
  * Clarified environment-variable interpolation (use ${VAR} / ${VAR:-default}; bare $VAR unsupported) and migration guidance.
  * Expanded installation/docs for defense, guardrails, and red‑teaming.

* **Chores**
  * Packaging/extras reorganized (security/defense/guardrails); removed prior pii-defense extra.
  * LLM configuration entries updated.

* **Tests**
  * Extensive unit tests added for dynamic middleware, YAML interpolation, and guardrails behavior.

Authors:
  - Eric Evans II (https://github.com/ericevans-nv)

Approvers:
  - David Gardner (https://github.com/dagardner-nv)
  - https://github.com/Salonijain27

URL: NVIDIA#2006
rapids-bot Bot pushed a commit that referenced this pull request Sep 21, 2026
…alues (#2242)

`yaml_loads` expanded `${VAR}` references twice: on the raw YAML text (`expand(config, surrounded_vars_only=True)`) and then again on every parsed string value (`_interpolate_config`), both added in #2006. The text-level pass already resolves every reference written in the config, so the only thing the second pass could act on was `${...}` that came from an environment variable's own value: a prompt template like `Hello ${name}`, a secret containing `${`, and so on were rewritten (usually to `Hello `, since the inner name is unset) instead of being used verbatim.

This removes the per-value pass and keeps the text-level expansion, which is the behaviour before #2006. `_resolve_file_references` still runs on the parsed tree as before.

Test: `test_yaml_loads_does_not_expand_variables_inside_env_values` sets env values containing `${...}` and `$$` and checks they come through unchanged while ordinary references still expand. It fails on `develop` (`'Hello world, token none' == 'Hello ${NAT_TEST_NAME}, ...'`). `test_yaml_tools.py`: 35 passed. yapf and ruff clean.

Closes #2241

## By Submitting this PR I confirm:
- I am familiar with the [Contributing Guidelines](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/docs/source/resources/contributing/index.md).
- We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
  - Any contribution which contains commits that are not Signed-Off will not be accepted.
- When the PR is ready for review, new or existing tests cover these changes.
- When the PR is ready for review, the documentation is up to date with these changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)




## Summary by CodeRabbit

* **Bug Fixes**
  * YAML configuration variables are now expanded only once before parsing.
  * Nested `${...}` expressions and dollar signs within environment variable values are preserved correctly.

* **Tests**
  * Added regression coverage for single-pass environment variable expansion.

Authors:
  - Anish Mehta (https://github.com/anishmehta24)
  - Will Killian (https://github.com/willkill07)

Approvers:
  - Will Killian (https://github.com/willkill07)

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

Labels

breaking Breaking change feature request New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants