embedding

package
v1.171.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 15 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 embedding provides text embedding generation for memory vector search.

Index

Constants

View Source
const (
	// KindNoop identifies the placeholder provider returned when no
	// embedder is configured. Callers MUST treat KindNoop as
	// "embedding unavailable" and refuse to persist vectors from it.
	KindNoop = "noop"

	// KindOllama identifies the Ollama-backed provider.
	KindOllama = "ollama"
)

Kind values for Provider.Kind. Used by callers (platform wiring, toolkit write paths) to distinguish a real, network-backed embedder from the placeholder noop. A noop returns zero vectors with no error, which is indistinguishable from a "real" embedding at the Embed/EmbedBatch contract level; without an explicit kind, downstream consumers cannot tell whether the vectors they hold are meaningful.

View Source
const DefaultBackgroundHold = time.Minute

DefaultBackgroundHold is how long a replica's background mark holds without being refreshed or cleared, so a replica that stops mid-embed is not waited on past it.

View Source
const DefaultDimension = 768

DefaultDimension is the default embedding dimensionality (nomic-embed-text).

View Source
const DefaultLinger = time.Second

DefaultLinger is how long the gate stays interactive after the last interactive embed ends. One search embeds its intent once per source it federates, one after another; without it each gap between two of them read as idle, and a waiting background embed went to the embedding server in the middle of the search.

View Source
const DefaultMaxInputBytes = 6000

DefaultMaxInputBytes bounds the byte length of each text the provider sends to Ollama. The platform must cap input itself rather than rely on Ollama's truncate flag, which is unreliable: against Ollama 0.18.0 + nomic-embed-text at a 2048-token context, real content that exceeds the context returns HTTP 400 "the input length exceeds the context length" EVEN with truncate:true, because Ollama's Go-layer truncation and the runner's tokenizer disagree on the token count for some content. Plain prose embeds at ~3.4 chars/token, so the ~2048-token boundary sits near 7000 bytes; 6000 leaves margin for tokenizer drift and denser content (code, JSON specs). Operators running a larger- context model can raise this via config. The cap only trims the text that is embedded; the full content is still stored. See #623.

View Source
const DefaultMaxYield = 30 * time.Second

DefaultMaxYield bounds how long a background embed waits for interactive embeds to finish before it goes ahead anyway, so a replica answering a steady stream of searches still makes indexing progress.

View Source
const DefaultSharedPoll = 250 * time.Millisecond

DefaultSharedPoll is how often a waiting background embed asks the shared signal whether another replica still has an interactive embed in flight.

View Source
const DefaultTimeout = 30

DefaultTimeout is the default HTTP timeout in seconds for embedding API calls. Tuned for the singular /api/embeddings path (one text per call), where a CPU-only Ollama with nomic-embed-text typically returns in 1-3 seconds; 30s is a generous ceiling for transient slowness on the request path. Synchronous request-path callers (memory_recall, memory_manage, knowledge capture_insight, apigateway query-vector) share this default so a wedged Ollama fails the tool call at 30s instead of holding an MCP request handler open for minutes.

The batched /api/embed path used by the api-gateway embed-jobs worker needs a much higher ceiling (CPU-only Ollama on a 32-text batch can take 60+ seconds). The worker constructs its own Provider with a longer timeout from apigateway.embed_jobs.embed_timeout — see pkg/platform/apigateway_embed_jobs.go. The default here intentionally does NOT cover the batch case so request-path consumers are not caught up in the worker's longer budget (#445).

View Source
const MaxSearchAllowance = 20 * time.Second

MaxSearchAllowance bounds how much longer than its own timeout a search's intent embed waits for the background input already at the embedding server (#2846).

View Source
const MinInputBytes = 256

MinInputBytes is the floor the adaptive input bound stops shrinking at. Below this, a refusal is no longer plausibly about the text's length: a model whose context cannot hold 256 bytes is misconfigured, and shrinking further would embed a fragment too small to carry meaning. The provider surfaces the error instead.

Variables

View Source
var ErrInputTooLarge = errors.New("embedding: input exceeds the model context length")

ErrInputTooLarge reports that the provider refused a text because it does not fit the model's context window.

It is separated from a generic provider failure because it is deterministic: the same bytes are refused on every attempt, so a caller that re-sends them unchanged fails identically forever. Callers either bound the text and try again (which this provider does itself, see Embed) or stop re-queueing the unit.

