Domain 4 · 20% of exam
Prompt Engineering & Structured Output cheat sheet
The idea this domain hangs on
Two kinds of reliability, and neither reaches meaning on its own.
| Reliability of form | Reliability of judgement | |
|---|---|---|
| Mechanisms | tool_use + JSON schema, tool_choice any or forced, strict: true (4.3) | Explicit criteria (4.1), few-shot examples (4.2), severity criteria with code examples |
| What it buys | Syntax errors eliminated | Precision improved, never guaranteed |
| What still gets through | Semantic errors: line items that do not sum, values in the wrong field | Misjudged edge cases |
- Both still fail semantically, so the rest of the domain catches what they miss: validation and feedback (4.4:
calculated_totalvsstated_total,conflict_detected, retry with the specific error) and architecture (4.5 batch for latency-tolerant volume; 4.6 an independent reviewer and per-file passes). - The favourite trap: assuming a strict schema fixes accuracy. It fixes shape.
4.1 Explicit Criteria
| Vague (wrong) | Explicit (correct) |
|---|---|
| "Be conservative" | "Report bugs and security vulnerabilities. Skip minor style preferences." |
| "Only report high-confidence findings" | Confidence routing comes after explicit criteria, never instead of them |
| "Check that comments are accurate" | Flag a comment only when its claimed behaviour contradicts the code |
| Prose severity ("could cause system failures") | Concrete code example per severity level, with the pattern named |
- Criteria live in the top-level
systemparameter;role: "system"entries inmessagesare mid-conversation system messages, not the standing system prompt. max_tokensis a ceiling, not a target.temperatureis a sampling setting, not a precision control — it cannot define what counts as a finding.- Two failure modes: hardcoded brittle logic vs vague high-level guidance. Target: minimal info that fully outlines expected behaviour.
- Criteria block = report list + skip list (with reasons) + "omit anything outside the report list". Out-of-scope finding → omit, never downgrade to "low".
- A criterion still leaning on "important" / "significant" / "suspicious" has only renamed the vagueness.
- High FP rate in ONE category destroys trust in ALL categories → temporarily disable, refine with code examples, re-enable.
- Precision = acted-on findings ÷ findings raised, per category (one noisy category drags the overall figure down; developers see that figure).
- Disabled category → shadow mode (generate and log, don't post); re-enable at a precision bar written down in advance.
- Confidence filtering fails three ways: uncalibrated, doesn't encode your policy (wrong findings are often high-confidence), unauditable. Emit confidence for routing; never filter on it in the prompt.
- Judge a criteria rewrite on the same labelled set, not by a drop in finding count (fewer findings ≠ higher precision).
- Best feedback form: clear rules + which rule failed and why (e.g. linting). Start evals with ~20 queries.
4.2 Few-Shot Prompting
| Trigger | Fix |
|---|---|
| Inconsistent formatting despite detailed instructions | Few-shot examples (NOT more instructions) |
| Inconsistent judgement on ambiguous cases | Few-shot examples with reasoning |
| Empty/null fields for data that exists | Few-shot examples across document structures |
| False positives on a pattern the team uses deliberately | Contrast pairs: acceptable vs genuine, side by side |
- 2-4 targeted examples (exam; current docs 3–5). Fewer than 2 = no pattern; 8-10 "for coverage" = wasted tokens / context rot.
- Every example needs reasoning (why this action, not just what) → teaches generalisation, not pattern-matching.
- "Pictures worth a thousand words" — curate diverse, canonical examples; never a laundry list of edge-case rules.
- Classification tasks: pair few-shot with a tool
enumfield or structured outputs. - Informal measurement ("a couple of tablespoons") →
quantitynull + original text kept + flagged informal. Never invent a number. - Examples cannot conjure data: a genuinely absent field → nullable + one example where null is correct.
- Not a few-shot problem: malformed JSON (→ tool_use), fabricated values (→ nullable fields), sum mismatches (→ validation loop), required ordering (→ hook / prerequisite), whole category unwanted (→ explicit criteria), prose instead of structured result (→ tool use with
tool_choice). - Similar tools confused → better tool descriptions first; few-shot only for requests still ambiguous after that (sample Q2).
4.3 Structured Output (the big one)
Reliability hierarchy: tool_use + JSON schema (eliminates syntax errors) > prompt-based JSON (no guarantees).
| tool_choice | Behaviour | Default when |
|---|---|---|
auto | May call a tool OR return text | tools provided |
any | Must call a tool, model picks which | — |
{"type":"tool","name":"..."} | Must call that tool | — |
none | No tool use | no tools provided |
- Unknown document type, several schemas →
any; which schema it chose = thetool_useblock'sname, data = itsinput. - A step that must run first → force it by name on that request, then
auto(forcing every turn = the loop never ends). tool_choice: "any"alone ≠ schema-valid input. Addstrict: trueon the tool for BOTH guarantees.- Forced (
any/tool) side effect: response starts with the tool call — no text beforetool_use, even if asked; skips thinking. - Current docs: forced
any/tool→ 400 on Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5, Fable 5.1, Mythos 5.1 (useauto+ strict, or structured outputs). Exam answer is still forced selection. - Structured outputs = JSON outputs (
output_config.format, constrains the response itself) + strict tool use (strict: true, constrains tool inputs). "Available on every model".output_formatis deprecated; citations +output_config.format→ 400. - Schema limits:
additionalProperties: falserequired for objects; NO recursive schemas,oneOf(useanyOf),not, external$ref,minimum/maximum/multipleOf,minLength/maxLength; enums are primitives only. - Per request: 20 strict tools, 24 optional params, 16 union-type params (each
["string","null"]counts); 180 s compile timeout. - First use of a schema = extra latency (grammar compiles); cached 24h from last use.
stop_reasonrefusalormax_tokens→ output may not match the schema; check it first. - Prefill: historical JSON-forcing hack → migrated to Structured Outputs. 400 error on last-turn prefill for Claude 4.6+ / Mythos Preview. (Forced tool choice is a separate setting, unaffected by that change.)
- What tool_use eliminates: syntax errors. What it does NOT eliminate: semantic errors (sums, field placement, fabrication).
- Nullable/optional fields = primary defence against fabrication. Required only if present in every valid document; pair nullable with a prompt line "a null is a correct extraction".
- Enum escapes:
other+ detail string → mine details, extend the enum;unclear→ human review.
4.4 Validation, Retry, Feedback Loops
Retry message = original document + failed extraction + specific validation error. Good error = what is wrong + the evidence + what to do.
| Retries FIX | Retries CANNOT FIX |
|---|---|
| Format mismatches | Info genuinely absent from source |
| Structural/field-placement errors | Data only in an external, unprovided doc |
| Missed line items (math errors) | Knowledge the model lacks |
- Unfixable → flag for human review / return null. Do NOT keep retrying.
- Classify before the first retry, from a typed
retryableflag set by the check — not by matching words in the error text. - Cap retries (two or three); never resend identical inputs; stop when the same error comes back.
- Invalid tool call: the API does not retry for you → send a
tool_resultwithis_error: true; Claude might call the tool again, so cap retries in your own loop.strict: trueremoves invalid calls entirely. - After a
tool_use, return the specific validation errors in atool_resultwithis_error: true(tool_result first, any text after, sametools) — not as plain text in a new user turn. - Self-correction schema:
calculated_total(computed from line items, never copied) vsstated_total(as printed, nullable), +total_discrepancyflag. conflict_detected+conflict_note= the retry stop condition for a totals mismatch: document contradicts itself → accept as extracted, route to review.detected_patternfield on findings → track dismissals → fix the pattern with the most dismissals (frequency × dismissal rate), not the highest rate.- True-but-unwanted dismissal → criteria change (4.1), not a model fix.
- Feedback ranking: rules-based (best) > ... > LLM-as-judge (weakest — "not a very robust method", latency cost).
- Schema syntax errors → eliminated by tool_use (4.3). Semantic validation errors → this task statement.
4.5 Batch Processing (airtight facts)
| Fact | Value |
|---|---|
| Cost discount | 50% of standard price, unconditional |
| Typical time | <1 hour (most batches) |
| Max processing window | 24 hours (hard) |
| Latency SLA | None — best-effort |
| Size limit | 100,000 requests OR 256 MB, whichever first → 413 if exceeded |
| custom_id | ^[a-zA-Z0-9_-]{1,64}$, unique within the batch; ALWAYS match results by custom_id — never assume order |
| processing_status | in_progress → canceling → ended |
| Result types | succeeded, errored, canceled, expired |
| Billed | Only succeeded |
| Results | .jsonl at results_url, populated only once ended; stream, don't bulk-download |
| Results retention | 29 days from created_at (NOT ended_at) |
| Rejected params | stream: true, speed, fallbacks, max_tokens: 0 |
| Param validation | Asynchronous — errors surface only after the batch ends; dry-run first |
| Prompt cache tip | Use 1-hour TTL (batches often exceed 5 min) |
Matching rule: is anything waiting for the result? Synchronous = blocking workflows (pre-merge checks); batch = latency-tolerant (overnight/weekly reports). Manager wants "switch everything to batch" → keep blocking workflows synchronous.
SLA math: gap between submissions + 24h + downstream ≤ SLA. 30h SLA → submit every 4h (guide; 6h at most with nothing downstream). Fixed deadline → submit ≥24h (+ downstream) before. SLA ≤ 24h → impossible on batch.
Failure handling: identify by custom_id → resubmit ONLY failures, each with the fix its failure calls for (oversized → chunk under derived ids such as doc-0042-chunk-0; expired / server error → unchanged; other invalid request → fix first) → never resubmit the whole batch.
Sample-set first: refine prompts on 5-10 docs spanning every format, iterating on the synchronous API (each batch round can cost 24h). 90% first-pass = 100 retries/1000 docs; 60% = 400 retries (4×).
- Forced
tool_choicecarries into batch requests unchanged; on the newest models it returns 400 — check every request's model accepts it.
4.6 Multi-Instance & Multi-Pass Review
| Design question | Right answer |
|---|---|
| Who reviews? | An independent instance with no generating context |
| How much per pass? | One file per pass, then one cross-file integration pass |
| What happens to each finding? | Routed by severity × confidence, threshold calibrated on labelled data |
- Self-review (same session) retains reasoning context → confirms rather than challenges itself. Independent instance = fresh context, no bias toward code it just wrote (official guidance).
- Give the reviewer the diff, the requirement, conventions (CLAUDE.md) and test results; withhold the generator's reasoning, even summarised.
- Writer/Reviewer pattern: Session A generates → Session B reviews fresh → Session A addresses feedback.
- Adversarial review: fresh subagent sees only the diff + criteria, never the generating reasoning.
- Second opinion: fresh model tries to refute the result — not just re-confirm.
- Basis: subagent context isolation (own context window, only relevant info sent back).
| Symptom (single-pass, multi-file) | Fix |
|---|---|
| Inconsistent depth across files | Per-file local analysis passes |
| Missed middle-file bugs | Per-file local analysis passes |
| Contradictory findings (diagnostic signature) | Cross-file integration pass |
- Bigger context window does NOT fix this — the problem is attention quality, not capacity. Nor does more thinking/effort on the single pass.
- Per-file pass gets its own file only (plus criteria). Integration pass gets all per-file findings as structured data, told to report only cross-file issues.
- Integration pass checks: data flow between modules, contradictions across per-file findings, API contract violations.
- "Flag only what 2 of 3 passes agree on" → wrong: suppresses intermittently caught real bugs (sample Q12).
- Routing: high conf + high sev → blocking comment; high conf + low sev → note; low conf + high sev → human; low/low → log. Raw self-reported confidence is uncalibrated — treat like LLM-as-judge (documented as the weakest verification method).
- Calibrate: group findings into confidence bands, measure the share correct against human verdicts or recorded outcomes — never against a second model's verdicts.
- Merge and de-duplicate in code, keyed on file + line +
detected_pattern; re-runs report only new or still-unaddressed issues. - Judge the end state, not the process followed. Rubric example: factual accuracy, citation accuracy, completeness, source quality, tool efficiency. Start with ~20 queries; manual testing still catches what evals miss.