Skip to content
Visual explainer 3h to learn 4 steps

Answers with validated source IDs or a reason to abstain

Return an answer with source IDs that are checked against the caller's visible evidence, or an abstain or escalate reason.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 12 minutes to read.

Topic 13 of 34

In short

A grounded answer is a typed record, not free text: a status, the answer text, the source IDs it relies on and, when there is no answer, a reason. Your code checks every cited ID against the evidence that was actually retrieved for this caller, so a model cannot cite a document it never saw or one the caller is not allowed to see. When the check fails or the evidence is thin, the assistant abstains or escalates instead of guessing.

Think of it like this: A citation contract works like an expense claim: every line needs a receipt, and the finance team checks that each receipt is real and belongs to you before paying.

Explained simply

When a knowledge assistant answers a question, people need to know where the answer came from. A citation is a pointer to the exact piece of a document that supports the answer. In this path every document section has a stable ID, such as kb-refunds#s2, so a citation is just that ID.

The trouble is that a language model can write anything, including IDs that look right but do not exist. It can also mention a document it saw in training rather than one you gave it. So you never trust a citation just because the model produced it. Your code checks it.

The check is simple. Before the model runs, your retrieval step already knows which sections it found for this user, after permission filtering. That list is the evidence set. After the model answers, every cited ID must be in that set. If even one is not, the answer is rejected.

Sometimes the right move is not to answer. If the evidence does not cover the question, the assistant abstains and says why, for example no matching policy found. If a person must decide, such as approving a refund exception, it escalates. Both are normal, useful results, not errors.

Press Play on a diagram to walk through it one step at a time.

FlowFrom retrieved evidence to a checked answer
  1. 1
    Retrieve for caller

    Only chunks the caller's scope allows

  2. 2
    Number the evidence

    Each chunk keeps its stable source ID

  3. 3
    Generate

    Model returns status, text, source_ids, reason

  4. 4
    Validate schema

    Reject malformed or missing fields

  5. 5
    Check citations

    Every ID must be in this request's evidence set

  6. 6
    Return or abstain

    Failed checks become abstain or escalate

CompareThe three outcomes of one request
Answered
  • Text plus one or more source IDs
  • Every ID in the caller's evidence set
  • Claims backed by those sources
Abstained
  • No text claims
  • Reason such as no_evidence
  • Optional pointer to a human channel
Escalated
  • A person must decide or act
  • Reason such as needs_approval
  • Carries question and sources found

In depth

Designing the answer schema

Start with the shape your API returns, not with the prompt. A good answer record has a status that can only be answered, abstained or escalated. It has the answer text, a list of source IDs and a reason field. Each status has rules. An answered result needs non-empty text and at least one source. An abstained or escalated result needs a reason chosen from a short fixed list, plus optional free text for the person reading it.

Using a fixed list of reason codes, such as no_evidence, conflicting_sources, out_of_scope and needs_approval, makes results countable. Later modules turn these counts into dashboards and evaluation scores. Free text alone cannot be counted reliably.

Ask the model for this shape using structured output if your provider supports it, then validate it again with Pydantic anyway. Structured output reduces malformed JSON; it does not check that IDs are real or permitted.

  • status: answered, abstained or escalated
  • text: required when answered
  • source_ids: at least one when answered
  • reason_code: required when not answered
  • Validate in your code even with structured output

Passing the evidence set safely

The evidence set must come from your retrieval code, never from the model's own output. In Pydantic v2 you can pass it at validation time with model_validate(data, context={'visible_ids': ids}). A model validator then reads info.context and compares each cited ID with that set. The model has no way to change the context because it never touches it.

Build the evidence set after the permission filter. If retrieval found ten chunks but the caller may only see six, the set holds six IDs. The prompt should also contain only those six chunks, each labelled with its ID, so the model has nothing else to cite.

Keep the set per request. Caching it across users or sessions is a common way to leak a hidden source ID into someone else's answer.

SequenceWho supplies which part of the check
API handler
Retriever
Model
Validator
  1. 1Search with caller scope
    API handler to Retriever: Search with caller scope
  2. 2Permitted chunks and their IDs
    Retriever to API handler: Permitted chunks and their IDs
  3. 3Prompt with labelled chunks only
    API handler to Model: Prompt with labelled chunks only
  4. 4JSON: status, text, source_ids
    Model to API handler: JSON: status, text, source_ids
  5. 5Validate with context visible_ids
    API handler to Validator: Validate with context visible_ids
  6. 6Valid answer, or error to abstain
    Validator to API handler: Valid answer, or error to abstain

What to do when validation fails

A failed check has three possible responses. You can retry once, telling the model which IDs were invalid; this often works for formatting slips. You can abstain with reason_code invalid_citation, which is safe and honest. Or you can escalate if the question matters enough that a person should look.

Do not repair the answer by deleting the bad citation and keeping the text. The text may depend on the invented source, so removing the ID leaves an unsupported claim with a clean-looking citation list.

Log every failure with the request ID, the invalid IDs and the evidence set size, but not the full document text. These logs show whether failures come from a weak prompt, a model change or a retrieval problem that leaves the model with too little to cite.

  • Retry at most once, with the invalid IDs named
  • Otherwise abstain with invalid_citation
  • Never strip bad IDs and keep the text
  • Log IDs and counts, not content

Abstain or escalate: drawing the line

Abstaining means the system cannot answer from what it has. Typical causes are no relevant evidence, evidence below your score threshold, or a question outside the assistant's topic. The user gets a short honest message and, ideally, a pointer to where to ask.

Escalating means a person should act. The question may be answerable, but the answer would grant something, such as an exception, or the sources conflict, or the user is asking about their own case. The escalation record carries the reason, the question and the source IDs already found, so the person does not start from zero.

