Chapter 2. Examples and structure

Learning objectives

  • Explain that examples teach accidental patterns alongside intended rules, and identify and eliminate accidental patterns.
  • Construct few-shot examples based on criteria of relevance, diversity, and format consistency, and separate examples from evaluation data.
  • Demarcate boundaries among instructions, context, examples, and inputs using XML tags.
  • Select formats suited to the consumer of the output (human, system, voice), and define data dictionaries and representations for missing values.
  • Choose appropriate methods among instructions, examples, and structured outputs for machine-readable output, and separately verify format compliance and content accuracy.
  • Migrate prompts that relied on prefill to methods suited to modern models.

Introduction

A mail-order company created a prompt to classify product inquiries into four categories: "Shipping, Exchange, Payment, Other." The person in charge included four examples, and by chance, all four examples were polite sentences starting with "Hello." Once operations began, inquiries written briefly without greetings were driven into "Other," and dozens of inquiries detailing urgent circumstances were left unattended for more than a day. The person in charge only identified the cause a week after the person handling "Other" complained about an increased workload. Along with the classification criteria that the person in charge intended to teach, the model had also learned an unintended rule: "It must be a polite sentence to be a formal inquiry." What caused the bias was not the instructions written by the person in charge, but the examples chosen by that person. Examples are the most powerful instructions, and at the same time, the most difficult instructions to control.

This chapter begins with the conditions for good examples, diversity design, boundary cases, procedures for reducing bias, and the separation of examples and evaluation data. Next, it examines tags that demarcate boundaries between instructions and reference materials, formats suited to consumers, data dictionaries and representations of missing values, the scope of guarantees and limitations of structured outputs, alternatives to prefill, and the design of rationale fields. In Going deeper, it addresses examples that demonstrate methods to models with thinking capabilities, as well as formatting issues depending on display environments.

Key concepts

Examples are sample clothes handed to a tailor

Handing a tailor several sample shirts is far more precise than telling them "a neat shirt." However, if all the samples are white short-sleeved shirts, the tailor may misunderstand that the customer only wants white short-sleeved shirts. The same applies to few-shot examples (the method of showing a few pairs of inputs and desired outputs). Anthropic guides identify examples as one of the most reliable ways to adjust the format, tone, and structure of output. However, the model also learns unintended patterns hidden in the examples.

Before including examples, writing down "what this set of examples teaches" in two columns makes the risks visible.

What is intended to be taught What may be taught accidentally
Classification criteria (which inquiries are exchanges) Sentence length, presence of greetings, honorific usage
Output format (single-word label) Frequency of specific labels (three out of four are shipping)
Tone (matter-of-fact explanation) Expressions repeated across examples, proper nouns, numerical magnitudes

If what is written in the right column is not evenly mixed across the examples, the model may accept it as a rule.

Conditions for good examples

Condition Meaning Basis
Relevance Examples resembling inputs that will actually be received Anthropic guides
Diversity Including boundary cases and being sufficiently distinct from one another so as not to teach unintended patterns Anthropic guides
Structure Wrapped in <example> and grouped under <examples> for multiple items to distinguish them from instructions Anthropic guides
Format consistency Identical structure across all examples, down to delimiters, tags, and line breaks Gemini guides

Regarding quantity, different vendors place emphasis on different points. Anthropic recommends 3 to 5, adding that models can be prompted to evaluate the relevance and diversity of examples or to generate additional examples. Gemini guides recommend always including examples, but warn that too many examples can cause overfitting, where responses align excessively with the examples. OpenAI best practices for reasoning models advise attempting without examples (zero-shot) first. Conversely, Google documentation explains that including hundreds of examples in a long context (many-shot) achieved performance comparable to fine-tuned models on specific tasks. In summary, the principle is "vary the content, standardize the format, determine the count through experimentation." Increase examples incrementally while measuring against the same evaluation set, and stop when scores plateau or outputs begin to mimic example sentences.

A table for designing diversity

"Diverse" is an unmeasurable expression, as seen in Chapter 1. When choosing examples, break down diversity across dimensions and fill out a table.

Dimension Check question
Label Does every label appear at least once? Does it not deviate significantly from real-world proportions?
Length Are short inputs and long inputs mixed?
Style Are polite texts, short notes, and texts with typos mixed?
Boundary Are there inputs that straddle two labels?
Exception Are there inputs with missing information or irrelevant inputs?
Order Do identical labels not appear consecutively? Is the final example not fixed to a specific label?

