rag

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 14 Imported by: ? 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 rag is retrieval over an embedded vector store. An Index is a persistent chromem-go database under the host's store directory; every collection in it belongs to one account and one purpose ("documents:{accountID}", "memory:{accountID}"), so a query can never cross tenants. Embeddings come from an embedding credential in the admin vault (Voyage, any OpenAI-compatible endpoint, or Ollama); Anthropic has no embeddings endpoint, so a model credential cannot be used here.

chromem-go is exhaustive cosine search in pure Go with one gob file per document on disk. That is the intended scale: a tenant's runbooks, configuration exports, and notes, not a corpus.

Index

Constants

View Source
const (
	// MetaSourceID is the Document.ID a chunk came from.
	MetaSourceID = "source_id"
	// MetaChunk is the chunk's index within its source, "0" for the first.
	MetaChunk = "chunk"
	// MetaEmbedDim is the length of the stored embedding. Query only
	// considers documents whose dimension matches the caller's embedder,
	// so a collection holding vectors from an earlier embedding model
	// returns no results for them instead of a length-mismatch error.
	MetaEmbedDim = "embed_dim"
)

Metadata keys Add sets on every stored chunk.

View Source
const (
	ChunkSize    = 1500
	ChunkOverlap = 200
)

ChunkSize is the rune length above which Add splits a document, and the size of the chunks it makes; ChunkOverlap is the shared context between consecutive chunks.

View Source
const (
	VoyageEndpoint     = "https://api.voyageai.com/v1"
	VoyageDefaultModel = "voyage-3"
	OllamaEndpoint     = ai.OllamaDefaultEndpoint + "/api"
	OllamaDefaultModel = "nomic-embed-text"
)

Default endpoints and models for the embedding providers.

View Source
const SearchToolName = "search_documents"

SearchToolName is the name of the tool SearchTool returns.

Variables

View Source
var ErrClosed = errors.New("rag: index is closed")

ErrClosed is returned by Collection after Close.

View Source
var ErrNoEmbedder = errors.New("rag: collection has no embedder; pass embeddings explicitly")

ErrNoEmbedder is what the placeholder embedding function of every collection returns, so an implicit chromem embed fails loudly.

Functions

func Add

func Add(ctx context.Context, col *Collection, docs []Document) error

Add indexes docs in col. Content longer than ChunkSize runes is split with Chunk into documents "{id}#{n}"; every stored document carries source_id (the Document.ID), chunk (its index), and embed_dim (its vector length) in metadata so Delete can remove the whole source. Adding a document whose id is already indexed replaces its earlier chunks. Every chunk is embedded with col's embedder (runtime.NumCPU concurrency) before anything is changed, so a failed embedding leaves the previously indexed version intact.

func Chunk

func Chunk(text string, size, overlap int) []string

Chunk splits text into pieces of about size runes for embedding. It splits on blank lines first, then on sentence ends for paragraphs longer than size, then packs the pieces into chunks that do not exceed size. Consecutive chunks share up to overlap runes of trailing context so a fact straddling a boundary is still found. A sentence longer than size is cut at the last space before size, or at size when there is none.

The result never contains an empty string; empty or whitespace input yields nil. size <= 0 or input shorter than size returns the trimmed text as a single chunk.

func CollectionName

func CollectionName(accountID, purpose string) string

CollectionName is the name Collection uses for an account and purpose.

func Delete

func Delete(ctx context.Context, col *Collection, sourceID string) error

Delete removes every chunk of sourceID from col. A source that is not indexed is not an error.

func Embedder

func Embedder(cred ai.Credential) (chromem.EmbeddingFunc, error)

