Aqbeż għall-kontenut ewlieni
Malti— Agħżel lingwa
Menu

Każijiet ta' Użu Avvanzati

Lezzjoni 10 / 12 Aġġornat 29 ta’ Lulju 2026 Zviluppatur
F'din il-paġna
  1. Lil Hinn mill-Eżempji Sempliċi
  2. Estrazzjoni ta’ Fattura
  3. Analiżi tar-Reviżjonijiet Aspett b’Aspett
  4. Klassifikazzjoni ta’ Test f’Diversi Kategoriji
  5. Fattorizzazzjoni tas-Sejħa
  6. Punti Ewlenin

Lil Hinn mill-Eżempji Sempliċi

Issa tgħallimt Pydantic, Zod, u client.chat.parse(). It-tliet każijiet li jmiss imorru lil hinn minn skemi sempliċi ta’ erba’ oqsma lejn xenarji li se tiltaqa’ magħhom f’ambjenti intrapriżali: dokumenti kontabilistiċi, analiżi dettaljata tar-reviżjonijiet tal-klijenti, u testi li jappartjenu għal diversi kategoriji fl-istess ħin. Kull wieħed juri teknika differenti ta’ mudellar.

Estrazzjoni ta’ Fattura

L-ipproċessar tad-dokumenti huwa t-territorju naturali għall-iskemi mbejjna (nested). Fattura mhix oġġett ċatt: fiha intestatura, piè di page bit-totali, u numru varjabbli ta’ entrati tal-linja li għandhom l-istruttura tagħhom stess. Għalhekk, immudellaw LineItem separatament u mbagħad nirreferenzjawh fi ħdan lista. Il-munita tuża enum, li jipprevjeni lill-mudell milli jirritorna "euros" jew "€" skont kif tkun ifformulata d-dokument.

from pydantic import BaseModel, Field
from typing import Optional
from enum import Enum

class Currency(str, Enum):
    eur = "EUR"
    usd = "USD"
    gbp = "GBP"

class LineItem(BaseModel):
    description: str = Field(description="Line item description")
    quantity: float = Field(description="Quantity")
    unit_price: float = Field(description="Unit price excluding tax")
    vat_rate: float = Field(description="VAT rate as a percentage (e.g., 20.0)")
    total_ht: float = Field(description="Line total excluding tax")

class InvoiceData(BaseModel):
    invoice_number: str = Field(description="Invoice number")
    date: str = Field(description="Invoice date in YYYY-MM-DD format")
    due_date: Optional[str] = Field(default=None, description="Due date")
    vendor_name: str = Field(description="Vendor name")
    vendor_address: Optional[str] = Field(default=None)
    client_name: str = Field(description="Client name")
    line_items: list[LineItem] = Field(description="Invoice line items")
    subtotal_ht: float = Field(description="Subtotal excluding tax")
    total_vat: float = Field(description="Total VAT amount")
    total_ttc: float = Field(description="Total including tax")
    currency: Currency = Field(description="Currency")
    payment_method: Optional[str] = Field(default=None)

# Extraction
response = client.chat.parse(
    model="mistral-large-latest",
    messages=[
        {
            "role": "system",
            "content": """You are an accounting expert. Extract data from the invoice.
Be precise with amounts. Calculate totals if necessary.
Dates must be in YYYY-MM-DD format."""
        },
        {"role": "user", "content": invoice_text}
    ],
    response_format=InvoiceData,
    temperature=0
)

invoice = response.choices[0].message.parsed
print(f"Invoice {invoice.invoice_number} — {invoice.vendor_name}")
print(f"Total incl. tax: {invoice.total_ttc} {invoice.currency.value}")
for item in invoice.line_items:
    print(f"  - {item.description}: {item.quantity} x {item.unit_price}€ = {item.total_ht}€ excl. tax")

Il-format tad-data infurzat fil-prompt tas-sistema mhix dettall minuri: mingħajru, dokument Franċiż jista’ jipproduċi 12/03/2026 filwaqt li wieħed Amerikan jagħti 03/12/2026, u joħloq żewġ strings indistingwibbli għad-database tiegħek. Il-verżjoni TypeScript issegwi l-istess arkitettura, bil-format iddokumentat permezz ta’ .describe().

