You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(advanced): run agent.json guardrails on advanced agents as middleware - #1260
Runs an agent's agent.json guardrails on an advanced agent as middleware. build_advanced_agent_guardrails converts each guardrail and its action, and returns the main agent's middleware and the subagents'.
Scopes: Agent scope runs on the main agent only; subagents get LLM and Tool scope. Agent POST checks the structured response when the agent returns one.
Validators: every validator type and custom rules, at the stages the standard path uses.
Actions: Log, Block, Escalate and Filter.
Escalate supports every recipient type. Argument recipients read the run's input, which the wrapper keeps in state only when such a guardrail is configured.
Filter removes top-level fields from a tool's arguments or result; a filtered result stays a JSON object. On any other scope it ends the run with TERMINATION_GUARDRAIL_ERROR.
create_advanced_agent takes subagent_middleware.
Version bumped to 0.21.12.
Tool-scope selectors that name an MCP tool by its display name are matched, as on the standard path.
Checks, actions and failure handling are the shared middleware's. The package docstring lists the known gaps, which are to be closed in the shared middleware (for coded agents too):
what the LLM input and output checks read;
Escalate re-evaluating on resume, rerunning a tool after a tool-output escalation, and not applying reviewer edits;
errors being logged and the content going through.
Code sandbox: this PR doesn't change the code interpreter. Tools and subagents called from eval run without guardrails; restricting or guarding them is a follow-up.
Testing
New tests cover conversion, scopes, Escalate recipients, Filter and the contracts for the shared-middleware methods the package overrides.
…eware
Converts each agent.json guardrail and its action into middleware for an
advanced agent: build_advanced_agent_guardrails returns the main agent's
middleware and the subagents'. Agent scope runs on the main agent only;
subagents get LLM and Tool scope.
- Every validator type and custom rules, at the stages the standard path
uses; Log, Block, Escalate (all recipient types) and Filter.
- Argument recipients read the run's input, which the wrapper keeps in
state when such a guardrail is configured.
- Filter removes top-level fields from a tool's arguments or result; on
any other scope it ends the run.
- create_advanced_agent takes subagent_middleware; the code interpreter
can exclude guarded tools and withhold task().
- Trace grouping accepts a parent resolver from the runtime.
Checks, actions and failure handling are the shared middleware's. Known
gaps, documented in the package docstring, are left to the shared
middleware: what the LLM and agent checks read, Escalate on resume and
reviewer edits, and errors being logged rather than ending the run.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Filter leaves text and array tool results alone instead of rewriting
them to {}.
- subagent_middleware is the last parameter of create_advanced_agent, so
positional callers keep working.
- Interpreter tests skip without the code-interpreter extra.
- Split the builder into helpers and tidied the tests Sonar flagged.
- Test that parallel subagents with an argument recipient finish.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
create_conversational_advanced_agent_graph accepts the converted middleware but neither declares this state field nor populates it in capture_exchange_start. Argument-based escalation therefore receives empty input and raises TERMINATION_ESCALATION_ERROR, even when the recipient is present in the conversational input schema. Mirror the field declaration and input-copy logic in that wrapper.
Preserve object shape when serializing filtered tool outputs
Returning this dictionary lets the shared create_modified_tool_result mistake a retained output field for its plain-text wrapper. For example, filtering secret from {"output":"safe","secret":"FLAG"} produces the raw text safe, not {"output":"safe"}. Serialize filtered object outputs explicitly (while keeping input arguments as dictionaries) so filtering preserves the remaining result's shape.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in d802c85: selector names are matched against each tool's display_name metadata, as the standard path does, and the tool's own name is used for both the middleware checks and guarded_tools. Covered by test_an_mcp_tool_selected_by_display_name_is_checked.
… filesystem tools out of eval
- A Tool-scope selector naming an MCP tool by its display name now maps to
the tool's own name, for the middleware checks and guarded_tools.
- exclude_from_ptc also applies to the filesystem tools offered in eval.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop exclude_from_ptc and allow_subagent_dispatch from the code
interpreter and guarded_tools from AdvancedAgentGuardrails. Sandbox
handling for agents with guardrails comes in a separate change; until
then, tools and subagents called from eval run without guardrails, as
the package docstring states.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Input capture is added only to the non-conversational wrapper. create_conversational_advanced_agent_graph also accepts these guardrails through middleware, but its capture_exchange_start never populates AGENT_INPUT_STATE_KEY, so argument-recipient escalations fail even when the exchange input contains the recipient. Apply the same conditional state declaration and input capture to the conversational wrapper.
Preserve JSON structure when filtering POST results
For a JSON result such as {"output": "safe", "secret": "FLAG"}, filtering secret returns {"output": "safe"}, but the shared create_modified_tool_result unwraps that single output key and writes plain safe. This changes the result's structure instead of only removing the selected field. JSON-serialize filtered POST objects before returning them, while keeping PRE arguments as dictionaries.
Evaluate structured responses in the Agent POST hook
The inherited Agent POST hook checks only the last AIMessage's text, not structured_response. With ToolStrategy, a final tool call with empty content and no attachments skips evaluation, so Agent-scoped output guardrails do not check the returned fields. Validate structured_response when present and add a regression test with a flagged structured answer.
…results' JSON shape
Agent-scope POST guardrails now evaluate the structured response when the
agent returns one, and a reviewer's edit replaces it. A Filter on a tool
result returns the remaining object as JSON, so a lone "output" key is no
longer unwrapped into plain text.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because nested guardrails can evaluate arguments the tool never received, while missing conversational input state can cause otherwise valid recipient escalations to fail.
It lets the runtime choose where a middleware check's trace container goes.
The second part changes the shared _grouping.py, which coded agents also use, and UiPath/uipath-agents-python#935 depends on it. It needs its own review and release. Its scope is AL-756: spans under the right model and tool calls, for parallel calls, and across a resume.
Keep the split a pure move, with no behaviour change in either PR. Review the trace part on the new PR.
Only component=tool_name, call_id=tool_call.get("id") in the two guardrail_stage(GuardrailScope.TOOL, ...) calls in _run_tool_guardrail, at PRE and POST
The _check_agent_output extraction from _after_agent_func
tests/guardrails/middlewares/test_grouping.py
The whole diff: three new imports and class TestParentResolver (4 tests)
Nothing
The _grouping.py diff contains:
GuardrailParentResolver and register_guardrail_parent_resolver;
close_deferred_guardrail_containers, close_guardrail_container_under and _end_deferred;
_resolved_place and _GroupingState.deferred;
the component and call_id parameters on guardrail_stage and _shared_container;
the deferred handling in GuardrailStageCloser.on_end and shutdown.
I checked that nothing under src/uipath_langchain/agent/advanced/ uses these functions and that no test under tests/agent/advanced/ registers a resolver. This PR keeps passing without them.
New PR (from main)
Create a branch and bring over the whole-file diffs:
In _base.py, add component=tool_name, call_id=tool_call.get("id") to the two tool guardrail_stage(...) calls in _run_tool_guardrail. Use git diff origin/main...f6176042 -- src/uipath_langchain/guardrails/middlewares/_base.py as the reference; only the first two hunks are yours.
uv run pytest tests/guardrails
uv run mypy --config-file pyproject.toml .
uv run ruff check .&& uv run ruff format --check .
Use a conventional-commit title, for example feat(guardrails): let the runtime choose where guardrail check containers go. In the body, say that coded agents don't change unless a resolver is registered, and that uipath-agents registers one in its trace PR.
Then put the two tool guardrail_stage(...) calls in _run_tool_guardrail back to their main form: drop component= and call_id= and undo the line wrapping. After that, the only _base.py change left here is _check_agent_output. Check that nothing is left behind (this should print nothing), then run the tests:
The two uipath-langchain PRs are independent: their only shared file is _base.py, and they touch different functions in it. Either can merge first. If the trace PR merges first, merging main here is clean.
uipath-agents needs a release with both: its trace PR imports the resolver functions, and its golden trace tests import build_advanced_agent_guardrails and create_advanced_agent(subagent_middleware=...) from this PR.
Done: the trace change is in #1267 as a pure move (_grouping.py, test_grouping.py, and the component/call_id arguments on the two tool guardrail_stage calls, version 0.21.12). This PR now keeps only the _check_agent_output extraction in _base.py; the leftover grep prints nothing and tests/agent/advanced tests/guardrails pass (846).
The reason will be displayed to describe this comment to others. Learn more.
Share the details with the low-code converter
_convert_action can't call build_guardrails_with_actions (agent/guardrails/guardrails_factory.py) directly. That function builds the graph-node actions in agent/guardrails/actions/, and this one builds middleware actions, with no common base. But the details the two share have already drifted:
Low-code
Advanced (this PR)
Block error
title Guardrail violation, detail Execution was blocked by guardrail [X], with reason: …
title Guardrail [X] blocked execution, detail is just the reason
Log text
the message, or Guardrail [X] validation failed for [SCOPE] [STAGE] with the following reason: …
[GUARDRAIL] [X] + the message, or Failed: …
Severity map
to logging.*
to LoggingSeverityLevel (an int enum with the same values)
Both raise the same error code, so only the text differs. Still, users see that text, and the parity tests (AL-757) may check it.
Suggestions
Block text: pass title and detail so the error reads as it does on low-code:
ifisinstance(action, AgentGuardrailBlockAction):
returnBlockAction(
title="Guardrail violation",
detail=f"Execution was blocked by guardrail [{guardrail.name}], with reason: {action.reason}",
)
Severity and title: use one AgentGuardrailSeverityLevel → LoggingSeverityLevel map and one title constant on both paths. LoggingSeverityLevel is an int enum, so the low-code LogAction(level=...) takes it as is.
Recipients: split a sync resolve_static_recipient(recipient, input_args) out of resolve_recipient_value in agent/tools/escalation_recipient.py, covering every type except assets. The async function calls it after the asset branch, and both paths use it. _resolve_without_io is then no longer needed, and so is driving the coroutine with send(None).
Later, optional: once low-code moves onto the shared middleware, the reuse goes the other way. _convert_action and _convert_escalate_action could then move to agent/guardrails/, next to the factory, rather than staying private to advanced/.
The reason will be displayed to describe this comment to others. Learn more.
Name this after agent.json custom guardrails, and keep it private
We agreed to support only the custom rules low-code agents have, not Python-callable rules as on coded agents. The behaviour matches that: the builder accepts only AgentCustomGuardrail. The class's name and its public export say otherwise.
Layer
Name
Studio Web
"Create custom"; $guardrailType: "custom"
agent.json model
AgentCustomGuardrail (word, number and boolean rules)
Low-code path
_convert_agent_custom_guardrail_to_deterministic; trace type "custom"
Read next to UiPathDeterministicGuardrailMiddleware, the name looks like the agent.json version of the Python-callable middleware.
Proposed changes
Rename it to AgentJsonCustomGuardrailMiddleware, and _deterministic.py to _custom.py, to match AgentCustomGuardrail and Studio Web. The change touches _builder.py (the import and middleware_class), both __init__.py files and the contract test. The class name doesn't appear in spans or graph node names, which come from the guardrail name and its index, and uipath-agents#935 doesn't reference it. So the rename doesn't change any trace.
Stop exporting AgentJsonGuardrailMiddleware and this class from agent/advanced/__init__.py and agent/advanced/guardrails/__init__.py. Keep only build_advanced_agent_guardrails and AdvancedAgentGuardrails public; feat(datafabric): fetch ontology R2RML alongside OWL #935 imports only those (plus create_advanced_agent).
The class takes any DeterministicGuardrail. In uipath-core, those rules carry detects_violation: Callable[...], so as a public class it accepts hand-written Python lambdas.
Through the builder, only agent.json rules get in: _convert_agent_rule_to_deterministic rejects any rule type other than word, number, boolean or universal at startup.
When AL-754 removes the overrides, there's no public class left to deprecate.
The contract test can import the classes from their private modules.
Using DeterministicGuardrail and DeterministicGuardrailsService inside the class is fine. They are uipath-core's engine names, and the low-code path uses them too.
Not for this PR: the startup error from _require_tool_scope says "Deterministic guardrail '{name}' can only be used with TOOL scope", while Studio Web users know these as custom guardrails. This PR only moved that code from the low-code factory, so rewording it changes the low-code message too. That's a separate small PR.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed together with UiPath/uipath-agents-python#935 and #1267. Two comments below, and one question on code outside the diff:
Question: should Agent scope run once per run? When the output file is missing, the wrapper sends the agent back in with a new user message (agent.py:856-863). If I read it right, the Agent input check then runs on that correction message, and the Agent output check runs a second time on the new answer. Is that intended, or should Agent scope run once per run?
The reason will be displayed to describe this comment to others. Learn more.
After Escalate moves out, fail at startup instead of skipping
Once the Escalate branch leaves _convert_action, an agent.json Escalate guardrail falls through to "uses an unknown action; skipped", and the agent runs without it. Today an advanced agent with any guardrail is rejected at startup (UiPath/uipath-agents-python#935 graph.py:365-377), so this would turn a configured check off without anyone noticing.
Raise AgentStartupError(INVALID_GUARDRAIL_CONFIG) for Escalate instead, with a message like "Escalate guardrails aren't supported on advanced agents yet"; #935 can add a test for it. The agent-input state moves to the Escalate PR with it: _reads_agent_input, AgentInputStateMiddleware, and the AGENT_INPUT_STATE_KEY handling in agent.py (784-810).
The reason will be displayed to describe this comment to others. Learn more.
Custom-rule checks get no evaluation span in the LLMOps trace
This override calls DeterministicGuardrailsService directly. Its @traced spans don't carry the custom-instrumentation marker, so uipath-agents drops them at export (FilteringSpanExporter(..., filter_fn=is_custom_instrumentation_span), UiPath/uipath-agents-python#935 factory.py:502-504). The coded custom-rule middleware wraps the same step (middlewares/deterministic.py:257-259):
Do the same here, and add a custom-rule case to #935's golden-trace tests.
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Runs an agent's
agent.jsonguardrails on an advanced agent as middleware.build_advanced_agent_guardrailsconverts each guardrail and its action, and returns the main agent's middleware and the subagents'.TERMINATION_GUARDRAIL_ERROR.create_advanced_agenttakessubagent_middleware.Trace container placement is in #1267.
Checks, actions and failure handling are the shared middleware's. The package docstring lists the known gaps, which are to be closed in the shared middleware (for coded agents too):
Code sandbox: this PR doesn't change the code interpreter. Tools and subagents called from
evalrun without guardrails; restricting or guarding them is a follow-up.Testing
🤖 Generated with Claude Code