Skip to main content

How to Add Source Citations to a RAG Chatbot (With Code)

Updated 8 min readMarkdown
How to Add Source Citations to a RAG Chatbot (With Code)

Show users where each answer came from, and catch made-up references before they reach the screen.

A RAG chatbot answers from your own content. But users can’t see that unless you show them. An answer with no source is just a claim. An answer with a link to the page it came from can be checked, trusted and corrected.

In this post I’ll show a practical way to add source citations to a RAG chatbot: keep the right metadata, number the context, ask the model to cite, validate what it cites, and show a clean sources list. The code is illustrative, so adapt it to your own stack.

Why citations matter

  • Trust. People trust an answer more when they can check it, especially for prices, policies and deadlines.
  • Debugging. When an answer is wrong, the citation tells you which page or chunk the model used, so you can fix the content instead of guessing.
  • Content quality. If the same page keeps being cited for the wrong reasons, that page probably needs rewriting.
  • Honest limits. A chatbot that has to cite is less likely to wander off into general knowledge.

What a good citation looks like

A good citation is specific and clickable. For a website chatbot, that usually means the page title and a link, sometimes with the section name. Avoid vague labels like “Source 1” with no link, and never show a citation you haven’t verified exists.

There are three common styles:

Style Example Best for
Numbered inline markers "Returns are accepted within 30 days [1]." Chat answers with a sources list below
Footnote list only A "Sources" list under the answer Short, simple answers
Structured output The model returns JSON with an answer and source IDs When you want to render citations in your own UI

This post uses numbered inline markers, because they're easy to prompt for and easy to validate.

The approach

  1. Keep source metadata with every chunk.
  2. Number the retrieved chunks in the prompt.
  3. Instruct the model to cite those numbers.
  4. Parse and validate the citations in code.
  5. Build a sources list from the valid ones.
  6. Show it clearly, and fall back safely when there is nothing to cite.

Step 1: Keep source metadata with every chunk

Citations are only possible if each chunk remembers where it came from. When you index your content, store at least a title and a URL.

chunk = {
    'text': 'You can return items within 30 days of delivery.',
    'title': 'Return policy',
    'source': 'https://example.com/return-policy',
    'section': 'Eligibility',
}

If you’re splitting documents by headings, the heading is a natural value for section. This is also why it’s worth deciding on metadata early, because adding it later means re-indexing everything.

Step 2: Number the context in the prompt

After retrieval, give each chunk a number and put it in the prompt. The model then has something short and unambiguous to cite.

NL = chr(10)

PROMPT = '''Answer using only the numbered sources below.
After each claim, cite the source number in square brackets, like [1].
If the sources do not contain the answer, say you do not know
and suggest contacting the team. Do not cite a source you did not use.

Sources:
{context}

Question: {question}'''

def build_prompt(question, chunks):
    blocks = []
    for i, c in enumerate(chunks, start=1):
        header = '[' + str(i) + '] ' + c['title']
        blocks.append(header + NL + c['text'])
    context = (NL * 2).join(blocks)
    return PROMPT.format(context=context, question=question)

Three things in that prompt do the real work: it restricts the model to the sources, it defines the citation format, and it gives an explicit way out when the answer isn’t there.

Step 3: Validate what the model cites

Never trust the citations as they come back. Models sometimes cite a number that doesn’t exist, such as [7] when you only supplied four sources. Check every one in code.

import re

CITATION = re.compile(r'\[(\d+)\]')

def validate_citations(answer, num_sources):
    cited = [int(n) for n in CITATION.findall(answer)]
    valid = sorted({n for n in cited if 1 <= n <= num_sources})
    invalid = sorted({n for n in cited if n not in valid})
    return valid, invalid

def strip_invalid(answer, invalid):
    for n in invalid:
        answer = answer.replace('[' + str(n) + ']', '')
    return answer

This catches the most obvious failure: references to sources that were never provided.

Step 4: Build the sources list

Turn the valid numbers back into titles and links. If several chunks come from the same page, show that page once.

