Documentation
¶
Overview ¶
Package semanticsearch is the library entry point: it composes an embedder, a metadata store, a vector store, and a set of strategies into an Engine that indexes a directory and answers meaning-based queries. Every dependency is an interface, so callers can use the built-in implementations (the NewXxx constructors) or supply their own.
Index ¶
- Constants
- Variables
- func NewAiEmbedder(config AiEmbedderConfig, model strategy.EmbeddingModel) strategy.AiClient
- func NewGeneralModel(name string, dimensions int) strategy.EmbeddingModel
- func NewModel(predefined PredefinedModel, dimensions ...int) strategy.EmbeddingModel
- func NewPostgresStorage(ctx context.Context, dsn string) (storage.Storage, error)
- func NewPostgresVectorStorage(ctx context.Context, dsn string, dimensions int, index PostgresVectorIndex) (storage.VectorStorage, error)
- func NewSQLiteStorage(ctx context.Context, path string) (storage.Storage, error)
- func NewSQLiteVectorStorage(ctx context.Context, path string, dimensions int) (storage.VectorStorage, error)
- type AiEmbedderConfig
- type Config
- type DocumentResult
- type Engine
- type IndexOptions
- type IndexPhase
- type IndexProgress
- type PostgresVectorIndex
- type PredefinedModel
- type SearchConfig
- type SearchResult
- type Standard
- type StrategyFactory
Constants ¶
const ( // PhaseScanning walks the tree and registers what it finds. No total. PhaseScanning = pipeline.PhaseScanning // PhaseIndexing reads, chunks, and embeds the files whose content changed. total is the // files the walk found, so done finishes below it when only some of them changed. PhaseIndexing = pipeline.PhaseIndexing // PhaseCleanup removes documents whose files are gone. No total. PhaseCleanup = pipeline.PhaseCleanup )
Variables ¶
var ( TaskGemma = model.GemmaTasks TaskNomic = model.NomicTasks )
Model-specific query task types for Search. Any string is accepted; these are just the tasks each model documents.
Functions ¶
func NewAiEmbedder ¶
func NewAiEmbedder(config AiEmbedderConfig, model strategy.EmbeddingModel) strategy.AiClient
NewAiEmbedder builds the transport client for the given standard, configured to send the model's id and validate its vector size. It returns nil for an unknown standard or a nil model; NewEngine rejects a nil embedder.
func NewGeneralModel ¶ added in v1.2.0
func NewGeneralModel(name string, dimensions int) strategy.EmbeddingModel
NewGeneralModel builds a template-free model with the given model id and vector size, for any OpenAI-standard model that needs no prompt templates. Switching models or vector sizes is then just a different call, with no new type to implement.
func NewModel ¶ added in v1.2.0
func NewModel(predefined PredefinedModel, dimensions ...int) strategy.EmbeddingModel
NewModel builds the model knowledge (id, dimensions, prompt templates) for a predefined model. Any value that is not a predefined constant is treated as a raw model id and returned as a template-free GeneralModel with the given dimensions. The dimensions argument is optional and ignored for predefined models that have a fixed vector size; supply it only for an unlisted model id.
func NewPostgresStorage ¶ added in v1.1.0
func NewPostgresVectorStorage ¶ added in v1.1.0
func NewPostgresVectorStorage(ctx context.Context, dsn string, dimensions int, index PostgresVectorIndex) (storage.VectorStorage, error)
NewPostgresVectorStorage opens a pgvector vector store at dsn, sized to the embedding dimensions, and prepares its schema. The server must have the pgvector extension available. The index selects exact (PostgresKNN) or approximate (PostgresHNSW) search. Point it at a different dsn than the metadata store to keep vectors in a separate database.
func NewSQLiteStorage ¶
NewSQLiteStorage opens a SQLite metadata store at path and prepares its schema. The returned value is the injectable storage.Storage; a caller can implement that interface instead to use a different backend.
func NewSQLiteVectorStorage ¶
func NewSQLiteVectorStorage(ctx context.Context, path string, dimensions int) (storage.VectorStorage, error)
NewSQLiteVectorStorage opens a sqlite-vec vector store at path, sized to the embedding dimensions, and prepares its schema. Point it at a different path than the metadata store to keep vectors in a separate database.
Types ¶
type AiEmbedderConfig ¶
type AiEmbedderConfig struct {
Standard Standard
BaseURL string
// APIKey is optional. When set it is sent as an "Authorization: Bearer <APIKey>" header
// for hosted endpoints; leave it empty for local servers that need no authentication.
APIKey string
// Timeout is optional per-request timeout for embedding calls. Zero uses the default.
Timeout time.Duration
}
AiEmbedderConfig configures the transport client: which protocol to speak and the endpoint, auth, and timeout to use. The model id and vector size come from the injected Model, not from here.
type Config ¶
type Config struct {
Model strategy.EmbeddingModel
Embedder strategy.AiClient
Storage storage.Storage
VectorStorage storage.VectorStorage
Strategies []StrategyFactory
Searcher search.Searcher
}
Config is the injected object graph for an Engine: the embedder, the two stores, and the strategies. All are required except Searcher, which defaults to the built-in document searcher. Every dependency is an interface, so a caller can supply the built-in implementations (via the NewXxx constructors) or their own.
type DocumentResult ¶ added in v1.3.0
type DocumentResult = search.DocumentResult
DocumentResult is one document match: its id, file name and path, relevance score, and the chunks that matched inside it, ranked best first. It is the type Search returns, defined in core/search and re-exported here for a single-import public API.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is a configured index/search unit. Multiple engines with different embedders, stores, and strategies can run independently and in parallel.
func NewEngine ¶
NewEngine validates the config and composes the engine. It errors on a missing dependency or when two strategies claim the same extension. Strategies are built per Index run (that is the only place they are used), so their resources live no longer than indexing needs them.
func (*Engine) Index ¶
Index runs the two pipelines: discover → register → fingerprint, then read → parse → chunk → embed. Re-running is incremental: unchanged files are not re-embedded. Documents whose files are gone are pruned unless IndexOptions.KeepMissingFiles is set. The strategies (and any resources they open, like the PDF extractor) are built here and released when indexing finishes.
func (*Engine) Search ¶
func (e *Engine) Search(ctx context.Context, config SearchConfig) ([]DocumentResult, error)
Search embeds the query and returns the matching documents, most relevant first, each carrying the chunks that matched inside it. The config carries the query and its optional knobs (MinRelevance, MaxDocuments, MaxChunks, TaskType); passing a task type to a model that does not support one returns an error.
type IndexOptions ¶
type IndexOptions struct {
// FailFast aborts on the first per-document error instead of collecting and continuing.
FailFast bool
// IncludeHidden indexes hidden files and directories.
IncludeHidden bool
// FollowSymlinks resolves and indexes symlink targets.
FollowSymlinks bool
// KeepMissingFiles keeps documents whose files no longer exist on disk. By default indexing
// removes them, along with their chunks and vectors.
KeepMissingFiles bool
// OnProgress, when set, is called as the run advances. It runs synchronously, so a slow
// callback slows the run down.
OnProgress IndexProgress
// EmbedBatchSize is how many chunks are buffered across documents before a batch is sent to
// the embedding server, and the cap on chunks per request. Leave it nil to use the default
// (50); set it to a positive value to override (1 embeds one chunk per request). A non-nil
// value of zero or less is rejected.
EmbedBatchSize *int
}
IndexOptions configures an index run.
type IndexPhase ¶ added in v1.5.0
IndexPhase names the stage an index run is currently in.
type IndexProgress ¶ added in v1.5.0
IndexProgress receives an index run's counters. total is 0 when the phase has none.
type PostgresVectorIndex ¶ added in v1.1.0
type PostgresVectorIndex string
PostgresVectorIndex selects how the pgvector store searches.
const ( // PostgresKNN is exact brute-force k-nearest-neighbor search (a sequential scan, 100% // recall). Best below a few hundred thousand vectors. PostgresKNN PostgresVectorIndex = "knn" // PostgresHNSW is approximate nearest-neighbor search backed by an HNSW index // (sub-linear, trades some recall for speed). Best at large scale. PostgresHNSW PostgresVectorIndex = "hnsw" )
type PredefinedModel ¶ added in v1.2.0
type PredefinedModel string
PredefinedModel selects one of the built-in embedding models by name. Each one bundles the model's id, vector size, and the prompt templates it needs, so callers do not hand-write templates. For a model that is not listed, implement strategy.EmbeddingModel yourself and inject it.
const ( // Gemma300mQAT is EmbeddingGemma (text-embedding-embeddinggemma-300m-qat, 768 dimensions). Gemma300mQAT PredefinedModel = "gemma-300m-qat" // Nomic768 is Nomic Embed Text v1.5 (768 dimensions). Nomic768 PredefinedModel = "nomic-v1.5" // E5Large1024 is Multilingual E5 large (1024 dimensions). E5Large1024 PredefinedModel = "e5-large" // BGELarge1024 is BGE large en v1.5 (1024 dimensions). BGELarge1024 PredefinedModel = "bge-large-en-v1.5" // Qwen30_6B1024 is Qwen3 Embedding 0.6B (1024 dimensions). Qwen30_6B1024 PredefinedModel = "qwen3-0.6b" // MxbaiLarge1024 is mxbai embed large v1 (1024 dimensions). MxbaiLarge1024 PredefinedModel = "mxbai-large-v1" )
Predefined embedding models. Each constant bundles a model id, its native vector size, and the prompt templates the model requires. The dimension is encoded in the constant name so it is visible at the call site (Gemma keeps its parameter-based name).
type SearchConfig ¶ added in v1.3.0
type SearchConfig = search.SearchConfig
SearchConfig is the whole input to a search: the query and its optional knobs. It is defined in core/search and re-exported here for a single-import public API.
type SearchResult ¶
type SearchResult = search.SearchResult
SearchResult is one chunk match: the document it belongs to, the chunk id, its title and text, and the relevance score (0 to 1, higher is closer). It is defined in core/search and re-exported here for a single-import public API.
type Standard ¶
type Standard string
Standard identifies the wire protocol an AI embedder speaks. Most embedding servers are OpenAI-compatible; other standards can be added later without changing callers.
const StandardOpenAI Standard = "openai"
StandardOpenAI is the OpenAI-compatible /v1/embeddings protocol (LM Studio, Ollama, and most local servers).
type StrategyFactory ¶
type StrategyFactory struct {
Extensions []string
Build func(model strategy.EmbeddingModel, embedder strategy.AiClient) (strategy.Strategy, func() error, error)
}
StrategyFactory is a deferred strategy: it declares the extensions the strategy claims (so the engine can reject duplicates before indexing) and builds the strategy once the engine supplies the shared model and embedder. Build may return a cleanup the engine runs after indexing (e.g. to release the PDF extractor); the cleanup is nil when there is nothing to release.
To register a custom strategy, construct a StrategyFactory whose Build returns it.
func NewCodeStrategy ¶
func NewCodeStrategy() StrategyFactory
NewCodeStrategy registers the source-code strategy.
func NewDocxStrategy ¶
func NewDocxStrategy() StrategyFactory
NewDocxStrategy registers the DOCX strategy.
func NewHTMLStrategy ¶ added in v1.6.0
func NewHTMLStrategy() StrategyFactory
NewHTMLStrategy registers the HTML strategy.
func NewMarkdownStrategy ¶
func NewMarkdownStrategy() StrategyFactory
NewMarkdownStrategy registers the Markdown strategy.
func NewPDFStrategy ¶
func NewPDFStrategy() StrategyFactory
NewPDFStrategy registers the PDF strategy. Each engine gets its own PDFium extractor, which the engine releases after indexing.
func NewTextStrategy ¶
func NewTextStrategy() StrategyFactory
NewTextStrategy registers the plain-text strategy (the general strategy used directly).
Directories
¶
| Path | Synopsis |
|---|---|
|
core
|
|
|
embedder/client
Package client holds the embedding transport clients: the code that talks to an embedding server over the wire (protocol, auth, retries).
|
Package client holds the embedding transport clients: the code that talks to an embedding server over the wire (protocol, auth, retries). |
|
embedder/model
Package model holds the embedding model definitions: each model's id, vector size, and the prompt templates it needs to phrase a document chunk and a query.
|
Package model holds the embedding model definitions: each model's id, vector size, and the prompt templates it needs to phrase a document chunk and a query. |
|
search
Package search holds the public search domain types: the query configuration a caller passes, the result types it gets back, and the Searcher seam.
|
Package search holds the public search domain types: the query configuration a caller passes, the result types it gets back, and the Searcher seam. |
|
storage
Package storage defines the resource entities — the data model the application persists and passes between layers.
|
Package storage defines the resource entities — the data model the application persists and passes between layers. |
|
storage/pgvector
Package pgvector implements storage.VectorStorage on PostgreSQL using the pgvector extension and the pure-Go pgx driver (no CGO).
|
Package pgvector implements storage.VectorStorage on PostgreSQL using the pgvector extension and the pure-Go pgx driver (no CGO). |
|
storage/postgres
Package postgres implements storage.Storage on PostgreSQL using the pure-Go pgx driver (no CGO).
|
Package postgres implements storage.Storage on PostgreSQL using the pure-Go pgx driver (no CGO). |
|
storage/sqlitevec
Package sqlitevec stores chunk embedding vectors in the same SQLite database as the document metadata, using the sqlite-vec extension's vec0 virtual table.
|
Package sqlitevec stores chunk embedding vectors in the same SQLite database as the document metadata, using the sqlite-vec extension's vec0 virtual table. |
|
strategy
Package strategy defines what a strategy is: the complete per-file recipe for turning a file's bytes into embedded chunks, plus the types that recipe speaks in.
|
Package strategy defines what a strategy is: the complete per-file recipe for turning a file's bytes into embedded chunks, plus the types that recipe speaks in. |
|
strategy/code
Package code provides the Code strategy.
|
Package code provides the Code strategy. |
|
strategy/docx
Package docx provides the DOCX strategy.
|
Package docx provides the DOCX strategy. |
|
strategy/general
Package general provides GeneralStrategy: the base structured strategy that parses and chunks any text file by generic rules.
|
Package general provides GeneralStrategy: the base structured strategy that parses and chunks any text file by generic rules. |
|
strategy/html
Package html provides the HTML strategy.
|
Package html provides the HTML strategy. |
|
strategy/markdown
Package markdown provides the Markdown strategy.
|
Package markdown provides the Markdown strategy. |
|
strategy/pdf
Package pdf provides the PDF strategy.
|
Package pdf provides the PDF strategy. |
|
examples
|
|
|
basic
command
Basic search: index a folder of files into an on-disk SQLite database, then run a semantic search over it and print the matching documents.
|
Basic search: index a folder of files into an on-disk SQLite database, then run a semantic search over it and print the matching documents. |
|
postgres
command
Postgres search: index the sample files into PostgreSQL with the pgvector extension, then run a semantic search.
|
Postgres search: index the sample files into PostgreSQL with the pgvector extension, then run a semantic search. |
|
progress
command
Progress: index a folder of files and print how far the run has got.
|
Progress: index a folder of files and print how far the run has got. |
|
searchconfig
command
Search config: index the sample files, then run a search that tunes the result set with SearchConfig — a task type, a minimum relevance, and caps on how many documents and chunks come back.
|
Search config: index the sample files, then run a search that tunes the result set with SearchConfig — a task type, a minimum relevance, and caps on how many documents and chunks come back. |
|
internal
|
|
|
pipeline
Package pipeline is the flow: the movement between files.
|
Package pipeline is the flow: the movement between files. |
|
textproc
Package textproc holds generic, format-agnostic text processing utilities: normalization, splitting, windowing, token estimation, and hashing.
|
Package textproc holds generic, format-agnostic text processing utilities: normalization, splitting, windowing, token estimation, and hashing. |
|
migrations
|
|