← Back to blog

Grounding LLM Answers in Real Sources: A Citation-First RAG Pipeline with Markdownify and OGSnap

Ask a RAG system a question and you'll usually get a confident answer with a neat little [1] at the end. Click the citation and you often land on a page that mentions the topic but never says the thing the model claimed. The answer was fluent, the citation was decoration, and nobody checked.

That gap is an architecture problem, not a prompt problem. If your pipeline throws unstructured chunks at a model and asks it to "cite sources," you're hoping the model invents a consistent numbering scheme, remembers which chunk said what, and quotes accurately under pressure. It won't, reliably.

This post builds the missing layer: stable source and passage IDs, a strict citation contract, and a verification step that rejects any claim whose quote isn't actually in the source. Everything runs on two FetchAPI endpoints — Markdownify for page content and OGSnap for canonical metadata — and the verification code is short enough to drop into an existing service today.

Why citations added after generation always leak

Four things break in the usual setup.

Chunks have no durable identity. If your chunk ID is an array index or a UUID generated at ingest time, the same passage gets a new ID every time you re-crawl. Citations in stored answers stop resolving.

The model never sees the ID it's supposed to cite. Chunks get concatenated into one blob, then the model is asked to reference "source 3." It has to count. It counts wrong.

Nobody verifies the quote. A model that paraphrases a sentence and wraps it in quotation marks has produced a fabricated quote, even if the surrounding claim is true.

Page content and page metadata come from different worlds. You cite https://example.com/blog/post?utm_source=... with a title scraped from an <h1> that may be a marketing slogan. Readers can't match the citation to the page.

The fix is to treat a citation as structured data with a lifecycle: resolve, extract, address, generate, verify.

Step 1: resolve the source with OGSnap

Start with metadata, because you need a stable human-readable label before you need body text. OGSnap returns Open Graph tags, Twitter Cards, and JSON-LD:

curl -s "https://fetchapi.tech/v1/ogsnap?url=https://en.wikipedia.org/wiki/Retrieval-augmented_generation" \
  | python3 -m json.tool | head -20
{
  "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation",
  "title": "Retrieval-augmented generation - Wikipedia",
  "description": "",
  "image": "",
  "site_name": "",
  "type": "website",
  "og": {},
  "twitter": {},
  "jsonld": [],
  "has_jsonld": false
}

Two practical notes from testing this against live pages. First, title is the field you can rely on; site_name and description are frequently empty, so never make your UI depend on them. Second, use the returned url as the canonical citation target rather than the URL you typed in — it strips tracking noise and gives you one identity per page.

Keep jsonld even when has_jsonld is false in your display. When it is present, it often carries the author, publisher, and datePublished values that make a citation credible.

Step 2: extract the body with Markdownify

curl -s "https://fetchapi.tech/v1/markdownify?url=https://en.wikipedia.org/wiki/Retrieval-augmented_generation" \
  | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['word_count'], d['char_count']); print(d['content'][:400])"

Real response fields:

{
  "content": "Retrieval-augmented generation (RAG) is a technique...",
  "title": "",
  "description": "",
  "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation",
  "word_count": 2034,
  "char_count": 19701
}

word_count is the most useful triage signal in the whole API. On the pages I tested — a Wikipedia article, the SQLite "When to use" page, and the Stripe API reference — the counts were 2,034, 2,313, and 958 words respectively. If a page you expect to be substantial comes back under ~150 words, you're probably looking at a JavaScript-only shell, a paywall, or a consent interstitial. Drop it from the source set rather than letting the model reason over three sentences of navigation.

Notice that title came back empty on all three pages. That's exactly why step 1 exists: OGSnap is your metadata authority, Markdownify is your body authority. Don't skip one and hope the other fills in.

Cache the result keyed by URL, and store a hash of content. You need both: the URL tells you which page, the hash tells you whether the text your answer was based on still exists.

Step 3: give every passage a stable address

The citation format used here is S{6 hex}-P{n}: a source ID derived from the canonical URL, and a passage index within that source. It's short enough for a model to copy correctly and stable across re-crawls as long as the page structure doesn't change radically.

import hashlib, re

def normalize(s):
    return re.sub(r"\s+", " ", s).strip()