import { z } from "zod";

const LineItemSchema = z.object({
  description: z.string(),
  quantity: z.number(),
  unitPrice: z.number().describe("Unit price excluding tax"),
  vatRate: z.number().describe("VAT rate in %"),
  totalHt: z.number(),
});

const InvoiceSchema = z.object({
  invoiceNumber: z.string(),
  date: z.string().describe("Format YYYY-MM-DD"),
  dueDate: z.string().nullable(),
  vendorName: z.string(),
  clientName: z.string(),
  lineItems: z.array(LineItemSchema),
  subtotalHt: z.number(),
  totalVat: z.number(),
  totalTtc: z.number(),
  currency: z.enum(["EUR", "USD", "GBP"]),
});

const response = await client.chat.parse({
  model: "mistral-large-latest",
  messages: [
    { role: "system", content: "Extract invoice data precisely." },
    { role: "user", content: invoiceText },
  ],
  responseFormat: InvoiceSchema,
  temperature: 0,
});

const invoice = response.choices[0].message.parsed!;
console.log(`Invoice ${invoice.invoiceNumber} — Total: ${invoice.totalTtc} ${invoice.currency}`);

Analiżi tar-Reviżjonijiet Aspett b’Aspett

Reviżjoni reali ta’ klijent rari tkun pożittiva jew negattiva b’mod uniformi. Ir-reviżjoni tal-lukanda hawn taħt tfaħħar il-kamra u l-kolazzjon, tikkundanna l-parkeġġ u l-Wi-Fi, u toffri veduta nuwanzata tal-persunal: punteġġ globali wieħed jitlifek din l-informazzjoni kollha. Is-soluzzjoni hija li timmodella AspectSentiment li tista’ terġa’ tużah u titlob lista minnhom. Il-qasam evidence huwa l-aktar parti interessanti tal-iskema—billi titlob kwotazzjoni mit-test, tisforza lill-mudell jibbaża l-ġudizzju tiegħu u tagħtik il-mezzi biex tivverifikah.

from pydantic import BaseModel, Field

class AspectSentiment(BaseModel):
    aspect: str = Field(description="The aspect analyzed (quality, price, service, delivery, etc.)")
    sentiment: str = Field(description="positive, negative, or neutral")
    score: float = Field(description="Score between -1.0 (very negative) and 1.0 (very positive)")
    evidence: str = Field(description="Quote or excerpt from the text justifying the sentiment")

class ReviewAnalysis(BaseModel):
    overall_sentiment: str = Field(description="Overall sentiment: positive, negative, mixed, or neutral")
    overall_score: float = Field(description="Overall score between -1.0 and 1.0")
    aspects: list[AspectSentiment] = Field(description="Aspect-by-aspect analysis")
    recommendation: bool = Field(description="Does the author recommend the product/service?")
    key_strengths: list[str] = Field(description="Identified strengths")
    key_weaknesses: list[str] = Field(description="Identified weaknesses")

review_text = """
The hotel is magnificent; the room was spacious and clean. The breakfast is excellent
with a wide selection. However, the parking is outrageously expensive (€35/night) and the Wi-Fi was
unstable throughout the stay. The reception staff was very welcoming,
but room service took over an hour to deliver our order.
"""

response = client.chat.parse(
    model="mistral-large-latest",
    messages=[
        {
            "role": "system",
            "content": "Analyze this customer review by detailing each mentioned aspect."
        },
        {"role": "user", "content": review_text}
    ],
    response_format=ReviewAnalysis,
    temperature=0
)

review = response.choices[0].message.parsed
print(f"Overall sentiment: {review.overall_sentiment} ({review.overall_score:+.1f})")
for aspect in review.aspects:
    print(f"  [{aspect.score:+.1f}] {aspect.aspect}: {aspect.sentiment}")

Klassifikazzjoni ta’ Test f’Diversi Kategoriji

Għall-kuntrarju tal-klassifikazzjoni sempliċi, fejn tiġi assenjata tikketta waħda, il-klassifikazzjoni multi-label tirrikonoxxi li test jista’ jappartjeni għal diversi kategoriji. L-inċident deskritt hawn taħt jmiss is-sigurtà, il-finanzi, il-frodi, u l-protezzjoni tad-data fl-istess ħin: li tisforza tikketta waħda tkun tifqar il-loġika tar-routing.

