semantic_cache

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: AGPL-3.0 Imports: 14 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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyRuntimeConfig

func ApplyRuntimeConfig(cfg RuntimeConfig)

ApplyRuntimeConfig creates or reconfigures the global semantic cache from runtime settings. When the cache already exists and the size/threshold/TTL parameters are unchanged, the existing cache is reused so stored entries are not discarded.

func BuildNamespace

func BuildNamespace(apiKeyID int, endpointFamily, requestedModel string) string

func Clear

func Clear()

Clear empties the cache.

func Enabled

func Enabled() bool

Enabled returns true if the semantic cache is initialized and active.

func ExtractNormalizedText

func ExtractNormalizedText(req *transmodel.InternalLLMRequest) (string, bool)

func GenerateEmbedding

func GenerateEmbedding(text string) []float64

GenerateEmbedding creates a 64-dimension embedding from the input text. Currently uses a SHA-256 hash for deterministic caching — identical requests produce identical embeddings, while similar (but not identical) requests will not match. A future upgrade can replace this with a real embedding model via the system's embedding relay pipeline.

func Init

func Init(maxEntries int, threshold float64, ttlSec int)

Init creates or reconfigures the global semantic cache.

func Lookup

func Lookup(namespace string, embedding []float64) (responseJSON []byte, found bool)

Lookup finds the best matching cache entry for the given embedding. Returns the response JSON and true if a match above threshold is found.

The cosine-similarity scan runs under a read lock so that concurrent lookups proceed in parallel rather than serializing on a single mutex. Expired entries are skipped inline; structural removal of expired entries is deferred to Store/Stats (which hold the write lock). Hit metadata is updated atomically, so recording a hit does not require the write lock.

func RecordBypass

func RecordBypass()

func RecordEvaluated

func RecordEvaluated()

func RecordHit

func RecordHit()

func RecordMiss

func RecordMiss()

func RecordStored

func RecordStored()

func Reset

func Reset()

Reset clears the cache and runtime configuration.

func ResetRuntimeStats

func ResetRuntimeStats()

func RuntimeEnabled

func RuntimeEnabled() bool

func Stats

func Stats() (hits, misses int64, size int)

Stats returns hit/miss counts and current cache size.

func Store

func Store(namespace, requestKey string, responseJSON []byte, embedding []float64)

Store adds a new entry to the cache. If the cache is full, the oldest entry is evicted.

Types

type CacheEntry

type CacheEntry struct {
	Namespace    string
	RequestKey   string
	ResponseJSON []byte
	Embedding    []float64
	CreatedAt    time.Time

	HitCount atomic.Int64
	// contains filtered or unexported fields
}

CacheEntry holds a cached request/response pair with its embedding.

Entries are stored behind pointers (see SemanticCache.entries) and the mutable hit metadata (lastAccessNs / HitCount) is accessed atomically so that Lookup can scan and record hits under a read lock without serializing concurrent lookups. The immutable fields (Namespace, ResponseJSON, Embedding, CreatedAt) are written once at Store time and never mutated in place afterwards, so they are safe to read after releasing the read lock.

type EmbeddingClient

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

func NewEmbeddingClient

func NewEmbeddingClient(cfg RuntimeConfig) *EmbeddingClient

func (*EmbeddingClient) CreateEmbedding

func (c *EmbeddingClient) CreateEmbedding(ctx context.Context, text string) ([]float64, error)

type RuntimeConfig

type RuntimeConfig struct {
	Enabled          bool
	MaxEntries       int
	Threshold        float64
	TTL              time.Duration
	EmbeddingBaseURL string
	EmbeddingAPIKey  string
	EmbeddingModel   string
	EmbeddingTimeout time.Duration
}

type RuntimeStats

type RuntimeStats struct {
	EvaluatedRequests int64
	CacheHitResponses int64
	CacheMissRequests int64
	BypassedRequests  int64
	StoredResponses   int64
}

func GetRuntimeStats

func GetRuntimeStats() RuntimeStats

type SemanticCache

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

SemanticCache is an in-memory vector store with cosine similarity lookup.

Jump to

Keyboard shortcuts

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