🎓 Claude Certification Prep

Home › CCAR-F › M04

Prompt Engineering & Structured Output

Domain 4 20% of exam 60 practice questions ~24 min read

Explicit criteria to reduce false positives, few-shot examples for ambiguous cases, enforcing structured output with tool use and JSON schemas, validation–retry loops, the Message Batches API, and multi-instance, multi-pass review architectures.

Skills measured in this domain:
  • 4.1 Design prompts with explicit criteria to improve precision and reduce false positives
  • 4.2 Apply few-shot prompting to improve output consistency and quality
  • 4.3 Enforce structured output using tool use and JSON schemas
  • 4.4 Implement validation, retry, and feedback loops for extraction quality
  • 4.5 Design efficient batch processing strategies
  • 4.6 Design multi-instance and multi-pass review architectures

Domain overview

Domain 4, "Prompt Engineering & Structured Output", makes up 20% of the exam (about 12 of 60 questions). The exam doesn't ask for generic prompting tips; it asks whether you know which mechanism fixes which kind of failure: vague criteria are fixed with specific criteria and examples; JSON syntax errors are fixed with schemas; semantic errors need validation and retry; and cost and latency come down to choosing the synchronous or the batch API.

Two scenarios are tightly linked to this domain:

  • Scenario 5 – Claude Code for Continuous Integration: automated code review, test generation, feedback on PRs; feedback must be actionable with few false positives.
  • Scenario 6 – Structured Data Extraction: extracting from unstructured documents, validating with JSON schemas, handling edge cases, passing data to downstream systems.

Exam tip: identify which layer the failure belongs to before choosing an answer. Distractors are often a powerful mechanism aimed at the wrong layer, e.g. switching to a larger model for a failure caused by vague criteria, or retrying a field that the source document doesn't contain at all.

(Source: CCAR-F Exam Guide, Domain 4, Scenarios 5 and 6)

Explicit criteria to improve precision (4.1)

Why "be careful" doesn't work

Instructions such as "be conservative" or "only report high-confidence findings" sound like they would reduce false positives, but the Exam Guide states clearly that they fail to improve precision compared with specific categorical criteria. The model doesn't know which kinds of findings "conservative" means dropping, so it keeps reporting the same things in a more hedged tone.

What works is writing well-defined criteria: which categories to report (bugs, security) and which to skip (minor style, local patterns the team has already accepted). The Exam Guide's example: replace "check that comments are accurate" with "flag comments only when the claimed behavior contradicts the actual code behavior".

Vague instruction Explicit criterion
"Check that comments are accurate" "Flag only when a comment describes behavior that contradicts the actual code"
"Be careful; report only when you're sure" "Report: logic errors, injection, personal data in logs. Skip: naming, formatting, patterns already used in the module"
"Assess severity sensibly" "Important: breaks behavior, leaks data, or violates a policy. Everything else is a Nit"

The Building with the Claude API course shows the same effect: adding only specific guidance on what the output must contain raised a prompt's eval score from 3.92 to 7.86.

False positives and developer trust

The Exam Guide stresses that a finding category with a high false positive rate drags down trust in the accurate categories too. Once developers are used to ignoring the bot, they also ignore its correct comments about security vulnerabilities. The skill being tested: temporarily disable high false-positive categories to restore trust while you improve the prompts for those categories.

Common trap: fixing false positives with a confidence threshold

Options such as "only post findings with confidence above 0.8" or "ask Claude to be more careful" are familiar distractors. They don't define which kinds of issues are worth reporting, so they don't touch the cause. When the item describes a specific finding category that creates noise, the better answer is usually a specific exclusion criterion for that category, or temporarily disabling it while you fix the prompt.

Defining severity with code examples

If you rely only on level names ("high", "medium"), severity classification will drift between runs. The Exam Guide recommends explicit severity criteria with concrete code examples for each level. The PR review play in the AI-native SDLC playbook writes this policy into a REVIEW.md file at the repo root: it splits the review into passes, defines Important and Nit, caps the number of nits, and states explicitly what not to report.

