Logo von Pydantic

Pydantic

Organisation
pydantic
pydantic

Pydantic is a Python data validation and serialization library, based on type hints. Use this skill whenever you need to do relatively complex data modeling using Pydantic, e.g. when adding constraints, defining a model hierarchy with subclasses, etc.

Übersicht

Herausgeberpydantic
Repositoryskills
Skill-Namepydantic
Sterne
147
Forks
7
Mitgelieferte Dateien
Nur Anweisungen
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • In sich abgeschlossen

    Alles, was das Modell braucht, steht in den Anweisungen — keine zusätzlichen Dateien zum Synchronisieren.

  • Open Source

    Von pydantic auf GitHub veröffentlicht. Prüfen Sie den Quellinhalt vor der Installation.

Installation

Installieren Sie den KI-Skill Pydantic in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner — liest SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/pydantic/skills/tree/main/plugins/pydantic/skills/pydantic
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill anlegen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format lesen kann, kann diesen Skill nutzen — kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/pydantic/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/plugins/pydantic/skills/pydantic .claude/skills/pydantic
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Pydantic in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Pydantic automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Pydantic nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Keys.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

Pydantic Validation

In a nutshell, Pydantic is dataclasses with runtime validation. It leverages type hints to understand how validation (and serialization) should be performed. It is mostly useful when dealing with external untrusted data, for example when defining an HTTP API.

It is generally not recommended to use Pydantic to define classes that are instantiated within the user code. By doing so, you will lose flexibility (e.g. you cannot use types not supported by Pydantic, and it is harder to perform post-init changes). It is usually better to use vanilla classes (or standard library dataclasses) in this case, as a static type checker will already catch type mismatches.

Basic usage

Here is a simple example of using a Pydantic model:

python
from datetime import date

from pydantic import BaseModel, Field


class Person(BaseModel):
    name: str
    age: int = Field(description='The age of the person')
    birthdate: date | None = None


p = Person(name='John', age=20, birthdate='1970-01-01')

Pydantic coerces compatible input: the ISO date string '1970-01-01' is parsed into a date.

Constraints and field metadata

The Field() function is used to provide metadata and constraints. You need to distinguish two types of metadata:

  • field specific metadata: metadata such as deprecated and alias, that only have meaning when attached to a field.
  • type specific metadata: this includes constraints such as gt, max_length, and also metadata that affects the JSON Schema (e.g. description, title).

Model fields are declared with Field() using the assignment form:

python
from pydantic import BaseModel, Field


class User(BaseModel):
    first_name: str = Field(alias='name')

or using the annotated pattern:

python
from typing import Annotated

from pydantic import BaseModel, Field


class Model(BaseModel):
    value: Annotated[int, Field(deprecated=True)] = 1

The annotated pattern has some advantages:

  • Using the f: <type> = Field() form (no default) can be confusing and might trick users into thinking f has a default value, while in reality the field is still required.
  • You can provide an arbitrary amount of metadata elements for a field. As shown in the example above, the Field() function only supports a limited set of constraints/metadata, and you may have to use different Pydantic utilities such as WithJsonSchema in some cases.

But note that:

  • You should use the assignment form for metadata that has a meaning for static type checkers. This includes: alias, default and default_factory.

  • field specific metadata can only be used on the "top-level" type. A common pitfall is to do the following:

    python
    from typing import Annotated
    
    from pydantic import BaseModel, Field
    
    
    class Model(BaseModel):
        field_bad: Annotated[int, Field(deprecated=True)] | None = None
        field_ok: Annotated[int | None, Field(deprecated=True)] = None

    field specific metadata should apply to the whole union in this example.

Constraints

As much as possible, use the "built-in" validation constraints, instead of defining custom validators:

python
from typing import Annotated

from annotated_types import Gt  # annotated_types is an alternative to the `Field()` function.
from pydantic import BaseModel, field_validator


class Model(BaseModel):
    constrained_int_ok: Annotated[int, Gt(1)]  # This is good

    constrained_int_bad: int

    @field_validator('constrained_int_bad')  # This is bad
    @classmethod
    def validate(cls, v: int) -> int:
        if not v > 1:
            raise ValueError('Value is not greater than 1')
        return v

Sometimes, constraints can't be expressed using the Field() function. For example, string constraints such as strip_whitespace, to_upper, to_lower and ascii_only can only be specified using pydantic.StringConstraints:

python
from typing import Annotated

from pydantic import BaseModel, StringConstraints


class Model(BaseModel):
    # Do this instead of a validator calling s.strip():
    a: Annotated[str, StringConstraints(strip_whitespace=True)]

https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types/ is the canonical documentation for all supported standard library types and their constraints.

Validators

In some cases, you may have to use custom validators. As much as possible, use after validators. Because they run after Pydantic validation, the value is already the field's type. If you use before validators, the input data can literally be anything, so it is more error-prone (especially for model validators, the input isn't necessarily a dict, it can also be an arbitrary object).

If possible, prefer using the annotated pattern for validators:

python
from typing import Annotated

from pydantic import AfterValidator, BaseModel, field_validator


def is_even(value: int) -> int:
    if value % 2 == 1:
        raise ValueError(f'{value} is not an even number')
    return value


