Sub topic 9
Extracting passages into the model's context
This chapter covers the step between ranking and writing: how an answer engine turns a ranked list of pages into the short pieces of text the language model actually reads. It assumes you know what the retrieve-then-generate pipeline is, how a question becomes search queries, and how candidate pages get ranked. It also assumes you can read basic HTML.
Why passages, not pages
A language model has a context window, which is a fixed limit on how much text it can read in one request. A single web page can run to thousands of words, and an answer engine may consider ten or more pages per question. Pasting all of them in would be slow and expensive, and it would bury the relevant sentences in noise.
So the engine does not hand the model whole pages. It cuts each page into smaller units called passages (also called chunks or snippets), picks the few that best match the question, and places only those in the prompt. The model then writes its answer from that selected text.
This has a direct consequence for page authors. The page that ranked well is not what the model reads. A passage from the page is. A page can rank first and still contribute nothing if none of its passages answers the question cleanly.
The exact methods differ between ChatGPT search, Perplexity, and Copilot, and none of them publishes full details. The stages below describe the general approach used across retrieval-based systems. Treat specifics such as chunk sizes as typical values, not documented facts about any one engine.
The extraction stages
1. Getting the page text
The engine needs the page's text. It may use a copy stored at crawl time, or it may fetch the page live. Live fetches are common when a user asks about a specific URL, and they are made by user-initiated agents such as ChatGPT-User or Perplexity-User. Either way, the engine usually starts from the HTML your server returns.
Many extractors do not run JavaScript, or run it only in limited cases. If your main content is injected by client-side code after load, the extractor may see an empty shell. Check this by requesting the page without a browser:
curl -s -A "Mozilla/5.0" https://www.example.com/guide | grep -c "your key sentence"If the count is 0, the sentence is not in the server-delivered HTML, and a simple extractor probably cannot see it.
2. Removing boilerplate
Pages contain text that is not the content: navigation menus, cookie banners, related-link lists, footers, and ads. Extraction tools try to isolate the main content, often using HTML structure (such as <main> and <article>) and text-density heuristics. They drop blocks that look like repeated site furniture.
Semantic HTML helps here. A page whose body is a long series of anonymous <div> elements gives the cleaner less to work with than one that marks its main content clearly.
3. Splitting into passages
The cleaned text is divided into chunks. Common strategies include:
- Splitting at headings, so each section becomes a passage.
- Splitting by paragraph or by a target length, often a few hundred tokens.
- Using overlapping windows, so a sentence near a boundary appears in two chunks.
Heading-based splitting is the one authors can influence most. When a heading and the text beneath it form a complete unit, that unit survives chunking intact.
4. Scoring passages
Each passage is compared with the question, or with the rewritten search queries. Systems often combine two signals:
- Lexical matching, which rewards shared words and phrases (as in BM25, a classic keyword ranking formula).
- Semantic matching, which compares embeddings. An embedding is a list of numbers representing the meaning of a text, so passages with similar meaning score close to the question even without shared words.
Some engines then apply a reranker, a model that reads the question and a passage together and gives a more accurate relevance score. Rerankers are slower, so they usually run only on a short list.
5. Fitting a token budget
The prompt has a limited size, measured in tokens. A token is a piece of text, roughly three-quarters of an English word. The engine keeps the highest-scoring passages until the budget is used. It may also limit how many passages come from a single domain, so that one site does not fill the whole context.
6. Labeling sources
Each kept passage is placed in the prompt with an identifier tying it to its URL, for example [1] or [2]. These labels are what later let the model, or a post-processing step, attach a citation to a claim. The next chapter covers that step.
What a model-ready prompt looks like
The sketch below shows the idea. It is a simplified illustration, not any engine's real prompt.
question = "How often should I rotate API keys?"
passages = [
{"id": 1, "url": "https://example.com/keys",
"text": "Rotate API keys at least every 90 days, or immediately after a suspected leak."},
{"id": 2, "url": "https://example.org/security",
"text": "Short-lived credentials reduce the damage from a leaked key."},
]
context = "\n\n".join(f"[{p['id']}] {p['text']}" for p in passages)
prompt = (
"Answer the question using only the sources below. "
"Cite sources by number.\n\n"
f"Sources:\n{context}\n\n"
f"Question: {question}\nAnswer:"
)
print(prompt)Note what the model sees: two short strings and numbers. It does not see your site design, your other pages, or the surrounding text you did not include in the passage. If passage 1 had said "Rotate them at least every 90 days" without naming API keys, the sentence would depend on a heading the chunker may have cut off.
What makes a passage survive extraction
The behavior above suggests concrete page-level habits.
| Problem | Why it hurts extraction | Fix |
|---|---|---|
| Key content rendered only by JavaScript | Extractor sees an empty page | Serve main text in the initial HTML |
| Answer depends on "it", "this", "the above" | Chunk is read without its neighbors | Name the subject inside the passage |
| Answer spread across many short paragraphs and a table image | No single chunk holds it | Put the direct answer in one or two sentences |
| Important text inside images or PDFs scans | No usable text | Provide the text in HTML |
| Vague headings such as "Overview" | Heading gives the chunk no topic | Use descriptive headings that match the question |
| Content hidden in tabs or accordions | May be absent from extracted text | Confirm it is present in the served HTML |
A useful test is to copy one section on its own and read it with no other context. If a stranger could understand and quote it, the model probably can too.
<h2>How often should you rotate API keys?</h2>
<p>Rotate API keys at least every 90 days, and immediately after a suspected
leak. Shorter lifetimes limit how long a stolen key stays useful.</p>This block names its subject, answers in the first sentence, and carries its own question as a heading. It stays meaningful if cut out of the page.
Edge cases and gotchas
- Truncation. Some extractors read only the first part of a long page. Put the most important material early, rather than relying on a conclusion at the bottom.
- Snippet controls. Directives such as
nosnippetandmax-snippetin a robots meta tag tell search engines how much text they may show. Bing, whose index Copilot draws on, documents support for these controls. Setting them restrictively can reduce what is available to quote. Check each engine's documentation before relying on them. - Paywalls and login walls. If the extractor receives a login page, the passages come from that page, not your article.
- Stale cached text. If the engine uses a stored copy, the passage may predate your latest edit. Sitemaps and IndexNow, covered in a later chapter, shorten that gap.
- Duplicate text. Near-identical passages from several sites compete, and the engine may keep only one. Original wording with specific facts is easier to distinguish.
- Tables and lists. Extractors often flatten them into plain text. A table with unclear column headers can turn into a string of unlabeled numbers.
Checking what an extractor sees
You can approximate a simple text extractor with a few lines of Python. This is not what any engine uses, but it shows whether your main content survives a basic pass.
import re
import urllib.request
from html.parser import HTMLParser
class TextOnly(HTMLParser):
SKIP = {"script", "style", "nav", "footer", "header", "aside"}
def __init__(self):
super().__init__()
self.depth = 0
self.parts = []
def handle_starttag(self, tag, attrs):
if tag in self.SKIP:
self.depth += 1
def handle_endtag(self, tag):
if tag in self.SKIP and self.depth > 0:
self.depth -= 1
def handle_data(self, data):
if self.depth == 0 and data.strip():
self.parts.append(data.strip())
url = "https://www.example.com/guide"
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
html = urllib.request.urlopen(req, timeout=10).read().decode("utf-8", "replace")
parser = TextOnly()
parser.feed(html)
text = " ".join(parser.parts)
print(len(text.split()), "words extracted")
print(re.sub(r"\s+", " ", text)[:500])If the printed text is missing your main content, or is mostly menu items, fix the page's markup or rendering before worrying about anything else.
Summary
- Answer engines place selected passages, not whole pages, in the model's context.
- The path is: get the text, remove boilerplate, split into chunks, score, fit a token budget, and label sources.
- A page's rank decides whether it is considered. Its passages decide whether it is used.
- Self-contained passages, descriptive headings, early answers, and text present in the served HTML make extraction more reliable.
Exercise
A page ranks well for "how often should I rotate API keys," but answer engines never quote it. Its main content loads through JavaScript after the page opens, and its key paragraph begins "It should be done every 90 days." Name two problems this creates for passage extraction and give a fix for each.
Show answer
First, the content is loaded by JavaScript, so a simple extractor may receive an empty page. Fix: serve the main text in the initial HTML response. Second, "It" has no referent inside the passage, so a chunk cut out of the page does not say what should be done every 90 days. Fix: rewrite the sentence to name the subject, for example "Rotate API keys at least every 90 days," and place it under a heading that states the question.
Exercise
Why might a system that splits pages at headings give better passages than one that splits every 200 words, and when can the heading-based approach still fail?
Show answer
Splitting at headings keeps a topic and its explanation together, so each chunk is a complete unit. A fixed 200-word split can cut a sentence or an argument in half. The heading-based approach fails when headings are vague (such as "Overview"), when one section is very long and gets truncated or diluted, or when the answer depends on text in a different section.