textsplitters

package
v0.0.31 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package textsplitters provides text chunking by character length, token length, and allows adding more advanced strategies (semantic, sentence-aware, etc.) via the TextSplitter interface.

Index

Constants

This section is empty.

Variables

View Source
var DefaultEstimatorCounter = &EstimatorCounter{CharsPerToken: 4}

DefaultEstimatorCounter uses 4 characters per token (typical for English and many tokenizers).

Functions

This section is empty.

Types

type ChunkOptions

type ChunkOptions struct {
	// ChunkSize is the target size per chunk (characters or tokens depending on splitter).
	ChunkSize int
	// ChunkOverlap is the number of characters/tokens to overlap between consecutive chunks.
	// Overlap helps preserve context across boundaries. Must be < ChunkSize.
	ChunkOverlap int
	// MandatorySeparators are hard boundaries applied before splitter-specific logic.
	// Splitting happens on these separators first, then each fragment is split normally.
	MandatorySeparators []string
}

ChunkOptions configures chunk size and overlap for length-based splitters.

func DefaultChunkOptions

func DefaultChunkOptions() ChunkOptions

DefaultChunkOptions returns sensible defaults: 1000 chars/tokens, 200 overlap.

type EstimatorCounter

type EstimatorCounter struct {
	CharsPerToken int
}

EstimatorCounter estimates token count from character count (e.g. ~4 chars per token for English). Useful when a real tokenizer is not available.

func (*EstimatorCounter) CountTokens

func (e *EstimatorCounter) CountTokens(text string) (int, error)

CountTokens returns ceil(rune_count / CharsPerToken).

type GradientBreakpointFinder

type GradientBreakpointFinder struct {
	// MinGradient is the minimum absolute change in similarity to consider a breakpoint.
	MinGradient float64
}

GradientBreakpointFinder identifies breakpoints based on similarity gradients. It finds points where the similarity change is most dramatic.

func (*GradientBreakpointFinder) FindBreakpoints

func (g *GradientBreakpointFinder) FindBreakpoints(ctx context.Context, similarities []float64) []int

FindBreakpoints returns indices where similarity gradient exceeds threshold.

type PercentileBreakpointFinder

type PercentileBreakpointFinder struct {
	// Percentile (0-100) below which similarities are considered breakpoints.
	// E.g., 25 means the lowest 25% of similarity scores become breakpoints.
	Percentile float64
}

PercentileBreakpointFinder finds breakpoints using statistical analysis. It identifies breakpoints where similarity is significantly lower than average.

func (*PercentileBreakpointFinder) FindBreakpoints

func (p *PercentileBreakpointFinder) FindBreakpoints(ctx context.Context, similarities []float64) []int

FindBreakpoints returns indices where similarity is in the lowest percentile.

type RecursiveOptions

type RecursiveOptions struct {
	// Separators defines recursive split boundaries from strongest to weakest.
	// If empty, markdown defaults are used.
	Separators []string
	// PreserveCodeBlocks keeps fenced code blocks (“`...“`) intact when possible.
	PreserveCodeBlocks bool
}

RecursiveOptions configures boundary selection for RecursiveSplitter. Separators are tried in order from most significant to least significant.

func DefaultMarkdownRecursiveOptions

func DefaultMarkdownRecursiveOptions() RecursiveOptions

DefaultMarkdownRecursiveOptions returns markdown-optimized recursive split options.

type RecursiveSplitter

type RecursiveSplitter struct {
	// contains filtered or unexported fields
}

RecursiveSplitter splits text using a recursive separator hierarchy. Chunk size and overlap are measured in tokens using the provided TokenCounter.

func NewMarkdownSplitter deprecated

func NewMarkdownSplitter(opts ChunkOptions, counter TokenCounter) (*RecursiveSplitter, error)

NewMarkdownSplitter creates a markdown-optimized recursive splitter.

Deprecated: use NewRecursiveSplitter with DefaultMarkdownRecursiveOptions().

func NewRecursiveSplitter

func NewRecursiveSplitter(opts ChunkOptions, recursiveOpts RecursiveOptions, counter TokenCounter) (*RecursiveSplitter, error)

NewRecursiveSplitter creates a recursive splitter with configurable separators.

func (*RecursiveSplitter) Split

func (s *RecursiveSplitter) Split(ctx context.Context, text string) ([]string, error)

Split splits markdown text into chunks that respect structural boundaries. Fenced code blocks are kept intact when possible. The text is split hierarchically on headers, then horizontal rules, paragraphs, lines, and finally word boundaries.

type SemanticSplitter

type SemanticSplitter struct {
	// contains filtered or unexported fields
}

SemanticSplitter chunks text based on semantic similarity between sentences. It first splits text into sentences, computes embeddings, and then groups consecutive sentences with similar embeddings into chunks. Chunk size limits (MaxChunkSize, MinChunkSize) are measured in tokens using the provided TokenCounter.

func NewSemanticSplitter

func NewSemanticSplitter(opts SemanticSplitterOptions, embedder embedder.Embedder, counter TokenCounter) (*SemanticSplitter, error)

NewSemanticSplitter creates a splitter that chunks by semantic similarity. counter is used to measure chunk sizes in tokens (MaxChunkSize, MinChunkSize) and is required.

func (*SemanticSplitter) Split

func (s *SemanticSplitter) Split(ctx context.Context, text string) ([]string, error)

Split splits text into semantically coherent chunks.

type SemanticSplitterOptions

type SemanticSplitterOptions struct {
	// MaxChunkSize is the maximum size of a chunk in tokens.
	// If 0, no maximum is enforced (chunks are purely similarity-based).
	MaxChunkSize int

	// MinChunkSize is the minimum size of a chunk in tokens.
	// Sentences below this will be merged with neighbors. Default: 0.
	MinChunkSize int

	// SimilarityThreshold is the cosine similarity threshold (0-1) for grouping sentences.
	// Higher values create more, smaller chunks. Lower values create fewer, larger chunks.
	// Default: 0.5
	SimilarityThreshold float64

	// BufferSize is the number of sentences to include on each side when computing embeddings.
	// This provides context for more accurate similarity calculation. Default: 1.
	BufferSize int

	// Separators defines the sentence boundaries to split on, in order of priority.
	// Default: paragraph breaks, sentence endings, semicolons, commas.
	Separators []string

	// MandatorySeparators are hard boundaries applied before semantic splitting.
	// Each fragment is then processed with normal semantic chunking logic.
	MandatorySeparators []string
}

SemanticSplitterOptions configures the semantic chunking behavior.

func DefaultSemanticSplitterOptions

func DefaultSemanticSplitterOptions() SemanticSplitterOptions

DefaultSemanticSplitterOptions returns sensible defaults for semantic splitting.

type TextSplitter

type TextSplitter interface {
	// Split splits the given text into one or more chunks.
	Split(ctx context.Context, text string) ([]string, error)
}

TextSplitter splits text into chunks. Implementations can use character length, token length, or other strategies.

type TokenCounter

type TokenCounter interface {
	CountTokens(text string) (int, error)
}

TokenCounter returns the number of tokens in text. Implementations can use model-specific tokenizers (e.g. tiktoken) or approximations.

type TokenLengthSplitter

type TokenLengthSplitter struct {
	// contains filtered or unexported fields
}

TokenLengthSplitter chunks text by token count using a TokenCounter, with optional overlap.

func NewTokenLengthSplitter

func NewTokenLengthSplitter(opts ChunkOptions, counter TokenCounter) (*TokenLengthSplitter, error)

NewTokenLengthSplitter creates a splitter that chunks by token length. Uses ChunkOptions for chunk size and overlap (in tokens).

func (*TokenLengthSplitter) Split

func (s *TokenLengthSplitter) Split(ctx context.Context, text string) ([]string, error)

Split splits text into chunks of at most opts.ChunkSize tokens, with opts.ChunkOverlap tokens overlapping between consecutive chunks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL