Lab: Enforced Schemas Across Two Providers
Request schema-constrained output in the shapes of OpenAI's Responses API and Claude's Messages API, from one Pydantic contract, against a local fake provider that also returns refusals, truncated replies and 400 errors. Count every outcome and score field accuracy on 30 documents.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: The contract
- Step 2: Thirty documents with known answers
- Step 3: A fake provider that fails on purpose
- Step 4: One client, two request shapes, six outcomes
- Step 5: Read the raw replies
- Step 6: Negative test, a schema strict modes reject
- Step 7: Run all thirty documents through both providers
- Step 8: Pointing the code at the real APIs
- Check your understanding
- Apply it
- Review prompt
Lessons of Structured Outputs
- Why Free Text Breaks Pipelines Concept · 10 min
- Designing a Schema for an Extraction Task Worked example · 20 min
- Constrained Decoding and Its Limits Concept · 15 min
- Lab: Enforced Schemas Across Two Providers Lab · 25 min
- Validation, Repair and Retry Budgets Worked example · 20 min
- Check: Schema and Failure Scenarios Knowledge check · 6 questions
What you will learn
- Request schema-constrained output from a provider and explain what constrained decoding does and does not guarantee.
- Validate model output in code and handle refusals, truncation and validation failures with a bounded repair or retry.
Prerequisites: LLM API Integration
01. Goal and setup
You will send the same extraction request to two providers, OpenAI's Responses API and Claude's Messages API, each with schema-constrained output switched on, and handle everything that can come back: a valid extraction, an honest "this is not an invoice", a refusal, a reply cut off at the token limit, a reply that fails your validators, and a 400 for a schema the provider will not accept. At the end you will have outcome counts and per-field accuracy for 30 documents, which is the report the skill project asks for.
Real API calls cost money and give different results on every run, so the lab runs against fake_provider.py, a small server built on Python's http.server. It is not a language model: it reads the documents with regular expressions and answers in each provider's response shape. It makes two deliberate reading mistakes and has a test hook for refusals, so every branch of your code runs. Step 8 shows how to point the same code at the real APIs.
You need: Python 3.12 or later and Pydantic (pip install pydantic==2.14.1, the version this lab was run with). No provider SDK and no API key. The client uses urllib from the standard library so that you see the raw request and response bodies.
so-lab/
├── invoice_schema.py step 1: the contract from lesson 2
├── make_invoices.py step 2: writes docs/ and labels.jsonl
├── fake_provider.py step 3: local stand-in for both APIs
├── extract.py step 4: one client, two request shapes, six outcomes
├── peek.py step 5: the raw replies, side by side
├── naive_schema.py step 6: negative test, a schema strict modes reject
├── run_lab.py step 7: 30 documents, outcome counts, field accuracy
├── docs/ 30 sample documents (generated)
└── labels.jsonl the expected answers (generated)mkdir so-lab && cd so-lab
python3 -m venv .venv && source .venv/bin/activate
python -m pip install pydantic==2.14.102. Step 1: The contract
Save the schema from lesson 2 as invoice_schema.py. It is repeated here so the lab is complete on its own. The root object carries a status (the "cannot answer" path), money is exact, every object forbids extra keys and every nullable field is still required, so the generated schema is accepted by both providers' strict modes.
"""Extraction contract shared by every provider (Pydantic v2)."""
from datetime import date
from decimal import Decimal
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, model_validator
# Money travels as a string such as "1250.00" and becomes an exact Decimal.
Money = Annotated[
Decimal,
WithJsonSchema({"type": "string", "pattern": "^-?[0-9]+[.][0-9]{2}$"}),
]
# Quantities travel as JSON numbers; Pydantic reads the digits exactly.
Quantity = Annotated[Decimal, WithJsonSchema({"type": "number"})]
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid") # -> "additionalProperties": false
class LineItem(Strict):
description: str
quantity: Quantity = Field(description="Units billed, as printed")
unit_price: Money
line_total: Money = Field(description="Negative for discounts and credits")
class Invoice(Strict):
vendor_name: str = Field(description="Billing company as printed")
invoice_number: str
invoice_date: date
due_date: date | None = Field(description="null if the document has none")
currency: Literal["USD", "EUR", "GBP", "JPY", "OTHER"] | None = Field(
description="ISO 4217 code; OTHER if another currency; null if not stated"
)
line_items: list[LineItem]
tax_amount: Money | None = Field(description="null if no tax line")
total_amount: Money = Field(description="Amount due, as printed")
@model_validator(mode="after")
def totals_add_up(self) -> "Invoice":
expected = sum(i.line_total for i in self.line_items) + (self.tax_amount or 0)
if expected != self.total_amount:
raise ValueError(
f"line items + tax = {expected}, total_amount = {self.total_amount}"
)
return self
class Extraction(Strict):
"""The root object: an invoice, or an explicit reason why there is none."""
status: Literal["ok", "not_an_invoice", "unreadable"]
reason: str | None = Field(description="Why status is not ok; else null")
invoice: Invoice | None = Field(description="null unless status is ok")
@model_validator(mode="after")
def invoice_matches_status(self) -> "Extraction":
if (self.status == "ok") != (self.invoice is not None):
raise ValueError("invoice must be set exactly when status is ok")
return self03. Step 2: Thirty documents with known answers
Accuracy needs labelled data. make_invoices.py writes 30 small text documents and the expected answer for each. A fixed random seed makes them identical on every machine. Most are ordinary invoices; a few are there to exercise one branch each: a delivery note (9), an unreadable scan (17), a Canadian-dollar invoice (12), two 40-line invoices (5 and 23), discount lines (3, 14, 27), a printed total that does not match its own lines (20) and a refusal test hook (26).
"""Write 30 sample documents to docs/ and the expected answers to labels.jsonl."""
import json
import random
from decimal import Decimal
from pathlib import Path
VENDORS = ["Northwind Supplies Ltd", "Blue Harbour Print", "Kestrel IT Services"]
ITEMS = [("A4 paper, box of 5", "12.50"), ("Toner cartridge", "64.00"),
("Desk lamp", "23.99"), ("On-site support, hour", "85.00")]
rng = random.Random(7)
out = Path("docs")
out.mkdir(exist_ok=True)
def invoice(n: int, lines: int, currency: str = "GBP", discount: bool = False,
due: bool = True, wrong_total: bool = False, note: str = "") -> dict:
items = []
for _ in range(lines):
desc, price = rng.choice(ITEMS)
qty = rng.randint(1, 5)
items.append((desc, qty, Decimal(price), qty * Decimal(price)))
if discount:
items.append(("Discount, loyal customer", 1, Decimal("-10.00"),
Decimal("-10.00")))
subtotal = sum(i[3] for i in items)
tax = (subtotal * Decimal("0.20")).quantize(Decimal("0.01"))
total = subtotal + tax + (Decimal("1.00") if wrong_total else 0)
vendor = VENDORS[n % 3]
text = [f"INVOICE INV-{1000 + n}", f"From: {vendor}",
f"Date: 2026-09-{n % 28 + 1:02d}"]
if due:
text.append(f"Due: 2026-10-{n % 28 + 1:02d}")
text.append(f"Currency: {currency}")
text += [f"- {d} | {q} x {p} = {t}" for d, q, p, t in items]
text += [f"Tax: {tax}", f"Total: {total}"]
if note:
text.append(note)
(out / f"inv-{n:02d}.txt").write_text("\n".join(text) + "\n")
cur = currency if currency in {"USD", "EUR", "GBP", "JPY"} else "OTHER"
return {"doc": f"inv-{n:02d}.txt", "status": "ok", "vendor_name": vendor,
"invoice_date": f"2026-09-{n % 28 + 1:02d}", "currency": cur,
"total_amount": str(total), "items": len(items)}
labels = []
for n in range(1, 31):
if n == 9:
(out / "inv-09.txt").write_text("DELIVERY NOTE DN-552\n3 boxes, no prices\n")
labels.append({"doc": "inv-09.txt", "status": "not_an_invoice"})
elif n == 17:
(out / "inv-17.txt").write_text("INV0ICE ### sc4n err0r ### T0ta1 ??\n")
labels.append({"doc": "inv-17.txt", "status": "unreadable"})
else:
labels.append(invoice(
n, lines=40 if n in (5, 23) else rng.randint(1, 5),
currency="CAD" if n == 12 else rng.choice(["GBP", "EUR", "USD"]),
discount=n in (3, 14, 27), due=n % 4 != 0, wrong_total=n == 20,
note="#refuse (test hook for the fake provider)" if n == 26 else ""))
Path("labels.jsonl").write_text("".join(json.dumps(r) + "\n" for r in labels))
print(f"wrote {len(labels)} documents to docs/ and labels.jsonl")python make_invoices.py && cat docs/inv-03.txtwrote 30 documents to docs/ and labels.jsonl
INVOICE INV-1003
From: Northwind Supplies Ltd
Date: 2026-09-04
Due: 2026-10-04
Currency: GBP
- Toner cartridge | 5 x 64.00 = 320.00
- A4 paper, box of 5 | 5 x 12.50 = 62.50
- On-site support, hour | 1 x 85.00 = 85.00
- Toner cartridge | 1 x 64.00 = 64.00
- Toner cartridge | 3 x 64.00 = 192.00
- Discount, loyal customer | 1 x -10.00 = -10.00
Tax: 142.70
Total: 856.2004. Step 3: A fake provider that fails on purpose
The fake serves POST /openai/v1/responses and POST /anthropic/v1/messages. Read openai_body and anthropic_body closely: they are the part of the fake that matters, because they reproduce the fields your code must check.
- A normal reply: OpenAI
status: "completed"with anoutput_textpart; Claudestop_reason: "end_turn"with atextblock. - A refusal: OpenAI puts a
refusalpart where the text would be; Claude setsstop_reason: "refusal". - Truncation: when the reply would exceed the token limit (estimated at four characters per token), the text is cut and OpenAI reports
status: "incomplete"with reasonmax_output_tokens, Claudestop_reason: "max_tokens". - A 400 error when a schema breaks the strict rules this fake checks. The real providers check many more rules, and their error text differs.
"""A local stand-in for two hosted model APIs. It is NOT a language model.
It reads invoices with regular expressions and answers in the response shape of
OpenAI's Responses API and Anthropic's Messages API, including refusals,
truncation at the token limit, 400 errors for non-strict schemas, and two
deliberate reading mistakes, so every branch of your client code runs offline.
"""
import json
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
LINE = re.compile(r"^- (.+) \| (\S+) x (\S+) = (\S+)$", re.M)
def field(text: str, name: str) -> str | None:
match = re.search(rf"^{name}: (.+)$", text, re.M)
return match.group(1).strip() if match else None
def read_document(text: str, repair_turn: bool) -> dict:
if text.startswith("DELIVERY NOTE"):
return {"status": "not_an_invoice", "invoice": None,
"reason": "The document is a delivery note with no amounts."}
if field(text, "Total") is None:
return {"status": "unreadable", "invoice": None,
"reason": "No total or line items could be read."}
number = int(re.search(r"INV-(\d+)", text).group(1))
items = [{"description": d, "quantity": int(q), "unit_price": p,
"line_total": t} for d, q, p, t in LINE.findall(text)]
if not repair_turn: # mistake 1: skips discount rows until told about them
items = [i for i in items if not i["description"].startswith("Discount")]
date, due = field(text, "Date"), field(text, "Due")
if due and number % 10 == 1: # mistake 2: reads the due date as the date
date = due
currency = field(text, "Currency")
return {"status": "ok", "reason": None, "invoice": {
"vendor_name": field(text, "From"), "invoice_number": f"INV-{number}",
"invoice_date": date, "due_date": due,
"currency": currency if currency in {"USD", "EUR", "GBP", "JPY"}
else "OTHER",
"line_items": items, "tax_amount": field(text, "Tax"),
"total_amount": field(text, "Total")}}
def schema_problems(node, openai: bool, path: str = "schema") -> list[str]:
"""The subset rules this fake enforces; real providers check many more."""
found = []
if isinstance(node, dict):
if node.get("type") == "object":
if node.get("additionalProperties") is not False:
found.append(f"{path}: additionalProperties must be false")
missing = set(node.get("properties", {})) - set(node.get("required", []))
if openai and missing:
found.append(f"{path}: every property must be required, "
f"missing {sorted(missing)}")
for key in ("minimum", "maximum", "minLength", "maxLength"):
if key in node and not openai:
found.append(f"{path}: '{key}' is not supported")
for key, value in node.items():
found += schema_problems(value, openai, f"{path}.{key}")
elif isinstance(node, list):
for i, value in enumerate(node):
found += schema_problems(value, openai, f"{path}[{i}]")
return found
class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
openai = self.path == "/openai/v1/responses"
if openai:
turns, fmt = body["input"], body["text"]["format"]
limit = body.get("max_output_tokens", 4096)
elif self.path == "/anthropic/v1/messages":
turns, fmt = body["messages"], body["output_config"]["format"]
limit = body["max_tokens"]
else:
return self.reply(404, {"error": "unknown path"})
problems = schema_problems(fmt["schema"], openai)
if problems:
return self.reply(400, self.error(openai, "; ".join(problems)))
user_turns = [t["content"] for t in turns if t["role"] == "user"]
answer = read_document(user_turns[0], repair_turn=len(user_turns) > 1)
text = json.dumps(answer)
used = len(text) // 4 + 1 # roughly four characters per token
if "#refuse" in user_turns[0]:
text, used, kind = "I can't help with that document.", 9, "refusal"
elif used > limit:
text, used, kind = text[: limit * 4], limit, "truncated"
else:
kind = "complete"
build = self.openai_body if openai else self.anthropic_body
self.reply(200, build(body["model"], text, used, kind))
@staticmethod
def openai_body(model: str, text: str, used: int, kind: str) -> dict:
part = ({"type": "refusal", "refusal": text} if kind == "refusal"
else {"type": "output_text", "text": text, "annotations": []})
return {"object": "response", "model": model,
"status": "incomplete" if kind == "truncated" else "completed",
"incomplete_details": {"reason": "max_output_tokens"}
if kind == "truncated" else None,
"output": [{"type": "message", "role": "assistant",
"content": [part]}],
"usage": {"input_tokens": 300, "output_tokens": used}}
@staticmethod
def anthropic_body(model: str, text: str, used: int, kind: str) -> dict:
stop = {"refusal": "refusal", "truncated": "max_tokens"}.get(kind, "end_turn")
return {"type": "message", "role": "assistant", "model": model,
"content": [{"type": "text", "text": text}], "stop_reason": stop,
"usage": {"input_tokens": 300, "output_tokens": used}}
@staticmethod
def error(openai: bool, message: str) -> dict:
if openai:
return {"error": {"type": "invalid_request_error",
"code": "invalid_json_schema", "message": message}}
return {"type": "error",
"error": {"type": "invalid_request_error", "message": message}}
def reply(self, status: int, payload: dict) -> None:
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args) -> None: # keep the terminal quiet
pass
if __name__ == "__main__":
print("fake provider on http://127.0.0.1:8765 (Ctrl+C to stop)", flush=True)
ThreadingHTTPServer(("127.0.0.1", 8765), Handler).serve_forever()python fake_provider.pyfake provider on http://127.0.0.1:8765 (Ctrl+C to stop)05. Step 4: One client, two request shapes, six outcomes
extract.py sends one request and returns an Outcome. The two provider functions build the request each API expects: OpenAI's schema goes in text.format with strict: true; Claude's goes in output_config.format. Both send the key as Authorization: Bearer, and the Claude request names the current API version, anthropic-version: 2026-10-21 (the older x-api-key header and version 2023-06-01 still work, but are not what new code should send). No temperature is sent, and model names come from environment variables with current examples as defaults.
The order of checks in extract() is the important part. First, how did the response end? A refusal or a truncated reply is classified before any parsing, because neither contains a complete answer. Only a complete reply is validated, and validation failures keep the raw text and a short error summary, which lesson 5 feeds back for repair. A valid reply whose status is not ok is a cannot_answer outcome: a correct result, not an error.
"""Ask either provider for an Extraction and sort the reply into one outcome."""
import json
import os
import urllib.request
from dataclasses import dataclass
from pydantic import ValidationError
from invoice_schema import Extraction
FAKE = "http://127.0.0.1:8765"
# Same conventions as the SDKs: OpenAI's base URL ends in /v1, Anthropic's is a host.
OPENAI_URL = os.environ.get("OPENAI_BASE_URL", f"{FAKE}/openai/v1") + "/responses"
ANTHROPIC_URL = os.environ.get("ANTHROPIC_BASE_URL", f"{FAKE}/anthropic")
ANTHROPIC_URL += "/v1/messages"
OPENAI_MODEL = os.environ.get("OPENAI_MODEL", "gpt-6.2-astra")
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
SCHEMA = Extraction.model_json_schema()
INSTRUCTIONS = (
"Extract the invoice in the user's document. Copy amounts exactly as printed. "
"If it is not an invoice, or cannot be read, set status to say so, explain "
"in reason and set invoice to null. Never guess a value that is not printed."
)
@dataclass
class Outcome:
kind: str # ok | cannot_answer | refused | truncated | invalid | stopped
data: Extraction | None = None
detail: str = ""
raw: str = ""
def post(url: str, headers: dict, body: dict) -> dict:
headers = {"content-type": "application/json", **headers}
request = urllib.request.Request(url, json.dumps(body).encode(), headers)
with urllib.request.urlopen(request, timeout=120) as response:
return json.load(response)
def ask_openai(turns: list, max_tokens: int, schema: dict) -> tuple[str, str]:
key = os.environ.get("OPENAI_API_KEY", "not-needed-for-the-fake")
reply = post(OPENAI_URL, {"authorization": f"Bearer {key}"}, {
"model": OPENAI_MODEL, "instructions": INSTRUCTIONS, "input": turns,
"max_output_tokens": max_tokens,
"text": {"format": {"type": "json_schema", "name": "extraction",
"schema": schema, "strict": True}},
})
parts = [part for item in reply["output"] if item["type"] == "message"
for part in item["content"]]
text = "".join(p.get("text", "") for p in parts)
if reply["status"] == "incomplete":
reason = reply["incomplete_details"]["reason"]
return ("truncated" if reason == "max_output_tokens" else reason), text
refusals = [p["refusal"] for p in parts if p["type"] == "refusal"]
return ("refusal", refusals[0]) if refusals else ("complete", text)
def ask_anthropic(turns: list, max_tokens: int, schema: dict) -> tuple[str, str]:
key = os.environ.get("ANTHROPIC_API_KEY", "not-needed-for-the-fake")
headers = {"authorization": f"Bearer {key}", "anthropic-version": "2026-10-21"}
reply = post(ANTHROPIC_URL, headers, {
"model": ANTHROPIC_MODEL, "max_tokens": max_tokens, "system": INSTRUCTIONS,
"messages": turns,
"output_config": {"format": {"type": "json_schema", "schema": schema}},
})
text = "".join(b["text"] for b in reply["content"] if b["type"] == "text")
stop = reply["stop_reason"]
kinds = {"end_turn": "complete", "refusal": "refusal", "max_tokens": "truncated"}
return kinds.get(stop, stop), text
ASK = {"openai": ask_openai, "anthropic": ask_anthropic}
def summarise(err: ValidationError) -> str:
"""Field path and message only: no stack trace, no input echo."""
return "; ".join(
f"{'.'.join(map(str, e['loc'])) or 'root'}: "
+ e["msg"].removeprefix("Value error, ")
for e in err.errors()
)
def extract(provider: str, turns: list, max_tokens: int = 800,
schema: dict = SCHEMA) -> Outcome:
kind, text = ASK[provider](turns, max_tokens, schema)
if kind == "refusal":
return Outcome("refused", detail=text)
if kind == "truncated":
return Outcome("truncated", detail=f"stopped after {len(text)} chars")
if kind != "complete":
return Outcome("stopped", detail=kind)
try:
data = Extraction.model_validate_json(text)
except ValidationError as err:
return Outcome("invalid", detail=summarise(err), raw=text)
if data.status != "ok":
return Outcome("cannot_answer", data, f"{data.status}: {data.reason}")
return Outcome("ok", data, raw=text)06. Step 5: Read the raw replies
Before trusting the client, look at what each API returns for a normal document, the refusal hook and a 40-line invoice with an 800-token limit. Run these in a second terminal while the fake is running.
"""Print the raw reply of each provider for one document."""
import json
import sys
from pathlib import Path
from extract import ANTHROPIC_URL, INSTRUCTIONS, OPENAI_URL, SCHEMA, post
doc, limit = sys.argv[1], int(sys.argv[2])
turns = [{"role": "user", "content": Path("docs", doc).read_text()}]
fmt = {"type": "json_schema", "schema": SCHEMA}
replies = {
"openai": post(OPENAI_URL, {}, {
"model": "gpt-6.2-astra", "input": turns, "max_output_tokens": limit,
"text": {"format": {**fmt, "name": "extraction", "strict": True}}}),
"anthropic": post(ANTHROPIC_URL, {}, {
"model": "claude-sonnet-5-5", "max_tokens": limit, "messages": turns,
"system": INSTRUCTIONS, "output_config": {"format": fmt}}),
}
openai, claude = replies["openai"], replies["anthropic"]
# [0] is safe only with this fake, which returns one item and one block. Real
# replies can start with a reasoning item or a thinking block: filter by type.
part = openai["output"][0]["content"][0]
print("openai: status =", openai["status"],
"| incomplete_details =", json.dumps(openai["incomplete_details"]))
text = part.get("text") or part.get("refusal")
print(" content[0].type =", part["type"], "|", repr(text)[-30:])
block = claude["content"][0]
print("anthropic: stop_reason =", claude["stop_reason"])
print(" content[0].type =", block["type"], "|", repr(block["text"])[-30:])python peek.py inv-01.txt 800
python peek.py inv-26.txt 800
python peek.py inv-05.txt 800$ python peek.py inv-01.txt 800
openai: status = completed | incomplete_details = null
content[0].type = output_text | ", "total_amount": "222.00"}}'
anthropic: stop_reason = end_turn
content[0].type = text | ", "total_amount": "222.00"}}'
$ python peek.py inv-26.txt 800
openai: status = completed | incomplete_details = null
content[0].type = refusal | an't help with that document."
anthropic: stop_reason = refusal
content[0].type = text | an't help with that document."
$ python peek.py inv-05.txt 800
openai: status = incomplete | incomplete_details = {"reason": "max_output_tokens"}
content[0].type = output_text | ine_total": "25.00"}, {"descr'
anthropic: stop_reason = max_tokens
content[0].type = text | ine_total": "25.00"}, {"descr'In the refusal case OpenAI still says completed: the signal is the part type, not the status. In the truncation case both providers return text that stops mid-object. Passing that text to a parser, or to a repair prompt, wastes a call; the useful fixes are a larger limit or a smaller document.
07. Step 6: Negative test, a schema strict modes reject
A model written without the lesson-2 rules generates a schema that strict modes refuse. This test proves your setup actually sends the schema and that a rejected schema surfaces as an error, rather than silently falling back to unconstrained output.
"""Negative test: a schema that breaks the strict rules must be rejected."""
import json
import urllib.error
from pydantic import BaseModel
from extract import extract
class Loose(BaseModel): # no extra="forbid", and an optional field with a default
vendor_name: str
due_date: str | None = None
for provider in ("openai", "anthropic"):
try:
extract(provider, [{"role": "user", "content": "INVOICE"}],
schema=Loose.model_json_schema())
print(provider, "accepted the schema: the strict check did not run")
except urllib.error.HTTPError as err:
print(provider, "HTTP", err.code)
for problem in json.load(err)["error"]["message"].split("; "):
print(" ", problem)python naive_schema.pyopenai HTTP 400
schema: additionalProperties must be false
schema: every property must be required, missing ['due_date']
anthropic HTTP 400
schema: additionalProperties must be false08. Step 7: Run all thirty documents through both providers
run_lab.py sends each document to each provider with an 800-token limit. A truncated reply gets exactly one retry with four times the room; anything else is counted and reported. For valid invoices it compares five fields with the labels.
"""Run all 30 documents through each provider; count outcomes; score fields."""
import json
import sys
from collections import Counter
from pathlib import Path
from extract import extract
FIELDS = ["vendor_name", "invoice_date", "currency", "total_amount", "items"]
def run(provider: str, labels: list[dict]) -> None:
outcomes, right, retries = Counter(), Counter(), 0
for label in labels:
turns = [{"role": "user", "content": Path("docs", label["doc"]).read_text()}]
outcome = extract(provider, turns, max_tokens=800)
if outcome.kind == "truncated": # one retry with more room, then stop
print(f" {label['doc']} truncated at 800 tokens, retrying with 3200")
retries += 1
outcome = extract(provider, turns, max_tokens=3200)
outcomes[outcome.kind] += 1
if outcome.kind not in ("ok", "cannot_answer"):
print(f" {label['doc']} {outcome.kind}: {outcome.detail}")
if outcome.kind == "cannot_answer":
right["status"] += outcome.data.status == label["status"]
if outcome.kind == "ok":
inv = outcome.data.invoice
got = {"vendor_name": inv.vendor_name, "currency": inv.currency,
"invoice_date": inv.invoice_date.isoformat(),
"total_amount": str(inv.total_amount),
"items": len(inv.line_items)}
right.update(f for f in FIELDS if got[f] == label[f])
print(" outcomes:", " ".join(f"{k}={v}" for k, v in sorted(outcomes.items())),
f"| truncation retries={retries}")
print(f" cannot_answer with the right status: {right['status']}"
f"/{outcomes['cannot_answer']}")
print(f" fields matching the labels, out of {outcomes['ok']} ok invoices:")
print(" ", " ".join(f"{f}={right[f]}" for f in FIELDS))
labels = [json.loads(line) for line in Path("labels.jsonl").read_text().splitlines()]
for name in sys.argv[1:] or ["openai", "anthropic"]:
print(f"{name}:")
run(name, labels)python run_lab.pyopenai:
inv-03.txt invalid: invoice: line items + tax = 866.20, total_amount = 856.20
inv-05.txt truncated at 800 tokens, retrying with 3200
inv-14.txt invalid: invoice: line items + tax = 288.36, total_amount = 278.36
inv-20.txt invalid: invoice: line items + tax = 1105.18, total_amount = 1106.18
inv-23.txt truncated at 800 tokens, retrying with 3200
inv-26.txt refused: I can't help with that document.
inv-27.txt invalid: invoice: line items + tax = 365.20, total_amount = 355.20
outcomes: cannot_answer=2 invalid=4 ok=23 refused=1 | truncation retries=2
cannot_answer with the right status: 2/2
fields matching the labels, out of 23 ok invoices:
vendor_name=23 invoice_date=20 currency=23 total_amount=23 items=23
anthropic:
inv-03.txt invalid: invoice: line items + tax = 866.20, total_amount = 856.20
inv-05.txt truncated at 800 tokens, retrying with 3200
inv-14.txt invalid: invoice: line items + tax = 288.36, total_amount = 278.36
inv-20.txt invalid: invoice: line items + tax = 1105.18, total_amount = 1106.18
inv-23.txt truncated at 800 tokens, retrying with 3200
inv-26.txt refused: I can't help with that document.
inv-27.txt invalid: invoice: line items + tax = 365.20, total_amount = 355.20
outcomes: cannot_answer=2 invalid=4 ok=23 refused=1 | truncation retries=2
cannot_answer with the right status: 2/2
fields matching the labels, out of 23 ok invoices:
vendor_name=23 invoice_date=20 currency=23 total_amount=23 items=23Both providers give the same counts because the fake behaves the same behind both shapes; with real models the two columns will differ, and will vary between runs. What the report shows is the point:
- Every reply that finished matched the schema, and still four failed validation. Three skipped a discount line (the fake's first mistake); one, inv-20, faithfully copied a total that is wrong on the document itself. The schema cannot see either problem; the totals validator sees both.
- Three invoice dates are wrong although every value is a valid date (the fake's second mistake: it read the due date). No validator caught it. Only comparison with labels shows this kind of error, which is why the project asks for field-level accuracy, not just a pass rate.
- The truncation retry worked for both long invoices, and the refusal and the two cannot-answer documents were counted, not parsed.
09. Step 8: Pointing the code at the real APIs
This step was not run for this lesson: it needs API keys, costs money, and its numbers would differ on every run. The client reads its endpoints and models from the environment, so switching is configuration only:
OPENAI_BASE_URL=https://api.openai.com/v1,OPENAI_API_KEY, andOPENAI_MODEL(the default,gpt-6.2-astra, is the model OpenAI's structured-outputs guide recommends for new projects, checked on 26 November 2026);ANTHROPIC_BASE_URL=https://api.anthropic.com,ANTHROPIC_API_KEY, andANTHROPIC_MODEL(defaultclaude-sonnet-5-5).
The two base URLs follow the SDKs' own conventions, because the SDKs read the same variables: OpenAI's includes /v1, Anthropic's is the host only and the client adds /v1/messages. Setting ANTHROPIC_BASE_URL with /v1 would send the SDK snippet below to /v1/v1/messages and get a 404. Unset all four variables to go back to the fake.
Raise the token limits first. Claude Sonnet 5.5 thinks by default, and on both providers reasoning tokens count towards the output limit, so 800 tokens can truncate a reply that the fake returned whole. Check each provider's models page before you pick a model; snapshots are retired on a published schedule. In production you would normally use the SDK helpers instead of raw HTTP; the illustrative snippet below shows the equivalent calls. Know one difference from extract.py: both helpers validate the reply inside parse(). A cut-off reply, a reply that fails your validators and, on Claude, a refusal all raise a Pydantic ValidationError from parse() itself, before you can read status or stop_reason. So catch that exception first. If you need to know why a reply is unusable, call responses.create or messages.create with the same schema and validate the text yourself, as extract.py does.
import os
from pathlib import Path
from anthropic import Anthropic
from openai import OpenAI
from pydantic import ValidationError
from extract import INSTRUCTIONS
from invoice_schema import Extraction
turns = [{"role": "user", "content": Path("docs/inv-01.txt").read_text()}]
try: # parse() validates while it builds the result
response = OpenAI().responses.parse(
model=os.environ["OPENAI_MODEL"], instructions=INSTRUCTIONS,
input=turns, text_format=Extraction, max_output_tokens=4000,
)
except ValidationError as err: # a cut-off reply, or a validator failed
print("not usable:", err.error_count(), "validation error(s)")
else:
if response.status == "incomplete":
print("incomplete:", response.incomplete_details.reason)
else:
print(response.output_parsed) # None when the model refused
try:
message = Anthropic().messages.parse(
model=os.environ["ANTHROPIC_MODEL"], max_tokens=4000,
system=INSTRUCTIONS, messages=turns, output_format=Extraction,
)
except ValidationError as err: # on Claude also a refusal or a cut-off reply
print("not usable:", err.error_count(), "validation error(s)")
else:
print(message.stop_reason, message.parsed_output)10. Check your understanding
11. Apply it
Turn this lab into the skill project:
- replace the generated documents with 30 real or realistic invoices and label them by hand, including a few that are not invoices;
- run them through one real provider (step 8), keeping the outcome counts and per-field accuracy exactly as
run_lab.pyreports them; - add the repair step from lesson 5 and report how many validation failures it fixed, how many refusals and truncations occurred, and how many documents went to review.
12. Review prompt
Without looking: give the request field and the end-of-response signal for schema-constrained output on OpenAI's Responses API and on Claude. Name the six outcomes extract() returns and the order in which it checks them. Explain why the step-7 report needs labels in addition to schema validation.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.