|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Tool-result validation rail for IORails. |
| 17 | +
|
| 18 | +Structurally validates the tool results carried on an incoming request against |
| 19 | +the tool calls the model previously made: every result must link to a prior |
| 20 | +call by ``call_id``, name a tool consistent with that call, and carry |
| 21 | +well-formed content. This PR validates structure only -- there are no declared |
| 22 | +response schemas yet. The rail is local and model-free; it runs through |
| 23 | +:meth:`ToolRailAction._guarded`, so a malformed result or an unexpected error |
| 24 | +fails closed (blocks) rather than propagating. |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +from typing import TYPE_CHECKING, List |
| 30 | + |
| 31 | +from nemoguardrails.guardrails.guardrails_types import RailResult |
| 32 | +from nemoguardrails.guardrails.tool_rail_action import ToolRailAction |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from nemoguardrails.guardrails.tool_schema import ToolResult |
| 36 | + from nemoguardrails.types import ToolCall |
| 37 | + |
| 38 | + |
| 39 | +def _is_well_formed_content(content: object) -> bool: |
| 40 | + """Tool-result content is a string, or a list of content-block dicts. |
| 41 | +
|
| 42 | + Matches the declared ``ToolResult.content`` type (``str | list[dict] | None``); |
| 43 | + a list of non-dict values (e.g. ``[1, 2, 3]``) is not well-formed. |
| 44 | + """ |
| 45 | + if isinstance(content, str): |
| 46 | + return True |
| 47 | + return isinstance(content, list) and all(isinstance(block, dict) for block in content) |
| 48 | + |
| 49 | + |
| 50 | +class ToolResultRailAction(ToolRailAction): |
| 51 | + """Check incoming tool results link to a prior call and are structurally well-formed.""" |
| 52 | + |
| 53 | + action_name = "tool result validation" |
| 54 | + |
| 55 | + async def run(self, tool_results: List["ToolResult"], prior_calls: List["ToolCall"]) -> RailResult: |
| 56 | + """Block unless every tool result links to a prior call with a consistent name and valid content.""" |
| 57 | + return self._guarded(lambda: self._validate(tool_results, prior_calls)) |
| 58 | + |
| 59 | + def _validate(self, tool_results: List["ToolResult"], prior_calls: List["ToolCall"]) -> RailResult: |
| 60 | + """Check call_id linkage, name consistency, and content shape for each result.""" |
| 61 | + calls_by_id = self._validate_prior_calls(prior_calls) |
| 62 | + if isinstance(calls_by_id, RailResult): |
| 63 | + return calls_by_id |
| 64 | + return self._validate_results(tool_results, calls_by_id) |
| 65 | + |
| 66 | + def _validate_prior_calls(self, prior_calls: List["ToolCall"]) -> "RailResult | dict[str, ToolCall]": |
| 67 | + """Build a call_id index from prior_calls; return a blocking RailResult on duplicate IDs.""" |
| 68 | + calls_by_id: dict[str, "ToolCall"] = {} |
| 69 | + for call in prior_calls: |
| 70 | + if not call.id: |
| 71 | + continue |
| 72 | + if call.id in calls_by_id: |
| 73 | + return RailResult( |
| 74 | + is_safe=False, |
| 75 | + reason=f"duplicate prior tool call id '{call.id}' makes tool-result linkage ambiguous", |
| 76 | + ) |
| 77 | + calls_by_id[call.id] = call |
| 78 | + return calls_by_id |
| 79 | + |
| 80 | + def _validate_results(self, tool_results: List["ToolResult"], calls_by_id: "dict[str, ToolCall]") -> RailResult: |
| 81 | + """Check each result links to a prior call with a consistent name and well-formed content.""" |
| 82 | + rail_result = self._validate_tool_result_ids(tool_results) |
| 83 | + if rail_result: |
| 84 | + return rail_result |
| 85 | + |
| 86 | + for result in tool_results: |
| 87 | + rail_result = self._validate_result_call_id(result, calls_by_id) |
| 88 | + if rail_result: |
| 89 | + return rail_result |
| 90 | + |
| 91 | + prior = calls_by_id[result.call_id] # type: ignore[index] |
| 92 | + rail_result = self._validate_result_name(result, prior) |
| 93 | + if rail_result: |
| 94 | + return rail_result |
| 95 | + |
| 96 | + rail_result = self._validate_result_content(result) |
| 97 | + if rail_result: |
| 98 | + return rail_result |
| 99 | + |
| 100 | + return RailResult(is_safe=True) |
| 101 | + |
| 102 | + def _validate_tool_result_ids(self, tool_results: List["ToolResult"]) -> "RailResult | None": |
| 103 | + """Return a blocking RailResult if any call_id appears more than once in the result list.""" |
| 104 | + seen: set[str] = set() |
| 105 | + for result in tool_results: |
| 106 | + if not result.call_id: |
| 107 | + continue |
| 108 | + if result.call_id in seen: |
| 109 | + return RailResult( |
| 110 | + is_safe=False, |
| 111 | + reason=f"duplicate tool result for call_id '{result.call_id}': each tool call must have exactly one result", |
| 112 | + ) |
| 113 | + seen.add(result.call_id) |
| 114 | + return None |
| 115 | + |
| 116 | + def _validate_result_call_id(self, result: "ToolResult", calls_by_id: "dict[str, ToolCall]") -> "RailResult | None": |
| 117 | + """Return a blocking RailResult if the result is missing a call_id or it has no prior call.""" |
| 118 | + call_id = result.call_id |
| 119 | + if not call_id: |
| 120 | + return RailResult(is_safe=False, reason="tool result is missing a call_id") |
| 121 | + if calls_by_id.get(call_id) is None: |
| 122 | + return RailResult( |
| 123 | + is_safe=False, |
| 124 | + reason=f"tool result for call_id '{call_id}' does not correspond to a prior tool call", |
| 125 | + ) |
| 126 | + return None |
| 127 | + |
| 128 | + def _validate_result_name(self, result: "ToolResult", prior: "ToolCall") -> "RailResult | None": |
| 129 | + """Return a blocking RailResult if the result name conflicts with the prior call's function name.""" |
| 130 | + if result.name and prior.function.name and result.name != prior.function.name: |
| 131 | + return RailResult( |
| 132 | + is_safe=False, |
| 133 | + reason=( |
| 134 | + f"tool result name '{result.name}' does not match the called tool " |
| 135 | + f"'{prior.function.name}' for call_id '{result.call_id}'" |
| 136 | + ), |
| 137 | + ) |
| 138 | + return None |
| 139 | + |
| 140 | + def _validate_result_content(self, result: "ToolResult") -> "RailResult | None": |
| 141 | + """Return a blocking RailResult if the result content is not a string or list of dicts.""" |
| 142 | + if result.content is not None and not _is_well_formed_content(result.content): |
| 143 | + return RailResult( |
| 144 | + is_safe=False, |
| 145 | + reason=f"tool result for call_id '{result.call_id}' has malformed content", |
| 146 | + ) |
| 147 | + return None |
0 commit comments