Pydantic logo

Pydantic

Organization
CodeAtCode
pydantic

Use when validating and serializing Python data with Pydantic v2 - models, field and model validators, constrained and special types, TypeAdapter, discriminated unions, BaseSettings, or FastAPI integration

Overview

PublisherCodeAtCode
Repositoryoss-ai-skills
Skill namepydantic
Stars
30
Forks
3
Bundled files
6
LicenseGPL-3.0
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.

  • 6 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

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

Installation

Install the Pydantic 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/CodeAtCode/oss-ai-skills/tree/master/frameworks/pydantic
  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/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/pydantic .claude/skills/pydantic
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Pydantic 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 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 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.

Objective: Use this skill to prevent data-validation gaps and serialization bugs by enforcing boundary-level validation, Field constraints over manual checks, and v2 migration patterns that avoid silent coercion failures.

Pydantic

Data validation using Python type annotations.

Overview

Pydantic provides data validation and settings management using Python type hints. Validates at runtime and generates JSON Schema.

Source: https://docs.pydantic.dev/ | https://github.com/pydantic/pydantic

Installation

bash
pip install pydantic          # Core
pip install pydantic[email]   # Email validation
pip install pydantic orjson   # Best performance
pip install pydantic-settings # Settings management

Quick Start

python
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int | None = None

# Validation + coercion
user = User(id="1", name="John", email="john@example.com")  # id coerced to int

# From dict/JSON
user = User.model_validate({"id": 2, "name": "Jane", "email": "jane@example.com"})
user = User.model_validate_json('{"id": 3, "name": "Bob", "email": "bob@example.com"}')

# Serialization
data = user.model_dump()           # dict
json_str = user.model_dump_json()  # JSON string

Field Constraints

Compact examples—see validators.md for full reference.

python
from pydantic import BaseModel, Field
from typing import Optional, List

class ConstrainedModel(BaseModel):
    # Strings
    name: str = Field(min_length=1, max_length=100)
    username: str = Field(pattern=r'^[a-zA-Z0-9_]+$')
    
    # Numbers
    age: int = Field(ge=0, le=150)
    price: float = Field(gt=0)
    
    # Collections
    tags: List[str] = Field(min_length=1)
    
    # Optional
    nickname: Optional[str] = Field(default=None, max_length=50)

Validators

See validators.md for comprehensive patterns.

python
from pydantic import BaseModel, field_validator, model_validator, Field
import re

class ValidatedModel(BaseModel):
    username: str
    password: str
    
    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if len(v) < 3:
            raise ValueError('Username must be at least 3 characters')
        return v.strip().lower()
    
    @model_validator(mode='after')
    def validate_password_strength(self):
        if len(self.password) < 8:
            raise ValueError('Password too short')
        if not re.search(r'[A-Z]', self.password):
            raise ValueError('Password needs uppercase')
        return self

v1 → v2 Migration Checklist

Critical: v2 changes can silently break v1 code. Check each item.

v1v2Symptom
@validator@field_validatorImport error; validator deprecated
@validator(..., each_item=True)@field_validator with PlainSerializerList validation fails
@root_validator@model_validator(mode='before'/'after')root_validator removed; need mode
class Configmodel_config = ConfigDict(...)Config class ignored
.dict().model_dump()Method not found
.json().model_dump_json()Method not found
.parse_obj().model_validate()Method not found
.parse_raw().model_validate_json()Method not found
.schema().model_json_schema()Method not found
Field(..., regex=r'...')Field(pattern=r'...')regex removed
Field(..., min_length=...)Field(min_length=...)Works (unchanged)
copy(update={...})model_copy(update={...})copy is shallow; use model_copy
allow_population_by_field_namepopulate_by_nameConfig key renamed
orm_modefrom_attributesConfig key renamed
Optional[X] = None default behaviorDefaults no longer filled for NoneNone stays None, not replaced

Source: https://docs.pydantic.dev/latest/migration/

Serialization Performance

Measure before optimizing: use timeit or a profiler on model_dump() for deeply nested models.

python
from pydantic import BaseModel
from typing import Optional, List
import time

class NestedModel(BaseModel):
    data: dict
    items: List[str]

class DeepModel(BaseModel):
    level1: NestedModel
    level2: NestedModel
    level3: NestedModel

model = DeepModel(
    level1=NestedModel(data={}, items=[]),
    level2=NestedModel(data={}, items=[]),
    level3=NestedModel(data={}, items=[])
)

# Measure
start = time.perf_counter()
for _ in range(10000):
    model.model_dump()
print(f"Time: {time.perf_counter() - start:.3f}s")

Guidance:

  • model_dump() vs dict(model): model_dump() is O(1) per field; dict(model) triggers reflection O(fields) each call. Always use model_dump().
  • model_dump(mode="json"): Use when the consumer is JSON (serializes datetime, decimals, etc. to JSON-native types).
  • exclude_none=True: Omits fields with None value. Use when you want to hide nulls.
  • exclude_unset=True: Omits fields that were never explicitly set (even if they have defaults). Usually what you want for partial updates.
  • Deeply nested models: The hot spot. Profile first; consider selective include/exclude or flattening.

Django Integration

See django.md for detailed patterns.

python
from pydantic import BaseModel, ConfigDict
from myapp.models import User as UserModel

class UserPydantic(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    
    id: int
    username: str
    email: str

# Accept ORM objects
user_orm = UserModel.objects.get(id=1)
user_py = UserPydantic.model_validate(user_orm)  # from_attributes=True enables this

# DjangoChoices for enum validation
from django.db import models

class Status(models.TextChoices):
    PENDING = "pending"
    ACTIVE = "active"

# Must be TextChoices, not plain str for enum validation
from pydantic import BaseModel

class Task(BaseModel):
    status: Status  # Works with TextChoices

Pitfalls:

  • Unsaved instances: Validating an unsaved Django model instance may fail if validators expect id or other DB-generated fields.
  • Lazy model fields: Use DjangoGetter wrapper for lazy evaluation of related fields (avoids N+1 queries).

When Not to Use a Strict Model

Not every case benefits from Pydantic's coercion:

  • Internal dataclasses: Where data is already validated at the boundary, coercion surprises hurt more than help. Use @dataclass or plain classes internally.
  • Boundary discipline: Validate external input ONCE at the boundary. Internal call sites should not re-validate—pass typed data directly.
  • Performance-critical paths: If validation is not needed (e.g., internal cache hits), skip Pydantic overhead.
python
# Good: Validate at boundary
def handle_request(raw_data: dict):
    user = User.model_validate(raw_data)  # Boundary
    process_user(user)  # Internal—no re-validation

def process_user(user: User):
    # Use user directly; trust the type
    send_email(user.email)

# Bad: Re-validating internally
def process_user_bad(raw_data: dict):
    user = User.model_validate(raw_data)
    # ...
    user_again = User.model_validate(user.model_dump())  # Unnecessary

Best Practices

  1. Use Field(default_factory=...) for mutable defaults

    python
    class Model(BaseModel):
        tags: List[str] = Field(default_factory=list)  # Good
        # tags: List[str] = []  # Bad in v2
  2. Separate schemas for operations

    python
    class UserBase(BaseModel):
        email: str
    
    class UserCreate(UserBase):
        username: str
        password: str
    
    class UserResponse(UserBase):
        id: int
        model_config = ConfigDict(from_attributes=True)
  3. Validate once at the boundary (see above)

Common Issues

Mutable Defaults

python
# v2 error: mutable default
class BadModel(BaseModel):
    items: list = []

# Fix: use default_factory
class GoodModel(BaseModel):
    items: list = Field(default_factory=list)

Performance

  • Use Pydantic v2 (parsing is 10-100x faster than v1)
  • Use orjson for serialization: model_config = ConfigDict(json_loads=orjson.loads, json_dumps=orjson.dumps)
  • Measure model_dump() on deeply nested models first

Deep Dives

Load these reference files on demand:

  • validators.md — Field/model validators, custom types, error handling, TypeAdapter, discriminated unions
  • types-and-defaults.md — Field aliases, naming conventions, constrained types, special types (email, URL, UUID, secrets, enums)
  • config-and-settings.md — Model configuration, strict mode, multi-environment settings, BaseSettings

References

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Pydantic AI skill do?

Use when validating and serializing Python data with Pydantic v2 - models, field and model validators, constrained and special types, TypeAdapter, discriminated unions, BaseSettings, or FastAPI integration

Why use Pydantic on TypingMind?

Because you install it once and use it with any model. Pydantic 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 in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pydantic. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Pydantic?

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?

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

Is the Pydantic AI skill free?

Yes. It is published on GitHub by CodeAtCode under the GPL-3.0 license. 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 👇