rag

package
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 16 Imported by: 1 module, 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 rag is retrieval over the caller's own documents: a chunker, a hybrid BM25 + optional-vector index, and nothing else.

It is a subpackage, not part of the root package, for the same reason server is: the root package's contract is small and stable, and retrieval is exactly the kind of capability that grows. Nothing here is imported by the root package.

The Index is deliberately concrete rather than built on a pluggable Store interface. Everything is in-memory, and that ceiling is documented, not hidden: scoring a hundred thousand 768-dim normalized vectors is a few milliseconds of dot product, which is less time than this project spends decoding a single token. A caller whose corpus has genuinely outgrown that — who needs a real vector database, row-level ACLs pushed into a query planner, or a document store shared across processes — is doing something this package's "batteries" tier isn't for, and has a cheap way out: register a hand-written gopherllm.AgenticTool (or agent.RawTool) against their own store instead of this Index. A pluggable Store/Retriever interface pair was considered and rejected: it roughly doubles this package's exported surface to serve a persona this design does not otherwise target, and every interface method added here is a permanent compatibility promise.

Non-goals, stated rather than silently unhandled:

  • CJK and other non-whitespace-delimited scripts. The tokenizer below is unicode.IsLetter/IsDigit-based and treats an unbroken run of such characters as one term, which makes term-frequency/IDF scoring close to meaningless on such content. Fixing this needs a different segmentation strategy (e.g. n-gram tokenization for CJK runs), which is out of scope for this package's first version.
  • Stemming ("return policy" vs. "return policies" is a surface-form miss in the lexical scorer).
  • Phrase and proximity scoring (postings carry no position information).
  • PDF/DOCX ingestion — IngestOptions.Extract is the hook; bring your own.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultTextExtension

func DefaultTextExtension(name string) bool

DefaultTextExtension reports whether name's extension is one AddFS indexes by default (case-insensitive). Exported so a caller building its own ingestion path — a file-upload HTTP handler, say — can apply the same plain-text allowlist without duplicating it, and reject a binary format (PDF, DOCX, a compiled image) before it gets indexed as garbled text instead of after.

Types

type Chunk

type Chunk struct {
	DocID string
	Index int
	Text  string
	Start int
	End   int
}

Chunk is one retrievable window of a Doc, with byte offsets into the original Doc.Text so a citation can point at the source, not a copy.

type Chunker

type Chunker struct {
	// MaxRunes bounds one chunk's size. Zero means 800. If Tokenizer is set,
	// this and OverlapRunes/MinRunes count model tokens instead of runes.
	MaxRunes int
	// OverlapRunes repeats this many trailing runes (or tokens) of a chunk at
	// the start of the next one, so a sentence spanning a chunk boundary is
	// still findable whole in at least one chunk. Zero means 120.
	OverlapRunes int
	// MinRunes is the smallest a trailing chunk may be before it is merged
	// backward into its predecessor instead of standing alone. Zero means
	// 200; a fragment this small on its own is rarely a useful retrieval
	// unit and mostly just dilutes BM25's document-length statistics.
	MinRunes int
	// Tokenizer, when set, makes MaxRunes/OverlapRunes/MinRunes count model
	// tokens rather than runes — the unit retrieval budgets actually care
	// about, since what ultimately matters is how much of the model's
	// context window a chunk consumes.
	Tokenizer *gopherllm.Tokenizer
	// TitlePrefix prepends "Title" (and any heading text tracked by a future
	// Doc field) before a chunk is handed to an Embedder, then strips it
	// before the chunk is shown in a Hit. It affects only the embedded,
	// model-facing text: BM25 indexes doc.Title alongside every chunk's text
	// regardless of this setting, because title terms are cheap to index and
	// among the highest-precision signals available.
	TitlePrefix bool
}

Chunker splits a Doc into overlapping windows sized to fit a retrieval budget. The zero value is ready to use.

func (Chunker) Split

func (c Chunker) Split(doc Doc) []Chunk

