Implementation:Guardrails ai Guardrails Guard For Pydantic
| Knowledge Sources | |
|---|---|
| Domains | Factory_Pattern, Structured_Output |
| Last Updated | 2026-02-14 00:00 GMT |
Overview
Concrete factory classmethod for creating a Guard from a Pydantic model provided by the guardrails package.
Description
The Guard.for_pydantic classmethod accepts a Pydantic BaseModel class (or List of models), extracts its JSON schema and embedded validators via pydantic_model_to_schema, and returns a Guard instance configured for structured output generation. It supports optional output formatters including the jsonformer constrained decoding backend.
Usage
Use this classmethod when you have a Pydantic model defining the desired output structure. Pass the model class to get a Guard ready for structured output generation.
Code Reference
Source Location
- Repository: guardrails
- File: guardrails/guard.py
- Lines: L453-508
Signature
@classmethod
def for_pydantic(
cls,
output_class: ModelOrListOfModels,
*,
reask_messages: Optional[List[Dict]] = None,
messages: Optional[List[Dict]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
output_formatter: Optional[Union[str, BaseFormatter]] = None,
):
"""Create a Guard instance using a Pydantic model to specify the output schema.
Args:
output_class: The pydantic model that describes the desired output structure.
messages: A list of messages to give to the LLM.
reask_messages: A list of messages to use during reasks.
name: A unique name for this Guard.
description: A description for this Guard.
output_formatter: 'none' (default), 'jsonformer', or a Guardrails Formatter.
"""
Import
from guardrails import Guard
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| output_class | ModelOrListOfModels | Yes | Pydantic BaseModel class or List[BaseModel] |
| messages | Optional[List[Dict]] | No | Default LLM messages |
| reask_messages | Optional[List[Dict]] | No | Messages for re-ask prompts |
| name | Optional[str] | No | Unique guard name (defaults to gr-{id}) |
| description | Optional[str] | No | Guard description |
| output_formatter | Optional[Union[str, BaseFormatter]] | No | "none" (default), "jsonformer", or custom BaseFormatter |
Outputs
| Name | Type | Description |
|---|---|---|
| guard | Guard[Dict] or Guard[List] | Guard instance with output schema, validators, and output type configured |
Usage Examples
Basic Structured Output
from pydantic import BaseModel, Field
from guardrails import Guard
class Person(BaseModel):
name: str = Field(description="Person's full name")
age: int = Field(description="Person's age")
guard = Guard.for_pydantic(output_class=Person)
result = guard(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Generate a person profile."}],
)
print(result.validated_output) # {"name": "...", "age": ...}
With Jsonformer Constrained Decoding
guard = Guard.for_pydantic(
output_class=Person,
output_formatter="jsonformer",
)