Most teams treat hallucination as a model-quality problem. In production RAG systems, it is usually a contract problem: the model is allowed to answer without evidence, and nothing downstream proves the evidence was actually used. Grounding fixes that by making evidence addressable, requiring citations, and failing closed when support is missing.
Two failure classes matter. Retrieval failure means the answer is not in the context at all. Synthesis failure means the context is there, but the model blends facts, overgeneralizes, or cites the wrong chunk. A useful checklist has to catch both, because a stronger model only helps with the second.
The practical grounding checklist
Retrieve before you generate, with a relevance cutoff. If no chunk passes, return an insufficient-evidence response without calling the model.
Assign stable evidence IDs at chunk level, such as [S1], [S2], and include the document title or section in each chunk.
Require sentence-level citations, not a bibliography. “Every factual sentence ends with [S#]” is mechanically testable.
Make abstention a valid success state. Prompt for an explicit INSUFFICIENT_EVIDENCE answer and count it in your metrics.
For high-stakes claims, use quote-first extraction: first extract supporting spans, then answer only from those spans. This reduces paraphrase drift.
Validate citations mechanically. Check that cited IDs exist and that quoted strings appear in the cited source chunk. Reject answers that fail.
Add a verifier pass. Ask a second call to label each claim supported or unsupported against its cited span. Use deepseek-v4-flash for routine checks and deepseek-v4-pro for high-stakes synthesis.
Track unsupported-claim rate and abstention rate, not just answer rate. A system that answers everything is not grounded.
Keep temperature low and prompts stable. Grounding is a control problem; randomness works against it.
Re-ground follow-ups. Do not let chat history become evidence; retrieve again for each new question.
| Failure mode | What you see | Mechanical check | Fix |
|---|---|---|---|
| Missing evidence | Fluent answer with no valid [S#] | Citation set is empty or invalid | Abstain and improve retrieval |
| Wrong chunk | Citation exists but does not support the claim | Quoted text not found in cited chunk | Span-level citations plus verifier |
| Overreach | Answer says more than the source | Claim not entailed by cited text | Quote-first extraction |
| Stale context | Answer uses an outdated document | Metadata date filter | Recency filter and re-retrieve |
A runnable grounded-answer function
The example below enforces four things: evidence IDs in the prompt, inline citations in the answer, a JSON response contract, and a mechanical rejection path. Set AICREDITS_API_KEY and install the OpenAI SDK before running it.
import json
import os
import re
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
def chat(messages, temperature=0.0):
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
temperature=temperature,
)
return response.choices[0].message.content
def parse_json(text):
text = text.strip()
if text.startswith('```'):
text = re.sub(r'^```(?:json)?\s*', '', text, flags=re.IGNORECASE)
text = re.sub(r'\s*```$', '', text)
start, end = text.find('{'), text.rfind('}')
if start != -1 and end != -1:
text = text[start:end + 1]
return json.loads(text)
def ground_answer(question, docs, min_citations=1):
evidence = '\n\n'.join(
'[S{}] {}\n{}'.format(i, doc['title'], doc['text'])
for i, doc in enumerate(docs, start=1)
)
system = (
'Answer only from the evidence. Cite every factual sentence with [S#]. '
'If the evidence is insufficient, return abstained=true and '
'answer=INSUFFICIENT_EVIDENCE. Return JSON with keys: answer, citations, abstained.'
)
user = 'Question: {}\n\nEvidence:\n{}'.format(question, evidence)
raw = chat([
{'role': 'system', 'content': system},
{'role': 'user', 'content': user},
])
try:
result = parse_json(raw)
except json.JSONDecodeError:
return {
'answer': 'INSUFFICIENT_EVIDENCE',
'citations': [],
'abstained': True,
'reason': 'unparseable_model_output',
}
answer = str(result.get('answer', '')).strip()
if result.get('abstained') or answer == 'INSUFFICIENT_EVIDENCE':
return {'answer': 'INSUFFICIENT_EVIDENCE', 'citations': [], 'abstained': True}
cited = set(re.findall(r'\[S(\d+)\]', answer))
valid = {str(i) for i in range(1, len(docs) + 1)}
invalid = cited - valid
if invalid:
return {
'answer': 'INSUFFICIENT_EVIDENCE',
'citations': [],
'abstained': True,
'reason': 'invalid_citations:{}'.format(sorted(invalid)),
}
if len(cited) < min_citations:
return {
'answer': 'INSUFFICIENT_EVIDENCE',
'citations': [],
'abstained': True,
'reason': 'no_citation',
}
return {
'answer': answer,
'citations': ['S{}'.format(i) for i in sorted(cited, key=int)],
'abstained': False,
}
def quote_check(answer, docs):
problems = []
for tag in re.findall(r'\[S(\d+)\]', answer):
idx = int(tag) - 1
if idx < 0 or idx >= len(docs):
problems.append('{}:out_of_range'.format(tag))
continue
source = docs[idx]['text'].lower()
for quote in re.findall(r'\x22([^\x22]{12,})\x22', answer):
if quote.lower() not in source:
problems.append('{}:quote_not_found'.format(tag))
return problems
if __name__ == '__main__':
docs = [
{'title': 'Installation', 'text': 'Install the package with pip and set the API key in an environment variable.'},
{'title': 'Retries', 'text': 'The client retries rate-limited requests with exponential backoff.'},
]
result = ground_answer('How do I install the package?', docs)
print(json.dumps(result, indent=2))
print('quote problems:', quote_check(result['answer'], docs))
The function does not prove truth. It proves that the model followed a citation contract or failed cleanly. That distinction matters: a grounded system should produce fewer unsupported claims and make the remaining failures visible.
The quote_check helper is deliberately cheap. It only catches quoted text that is missing from the cited chunk. It will not catch subtle paraphrase errors, so keep it as a fast integrity check, not your only defense.
When to use deepseek-v4-pro
Use deepseek-v4-flash as the default for retrieval-answer generation, citation extraction, and routine checks. It is the fast path and keeps the loop practical. Reserve deepseek-v4-pro for a second-pass verifier on high-stakes answers, ambiguous synthesis, or cases where the cost of an unsupported claim is high. Pro costs more than flash, so spend it where the verifier actually changes behavior. Current rates are listed at aicreditsapi.com/deepseek-prices.
FAQ
No. It reduces unsupported claims and makes failures inspectable. You still need retrieval quality, evaluation, and human review for high-stakes decisions.
Usually not. Use deepseek-v4-flash for generation and routine validation, and reserve deepseek-v4-pro for verifier passes or high-stakes answers. Pro costs more than flash.
Enough clean, relevant evidence to answer the question, with stable chunk IDs. Too much low-relevance context increases distraction. Retrieve, rerank, then drop weak chunks before generation.
Unsupported-claim rate: the share of factual sentences without a valid supporting citation. Pair it with abstention rate so you can see whether the system is failing closed or guessing.