4.3 Production System Prompts, Few-Shot Design & Structured Outputs
Key Takeaways
Modular system prompts separate role, explicit decision criteria, domain policy, escalation triggers, and output contracts—and are version-controlled independently of application code
Clarify ambiguous decision boundaries and test changes against both positive and negative cases; do not assume recall remains unchanged.
Start zero-shot for straightforward tasks; use a small diverse set of examples (Anthropic suggests 3–5) for boundary or formatting ambiguity, and evaluate the gain.
JSON outputs use output_config.format; strict tool use constrains tool arguments. Handle refusals, truncation and schema limitations, and enforce semantic rules separately.
Allow explicit unknown or null states and test them; bounded validation and correction loops reduce, but cannot eliminate, unsupported values.
Production System Prompts, Few-Shot Design & Structured Outputs
Prototypes rely on monolithic prose prompts and fragile JSON.parse() regex wrappers. Production systems treat prompts as versioned software artifacts and enforce machine-checkable contracts at both the decoding layer and the application validation layer.
Modular System Prompt Architecture
A maintainable enterprise system prompt is structured into discrete, clearly delimited modules (commonly wrapped in semantic XML tags such as <role>, <decision_criteria>, <domain_policy>, <escalation_rules>, and <output_contract>):
| Prompt Module | Core Responsibility | Production Anti-Pattern |
|---|---|---|
| Identity & Scope | Defines persona, authority limits, and supported tasks | Vague "helpful expert" phrasing with unbounded scope |
| Explicit Decision Criteria | Enumerates concrete inclusion, severity, and exclusion rules | Asking Claude to "flag risky code" without defining benign exceptions |
| Domain Policy & Grounding | Embeds compliance rules and "cite-or-abstain" constraints | Allowing ungrounded priors to fill missing source facts |
| Escalation Rules | Specifies exact triggers to hand off or return needs_human_review | Forcing a definitive answer when evidence is contradictory |
| Output Contract | Clarifies semantic field definitions alongside JSON Schema | Duplicating raw syntax rules instead of explaining field semantics |
Cutting False Positives with Explicit Decision Criteria
When a security or compliance reviewer suffers from high false-positive rates, adding more adjectives ("be very careful and accurate") rarely helps. Instead, add explicit exclusion criteria inside <decision_criteria>—for example, distinguishing a parameterized ORM query from raw SQL concatenation, or explicitly exempting sanitized test fixtures. Clear boundary definitions may improve precision; measure recall on representative true-positive cases before deploying. A model review is advisory, and remediation decisions still need validated evidence and human review.
Version-Controlling Prompts Separately from Code
Hardcoding 3,000-token prompts inside application source files couples prompt iteration to full CI/CD binary rollouts. Enterprise architectures store prompts in dedicated versioned prompt registries (Git-backed YAML/Markdown artifacts tagged with semantic versions like claims-triage-v3.2.0), gate prompt edits against golden evaluation suites, and log the exact prompt_version alongside model_id in every telemetry trace for reproducibility and controlled rollback. Keep schema, prompt and application versions compatible and retain a tested rollback path.
Targeted Few-Shot Design
Zero-shot prompting supplies clear task instructions without worked examples. Begin there when the output and decision boundaries are straightforward. If evaluation exposes ambiguity or formatting drift, add few-shot examples curated for the actual use case:
- Start with 3–5 high-signal examples: Stuffing 15–20 nearly identical happy-path examples bloats input token costs, dilutes attention across the context window, and can encourage overfitting to superficial phrasing. Measure accuracy, recall and token cost.
- Prioritize negative and edge cases: Include at least one near-miss negative example (an input that superficially resembles a trigger condition but must be excluded under policy) and one abstention/null example showing how Claude should behave when required data is absent.
Structured Outputs & Strict Tool Schemas
Prompting "respond only in valid JSON without markdown fences" is never sufficient for production pipelines. Claude provides two grammar-constrained mechanisms on supported models/surfaces:
output_config.format(JSON Schema / Pydantic / Zod): Passing a JSON Schema viaoutput_config.format(or using first-party SDK helpers for Pydantic in Python and Zod in TypeScript) constrains generation to the supported JSON Schema subset for a normal completed structured response.strict: trueon Tool Definitions: Settingstrict: trueon tool schemas enforces the same constrained decoding on tool-use arguments—constraining generated arguments to the supported schema. The application must still check identity, authorization, domain constraints and side effects before dispatch.
Schema Design & Semantic Validation-Retry Loops
Grammar-constrained decoding addresses shape, not truth or permission. Check completion and refusal before accepting outputs: a safety refusal (even HTTP 200) or a max_tokens stop may not match the schema, and the official docs note a capitalization caveat for string enums/consts. Supported JSON Schema is a subset: for example numeric minima/maxima and arbitrary extra keys are not supported by constrained decoding. Revalidate locally and enforce domain rules.
1. Nullable Fields & Explicit Enums Represent Missing Evidence
Suppose an extraction schema marks contract_renewal_date as a required non-nullable string and risk_tier as ["low", "medium", "high"]. When an uploaded PDF omits the renewal date or lacks sufficient context to score risk, a normally completed constrained response must use an allowed value, which can encourage unsupported placeholders like "N/A", "2026-01-01", or guessed tiers.
- Fix: Define optional/uncertain attributes as nullable and include explicit uncertainty values inside enums (such as
"unknown"or"insufficient_evidence"), accompanied by a clear instruction: "Returnnullorunknownwhenever the source document does not state the value explicitly." Below is an schema fragment for theschemafield withinoutput_config.format(whose type isjson_schema):
{
"type": "object",
"additionalProperties": false,
"required": ["contract_renewal_date", "risk_tier"],
"properties": {
"contract_renewal_date": { "anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "description": "Date or null if absent" },
"risk_tier": { "type": "string", "enum": ["low", "medium", "high", "unknown"] }
}
}
Setting additionalProperties: false alongside explicit required arrays constrains output keys while giving the model a valid missing-data state (null or "unknown") whenever evidence is absent.
2. Semantic Validation-Retry Loops
JSON Schema cannot verify that subtotal + tax == invoice_total, that a discharge_date occurs on or after admission_date, or that a generated sku_code exists in the catalog. Production pipelines wrap Claude calls in a bounded semantic validation-retry loop:
- Parse & Validate: After a completed response, parse and verify the JSON from
output_config.formatand run deterministic domain validators (arithmetic checks, date ordering, database foreign-key lookups). - Targeted Error Feedback: If a rule fails, append a concise, structured error message to the conversation (e.g.,
Validation error: line_item_sum (412.50) does not equal invoice_total (432.50); re-extract line items and verify totals) and retry. Returning the exact failing field path and expected invariant gives a concrete correction target; measure whether the retry actually improves quality. Do not retry a safety refusal as a format error. - Bounded Retries & Escalation: Cap retries according to deadline and cost (for example, two or three attempts) (and optionally escalate the final retry to a higher tier such as Sonnet 5.5 or Opus 5.5 if the first pass used Haiku 5.5) to prevent runaway token loops; if semantic validation still fails, route the payload to a human-review queue with the validator diagnostics attached.
Choosing reasoning and output techniques
Prompt diagnosis begins with evidence: unclear label criteria call for concrete boundaries and examples; missing input data calls for authorized retrieval or abstention; invalid structure calls for a supported structured-output contract. For complex reasoning on current models, tune native thinking/effort and request a concise, evidence-based explanation, not the model’s private internal reasoning. A supported legacy model without native thinking may benefit from a worked-method example. Do not assume that appending lengthy reasoning instructions improves every task. Evaluate the simplest technique that solves the observed failure.
Structured output and native document citations cannot be enabled together in the same Messages request: the API rejects that combination. If both are needed, separate evidence extraction from structured validation, preserving source IDs and checking their support. Avoid sensitive data in schema property names, enum choices, or examples: compiled schemas have a separate cache lifetime. On HIPAA-ready configurations, the official guidance excludes PHI from schema definitions.
Official references
A defensive database code-review assistant flags 40% of legitimate migrations as security concerns. Which prompt change should the team evaluate to reduce false positives while retaining detection of genuine security concerns?
Clarify inclusion/exclusion criteria and add a few vetted boundary examples, then measure both precision and recall.
Remove the system prompt's formatting instructions and raise temperature to 0.9 so the model explores alternative interpretations
Prepend 25 happy-path SQL-injection examples at the top of the system prompt while leaving decision rules implicit
Set strict: true on tool schemas so the model stops emitting markdown explanations
A healthcare-intake extractor uses output_config.format with a JSON Schema requiring discharge_date as a non-nullable string and insurance_status as an enum of ["active", "expired"]. On normally completed responses for outpatient records that have no discharge date or insurance card, Claude frequently outputs "1900-01-01" and "expired". What is the root cause and proper fix?
JSON Schema validation is ignored on output_config.format unless effort is set to "max"
Switching from Pydantic to raw regex post-processing allows Claude to omit required fields gracefully
The schema does not represent missing data; allow a nullable discharge date and an explicit unknown insurance status, and validate against the source.
Adding stop_sequences: ["1900"] prevents Claude from hallucinating dates while keeping the schema non-nullable
An accounts-payable pipeline uses output_config.format and normally completed responses parse as valid JSON, yet 4% of extractions fail downstream ERP ingestion because extracted line_items do not sum to invoice_total or cite non-existent vendor IDs. Which architecture pattern resolves this cleanly?
Replace output_config.format with free-form XML output because XML supports arithmetic expressions
Run deterministic server-side business validators and pass exact validation error messages back to Claude in a bounded 2–3 attempt retry loop before human escalation
Increase top_p to 0.99 and run an infinite retry loop until the ERP accepts the JSON payload
Embed the entire 500,000-row vendor table directly into the system prompt on every single request without caching
A platform team wants rapid iteration on prompt wording, rigorous regression gating, and instant rollback across 12 microservices without waiting for container rebuilds and binary deployments. How should system prompts be managed?
Inline prompt strings inside compiled service binaries so prompts and code always share a single build artifact
Let each microservice fetch unversioned prompt drafts from a shared mutable wiki page at runtime
Allow end users to pass the entire system prompt inside the client request payload to avoid server deployments
Store modular prompts in a separate version-controlled prompt registry with semantic versioning, automated eval gates, and prompt_version telemetry logging
Sections you finish are checked off in the contents.