Build a Small Evaluation Dataset Before Tuning Your RAG System
A practical method for building a compact, versioned RAG evaluation set that separates retrieval, grounding, answer quality, and safe abstention.
AI
A practical guide to schemas, refusals, bounded repair, domain validation, and safe application actions for reliable LLM outputs.

Estimated reading time: 9 minutes
A model response is often treated as text that happens to look like JSON. That is a fragile interface. Production code needs a contract: what shapes are acceptable, what the values mean, and what the application should do when the model refuses, stops early, or returns a structurally valid but unsafe answer.
Structured output features improve the first part of that contract. With a supported schema, a provider can constrain a completed, non-refusal response to an agreed shape. That is valuable: callers spend less effort stripping code fences or guessing whether a field is missing. Yet JSON that validates is not automatically true, authorized, complete, or safe to execute. Reliability comes from a pipeline that treats generation, parsing, schema validation, domain validation, and side effects as separate decisions.
Consider a model asked to extract a proposed refund from a support conversation. A JSON Schema can require an object with a string order ID, a numeric amount, and a reason chosen from a short enum. It can reject an omitted field or an unknown property. It cannot establish that the order exists, that the amount is below the refundable balance, that the customer owns the order, or that a refund is permitted under policy.
JSON Schema defines structural assertions such as type, required, enum, numeric bounds, and object-property rules. Its format vocabulary deserves particular care: in the standard, format can be annotation-only unless an implementation declares and supports assertion behavior. A schema containing an email format should therefore not be treated as a universal mailbox existence check. Keep application rules explicit and test the validator’s actual behavior.
flowchart TD
A["Request with task and schema"] --> B["Model provider response"]
B --> C{"Response state"}
C -->|"Refusal or incomplete"| D["Handle without parsing as success"]
C -->|"Completed content"| E["Parse and validate schema"]
E -->|"Invalid"| F["Bounded repair or review"]
F --> E
E -->|"Valid"| G["Business checks before use"]
G -->|"Pass"| H["Application action"]
G -->|"Fail"| D
The diagram separates the provider response state from the content checks. A refusal or truncated answer does not enter the success path simply because the body resembles JSON. Completed content must parse and satisfy the schema, then pass application rules before it can affect a user or a system. The repair loop is deliberately bounded; it does not turn repeated guesses into evidence.
A useful schema is narrow enough to express the contract and clear enough for both the model and the application. Make important fields required, constrain closed sets with enum, put sensible bounds on strings and numbers, and decide explicitly whether additional object keys are allowed. If an API supports strict schema mode, check its documented subset before sending the schema. Providers do not necessarily implement every JSON Schema keyword or report edge cases identically.
For example, a routing result might be:
{
"type": "object",
"properties": {
"route": { "type": "string", "enum": ["billing", "technical", "other"] },
"summary": { "type": "string", "minLength": 1, "maxLength": 400 },
"needs_human": { "type": "boolean" }
},
"required": ["route", "summary", "needs_human"],
"additionalProperties": false
}
This schema excludes misspelled or invented fields and requires a route, summary, and review flag. It still does not prove that the route is correct. If a support issue mentions both an invoice and an outage, the application may need a priority rule, a multi-label design, or human review. Do not make a schema appear precise by encoding business policy that the model cannot observe.
Schema strictness has a cost. A closed object can simplify downstream code but may make evolution harder. Version schemas as application contracts: add optional fields cautiously, define how old consumers behave, and avoid changing the meaning of an existing enum value. Before deployment, test representative valid and invalid inputs, including empty, ambiguous, adversarial, multilingual, and unusually long cases. Keep a small evaluation set in version control and run it when prompts, schemas, models, or parsers change.
The first branch should inspect the provider’s response envelope, not call a JSON parser on whatever text happens to be present. Distinguish at least:
Provider documentation makes this distinction concrete. OpenAI documents an explicit refusal signal for structured output and notes that applications still need to handle refusals, incomplete responses, and API errors. Anthropic documents a refusal stop reason and a maximum-token stop condition; the refusal can take precedence over the requested schema. These are provider-specific envelope details, so write a small adapter per provider that converts them into your own internal states.
For a streaming response, do not expose a half-built object as a final decision. Buffer the structured content until the provider reports completion, then parse and validate. If a user interface streams progress, label it as provisional. A partial JSON prefix such as an object with a route but no closing brace is not a valid routing result. The UI can show a neutral “processing” state without implying a decision has been made.
Input: a message says, “Please refund order A-104 for 28.50; the duplicate charge happened yesterday.” The model returns an object containing order_id, amount, currency, and reason.
Decision: First, the adapter checks that the response completed and was not a refusal. The JSON parser checks syntax. A schema then requires a non-empty order_id, a positive number for amount, a three-letter currency string, and a reason from duplicate_charge, late_delivery, or other. If the model adds approved=true, a closed schema rejects it because approval is not the model’s authority.
Next, application code looks up A-104, confirms the account relationship, calculates the refundable balance, and checks the organization’s refund policy. Those are authoritative data and policy checks, not generation tasks.
Output: if every rule passes, the application can create a proposed refund operation for an authorized review flow. If the order is unknown or only 20.00 is refundable, it does not silently clamp or execute the 28.50 request. It returns a typed business-rule failure or routes the case to a human. The shape being valid is one gate, not the approval.
Input: a user asks, “The dashboard says my card was charged twice, and I cannot download the receipt.” A classifier schema allows one route from billing, technical, or other, plus a short summary and needs_human.
Decision: the first completed result is valid JSON but has an empty summary. The schema rejects it. The application may make one corrective generation request that includes the validation error and original task, while keeping the same schema. If the second result is valid, a business rule checks whether the summary contains enough context for the receiving team. If it still fails, the case goes to a review queue. A refusal is not retried as an ordinary validation error; nor is a non-retryable permission or authentication error.
Output: either a bounded, validated routing suggestion or an explicit review state. The application does not enter an unbounded loop and does not claim that the model’s label is ground truth. The event log records the schema version, provider/model identifier, response state, validation outcome, retry count, and final route, subject to the system’s privacy policy.
Retries should be specific to the failure. A network timeout may be retried with exponential backoff and jitter if the request is safe to repeat. A schema mismatch may justify one repair attempt. A refusal should be surfaced or routed according to product policy, not hidden by asking again until a prohibited answer appears. A deterministic business-rule failure should be fixed in the application or sent for review, not repeatedly submitted to the model.
Never attach an external side effect directly to “valid JSON.” For payments, bookings, access changes, or deletion, use a separate authorization and execution step. Check current state immediately before the action. Make the side-effect call idempotent where possible so a timeout does not create duplicates. Preserve a clear audit boundary between the proposed model output and the verified action.
A schema-valid answer can still be unhelpful or wrong. Measure at least three distinct properties: whether the output conforms to the supported schema, whether it performs the task correctly, and what latency or resource cost the constraint adds. JSONSchemaBench is a research benchmark that evaluates structured-generation frameworks across efficiency, schema-feature coverage, and task quality; its framing is useful precisely because conformance alone is not the whole evaluation.
Keep operational metrics aggregated and privacy-aware. Useful counters include refusal rate, truncation rate, schema failure rate, business-rule rejection rate, bounded-retry rate, and human-review rate. Segment by schema version and use case. Do not log sensitive raw prompts or extracted personal data by default. When investigation requires examples, redact or use synthetic fixtures. Track changes with deployment versions so an increased validation failure rate can be tied to a specific schema or provider update.
Before relying on structured output, answer these questions:
The strongest design is not “the model always returns valid JSON.” It is a system whose boundaries remain clear when the model returns valid data, invalid data, a refusal, a partial response, or a plausible but incorrect value. Schema constraints narrow the representation. Independent validation and authorization establish whether that representation is safe to use.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.