Documentation
¶
Overview ¶
Package sense holds what the language-AI packages of this module share: the ports a model runtime implements, Embedder for text embedding models, ImageEmbedder for image embedding models, VideoEmbedder for models that embed a video as Segments, and Completer for chat models; the Role an Embedder is asked to embed a text as; Identified, by which a model names the vectors it makes; ErrClosed, which every call on a closed value wraps; and Normalize, which the providers scale their vectors to unit length with. LazyEmbedder, LazyImageEmbedder and LazyCompleter defer loading a model to its first use. It imports no runtime, no store and no other package of the module.
The capabilities live in subpackages: search answers free-text queries over documents and finds the images and videos that look like a given image or video, and tagging suggests tags for a text, from the tags an application already has (Tagger) or written from nothing (Generator). The implementations sit in groups by the port they implement: provider/yzma runs GGUF models locally through llama.cpp, provider/onnx runs image embedding models through ONNX Runtime, provider/phash hashes pictures perceptually to find duplicates without a model, media/ffmpeg samples and cuts videos for the media ports in media, and vector/sqlitevec and vector/pgvec store search vectors. sensetest has the fakes for tests, and zarf/eval measures an Embedder's search and tagging quality over a labelled dataset.
Index ¶
- Variables
- func Normalize(vec []float32)
- type Completer
- type Embedder
- type Identified
- type ImageEmbedder
- type LazyCompleter
- type LazyEmbedder
- func (l *LazyEmbedder) Close() error
- func (l *LazyEmbedder) Dimensions() int
- func (l *LazyEmbedder) Embed(ctx context.Context, role Role, texts []string) ([][]float32, error)
- func (l *LazyEmbedder) Load(ctx context.Context) error
- func (l *LazyEmbedder) Model() string
- func (l *LazyEmbedder) State() (LazyState, error)
- type LazyImageEmbedder
- func (l *LazyImageEmbedder) Close() error
- func (l *LazyImageEmbedder) Dimensions() int
- func (l *LazyImageEmbedder) EmbedImages(ctx context.Context, images []image.Image) ([][]float32, error)
- func (l *LazyImageEmbedder) Load(ctx context.Context) error
- func (l *LazyImageEmbedder) Model() string
- func (l *LazyImageEmbedder) State() (LazyState, error)
- type LazyState
- type LoadPanicError
- type Role
- type Segment
- type VideoEmbedder
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("sense: closed")
ErrClosed is what every call returns, wrapped, on something of this module that has been closed: a provider's model, whose native resources are gone, a lazy model, and a tagging.Tagger. It stays unusable. Test for it with errors.Is to tell a call that arrived after shutdown from one that failed while the model ran.
Functions ¶
func Normalize ¶
func Normalize(vec []float32)
Normalize scales vec to unit length in place, so cosine similarity and dot product rank alike. The model providers call it on what their models return. An all-zero vector has no direction and stays zero; the vector stores refuse one (see vector.Validate).
Types ¶
type Completer ¶
Completer is a chat model: it answers one prompt, a system message that sets the task and a user message that carries the text, with the text of its reply. provider/yzma's Completer is the local implementation. The user message comes from outside, so an implementation must treat it as data, not as markup for its own prompt format.
type Embedder ¶
type Embedder interface {
Embed(ctx context.Context, role Role, texts []string) ([][]float32, error)
Dimensions() int
}
Embedder turns texts into embedding vectors. All vectors returned must have exactly Dimensions() entries; the result slice matches the input order. The role lets an asymmetric model apply its query or document prefix.
type Identified ¶
type Identified interface {
Model() string
}
Identified is an optional port of a model runtime: Model names the model whose vectors it makes, the same string for every instance of the same model and a different one for any other model, so that a store can refuse to mix two models' vectors in one collection even when their dimensions agree. An empty name means the model is unknown, and nothing is checked.
type ImageEmbedder ¶
type ImageEmbedder interface {
EmbedImages(ctx context.Context, images []image.Image) ([][]float32, error)
Dimensions() int
}
ImageEmbedder turns images into embedding vectors, one per image in input order, each with exactly Dimensions() entries, compared by cosine. Images carry no Role: an image model is symmetric. The vectors of one model form one space; they never compare with another model's, nor with a text Embedder's, unless the two are the towers of one model trained together. The method is not called Embed so that one type can implement both ports.
type LazyCompleter ¶
type LazyCompleter struct {
// contains filtered or unexported fields
}
LazyCompleter is a Completer that defers building the real one, a chat model of a few gigabytes, to its first use. It behaves as LazyEmbedder does: one load under a context only Close cancels, and a kept failure.
func NewLazyCompleter ¶
func NewLazyCompleter(load func(ctx context.Context) (Completer, error)) *LazyCompleter
NewLazyCompleter returns a LazyCompleter that calls load on first use and keeps what it returns until Close. load gets a context that Close cancels and should stop for it; a load that panics or returns a nil Completer fails like one that returns an error.
func (*LazyCompleter) Close ¶
func (l *LazyCompleter) Close() error
Close releases the model and fails every waiting and later call. See LazyEmbedder.Close.
func (*LazyCompleter) Complete ¶
Complete implements Completer. It loads the model on the first call (unless Load already did), waits for a load in progress while ctx lasts, and passes the prompt to the loaded model.
func (*LazyCompleter) Load ¶
func (l *LazyCompleter) Load(ctx context.Context) error
Load builds the model now instead of on the first Complete call. ctx bounds the wait, not the load. See LazyEmbedder.Load.
func (*LazyCompleter) State ¶
func (l *LazyCompleter) State() (LazyState, error)
State reports where the model stands and, when its calls can no longer succeed, the error they return. See LazyEmbedder.State.
type LazyEmbedder ¶
type LazyEmbedder struct {
// contains filtered or unexported fields
}
LazyEmbedder is an Embedder that defers building the real one (with the yzma embedder: its model and library downloads too) to the first Embed call rather than server startup, unless the caller asks for it earlier through Load. Model and Dimensions answer from the configuration without loading, so an Index or a vector store, which needs both to set up its collection, can be built at startup before the model is ever touched.
The load runs once, under a context of the LazyEmbedder's own that only Close cancels: a caller whose context ends stops waiting, and the load goes on for the others. A load failure is kept: it is returned unchanged by every later call instead of retried, so a broken or unreachable model degrades gracefully instead of re-attempting a download on every request. To load again once the cause is gone, build a new LazyEmbedder with NewLazyEmbedder, hand it to whatever held this one, and Close this one; LazyImageEmbedder and LazyCompleter recover the same way. State exposes all of it to a health endpoint. A LazyEmbedder is safe for concurrent use and must not be copied.
func NewLazyEmbedder ¶
func NewLazyEmbedder(model string, dims int, load func(ctx context.Context) (Embedder, error)) *LazyEmbedder
NewLazyEmbedder returns a LazyEmbedder that calls load on first use and keeps what it returns until Close. model is what Model reports, exactly the string the loaded embedder's Model will return ("" leaves the model unknown and unchecked), and dims what Dimensions reports. A provider's spec gives both before a model loads: yzma's ModelSpec.ModelID and Dims, for one. A loaded embedder with another dimensionality, or one that names another model, fails the load and is closed.
load gets a context that Close cancels and should stop for it. A load that panics or returns a nil Embedder fails like one that returns an error.
Example ¶
This example defers a model's load to its first use. The identity and the dimensions come from the configuration, as a provider's spec gives them before anything loads (yzma's ModelSpec.ModelID and Dims), so a store can be set up first; the loaded model must then report exactly that identity.
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/go-bumbu/sense"
"github.com/go-bumbu/sense/sensetest"
)
func main() {
ctx := context.Background()
emb := sense.NewLazyEmbedder(sensetest.FakeEmbedderModel, 64, func(context.Context) (sense.Embedder, error) {
return sensetest.FakeEmbedder{}, nil // an app returns yzma.New(ctx, cfg)
})
state, _ := emb.State()
fmt.Println(emb.Model(), emb.Dimensions(), state)
vecs, err := emb.Embed(ctx, sense.RoleQuery, []string{"hello"})
if err != nil {
log.Fatal(err)
}
state, _ = emb.State()
fmt.Println(len(vecs[0]), state)
if err := emb.Close(); err != nil {
log.Fatal(err)
}
_, err = emb.Embed(ctx, sense.RoleQuery, []string{"hello"})
fmt.Println(errors.Is(err, sense.ErrClosed))
}
Output: sensetest/fake-embedder 64 not started 64 loaded true
func (*LazyEmbedder) Close ¶
func (l *LazyEmbedder) Close() error
Close releases the model: it cancels a load in progress and waits for it to return, and closes the loaded embedder when it is an io.Closer. Every call waiting for the load and every later one fails with an error wrapping ErrClosed. Calls already inside the loaded embedder are its Close's to deal with. Closing again does nothing.
func (*LazyEmbedder) Dimensions ¶
func (l *LazyEmbedder) Dimensions() int
Dimensions implements Embedder. It returns the configured dimensionality without triggering a load, so callers can size a vector store before the model is loaded.
func (*LazyEmbedder) Embed ¶
Embed implements Embedder. It loads the model on the first call (unless Load already did), waits for a load in progress while ctx lasts, and passes the call, role included, to the loaded embedder.
func (*LazyEmbedder) Load ¶
func (l *LazyEmbedder) Load(ctx context.Context) error
Load builds the embedder now instead of on the first Embed call, for a server that would rather pay for the downloads and the model load at startup than on the first request. It is the same load Embed performs: whichever of the two comes first starts it, the other waits for and reuses its result. ctx bounds the wait, not the load. Load returns nil once the model is loaded, and otherwise what Embed would fail with.
func (*LazyEmbedder) Model ¶
func (l *LazyEmbedder) Model() string
Model implements Identified. It returns the configured model name without triggering a load.
func (*LazyEmbedder) State ¶
func (l *LazyEmbedder) State() (LazyState, error)
State reports where the embedder stands and, when its calls can no longer succeed, the error they return: the load's in LazyFailed, one wrapping ErrClosed in LazyClosed.
type LazyImageEmbedder ¶
type LazyImageEmbedder struct {
// contains filtered or unexported fields
}
LazyImageEmbedder is an ImageEmbedder that defers building the real one to its first use. It behaves as LazyEmbedder does: one load under a context only Close cancels, a kept failure, and Model and Dimensions answered from the configuration without loading.
func NewLazyImageEmbedder ¶
func NewLazyImageEmbedder(model string, dims int, load func(ctx context.Context) (ImageEmbedder, error)) *LazyImageEmbedder
NewLazyImageEmbedder returns a LazyImageEmbedder that calls load on first use and keeps what it returns until Close. model, dims and load are NewLazyEmbedder's.
func (*LazyImageEmbedder) Close ¶
func (l *LazyImageEmbedder) Close() error
Close releases the model and fails every waiting and later call. See LazyEmbedder.Close.
func (*LazyImageEmbedder) Dimensions ¶
func (l *LazyImageEmbedder) Dimensions() int
Dimensions implements ImageEmbedder. It returns the configured dimensionality without triggering a load.
func (*LazyImageEmbedder) EmbedImages ¶
func (l *LazyImageEmbedder) EmbedImages(ctx context.Context, images []image.Image) ([][]float32, error)
EmbedImages implements ImageEmbedder. It loads the model on the first call (unless Load already did), waits for a load in progress while ctx lasts, and passes the call to the loaded embedder.
func (*LazyImageEmbedder) Load ¶
func (l *LazyImageEmbedder) Load(ctx context.Context) error
Load builds the embedder now instead of on the first EmbedImages call. ctx bounds the wait, not the load. See LazyEmbedder.Load.
func (*LazyImageEmbedder) Model ¶
func (l *LazyImageEmbedder) Model() string
Model implements Identified. It returns the configured model name without triggering a load.
func (*LazyImageEmbedder) State ¶
func (l *LazyImageEmbedder) State() (LazyState, error)
State reports where the embedder stands and, when its calls can no longer succeed, the error they return. See LazyEmbedder.State.
type LazyState ¶
type LazyState int
LazyState is where a lazy model stands: LazyEmbedder, LazyImageEmbedder and LazyCompleter report it through State.
const ( // LazyNotStarted means that nothing has asked for the model yet. LazyNotStarted LazyState = iota // LazyLoading means that the load is running. LazyLoading // LazyLoaded means that the model is loaded and calls reach it. LazyLoaded // LazyFailed means that the load failed. The failure is kept: every call // returns it and nothing loads again. To try again, build a new lazy // value with the same constructor and use it in place of this one. LazyFailed // LazyClosed means that Close was called. Every call fails. LazyClosed )
type LoadPanicError ¶
type LoadPanicError struct {
// Value is what the load function panicked with.
Value any
// Stack is the stack of the goroutine that panicked.
Stack []byte
}
LoadPanicError is the load error of a lazy model whose load function panicked: the panic is kept from taking the process down and fails the load instead.
func (*LoadPanicError) Error ¶
func (e *LoadPanicError) Error() string
Error implements error. The stack is left out; read it from Stack.
type Role ¶
type Role int
Role tells an Embedder what a text is for. Asymmetric models are trained with different prefixes for the text being searched with and the texts it is searched against; symmetric models ignore the role.
type Segment ¶
Segment is one stretch of a video embedded as a whole: where it starts and ends, from the start of the video, and its vector.
type VideoEmbedder ¶
type VideoEmbedder interface {
EmbedVideo(ctx context.Context, path string) ([]Segment, error)
Dimensions() int
}
VideoEmbedder embeds a video with a model that takes video, as one vector per segment of the file, in time order. The implementation decides the segment length (a model reads so many frames at a time) and the frame rate it samples at. The vectors are Dimensions() long and share the space of the images and texts the same model embeds, so that an image or a text query finds a segment. A video is a file path rather than a reader because the common containers need seeking. A file that cannot be read or holds no video is an error, not an empty result.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
fetch
Package fetch is what the providers share to get their native libraries and models onto disk: a download verified by size and SHA-256 before it appears under its final name, a file that is downloaded only when it is missing or not the pinned size, an unverified download that reports the digest a new pin needs, the extraction of the libraries out of a release tarball (extract.go), and the staged install of such a tarball into a directory (install.go).
|
Package fetch is what the providers share to get their native libraries and models onto disk: a download verified by size and SHA-256 before it appears under its final name, a file that is downloaded only when it is missing or not the pinned size, an unverified download that reports the digest a new pin needs, the extraction of the libraries out of a release tarball (extract.go), and the staged install of such a tarball into a directory (install.go). |
|
hw
Package hw reports which accelerators a machine appears to have, so a provider can pick the matching runtime build and say why.
|
Package hw reports which accelerators a machine appears to have, so a provider can pick the matching runtime build and say why. |
|
imageutil
Package imageutil is the picture preparation the providers share, so that every model sees the same pixels for the same picture: scaling with a resampling kernel, and transparency composed on white.
|
Package imageutil is the picture preparation the providers share, so that every model sees the same pixels for the same picture: scaling with a resampling kernel, and transparency composed on white. |
|
tablename
Package tablename derives the physical table names of the SQL vector stores (vector/sqlitevec and vector/pgvec, through vector/internal/sqlstore), which keep one table set per index (e.g.
|
Package tablename derives the physical table names of the SQL vector stores (vector/sqlitevec and vector/pgvec, through vector/internal/sqlstore), which keep one table set per index (e.g. |
|
Package media holds the ports for decoding video.
|
Package media holds the ports for decoding video. |
|
ffmpeg
Package ffmpeg is a media.Sampler over the ffmpeg and ffprobe binaries: it decodes a video once and keeps the frames that stand for it, the first frame, every scene cut and one frame per interval in between, scaled down to a size an image embedder is happy with.
|
Package ffmpeg is a media.Sampler over the ffmpeg and ffprobe binaries: it decodes a video once and keeps the frames that stand for it, the first frame, every scene cut and one frame per interval in between, scaled down to a size an image embedder is happy with. |
|
provider
|
|
|
onnx
Package onnx runs image embedding models locally through ONNX Runtime, as a sense.ImageEmbedder.
|
Package onnx runs image embedding models locally through ONNX Runtime, as a sense.ImageEmbedder. |
|
phash
Package phash hashes pictures perceptually, as a sense.ImageEmbedder without a model: a picture becomes 64 (or 256) bits that survive a re-encode, a resize or a small edit, and the bits become a unit-length vector of +1/sqrt(bits) and -1/sqrt(bits) entries.
|
Package phash hashes pictures perceptually, as a sense.ImageEmbedder without a model: a picture becomes 64 (or 256) bits that survive a re-encode, a resize or a small edit, and the bits become a unit-length vector of +1/sqrt(bits) and -1/sqrt(bits) entries. |
|
yzma
Package yzma runs GGUF models locally through llama.cpp: a sentence-embedding model as a sense.Embedder, an instruction-tuned chat model as a sense.Completer, which a tagging.Generator has write tags, and a vision embedding model as a Vision, which is a sense.Embedder, a sense.ImageEmbedder and a sense.VideoEmbedder over one vector space.
|
Package yzma runs GGUF models locally through llama.cpp: a sentence-embedding model as a sense.Embedder, an instruction-tuned chat model as a sense.Completer, which a tagging.Generator has write tags, and a vision embedding model as a Vision, which is a sense.Embedder, a sense.ImageEmbedder and a sense.VideoEmbedder over one vector space. |
|
Package search is a reusable semantic-search capability: it turns documents into embedding vectors (via a sense.Embedder), stores them in a vector.Store, and answers free-text queries with the closest documents.
|
Package search is a reusable semantic-search capability: it turns documents into embedding vectors (via a sense.Embedder), stores them in a vector.Store, and answers free-text queries with the closest documents. |
|
Package sensetest provides fakes of the sense ports for tests: of this module's packages and of the code that uses them.
|
Package sensetest provides fakes of the sense ports for tests: of this module's packages and of the code that uses them. |
|
Package tagging suggests tags for texts in two ways: a Tagger chooses among the tags an application already has, and a Generator writes new ones.
|
Package tagging suggests tags for texts in two ways: a Tagger chooses among the tags an application already has, and a Generator writes new ones. |
|
cachetest
Package cachetest is the conformance suite for tagging.EmbeddingCache.
|
Package cachetest is the conformance suite for tagging.EmbeddingCache. |
|
internal/sqlcache
Package sqlcache implements tagging.EmbeddingCache on database/sql for the databases a Dialect describes.
|
Package sqlcache implements tagging.EmbeddingCache on database/sql for the databases a Dialect describes. |
|
pgcache
Package pgcache is a tagging.EmbeddingCache backed by PostgreSQL.
|
Package pgcache is a tagging.EmbeddingCache backed by PostgreSQL. |
|
sqlitecache
Package sqlitecache is a tagging.EmbeddingCache backed by SQLite.
|
Package sqlitecache is a tagging.EmbeddingCache backed by SQLite. |
|
Package vector stores embedding vectors and finds the closest ones.
|
Package vector stores embedding vectors and finds the closest ones. |
|
internal/sqlstore
Package sqlstore implements vector.Store on database/sql for the databases a Dialect describes.
|
Package sqlstore implements vector.Store on database/sql for the databases a Dialect describes. |
|
pgvec
Package pgvec is a vector.Store backed by Postgres with the pgvector extension.
|
Package pgvec is a vector.Store backed by Postgres with the pgvector extension. |
|
sqlitevec
Package sqlitevec is a vector.Store backed by SQLite with the sqlite-vec extension.
|
Package sqlitevec is a vector.Store backed by SQLite with the sqlite-vec extension. |
|
vectortest
Package vectortest is the conformance suite for vector.Store.
|
Package vectortest is the conformance suite for vector.Store. |
|
zarf
|
|
|
eval
Package eval measures how well a sense.Embedder serves the two tasks this module uses embeddings for, over a labelled dataset:
|
Package eval measures how well a sense.Embedder serves the two tasks this module uses embeddings for, over a labelled dataset: |
|
examples
command
Command examples is a single-user web service to exercise sense's features by hand: run it on a directory of media and click around.
|
Command examples is a single-user web service to exercise sense's features by hand: run it on a directory of media and click around. |
|
examples/assets
Package assets holds what the example service's pages share: the base stylesheet that makes them read as one application, and a script with the navigation between them and the small DOM helpers the newer pages are written with.
|
Package assets holds what the example service's pages share: the base stylesheet that makes them read as one application, and a script with the navigation between them and the small DOM helpers the newer pages are written with. |
|
examples/autotag
Package autotag is the automatic-tagging page of the example service: a notebook of notes and tags.
|
Package autotag is the automatic-tagging page of the example service: a notebook of notes and tags. |
|
examples/duplicates
Package duplicates is the example service's duplicate finder: it hashes the pictures of a directory with provider/phash, which runs no model, and shows both faces of that package.
|
Package duplicates is the example service's duplicate finder: it hashes the pictures of a directory with provider/phash, which runs no model, and shows both faces of that package. |
|
examples/mediasearch
Package mediasearch is the example service's media similarity search: it scans a directory of images and videos into a search.MediaIndex, keeps a catalog of what it found, answers "what looks like this" for an item or an uploaded file, and makes the thumbnails and storyboards the page shows.
|
Package mediasearch is the example service's media similarity search: it scans a directory of images and videos into a search.MediaIndex, keeps a catalog of what it found, answers "what looks like this" for an item or an uploaded file, and makes the thumbnails and storyboards the page shows. |
|
examples/status
Package status is the example service's home page: what is loaded and how.
|
Package status is the example service's home page: what is loaded and how. |
|
examples/textsearch
Package textsearch is the example service's semantic text search: it scans a directory of Markdown and text files into a search.Index with one IndexBatch call, reconciles the index with the directory through Docs and Delete, keeps a catalog of what it found, and answers a free-text query or "more like this document" with the chunk that matched and its score.
|
Package textsearch is the example service's semantic text search: it scans a directory of Markdown and text files into a search.Index with one IndexBatch call, reconciles the index with the directory through Docs and Delete, keeps a catalog of what it found, and answers a free-text query or "more like this document" with the chunk that matched and its score. |