Learn / NLP & Practical LLMs / Module 02
NLP & Practical LLMs · Module 02
Prompt Engineering and Schema-First Structured Outputs
Replace fragile chat prompts with clear task contracts, deterministic pre-checks, and validated JSON Schema / Pydantic outputs.
<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->
Why free-form chat output breaks pipelines
Asking an LLM "Extract the issue and severity from this ticket" produces a friendly paragraph—which breaks the moment downstream code expects a field named severity with values "low", "medium", or "high".
Treat every LLM call inside software like an untrusted parser that needs a strict interface contract.
Four basics of reliable prompts
- Separate instructions from untrusted input: keep system rules clearly delimited from user documents or pasted emails.
- Define the exact rubric: spell out what makes something
"high"vs."medium"instead of hoping the model guesses your team's policy. - Give 1–2 concrete examples (few-shot): one short input/output pair eliminates more ambiguity than three paragraphs of prose.
- Allow abstention: always include an explicit
"unknown"ornulloption so the model is not forced to invent a value when the text does not say.
Schema-first structured outputs with Pydantic
Modern LLM APIs (and local servers like Ollama) support structured outputs constrained by a JSON Schema. Defining that schema in Python with pydantic gives you both the prompt contract and automatic runtime validation:
from typing import Literal
from pydantic import BaseModel, Field
class IssueExtraction(BaseModel):
category: Literal["hardware", "software", "data", "unknown"]
severity: Literal["low", "medium", "high"]
summary: str = Field(max_length=160)
evidence_quote: str = Field(
description="Exact substring copied from the source text."
)
# Send IssueExtraction.model_json_schema() as the response schema,
# then validate the returned JSON before trusting any field:
raw_json = (
'{"category":"data","severity":"high",'
'"summary":"Sensor timestamp column shifted by 5 hours.",'
'"evidence_quote":"timestamps are offset by UTC-5 after the update"}'
)
record = IssueExtraction.model_validate_json(raw_json)
print(record.category, record.severity)The validation-repair loop
Even with schema guidance, smaller local models occasionally violate a field constraint. Wrap the call in a bounded retry loop (at most 2 retries):
- Parse the JSON with
model_validate_json(...). - If validation fails, pass the exact Pydantic error message back to the model and ask it to fix only the invalid field.
- If it still fails after 2 tries, route the record to a human review queue instead of silently corrupting your database.
<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->
Finished this module?
Mark it complete to update your browser-local progress bar for NLP & Practical LLMs.