mirror of
https://github.com/mudler/LocalAI.git
synced 2026-09-12 22:33:54 -04:00
* feat(router): make KNN a first-class classifier with a persisted, curated corpus
Add `classifier: knn` — similarity-weighted voting over labelled
example prompts. Unlike score/colbert it needs no classifier model:
label knowledge lives in a corpus seeded and curated through the
admin API, so routing decisions are deterministic, auditable, and
grounded in graded experience rather than a model's opinion.
Epistemic gate: corpus entries below knn.similarity_threshold cannot
vote; when none clears it the classifier activates no labels and the
router uses the fallback — a prompt unlike all labelled experience is
treated as undecidable, not guessed. Decisions record
nearest_similarity (also on fallback rows) so admins can see how far
the nearest labelled experience was; the Routing tab explains
out-of-corpus fallbacks and shows per-label corpus counts.
Persistence: one JSONL file per router under
<data path>/router-corpus (text, labels, vector, embedder
fingerprint). The file is the source of truth; the local-store index
is rebuilt from it at classifier build time and stays a pure
in-memory index. Entries recorded under a different embedding model
re-embed on load. Also corrects the docs' false claim that
local-store collections persist — the embedding cache never survived
restarts (and still doesn't); the corpus does.
Corpus input is API-only by design (entries may contain example user
content): POST /api/router/{name}/corpus seeds (labels validated
against declared policies, embedded server-side, indexed
immediately), GET .../corpus/stats inspects — label counts only,
entry texts are never returned by any surface — DELETE .../corpus
wipes. Admin-gated like the sibling router endpoints, and exposed as
MCP tools (seed_router_corpus / get_router_corpus_stats /
clear_router_corpus) in both the httpapi and inproc clients with
coverage-test route mappings.
Plumbing: VectorStore gains SearchK (top-K was hardcoded to 1);
local-store gets InsertBatch/Delete as optional fast paths;
RouterConfig gains a knn block (embedding_model, k,
similarity_threshold, vote_threshold, store_name) with meta-registry
fields; the classifier dropdown now offers knn and the
previously-missing colbert; embedding_cache is ignored (with a
warning) for knn — it IS an embedding-KNN lookup; the stale
/api/instructions intelligent-routing entry is rewritten (it
described a classifier that no longer exists); swagger regenerated.
Tests: KNN vote/gate specs with hand-computed vote shares, corpus
manager suite (restart reload without re-embedding, fingerprint
re-embed, dedupe, hostile store names), middleware specs (corpus
routing, gate fallback, config validation, cache-wrap refusal),
corpus endpoint specs pinning the texts-never-returned contract, MCP
catalog + route-mapping gates, and a Playwright spec for corpus
stats and the out-of-corpus decision detail.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(router): name consulted corpus neighbours in knn decisions
Every knn decision (decision log rows and the /api/router/decide
response) now carries neighbors: the K retrieved corpus entries by
descending similarity - including ones below the epistemic gate, which
is what makes fallback decisions diagnosable - each as {id, similarity,
labels}. The id is the entry's content hash (first 8 bytes of the
SHA-256 of its text, hex): stable across reseeds and re-embeds, and
text-free, so an external platform that seeded the corpus can recompute
text->id on its own copy and bucket decisions by corpus region (per-
region reliability accounting) without corpus text ever leaving the
server. A corrupt index payload surfaces as an id-less neighbour at a
real similarity instead of disappearing.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* refactor(router): deduplicate knn plumbing and cut corpus hot-path waste
Post-review cleanup of the knn-first-class-router branch; no behaviour
changes on the API surface.
Reuse/altitude:
- RouterKNNConfig.ResolvedStoreName is now the single source of the
router-corpus-<name> default (was hand-derived in four files).
- corpus.ResolveKNNRouter + corpus.Seed carry the shared model
resolution and seed validation; the REST endpoints and the assistant
MCP client are thin transport adapters over them, with sentinel
errors mapped to HTTP statuses at the echo boundary.
- middleware.NewClassifierDeps assembles the classifier dependency set
once for all five entry points (OpenAI, Anthropic, realtime, decide,
corpus) instead of five hand-copied literals.
- router.AllClassifiers feeds both the status endpoint and the
unknown-classifier error, ending the classifier-list drift.
- Per-classifier requirements moved out of validateRouterPolicies into
their buildClassifier arms; the knn arm owns its embedding_cache
opt-out instead of a name-check in the shared wrap tail.
- adminOnly replaces four inline copies of the admin gate in the
middleware routes.
- localVectorStore.Search delegates to SearchK (identical traces).
Efficiency:
- Manager.Add embeds outside the manager mutex and appends to the
JSONL file (O(new) instead of O(corpus) rewrite); a torn tail from a
crash mid-append is tolerated on read and repaired on next write.
- Stats memoises per store keyed on the file's stat fingerprint and no
longer takes the manager mutex, so the 5s status poll stops parsing
vector-laden JSONL and stops blocking behind seeds.
- KNN Classify decodes each neighbour payload once (was twice) and
builds refs and votes in a single pass with one fallback return.
- Corpus file writes fsync before rename/close.
- The corpus manager is built eagerly in newApplication (sync.Once
dropped); test helper dead branch removed.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(router): bind knn corpus vectors to an embedder fingerprint and fail closed on mismatch
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* chore(mcp): align corpus tool prompts and the mutating-tool safety list
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(proto,backend): report embedding shape from the llama-cpp backend
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(embeddings): Go-side pooling — mean/last/decayed_mean with half-life
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* feat(embeddings): accept chat messages[] and per-request pooling on /v1/embeddings
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* chore(middleware): name the failing fields when post-merge validation 400s
An intermittent post-merge validation failure surfaced as an opaque 400
during integration (pooling scheme mismatch that no client had sent).
Log the model, the request's pooling override, and the merged config's
pooling fields at the failure point so the next occurrence identifies
whether the request or the stored config carried the bad value.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* fix(embeddings): scheme override must not inherit the config's half-life
A model config defaulting to decayed_mean pooling carries
pooling_half_life_tokens; a request overriding the scheme to mean/last
without its own half-life inherited that value, and post-merge
validation rejected the pair the server itself had assembled. Zero the
inherited half-life when the overridden scheme is not decayed_mean; a
request that explicitly pairs a half-life with a non-decayed scheme
still 400s.
Assisted-by: Claude:claude-fable-5 [Claude Code]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* fix embedding pooling validation and router bounds
Declare backend embedding layouts and reject incompatible pooling modes. Reset local-store dimensions after a full clear, validate KNN thresholds, and add real backend and store integration coverage.
Assisted-by: Codex:gpt-5
Signed-off-by: Richard Palethorpe <io@richiejp.com>
* ci: run local-store integration tests
Build and install the local-store backend in the Linux test job, then run the existing store integration suite so new specs are discovered automatically.
Assisted-by: Codex:gpt-5
Signed-off-by: Richard Palethorpe <io@richiejp.com>
---------
Signed-off-by: Richard Palethorpe <io@richiejp.com>
159 lines
6.2 KiB
Go
159 lines
6.2 KiB
Go
package schema
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// LogprobsValue represents the logprobs parameter which is a boolean.
|
|
// According to OpenAI API: true means return log probabilities, false/null means don't return them.
|
|
// The actual number of top logprobs per token is controlled by top_logprobs (0-5).
|
|
type LogprobsValue struct {
|
|
Enabled bool // true if logprobs should be returned
|
|
}
|
|
|
|
// UnmarshalJSON implements json.Unmarshaler to handle boolean
|
|
func (l *LogprobsValue) UnmarshalJSON(data []byte) error {
|
|
// Try to unmarshal as boolean
|
|
var b bool
|
|
if err := json.Unmarshal(data, &b); err == nil {
|
|
l.Enabled = b
|
|
return nil
|
|
}
|
|
|
|
// If it's null, set to false
|
|
var n *bool
|
|
if err := json.Unmarshal(data, &n); err == nil {
|
|
l.Enabled = false
|
|
return nil
|
|
}
|
|
|
|
// Try as integer for backward compatibility (treat > 0 as true)
|
|
var i int
|
|
if err := json.Unmarshal(data, &i); err == nil {
|
|
l.Enabled = i > 0
|
|
return nil
|
|
}
|
|
|
|
return json.Unmarshal(data, &l.Enabled)
|
|
}
|
|
|
|
// MarshalJSON implements json.Marshaler
|
|
func (l LogprobsValue) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(l.Enabled)
|
|
}
|
|
|
|
// UnmarshalYAML implements yaml.Unmarshaler to handle boolean
|
|
func (l *LogprobsValue) UnmarshalYAML(value *yaml.Node) error {
|
|
switch value.Kind {
|
|
case yaml.ScalarNode:
|
|
switch value.Tag {
|
|
case "!!bool":
|
|
var b bool
|
|
if err := value.Decode(&b); err != nil {
|
|
return err
|
|
}
|
|
l.Enabled = b
|
|
return nil
|
|
case "!!int":
|
|
// For backward compatibility, treat integer > 0 as true
|
|
var i int
|
|
if err := value.Decode(&i); err != nil {
|
|
return err
|
|
}
|
|
l.Enabled = i > 0
|
|
return nil
|
|
case "!!null":
|
|
l.Enabled = false
|
|
return nil
|
|
}
|
|
}
|
|
return value.Decode(&l.Enabled)
|
|
}
|
|
|
|
// IsEnabled returns true if logprobs should be returned
|
|
func (l *LogprobsValue) IsEnabled() bool {
|
|
return l.Enabled
|
|
}
|
|
|
|
// @Description PredictionOptions contains prediction parameters for model inference
|
|
type PredictionOptions struct {
|
|
|
|
// Also part of the OpenAI official spec
|
|
BasicModelRequest `yaml:",inline"`
|
|
|
|
// Also part of the OpenAI official spec
|
|
Language string `json:"language,omitempty" yaml:"language,omitempty"`
|
|
|
|
// Only for audio transcription
|
|
Translate bool `json:"translate,omitempty" yaml:"translate,omitempty"`
|
|
|
|
// Also part of the OpenAI official spec. use it for returning multiple results
|
|
N int `json:"n,omitempty" yaml:"n,omitempty"`
|
|
|
|
// Common options between all the API calls, part of the OpenAI spec
|
|
TopP *float64 `json:"top_p,omitempty" yaml:"top_p,omitempty"`
|
|
TopK *int `json:"top_k,omitempty" yaml:"top_k,omitempty"`
|
|
MinP *float64 `json:"min_p,omitempty" yaml:"min_p,omitempty"`
|
|
Temperature *float64 `json:"temperature,omitempty" yaml:"temperature,omitempty"`
|
|
Maxtokens *int `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
|
|
// MaxCompletionTokens is the modern alias for max_tokens
|
|
// (OpenAI deprecated max_tokens; gpt-5 / o-series reject it).
|
|
// Accepted on the wire so up-to-date clients can use the new
|
|
// name; the request middleware collapses it into Maxtokens so
|
|
// internal code reads exactly one field.
|
|
MaxCompletionTokens *int `json:"max_completion_tokens,omitempty" yaml:"-"`
|
|
Echo bool `json:"echo,omitempty" yaml:"echo,omitempty"`
|
|
|
|
// Custom parameters - not present in the OpenAI API
|
|
Batch int `json:"batch,omitempty" yaml:"batch,omitempty"`
|
|
IgnoreEOS bool `json:"ignore_eos,omitempty" yaml:"ignore_eos,omitempty"`
|
|
RepeatPenalty float64 `json:"repeat_penalty,omitempty" yaml:"repeat_penalty,omitempty"`
|
|
|
|
RepeatLastN int `json:"repeat_last_n,omitempty" yaml:"repeat_last_n,omitempty"`
|
|
|
|
Keep int `json:"n_keep,omitempty" yaml:"n_keep,omitempty"`
|
|
|
|
FrequencyPenalty float64 `json:"frequency_penalty,omitempty" yaml:"frequency_penalty,omitempty"`
|
|
PresencePenalty float64 `json:"presence_penalty,omitempty" yaml:"presence_penalty,omitempty"`
|
|
TFZ *float64 `json:"tfz,omitempty" yaml:"tfz,omitempty"`
|
|
|
|
TypicalP *float64 `json:"typical_p,omitempty" yaml:"typical_p,omitempty"`
|
|
Seed *int `json:"seed,omitempty" yaml:"seed,omitempty"`
|
|
|
|
// OpenAI API logprobs parameters
|
|
// logprobs: boolean - if true, returns log probabilities of each output token
|
|
// top_logprobs: integer 0-20 - number of most likely tokens to return at each token position
|
|
Logprobs LogprobsValue `json:"logprobs,omitempty" yaml:"logprobs,omitempty"` // Whether to return log probabilities (true/false)
|
|
TopLogprobs *int `json:"top_logprobs,omitempty" yaml:"top_logprobs,omitempty"` // Number of top logprobs per token (0-20)
|
|
LogitBias map[string]float64 `json:"logit_bias,omitempty" yaml:"logit_bias,omitempty"` // Map of token IDs to bias values (-100 to 100)
|
|
|
|
NegativePrompt string `json:"negative_prompt,omitempty" yaml:"negative_prompt,omitempty"`
|
|
RopeFreqBase float32 `json:"rope_freq_base,omitempty" yaml:"rope_freq_base,omitempty"`
|
|
RopeFreqScale float32 `json:"rope_freq_scale,omitempty" yaml:"rope_freq_scale,omitempty"`
|
|
NegativePromptScale float32 `json:"negative_prompt_scale,omitempty" yaml:"negative_prompt_scale,omitempty"`
|
|
|
|
// Diffusers
|
|
ClipSkip int `json:"clip_skip,omitempty" yaml:"clip_skip,omitempty"`
|
|
|
|
// RWKV (?)
|
|
Tokenizer string `json:"tokenizer,omitempty" yaml:"tokenizer,omitempty"`
|
|
|
|
// Embedding encoding format: "float" (default) or "base64" (OpenAI Node.js SDK default)
|
|
EncodingFormat string `json:"encoding_format,omitempty" yaml:"encoding_format,omitempty"`
|
|
|
|
// Pooling is a LocalAI extension for /v1/embeddings: how the backend's
|
|
// per-token vectors are reduced to a single embedding. "" or "backend"
|
|
// leaves pooling to the inference backend (the pre-existing behavior);
|
|
// "mean", "last" and "decayed_mean" pool Go-side from raw per-token
|
|
// vectors (the backend must run with the "pooling:none" option, which
|
|
// model configs get automatically when this is set).
|
|
Pooling string `json:"pooling,omitempty" yaml:"pooling,omitempty"`
|
|
// PoolingHalfLifeTokens is a LocalAI extension for /v1/embeddings: the
|
|
// half-life (in tokens) of the "decayed_mean" pooling scheme — a token's
|
|
// weight halves every this-many positions counting back from the end of
|
|
// the conversation. Defaults to 256 when unset.
|
|
PoolingHalfLifeTokens int `json:"pooling_half_life_tokens,omitempty" yaml:"pooling_half_life_tokens,omitempty"`
|
|
}
|