## Passes
Run three passes and tag each finding with its pass:
- Bugs: logic errors, broken edge cases, subtle regressions
- Security: injection risks, authentication gaps, PII in logs
- Compliance: the change matches spec.md, plan.md and our design principles
## What Important means here
Reserve Important for findings that would break behavior, leak data
or breach a policy. Style and naming are nits.
## Cap the nits
Report at most five nits per review; summarize the rest as a count.
## Do not report
Generated files under src/gen/ and anything CI already enforces.

Each month the tech lead scores the findings and adjusts the nit cap, in the spirit of the feedback loop in Task 4.4.

(Sources: CCAR-F Exam Guide, Task 4.1; Anthropic Academy: Building with the Claude API — Being specific; Anthropic Academy: The AI-native SDLC playbook — AI in the PR review loop)

Scenario 5: developers ignore the review bot

A review bot posts an average of 25 comments per PR and developers ignore almost all of them, including a correct comment about SQL injection. Most comments fall into two categories: "unclear naming" and "should split the function". The fix per Task 4.1: temporarily disable those two categories; rewrite the prompt with specific report and skip lists; define each severity level with a sample code snippet; re-enable a category only when the new criteria reach acceptable precision on a set of labeled PRs.

Few-shot prompting (4.2)

When few-shot beats detailed instructions

The Exam Guide considers few-shot examples the most effective technique for consistent, actionable output when detailed instructions still produce inconsistent results. Examples do well what prose does poorly:

  • Demonstrating how to handle ambiguous cases: which tool to choose when a request can be read two ways, or branch-level test coverage gaps.
  • Generalizing judgment to novel patterns, rather than matching only the listed cases.
  • Locking in the format: every finding always has location, issue, severity, suggested fix.
  • Reducing hallucination in extraction: informal measurements, documents with varied structures.

Designing the example set

The skill the Exam Guide lists: create 2–4 targeted examples for ambiguous scenarios, each explaining why one action was chosen over plausible alternatives. The explanation helps the model learn the criteria rather than memorize the answers.

The prompting courses add: wrap examples in XML tags such as <sample_input> and <ideal_output>, explain why the sample output is ideal, and choose relevant, varied examples. The real-world prompting material suggests starting with about 3–5 examples and adding targeted ones if results fall short; the Exam Guide's 2–4 applies to specific ambiguous scenarios.

<sample_input>
def get_user(id):
    # Returns None if the user does not exist
    return db.users.find_one({"_id": id})
</sample_input>
<ideal_output>
Do not report: find_one returns None when nothing is found, which matches the comment.
</ideal_output>

<sample_input>
def total(items):
    # Sum of prices including tax
    return sum(i.price for i in items)
</sample_input>
<ideal_output>
location: total(), line 3
issue: the comment says tax is included but the code only sums price
severity: Important (wrong amount shown to the customer)
suggested_fix: add tax or correct the comment to match the behavior
</ideal_output>

This pair of examples teaches both the four-field format and the boundary between an acceptable pattern and a genuine issue, the kind of example the Exam Guide treats as a way to reduce false positives while still enabling generalization.

Purpose What the examples should show
Consistent format All fields: location, issue, severity, suggested fix
Fewer false positives Code that looks suspicious but is valid, with the reason not to report it
Ambiguous cases Two plausible choices and the reason for picking one
Varied documents Inline citations vs end-of-document bibliographies; separate methodology sections vs details scattered through the body
Required fields returned empty A document with an unusual format that still contains the value, and how to find it

Few-shot teaches judgment, not a lookup list

Good examples explain the criteria behind the decision, so the model can apply them to patterns it has never seen. If every new failure needs another new example, the current examples most likely lack reasoning or are too similar to each other.

