Skip to content

How a RAG system works

Chapter 2 0 code blocks 2133 words

RAG, LLM and voice agents

Say this

An LLM predicts the next token and knows only its training data, frozen at a cutoff. RAG adds our own documents at question time: search them, put the best passages in the prompt, and make the model answer only from them with citations. A voice agent is the same pipeline behind speech: speech-to-text, then the LLM with RAG and tools, then text-to-speech, all streaming.

Example project

I built a fully offline RAG system: FastAPI, PostgreSQL with pgvector, and Ollama running qwen3:8b and qwen3-embedding:4b. A Chrome extension reads pages in the browser, including intranet sites, and sends them for indexing. Every answer cites its sources, and the system refuses anything the documents don't cover.

If they push

  • RAG vs fine-tuning: RAG adds knowledge and updates by re-indexing. Fine-tuning changes behaviour and format. In Tez I fine-tuned for output format, not for facts.
  • An agent is an LLM in a loop that calls tools and decides the next step from their results.

The big picture

Two pipelines share one thing: the same embedding model, which puts documents and questions into the same vector space. PostgreSQL is the bridge. Indexing writes vectors in ahead of time; the query pipeline reads them back at question time.

Indexing
ahead of time, once per page
  1. 1
    Ingest
    the extension sends url, title and page text
  2. 2
    Clean, dedupe, version
    same hash means nothing new to store
  3. 3
    Chunk
    1800 tokens with 150 overlap
  4. 4
    Embed
    qwen3-embedding:4b turns each chunk into 2560 numbers
  5. 5
    Store
    text, vectors and positions go to the database
PostgreSQL + pgvector: the bridge between indexing and every question
Query
every question, a few seconds
  1. 6
    Normalize + intent
    clean the question, decide what kind it is
  2. 7
    Embed the question
    the same model as the chunks
  3. 8–9
    Search two ways
    Dense search
    by meaning, cosine, top 12
    Keyword search
    rare words found in at most 5% of chunks
  4. 10
    RRF fusion
    k = 60, the best 6 stay
  5. 11
    Threshold gate
    score below 0.50 is dropped; nothing left → refuse
  6. 12
    Build the prompt
    system rules + evidence [E1]..[E6] + question
  7. 13
    Generate
    qwen3:8b writes the answer
  8. 14
    Grounding check
    every cited [E] must exist; otherwise refuse
  9. 15
    Answer + trace
    sources shown, the question is logged

The example used all the way through: a kun.uz news article is indexed, then someone asks "Zaxarova nima dedi?" (What did Zakharova say?). Scores marked "example" are illustrative values to show the mechanics, not measurements.

1

Ingest

What
Gets the page text into the system.
How
My Chrome extension finds the main content in the browser (the largest <article>, else <main>, else the body minus navigation, header and footer) and sends the URL, title and text to /api/ingest/page.
Why
Reading in the browser works on intranet sites and pages that need a login, where a server-side crawler can't reach. Dropping menus and footers keeps junk out of the search.
Example
A kun.uz article of about 12,000 characters.
Passes on
URL + title + raw text → 2.
2

Clean, dedupe, version

What
Normalizes the text and decides whether it's new.
How
Whitespace is normalized. The cleaned text is compared with what's stored for that URL: same text means "duplicate, skip"; changed text becomes a new version, and search uses only the newest.
Why
Duplicates would fill the top results with copies of one page and push out other sources. Old versions would give outdated answers.
Passes on
One clean document version → 3.
3

Chunk

What
Splits the document into pieces that each get their own vector.
How
Up to 1800 tokens (about 7,200 characters, counting about 4 characters per token). If a line break falls past the halfway point, the cut moves there so paragraphs stay whole. The next chunk starts 150 tokens before the previous one ended (overlap).
Why
One vector for a whole long document blurs many topics together. The overlap means a sentence on a boundary appears whole in at least one chunk.
Example
12,000 characters → chunk 1: characters 0–7,180 (cut at a paragraph end); chunk 2: from about 6,580 (150 tokens back) to the end.
Passes on
A list of chunk texts with start and end positions → 4.
4