def build_sources(valid, chunks):
    seen, sources = set(), []
    for n in valid:
        c = chunks[n - 1]
        if c['source'] in seen:
            continue
        seen.add(c['source'])
        sources.append({'title': c['title'], 'url': c['source']})
    return sources

Step 5: Put it together, with a safe fallback

Decide what happens when the answer has no valid citation. For a business chatbot, the safest default is to show a fallback message rather than an uncited answer.

FALLBACK = 'I\u2019m not sure about that. Please contact our team for help.'

def answer_with_citations(question, retrieve, llm):
    chunks = retrieve(question)
    answer = llm(build_prompt(question, chunks))

    valid, invalid = validate_citations(answer, len(chunks))
    answer = strip_invalid(answer, invalid)

    if not valid:
        return {'answer': FALLBACK, 'sources': []}

    return {'answer': answer, 'sources': build_sources(valid, chunks)}

Here retrieve is your search function and llm is a function that calls your model. Both are placeholders for whatever you use.

One design choice to be aware of: this returns the fallback even if the model gave a correct but uncited answer. For some chatbots that’s too strict, and you may prefer to show the answer with a note. For prices, policies and anything users might act on, strict is usually the better default.

Step 6: Display it clearly

  • Show the sources below the answer, with the page title as the link text.
  • Make links open in a new tab so users don’t lose the chat.
  • Keep the list short. Three or fewer sources is easier to scan than ten.
  • For time-sensitive facts, consider showing when the page was last updated, if you store that metadata.
  • If you use inline markers like [1], make them match the numbering in the sources list, or replace them with small clickable links.

Step 7: Test your citations

Two tests are worth writing early.

def test_answer_cites_expected_source(ask):
    result = ask('What is your return policy?')
    urls = ' '.join(s['url'] for s in result['sources'])
    assert '/return-policy' in urls

def test_invalid_citation_is_removed():
    answer = 'Returns take 30 days [1] and refunds are instant [9].'
    valid, invalid = validate_citations(answer, num_sources=2)
    assert valid == [1]
    assert invalid == [9]

The first checks that the right page is cited for a known question. The second checks that fake citations are caught. Run both after every change to your prompt, retrieval or chunking.

What citations don’t guarantee

This is the part people skip. A citation tells the user which source the model was given. It does not prove the answer matches that source.

A model can cite [1] while stating something source 1 doesn’t actually say. A few ways to reduce that risk:

  • Keep chunks small and focused, so each citation points at one clear idea.
  • Retrieve fewer, better chunks instead of many loosely related ones.
  • Add a review step for high-stakes answers, where a second check compares the answer with the cited text.
  • Log answers and citations, and review real conversations regularly.
  • Don’t describe citations to users as proof. “Based on these pages” is more accurate than “verified.”

Common mistakes

  1. Citing without metadata, so the sources list is empty or generic.
  2. Trusting model-generated links. Build links from your own metadata, never from text the model writes.
  3. Not validating numbers, so non-existent sources appear in answers.
  4. Citing whole pages when only one section applies, which makes verification hard.
  5. Showing too many sources, which looks like noise.
  6. Stale sources. If your index is out of date, you’ll cite pages that have changed or disappeared.
  7. Treating citations as a guarantee of accuracy.

What to remember

Source citations are mostly plumbing: keep metadata, number the context, ask for numbered citations, validate them in code and render a clean list. It’s a small amount of code, and it changes how users see the chatbot, from something that sounds confident to something they can check.

Do you show sources in your own chatbots, and do users actually click them? I’d like to hear how you handle it in the comments.

These notes come from AI chatbot projects we built for client websites at Techowdy.

Validating cited marker IDs in code before rendering the sources list catches one of the most embarrassing RAG bugs—a model emitting [4] when only three chunks were passed in the prompt. Stripping or flagging out-of-range markers before the UI displays them keeps every clickable link honest.

One extra step worth pairing with numbered inline markers is preserving the section anchor alongside the page URL. Dropping a user onto the top of a 3,000-word policy page forces them to Ctrl+F to verify the sentence, whereas a section heading or fragment link makes verification immediate.

TTechowdy5d ago

I really appreciate you reading this so carefully. Thanks for the kind words and the useful suggestion.