Pydantic Patterns logo

Pydantic Patterns

Community
manikosto
pydantic-patterns

Pydantic v2 patterns — models, validators, serialization, computed fields, discriminated unions, settings management, and integration with FastAPI/SQLAlchemy.

Overview

Publishermanikosto
Repositoryclaude-code-python-stack
Skill namepydantic-patterns
Stars
54
Forks
10
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by manikosto on GitHub. Read the source before you install it.

Installation

Install the Pydantic Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/manikosto/claude-code-python-stack/tree/main/skills/pydantic-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/manikosto/claude-code-python-stack.git /tmp/claude-code-python-stack
mkdir -p .claude/skills
cp -r /tmp/claude-code-python-stack/skills/pydantic-patterns .claude/skills/pydantic-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Pydantic Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Pydantic Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Pydantic Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Pydantic v2 Patterns

Data validation and serialization patterns using Pydantic v2.

When to Activate

  • Defining request/response schemas for APIs
  • Validating external data (user input, API responses, file content)
  • Managing application settings with environment variables
  • Converting between domain models and DTOs

Basic Models

python
from pydantic import BaseModel, Field, EmailStr
from datetime import datetime

class UserCreate(BaseModel):
    email: EmailStr
    name: str = Field(min_length=1, max_length=255)
    password: str = Field(min_length=8, max_length=128)
    age: int | None = Field(None, ge=0, le=150)

class UserResponse(BaseModel):
    id: int
    email: str
    name: str
    created_at: datetime

    model_config = {"from_attributes": True}  # Enable ORM mode

Validators

Field Validators

python
from pydantic import BaseModel, field_validator, model_validator
import re

class UserCreate(BaseModel):
    username: str
    password: str
    password_confirm: str

    @field_validator("username")
    @classmethod
    def username_alphanumeric(cls, v: str) -> str:
        if not re.match(r"^[a-zA-Z0-9_]+$", v):
            raise ValueError("Username must be alphanumeric")
        return v.lower()

    @field_validator("password")
    @classmethod
    def password_strength(cls, v: str) -> str:
        if not re.search(r"[A-Z]", v):
            raise ValueError("Password must contain uppercase letter")
        if not re.search(r"[0-9]", v):
            raise ValueError("Password must contain a digit")
        return v

    @model_validator(mode="after")
    def passwords_match(self) -> "UserCreate":
        if self.password != self.password_confirm:
            raise ValueError("Passwords do not match")
        return self

Before and After Validators

python
from pydantic import field_validator

class Product(BaseModel):
    name: str
    price: float
    tags: list[str] = []

    @field_validator("name", mode="before")
    @classmethod
    def strip_name(cls, v):
        if isinstance(v, str):
            return v.strip()
        return v

    @field_validator("tags", mode="before")
    @classmethod
    def parse_tags(cls, v):
        if isinstance(v, str):
            return [t.strip() for t in v.split(",")]
        return v

    @field_validator("price")
    @classmethod
    def round_price(cls, v: float) -> float:
        return round(v, 2)

Computed Fields

python
from pydantic import BaseModel, computed_field

class OrderItem(BaseModel):
    product_name: str
    quantity: int
    unit_price: float

    @computed_field
    @property
    def total_price(self) -> float:
        return round(self.quantity * self.unit_price, 2)

class Order(BaseModel):
    items: list[OrderItem]

    @computed_field
    @property
    def grand_total(self) -> float:
        return round(sum(item.total_price for item in self.items), 2)

Discriminated Unions

python
from pydantic import BaseModel, Discriminator, Tag
from typing import Annotated, Literal

class EmailNotification(BaseModel):
    type: Literal["email"] = "email"
    to: str
    subject: str
    body: str

class SMSNotification(BaseModel):
    type: Literal["sms"] = "sms"
    phone: str
    message: str

class PushNotification(BaseModel):
    type: Literal["push"] = "push"
    device_token: str
    title: str
    body: str

Notification = Annotated[
    EmailNotification | SMSNotification | PushNotification,
    Discriminator("type"),
]

class NotificationRequest(BaseModel):
    notifications: list[Notification]

Serialization Control

python
from pydantic import BaseModel, field_serializer, model_serializer
from datetime import datetime

class Event(BaseModel):
    name: str
    start_time: datetime
    metadata: dict

    @field_serializer("start_time")
    def serialize_time(self, v: datetime, _info) -> str:
        return v.strftime("%Y-%m-%d %H:%M")

    # Exclude None values
    model_config = {
        "json_schema_extra": {"examples": [{"name": "Conference", "start_time": "2025-01-15 09:00"}]}
    }