Blank cells in the table represent the examples that need to be found next. Find inputs matching the blank cells from actual logs, but remove personal information before including them.

Boundary cases and contrastive pairs

The model already answers easy examples correctly. What teaches the criteria of judgment are ambiguous examples. Is "The box is crushed, but I haven't opened the product yet" a shipping issue or an exchange request? Showing such boundary cases with their correct answers teaches the model where the dividing line between the two categories lies.

To make boundaries clearer, use contrastive pairs. These are pairs where two nearly identical inputs receive different labels due to a single subtle difference.

<examples>
  <example>
    <input>One heel of the shoes I received has fallen off. Please exchange it for the same size.</input>
    <label>Exchange</label>
  </example>
  <example>
    <input>One heel of the shoes I received has fallen off. I just want my money back.</input>
    <label>Refund</label>
  </example>
</examples>

Caution is required when demonstrating incorrect outputs as examples. Showing incorrect formats at length leaves a strong trace in the context, which the model may inadvertently imitate. If negative examples are strictly necessary, keep them brief, label them with "do not do this" along with a reason, and place the correct example immediately after. The baseline is to demonstrate the desired outcome.

Procedure for reducing example bias

Example bias is a phenomenon where imbalances in a set of examples skew the model's judgment. There are three common types: cases where an overrepresented label skews predictions toward that label, cases where the order of examples or the final example pulls the outcome, and cases where the wording of examples is copied verbatim. Diagnose and mitigate it through the following procedure:

  1. Confirm symptoms numerically. Compare per-label accuracy and output label distribution with the actual distribution. If a specific label appears more frequently than in reality, it indicates skew.
  2. Map examples against the diversity table. Check whether the skewed label is also overrepresented in the examples, and whether style or length is concentrated on one side.
  3. Change only one thing at a time. Alter one factor among balancing labels, shuffling order, or mixing styles, and measure again against the same evaluation set.
  4. Check for copying. In generation tasks, count sentence overlap between outputs and examples. If there is overlap, differentiate the phrasing across examples, and state with justification: "Examples are provided to illustrate structure and tone; do not copy sentences verbatim."
  5. Do not compensate with rules. Follow the advice of the Anthropic context engineering article by prioritizing a representative set of examples over a long list of exceptions.

Do not mix examples with evaluation data

The source for selecting examples and the source for building evaluation sets are often the same logs. If inputs used as examples remain in the evaluation set, the model ends up resolving problems for which it has already seen the answers, resulting in scores higher than reality. The sequence is as follows: first, set aside and lock the evaluation inputs, and then choose examples to populate the diversity table from the remaining inputs. Whenever examples are changed, verify that they do not overlap with the evaluation inputs. In Chapter 5, this principle is revisited as "Separation of improvement sets and validation sets."

Demarcate boundaries with XML tags

When instructions, reference materials, examples, and user inputs are mixed in a prompt, the model can mistake sentences within reference materials for instructions. Anthropic guides explain that wrapping each category of content in tags such as <instructions>, <context>, and <input> reduces misunderstandings. Tags serve a role similar to tab dividers in a file folder.

<instructions>
Read the quote request email and extract requested items and preferred delivery dates.
</instructions>
<price_policy>
Quote validity period is 30 days from the date of issue.
</price_policy>
<email>
{{CUSTOMER_EMAIL}}
</email>

The principles for using tags are straightforward:

  • Tag names are not fixed. Choose names that clearly convey the enclosed content, and keep chosen names consistent throughout.
  • Nest content that has hierarchy. For multiple documents, place <document index="1"> inside <documents>, and metadata can be attached via XML attributes to reference them in instructions, as in OpenAI guides.
  • The role of tags ends at boundary demarcation. Output formats must be defined separately, and tags do not serve as security barriers. If external data may contain strings like </email> that could break boundaries, wrapping them in JSON is safer, as covered in Chapter 3.
  • Both OpenAI and Anthropic also mention Markdown headings as a means of section demarcation. Standardize on one approach within a single prompt.

Choose a format suited to the consumer

When determining a format, the first question to ask is "Who is receiving this output?"

