# Text Chunker for RAG: text, pages and datasets to chunks (`examsens.ai/text-chunker`) Actor

Splits texts, Markdown, web pages and Apify datasets into chunks for retrieval and vector databases, by paragraphs, headings, sentences or token windows, with overlap, exact OpenAI token counts, heading paths, character offsets and stable chunk IDs.

- **URL**: https://apify.com/examsens.ai/text-chunker.md
- **Developed by:** [Ed Rayyis](https://apify.com/examsens.ai) (community)
- **Categories:** AI, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $10.00 / 1,000 document chunkeds

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

## Text Chunker for RAG: text, pages and datasets to chunks

Split documents into chunks ready for embeddings and vector databases. Give it pasted text or Markdown, web page and file URLs, or Apify datasets such as a crawler's results, and get one dataset item per chunk with its exact token count.

### Strategies

- Recursive (default): fills each chunk with whole paragraphs. A paragraph too long for one chunk is split into sentences, and a sentence too long into token windows. Chunks run across headings.
- By headings: never mixes two sections in one chunk. Set the section level: 2 starts a new chunk at `#` and `##` headings, 3 also at `###`. A long section is split by paragraphs, then sentences.
- By sentences: packs whole sentences up to the chunk size. A heading starts a new chunk.
- Fixed token windows: cuts the text every N tokens, with the overlap as the step back.

Fenced code blocks are kept whole when they fit. Sentence splitting skips common abbreviations such as "Dr." and "e.g." and decimal numbers such as 3.5.

### Every chunk carries

- `text`: what to embed. It starts with the heading path (such as `Returns policy > Refunds`) when the chunk does not start with its own heading, then the overlap from the chunk before, then the content.
- `tokenCount` for `text`, and `contentTokenCount` for the content alone, counted with the tokenizer you pick: `o200k_base`, `cl100k_base` (the encoding OpenAI's text-embedding-3 models use \[1]), or words
- `startChar` and `endChar`: where the content sits in the source text. The content is an exact slice of the source.
- `headingPath`: the list of headings above the chunk
- `overlapText`: the repeated tail of the chunk before. It starts at a sentence or word boundary, and with the headings strategy it never crosses into another section.
- `chunkId`: a stable ID from the source, position and content, so a rerun on the same text gives the same IDs
- `source`, `title`, `chunkIndex`, `chunkCount`, and any dataset fields you choose to copy

### Input

- Texts: plain text or Markdown, one document per entry
- URLs: web pages are reduced to their main text as Markdown with headings kept, and footnote markers and wiki edit links removed. Markdown and text files are read as they are. Up to 20 MB each.
- Apify datasets: each item is one document. The text field is found for you (`markdown`, `text`, `content`, `body`, `transcript`, `article`, `description`), or name it. Copy fields such as `url` onto every chunk.
- Strategy, chunk size in tokens (default 500), overlap in tokens (default 50), tokenizer, section heading level
- Heading path in chunk text (default on)
- Smallest chunk: a chunk with fewer tokens joins the chunk before it in the same section

### Output

Dataset: one item per chunk. A source that cannot be read gets one item with `source` and `error`, such as `HTTP 404`, `PDF files are not read; convert them to text first`, or `no text field found` for a dataset item. The other sources still run.

The key-value store holds a `SUMMARY` record with, for each source, the number of chunks, characters and tokens, or its error, plus the settings used.

### Pricing

Pay per event: one event per document chunked, whatever the number of chunks. A source that fails is not charged. The run stops when it reaches the maximum charge you set.

### Scope and conduct

The actor downloads each URL once. It reads only the datasets you pick, writes nothing to them, and stores nothing beyond the run's own storage.

### Support

Questions and problems: the Issues tab on this page.

### References

1. tiktoken/tiktoken/model.py at main · openai/tiktoken | openai/tiktoken | github.com. https://github.com/openai/tiktoken/blob/main/tiktoken/model.py

# Actor input Schema

## `texts` (type: `array`):

Plain text or Markdown, one document per entry.

## `urls` (type: `array`):

Web pages, Markdown or text files. Web pages are reduced to their main text in Markdown, with headings kept. Up to 20 MB each.

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

Datasets in your account, such as the results of a crawler. Each item is one document. The text field is found for you (markdown, text, content, body, transcript, article, description), or set it below.

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

Field of each dataset item that holds the text, when it is not one of the usual names.

## `keepFields` (type: `array`):

Fields of each dataset item copied onto every one of its chunks, such as url or language.

## `strategy` (type: `string`):

Recursive fills each chunk with whole paragraphs, then sentences, then token windows, across headings. Headings never mixes two sections in one chunk. Sentences packs whole sentences. Tokens cuts fixed token windows.

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

Largest chunk content, in tokens. The heading path and the overlap are added on top.

## `overlap` (type: `integer`):

Tokens from the end of the chunk before, repeated at the start of the next, starting at a sentence or word boundary. 0 for none.

## `encoding` (type: `string`):

cl100k_base is the encoding OpenAI's text-embedding-3 models use. Words counts words.

## `headingLevel` (type: `integer`):

For the headings strategy: 2 starts a new chunk at # and ## headings, 3 also at ###.

## `includeHeadingInText` (type: `boolean`):

Start each chunk's text with its heading path, such as Returns policy > Refunds, when the chunk does not start with that heading.

## `minChunkTokens` (type: `integer`):

Join a chunk smaller than this onto the chunk before it in the same section. 0 keeps every chunk.

## Actor input object example

```json
{
  "texts": [
    "# Returns policy\n\nYou can return most items within 30 days of delivery. Items must be unused and in their original packaging.\n\n## Refunds\n\nRefunds go back to the original payment method within 5 business days of the return arriving. Shipping costs are not refunded.\n\n## Exchanges\n\nTo exchange an item, start a return and place a new order."
  ],
  "urls": [
    {
      "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation"
    }
  ],
  "strategy": "recursive",
  "chunkSize": 500,
  "overlap": 50,
  "encoding": "o200k_base",
  "headingLevel": 2,
  "includeHeadingInText": true,
  "minChunkTokens": 0
}
```

# Actor output Schema

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

No description

# 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 = {
    "texts": [
        "# Returns policy\n\nYou can return most items within 30 days of delivery. Items must be unused and in their original packaging.\n\n## Refunds\n\nRefunds go back to the original payment method within 5 business days of the return arriving. Shipping costs are not refunded.\n\n## Exchanges\n\nTo exchange an item, start a return and place a new order."
    ],
    "urls": [
        {
            "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("examsens.ai/text-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 = {
    "texts": ["""# Returns policy

You can return most items within 30 days of delivery. Items must be unused and in their original packaging.

## Refunds

Refunds go back to the original payment method within 5 business days of the return arriving. Shipping costs are not refunded.

## Exchanges

To exchange an item, start a return and place a new order."""],
    "urls": [{ "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation" }],
}

# Run the Actor and wait for it to finish
run = client.actor("examsens.ai/text-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 '{
  "texts": [
    "# Returns policy\\n\\nYou can return most items within 30 days of delivery. Items must be unused and in their original packaging.\\n\\n## Refunds\\n\\nRefunds go back to the original payment method within 5 business days of the return arriving. Shipping costs are not refunded.\\n\\n## Exchanges\\n\\nTo exchange an item, start a return and place a new order."
  ],
  "urls": [
    {
      "url": "https://en.wikipedia.org/wiki/Retrieval-augmented_generation"
    }
  ]
}' |
apify call examsens.ai/text-chunker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,examsens.ai/text-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/QPSog58eKheHhYbOk/builds/9u25Z5QAJfIX7LgP1/openapi.json