Split chunks doc.Text with a paragraph -> sentence -> whitespace -> hard-cut cascade: each fallback is reached only when the one above cannot produce a unit that fits MaxRunes. The result is deterministic — the same input always produces the same offsets — which is what lets a golden-ranking test pin a corpus's expected results as literal data. If a single rune alone exceeds a token budget, it is retained as one chunk: splitting its UTF-8 bytes would corrupt the text. An embedding model can then report that the configured budget cannot represent this input.

type Doc

type Doc struct {
	// ID is the document's stable identity. Re-adding the same ID replaces
	// its chunks (and their BM25 postings) rather than duplicating them.
	ID    string
	Title string // shown in a citation, and folded into BM25 regardless of Chunker.TitlePrefix
	Path  string // where it came from; empty for an in-memory document
	Text  string
	// Time is the document's date, used for the recency signal. The zero
	// value disables recency scoring for this document only.
	Time time.Time
	Kind string // caller-defined class ("note", "email"); see Ranking.KindWeight
	Meta map[string]string
}

Doc is one source document before chunking.

type DocInfo

type DocInfo struct {
	ID, Title, Path, Kind string
	Time                  time.Time
	Chunks                int
}

DocInfo summarizes one indexed Doc for a listing UI, without its (potentially large) Text.

type Embedder

type Embedder interface {
	EmbedBatch(ctx context.Context, texts []string) ([]gopherllm.EmbeddingResult, error)
}

Embedder produces one vector per text, batched. *gopherllm.Model satisfies it via Model.EmbedBatch.

type Hit

type Hit struct {
	Chunk
	Title string
	Path  string
	Kind  string
	Time  time.Time
	// Vector is the cosine similarity in [-1,1], 0 when the Index has no
	// Embedder configured.
	Vector float32
	// Keyword is the BM25 score, batch-normalized into [0,1] for this query.
	Keyword float32
	// Recency is the exponential-decay score against Ranking.RecencyHalfLife,
	// in [0,1]; 0 when the chunk's Doc.Time is zero.
	Recency float32
	// Score is the blend actually used for ordering, in [0,1].
	Score float32
	// LexicalOnly reports that this hit survived Query.MinVector only because
	// it is a genuine BM25 term match, not a vector neighbor.
	LexicalOnly bool
}

Hit is one retrieved chunk with every score component kept separately, so a ranking can be explained: "this came back because the words matched, not because it is semantically close" is a different bug report from the reverse.

type Index

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

Index is an in-memory hybrid index. Search holds a read lock while ranking indexed chunks. Add and Remove hold the write lock while updating them.

func Load

func Load(r io.Reader, opts Options) (*Index, error)

Load rebuilds an Index from a snapshot written by Save. opts.EmbedderID must match the snapshot's recorded value (both empty counts as a match, meaning "no embedder either time"): comparing vectors from two different embedders as if they shared a space would silently return meaningless results, so a mismatch is refused rather than risked. opts.Embedder itself is used for future Add calls and Search's query embedding; it is not required to reload a pure-BM25 snapshot.

func New

func New(opts Options) *Index

New returns an empty Index configured by opts.

func (*Index) Add

func (ix *Index) Add(ctx context.Context, docs ...Doc) error

Add chunks and indexes docs. Re-adding an existing Doc.ID replaces its chunks (and their BM25 postings) entirely rather than duplicating them. Every document's chunks are embedded in one batch (when an Embedder is configured), so adding a corpus's worth of documents in one Add call is materially cheaper than one call per document.

func (*Index) AddFS

func (ix *Index) AddFS(ctx context.Context, fsys fs.FS, opts IngestOptions) (added, skipped int, err error)

AddFS walks fsys and indexes every file opts.Match accepts (or the default plain-text extension list), using opts.Extract (or a plain UTF-8 read) to turn each into a Doc. added and skipped count files, not chunks.

A file Extract errors on, or one over MaxFileBytes, is skipped and does not fail the walk. The first error from the walk itself (a permission failure, an unreadable directory) does fail it, since that indicates fsys cannot be trusted rather than one file being unreadable content.

func (*Index) Docs

func (ix *Index) Docs() int

Docs reports the total number of indexed documents.

