Documentation
¶
Overview ¶
Package vex provides type-safe embedding vector generation for Go.
Index ¶
- Variables
- func NewTerminal(provider Provider) pipz.Chainable[*EmbedRequest]
- type ChunkStrategy
- type Chunker
- type EmbedRequest
- type EmbeddingResponse
- type Option
- func WithBackoff(maxAttempts int, baseDelay time.Duration) Option
- func WithCircuitBreaker(failures int, recovery time.Duration) Option
- func WithErrorHandler(handler pipz.Chainable[*pipz.Error[*EmbedRequest]]) Option
- func WithFallback(fallback ServiceProvider) Option
- func WithRateLimit(rps float64, burst int) Option
- func WithRetry(maxAttempts int) Option
- func WithTimeout(duration time.Duration) Option
- type PoolingMode
- type Provider
- type QueryProviderFactory
- type Service
- func (s *Service) Batch(ctx context.Context, texts []string) ([]Vector, error)
- func (s *Service) BatchQuery(ctx context.Context, texts []string) ([]Vector, error)
- func (s *Service) Dimensions() int
- func (s *Service) Embed(ctx context.Context, text string) (Vector, error)
- func (s *Service) EmbedQuery(ctx context.Context, text string) (Vector, error)
- func (s *Service) GetPipeline() pipz.Chainable[*EmbedRequest]
- func (s *Service) Provider() Provider
- func (s *Service) WithChunker(c *Chunker) *Service
- func (s *Service) WithNormalize(normalize bool) *Service
- func (s *Service) WithPooling(mode PoolingMode) *Service
- type ServiceConfig
- type ServiceProvider
- type SimilarityMetric
- type Usage
- type Vector
Constants ¶
This section is empty.
Variables ¶
var ( EmbedStarted = capitan.NewSignal("vex.embed.started", "Embedding request initiated") EmbedCompleted = capitan.NewSignal("vex.embed.completed", "Embedding request succeeded") EmbedFailed = capitan.NewSignal("vex.embed.failed", "Embedding request failed") ProviderCallStarted = capitan.NewSignal("vex.provider.call.started", "Provider HTTP call initiated") ProviderCallCompleted = capitan.NewSignal("vex.provider.call.completed", "Provider HTTP call succeeded") ProviderCallFailed = capitan.NewSignal("vex.provider.call.failed", "Provider HTTP call failed") )
Signals for hook events.
var ( RequestIDKey = capitan.NewStringKey("vex.request.id") ProviderKey = capitan.NewStringKey("vex.provider") ModelKey = capitan.NewStringKey("vex.model") InputCountKey = capitan.NewIntKey("vex.input.count") DimensionsKey = capitan.NewIntKey("vex.dimensions") DurationMsKey = capitan.NewIntKey("vex.duration.ms") PromptTokensKey = capitan.NewIntKey("vex.tokens.prompt") TotalTokensKey = capitan.NewIntKey("vex.tokens.total") ErrorKey = capitan.NewStringKey("vex.error") )
Keys for hook event fields.
Functions ¶
func NewTerminal ¶
func NewTerminal(provider Provider) pipz.Chainable[*EmbedRequest]
NewTerminal creates a terminal processor that calls the embedding provider.
Types ¶
type ChunkStrategy ¶
type ChunkStrategy int
ChunkStrategy defines how long texts are split before embedding.
const ( // ChunkNone performs no chunking. ChunkNone ChunkStrategy = iota // ChunkSentence splits on sentence boundaries. ChunkSentence // ChunkParagraph splits on paragraph boundaries. ChunkParagraph // ChunkFixed splits into fixed-size chunks. ChunkFixed )
type Chunker ¶
type Chunker struct {
Strategy ChunkStrategy
MaxSize int // Maximum chunk size in characters (for ChunkFixed)
Overlap int // Overlap between chunks (for ChunkFixed)
TrimSpace bool // Trim whitespace from chunks
}
Chunker splits text into smaller pieces for embedding.
func DefaultChunker ¶
func DefaultChunker() *Chunker
DefaultChunker returns a chunker with sensible defaults.
type EmbedRequest ¶
type EmbedRequest struct {
Error error
Response *EmbeddingResponse
RequestID string
Provider string
Texts []string
}
EmbedRequest represents a request flowing through the pipeline.
type EmbeddingResponse ¶
EmbeddingResponse contains the result of an embedding request.
type Option ¶
type Option func(pipz.Chainable[*EmbedRequest]) pipz.Chainable[*EmbedRequest]
Option modifies a pipeline for reliability features.
func WithBackoff ¶
WithBackoff adds retry logic with exponential backoff to the pipeline. Failed requests are retried with increasing delays between attempts. The delay starts at baseDelay and doubles after each failure.
func WithCircuitBreaker ¶
WithCircuitBreaker adds circuit breaker protection to the pipeline. After 'failures' consecutive failures, the circuit opens for 'recovery' duration.
func WithErrorHandler ¶
WithErrorHandler adds error handling to the pipeline. The error handler receives error context and can process/log/alert as needed.
func WithFallback ¶
func WithFallback(fallback ServiceProvider) Option
WithFallback adds a fallback service for resilience. If the primary fails, the fallback will be tried.
func WithRateLimit ¶
WithRateLimit adds rate limiting to the pipeline. rps = requests per second, burst = burst capacity.
func WithRetry ¶
WithRetry adds retry logic to the pipeline. Failed requests are retried up to maxAttempts times.
func WithTimeout ¶
WithTimeout adds timeout protection to the pipeline. Operations exceeding this duration will be canceled.
type PoolingMode ¶
type PoolingMode int
PoolingMode defines how multiple chunk vectors are combined.
const ( // PoolMean averages all vectors. PoolMean PoolingMode = iota // PoolFirst uses only the first vector. PoolFirst // PoolMax takes element-wise maximum. PoolMax )
type Provider ¶
type Provider interface {
// Embed generates embedding vectors for the given texts.
Embed(ctx context.Context, texts []string) (*EmbeddingResponse, error)
// Name returns the provider identifier.
Name() string
// Dimensions returns the output vector dimensionality.
Dimensions() int
}
Provider defines the interface for embedding backends.
type QueryProviderFactory ¶
type QueryProviderFactory interface {
Provider
// ForQuery returns a provider configured for query embedding mode.
ForQuery() Provider
}
QueryProviderFactory is optionally implemented by providers that distinguish query vs document embeddings. Providers implementing this interface can generate query-optimized embeddings for improved retrieval quality.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service wraps an embedding provider with pipeline-based reliability.
func NewService ¶
NewService creates a new embedding Service with the given provider and options.
func (*Service) BatchQuery ¶
BatchQuery generates query-optimized embeddings for multiple texts. For providers that distinguish query vs document embeddings, this uses query-optimized mode. Otherwise behaves identically to Batch.
func (*Service) Dimensions ¶
Dimensions returns the output vector dimensionality from the provider.
func (*Service) Embed ¶
Embed generates an embedding for a single text. Uses document mode for providers that distinguish query vs document embeddings.
func (*Service) EmbedQuery ¶
EmbedQuery generates an embedding optimized for search queries. For providers that distinguish query vs document embeddings (Voyage, Cohere, Gemini), this uses query-optimized mode. For providers without this distinction (OpenAI), this behaves identically to Embed.
func (*Service) GetPipeline ¶
func (s *Service) GetPipeline() pipz.Chainable[*EmbedRequest]
GetPipeline returns the internal pipeline for composition.
func (*Service) WithChunker ¶
WithChunker sets the chunking strategy.
func (*Service) WithNormalize ¶
WithNormalize sets whether to L2-normalize output vectors.
func (*Service) WithPooling ¶
func (s *Service) WithPooling(mode PoolingMode) *Service
WithPooling sets the pooling mode for chunked embeddings.
type ServiceConfig ¶
type ServiceConfig struct {
Chunker *Chunker
PoolingMode PoolingMode
Normalize bool
}
ServiceConfig configures a Service.
type ServiceProvider ¶
type ServiceProvider interface {
GetPipeline() pipz.Chainable[*EmbedRequest]
}
ServiceProvider is implemented by types that can provide a pipeline for composition.
type SimilarityMetric ¶
type SimilarityMetric int
SimilarityMetric defines how vectors are compared.
const ( // Cosine measures the cosine of the angle between vectors. Cosine SimilarityMetric = iota // DotProduct computes the dot product of vectors. DotProduct // Euclidean computes the Euclidean distance between vectors. Euclidean )
type Vector ¶
type Vector []float32
Vector represents an embedding vector. Uses float32 for compatibility with vector databases (pgvector, Pinecone, Qdrant, etc.).
func Pool ¶
func Pool(vectors []Vector, mode PoolingMode) Vector
Pool combines multiple vectors using the specified pooling mode.
func (Vector) CosineSimilarity ¶
CosineSimilarity computes cosine similarity with another vector. Returns value in range [-1, 1], where 1 means identical direction.
func (Vector) EuclideanDistance ¶
EuclideanDistance computes the Euclidean distance to another vector.
func (Vector) Similarity ¶
func (v Vector) Similarity(other Vector, metric SimilarityMetric) float64
Similarity computes similarity using the specified metric.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cohere provides an embedding provider for the Cohere API.
|
Package cohere provides an embedding provider for the Cohere API. |
|
Package gemini provides an embedding provider for the Google Gemini API.
|
Package gemini provides an embedding provider for the Google Gemini API. |
|
Package openai provides an embedding provider for the OpenAI API.
|
Package openai provides an embedding provider for the OpenAI API. |
|
Package testing provides test utilities for vex.
|
Package testing provides test utilities for vex. |
|
Package voyage provides an embedding provider for the Voyage AI API.
|
Package voyage provides an embedding provider for the Voyage AI API. |