(Sources: CCAR-F Exam Guide, Task 4.2; Anthropic Academy: Building with the Claude API — Providing examples; Anthropic Courses (GitHub): Real world prompting)

Enforcing structured output with tool use and JSON schemas (4.3)

Tool use as a mold for JSON

The Exam Guide considers tool use with JSON schemas the most reliable way to get schema-compliant output, eliminating JSON syntax errors. Define an extraction tool whose input_schema is exactly the data structure you want; when Claude calls the tool, the call's arguments are the structured data. You don't execute anything; you just read the input field of the tool_use block, and you should find the block by type rather than assuming its position.

tools = [{
    "name": "extract_invoice",
    "description": "Extracts invoice information from the provided text.",
    "input_schema": {
        "type": "object",
        "properties": {
            "invoice_number": {"type": "string"},
            "vendor": {"type": "string"},
            "stated_total": {"type": "number"}
        },
        "required": ["invoice_number", "vendor", "stated_total"]
    }
}]

response = client.messages.create(
    model=MODEL,
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "tool", "name": "extract_invoice"},
    messages=[{"role": "user", "content": document_text}],
)
data = next(b.input for b in response.content if b.type == "tool_use")

tool_choice: auto, any, and forcing a specific tool

tool_choice value Behavior When to use (per the Exam Guide)
{"type": "auto"} (default) May call a tool or return text Normal conversation; structured output not guaranteed
{"type": "any"} Must call a tool, chooses which one Multiple extraction schemas, document type unknown
{"type": "tool", "name": "extract_metadata"} Must call that specific tool Ensure a particular extraction runs before enrichment steps

Forcing a tool doesn't stop Claude from calling several tools in one turn; if you need at most one call, add "disable_parallel_tool_use": true to tool_choice.

Model note: forced tool_choice is rejected on some newer models

Per the current claude-api documentation, {"type": "any"} and {"type": "tool", ...} return a 400 error on Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, and Claude Sonnet 5.5, including in Message Batches. On these models, use auto with clear instructions in the prompt and check whether the tool was called; add strict: true to keep the guarantee that arguments match the schema; or use structured outputs (output_config.format) if the forced call was only meant to get JSON. The exam still tests the auto/any/forced concepts as in the table above, so know both.

Strict tool use and structured outputs

Tool use without strict can still produce arguments of the wrong type or with missing fields. The current documentation offers two guarantee features:

  • Strict tool use: "strict": true at the tool level and "additionalProperties": false on every object; token generation is constrained to the schema. In the tool use course demo, Meridian's validator rejected 79/100 calls with strict off, and rejected none with strict on and a schema generated from the validator itself.
  • JSON outputs: output_config.format with {"type": "json_schema", "schema": {...}} constrains the response itself to the schema, without a tool. It works with the Batches API but cannot be combined with citations (returns 400) or message prefilling.

Limits to remember: minimum, maximum, minLength, maxLength are not supported (the Python and TypeScript SDKs strip them and check client-side), so keep bound constraints in your validator; one request can contain at most 20 strict tools, 24 optional parameters, and 16 parameters using anyOf or type arrays (nullable fields generate anyOf). Output can still deviate from the schema when Claude refuses (stop_reason: "refusal") or is cut off by max_tokens.

The Exam Guide and current documentation say the same thing

The Exam Guide calls it "strict JSON schemas via tool use"; the current documentation splits it into strict: true for tools and output_config.format for the response. The common point to remember: schema constraints eliminate syntax and structural errors, but don't guarantee values that are semantically correct.

Correct syntax doesn't guarantee correct semantics

The schema guarantees that stated_total is a number, but not that the line items sum to the total, or that the delivery date isn't placed in the invoice date field. Those are semantic errors, which need a separate validation layer (4.4). Strict also doesn't create facts: in the Meridian demo, 28/100 requests didn't mention a permit number, and because the schema allowed null, all 28 returned null instead of a fabricated number.

