search

package
v0.20.2 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 20 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 search provides the search service and embedding engine abstractions.

Package search provides the search service that combines full-text and vector (embedding-based) search over collected documents.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AggregateFPPenalty added in v0.20.0

func AggregateFPPenalty(results [][]string, irrelevant []map[string]bool, k int) float64

AggregateFPPenalty computes the macro-average FalsePositivePenalty over all queries in the eval set. results[i] and irrelevant[i] must have equal length. Returns 0 when the inputs are empty or when no irrelevant sets are provided.

func Expand

func Expand(ctx context.Context, client llm.Completer, query string) string

Expand returns a hypothetical document embedding query by asking the LLM to generate a plausible answer for the query. The generated answer is appended to the original query so that both the original keywords and the hypothetical document's vocabulary are used for retrieval.

It is safe to call with a nil client — the original query is returned unchanged. When the LLM call fails or returns an empty string, the original query is returned unchanged and no error is propagated.

func FalsePositivePenalty added in v0.20.0

func FalsePositivePenalty(results []string, irrelevant map[string]bool, k int) float64

FalsePositivePenalty computes the proportion of top-K results that are explicitly marked as irrelevant (thumbs=-1) for a single query.

A false positive (FP) is a document that appears in the top-K results but is in the irrelevant set. The penalty is the fraction of top-K slots that are FPs: penalty = |top-K ∩ irrelevant| / K.

Returns 0 when irrelevant is empty or k <= 0. A score of 0 means no false positives; 1.0 means all top-K results are FPs.

func MRRK

func MRRK(results []string, relevant map[string]bool, k int) float64

MRRK computes the Mean Reciprocal Rank for a single query within the top-K results. Returns 1/rank of the first relevant result, or 0 if no relevant result appears within the top-K. k <= 0 means no cutoff.

func NDCGK

func NDCGK(results []string, relevant map[string]bool, k int) float64

NDCGK computes Normalised Discounted Cumulative Gain at rank K for a single query. results contains document IDs in ranked order (position 0 = rank 1). relevant is the ground-truth set of relevant document IDs. k is the cutoff; if k <= 0 or k > len(results), the full results slice is used.

Returns 0 when relevant is empty or no relevant result appears in the top-K.

Types

type ChunkSearcher

type ChunkSearcher interface {
	SearchFTS(ctx context.Context, query string, limit int) ([]store.ChunkSearchResult, error)
	SearchVector(ctx context.Context, queryVec []float32, limit int) ([]store.ChunkSearchResult, error)
}

ChunkSearcher is the subset of the chunk store used for chunk-based search. It is satisfied by *store.ChunkStore.

type DocCounter

type DocCounter interface {
	CountBySource(ctx context.Context) (map[string]int, error)
}

DocCounter is the subset of store.DocumentStore used by ReindexChecker. It is satisfied by *store.DocumentStore.

type DocumentSearcher

type DocumentSearcher interface {
	Search(ctx context.Context, query model.SearchQuery) ([]*model.SearchResult, error)
}

DocumentSearcher is the subset of the document store used by the search service.

type EmbedClient

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

EmbedClient calls an OpenAI-compatible /v1/embeddings endpoint to produce vector representations of text. When apiURL is empty all methods are no-ops and return nil, enabling full-text-only operation.

Token resolution at construction time:

  1. apiKey non-empty → static Bearer token
  2. authFilePath non-empty → CliProxyAPI OAuth token (auto-refreshed with 5-min TTL)
  3. both empty → no Authorization header sent

EmbedClient satisfies the EmbeddingEngine interface.

func NewEmbedClient

func NewEmbedClient(apiURL, apiKey, authFilePath, model string, dim int) *EmbedClient

NewEmbedClient returns an EmbedClient. When apiURL is empty the client is disabled — Embed and EmbedBatch return nil results without error.

Token priority: apiKey > authFilePath > no auth.

As a convenience, when neither apiKey nor authFilePath is set we force the client into the disabled state regardless of apiURL. This lets operators disable embeddings by clearing EMBEDDING_API_KEY/CLIPROXY_AUTH_FILE without also having to override the default EMBEDDING_API_URL.

dim is the advisory vector dimension (e.g. 1536 for text-embedding-3-small). Pass 0 when unknown.

func (*EmbedClient) Dimension

func (c *EmbedClient) Dimension() int

Dimension returns the advisory vector dimension configured for this client. A value of 0 indicates that the dimension is unknown.