Consumer Appropriate format Points to note
Human reading on a screen Paragraphs, tables and lists only when necessary Verify whether the display environment renders Markdown
Human reading on printed material Paragraphs with headings, tables Source names instead of links
Read aloud by voice Short declarative sentences Explicitly state reasons for prohibiting symbols, parentheses, abbreviations, and tables
Parsed by a system Schematized formats such as JSON Enforce with structured outputs, separate from human-readable explanations
Pasted into a spreadsheet CSV or tab-delimited Processing rules for values containing commas, line breaks, or quotation marks

If human-readable explanations and system-readable data must be received together, place explanations in designated tags and data in separate fields, or split the calls. If explanatory sentences are inserted between data, the parser breaks.

Data dictionary and missing-value representations

If only field names are decided without defining their meanings, different people and different requests will populate the same field differently. Build a data dictionary before writing a schema.

Field Business meaning Type/Unit Allowed values When missing
requested_items Items for which the customer requested a quote String array Codes present in the item code table Empty array []
due_date Delivery date requested by the customer Date (YYYY-MM-DD) After today null
urgency Urgency expressed in the email String high, normal unknown if indeterminable

In particular, it is important not to lump "none" into a single catch-all. Cases where information is absent from the source text, cases where the item itself does not apply, and cases where insufficient evidence prevents a determination have different meanings in downstream workflows. Define these three as distinct values, and document them in both the instructions and the schema descriptions. If only required string fields are defined, the model attempts to fill in plausible values even when information is missing. Schemas must be designed to allow null for fields that may lack values.

Structured outputs: Features that enforce format

There are three levels of methods for fixing output formats.

Method Guarantee level Suitable situation
Requesting format via instructions Generally followed, but no guarantee Human-readable output
Demonstrating format via examples Consistency increases When style and composition must also align
Structured outputs (JSON schema) Enforces schema compliance Output that systems immediately read and store

OpenAI documentation distinguishes between JSON mode and structured outputs. Both produce valid JSON, but only structured outputs guarantee schema compliance, and it is recommended to use structured outputs whenever possible. Vendor requirements differ slightly.

Vendor Configuration Key points to know
OpenAI json_schema with strict: true in text.format of the Responses API, or strict mode in function calling All fields must be required, optional fields are expressed as unions with null, and all objects require additionalProperties: false. Output follows the key order of the schema
Anthropic output_config.format (JSON output) and strict: true in tool definitions Complies with schemas via constrained decoding. Certain constraints like minimum, maximum, minLength, and maxLength are not supported, resulting in a 400 error if sent directly to the API; most SDK helpers send these as descriptions, and helpers that validate responses re-check against original constraints. Required properties appear first, followed by optional properties
Google Specify JSON for response and provide a schema Supports only a subset of JSON schema. Guides advise always validating values in the application even if the output is syntactically valid

For classification tasks, define allowed labels as an enum. Anthropic documentation recommends using tools with enum fields or structured outputs for classification, advising that case sensitivity of enum values is not guaranteed, so comparisons should be case-insensitive and values differing only by case should be avoided.

Format compliance and content accuracy are different

What structured outputs guarantee is the shape. They do not guarantee that the content is correct. OpenAI documentation explicitly states that structured outputs can still contain mistakes, and recommends refining instructions, providing examples, or breaking tasks into simpler subtasks. Therefore, machine-readable output is verified in four stages:

  1. Syntax: Does it parse as JSON?
  2. Schema: Are fields, types, and enums correct? Constraints that could not be enforced due to lack of support (maximum values, lengths) are verified here via code.
  3. Business rules: Is the delivery date after today? Is the item code in the code table?
  4. Source text cross-check: Are the values actually present in the source text? Verify by drawing samples for human review or through source text string searches.

Caution

Structured outputs also have exceptions. If the model refuses a request for safety reasons or is truncated due to output limits, the result may not conform to the schema. In such cases, Anthropic returns a stop_reason of refusal or max_tokens, and OpenAI reports this via a refusal field or an incomplete status. Check the termination reason before parsing.

Principles of prefill and alternatives

