← Back to blog

From Docs Site to Fine-Tuning Dataset: Building an LLM-Ready Corpus with the Markdownify API

Fine-tuning fails for boring reasons. Not the hyperparameters — the data. You need a few thousand clean, consistently-shaped examples, and the internet hands you HTML with cookie banners stapled to it.

Technical documentation is the best free source of that data: dense prose, consistent structure, code that actually compiles, and a sitemap that tells you every URL without guessing. What docs sites don't give you is clean text, which is the part everyone underestimates.

This tutorial builds a corpus pipeline with the Markdownify API: sitemap discovery → markdown extraction → quality gates → heading-aware chunking → JSONL for training. Every number below comes from a real run against docs.astral.sh/uv (84 URLs, 12 sampled), including the pages that failed and why.

Why docs sites make good training corpora

Three properties matter more than raw size:

One caveat before you start: a permissive code license does not automatically license the prose. Check the repository license and the site's terms, and keep attribution metadata (url, title, dateModified) attached to every chunk so you can honor it later.

Step 1: Enumerate the corpus from the sitemap

curl -s https://docs.astral.sh/uv/sitemap.xml | grep -o '<loc>[^<]*' | sed 's/<loc>//' \
  | grep '/reference/' | head -12

That returns 84 URLs total, 12 of them under /reference/ — a good sample size for a test run, since reference pages are the densest part of the site.

If you do this in Python, set a User-Agent. The default urllib UA got a 403 from this sitemap before I added one:

req = urllib.request.Request(sm_url, headers={"User-Agent": "Mozilla/5.0 (corpus-builder)"})
root = ET.fromstring(urllib.request.urlopen(req, timeout=30).read())
urls = [loc.text for loc in root.findall(".//s:loc", ns)]

Step 2: Extract each page as markdown

curl -s "https://fetchapi.tech/v1/markdownify?url=https://docs.astral.sh/uv/reference/environment/" \
  -o page.json
{
  "content": "uv defines and respects the following environment variables:\n\nadded in `0.11.14`\n\n...",
  "title": "",
  "description": "",
  "url": "https://docs.astral.sh/uv/reference/environment/",
  "word_count": 4831,
  "char_count": 34439
}

Notice what came back: 34 KB of markdown, and an empty title. Docs pages frequently don't expose a reliable headline to the body extractor, so don't build your dataset filenames on title. Pull it from metadata instead:

curl -s "https://fetchapi.tech/v1/ogsnap?url=https://docs.astral.sh/uv/reference/environment/" \
  | python3 -c "import json,sys; print(json.load(sys.stdin)['title'])"
# Environment variables | uv

OGSnap also returned JSON-LD here, including dateModified. That timestamp is worth keeping — it lets you build a time-based train/eval split later instead of a random one.

Step 3: Gate on quality before you spend tokens

word_count arrives in the same response, free. So gate on it instead of discovering bad pages after embedding.

Here are the actual results for those 12 pages:

Outcome Pages Example
Kept 8 /reference/cli/ — 64,526 words
Dropped: navigation-only 3 /reference/benchmarks/ — 74 words out of 61 KB HTML
Rejected by API 1 /reference/policies/ — HTTP 400

The three thin pages are the important lesson. Each shipped 61 KB of HTML and produced 9 to 74 words of content, because they're index pages whose body is almost entirely sidebar links. Ungated, they'd have become hundreds of garbage training examples.

The rejection is more interesting. /reference/policies/ returns HTTP 200 from the origin, but the extracted text was about 200 words of chrome, and the API declined to pretend otherwise:

{"detail": "No content could be extracted from this page"}

Treat that 400 as a classification, not an error: the page has no body content. Log it and move on. Just don't confuse it with 429, which means you're out of quota and should stop the run — more on that below.

Step 4: Chunk with structure, but verify the structure exists

Fine-tuning examples want one coherent idea each. Split on headings so a chunk is "this section of this page", and prepend the heading path so the chunk is self-contained:

def chunks(markdown, page_title="", budget=600):
    sections, path, buf, in_fence, root = [], [], [], False, page_title
    for line in markdown.splitlines():
        if line.startswith("```"):
            in_fence = not in_fence          # never split inside code
        if not in_fence and line.startswith("# "):
            root = root or line[2:].strip()
            continue
        if not in_fence and re.match(r"^#{2,3} ", line):
            if buf:
                sections.append((path, "\n".join(buf).strip()))
            path, buf = [line.lstrip("# ").strip()], []
        else:
            buf.append(line)
    if buf:
        sections.append((path, "\n".join(buf).strip()))

    out = []
    for path, body in sections:
        head = " > ".join([root, *path]) if root else " > ".join(path)
        for i in range(0, len(body), budget * 4):   # ~4 chars/token
            piece = body[i:i + budget * 4].strip()
            if len(piece.split()) >= 40:
                out.append({"heading": head, "text": f"{head}\n\n{piece}"})
    return out

Here's the part nobody warns you about: the /reference/environment/ page contained zero ## markers across its 34,439 characters. The extractor returned clean prose, but the heading hierarchy had been flattened into plain links. Heading-aware chunking silently degraded into windowed chunking, which is why the function falls back to page_title and splits at ~2,400 characters.

The results on that page: 4,831 words → 15 chunks averaging 579 tokens, smallest 210 tokens. No chunk exceeded the budget, and no chunk split a code fence.

Add a cheap diagnostic before you trust the structure: if content.count("\n## ") == 0, your chunker is in fallback mode and your heading breadcrumbs are all identical. That's not fatal for training, but it does mean you should not advertise "section-level retrieval" on top of it.

Step 5: Write JSONL and split by URL

Write one JSON object per chunk — url, title, heading, text — and split by URL, never by chunk. Chunks from the same page overlap in vocabulary, so a random chunk split leaks evaluation data into training and inflates your metrics by a few points that vanish in production.

From this run: 8 pages produced 86,577 words, 658,662 characters of markdown, and roughly 164,667 tokens at the common chars / 4 estimate. The single /reference/cli/ page accounts for 75% of that — 1.18 MB of HTML compressed to 500 KB of markdown. If your goal is a balanced dataset, cap per-page chunk counts or you'll train a model that only knows CLI flags.

For comparison: the same 8 pages were 2.31 MB of raw HTML. The markdown corpus is 28% of that — a 72% reduction — and it still contains all the prose and code. That ratio is the whole argument for extraction over wget.

Step 6: Run it, resumably

The free tier is 50 requests per day. An 84-page sitemap needs two days, so the state file isn't optional — it's the difference between a corpus and a corpus you keep restarting:

page = get_json("/v1/markdownify", url=url)
if page["status"] == 429:                       # transient: quota
    print("rate limited, stopping early"); break
if page["status"] == 400:                       # permanent: no content
    state[url] = "empty"; continue
if page.get("word_count", 0) < 150:             # permanent: nav-only
    state[url] = "thin"; continue
title = page.get("title") or get_json("/v1/ogsnap", url=url).get("title") or url
state[url] = "kept"

Two details that matter in practice. First, word_count is your only free signal — use it before you call anything else. Second, 429 and 400 demand opposite responses: one means come back tomorrow, the other means never come back. If you collapse both into "drop the page", as my first version did, you silently lose every page in the run after you hit the quota wall.

Persist state to disk after each page. A crash on page 60 of 84 shouldn't cost you the quota for pages 1 through 59.

What to check before you train

None of this requires a browser, a proxy pool, or a scraper per domain — which is the point. The pipeline is one GET per page plus a handful of filters, and the filters are where the quality actually comes from.

If you're deciding between extraction strategies, our token measurement of seven real pages covers the cost side, and the JSON Schema tutorial covers the case where you need typed fields instead of prose.