Sub topic 2
The retrieve-then-generate pipeline
This chapter explains the working model behind a cited answer: a question goes in, a set of web pages is retrieved, and a language model writes an answer grounded in those pages. It assumes you know how search engines crawl and index pages, that you are comfortable with HTML and HTTP requests, and that you have a general idea of what a large language model (LLM) is.
Why a language model alone is not enough
An LLM stores patterns learned during training. It does not store a current copy of the web. Two problems follow from this:
- Stale knowledge. The model knows nothing that happened after its training data was collected.
- No sources. The model cannot reliably say where a claim came from. When it tries to recall a URL from memory, it can produce one that does not exist.
Answer engines address both problems with retrieval-augmented generation (RAG). In RAG, the system first retrieves documents relevant to the question. It then puts passages from those documents into the model's input and asks the model to write an answer based on them. The page URLs travel with the passages, so the system can show them as citations.
This is the idea behind ChatGPT search, Perplexity, and Copilot. The details differ between products, and the later chapters cover those differences. The shape of the pipeline is shared.
The stages
A cited answer passes through these stages:
- Query understanding and rewriting. The system decides whether it needs the web at all. If it does, it turns the user's message into one or more search queries.
- Retrieval. The queries run against a web index or a search API. The result is a list of candidate pages with titles, URLs, and snippets.
- Ranking and selection. The candidates are scored, and only a small number are kept.
- Passage extraction. The system reads the selected pages, or uses stored copies, and cuts out the passages most relevant to the question.
- Grounded generation. The model receives the question plus the passages and writes an answer from them.
- Citation attachment. Claims in the answer are linked to the sources they came from.
Each stage can drop your page. A page that is not crawled cannot be indexed. A page that is not retrieved cannot be ranked. A page that is not extracted cannot be quoted. Understanding the pipeline is mostly a matter of knowing where a page can fall out.
Stage 1: deciding whether to search
Answer engines do not always search. A request such as "rewrite this sentence more politely" needs no web results. A request such as "what changed in the latest release of a library" does. Many products make this decision with the model itself, which can emit a search request as a tool call. Some products also let the user force a search.
The consequence for site owners is that only some questions trigger retrieval at all. For the rest, no page is cited because none was fetched.
Stage 2: retrieval
Retrieval is a search over an index. Most engines use keyword matching, semantic matching, or both:
- Keyword (lexical) matching finds pages that contain the query terms. It rewards exact wording.
- Semantic matching converts the query and the passages into numeric vectors called embeddings. Passages whose vectors lie close to the query vector count as similar in meaning, even when the words differ.
Many systems combine the two and then merge the ranked lists, often with a scheme such as reciprocal rank fusion. The sketch below shows that merge in a few lines of Python. It illustrates the idea and does not describe any specific engine's code.
def reciprocal_rank_fusion(rankings, k=60):
"""Merge several ranked lists of URLs into one list."""
scores = {}
for ranking in rankings:
for position, url in enumerate(ranking, start=1):
scores[url] = scores.get(url, 0.0) + 1.0 / (k + position)
return sorted(scores, key=scores.get, reverse=True)
keyword_results = ["a.com/guide", "b.com/faq", "c.com/blog"]
semantic_results = ["b.com/faq", "d.com/docs", "a.com/guide"]
print(reciprocal_rank_fusion([keyword_results, semantic_results]))Running this prints ['b.com/faq', 'a.com/guide', 'd.com/docs', 'c.com/blog']. Pages that appear in both lists rise to the top. A page ranked well by only one method can still survive the merge.
Stage 3: ranking and selection
The first retrieval pass is built for speed, so its ordering is rough. A second pass, often called reranking, applies a slower and more accurate model to a short list. It scores each candidate against the actual question.
Then the system cuts the list. The cut exists because the model's input has a fixed size, called the context window, and because every extra passage adds cost and noise. Only a handful of sources usually survive. Ranking in a conventional search results page does not guarantee a place in this short list, and a page can be selected without ranking first.
Stage 4: passage extraction
Pages are long, and the model's context is limited. The system therefore works with passages rather than whole pages. Pages are split into chunks, for example by headings, paragraphs, or a fixed number of tokens. The chunks most similar to the question are placed into the prompt.
This has a direct effect on how content gets used. A chunk is judged mostly on its own. If a paragraph says "it supports this as well" and the noun it refers to sits three paragraphs earlier, the chunk loses its meaning once separated from its neighbors. Self-contained passages survive chunking better.
A simplified chunker shows the principle:
def chunk_by_paragraph(text, max_chars=800):
"""Split text into chunks that never cut a paragraph in half."""
chunks, current = [], ""
for paragraph in text.split("\n\n"):
if current and len(current) + len(paragraph) > max_chars:
chunks.append(current.strip())
current = ""
current += paragraph + "\n\n"
if current.strip():
chunks.append(current.strip())
return chunks
page = "Rotate keys every 90 days.\n\nStore them in a vault.\n\nNever commit them."
print(chunk_by_paragraph(page, max_chars=40))With max_chars=40, the output is ['Rotate keys every 90 days.', 'Store them in a vault.', 'Never commit them.']. Each chunk stands alone, so each must make sense alone.
Stage 5: grounded generation
The model now receives a prompt that contains the user's question, the numbered passages with their source URLs, and instructions such as "answer using only the sources below and cite them." Grounding means the answer is meant to rest on the supplied text instead of on the model's memory.
Grounding reduces unsupported statements but does not remove them. The model can still misread a passage, merge two sources into a claim neither makes, or add details from its training data.
Stage 6: citation attachment
Citations are produced in one of two common ways:
- Inline markers from the model. The prompt numbers the sources, and the model writes markers such as
[2]next to claims. The interface maps each marker to a URL. - Post-hoc matching. The system writes the answer first, then compares each sentence with the retrieved passages and attaches the best match.
Both methods have a failure mode. A cited page may not actually support the sentence beside it. A page may also have been retrieved but never cited, because the model did not use it. Retrieval is necessary for a citation. It is not sufficient.
Where you can and cannot influence the pipeline
| Stage | What you can influence | What you cannot control |
|---|---|---|
| Crawling and indexing | robots.txt, sitemaps, server availability | How often the engine returns |
| Query rewriting | Using the terms your audience uses | The exact queries the engine generates |
| Retrieval and ranking | Relevance, clarity, freshness | The engine's scoring models |
| Passage extraction | Clear headings, self-contained paragraphs | Where the engine splits the page |
| Generation and citation | Accurate, quotable statements | Which sources the model chooses to cite |
Later chapters take each row in turn.
Edge cases
- Search results differ between runs. Query rewriting and generation involve sampling, so the same question can produce different queries, sources, and citations. The final chapter returns to this.
- Live fetches. Some engines fetch a page at question time, for example when a user pastes a URL. This is separate from index-based retrieval and uses a different crawler identity.
- Paywalled or script-rendered content. A fetcher that does not run JavaScript sees only the initial HTML. Text that appears only after scripts run may never reach the passage stage.
- Duplicate content. If several pages say the same thing, the system may keep one and drop the rest.
Exercise
A page ranks well in a conventional search engine for a question, but an answer engine never cites it. Name two stages of the retrieve-then-generate pipeline where the page could have been dropped, and say why for each.
Show answer
Any two of these. (1) Selection: after reranking, only a handful of sources fit in the context window, so the page may have been cut. (2) Passage extraction: the page may have been chunked so that no single passage answered the question on its own. (3) Generation: the page may have been retrieved and placed in the prompt, but the model did not use it in the answer. (4) Query rewriting: the engine's rewritten queries may not have matched the page's wording.
Exercise
In the reciprocal_rank_fusion example, why does b.com/faq finish ahead of a.com/guide?
Show answer
b.com/faq is ranked 2nd by keyword and 1st by semantic matching, giving 1/62 + 1/61. a.com/guide is ranked 1st by keyword and 3rd by semantic matching, giving 1/61 + 1/63. Since 1/62 + 1/61 is larger than 1/61 + 1/63, b.com/faq scores higher.