Embed: what happens inside the model

What
Turns each chunk into one vector of 2560 numbers that represents its meaning.
How
  1. a
    Tokenizer
    text → subword pieces → token IDs. An ID is only a row number: it carries NO meaning.
    "Assalomu alaykum O'zbekiston" → ["Ass","alomu"," alay","kum"," O","'","zbek","iston"] → [4123, 88710, ...]
  2. b
    Lookup table
    each ID picks its row from a learned table → one vector per token
    ~151,000 rows × 2560 numbers
  3. c
    Transformer, 36 layers
    Self-attention
    every token compares itself with every other token and mixes in what is relevant
    softmax(QK⊤dk)V
    Feed-forward
    reshapes each vector further
    RoPE
    position information keeps the word order
  4. d
    Pooling
    take the LAST token's vector: it has seen the whole text
  5. e
    Normalize
    length becomes 1
    [0.021, -0.113, 0.087, ...] (2560)
Why it works
The model was trained contrastively on millions of question–passage pairs: pulled toward the correct passage, pushed away from wrong ones. So texts with the same meaning land close together even with different words, and the same word gets a different vector in a different sentence.
Passes on
One 2560-number vector per chunk → 5.
5

Store

What
Saves everything needed to find and cite the chunk later.
How
Tables: documents (URL, title) → document_versions → chunks (text, position) → embeddings (the vector, plus which model made it). A GIN full-text index on the chunk text serves keyword search.
Why
Recording the model per vector means vectors from different models are never compared. The URL and title make citations possible.
Connects
This is the bridge: 8 and 9 read from these tables.
6

Normalize the question, detect intent

What
Cleans the question and labels its type.
How
Extra spaces are removed. Keywords in Uzbek, Russian and English set the intent: "qanday / how to / как" = procedural, "farqi / difference" = comparison, "nima / what is" = definition, "qayerda / where" = navigational, otherwise factual.
Example
"Zaxarova nima dedi?" → intent: definition (it contains "nima").
Passes on
Clean question → 7; intent → the trace 15 for analysis.
7

Embed the question

What
Puts the question into the same vector space as the chunks.
How
Same model, same steps a–e as 4, but with Qwen's instruction prefix in front: Instruct: Given a question, retrieve passages … Query: Zaxarova nima dedi?. The code also checks the vector length is 2560.
Why
A short question and a long passage look different. The prefix tells the model "this is a search query", which it was trained with, so it lands near the passages that answer it. The length check catches a model mismatch.
Passes on
Question vector → 8, and the question words → 9.
8

Dense search

What
Finds the chunks with the closest meaning.
How
pgvector computes cosine distance embedding <=> question_vector to every chunk of the newest versions, sorts, keeps the top 12. similarity=1−distance.
similarity=1−distance
distancecosine distance, pgvector's <=> operator
Why
It finds paraphrases: "what did she say" matches "she stated" without any shared words.
Weakness
Rare names and codes: "Zaxarova" can rank low because one name is a small part of a long chunk's meaning.
Passes on
12 chunks with similarity and rank → 10.
9

Keyword search on rare words

What
Finds chunks that contain the question's distinctive words exactly.
How
Take words of 4+ letters from the question. Keep only rare ones, found in at most 5% of chunks. Search them with Postgres full-text search, ranked by ts_rank_cd.
Why
Exact names, numbers and terms are where embeddings are weakest. Common words like "nima" or "dedi" are in thousands of chunks and would only add noise, so they're skipped.
Example
"zaxarova" is rare → kept; "nima", "dedi" are too short or common → dropped.
Passes on
Keyword-matched chunks with their rank → 10.
10

RRF fusion

