# RAG Chunker: split web content for vector databases (`ucchiii/rag-chunker`) Actor

Split the output of rag-web-browser, web-fetch or website-content-crawler into clean, overlapping chunks with heading paths, token estimates and hashes. Ready for LangChain, LlamaIndex, Pinecone and more. $0.20 per 1,000 chunks.

- **URL**: https://apify.com/ucchiii/rag-chunker.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** AI, Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.14 / 1,000 chunks

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## RAG Chunker — split web content into clean chunks for vector databases

You crawled a website with `apify/rag-web-browser`, `apify/web-fetch` or `apify/website-content-crawler`. Now you need
**chunks** your vector database can embed. This Actor reads those datasets and writes **one row per chunk** — no
scraping, no LLM, no embedding API, no proxies.

- **Heading-aware splitting**: chunks follow Markdown headings and carry a `headingPath` (`["Guide", "Install"]`)
- **Overlap** between chunks to keep context; chunk size is set in characters
- **Code blocks are never cut in the middle** (an oversized block is split by lines and re-fenced)
- **Short fragments merged** into the previous chunk (`minChunkChars`)
- **Boilerplate removed**: repeated blank lines, image-only lines, link-only nav rows, short lines repeated on a page
- **Dedupe** identical chunks across pages and datasets
- Works for English and Japanese (sentence boundaries at `.`, `!`, `?`, `。`, `！`, `？`)
- Stable `chunkId` and `contentHash`, handy as vector IDs for upserts
- **$0.20 per 1,000 chunks written** ($0.0002 each). Reading, duplicates and merged fragments are free.

### Use cases

- Turn a crawled documentation site into chunks for a vector database (Pinecone, Qdrant, pgvector)
- Build a support chatbot knowledge base from help-center pages
- Re-chunk existing crawls with a different chunk size without crawling again
- Deduplicate repeated boilerplate across pages before embedding

### Input

```json
{
  "datasetIds": ["<dataset ID of your website-content-crawler run>"],
  "textField": "markdown",
  "chunkSize": 1500,
  "chunkOverlap": 200,
  "splitBy": "markdown-headings"
}
```

Leave `datasetIds` empty for a free demo on sample pages (rows are marked `_demo: true`).

Pages are read defensively: `url` / `metadata.url` / `crawl.loadedUrl`, `metadata.title` / `title`,
`metadata.languageCode`, and the body from `textField`, then `markdown`, then `text`.

### Output (one row per chunk)

```json
{
  "chunkId": "9f2c1a7b3d4e5f60", "url": "https://example.com/docs/getting-started", "title": "Getting started",
  "headingPath": ["Getting started", "Install"], "chunkIndex": 1, "chunkCount": 4,
  "text": "## Install\n\nInstall the package with pip ...", "charCount": 412, "approxTokens": 103,
  "languageCode": "en", "contentHash": "a1b2c3d4e5f60718", "sourceDatasetId": "abc123"
}
```

`approxTokens` is an **estimate (characters / 4)**, not a real tokenizer count. It is rough for Japanese and code.
Run statistics (`pagesRead`, `chunksCreated`, `duplicates`, `written`, ...) are saved in the key-value store as `STATS`.

### Use with LangChain, LlamaIndex, Pinecone

```python
from apify_client import ApifyClient
client = ApifyClient("<APIFY_TOKEN>")
run = client.actor("<this-actor>").call(run_input={"datasetIds": ["<crawler dataset>"]})
rows = list(client.dataset(run["defaultDatasetId"]).iterate_items())

## LangChain
from langchain_core.documents import Document
docs = [Document(page_content=r["text"], metadata={"source": r["url"], "title": r["title"], "headings": r["headingPath"]}) for r in rows]

## LlamaIndex
from llama_index.core import Document as LIDoc
nodes = [LIDoc(text=r["text"], id_=r["chunkId"], metadata={"url": r["url"], "title": r["title"]}) for r in rows]

## Pinecone (embed with your own model; chunkId is a stable vector ID)
index.upsert([(r["chunkId"], embed(r["text"]), {"url": r["url"], "text": r["text"]}) for r in rows])
```

### Notes

This Actor only processes datasets you already own; it does not access any website. You are responsible for how the
underlying content was collected and for your right to reuse it.

### More tools from the same developer

- [Sitemap URL Extractor](https://apify.com/ucchiii/sitemap-urls) — list every URL of a website from its sitemaps
- [Bulk URL Status Checker](https://apify.com/ucchiii/url-status-checker) — bulk HTTP status and redirect-chain checker for URL lists
- [RSS Feed Reader & Aggregator](https://apify.com/ucchiii/rss-feed-reader) — many RSS / Atom feeds merged into one clean article list
- [Dataset Merge & Dedup](https://apify.com/ucchiii/dataset-dedup-merge) — merge Apify datasets and remove duplicates by the fields you choose

# Actor input Schema

## `datasetIds` (type: `array`):

Dataset IDs (the 'defaultDatasetId' of a finished run of the source Actor, e.g. 'WkzbQMuFYuamGv3YF'). Datasets from your runs of apify/rag-web-browser, apify/web-fetch or apify/website-content-crawler. Leave empty for a free demo on sample pages.

## `textField` (type: `string`):

Name of the field that holds the page body. Falls back to 'markdown' and then 'text' if the field is missing.

## `chunkSize` (type: `integer`):

Target maximum length of one chunk in characters. A code block is kept whole where possible.

## `chunkOverlap` (type: `integer`):

How many characters of the previous chunk are repeated at the start of the next one (capped at half the chunk size).

## `splitBy` (type: `string`):

How to split: 'markdown-headings' (default) splits at headings, then by paragraphs, and records the heading path. 'paragraphs' ignores headings. 'characters' is a fixed-size sliding window.

## `minChunkChars` (type: `integer`):

Fragments shorter than this are merged into the previous chunk (or the next one if first), as long as the merged chunk still fits the chunk size.

## `removeBoilerplate` (type: `boolean`):

Drop repeated blank lines, image-only lines, link-only navigation lines and short lines repeated 3+ times on a page.

## `dedupe` (type: `boolean`):

Skip chunks whose text is identical to one already written (across all pages and datasets).

## Actor input object example

```json
{
  "textField": "markdown",
  "chunkSize": 1500,
  "chunkOverlap": 200,
  "splitBy": "markdown-headings",
  "minChunkChars": 100,
  "removeBoilerplate": true,
  "dedupe": true
}
```

# Actor output Schema

## `results` (type: `string`):

One item per chunk: text, url, title, headingPath, chunkIndex, chunkCount, charCount, approxTokens, languageCode and a content hash.

## `stats` (type: `string`):

Record STATS: run counts (items read, chunks written).

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/rag-chunker").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/rag-chunker").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 '{}' |
apify call ucchiii/rag-chunker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ucchiii/rag-chunker"
        }
    }
}
```

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/YM3Bh4efkmXOooT6k/builds/3zhE8iIQdJbGbFxZe/openapi.json
