Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Pydantic BaseModel go mion

Ceacht 6 as 12 Nuashonraithe 30 Iúil 2026 Forbróir
Ar an leathanach seo
  1. Pydantic: An comhpháirtí idéalach
  2. Bunús Pydantic d’aschuir struchtúrtha
  3. Cineálacha Python a dtacaítear leo
  4. Samhlacha neadaithe
  5. Áireamhuithe le Pydantic
  6. Úsáid a bhaint as parse()
  7. Úsáid a bhaint as response_format
  8. Luachanna réamhshocraithe agus doiciméadú
  9. Príomhphointí

Pydantic: An comhpháirtí idéalach

Is é Pydantic an leabharlann Python caighdeánach le haghaidh bailíochtaithe sonraí. Le haschuir struchtúrtha Grok, éiríonn sé ina uirlis riachtanach: sainíonn tú do scéimí mar aicmí Python, agus líonann an tsamhail na haicmí sin go huathoibríoch.

Bunús Pydantic d’aschuir struchtúrtha

Cruthaíonn tú samhail Pydantic trí oidhreacht a fháil ó BaseModel. Déantar gach tréith le nodaireacht cineáil ina réimse sa scéima JSON:

from pydantic import BaseModel

class Produit(BaseModel):
    nom: str
    prix: float
    en_stock: bool
    categorie: str

Gineann an tsamhail seo an scéima JSON coibhéiseach go huathoibríoch. Ní gá duit aon rud eile a scríobh.

Cineálacha Python a dtacaítear leo

Seo an léarscáil idir cineálacha Python agus cineálacha Scéima JSON:

class ExempleComplet(BaseModel):
    # Scálairí
    texte: str                    # → "type": "string"
    nombre: float                 # → "type": "number"
    entier: int                   # → "type": "number"
    actif: bool                   # → "type": "boolean"

    # Roghanna
    note: str | None              # → anyOf string/null

    # Bailiúcháin
    tags: list[str]               # → array of strings
    scores: list[float]           # → array of numbers

    # Áireamhuithe
    niveau: str                   # + enum in Field

Samhlacha neadaithe

Tá fíor-chumhacht Pydantic le fáil i neadú samhlacha:

class Adresse(BaseModel):
    rue: str
    ville: str
    code_postal: str
    pays: str

class Competence(BaseModel):
    nom: str
    niveau: str  # "debutant", "intermediaire", "expert"
    annees: int

class Candidat(BaseModel):
    prenom: str
    nom: str
    email: str
    adresse: Adresse
    competences: list[Competence]
    disponible: bool
    pretention_salariale: float | None

Nuair a ritear Candidat mar an response_format, líonfaidh an tsamhail an hierarchaí iomlán: an seoladh iomlán, gach scil lena sonraí féin, agus mar sin de.

Áireamhuithe le Pydantic

Chun luachanna réamhshocraithe a fhorfheidhmiú, úsáid Literal ó Python:

from typing import Literal

class Ticket(BaseModel):
    titre: str
    description: str
    priorite: Literal["basse", "moyenne", "haute", "critique"]
    statut: Literal["ouvert", "en_cours", "resolu", "ferme"]
    type: Literal["bug", "feature", "documentation"]

Ní féidir leis an tsamhail ach na luachanna liostaithe a thabhairt ar ais. Tá aon luach eile dodhéanta.

Úsáid a bhaint as parse()

response, ticket = client.chat.parse(
    model="grok-4.20-0309-reasoning",
    messages=[{
        "role": "user",
        "content": "The login button does not work on mobile"
    }],
    response_format=Ticket
)

print(ticket.priorite)  # "haute"
print(ticket.type)       # "bug"
print(ticket.statut)     # "ouvert"

Úsáid a bhaint as response_format

response = client.chat.create(
    model="grok-4.20-0309-reasoning",
    messages=[{
        "role": "user",
        "content": "The login button does not work on mobile"
    }],
    response_format=Ticket
)

ticket = Ticket.model_validate_json(
    response.choices[0].message.content
)

Luachanna réamhshocraithe agus doiciméadú

Is féidir leat cur síosanna a chur le do réimsí trí Field a úsáid. Cuidíonn na cur síosanna seo leis an tsamhail tuiscint níos fearr a fháil ar an méid atá tú ag súil leis:

from pydantic import BaseModel, Field

class AnalyseSentiment(BaseModel):
    texte_original: str = Field(
        description="The text analyzed as is"
    )
    sentiment: Literal["positif", "negatif", "neutre"] = Field(
        description="The dominant sentiment of the text"
    )
    score_confiance: float = Field(
        description="Confidence score between 0.0 and 1.0"
    )
    mots_cles: list[str] = Field(
        description="The 3 to 5 most significant keywords"
    )

Cuirtear na cur síosanna i Field san áireamh sa scéima JSON a sheoltar chuig an tsamhail. Feabhsaíonn siad cáilíocht na bhfreagraí.

Príomhphointí

  • Tiontaíonn Pydantic do chuid aicmí Python go scéimí JSON go huathoibríoch
  • Ceadaíonn neadú samhlacha duit sonraí casta a struchtúrú
  • Cuireann Literal in ionad enum chun luachanna réamhshocraithe a fhorfheidhmiú
  • Déanann str | None réimse roghnach (is féidir leis a bheith null)
  • Feabhsaíonn Field(description=...) cáilíocht fhreagraí na samhla
  • Oibríonn sé le parse() (uathoibríoch) agus response_format (láimhe)