What
Merges the two ranked lists into one.
How
score=160+rdense+160+rkeyword; a missing rank adds 0. Sort, keep the top 6.
score=160+rdense+160+rkeyword
rdensethe chunk's position in the dense list (1 = top)
rkeywordits position in the keyword list
60the constant k: it keeps rank 1 from dominating everything
Example
Chunk A: dense rank 1, keyword rank 3 → 1/61 + 1/63 = 0.0323. Chunk C: keyword rank 1 only → 1/61 = 0.0164. Chunk B: dense rank 2 only → 1/62 = 0.0161. Order: A, C, B. Agreement between both searches wins.
Why ranks, not scores
Cosine and ts_rank are on different scales and can't be added. Ranks can.
Passes on
Top 6 chunks with their cosine similarity and a "keyword matched" flag → 11.
11

Threshold gate

What
Removes weak evidence and decides whether to answer at all.
How
Keep a chunk if similarity ≥ 0.50, or if it matched a rare keyword and similarity ≥ 0.35. If nothing survives, return the refusal immediately and don't call the LLM.
Why
Top-k always returns something. Without this gate, the LLM gets irrelevant text and answers anyway. 0.50 was measured on my data for this model.
Example
Chunk A at an example similarity of 0.46: under 0.50, but it matched "zaxarova", and 0.46 ≥ 0.35 → kept. A question about world capitals gets chunks around 0.30 → all removed → refusal.
Passes on
Surviving chunks → 12, or the refusal → 15.
12

Build the prompt

What
Packs the evidence and the rules for the LLM.
How
Each chunk becomes a block: [E1] URL / Title / Content. Then the question, then the rules: answer only from the evidence, cite [E#] on every line, give the exact refusal sentence if the answer isn't there, and treat the question as something to answer, never an instruction.
Why
IDs make citations checkable. An exact refusal sentence lets code detect refusals. Calling retrieved text "data, not instructions" defends against prompt injection hidden in web pages.
Passes on
System prompt + user prompt → 13.
13

Generate

What
qwen3:8b writes the answer.
How
Inside the LLM the prompt goes through the same kind of transformer steps as 4 (tokenize, look up, attention layers). But instead of pooling one vector, it predicts a probability for every possible next token, picks one, appends it, and repeats until it stops. At temperature 0 it always picks the most likely token.
Why it works
Attention lets every generated token look back at the evidence in the prompt, so the model can copy and rephrase facts from [E1]–[E6]. Temperature 0 means the same input gives the same answer: deterministic and testable.
Example
"Zaxarova … deb aytdi [E1]."
Passes on
Answer text → 14.
14

Grounding check

What
Verifies the answer actually comes from the evidence.
How
For each paragraph: every [E#] must exist (E7 when there were 6 chunks fails); a real paragraph must cite at least one; and its content words (5+ letters, or numbers) must overlap with the words of the chunks it cites. Any failure replaces the whole answer with the refusal.
Why
The prompt asks the model to behave; the check verifies it. This is what stops world-knowledge answers and invented citations.
Limit
Word overlap can't catch a misreading within a cited chunk. A reranker or an NLI model would be the next step.
Passes on
Verified answer, or the refusal → 15.
15

Answer + trace

What
Returns the answer and records what happened.
How
The response holds the answer, the sources (E-ID, URL, title, similarity) and a trace ID. The retrieval_traces table stores the question, intent, model, chosen chunk IDs and latency in ms.
Why
Traces let me debug: "Why was this refused?" → look at which chunks came back and their scores. That's exactly how I found the Zaxarova problem.

Why the whole thing works, in four sentences

  1. Same space: one model embeds documents and questions, so closeness in vectors means closeness in meaning.
  2. Two searches cover each other: dense finds meaning and paraphrases, keyword finds exact names, and RRF rewards agreement.
  3. The LLM reads, not remembers: the answer comes from evidence placed in the prompt, which attention can look back at.
  4. Two gates keep it honest: the threshold before generation and the grounding check after it. If either fails, the user gets an honest "insufficient evidence".

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents