DEV Community

Cover image for I Cut Web Doc Tokens 93% for My AI Agent. 151 Code Blocks and 273 Spec Definitions Silently Broke
Sean Kwon
Sean Kwon

Posted on Edited on AI-assisted

I Cut Web Doc Tokens 93% for My AI Agent. 151 Code Blocks and 273 Spec Definitions Silently Broke

Last week I ran an HTML-to-Markdown benchmark across 10 public developer documentation pages I feed into AI coding agents, including GitHub Actions, Python, FastAPI, Kubernetes, MDN, Git, Cloudflare, and the MCP docs. My first local converter cut the combined footprint from 1,116,140 estimated tokens down to 80,462 tokens, a 92.8% drop. I almost shipped that pipeline until I inspected the extracted files and found 151 out of 240 code blocks shattered into single-token lines and 273 API and CLI definitions missing with zero errors.

Every fetch returned HTTP 200 and every summary metric looked like a win. None of the failures raised an exception, which is why broken web extraction hides in agent pipelines until the model produces corrupted YAML or invents a flag that never existed.

Why raw HTML hurts more than your token bill

Documentation pages ship navigation trees, inline SVG icons, search modals, and hydration scripts long before the first technical paragraph. In my local run, one GitHub Actions reference page weighed 276,278 estimated tokens as raw HTML, and a Kubernetes Pods page weighed 137,236 estimated tokens (using a 4-characters-per-token estimate across UTF-8 text).

Infrastructure benchmarks show the same overhead. In Cloudflare's Markdown for Agents post, they measured their own article at 16,180 tokens in HTML versus 3,150 tokens in Markdown, an 80% drop, and noted that a plain heading costs roughly 3 tokens in Markdown compared to 12 to 15 tokens in HTML before counting surrounding wrappers and scripts.

Context bloat also weakens model recall well below the advertised window limit. As Anthropic's context engineering guide explains, as the number of tokens in the context window increases, a model's ability to accurately recall information from that context decreases. Good extraction aims for the smallest set of high-signal tokens that still preserves every structure the agent needs.

What happened across 10 live documentation pages

On November 27, 2026, I tested five extraction paths against the same 10 live URLs: raw HTML, server-side content negotiation with Accept: text/markdown, text/html;q=0.5 per MDN's HTTP Accept header reference, a naive get_text(" ") strip with BeautifulSoup, a common local HTML-to-Markdown script, and a fixed hybrid pipeline.

Page Raw HTML (est. t) Accept: text/markdown Naive Strip Broken Local MD Fixed Local MD Split <pre> Blocks Dropped <dt> Specs
Cloudflare Docs (MD for Agents) 50,389 Yes (6,238) 6,050 4,902 4,834 10 / 12 0
Cloudflare Blog (MD for Agents) 79,673 Yes (4,674) 5,006 2,164 2,146 4 / 5 0
Claude Code Docs (MCP) 332,014 Yes (44,586) 38,320 17,614 17,467 38 / 71 0
MCP Spec Intro 40,346 Yes (949) 853 267 278 0 / 0 0
GitHub Actions Events 276,278 Yes (23,856) 17,922 17,931 17,605 55 / 69 0
MDN Accept Header 54,532 No 3,199 794 817 0 / 5 4
Python subprocess Docs 52,117 No 13,743 13,200 15,664 26 / 28 70
FastAPI First Steps 36,185 No 4,379 3,312 3,221 12 / 22 0
Kubernetes Pods 137,236 No 11,781 5,466 5,427 3 / 4 0
Git diff Docs 57,370 No 15,433 14,812 18,152 3 / 24 199
Total (10 pages) 1,116,140 5 / 10 honored 116,686 (-89.5%) 80,462 (-92.8%) 85,611 (-92.3%) 151 / 240 273

Here is the summary printed directly by the local benchmark run:

Audit run at UTC: 2026-11-27T13:37:03Z
Pages audited:                    10
Accept: text/markdown honored:    5/10
Total Raw HTML est tokens:        1,116,140
Total Naive strip est tokens:     116,686 (-89.5%) [0/240 fenced blocks, 0/52 pipe tables]
Total Broken MD est tokens:       80,462 (-92.8%) [151/240 code blocks span-exploded, 273 <dt> definitions dropped, 3 <h1> headings dropped]
Total Fixed Local MD est tokens:  85,611 (-92.3%) [0/240 span-exploded, 273/273 <dt> definitions preserved]
Total Hybrid (Neg+Fixed) tokens:  123,584 (-88.9%)
Enter fullscreen mode Exit fullscreen mode

If you only watch the top-line compression ratio, the broken local converter looks like the winner at -92.8%. Inspecting the output exposed three silent failure modes.

Three silent failures behind the 93% token drop