class Model(BaseModel):
    # Prefer this form: the validator is right next to the field, making it easy to understand
    even: Annotated[int, AfterValidator(is_even)]
    odd: int

    # If you define a validator as decorator, make sure to define it as classmethod.
    @field_validator('odd', mode='after')
    @classmethod
    def is_odd(cls, value: int) -> int:
        if value % 2 == 0:
            raise ValueError(f'{value} is not an odd number')
        return value

Using the decorator pattern can lead to unclear behavior, especially regarding the order in which validators run (in particular on subclasses).

Type coercion, collections and unions

Unless you are using strict mode, Pydantic applies type coercion in most cases. For instance, for a field typed as int, strings like '123' will be accepted. This also applies to collection types: list[str] also accepts tuples, sets etc.

This is why you should avoid:

  • using unions such as int | str, if your goal is to coerce the str to an int via a validator.
  • using abstract collections such as collections.abc.Sequence, if your goal is to accept both lists and tuples. Using these abstract collections is inefficient.

In the general case, unions are best avoided because every use of the field will need to check for each type before doing anything with it.

Forward annotations

Python has the ability to write annotations as forward references, by using strings. This can cause challenges for Pydantic to evaluate them, so they are best avoided if possible.

If you are defining Pydantic models in a module, avoid using from __future__ import annotations if possible (which stringifies all annotations by default). Only add explicit quotes to annotations that aren't defined yet, e.g.:

python
from pydantic import BaseModel


class Model(BaseModel):
    self_ref: 'Model'

Also note that in Python >= 3.14, annotation evaluation is deferred, so you should not use string annotations at all.

Recursive type aliases

You might be tempted to define aliases like this:

python
from typing import TypeAlias

JsonValue: TypeAlias = 'list[JsonValue] | dict[str, JsonValue] | str | bool | int | float | None'

The alias needs to be quoted because it is recursive. Pydantic will generally not be able to evaluate a quoted TypeAlias. Instead, use an explicit type alias (type on Python 3.12+, or TypeAliasType), which Pydantic can resolve:

python
type JsonValue = list[JsonValue] | dict[str, JsonValue] | str | bool | int | float | None
# Or, if not on Python >= 3.12:
from typing_extensions import TypeAliasType

JsonValue = TypeAliasType('JsonValue', 'list[JsonValue] | dict[str, JsonValue] | str | bool | int | float | None')

Model subclasses, discriminated unions

Subclassing is a really common Python pattern, but can be a footgun in Pydantic. You might be tempted to do:

python
from pydantic import BaseModel


class Base(BaseModel):
    base_field: int

    def common_method(self) -> None: ...


class Sub1(Base):
    sub1_field: str


class Sub2(Base):
    sub2_field: bool


class Main(BaseModel):
    model: Base


m: Main = Main(model=Sub1(base_field=1, sub1_field='test'))

This example works, but will not behave as expected when serializing m:

python
m.model_dump()
#> {'model': {'base_field': 1}} -> sub1_field missing

This is because Pydantic serializes according to the declared type (Base), not the runtime subclass. Validation follows the same rule: Main(model={'base_field': 1, 'sub1_field': 'test'}) validates against Base, so sub1_field is ignored rather than producing a Sub1 instance.

Instead, try to use discriminated unions (provided that you can set a type field to distinguish models):

python
from typing import Annotated, Literal, TypeAlias

from pydantic import BaseModel, Field


class Sub1(Base):
    type: Literal['sub1']
    sub1_field: str


class Sub2(Base):
    type: Literal['sub2']
    sub2_field: bool


Subs: TypeAlias = Annotated[Sub1 | Sub2, Field(discriminator='type')]


class Main(BaseModel):
    model: Subs

or generics:

python
from pydantic import BaseModel


class Main[BaseT: Base](BaseModel):
    model: BaseT


m: Main[Sub1] = Main[Sub1](model={'base_field': 1, 'sub1_field': 'test'})  # Will work

If neither discriminated unions nor generics fit, polymorphic serialization (in Pydantic >=2.13) or serialize as any (in Pydantic <2.13) can be used as a last resort.

Häufig gestellte Fragen

Was macht der KI-Skill Pydantic?

Pydantic is a Python data validation and serialization library, based on type hints. Use this skill whenever you need to do relatively complex data modeling using Pydantic, e.g. when adding constraints, defining a model hierarchy with subclasses, etc.

Warum Pydantic in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Pydantic besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Pydantic in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/pydantic/skills/tree/main/plugins/pydantic/skills/pydantic ein. TypingMind liest die Datei SKILL.md und installiert den Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Pydantic nutzen?

Jedes Modell, das Sie in TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Pydantic verwenden?

So viele Sie möchten. Solange ein Modell Skills unterstützt, können Sie Pydantic damit verwenden – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama und weitere – alles in TypingMind mit Ihren eigenen API-Schlüsseln.

Ist der KI-Skill Pydantic kostenlos?

Ja. Der Skill wird von pydantic auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: eine Datei namens SKILL.md mit einem Namen und einer Beschreibung sowie allen Skripten, Vorlagen oder Referenzdateien, die das Modell möglicherweise benötigt. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und benötigen daher weder Server noch API-Schlüssel oder Laufzeitumgebung. Sie funktionieren mit jedem Modell.

Alle

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