Citations & grounding
Return answers with source citations and refuse when context is missing.
By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.
In short
Citations show which sources support each part of an answer, so users can verify it. Grounding instructions keep the model inside the retrieved context and make it refuse when the answer is not there.
Explained simply
A citation is a small label in an answer, like [2], that points to the passage a claim came from. It lets readers click through and check for themselves. For anything that matters, like a policy, a price or a legal rule, people trust an answer much more when they can see its source.
Grounding means the model sticks to the text you gave it. You tell it plainly: use only the context below, and say you don't know when the answer is not there. Models follow this well most of the time, but not every time, so your code double-checks the result.
Refusing is a feature, not a failure. A bot that says I could not find that in the docs is far more useful than one that invents a confident wrong answer. You can even refuse before calling the model at all, when search finds nothing close enough.
The full loop is simple: number the chunks, ask for a citation after each claim, check in code that every cited number really exists, and show the sources as links the user can open.
Press Play on a diagram to walk through it one step at a time.
- 1Label chunks
Give each retrieved chunk an ID like [1]
- 2Instruct citing
Cite IDs after each claim
- 3Generate
Model answers from context only
- 4Verify IDs
Drop or flag citations not in context
- 5Show sources
Link IDs to titles and URLs
- User to App: Ask a question1Ask a question
- App to Retriever: Search2Search
- Retriever to App: Chunks with scores3Chunks with scores
- 4Best score too low? RefuseApp to App: Best score too low? Refuse
- App to LLM: Numbered chunks plus rules5Numbered chunks plus rules
- LLM to App: Answer citing [1] [2]6Answer citing [1] [2]
- 7Verify every citationApp to App: Verify every citation
- App to User: Answer with source links8Answer with source links
In depth
Three ways to ask for citations
The simplest format is inline IDs: the model writes Refunds take 5 days [1]. It is easy to read and easy to parse with a regular expression, but it only tells you which chunk was used, not which sentence in it.
A stronger format asks for a short exact quote from the chunk for each claim. Your code can then check that the quote really appears in that chunk. A made-up quote is a strong sign of a made-up claim.
The most robust format uses structured output: the model returns JSON with an answer field and a list of citations, each with a chunk ID and a quote. You validate it with a schema such as a Pydantic model. Some provider APIs also have built-in citation features that return exact source spans; when your provider offers one, it is usually more reliable than parsing text yourself.
- Text like [1] [3]
- Easy to read and parse
- Checks the chunk, not the claim
- Exact words from the chunk
- Code checks the quote exists
- Catches invented support
- answer plus citations list
- Validated with a schema
- Easiest to render as links
Verifying citations in code
Never show a citation you have not checked. First, every cited ID must be one you actually put in the prompt. Models sometimes cite [4] when only three chunks were given. Second, if you asked for quotes, check that each quote appears in its chunk. Normalise first: collapse whitespace and compare in lowercase so a line break does not cause a false alarm.
A deeper check asks whether the sentence is really supported by the quoted text. This needs a second model call (an LLM judge or an entailment model) and costs time and money, so many teams run it offline in evals rather than on every request.
When a check fails, you have three choices: drop the bad citation, drop the unsupported sentence, or replace the whole answer with a refusal. For high-stakes domains, refusing is the safer default.
- Cited ID not provided: invalid citation
- Quote not found in chunk: likely invented
- No citations at all: treat the answer as ungrounded
- 1Parse citations
IDs and quotes from the answer
- 2Check IDs
Every ID was in the prompt
- 3Check quotes
Each quote appears in its chunk
- 4Decide
Show, strip bad parts, or refuse
- 5Render sources
Titles and links for valid IDs
Grounding instructions that hold up
Vague rules like be accurate do little. Clear, testable rules work better. Tell the model to answer only from the context, to cite the chunk ID after every factual sentence, and to prefer the context over its own knowledge even when they disagree. Give it an exact refusal sentence to use when the context does not contain the answer, so your code and your evals can detect refusals with a simple string match.
Tell it what to do with partial answers too, for example: answer the part the context supports and say which part is missing. With long contexts, repeating a one-line reminder of the rules after the context block helps.
Use a low temperature for factual Q and A. It does not guarantee correctness, but it reduces creative wandering away from the sources.
- Answer only from the context inside the context tags
- Cite like [2] after each factual sentence
- If the context does not contain the answer, reply exactly: I could not find this in the documentation.
Refusing before and after generation
There are two places to refuse. Before generation: if the best retrieval score is below a threshold, skip the model call and return a not found message. This is cheap and blocks the most common source of invented answers, which is a question with no relevant context. Choose the threshold from data. Run your eval questions, look at the top score for answerable and unanswerable ones, and pick a value between the two groups.
After generation: detect the model's refusal phrase and show a helpful not found screen, perhaps with links to search or support.
Track your refusal rate in production. A sudden jump often means ingestion broke or a new topic appeared that your docs do not cover. A very low rate on a narrow bot can mean it is answering questions it should not.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Return source citations with answers~40m
- 2Instruct the model to stay in context~40m
- 3Refuse when context is missing~40m
Key points
- Number chunks in the prompt so the model can refer to them.
- Check in code that every cited ID was actually provided.
- Give a fixed refusal phrase for when context lacks the answer.
- A citation shows where a claim came from, not that the claim is correct.
Key terms
Tap a card to flip it. 0/4 known
Examples
import re
answer = 'Refunds take 5 business days [1]. Fees are waived [3].'
provided_ids = {1, 2}
cited = {int(n) for n in re.findall(r'\[(\d+)\]', answer)}
invalid = cited - provided_ids
if invalid:
print('Unsupported citations:', invalid) # {3}
if not cited:
print('Answer has no sources; consider refusing.')Check that the model only cites chunks it was given.
Checking quote-based citations
You ask the model for structured output: an answer plus a list of citations, each with a chunk_id and a short exact quote. Step 1: validate the JSON with Pydantic. Step 2: for each citation, check the chunk ID exists in the chunks you sent. Step 3: normalise whitespace and case, then check the quote is inside that chunk's text. Step 4: if any citation is bad, log it and either strip it or refuse. In this example a citation pointing to chunk 9, which was never sent, would be reported.
from pydantic import BaseModel
class Cite(BaseModel):
chunk_id: int
quote: str
def norm(s: str) -> str:
return " ".join(s.split()).lower()
def bad_citations(cites: list[Cite], chunks: dict[int, str]) -> list[str]:
bad = []
for c in cites:
if c.chunk_id not in chunks or norm(c.quote) not in norm(chunks[c.chunk_id]):
bad.append(f"[{c.chunk_id}] {c.quote[:40]}")
return badPicking a refusal threshold from data
Your bot answers HR questions. Step 1: take 30 eval questions, 20 that the docs answer and 10 that they do not (like what is the CEO's salary?). Step 2: run retrieval only and record the best similarity score for each. Step 3: sort and compare. In this run the answerable questions mostly score above 0.55 and the unanswerable ones mostly below 0.45. Step 4: set the threshold at 0.50 and count mistakes on both sides. Step 5: one answerable question scored 0.48 because the user wrote PTO and the docs say paid leave. Rather than lowering the threshold for everyone, add the synonym to the doc or use hybrid search. Re-check the numbers whenever you change the embedding model, because scores shift.
Quick reference
- Number chunks in the prompt and ask for [n] after each factual sentence
- Reject any cited ID that was not in the prompt
- Ask for exact quotes when you need proof; check them with a normalised substring match
- Give the model one exact refusal sentence so code and evals can detect it
- Refuse before calling the model when the best retrieval score is below a threshold
- Choose the threshold from scores of answerable vs unanswerable eval questions
- A valid citation shows the source used; it does not prove the claim is correct
- Track refusal rate in production; sudden changes signal ingestion or coverage problems
Common mistakes
- Showing citations without verifying they exist in the retrieved set.
- Letting the model fill gaps from general knowledge when context is missing.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a function that finds all [n] citation IDs in an answer and returns the ones that were not provided.
- Exercise 2medium
Write answer_or_refuse(question, search, generate, threshold) that refuses without calling the model when the best score is below the threshold.
- Exercise 3hard
Turn a checked answer into display text: keep only valid [n] markers, remove invalid ones, and append a numbered source list with titles and URLs for the IDs actually used.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can a model with citations still hallucinate?
- Yes. It can cite a real chunk and still misstate what it says. Citations make checking possible; quote checks and faithfulness evals catch more of the errors.
- Should the model cite per sentence or per answer?
- Per sentence or per claim is better. It shows exactly which source supports which statement and makes unsupported sentences easy to spot.
- What should a RAG bot say when it does not know?
- A short, honest message that the docs do not cover it, ideally with a next step like a search link or a way to contact support.