Straitéisí Bailíochtaithe agus Atriail
Ar an leathanach seo
Bailíochtú: An Cosaint Deireanach Roimh Tháirgeadh
Fiú le hAschuir Struchtúrtha Saincheaptha, fanann bailíochtú riachtanach. Ráthaíonn an scéama struchtúr, ní comhleanúnachas shéimeantach. D’fhéadfadh réimse price luach -999.0 a bheith ann: snámhphointe bailí a oireann go foirfe don scéama, ach nach bhfuil ciall ar bith aige mar phraghas.
Tá an difríocht soiléir. Déanann Pydantic agus Zod bailíochtú struchtúrach go huathoibríoch: réimsí éigeantacha, cineálacha réimsí, srianta enum, agus struchtúir neadaithe. Ní gá duit aon chód a scríobh chuige seo. Is faoi do dhílseacht féin atá bailíochtú séimeantach, áfach. Áirítear leis seo teorainneacha uimhriúla (praghas níos mó ná nialas, scór idir 0 agus 1), comhsheasmhacht tras-réimse (caithfidh an t-iomlán a bheith cothrom le suim na míreanna líne), formáidí teaghráin (ríomhphost bailí i ndáiríre, dáta formáidithe i gceart), agus loighic gnó (dáta dlite níos déanaí ná dáta an fhactúra).
Rialacha Gnó a Leabú sa Scéama
Ligeann Pydantic duit na seiceálacha seo a leabú go díreach sa mhúnla, rud a fhágann go bhfuil siad doscartha ón struchtúr. Láimhseálann @field_validator réimsí aonair – mar shampla, a chinntiú go bhfuil cainníocht dearfach nó nach bhfuil praghas aonaid diúltach. Rithtear @model_validator(mode="after") nuair a líontar gach réimse, rud a chumasóidh seiceálacha tras-réimse, amhail a fhíorú go bhfuil an t-iomlán luaite cothrom le cainníocht × praghas aonaid laistigh de chint.
from pydantic import BaseModel, Field, field_validator, model_validator
class InvoiceLine(BaseModel):
description: str
quantity: float
unit_price: float
total: float
@field_validator("quantity")
@classmethod
def quantity_positive(cls, v):
if v <= 0:
raise ValueError(f"Quantity must be positive, got: {v}")
return v
@field_validator("unit_price")
@classmethod
def price_non_negative(cls, v):
if v < 0:
raise ValueError(f"Unit price cannot be negative: {v}")
return v
@model_validator(mode="after")
def check_total(self):
expected = round(self.quantity * self.unit_price, 2)
if abs(self.total - expected) > 0.01:
raise ValueError(
f"Inconsistent total: {self.total} != {self.quantity} x {self.unit_price} = {expected}"
)
return self
Sloinneann Zod an loighic chéanna ag baint úsáide as srianta ionsuite cosúil le .positive() agus .nonnegative() do réimsí, agus .refine() do rialacha tras-oiriachta a chuirtear i bhfeidhm ar an oibiacht iomlán.
import { z } from "zod";
const InvoiceLineSchema = z
.object({
description: z.string(),
quantity: z.number().positive("Quantity must be positive"),
unitPrice: z.number().nonnegative("Price cannot be negative"),
total: z.number(),
})
.refine(
(data) => Math.abs(data.total - data.quantity * data.unitPrice) < 0.01,
{ message: "Total does not match quantity x unit price" }
);
Atriail le hAiseolas
Nuair a theipeann ar bhailíochtú, is é an patrún is éifeachtaí ná an earráid a sheoladh ar ais chuig an tsamhail ionas gur féidir léi í féin a cheartú. Slabhraíonn an fheidhm thíos trí sheiceáil in ord tábhachta: freagra iomlán, oibiacht neamh-nul, agus comhlíonadh rialacha gnó. Ar theip, cuireann sí an freagra lochtach agus an teachtaireacht earráide leis an gcomhrá, rud a thugann comhthéacs diagnóiseach cruinn don chéad iarracht eile. Tabhair faoi deara an cóip den liosta teachtaireachtaí ag tús na feidhme – gan é, thruaillfeá stair chomhrá an ghlaoóra.
from mistralai.client import Mistral
from pydantic import BaseModel, ValidationError
import json
def extract_with_retry(
client: Mistral,
messages: list,
schema,
max_retries: int = 3,
model: str = "mistral-large-latest"
):
"""Extraction with retry and structured error feedback."""
conversation = list(messages) # Copy to avoid modifying the original
for attempt in range(max_retries):
try:
response = client.chat.parse(
model=model,
messages=conversation,
response_format=schema,
temperature=0,
max_tokens=2048
)
# Check that the response is complete
if response.choices[0].finish_reason != "stop":
raise ValueError(
f"Incomplete response (finish_reason={response.choices[0].finish_reason})"
)
parsed = response.choices[0].message.parsed
if parsed is None:
raise ValueError("Parsed response is None")
# Additional semantic validation
validate_business_rules(parsed)
return parsed
except (ValidationError, ValueError) as e:
error_msg = str(e)
print(f"Attempt {attempt + 1}/{max_retries} failed: {error_msg}")
if attempt < max_retries - 1:
# Add feedback to context
raw = response.choices[0].message.content if response else ""
conversation.append({"role": "assistant", "content": raw})
conversation.append({
"role": "user",
"content": f"Your response contains an error: {error_msg}. Please correct it."
})
else:
raise RuntimeError(
f"Failed after {max_retries} attempts. Last error: {error_msg}"
)
Sraith Pleananna Cúltaca
Ní réitíonn atriail gach rud: uaireanta tá doiciméad ró-ghnách don scéama. In ionad teipthe go tobann, déan meath go grásúil. Úsáideann an chéad iarracht Aschuir Struchtúrtha Saincheaptha, an rogha is iontaofa. Má theipeann air sin, téigh ar ais go dtí Mód JSON, atá níos solúbtha, ansin cuir an t-aschur trí model_validate() – coinníonn sé seo srianta an scéama gan brath ar an tsamhail chun iad a ghiniúint go foirfe. Mar rogha dheireanach, filleann an fheidhm None, ag fágáil an ghlaoraí chun cinneadh a dhéanamh idir ciúáil láimhe nó tréigean.
def extract_with_fallback(client, text, schema, system_prompt):
"""Extraction with fallback cascade."""
# Attempt 1: Custom Structured Output (best)
try:
return extract_with_retry(
client,
[
{"role": "system", "content": system_prompt},
{"role": "user", "content": text}
],
schema,
max_retries=2,
model="mistral-large-latest"
)
except RuntimeError:
print("Custom parse failed, falling back to JSON Mode")
# Attempt 2: JSON Mode (more flexible)
try:
response = client.chat.complete(
model="mistral-large-latest",
messages=[
{"role": "system", "content": system_prompt + "\nReturn valid JSON."},
{"role": "user", "content": text}
],
response_format={"type": "json_object"},
temperature=0
)
raw = json.loads(response.choices[0].message.content)
return schema.model_validate(raw) # Attempt Pydantic validation
except Exception:
print("JSON Mode failed, falling back to manual extraction")
# Attempt 3: Return partial object or error
return None
Dún an Tap in Am
I bpíblíne ardmhinicíochta, déanann briseadh API méadaitheoir d’atriail: teipeann ar gach doiciméad trí huaire, méadaíonn do bhille faoi thrí, agus buaileann moill mhéadaithe. Monatóraíonn briseoir ciorcaid teipthe thar fhuinneog shleamhnáin agus bacann sé glaoithe nuair a sháraítear tairseach – cúig theipthe i seasca soicind sa chumraíocht a thaispeántar anseo. Dúnann rath an ciorcad agus glanann sé an t-áireamh.
from collections import deque
from time import time
class CircuitBreaker:
def __init__(self, failure_threshold=5, window_seconds=60):
self.failures = deque()
self.threshold = failure_threshold
self.window = window_seconds
self.is_open = False
def record_failure(self):
now = time()
self.failures.append(now)
# Clean up errors outside the window
while self.failures and self.failures[0] < now - self.window:
self.failures.popleft()
if len(self.failures) >= self.threshold:
self.is_open = True
def record_success(self):
self.is_open = False
self.failures.clear()
def can_proceed(self) -> bool:
if not self.is_open:
return True
# Check if the window has passed
now = time()
while self.failures and self.failures[0] < now - self.window:
self.failures.popleft()
if len(self.failures) < self.threshold:
self.is_open = False
return True
return False
# Usage
breaker = CircuitBreaker(failure_threshold=5, window_seconds=60)
def safe_extract(client, text, schema):
if not breaker.can_proceed():
raise RuntimeError("Circuit open—too many recent errors")
try:
result = extract_with_retry(client, [...], schema)
breaker.record_success()
return result
except RuntimeError:
breaker.record_failure()
raise
Déan Infheicthe É
Fanann an t-innealra seo go léir dall gan lorg. Logáil gach glao lena fhad agus an scéama atá i gceist, cibé acu a éiríonn leis nó a theipeann. Ligeann na sonraí seo duit a chinneadh níos déanaí an dtagann meath ó fhadhb samhla, ó chineál doiciméid, nó ó athrú leid.
import logging
import time
logger = logging.getLogger("structured_output")
def monitored_extract(client, text, schema, **kwargs):
start = time.time()
try:
result = extract_with_retry(client, [...], schema, **kwargs)
duration = time.time() - start
logger.info(f"Extraction succeeded in {duration:.2f}s — schema={schema.__name__}")
return result
except Exception as e:
duration = time.time() - start
logger.error(f"Extraction failed in {duration:.2f}s — schema={schema.__name__} — {e}")
raise
Príomhphointí
- Tá bailíochtú struchtúrach (cineálacha) uathoibríoch; is faoi do dhílseacht féin atá bailíochtú séimeantach (loighic)
- Is é an patrún is éifeachtaí ná atriail le haiseolas: seol an earráid ar ais chuig an tsamhail
- Cuir sraith chúltaisce i bhfeidhm: Saincheaptha > Mód JSON > luach réamhshocraithe
- I dtáirgeadh ardmhinicíochta, úsáid briseoir ciorcaid chun cascáidí earráide a chosc
- Logáil gach glao chun monatóireachta agus diagnóise