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
- func Activate(ctx context.Context, db *sql.DB, space *Space) (bool, error)
- func Blob(v []float32) []byte
- func Chunk(text string) []string
- func CleanOrphans(ctx context.Context, db *sql.DB) (int, error)
- func CountPending(ctx context.Context, db *sql.DB, space *Space) (pending, total int, err error)
- func DisabledHandler(context.Context, string) error
- func DocText(title, body, files string) string
- func Enqueue(ctx context.Context, x jobs.Execer) error
- func EstimateTokens(s string) int
- func StoreChunks(ctx context.Context, db *sql.DB, space *Space, items []Embedded, ...) error
- type Client
- type Config
- type Embedded
- type Hit
- type PendingDoc
- type Service
- func (s *Service) Handler() jobs.Handler
- func (s *Service) MinSimilarities() (inject, searchFloor float64)
- func (s *Service) SemanticSearch(ctx context.Context, query string, projectIDs []string, k int) ([]search.SemanticHit, error)
- func (s *Service) Similar(ctx context.Context, query string, projectIDs []string, k int) ([]Hit, error)
- func (s *Service) Start(ctx context.Context)
- func (s *Service) Status(ctx context.Context) Status
- func (s *Service) Sweep(ctx context.Context, maxDocs int) (bool, error)
- func (s *Service) Thresholds() Thresholds
- type ServiceInfo
- type Space
- type SpaceInfo
- type Status
- type Thresholds
Constants ¶
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.
const DefaultTimeout = 60 * time.Second
DefaultTimeout bounds background embedding requests.
const JobKind = "embedding.sweep"
JobKind is the job queue kind of the embedding sweep.
Variables ¶
This section is empty.
Functions ¶
func Activate ¶
Activate makes space the query space once it covers every document, and retires older spaces (dropping their vectors).
func Chunk ¶
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 ¶
CleanOrphans removes vectors whose chunks were deleted.
func CountPending ¶
CountPending reports how many documents a space still lacks.
func DisabledHandler ¶
DisabledHandler is the job handler when semantic search is off: sweeps enqueued by ingest complete immediately.
func EstimateTokens ¶
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 ¶
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.
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 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 ¶
PendingDoc is a document without chunks in a space.
func PendingDocs ¶
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 (*Service) MinSimilarities ¶
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 ¶
Start describes the service (so queries can be served) and schedules a sweep; errors are recorded and retried by the job queue.
func (*Service) Sweep ¶
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 ¶
ActiveSpace returns the space used for queries, or nil.
func EnsureSpace ¶
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.