Implementation:Guardrails ai Guardrails Guard Use
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Validation, API |
| Last Updated | 2026-02-14 00:00 GMT |
Overview
Concrete method for attaching validators to a Guard instance provided by the guardrails package.
Description
The Guard.use method adds a single validator to the Guard's validation pipeline. It accepts an instantiated Validator (or deprecated: a Validator class with arguments), hydrates it, registers it in the Guard's internal validator map keyed by target path, and persists the Guard state if running in server mode.
Usage
Use this method when constructing a Guard pipeline by attaching validators one at a time. Chain multiple .use() calls for a fluent builder pattern.
Code Reference
Source Location
- Repository: guardrails
- File: guardrails/guard.py
- Lines: L907-940
Signature
def use(
self,
validator: UseValidatorSpec,
*args,
on: str = "output",
**kwargs,
) -> "Guard":
"""Use a validator to validate either of the following:
- The output of an LLM request
- The message history
Args:
validator: The validator to use. Either the class or an instance.
on: The part of the LLM request to validate. Defaults to "output".
"""
Import
from guardrails import Guard
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| validator | UseValidatorSpec | Yes | A Validator instance (or deprecated: Validator class with args) |
| on | str | No | Target for validation: "output" (default), "messages", or JSON path like "$.field" |
Outputs
| Name | Type | Description |
|---|---|---|
| self | Guard | Returns the Guard instance (fluent interface for chaining) |
Usage Examples
Basic Validator Attachment
from guardrails import Guard
from guardrails.hub import RegexMatch, ToxicLanguage
# Chain validators using fluent API
guard = Guard().use(
RegexMatch(regex=r"\d{3}-\d{2}-\d{4}", on_fail="exception")
).use(
ToxicLanguage(on_fail="fix")
)
Field-Level Validation
from guardrails import Guard
from guardrails.hub import ValidLength
# Target a specific JSON path
guard = Guard().use(
ValidLength(min=1, max=100, on_fail="fix"),
on="$.name"
)
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment