A2ZSkillsBrowse courses

Domain 4 · 20% of scored content

Prompt Engineering & Structured Output

This domain is about making outputs you can act on. Half of it is precision — writing criteria specific enough that a reviewer trusts the findings — and half is structure: tool use with JSON schemas, validation loops, and knowing when a retry is pointless. The through-line is that vague instructions produce vague compliance, and that a schema eliminates syntax errors but never semantic ones.

Two diagrams. Left: the six ordered parts of a prompt — role and context, task instructions, few-shot examples, tool and schema definitions, output format spec, and the specific request placed last. Right: the schema-constrained output loop — define a JSON or tool schema, force the model to answer through it, validate the response, then use it if valid or feed the validation error back for a retry if not.Open full size
Stable context first, the actual ask last. On the right, the difference between requesting a format and enforcing one.
4.1

Design prompts with explicit criteria to improve precision and reduce false positives

"Check that comments are accurate" and "flag comments only when the claimed behaviour contradicts the actual code behaviour" ask for the same thing and get very different results. The second states a test the model can apply; the first states a topic.

General exhortations do not help. "Be conservative" and "only report high-confidence findings" sound like precision controls and are not — they ask the model to filter on a self-assessment it is not good at. Specific categorical criteria are what actually move the false positive rate.

False positives are expensive beyond the noise. One category that cries wolf undermines confidence in the categories that are right, so developers start skimming everything. When a category is badly calibrated, turning it off temporarily while you fix its prompt protects trust in the rest.

For consistent severity classification, define each level with concrete code examples rather than adjectives.

Know

  • Explicit criteria beat vague instructions
  • "Be conservative" and confidence-based filtering do not improve precision the way categorical criteria do
  • High false positive rates in one category undermine trust in accurate categories

Be able to

  • Write criteria that name what to report (bugs, security) and what to skip (minor style, local patterns)
  • Temporarily disable a high-false-positive category while improving its prompt
  • Define severity levels with concrete code examples for each level

Anti-patterns

  • Asking for high-confidence findings instead of defining what qualifies
  • Describing a topic when you meant to describe a test
  • Leaving a noisy category enabled and hoping developers filter it themselves
4.2

Apply few-shot prompting to improve output consistency and quality

When detailed instructions still produce inconsistent output, few-shot examples are the most effective next move. They are especially strong on ambiguous cases — which tool to pick for a request that could go either way, what counts as a branch-level coverage gap — because they demonstrate a judgement rather than describing one.

Two to four targeted examples do more than a dozen generic ones, and the best of them show reasoning: why this action was chosen over the plausible alternative. That is what lets the model generalise to patterns you did not enumerate, instead of matching only the cases you listed.

In extraction work, few-shot examples reduce hallucination. Documents vary — inline citations versus bibliographies, methodology sections versus details buried in prose, informal measurements — and showing correct handling of that variety fixes the empty and null extractions that structural variation causes.

They also reduce false positives, by contrasting acceptable patterns against genuine issues.

Know

  • Few-shot examples are the most effective technique when detailed instructions alone produce inconsistent output
  • They are particularly useful for demonstrating handling of ambiguous cases
  • Examples enable generalisation to novel patterns rather than matching only pre-specified cases
  • They reduce hallucination in extraction across varied document structures

Be able to

  • Create 2–4 targeted examples for ambiguous scenarios showing why one action was chosen over a plausible alternative
  • Demonstrate the exact desired output format — location, issue, severity, suggested fix
  • Contrast acceptable code patterns with genuine issues to cut false positives while preserving generalisation
  • Show correct extraction from documents with varied structures to fix empty or null required fields

Anti-patterns

  • Adding examples to fix a problem whose root cause is a thin tool description
  • Listing many similar examples instead of a few well-chosen ambiguous ones
  • Showing the answer without the reasoning, so the model matches surface features
4.3

Enforce structured output using tool use and JSON schemas

Tool use with a JSON schema is the reliable way to get schema-compliant output. Define the extraction tool with the schema as its input parameters and read the structured data out of the tool_use response. JSON syntax errors stop being a category of failure.

tool_choice decides how firmly. "auto" permits the model to answer in text instead of calling anything. "any" requires a tool call but lets the model choose which — the right setting when several extraction schemas exist and you do not know the document type yet. Forced selection, {"type": "tool", "name": "extract_metadata"}, guarantees a specific extraction runs first, with enrichment following in later turns.

A strict schema removes syntax errors and nothing else. Line items that do not sum to the stated total, a value placed in the wrong field, an invented date — all of those are perfectly valid JSON.

Schema design has real consequences for hallucination. Make a field required when the source may not contain it and you have instructed the model to invent something; nullable optional fields let it say nothing. Add an "unclear" enum value for ambiguous cases and an "other" value with a detail string for categories you cannot enumerate in advance. Put format normalisation rules in the prompt alongside the schema — the schema constrains shape, not convention.

Know

  • Tool use with JSON schemas is the most reliable route to guaranteed schema-compliant output
  • tool_choice: "auto" allows text; "any" forces some tool; forced selection pins a named tool
  • Strict schemas eliminate syntax errors but not semantic errors
  • Required versus optional fields, enums with "other" plus a detail string, and nullable fields are the design levers

Be able to

  • Define extraction tools whose input schema is the output shape you want, then read tool_use
  • Set tool_choice: "any" when multiple schemas exist and the document type is unknown
  • Force a named tool when one extraction must run before enrichment steps
  • Make fields nullable when the source may not contain them, so the model reports absence instead of fabricating
  • Add "unclear" for ambiguity and "other" plus detail for extensible categories
  • State format normalisation rules in the prompt alongside the schema

Anti-patterns

  • Assuming a valid schema means a correct extraction
  • Marking fields required to "force completeness" and getting fabricated values
  • Leaving tool_choice on "auto" when structured output is non-negotiable
4.4

Implement validation, retry, and feedback loops for extraction quality

A retry with no new information is just a second roll of the dice. A retry that includes the original document, the failed extraction, and the specific validation errors gives the model something to correct against.

Know when retrying cannot work. Format mismatches and structural output errors respond to feedback. Information that simply is not in the document — because it lives in an external file you never supplied — will not appear on the third attempt either, and each attempt costs money.

Design validation the model can participate in. Extracting calculated_total alongside stated_total turns an invisible arithmetic error into a flagged discrepancy. A conflict_detected boolean lets the model report that the source contradicts itself rather than silently picking a side.

For the feedback loop that improves the system over time, add a detected_pattern field to each finding. When developers dismiss findings, you can then analyse which code constructs generate false positives instead of guessing.

Know

  • Retry with error feedback: append the specific validation errors to guide correction
  • Retries fail when the required information is absent from the source, as opposed to malformed
  • detected_pattern fields make dismissal patterns analysable
  • Semantic validation errors are a different class from schema syntax errors

Be able to

  • Send follow-up requests containing the document, the failed extraction and the specific errors
  • Identify up front whether a failure is recoverable by retry
  • Add detected_pattern to structured findings to enable false positive analysis
  • Extract calculated_total alongside stated_total, and add conflict_detected for inconsistent sources

Anti-patterns

  • Retrying identically and hoping for a different result
  • Burning retries on information that was never in the document
  • Treating schema validity as sufficient validation
4.5

Design efficient batch processing strategies

The Message Batches API costs 50% less, processes within up to 24 hours, and offers no latency SLA. Those three facts decide every question on this objective.

It fits non-blocking, latency-tolerant work: overnight technical debt reports, weekly audits, nightly test generation. It does not fit anything a person is waiting on, and a blocking pre-merge check is the canonical example — "usually faster than the limit" is not a guarantee you can put in front of developers waiting to merge.

One structural limit: batch requests do not support multi-turn tool calling. You cannot execute a tool mid-request and feed the result back.

Operationally, custom_id correlates requests with responses, which is also how you identify and resubmit only the documents that failed — chunking the ones that exceeded context limits rather than resubmitting the whole batch. When you have SLA maths to do, work backwards: a 30-hour commitment against a 24-hour worst case leaves 6 hours, so submissions every 4 hours keep you inside it. And refine the prompt on a sample before committing 100 documents, because iterative resubmission is where batch savings go to die.

Know

  • Message Batches API: 50% cost savings, up to 24-hour processing, no guaranteed latency SLA
  • Appropriate for non-blocking latency-tolerant workloads, inappropriate for blocking workflows
  • No multi-turn tool calling within a single batch request
  • custom_id correlates request and response pairs

Be able to

  • Match the API to the latency requirement: synchronous for blocking checks, batch for overnight and weekly analysis
  • Calculate submission frequency from the SLA and the 24-hour worst case
  • Resubmit only failed documents by custom_id, chunking any that exceeded context limits
  • Refine prompts on a sample before processing large volumes

Anti-patterns

  • Switching a blocking workflow to batch because it is "often faster"
  • Adding a timeout fallback to real-time, which is complexity standing in for a decision
  • Believing batch results cannot be correlated — that is what custom_id is for
4.6

Design multi-instance and multi-pass review architectures

A model that just generated code carries the reasoning that produced it. Asked to review its own work in the same session, it is disinclined to question decisions it just justified. Telling it to be critical does not remove the context; neither does extended thinking.

An independent instance, with no prior reasoning, catches subtle issues the author's session will not. This is the same reason human code review works.

The second architecture is multi-pass. A single pass over fourteen files dilutes attention: detailed feedback on some, superficial on others, and contradictory verdicts on identical patterns in the same PR. Split it — per-file passes for local issues, then a separate integration pass for cross-file data flow. A larger context window does not fix this, because the problem is attention quality, not capacity.

Where you need to route review effort, have the model report confidence alongside each finding so triage is calibrated.

Know

  • A model retains generation context, making self-review weak in the same session
  • Independent review instances outperform self-review instructions and extended thinking
  • Multi-pass review avoids attention dilution and contradictory findings

Be able to

  • Use a second independent instance to review generated code
  • Split large multi-file reviews into per-file local passes plus cross-file integration passes
  • Run verification passes where the model self-reports confidence per finding to route review attention

Anti-patterns

  • Upgrading the model or the context window to fix attention dilution
  • Requiring consensus across three identical passes, which hides intermittently-caught real bugs
  • Pushing PR size limits onto developers instead of fixing the review architecture