Course contents · Lesson 10 of 16

Make Your RAG App Cite Its Sources, Hands-On

A RAG App · Lesson 10 of 16 · 12 min Hands-on

A colleague at Kettle and Leaf is about to resign and asks the handbook assistant how much notice to give. It replies "one month", which sounds right, but they want to see where the handbook says so. In this lesson you make the RAG app from lesson 9 cite its sources, check the citations in code, and refuse without calling the model when no document is close to the question.

Why an answer needs footnotes

The lesson 9 app's reply is plain text. A correct answer and a hallucinated one, a fluent sentence the model made up, look the same, so checking means searching the whole handbook.

A citation is a pointer from a claim to the passage it came from, and it turns checking into reading one quoted line. In the before-and-after, notice that the answer's words do not change; only the second version tells you where to look.

Before and after for the question What is the notice period for resignation. Both panels show the same answer: the notice period is one month for permanent staff, and 7 days during the first three months. Before, with no citations, a warning sign asks where this comes from: right or made up, you cannot tell, and to check it you must read every file of the handbook. After, the answer ends with the marker [1], and a Sources list shows [1] 06-leaving-the-company.md, section Notice period, with the quoted sentence. Same words; only one can be checked in seconds.
Word for word the same answer; only the Sources list makes it checkable.

Number the chunks, then ask for answer and sources

Lesson 9 already numbered the chunks [1] to [4]. Now each number also carries the chunk's file name and section, the metadata kept since lesson 7, and the rule tells the model to write the number after each sentence. A digit is easy for a 3B model to copy; code turns it back into a file and a line. The context starts like this:

[1] 06-leaving-the-company.md, "Notice period"
## Notice period

If you decide to resign, tell your manager and email the people team. The notice period is ...

Parsing a "Sources:" line out of free text is fragile, so the script asks for structured JSON with two fields: answer, the text with its markers, and sources, the chunk numbers it cites. A pydantic class defines the shape, and its schema goes in the format field, as in lesson 4:

class CitedAnswer(BaseModel):
    answer: str          # "The notice period is one month for permanent staff [1]."
    sources: list[int]   # [1]

SCHEMA = CitedAnswer.model_json_schema()   # sent as "format", and pasted into the prompt

This is the pattern in Ollama's structured outputs docs. The schema only says "a list of integers", so a reply citing [7] still fits it. When the context does not answer the question, the rule asks for a refusal: exactly not found in the documents and an empty list.

An example answer, wording illustrative: Customers can return unopened tea within 30 days of delivery [1], and the refund is paid within 5 working days of the parcel arriving [3]. An arrow from the marker [1] leads to a source card for 05-customer-returns.md, section The return window, quoting Customers can return unopened tea within 30 days of delivery for a full refund. An arrow from [3] leads to a card for 05-customer-returns.md, section Refunds, quoting Refund the original payment method within 5 working days of receiving the parcel. Chunks 2 and 4 were retrieved but not cited.
Each marker is a footnote: it leads to one chunk, its file and section, and a line you can read.

Check the citations in code

A marker is text the model wrote, so check it before anyone trusts it. citations.py has two hard rules: every cited number, in the markers and in sources, must be one of the retrieved chunks, and an answer that is not a refusal must cite at least one. A reply that fails pydantic's check or breaks a rule is retried once with the error message, as in lesson 4, then rejected.

A soft check follows. A claim's key words are its numbers and its words of four or more letters, minus common ones such as "that". If fewer than half appear in the chunks it cites, the claim is flagged as weak support. python3 citations.py runs both checks on four fixed replies that cite the "Notice period" chunk, without a model, so its output never varies. After a header line it prints:

1. The notice period is one month for permanent staff [1].
   numbers ok; key words found in the cited chunk: 5 of 5: supported

2. The notice period is one month [5].
   rejected: cites [5], but only chunks [1] to [4] exist

3. Refunds are paid within 5 working days [1].
   numbers ok; key words found in the cited chunk: 1 of 6: weak support

4. Permanent staff have 7 days of notice [1].
   numbers ok; key words found in the cited chunk: 5 of 5: supported
   but: false. The chunk gives permanent staff one month; 7 days is for probation.

