mirror of
https://github.com/mudler/LocalAI.git
synced 2026-07-31 10:28:43 -04:00
* feat(llama-cpp): route Score through the slot loop Score previously bypassed the slot loop with a direct llama_decode: a conflict guard aborted the whole process if scoring raced generation, the config validator had to reject score alongside chat/completion/embeddings, and every candidate re-decoded the full shared prompt. Add SERVER_TASK_TYPE_SCORE to the (patched) upstream server so score tasks are scheduled like any other slot work: generation and scoring serialize naturally, the shared prompt is decoded once per call, and the slot's prompt cache carries the conversation prefix across calls. Context checkpoints at the score boundary and at the cache-divergence point keep SWA/hybrid/recurrent models (e.g. LFM2.5) from re-prefilling the whole prompt per candidate: warm-turn scoring on a 6-option set drops from ~8s to ~0.5s on a desktop CPU. The conflict guard and the validation split are removed; declaring score with generation usecases on one config is now supported and shares the slot cache. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): classifier wire types and pipeline config Wire types and YAML config for realtime classifier mode: sessions carry a localai_classifier extension (options with canned replies/tool calls, softmax threshold, normalization, history trimming, fallback modes, and a deterministic wake-word address gate), mirrored by pipeline.classifier in the model YAML and surfaced in the config-meta registry. The localai.classifier.result server event reports the full score distribution per turn. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): classifier response flow Classifier-mode responses: instead of autoregressive generation, each user turn is prefill-scored against the option list (router.ScoreClassifier prompt/candidate shapes over the Score primitive) and the winning option's canned reply and tool call are emitted through the existing response machinery. Below-threshold turns take the configured fallback (none / canned reply / generate); empty transcripts and unaddressed turns (wake word not mentioned) skip scoring entirely. The scoring probe defaults to the latest user message only — small scorers echo canned replies from prior turns back as the top option otherwise. Built for hardware that can afford prompt processing but not decode: with slot-based Score the option list stays KV-cached across turns, so a turn costs roughly one forward pass over the new words. session_update_error events now carry the validation cause instead of a generic message. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(realtime): bound the VAD tick's scan window and buffer retention The VAD tick loop re-scanned the entire input buffer every 300ms and only trimmed it on zero-segment ticks or commits. Audio that keeps producing segments without a committing pause (steady noise a mic pipeline lets through, music, continuous speech) grew the buffer toward the 100MB cap with each tick rescanning all of it — O(n^2), measured at ~3.3ms of silero per buffered second: past ~90s retained, ticks run back to back and pin ~4 cores until the stream stops. Silero's recurrent state only carries a few hundred ms of context, so rescanning old audio buys nothing. Clip the slice handed to the VAD to the largest silence the commit test can need to measure (server_vad silence window or the semantic eagerness fallback) plus a warm-up margin, and rebase the returned segment times so every downstream consumer keeps whole-buffer coordinates. An open turn whose clipped window is all silence now commits (the silence outran the window) instead of being discarded as no-speech. Independently, retain at most 90s of raw buffer, rebasing the live-feed and EOU cursors on trim — this also bounds the previously unbounded VAD-error path. Turn boundaries are otherwise unchanged: no forced commits, no new coordinator states. pipeline.turn_detection.vad_window_sec can widen the scan window; values below the automatic floor are ignored. The tick body is extracted into vadTick so specs can drive turn detection synchronously (same shape as classifySoundWindow); the babble reproduction that pinned 4 cores now plateaus under 10% of one core. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(backend): let per-model threads override the global default ModelOptions overrode a set per-model threads value with the app-level --threads whenever the latter was non-zero — and WithThreads defaults it to the physical core count, so it always was. The YAML threads: knob has been dead config: a tiny VAD model could never opt down from the global pool size. SetDefaults already fills an unset per-model value from the app config, which is the intended precedence; resolve threads through a helper that honors it (explicit threads: 0 still means unset). Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * chore(gallery): single-thread the silero VAD Silero is a ~2MB recurrent model with no exploitable graph parallelism: measured per-call latency is identical at 1 and 10 ORT threads, while every extra pool thread just spin-waits between the realtime loop's frequent tiny inferences. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * docs(realtime): classifier mode, VAD scan window, threads precedence Document the realtime classifier mode (options, threshold guidance, wake-word address gate, empty-transcript handling), the VAD scan window and 90s buffer retention (pipeline.turn_detection.vad_window_sec), the per-model threads precedence, and the M3 classifier note in the realtime state-machine design doc. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * perf(llama-cpp): score all candidates in one batched decode One scoring call is now a single SERVER_TASK_TYPE_SCORE task: the slot decodes the shared prefix (prompt + longest common candidate token prefix) once, then forks one sequence per candidate off it (metadata-only for the unified KV cache, copy-on-write for recurrent state) and decodes every candidate's unique tail in one llama_decode. Previously each candidate was its own task that restored the boundary checkpoint and re-decoded its full tail sequentially, paying per-candidate task and decode overhead. The context reserves SERVER_SCORE_FORK_SEQS extra sequence ids (and recurrent-state cells) beyond the parallel slots via the new common_params::n_seq_score_forks. Forking requires the unified KV cache (already this backend's default) since per-sequence streams would shrink n_ctx_seq; an explicit kv_unified:false disables forking and Score calls that need it fail cleanly. Candidates beyond the fork/output budget decode in successive chunks. Wire contract and scores are unchanged: per-token logprobs are stitched from the shared region and the forked tails. Verified bitwise deterministic call-to-call and independent of candidate order (no cross-fork leakage via equal-length candidate swap); ranking matches the per-candidate implementation on the drone battery (winner softmax 0.99996 vs 0.99997), and >16-candidate chunking, prefix-of-another and empty candidates all pass. Measured on a desktop CPU: warm /api/score calls 0.52s -> 0.23s; warm realtime classifier turns 196-303ms. The 9-candidate drone turn decodes ~17 unique tail tokens in one batch instead of nine sequential ~220ms checkpoint-restore tasks. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(realtime): gate scoring capacity by model usecase Reserve llama.cpp scoring slots only for models that explicitly declare the score usecase, while allowing score to coexist with chat and completion. Reject incompatible unified-KV settings and classifier activation on models without scoring capacity. Propagate application defaults when resolving realtime and preload pipeline stages so unset thread counts are resolved consistently without overriding explicit model settings. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): honor APT mirrors in the prebuilt llama-cpp compile step The builder-prebuilt path installs gcc-14 with apt directly and ignored the APT_MIRROR/APT_PORTS_MIRROR build args the from-source path already honors, so an ubuntu mirror outage broke every arm64 backend build. Pass the args into the stage and run apt-mirror.sh (already in the build context via COPY . /LocalAI) before the apt step. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): classifier argument slots via constrained completion Hybrid classify-then-complete: a classifier option's canned tool call can declare typed argument slots (number | enum | string, with defaults and prompt hints) referenced as "{{name}}" in the arguments template. When the option wins, the slots are filled by a short grammar-constrained completion that continues the exact scoring prompt — rendered by the same cached ScoreClassifier, so the llama.cpp prompt cache is already warm — with the chosen route JSON re-opened at the first slot field. A GBNF grammar pins the field skeleton and frees only the values; temperature 0, a couple dozen tokens at most (~300ms on a desktop CPU for two slots). Slot declarations and hints ride the option descriptions in the shared system prompt, informing scoring and the fill alike at no per-turn token cost. The localai.classifier.result event carries the final arguments and a fill_latency_ms. On inference failure the slots' defaults apply; a slot without a default fails the response (or falls through with fallback.mode: generate). Slot filling requires completion alongside score in the scoring model's known_usecases. Verified end-to-end on the Pi drone demo: "fly forward three meters" in distance mode classifies forward and infers {"distance": 3, "units": "meters"} in ~310ms, and the drone flies exactly 3 units. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): splice filled slot values into classifier replies A classifier option's spoken reply can now reference its tool's argument slots ("Going forward {{distance}} {{units}}."): the values inferred by the slot-fill completion — or the recovery defaults — are spliced into the reply as plain text before it is emitted, so what the assistant says confirms what it actually inferred. Placeholders without a value stay literal, and options without slots are untouched. FillToolArguments now returns the raw slot values alongside the spliced arguments JSON to make the reply templating possible. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(realtime): harden classifier slot completion Reserve context for constrained slot filling, size completions from their encoded output, and encode enum grammar literals as valid JSON. Reject empty enum values and cover the failure modes with regression tests. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): prewarm the classifier scoring prompt on registration Swapping a session's classifier option list (a voice-switched command mode, for instance) made the next turns pay a full re-prefill of the new option-list prompt — measured 2.4s vs 0.3s warm on a desktop CPU, and worse: on hybrid-memory models like LFM2.5, whose state cannot be partially rewound (llama.cpp can only restore checkpoints), *every* probe change re-prefilled from scratch whenever the last checkpoint missed the probe boundary, so even same-list turns intermittently cost full prefills. Registering an option list (pipeline seed or session.update) now fires a best-effort background prewarm: two throwaway scores with distinct probes. The first prefills the new option-list prompt; the second, diverging exactly where per-turn probe text starts, plants the backend's rewind point (KV checkpoint) at the stable-prefix boundary that every real turn reuses. The prewarm hides behind the canned mode-switch reply — by the time it finishes speaking, the cache is warm. Idempotent per option set, detached from the registering request's lifetime. Measured on the drone demo (LFM2.5-1.2B, desktop CPU): first turn after a mode switch 2374ms -> 340ms; intermittent same-list full prefills (1.3-2.1s) all -> under 0.5s. For clients that swap lists frequently, options: [parallel:2] on the scoring model additionally keeps one slot per list via prefix-similarity routing (+26MB RSS, unified KV). Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * perf(llama-cpp): checkpoint scoring at the caller-declared stable prefix Hybrid-memory models (LFM2.5 shortconv, Qwen3.5 deltanet — where new small models are headed) cannot rewind their state, so any prompt-cache reuse that needs a rewind falls back to a full re-prefill. For classifier scoring that meant every probe change re-processed the whole option-list prompt: the server's checkpoints were placed reactively (at wherever the previous task happened to diverge), so a checkpoint past the next divergence was erased rather than restored — measured as intermittent 2-10s turns on prompts with a 95%+ common prefix. The classifier now computes the probe-invariant prompt prefix once (the byte-wise common prefix of two synthetic probe renders) and declares its length with every Score request; the server maps it to a token boundary and forces a KV checkpoint exactly there on each score prefill. That checkpoint sits at or before every future divergence under the same option list, so it always survives and always restores — repeat scoring costs probe+candidates regardless of how the probe changes. Also: - prewarm reruns on every option-list registration instead of memoizing per list: with boundary checkpoints a redundant rewarm costs two probe-sized decodes, while skipping one after a slot eviction (three lists sharing fewer slots evict in LRU cascades) silently moves a full re-prefill onto the user's next turn - new llama.cpp backend option rs_seq:N exposes bounded recurrent-state rollback outside speculative decoding; measured impractical for deltanet-scale states (65GB for 64 snapshots on Qwen3.5-4B) but cheap insurance for small-state models - docs: the multi-list recipe (parallel:N + sps:0.5 — the default slot similarity threshold funnels distinct lists onto one slot) Measured on the drone demo (LFM2.5-1.2B scorer, desktop CPU), steady state: every turn 285-421ms including mode switches, vs 2.4s post-switch and intermittent 1.3-2.9s re-prefills before. Assisted-by: Claude:claude-fable-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(realtime): align classifier cache guidance Document the single-score prewarm behavior and clean the vendored score patch formatting. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(llama-cpp): guard score task for fork backends TurboQuant and Bonsai reuse the primary gRPC server against llama.cpp forks that do not carry LocalAI's slot-based Score patches. Compile the Score integration only for the patched primary backend and return UNIMPLEMENTED from fork builds instead of referencing absent task types and common_params fields. Assisted-by: Codex:gpt-5 [gh] Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(dev): generate gRPC code before commit lint The coverage phase regenerates ignored protobuf bindings, but lint runs first and can fail against missing or stale output. Generate the pinned bindings before lint so the gate always type-checks the current schema. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> --------- Signed-off-by: Richard Palethorpe <io@richiejp.com>
904 lines
30 KiB
Go
904 lines
30 KiB
Go
package config
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
. "github.com/onsi/ginkgo/v2"
|
|
. "github.com/onsi/gomega"
|
|
|
|
"github.com/mudler/LocalAI/pkg/modelartifacts"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
var _ = Describe("Test cases for config related functions", func() {
|
|
Context("ModelID", func() {
|
|
It("returns Name when set", func() {
|
|
c := ModelConfig{Name: "my-name"}
|
|
c.Model = "my-model"
|
|
Expect(c.ModelID()).To(Equal("my-name"))
|
|
})
|
|
It("falls back to Model when Name is empty", func() {
|
|
c := ModelConfig{}
|
|
c.Model = "my-model"
|
|
Expect(c.ModelID()).To(Equal("my-model"))
|
|
})
|
|
It("returns empty string when both are empty", func() {
|
|
c := ModelConfig{}
|
|
Expect(c.ModelID()).To(Equal(""))
|
|
})
|
|
})
|
|
|
|
It("round-trips and validates a managed model artifact", func() {
|
|
raw := []byte(`
|
|
name: qwen-asr
|
|
backend: qwen-asr
|
|
artifacts:
|
|
- name: model
|
|
target: model
|
|
source:
|
|
type: huggingface
|
|
repo: Qwen/Qwen3-ASR-1.7B
|
|
parameters:
|
|
model: Qwen/Qwen3-ASR-1.7B
|
|
`)
|
|
var cfg ModelConfig
|
|
Expect(yaml.Unmarshal(raw, &cfg)).To(Succeed())
|
|
Expect(cfg.Artifacts).To(HaveLen(1))
|
|
valid, err := cfg.Validate()
|
|
Expect(err).NotTo(HaveOccurred())
|
|
Expect(valid).To(BeTrue())
|
|
})
|
|
|
|
It("derives a managed snapshot filename without replacing the logical model", func() {
|
|
const cacheKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
|
cfg := ModelConfig{
|
|
Artifacts: []modelartifacts.Spec{{
|
|
Source: modelartifacts.Source{Type: "huggingface", Repo: "owner/repo"},
|
|
Resolved: &modelartifacts.Resolved{CacheKey: cacheKey},
|
|
}},
|
|
}
|
|
cfg.Model = "owner/repo"
|
|
Expect(cfg.Model).To(Equal("owner/repo"))
|
|
Expect(cfg.ModelFileName()).To(Equal(filepath.Join(".artifacts", "huggingface", cacheKey, "snapshot")))
|
|
})
|
|
|
|
It("resolves a single-file managed snapshot to the file inside the snapshot", func() {
|
|
const cacheKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
|
cfg := ModelConfig{
|
|
Artifacts: []modelartifacts.Spec{{
|
|
Source: modelartifacts.Source{Type: "huggingface", Repo: "owner/repo"},
|
|
Resolved: &modelartifacts.Resolved{
|
|
CacheKey: cacheKey,
|
|
PrimaryFile: "nomic-embed-text-v1.5.f16.gguf",
|
|
},
|
|
}},
|
|
}
|
|
cfg.Model = "huggingface://owner/repo/nomic-embed-text-v1.5.f16.gguf"
|
|
// A single-file GGUF must resolve to the file itself, never the snapshot
|
|
// directory, or the backend fails with "failed to read magic".
|
|
Expect(cfg.ModelFileName()).To(Equal(
|
|
filepath.Join(".artifacts", "huggingface", cacheKey, "snapshot", "nomic-embed-text-v1.5.f16.gguf")))
|
|
})
|
|
|
|
Context("Test Read configuration functions", func() {
|
|
It("Test Validate", func() {
|
|
tmp, err := os.CreateTemp("", "config.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer os.Remove(tmp.Name())
|
|
_, err = tmp.WriteString(
|
|
`backend: "../foo-bar"
|
|
name: "foo"
|
|
parameters:
|
|
model: "foo-bar"
|
|
known_usecases:
|
|
- chat
|
|
- COMPLETION
|
|
`)
|
|
Expect(err).ToNot(HaveOccurred())
|
|
configs, err := readModelConfigsFromFile(tmp.Name())
|
|
config := configs[0]
|
|
Expect(err).To(BeNil())
|
|
Expect(config).ToNot(BeNil())
|
|
valid, err := config.Validate()
|
|
Expect(err).To(HaveOccurred())
|
|
Expect(valid).To(BeFalse())
|
|
Expect(config.KnownUsecases).ToNot(BeNil())
|
|
})
|
|
It("Test Validate", func() {
|
|
tmp, err := os.CreateTemp("", "config.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer os.Remove(tmp.Name())
|
|
_, err = tmp.WriteString(
|
|
`name: bar-baz
|
|
backend: "foo-bar"
|
|
parameters:
|
|
model: "foo-bar"`)
|
|
Expect(err).ToNot(HaveOccurred())
|
|
configs, err := readModelConfigsFromFile(tmp.Name())
|
|
config := configs[0]
|
|
Expect(err).To(BeNil())
|
|
Expect(config).ToNot(BeNil())
|
|
// two configs in config.yaml
|
|
Expect(config.Name).To(Equal("bar-baz"))
|
|
valid, err := config.Validate()
|
|
Expect(err).To(BeNil())
|
|
Expect(valid).To(BeTrue())
|
|
|
|
// Score runs through the llama-cpp slot loop, so mixing the
|
|
// score usecase with chat/completion/embeddings on one config
|
|
// is valid — the slot scheduler serializes score against
|
|
// generation and shares the prompt cache between them.
|
|
scoreFlag := FLAG_SCORE | FLAG_CHAT
|
|
scoringChat := ModelConfig{
|
|
Name: "router-and-chat",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &scoreFlag,
|
|
}
|
|
valid, err = scoringChat.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
scoreOnly := FLAG_SCORE
|
|
dedicated := ModelConfig{
|
|
Name: "router-only",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &scoreOnly,
|
|
}
|
|
valid, err = dedicated.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
tcAndChat := FLAG_TOKEN_CLASSIFY | FLAG_CHAT
|
|
tcCombined := ModelConfig{
|
|
Name: "ner-and-chat",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &tcAndChat,
|
|
}
|
|
valid, err = tcCombined.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
tcAndEmbeddings := FLAG_TOKEN_CLASSIFY | FLAG_EMBEDDINGS
|
|
tcWithEmbeddings := ModelConfig{
|
|
Name: "pii-ner",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &tcAndEmbeddings,
|
|
}
|
|
valid, err = tcWithEmbeddings.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
// Cloud-proxy: api_key_env and api_key_file are mutually
|
|
// exclusive — picking both is a config bug we catch at
|
|
// load/save rather than at backend-load time.
|
|
bothKeys := ModelConfig{
|
|
Name: "both-keys",
|
|
Backend: "cloud-proxy",
|
|
Proxy: ProxyConfig{
|
|
UpstreamURL: "https://example.com/v1",
|
|
APIKeyEnv: "OPENAI_KEY",
|
|
APIKeyFile: "/run/secrets/openai",
|
|
},
|
|
}
|
|
valid, err = bothKeys.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("mutually exclusive")))
|
|
|
|
// Translate mode requires a provider — without one, the
|
|
// backend has no way to pick a wire format.
|
|
translateNoProvider := ModelConfig{
|
|
Name: "translate-no-provider",
|
|
Backend: "cloud-proxy",
|
|
Proxy: ProxyConfig{UpstreamURL: "https://example.com/v1", Mode: ProxyModeTranslate},
|
|
}
|
|
valid, err = translateNoProvider.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("translate mode requires provider")))
|
|
|
|
// Unknown mode is rejected.
|
|
badMode := ModelConfig{
|
|
Name: "bad-mode",
|
|
Backend: "cloud-proxy",
|
|
Proxy: ProxyConfig{UpstreamURL: "https://example.com/v1", Mode: "rewrite"},
|
|
}
|
|
valid, err = badMode.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("unknown mode")))
|
|
|
|
// Passthrough (default) with one key source is happy.
|
|
passthroughOK := ModelConfig{
|
|
Name: "passthrough-ok",
|
|
Backend: "cloud-proxy",
|
|
Proxy: ProxyConfig{UpstreamURL: "https://example.com/v1", APIKeyEnv: "OPENAI_KEY"},
|
|
}
|
|
valid, err = passthroughOK.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
// router.score_normalization: load-time rejection of an
|
|
// unknown value. The classifier consumes it lazily, so
|
|
// without this validation a YAML typo wouldn't surface
|
|
// until the first router request panicked deep in
|
|
// NewScoreClassifier.
|
|
badNorm := ModelConfig{
|
|
Name: "bad-norm",
|
|
Router: RouterConfig{
|
|
ScoreNormalization: "men", // typo of "mean"
|
|
},
|
|
}
|
|
valid, err = badNorm.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("unknown score_normalization")))
|
|
|
|
// Accepted values pass.
|
|
for _, mode := range []string{"", ScoreNormalizationRaw, ScoreNormalizationMean} {
|
|
goodNorm := ModelConfig{
|
|
Name: "good-norm-" + mode,
|
|
Router: RouterConfig{ScoreNormalization: mode},
|
|
}
|
|
valid, err = goodNorm.Validate()
|
|
Expect(valid).To(BeTrue(), "score_normalization=%q should be accepted", mode)
|
|
Expect(err).NotTo(HaveOccurred())
|
|
}
|
|
|
|
// router.classifier_system_template: parse-time rejection
|
|
// of malformed Go templates. Same reasoning as above —
|
|
// without this the parse error wouldn't surface until
|
|
// the first router request panicked in NewScoreClassifier.
|
|
badTmpl := ModelConfig{
|
|
Name: "bad-tmpl",
|
|
Router: RouterConfig{
|
|
ClassifierSystemTemplate: "Routes: {{range .Policies",
|
|
},
|
|
}
|
|
valid, err = badTmpl.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("classifier_system_template parse error")))
|
|
|
|
// Well-formed template passes.
|
|
goodTmpl := ModelConfig{
|
|
Name: "good-tmpl",
|
|
Router: RouterConfig{
|
|
ClassifierSystemTemplate: `Routes: {{range .Policies}}{{.Label}} {{end}}`,
|
|
},
|
|
}
|
|
valid, err = goodTmpl.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
// download https://raw.githubusercontent.com/mudler/LocalAI/v2.25.0/embedded/models/hermes-2-pro-mistral.yaml
|
|
httpClient := http.Client{}
|
|
resp, err := httpClient.Get("https://raw.githubusercontent.com/mudler/LocalAI/v2.25.0/embedded/models/hermes-2-pro-mistral.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer resp.Body.Close()
|
|
tmp, err = os.CreateTemp("", "config.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer os.Remove(tmp.Name())
|
|
_, err = io.Copy(tmp, resp.Body)
|
|
Expect(err).To(BeNil())
|
|
configs, err = readModelConfigsFromFile(tmp.Name())
|
|
config = configs[0]
|
|
Expect(err).To(BeNil())
|
|
Expect(config).ToNot(BeNil())
|
|
// two configs in config.yaml
|
|
Expect(config.Name).To(Equal("hermes-2-pro-mistral"))
|
|
valid, err = config.Validate()
|
|
Expect(err).To(BeNil())
|
|
Expect(valid).To(BeTrue())
|
|
})
|
|
})
|
|
It("Properly handles backend usecase matching", func() {
|
|
a := ModelConfig{
|
|
Name: "a",
|
|
}
|
|
Expect(a.HasUsecases(FLAG_ANY)).To(BeTrue()) // FLAG_ANY just means the config _exists_ essentially.
|
|
|
|
b := ModelConfig{
|
|
Name: "b",
|
|
Backend: "stablediffusion",
|
|
}
|
|
Expect(b.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(b.HasUsecases(FLAG_IMAGE)).To(BeTrue())
|
|
Expect(b.HasUsecases(FLAG_CHAT)).To(BeFalse())
|
|
|
|
c := ModelConfig{
|
|
Name: "c",
|
|
Backend: "llama-cpp",
|
|
TemplateConfig: TemplateConfig{
|
|
Chat: "chat",
|
|
},
|
|
}
|
|
Expect(c.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(c.HasUsecases(FLAG_IMAGE)).To(BeFalse())
|
|
Expect(c.HasUsecases(FLAG_COMPLETION)).To(BeFalse())
|
|
Expect(c.HasUsecases(FLAG_CHAT)).To(BeTrue())
|
|
|
|
d := ModelConfig{
|
|
Name: "d",
|
|
Backend: "llama-cpp",
|
|
TemplateConfig: TemplateConfig{
|
|
Chat: "chat",
|
|
Completion: "completion",
|
|
},
|
|
}
|
|
Expect(d.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(d.HasUsecases(FLAG_IMAGE)).To(BeFalse())
|
|
Expect(d.HasUsecases(FLAG_COMPLETION)).To(BeTrue())
|
|
Expect(d.HasUsecases(FLAG_CHAT)).To(BeTrue())
|
|
|
|
trueValue := true
|
|
e := ModelConfig{
|
|
Name: "e",
|
|
Backend: "llama-cpp",
|
|
TemplateConfig: TemplateConfig{
|
|
Completion: "completion",
|
|
},
|
|
Embeddings: &trueValue,
|
|
}
|
|
|
|
Expect(e.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(e.HasUsecases(FLAG_IMAGE)).To(BeFalse())
|
|
Expect(e.HasUsecases(FLAG_COMPLETION)).To(BeTrue())
|
|
Expect(e.HasUsecases(FLAG_CHAT)).To(BeFalse())
|
|
Expect(e.HasUsecases(FLAG_EMBEDDINGS)).To(BeTrue())
|
|
|
|
// Router models are chat dispatchers: no chat template of their
|
|
// own, but invoked through the chat endpoint, so they default to
|
|
// chat-capable.
|
|
r := ModelConfig{
|
|
Name: "r",
|
|
Router: RouterConfig{
|
|
Candidates: []RouterCandidate{{Model: "downstream", Labels: []string{"general"}}},
|
|
},
|
|
}
|
|
Expect(r.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(r.HasUsecases(FLAG_CHAT)).To(BeTrue())
|
|
|
|
f := ModelConfig{
|
|
Name: "f",
|
|
Backend: "piper",
|
|
}
|
|
Expect(f.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(f.HasUsecases(FLAG_TTS)).To(BeTrue())
|
|
Expect(f.HasUsecases(FLAG_CHAT)).To(BeFalse())
|
|
|
|
g := ModelConfig{
|
|
Name: "g",
|
|
Backend: "whisper",
|
|
}
|
|
Expect(g.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(g.HasUsecases(FLAG_TRANSCRIPT)).To(BeTrue())
|
|
Expect(g.HasUsecases(FLAG_TTS)).To(BeFalse())
|
|
|
|
h := ModelConfig{
|
|
Name: "h",
|
|
Backend: "transformers-musicgen",
|
|
}
|
|
Expect(h.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(h.HasUsecases(FLAG_TRANSCRIPT)).To(BeFalse())
|
|
Expect(h.HasUsecases(FLAG_TTS)).To(BeTrue())
|
|
Expect(h.HasUsecases(FLAG_SOUND_GENERATION)).To(BeTrue())
|
|
|
|
knownUsecases := FLAG_CHAT | FLAG_COMPLETION
|
|
i := ModelConfig{
|
|
Name: "i",
|
|
Backend: "whisper",
|
|
// Earlier test checks parsing, this just needs to set final values
|
|
KnownUsecases: &knownUsecases,
|
|
}
|
|
Expect(i.HasUsecases(FLAG_ANY)).To(BeTrue())
|
|
Expect(i.HasUsecases(FLAG_TRANSCRIPT)).To(BeTrue())
|
|
Expect(i.HasUsecases(FLAG_TTS)).To(BeFalse())
|
|
Expect(i.HasUsecases(FLAG_COMPLETION)).To(BeTrue())
|
|
Expect(i.HasUsecases(FLAG_CHAT)).To(BeTrue())
|
|
|
|
// Declared `known_usecases: [score]` is authoritative — the
|
|
// guessing heuristic must NOT add chat on top, even though the
|
|
// inherited chatml template would otherwise satisfy the chat
|
|
// heuristic. A score-only declaration means "this model is
|
|
// reserved for the router classifier"; surfacing it as a chat
|
|
// model defeats the reservation. (Operators who do want both
|
|
// may declare both — the combination is supported.)
|
|
scoreReserved := FLAG_SCORE
|
|
j := ModelConfig{
|
|
Name: "arch-router",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &scoreReserved,
|
|
TemplateConfig: TemplateConfig{
|
|
Chat: "inherited from chatml",
|
|
ChatMessage: "inherited from chatml",
|
|
Completion: "inherited from chatml",
|
|
},
|
|
}
|
|
Expect(j.HasUsecases(FLAG_SCORE)).To(BeTrue())
|
|
Expect(j.HasUsecases(FLAG_CHAT)).To(BeFalse())
|
|
Expect(j.HasUsecases(FLAG_COMPLETION)).To(BeFalse())
|
|
Expect(j.HasUsecases(FLAG_EMBEDDINGS)).To(BeFalse())
|
|
|
|
// Declared `known_usecases: [token_classify]` is likewise
|
|
// authoritative — a PII NER model is reserved for the redactor's
|
|
// NER tier and must not surface as chat or as a general embeddings
|
|
// model, even though it loads with embeddings enabled (its
|
|
// TOKEN_CLS head produces BIOES logits, not reusable embeddings).
|
|
tcReserved := FLAG_TOKEN_CLASSIFY
|
|
embTrue := true
|
|
k := ModelConfig{
|
|
Name: "privacy-filter",
|
|
Backend: "llama-cpp",
|
|
KnownUsecases: &tcReserved,
|
|
Embeddings: &embTrue,
|
|
TemplateConfig: TemplateConfig{
|
|
Chat: "inherited from chatml",
|
|
ChatMessage: "inherited from chatml",
|
|
},
|
|
}
|
|
Expect(k.HasUsecases(FLAG_TOKEN_CLASSIFY)).To(BeTrue())
|
|
Expect(k.HasUsecases(FLAG_CHAT)).To(BeFalse())
|
|
Expect(k.HasUsecases(FLAG_EMBEDDINGS)).To(BeFalse())
|
|
})
|
|
It("Test Validate with invalid MCP config", func() {
|
|
tmp, err := os.CreateTemp("", "config.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer os.Remove(tmp.Name())
|
|
_, err = tmp.WriteString(
|
|
`name: test-mcp
|
|
backend: "llama-cpp"
|
|
mcp:
|
|
stdio: |
|
|
{
|
|
"mcpServers": {
|
|
"ddg": {
|
|
"command": "/docker/docker",
|
|
"args": ["run", "-i"]
|
|
}
|
|
"weather": {
|
|
"command": "/docker/docker",
|
|
"args": ["run", "-i"]
|
|
}
|
|
}
|
|
}`)
|
|
Expect(err).ToNot(HaveOccurred())
|
|
configs, err := readModelConfigsFromFile(tmp.Name())
|
|
config := configs[0]
|
|
Expect(err).To(BeNil())
|
|
Expect(config).ToNot(BeNil())
|
|
valid, err := config.Validate()
|
|
Expect(err).To(HaveOccurred())
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err.Error()).To(ContainSubstring("invalid MCP configuration"))
|
|
})
|
|
It("Test Validate with valid MCP config", func() {
|
|
tmp, err := os.CreateTemp("", "config.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer os.Remove(tmp.Name())
|
|
_, err = tmp.WriteString(
|
|
`name: test-mcp-valid
|
|
backend: "llama-cpp"
|
|
mcp:
|
|
stdio: |
|
|
{
|
|
"mcpServers": {
|
|
"ddg": {
|
|
"command": "/docker/docker",
|
|
"args": ["run", "-i"]
|
|
},
|
|
"weather": {
|
|
"command": "/docker/docker",
|
|
"args": ["run", "-i"]
|
|
}
|
|
}
|
|
}`)
|
|
Expect(err).ToNot(HaveOccurred())
|
|
configs, err := readModelConfigsFromFile(tmp.Name())
|
|
config := configs[0]
|
|
Expect(err).To(BeNil())
|
|
Expect(config).ToNot(BeNil())
|
|
valid, err := config.Validate()
|
|
Expect(err).To(BeNil())
|
|
Expect(valid).To(BeTrue())
|
|
})
|
|
It("Test Validate rejects unmarshalable engine_args", func() {
|
|
// chan values cannot be JSON-marshalled. A valid YAML config could
|
|
// not produce one, but a Go caller stuffing a bad value would, and
|
|
// silently dropping it would change runtime behaviour.
|
|
cfg := &ModelConfig{
|
|
Backend: "vllm",
|
|
LLMConfig: LLMConfig{
|
|
EngineArgs: map[string]any{
|
|
"speculative_config": make(chan int),
|
|
},
|
|
},
|
|
}
|
|
valid, err := cfg.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).ToNot(BeNil())
|
|
Expect(err.Error()).To(ContainSubstring("engine_args is not JSON-serialisable"))
|
|
})
|
|
It("Test Validate accepts well-formed engine_args", func() {
|
|
cfg := &ModelConfig{
|
|
Backend: "vllm",
|
|
LLMConfig: LLMConfig{
|
|
EngineArgs: map[string]any{
|
|
"data_parallel_size": 8,
|
|
"speculative_config": map[string]any{
|
|
"method": "ngram",
|
|
"num_speculative_tokens": 4,
|
|
},
|
|
},
|
|
},
|
|
}
|
|
valid, err := cfg.Validate()
|
|
Expect(err).To(BeNil())
|
|
Expect(valid).To(BeTrue())
|
|
})
|
|
Context("ConcurrencyGroups", func() {
|
|
It("returns nil when no groups are configured", func() {
|
|
cfg := &ModelConfig{Name: "no-groups"}
|
|
Expect(cfg.GetConcurrencyGroups()).To(BeNil())
|
|
})
|
|
It("returns nil when all entries are blank", func() {
|
|
cfg := &ModelConfig{
|
|
Name: "blanks",
|
|
ConcurrencyGroups: []string{"", " ", "\t"},
|
|
}
|
|
Expect(cfg.GetConcurrencyGroups()).To(BeNil())
|
|
})
|
|
It("trims whitespace, drops empty entries, and dedupes", func() {
|
|
cfg := &ModelConfig{
|
|
Name: "messy",
|
|
ConcurrencyGroups: []string{" vram-heavy ", "", "vram-heavy", "vision", " vision "},
|
|
}
|
|
Expect(cfg.GetConcurrencyGroups()).To(Equal([]string{"vram-heavy", "vision"}))
|
|
})
|
|
It("returns a defensive copy", func() {
|
|
cfg := &ModelConfig{
|
|
Name: "copy",
|
|
ConcurrencyGroups: []string{"heavy"},
|
|
}
|
|
got := cfg.GetConcurrencyGroups()
|
|
got[0] = "tampered"
|
|
Expect(cfg.GetConcurrencyGroups()).To(Equal([]string{"heavy"}))
|
|
})
|
|
It("parses concurrency_groups from YAML", func() {
|
|
tmp, err := os.CreateTemp("", "concgroups.yaml")
|
|
Expect(err).To(BeNil())
|
|
defer func() { _ = os.Remove(tmp.Name()) }()
|
|
_, err = tmp.WriteString(
|
|
`name: heavy-a
|
|
backend: llama-cpp
|
|
parameters:
|
|
model: heavy-a.gguf
|
|
concurrency_groups:
|
|
- vram-heavy
|
|
- "120b"
|
|
`)
|
|
Expect(err).ToNot(HaveOccurred())
|
|
configs, err := readModelConfigsFromFile(tmp.Name())
|
|
Expect(err).To(BeNil())
|
|
Expect(configs).To(HaveLen(1))
|
|
Expect(configs[0].ConcurrencyGroups).To(Equal([]string{"vram-heavy", "120b"}))
|
|
Expect(configs[0].GetConcurrencyGroups()).To(Equal([]string{"vram-heavy", "120b"}))
|
|
})
|
|
})
|
|
|
|
// When templating is delegated to the backend (use_tokenizer_template),
|
|
// the backend also owns tool-call grammar generation and parsing. A
|
|
// LocalAI-generated grammar sent alongside would override the backend's
|
|
// native (name-first) tool pipeline and make it stream the tool-call JSON
|
|
// back as plain content (issue #10052). SetDefaults must therefore couple
|
|
// the two: tokenizer template implies grammar generation is disabled.
|
|
Context("use_tokenizer_template couples with grammar disable (issue #10052)", func() {
|
|
It("disables Go grammar generation when the tokenizer template is used", func() {
|
|
cfg := &ModelConfig{
|
|
TemplateConfig: TemplateConfig{UseTokenizerTemplate: true},
|
|
}
|
|
Expect(cfg.FunctionsConfig.GrammarConfig.NoGrammar).To(BeFalse())
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.FunctionsConfig.GrammarConfig.NoGrammar).To(BeTrue(),
|
|
"use_tokenizer_template must imply grammar.disable so tools go to the backend's native pipeline")
|
|
})
|
|
|
|
It("leaves grammar generation enabled when the tokenizer template is not used", func() {
|
|
cfg := &ModelConfig{}
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.FunctionsConfig.GrammarConfig.NoGrammar).To(BeFalse(),
|
|
"models that template in Go still rely on the Go-generated grammar")
|
|
})
|
|
})
|
|
|
|
// The default top_k=40 is llama.cpp's sampling default and is WRONG for
|
|
// backends whose native default differs. mlx_lm's intended default is
|
|
// top_k=0 (disabled) and mlx does not remap 0->40, so injecting 40 silently
|
|
// changes sampling for mlx clients that omit top_k (issue #6632). Gate the
|
|
// injection on backend family: keep 40 for the llama.cpp family and for the
|
|
// empty/auto backend (the GGUF auto-detect path resolves to llama.cpp), but
|
|
// leave TopK nil for the mlx family so the wire value is 0.
|
|
Context("TopK default is backend-gated (issue #6632)", func() {
|
|
It("injects top_k=40 for the llama.cpp backend", func() {
|
|
cfg := &ModelConfig{}
|
|
cfg.Backend = "llama-cpp"
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).NotTo(BeNil(), "llama.cpp must keep its top_k=40 default")
|
|
Expect(*cfg.TopK).To(Equal(40))
|
|
})
|
|
|
|
It("injects top_k=40 for the empty/auto backend (GGUF auto-detect)", func() {
|
|
cfg := &ModelConfig{}
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).NotTo(BeNil(), "empty backend resolves to llama.cpp; default unchanged")
|
|
Expect(*cfg.TopK).To(Equal(40))
|
|
})
|
|
|
|
It("leaves TopK nil for the mlx backend", func() {
|
|
cfg := &ModelConfig{}
|
|
cfg.Backend = "mlx"
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).To(BeNil(),
|
|
"mlx_lm's intended default is top_k=0 (disabled); LocalAI must not inject 40")
|
|
})
|
|
|
|
It("leaves TopK nil for the mlx-vlm backend", func() {
|
|
cfg := &ModelConfig{}
|
|
cfg.Backend = "mlx-vlm"
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).To(BeNil())
|
|
})
|
|
|
|
It("leaves TopK nil for the mlx-distributed backend", func() {
|
|
cfg := &ModelConfig{}
|
|
cfg.Backend = "mlx-distributed"
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).To(BeNil())
|
|
})
|
|
|
|
It("respects an explicit top_k even for the mlx backend", func() {
|
|
explicit := 7
|
|
cfg := &ModelConfig{}
|
|
cfg.Backend = "mlx"
|
|
cfg.TopK = &explicit
|
|
|
|
cfg.SetDefaults()
|
|
|
|
Expect(cfg.TopK).NotTo(BeNil())
|
|
Expect(*cfg.TopK).To(Equal(7))
|
|
})
|
|
})
|
|
})
|
|
|
|
var _ = Describe("TTS capability configuration", func() {
|
|
It("preserves an explicit voice-cloning opt-out from YAML", func() {
|
|
var cfg ModelConfig
|
|
Expect(yaml.Unmarshal([]byte("name: private-voice\ntts:\n voice_cloning: false\n"), &cfg)).To(Succeed())
|
|
Expect(cfg.VoiceCloning).NotTo(BeNil())
|
|
Expect(*cfg.VoiceCloning).To(BeFalse())
|
|
|
|
raw, err := yaml.Marshal(cfg)
|
|
Expect(err).NotTo(HaveOccurred())
|
|
Expect(string(raw)).To(ContainSubstring("voice_cloning: false"))
|
|
})
|
|
|
|
It("leaves voice-cloning detection automatic when the field is omitted", func() {
|
|
var cfg ModelConfig
|
|
Expect(yaml.Unmarshal([]byte("name: automatic-voice\ntts:\n audio_path: voices/default.wav\n"), &cfg)).To(Succeed())
|
|
Expect(cfg.VoiceCloning).To(BeNil())
|
|
})
|
|
})
|
|
|
|
var _ = Describe("PII config accessors", func() {
|
|
It("PIIDetectors returns a fresh copy of the consumer's detector list", func() {
|
|
cfg := &ModelConfig{PII: PIIConfig{Detectors: []string{"a", "b"}}}
|
|
got := cfg.PIIDetectors()
|
|
Expect(got).To(Equal([]string{"a", "b"}))
|
|
got[0] = "mutated"
|
|
Expect(cfg.PII.Detectors[0]).To(Equal("a"), "accessor must not alias the underlying slice")
|
|
})
|
|
|
|
It("PIIDetectors is nil when none are configured", func() {
|
|
Expect((&ModelConfig{}).PIIDetectors()).To(BeNil())
|
|
})
|
|
|
|
It("exposes the detector model's pii_detection policy", func() {
|
|
cfg := &ModelConfig{PIIDetection: PIIDetectionConfig{
|
|
MinScore: 0.5,
|
|
DefaultAction: "mask",
|
|
EntityActions: map[string]string{"PASSWORD": "block", "EMAIL": "mask"},
|
|
}}
|
|
Expect(cfg.PIIDetectionMinScore()).To(BeNumerically("~", 0.5, 1e-6))
|
|
Expect(cfg.PIIDetectionDefaultAction()).To(Equal("mask"))
|
|
ea := cfg.PIIDetectionEntityActions()
|
|
Expect(ea).To(HaveKeyWithValue("PASSWORD", "block"))
|
|
ea["PASSWORD"] = "mutated"
|
|
Expect(cfg.PIIDetection.EntityActions["PASSWORD"]).To(Equal("block"), "accessor must return a fresh map")
|
|
})
|
|
|
|
It("unmarshals pii.detectors and pii_detection from YAML", func() {
|
|
var cfg ModelConfig
|
|
raw := []byte("name: consumer\npii:\n enabled: true\n detectors: [pf]\npii_detection:\n min_score: 0.4\n default_action: mask\n entity_actions:\n PASSWORD: block\n")
|
|
Expect(yaml.Unmarshal(raw, &cfg)).To(Succeed())
|
|
Expect(cfg.PIIDetectors()).To(Equal([]string{"pf"}))
|
|
Expect(cfg.PIIDetectionDefaultAction()).To(Equal("mask"))
|
|
Expect(cfg.PIIDetectionEntityActions()).To(HaveKeyWithValue("PASSWORD", "block"))
|
|
})
|
|
})
|
|
|
|
var _ = Describe("GGUF importer chat-default guard (reservedNonChatModel)", func() {
|
|
mk := func(flags ModelConfigUsecase) *ModelConfig {
|
|
return &ModelConfig{Backend: "llama-cpp", KnownUsecases: &flags}
|
|
}
|
|
|
|
It("treats declared score / token_classify models as reserved (no chat defaults)", func() {
|
|
Expect(reservedNonChatModel(mk(FLAG_SCORE))).To(BeTrue())
|
|
Expect(reservedNonChatModel(mk(FLAG_TOKEN_CLASSIFY))).To(BeTrue())
|
|
// embeddings declared alongside token_classify (the PII NER shape) is
|
|
// still reserved.
|
|
Expect(reservedNonChatModel(mk(FLAG_TOKEN_CLASSIFY | FLAG_EMBEDDINGS))).To(BeTrue())
|
|
})
|
|
|
|
It("does not reserve ordinary or undeclared models", func() {
|
|
Expect(reservedNonChatModel(mk(FLAG_CHAT))).To(BeFalse())
|
|
Expect(reservedNonChatModel(mk(FLAG_EMBEDDINGS))).To(BeFalse())
|
|
Expect(reservedNonChatModel(&ModelConfig{Backend: "llama-cpp"})).To(BeFalse())
|
|
})
|
|
|
|
It("keeps a token_classify GGUF config valid by withholding FLAG_CHAT", func() {
|
|
// The privacy-filter import shape: the GGUF importer appends FLAG_CHAT
|
|
// to a templateless model, which the next sync folds into
|
|
// KnownUsecases. token_classify+chat is a VALID combination
|
|
// (token_classify runs on the privacy-filter backend, not llama-cpp,
|
|
// so the score/chat conflict check does not apply to it), but the
|
|
// importer must still not paint a declared-reserved model as chat
|
|
// — that would surface it in every chat picker.
|
|
reserved := []string{"token_classify"}
|
|
withChat := append(append([]string{}, reserved...), "FLAG_CHAT")
|
|
|
|
// What the importer would produce WITHOUT the guard: valid (the
|
|
// score/chat conflict check is score-specific), just undesirable
|
|
// defaults.
|
|
combined := &ModelConfig{Backend: "llama-cpp", KnownUsecaseStrings: withChat}
|
|
combined.syncKnownUsecasesFromString()
|
|
valid, err := combined.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
|
|
// With the guard (FLAG_CHAT withheld): the declaration survives and the
|
|
// config validates.
|
|
good := &ModelConfig{Backend: "llama-cpp", KnownUsecaseStrings: reserved}
|
|
good.syncKnownUsecasesFromString()
|
|
Expect(reservedNonChatModel(good)).To(BeTrue())
|
|
valid, err = good.Validate()
|
|
Expect(valid).To(BeTrue())
|
|
Expect(err).NotTo(HaveOccurred())
|
|
Expect(good.HasUsecases(FLAG_TOKEN_CLASSIFY)).To(BeTrue())
|
|
})
|
|
})
|
|
|
|
var _ = Describe("PIIFilterApplies (Middleware admin list scoping)", func() {
|
|
withUsecases := func(backend string, flags ModelConfigUsecase) *ModelConfig {
|
|
return &ModelConfig{Name: "m", Backend: backend, KnownUsecases: &flags}
|
|
}
|
|
|
|
It("includes chat-capable models and cloud-proxy models", func() {
|
|
Expect(withUsecases("llama-cpp", FLAG_CHAT).PIIFilterApplies()).To(BeTrue())
|
|
// cloud-proxy is always covered (MITM / proxy chat path), regardless
|
|
// of declared usecases.
|
|
Expect((&ModelConfig{Name: "claude", Backend: "cloud-proxy"}).PIIFilterApplies()).To(BeTrue())
|
|
})
|
|
|
|
It("excludes the detector and score models themselves", func() {
|
|
// token_classify detectors are the filters, not consumers; score
|
|
// classifiers are internal primitives. Both short-circuit
|
|
// HasUsecases(FLAG_CHAT) to false.
|
|
Expect(withUsecases("llama-cpp", FLAG_TOKEN_CLASSIFY).PIIFilterApplies()).To(BeFalse())
|
|
Expect(withUsecases("llama-cpp", FLAG_SCORE).PIIFilterApplies()).To(BeFalse())
|
|
})
|
|
|
|
It("includes embedding and completion models (their request text is filtered)", func() {
|
|
// Phase 4 wired PII onto /v1/embeddings, /v1/completions and /v1/edits,
|
|
// so those usecases are now coverable.
|
|
emb := withUsecases("llama-cpp", FLAG_EMBEDDINGS)
|
|
t := true
|
|
emb.Embeddings = &t
|
|
Expect(emb.PIIFilterApplies()).To(BeTrue())
|
|
Expect(withUsecases("llama-cpp", FLAG_COMPLETION).PIIFilterApplies()).To(BeTrue())
|
|
})
|
|
|
|
It("excludes models with no text-accepting, PII-covered endpoint", func() {
|
|
// VAD / audio-in models carry no coverable usecase.
|
|
Expect((&ModelConfig{Name: "vad", Backend: "silero-vad"}).PIIFilterApplies()).To(BeFalse())
|
|
Expect(withUsecases("whisper", FLAG_TRANSCRIPT).PIIFilterApplies()).To(BeFalse())
|
|
})
|
|
})
|
|
|
|
var _ = Describe("pattern detector config", func() {
|
|
patternCfg := func() *ModelConfig {
|
|
c := &ModelConfig{Name: "secret-filter", Backend: "pattern"}
|
|
c.PIIDetection.Builtins = []string{"anthropic_api_key"}
|
|
c.PIIDetection.Patterns = []PIIPattern{{Name: "INTERNAL", Match: `tok-[A-Za-z0-9]{20,}`}}
|
|
return c
|
|
}
|
|
|
|
It("IsPatternDetector keys off builtins/patterns", func() {
|
|
Expect(patternCfg().IsPatternDetector()).To(BeTrue())
|
|
Expect((&ModelConfig{Name: "ner", Backend: "llama-cpp"}).IsPatternDetector()).To(BeFalse())
|
|
})
|
|
|
|
It("Validate accepts a well-formed pattern detector (no model file needed)", func() {
|
|
ok, err := patternCfg().Validate()
|
|
Expect(err).NotTo(HaveOccurred())
|
|
Expect(ok).To(BeTrue())
|
|
})
|
|
|
|
It("Validate rejects an unknown built-in", func() {
|
|
c := &ModelConfig{Name: "x", Backend: "pattern"}
|
|
c.PIIDetection.Builtins = []string{"does_not_exist"}
|
|
_, err := c.Validate()
|
|
Expect(err).To(MatchError(ContainSubstring("unknown built-in")))
|
|
})
|
|
|
|
It("Validate rejects an unanchored custom pattern", func() {
|
|
c := &ModelConfig{Name: "x", Backend: "pattern"}
|
|
c.PIIDetection.Patterns = []PIIPattern{{Name: "EMAILish", Match: `[\w.]+@[\w.]+\.\w+`}}
|
|
_, err := c.Validate()
|
|
Expect(err).To(MatchError(ContainSubstring("pattern \"EMAILish\"")))
|
|
})
|
|
})
|
|
|
|
var _ = Describe("ModelConfig alias", func() {
|
|
It("reports IsAlias when alias is set", func() {
|
|
c := ModelConfig{Name: "gpt-4", Alias: "my-llama-3"}
|
|
Expect(c.IsAlias()).To(BeTrue())
|
|
Expect(ModelConfig{Name: "real"}.IsAlias()).To(BeFalse())
|
|
})
|
|
|
|
It("validates a minimal alias config", func() {
|
|
c := ModelConfig{Name: "gpt-4", Alias: "my-llama-3"}
|
|
ok, err := c.Validate()
|
|
Expect(err).ToNot(HaveOccurred())
|
|
Expect(ok).To(BeTrue())
|
|
})
|
|
|
|
It("rejects an alias pointing to itself", func() {
|
|
c := ModelConfig{Name: "loop", Alias: "loop"}
|
|
ok, err := c.Validate()
|
|
Expect(ok).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("itself")))
|
|
})
|
|
|
|
It("rejects an alias that also sets a backend", func() {
|
|
c := ModelConfig{Name: "gpt-4", Alias: "my-llama-3", Backend: "llama-cpp"}
|
|
ok, err := c.Validate()
|
|
Expect(ok).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("pure redirect")))
|
|
})
|
|
|
|
It("rejects artifacts on alias configurations", func() {
|
|
cfg := ModelConfig{
|
|
Name: "alias-name",
|
|
Alias: "target-name",
|
|
Artifacts: []modelartifacts.Spec{{
|
|
Source: modelartifacts.Source{Type: "huggingface", Repo: "owner/repo"},
|
|
}},
|
|
}
|
|
valid, err := cfg.Validate()
|
|
Expect(valid).To(BeFalse())
|
|
Expect(err).To(MatchError(ContainSubstring("alias")))
|
|
})
|
|
})
|