Inferensys

Prompt

Source-Aware Output Contract Prompt (JSON with Citations)

A practical prompt playbook for engineering teams building citation-enabled APIs. Produces structured JSON outputs with typed citation arrays, source metadata, and claim-to-evidence mappings. Includes schema enforcement, field-level citation rules, and output validation harness.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Identify the production scenarios where a structured, citation-enforced output contract is required and when a simpler approach will suffice.

This prompt is for engineering teams building citation-enabled APIs that must return structured JSON with auditable source references. Use it when every factual claim in the output must be traceable to a specific source passage, and when downstream systems consume the response as a typed object rather than free text. This prompt belongs in production RAG pipelines, document intelligence APIs, compliance review systems, and any workflow where an unsupported claim is a product defect.

The ideal user is a developer or AI engineer who has already solved retrieval and now needs the model to synthesize multiple source passages into a single, structured answer. The required context includes retrieved documents with stable identifiers, a defined JSON schema for the output, and clear rules for when to cite, abstain, or express uncertainty. This prompt assumes you are not asking the model to perform retrieval, judge source authority from scratch, or decide the output schema on the fly.

Do not use this prompt for conversational chat, creative writing, or tasks where source grounding is optional. It is a poor fit for low-latency, single-turn Q&A where a plain text answer with markdown links is acceptable. Avoid it when the cost of generating and validating structured JSON outweighs the benefit of downstream machine readability. If your application only needs a human-readable answer with occasional references, a simpler RAG citation prompt without a strict output contract will be cheaper, faster, and easier to debug.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Source-Aware Output Contract Prompt delivers reliable, auditable JSON and where it introduces risk or unnecessary complexity.

01

Strong Fit: Regulated or High-Trust Domains

Use when: outputs must be auditable, every claim needs a source, and unsupported statements are unacceptable. Guardrail: enforce a strict schema that rejects any claim object missing a non-empty citations array.

02

Strong Fit: API Products Requiring Structured Data

Use when: downstream code consumes the output and needs typed fields, not free text. Guardrail: validate the JSON against the output schema in your application layer before returning it to the consumer.

03

Poor Fit: Open-Ended Creative Writing

Avoid when: the task is brainstorming, story generation, or subjective analysis where source attribution is unnatural. Guardrail: use a simpler structured output prompt without mandatory citation fields to avoid forcing fabricated references.

04

Required Input: Pre-Retrieved, ID'd Source Chunks

Risk: the model will hallucinate plausible-sounding citations if sources aren't provided. Guardrail: always inject source objects with unique IDs and text into the prompt context; never ask the model to recall sources from training data.

05

Operational Risk: Citation Bloat and Cost

Risk: exhaustive citation requirements can double output tokens, increasing latency and cost. Guardrail: use a citation_density parameter in the prompt to control whether citations are per-claim or per-section, and monitor token usage in production.

06

Operational Risk: Schema Brittleness

Risk: a minor prompt change can break the JSON structure, causing parsing failures downstream. Guardrail: implement a retry-and-repair loop that catches JSONDecodeError and feeds the raw output and schema back to the model for correction.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready system prompt that enforces a strict JSON output contract with typed citation arrays, source metadata, and claim-to-evidence mappings.

This template is designed for placement in the system message of a chat completion request. It instructs the model to produce a structured JSON response where every factual claim is backed by a citation to a provided source passage. The user message should contain the query and the retrieved source passages formatted as specified in the [CONTEXT] placeholder. Before integrating this into your application, replace all square-bracket placeholders with runtime values and ensure your output validation layer can parse and enforce the schema described in [OUTPUT_SCHEMA].

code
SYSTEM
You are an evidence-grounded assistant operating under a strict output contract. Your response must be a single valid JSON object conforming to the schema below. You are forbidden from generating any factual claim that is not directly supported by a source passage provided in the user message. If the provided context is insufficient to answer the query fully or partially, you must indicate this in the output rather than fabricate information.

## OUTPUT SCHEMA
[OUTPUT_SCHEMA]

## CITATION RULES
- Every claim in the `answer` field must have a corresponding entry in the `citations` array.
- Each citation object must include the `source_id` of the passage, the `quote` text used, and a `relevance` explanation.
- If a claim synthesizes information from multiple sources, list all relevant source_ids in the `source_ids` array for that claim.
- Do not cite sources that do not directly support the claim.
- If no source supports a claim, do not make the claim. Instead, use the `gaps` field to note missing evidence.

## CONSTRAINTS
[CONSTRAINTS]

## RISK LEVEL
[RISK_LEVEL]

## EXAMPLES
[EXAMPLES]

USER
Query: [QUERY]

Source Passages:
[CONTEXT]

Adapt this template by first defining your [OUTPUT_SCHEMA] as a concrete JSON Schema or a detailed field-by-field description. For high-risk domains such as healthcare or finance, set [RISK_LEVEL] to high and ensure your application layer enforces human review for any response where the gaps array is non-empty or where citation confidence falls below a defined threshold. The [CONSTRAINTS] placeholder should include domain-specific rules, such as prohibited topics, tone requirements, or length limits. The [EXAMPLES] placeholder is critical for model performance; provide at least two few-shot examples that demonstrate the exact JSON structure, including edge cases like insufficient context and multi-source claims. After the model responds, always validate the JSON structure against your schema, verify that every source_id in the citations matches a provided passage, and log any validation failures for prompt refinement.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate each before assembly.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The user's question or task that requires a source-grounded answer.

What are the key risks identified in the Q3 security audit?

Required. Must be a non-empty string. Reject if null or whitespace only.

[RETRIEVED_CONTEXT]

An array of source documents or passages to ground the answer. Each object must have id, text, and optional metadata.

[{"id": "doc-1", "text": "...", "metadata": {"title": "Q3 Audit", "date": "2024-09-30"}}]

Required. Must be a valid JSON array with at least one object. Each object must contain a non-empty 'id' and 'text' field. Reject if empty or malformed.

[OUTPUT_SCHEMA]

The strict JSON schema the model must follow for its response, defining the shape of claims and citations.

{"type": "object", "properties": {"answer_summary": {"type": "string"}, "claims": {"type": "array", "items": {"type": "object", "properties": {"claim": {"type": "string"}, "citation_ids": {"type": "array", "items": {"type": "string"}}}}}}, "required": ["answer_summary", "claims"]}

Required. Must be a valid, parseable JSON Schema object. Validate with a JSON Schema validator before prompt assembly. Reject if schema is invalid.

[CITATION_STYLE]

A string specifying the required citation format for inline markers or reference lists.

inline-numeric

Optional. If provided, must be one of the allowed enum values: 'inline-numeric', 'inline-author-date', 'reference-list'. Defaults to 'inline-numeric' if null.

[ABSTENTION_THRESHOLD]

A float between 0.0 and 1.0 indicating the minimum confidence required to make a claim. Below this, the model should abstain.

0.7

Optional. Must be a float between 0.0 and 1.0. Defaults to 0.5 if null. Reject if out of range or not a number.

[MAX_CLAIMS]

An integer limiting the maximum number of claims the model can generate in a single response.

5

Optional. Must be a positive integer. Defaults to 10 if null. Reject if negative or zero.

[MODEL_PROVIDER]

A string identifying the target model family to load specific formatting instructions.

anthropic

Required. Must be one of the allowed enum values: 'openai', 'anthropic', 'google'. Used to select model-specific prompt wrappers. Reject if unrecognized.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Source-Aware Output Contract Prompt into a production application with validation, retries, and logging.

This prompt is designed to be called from an application layer that manages retrieval, prompt assembly, and output validation. The model is not responsible for fetching sources; it receives a pre-assembled context block containing retrieved passages with unique identifiers. The application must construct the [CONTEXT] variable by mapping each retrieved chunk to a stable ID (e.g., chunk_id from your vector store or document index) and including enough metadata for the model to produce accurate citations. A typical assembly flow: (1) run retrieval, (2) deduplicate and rank passages, (3) assign each passage a short reference ID, (4) inject the passages into the [CONTEXT] placeholder, (5) inject the user query into [QUERY], (6) inject the JSON schema into [OUTPUT_SCHEMA], and (7) send the assembled prompt to the model.

After receiving the model response, validate the JSON structure before surfacing it to users or downstream systems. At minimum, confirm that: the top-level object parses without error; the claims array is present and non-empty; each claim object contains claim_text, citation_ids, and confidence fields; every citation_id in the claims array resolves to an entry in the citations array; and each citation contains a source_id that matches a passage ID you provided in the context. If validation fails, do not show the raw output. Instead, log the failure with the prompt version, model, and raw response, then either retry with a repair prompt or escalate for human review depending on the [RISK_LEVEL] configuration. For high-risk domains, always require human approval before any output is shown to end users.

Implement a retry strategy that distinguishes between format failures and content failures. A format failure (invalid JSON, missing required fields) can be retried up to two times with a repair prompt that includes the original instructions, the malformed output, and a specific error message. A content failure (citation ID not found in context, confidence below threshold) should trigger a different path: log the issue, optionally re-retrieve with expanded queries, and regenerate. Never retry more than three times total; after that, surface a controlled fallback message. Log every attempt with a correlation ID, the model used, token counts, latency, and validation results. This trace data is essential for debugging citation drift, hallucination patterns, and retrieval gaps over time.

Model choice matters for this prompt. Use a model with strong JSON mode or structured output support (e.g., GPT-4o with response_format set to json_schema, or Claude 3.5 Sonnet with tool-use mode forcing a typed output). Avoid models that frequently drop closing braces or hallucinate field names under long context. If you must use a weaker model, add a post-processing step that attempts to repair truncated JSON before validation. For latency-sensitive applications, consider streaming the response into a buffer and validating only after the full JSON is received. Do not stream partial claims to users; citation integrity requires the complete object.

Finally, build an eval harness that runs offline against a golden dataset of queries, retrieved contexts, and expected citation mappings. Measure citation precision (do cited sources actually support the claim?), citation recall (are all supported claims cited?), and hallucination rate (claims with no valid citation). Run these evals on every prompt change before deployment. In production, sample a percentage of outputs for human review, especially for [RISK_LEVEL] high configurations. The goal is not just a working prompt but a verifiable pipeline where every claim can be traced back to evidence.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the strict JSON schema for a source-aware output. Every claim must be traceable to a source. Use this contract to validate model responses before they reach downstream systems.

Field or ElementType or FormatRequiredValidation Rule

answer_summary

string

Must be a non-empty string. Cannot contain unsupported claims. If no evidence exists, this must be an abstention message.

claims

array of objects

Must be a valid JSON array. If empty, answer_summary must indicate abstention. Each object must pass the claim schema check.

claims[].claim_id

string

Must be a unique UUID v4 string within the claims array. No duplicates allowed.

claims[].statement

string

Must be a single, verifiable factual assertion. Cannot be compound. Must match a substring or logical inference from at least one cited source.

claims[].citation_ids

array of strings

Must contain at least one string matching a source_id in the sources array. Null or empty arrays are invalid.

claims[].confidence

string

Must be one of the enum values: 'HIGH', 'MEDIUM', 'LOW'. 'HIGH' requires exact quote support. 'LOW' requires explicit uncertainty language in the statement.

sources

array of objects

Must be a valid JSON array. Must contain all sources referenced by claims[].citation_ids. No orphan citations allowed.

sources[].source_id

string

Must be a unique string within the sources array. Typically a chunk ID or document UUID passed in [CONTEXT].

PRACTICAL GUARDRAILS

Common Failure Modes

Production failures in source-aware JSON output contracts often stem from schema ambiguity, citation drift, and unverified claims. These cards identify the most common breakages and the specific guardrails that prevent them.

01

Citation Fabrication Under Schema Pressure

What to watch: The model invents plausible-looking citation IDs, source titles, or excerpt text to satisfy a required field when it cannot find a perfect match in the provided context. This is most common when the output schema mandates a citation for every claim.

Guardrail: Make the citation array optional or allow a null value. Add a strict instruction: 'If no source directly supports a claim, set the citation object to null. Never generate a citation that does not match a provided source exactly.' Validate post-generation by checking every returned citation ID against the input source list.

02

Schema Drift in Nested Citation Objects

What to watch: The model outputs the right data but nests it incorrectly (e.g., placing source_id at the root instead of inside a citation object, or returning a string instead of an array of objects). This breaks downstream JSON parsers.

Guardrail: Provide the exact JSON Schema or a TypeScript interface in the prompt. Use a validation harness (e.g., jsonschema in Python, zod in TypeScript) that runs immediately after generation. If validation fails, feed the specific schema error back into a retry prompt with the original context.

03

Claim-to-Evidence Mismatch

What to watch: A claim is correctly paired with a citation object, but the cited source text does not actually support the claim. The model has confused a related passage for direct evidence, creating a dangerous false sense of auditability.

Guardrail: Implement a two-pass verification. First, generate the answer with citations. Second, use a separate 'verification' prompt that receives only the claim and the cited text, asking: 'Does this text directly support the claim? Answer only YES or NO.' Route NO answers for human review or claim removal.

04

Incomplete Source Metadata Propagation