# Usage
event = Event(name="Conf", start_time=datetime.now(), metadata={"key": "val"})
event.model_dump(exclude_none=True)          # dict without None values
event.model_dump(include={"name", "start_time"})  # only specific fields
event.model_dump_json()                      # JSON string

Nested Models

python
class Address(BaseModel):
    street: str
    city: str
    country: str = "US"
    zip_code: str

class Company(BaseModel):
    name: str
    address: Address
    employees: list["Employee"] = []

class Employee(BaseModel):
    name: str
    email: EmailStr
    department: str
    company: Company | None = None

# Parsing nested data
data = {
    "name": "Acme Inc",
    "address": {"street": "123 Main St", "city": "NYC", "zip_code": "10001"},
    "employees": [
        {"name": "Alice", "email": "alice@acme.com", "department": "Engineering"},
    ],
}
company = Company.model_validate(data)

Settings Management

python
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import SecretStr

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        env_prefix="APP_",
        case_sensitive=False,
    )

    # Required
    database_url: str
    secret_key: SecretStr
    redis_url: str

    # Optional with defaults
    debug: bool = False
    log_level: str = "INFO"
    port: int = 8000
    allowed_origins: list[str] = ["http://localhost:3000"]

    # Nested settings
    class DBConfig(BaseSettings):
        pool_size: int = 20
        max_overflow: int = 10

    db: DBConfig = DBConfig()

# .env file:
# APP_DATABASE_URL=postgres://user:pass@localhost/db
# APP_SECRET_KEY=my-secret-key
# APP_DEBUG=true
# APP_ALLOWED_ORIGINS=["http://localhost:3000","http://localhost:8080"]

settings = Settings()

Generic Response Models

python
from pydantic import BaseModel
from typing import TypeVar, Generic

T = TypeVar("T")

class APIResponse(BaseModel, Generic[T]):
    success: bool = True
    data: T | None = None
    error: str | None = None

class PaginatedData(BaseModel, Generic[T]):
    items: list[T]
    total: int
    page: int
    per_page: int

    @computed_field
    @property
    def pages(self) -> int:
        return (self.total + self.per_page - 1) // self.per_page

# Usage in FastAPI
@router.get("/users", response_model=APIResponse[PaginatedData[UserResponse]])
async def list_users(): ...

Integration with SQLAlchemy

python
from pydantic import BaseModel

class UserResponse(BaseModel):
    id: int
    email: str
    name: str

    model_config = {"from_attributes": True}

# Converts SQLAlchemy model to Pydantic
user_orm = await session.get(User, 1)
user_schema = UserResponse.model_validate(user_orm)

Custom Types

python
from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema

class PhoneNumber(str):
    @classmethod
    def __get_pydantic_core_schema__(cls, source, handler: GetCoreSchemaHandler):
        return core_schema.no_info_after_validator_function(
            cls._validate,
            core_schema.str_schema(min_length=10, max_length=15),
        )

    @classmethod
    def _validate(cls, v: str) -> "PhoneNumber":
        cleaned = "".join(c for c in v if c.isdigit() or c == "+")
        if not cleaned.startswith("+"):
            cleaned = f"+{cleaned}"
        return cls(cleaned)

class Contact(BaseModel):
    name: str
    phone: PhoneNumber

Quick Reference

FeatureUsage
model_validate(data)Parse dict/ORM to model
model_dump()Convert to dict
model_dump_json()Convert to JSON string
model_json_schema()Generate JSON Schema
@field_validatorValidate single field
@model_validatorValidate across fields
@computed_fieldDerived field in output
from_attributes=TrueEnable ORM mode
Field(ge=0, le=100)Numeric constraints
SecretStrHide sensitive values
Discriminator("field")Tagged unions

Remember: Pydantic v2 uses model_validate instead of parse_obj, model_dump instead of dict(). Always use the v2 API.

Frequently asked questions

What does the Pydantic Patterns AI skill do?

Pydantic v2 patterns — models, validators, serialization, computed fields, discriminated unions, settings management, and integration with FastAPI/SQLAlchemy.

Why use Pydantic Patterns on TypingMind?

Because you install it once and use it with any model. Pydantic Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Pydantic Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/manikosto/claude-code-python-stack/tree/main/skills/pydantic-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Pydantic Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Pydantic Patterns?

As many as you like. As long as a model supports skills, you can use Pydantic Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Pydantic Patterns AI skill free?

It is published on GitHub by manikosto. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