# Docs to RAG Chunks — Ultra-Fast LLM Documentation Scraper (`weiyi-ai/docs-to-rag-chunks`) Actor

Ultra-fast LLM documentation scraper & heading-aware RAG chunker. Auto-detects llms.txt, sitemaps, and 12+ doc frameworks with code-safe token chunking, SHA-256 incremental sync, and LangChain/LlamaIndex/Pinecone/Qdrant export.

- **URL**: https://apify.com/weiyi-ai/docs-to-rag-chunks.md
- **Developed by:** [Weiyi Wang](https://apify.com/weiyi-ai) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 documentation page processeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Docs to RAG Chunks — Ultra-Fast LLM Documentation Scraper & Chunker

Turn any documentation site, API reference, or help center into **clean, heading-aware, token-bounded RAG chunks** ready for **Pinecone, Qdrant, Weaviate, LangChain, LlamaIndex, OpenAI Vector Stores, and MCP AI Agents** — **up to 20× faster and 90% cheaper** than headless browser crawlers.

***

### Verified Cloud Benchmark (`512 MB` RAM, Zero Headless Browser Bloat)

| Metric | Docs to RAG Chunks | Typical Browser-Based Crawler |
| :--- | :--- | :--- |
| **10 Documentation Pages** | **4 seconds** (179 RAG chunks) | 45–90 seconds (10 raw HTML blobs) |
| **Platform Compute Cost** | **~$0.001 / 10 pages** | ~$0.02–$0.08 / 10 pages |
| **Output Format** | Ready-to-embed token-bounded chunks | Unchunked HTML/Markdown with nav noise |
| **Code Block Protection** | Preserves language tags & `# comments` | Frequently splits mid-function |
| **Incremental Re-Sync** | Built-in SHA-256 skip (**$0 on unchanged pages**) | Re-scrapes & re-embeds everything |

***

### Supported Frameworks & Output Formats

- **12+ Documentation Frameworks**: **Docusaurus, Mintlify, GitBook, MkDocs Material, VitePress, Nextra, Astro Starlight, Sphinx / ReadTheDocs, ReadMe, Zendesk, Intercom**, plus clean semantic HTML fallback.
- **Smart Discovery Pipeline**: Automatically checks `llms-full.txt` and `llms.txt` first, falls back to `sitemap.xml` / `sitemap_index.xml`, and performs prefix-locked crawling with `robots.txt` compliance.
- **5 Native Export Presets**: `standard`, `langchain`, `llamaindex`, `pinecone`, and `qdrant`.

***

### Quick Start Examples

#### 1. Python (`apify-client`)

```python
from apify_client import apify_client

client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("weiyi-ai/docs-to-rag-chunks").call(
    run_input={
        "startUrls": [{"url": "https://www.python-httpx.org/"}],
        "maxPages": 25,
        "discoveryMode": "auto",
        "maxTokensPerChunk": 512,
        "chunkOverlapTokens": 50,
        "outputFormat": "langchain",
    }
)

chunks = list(client.dataset(run["defaultDatasetId"]).iterate_items())
summary = client.key_value_store(run["defaultKeyValueStoreId"]).get_record("SUMMARY")["value"]
print(f"Extracted {len(chunks)} chunks across {summary['pagesProcessed']} pages")
```

#### 2. Apify MCP Server (Claude Desktop, Cursor, Windsurf & AI Agents)

Connect this Actor directly as a live documentation ingestion tool via the official Apify MCP endpoint:

```json
{
  "mcpServers": {
    "apify-docs-rag": {
      "url": "https://mcp.apify.com/?actors=weiyi-ai/docs-to-rag-chunks",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}
```

#### 3. Incremental Sync (Save 90% on Vector Embedding Bills)

1. Run the Actor once and store `summary["pageHashes"]` from the `SUMMARY` Key-Value Store record.
2. On your next scheduled daily/weekly run, pass `previousPageHashes: summary["pageHashes"]`.
3. Unchanged pages are skipped automatically — **you pay $0 for skipped pages and skip redundant OpenAI/Cohere embedding calls**.

***

### Example Output (`standard` preset)

```json
{
  "chunkId": "56207d49375e-0000-a3358fb9",
  "url": "https://www.python-httpx.org/",
  "pageTitle": "HTTPX",
  "framework": "mkdocs",
  "headingPath": ["HTTPX", "QuickStart"],
  "chunkIndex": 0,
  "totalPageChunks": 5,
  "tokenCount": 213,
  "charCount": 802,
  "hasCodeBlock": true,
  "hasTable": false,
  "chunkHash": "a3358fb970e5d7d007e5166294efb5332d047a38f4d62f02d9efe3cf0e592888",
  "pageContentHash": "8c029c8cfa70ad5ddbc27acd07615e0208434ba25a40445f3ba46b9e97e490cc",
  "text": "Document: HTTPX > QuickStart\nSource: https://www.python-httpx.org/\n---\n# HTTPX\n...",
  "scrapedAt": "2026-11-26T03:19:38.215433+00:00"
}
```

***

### Transparent Pay-Per-Event Pricing

- **Only charged per successfully processed page (`page-processed`)** that produces valid RAG chunks.
- **Free when skipped or failed**: Unchanged pages skipped via `previousPageHashes`, 404s, and empty boilerplate pages are **never charged**.

***

### FAQ

**Q: Why does this Actor not break Python or Bash `# comments` inside code blocks?**
Unlike naive regex splitters that split on every `^#`, our parser tracks fenced code block boundaries (` ``` ` / `~~~`) first so comments inside code never become false section headings, and keeps code blocks intact with their language tags.

**Q: How accurate are the token counts?**
Every chunk is measured directly with OpenAI's `tiktoken` (`cl100k_base`) encoding, guaranteeing chunks stay safely inside your embedding model's context window.

**Q: Can I use this in n8n, Make, or Zapier?**
Yes! Trigger the Actor via the native Apify node in n8n/Make, read the dataset items directly into Pinecone, Qdrant, Supabase `pgvector`, or Weaviate, and pass `SUMMARY.pageHashes` back on the next run.

**Q: Does it work with `llms.txt` and `llms-full.txt`?**

# Actor input Schema

## `startUrls` (type: `array`):

One or more root documentation URLs (e.g. https://docs.stripe.com/api or https://fastapi.tiangolo.com/tutorial/).

## `maxPages` (type: `integer`):

Maximum number of documentation pages to fetch and chunk.

## `discoveryMode` (type: `string`):

How to discover pages: 'auto' tries llms.txt -> sitemap.xml -> same-prefix crawling; 'llms_txt' only uses llms-full.txt/llms.txt; 'sitemap' uses sitemap.xml; 'crawl' follows internal links only.

## `stayWithinStartPath` (type: `boolean`):

Only process URLs that share the same path prefix as your Start URLs (prevents wandering into marketing blogs or unrelated locales).

## `includeUrlPatterns` (type: `array`):

Optional regex patterns; if provided, only matching URLs are processed.

## `excludeUrlPatterns` (type: `array`):

Optional regex patterns to skip (e.g. changelog, blog, localized paths like /ja/ or /zh/).

## `maxTokensPerChunk` (type: `integer`):

Target maximum token count per RAG chunk (counted via tiktoken cl100k_base). Code blocks and tables are kept intact whenever possible.

## `minTokensPerChunk` (type: `integer`):

Merge tiny sibling chunks below this token threshold with adjacent chunks under the same parent section.

## `chunkOverlapTokens` (type: `integer`):

Number of overlapping tokens preserved between consecutive split chunks inside the same section.

## `prependHeadingContext` (type: `boolean`):

Prepend 'Page Title > H2 > H3' context header to each chunk so vector search retains full section context.

## `outputFormat` (type: `string`):

Choose schema tailored to your downstream vector database or AI framework.

## `previousPageHashes` (type: `object`):

Optional map of { url: pageContentHash } from a previous run. Unchanged pages are skipped to save embedding costs.

## `maxConcurrency` (type: `integer`):

Number of simultaneous HTTP requests.

## `requestTimeoutSecs` (type: `integer`):

HTTP timeout per page request.

## `respectRobotsTxt` (type: `boolean`):

Check and honor robots.txt disallow rules.

## `useApifyProxy` (type: `boolean`):

Route requests through Apify Proxy (recommended only if target site rate-limits datacenter IPs).

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://www.python-httpx.org/"
    }
  ],
  "maxPages": 15,
  "discoveryMode": "auto",
  "stayWithinStartPath": true,
  "includeUrlPatterns": [],
  "excludeUrlPatterns": [
    "\\.(png|jpg|jpeg|gif|svg|webp|ico|pdf|zip|tar|gz|mp4|mp3|woff2?|css|js)$"
  ],
  "maxTokensPerChunk": 512,
  "minTokensPerChunk": 60,
  "chunkOverlapTokens": 50,
  "prependHeadingContext": true,
  "outputFormat": "standard",
  "previousPageHashes": {},
  "maxConcurrency": 8,
  "requestTimeoutSecs": 20,
  "respectRobotsTxt": true,
  "useApifyProxy": false
}
```

# Actor output Schema

## `chunks` (type: `string`):

Structured, heading-aware Markdown chunks ready for vector databases and AI agents.

## `summary` (type: `string`):

JSON summary with page counts, frameworks detected, and SHA-256 pageHashes for incremental sync.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrls": [
        {
            "url": "https://www.python-httpx.org/"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("weiyi-ai/docs-to-rag-chunks").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "startUrls": [{ "url": "https://www.python-httpx.org/" }] }

# Run the Actor and wait for it to finish
run = client.actor("weiyi-ai/docs-to-rag-chunks").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrls": [
    {
      "url": "https://www.python-httpx.org/"
    }
  ]
}' |
apify call weiyi-ai/docs-to-rag-chunks --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,weiyi-ai/docs-to-rag-chunks"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Nmi0jTvKwbJvuGtQj/builds/RKJcqvqicNaPzzckz/openapi.json