Embedder builds the embedding function for an embedding credential, chosen by cred.Provider:

  • ai.ProviderVoyage: Voyage's OpenAI-compatible endpoint (VoyageEndpoint unless cred.Endpoint is set), model VoyageDefaultModel unless cred.Model is set; the bearer is the Voyage API key.
  • ai.ProviderOpenAICompat: any OpenAI-compatible /embeddings endpoint; cred.Endpoint and cred.Model are required, the bearer is optional for local servers.
  • ai.ProviderOllama: Ollama's native API under the server root (ai.OllamaBaseURL: OllamaEndpoint unless cred.Endpoint is set; a trailing /api or /v1 is accepted), model OllamaDefaultModel unless set.

Anthropic has no embeddings endpoint, so ai.ProviderAnthropic and any other provider are an error. Vectors are normalized by chromem when the provider does not already return unit vectors.

func FormatResults

func FormatResults(hits []Result) string

FormatResults renders hits as the numbered list the search tool returns.

func SearchTool

func SearchTool(index *Index, embed chromem.EmbeddingFunc, purpose string) ai.Tool

SearchTool returns the read-only "search_documents" tool. It queries the caller's account collection for purpose (ai.CallerFromContext supplies the account; a missing caller is an error result) and returns a numbered list of hits with id, similarity, metadata, and content.

Types

type Collection

type Collection struct {
	*chromem.Collection
	// contains filtered or unexported fields
}

Collection is one account collection bound to the embedding function of the caller that opened it. The underlying chromem collection is shared by every caller in the account, but its own embedding function is a placeholder that always fails: Add, Query, and the memory package embed with the function held here, so each caller's credential is used for that caller's operations only, and rotating or deleting a credential takes effect on the next call. The chromem methods are promoted for reads (Count, GetByID) and deletes; calling a chromem method that would embed implicitly (AddDocument without an Embedding, Query by text) fails with ErrNoEmbedder instead of silently using someone else's key.

func (*Collection) Embed

func (c *Collection) Embed(ctx context.Context, text string) ([]float32, error)

Embed returns the embedding of text from the caller's embedding function. An empty vector is an error.

type Document

type Document struct {
	ID       string
	Content  string
	Metadata map[string]string
}

Document is a piece of text to index. Metadata is stored on every chunk and can be used as a Query filter; the keys source_id, chunk, and embed_dim are reserved for Add.

type Index

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

Index is an open vector database holding per-account collections.

func Open

func Open(dir string) (*Index, error)

Open opens (or creates) the persistent database under dir. Files are gzip-compressed gob; writes are synchronous, so there is nothing to flush on Close.

func (*Index) Close

func (ix *Index) Close() error

Close releases the index. chromem-go persists every write as it happens, so Close only marks the index unusable; it never fails today but returns an error for callers that treat it like any other closer.

func (*Index) Collection

func (ix *Index) Collection(accountID, purpose string, embed chromem.EmbeddingFunc) (*Collection, error)

Collection returns the account's collection for purpose, creating it on first use, bound to embed. The name is "{purpose}:{accountID}". purpose must not contain a colon so the name stays unambiguous; accountID is the admin account id. embed is never stored on the shared chromem collection (see Collection); it is used only through the returned handle, so open a handle per caller and per request.

The call is serialized because chromem's GetOrCreateCollection is not atomic: two concurrent creators would each build an empty collection and the second would replace the first in the database's map.

type Result

type Result struct {
	// ID is the stored document id ("{source}#{n}" for a chunk).
	ID       string
	Content  string
	Metadata map[string]string
	// Similarity is the cosine similarity to the query, in [-1, 1].
	Similarity float32
}

Result is one query hit.

func Query

func Query(ctx context.Context, col *Collection, text string, n int, where map[string]string) ([]Result, error)

Query returns the n documents in col most similar to text, best first, optionally restricted to documents whose metadata matches every entry of where. The query is embedded with col's embedder, and only documents stored with the same embedding dimension (embed_dim) are considered, so vectors from a different embedding model are skipped rather than compared. It returns nil for an empty collection and clamps n to the collection size, since chromem rejects nResults above the document count.

Jump to

Keyboard shortcuts

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