# Chunk Text

> Split large text into smaller chunks for parallel processing.

Source: https://docs.sommatic.ai/en/nodes/data.chunk/

- Slug: `data.chunk`
- Family: Data
- Version: 1.0.0
- Status: Available
- Execution: sync

Split large text into smaller chunks for parallel processing.

Essential for processing documents that exceed LLM context windows. Supports multiple splitting strategies with configurable overlap to prevent losing information at chunk boundaries.

**Split Modes:**
- **Pages:** Split at page markers (--- PAGE N ---). Groups pages to stay under chunk size. Best after OCR.
- **Paragraphs:** Split at paragraph boundaries (double newline). Groups paragraphs to stay under chunk size.
- **Characters:** Split at character boundaries with smart backtracking to sentence/paragraph ends.

## Configuration

- `chunk_size` (number, optional): Target maximum characters per chunk (~10,000 tokens). Actual chunks may be slightly smaller due to boundary alignment. Default: `40000`.
- `overlap` (number, optional): Number of characters to repeat between adjacent chunks. Prevents entity loss at boundaries. Default: `500`.
- `split_mode` (string, optional): Pages: split at page markers from OCR. Paragraphs: split at double newlines. Characters: split at character count. Default: `pages`. Allowed values: `pages`, `paragraphs`, `characters`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `success` (default): Chunked
- `error`: Error

## Input contract

- `text` (string, required): Full text to split into chunks.

## Output contract

- `chunks` (array, optional): Array of text chunks ready for flow.split.
- `chunk_count` (number, optional)
- `total_chars` (number, optional)

## In expressions

What a later node can read from this node's output with `$("Chunk Text").item.json.<path>` (write your node's label instead of `Chunk Text`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `success`, from the output shown in Ports.

- `$("Chunk Text").item.json.chunks` (array) = `[…] (2)`: Array of text chunks ready for flow.split.
- `$("Chunk Text").item.json.chunk_count` (number) = `2`
- `$("Chunk Text").item.json.total_chars` (number) = `61234`
- `$("Chunk Text").item.json.avg_chunk_size` (number) = `30617` (Not suggested by the editor)


## How it works

Splits a long text into chunks by page markers, paragraphs or characters, with an overlap between neighbours, and returns the chunks with their counts.

1. Resolves the config and merges it over the incoming payload; config keys win over payload keys.
2. Reads the text from `text` (config first, then payload). It must be a non-empty string, otherwise the node fails.
3. Applies the defaults `chunk_size` 40000, `overlap` 500 and `split_mode` `pages` (a value of 0 also falls back to the default).
4. `pages`: splits at markers like `--- PAGE 3 ---` (three or more dashes, any case) and groups whole pages while the chunk stays under `chunk_size`. With one page or none it falls back to `paragraphs`.
5. `paragraphs`: splits at blank lines and groups whole paragraphs the same way. In both modes each new chunk starts with the last `overlap` characters of the previous one.
6. `characters`: cuts every `chunk_size` characters, moving the cut back to the last blank line, `. ` or newline found in the 200 characters before it; the next chunk starts `overlap` characters before the cut.
7. Returns `{ chunks, chunk_count, total_chars, avg_chunk_size }` through `success`.

## In a workflow

### Node

```json
{
  "node_id": "node-chunk-contract",
  "label": "Chunk contract",
  "operator_slug": "data.chunk",
  "operator_version": "1.0.0",
  "config": {
    "split_mode": "pages",
    "chunk_size": 40000,
    "overlap": 500
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "chunks": [
      "--- PAGE 1 ---\nContract between the parties...",
      "...last 500 characters of chunk 1\n--- PAGE 9 ---\nAnnex A..."
    ],
    "chunk_count": 2,
    "total_chars": 61234,
    "avg_chunk_size": 30617
  },
  "port": "success"
}
```

## Output ports (behaviour in the code)

### `success`

The text was split. `chunks` is an array of strings, trimmed at both ends.

```json
{
  "chunks": [
    "--- PAGE 1 ---\nContract between the parties...",
    "...last 500 characters of chunk 1\n--- PAGE 9 ---\nAnnex A..."
  ],
  "chunk_count": 2,
  "total_chars": 61234,
  "avg_chunk_size": 30617
}
```

### `error`

The text is missing or `split_mode` is unknown.

```json
{
  "error": "Missing input text to chunk."
}
```

## Behaviour in the code

- `text`: Not declared in the schema, but read by the code and resolved like any config key. Use it to point at a field other than `text`; it overrides `text` from the payload.
- `overlap`: In `characters` mode, if `overlap` is equal to or larger than the distance between two cuts, the loop stops after the first chunk and the rest of the text is dropped. Keep it well below `chunk_size`.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text to chunk.` | `error` | Neither the config nor the payload has a non-empty string in `text`. Map the text explicitly, for example `"text": "{{ $json.ocr_text }}"` in the config. |
| `Unknown split mode: <split_mode>` | `error` | `split_mode` is not `pages`, `paragraphs` or `characters`. |

## Notes and limits

- In `pages` and `paragraphs` mode a single page or paragraph longer than `chunk_size` is kept whole, so a chunk can exceed `chunk_size`.
- Sizes are counted in characters, not tokens. Feed `chunks` to `flow.split` with `path` `chunks` to process each chunk.
- The incoming payload is replaced by the chunk result; reference earlier data with `$("Node")`.
- The worker does not set `ok` (the example shows `true`); the engine routes only by `port`.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.chunk",
  "name": "Chunk Text",
  "category": "data",
  "version": "1.0.0",
  "description": "Split large text into smaller chunks for parallel processing.\n\n  Essential for processing documents that exceed LLM context windows. Supports multiple splitting strategies with configurable overlap to prevent losing information at chunk boundaries.\n\n  **Split Modes:**\n  - **Pages:** Split at page markers (--- PAGE N ---). Groups pages to stay under chunk size. Best after OCR.\n  - **Paragraphs:** Split at paragraph boundaries (double newline). Groups paragraphs to stay under chunk size.\n  - **Characters:** Split at character boundaries with smart backtracking to sentence/paragraph ends.",
  "capabilities": [
    "text",
    "chunking",
    "split",
    "preprocessing"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "chunk_size": {
        "type": "number",
        "title": "Chunk Size (characters)",
        "default": 40000,
        "description": "Target maximum characters per chunk (~10,000 tokens). Actual chunks may be slightly smaller due to boundary alignment."
      },
      "overlap": {
        "type": "number",
        "title": "Overlap (characters)",
        "default": 500,
        "description": "Number of characters to repeat between adjacent chunks. Prevents entity loss at boundaries."
      },
      "split_mode": {
        "type": "string",
        "title": "Split Mode",
        "enum": [
          "pages",
          "paragraphs",
          "characters"
        ],
        "default": "pages",
        "description": "Pages: split at page markers from OCR. Paragraphs: split at double newlines. Characters: split at character count."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Full text to split into chunks."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "chunks": {
        "type": "array",
        "description": "Array of text chunks ready for flow.split."
      },
      "chunk_count": {
        "type": "number"
      },
      "total_chars": {
        "type": "number"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Chunked",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "supports_condition": false
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "data",
    "chunk",
    "split",
    "text",
    "preprocessing"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "chunk_size": {
      "type": "number",
      "title": "Chunk Size (characters)",
      "default": 40000,
      "description": "Target maximum characters per chunk (~10,000 tokens). Actual chunks may be slightly smaller due to boundary alignment."
    },
    "overlap": {
      "type": "number",
      "title": "Overlap (characters)",
      "default": 500,
      "description": "Number of characters to repeat between adjacent chunks. Prevents entity loss at boundaries."
    },
    "split_mode": {
      "type": "string",
      "title": "Split Mode",
      "enum": [
        "pages",
        "paragraphs",
        "characters"
      ],
      "default": "pages",
      "description": "Pages: split at page markers from OCR. Paragraphs: split at double newlines. Characters: split at character count."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Full text to split into chunks."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "chunks": {
      "type": "array",
      "description": "Array of text chunks ready for flow.split."
    },
    "chunk_count": {
      "type": "number"
    },
    "total_chars": {
      "type": "number"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Chunked",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "supports_condition": false
  }
]
```
