Why prompt hard first
In Level 1 you drew the map: prompt, retrieve, tune or go bigger. This level covers the cheapest of those options, and you have to work it properly before you can rule it out. A fine-tuning project that starts without a measured prompted baseline can't show it achieved anything. If you can't say "the best prompt we could write gets 91% of fields right and fails to parse 0.4% of the time," you have nothing for a tuned model to beat.
We'll use one structured task for the rest of the course: support-ticket triage. Free text goes in, a small JSON object comes out:
{"category": "outage", "priority": "p1", "summary": "Production API returning 503 errors since 09:10 UTC."}
There are three tools for making that output reliable:
- System prompt: the rules, written as you would write them for a new colleague.
- Few-shot examples: two to five worked input/output pairs. Models copy examples more faithfully than they follow descriptions.
- Schema-constrained output: the provider restricts generation so that only tokens matching your JSON Schema can be produced. This is the strongest of the three.
Think of it like TypeScript. The prompt is the comments, the examples are the tests, and the schema is the compiler.
One task, one schema
# task.py: shared by every provider
SYSTEM = """You triage support tickets for Acme Cloud. Rules:
- category: billing | outage | bug | how_to | other
- priority: p1 if production is down or data is lost; p2 if a paying customer is blocked; otherwise p3
- summary: one sentence, under 20 words, no customer names
Return only JSON matching the schema."""
SCHEMA = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "outage", "bug", "how_to", "other"]},
"priority": {"type": "string", "enum": ["p1", "p2", "p3"]},
"summary": {"type": "string"},
},
"required": ["category", "priority", "summary"], # OpenAI strict mode wants every field required
"additionalProperties": False, # Claude and OpenAI strict mode both require this
}
# Few-shot as fake earlier turns: user input, then the exact JSON you want back
FEW_SHOT = [
{"role": "user", "content": "My card was charged twice for October."},
{"role": "assistant", "content": '{"category":"billing","priority":"p2","summary":"Customer charged twice for October invoice."}'},
{"role": "user", "content": "ALL our API calls return 503 since 09:10 UTC, prod is down!!"},
{"role": "assistant", "content": '{"category":"outage","priority":"p1","summary":"Production API returning 503 errors since 09:10 UTC."}'},
]
Gotcha: providers support different parts of JSON Schema. Claude rejects
minLength,maximumandoneOfwith a 400 error. Gemini quietly ignores keywords it doesn't support. Keep the schema simple (types,enum,required) and enforce rules like "under 20 words" in your own validation code.
The thin client layer in Python
Each provider gets one function with the same signature: messages in, raw text out. Keep the layer this thin. You want to see exactly what each API receives.
# clients.py
from anthropic import Anthropic
from openai import OpenAI
from google import genai
from task import SYSTEM, SCHEMA
def claude(msgs, constrained=True):
extra = {"output_config": {"format": {"type": "json_schema", "schema": SCHEMA}}} if constrained else {}
r = Anthropic().messages.create(model="claude-haiku-5-5", max_tokens=300,
system=SYSTEM, messages=msgs, **extra)
return next(b.text for b in r.content if b.type == "text")
def openai(msgs, constrained=True):
fmt = {"format": {"type": "json_schema", "name": "ticket", "schema": SCHEMA, "strict": True}}
r = OpenAI().responses.create(model="gpt-6.2-astra",
input=[{"role": "system", "content": SYSTEM}, *msgs],
**({"text": fmt} if constrained else {}))
return r.output_text
def gemini(msgs, constrained=True):
contents = [{"role": "model" if m["role"] == "assistant" else "user", # Gemini calls the assistant "model"
"parts": [{"text": m["content"]}]} for m in msgs]
cfg = {"system_instruction": SYSTEM}
if constrained:
cfg |= {"response_mime_type": "application/json", "response_json_schema": SCHEMA}
return genai.Client().models.generate_content(model="gemini-4-hydrogen",
contents=contents, config=cfg).text
def local(msgs, constrained=True):
# Ollama serves an OpenAI-compatible API on port 11434. Run `ollama pull gemma4:e4b` first.
c = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # the key is ignored
extra = {"response_format": {"type": "json_schema",
"json_schema": {"name": "ticket", "schema": SCHEMA}}} if constrained else {}
r = c.chat.completions.create(model="gemma4:e4b", temperature=0,
messages=[{"role": "system", "content": SYSTEM}, *msgs], **extra)
return r.choices[0].message.content
PROVIDERS = {"claude": claude, "openai": openai, "gemini": gemini, "local": local}
Model names change every few months, so check each provider's model list before you run this. Structured outputs work against a local Ollama server. Ollama's cloud does not support them yet.
The same layer in TypeScript
// clients.ts: same contract: (msgs) => Promise<string>
import Anthropic from "@anthropic-ai/sdk";
import OpenAI from "openai";
import { GoogleGenAI } from "@google/genai";
import { SYSTEM, SCHEMA } from "./task";
type Msg = { role: "user" | "assistant"; content: string };
export const providers: Record<string, (m: Msg[]) => Promise<string>> = {
claude: async (m) => {
const r = await new Anthropic().messages.create({
model: "claude-haiku-5-5", max_tokens: 300, system: SYSTEM, messages: m,
output_config: { format: { type: "json_schema", schema: SCHEMA } },
});
return r.content.find((b) => b.type === "text")!.text;
},
openai: async (m) =>
(await new OpenAI().responses.create({
model: "gpt-6.2-astra", input: [{ role: "system", content: SYSTEM }, ...m],
text: { format: { type: "json_schema", name: "ticket", schema: SCHEMA, strict: true } },
})).output_text,
gemini: async (m) =>
(await new GoogleGenAI({}).models.generateContent({
model: "gemini-4-hydrogen",
contents: m.map((x) => ({ role: x.role === "assistant" ? "model" : "user", parts: [{ text: x.content }] })),
config: { systemInstruction: SYSTEM, responseMimeType: "application/json", responseJsonSchema: SCHEMA },
})).text ?? "",
local: async (m) =>
(await new OpenAI({ baseURL: "http://localhost:11434/v1", apiKey: "ollama" }).chat.completions.create({
model: "gemma4:e4b", temperature: 0, messages: [{ role: "system", content: SYSTEM }, ...m],
response_format: { type: "json_schema", json_schema: { name: "ticket", schema: SCHEMA } },
})).choices[0].message.content ?? "",
};
Measure parse failures, then record the baseline
Constrained decoding guarantees that the JSON is well formed. It does not guarantee the values are correct: "priority": "p3" for a production outage parses fine. Output can also break in ways the schema can't stop: a refusal, or a response cut off at max_tokens before the JSON closes. So count three things separately:
# baseline.py: eval.jsonl holds about 100 hand-labelled tickets, e.g.
# {"text": "Can't log in since the SSO change", "expected": {"category": "bug", "priority": "p2"}}
import json, time, hashlib, datetime
from clients import PROVIDERS
from task import SYSTEM, FEW_SHOT
cases = [json.loads(l) for l in open("eval.jsonl")]
prompt_id = hashlib.sha256((SYSTEM + json.dumps(FEW_SHOT)).encode()).hexdigest()[:8]
for name, call in PROVIDERS.items():
for constrained in (False, True): # ablation: what does schema mode add?
parse_fail = invalid = correct = 0
t0 = time.time()
for c in cases:
try:
out = json.loads(call(FEW_SHOT + [{"role": "user", "content": c["text"]}], constrained))
except Exception: # JSON that won't parse, a refusal, a truncation or an API error
parse_fail += 1; continue
if out.get("priority") not in ("p1", "p2", "p3") or len(out.get("summary", "").split()) > 20:
invalid += 1; continue # parsed, but breaks a rule
correct += all(out[k] == v for k, v in c["expected"].items())
row = {"provider": name, "constrained": constrained, "prompt_id": prompt_id,
"n": len(cases), "parse_fail": parse_fail / len(cases),
"invalid": invalid / len(cases), "accuracy": correct / len(cases),
"secs": round(time.time() - t0, 1), "date": datetime.date.today().isoformat()}
print(row)
open("baseline.jsonl", "a").write(json.dumps(row) + "\n")
A typical result: with constrained output off, small local models sometimes wrap the JSON in Markdown code fences or add a chatty preamble. With it on, the parse failure rate falls to roughly zero, and accuracy becomes the number that separates the models.
Best practice: treat
baseline.jsonllike a benchmark fixture. Freezeeval.jsonl, store theprompt_id, and never tune your prompt on the same tickets you score it on. Every later level compares against these rows.
Exercise
- Label 50–100 real or realistic tickets in
eval.jsonl. Include awkward ones: two problems in one ticket, an angry ticket that isn't urgent, a ticket that isn't in English. - Run
baseline.pyagainst at least two hosted providers and the local model, with constrained output on and off. - Change one thing at a time: zero, two, then five few-shot examples. Note how parse failures and accuracy move.
- Commit your best row per provider as the baseline that later levels must beat.
Key takeaways
- Prompt hard first. A tuned model only means something next to a measured prompted baseline.
- System prompt, few-shot examples and a JSON schema stack on each other. The schema is the strongest lever for format.
- Each provider names the feature differently: Claude uses
output_config.format, OpenAI Responses usestext.format, Gemini usesresponse_json_schema, and Ollama or other OpenAI-compatible servers useresponse_format. - Schema mode guarantees syntax, not correctness. Count parse failures, rule violations and accuracy separately.
- Freeze the eval set and version the prompt so later comparisons are fair.