What to watch: The model correctly cites a source but fails to populate required metadata fields like page_number, section_title, or document_date, leaving them as empty strings or omitting them entirely.

Guardrail: Explicitly define which metadata fields are mandatory in the output schema. In the prompt, add a rule: 'For every citation, you MUST extract all available metadata fields from the source object. If a field is not present in the source, use null, not an empty string.' Use a post-processing script to check for empty strings in required metadata fields.

05

Context Window Truncation Silently Drops Sources

What to watch: A large number of retrieved documents pushes the system prompt and output schema out of the context window. The model loses the citation format instructions and reverts to generating uncited, fluent prose, but the output still parses as valid JSON with an empty citations array.

Guardrail: Calculate the token count of the assembled prompt before inference. If it exceeds a safe threshold (e.g., 80% of the model's limit), either truncate the least relevant sources with a clear [TRUNCATED] marker or split the task into multiple calls. Monitor the citations array length; a sudden drop to zero is a critical runtime alert.

06

Over-Citation of Obvious or Common Knowledge

What to watch: The model attaches a citation to every single sentence, including basic summaries or common-knowledge transitions, making the output unreadable and diluting the signal of genuinely important citations.

Guardrail: Add a citation density rule to the prompt: 'Only cite a source when stating a specific, non-obvious fact, statistic, or direct quote. Do not cite your own summaries or logical transitions.' Use an eval metric that measures the ratio of cited claims to total claims, flagging outputs where over 80% of sentences have a citation.

IMPLEMENTATION TABLE

Evaluation Rubric

Score each criterion on a pass/fail basis across a golden dataset of at least 50 query-source pairs. Use this rubric to gate the Source-Aware Output Contract Prompt before production deployment.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

Output is valid JSON that parses without errors and matches the [OUTPUT_SCHEMA] exactly

JSON parse error, missing required fields, or extra unexpected fields

Automated JSON Schema validator run against every output in the golden dataset

Citation Completeness

Every factual claim in the answer field has a corresponding entry in the citations array with a matching claim_index

A claim exists with no citation, or a claim_index references a non-existent claim

Regex extraction of claims paired with programmatic check that each claim index appears in the citations array

Citation Accuracy

Each citation's source_id and excerpt match the provided [SOURCES] and the excerpt text is a verbatim substring of the referenced source

Hallucinated source_id, excerpt text not found in the referenced source, or excerpt fabricated from multiple non-contiguous spans

Automated substring match of each citation excerpt against the referenced source text in the golden dataset

Source Grounding

The answer field contains no factual statements that cannot be traced to at least one provided [SOURCES] object

A factual statement in the answer is not covered by any citation and cannot be verified in the provided sources

Human review of 50 random claim-source pairs, or LLM-as-judge with a grounding verification prompt

Abstention Behavior

When [SOURCES] contain insufficient information to answer the [QUERY], the answer field is null and the abstention object is populated with a non-empty reason

An answer is generated from insufficient sources, or abstention is triggered when sources are sufficient

Programmatic check: if answer is null, assert abstention.reason is a non-empty string; spot-check 10 abstention cases manually

Confidence Calibration

The confidence score is between 0.0 and 1.0, and scores below [CONFIDENCE_THRESHOLD] correlate with ambiguous or conflicting source evidence

Confidence is 0.9+ when sources conflict, or confidence is below threshold when a single authoritative source clearly answers the query

Statistical correlation check between confidence scores and human-annotated source sufficiency labels across the golden dataset

Multi-Source Attribution

When multiple sources contribute to a single claim, the source_id array in the citation contains all relevant source identifiers

A claim supported by two sources only cites one, or a citation lists a source that does not support the claim

Manual review of 20 multi-source claims, verifying that each cited source independently supports the claim

Output Determinism

The same [QUERY] and [SOURCES] produce structurally identical JSON (same fields, same claim count) across 5 runs with temperature 0

Field presence varies, claim count changes, or citation array length differs between runs

Run each golden dataset entry 5 times at temperature 0 and compare JSON structure hashes

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple JSON schema. Use [CITATION_REQUIREMENT] set to "optional" so the model isn't penalized for missing citations during early testing. Remove the claim_to_evidence_map field initially—focus on getting the answer and citations array right. Test with 5-10 known documents before adding validation.

Watch for

  • The model inventing citation IDs that don't match any source
  • JSON parse failures when citations contain unescaped quotes
  • Overly verbose source_excerpt fields that bloat token usage
Prasad Kumkar

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.