Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Principle:Guardrails ai Guardrails Guard Pydantic Factory

From Leeroopedia
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:

  1. Schema Extraction: Convert the Pydantic model to a JSON Schema for LLM output structuring
  2. Validator Extraction: Traverse field metadata to build a path-to-validator map
  3. Guard Assembly: Create a Guard instance with the schema, validators, and output type (Dict or List) configured

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment