GyaanStack. Blog

Articles / ragprojectspython

Turn a website into a chatbot that cites its pages (polite crawler, Python, no API key)

Crawl a site within robots.txt and a rate limit, index the article text, answer with source URLs, check grounding, and re-crawl only what changed.

By Raghunath · · 24 min read

Most site search returns ten links and leaves the reading to you. A small retrieval-augmented bot can read the pages for you and answer with the URL of the section it used. Building one is a crawler problem first and a model problem second: which pages you may fetch, how fast, what part of each page is the article, and how to notice when a page changes without downloading the whole site again.

This post builds that bot in about 320 lines of Python and runs it against this blog, blog.gyaanstack.com, capped at 30 pages and one request every two seconds. Everything below is real output from one run on Python 3.15 with Beautiful Soup 4.15 and SQLite 3.54. Retrieval is SQLite's built-in full-text search. Generation goes through a local model in Ollama, and there is a stub generator behind the same interface so the code runs with no model at all.

If you want the PDF version of this idea, with page numbers instead of URLs, read the PDF question-answering bot. For the large-scale write side (connectors, embedding cost, blue/green re-indexing), see RAG ingestion pipeline design. This post stays on the parts specific to websites.

What the bot does#

 robots.txt ──> allowed? crawl-delay?          sitemap.xml ──> URLs + <lastmod>
        │                                             │
        └──────────────┬──────────────────────────────┘
                       v
   for each same-site URL (max 30, 2 s apart):
     lastmod unchanged?          -> skip, no request
     GET with If-None-Match      -> 304: keep old chunks
     200: extract <article> text -> hash unchanged? keep : re-chunk
                       │
                       v
   SQLite: pages(url, lastmod, etag, hash)   chunks(FTS5: text, section, url#anchor)
                       │
 question ──> BM25 top 4 prose chunks ──> evidence gate ──> LLM (or stub)
                                                          │
                                answer with [n] markers + URL#section
                                                          │
                                grounding check per sentence

Two tables carry the whole design. pages remembers what the crawler saw last time, so a refresh can skip work. chunks is an FTS5 virtual table whose rows point at a URL plus the section's id, so every citation lands on the heading the answer came from, not at the top of a long page.

Setup#

python3 -m venv .venv
.venv/bin/pip install beautifulsoup4      # 4.15.0 here; everything else is standard library
ollama pull qwen3:4b-instruct             # optional; the stub needs nothing

No LangChain, no vector database. Python's standard library already has a robots.txt parser (urllib.robotparser), an HTTP client and SQLite with FTS5 compiled in on most builds. Check yours with python3 -c "import sqlite3; sqlite3.connect(':memory:').execute('create virtual table t using fts5(x)')".

Crawl politely#

A crawler that ignores the site's rules gets blocked, and on someone else's site it can cost them real money in bandwidth. Four rules cover most of it:

  1. Read robots.txt and obey it. The format is now a standard, RFC 9309, which also says a crawler should not use a cached copy of robots.txt for more than 24 hours.
  2. Get the URL list from sitemap.xml instead of following every link. The sitemaps protocol gives you each URL and an optional <lastmod> date, and caps one file at 50,000 URLs or 50 MB.
  3. Stay on one host, over HTTPS, and skip pages with no answers in them (tag listings, the about page).
  4. Send a User-Agent that names the bot and links to a contact page, and wait between requests. Honor Crawl-delay if the site sets one; it is not part of RFC 9309, but Python's parser reads it anyway.

The fetch function sends conditional headers when it has them, which matters later for refreshes:

SITE = "https://blog.gyaanstack.com/"
UA = "GyaanStackSiteBot/0.1 (+https://blog.gyaanstack.com/about/)"
MAX_PAGES = 30
DELAY = 2.0          # seconds between requests, raised if robots.txt asks for more
SKIP = ("/tag/", "/about/")
HOST = urlparse(SITE).netloc


def fetch(url, etag=None, last_modified=None):
    """GET with conditional headers. Returns (status, body, headers)."""
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    if etag:
        req.add_header("If-None-Match", etag)
    if last_modified:
        req.add_header("If-Modified-Since", last_modified)
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return r.status, r.read().decode("utf-8", "replace"), r.headers
    except urllib.error.HTTPError as e:
        return e.code, "", e.headers


def same_site(url):
    p = urlparse(url)
    return p.scheme == "https" and p.netloc == HOST and not any(s in p.path for s in SKIP)


def sitemap_urls(robots):
    maps = robots.site_maps() or [urljoin(SITE, "sitemap.xml")]
    _, xml, _ = fetch(maps[0])
    ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"}
    out = []
    for u in ET.fromstring(xml).findall("s:url", ns):
        loc = u.findtext("s:loc", namespaces=ns)
        mod = u.findtext("s:lastmod", default="", namespaces=ns)
        if loc != SITE and same_site(loc) and robots.can_fetch(UA, loc):
            out.append((loc, mod))
    return out

urllib raises HTTPError for a 304, so the except branch turns it back into a status code. robots.site_maps() returns the Sitemap: lines from robots.txt, which is where this blog announces its sitemap. A site with a sitemap index file (a sitemap of sitemaps) needs one more level of parsing; this one has a single file.

Keep only the article#

Every page on a typical site carries the same header, navigation, table of contents, newsletter box and footer. If that text goes into the index, every page matches a query about "RAG" because the nav says "RAG", and the chunks the model sees are half boilerplate. Strip it before chunking:

def extract(html):
    """Keep the <article>; drop nav, table of contents, breadcrumbs, CTA boxes, scripts.
    Returns sections of (kind, text) parts, kind is prose or code."""
    soup = BeautifulSoup(html, "html.parser")
    title = soup.title.get_text(strip=True) if soup.title else ""
    art = soup.find("article") or soup.find("main") or soup.body
    for tag in art.find_all(["nav", "aside", "script", "style", "footer", "form"]):
        tag.decompose()
    for tag in art.select(".crumbs, .meta"):
        tag.decompose()
    sections, current = [], {"id": "", "head": title, "parts": []}
    for el in art.find_all(["h2", "h3", "p", "li", "pre", "tr"]):
        if el.name in ("h2", "h3"):
            sections.append(current)
            head = el.get_text(" ", strip=True).removesuffix("#").strip()   # drop the anchor link
            current = {"id": el.get("id", ""), "head": head, "parts": []}
        elif el.find_parent(["li", "pre", "tr"]):
            continue                                  # already taken in by its parent
        elif el.name == "pre":
            current["parts"].append(("code", el.get_text().strip()))
        elif el.name == "tr":                         # one table row -> "cell | cell | cell"
            cells = [c.get_text(" ", strip=True) for c in el.find_all(["th", "td"])]
            current["parts"].append(("prose", " | ".join(cells) + "."))
        elif text := el.get_text(" ", strip=True):
            current["parts"].append(("prose", text))
    sections.append(current)
    return title, [s for s in sections if s["parts"] and s["head"].lower() != "sources"]

The selectors (article, .crumbs, .meta) are specific to this blog's templates. Open two or three pages of your target site in the browser's inspector and write the equivalent; it takes five minutes and does more for answer quality than any prompt change. For sites without semantic HTML, a general-purpose extractor such as trafilatura is the next thing to try.

Three choices in that function came from looking at bad output during the build:

  • Code blocks are tagged, not mixed in. The first version put <pre> text into prose chunks. A question about tokens per word then retrieved a chunk that was 90% printed program output, and the stub answer was a wall of numbers. Code now goes into its own chunks, and retrieval asks for prose only.
  • Table rows become sentences. Taking each <td> as a separate paragraph produced lines like "0.951 AUC" with no row label. Joining a row with | keeps "Post-outcome feature | 0.951 AUC | 0.734 AUC" together.
  • Reference lists are dropped. Every post here ends with a "Sources" section full of library names. Those sections won BM25 matches for questions they could not answer.

Chunk by section, keep the anchor#

The blog's headings already split each post into topics, so a chunk is one section, cut on paragraph edges if it runs past 1,200 characters, with one paragraph carried over as overlap:

def chunk(sections, max_chars=1200, overlap=1):
    """Prose: one chunk per section, long sections split on paragraph edges with one
    paragraph of overlap. Code blocks become their own chunks so they never crowd out prose."""
    for s in sections:
        buf = []
        for kind, text in s["parts"]:
            if kind == "code":
                yield s, "code", text[:max_chars * 2]
                continue
            if buf and sum(len(p) for p in buf) + len(text) > max_chars:
                yield s, "prose", "\n".join(buf)
                buf = buf[-overlap:]
            buf.append(text[:max_chars])
        if buf:
            yield s, "prose", "\n".join(buf)


def index_page(db, url, title, sections):
    db.execute("DELETE FROM chunks WHERE url LIKE ?", (url + "%",))
    n = 0
    for s, kind, text in chunk(sections):
        anchor = url + ("#" + s["id"] if s["id"] else "")
        db.execute("INSERT INTO chunks VALUES (?,?,?,?,?)", (text, title, s["head"], anchor, kind))
        n += 1
    return n

index_page deletes a page's old chunks before inserting new ones, so a re-crawl replaces a page instead of piling duplicates on top of it. The LIKE url% match works because every URL here ends in /; /rag/% cannot match /rag-cheat-sheet/. The schema is two statements:

CREATE TABLE IF NOT EXISTS pages(url TEXT PRIMARY KEY, title TEXT, lastmod TEXT,
                                 etag TEXT, last_modified TEXT, hash TEXT, fetched REAL);
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(text, title, section, url UNINDEXED, kind UNINDEXED);

The crawl loop and keeping the index fresh#

A refresh should cost almost nothing when nothing changed. The loop checks three things, cheapest first:

  1. Sitemap <lastmod>. If it matches what was stored, skip the URL with no request. Google's sitemap guide says it uses lastmod only when the value is "consistently and verifiably" accurate, and the same caution applies to your crawler: some sites stamp today's date on every URL.
  2. Conditional GET. Send the stored ETag as If-None-Match and the stored Last-Modified as If-Modified-Since. A server that supports them answers 304 Not Modified with no body (RFC 9110, section 13).
  3. Content hash. On a full 200, hash the extracted sections, not the raw HTML. A page whose sidebar or related-posts list changed has new markup and the same article; hashing markup would re-index it for nothing.
def crawl(db, limit=MAX_PAGES):
    robots = urllib.robotparser.RobotFileParser(urljoin(SITE, "robots.txt"))
    robots.read()
    delay = max(DELAY, robots.crawl_delay(UA) or 0)
    listed = sitemap_urls(robots)
    urls = listed[:limit]
    known = {r[0]: r[1:] for r in db.execute("SELECT url, lastmod, etag, last_modified, hash FROM pages")}
    stats = {"skipped_lastmod": 0, "not_modified_304": 0, "unchanged_hash": 0, "indexed": 0, "chunks": 0}
    for url, lastmod in urls:
        old = known.get(url)
        if old and lastmod and old[0] == lastmod:
            stats["skipped_lastmod"] += 1          # sitemap says nothing changed: no request at all
            continue
        status, html, headers = fetch(url, *(old[1:3] if old else (None, None)))
        time.sleep(delay)
        if status == 304:
            stats["not_modified_304"] += 1
            db.execute("UPDATE pages SET lastmod=?, fetched=? WHERE url=?", (lastmod, time.time(), url))
            continue
        if status != 200:
            print("skip", status, url)
            continue
        title, sections = extract(html)
        h = hashlib.sha256(repr(sections).encode()).hexdigest()   # hash the text, not the markup
        if old and old[3] == h:
            stats["unchanged_hash"] += 1
        else:
            n = index_page(db, url, title, sections)
            stats["indexed"] += 1
            stats["chunks"] += n
        db.execute("INSERT OR REPLACE INTO pages VALUES (?,?,?,?,?,?,?)",
                   (url, title, lastmod,
                    headers.get("ETag"), headers.get("Last-Modified"), h, time.time()))
    gone = set(known) - {u for u, _ in listed}
    for url in gone:                                # page left the sitemap: drop it from the index
        db.execute("DELETE FROM pages WHERE url=?", (url,))
        db.execute("DELETE FROM chunks WHERE url LIKE ?", (url + "%",))
    db.commit()
    stats["removed"] = len(gone)
    return stats

Deletions are compared against the full sitemap, not the capped list. An earlier version compared against the first 30 URLs, which meant that every new post pushed an older one past the cap and the crawler deleted a page that still existed.

Here are four runs against the live blog, one after another. The first builds the index. The second runs a few minutes later. The third pretends every sitemap date changed, which forces a conditional GET per page. The fourth also forgets the stored validators, so every page comes back in full and only the hash can save work.

$ python crawl.py                                   # first crawl
{'skipped_lastmod': 0, 'not_modified_304': 0, 'unchanged_hash': 0, 'indexed': 30, 'chunks': 835, 'removed': 0} 67.5s
$ python crawl.py                                   # a few minutes later
{'skipped_lastmod': 29, 'not_modified_304': 0, 'unchanged_hash': 0, 'indexed': 1, 'chunks': 31, 'removed': 0} 2.5s
$ python crawl.py --forget-lastmod                  # sitemap dates all bumped
{'skipped_lastmod': 0, 'not_modified_304': 17, 'unchanged_hash': 13, 'indexed': 0, 'chunks': 0, 'removed': 0} 65.4s
$ python crawl.py --forget-lastmod --forget-etag    # no validators either
{'skipped_lastmod': 0, 'not_modified_304': 0, 'unchanged_hash': 30, 'indexed': 0, 'chunks': 0, 'removed': 0} 67.1s

The second run caught a post published between runs: one new URL at the top of the sitemap, fetched and indexed, while the other 29 were skipped on lastmod with no request. The page that fell off the 30-page cap stayed in the index, which is the fix above working.

In the third run, only 17 of 30 pages answered 304. The other 13 came back as full 200 responses with a new ETag, because the site had been rebuilt and redeployed in between, and the article text was identical. The hash caught all 13, so nothing was re-indexed. Without the hash layer, every deploy would look like a site-wide change.

The timings show where the time goes. Thirty pages at two seconds apart is 60 seconds of deliberate waiting, so a full crawl and a 304 sweep take about the same time; the 304 run saves bandwidth (no bodies), not minutes. The lastmod skip is the one that saves time, 2.5 seconds against 67, which is why a trustworthy sitemap is the first thing to check on a target site. At this rate a 1,000-page site takes over half an hour to crawl once. That is fine for a nightly job and a reason not to re-crawl on every question.

Retrieve with BM25#

FTS5 ships a bm25() ranking function that takes one weight per column. Lower scores are better, so the query sorts ascending. Section headings get double weight, page titles half:

STOP = set("""a an and are as at be by can do does for from how i in is it of on or should
that the this to what when where which who why with you your my me we our about into vs""".split())


def terms(text):
    return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP and len(w) > 1]


def retrieve(db, question, k=4):
    q = " OR ".join(f'"{t}"' for t in terms(question))
    rows = db.execute(
        "SELECT text, title, section, url, bm25(chunks, 1.0, 0.5, 2.0) AS score "
        "FROM chunks WHERE chunks MATCH ? AND kind = 'prose' ORDER BY score LIMIT ?", (q, k)).fetchall()
    return [dict(zip(("text", "title", "section", "url", "score"), r)) for r in rows]


def enough_evidence(question, hits, min_terms=2):
    """Refuse unless the best chunk shares at least `min_terms` distinct content words with the question."""
    if not hits:
        return False
    best = set(terms(hits[0]["text"] + " " + hits[0]["section"]))
    return len(set(terms(question)) & best) >= min_terms

Each term is quoted so that a word like or or a hyphenated token cannot be read as FTS5 query syntax. Keyword search is a fair start for a technical blog, where questions reuse the page's own words (HNSW, SMOTE, pickle). It misses paraphrases: "how do I stop the model peeking at test data" shares no words with a post titled "data leakage". When that happens on your site, add embeddings next to FTS5 and fuse the two rankings, as in the local RAG build with sqlite-vec, and measure the change with the hybrid search comparison method.

enough_evidence is a cheap first refusal. If the best chunk shares fewer than two content words with the question, the bot says it found nothing and never calls the model.

