moon-semchunk

    Semantic chunking for RAG: embedding-similarity-based document splitting with a pluggable Embedder contract.

    rag
    semantic-chunking
    nlp
    text
    Download zip
    Author
    Version
    0.2.1
    License
    MIT
    Last updated
    11 minutes ago
    Downloads
    49

    No dependencies

    #moon-semchunk

    Semantic chunking for RAG in pure MoonBit.

    Splits documents at semantic boundaries instead of fixed character counts. Sentences are embedded via a caller-supplied callback, adjacent cosine differences are computed, and statistical breakpoints decide where one chunk ends and the next begins.

    #Why

    Naive fixed-length or recursive splitting cuts mid-thought and harms retrieval quality. Semantic chunking keeps topically related sentences together. Existing MoonBit RAG libraries provide recursive / token / markdown / HTML splitters, but none implement similarity-based semantic boundaries. moon-semchunk fills that gap as a standalone, reusable library.

    Design follows LangChain's SemanticChunker (MIT, https://github.com/langchain-ai/langchain-experimental/blob/main/libs/experimental/langchain_experimental/text_splitter.py) and LlamaIndex's SemanticSplitterNodeParser (MIT, https://github.com/run-llama/llama_index), reimplemented natively in MoonBit. It is a port of the algorithm, not a copy of the source. Ported: statistical threshold computation, similarity-to-difference conversion and adjacent-sentence breakpoint detection. Not ported: buffer windows, token budgets, hierarchical node structures and LLM-based rewrites.

    #Install

    moon add yuzhiblue/moon-semchunk

    #Usage

    ///|
    fn embed(text : String) -> Array[Double] {
    // Replace with a call to your embedding provider.
    [1.0, 0.0]
    }

    ///|
    fn main {
    let text = "The cat sleeps. The cat plays. The ocean is deep. Ships cross it."
    let chunks = @moon_semchunk.chunk(
    text,
    embed,
    @moon_semchunk.Percentile(95.0),
    )
    for chunk in chunks {
    println(chunk.text)
    }
    }

    The library never calls a model itself. embedder : (String) -> Array[Double] is a pure callback, so the whole pipeline is deterministic and testable on every backend (native / wasm / wasm-gc / js).

    #API

    • chunk(text, embedder, strategy) — one-shot semantic splitting.
    • chunk_with_options(text, embedder, options) — configurable splitting with context windows and size budgets.
    • ChunkOptions — configuration for buffer size, max chunk size and overlap (size budget is a soft cap at sentence boundaries).
    • embed_with_context(sentences, embedder, buffer_size) — context-aware sentence embeddings.
    • chunk_by_budget(text, max_size, overlap) — rule-only size-capped splitting.
    • chunk_stats(chunks) — count, min/max/mean length and sentence count.
    • add_sentence_overlap(chunks, count) — post-split sentence overlap.
    • split_sentences(text) — sentence segmentation (.!?。!?) with decimal-point, abbreviation and repeated-punctuation handling.
    • cosine(a, b) — cosine similarity.
    • adjacent_differences(embeddings) — 1 - cosine between neighbours.
    • detect_breakpoints(differences, strategy) — boolean breakpoint mask.
    • merge_sentences(sentences, breakpoints) — assemble Chunk values.

    Threshold strategies:

    • Percentile(p) — break above the p-th percentile of differences (default 95).
    • StandardDeviation(k) — break above mean + k * stddev (default 3).
    • Interquartile(k) — break above Q3 + k * IQR (default 1.5).

    #License

    MIT. Algorithm references: LangChain SemanticChunker (MIT, https://github.com/langchain-ai/langchain-experimental/blob/main/libs/experimental/langchain_experimental/text_splitter.py) and LlamaIndex SemanticSplitterNodeParser (MIT, https://github.com/run-llama/llama_index). Source code was not copied.

    Chunk

    pub(all) struct Chunk {
    text : String
    index : Int
    }

    A chunk produced by semantic splitting.

    ChunkOptions

    pub(all) struct ChunkOptions {
    strategy : Threshold
    buffer_size : Int
    max_chunk_size : Int
    overlap : Int
    }

    Options for the configurable chunking entry point.

    buffer_size controls context-aware embedding: when greater than zero, sentence i is embedded together with buffer_size neighbours on each side, so its vector carries local context. This mirrors LangChain's buffer_size but stays a pure callback contract.

    max_chunk_size caps the character length of a chunk. A chunk that is still too long after semantic splitting is split again on sentence boundaries. overlap repeats that many trailing sentences of one piece at the head of the next, preserving context across the artificial cut.

    ChunkStats

    pub(all) struct ChunkStats {
    count : Int
    min_length : Int
    max_length : Int
    mean_length : Double
    sentence_count : Int
    }

    Summary statistics for a chunk list, useful for tuning a RAG pipeline.

    Threshold

    pub(all) enum Threshold {
    Percentile(Double)
    StandardDeviation(Double)
    Interquartile(Double)
    }

    Strategy for deciding where a semantic boundary lies.

    add_sentence_overlap

    fn add_sentence_overlap(chunks : Array[Chunk], count : Int) -> Array[Chunk]

    Add sentence-level overlap to an existing chunk list.

    Unlike the budget overlap in ChunkOptions, this operates after all splitting is done: each chunk (except the first) is prefixed with the last count sentences of its predecessor. Indices are reassigned.

    adjacent_differences

    fn adjacent_differences(embeddings : Array[Array[Double]]) -> Array[Double]

    Adjacent sentence differences from a list of embeddings.

    budget_options

    fn budget_options(strategy : Threshold, buffer_size : Int, max_chunk_size : Int) -> ChunkOptions

    Create a ChunkOptions with a context window and size budget configured.

    This is a convenience constructor for the common case where callers want context-aware embedding and a hard size cap, leaving overlap at zero.

    chunk

    fn chunk(text : String, embedder : (String) -> Array[Double], strategy : Threshold) -> Array[Chunk]

    Split text at semantic boundaries using a caller-supplied embedder.

    This is the one-shot entry point: it splits into sentences, obtains a vector for each sentence via embedder, computes adjacent differences, detects breakpoints with strategy, and merges sentences into chunks.

    The library never calls a model itself; embedder is a pure callback so the whole pipeline stays deterministic and testable on every backend.

    chunk_by_budget

    fn chunk_by_budget(text : String, max_size : Int, overlap : Int) -> Array[Chunk]

    Split text into budgeted pieces without semantic analysis.

    Useful as a rule-based baseline or when callers already know the document has a single topic and only need a size cap with overlap.

    chunk_stats

    fn chunk_stats(chunks : Array[Chunk]) -> ChunkStats

    Compute quality statistics from a chunk list.

    Does not re-split text; it inspects the chunks as given, so it can be applied to output from any entry point in this module.

    chunk_texts

    fn chunk_texts(chunks : Array[Chunk]) -> Array[String]

    Convert a chunk list into plain text strings in order.

    chunk_with_options

    fn chunk_with_options(text : String, embedder : (String) -> Array[Double], options : ChunkOptions) -> Array[Chunk]

    Split text with full control over context, strategy and size budget.

    Pipeline: split into sentences, embed each with its context window, compute adjacent differences, detect breakpoints, merge into chunks, then enforce the size budget with overlap. The simpler chunk() function is equivalent to calling this with default_options(strategy).

    chunks_well_formed

    fn chunks_well_formed(chunks : Array[Chunk]) -> Bool

    Check that chunk indices are contiguous starting from zero.

    Useful as an invariant check after composing several chunk operations.

    contextual_differences

    fn contextual_differences(sentences : Array[String], embedder : (String) -> Array[Double], buffer_size : Int) -> Array[Double]

    Compute adjacent differences from context-aware embeddings.

    This is the context-aware counterpart of adjacent_differences, kept as a separate entry so callers can compose their own pipelines.

    cosine

    fn cosine(a : Array[Double], b : Array[Double]) -> Double

    Cosine similarity between two vectors. Returns 0.0 when either vector has zero magnitude or lengths differ.

    default_options

    fn default_options(strategy : Threshold) -> ChunkOptions

    Build options with defaults: no context window and no size budget.

    detect_breakpoints

    fn detect_breakpoints(differences : Array[Double], strategy : Threshold) -> Array[Bool]

    Decide which adjacent positions are semantic breakpoints. Returns a boolean array of length differences.length().

    drop_long_chunks

    fn drop_long_chunks(chunks : Array[Chunk], max_length : Int) -> Array[Chunk]

    Drop chunks longer than max_length characters.

    Complements drop_short_chunks for pipelines that prefer to discard oversized material rather than split it further.

    drop_short_chunks

    fn drop_short_chunks(chunks : Array[Chunk], min_length : Int) -> Array[Chunk]

    Drop chunks shorter than min_length characters.

    Very short chunks are often noise from stray punctuation or headings; removing them before embedding can improve retrieval quality. Indices are reassigned so the result stays well-formed.

    embed_with_context

    fn embed_with_context(sentences : Array[String], embedder : (String) -> Array[Double], buffer_size : Int) -> Array[Array[Double]]

    Embed every sentence with its context window.

    The result has the same length as sentences. buffer_size is clamped to zero for negative input, making this function total for any caller value.

    filter_chunks

    fn filter_chunks(chunks : Array[Chunk], predicate : (Chunk) -> Bool) -> Array[Chunk]

    Filter chunks by predicate while keeping indices contiguous.

    The index field of the returned chunks is reassigned from zero so the result remains a well-formed chunk list.

    flatten_chunks

    fn flatten_chunks(chunks : Array[Chunk], separator : String) -> String

    Concatenate all chunk texts with a separator, preserving order.

    make_options

    fn make_options(strategy : Threshold, buffer_size : Int, max_chunk_size : Int, overlap : Int) -> ChunkOptions

    Create a ChunkOptions with all fields specified.

    merge_sentences

    fn merge_sentences(sentences : Array[String], breakpoints : Array[Bool]) -> Array[Chunk]

    Merge sentences into chunks at breakpoint positions.

    breakpoints[i] is true when a boundary sits between sentence i and sentence i + 1. Sentences are joined with a single space.

    split_sentences

    fn split_sentences(text : String) -> Array[String]

    Break text into sentences at sentence-ending punctuation.

    Supported terminators: ., !, ?, 。, !, ?. The terminator is kept at the end of the sentence. Empty sentences are dropped.

    Context rules avoid the three common false positives of naive splitters: a dot between digits is a decimal point (3.14), a dot after a known abbreviation before a capital is not a boundary (Dr. Smith), and a run of punctuation (..., !!?) is kept as one terminator.

    total_chars

    fn total_chars(chunks : Array[Chunk]) -> Int

    Count the total characters across all chunks.

    window_text

    fn window_text(text : String, width : Int) -> Array[String]

    Split a long string into equal-width windows for batching.

    This is not semantic chunking; it is a helper for feeding many documents through an embedder in batches. The final window may be shorter.

    Source Files