embedding

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 23 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 embedding adds semantic search on top of the full-text index: it chunks search documents, embeds them through an OpenAI-compatible embeddings service (e.g. embeddings.cpp's embeddings_server), stores the vectors with sqlite-vec, and answers nearest-neighbour queries.

Vectors are grouped in "spaces", one per embedding service fingerprint (model, quantization, dimensions, truncation). Changing the service creates a new space that is built in the background and replaces the old one only when complete, so vectors from different services are never compared.

Index

Constants

View Source
const (
	ChunkTokens  = 380
	ChunkOverlap = 40
)

Chunking targets (estimated tokens). Snowflake's tokenizer truncates at 512; staying well below keeps every chunk whole and attention cheap.

View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout bounds background embedding requests.

View Source
const JobKind = "embedding.sweep"

JobKind is the job queue kind of the embedding sweep.

Variables

This section is empty.

Functions

func Activate

func Activate(ctx context.Context, db *sql.DB, space *Space) (bool, error)

Activate makes space the query space once it covers every document, and retires older spaces (dropping their vectors).

func Blob

func Blob(v []float32) []byte

Blob encodes a vector the way sqlite-vec expects (little-endian float32).

func Chunk

func Chunk(text string) []string

Chunk splits text into pieces of about ChunkTokens, preferring to cut at line or sentence ends, with ChunkOverlap tokens repeated between neighbours so a match spanning a boundary is not lost.

func CleanOrphans

func CleanOrphans(ctx context.Context, db *sql.DB) (int, error)

CleanOrphans removes vectors whose chunks were deleted.

func CountPending

func CountPending(ctx context.Context, db *sql.DB, space *Space) (pending, total int, err error)

CountPending reports how many documents a space still lacks.

func DisabledHandler

func DisabledHandler(context.Context, string) error

DisabledHandler is the job handler when semantic search is off: sweeps enqueued by ingest complete immediately.

func DocText

func DocText(title, body, files string) string

DocText is what gets embedded for a search document.

func Enqueue

func Enqueue(ctx context.Context, x jobs.Execer) error

Enqueue schedules an embedding sweep (deduplicated).

func EstimateTokens

func EstimateTokens(s string) int

EstimateTokens approximates subword tokens without a tokenizer: about one per CJK character, ~1.3 per other word, one per punctuation mark.

func StoreChunks

func StoreChunks(ctx context.Context, db *sql.DB, space *Space, items []Embedded, texts map[int64]string) error

StoreChunks writes chunks and vectors in one transaction. A document whose content changed meanwhile (its doc_id was re-indexed) is skipped: its chunks were deleted, so it stays pending and is embedded again.

Types

type Client

type Client struct {
	URL        string // full endpoint, e.g. http://127.0.0.1:8090/v1/embeddings
	Model      string
	APIKey     string
	Dimensions int // request Matryoshka truncation; 0 = native size
	HTTP       *http.Client
}

Client talks to an OpenAI-compatible embeddings endpoint.

func (*Client) Describe

func (c *Client) Describe(ctx context.Context, queryPrefix string) (ServiceInfo, error)

Describe returns the service identity. It reads embeddings.cpp's /info when the service has one; otherwise it embeds a probe text to learn the dimension. The requested dimension and the query prefix are part of the identity because they change the vectors MemSpace stores and compares.

func (*Client) Embed

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

Embed returns one vector per input, in order.

func (*Client) EmbedBackground added in v0.1.4

func (c *Client) EmbedBackground(ctx context.Context, inputs []string) ([][]float32, error)

EmbedBackground marks index-building work as lower priority. Providers that do not implement the optional header still receive a standard embeddings body.

type Config

type Config struct {
	URL          string
	Model        string
	APIKey       string
	Dimensions   int
	QueryPrefix  string // "" = automatic ("query: " for Snowflake arctic-embed)
	BatchSize    int
	QueryTimeout time.Duration
	// MinSimilarity and SearchMinSimilarity override the model's calibrated
	// thresholds (0 = calibrated default; see ThresholdsFor).
	MinSimilarity       float64
	SearchMinSimilarity float64
}

Config configures the service (from config.EmbeddingConfig).

type Embedded

type Embedded struct {
	DocID     int64
	ProjectID string
	ChunkNo   int
	Text      string
	Vector    []float32
}

Embedded is one chunk's vector, ready to store.

type Hit

type Hit struct {
	DocID      int64
	ChunkText  string
	Similarity float64 // cosine similarity, 1 = identical direction
}

Hit is a document found by vector similarity.

func KNN

func KNN(ctx context.Context, db *sql.DB, space *Space, vector []float32, projectIDs []string, k int) ([]Hit, error)

KNN returns documents nearest to vector in the space, best chunk per document, optionally restricted to projects. It over-fetches chunks so that k documents remain after grouping.

type PendingDoc

type PendingDoc struct {
	DocID     int64
	ProjectID string
	Text      string
}

PendingDoc is a document without chunks in a space.

func PendingDocs

func PendingDocs(ctx context.Context, db *sql.DB, space *Space, limit int) ([]PendingDoc, error)

PendingDocs lists up to limit documents not yet embedded in space.

type Service

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

Service embeds documents in the background and answers semantic queries. A nil *Service means semantic search is disabled.

func New

func New(db *sql.DB, cfg Config) *Service

New returns nil when cfg.URL is empty.

func (*Service) Handler

func (s *Service) Handler() jobs.Handler

Handler is the jobs.Handler for JobKind.

func (*Service) MinSimilarities

func (s *Service) MinSimilarities() (inject, searchFloor float64)

MinSimilarities implements search.Semantic.

func (*Service) SemanticSearch

func (s *Service) SemanticSearch(ctx context.Context, query string, projectIDs []string, k int) ([]search.SemanticHit, error)

SemanticSearch implements search.Semantic.

func (*Service) Similar

func (s *Service) Similar(ctx context.Context, query string, projectIDs []string, k int) ([]Hit, error)

Similar embeds query and returns the nearest documents in the active space. It returns nothing (and no error) when semantic search cannot be used right now: no active space yet, the service changed and the new space is still building, or the service recently failed (circuit breaker).

func (*Service) Start

func (s *Service) Start(ctx context.Context)

Start describes the service (so queries can be served) and schedules a sweep; errors are recorded and retried by the job queue.

func (*Service) Status

func (s *Service) Status(ctx context.Context) Status

Status reports the service and index state.

func (*Service) Sweep

func (s *Service) Sweep(ctx context.Context, maxDocs int) (bool, error)

Sweep embeds up to maxDocs pending documents into the current service's space and activates it once complete. It reports whether work remains.

func (*Service) Thresholds

func (s *Service) Thresholds() Thresholds

Thresholds returns the similarity thresholds for the current service's model. Before the service has been described, the configured model name (if any) decides.

type ServiceInfo

type ServiceInfo struct {
	Model        string `json:"model"`
	Architecture string `json:"architecture,omitempty"`
	FType        string `json:"ftype,omitempty"`
	// WeightTypes tells mixed quantizations apart (their ftype is the same),
	// e.g. "q4_K:49,q8_0:97" from embeddings.cpp's /info.
	WeightTypes string `json:"weight_types,omitempty"`
	Pooling     string `json:"pooling,omitempty"`
	MaxTokens   int    `json:"max_tokens,omitempty"`
	Dimensions  int    `json:"dimensions"`
	QueryPrefix string `json:"query_prefix,omitempty"`
}

ServiceInfo identifies the embedding service configuration. Two services with equal fingerprints produce comparable vectors.

func (ServiceInfo) Fingerprint

func (i ServiceInfo) Fingerprint() string

Fingerprint is a stable identifier of the info.

type Space

type Space struct {
	ID          int64
	Fingerprint string
	Model       string
	Dimensions  int
	VecTable    string
	Status      string // building | active | retired
}

Space is one embedding service configuration and its vector table.

func ActiveSpace

func ActiveSpace(ctx context.Context, db *sql.DB) (*Space, error)

ActiveSpace returns the space used for queries, or nil.

func EnsureSpace

func EnsureSpace(ctx context.Context, db *sql.DB, info ServiceInfo) (*Space, error)

EnsureSpace returns the space for info, creating it (status building, with its sqlite-vec table) when the fingerprint is new.

type SpaceInfo

type SpaceInfo struct {
	Model       string `json:"model"`
	Dimensions  int    `json:"dimensions"`
	Fingerprint string `json:"fingerprint"`
	Docs        int    `json:"docs_embedded"`
	Pending     int    `json:"docs_pending"`
}

SpaceInfo summarizes a space's coverage.

type Status

type Status struct {
	Enabled      bool         `json:"enabled"`
	URL          string       `json:"url,omitempty"`
	Service      *ServiceInfo `json:"service,omitempty"`
	Active       *SpaceInfo   `json:"active_space,omitempty"`
	Building     *SpaceInfo   `json:"building_space,omitempty"`
	Thresholds   *Thresholds  `json:"thresholds,omitempty"`
	LastError    string       `json:"last_error,omitempty"`
	LastErrorAt  *time.Time   `json:"last_error_at,omitempty"`
	BreakerUntil *time.Time   `json:"breaker_until,omitempty"`
}

Status describes the semantic index.

type Thresholds

type Thresholds struct {
	// Inject: a semantic-only match is put into an agent's context.
	Inject float64 `json:"inject"`
	// SearchFloor: below it, semantic hits are noise and dropped from search.
	SearchFloor float64 `json:"search_floor"`
	// Source says where the values come from: historical model defaults,
	// "config", or "default" for an uncalibrated model.
	Source string `json:"source"`
}

Thresholds are the cosine similarities a meaning-only match needs. Their scale depends on the model: Snowflake arctic-embed scores relevant pairs around 0.32, bge-m3 around 0.60 on a Chinese/English agent-history benchmark (scripts/bench/eval.py), so one set of numbers cannot serve both.

func ThresholdsFor

func ThresholdsFor(model string, inject, searchFloor float64) Thresholds

ThresholdsFor returns the thresholds for a model, with non-zero overrides (from the config) taking precedence.

Jump to

Keyboard shortcuts

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