Prefill is a technique of populating the beginning of the assistant message in advance so that the model continues from there. For example, if the final assistant message is populated with {, the model continues writing the remainder of the JSON. It was a method of locking the opening step by exploiting the model's property of generating text by predicting the next token.

According to Anthropic documentation, from the Claude 4.6 models onward (and in Claude Mythos Preview), prefill on the final assistant turn is no longer supported, and such requests return a 400 error. Earlier models still support prefill, and inserting assistant messages in the middle of a conversation remains unaffected. The documentation explains that improvements in model instruction-following have rendered prefill unnecessary for most use cases, and outlines migration paths by use case.

Use case of prefill Alternative method
Enforcing JSON or classification formats Structured outputs, tools with enum fields. One can also first request format adherence and use this in conjunction with retries
Eliminating preamble phrasing System instructions stating "Answer immediately without preamble," outputs inside tags, structured outputs, or tool calls. Occasionally remaining preambles are removed via post-processing
Avoiding unnecessary refusals Clear instructions inside the user message are sufficient
Continuing truncated responses Place the tail end of the previous response in the user message and request continuation, or resend the request
Reminding context in long conversations Place reminder content in the user turn, or introduce it during tool calls or context compression phases

Prefill is the first item to inspect when changing models. Because the failure points are explicit, it is easy to locate, but determining what should replace what prefill used to do must be decided separately by use case, as shown in the table above.

Rationale fields as brief explanations

There are many occasions where one wants to receive a rationale alongside a determination result. In such cases, two aspects must be designed. The first is the order of fields. Because models generate text from the front, having them write the rationale first and the determination later grounds the determination in the rationale. OpenAI structured outputs follow the key order of the schema, while Anthropic outputs required properties first; therefore, to preserve order, make all properties required or parse with reordering in mind.

The second is what is demanded of the rationale field. In recent Claude models equipped with thinking capabilities, requesting step-by-step thinking processes in fields like reasoning, thinking, or trace can result in refusals categorized under reasoning_extraction. Official documentation advises requesting brief explanations or evidence supporting the result instead. Field names should also be chosen to reflect what is desired, such as evidence or explanation. This topic is revisited in Chapter 4.

Give directions instead of procedures to thinking-enabled models

Default values for thinking capabilities differ across models. Based on Anthropic documentation, for Opus 4.6 to 4.8 and Sonnet 4.6, omitting the thinking parameter turns thinking off, whereas for Opus 5, Sonnet 5/5.5, and Haiku 5.5, it is enabled by default. For Fable 5/5.1, Mythos 5/5.1, and Opus 5.5, it is always enabled regardless of parameters. When migrating models, check first whether existing prompts were written assuming models with thinking disabled.

With thinking-enabled models, two habits must be discarded. One is handcrafted step-by-step plans. Anthropic recommends general instructions over prescriptive steps. It explains that a single line saying "consider thoroughly" often yields better reasoning than handcrafted step-by-step plans. The other is instructions demanding that reasoning be written out in the response body. Requesting that reasoning be written inside <thinking> tags in recent Claude models can lead to request refusals. Anthropic recommends entrusting the process to thinking with a reduced effort level instead of such instructions. Google also notes that reasoning models generally do not need to lay out reasoning steps in the response body.

According to OpenAI reasoning model guides, reasoning models frequently produce good results even without few-shot examples. They still advise using delimiters; Markdown, XML tags, and section titles are examples. Google guides also consider XML-style tags or Markdown headings effective, and advise placing questions at the very end when providing extensive materials. The role assigned to examples changes as well. Defer the shape of the answer to the schema. Structure examples as "problem, method to apply, expected answer" to demonstrate the method the model should follow within its thinking block.

Suppose a claim review prompt contained a twelve-line procedure and a sentence saying, "Write your judgment process inside <thinking>." When migrating to Opus 5.5, the procedure was reduced to a single line: "Thoroughly compare the terms and the claim to determine whether to pay." Below that, two worked examples applying company-specific rules (requesting additional documentation for three or more outpatient visits) were appended, and the <thinking> instruction was removed.

New settings for structured outputs and deprecated sampling parameters

As of 2026-11-01, Anthropic structured outputs is a generally available feature. The schema is provided in output_config.format by specifying type as json_schema, without attaching beta headers. The output_format parameter from the beta period has been marked for deprecation. To continue using it, the structured-outputs-2025-11-13 beta header must be attached separately. Do not leave legacy code as is simply because it still runs; migrate it to the new location.

It is also time to retire the habit of lowering temperature to enforce format. The Claude API removed temperature, top_p, and top_k in version 2026-10-21, and sending these values returns a 400 error. Gemini 4 Argon ignores these three values even if it receives them. In effect, requests fail on one side and pass through without effect on the other. Teams calling both vendors should remove these three values from shared invocation code. While the deprecated Gemini 3 developer guides still retain recommendations to maintain a temperature of 1.0, do not use them as a rationale for configuring new models.

The stability previously sought by lowering temperature is distributed across the methods in this chapter. Structured outputs take charge of format, examples with identical formatting handle style and composition, and four-stage verification ensures value accuracy.

Suppose order extraction code at a logistics company was sending a beta header, output_format, and temperature: 0 together. There were three areas to modify: the header and temperature were removed, and the schema was moved under output_config.format. The "consistent shape every time" that relied on temperature 0 was something guaranteed by the schema from the outset. Whether values fluctuate was checked separately using source text cross-check samples.

Thinking tokens count toward the output limit

Gemini 4 Argon (gemini-4-argon) is Google's latest model as of 2026-10-27. The max_output_tokens of this model does not measure only the response length. It is an overall ceiling combining thinking tokens and output tokens, and the response is cut off the moment it is exceeded. If limits were set based solely on JSON length in earlier models, inputs triggering extended thinking will be truncated before the JSON closes. Because structured outputs cannot force truncated responses into schema compliance, check the termination reason first, as cautioned in the section on structured outputs.

Thinking levels consist of three tiers—low, medium, and high—with medium as the default. Google recommends evaluating across all three levels and selecting the lowest level that exceeds quality standards. This follows the same approach used to determine the number of examples. Fix the evaluation set, vary only the level, and count accuracy, format errors, and truncation occurrences together. Because raising the level increases thinking tokens and causes truncation under the same limit, determine the thinking level and max_output_tokens as a pair. Factor in that explicit caching is not supported when calculating costs. Designs that reduced costs by placing long sets of examples in explicit cache cannot be used as-is with this model.

Suppose a real estate brokerage platform set max_output_tokens to 300 while extracting area, floor number, and maintenance fees from property listings. While 120 tokens were sufficient for the JSON, listings where thinking exceeded 180 tokens at the medium level caused the JSON to be cut off midway. The practitioner ran the same evaluation set across all three levels. When accuracy exceeded criteria even at low, low was chosen. The limit was reset with a margin after checking the distribution of thinking tokens.

Going deeper

Show the method to models with thinking capabilities

Examples remain effective even in models with thinking capabilities. Anthropic documentation explains that worked examples shape how the model approaches similar problems inside its thinking block, and recommends presenting each example as “problem, method to apply, expected answer”. Examples that show only the input and the answer teach only the shape of the answer, but examples that also show the method teach procedures that the model cannot know through general knowledge, such as company-specific calculation rules.

Example format What it teaches Risk
Input → Answer Format and size of the answer Skew toward producing numbers similar to the example answer
Input → Method → Answer Rules and sequence to apply Tokens increase as examples become longer

Even when showing the method, instructing the model to extract the final answer only from a designated field or tag prevents parsing from breaking due to explanations and answers getting mixed together.

The display environment determines the formatting

If the default formatting of the model does not match the display environment, users will see the symbols as they are. A typical example is asterisks and hashes appearing on a screen that cannot render Markdown. Anthropic documentation notes that modern models use LaTeX by default for mathematical expressions, and provides example phrasing to format mathematical formulas using only symbols such as /, *, and ^ instead of LaTeX or MathJax when plain text is needed.

When fixing formatting issues, the principles from Chapter 1 apply directly.

  1. State the desired format instead of prohibitions. Use “in smooth paragraphs” rather than “no Markdown”.
  2. Attach a reason. “This screen cannot render formatting, so asterisks appear as literal characters.”
  3. Match the prompt's formatting to the desired output. If plain text output is desired, remove headings and bullet points from the prompt as well.
  4. Keep post-processing as a last resort. Removing symbols with regular expressions can also delete intended symbols (such as multiplication signs in formulas).

At work

Sunrise Clinic: Turning reception memos into chart fields

Sunrise Clinic, a local clinic, sought to pre-fill electronic medical chart fields with symptoms, onset, and current medications extracted from memos written by nurses at the reception counter. The initial prompt was “Extract information as JSON from the following memo” along with two examples. In operation, the onset field name occasionally changed to start_date, and when there were no current medications, the field was omitted entirely. When the memo stated the onset only as “from a few days ago”, a specific fabricated date was entered.

Assistant Manager Seo of the information team divided the causes into three categories. First, because both examples were memos that had current medications and clear onsets, they failed to demonstrate what “cases with none” and “ambiguous cases” should look like. Second, instructions and examples alone could not guarantee field names or field presence. Third, because onset was a required date field, the model had no way to leave the value empty.

Assistant Manager Seo first created a data dictionary. onset was defined as “the symptom onset time stated by the patient”; if a date was present in the memo, it was recorded as a date, but if there was only a relative expression such as “three days ago”, the original expression was placed as is into onset_text and onset was set to null. For current medications, a distinction was made between “stated as none” (an empty array) and “not mentioned in the memo” (null). This was because the latter was precisely what nurses needed to ask about during the subsequent medical interview.

Next, the examples were expanded to four in accordance with a diversity table. These were a memo stating that there were no medications, a memo with no mention of medications, a memo where the onset was a relative expression, and a memo with multiple symptoms. All four examples used the same tags and the same field order. The original memo text was wrapped in <memo> tags to separate it from instructions. Because the chart input was read directly by the system, the schema was enforced using structured outputs, and onset was modified to allow either a date or null.

One team member suggested inserting the reception date if a date could not be extracted, but Assistant Manager Seo rejected the idea. The reception date was not the symptom onset date, and if a plausible value were filled in, the physician might overlook it without verification. Finally, the finish reason was checked first so that the chart was populated only upon normal completion, and nurses were asked to cross-check a sample of ten cases per day against the original text. Afterward, instances of field names changing or being omitted disappeared, and no fabricated dates appeared in the sample. The key was dividing the roles so that examples handled decision boundaries, the schema handled the shape, and the data dictionary handled the semantics.

Corner Office: Fixing skew in facility complaint classification

Corner Office, a coworking space operator, automatically assigned facility complaints submitted by tenant companies via an app to responsible teams by classifying them into five labels: “equipment failure, cleanliness, noise, access and security, other”. During two weeks of pilot operation, complaints from team leads accumulated. Irrelevant complaints flooded the facilities team, while noise complaints were repeatedly diverted to “other”.

Operations Planning Manager Cha compared the model’s classifications with 400 cases that had been reclassified by humans. The model selected “equipment failure” far more often than was actually the case. Checking the examples against a diversity table revealed the cause. Three out of the five examples were equipment failures, all five were long polite sentences, and the final example was also an equipment failure. In contrast, more than half of the actual complaints were short phrases, such as “too noisy next to the 3rd floor meeting room”.

Before making changes, Manager Cha set aside and locked 150 of the 400 cases for evaluation. From the remaining 250 cases, examples were selected to fill the empty cells of the diversity table. At least one example was included for each label, covering both short and long texts, along with two borderline cases. One was “The air conditioner is so loud that I cannot make phone calls,” which appeared to be noise, but was an equipment failure because the cause was equipment. The other was “Someone is continuously talking loudly on the phone in the hallway,” which was noise. A short rationale was attached to both examples alongside the label: “If the cause is equipment, it is an equipment failure.” The order of the examples was also shuffled so that the same labels did not appear consecutively.

Because the assignment system read the output directly, label was enforced as an enum using structured outputs, and a brief extract of the phrasing in the complaint that served as the basis for the decision was placed into an evidence field for the team lead to review. No field was created for writing out the thinking process.

During the review meeting, someone suggested adding exception rules for each label, but Manager Cha decided to first evaluate a version that only changed the example composition. This was because changing rules and examples at the same time would make it impossible to determine what produced the effect. When compared using the locked 150 cases, the accuracy rate for noise complaints increased significantly and the skew toward equipment failure decreased. Most of the remaining errors were at the boundary between “other” and different labels, and Manager Cha singled out only those types to record them as targets for the next revision.

Common mistakes

  • The more examples, the better. Increasing the same type only strengthens skew, and having too many leads to overfitting. Determine the number through experimentation.
  • As long as the examples are good, the evaluation can also be trusted. If inputs used as examples are mixed into the evaluation set, the score appears inflated. Set aside evaluation inputs first.
  • Using tags in the input also structures the output. Output format must be specified separately, and output intended for machine consumption must be enforced with a schema.
  • JSON mode guarantees fields as well. JSON mode guarantees only syntax. Fields and types are guaranteed by structured outputs.
  • If the schema is followed, the values are also correct. Structured outputs guarantee only the shape, not the content. Business rules and cross-checks against the original text must be validated separately.
  • Making a field required eliminates omissions. If a field is made required when information is absent, plausible values will be hallucinated. Allow null for values that may be absent.
  • Prefilling works everywhere. In the latest Claude models, it causes a 400 error. Migrate to purpose-specific alternatives.

Summary at a glance

Topic What to remember
Power and risks of examples Teaches format, tone, and boundaries most reliably, but also teaches accidental patterns
Good examples Relevance, diversity, structure, with identical format for all. Determine the count through experimentation
Reducing bias Check with metrics → diversity table → change one by one → check for copying
Data separation Set aside evaluation inputs first, then select examples from what remains
Tags Consistent and descriptive names, nested hierarchy. Demarcates boundaries, not a security barrier
Data dictionary Semantics, types, permitted values, missing data rules. Distinguish none / not applicable / cannot determine
Structured outputs Enforce schema compliance. Vendor-specific constraints vary, and refusals or truncations are exceptions
Four-stage validation Syntax → schema → business rules → cross-check against original text
Prefilling 400 error from Claude 4.6 onward. Replace with structured outputs, direct instructions, and tags

Check the official docs

Self-check

2-1. Give two examples each of "what examples are intended to teach" and "what they might inadvertently teach."

2-2. You have only a single log source from which to select examples and create an evaluation set. State how you should order the work, and explain what problems arise if you reverse that order.

2-3. Rewrite "Draft a reply to the event inquiry below. If it rains, the event will move to the indoor gymnasium. Inquiry: …" using tags so that instructions, policy, and input are separated.

2-4. You are exporting the same sales performance data for (a) an executive reporting screen, (b) an in-store announcement, and (c) loading into an inventory system. State the appropriate format and one precaution for each.

2-5. In a business trip expense report, there is a field that extracts a "list of companion names" (an array of strings). Decide what values to use to represent each of the following cases and state the reason: when it explicitly states there were no companions, when whether there were companions is not written at all, and when the handwriting is smudged and illegible.

2-6. State two cases where a response might not match the schema even with structured outputs enabled, and what to check before parsing.

2-7. Suppose there are three prompts that used to prefill the final assistant message. Their purposes were (a) outputting only a single label, (b) removing greetings at the beginning of the response, and (c) continuing a long text that was cut off. State what to replace each of them with when migrating to the latest Claude models.

Hands-on tasks

Exercise

Example Configuration Comparison Experiment (45 minutes)

  1. Create a prompt that classifies inquiries or feedback into three categories.
  2. First write down separately 20 test inputs you created yourself (including 6 edge cases). Do not use these 20 as examples.
  3. Create Version A with no examples, Version B with 3 examples covering only a single category, and Version C with 4–5 examples mixing all three categories, edge cases, writing styles, and lengths.
  4. Pass the 20 test inputs to all three versions, and organize in a table the total number of correct answers, the number of correct answers on edge cases, and the output label distribution for each version.

Done when: You confirm the label skew of Version B and the number of correct answers on edge cases in Version C in the table, and write the reason in a single line if the results differ from expectations.

Exercise

Data Dictionary and Schema Design (40 minutes)

  1. Choose one among receipts, application forms, or emails, and select five fields to extract.
  2. For each field, write down its business meaning, type/unit, allowed values, and value when absent in a data dictionary table. Distinguish between at least two of the following: absent, not applicable, or indeterminable.
  3. Convert the data dictionary into a JSON Schema. Make classification fields an enum, and allow null for fields that may be absent.
  4. Obtain results for five inputs, including three inputs with partially missing information, and perform the 4-step check (syntax, schema, business rules, source text comparison) yourself.

Done when: 4-step check results remain recorded in a table for all five results, and not a single fabricated value is present across the three inputs with missing information.