Chunking Strategies

Document chunking strategies for optimal RAG performance using the chonkie library

PraisonAI integrates chonkie for high-performance document chunking.

python
from praisonaiagents import Agent

agent = Agent(
    name="researcher",
    instructions="Use chunked knowledge for long documents",
    knowledge=True,
)

agent.start("Find the section about deployment limits")

The user queries long sources; chunking controls what reaches retrieval.

Diagram

Chunking

📋 Document

✂️ Chunking Engine

💾 Vector DB

✅ Retrieval

PraisonAI integrates chonkie for high-performance document chunking.

Quick Start

  1. Default chunking on an agent
    Agent with Chunking (Simplest)
    from praisonaiagents import Agent
    
    # Default chunking (token-based)
    agent = Agent(
        instructions="Answer questions from documents.",
        knowledge=["research.pdf", "docs/"]
    )
    
    response = agent.start("What are the key findings?")
    Agent with Custom Chunking
    from praisonaiagents import Agent
    
    agent = Agent(
        instructions="Answer questions from documents.",
        knowledge={
            "sources": ["research.pdf"],
            "chunker": {
                "type": "semantic",       # token, sentence, recursive, semantic, sdpm, late
                "chunk_size": 512,
                "chunk_overlap": 128
            }
        }
    )
    
    response = agent.start("What methodology was used?")
    Direct Chunking API
    from praisonaiagents import Chunking
    
    # Create chunker
    chunker = Chunking(
        chunker_type="recursive",
        chunk_size=512,
        chunk_overlap=128
    )
    
    # Chunk text
    chunks = chunker.chunk("Your document content here...")
    for chunk in chunks:
        print(f"Tokens: {chunk.token_count}")
        print(chunk.text[:100])

Available Strategies

StrategyBest ForSpeed
tokenFixed-size chunks⚡ Fastest
sentenceNatural boundaries⚡ Fast
recursiveStructured docs (markdown)⚡ Fast
semanticTopic segmentation🔄 Medium
sdpmResearch papers🔄 Medium
lateBest embeddings🔄 Medium

Chunker Configuration

All Parameters

ParameterTypeDefaultApplies To
typestr"token"All
chunk_sizeint512All
chunk_overlapint128token, sentence
tokenizer_or_token_counterstr"gpt2"token, sentence, recursive
embedding_modelstrautosemantic, sdpm, late

Strategy Examples

Token

python
agent = Agent(
    instructions="Process documents.",
    knowledge={
        "sources": ["docs/"],
        "chunker": {
            "type": "token",
            "chunk_size": 256,
            "chunk_overlap": 50
        }
    }
)

Sentence

python
agent = Agent(
    instructions="Process articles.",
    knowledge={
        "sources": ["articles/"],
        "chunker": {
            "type": "sentence",
            "chunk_size": 512
        }
    }
)

Recursive

python
agent = Agent(
    instructions="Process markdown docs.",
    knowledge={
        "sources": ["README.md", "docs/"],
        "chunker": {
            "type": "recursive",
            "chunk_size": 512
        }
    }
)

Semantic

python
agent = Agent(
    instructions="Process research papers.",
    knowledge={
        "sources": ["papers/"],
        "chunker": {
            "type": "semantic",
            "chunk_size": 512,
            "embedding_model": "all-MiniLM-L6-v2"
        }
    }
)

Which Strategy Should I Use?

Diagram

Speed

Quality

Structured/Markdown

Natural prose

Yes

No

What’s your priority?

Speed or quality?

token
fast, fixed-size

Document type?

recursive

Topic boundaries?

semantic

sentence


How It Works

The user adds documents; the chunking engine splits them by the chosen strategy, embeds each chunk, and stores it for retrieval.

Diagram
VectorDBChunkerAgentUserVectorDBChunkerAgentUserknowledge=[“docs/”]Split documentsStore embedded chunksstart(“Find deployment limits”)Retrieve relevant chunksAnswer from chunks

Installation

bash
pip install "praisonaiagents[knowledge]"

This installs the chonkie library automatically.

Best Practices

Match chunk size to retrieval use case

Smaller chunks improve precision for Q&A; larger chunks preserve narrative for summarisation tasks.

Install the knowledge extra

Run pip install "praisonaiagents[knowledge]" so chonkie and indexing backends load only when needed.

Test overlap on sample docs

Tune overlap on a representative document before indexing an entire corpus.

Pair with smart retrieval

Combine chunking with hybrid search and reranking for better recall on long knowledge bases.

Troubleshooting

SymptomCauseFix
ImportError: chonkie package not found. Please install it using: pip install 'praisonaiagents[knowledge]' on the first Knowledge.add(...) / agent.start(...) callsemantic (the default), sdpm, or late chunker is selected but the [knowledge] extra is not installed. Since PraisonAI PR #5105 both the chunker registry and the embedding backend surface the same actionable hint.pip install 'praisonaiagents[knowledge]'. Or fall back to chunking_strategy="sentence" / "paragraph" / "fixed" / "token", which do not need chonkie’s embedding model.
ImportError that names chonkie.embeddings but omits the pip install hintchonkie is installed but its embeddings submodule cannot import (broken sentence-transformers, torch, or transformers). PR #5105 intentionally preserves the original error so real transitive failures are not masked.Read the underlying error, then reinstall or upgrade that package (pip install --upgrade sentence-transformers is the most common fix).

Related