func (*Index) HasEmbedder

func (ix *Index) HasEmbedder() bool

HasEmbedder reports whether this Index was constructed with an Embedder and therefore blends vector similarity into Search, rather than scoring on BM25 keyword matching alone. Exported so a caller reporting the index's capabilities (a status endpoint, a CLI summary) does not need its own copy of Options to know which mode is active.

func (*Index) Len

func (ix *Index) Len() int

Len reports the total number of indexed chunks.

func (*Index) List

func (ix *Index) List() []DocInfo

List reports every indexed Doc, in the order each was first added (or, for an Index rebuilt by Load, the order Save wrote them in).

func (*Index) Remove

func (ix *Index) Remove(ids ...string) int

Remove deletes docs by ID, along with their chunks and BM25 postings. An ID not present in the Index is silently ignored. It returns how many of the given IDs were actually present and removed.

func (*Index) Save

func (ix *Index) Save(w io.Writer) error

Save writes a snapshot of the index. The format is encoding/gob over plain Go structs — simpler and safer than a hand-rolled binary layout, at the cost of some size versus a packed float32 slab; this package has made no promise yet that a saved index is small, only that reloading it is fast compared to re-embedding a whole corpus.

func (*Index) Search

func (ix *Index) Search(ctx context.Context, query string, q Query) ([]Hit, error)

Search ranks the index against query, blending BM25 keyword matching, cosine vector similarity (when this Index has an Embedder), and recency, per q and the Index's Ranking.

type IngestOptions

type IngestOptions struct {
	// Match selects which files to read. The default accepts common
	// plain-text extensions (.txt .md .markdown .csv .tsv .json .log .go and
	// a handful of others); a file is skipped when Match returns false.
	Match func(path string, info fs.FileInfo) bool
	// MaxFileBytes skips a file larger than this. Zero means 4 MiB.
	MaxFileBytes int64
	// FollowSymlinks controls whether a symlink entry is followed. Default
	// false: an untrusted or accidentally-circular directory tree should not
	// be walked into just because AddFS was pointed at it.
	FollowSymlinks bool
	// Extract turns a file's raw bytes into a Doc. The default treats the
	// content as UTF-8 text and uses the file's base name as Doc.Title. This
	// is the hook for PDF/DOCX/HTML ingestion: this package ships none of
	// those extractors (see the package doc's non-goals) — bring your own.
	Extract func(path string, data []byte) (Doc, error)
}

IngestOptions configures AddFS's directory walk.

type LexicalMode

type LexicalMode int

LexicalMode selects how a Query's BM25 half treats multiple query terms.

const (
	// LexicalAny scores a chunk if it contains at least one query term (an OR
	// match) — the default, and the right choice for an ordinary question.
	LexicalAny LexicalMode = iota
	// LexicalAll requires every query term to appear in a chunk (an AND
	// match) — the right choice for a query that IS an identifier or a short
	// exact phrase, where a partial match is usually noise.
	LexicalAll
)

func GuessLexicalMode

func GuessLexicalMode(query string) LexicalMode

GuessLexicalMode is a heuristic a caller MAY use when building a Query, not something Search applies automatically: the zero value of LexicalMode is LexicalAny, indistinguishable from "the caller wants OR-recall", so applying this automatically would reintroduce exactly the zero-value ambiguity Ranking's weight rule (see effectiveWeights) exists to avoid.

It returns LexicalAll for a short query (at most 3 whitespace-separated tokens) containing a token that mixes letters and digits, or that joins two alphanumeric runs with a hyphen, underscore, dot or slash — the shape of an exact identifier lookup — and LexicalAny otherwise.

type Options