Answer with citations#

The generator sits behind a one-method interface. OllamaGenerator is the real call; replace its body with any hosted API. StubGenerator picks the best-matching sentence from each of the top two chunks, so the pipeline runs end to end with no model.

class Generator(Protocol):
    def answer(self, question: str, hits: list[dict]) -> str: ...


PROMPT = """Answer the question using only the numbered sources. After every sentence put the
source number in brackets, like [2]. If the sources do not contain the answer, reply exactly:
NOT FOUND. Write two or three full sentences, under 80 words.

{sources}

Question: {question}"""


class OllamaGenerator:
    """Real call: a local model through Ollama's /api/chat. Swap in any hosted API here."""
    def __init__(self, model="qwen3:4b-instruct", host="http://localhost:11434"):
        self.model, self.host = model, host

    def answer(self, question, hits):
        sources = "\n\n".join(f"[{i}] ({h['section']}) {h['text'][:700]}" for i, h in enumerate(hits, 1))
        body = {"model": self.model, "stream": False, "options": {"temperature": 0, "num_ctx": 4096},
                "messages": [{"role": "user", "content": PROMPT.format(sources=sources, question=question)}]}
        req = urllib.request.Request(self.host + "/api/chat", json.dumps(body).encode(),
                                     {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=600) as r:
            return json.loads(r.read())["message"]["content"].strip()


class StubGenerator:
    """No model: returns the best-matching sentence from each of the top two chunks."""
    def answer(self, question, hits):
        q, out = set(terms(question)), []
        for i, h in enumerate(hits[:2], 1):
            sents = re.split(r"(?<=[.!?])\s+", h["text"])
            best = max(sents, key=lambda s: len(q & set(terms(s))))
            out.append(f"{best} [{i}]")
        return " ".join(out)

Ollama's chat API takes num_ctx in options per request. The first version asked for 8,192 while the running model had been loaded at 4,096 (/api/ps reports context_length), and on a GPU shared with other jobs the first request timed out after 180 seconds. Four chunks cut to 700 characters fit in 4,096 tokens with room to spare, so the request now asks for the size already loaded and the timeout is longer. The [n] markers are what turn an answer into citations: the code maps each number back to the chunk's url#section.

ask() ties the pieces together, with two refusal points before any answer goes out:

def ask(db, gen, question):
    hits = retrieve(db, question)
    if not enough_evidence(question, hits):
        return "I could not find that on this site.", [], []
    text = gen.answer(question, hits)
    if "NOT FOUND" in text:
        return "I could not find that on this site.", [], []
    used = sorted({int(n) for n in re.findall(r"\[(\d+)\]", text) if 0 < int(n) <= len(hits)})
    return text, [(n, hits[n - 1]["url"]) for n in used], grounding(text, hits, question)

Real answers#

Here are two answers from qwen3:4b-instruct (Q4_K_M, temperature 0) over the 30-page index, with the source paths the [n] markers resolved to and the per-sentence support scores from the check in the next section:

Q: Why is loading a pickle file from an untrusted source dangerous?
A: Loading a pickle file from an untrusted source is dangerous because it can execute arbitrary
   code [1]. The pickle module stores instructions that may call any importable function,
   allowing an attacker to run malicious commands like a reverse shell [1].
   sources: /save-ml-models-for-production/#pickle-runs-code-when-it-loads
   support: [0.75, 0.75]

Q: How many trials does a prompt injection test need before the rate means something?
A: A prompt injection test needs enough trials to make the upper bound small, with a rule of
   three: zero successes in n trials imply a 95% upper bound of about 3/n [3]. Thus, for the rate
   to mean something, at least 3 trials are needed, and more trials reduce uncertainty [3].
   sources: /llm-red-teaming-prompt-injection-tests/#how-many-trials-before-a-number-means-something
   support: [0.91, 0.0]

The first answer is right and both sentences trace to the cited section. The second answer starts right and then goes wrong. The rule of three is in the source; "at least 3 trials" is the model's own conclusion, and it is false: with 3 trials and zero successes the rule of three gives 3/3, a bound of 100%, and the exact 95% bound is still 63%. The citation marker on that sentence points at a real section that does not say it. The grounding check below is there to catch this.

Check that answers are grounded#

A citation marker proves only that the model typed a number. The check below asks two things of every sentence: does it cite a source, and do most of its content words appear in the chunk it cites?

def stem(w):
    for suf in ("ing", "ed", "es", "s"):
        if w.endswith(suf) and len(w) - len(suf) >= 3:
            return w[:-len(suf)]
    return w


def grounding(answer, hits, question, threshold=0.6):
    """Per sentence: does it cite a source, and are most of its new content words in that source?
    Words copied from the question do not count either way; an answer with no sentences fails."""
    report, asked = [], {stem(w) for w in terms(question)}
    for sent in re.split(r"(?<=[.!?\]])\s+(?=[A-Z])", answer):
        cites = [int(n) for n in re.findall(r"\[(\d+)\]", sent) if 0 < int(n) <= len(hits)]
        words = {stem(w) for w in terms(re.sub(r"\[\d+\]", "", sent))} - asked
        if not words:
            continue
        src = {stem(w) for c in cites for w in terms(hits[c - 1]["text"] + " " + hits[c - 1]["section"])}
        support = len(words & src) / len(words)
        report.append({"cited": bool(cites), "support": round(support, 2),
                       "ok": bool(cites) and support >= threshold, "sentence": sent[:70]})
    return report or [{"cited": False, "support": 0.0, "ok": False, "sentence": "(empty answer)"}]

Word overlap is a crude test. It passes a sentence that reuses the source's words in a wrong order ("pickle is safe" against a source saying pickle is not safe), and it fails a correct paraphrase. It is still worth running on every answer because it is free and it catches the common failure, a sentence with no source behind it. For a stronger check, use a judge model per sentence, as in the hallucination detection post.

The test set is ten questions: eight whose answer sits on a known page, and three that should be refused, one of which shares words with the site ("Ollama", "cost") but has no answer on it.

$ python check.py --show
top1     Why is loading a pickle file from an untrusted source danger grounded 2/2
top1     What happens if you oversample with SMOTE before the train t grounded 1/2
top1     How much memory does a 7B model need at 4-bit quantization?  grounded 0/0
top1     How do correlated features affect SHAP values?               grounded 1/2
top1     How many trials does a prompt injection test need before the grounded 1/2
top1     What does the quality gate check before a retrained model is grounded 1/2
top1     How does HNSW search a layered graph?                        grounded 0/0
top1     Why does Hindi text cost more tokens than English?           grounded 0/0
REFUSED  What is the capital of Peru?
REFUSED  Who won the 2011 cricket world cup final?
REFUSED  How much does an Ollama team plan cost per month?

retrieval hit@1 8/8, hit@4 8/8; answered 5/8; refused off-site 3/3; supported sentences 6/10

(The --show lines with each full answer are cut here.) Read it from the bottom up.

All three off-site questions were refused. Peru and cricket stopped at the evidence gate. The Ollama pricing question passed the gate, because the index has pages about Ollama and about cost, and the stub generator happily answered it in an earlier run. The model replied NOT FOUND, so the second refusal layer did its job.

Six of ten answer sentences passed. The four that failed are each a real problem. One is the false "at least 3 trials" claim above. One (SHAP) adds "mislead readers into thinking individual features are less important", which the source does not say. One (SMOTE) blends in a claim from a second chunk that scored 0.29. One (the quality gate) is a correct sentence with no citation marker, which the check counts as a failure on purpose: an uncited sentence cannot be verified by the reader either.

The retrieval line is misleading. Retrieval scored 8/8 at page level, yet three questions came back "I could not find that". For HNSW, the explanation on that page is an ASCII diagram, and extract files every <pre> block as code, which retrieval skips. For the 7B memory question, the four chunks returned were all from the quantization section, and the arithmetic lives in the next section, "Memory math you can do by hand". Page-level labels hid both misses. Label the expected section, not the page, and the score drops to where the answers are.

The first version of the check had two bugs of its own. It scored a correct paraphrase of the pickle answer at 0.59 (failing) because "loading" did not match "loads"; the crude stem fixed that. And it returned an empty report, which printed as 0/0 and looked harmless, when the model answered with nothing but [3]; empty answers now count as a failed sentence.

Ten questions is a smoke test, not a benchmark. For a real evaluation with recall@k, MRR and faithfulness scored separately, follow the RAG evaluation pipeline and label 50 or more questions from real search logs.

Failure modes#

  • JavaScript-rendered pages. If the article only appears after scripts run, urllib gets an empty shell and the extractor indexes nothing. Check the raw HTML with curl first. A headless browser fixes it, at the cost of a full browser render per page.
  • Boilerplate leaking in. A site with no <article> tag falls back to <main> or <body>, and navigation text ends up in every chunk. Symptom: the same three pages win every query.
  • Lying lastmod. A sitemap that stamps every URL with today's date defeats the cheapest skip. A sitemap that never updates lastmod is worse, because the crawler skips pages that did change. Run a full conditional-GET sweep weekly as a backstop.
  • Weak ETags across servers. This blog sends weak ETags (W/"..."). Behind a load balancer, two servers can give the same file different ETags, so 304s never happen and every refresh downloads everything. The content hash still prevents re-indexing.
  • Stale answers between crawls. The bot answers from the last crawl. Show the crawl date next to each source so a reader can judge.
  • Prompt injection in page text. Crawled text goes straight into the prompt. On your own site that is low risk; on a site with user comments or forum posts, someone can plant instructions. Strip comment sections and test with prompt injection cases.
  • Crawling sites you do not own. robots.txt permission is not a licence to republish. Check the site's terms, keep the rate low, and stop if asked.

Where to take it next#

Run the crawler on a schedule (cron or a CI job), keep site.db on the server, and put a small FastAPI service in front of ask(). Log every question that gets refused; those are the pages your site is missing.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.