semantic-chunking

repository·main·Indexed 40 days ago

https://github.com/jparkerweb/semantic-chunking

An NPM package for creating semantically meaningful chunks from large texts, optimized for RAG (Retrieval-Augmented Generation) workflows with LLMs. Version 3.0.2 uses sentence similarity and ONNX embedding models to group related text segments. It features a high-performance `createChunker` for server environments, a microservice API server, and support for custom embedding providers via `embedCallback`.

Tokens
12K
Snippets
37
Records
52
Agent score
50%

What's inside semantic-chunking

  1. Overview of the Semantic Chunking API

    main

    The Semantic Chunking API is a RESTful microservice designed for containerized environments. It provides text chunking capabilities using ONNX embedding models through three primary methods: semantic, dense, and sentence-level.

    Key Features:

    • Three chunking methods: semantic (similarity-based), dense (token-limit based), and sentence-level (individual sentences).
    • Authentication: Optional Bearer token support via API_AUTH_TOKEN.
    • CORS enabled: Supports cross-origin requests.
    • Format: Uses JSON for all requests and responses.
    • Deployment: Docker-ready with built-in health checks.
  2. Configure embedding cache modes in createChunker

    main

    When using createChunker, you can specify a cache mode to manage how embeddings are stored:

    • 'request' (default): Embeddings are deduplicated within a single call and dropped immediately after. Best for sensitive content.
    • 'instance': Uses a byte-bounded LRU cache (500 entries / 50 MB / 1h TTL) that persists across calls on that specific chunker instance.
    • false: No caching is performed.
  3. Integrate custom embedding providers via embedCallback

    main

    Instead of using the built-in ONNX models, you can provide a custom embedding function using the embedCallback option. This is useful for using providers like OpenAI or Cohere. When embedCallback is provided, the built-in ONNX model is not initialized, saving memory and startup time.

    Type Signature: (texts: string[]) => Promise<number[][]>

    Note: If using embedCallback, you can use modelName and dtypeLabel to override the metadata reported in the results (which defaults to custom-embedding and custom).

    // OpenAI Example
    import { chunkit } from 'semantic-chunking';
    import OpenAI from 'openai';
    
    const openai = new OpenAI();
    
    const embedCallback = async (texts) => {
      const response = await openai.embeddings.create({
        input: texts,
        model: 'text-embedding-3-small'
      });
      return response.data.map(d => d.embedding);
    };
    
    const documents = [{ document_name: 'doc1', document_text: '...' }];
    const chunks = await chunkit(documents, { embedCallback });
  4. How semantic chunking works

    main

    The semantic chunking process follows these steps:

    1. Sentence Splitting: The input text is split into an array of sentences.
    2. Embedding Generation: A vector is created for each sentence using the specified ONNX model.
    3. Similarity Calculation: Cosine similarity scores are calculated for each sentence pair.
    4. Chunk Formation: Sentences are grouped into chunks based on the similarity threshold and max token size.
    5. Chunk Rebalancing: Optionally, similar adjacent chunks are combined into larger ones up to the max token size.
    6. Output: The final chunks are returned as an array of objects.
  5. Configure Authentication for the Semantic Chunking API

    main

    Authentication is optional. You can enable it by setting the API_AUTH_TOKEN environment variable. When enabled, all protected endpoints require a Bearer token in the Authorization header.

    Enabling Authentication:

    • Local: export API_AUTH_TOKEN=your-secret-token-here
    • Docker: Use the -e API_AUTH_TOKEN=your-secret-token-here flag in docker run.
    • Docker Compose: Add API_AUTH_TOKEN: your-secret-token-here under the environment key.

    Using Authentication: Include the token in your request header as Authorization: Bearer <your-token>.

    Unprotected Endpoints: The following endpoints do not require authentication:

    • GET / (landing page)
    • GET /api/health
    • GET /api/version
    curl -X POST http://localhost:3001/api/chunkit \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer your-secret-token-here" \
      -d '{"documents": [...]}'
  6. Optimize RAG workflows with chunkPrefix

    main

    For Retrieval-Augmented Generation (RAG) applications, you can improve embedding quality by using the chunkPrefix option. This is particularly effective for models that support task-specific prefixes (like nomic-embed-text-v1.5).

    1. Chunk Documents: Use a prefix like search_document when chunking your knowledge base.
    2. Process Queries: Use a different prefix like search_query when processing the user's search query.

    This ensures the embedding model treats the document chunks and the query with the appropriate semantic context, improving retrieval accuracy.

    // Chunking documents for the vector DB
    const myDocumentChunks = await cramit(documents, { 
        chunkPrefix: "search_document", 
        returnEmbedding: true 
    });
    
    // Processing the user query
    const mySearchQueryChunk = await cramit(queryDocuments, { 
        chunkPrefix: "search_query", 
        returnEmbedding: true 
    });
  7. Use the Semantic Chunking Web UI for experimentation

    main

    The Semantic Chunking Web UI is a visual tool for testing chunking parameters in real-time. It is useful for finding the optimal configuration for your specific text before implementing it in code.

    Key Features:

    • Interactive controls for all chunking parameters.
    • Real-time text processing and visual feedback for similarity thresholds.
    • Model selection and configuration.
    • Results can be downloaded in JSON format.
    • Code Generation: Once you find the best settings, the UI can generate the code required to implement those settings in your project.
  8. Run semantic-chunking with Docker Compose

    main

    The easiest way to run the project, including the Web UI, is via Docker Compose. This method handles port mapping (3000:3000) and persists downloaded embedding models in a ./models directory.

    To start the Web UI server:

    npm run docker:compose:up

    To stop the server:

    npm run docker:compose:down

    Once started, access the Web UI at http://localhost:3000.

  9. Use custom embedding providers with `embedCallback`

    main

    Starting from v2.6.0, you can bypass the built-in ONNX models by using the embedCallback parameter. This allows you to integrate external embedding services. Below are the available implementation patterns:

    Hugging Face Inference API (Free)

    Best for beginners. Requires a free API key from Hugging Face.

    export HF_API_KEY=your_token_here
    npm run example-embedCallback-huggingface

    Local Ollama (Private/Offline)

    Best for privacy. Requires Ollama installed locally and a model pulled (e.g., nomic-embed-text).

    # Install Ollama and pull model
    curl https://ollama.ai/install.sh | sh
    ollama pull nomic-embed-text
    
    # Run example
    npm run example-embedCallback-ollama

    Mock Embeddings (Testing Only)

    Best for CI/CD or zero-dependency testing. It is deterministic but not semantically meaningful.

    npm run example-embedCallback-mock

    OpenAI (Paid)

    Best for production-grade quality. Requires a paid OpenAI API key.

    export OPENAI_API_KEY=your_key_here
    npm run example-embedCallback-openai
  10. Use the Web UI to export results and code

    main

    After tuning your settings in the Web UI, you can utilize the following outputs:

    • Real-time Results: View chunk count, average token length, and processing time immediately.
    • JSON Download: Download the processed chunking results as a JSON file.
    • Code Generation: Generate the implementation code for your specific settings to use in your own project.
  11. Deploy the Semantic Chunking API via Docker

    main

    The API is designed to be deployed using Docker or Docker Compose.

    Quick Start with Docker Compose:

    • API Only: docker-compose up -d (Available at http://localhost:3001)
    • With Web UI: docker-compose --profile webui up -d (API at http://localhost:3001, Web UI at http://localhost:3000)

    Manual Docker Run: To run the API server manually:

    docker run -d \
      -p 3001:3001 \
      -v ./models:/app/models \
      -e API_AUTH_TOKEN=your-token \
      --name semantic-chunking-api \
      semantic-chunking

    Important Configuration:

    • Volume Mounts: It is highly recommended to mount a local directory to /app/models (e.g., -v ./models:/app/models) to persist downloaded ONNX models. This prevents re-downloading large models (23MB to 548MB) on every restart.
    • Environment Variables:
      • PORT: Server port (default: 3001)
      • NODE_ENV: Environment mode (e.g., production)
      • API_AUTH_TOKEN: Optional Bearer token for authentication
    docker build -t semantic-chunking .
    
    docker run -d \
      -p 3001:3001 \
      -v ./models:/app/models \
      -e API_AUTH_TOKEN=your-token \
      --name semantic-chunking-api \
      semantic-chunking