func (*EmbedClient) Embed

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

Embed returns the embedding vector for text, or nil if the client is disabled. text is silently truncated to maxEmbedTokens cl100k_base tokens before sending to the API (falls back to rune-based truncation when the offline encoder is unavailable).

Transient errors (5xx, network failures) and 429 rate-limit responses are retried up to embedMaxRetries times with exponential backoff (1s/2s/4s). When the server returns a Retry-After header with a longer delay, that delay is honoured instead of the default backoff interval. 4xx errors other than 429 are not retried.

func (*EmbedClient) EmbedBatch

func (c *EmbedClient) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch generates embeddings for multiple texts. Each text is silently truncated to maxEmbedTokens tokens before processing.

When the total character count of all texts exceeds maxBatchChars the input is automatically split into sub-batches, each dispatched as a separate API call. The resulting vectors are concatenated in the original input order before being returned. This prevents 400 max_tokens_per_request errors that occur when a large backfill batch exceeds the per-request token limit.

A single item whose character count alone exceeds maxBatchChars is sent as its own sub-batch (the existing per-document rune truncation makes this case practically unreachable, but we handle it defensively).

func (*EmbedClient) Enabled

func (c *EmbedClient) Enabled() bool

Enabled reports whether an embedding API is configured.

type EmbeddingEngine

type EmbeddingEngine interface {
	// Embed returns the embedding vector for a single text, or nil if the
	// engine is disabled. text may be silently truncated by the implementation
	// before sending to the backend.
	Embed(ctx context.Context, text string) ([]float32, error)

	// EmbedBatch returns embedding vectors for multiple texts in the same
	// order as the input slice. When the engine is disabled every entry is nil.
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

	// Enabled reports whether the engine is configured and operational.
	// When false, Embed and EmbedBatch return nil results without error.
	Enabled() bool

	// Dimension returns the expected vector dimension produced by this engine.
	// The value comes from the configuration (EMBEDDING_DIM) and is advisory:
	// the actual dimension of returned vectors is determined by the backend.
	Dimension() int
}

EmbeddingEngine is the embedding backend abstraction used throughout the application. It is satisfied by *EmbedClient (OpenAI) and *LocalEmbedder (Ollama-compatible). A nil implementation should never be passed; use the disabled-state variants (Enabled()==false) instead.

Implementations must be safe for concurrent use from multiple goroutines.

func NewEmbeddingEngine

func NewEmbeddingEngine(cfg *config.Config) (EmbeddingEngine, error)

NewEmbeddingEngine constructs the appropriate EmbeddingEngine based on cfg.EmbeddingProvider:

  • "openai" (default) → *EmbedClient using the OpenAI-compatible API
  • "local" → *LocalEmbedder using an Ollama-compatible API
  • anything else → error

The returned engine may be in the disabled state (Enabled()==false) when the required configuration keys are not set; callers should check Enabled() before assuming vector search is available.

When the engine's Dimension() does not match cfg.EmbeddingDim a warning is logged but no error is returned — the mismatch is advisory only.

type EntityFetcher

type EntityFetcher interface {
	EntitiesForDocuments(ctx context.Context, docIDs []uuid.UUID) (map[uuid.UUID][]model.Entity, error)
}

EntityFetcher retrieves entities linked to a set of documents. It is satisfied by *store.EntityStore.

type EvalMetrics

type EvalMetrics struct {
	NDCG5  float64 // NDCG@5 macro-average
	NDCG10 float64 // NDCG@10 macro-average
	MRR10  float64 // MRR@10 macro-average
	Pairs  int     // number of query/relevance pairs evaluated
}

EvalMetrics aggregates evaluation metrics over an eval set. Each field is the macro-average over all query/relevance pairs.

func Aggregate

func Aggregate(results [][]string, relevant []map[string]bool) EvalMetrics

Aggregate computes EvalMetrics from parallel slices of results and relevance judgements. results[i] is the ranked result list for query i; relevant[i] is the ground-truth set for query i. The slices must have equal length.

Returns a zero EvalMetrics when the input is empty.

type EvalMetricsProvider

type EvalMetricsProvider interface {
	Latest(ctx context.Context) (*store.EvalMetricsRecord, error)
}

EvalMetricsProvider is the subset of store.EvalMetricsStore used by ReindexChecker. It is satisfied by *store.EvalMetricsStore.

type EvalSnapshot

