AIForum.

How to Add Source Citations to RAG Answers

On this page

THE SHORT ANSWER

Citations in a RAG answer depend on two things: a stable chunk ID that travels with each retrieved passage into the model's context, and a renderer that maps those IDs back to readable sources. This guide covers the context format, the system-prompt rules, the two common display patterns, and the failure modes worth checking before you ship.
Quick facts

Adding citations to a RAG answer takes two pieces of engineering, not one. You have to keep a stable identifier attached to every retrieved chunk as it travels into the model’s context, and you have to give the reader an interface that turns those identifiers back into readable sources. Skip the first and the model has nothing reliable to cite; skip the second and even a correct citation stays invisible.

This guide is for developers and technically curious practitioners who already have a retrieval pipeline returning chunks and now want the answers to point back at them. It follows the approach documented by Agentset for its search API and the UI and failure-mode analysis published by RedHop. The code samples below are reproduced from the Agentset documentation; the prompt template and the test list are illustrative unless stated otherwise.

The model can only cite what it can identify

When retrieved chunks are concatenated into one undifferentiated block of text, the model has no handle to reference. The result is one of the two failure modes RedHop names as the ones to design against: the model hallucinates a citation that does not exist, or it attaches a real citation to the wrong passage.

The fix is structural rather than stylistic. Give every chunk an identifier before it enters the prompt, and keep that identifier physically next to the chunk’s text so the model can copy it without guessing which passage is which.

Step 1: Pass a stable chunk ID with each chunk’s text

Agentset’s documentation is explicit about the mechanism: include each chunk’s id in the context you pass to the model. The reason to prefer IDs over “chunk 1, chunk 2, chunk 3” is stability. IDs stay the same no matter how many searches produced the context, which makes them more reliable than position-based numbering.

In TypeScript, the pattern is to map search results into objects that keep the ID adjacent to the text:

import { Agentset } from "agentset";

const agentset = new Agentset({
  apiKey: process.env.AGENTSET_API_KEY,
});

const ns = agentset.namespace("YOUR_NAMESPACE_ID");
const results = await ns.search("What is multi-head attention?");

// Keep the id with each chunk so the model can cite it
const context = results
  .map((r) => JSON.stringify({ id: r.id, text: r.text }))
  .join("nn");

The Python equivalent follows the same shape:

import json
import os
from agentset import Agentset

client = Agentset(
    namespace_id="YOUR_NAMESPACE_ID",
    token=os.environ["AGENTSET_API_KEY"],
)

results = client.search.execute(query="What is multi-head attention?")

# Keep the id with each chunk so the model can cite it
context = "nn".join(
    [json.dumps({"id": r.id, "text": r.text}) for r in results.data]
)

Two details matter. First, the ID travels with the text rather than in a separate list, so the model can copy it without a second lookup step. Second, the context is assembled from whatever the retriever returned for this query — if a single answer draws on three chunks from two different searches, all three IDs are present in the same context and none of them are renumbered.

What to store alongside the ID

A chunk ID is only useful if you can resolve it later. Keep a server-side record that maps each ID to the document title, a resolvable URL, and ideally a page or section anchor, plus enough of the chunk text to render a preview. If you also store a hash of the chunk text, you can detect when a source document has changed and an old citation now points at content that no longer says what the answer claims.

Step 2: Instruct the model to cite by ID — in the right place

Where the citation instructions belong depends on who owns the citation layer. Agentset notes that its hosted chat and playground always apply citation rules on top of your system prompt, so you should customize the prompt freely and not add citation-format instructions to it. If you are building your own application against the search API, the opposite applies: the system prompt is where the citation contract lives.

The refusal sentence below is the one Agentset documents; the remaining lines are an illustrative template you can adapt to your own output format.

You are an AI assistant. Answer questions based ONLY on the provided context.

Guidelines:
1. If the context does not contain information to answer the query, state clearly:
   "I cannot answer this question based on the available information."
2. Cite the id of every chunk you use, in square brackets, immediately after
   the claim it supports.
3. Never cite an id that does not appear in the context.

Guideline 3 addresses hallucinated citations directly. It gives the model an explicit rule to check itself against instead of relying on its own judgment about what looks like a plausible source. A cheap post-generation check — scan the answer for bracketed IDs and verify each one against the set of IDs you actually retrieved — catches the rest.

Step 3: Choose how the citation is displayed

RedHop separates the display question into two UI patterns used by consumer AI products. The first is inline footnotes, the Perplexity-style arrangement: numbered markers are interleaved with the prose, the sources appear in a panel or list at the bottom, and hovering a marker shows a preview of the source. The guide’s illustration of the pattern reads:

The governing law of this contract is Delaware [1], with arbitration in San Francisco [2].

