Sub topic 2
Classifying Text and Extracting Fields
Assume you know basic Python, JSON, and HTTP APIs. An LLM application usually combines a model with ordinary program code that checks and uses the model's output.
Classifying text and extracting fields
Classification assigns text to one label. Extraction finds named fields, such as a vendor and total in an invoice. Both tasks work well when the prompt defines the allowed result clearly.
import json
LABELS = ["billing", "bug", "feature_request", "other"]
def classify(ticket, complete):
prompt = (
"Classify this ticket as exactly one of: "
+ ", ".join(LABELS)
+ ". Reply with the label only.\n\nTicket: "
+ ticket
)
answer = complete(prompt).strip().lower()
return answer if answer in LABELS else "other"
def parse_invoice(raw):
data = json.loads(raw)
if not isinstance(data.get("vendor"), str):
raise ValueError("vendor must be a string")
if not isinstance(data.get("total"), (int, float)):
raise ValueError("total must be a number")
return dataGetting structured output you can trust
Structured output follows a format such as JSON. Parsing is not validation. Check required fields, types, ranges, and allowed values before passing data to another system. Reject malformed output or send it for human review.
Building conversational assistants
An assistant sends the conversation history, or a selected summary of it, with each request. Context management keeps prompts within the model's context limit. Store durable facts separately, and do not assume that a model remembers earlier sessions.
Code generation and review helpers
Models can draft tests, explain errors, and suggest patches. They are useful accelerators, but generated code still needs compilation, tests, dependency review, and security review. Give the model a narrow task and relevant files rather than an entire codebase.
Working with images, audio, and documents
Multimodal models accept inputs such as images, speech transcripts, PDFs, or scanned pages. They can describe, transcribe, and extract information from these inputs. Image quality, layout, handwriting, tables, and missing audio context can reduce accuracy.
Embeddings and semantic search
An embedding is a vector representing the meaning of text. Semantic search compares the query vector with document vectors, often using cosine similarity, and returns the closest passages. It can find related wording even when keywords differ.
Answering from your own documents with retrieval
Retrieval-augmented generation (RAG) retrieves relevant passages and places them in the model's prompt before generating an answer. Index documents in chunks, retrieve a small number of relevant chunks, and require answers to cite or stay within that evidence.
Exercise
Why should a classifier return a fallback label when the model produces an unknown label?
Show answer
The fallback keeps unexpected model output from silently entering downstream business logic.