Principle:Guardrails ai Guardrails Guard Pydantic Factory
| Knowledge Sources | |
|---|---|
| Domains | Factory_Pattern, Structured_Output |
| Last Updated | 2026-02-14 00:00 GMT |
Overview
A factory pattern that creates a Guard instance pre-configured with output schema and field-level validators extracted from a Pydantic model.
Description
The Guard Pydantic Factory principle provides a single-step creation of a fully configured Guard from a Pydantic model class. Instead of manually constructing a Guard and attaching validators one by one, the factory method extracts the JSON schema and all embedded validators from the Pydantic model's field metadata, constructs the appropriate validator map, and returns a Guard ready for structured output generation.
This automates the binding between schema definition and validation configuration, ensuring consistency between the output structure the LLM is prompted to produce and the validators that check it.
Usage
Use this factory when you have a Pydantic model defining your desired output structure (optionally with embedded validators). It replaces the manual Guard() + .use() pattern for structured output scenarios.
Theoretical Basis
The factory performs three operations atomically:
- Schema Extraction: Convert the Pydantic model to a JSON Schema for LLM output structuring
- Validator Extraction: Traverse field metadata to build a path-to-validator map
- Guard Assembly: Create a Guard instance with the schema, validators, and output type (Dict or List) configured