Żewġ elementi tal-iskema jistħoqqilhom attenzjoni. reasoning jeħtieġ ġustifikazzjoni għal kull tikketta, li ttejjeb il-kwalità tal-punteġġ. requires_human_review ibiddel l-inċertezza tal-mudell f’sinjal operazzjonali: minflok ma tiskopri wara l-fatt li klassifikazzjoni kienet dubjuża, awtomatikament tgħaddiha lil bniedem meta l-kunfidenza tonqos taħt 0.7.

from pydantic import BaseModel, Field

class LabelScore(BaseModel):
    label: str = Field(description="Category name")
    confidence: float = Field(description="Confidence score between 0.0 and 1.0")
    reasoning: str = Field(description="One-sentence justification")

class MultiLabelClassification(BaseModel):
    primary_label: str = Field(description="Primary category")
    all_labels: list[LabelScore] = Field(
        description="All applicable categories with their confidence scores"
    )
    requires_human_review: bool = Field(
        description="True if classification is uncertain (confidence < 0.7)"
    )

text = """
Our mobile payment application has a security vulnerability allowing
access to banking data. Several customers have reported unauthorized
transactions. The technical team is currently investigating.
"""

response = client.chat.parse(
    model="mistral-large-latest",
    messages=[
        {
            "role": "system",
            "content": """Classify this text among the following categories (multiple possible):
security, finance, technical, legal, customer_support, compliance, fraud, data_privacy.
Assign a confidence score to each applicable category."""
        },
        {"role": "user", "content": text}
    ],
    response_format=MultiLabelClassification,
    temperature=0
)

result = response.choices[0].message.parsed
print(f"Primary category: {result.primary_label}")
print(f"Human review required: {'Yes' if result.requires_human_review else 'No'}")
for label in result.all_labels:
    print(f"  [{label.confidence:.0%}] {label.label} — {label.reasoning}")

Fattorizzazzjoni tas-Sejħa

Dawn it-tliet eżempji jaqsmu l-istess mekkaniżmu: prompt tas-sistema, test, skema, u temperature=0. Minflok ma tikkopja s-sejħa għal kull każ ġdid, estrajha f’funzjoni ġenerika. Il-TypeVar marbut ma’ BaseModel iżomm it-tipar (typing): l-oġġett irritornat ikollu t-tip tal-iskema mgħoddija bħala argument, u l-IDE tiegħek ikun jaf dan.

from typing import TypeVar, Type
from pydantic import BaseModel

T = TypeVar("T", bound=BaseModel)

def extract(client, text: str, schema: Type[T], system_prompt: str = "") -> T:
    """Reusable structured extraction."""
    messages = []
    if system_prompt:
        messages.append({"role": "system", "content": system_prompt})
    messages.append({"role": "user", "content": text})

    response = client.chat.parse(
        model="mistral-large-latest",
        messages=messages,
        response_format=schema,
        temperature=0
    )
    return response.choices[0].message.parsed

# Usage
invoice = extract(client, invoice_text, InvoiceData, "Extract invoice data.")
review = extract(client, customer_review, ReviewAnalysis, "Analyze this customer review.")
classification = extract(client, ticket, MultiLabelClassification, "Classify this text.")

Tliet każijiet ta’ użu differenti ħafna, kull wieħed jeħtieġ biss linja waħda ta’ kodiċi biex isejjaħ: dan huwa l-benefiċċju konkret ta’ mudellar tajjeb tal-iskemi.

Punti Ewlenin

  • L-iskemi mbejjna (list[LineItem], list[AspectSentiment]) jippermettu analiżijiet kumplessi
  • L-enums (Currency, kategoriji) jillimitaw il-valuri possibbli
  • Il-qasam evidence / reasoning jisforza lill-mudell jiġġustifika l-għażliet tiegħu
  • Wrapper ġeneriku jnaqqas id-duplikazzjoni tal-kodiċi
  • temperature=0 huwa obbligatorju għal dawn il-każijiet ta’ użu fil-produzzjoni