def passages(md, target=900):
    """Split on headings, merge small sections, hard-split anything huge."""
    chunks, cur = [], []
    for block in re.split(r"\n(?=#{1,4} )", md):
        if not block.strip():
            continue
        if cur and len("\n\n".join(cur)) + len(block) > target:
            chunks.append("\n\n".join(cur)); cur = []
        cur.append(block.strip())
    if cur:
        chunks.append("\n\n".join(cur))

    out = []
    for c in chunks:
        if len(c) <= target * 2:
            out.append(c)
        else:
            words, step = c.split(), max(1, target // 6)
            out += [" ".join(words[i:i + step]) for i in range(0, len(words), step)]
    return out

def build_source(url, title, md):
    sid = "S" + hashlib.sha1(url.encode()).hexdigest()[:6]
    return {
        "id": sid, "url": url, "title": title,
        "passages": [
            {"pid": f"{sid}-P{i+1}", "text": p,
             "hash": hashlib.sha1(normalize(p).encode()).hexdigest()[:10]}
            for i, p in enumerate(passages(md))
        ],
    }

Splitting on headings matters more than any tuning constant. A 900-character window that starts mid-table produces citations that are technically real and practically useless. Heading-aligned chunks keep a definition with its explanation and a list with its intro.

Now the trade-off you have to decide consciously: index-based IDs are stable but not change-proof; hash-based IDs are change-proof but not stable. If you use the content hash as the passage ID, every edit to the page breaks every stored citation to it. Use the index as the address and the hash as the freshness check. When the hash changes, you know the cited text may have moved, and you can mark the old answer stale instead of silently serving it.

Step 4: make the model earn its citations

Send numbered, labelled context and a contract with explicit failure modes. The key is that the model must reproduce the ID it was given — not derive one.

You answer only from the SOURCES below. Each source contains labelled passages.

Rules:
1. End every factual sentence with the passage ID in square brackets, e.g. [Sa1b2c3-P4].
2. If you quote, copy the text verbatim and keep it under 25 words. Put the ID immediately after the closing quote.
3. Never cite a passage you did not use. Never invent an ID.
4. If two sources disagree, report both claims with both IDs. Do not average them.
5. If the sources don't answer the question, say "Not in the provided sources." and stop.
6. Do not use knowledge from outside the sources, even if you are confident.

SOURCE Sa1b2c3 | Retrieval-augmented generation - Wikipedia
URL: https://en.wikipedia.org/wiki/Retrieval-augmented_generation
Retrieved: 2026-11-01T09:00:00Z

[Sa1b2c3-P1]
Retrieval-augmented generation (RAG) is a technique that...

Rule 5 is the one teams forget. Without an explicit no-answer path, a model with thin retrieval will fill the gap from pretraining and attach a real-looking ID to it. Give it permission to fail and it fails honestly.

Only put the top few passages per source in the prompt. With heading-aware chunks around 900 characters, three passages per source is roughly 700 tokens — versus tens of thousands for raw HTML. Retrieval quality improves when the context is mostly signal.

Step 5: verify before you return the answer

This is the part that turns citations from decoration into a guarantee. Check three things: every cited ID exists, every quoted span appears verbatim in the passage it's attached to, and every paragraph carries at least one citation.

CITE = re.compile(r"\[(S[0-9a-f]{6}-P\d+)\]")

def verify(answer, sources):
    by_id = {p["pid"]: p for s in sources for p in s["passages"]}
    cited = CITE.findall(answer)
    unknown = [c for c in cited if c not in by_id]

    unsupported = []
    for m in re.finditer(r'"([^"]{20,300})"\s*\[(S[0-9a-f]{6}-P\d+)\]', answer):
        quote, cid = m.group(1), m.group(2)
        src = by_id.get(cid)
        if src and normalize(quote).lower() not in normalize(src["text"]).lower():
            unsupported.append((quote[:40], cid))

    uncited = [p for p in answer.split("\n\n")
               if len(p.split()) > 25 and not CITE.search(p)]

    return {"ok": not unknown and not unsupported and not uncited,
            "unknown_ids": unknown, "unsupported_quotes": unsupported,
            "uncited_paragraphs": len(uncited)}

Running it against a two-source ingest (the Wikipedia RAG article and SQLite's "Appropriate Uses" page) produced 14 and 16 passages respectively, and the checker behaved exactly as intended:

On failure, don't return the answer with a warning badge. Either strip the unsupported sentences and re-verify, or re-prompt once with the specific failing quote and the instruction "this quote is not in the passage; remove it or replace it with a verbatim span." One repair pass catches most of it. If it still fails, return the no-answer response — a missing answer is cheaper than a wrong one with a link.

Handle disagreement and drift explicitly

Two sources will contradict each other, and the model's default instinct is to blend them into a confident middle. Rule 4 blocks the blend, but your data model should support it: allow multiple citations per sentence and render them as "Source A says X [id]; Source B says Y [id]."

Store retrieved_at on every source and show it next to the citation. A citation without a date is a claim about the present tense that you can't back up. When re-crawling, compare content hashes and invalidate any cached answer whose cited passages changed. That's the difference between a citation system and a citation-shaped decoration.

Observed failure modes worth coding around

The five-line version

If you take nothing else: resolve metadata separately from body text, give every passage an ID the model can copy, require verbatim quotes, verify the IDs and quotes before returning, and keep a no-answer path. That's a citation pipeline. Everything else — chunk size, reranker, embedding model — is tuning on top of a contract that already holds.

Try it on a page you actually care about:

curl -s "https://fetchapi.tech/v1/ogsnap?url=YOUR_URL" | python3 -m json.tool
curl -s "https://fetchapi.tech/v1/markdownify?url=YOUR_URL" | python3 -m json.tool | head -40

The free tier needs no API key, so you can measure extraction quality on your own corpus before you commit to an architecture. Full parameters are in the docs.