In Stage 1 you called a model and logged what every answer cost. The answers were free text, which is fine for people but not for programs. In this stage you’ll make a model return structured data that your code can check, and you’ll measure how often it’s right. That measurement is the start of everything that follows in the path.

You’ll build: an extractor that turns job ads into validated records, plus a tiny evaluation that scores it.

You need: the Stage 1 setup (Python, requests, a local model in Ollama) and one more package:

pip install pydantic

1. A prompt is a specification

Most bad outputs come from vague instructions. A useful prompt states three things:

  1. The task: what to produce, from what input.
  2. The rules for uncertainty: what to do when the input doesn’t say. Without this rule, models tend to guess.
  3. The output format: exactly what shape the answer must take.

Keep instructions (the system message) separate from data (the user message). That way the model can tell your rules from the text it’s processing, and you can change one without touching the other.

2. Define the output as a schema

With Pydantic you describe the record once, in Python, and get two things from it: a JSON Schema to send to the model, and a validator for what comes back. Save this as extract.py:

import requests
from pydantic import BaseModel, ValidationError

OLLAMA = "http://localhost:11434/api/chat"

class JobAd(BaseModel):
    title: str
    company: str | None
    location: str | None
    remote: bool
    skills: list[str]

SYSTEM = (
    "Extract the job ad's fields. Use null for company or location if the ad doesn't state them. "
    "remote is true only if the ad says remote work is allowed. "
    "skills lists the technical skills the ad names, in lowercase. Do not guess."
)

def extract(model: str, ad: str) -> JobAd:
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": ad}]
    for attempt in range(2):
        r = requests.post(OLLAMA, json={
            "model": model,
            "messages": messages,
            "stream": False,
            "format": JobAd.model_json_schema(),   # constrain the output to the schema
            "options": {"temperature": 0},
        }, timeout=300)
        r.raise_for_status()
        raw = r.json()["message"]["content"]
        try:
            return JobAd.model_validate_json(raw)
        except ValidationError as e:
            # Retry once, telling the model exactly what was wrong.
            messages += [{"role": "assistant", "content": raw},
                         {"role": "user", "content": f"That output was invalid: {e}. Return corrected JSON only."}]
    raise ValueError(f"no valid output after 2 attempts: {raw[:200]}")

Three details matter:

  • The format parameter passes the JSON Schema to Ollama, which constrains generation to output that fits it. Hosted APIs offer equivalent “structured output” or “JSON mode” options.
  • temperature: 0 makes extraction as repeatable as possible.
  • Validation still happens in your code. A schema-shaped answer can still be wrong, and a validator is what stands between model output and the rest of your system.

3. Build a small test set

You can’t improve what you don’t measure. Write a few inputs with the answers you expect, including awkward cases. Save this as evaluate.py:

import sys
from extract import extract

CASES = [
    ("Senior Data Analyst at Northwind, Lisbon. SQL and Python required; Tableau a plus. Hybrid, 2 days remote.",
     {"title": "Senior Data Analyst", "company": "Northwind", "location": "Lisbon", "remote": True,
      "skills": {"sql", "python", "tableau"}}),
    ("We're hiring an ML Engineer to deploy models with Docker and Kubernetes. Fully remote.",
     {"title": "ML Engineer", "company": None, "location": None, "remote": True,
      "skills": {"docker", "kubernetes"}}),
    ("Office-based BI Developer in Monterrey for Acme Corp. Power BI, DAX and SQL Server.",
     {"title": "BI Developer", "company": "Acme Corp", "location": "Monterrey", "remote": False,
      "skills": {"power bi", "dax", "sql server"}}),
]

def score(model: str) -> None:
    fields, correct = 0, 0
    for ad, want in CASES:
        got = extract(model, ad).model_dump()
        got["skills"] = {s.lower() for s in got["skills"]}
        for k, v in want.items():
            fields += 1
            ok = got[k] == v if k != "title" else v.lower() in (got[k] or "").lower()
            correct += ok
            if not ok:
                print(f"  miss {k}: expected {v!r}, got {got[k]!r}")
    print(f"{model}: {correct}/{fields} fields correct ({correct / fields:.0%})")

if __name__ == "__main__":
    score(sys.argv[1])

Run it with python evaluate.py <model>. You’ll get a number, and a list of the exact fields the model got wrong.

4. Use the misses

Every miss is information. Common ones and what to try:

Miss Likely cause Try
A guessed company or location The uncertainty rule isn’t strong enough Make the null rule more explicit, with an example
“Hybrid” read as fully remote, or not remote The field’s meaning is ambiguous Define remote precisely in the system message
Skills that aren’t skills (“communication”) No definition of a skill Say “technical skills” and give two examples
Validation errors Output doesn’t fit the schema Check the schema; the retry should fix rare cases
'Acme Corp.' vs 'Acme Corp' The scorer, not the model, is too strict Normalise strings (trim, case, trailing punctuation) before comparing

When we ran this exact code on a small local model (gemma4:e4b), it scored 14 of 15 fields. The only miss was 'Acme Corp.' with a trailing full stop: a scoring problem, not an extraction one. Decide which side a miss is on before you change anything.

Change one thing at a time and re-run the evaluation. If the score goes up, keep the change; if not, revert it. That loop of changing, measuring and keeping or reverting is the core habit of AI engineering. Later stages make it more rigorous, but the idea doesn’t change.

Project checklist

  • extract.py returns validated JobAd records and retries once on invalid output.
  • evaluate.py scores at least five ads, including one with missing fields.
  • You’ve compared two models, or two prompt versions, by score.
  • A short note: which misses remain, and what you’d try next.

Next: Stage 3, retrieval: answering questions over documents that don’t fit in a prompt. Join the waitlist to get it when it’s published.

Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.