← Back to blog

Generate llms.txt for Any Documentation Site with the Markdownify and OGSnap APIs

Every coding agent eventually does the same thing: it fetches your docs, strips the navigation, and hopes the important part survived. The /llms.txt convention exists to make that unnecessary — a single markdown file at the site root that tells a model what your documentation contains and where to read more. The v2.1 spec was revised on November 28, 2026, and Chrome's Lighthouse now audits sites for the file as part of its agentic-browsing checks.

The problem is coverage. Most documentation sites still don't publish one, and hand-writing an index for 150 pages is nobody's idea of a good afternoon.

This post builds a generator that reads a sitemap, extracts every page with the Markdownify API, pulls canonical titles from OGSnap, and emits both llms.txt (the index) and llms-full.txt (the whole corpus in one file). The numbers below come from a live run against fastapi.tiangolo.com.

What the spec actually requires

The format is deliberately boring, which is why parsers can handle it with regex:

# Project name

> One-paragraph summary of what this documentation covers.

Base URL: https://example.com/docs/

Optional supporting context: version, audience, how the files are organized.

## Tutorial

- [Query Parameters and String Validations](https://example.com/tutorial/query-params/): How to declare
  and validate query parameters, with defaults and length constraints.
- [Response Model](https://example.com/tutorial/response-model/): Declaring return types and filtering
  what the API exposes.

## Reference

- [API routes](https://example.com/reference/routes/): Complete endpoint reference.

The rules that matter in practice:

Two details are easy to get wrong. First, the file must be served as markdown or plain text — if your server returns the SPA's HTML shell for unknown paths, agents will read a React bundle instead of your index. Second, llms.txt is an index, not a dump: the spec expects a short file that links out, with full content living at page.md or in a separate llms-full.txt.

The measured baseline

fastapi.tiangolo.com/sitemap.xml lists 154 URLs. We ran the first 40 through Markdownify and recorded what came back.

Metric Result
Pages requested 40
HTTP 200 responses 40
Total words extracted 53,019
Total characters 379,743
Estimated tokens (chars ÷ 4) ~94,900
Median words per page 1,131
Pages under 300 words 2
Pages under 100 words 1
Latency p50 / max (6 workers) 2.23 s / 4.76 s

Three findings shaped the design.

The corpus is small enough to ship whole. 40 pages of FastAPI docs compress to roughly 95k tokens of markdown. A 150-page site lands in the low hundreds of thousands — large, but addressable with a retrieval step or by splitting llms-full.txt by section.

Markdown is dramatically smaller than HTML. For the five pages where we measured both, raw HTML ranged from 138 KB to 245 KB while the extracted markdown ranged from 16 KB to 28 KB — an 84.1% to 89.7% reduction. That is the difference between a model reading your docs and a model reading your theme.

Thin pages are real. fastapi.tiangolo.com/learn/ returned 57 words — a landing page with cards, not prose. Indexing it would waste an entry and teach an agent nothing. It needs a word-count gate, not a special case.

Step 1: Discover the URLs

Start from the sitemap, and handle the two shapes you will actually encounter: a flat <urlset> and an index that points at child sitemaps.

curl -s https://fastapi.tiangolo.com/sitemap.xml \
  | grep -oE '<loc>[^<]+</loc>' \
  | sed -E 's#</?loc>##g' \
  | head -5
import re, requests

UA = {"User-Agent": "llms-txt-builder/1.0 (+https://fetchapi.tech)"}

def sitemap_urls(url):
    xml = requests.get(url, headers=UA, timeout=30).text
    if "<sitemapindex" in xml:
        out = []
        for child in re.findall(r"<loc>(.*?)</loc>", xml):
            out += sitemap_urls(child)
        return out
    return re.findall(r"<loc>(.*?)</loc>", xml)

urls = [u for u in sitemap_urls("https://fastapi.tiangolo.com/sitemap.xml")
        if not re.search(r"/(ja|de|es|fr|pt|zh|ko|ru|uk)/", u)]

Filter translations before you spend a single request. On FastAPI's sitemap that alone removes a large fraction of the 154 entries, and mixing languages into one index makes the file useless to a model that needs English docs.

Step 2: Extract each page

Markdownify takes one query parameter and returns JSON:

curl -s "https://fetchapi.tech/v1/markdownify?url=https://fastapi.tiangolo.com/async/" \
  | jq '{title, word_count, char_count, first: (.content[0:120])}'

The response fields you care about here are content, title, description, word_count, and char_count. Code fences survive intact, which matters for a docs index — the snippets are the part agents copy.

Now the wrinkle we hit: Markdownify returned an empty title for all 40 FastAPI pages. The extractor is tuned for article bodies, and docs themes often put the real title in a template the extractor discards. OGSnap fills that gap:

curl -s "https://fetchapi.tech/v1/ogsnap?url=https://fastapi.tiangolo.com/async/" \
  | jq '{title, description, image}'
# {"title":"Concurrency and async / await - FastAPI","description":"","image":""}

Across the eight pages we checked, OGSnap returned a usable title 8 out of 8 times, including the site suffix you want to strip (- FastAPI). Its description was empty 8 out of 8 times — FastAPI's theme ships no meta description. So titles come from OGSnap, and descriptions come from the first real paragraph of the markdown.

def build(url):
    doc = requests.get(f"https://fetchapi.tech/v1/markdownify",
                       params={"url": url}, timeout=60).json()
    if not doc.get("content"):
        return None
    og = requests.get(f"https://fetchapi.tech/v1/ogsnap",
                      params={"url": url}, timeout=60).json()
    title = (og.get("title") or doc.get("title") or url).strip()
    return {"url": url, "title": strip_site(title, "FastAPI"),
            "description": og.get("description") or first_paragraph(doc["content"]),
            "md": doc["content"], "words": doc.get("word_count", 0)}

first_paragraph should skip headings, lists, code blocks, and images, and stop at about 180 characters:

def first_paragraph(md):
    for block in re.split(r"\n\s*\n", md):
        b = " ".join(block.split())
        if not b or b[0] in "#-*|>`!<" or b.startswith("```"):
            continue
        b = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", b)   # links -> text
        b = re.sub(r"[*_`]", "", b)
        if len(b.split()) >= 8:
            return b[:180].rsplit(" ", 1)[0] + "…"
    return ""

Step 3: Gate before you index

Drop anything under 300 words. In the 40-page run that removed exactly one page — the 57-word /learn/ hub — while keeping every genuine tutorial, the shortest of which was 295 words. A 300-word floor is conservative: it will not remove real reference pages, and it reliably catches card grids and "coming soon" stubs.

Keep the dropped URLs in a log rather than silently discarding them. If a page you expected is missing from the index, the gate is the first place to look.

Step 4: Emit both files

Sort by path depth so overview pages come first, group by the first path segment, and write the index. Here is the shape of the output, abridged to one section with the generated notes replaced by page word counts for space:

# fastapi.tiangolo.com

> Documentation for fastapi.tiangolo.com, compiled from 39 pages of official docs.

Every entry links to the canonical page. `llms-full.txt` contains the complete
markdown of all listed pages in a single file for one-shot context loading.

## Overview

- [FastAPI](https://fastapi.tiangolo.com/): 2,089 words

## Tutorial

- [Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/): 4,043 words
- [Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/): 3,121 words
- [Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/): 2,541 words
- [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/): 1,970 words
- [Classes as Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/): 1,904 words
- [Python Types Intro](https://fastapi.tiangolo.com/python-types/): 1,837 words

Every title above came from OGSnap with the - FastAPI suffix stripped programmatically. For llms-full.txt, concatenate the bodies with a source marker so an agent can still attribute what it reads:

with open("llms-full.txt", "w") as f:
    f.write(f"# {site} — full documentation\n\n")
    for p in pages:
        f.write(f'\n\n---\n\n<!-- source: {p["url"]} -->\n\n')
        f.write(re.sub(r"^# ", "## ", p["md"], count=1))   # demote page H1

Demoting the page's own H1 to H2 keeps one document outline in the concatenated file. Without it, the file has 39 competing top-level headings.

Step 5: Publish and verify

Write both files to your site root, then confirm you are serving markdown and not an HTML fallback:

curl -sI https://your-site.com/llms.txt | grep -i content-type
curl -s https://your-site.com/llms.txt | head -3

A text/html content type here usually means a catch-all route swallowed the request. Also check that the links resolve — a relative link without a Base URL: line resolves against the file's own location, which is correct only if the index sits where the pages do.

The quota reality

This is the part tutorials skip. FetchAPI's free tier allows 50 requests per day, and the generator above spends two per page — one Markdownify call and one OGSnap call. That is 25 pages per day, not 154.

We hit the ceiling mid-run and got an explicit error rather than a silent truncation:

{"detail":"Daily limit reached (50). Upgrade your plan."}

Design for it instead of discovering it at page 26:

On a paid plan the same pipeline runs end to end without interruption: 40 pages completed in well under a minute of wall time at six concurrent workers, with a p50 of 2.23 seconds per request. A 154-page site at that rate is a few minutes of work, not an overnight crawl.

Maintenance

An index that goes stale is worse than no index: it advertises pages that no longer exist. Rebuild weekly from the sitemap, diff the new file against the committed one, and only publish if the entry list changed. When DiffCheck ships, the same job can watch individual pages and re-extract only the ones whose content actually moved, instead of re-running the whole sitemap.

Until then, the cheap version is a nightly curl of the sitemap plus a hash of its <lastmod> values. If the hash is unchanged, skip the rebuild entirely.

Checklist

The whole generator is under 80 lines of Python and a sitemap. If your docs already have clean markdown, the file is one curl loop away — and the next agent that lands on your site will thank you by not scraping your navigation menu.