chonkie

repository·main·Indexed 26 days ago

https://github.com/feyninc/chonkie

A lightweight, high-performance Python library for efficient text chunking in RAG (Retrieval-Augmented Generation) pipelines. Version 1.7.0 supports various strategies including token-based, semantic, agentic, and code chunking. It features a Pipeline API for chaining chunking and refinement steps, a self-hosted REST API server, and integrated support for multiple tokenizers, embedding providers, LLM genies, and vector database handshakes.

Tokens
64.3K
Snippets
205
Records
339
Agent score
88%

What's inside chonkie

  1. Overview of Chonkie REST API

    main
    Chonkie can be run as a self-hosted REST API, allowing you to perform text chunking and refinement from any language or framework (e.g., JavaScript, Go, Ruby) via HTTP. This approach ensures data stays within your infrastructure and provides full feature parity with the Chonkie library, including batch support for multiple documents and no authentication requirements.
  2. Refine chunks using Chonkie Refinery

    main

    The Refinery module in Chonkie is used to enhance chunks by adding additional context. This process improves the quality of embeddings and keyword indexing.

    There are two primary types of refineries available:

    • OverlapRefinery: Refines chunks by adding overlapping chunks to the original chunk.
    • EmbeddingsRefinery: Refines chunks by adding embeddings to the original chunk.
  3. Available Chunking Strategies in Chonkie

    main

    Chonkie provides several chunking strategies tailored for different use cases. Choose a chunker based on your data type and performance requirements:

    • CodeChunker: Splits code using ASTs; ideal for source files.
    • FastChunker: SIMD-accelerated byte-based chunking (100+ GB/s); best for high-throughput pipelines.
    • LateChunker: Uses the Late Chunking algorithm; best for high recall in RAG.
    • NeuralChunker: Uses a fine-tuned BERT model for semantic shifts.
    • RecursiveChunker: Recursively chunks long documents with structure.
    • SemanticChunker: Groups content by semantic similarity.
    • SentenceChunker: Splits text at sentence boundaries.
    • SlumberChunker: Agentic chunking using LLMs via the Genie interface.
    • TableChunker: Splits markdown tables by row while preserving headers.
    • TeraflopAIChunker: Uses the TeraflopAI Segmentation API for domain-specific tasks (e.g., legal).
    • TokenChunker: Splits text into fixed-size token chunks.
  4. Connect Chonkie to vector databases using Handshakes

    main

    Chonkie uses a concept called Handshakes to facilitate easy integration with various vector databases. Handshakes allow you to embed your text chunks and write them directly to your chosen database with minimal code.

    Supported vector database handshakes include:

    • ChromaDB: Connect to ephemeral or persistent instances.
    • Elasticsearch: Connect to your Elasticsearch index.
    • LanceDB: Connect to local or cloud tables.
    • Milvus: Connect to Milvus collections.
    • MongoDB: Connect to MongoDB collections.
    • Pgvector: Connect to Pgvector databases.
    • Pinecone: Connect to Pinecone indices.
    • Qdrant: Connect to Qdrant databases.
    • Turbopuffer: Connect to Turbopuffer databases.
    • Weaviate: Connect to Weaviate databases.
  5. Understand Chonkie's chunking philosophy and architecture

    main

    Chonkie is designed for RAG (Retrieval-Augmented Generation) applications with a focus on speed, simplicity, and lightweight resource usage.

    Chunking Stages

    To ensure high-quality chunks, Chonkie divides the process into three distinct stages:

    1. Pre-processing
    2. Chunking
    3. Post-processing

    Ideal Chunk Characteristics

    When using Chonkie, aim for chunks that are:

    • Reconstructable: Chunks can be combined to recreate the original text.
    • Independent: Each chunk is a standalone unit of an idea.
    • Sufficient: Chunks contain enough information to be meaningful.

    Performance Optimizations

    Chonkie achieves high performance through several internal mechanisms:

    • Pipelining: Uses a pipeline approach for stronger chunking heuristics.
    • Caching: Caches chunking results to avoid re-computation.
    • Token Management: Uses AutoTikTokenizer (a wrapper around tiktoken) with estimate-validate feedback loops to optimize chunk sizes efficiently.
    • Fast Embeddings: Uses Model2Vec static embeddings by default for ultra-fast, lightweight embedding lookups.
    • Parallel Processing: Leverages parallel execution to maximize resource utilization.
  6. Configure Chonkie CLI parameters

    main

    The Chonkie CLI allows you to configure chunking behavior using two methods: dedicated explicit options and key-value parameter pairs.

    Explicit Parameters

    Use these dedicated flags for common settings:

    • --chunk-size: Set the maximum tokens per chunk.
    • --chunk-overlap: Set the overlap between chunks.
    • --threshold: Set the semantic similarity threshold.

    Key-Value Parameters

    For component-specific or additional parameters, use the *_params options (e.g., --chunker-params, --chef-params, --refiner-params, --handshaker-params) with key=value syntax.

    Type Conversion Rules:

    • true/false $\rightarrow$ boolean
    • none/null $\rightarrow$ None
    • Numeric strings $\rightarrow$ int or float
    • Other strings $\rightarrow$ string

    Precedence: Explicit options (like --chunk-size) will override values provided within *_params if both are present.

    # Single parameter
    --chunker-params tokenizer=gpt2
    
    # Multiple parameters (repeat the option)
    --chunker-params tokenizer=gpt2 --chunker-params min_characters_per_chunk=50
    
    # Boolean parameters
    --chunker-params verbose=true
    
    # Numeric parameters
    --chunker-params chunk_size=512
    --chunker-params threshold=0.8
  7. Use Fetchers in a Pipeline

    main

    Fetchers are the first stage in the CHOMP pipeline (CHef -> CHunker -> Refinery -> Porter/Handshake). They retrieve data from sources and pass it to subsequent stages. You can use the .fetch_from() method within a Pipeline object to ingest data.

    from chonkie.pipeline import Pipeline
    
    # Fetch a single file
    doc = (Pipeline()
        .fetch_from("file", path="document.txt")
        .process_with("text")
        .chunk_with("recursive", chunk_size=512)
        .run())
    
    # Fetch all files in a directory with specific extensions
    docs = (Pipeline()
        .fetch_from("file", dir="./docs", ext=[".txt", ".md"])
        .process_with("text")
        .chunk_with("recursive", chunk_size=512)
        .run())