Functions

func EmbedChunksForSearch added in v1.120.0

func EmbedChunksForSearch(ctx context.Context, p Provider, texts []string) [][]float32

EmbedChunksForSearch returns one query embedding per text, or nil to signal that the caller should fall back to lexical-only ranking. It is EmbedForSearch for a caller whose query is itself too large to embed in one call (the knowledge-page dedup probe embeds a candidate page, which can exceed the provider's input budget), so the caller splits it and probes with every piece. The whole set is discarded on any failure: a probe run on a subset of the candidate is exactly the partial-coverage defect chunking exists to remove, so degrading to lexical is the honest outcome. An empty texts slice returns nil.

func EmbedForSearch added in v1.81.0

func EmbedForSearch(ctx context.Context, p Provider, query string) []float32

EmbedForSearch returns a query embedding for relevance ranking, or nil to signal that the caller should fall back to lexical-only ranking. It returns nil when no real provider is configured, when the embed call errors, or when the result is a zero vector (the noop placeholder's output). This is the one hybrid-vs-lexical decision shared by every request-path search surface (recall_insight, the portal knowledge/asset search), so they cannot drift.

func IsConfigured added in v1.64.0

func IsConfigured(p Provider) bool

IsConfigured reports whether p is a real, configured embedding provider whose vectors are safe to persist. Returns false for nil and for the noop placeholder. Used by the platform wiring layer and toolkit write paths as a single-line guard.

func IsZeroVector added in v1.80.0

func IsZeroVector(v []float32) bool

IsZeroVector reports whether every component of v is zero, the signature of the noop provider's output (an unconfigured embedder). Cosine similarity against a zero vector is meaningless, so request-path callers (memory_recall, the portal knowledge/memory search) use this to degrade to lexical ranking. Shared so every surface makes the same hybrid-vs- lexical decision and they cannot drift.

func MaxInputBytes added in v1.120.0

func MaxInputBytes(p Provider) int

MaxInputBytes returns the per-text byte budget p trims input to, or DefaultMaxInputBytes when the concrete provider does not expose one (or reports a non-positive budget). Callers that must not be trimmed — the knowledge-page chunker, which sizes each chunk so the whole page reaches the model — size their text from this rather than from the constant, so raising embedding.ollama.max_input_bytes for a larger-context model widens the chunks with it.

func ModelName added in v1.74.0

func ModelName(p Provider) string

ModelName returns p's underlying embedding model identifier when the concrete provider exposes one, else "". The memory write path stamps this on each row (embedding_model) and the indexjobs memory Sink diffs stored rows against the current provider's model to find model-swap gaps, so both sides must read the model the same way. Mirrors the unexported indexjobs.providerModel.

func SearchAllowance added in v1.169.5

func SearchAllowance(ctx context.Context, p Provider) time.Duration

SearchAllowance is how much longer than its own timeout a search's embed through p waits, because background work is at the embedding server (#2846).

A CPU embedding server serves one input at a time and does not stop one it has begun: a background call the gate preempts still finishes the input in progress, so a search waits for it. A chunk near the input budget takes seconds on a CPU embedder, as long as a search's whole embedding timeout or longer, and a search that gave up then was ranked by words alone while the embedder was about to answer it. The allowance is the expected time of the background input at the server (measured by this replica's worker, or published by another replica's), at most MaxSearchAllowance, and zero when no background work is at the server or p is not the interactive side of a gate.

Types

type BackgroundSignal added in v1.169.5

type BackgroundSignal interface {
	MarkBackground(ctx context.Context, input time.Duration) error
	ClearBackground(ctx context.Context) error
	BackgroundInput(ctx context.Context) (time.Duration, error)
}

BackgroundSignal is the deployment-wide half of the search allowance (#2846). A Signal that also implements it carries, besides the interactive embeds, how long the background input each replica has at the embedding server is expected to take: MarkBackground says this replica has one that takes about input, ClearBackground that it has none, and BackgroundInput how long the server needs to finish what every replica has at it now. A mark a stopped replica leaves lapses.

type Gate added in v1.138.2

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

Gate puts the embeds a person is waiting on ahead of the ones nobody is (#1988). A search, a discovery ranking or a knowledge-page dedup probe goes through the Interactive side; the index worker goes through the Background side, and before each call waits until no interactive embed is in flight on this replica.

Both kinds share one embedding server, and a CPU-bound one serves them in arrival order: a backlog of index jobs from a bulk write put every interactive embed behind it for minutes. The gate stops this replica adding background work while an interactive call waits, and with a Signal shared (Share) the background side also waits while another replica has an interactive embed in flight, which is what reaches the workers of every replica.

Waiting between calls is not enough on a CPU embedder: one background call already at the server held it for minutes, and every search behind it gave up at its embedding timeout (#2839). So a background call at the server is preempted: when an interactive embed begins (on this replica, or on another as the shared signal reports it), the background call's request is canceled, which makes the server stop the inputs it has not reached (Ollama does, measured on 0.30.6: the search waits for the input in progress, not the rest of the batch), and the call is sent again once the interactive work is done. A background call is preempted only within maxYield of its first attempt; past it the call runs to the end, so a replica answering a steady stream of searches still makes indexing progress.

A Gate is safe for concurrent use. The zero value is not usable; call NewGate.

func NewGate added in v1.138.2

func NewGate(maxYield time.Duration) *Gate

NewGate returns a gate whose background side waits at most maxYield for interactive embeds to finish; a non-positive value means DefaultMaxYield.

func (*Gate) Background added in v1.138.2

func (g *Gate) Background(p Provider) Provider

Background wraps p so each call first yields to interactive embeds, and is preempted by one that begins while it is at the server. A nil p stays nil.

func (*Gate) Interactive added in v1.138.2

func (g *Gate) Interactive(p Provider) Provider

Interactive wraps p so its calls count as interactive. A nil p stays nil.

func (*Gate) Preempted added in v1.169.3

func (g *Gate) Preempted() int

Preempted is how many background calls the gate has preempted.

func (*Gate) Share added in v1.138.2

func (g *Gate) Share(sig Signal, poll time.Duration)

Share makes the gate deployment-wide: this replica publishes its interactive embeds to sig, and its background side also waits while sig reports one anywhere, asking again every poll (DefaultSharedPoll when not positive). Call it before the gate is used.

type OllamaConfig

type OllamaConfig struct {
	URL     string
	Model   string
	Timeout time.Duration
	// MaxInputBytes caps the byte length of each text sent to Ollama.
	// Zero or negative selects DefaultMaxInputBytes. See that constant
	// for why the platform bounds input itself rather than trusting
	// Ollama's truncate flag.
	MaxInputBytes int
}

OllamaConfig configures the Ollama embedding provider.

type Provider

type Provider interface {
	// Embed generates an embedding vector for a single text input.
	Embed(ctx context.Context, text string) ([]float32, error)

	// EmbedBatch generates embedding vectors for multiple text inputs.
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

	// Dimension returns the dimensionality of the generated embeddings.
	Dimension() int

	// Kind returns a short identifier for the provider implementation
	// (KindOllama, KindNoop, ...). Callers use this to refuse to
	// persist vectors from the noop placeholder without depending on
	// concrete type assertions.
	Kind() string
}

Provider generates vector embeddings from text.

func NewNoopProvider

func NewNoopProvider(dim int) Provider

NewNoopProvider creates a no-op embedding provider.

func NewOllamaProvider

func NewOllamaProvider(cfg OllamaConfig) Provider

NewOllamaProvider creates an embedding provider that calls Ollama.

func WithMetrics added in v1.141.0

func WithMetrics(p Provider, m *observability.Metrics) Provider

WithMetrics wraps a provider so every call it answers is counted and timed under its model (embedding_calls_total{model, status}, embedding_call_duration_seconds{model}, #1895), on the query path and the indexing path alike, and so a search that fell back to lexical ranking because the call failed is counted (embedding_fallbacks_total{model}). A nil recorder or a provider that is not configured is returned as it is.

type Signal added in v1.138.2

type Signal interface {
	Mark(ctx context.Context) error
	Clear(ctx context.Context) error
	Busy(ctx context.Context) (bool, error)
}

Signal carries "an interactive embed is in flight" between the replicas of one deployment, which share one embedding server (#1988). Mark says this replica has one, Clear that it has none, and Busy whether any replica, this one included, has one now. A replica that stops without clearing its mark is not waited on forever: an implementation lets a mark lapse.

Jump to

Keyboard shortcuts

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