Write these rules down as a small table and test each row. A test that sends a question with no matching document must get abstained with no_evidence. A test that asks for an exception must get escalated with needs_approval.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Define the answer and citation schema~45m
  2. 2
    Check each citation against retrieved evidence~45m
  3. 3
    Reject citations the caller cannot see~45m
  4. 4
    Return abstain or escalate reasons~45m

Key points

  • The response has three outcomes: answered, abstained or escalated, each with required fields.
  • Citations are stable source IDs such as kb-refunds#s2, never page titles or URLs the model typed.
  • The allowed set of IDs comes from the retrieval step for this caller, passed in by your code.
  • A citation to an unknown or hidden ID fails the whole answer; you do not silently drop it.
  • Abstain when evidence is missing; escalate when a person must decide or the request is out of policy.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from typing import Literal
from pydantic import BaseModel, ValidationInfo, model_validator
class Answer(BaseModel):
    status: Literal['answered', 'abstained', 'escalated']
    text: str = ''
    source_ids: list[str] = []
    reason: str | None = None
    @model_validator(mode='after')
    def check_sources(self, info: ValidationInfo):
        visible = (info.context or {}).get('visible_ids', set())
        if self.status == 'answered' and not self.source_ids:
            raise ValueError('an answer needs at least one source')
        if bad := [s for s in self.source_ids if s not in visible]:
            raise ValueError(f'unknown or hidden sources: {bad}')
        return self

Pydantic v2: the caller's visible IDs arrive through validation context, not from the model.

Catching an invented citation

Prerequisites: the deterministic model stub from module 1 and the retriever from module 4. Step 1: a staff user asks how long refunds take. Retrieval returns kb-refunds#s2 and kb-faq#s4, both visible to staff. Step 2: the stub is scripted to answer and cite kb-refunds#s2 and kb-refunds#s9. Step 3: validation fails because kb-refunds#s9 is not in the evidence set. Expected evidence: a ValidationError naming the bad ID, and an API response with status abstained and reason_code invalid_citation. Cleanup: none; the stub keeps everything local.

python
from pydantic import ValidationError

visible = {'kb-refunds#s2', 'kb-faq#s4'}
raw = {'status': 'answered', 'text': 'Refunds take 30 days.',
       'source_ids': ['kb-refunds#s2', 'kb-refunds#s9']}
try:
    answer = Answer.model_validate(raw, context={'visible_ids': visible})
except ValidationError as e:
    answer = Answer(status='abstained', reason='invalid_citation')
    print(e.errors()[0]['msg'])
print(answer.status)  # abstained

A hidden document never reaches the answer

Two scopes exist: staff and finance. The finance-only document fin-payroll#s1 mentions bonus dates. Step 1: a staff user asks about bonus dates. Step 2: retrieval with the staff scope returns nothing relevant, so the evidence set is empty. Step 3: even if a badly behaved model cites fin-payroll#s1, the validator rejects it because the ID is not in the staff evidence set. Step 4: the API returns abstained with no_evidence. Expected evidence: a test that asserts the response never contains fin-payroll#s1 for the staff scope, and does contain it for the finance scope.

python
def test_staff_cannot_cite_finance_doc(client_for):
    r = client_for('staff').ask('When are bonuses paid?')
    assert r['status'] == 'abstained'
    assert 'fin-payroll#s1' not in r['source_ids']

def test_finance_can_cite_finance_doc(client_for):
    r = client_for('finance').ask('When are bonuses paid?')
    assert r['status'] == 'answered'
    assert 'fin-payroll#s1' in r['source_ids']

Quick reference

  • Statuses: answered, abstained, escalated; every non-answer needs a reason code
  • Cite stable section IDs (kb-refunds#s2), never titles or URLs written by the model
  • Evidence set = retrieved chunks after the permission filter, built per request
  • Pydantic v2: model_validate(data, context={...}); read info.context in a validator
  • Any unknown or hidden ID fails the answer; do not strip it and keep the text
  • Structured output fixes JSON shape, not truth; always validate IDs in your code
  • Abstain = cannot answer from evidence; escalate = a person must decide or act

Common mistakes

  • Trusting that a source ID exists because it looks plausible; models invent IDs that match your naming pattern.
  • Checking citations against the whole corpus instead of this caller's evidence set, which lets hidden documents through.
  • Returning an empty answer with status answered when the model gave up; require a reason for every non-answer.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the list of allowed citation IDs come from?

Question 2

2The model cites two IDs and one is not in the evidence set. What is the safest default?

Question 3

3A user asks for a refund exception that policy says a manager must approve. What status fits?

Question 4

4Why use fixed reason codes as well as free text?

Question 5

5Your provider supports structured output with a JSON schema. What does it guarantee?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write three answer records as JSON: one answered, one abstained, one escalated, for questions about the synthetic refund policy.

  2. Exercise 2medium

    Extend the Answer model so that abstained and escalated results must have a reason from a fixed set, and answered results must not have one.

  3. Exercise 3hard

    Write a pytest suite that runs ten fixture questions for both the staff and finance scopes and fails if any response cites an ID outside that scope's visible documents.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I just ask the model to only cite real sources?
You should ask, but you cannot rely on it. Models follow instructions most of the time, not every time, so the check must be in code.
Should citations point to whole documents or sections?
Sections or chunks are better because a reader can find the exact supporting text. Keep the document ID inside the section ID so you can group them later.
Is abstaining a failure?
No. Abstaining when the evidence is missing is the correct behaviour. A wrong confident answer is the real failure.
Do I need a hosted model to practise this?
No. A deterministic stub that returns scripted JSON lets you test every path, including invented citations, for free and offline.

Go deeper

ShareXLinkedInWhatsApp