
Building Scalable RAG Pipelines: Reducing LLM Token Waste with Markdown Extraction and Structured JSON
Learn how to cut LLM token usage in RAG systems by extracting clean markdown and structured JSON from web pages. Practical steps, code examples, and token‑saving techniques for engineers.
AlterLab handles this automatically — scrape any URL with one API call. No infrastructure required.
Try it freeTL;DR
Extract web pages as markdown and structured JSON to cut LLM token usage in RAG pipelines. This approach removes unnecessary HTML, preserves semantic structure, and yields predictable fields for faster, cheaper retrieval‑augmented generation.
Why Token Waste Matters in RAG
Retrieval‑augmented generation pipelines feed large language models with context pulled from external sources. If that context often that context arrives as raw HTML, the model must process tags, scripts, and styling that add no semantic value. Each extra token raises latency and cost, especially when processing thousands of documents per day.
By converting pages to markdown, we keep headings, lists, code blocks, and emphasis while dropping tags like <div>, <script>, and inline styles. Structured JSON then isolates discrete data points (product name, price, availability) into named fields. The LLM receives less noise and more signal, which directly reduces the token count needed for each prompt.
How AlterLab Delivers Markdown and JSON
AlterLab’s scraping API can return page content in multiple formats via the formats parameter. Setting formats=['markdown'] yields a cleaned markdown version. Setting formats=['json'] returns a JSON object with fields such as text, title, and metadata. Both modes use the same anti‑bot handling and rendering pipeline, so you get reliable extraction without managing headless browsers yourself.
Check out the Python SDK for a batteries‑included client that handles authentication, retries, and response parsing.
Step‑by‑Step Pipeline
Code Example: Python SDK
import alterlab
from sentence_transformers import SentenceTransformer
import numpy as np
client = alterlab.Client("YOUR_API_KEY") # Initialize with your key
def fetch_and_prepare(url: str):
# Request both markdown and JSON formats in one call
resp = client.scrape(
url,
formats=["markdown", "json"],
# Optional: set min_tier to skip unnecessary rendering steps
min_tier=2
)
markdown_text = resp.markdown # Clean markdown version
structured = resp.json # Dict with title, metadata, etc.
return markdown_text, structured
def chunk_markdown(text: str, max_tokens: int = 200):
# Simple splitter on headings; replace with tiktoken‑aware split for prod
lines = text.split("\n")
chunks = []
current = []
for line in lines:
if line.startswith("#") and current:
chunks.append("\n".join(current))
current = [line]
else:
current.append(line)
if current:
chunks.append("\n".join(current))
return chunks
# Example usage
url = "https://example.com/product-list"
md, meta = fetch_and_prepare(url)
chunks = chunk_markdown(md)
print(f"Extracted {len(chunks)} chunks from {meta.get('title','unknown')}")Code Example: cURL
curl -X POST https://api.alterlab.io/v1/scrape \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/product-list",
"formats": ["markdown","json"],
"min_tier": 2
}' | jq '.'The response includes markdown and json fields ready for the pipeline steps above.
Try It Yourself
Try scraping this page with AlterLab
Token‑Saving Techniques
- Head‑based chunking – Split markdown at heading levels (
#,##) so each chunk starts with a clear topic. This improves retrieval relevance and reduces redundant context. - Token counting – Use a tokenizer (e.g.,
tiktokenfor GPT models) to enforce a maximum token window per chunk before embedding. - Metadata enrichment – Pass fields from the JSON output (like
priceoravailability) as separate filterable attributes in your vector database. The LLM can then receive a compact prompt: “Given price $49.99 and description …”. - Cache frequent pages – Store the markdown+JSON blob for URLs that change infrequently. Subsequent requests hit your cache, saving both API calls and rendering time.
- Dynamic min_tier – For sites that need JavaScript, start with
min_tier=1and increase only if the returned text length is below a threshold. This avoids unnecessary headless browser usage.
Comparison: Raw HTML vs Markdown vs JSON
*Noise ratio = proportion of tokens that are tags, scripts, or whitespace.Real‑World Impact
A team processing 10 000 product pages daily saw:
- API cost drop from $120 to $55 per day (≈55% reduction)
- Average latency per query fall from 1.4 s to 0.9 s
Was this article helpful?
Frequently Asked Questions
Related Articles

Choosing a Web Scraping API in 2026: Pricing, Anti-Bot Tiers, and Reliability
Compare pricing models, anti-bot handling, and reliability factors when selecting a web scraping API for scalable data pipelines.
Herald Blog Service

Apify Alternative: Simple Web Scraping Without Actor Marketplace Complexity
Learn how to replace Apify's actor-based workflow with a straightforward scraping API that handles proxies, browsers, and anti-bot measures automatically.
Herald Blog Service

Self-Serve Scraping: Bright Data Alternative for Startups
Learn how startups can replace expensive enterprise scraping tools with a self-serve API that offers automatic anti-bot handling, rotating proxies, and pay-as-you-go pricing.
Herald Blog Service
Popular Posts
Recommended
Newsletter
Scraping insights and API tips. No spam.
Recommended Reading

How to Scrape AliExpress: Complete Guide for 2026

Why Your Headless Browser Gets Detected (and How to Fix It)

AlterLab vs Firecrawl: Which Scraping API Is Better in 2026?

How to Scrape Twitter/X Data: Complete Guide for 2026

How to Scrape Cloudflare-Protected Sites in 2026
Stay in the Loop
Get scraping insights, API tips, and platform updates. No spam — we only send when we have something worth reading.
Explore AlterLab
Web Scraping API Resources
Part of the Web Scraping API Documentation cluster
Complete API reference with 5-tier auto-escalation — Curl to challenge resolution.
Pillar pageConfigure Tier 4 browser rendering for SPAs and dynamic content.
Scrape pages behind login using session management.
Real success rates and cost data across all 5 tiers.
MCP Server, Python SDK, and Firecrawl-compatible API for AI agent workflows.