(Sources: CCAR-F Exam Guide, Task 4.3; Anthropic Skills: claude-api — Tool Use Concepts; Anthropic Academy: Tool use with the Messages API — Strict tool use)

Schema design that prevents fabrication

Five schema design decisions that come up often on the exam:

  • Required vs optional: make fields the source may not contain optional or nullable; requiring them pushes the model into fabricating values.
  • Extensible enums: an "other" value plus a detail string field.
  • An "unclear" value for ambiguous cases, instead of forcing the model to guess.
  • Format normalization rules (dates, units, currency) written in the prompt alongside the schema, because sources are often inconsistent.
  • Cross-check fields such as calculated_total next to stated_total, and a conflict_detected flag.
{
  "type": "object",
  "properties": {
    "invoice_number": {"type": "string"},
    "due_date": {"type": ["string", "null"], "description": "YYYY-MM-DD; null if the document doesn't state it"},
    "category": {"type": "string", "enum": ["hardware", "software", "services", "other", "unclear"]},
    "category_detail": {"type": ["string", "null"], "description": "Description when category is other"},
    "stated_total": {"type": ["number", "null"]},
    "calculated_total": {"type": ["number", "null"]},
    "conflict_detected": {"type": "boolean"}
  },
  "required": ["invoice_number", "due_date", "category", "category_detail",
               "stated_total", "calculated_total", "conflict_detected"],
  "additionalProperties": false
}

The fields stay in required but their types allow null: the model must always answer the field, and an honest "not present" answer is valid.

Required fields that don't allow null are a source of fabrication

If the item describes a system that "fills in plausible but wrong values" for documents missing information, the root cause is usually in the schema: required fields that don't allow null. Adding "don't make things up" to the prompt treats the symptom; allowing null and stating when null is the correct answer fixes the cause.

Scenario 6: extracting payment terms

Supplier contracts come in many templates: some say "payment within 30 days", some say "Net 30", a few say nothing. A sound design: payment_terms_days as a number or null; normalization rules in the prompt ("Net 30" and "30 days" are both 30); a payment_method enum with "other" plus payment_method_detail; and 2–3 few-shot examples for different contract layouts.

Validation, retry, and feedback loops (4.4)

Retry with specific error messages

When a result fails the validator (Pydantic, JSON schema, or business rules), don't just resend the original request. The Exam Guide's retry-with-error-feedback technique: the follow-up request includes the original document, the failed result, and the specific validation errors, so the model fixes exactly the right places.

<document>
{document_text}
</document>

<previous_extraction>
{failed_json}
</previous_extraction>

<validation_errors>
- line_items: sum 1,180,000 does not match stated_total 1,250,000
- due_date: "15/03" is missing the year; required format is YYYY-MM-DD
</validation_errors>

Correct the result to fix the errors above. Use only information in <document>.
If the document does not contain a required value, return null for that field.

When retry is pointless

Retry works when the information is in the document but was extracted with the wrong format or structure. When the information is absent, or exists only in an external document that wasn't provided, no number of retries will produce it; the pressure to "fix the error" can even push the model to fabricate a value.

Error type Does retry help? What to do
Wrong format (date, unit, currency) Yes Retry with the error; add normalization rules to the prompt
Structural error (wrong field, missing key) Yes Retry with the error; consider strict to eliminate it entirely
Information not in the document No Allow null, mark as missing
Information in another document not yet provided No Add that document to the input or route to a human
Source contradicts itself Don't force a fix Record both values, set conflict_detected, route to review

The Introduction to evals course illustrates this: Claude Haiku 4.5 scored only 84% on Meridian's extraction eval. Two prompt changes, stating when null is the correct answer and requiring a quote of the source passage before answering, brought Haiku 4.5 to 100%. Along with that: group failures by document type and by field, run each case at least twice, and upgrade the model only when prompt changes stop improving the score.

Retry can't replace missing data

Items often describe a field that "still fails after three retries" and then offer "increase the number of retries" or "switch to a stronger model". Check whether that information is actually in the document. If it isn't, the right answer is to allow null or add the source.

Self-checking with cross-check fields

Some semantic errors surface during extraction itself if the schema requires both the stated value and a self-calculated value. When calculated_total differs from stated_total, downstream code knows the record needs review; the conflict_detected flag marks inconsistent source data so the system doesn't silently pick one value.

detected_pattern and dismissal analysis

In automated review, each finding should have a detected_pattern field recording which code construct triggered it, e.g. "string concatenation in SQL". When developers dismiss findings, aggregating by pattern shows which categories have high dismissal rates, giving you a basis to rewrite the criteria (4.1), add distinguishing examples (4.2), or temporarily disable that category.

Domain 4's closed feedback loop

Criteria (4.1) and few-shot examples (4.2) produce findings; the schema (4.3) makes findings machine-readable, with detected_pattern; validation and dismissal data (4.4) show which criteria need fixing; the fixes feed back into 4.1 and 4.2.

(Sources: CCAR-F Exam Guide, Task 4.4, Exercise 3; Anthropic Academy: Introduction to evals — Iterate the prompt before you upgrade the model; Claude Docs: Reduce hallucinations)

Efficient batch processing (4.5)

The Message Batches API in one table

Characteristic Value
Cost 50% lower than synchronous calls
Processing time Up to 24 hours, most finish within 1 hour; no latency SLA
Batch limits 100,000 requests or 256 MB, whichever comes first
Result retention 29 days from creation
Result order Not guaranteed; match requests and results with custom_id (1–64 characters: letters, digits, -, _)
Result types succeeded, errored, canceled, expired; the last three are not billed
After submission Cannot be modified; to change it, cancel and submit a new batch
{
  "requests": [
    {
      "custom_id": "invoice-2026-11-000123",
      "params": {
        "model": "claude-opus-5-5",
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": "..."}]
      }
    }
  ]
}

Choosing the synchronous or batch API

The deciding question: is anyone or any process waiting for the result? Batch suits non-blocking, latency-tolerant work: overnight reports, weekly audits, nightly test generation. Batch doesn't suit blocking work such as pre-merge checks, because developers can't wait up to 24 hours.

The Exam Guide also states that the batch API does not support multi-turn tool calling within a single request: you cannot execute your tools mid-request and return the results to the same request. Current documentation says batch requests can use tool use, including server tools, but an agent loop that needs the client to execute tools still has to span multiple requests.

Don't move pre-merge checks to batch just because it's 50% cheaper

Familiar distractors: move every workflow to batch, add polling, or "fall back to synchronous if it takes too long". Workflows that block developers need the synchronous API; only background workflows benefit from batch. The correct answer usually separates the two kinds of workflow instead of applying one API to everything.

Calculating submission frequency from the SLA

Because a batch can take up to 24 hours, submission frequency has to be worked out backward from the SLA. The Exam Guide's example: to guarantee a 30-hour SLA with a maximum processing time of 24 hours, submit batches in 4-hour windows. The reasoning: a document that arrives right after a submission waits at most 4 hours to be submitted, plus 24 hours of processing makes 28 hours, leaving room to process the results within 30 hours.

Handling failures and resubmitting

When requests fail, resubmit only the failed requests, identified by custom_id, with adjustments for the cause, e.g. chunking documents that exceeded the context limit. For errored results, invalid_request_error means the request was malformed and must be fixed before resubmitting; other errors can be resubmitted directly. To reduce resubmission rounds, the Exam Guide recommends refining the prompt on a sample set before running large volumes; the batch documentation adds: test a single request with the Messages API first to catch validation errors.

Scenario 6: 40,000 invoices every night

