AI and machine learning · Intermediate · 22 min
Get schema-valid JSON from a local model with Ollama
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Ollama 0.40.18 · qwen3:0.6b · Python 3.15 · ollama (Python) 0.6.3 · Pydantic 2.14.4
You will make a small local model extract salary details from 20 job adverts as JSON that matches a Pydantic schema, then measure how many replies are still wrong on meaning and how many a retry with the validation error repairs.
On this page
Asking a model to "reply in JSON" works most of the time. A small local model will sometimes add a sentence first, wrap the JSON in a Markdown fence, rename a field or stop halfway. Ollama can rule most of that out. Pass a JSON Schema in the format parameter and Ollama restricts which tokens the model may write next, so the reply is built to fit the schema as it is generated. This is called constrained decoding.
Constrained decoding fixes the shape of the reply, not its meaning. A model can return a perfectly valid object with a salary of 260,000 when the advert says 240,000 plus a 20,000 bonus. In this tutorial you measure both kinds of failure on a task you can check: extracting the pay from 20 short job adverts. You will:
- describe the reply as a Pydantic model and send its JSON Schema to Ollama,
- add rules the schema cannot express, such as "every salary figure must appear in the advert",
- score all 20 replies against the answers you wrote by hand,
- add one retry that sends the validation error back to the model, and see what it fixes and what it cannot.
The model is qwen3:0.6b, about 520 MB, running on a CPU. Every call uses temperature 0 and a fixed seed, so a rerun gives the same replies. A larger model will make fewer mistakes, and your counts will differ from anyone else's, but the method does not change. The adverts use naira, shillings, cedis, rand and CFA francs, and one is in French, because pay in real adverts is written in many ways. Because the model is local, adverts and anything else you extract from, such as CVs, never leave your machine.
This tutorial is about a local model. For the same task with a hosted model, Anthropic's API has its own feature, covered in get structured JSON output from an LLM.
Step 1 · Pull the model and create the project
Check that Ollama is running and download the model. It is about 520 MB, so on prepaid mobile data start it on Wi-Fi or during an off-peak bundle. If the download stops, run the same command again and it carries on:
ollama --version
ollama pull qwen3:0.6bCreate a project with Python 3.15, the official Ollama client and Pydantic. Exact pins stop a new release from changing behaviour between runs:
mkdir -p ~/jobads-demo/data
cd ~/jobads-demo
uv init --no-package --python 3.15
uv add "ollama==0.6.3" "pydantic==2.14.4"Check it worked
uv run python -c "import sys; from importlib.metadata import version; print(sys.version.split()[0], version('ollama'), version('pydantic'))"
ollama listThe first line prints a 3.15 version number, 0.6.3 and 2.14.4. ollama list shows qwen3:0.6b at about 522 MB.
Step 2 · Describe the reply as a Pydantic model
Write the shape you want back as a class. Pydantic turns it into a JSON Schema for Ollama, and later uses the same class to check each reply. Create models.py:
cat > models.py <<'PY'
from typing import Literal
from pydantic import BaseModel, ConfigDict
Currency = Literal["NGN", "KES", "GHS", "ZAR", "XOF", "USD", "EUR", "GBP"]
Period = Literal["hour", "day", "month", "year"]
class JobAd(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
company: str
city: str | None
remote: bool
currency: Currency | None
salary_min: int | None
salary_max: int | None
period: Period | None
SCHEMA = JobAd.model_json_schema()
PYThree choices in this class matter for extraction:
- No defaults.
city: str | Nonewith no= Nonemakes the field required but allowed to benull. The model must write every key, and must say "nothing" explicitly rather than skip a key you then have to guess about. Literalfor closed sets. Currency and period become a fixed list in the schema, so the model cannot writenaira,Kshormonthly. Your code then compares against eight codes, not every spelling a human might use.extra="forbid". The schema says no other keys are allowed, and Pydantic rejects any it finds.
Print the schema Ollama will receive:
uv run python -c "import json; from models import SCHEMA; print(json.dumps(SCHEMA, indent=2))" | tee schema.jsonCheck it worked
uv run python - <<'PY'
import json
schema = json.load(open("schema.json", encoding="utf-8"))
print("required:", schema["required"])
print("additionalProperties:", schema["additionalProperties"])
print("currency:", schema["properties"]["currency"])
assert len(schema["required"]) == 8 and schema["additionalProperties"] is False
PYrequired lists all eight fields and additionalProperties is False. The currency entry is something like {'anyOf': [{'enum': ['NGN', ...], 'type': 'string'}, {'type': 'null'}], 'title': 'Currency'}: one of the eight codes, or null.
Step 3 · Write 20 adverts and the answers you expect
You cannot count wrong answers without knowing the right ones. Each line holds an advert and the four pay fields you would write yourself. A single figure goes in both salary_min and salary_max; an advert with no figure gets four nulls. Several adverts contain numbers that are not pay, such as a team size, an allowance or a signing bonus, because those are where small models slip:
cat > data/adverts.jsonl <<'JSONL'
{"id": 1, "text": "Delivery rider, Swift Parcels, Lagos. Own smartphone needed. Pay: NGN 180,000 per month.", "expected": {"currency": "NGN", "salary_min": 180000, "salary_max": 180000, "period": "month"}}
{"id": 2, "text": "Junior data analyst at Mazao Insights, Nairobi. Hybrid, two days in the office. KES 85,000 to 110,000 a month.", "expected": {"currency": "KES", "salary_min": 85000, "salary_max": 110000, "period": "month"}}
{"id": 3, "text": "Customer support agent, fully remote, for Kopa Telecom. Salary: competitive.", "expected": {"currency": null, "salary_min": null, "salary_max": null, "period": null}}
{"id": 4, "text": "Senior backend engineer, Tembo Pay. Remote across Africa. USD 48,000-60,000 per year.", "expected": {"currency": "USD", "salary_min": 48000, "salary_max": 60000, "period": "year"}}
{"id": 5, "text": "Pharmacy assistant at Akwaaba Health, Kumasi. GHS 3,500 monthly plus GHS 500 transport allowance.", "expected": {"currency": "GHS", "salary_min": 3500, "salary_max": 3500, "period": "month"}}
{"id": 6, "text": "Warehouse supervisor, Cape Freight, Cape Town. Team of 14. R 28,000 per month and a 13th cheque.", "expected": {"currency": "ZAR", "salary_min": 28000, "salary_max": 28000, "period": "month"}}
{"id": 7, "text": "Chargé de clientèle, Banque Teranga, Dakar. Salaire : 450 000 FCFA par mois.", "expected": {"currency": "XOF", "salary_min": 450000, "salary_max": 450000, "period": "month"}}
{"id": 8, "text": "Freelance translator, English to Swahili, Lugha Studio. Remote. USD 25 an hour.", "expected": {"currency": "USD", "salary_min": 25, "salary_max": 25, "period": "hour"}}
{"id": 9, "text": "Event photographer for Ankara Weddings, Abuja. ₦60,000 per day for each wedding.", "expected": {"currency": "NGN", "salary_min": 60000, "salary_max": 60000, "period": "day"}}
{"id": 10, "text": "Product designer, Oya Labs, Lagos. ₦9,600,000 a year, paid monthly.", "expected": {"currency": "NGN", "salary_min": 9600000, "salary_max": 9600000, "period": "year"}}
{"id": 11, "text": "Field sales representative, SunBox Solar, Kampala. Commission only, no basic salary.", "expected": {"currency": null, "salary_min": null, "salary_max": null, "period": null}}
{"id": 12, "text": "Mobile developer (Flutter), Duka App. Remote within Kenya. KES 1,800,000 per year before tax.", "expected": {"currency": "KES", "salary_min": 1800000, "salary_max": 1800000, "period": "year"}}
{"id": 13, "text": "Night-shift security guard, Harbour Logistics, Mombasa. KES 22,000 a month, 6 nights on and 2 off.", "expected": {"currency": "KES", "salary_min": 22000, "salary_max": 22000, "period": "month"}}
{"id": 14, "text": "IT support technician at Northgate College, Manchester. £27,500 to £31,000 per annum.", "expected": {"currency": "GBP", "salary_min": 27500, "salary_max": 31000, "period": "year"}}
{"id": 15, "text": "Contract DevOps engineer for a Dutch client, 100% remote. €450 per day, 6-month contract.", "expected": {"currency": "EUR", "salary_min": 450, "salary_max": 450, "period": "day"}}
{"id": 16, "text": "Part-time bookkeeper, Mama Put Foods, Ibadan. 20 hours a week at ₦3,500 an hour.", "expected": {"currency": "NGN", "salary_min": 3500, "salary_max": 3500, "period": "hour"}}
{"id": 17, "text": "Teaching assistant, Bright Steps Academy, Accra. GH₵ 2,800 a month after a 3-month probation.", "expected": {"currency": "GHS", "salary_min": 2800, "salary_max": 2800, "period": "month"}}
{"id": 18, "text": "Graduate trainee, Kalahari Mining, Johannesburg. R 240,000 per year with a R 20,000 signing bonus.", "expected": {"currency": "ZAR", "salary_min": 240000, "salary_max": 240000, "period": "year"}}
{"id": 19, "text": "Content moderator for Sauti Media, remote, Hausa and English. USD 600 per month.", "expected": {"currency": "USD", "salary_min": 600, "salary_max": 600, "period": "month"}}
{"id": 20, "text": "Head chef, Jollof House, London. £42,000 a year plus tips.", "expected": {"currency": "GBP", "salary_min": 42000, "salary_max": 42000, "period": "year"}}
JSONLThe French advert reads "Customer adviser ... Salary: 450,000 CFA francs a month". Its figure uses a space as the thousands separator, as French does. FCFA in Senegal is the West African CFA franc, code XOF.
Check it worked
uv run python - <<'PY'
import json
from collections import Counter
rows = [json.loads(line) for line in open("data/adverts.jsonl", encoding="utf-8")]
print(len(rows), "adverts")
print("no salary:", sum(r["expected"]["salary_min"] is None for r in rows))
print("periods:", dict(Counter(r["expected"]["period"] for r in rows)))
assert len(rows) == 20 and [r["id"] for r in rows] == list(range(1, 21))
PYThe output is 20 adverts, no salary: 2, and counts for each period, with month the most common.
Step 4 · Add the rules a schema cannot express
The schema guarantees types. It cannot say "if there is a salary, there must be a currency", and it knows nothing about the advert. Pydantic can check both. Create rules.py. CheckedJobAd adds three rules on top of JobAd, and the last one reads the advert from the validation context:
- a salary needs a currency and a period, and no salary means neither,
salary_minis not larger thansalary_max,- every salary figure appears in the advert as a number.
numbers_injoins thousands written as9,600,000or450 000before it looks.
check sorts every reply into one of three results: schema (not valid JSON, or the wrong shape), rule (the right shape, but a rule failed) or ok.
cat > rules.py <<'PY'
import re
from typing import Self
from pydantic import ValidationError, ValidationInfo, model_validator
from models import JobAd
THOUSANDS = re.compile(r"(?<=\d)[,\s ](?=\d{3}\b)")
def numbers_in(text):
return {int(n) for n in re.findall(r"\d+", THOUSANDS.sub("", text))}
class CheckedJobAd(JobAd):
@model_validator(mode="after")
def check_salary(self, info: ValidationInfo) -> Self:
amounts = [v for v in (self.salary_min, self.salary_max) if v is not None]
if amounts and (self.currency is None or self.period is None):
raise ValueError("a salary needs both currency and period")
if not amounts and (self.currency is not None or self.period is not None):
raise ValueError("currency and period must be null when there is no salary")
if len(amounts) == 2 and self.salary_min > self.salary_max:
raise ValueError("salary_min is larger than salary_max")
advert = (info.context or {}).get("advert")
if advert:
found = numbers_in(advert)
for name in ("salary_min", "salary_max"):
value = getattr(self, name)
if value is not None and value not in found:
raise ValueError(f"{name} {value} does not appear in the advert")
return self
def check(raw, advert):
"""Return (status, ad, error), where status is schema, rule or ok."""
try:
ad = JobAd.model_validate_json(raw)
except ValidationError as error:
return "schema", None, error
try:
CheckedJobAd.model_validate(ad.model_dump(), context={"advert": advert})
except ValidationError as error:
return "rule", ad, error
return "ok", ad, None
PYTest the rules with hand-written replies before you involve the model. The advert is number 18, with a salary and a signing bonus:
uv run python - <<'PY'
import json
from rules import check, numbers_in
advert = "Graduate trainee, Kalahari Mining, Johannesburg. R 240,000 per year with a R 20,000 signing bonus."
print("numbers:", sorted(numbers_in(advert)))
base = {"title": "Graduate trainee", "company": "Kalahari Mining", "city": "Johannesburg",
"remote": False, "currency": "ZAR", "period": "year"}
cases = {
"right": {**base, "salary_min": 240000, "salary_max": 240000},
"bonus added": {**base, "salary_min": 260000, "salary_max": 260000},
"bonus as min": {**base, "salary_min": 20000, "salary_max": 240000},
"no currency": {**base, "currency": None, "salary_min": 240000, "salary_max": 240000},
}
results = []
for name, data in cases.items():
status, ad, error = check(json.dumps(data), advert)
results.append(status)
print(f"{name:<13} {status:<5} {error.errors()[0]['msg'] if error else ''}")
status, ad, error = check('{"title": "Graduate trainee", "comp', advert)
print(f"{'cut off':<13} {status:<5} {error.errors()[0]['type']}")
assert results == ["ok", "rule", "ok", "rule"] and status == "schema"
PYCheck it worked
The numbers are [20000, 240000]. right is ok. bonus added is rule with Value error, salary_min 260000 does not appear in the advert, and no currency is rule too. A reply cut off mid-key is schema with the error type json_invalid.
Look at bonus as min: it is ok, yet the salary is wrong. Both figures are in the advert and the minimum is below the maximum, so no rule fires. That is the kind of failure only your expected answers will reveal.
Step 5 · Send the schema with the request
Create extract.py. ask calls the model with format=SCHEMA, thinking turned off, temperature 0, seed 42 and a cap of 400 output tokens, which is several times what one reply needs. The schema also goes into the system prompt as text: Ollama's documentation recommends it, because the model writes better values when it can read what each field is for, not only which tokens are allowed. extract checks the reply and, if retries is above zero, sends the errors back and asks again. retries stays at 0 until the step after next.
cat > extract.py <<'PY'
import json
import sys
from pathlib import Path
import ollama
from models import SCHEMA
from rules import check
MODEL = "qwen3:0.6b"
OPTIONS = {"temperature": 0, "seed": 42, "num_predict": 400}
INSTRUCTIONS = f"""Extract facts from one job advert as JSON matching this schema:
{json.dumps(SCHEMA)}
Rules:
- salary_min and salary_max are whole numbers in the advert's currency, with no separators. For a single figure, use it for both.
- period is how often that amount is earned: hour, day, month or year.
- Ignore bonuses, allowances, tips, team sizes and other numbers that are not the salary.
- If the advert gives no salary figure, set currency, salary_min, salary_max and period to null.
- city is null when the advert names none. remote is true only if the job can be done fully remotely.
- Use only facts stated in the advert."""
def load_adverts(path="data/adverts.jsonl"):
lines = Path(path).read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
def first_messages(advert):
return [
{"role": "system", "content": INSTRUCTIONS},
{"role": "user", "content": advert},
]
def ask(messages, use_format=True):
response = ollama.chat(
model=MODEL,
messages=messages,
format=SCHEMA if use_format else None,
think=False,
options=OPTIONS,
)
return response.message.content or "", response.done_reason
def format_errors(error):
lines = []
for item in error.errors():
where = ".".join(str(part) for part in item["loc"]) or "whole object"
lines.append(f"- {where}: {item['msg']}")
return "\n".join(lines)
def extract(advert, retries=0):
messages = first_messages(advert)
attempts = []
for _ in range(retries + 1):
raw, done_reason = ask(messages)
status, ad, error = check(raw, advert)
feedback = format_errors(error) if error else None
if done_reason != "stop":
feedback = f"- the reply stopped early ({done_reason})\n{feedback or ''}"
attempts.append({"raw": raw, "status": status, "done_reason": done_reason, "error": feedback})
if status == "ok":
break
messages = messages + [
{"role": "assistant", "content": raw},
{"role": "user", "content": f"That JSON failed validation:\n{feedback}\n"
"Return corrected JSON for the same advert."},
]
return status, ad, attempts
if __name__ == "__main__":
wanted = int(sys.argv[1]) if len(sys.argv) > 1 else 1
item = next(a for a in load_adverts() if a["id"] == wanted)
print(item["text"])
for use_format in (False, True):
raw, done_reason = ask(first_messages(item["text"]), use_format)
status, ad, error = check(raw, item["text"])
label = "schema" if use_format else "none"
print(f"\n--- format={label} done_reason={done_reason} result={status}")
print(raw.strip()[:500])
PYdone_reason is stop when the model finished on its own. Anything else means it was cut short, usually by num_predict, and the JSON is incomplete. Telling the model so in the retry message gives it a reason to write less.
Run the same advert with and without the schema:
uv run python extract.py 10Check it worked
uv run python - <<'PY'
from extract import ask, first_messages, load_adverts
from rules import check
item = load_adverts()[0]
raw, done_reason = ask(first_messages(item["text"]))
status, ad, error = check(raw, item["text"])
print(done_reason, status, ad)
assert status != "schema"
PYWithout format, the reply may be JSON, JSON inside a Markdown code fence, or JSON with a sentence around it; with a 0.6b model it is often schema because of that. With format=schema the reply is a single object with all eight keys and result is ok or rule. The second command checks advert 1, the delivery rider. It prints stop, then ok or rule, then the parsed JobAd.
Step 6 · Score all 20 adverts
Create run.py. It extracts every advert, compares the four pay fields with your expected answers and saves the details:
cat > run.py <<'PY'
import argparse
import json
from collections import Counter
from pathlib import Path
from extract import extract, load_adverts
PAY = ("currency", "salary_min", "salary_max", "period")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--retries", type=int, default=0)
args = parser.parse_args()
rows = []
for item in load_adverts():
status, ad, attempts = extract(item["text"], retries=args.retries)
got = ad.model_dump() if ad else None
salary_ok = got is not None and all(got[k] == item["expected"][k] for k in PAY)
rows.append({"id": item["id"], "status": status, "attempts": len(attempts),
"salary_ok": salary_ok, "got": got, "expected": item["expected"],
"text": item["text"], "log": attempts})
summary = {
"retries": args.retries,
"total": len(rows),
"status": dict(Counter(r["status"] for r in rows)),
"retried": sum(r["attempts"] > 1 for r in rows),
"salary_correct": sum(r["salary_ok"] for r in rows),
"passed_but_wrong": sum(r["status"] == "ok" and not r["salary_ok"] for r in rows),
}
Path("results").mkdir(exist_ok=True)
out = Path(f"results/retries-{args.retries}.json")
out.write_text(json.dumps({"summary": summary, "rows": rows}, indent=2, ensure_ascii=False),
encoding="utf-8")
s = summary
print(f"retries={s['retries']} results {s['status']} salary right {s['salary_correct']}/{s['total']}"
f" passed every check but wrong {s['passed_but_wrong']}")
for r in rows:
if r["status"] != "ok" or not r["salary_ok"]:
got = [r["got"][k] for k in PAY] if r["got"] else None
want = [r["expected"][k] for k in PAY]
print(f" advert {r['id']:>2} {r['status']:<6} got {got} want {want}")
if r["log"][-1]["error"]:
print(" " + r["log"][-1]["error"].replace("\n", "\n "))
print(f"saved {out}")
if __name__ == "__main__":
main()
PY
uv run python run.pyOn a laptop CPU the 20 calls take somewhere between half a minute and a few minutes.
Check it worked
uv run python - <<'PY'
import json
s = json.load(open("results/retries-0.json", encoding="utf-8"))["summary"]
print(s)
assert s["total"] == 20 and sum(s["status"].values()) == 20 and s["retried"] == 0
PYThe first line of output reads something like retries=0 results {'ok': 15, 'rule': 5} salary right 13/20 passed every check but wrong 2, with your own numbers. Below it is one line per advert that failed a rule or got the pay wrong, with what the model wrote, what you expected, and the validation error if there was one.
Sort the results into three groups:
schemashould be 0. Constrained decoding exists to make this zero. If it is not, the reply was cut off: look forstopped earlyin the error.rulereplies are the right shape but break a rule, such as a figure that is not in the advert. Your code can see these, so it can act on them.- Passed every check but wrong is the number to worry about. These replies would flow into your database without complaint. Look for the wrong period (advert 10 is quoted per year but paid monthly) and for a bonus or allowance counted in the range.
Step 7 · Retry with the validation error
A rule failure comes with a precise message, so you can send it back and ask for a correction. Run the scorer again with one retry:
uv run python run.py --retries 1Put the two runs side by side. Create compare.py:
cat > compare.py <<'PY'
import json
from pathlib import Path
runs = sorted(
(json.loads(p.read_text(encoding="utf-8")) for p in Path("results").glob("retries-*.json")),
key=lambda run: run["summary"]["retries"],
)
print(f"{'retries':>7} {'ok':>4} {'rule':>5} {'schema':>7} {'retried':>8} {'salary right':>13} {'passed but wrong':>17}")
for run in runs:
s, st = run["summary"], run["summary"]["status"]
print(f"{s['retries']:>7} {st.get('ok', 0):>4} {st.get('rule', 0):>5} {st.get('schema', 0):>7} "
f"{s['retried']:>8} {s['salary_correct']:>10}/{s['total']} {s['passed_but_wrong']:>17}")
if len(runs) == 2:
before = {r["id"]: r for r in runs[0]["rows"]}
for r in runs[1]["rows"]:
b = before[r["id"]]
if (b["status"], b["salary_ok"]) != (r["status"], r["salary_ok"]):
print(f"advert {r['id']:>2}: {b['status']} -> {r['status']}, "
f"salary right {b['salary_ok']} -> {r['salary_ok']}")
PY
uv run python compare.py | tee comparison.txtCheck it worked
test "$(grep -cE '^ +(0|1) ' comparison.txt)" -eq 2
uv run python - <<'PY'
import json
before = json.load(open("results/retries-0.json", encoding="utf-8"))["rows"]
run = json.load(open("results/retries-1.json", encoding="utf-8"))
s, rows = run["summary"], run["rows"]
print(s)
failed_first = sum(r["log"][0]["status"] != "ok" for r in rows)
assert s["total"] == 20 and s["retried"] == failed_first
same = sum(a["log"][0]["raw"] == b["log"][0]["raw"] for a, b in zip(before, rows))
print(f"first attempts identical to the 0-retry run: {same}/20")
PYThe table has one row for 0 retries and one for 1. The check confirms that the retried count for the second run equals the number of adverts whose first attempt in that same run failed, because only failed replies get a second attempt. It also prints how many first attempts match the 0-retry run word for word. Below the table is one line per advert whose result changed.
Read the table carefully:
- With temperature 0 and a fixed seed, first attempts should normally be identical in both runs, but Ollama does not promise identical output from one run to the next. If the check reports fewer than 20 matching first attempts, a change for those adverts is not from the retry.
- A retry can turn
ruleintook. Check whether the salary also became right: a model told that 260000 is not in the advert may answer 240000, or may move to 20000, which passes the rules and is still wrong. - The retry never touches replies that passed every check, so
passed but wrongdoes not go down. It can go up, when a retry turns arulefailure into a wrong answer that the rules accept.
Each retry is a second model call for that advert, so it costs time on a CPU. Try one retry; if the second attempt fails the same rule, send the advert to a person rather than retrying again.
Step 8 · Read the replies that passed but were wrong
The counts tell you how often, but the replies tell you why. Print every advert that passed all checks with the wrong pay, next to its text:
uv run python - <<'PY'
import json
rows = json.load(open("results/retries-1.json", encoding="utf-8"))["rows"]
wrong = [r for r in rows if r["status"] == "ok" and not r["salary_ok"]]
print(len(wrong), "replies passed every check with the wrong pay")
for r in wrong:
fields = ("currency", "salary_min", "salary_max", "period")
diff = {k: (r["got"][k], r["expected"][k]) for k in fields if r["got"][k] != r["expected"][k]}
print(f"\nadvert {r['id']}: {r['text']}")
for k, (got, want) in diff.items():
print(f" {k}: got {got!r}, want {want!r}")
PYCheck it worked
You see a count, then for each wrong reply the advert text and the fields that differ, such as period: got 'month', want 'year'. If the count is 0, the small model got every passing reply right on this set; try a few adverts of your own with tricky wording before you believe it holds in general.
For each wrong reply, decide which of these helps:
- A rule. Some errors can be caught in code. A monthly salary above, say, 5,000,000 naira or a daily rate above an annual one is worth flagging. Add it to
CheckedJobAd, rerun both scores and compare. - A clearer instruction. If the model keeps reading "paid monthly" as the period, say in the prompt that the period is the one the amount is quoted in.
- A person. Nothing in this pipeline proves a passing reply is right. Before you use extracted data for anything that matters, such as filtering candidates by salary, have someone check a sample against the adverts, and keep growing the list of adverts with expected answers so every change to the prompt, rules or model is measured the same way.
Step 9 · Clean up
Delete the project folder and remove the model. If you plan to follow the related tutorials, keep the model: they use the same one, so skip the ollama rm line.
cd ~
rm -rf ~/jobads-demo
ollama rm qwen3:0.6b
ollama list
test ! -e ~/jobads-demo && ! ollama list | grep -q 'qwen3:0.6b' && echo 'clean'Check it worked
The last command prints clean: the folder is gone and ollama list no longer shows qwen3:0.6b. If you kept the model, run test ! -e ~/jobads-demo && echo 'clean' instead.
Next steps
- Compare constrained decoding on a local model with a hosted API's structured outputs in get structured JSON output from an LLM.
- Try whether a few worked examples in the prompt reduce the wrong-but-valid replies, using the method in improve LLM answers with few-shot examples.
- Compare Pydantic with Python's built-in way to describe records in model data with Python dataclasses.
Related tutorials
- Use MCP server tools from your own Claude appYou will connect a Python app to the stdio clinic-hours MCP server, hand an allowlisted set of its tools to Claude, pass every tool call through to the server with a tested bridge, and know when the API's MCP connector can do the connecting for you.
- Trace LLM calls with OpenTelemetryYou will have a Python app whose Claude calls, retries and tool runs appear as one OpenTelemetry trace with GenAI attributes, token and latency metrics, prompts kept out by default, and an export path from the console to an OpenTelemetry Collector.
- Serve an MCP server over Streamable HTTP with authenticationYou will run an MCP server over Streamable HTTP on localhost that checks the Origin header, accepts only bearer tokens your token verifier knows, limits each tool to the right scope, and refuses calls without a token.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials