This prompt is designed for integration engineers and developers who need to enforce strict output contracts—JSON, XML, CSV, or custom schemas—from an LLM in production. The core job-to-be-done is teaching the model to recognize and avoid specific, subtle schema violations that are difficult to describe with abstract rules alone. You should use this prompt when you have a well-defined output schema, a history of format drift or malformed outputs in production, and a set of known failure modes (e.g., missing required fields, incorrect enum values, wrapping objects in an extra array, or using the wrong data type). The ideal user is someone who has already tried schema descriptions and response_format parameters but still sees intermittent conformance failures under load or with edge-case inputs.
Prompt
Structured Output Schema Violation Counterexample Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Structured Output Schema Violation Counterexample Prompt.
This approach is not a replacement for a validation layer; it is a complement to it. You should not use this prompt when you lack concrete examples of real failures, as fabricated or generic counterexamples can confuse the model and degrade performance on valid inputs. It is also the wrong tool if your primary problem is ambiguous user intent rather than output structure. In high-risk domains such as healthcare, finance, or legal applications, the counterexamples must be reviewed by a domain expert to ensure they do not inadvertently teach the model to omit critical information or alter factual content in the pursuit of schema compliance. Always pair this prompt with a post-generation validation harness that can reject non-conforming outputs and trigger a retry or repair workflow.
Before implementing, gather at least three to five real examples of schema violations from your logs or test suite. These should represent the most frequent and impactful failure modes, not edge cases that occur once in a million calls. The prompt works by pairing a valid output with a deliberately malformed version of the same output, clearly labeling the violation. This contrastive approach teaches the model the boundary between acceptable and unacceptable structure more effectively than a list of rules. After deploying, monitor your schema conformance rate and be prepared to rotate counterexamples as the model's failure modes shift over time.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if a counterexample-driven schema enforcement approach is the right fit for your integration.
Good Fit: Strict API Contracts
Use when: You are integrating with a downstream system that rejects malformed JSON, XML, or CSV. Why: The prompt teaches the model to recognize and avoid common structural violations by pairing valid outputs with deliberately broken counterexamples. Guardrail: Always run a schema validator before the model response reaches your API client.
Bad Fit: Free-Form Creative Text
Avoid when: The output is prose, markdown, or unstructured natural language without a strict schema. Why: Negative examples for format violations add token overhead without benefit and can confuse the model into over-refusing legitimate stylistic variation. Guardrail: Use this pattern only when a machine-readable schema is the primary contract.
Required Inputs
What you need: A target schema (JSON Schema, XML DTD, or CSV column spec), 2-3 valid output examples, and 2-3 counterexamples that violate the schema in specific, common ways. Why: The model learns the boundary between valid and invalid only when both sides are shown. Guardrail: Validate all examples against the schema before including them in the prompt.
Operational Risk: Counterexample Drift
What to watch: As your schema evolves, old counterexamples may become valid or stop representing real production failures. Why: Stale negative examples teach the model to reject acceptable outputs, increasing false-positive schema rejections. Guardrail: Version your counterexample set alongside your schema and run regression tests on every schema change.
Operational Risk: Over-Refusal
What to watch: The model becomes too conservative and rejects valid outputs that differ slightly from the positive examples. Why: Too many or too aggressive negative examples can shrink the model's acceptable output space. Guardrail: Measure the false-positive rejection rate on a golden set of valid outputs and adjust counterexample severity if rejections exceed 5%.
When to Escalate Beyond Prompting
What to watch: The model consistently fails on nested optional fields, polymorphic types, or deeply recursive schemas despite counterexamples. Why: Some schema complexities exceed what few-shot pattern teaching can reliably enforce. Guardrail: For complex schemas, combine this prompt with a post-processing repair step or a constrained decoding library rather than relying on prompting alone.
Copy-Ready Prompt Template
A reusable prompt that pairs valid structured outputs with deliberately malformed counterexamples to teach schema compliance.
This prompt template teaches a model to produce outputs that strictly conform to a target schema by showing it both correct examples and carefully constructed violations. The counterexamples are not random errors; they are specific, high-signal failures—missing required fields, wrong types, extra keys, malformed delimiters—that the model is likely to produce under ambiguity or context pressure. By labeling each counterexample as invalid and explaining why, the prompt establishes a clear boundary that reduces schema drift in production.
textYou are a structured output generator. Your only job is to produce output that strictly conforms to the schema described below. Before every output, you must validate your own response against the schema. If you detect a violation, correct it before responding. ## TARGET OUTPUT SCHEMA [OUTPUT_SCHEMA] ## FORMAT RULES [CONSTRAINTS] ## CORRECT EXAMPLES These examples show valid outputs that fully conform to the schema and rules above. ### Example 1 Input: [EXAMPLE_INPUT_1] Valid Output: [EXAMPLE_VALID_OUTPUT_1] ### Example 2 Input: [EXAMPLE_INPUT_2] Valid Output: [EXAMPLE_VALID_OUTPUT_2] ## COUNTEREXAMPLES: SCHEMA VIOLATIONS These examples show deliberately malformed outputs. Each is labeled with the specific violation and the correction. Study these to understand what NOT to produce. ### Counterexample 1: [VIOLATION_TYPE_1] Input: [COUNTEREXAMPLE_INPUT_1] INVALID Output (do NOT produce this): [COUNTEREXAMPLE_INVALID_OUTPUT_1] Violation: [VIOLATION_EXPLANATION_1] Corrected Output: [COUNTEREXAMPLE_CORRECTED_OUTPUT_1] ### Counterexample 2: [VIOLATION_TYPE_2] Input: [COUNTEREXAMPLE_INPUT_2] INVALID Output (do NOT produce this): [COUNTEREXAMPLE_INVALID_OUTPUT_2] Violation: [VIOLATION_EXPLANATION_2] Corrected Output: [COUNTEREXAMPLE_CORRECTED_OUTPUT_2] ### Counterexample 3: [VIOLATION_TYPE_3] Input: [COUNTEREXAMPLE_INPUT_3] INVALID Output (do NOT produce this): [COUNTEREXAMPLE_INVALID_OUTPUT_3] Violation: [VIOLATION_EXPLANATION_3] Corrected Output: [COUNTEREXAMPLE_CORRECTED_OUTPUT_3] ## INSTRUCTIONS 1. Read the input carefully. 2. Generate an output that strictly conforms to the TARGET OUTPUT SCHEMA and FORMAT RULES. 3. Before responding, mentally check your output against every violation shown in the counterexamples. 4. If your output would match any counterexample pattern, revise it to match the corrected version instead. 5. Return ONLY the valid output. Do not include explanations, markdown fences, or extra text unless the schema explicitly requires it. ## INPUT [INPUT]
To adapt this template, replace each square-bracket placeholder with concrete values specific to your schema and failure modes. The [OUTPUT_SCHEMA] should be a precise specification—JSON Schema, XML DTD, or a plain-text description of required fields, types, and constraints. The [CONSTRAINTS] block should enumerate format rules like "no trailing commas," "all fields required unless nullable," or "dates in ISO 8601." Choose counterexamples that represent the most frequent violations observed in your logs or eval runs. If you lack production data, start with structural violations—missing required fields, wrong types, unterminated strings—and expand as you observe new failure patterns. For high-risk domains where schema violations could cause downstream data corruption, always pair this prompt with a post-generation validation harness that rejects non-conforming outputs before they reach storage or APIs.
Prompt Variables
Required inputs for the Structured Output Schema Violation Counterexample Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TARGET_SCHEMA] | The exact JSON Schema, XML Schema Definition, or CSV column specification the model must follow | {"type": "object", "properties": {"id": {"type": "integer"}}, "required": ["id"]} | Must be a valid, parseable schema. Test with a schema validator before prompt assembly. Invalid schemas cause the model to learn incorrect constraints. |
[VALID_OUTPUT_EXAMPLE] | A correctly formatted output that fully conforms to TARGET_SCHEMA, used as the positive demonstration | {"id": 42} | Must pass validation against TARGET_SCHEMA. Use a programmatic schema validator, not manual review. A single field error in this example poisons the entire prompt. |
[VIOLATION_TYPE] | The specific schema violation category to demonstrate as a counterexample: missing_required, wrong_type, extra_field, malformed_syntax, null_violation, enum_violation | missing_required | Must be one of the enumerated violation types. Unrecognized types cause the model to invent its own violation patterns, reducing counterexample effectiveness. |
[VIOLATION_OUTPUT] | A deliberately malformed output that violates TARGET_SCHEMA in exactly the way specified by VIOLATION_TYPE | {"id": "forty-two"} | Must fail validation against TARGET_SCHEMA with the expected error type. Pre-validate that the violation is detectable by your production validator. A violation that passes validation teaches the wrong boundary. |
[VIOLATION_EXPLANATION] | A concise natural-language explanation of why VIOLATION_OUTPUT is incorrect, paired with the counterexample | The 'id' field must be an integer, but a string was provided. This violates the type constraint. | Must reference the specific schema rule broken. Generic explanations like 'this is wrong' do not teach the model which constraint was violated. Keep under 100 words. |
[OUTPUT_FORMAT_INSTRUCTION] | The format wrapper instruction that tells the model how to structure its final response, distinct from the schema itself | Respond with a JSON object that strictly follows the provided schema. Do not include markdown fences, comments, or extra text. | Must be explicit about fences, comments, and extra-text rules. Ambiguous format instructions are the most common cause of schema violations in production, even with counterexamples present. |
[ADDITIONAL_VIOLATIONS] | Optional array of 2-4 more violation-type and violation-output pairs for multi-pattern teaching | [{"type": "extra_field", "output": "{"id": 42, "name": "extra"}"}] | Each entry must be independently validated. Too many counterexamples in one prompt can cause the model to over-refuse or become confused about which violations to avoid. Start with 1-2 and add only if eval shows gaps. |
[CONFIDENCE_THRESHOLD] | The minimum confidence score below which the model should refuse to produce output rather than risk a violation | 0.85 | Must be a float between 0.0 and 1.0. Set based on your tolerance for false positives vs. schema violations. A threshold of 1.0 causes excessive refusal; a threshold of 0.0 disables the guard. Calibrate against your eval harness. |
Implementation Harness Notes
How to wire the schema violation counterexample prompt into a production application with validation, retries, and observability.
This prompt is designed to be used as a pre-deployment hardening step, not as a runtime repair prompt. You run it once to generate a set of valid and deliberately malformed examples, then inject those examples into your primary structured-output prompt as few-shot demonstrations. The harness therefore has two phases: a generation phase where you call this prompt, and an injection phase where you embed its output into your production prompt template. The generation phase should be treated as a build step—version the output, review it manually, and store it alongside your prompt templates.
Generation harness: Call the prompt with your target schema, constraints, and the number of counterexample pairs you need. The model will return a JSON object containing valid_examples and violation_examples. Validate the output immediately: confirm that every valid_example passes your schema validator and every violation_example fails in the specific way described by its violation_type field. If validation fails, retry once with the validation errors appended to the prompt as additional context. Log both the generated examples and the validation results. For high-stakes schemas—such as those used in finance, healthcare, or legal workflows—require a human reviewer to approve the counterexample set before it enters the production prompt.
Injection harness: Once approved, inject the examples into your production structured-output prompt as a few-shot block. Place valid examples first, followed by violation examples with explicit DO NOT DO THIS annotations. Monitor production for schema conformance drift using your existing output validation pipeline. If the violation rate on a specific violation_type increases, regenerate the counterexample set with a higher weight on that violation category. Model choice: This prompt works best with models that have strong instruction-following and JSON generation capabilities (e.g., GPT-4o, Claude 3.5 Sonnet). Avoid using smaller or older models for the generation phase, as they may produce counterexamples that are themselves malformed or ambiguous. What to avoid: Do not use this prompt at runtime for every user request—the token cost and latency are prohibitive. Do not skip the validation step; a counterexample that fails for the wrong reason will teach the model the wrong boundary.
Expected Output Contract
Schema contract for the structured output violation counterexample prompt. Use this to validate that the model's response contains both a valid example and a deliberately malformed counterexample that violates the specified rules.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
valid_example | object | Must parse as valid JSON. Must conform to [OUTPUT_SCHEMA]. All required fields present. No extra fields beyond schema definition. | |
valid_example.[FIELD_NAME] | per schema | per schema | Each field must match the type, format, and constraints defined in [OUTPUT_SCHEMA]. Enum fields must use allowed values only. |
counterexample | object | Must parse as valid JSON. Must contain at least one intentional schema violation relative to [OUTPUT_SCHEMA]. Cannot be identical to valid_example. | |
counterexample.violation_type | string | Must be one of: missing_required_field, wrong_type, invalid_enum, extra_field, null_violation, format_mismatch, out_of_range. Must match the actual violation present in counterexample. | |
counterexample.violation_field | string | Must name the specific field that violates the schema. Field name must exist in [OUTPUT_SCHEMA] or be explicitly identified as an extra field. | |
counterexample.violation_description | string | Must describe what the violation is and why it breaks the schema. Minimum 10 characters. Must reference the specific constraint from [OUTPUT_SCHEMA] that is violated. | |
counterexample.[VIOLATED_FIELD] | any | The field value must demonstrably violate the type, format, enum, or constraint rule specified in [OUTPUT_SCHEMA]. Parse check must confirm the violation is real, not cosmetic. | |
explanation | string | If present, must explain why the counterexample is invalid and how to fix it. Must not contradict violation_type or violation_description. Null allowed if explanation is embedded in violation_description. |
Common Failure Modes
When teaching schema compliance through counterexamples, these failure modes degrade reliability. Each card pairs a concrete risk with a production-ready guardrail.
Counterexample Teaches Wrong Pattern
What to watch: A malformed negative example accidentally introduces a new error pattern the model then reproduces. If your counterexample shows "status": "OK" as invalid but the correct value is "active", the model may start outputting "OK" more often. Guardrail: Validate that every counterexample violates exactly one constraint and pair it with a correct example that demonstrates the fix.
Schema Drift After Context Window Shift
What to watch: Counterexamples placed early in the prompt lose influence over long outputs. The model reverts to its pretrained schema defaults after several thousand tokens, ignoring your format violations. Guardrail: Place at least one counterexample within the last 2,000 tokens of the prompt and test with maximum-length target outputs.
Over-Correction to Adjacent Fields
What to watch: A counterexample targeting date_of_birth format causes the model to also change created_at formatting, even though that field was correct. Negative examples bleed across semantically similar fields. Guardrail: Include explicit positive examples for adjacent fields immediately after the counterexample and test field-level conformance independently.
Model Learns to Refuse Valid Edge Cases
What to watch: Counterexamples showing rejection of malformed inputs cause the model to also reject valid but unusual inputs—like empty arrays, null optional fields, or Unicode strings. The refusal boundary expands silently. Guardrail: Add positive examples for each edge case you want accepted and measure refusal rate on a held-out valid-input test set after every prompt change.
Counterexample Conflicts with System Instructions
What to watch: Your system prompt says "always output valid JSON" but a counterexample shows invalid JSON. The model resolves this conflict unpredictably—sometimes ignoring the counterexample, sometimes ignoring the system instruction. Guardrail: Frame counterexamples as "here is what NOT to output" with explicit instructional framing, and test both instruction-only and instruction-plus-example variants.
Validation Passes but Semantics Are Wrong
What to watch: Counterexamples teach the model to produce schema-valid JSON with correct types but wrong values—like "confidence": 0.99 on a low-certainty extraction. Schema conformance metrics look perfect while accuracy degrades. Guardrail: Add semantic eval checks that verify field values against ground truth, not just type and structure validation.
Evaluation Rubric
Use this rubric to test whether the prompt reliably teaches schema compliance via counterexamples. Run each criterion against a held-out set of schema-violation inputs before shipping.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema Conformance Rate | Output passes JSON Schema validation for [OUTPUT_SCHEMA] on 100% of valid inputs | Any schema validation error on a valid input | Run 50 valid inputs through the prompt; assert zero schema validation errors |
Counterexample Rejection Rate | Model rejects or corrects 95% of inputs matching known violation patterns from [NEGATIVE_EXAMPLES] | Model produces output matching a counterexample pattern without flagging the violation | Feed 20 inputs constructed to match each counterexample class; measure rejection or correction rate |
False Positive Rejection | Model rejects fewer than 5% of valid inputs that do not match any counterexample pattern | Valid input incorrectly flagged as a schema violation or refused | Run 50 valid inputs outside counterexample patterns; assert rejection rate below threshold |
Field-Level Null Discipline | Required fields are never null in output; optional fields are null only when input lacks data | Required field appears as null, or optional field is populated with hallucinated value | Parse output; assert all required fields present and non-null; spot-check 10 optional fields for hallucination |
Type Coercion Prevention | No field type mismatches (string where integer expected, array where object expected) | Field type differs from [OUTPUT_SCHEMA] type definition | Validate output types against schema; flag any type mismatch |
Enum Constraint Adherence | All enum fields contain only values from [ALLOWED_ENUMS] | Enum field contains value outside allowed set | Extract all enum fields; assert membership in allowed value set |
Boundary Condition Handling | Model correctly handles max-length, min-length, and required-array constraints from [CONSTRAINTS] | Output exceeds max length, falls below min length, or empty required array | Test 5 inputs at each boundary; assert output respects constraint limits |
Counterexample Coverage Completeness | All violation classes in [NEGATIVE_EXAMPLES] are represented in at least one test case | A counterexample class has zero test coverage | Map each negative example to test cases; assert 100% coverage |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and 3–5 violation counterexamples that cover the most common schema mistakes in your pipeline (missing required fields, wrong types, extra keys). Use a lightweight validation harness that logs schema conformance pass/fail without blocking iteration.
Prompt modification
code[VALID_OUTPUT_EXAMPLE] [VIOLATION_EXAMPLE_1] // This is wrong because: [REASON] [VIOLATION_EXAMPLE_2] // This is wrong because: [REASON] Now generate output for: [INPUT]
Watch for
- Counterexamples that are too subtle for the model to learn from
- Over-correction where the model becomes overly rigid and rejects valid edge cases
- No measurement of whether violations actually decrease after adding counterexamples

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us