The finance team needs the data on its dashboard before 8 a.m. Design: refine the prompt and schema on 200 labeled sample invoices; test one synchronous request; submit the batch at 8 p.m. with the invoice number as custom_id; match results by custom_id, validate each record, and resubmit only the failed invoices (splitting overly long invoices by page) in a small batch. Because batch has no SLA, leave time for a second batch.

(Sources: CCAR-F Exam Guide, Task 4.5; Claude Docs: Batch processing)

Multi-instance and multi-pass review (4.6)

Limits of self-review

The instance that just generated the code still holds the reasoning that led to it, so it is less likely to question its own decisions when reviewing in the same session. The Exam Guide states that an independent review instance, without the generator's reasoning context, catches subtle issues more effectively than a "review your work carefully" instruction or extended thinking. The PR review play also keeps separation of duties: the agent that writes the code cannot approve it.

Multi-pass: per file, then integration

Reviewing a large PR in a single pass invites attention dilution: one file gets detailed comments, another gets a cursory look, and there can even be contradictory findings when the same pattern is flagged in one file but accepted in another. The Exam Guide recommends:

  1. Per-file local passes for issues within a file's scope.
  2. A separate integration pass for cross-file data flow: changed interfaces, assumptions between modules.

A larger context window doesn't fix attention quality; splitting the work does.

Verification passes and confidence

A verification pass can ask the model to self-report confidence for each finding to drive routing: high confidence is posted directly, low confidence goes to a human reviewer. Self-reported confidence must be calibrated against a labeled dataset before it is used as a threshold (Domain 5).

Architecture Solves Doesn't solve
Independent review instance Bias from the generation step Attention dilution when the PR is too large
Per-file local passes Uneven depth across files Cross-file bugs
Integration pass Data flow, interfaces between modules Detailed bugs within each file
Verification pass with confidence Routing to a human or automation Finding accuracy, if not yet calibrated

Multi-pass consensus isn't always better

Running several review passes over the whole PR and keeping only findings that appear in a majority of passes sounds rigorous, but it discards exactly the real bugs that are caught inconsistently, and it doesn't touch the root cause, attention dilution. Splitting by scope (per file, then integration) targets the cause more directly.

(Sources: CCAR-F Exam Guide, Task 4.6; Anthropic Academy: The AI-native SDLC playbook — AI in the PR review loop)

Quick summary

  • Specific categorical criteria (what to report, what to skip) improve precision; "be careful" or confidence-based filtering doesn't.
  • A high false-positive category erodes trust in the accurate categories too: temporarily disable it while fixing the prompt; define severity with code examples.
  • Few-shot is the most effective technique for consistent format; use 2–4 examples for ambiguous cases, with the reason one action was chosen over the alternatives.
  • Examples that distinguish "valid pattern" from "genuine issue" reduce false positives while still enabling generalization.
  • Tool use + JSON schema is the most reliable way to get structured output; read the data from the input of the tool_use block.
  • auto may return text; any forces a call to a tool of the model's choice; {"type": "tool", "name": ...} forces one specific tool. On Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1, and Claude Mythos 5.1, forced tool_choice returns 400.
  • Strict schemas eliminate syntax errors, not semantic errors (totals that don't match, values in the wrong field).
  • Fields that may be absent must allow null; enums get "other" + a detail field and "unclear"; normalization rules go in the prompt next to the schema.
  • Retry with the original document, the failed result, and the specific validation errors; retry is pointless when the information isn't in the document.
  • calculated_total next to stated_total and conflict_detected to surface inconsistencies; detected_pattern to analyze dismissals.
  • Batch: 50% cheaper, up to 24 hours, no SLA; for background work, not for pre-merge checks; match results with custom_id.
  • Work out batch submission frequency backward from the SLA; resubmit only failed requests; refine the prompt on a sample set before running large volumes.
  • An independent review instance beats self-review or extended thinking in the same session.
  • Large PRs: per-file local passes plus an integration pass; self-reported confidence must be calibrated before it is used for routing.