Hoppa till huvudinnehåll
Svenska— Välj ett språk
Meny

Extraktion och validering med verktyg

Lektion 10 av 12 Uppdaterad 30 juli 2026 Utvecklare
På denna sida
  1. Bygg pålitliga extraktionspipelines
  2. Mönster: berikad extraktion
  3. Mönster: korsvalidering
  4. Mönster: beräkning och strukturering
  5. Arkitektur för en robust pipeline
  6. Felhantering i produktion
  7. Viktiga punkter

Bygg pålitliga extraktionspipelines

Genom att kombinera strukturerade utdata med verktyg (webbsökning, kodexekvering) kan du bygga robusta pipelines för extraktion och validering. Denna lektion visar hur du arkitektoniskt utformar dessa pipelines för produktionsmiljöer.

Mönster: berikad extraktion

Det vanligaste mönstret är att berika dataextraktion med webbsökning. Du börjar med råtext, och modellen extraherar entiteter för att sedan berika dem med information som hittas online.

from pydantic import BaseModel

class EntrepriseEnrichie(BaseModel):
    nom: str
    secteur: str
    pays_siege: str
    site_web: str | None
    description_courte: str
    nombre_employes_estime: str | None
    technologies_utilisees: list[str]

class ExtractionEnrichie(BaseModel):
    entreprises: list[EntrepriseEnrichie]
    relations: list[str]
    contexte: str

response, parsed = client.chat.parse(
    model="grok-4.20-0309-reasoning",
    messages=[{
        "role": "user",
        "content": """Extract and enrich the companies mentioned in this text:

        'Mistral AI announced a partnership with Scaleway to
        host its models in France. Meanwhile, Hugging Face
        continues to collaborate with OVHcloud on open source
        infrastructure.'"""
    }],
    response_format=ExtractionEnrichie,
    tools=[{"type": "web_search"}]
)

Mönster: korsvalidering

Korsvalidering använder webbsökning för att verifiera information som extraherats från ett dokument:

class FactCheck(BaseModel):
    affirmation: str
    verifie: bool
    source: str | None
    correction: str | None
    confiance: float

class RapportValidation(BaseModel):
    document_original: str
    verifications: list[FactCheck]
    fiabilite_globale: float
    resume: str

response, parsed = client.chat.parse(
    model="grok-4.20-0309-reasoning",
    messages=[{
        "role": "user",
        "content": """Verify the facts in this text:
        'France has 68 million inhabitants. Paris is the
        largest city in Europe. France's GDP is the 7th
        largest worldwide.'"""
    }],
    response_format=RapportValidation,
    tools=[{"type": "web_search"}]
)

for v in parsed.verifications:
    status = "Verified" if v.verifie else "Unverified"
    print(f"[{status}] {v.affirmation}")
    if v.correction:
        print(f"  → Correction: {v.correction}")

Mönster: beräkning och strukturering

Kombinera kodexekvering för beräkningar och strukturerade utdata för formatering:

class LigneFacture(BaseModel):
    description: str
    quantite: int
    prix_unitaire_ht: float
    montant_ht: float
    tva: float
    montant_ttc: float

class Facture(BaseModel):
    lignes: list[LigneFacture]
    total_ht: float
    total_tva: float
    total_ttc: float

response, parsed = client.chat.parse(
    model="grok-4.20-0309-reasoning",
    messages=[{
        "role": "user",
        "content": """Calculate the invoice:
        - 3x Pro License at 299 EUR excl. VAT (VAT 20%)
        - 1x Training at 1500 EUR excl. VAT (VAT 20%)
        - 12x Monthly Support at 49 EUR excl. VAT (VAT 20%)"""
    }],
    response_format=Facture,
    tools=[{"type": "code_interpreter"}]
)

print(f"Total excl. VAT: {parsed.total_ht} EUR")
print(f"Total incl. VAT: {parsed.total_ttc} EUR")

Arkitektur för en robust pipeline

För produktionsbruk bör du strukturera din pipeline i steg:

# Steg 1: Rå extraktion
class ExtractionBrute(BaseModel):
    entites: list[str]
    dates: list[str]
    montants: list[str]

# Steg 2: Berikning
class EntiteEnrichie(BaseModel):
    nom: str
    type: str
    details: str

# Steg 3: Validering
class ResultatValide(BaseModel):
    entites: list[EntiteEnrichie]
    score_qualite: float
    alertes: list[str]

Varje steg använder ett separat anrop med ett skräddarsytt schema. Denna modulära approach förenklar felsökning och övervakning.

Felhantering i produktion

try:
    response, parsed = client.chat.parse(
        model="grok-4.20-0309-reasoning",
        messages=messages,
        response_format=MonSchema,
        tools=[{"type": "web_search"}]
    )
except Exception as e:
    # Fallback utan webbsökning
    response, parsed = client.chat.parse(
        model="grok-4.20-0309-reasoning",
        messages=messages,
        response_format=MonSchema
    )

Viktiga punkter

  • Berikad extraktion kombinerar webbsökning + strukturerade utdata för komplett data
  • Korsvalidering verifierar fakta med webbsökning
  • Kodexekvering säkerställer exakta beräkningar i finansiella pipelines
  • Strukturera i separata steg för robusthet och felsökning
  • Planera alltid för en fallback-lösning om verktygen misslyckas