type EvalSnapshot struct {
	NDCG5  float64
	NDCG10 float64
	MRR10  float64
}

EvalSnapshot holds a point-in-time snapshot of eval metrics for comparison.

type HTTPReranker

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

HTTPReranker calls a Jina-compatible /rerank endpoint. When apiURL is empty, it acts as a no-op and returns the original order.

func NewHTTPReranker

func NewHTTPReranker(apiURL, apiKey, model string, topN int) *HTTPReranker

NewHTTPReranker creates a reranker backed by the given endpoint. Pass empty apiURL to get a disabled (no-op) reranker.

func (*HTTPReranker) Enabled

func (r *HTTPReranker) Enabled() bool

Enabled reports whether a rerank API endpoint is configured.

func (*HTTPReranker) Rerank

func (r *HTTPReranker) Rerank(ctx context.Context, query string, docs []string) ([]RerankResult, error)

Rerank scores each document against the query and returns results ordered by descending relevance score. When the reranker is disabled (empty apiURL) it returns the original order with synthetic scores so callers need not branch.

type LocalEmbedder

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

LocalEmbedder sends embedding requests to an Ollama-compatible local server. The expected API contract is:

POST {endpoint}/api/embeddings
Body: {"model": "<model>", "prompt": "<text>"}
Response: {"embedding": [<float32>, ...]}

When endpoint is empty the embedder is in the disabled state and all methods return nil results without error.

LocalEmbedder satisfies the EmbeddingEngine interface.

func NewLocalEmbedder

func NewLocalEmbedder(endpoint, model string, dim int) *LocalEmbedder

NewLocalEmbedder returns a LocalEmbedder targeting the given Ollama endpoint. endpoint should be the base URL, e.g. "http://localhost:11434". model is the Ollama model name, e.g. "bge-m3". dim is the advisory vector dimension from config (used by Dimension()).

func (*LocalEmbedder) Dimension

func (e *LocalEmbedder) Dimension() int

Dimension returns the advisory vector dimension for this embedder.

func (*LocalEmbedder) Embed

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

Embed returns the embedding vector for a single text. Returns nil, nil when the embedder is disabled.

func (*LocalEmbedder) EmbedBatch

func (e *LocalEmbedder) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch returns embedding vectors for multiple texts in input order. Requests are issued sequentially; the loop honours ctx cancellation between iterations so that callers can cancel large batches promptly.

Returns a slice of nil vectors (not an error) when the embedder is disabled.

func (*LocalEmbedder) Enabled

func (e *LocalEmbedder) Enabled() bool

Enabled reports whether the local embedding endpoint is configured.

type ReindexChecker

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

ReindexChecker evaluates reindex thresholds against live data and returns a recommendation. It never initiates any mutation.

func NewReindexChecker

func NewReindexChecker(
	config ReindexConfig,
	metricsStore EvalMetricsProvider,
	docCounter DocCounter,
	stateStore ReindexStateProvider,
) *ReindexChecker

NewReindexChecker returns a ReindexChecker wired to the provided data sources.

func (*ReindexChecker) Check

Check evaluates all thresholds and returns a recommendation.

Three independent checks are performed:

  1. Eval regression: the latest eval metrics are compared against a regression threshold to detect quality degradation.
  2. New document growth: the total active document count is compared against the doc count recorded at the last reindex.
  3. Staleness: the last reindex timestamp is compared against the configured staleness window.

When no reindex event has been recorded (first run), the system recommends reindexing so that a baseline is established.

func (*ReindexChecker) CheckWithBaseline

func (c *ReindexChecker) CheckWithBaseline(
	ctx context.Context,
	current, baseline EvalSnapshot,
) (ReindexRecommendation, error)

CheckWithBaseline is a convenience method that adds eval regression detection when the caller already holds both the current and baseline metric snapshots. This is the typical path used by cmd/eval.

type ReindexConfig

type ReindexConfig struct {
	// EvalRegressionThreshold is the minimum relative metric drop that triggers
	// a reindex recommendation (e.g. 0.05 = 5%).
	EvalRegressionThreshold float64

	// NewDocThreshold is the minimum number of new documents since the last
	// reindex that triggers a recommendation.
	NewDocThreshold int

	// StalenessDays is the minimum number of days since the last reindex
	// before a staleness recommendation is generated.
	StalenessDays int
}

ReindexConfig holds the threshold configuration for reindex recommendations. All thresholds are evaluated independently; a recommendation is generated when ANY threshold is breached.

func DefaultReindexConfig

func DefaultReindexConfig() ReindexConfig

DefaultReindexConfig returns a ReindexConfig with conservative production defaults.

type ReindexRecommendation

type ReindexRecommendation struct {
	ShouldReindex bool     `json:"should_reindex"`
	Reasons       []string `json:"reasons"`
}

ReindexRecommendation is the output of the threshold check. ShouldReindex is true when at least one threshold has been breached. Reasons lists a human-readable description for each breached threshold.

IMPORTANT: This is a recommendation only. The system NEVER auto-executes reindexing; the operator must trigger it manually ("완전 자율 금지").

type ReindexStateProvider

type ReindexStateProvider interface {
	Latest(ctx context.Context) (*store.ReindexState, error)
}

ReindexStateProvider is the subset of store.ReindexStateStore used by ReindexChecker. It is satisfied by *store.ReindexStateStore.

type RerankResult

type RerankResult struct {
	Index int     `json:"index"`
	Score float64 `json:"relevance_score"`
}

RerankResult holds the reranked position and score for a document.

type Reranker

type Reranker interface {
	Enabled() bool
	Rerank(ctx context.Context, query string, docs []string) ([]RerankResult, error)
}

Reranker scores query-document pairs and returns results sorted by relevance.

type Service

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

Service performs hybrid search: it enriches queries with embeddings when available, then delegates to the document store. When chunks are available, chunk-based FTS is used as a fallback for full-document FTS. HyDE (Hypothetical Document Embeddings) can be enabled per-request to improve recall for short or ambiguous queries.

func NewService

func NewService(store DocumentSearcher, embed EmbeddingEngine) *Service

NewService returns a search Service. Use WithChunkStore to enable chunk-based FTS search (issue #9).

func (*Service) Search

func (s *Service) Search(ctx context.Context, q model.SearchQuery) ([]*model.SearchResult, error)

Search executes a search for the given query. If an embedding client is configured, the query text is embedded and the result is used for hybrid (RRF) search; otherwise only full-text search is performed.

When q.UseHyDE is true and an LLM client is configured, the query is expanded via HyDE (Hypothetical Document Embeddings) before retrieval. HyDE adds ~1-3 s of latency due to an additional LLM round-trip; it is opt-in and disabled by default.

Chunk signals (vector + FTS) are fused into the RRF result set when a chunkStore is configured (issue #71). Full-document retrieval is always attempted first; chunk signals are additive and never replace it.

When the primary path returns no results AND a chunk store is configured, chunk-based FTS is attempted as a final fallback strategy.

func (*Service) WithChunkStore

func (s *Service) WithChunkStore(cs ChunkSearcher) *Service

WithChunkStore attaches a ChunkSearcher so that the service can perform chunk-based FTS and vector search.

Chunk signals are incorporated into the RRF fusion as additional retrieval sources alongside the full-document path (issue #71). The full-document path is preserved to avoid regression: chunk vector + chunk FTS are additive.

When the primary path (full-document FTS + vector) returns no results, chunk FTS is attempted as a secondary fallback strategy.

func (*Service) WithEntityFetcher

func (s *Service) WithEntityFetcher(ef EntityFetcher) *Service

WithEntityFetcher attaches an entity store so that named entities extracted from the returned documents are populated in SearchResult.Entities. This is ADDITIVE and omitempty — existing consumers are unaffected when the field is nil. Safe to call with nil — surfacing is silently skipped.

func (*Service) WithLLM

func (s *Service) WithLLM(client llm.Completer) *Service

WithLLM attaches an LLM client used for HyDE (Hypothetical Document Embeddings) query expansion. When set, callers may opt in to HyDE by setting UseHyDE in SearchOptions. Safe to call with a nil client.

func (*Service) WithReranker

func (s *Service) WithReranker(r Reranker) *Service

WithReranker attaches a cross-encoder reranker that post-processes search results when q.UseRerank is true. Safe to call with nil — reranking is silently skipped when the reranker is nil or disabled.

func (*Service) WithWeights

func (s *Service) WithWeights(w model.SearchWeights) *Service

WithWeights sets the RRF fusion weights applied to every search request issued through this service. Zero fields fall back to defaults (k=60, all signal weights = 1.0). Weights are applied per-request and do not affect the store configuration directly.

Jump to

Keyboard shortcuts

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