Guardrails¶
Guardrails inspect inputs and outputs for policy violations — PII, harmful content, prompt injection, intellectual property, and custom rules — and respond by logging, blocking, or modifying the data.
The UiPath LangChain SDK exposes two complementary patterns:
- Middleware — a LangChain-native approach. Guardrail classes are passed as a list to
create_agent(..., middleware=[...]). Each class registers hooks (before_agent,after_agent,before_model,after_model,wrap_tool_call) automatically for the configured scope. - Decorator — the same
@guardrailAPI from the core SDK, extended to understand LangChain/LangGraph objects. Scope is inferred automatically from the decorated target type.
For the full list of validators, actions, execution stages, and the low-level API, see the core guardrails documentation.
Middleware pattern¶
Middleware is the preferred approach when all guardrail configuration should live in one place, next to the create_agent() call.
How it works¶
Each built-in middleware class is iterable — unpacking it with * yields one or more AgentMiddleware hook objects that LangChain registers internally. Pass them all inside the middleware=[] list:
from langchain.agents import create_agent
agent = create_agent(
model=llm,
tools=[my_tool],
system_prompt=SYSTEM_PROMPT,
middleware=[
*UiPathPIIDetectionMiddleware(...),
*UiPathHarmfulContentMiddleware(...),
# ... more middleware
],
)
Imports¶
from uipath_langchain.guardrails import (
BlockAction,
EscalateAction,
LogAction,
LoggingSeverityLevel,
UiPathDeterministicGuardrailMiddleware,
UiPathHarmfulContentMiddleware,
UiPathIntellectualPropertyMiddleware,
UiPathLLMAsJudgeMiddleware,
UiPathPIIDetectionMiddleware,
UiPathUserPromptAttacksMiddleware,
PIIDetectionEntity,
HarmfulContentEntity,
GuardrailExecutionStage,
)
from uipath_langchain.guardrails.enums import (
HarmfulContentEntityType,
IntellectualPropertyEntityType,
PIIDetectionEntityType,
)
from uipath.core.guardrails import GuardrailScope
Built-in middleware classes¶
| Class | Supported scopes | Stage support | Extra parameters |
|---|---|---|---|
UiPathPIIDetectionMiddleware |
AGENT, LLM, TOOL | PRE / POST / PRE_AND_POST | entities, tools, stage |
UiPathHarmfulContentMiddleware |
AGENT, LLM, TOOL | PRE / POST / PRE_AND_POST | entities, tools, stage |
UiPathUserPromptAttacksMiddleware |
LLM only | PRE only | — |
UiPathIntellectualPropertyMiddleware |
AGENT, LLM only | POST only | entities |
UiPathLLMAsJudgeMiddleware |
AGENT, LLM, TOOL | PRE / POST / PRE_AND_POST | guardrail_text, model, threshold, positive_examples, negative_examples, tools, stage |
UiPathDeterministicGuardrailMiddleware |
TOOL only | PRE / POST / PRE_AND_POST | tools, rules, stage |
UiPathByoGuardrailMiddleware |
AGENT, LLM, TOOL | PRE / POST / PRE_AND_POST | validator_name, validator_parameters, tools, stage |
TOOL scope for UiPathPIIDetectionMiddleware, UiPathHarmfulContentMiddleware, and UiPathLLMAsJudgeMiddleware requires passing tools=[...] to restrict wrap_tool_call hooks to specific tools.
All classes share these common parameters:
name(str) — display name for this guardrail instance.action— what to do on violation:LogAction(...),BlockAction(...), orEscalateAction(...)(escalate to a human — see Escalation action).scopes(list[GuardrailScope]) — restrict which hooks are registered. Defaults shown in the table above. UseGuardrailScope.AGENT,GuardrailScope.LLM,GuardrailScope.TOOL.enabled_for_evals(bool, defaultTrue) — setFalseto skip this guardrail when the agent runs in evaluation mode.detection_scope(defaultNone, sent to the Agents backend as the guardrail'sdetectionScopeparameter, shown as Detection scope in the Agents designer) — what the validator evaluates:DetectionScope.TEXTthe text only,DetectionScope.FILESthe attached files only,DetectionScope.BOTHboth. The strings"Text","Files"and"Both"are accepted too; any other value raisesValueError.Nonesends nodetectionScopeparameter, and the backend reads that asTextfor every validator, so files are read only when a guardrail asks for them.UiPathDeterministicGuardrailMiddlewarehas nodetection_scope: its rules run locally and see no files. ImportDetectionScopefromuipath_langchain.guardrails. See Files (attachments).
Additional parameters per class:
UiPathPIIDetectionMiddleware/UiPathHarmfulContentMiddleware:entities(list of entity configs),tools(restrict TOOL-scope hooks to specific tools),stage.UiPathUserPromptAttacksMiddleware: no extra parameters.UiPathIntellectualPropertyMiddleware:entities(list ofIntellectualPropertyEntityTypevalues).UiPathLLMAsJudgeMiddleware:guardrail_text(required — the plain-language rule the judge evaluates against, ≤ 4000 chars),model(required — judge model id, e.g."gpt-4o-2024-08-06"; must be a model your governance policy allows for the LLM-as-judge guardrail — LLM Gateway enforces the permitted list),threshold(0strictest …6most lenient, default2),positive_examples/negative_examples(optional calibration payloads — ≤ 2 each, ≤ 1000 chars each),tools(required only whenGuardrailScope.TOOLis used),stage. See the core guardrails documentation for the full parameter reference.UiPathDeterministicGuardrailMiddleware:tools(required — list of tools to guard),rules(list of lambda functions),stage.UiPathByoGuardrailMiddleware:validator_name(required — the BYOG configuration's validator name, unique per tenant),validator_parameters(optional connector-defined parameters, passed through as-is),tools(required only whenGuardrailScope.TOOLis used),stage. See Bring Your Own Guardrail.
Full example¶
from langchain.agents import create_agent
from langchain_core.tools import tool
from uipath_langchain.chat import UiPathChat
from uipath_langchain.guardrails import (
BlockAction,
LogAction,
LoggingSeverityLevel,
UiPathDeterministicGuardrailMiddleware,
UiPathHarmfulContentMiddleware,
UiPathIntellectualPropertyMiddleware,
UiPathLLMAsJudgeMiddleware,
UiPathPIIDetectionMiddleware,
UiPathUserPromptAttacksMiddleware,
PIIDetectionEntity,
HarmfulContentEntity,
GuardrailExecutionStage,
)
from uipath_langchain.guardrails.enums import (
HarmfulContentEntityType,
IntellectualPropertyEntityType,
PIIDetectionEntityType,
)
from uipath.core.guardrails import GuardrailScope
@tool
def analyze_text(text: str) -> str:
"""Count words in the provided text."""
return f"Word count: {len(text.split())}"
llm = UiPathChat(model="gpt-4o-2024-08-06")
agent = create_agent(
model=llm,
tools=[analyze_text],
system_prompt="You are a helpful assistant.",
middleware=[
# PII detection on agent input/output and LLM messages
*UiPathPIIDetectionMiddleware(
name="PII detector",
scopes=[GuardrailScope.AGENT, GuardrailScope.LLM],
action=LogAction(severity_level=LoggingSeverityLevel.WARNING),
entities=[
PIIDetectionEntity(PIIDetectionEntityType.EMAIL, threshold=0.5),
PIIDetectionEntity(PIIDetectionEntityType.CREDIT_CARD_NUMBER, threshold=0.5),
],
),
# PII detection restricted to TOOL scope for specific tools
*UiPathPIIDetectionMiddleware(
name="Tool PII detector",
scopes=[GuardrailScope.TOOL],
action=LogAction(severity_level=LoggingSeverityLevel.WARNING),
entities=[
PIIDetectionEntity(PIIDetectionEntityType.PHONE_NUMBER, threshold=0.5),
],
tools=[analyze_text],
enabled_for_evals=False,
),
# Block adversarial user prompts at the LLM level
*UiPathUserPromptAttacksMiddleware(
name="User prompt attacks",
action=BlockAction(),
enabled_for_evals=False,
),
# Block harmful content in agent + LLM messages
*UiPathHarmfulContentMiddleware(
name="Harmful content",
scopes=[GuardrailScope.AGENT, GuardrailScope.LLM],
action=BlockAction(),
entities=[
HarmfulContentEntity(HarmfulContentEntityType.VIOLENCE, threshold=2),
],
),
# Log IP violations in LLM output (POST only)
*UiPathIntellectualPropertyMiddleware(
name="IP detection",
scopes=[GuardrailScope.LLM],
action=LogAction(severity_level=LoggingSeverityLevel.WARNING),
entities=[IntellectualPropertyEntityType.TEXT],
),
# LLM-as-judge: block responses that violate a plain-language rule (POST)
*UiPathLLMAsJudgeMiddleware(
name="No financial advice",
scopes=[GuardrailScope.AGENT],
action=BlockAction(),
guardrail_text=(
"The response must remain professional and must not contain "
"financial or investment advice."
),
model="gpt-4o-2024-08-06",
stage=GuardrailExecutionStage.POST,
),
# Deterministic: block tool input longer than 1000 chars
*UiPathDeterministicGuardrailMiddleware(
tools=[analyze_text],
rules=[lambda data: len(data.get("text", "")) > 1000],
action=BlockAction(detail="Input too long"),
stage=GuardrailExecutionStage.PRE,
name="Length limiter",
),
],
)
Files (attachments)¶
Every built-in middleware class except UiPathDeterministicGuardrailMiddleware can forward references to the files the run holds; which files each hook sends is in the table below, and detection_scope=Text sends none. UiPathByoGuardrailMiddleware accepts detection_scope, but BYO guardrails evaluate text only; the files are not read. Only references are forwarded: {id, fileName, mimeType} for each file, at most 5 per evaluation. The Agents backend downloads each file by its Orchestrator id, decodes or extracts it, and evaluates it. File reading is gated by the tenant's guardrail file-support flags; where they are off, a guardrail configured for files degrades to text. detection_scope sets whether the validator evaluates the text, the files or both (see the common parameters above).
from uipath_langchain.guardrails import DetectionScope
agent = create_agent(
model=llm,
tools=[analyze_files],
middleware=[
*UiPathHarmfulContentMiddleware(
name="Harmful content in attached files",
scopes=[GuardrailScope.AGENT],
stage=GuardrailExecutionStage.PRE,
action=BlockAction(),
entities=[
HarmfulContentEntity(HarmfulContentEntityType.VIOLENCE, threshold=2),
],
detection_scope=DetectionScope.FILES,
),
],
)
How a file becomes visible to a guardrail:
| Source | What you do | What the guardrails find |
|---|---|---|
Typed Attachment input (file: Attachment in the input schema) |
Render it into the prompt with render_attachments_block (below) |
The <uip:attachments> block in the HumanMessage. The model reads it and copies the object into tool arguments |
| Conversational agents | Nothing | The attachments the runtime puts on each HumanMessage (additional_kwargs["attachments"] and the same block) |
| Tool arguments | Nothing: the model copies {"ID", "FullName", "MimeType"} from the block |
The ids in the arguments that the run already holds |
| Tool results | Return {"ID", "FullName", "MimeType"} from the tool, as Create File does |
The files the result returns. Later hooks treat them as held |
| SDK-built multimodal blocks | Build them with build_file_content_blocks_for from a FileInfo that has an attachment_id, and keep them in the messages |
The id each image or file block carries in extras["uipath_attachment_id"] (TIFF pages are not tagged) |
| Author-built raw base64 blocks | — | Nothing. Raw bytes carry no attachment id, so they are not forwarded (known gap) |
An advanced agent's uipath__job_attachments state is read too.
render_attachments_block writes the same <uip:attachments>[{"ID", "FullName", "MimeType"}]</uip:attachments> text the conversational runtime writes:
from langchain_core.messages import HumanMessage
from pydantic import BaseModel
from uipath.platform.attachments import Attachment
from uipath_langchain.guardrails import render_attachments_block
class Input(BaseModel):
file: Attachment
async def screen_cv(state: Input):
# `agent` is a create_agent(..., response_format=..., middleware=[...]) graph.
attachment = state.file.model_dump(mode="json", exclude_none=True)
prompt = (
"Summarise the CV in the attached file using the Analyze Files tool.\n"
f"{render_attachments_block([attachment])}"
)
result = await agent.ainvoke({"messages": [HumanMessage(content=prompt)]})
return result["structured_response"]
Which files each hook forwards:
| Hook | Forwards |
|---|---|
before_agent, before_model |
Every file the run holds |
wrap_tool_call, PRE |
The files the tool arguments name, if the run holds them |
wrap_tool_call, POST |
The files the tool result names: held ones, and new ones it describes with a name and a type |
after_model |
The held files the model's message names, in its content or its tool calls |
after_agent |
The held files the final message or the structured response names |
Notes:
- An id the run never held is not forwarded. Ids in tool arguments and in the model's or the agent's output are matched against the files the run holds, so an id a prompt-injected argument names is skipped instead of being sent for lookup. A file a tool result describes with its own name and type counts as that tool's output, and is held from then on.
- Text is evaluated with the files. A message whose only text is the
<uip:attachments>block is not empty: that text is sent with the files. A check that has files but no text at all, such as one on a message made only of file blocks, evaluates the placeholder[no text content]as its text. - No file found, or none readable. When the detection scope includes files (
FilesorBoth, set bydetection_scopeor adetectionScopeparameter) and a check finds no file, the request carries an empty attachment list: aFilesguardrail then passes without a provider call and aBothguardrail still evaluates the text. When a payload or the state cannot be read, the request says nothing about files and the text is evaluated as before. - A rejected reference never disables a guardrail. When the validate API rejects the attachment references (HTTP 400), the check runs again without them and logs a warning. The check then degrades to text.
- Filters apply to text only. An action that returns modified data, like the
RedactActionin Custom actions, rewrites text; a verdict about a file cannot rewrite the file. ForFiles, useBlockAction,LogActionorEscalateAction.
Deterministic middleware¶
UiPathDeterministicGuardrailMiddleware applies in-process rule functions without any API call.
rules— list of callables. ForPREstage:(input_dict: dict) -> bool. ForPOSTstage:(input_dict: dict, output_dict: dict) -> bool. ReturnTrueto signal a violation.rules=[](empty list) — always triggers the action, useful for unconditional transforms.stage—GuardrailExecutionStage.PRE,POST, orPRE_AND_POST.
# Always replace a word in tool output (unconditional transform, empty rules)
*UiPathDeterministicGuardrailMiddleware(
tools=[analyze_text],
rules=[],
action=CustomFilterAction(word_to_filter="count", replacement="total"),
stage=GuardrailExecutionStage.POST,
name="Output transformer",
),
Bring Your Own Guardrail (BYOG)¶
Platform Availability
UiPathByoGuardrailMiddleware ships in the uipath-langchain package on PyPI and works on any tenant where Bring Your Own Guardrail is enabled. The admin step it depends on — configuring a guardrail connection from a guardrail connection template under Admin → AI Trust Layer → Guardrails Configurations — is still rolling out and isn't enabled on every tenant yet. If that page isn't in your Admin panel, BYOG isn't enabled on yours — watch the UiPath product release notes for when it lands.
UiPathByoGuardrailMiddleware runs a customer-managed validator instead of a UiPath-managed one — for example a cloud content-safety subscription, a vendor validation service, or a custom Integration Service connector wrapping an internal classifier.
Admin prerequisite. An Org Admin first creates the BYOG configuration under Admin → AI Trust Layer → Guardrails Configurations: pick a guardrail connector (a UiPath-shipped one or a custom one wrapping your own vendor), create an Integration Service connection with your credentials, and save the configuration with a validator name.
The middleware references that configuration by name:
from uipath.core.guardrails import GuardrailScope
from uipath_langchain.guardrails import (
BlockAction,
UiPathByoGuardrailMiddleware,
)
byog = UiPathByoGuardrailMiddleware(
validator_name="my-harmful-content-guardrail", # the configuration's validator name
scopes=[GuardrailScope.AGENT],
action=BlockAction(),
)
agent = create_agent(model=llm, tools=[...], middleware=[*byog])
To find the validator_name, list your tenant's BYOG configurations:
Each entry carries ByoValidatorName (→ validator_name), alongside its AllowedScopes / GuardrailStages and the full Parameters schema. No connection details are needed: the Integration Service connection is resolved server-side from the BYOG configuration.
Notes:
- The name is the identity. Validator names are unique per tenant, so the name alone resolves the configuration; the connection comes from the configuration, so an admin rebind is always honored.
- You choose the scopes and stages. BYOG validators are not scope- or stage-restricted: like the built-in validators they are available on AGENT, LLM and TOOL scope for both PRE and POST, and it is up to you which ones to register. The entry's
AllowedScopes/GuardrailStagesin the CLI output confirm what a given validator accepts. - Parameters are connector-defined. Pass
validator_parametersas raw parameter values when your connector expects them; there is no static schema on the client. See Tuning a BYOG validator below. - Error semantics. A removed or disabled configuration, BYOG not being enabled for the tenant, or a vendor failure (with fallback off) returns
PROVIDER_ERROR/FEATURE_DISABLED— the middleware treats these like any non-failed result (fail-open) and logs the details. Fallback to the UiPath-managed validator (FallbackOnUiPath) applies only when the configuration's validator type maps to an out-of-the-box validator.
Tuning a BYOG validator¶
validator_parameters is forwarded to the guardrail on every evaluation. The parameter ids, types and allowed values are defined by the guardrail connector, not by this SDK — read them from the validator's Parameters array in uip agent guardrails list --byo, which gives each parameter's Id, Type, whether it is Required, its DefaultValue, and the applicable Options / KeySource / Min / Max / Step. Omit the argument to fall back to those DefaultValues.
from uipath.platform.guardrails import EnumListParameterValue, MapEnumParameterValue
from uipath_langchain.guardrails.enums import HarmfulContentEntityType
# Example for the Azure Content Safety connector's `harmful_content` validator:
# select the harm categories and set a per-category severity threshold.
byog_parameters = [
EnumListParameterValue(
parameter_type="enum-list",
id="harmfulContentEntities",
value=[entity.value for entity in HarmfulContentEntityType],
),
MapEnumParameterValue(
parameter_type="map-enum",
id="harmfulContentEntityThresholds",
value={entity.value: 4 for entity in HarmfulContentEntityType},
),
]
byog = UiPathByoGuardrailMiddleware(
validator_name="my-harmful-content-guardrail",
scopes=[GuardrailScope.AGENT],
action=BlockAction(),
validator_parameters=byog_parameters,
)
That connector flags a category when severity >= threshold on Azure's 0/2/4/6 scale, so a threshold of 4 lets low-severity (2) content through while still blocking 4 and 6; categories that are not selected are ignored. Other connectors define their own parameters — always read the ids out of uip agent guardrails list --byo rather than assuming these ones.
Custom middleware hooks¶
For logic that doesn't fit a built-in class, implement raw middleware hooks using the langchain.agents.middleware decorators and pass them directly to the middleware list.
Available hook decorators: before_agent, after_agent, before_model, after_model, wrap_tool_call.
from langchain.agents.middleware import AgentState, before_agent, after_agent
from langchain_core.messages import AIMessage, HumanMessage
from langgraph.runtime import Runtime
@before_agent
async def log_agent_input(state: AgentState, runtime: Runtime) -> None:
for msg in reversed(state.get("messages", [])):
if isinstance(msg, HumanMessage):
print(f"[INPUT] {msg.content}")
break
@after_agent
async def log_agent_output(state: AgentState, runtime: Runtime) -> None:
for msg in reversed(state.get("messages", [])):
if isinstance(msg, AIMessage):
print(f"[OUTPUT] {msg.content}")
break
LoggingMiddleware = [log_agent_input, log_agent_output]
agent = create_agent(
model=llm,
tools=[analyze_text],
middleware=[
*LoggingMiddleware,
*UiPathPIIDetectionMiddleware(...),
],
)
Escalation action (human-in-the-loop)¶
EscalateAction routes a violation to a human reviewer instead of logging or blocking it. On a violation it builds the review payload and calls the documented HITL primitive interrupt(CreateEscalation(...)) — creating a task in a UiPath Action App and suspending the run until the reviewer responds. On resume:
- Approve — if the reviewer edited the content, the edited value is substituted back into the flagged message / tool args / output; otherwise the original is kept. The edit is read from
ReviewedInputsfor a PRE (input) escalation andReviewedOutputsfor a POST (output) one. - Reject — raises
GuardrailBlockException, terminating the run.
from uipath_langchain.guardrails import EscalateAction
from uipath.platform.action_center.tasks import TaskRecipient, TaskRecipientType
*UiPathPIIDetectionMiddleware(
name="PII escalation",
scopes=[GuardrailScope.AGENT],
stage=GuardrailExecutionStage.PRE, # validate once → escalate once per run
action=EscalateAction(
app_name="Guardrail Escalation Action App",
app_folder_path="Shared",
# route the review task to a specific recipient (user / group / email)
recipient=TaskRecipient(
type=TaskRecipientType.EMAIL, value="reviewer@example.com"
),
),
entities=[PIIDetectionEntity(PIIDetectionEntityType.EMAIL, threshold=0.5)],
),
Parameters:
app_name(str, required) — the published Action App that renders the review task.app_folder_path(str) — folder where the app is deployed.assignee(str) — the simple username/email to assign the task to.recipient(TaskRecipient) — a typed escalation target (shown above); takes precedence overassignee. Supports the fourTaskRecipientTypemembers —USER_ID,GROUP_ID,EMAIL(user email), andGROUP_NAME, e.g.TaskRecipient(type=TaskRecipientType.GROUP_NAME, value="Reviewers").title(str) — task title; defaults to a message derived from the guardrail name.
💡 Escalate once per run. On AGENT/LLM scope a guardrail validates both before and after by default, which can escalate twice. Set
stage=GuardrailExecutionStage.PRE(orPOST) so only a single checkpoint is registered.⚠️ Requires a published Action App. The target app must exist in the configured folder for the task to be created. Resume is durable — the run suspends on
interrupt()and resumes when the task is completed. See Human In The Loop for the underlying primitive.
Custom actions¶
Both the built-in middleware and UiPathDeterministicGuardrailMiddleware accept any GuardrailAction subclass as the action parameter. This lets you implement content sanitisation, redaction, or any other custom response to a violation:
import re
from dataclasses import dataclass
from typing import Any
from uipath.core.guardrails import GuardrailValidationResult, GuardrailValidationResultType
from uipath_langchain.guardrails import GuardrailAction
@dataclass
class RedactAction(GuardrailAction):
pattern: str
replacement: str = "[REDACTED]"
def handle_validation_result(
self,
result: GuardrailValidationResult,
data: str | dict[str, Any],
guardrail_name: str,
) -> str | dict[str, Any] | None:
if result.result != GuardrailValidationResultType.VALIDATION_FAILED:
return None
if isinstance(data, str):
return re.sub(self.pattern, self.replacement, data, flags=re.IGNORECASE)
return None
Decorator pattern¶
Importing uipath_langchain.guardrails auto-registers a LangChain adapter that extends @guardrail to wrap LangChain/LangGraph objects in addition to plain Python callables. All validators, actions, execution stages, stacking, and GuardrailExclude work exactly as described in the core guardrails documentation — use uipath_langchain.guardrails as the import path, which re-exports everything from the core SDK. @guardrail takes the same detection_scope as the middleware classes (DetectionScope.TEXT / FILES / BOTH or the strings; None is text only) — see Files.
LangChain target types¶
On LangChain objects, scope is inferred automatically from the target — no stage inference, but no explicit scopes= parameter is needed either:
| Decorated target | Inferred scope | Notes |
|---|---|---|
@tool function |
TOOL | @guardrail must be placed above @tool |
BaseChatModel factory |
LLM | Decorate the factory function, not the model instance |
create_agent() factory |
AGENT | Decorate the factory function, not the returned agent |
| LangGraph node (async fn) | AGENT | — |
LLM factory¶
from uipath_langchain.chat import UiPathChat
from uipath_langchain.guardrails import guardrail, PIIValidator, BlockAction, GuardrailExecutionStage, PIIDetectionEntity
from uipath_langchain.guardrails.enums import PIIDetectionEntityType
@guardrail(
validator=PIIValidator(
entities=[PIIDetectionEntity(PIIDetectionEntityType.EMAIL, threshold=0.5)],
),
action=BlockAction(),
name="LLM PII check",
stage=GuardrailExecutionStage.PRE,
)
def create_llm():
return UiPathChat(model="gpt-4o-2024-08-06")
llm = create_llm()
Tool¶
@guardrail must be placed above @tool:
from langchain_core.tools import tool
from uipath_langchain.guardrails import guardrail, CustomValidator, BlockAction, GuardrailExecutionStage
@guardrail(
validator=CustomValidator(lambda args: len(args.get("text", "")) > 1000),
action=BlockAction(detail="Text exceeds 1000 characters"),
stage=GuardrailExecutionStage.PRE,
name="Length limiter",
)
@tool
def analyze_text(text: str) -> str:
"""Count words in the provided text."""
return f"Word count: {len(text.split())}"
The guard runs on invoke and ainvoke, so an async def tool, or one built with coroutine=, is checked in an async run too. To guard a tool object a factory returns, call the decorator on it: guardrail(validator=..., action=...)(create_analyze_file_tool(...)).
Agent factory¶
from langchain.agents import create_agent
from uipath_langchain.guardrails import guardrail, HarmfulContentValidator, BlockAction, GuardrailExecutionStage, HarmfulContentEntity
from uipath_langchain.guardrails.enums import HarmfulContentEntityType
@guardrail(
validator=HarmfulContentValidator(
entities=[HarmfulContentEntity(HarmfulContentEntityType.VIOLENCE, threshold=2)],
),
action=BlockAction(),
name="Block harmful content",
stage=GuardrailExecutionStage.PRE,
)
def create_my_agent():
return create_agent(model=llm, tools=[analyze_text], system_prompt="...")
agent = create_my_agent()
LLM-as-judge¶
Use LLMAsJudgeValidator to check content against a plain-language rule via a judge LLM. Scope is inferred from the decorated target (here, the agent factory → AGENT scope). See the core guardrails documentation for the full parameter reference (threshold, positive_examples, negative_examples, and their limits).
from langchain.agents import create_agent
from uipath_langchain.guardrails import guardrail, LLMAsJudgeValidator, BlockAction, GuardrailExecutionStage
@guardrail(
validator=LLMAsJudgeValidator(
guardrail_text=(
"The response must remain professional and must not contain "
"financial or investment advice."
),
model="gpt-4o-2024-08-06",
threshold=2,
),
action=BlockAction(),
name="No financial advice",
stage=GuardrailExecutionStage.POST,
)
def create_my_agent():
return create_agent(model=llm, tools=[analyze_text], system_prompt="...")
agent = create_my_agent()
LangGraph node¶
from uipath_langchain.guardrails import guardrail, PIIValidator, BlockAction, GuardrailExecutionStage, PIIDetectionEntity
from uipath_langchain.guardrails.enums import PIIDetectionEntityType
@guardrail(
validator=PIIValidator(
entities=[PIIDetectionEntity(PIIDetectionEntityType.PERSON, threshold=0.5)],
),
action=BlockAction(title="Person name in input"),
name="Node PII check",
stage=GuardrailExecutionStage.PRE,
)
async def my_node(state: Input) -> Output:
...
Files¶
API-based validators forward file references from the decorated target, with the same reference format, limit of 5, detection_scope scopes and HTTP 400 text-only retry as the middleware. The LLM and graph targets evaluate the placeholder [no text content] when the messages hold files but no text. Where the files come from depends on the target:
| Decorated target | PRE forwards | POST forwards |
|---|---|---|
| Plain or async function | Attachment arguments and {"ID", "FullName", "MimeType"} mappings in the arguments; GuardrailExclude parameters are not scanned |
The same shapes in the return value |
Tool (@tool, BaseTool) |
Mentions in the tool input that carry their own name and type | Mentions in the tool result that carry their own name and type |
LLM factory (BaseChatModel) |
Every file the message list holds, read as the middleware reads it | The held files the response names |
Agent factory, StateGraph, compiled graph |
Every file the input messages hold, plus attachments in the other input state keys | The held files the last message or structured_response names, plus attachments in the other output state keys, including an input key the graph echoes |
Notes:
- Tool mentions are self-describing. The tool wrapper sees no message history, so a mention is forwarded with the name and type it carries, without checking that the run holds it. Treat a decorated tool like any other tool that can read attachments by id; the middleware matches ids against the files the run holds.
- Graph targets need
messages. An input or an output without amessageskey is not checked. - Tools are guarded on
invokeandainvoke. In an async run (agent.ainvoke), the tool node calls tools throughainvoke, so a tool with a coroutine (anasync deftool, or one built withcoroutine=, such as the Analyze Files tool fromcreate_analyze_file_tool) and aBaseToolsubclass are checked as well. A sync tool thatainvokeruns throughinvokeis checked once per stage. Callingrunorarundirectly skips the guard.
Bring Your Own Guardrail (BYOG)¶
Platform Availability
Same rollout as the middleware flavor — the guardrail connection template configuration isn't enabled on every tenant yet. See Bring Your Own Guardrail (BYOG) under the middleware pattern.
ByoValidator is the decorator equivalent of UiPathByoGuardrailMiddleware: it runs a customer-managed validator instead of a UiPath-managed one — your own content-safety subscription, a vendor validation service, or a custom Integration Service connector wrapping an internal classifier.
The admin prerequisite and how to look up the validator name and parameter schema are the same as for the middleware flavor — see Bring Your Own Guardrail (BYOG) under the middleware pattern.
The validator references that configuration by name; scope is inferred from the decorated target as usual:
from uipath_langchain.guardrails import BlockAction, ByoValidator, guardrail
byog_harmful_content = ByoValidator(
"my-harmful-content-guardrail", # the configuration's validator name (unique per tenant)
)
@guardrail(validator=byog_harmful_content, action=BlockAction())
def create_joke_agent():
return create_agent(model=llm, tools=[...])
Notes specific to the decorator path — the middleware notes on naming, scopes/stages and connector-defined parameters apply here too:
parametersinstead ofvalidator_parameters. Same passthrough of raw parameter values; read the ids and allowed values from the validator'sParametersarray inuip agent guardrails list --byo.- No static stage restriction. Because BYOG validators are available on every scope and stage,
ByoValidatordeclares nosupported_stages— you pick thestage, and the scope comes from the decorated target. - Error semantics. A removed or disabled configuration, BYOG not being enabled for the tenant, or a vendor failure (with fallback off) returns
PROVIDER_ERROR/FEATURE_DISABLED— the decorator path treats these like any non-failed result (fail-open) and logs the details, including the guardrail name and traceback.
Escalation action (human-in-the-loop)¶
EscalateAction works on the decorator path exactly as it does for middleware — on a violation it suspends the run via interrupt(CreateEscalation(...)), creates a review task in a UiPath Action App, and resumes on Approve/Reject. It is the same action class as the middleware path; just pass it as the action of a @guardrail on the factory you want to guard. The escalation task's Component / ExecutionStage are derived automatically from the inferred scope of the decorated target — no extra configuration:
from langchain.agents import create_agent
from uipath_langchain.guardrails import (
guardrail,
EscalateAction,
PIIValidator,
GuardrailExecutionStage,
PIIDetectionEntity,
)
from uipath_langchain.guardrails.enums import PIIDetectionEntityType
from uipath.platform.action_center.tasks import TaskRecipient, TaskRecipientType
@guardrail(
validator=PIIValidator(
entities=[PIIDetectionEntity(PIIDetectionEntityType.EMAIL, threshold=0.5)],
),
action=EscalateAction(
app_name="Guardrail Escalation Action App",
app_folder_path="Shared",
# optional: route the review task to a specific recipient
recipient=TaskRecipient(
type=TaskRecipientType.EMAIL, value="reviewer@example.com"
),
),
name="Agent PII escalation",
stage=GuardrailExecutionStage.PRE, # escalate once per run
)
def create_my_agent():
return create_agent(model=llm, tools=[analyze_text], system_prompt="...")
agent = create_my_agent()
On resume: Approve continues, substituting the reviewer's edit if any — read from ReviewedInputs for a PRE (input) escalation and ReviewedOutputs for a POST (output) one, otherwise keeping the original; Reject raises GuardrailBlockException and terminates the run. The app_name / app_folder_path / assignee / recipient / title parameters and the auto-derived payload fields behave identically to the middleware escalation action above — refer to it for the full parameter list.
💡 Scope inference for the payload context.
Component/ExecutionStageare derived automatically for the adapter-handled LangChain targets —@tool,BaseChatModelfactories, andcreate_agent()factories. On a plain LangGraph node or plain Python function (handled by the core@guardrail, which doesn't publish the LangChain runtime context) the escalation still suspends, but those two fields are not populated.💡 Escalate once per run. As with middleware, AGENT/LLM scope validates both before and after by default. Set
stage=GuardrailExecutionStage.PRE(orPOST) so only a single checkpoint is registered.
Choosing between middleware and decorator¶
| Middleware | Decorator | |
|---|---|---|
| Configuration location | Centralised in create_agent() |
Per-target, co-located with the object |
| Scope specification | Explicit scopes= parameter |
Auto-inferred from the decorated type |
Works outside create_agent |
No | Yes — any LangGraph graph or plain function |
| Reusable validator objects | No | Yes — declare once, use in multiple decorators |
| Parameter exclusion | No | GuardrailExclude() annotation |
| Custom deterministic rules | UiPathDeterministicGuardrailMiddleware(rules=[...]) |
CustomValidator(lambda ...) |
Use middleware when you want all guardrail policy in one place alongside a single create_agent() call. Use decorators when building custom LangGraph graphs, reusing validators across multiple agents, or guarding code outside the agent context.
Sample agents¶
samples/joke-agent— middleware patternsamples/joke-agent-decorator— decorator patternsamples/joke-agent-bring-your-own-guardrail— Bring Your Own Guardrail, both patterns in one agent (middleware logging on the agent scope, decorator blocking on the LLM)samples/cv-screener-agent— file guardrails, both patterns in one agent (decorators on the LLM and the Analyze Files tool, middleware on the agent), with aPARITY_CHECKswitch that adds the other pattern of each guardrail
Reference¶
GuardrailScope¶
Imported from uipath.core.guardrails.
| Value | Description |
|---|---|
AGENT |
Hooks run at agent input/output boundary (before_agent / after_agent) |
LLM |
Hooks run around every LLM call (before_model / after_model) |
TOOL |
Hooks run around every tool call (wrap_tool_call) |
GuardrailExecutionStage¶
Imported from uipath_langchain.guardrails.
| Value | When it fires |
|---|---|
PRE |
Before the call (inspect / block inputs) |
POST |
After the call (inspect / transform outputs) |
PRE_AND_POST |
Both checkpoints (the default) |
LoggingSeverityLevel¶
Used in LogAction(severity_level=...). Imported from uipath_langchain.guardrails.
| Value |
|---|
DEBUG |
INFO |
WARNING |
ERROR |
PIIDetectionEntityType¶
Imported from uipath_langchain.guardrails.enums. Wrap each value in PIIDetectionEntity(entity_type, threshold=0.5) — threshold is a float from 0.0 to 1.0.
PII detection entity types supported by UiPath guardrails.
| Value |
|---|
PERSON |
ADDRESS |
DATE |
PHONE_NUMBER |
EUGPS_COORDINATES |
EMAIL |
CREDIT_CARD_NUMBER |
INTERNATIONAL_BANKING_ACCOUNT_NUMBER |
SWIFT_CODE |
ABA_ROUTING_NUMBER |
US_DRIVERS_LICENSE_NUMBER |
UK_DRIVERS_LICENSE_NUMBER |
US_INDIVIDUAL_TAXPAYER_IDENTIFICATION |
UK_UNIQUE_TAXPAYER_NUMBER |
US_BANK_ACCOUNT_NUMBER |
US_SOCIAL_SECURITY_NUMBER |
USUK_PASSPORT_NUMBER |
URL |
IP_ADDRESS |
HarmfulContentEntityType¶
Imported from uipath_langchain.guardrails.enums. Wrap each value in HarmfulContentEntity(entity_type, threshold=2) — threshold must be one of 0, 2, 4, or 6 (higher = less sensitive).
Harmful content entity types supported by UiPath guardrails.
| Value |
|---|
HATE |
SELF_HARM |
SEXUAL |
VIOLENCE |
IntellectualPropertyEntityType¶
Imported from uipath_langchain.guardrails.enums. Pass values directly in entities=[...] — no wrapper model class.
Intellectual property entity types supported by UiPath guardrails.
| Value |
|---|
TEXT |
CODE |