Reply 2 cites a chunk that does not exist. Reply 3 is about refunds and only "days" matches. Reply 4 passes both checks and is still false; the last section returns to it. In the flowchart, note that the score check runs before the model and the citation check after.

Flowchart of ask_with_sources.py. 1, the question. 2, retrieve the top 4 chunks with a cosine score for each. Decision: best score at least the threshold? No: Not found in the documents, model not called, default 0.50. Yes: 3, ask the model with chunks [1] to [4] and the JSON schema. Decision: valid JSON that cites only [1] to [4]? No: retry once with the error, the model sees what was wrong, back to step 3; after a second failure, reject, no answer shown. Yes: show the answer and the Sources list, with key words checked and weak claims flagged.
Two exits show no model answer: one before the model is called, one after two failed checks.

Refuse before calling the model

Top-k always returns four chunks, however unrelated, as the cricket question showed in lesson 9. The refusal rule uses the cosine score: if even the best chunk scores below a threshold, MIN_SCORE of 0.5 by default, the script prints Not found in the documents without calling the chat model. That saves a slow call, and a small model never gets to answer from unrelated text.

Lesson 8 advised comparing scores with each other, not with a fixed line, and a threshold is such a line. So 0.5 is a starting point for this model and handbook, not a universal number: read the best scores of questions the handbook does and does not answer, and set --min-score between them. The model's own refusal stays as a second layer.

Run it on the handbook

The folder course-labs/building-llm-apps/10-citations holds its own copy of the handbook, the index step from lesson 9, and pinned requests and pydantic. With Ollama running on port 11434 and both models pulled, run:

cd course-labs/building-llm-apps/10-citations
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 index.py data/handbook
python3 ask_with_sources.py 'What is the notice period for resignation?'

index.py should report 34 chunks and Saved the chunks and their vectors to index.json. The last command prints the numbered chunks, each attempt, then the answer. Trimmed, with illustrative scores and wording:

Top 4 of 34 chunks (best score 0.741, threshold 0.50):
  [1] 0.741  06-leaving-the-company.md, "Notice period"
  ...
attempt 1: checks passed

Answer:
The notice period is one month for permanent staff, and 7 days during the first three months, the probation period [1].

Sources:
  [1] 06-leaving-the-company.md, "Notice period" (score 0.741)
      "The notice period is one month for permanent staff, and 7 days during your first three months, the probation period."
...
  claim 1 cites [1]: 11 of 11 key words found there

It worked if the answer says one month, or 7 days in probation, and its marker's source is 06-leaving-the-company.md. Code picks the quoted line from the chunk's own text, so it is a real line of the file. attempt 1: rejected then attempt 2: checks passed is the retry working; No module named 'pydantic' means the environment is not active.

Then ask 'Who won the 2011 cricket World Cup?'. You should see Not found in the documents. and a reason: the best score, for example 0.452, is below 0.50, so the model was not called. If your score is higher, or --min-score 0 turns the rule off, the model is called and should refuse by itself: (the model found no answer in the 4 chunks).

Honest limits: a citation is not proof

Look again at reply 4. Chunk 1 exists and holds every key word, because it mentions both permanent staff and 7 days. The claim is still wrong: it joined two true facts the wrong way. A model can cite the right chunk for a wrong claim, and no word count catches that.

So citations make checking fast, not answers correct. Show the quoted line next to the answer, keep each claim short with its own marker, and measure how often answers are right, which lesson 11 does with a test set.

Check yourself

The model cites [6], but only 4 chunks were retrieved. Why reject a reply the schema accepted?

The schema only says "a list of integers" and knows nothing about this question's chunks. The code check does, and [6] points to nothing a reader could open.

"Can I bring my dog to the office?" scores 0.58 against a threshold of 0.5. What happens, and is that a bug?

The model gets four loosely related chunks and should answer "not found in the documents". Not a bug: the threshold only stops clearly unrelated questions, and the model's refusal is the next layer.

An answer passes every check. Can you tell the user it is correct?

No. The checks show the claim points to a real chunk with the same words, not that it says what the chunk says: "7 days for permanent staff" passes against the notice chunk.