Repository navigation
Add NeMo Guardrails policy middleware - #2006
rapids-bot[bot] merged 9 commits into
Conversation
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]>
|
Complex PR? Review this PR in Change Stack to move by importance, not file order. Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds NeMo Guardrails middleware, guardrails configs and tests; changes YAML loading to braced ChangesGuardrails and YAML Interpolation
Security Namespace Migration and Retail Example
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
…eature/nemo-guardrails-integration
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (84)
examples/A2A/math_assistant_a2a/uv.lockis excluded by!**/*.lockexamples/A2A/math_assistant_a2a_protected/uv.lockis excluded by!**/*.lockexamples/HITL/por_to_jiratickets/uv.lockis excluded by!**/*.lockexamples/HITL/simple_calculator_hitl/uv.lockis excluded by!**/*.lockexamples/MCP/service_account_auth_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_auth_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_fastmcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_fastmcp_protected/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_mcp_protected/uv.lockis excluded by!**/*.lockexamples/RAG/simple_rag/uv.lockis excluded by!**/*.lockexamples/a365_example/uv.lockis excluded by!**/*.lockexamples/advanced_agents/alert_triage_agent/uv.lockis excluded by!**/*.lockexamples/agents/uv.lockis excluded by!**/*.lockexamples/control_flow/hybrid_control_flow/uv.lockis excluded by!**/*.lockexamples/control_flow/parallel_executor/uv.lockis excluded by!**/*.lockexamples/control_flow/router_agent/uv.lockis excluded by!**/*.lockexamples/control_flow/sequential_executor/uv.lockis excluded by!**/*.lockexamples/custom_functions/automated_description_generation/uv.lockis excluded by!**/*.lockexamples/custom_functions/plot_charts/uv.lockis excluded by!**/*.lockexamples/documentation_guides/uv.lockis excluded by!**/*.lockexamples/documentation_guides/workflows/text_file_ingest/uv.lockis excluded by!**/*.lockexamples/dynamo_integration/latency_sensitivity_demo/uv.lockis excluded by!**/*.lockexamples/dynamo_integration/react_benchmark_agent/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/email_phishing_analyzer/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/simple_calculator_eval/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/simple_web_query_eval/uv.lockis excluded by!**/*.lockexamples/finetuning/dpo_tic_tac_toe/uv.lockis excluded by!**/*.lockexamples/finetuning/rl_with_openpipe_art/uv.lockis excluded by!**/*.lockexamples/frameworks/adk_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/agno_personal_finance/uv.lockis excluded by!**/*.lockexamples/frameworks/haystack_deep_research_agent/uv.lockis excluded by!**/*.lockexamples/frameworks/multi_frameworks/uv.lockis excluded by!**/*.lockexamples/frameworks/nat_autogen_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/semantic_kernel_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/strands_demo/uv.lockis excluded by!**/*.lockexamples/front_ends/per_user_workflow/uv.lockis excluded by!**/*.lockexamples/front_ends/simple_auth/uv.lockis excluded by!**/*.lockexamples/front_ends/simple_calculator_custom_routes/uv.lockis excluded by!**/*.lockexamples/getting_started/simple_calculator/uv.lockis excluded by!**/*.lockexamples/getting_started/simple_web_query/uv.lockis excluded by!**/*.lockexamples/memory/redis/uv.lockis excluded by!**/*.lockexamples/notebooks/uv.lockis excluded by!**/*.lockexamples/object_store/user_report/uv.lockis excluded by!**/*.lockexamples/observability/simple_calculator_observability/uv.lockis excluded by!**/*.lockexamples/prompt_from_file/uv.lockis excluded by!**/*.lockexamples/safety_and_security/retail_agent/assets/guardrails-score.pngis excluded by!**/*.pngexamples/safety_and_security/retail_agent/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_a2a/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_a365/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_adk/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_agno/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_app/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_atif/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_autogen/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_config_optimizer/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_core/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_crewai/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_data_flywheel/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_eval/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_fastmcp/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_langchain/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_llama_index/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_mcp/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_mem0ai/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_memmachine/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_mysql/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_nemo_customizer/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_openpipe_art/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_opentelemetry/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_phoenix/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_profiler/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_rag/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_ragaai/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_ragas/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_redis/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_s3/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_security/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_semantic_kernel/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_strands/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_test/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_weave/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_zep_cloud/uv.lockis excluded by!**/*.lockuv.lockis excluded by!**/*.lock
📒 Files selected for processing (53)
ci/.nim_models_used.jsondocs/source/build-workflows/workflow-configuration.mddocs/source/get-started/installation.mddocs/source/resources/migration-guide.mdexamples/README.mdexamples/safety_and_security/retail_agent/README.mdexamples/safety_and_security/retail_agent/pyproject.tomlexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-defenses.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.copackages/nvidia_nat_core/pyproject.tomlpackages/nvidia_nat_core/src/nat/middleware/__init__.pypackages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_function_middleware.pypackages/nvidia_nat_core/src/nat/middleware/dynamic/dynamic_middleware_config.pypackages/nvidia_nat_core/src/nat/middleware/register.pypackages/nvidia_nat_core/src/nat/utils/io/yaml_tools.pypackages/nvidia_nat_core/tests/nat/middleware/test_dynamic_middleware.pypackages/nvidia_nat_core/tests/nat/utils/test_yaml_tools.pypackages/nvidia_nat_security/pyproject.tomlpackages/nvidia_nat_security/src/nat/plugins/security/eval/runners/red_teaming_runner/config.pypackages/nvidia_nat_security/src/nat/plugins/security/eval/runners/red_teaming_runner/runner.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/__init__.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_content_guard.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_data_models.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_output_verifier.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_pii.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/defense_middleware_pre_tool_verifier.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/defense/register.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/__init__.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/exceptions.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/register.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/__init__.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/red_teaming_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/red_teaming_middleware_config.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/red_teaming/register.pypackages/nvidia_nat_security/src/nat/plugins/security/register.pypackages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_config.pypackages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.pypackages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware.pypackages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_content_guard.pypackages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_output_verifier.pypackages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_pii.pypackages/nvidia_nat_security/tests/middleware/defense/test_defense_middleware_pre_tool_verifier.pypackages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.pypackages/nvidia_nat_security/tests/middleware/guardrails/test_resolve_guardrails_policy_path.pypackages/nvidia_nat_security/tests/middleware/red_teaming/test_red_teaming_middleware.pypyproject.tomltest_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
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]>
There was a problem hiding this comment.
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 winBlocked 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
⛔ Files ignored due to path filters (8)
examples/experimental/claude_code_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/codex_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/cursor_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/hermes_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/openclaw_agent_adapter/uv.lockis excluded by!**/*.lockexamples/safety_and_security/retail_agent/uv.lockis excluded by!**/*.lockpackages/nvidia_nat_security/uv.lockis excluded by!**/*.lockuv.lockis excluded by!**/*.lock
📒 Files selected for processing (12)
ci/scripts/path_checks.pyci/vale/styles/config/vocabularies/nat/accept.txtdocs/source/get-started/installation.mdexamples/safety_and_security/retail_agent/README.mdexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/config-with-guardrails.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/configs/red-teaming-with-guardrails.ymlexamples/safety_and_security/retail_agent/src/nat_retail_agent/guardrails/verifier_redirect.copackages/nvidia_nat_security/pyproject.tomlpackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.pypackages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.pypackages/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
Signed-off-by: Eric Evans <[email protected]>
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (53)
examples/A2A/math_assistant_a2a/uv.lockis excluded by!**/*.lockexamples/A2A/math_assistant_a2a_protected/uv.lockis excluded by!**/*.lockexamples/HITL/por_to_jiratickets/uv.lockis excluded by!**/*.lockexamples/HITL/simple_calculator_hitl/uv.lockis excluded by!**/*.lockexamples/MCP/service_account_auth_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_auth_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_fastmcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_fastmcp_protected/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_mcp/uv.lockis excluded by!**/*.lockexamples/MCP/simple_calculator_mcp_protected/uv.lockis excluded by!**/*.lockexamples/RAG/simple_rag/uv.lockis excluded by!**/*.lockexamples/a365_example/uv.lockis excluded by!**/*.lockexamples/advanced_agents/alert_triage_agent/uv.lockis excluded by!**/*.lockexamples/agents/uv.lockis excluded by!**/*.lockexamples/control_flow/hybrid_control_flow/uv.lockis excluded by!**/*.lockexamples/control_flow/parallel_executor/uv.lockis excluded by!**/*.lockexamples/control_flow/router_agent/uv.lockis excluded by!**/*.lockexamples/control_flow/sequential_executor/uv.lockis excluded by!**/*.lockexamples/custom_functions/automated_description_generation/uv.lockis excluded by!**/*.lockexamples/custom_functions/plot_charts/uv.lockis excluded by!**/*.lockexamples/documentation_guides/uv.lockis excluded by!**/*.lockexamples/documentation_guides/workflows/text_file_ingest/uv.lockis excluded by!**/*.lockexamples/dynamo_integration/latency_sensitivity_demo/uv.lockis excluded by!**/*.lockexamples/dynamo_integration/react_benchmark_agent/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/email_phishing_analyzer/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/simple_calculator_eval/uv.lockis excluded by!**/*.lockexamples/evaluation_and_profiling/simple_web_query_eval/uv.lockis excluded by!**/*.lockexamples/experimental/claude_code_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/codex_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/cursor_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/hermes_agent_adapter/uv.lockis excluded by!**/*.lockexamples/experimental/openclaw_agent_adapter/uv.lockis excluded by!**/*.lockexamples/finetuning/dpo_tic_tac_toe/uv.lockis excluded by!**/*.lockexamples/finetuning/rl_with_openpipe_art/uv.lockis excluded by!**/*.lockexamples/frameworks/adk_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/agno_personal_finance/uv.lockis excluded by!**/*.lockexamples/frameworks/haystack_deep_research_agent/uv.lockis excluded by!**/*.lockexamples/frameworks/multi_frameworks/uv.lockis excluded by!**/*.lockexamples/frameworks/nat_autogen_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/semantic_kernel_demo/uv.lockis excluded by!**/*.lockexamples/frameworks/strands_demo/uv.lockis excluded by!**/*.lockexamples/front_ends/per_user_workflow/uv.lockis excluded by!**/*.lockexamples/front_ends/simple_auth/uv.lockis excluded by!**/*.lockexamples/front_ends/simple_calculator_custom_routes/uv.lockis excluded by!**/*.lockexamples/getting_started/simple_calculator/uv.lockis excluded by!**/*.lockexamples/getting_started/simple_web_query/uv.lockis excluded by!**/*.lockexamples/memory/redis/uv.lockis excluded by!**/*.lockexamples/notebooks/uv.lockis excluded by!**/*.lockexamples/object_store/user_report/uv.lockis excluded by!**/*.lockexamples/observability/simple_calculator_observability/uv.lockis excluded by!**/*.lockexamples/prompt_from_file/uv.lockis excluded by!**/*.lockexamples/safety_and_security/retail_agent/uv.lockis excluded by!**/*.lockuv.lockis excluded by!**/*.lock
📒 Files selected for processing (8)
docs/source/build-workflows/advanced/middleware.mddocs/source/resources/migration-guide.mdexamples/safety_and_security/retail_agent/README.mdpackages/nvidia_nat_security/pyproject.tomlpackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.pypackages/nvidia_nat_security/tests/middleware/guardrails/test_nemo_guardrails_middleware.pypyproject.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
Signed-off-by: Eric Evans <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.py (1)
50-56: ⚡ Quick winConsider adding type hints for better type safety.
The new
empty_functionregistration 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 innerAs 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
📒 Files selected for processing (7)
docs/source/build-workflows/advanced/middleware.mdexamples/safety_and_security/retail_agent/README.mdpackages/nvidia_nat_security/pyproject.tomlpackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware.pypackages/nvidia_nat_security/src/nat/plugins/security/middleware/guardrails/nemo_guardrails_middleware_config.pypackages/nvidia_nat_security/tests/eval/runners/red_teaming_runner/test_red_teaming_runner.pypackages/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
Signed-off-by: Eric Evans <[email protected]>
Salonijain27
left a comment
There was a problem hiding this comment.
Approved from a dependency point of view
Signed-off-by: Eric Evans <[email protected]>
|
I ran the documented retail guardrails workflow and hit a bad happy-path outcome. Input used: This is the same benign query shown in the README's Observed behavior: the configured Relevant log snippets: 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. |
Signed-off-by: Eric Evans <[email protected]>
…and harmful-suggestion attacks Signed-off-by: Eric Evans <[email protected]>
00d6be7 to
e53cd6b
Compare
|
/merge |
|
Follow-up: I reinstalled/reran the retail guardrails example on the latest PR head ( The documented benign input now stays intact through workflow input rails: The agent then completes the expected product lookup / email flow and calls The final workflow result is successful, with PII masked only in the returned output: So the blocker from my earlier comment appears resolved. Only minor polish note: output masking turns |
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
…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
Description
This PR adds first-class NeMo Guardrails support to the NeMo Agent Toolkit and
consolidates all safety/security middleware into the
nvidia-nat-securityplugin.New: NeMo Guardrails middleware (
_type: guardrails)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.
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 railcall; 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 valueis guarded.
text is written back to the input/output, blocks short-circuit the call and return
the rail's message (
on_post_invoke_blocked/PostInvokeBlockedErrorareoverridable).
Refactor / packaging
pii_defense,content_safety_guard,output_verifier,pre_tool_verifier) and the red-teaming middleware out ofnvidia-nat-coreand into thenvidia-nat-securityplugin (renames preserve history).pii-defenseextra fromnvidia-nat-core.defenseandguardrailsextras tonvidia-nat-security(and surfaces themon the umbrella
nvidia-natpackage).guardrailspulls innemoguardrails.ci/.nim_models_used.jsonto reflect theextras restructuring and the new example's NIM models.
Config loading
${VAR}-style environment interpolation(
surrounded_vars_only=True) and interpolates recursively after parse, so${VAR:-default}resolves consistently in nested config structures.Example & documentation
config-with-guardrails.yml,red-teaming-with-guardrails.yml, and averifier_redirect.coColang policy.en_core_web_lgspaCy model and thetransformers[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.
examples/README.mdand theworkflow-configuration / installation / migration-guide docs.
Tests
Closes
By Submitting this PR I confirm:
Summary by CodeRabbit
New Features
Documentation
Chores
Tests