The second pattern is the one associated with ChatGPT. RedHop groups the two products together as the reference implementations worth studying, and its write-up details the inline-footnote pattern most fully. In practice the choice comes down to how much of the source should be visible beside the answer: inline markers keep the link between claim and source tight but add visual noise, while a separate source list keeps the prose clean but asks the reader to scroll.

Either way, the renderer needs a mapping the model never sees — chunk ID to document title, URL, and anchor. Store that mapping in your application rather than in the prompt. A model that is responsible for producing URLs can produce URLs that do not resolve, and a broken link looks exactly like a hallucinated source to the reader.

If the answer is rendered in WordPress

When a RAG endpoint returns answer text plus a list of chunk IDs, the WordPress side is a rendering problem rather than a retrieval one: resolve each ID against your stored metadata and output an ordered source list beneath the answer. Keeping the resolution server-side means the model never needs to know a permalink, and a broken link becomes a metadata bug you can reproduce rather than a model behaviour you have to guess at.

Where citations break, and what each failure tells you

RedHop’s failure modes are short enough to memorize, and each one points at a different part of the pipeline:

  • A citation that does not exist. The model produced an ID that was never in the context. This is a generation-side problem, caught by an explicit “never cite an id that does not appear in the context” rule plus a post-generation check against the retrieved ID set.
  • A citation that points at the wrong chunk. The ID is real but does not support the claim. This is usually a retrieval problem — the passage that would have supported the claim was never in the context — and it is exactly the kind of bug citations make visible in the UI without digging through logs.
  • No citation where one was needed. Often the result of a context format that separated IDs from text, leaving the model unable to match them reliably.

This is also where the debugging value of citations shows up. RedHop lists debugging as the second of three reasons citations matter, alongside trust and verifiability and compliance — the last being non-negotiable in legal, medical, financial, and many enterprise deployments, where “where did this answer come from” is a requirement rather than a feature.

A verification loop to run before shipping

The checks below are a suggested protocol, not a record of measured results. Each one isolates a different link in the citation chain:

  1. Ask a question whose answer sits in exactly one chunk. Confirm the marker resolves to that chunk and not a neighbouring one.
  2. Ask a question the corpus cannot answer. Confirm the response contains the refusal sentence and no citation markers.
  3. Ask a question that requires two chunks. Confirm both IDs appear and that each is attached to the claim it actually supports.
  4. Log the ID-to-source mapping for every response. When a citation is wrong, the log tells you whether retrieval or generation is at fault.

If that mapping is missing from your logs, add it first. Without it, a wrong citation is indistinguishable from a wrong retrieval, and you will end up tuning prompts to fix a search problem.

What to do next

Start with the identifier, not the interface. Add a stable chunk ID to every result your retriever returns, pass it into the context next to the chunk’s text, and log the ID-to-source map. Once those three things exist, the display pattern is a styling decision and the citation rules in your system prompt have something real to point at.

If you are working through this on your own stack, the community is a good place to compare notes — share your retrieval setup, the context format you settled on, and any citation failure you have had to debug.

FAQ

Should I put citation-format instructions in my system prompt?

It depends on who owns the citation layer. Agentset's hosted chat and playground always apply their citation rules on top of your system prompt, so the documentation advises customizing the prompt freely and not adding citation-format instructions to it. When you build your own app against the search API, the system prompt is where you instruct the model to cite by chunk ID.

Why not just number the chunks 1, 2, 3 in the prompt?

Position-based numbering is less reliable than chunk IDs. Agentset notes that IDs stay stable no matter how many searches produced the context, so a citation still resolves correctly when the context is assembled from several retrieval calls.

What should the model do when the retrieved context has no answer?

Give it an explicit refusal path. The Agentset prompt template instructs the model to state: "I cannot answer this question based on the available information." That keeps a missing answer from being filled in from general knowledge and presented with a fabricated source.

How do I tell whether a bad citation is a retrieval bug or a generation bug?

Check the ID against the set of chunks you actually retrieved. If the ID was never in the context, the model invented it. If the ID is real but does not support the claim, the passage that would have supported it was probably never retrieved, which points at search rather than prompting.

References

  1. https://docs.agentset.ai/search-and-retrieval/citations
  2. https://www.redhopai.com/guides/rag-citations/

Related terms

Chunk ID
A stable identifier attached to a retrieved passage, used by the model to reference its source and by your application to resolve that reference to a document.
Grounding
Constraining a model's answer to information supplied in the prompt rather than its general training knowledge.
Inline footnote citation
A display pattern in which numbered markers sit inside the answer prose and the corresponding sources appear in a panel or list below.
Hallucinated citation
A citation the model produces that does not correspond to any source actually present in the retrieved context.
Retrieval-augmented generation (RAG)
A pipeline that retrieves relevant passages from a corpus and passes them to a language model as context for generating an answer.

Leave a Reply

Your email address will not be published. Required fields are marked *