type Options struct {
	// Embedder produces the vector half of retrieval. Nil (the default)
	// means pure BM25: no model is required, and Search never calls
	// anything. This is deliberately not the always-on default — a chat
	// model's mean-pooled hidden states are not a trained embedding head,
	// every indexed chunk clears the Runner's KV prefix cache, and plain
	// BM25 already wins the queries people actually type at their own
	// documents: part numbers, error codes, invoice ids, surnames. Configure
	// a dedicated encoder (BGE/E5/Nomic/Granite) here when semantic recall is
	// worth those two costs.
	Embedder Embedder
	// EmbedderID identifies which embedder produced this Index's vectors.
	// Load refuses to open a snapshot whose recorded EmbedderID does not
	// match, since comparing vectors from two different embedders as if they
	// shared a space would silently return meaningless neighbors.
	EmbedderID string
	// QueryPrefix and DocPrefix are prepended before embedding a query or a
	// document chunk, for models trained with an instruction convention
	// (E5's "query: "/"passage: ", Nomic's "search_query: "/
	// "search_document: "). Empty by default — GopherLLM embeds no
	// third-party convention for you to opt into by accident.
	QueryPrefix, DocPrefix string
	Chunker                Chunker
	Ranking
}

Options configures a new Index.

type Query

type Query struct {
	// TopK bounds the number of hits returned. Zero means 5.
	TopK int
	// MinScore is the minimum blended Score (see Ranking) a hit must reach.
	// Zero means 0.25. For a chunk with no keyword match at all, the check is
	// made against the score with its recency contribution stripped out, so
	// a merely-recent, otherwise-irrelevant chunk cannot pass the bar on
	// freshness alone.
	MinScore float32
	// MinVector is the minimum cosine similarity a chunk needs to be
	// considered AT ALL when an Embedder is configured — except a chunk that
	// is a genuine BM25 term match, which is exempt (see Hit.LexicalOnly).
	// Zero (the default) disables this filter.
	MinVector float32
	// MaxChunksPerDoc caps how many of TopK's slots one Doc may occupy — a
	// diversity guard against one long document crowding out every other
	// source. Zero means 2; a negative value disables the cap.
	MaxChunksPerDoc int
	// MaxDocs caps the number of distinct documents represented across all
	// hits. Zero means unlimited.
	MaxDocs int
	// Neighbours widens each hit to include this many chunks before and
	// after the matched one, from the same Doc, using the ORIGINAL
	// contiguous text between their offsets (not a concatenation of the
	// individual chunk strings, which may overlap per Chunker.OverlapRunes).
	Neighbours int
	// Filter, when set, excludes a Doc from consideration before any scoring
	// happens.
	Filter func(Doc) bool
	// Lexical selects BM25's OR/AND behavior. See GuessLexicalMode for a
	// heuristic a caller may apply when building a Query.
	Lexical LexicalMode
}

Query configures one Search call.

type Ranking

type Ranking struct {
	// VectorWeight, KeywordWeight and RecencyWeight blend the three signals.
	//
	// If ALL THREE are zero (the zero-value Ranking{} case), the documented
	// defaults apply: 0.7 / 0.2 / 0.1, renormalized over whichever signals
	// are actually present in this Index (an index with no Embedder scores
	// 0.67 keyword / 0.33 recency, not capped at 0.3 keyword).
	//
	// If ANY ONE of the three is non-zero, all three are taken EXACTLY as
	// given — including a zero among them, which then means exactly zero
	// weight for that signal. This is the whole rule: it is what lets
	// Ranking{KeywordWeight: 1} mean pure lexical search, rather than the
	// zero VectorWeight being silently reinterpreted as "use the default
	// 0.7" the way it would be under a naive per-field default.
	VectorWeight, KeywordWeight, RecencyWeight float32
	// RecencyHalfLife is the exponential decay half-life for the recency
	// signal. Zero means 180 days. A chunk whose Doc.Time is zero scores 0
	// for recency, regardless of this value.
	RecencyHalfLife time.Duration
	// KindWeight multiplies a chunk's final score by Doc.Kind. A Kind with no
	// entry here scores ×1.0, never ×0 — an unconfigured Kind is not
	// silently excluded.
	KindWeight map[string]float32
	// Stopwords are excluded from BM25 entirely: never indexed, never
	// counted in a query. Empty by default; this package ships no built-in
	// list for any language, so it embeds none.
	Stopwords map[string]bool
}

Ranking configures the blend Search uses to order results.

Jump to

Keyboard shortcuts

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