1. Syntax-highlighting spans broke 151 of 240 code blocks

Modern doc sites highlight code with Shiki, Prism, or Pygments, wrapping individual keywords, flags, and punctuation marks in separate <span> tags. Calling pre.get_text("\n") to preserve line breaks inserts a newline between every adjacent syntax span.

Here is an actual YAML snippet captured from the live GitHub Actions Events page during this run:

Expected (pre.get_text()):
on:
  branch_protection_rule:
    types: [created, deleted]

Broken (pre.get_text("\n") across syntax spans):
on:


branch_protection_rule:


types:
 [
created
, 
deleted
]
Enter fullscreen mode Exit fullscreen mode

That single mistake corrupted 55 of 69 code blocks on GitHub Actions, 26 of 28 on Python's subprocess docs, 12 of 22 on FastAPI, and 10 of 12 on Cloudflare Docs. Naive BeautifulSoup.get_text(" ") failed the other way, keeping 0 of 240 code fences and 0 of 52 HTML tables, flattening multi-column reference tables into a single text blob.

2. Tag whitelists dropped 273 API and CLI definitions

Lightweight HTML-to-Markdown scripts often walk a short element list: h1 through h4, p, pre, table, and li. That fails without a warning on Sphinx, MDN, and Git reference manuals, which store CLI options, function signatures, and header directives inside <dl>, <dt>, and <dd> definition lists.

On Git's git-diff page alone, omitting <dt> and <dd> silently deleted 199 flag definitions. Python's subprocess docs lost 70 definitions, and MDN's Accept header reference lost 4. The broken converter looked smaller specifically because it threw away the reference manual.

3. Blanket <header> removal and doc components hid real prose

Decomposing every <header> tag inside <main> erased the <h1> page title on 3 of the 10 pages. On component-heavy docs like the MCP Spec Intro, local HTML walking kept only 278 estimated tokens compared to the 949 tokens returned by the origin's own Accept: text/markdown endpoint, because custom wrapper components were missed.

Why Accept: text/markdown alone is only half the fix

Server-side content negotiation is the cleanest option when supported, because the publisher sends clean Markdown directly. In this test, 5 of the 10 sites honored Accept: text/markdown: Cloudflare Docs, Cloudflare Blog, Claude Code Docs, MCP Spec Intro, and GitHub Docs. The other 5 (MDN, Python, FastAPI, Kubernetes, and Git) ignored the header and returned full HTML.

Negotiated payloads also carry their own quirk. On Cloudflare's blog post, Accept: text/markdown returned 4,674 estimated tokens while the scoped local extractor returned 2,146 tokens. Inspecting the response explained the gap: the negotiated Markdown included an agent YAML frontmatter block at the top and a JSON-LD BlogPosting block at the bottom. That extra metadata is valid, though worth accounting for in tight context budgets.

The hybrid pipeline that kept every block intact

Combining Accept: text/markdown first with a structure-safe local fallback fixed all three regressions. Here is the minimal Python extractor I run locally:

import re
import urllib.request
from bs4 import BeautifulSoup, Tag

def fetch_agent_markdown(url: str) -> tuple[str, str]:
    req = urllib.request.Request(
        url,
        headers={
            "User-Agent": "doc-audit/1.0",
            "Accept": "text/markdown, text/html;q=0.5",
        },
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        body = resp.read().decode("utf-8", errors="replace")
        ctype = (resp.headers.get("Content-Type") or "").lower()
    if "markdown" in ctype:
        return body.strip(), "negotiated"
    return html_to_safe_markdown(body), "local_fallback"

def render_pipe_table(tbl: Tag) -> str:
    rows = []
    for tr in tbl.find_all("tr", recursive=True):
        if tr.find_parent("table") is not tbl:
            continue
        cells = [
            re.sub(r"\s+", " ", c.get_text(" ", strip=True)).replace("|", "\\|")
            for c in tr.find_all(["th", "td"], recursive=False)
        ]
        if cells:
            rows.append(cells)
    if not rows:
        return ""
    width = max(len(r) for r in rows)
    padded = [r + [""] * (width - len(r)) for r in rows]
    out = [
        "| " + " | ".join(padded[0]) + " |",
        "| " + " | ".join(["---"] * width) + " |",
    ]
    out.extend("| " + " | ".join(r) + " |" for r in padded[1:])
    return "\n".join(out)

def html_to_safe_markdown(html: str) -> str:
    soup = BeautifulSoup(html, "lxml")
    root = soup.find("main") or soup.find("article") or soup.body or soup
    for bad in root.select("script, style, noscript, svg, nav, footer, aside, button, form, iframe"):
        bad.decompose()
    for hdr in list(root.find_all("header")):
        if not hdr.find(["h1", "h2"]):
            hdr.decompose()

    blocks = []
    for el in root.find_all(["h1", "h2", "h3", "h4", "p", "pre", "table", "li", "dt", "dd"]):
        if (el.name != "pre" and el.find_parent("pre")) or (el.name != "table" and el.find_parent("table")):
            continue
        if el.name == "p" and (el.find_parent("li") or el.find_parent("dd")):
            continue
        if el.name in ("h1", "h2", "h3", "h4"):
            txt = re.sub(r"\s+", " ", el.get_text(" ", strip=True))
            if txt:
                blocks.append(f"\n{'#' * int(el.name[1])} {txt}\n")
        elif el.name == "pre":
            # Keep raw text intact instead of splitting on syntax <span> nodes
            code = el.get_text().strip("\n")
            if code.strip():
                blocks.append(f"\n```

\n{code}\n

```\n")
        elif el.name == "table":
            tbl = render_pipe_table(el)
            if tbl:
                blocks.append(f"\n{tbl}\n")
        elif el.name == "dt":
            txt = re.sub(r"\s+", " ", el.get_text(" ", strip=True))
            if txt:
                blocks.append(f"\n**{txt}**")
        elif el.name == "dd":
            txt = re.sub(r"\s+", " ", el.get_text(" ", strip=True))
            if txt:
                blocks.append(f": {txt}\n")
        elif el.name == "li":
            txt = re.sub(r"\s+", " ", el.get_text(" ", strip=True))
            if txt:
                blocks.append(f"- {txt}")
        else:
            txt = re.sub(r"\s+", " ", el.get_text(" ", strip=True))
            if txt:
                blocks.append(f"\n{txt}\n")
    return re.sub(r"\n{3,}", "\n\n", "\n".join(blocks)).strip()
Enter fullscreen mode Exit fullscreen mode

Across the same 10 pages, this hybrid pipeline reduced total estimated tokens from 1,116,140 to 123,584 (-88.9%). Span-exploded code blocks fell from 151 to 0, all 273 <dt> definitions survived, and the 5 sites serving text/markdown delivered complete component prose directly from the origin.

Three checks to run before trusting any doc fetcher

Before shipping a web-to-Markdown step inside an agent loop, run a quick diff against three to five documentation pages your team actually relies on:

  • Compare the line count of every extracted fenced code block against pre.get_text() so syntax spans never shred commands or YAML.
  • Count <dt> definition terms and <table> elements inside <main> against the Markdown output so CLI flags and API parameters do not vanish without an error.
  • Inspect the head and tail of any Accept: text/markdown response so frontmatter instructions or embedded JSON-LD blocks do not surprise your token budget.

If you feed live documentation into an AI coding agent or RAG pipeline, which site or HTML structure broke your extractor without throwing an error before anyone noticed?

Top comments (3)

Collapse
 
userxnom profile image
Abdullah Naseer •

The headline number is the trap, and you proved it with your own table — the broken local converter looked like the winner at minus 92.8% while quietly shredding 151 of 240 code blocks and deleting 273 definitions. That is the exact failure mode that scares me about feeding docs into an agent: every fetch returned 200, every summary metric looked like a win, and the agent would have gone on writing code from YAML that no longer parsed. The pre.get_text("\n") detail is the one I will remember — one call that seems obviously right inserts a newline between every Shiki syntax span and turns a clean GitHub Actions snippet into confetti, 55 of 69 blocks gone on one page. And the

/
omission is worse in a way, because losing 199 git-diff flag definitions is not a formatting problem, it is an agent confidently inventing flags that do not exist. Your hybrid answer is the right shape too: negotiate Accept: text/markdown first, since only 5 of 10 sites honored it, and keep a structure-safe local fallback that counts code fences and definition terms before trusting the output. One question: which site or structure surprised you most — was there any page where even the hybrid pipeline needed a special case, or one you would trust least to fetch again tomorrow?
Collapse
 
seanjhkwon profile image
Sean Kwon •

Two pages caught me off guard for opposite reasons.

Claude Code's MCP docs honored Accept: text/markdown, yet the negotiated payload still came back at 44,586 estimated tokens, more than double the 17,467 tokens from my fixed local extractor. Even when content negotiation works, publishers can still include extra sections or metadata that a scoped <main> extractor trims out, so I now check response size and head/tail structure on negotiated Markdown too.

The page I would trust least to fetch again tomorrow is the MCP Spec Intro. Local HTML walking dropped it from 949 negotiated tokens down to 278 because component-heavy layouts bury real prose outside plain semantic tags. If a site like that changes its DOM components or stops serving Markdown on Accept, a local fallback can lose most of the page while returning HTTP 200.

Collapse
 
the_daily_flare profile image
The daily flare •

Would my own fetcher have caught those 199 missing git-diff flags?