mirror of
https://github.com/mudler/LocalAI.git
synced 2026-09-13 06:45:26 -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>
414 lines
15 KiB
Go
414 lines
15 KiB
Go
package routes
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/mudler/LocalAI/core/application"
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/core/http/auth"
|
|
"github.com/mudler/LocalAI/core/http/endpoints/localai"
|
|
"github.com/mudler/LocalAI/core/http/middleware"
|
|
"github.com/mudler/LocalAI/core/services/routing/router"
|
|
)
|
|
|
|
// RegisterMiddlewareRoutes wires the routing-module admin surface that
|
|
// powers the /app/middleware React page. Two endpoints:
|
|
//
|
|
// - GET /api/middleware/status — single round-trip aggregator. Lists
|
|
// PII patterns with current actions, each model's resolved
|
|
// enabled/override state, recent event count, and a router status
|
|
// stub (until subsystem 2 lands).
|
|
// - GET /api/router/status — placeholder that the page renders for
|
|
// the Routing tab. Returns { configured: false, models: [] } today;
|
|
// subsystem 2 fills it in.
|
|
//
|
|
// Both are admin-only when auth is on. In single-user (no-auth) mode
|
|
// the synthetic local user has Role: admin so the page works without
|
|
// extra config — same gating shape as the existing /api/usage/all.
|
|
func RegisterMiddlewareRoutes(e *echo.Echo, app *application.Application) {
|
|
e.GET("/api/middleware/status", adminOnly(app, func(c echo.Context) error {
|
|
piiSection := buildPIIStatus(app)
|
|
routerSection := buildRouterStatus(app)
|
|
mitmSection := buildMITMStatus(app)
|
|
admissionSection := buildAdmissionStatus(app)
|
|
|
|
return c.JSON(http.StatusOK, map[string]any{
|
|
"pii": piiSection,
|
|
"router": routerSection,
|
|
"mitm": mitmSection,
|
|
"admission": admissionSection,
|
|
})
|
|
}))
|
|
|
|
e.GET("/api/router/status", func(c echo.Context) error {
|
|
// Read-only — admins want to see classifier configurations
|
|
// without authenticating, same as /api/pii/patterns.
|
|
return c.JSON(http.StatusOK, buildRouterStatus(app))
|
|
})
|
|
|
|
e.GET("/api/middleware/proxy-ca.crt", func(c echo.Context) error {
|
|
// The CA cert is the public half — safe to expose without
|
|
// auth so clients can curl it during initial setup. The
|
|
// private key never leaves disk and is mode 0600. Returning
|
|
// 404 (rather than 500) when MITM is disabled keeps the
|
|
// endpoint a clean "is this feature available?" probe.
|
|
ca := app.MITMCA()
|
|
if ca == nil {
|
|
return c.JSON(http.StatusNotFound, map[string]string{
|
|
"error": "mitm proxy is not enabled (set --mitm-listen to start it)",
|
|
})
|
|
}
|
|
c.Response().Header().Set("Content-Type", "application/x-pem-file")
|
|
c.Response().Header().Set("Content-Disposition", `attachment; filename="localai-mitm-ca.crt"`)
|
|
return c.Blob(http.StatusOK, "application/x-pem-file", ca.PublicCertPEM())
|
|
})
|
|
|
|
// Decision logs may include user ids — admin-only when auth is
|
|
// on; the synthetic local user has admin so single-user mode
|
|
// works.
|
|
e.GET("/api/router/decisions", adminOnly(app, func(c echo.Context) error {
|
|
store := app.RouterDecisions()
|
|
if store == nil {
|
|
return c.JSON(http.StatusOK, map[string]any{"decisions": []any{}})
|
|
}
|
|
|
|
limit := 100
|
|
if v := c.QueryParam("limit"); v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
|
limit = n
|
|
}
|
|
}
|
|
decisions, err := store.List(c.Request().Context(), router.DecisionListQuery{
|
|
CorrelationID: c.QueryParam("correlation_id"),
|
|
UserID: c.QueryParam("user_id"),
|
|
RouterModel: c.QueryParam("router_model"),
|
|
Limit: limit,
|
|
})
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list decisions"})
|
|
}
|
|
return c.JSON(http.StatusOK, map[string]any{"decisions": decisions})
|
|
}))
|
|
|
|
// GET /api/router/cache/stats — embedding-cache counters per
|
|
// router model. Read-only; same auth gating as /api/router/status
|
|
// (any authenticated user can see configuration). Omitted entries
|
|
// indicate "embedding cache not enabled for this router".
|
|
e.GET("/api/router/cache/stats", func(c echo.Context) error {
|
|
reg := app.RouterClassifierRegistry()
|
|
stats := map[string]router.EmbeddingCacheStats{}
|
|
if reg != nil {
|
|
stats = reg.EmbeddingCacheStatsByRouter()
|
|
}
|
|
return c.JSON(http.StatusOK, map[string]any{"caches": stats})
|
|
})
|
|
|
|
// POST /api/router/decide — programmatic decision-oracle endpoint
|
|
// for external routers. Runs the same classifier that the in-band
|
|
// RouteModel middleware would have run and returns the chosen
|
|
// label set + candidate model, without rewriting the request,
|
|
// forwarding it, or recording a row in the decision store.
|
|
//
|
|
// Admin-only — same gating as /api/router/decisions. The risk
|
|
// surface is "runs classifier inference on arbitrary input", which
|
|
// matches the decision-log endpoint's gating.
|
|
decideHandler := localai.RouterDecideEndpoint(
|
|
app.ModelConfigLoader(),
|
|
app.ApplicationConfig(),
|
|
middleware.NewClassifierDeps(app),
|
|
)
|
|
e.POST("/api/router/decide", adminOnly(app, decideHandler))
|
|
|
|
// Router KNN corpus management. Corpus input/curation is API-only
|
|
// by design — entries can contain example user content, so the UI
|
|
// never sends or renders them; the stats endpoint returns label
|
|
// counts only. Admin-gated like /api/router/decide: seeding the
|
|
// corpus changes routing behaviour and Add runs embedding
|
|
// inference on arbitrary input.
|
|
corpusDeps := middleware.NewClassifierDeps(app)
|
|
corpusAdd := localai.RouterCorpusAddEndpoint(app.ModelConfigLoader(), app.ApplicationConfig(), app.RouterCorpus(), corpusDeps)
|
|
corpusStats := localai.RouterCorpusStatsEndpoint(app.ModelConfigLoader(), app.ApplicationConfig(), app.RouterCorpus())
|
|
corpusClear := localai.RouterCorpusClearEndpoint(app.ModelConfigLoader(), app.ApplicationConfig(), app.RouterCorpus(), corpusDeps)
|
|
e.POST("/api/router/:name/corpus", adminOnly(app, corpusAdd))
|
|
e.GET("/api/router/:name/corpus/stats", adminOnly(app, corpusStats))
|
|
e.DELETE("/api/router/:name/corpus", adminOnly(app, corpusClear))
|
|
}
|
|
|
|
// adminOnly wraps a handler with the admin gate every routing-module
|
|
// endpoint shares: 401 when unauthenticated, 403 for non-admins. The
|
|
// synthetic local user has Role: admin, so single-user (no-auth) mode
|
|
// passes without extra config — same shape as /api/usage/all.
|
|
func adminOnly(app *application.Application, h echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
viewer := resolveUsageUser(c, app)
|
|
if viewer == nil {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "not authenticated"})
|
|
}
|
|
if viewer.Role != auth.RoleAdmin {
|
|
return c.JSON(http.StatusForbidden, map[string]string{"error": "admin access required"})
|
|
}
|
|
return h(c)
|
|
}
|
|
}
|
|
|
|
// buildRouterStatus inventories every model that declares a Router
|
|
// block and reports their classifiers + candidate tables. Reads from
|
|
// the same loader the RouteModel middleware uses so the admin page
|
|
// agrees with what's actually live in the request path.
|
|
func buildRouterStatus(app *application.Application) map[string]any {
|
|
models := []map[string]any{}
|
|
hasAny := false
|
|
cacheStats := map[string]router.EmbeddingCacheStats{}
|
|
if reg := app.RouterClassifierRegistry(); reg != nil {
|
|
cacheStats = reg.EmbeddingCacheStatsByRouter()
|
|
}
|
|
for _, cfg := range app.ModelConfigLoader().GetAllModelsConfigs() {
|
|
if !cfg.HasRouter() {
|
|
continue
|
|
}
|
|
hasAny = true
|
|
candidates := make([]map[string]any, 0, len(cfg.Router.Candidates))
|
|
for _, ca := range cfg.Router.Candidates {
|
|
candidates = append(candidates, map[string]any{
|
|
"model": ca.Model,
|
|
"labels": ca.Labels,
|
|
})
|
|
}
|
|
policies := make([]map[string]any, 0, len(cfg.Router.Policies))
|
|
for _, p := range cfg.Router.Policies {
|
|
policies = append(policies, map[string]any{
|
|
"label": p.Label,
|
|
"description": p.Description,
|
|
})
|
|
}
|
|
classifier := cfg.Router.Classifier
|
|
if classifier == "" {
|
|
classifier = router.ClassifierScore
|
|
}
|
|
entry := map[string]any{
|
|
"name": cfg.Name,
|
|
"classifier": classifier,
|
|
"policies": policies,
|
|
"candidates": candidates,
|
|
"fallback": cfg.Router.Fallback,
|
|
}
|
|
if ec := cfg.Router.EmbeddingCache; ec != nil {
|
|
cacheEntry := map[string]any{
|
|
"embedding_model": ec.EmbeddingModel,
|
|
"similarity_threshold": ec.SimilarityThreshold,
|
|
"confidence_threshold": ec.ConfidenceThreshold,
|
|
"store_name": ec.StoreName,
|
|
}
|
|
if s, ok := cacheStats[cfg.Name]; ok {
|
|
cacheEntry["stats"] = s
|
|
}
|
|
entry["embedding_cache"] = cacheEntry
|
|
}
|
|
if kc := cfg.Router.KNN; kc != nil {
|
|
storeName := kc.ResolvedStoreName(cfg.Name)
|
|
knnEntry := map[string]any{
|
|
"embedding_model": kc.EmbeddingModel,
|
|
"k": kc.K,
|
|
"similarity_threshold": kc.SimilarityThreshold,
|
|
"vote_threshold": kc.VoteThreshold,
|
|
"store_name": storeName,
|
|
}
|
|
// Corpus stats are counts only — entry texts never reach
|
|
// the UI (or any API surface).
|
|
if s, err := app.RouterCorpus().Stats(storeName); err == nil {
|
|
knnEntry["corpus"] = map[string]any{
|
|
"total": s.Total,
|
|
"label_counts": s.LabelCounts,
|
|
}
|
|
}
|
|
entry["knn"] = knnEntry
|
|
}
|
|
models = append(models, entry)
|
|
}
|
|
|
|
recentCount := 0
|
|
if store := app.RouterDecisions(); store != nil {
|
|
if n, err := store.Count(context.Background()); err == nil {
|
|
recentCount = n
|
|
}
|
|
}
|
|
|
|
out := map[string]any{
|
|
"configured": hasAny,
|
|
"models": models,
|
|
"recent_decision_count": recentCount,
|
|
"available_classifiers": router.AllClassifiers,
|
|
}
|
|
if !hasAny {
|
|
out["note"] = "No router models configured. Add a `router:` block to a model YAML to enable intelligent routing."
|
|
}
|
|
return out
|
|
}
|
|
|
|
func buildMITMStatus(app *application.Application) map[string]any {
|
|
srv := app.MITMServer()
|
|
ca := app.MITMCA()
|
|
cfg := app.ApplicationConfig()
|
|
|
|
// MITM-bound model configs — anything with an mitm: block, even
|
|
// if hosts is empty. Surfaces a "fresh from template" config the
|
|
// admin started but hasn't yet attached a host to.
|
|
mitmModels := []map[string]any{}
|
|
for _, mc := range app.ModelConfigLoader().GetModelConfigsByFilter(func(_ string, c *config.ModelConfig) bool {
|
|
return len(c.MITM.Hosts) > 0
|
|
}) {
|
|
mitmModels = append(mitmModels, map[string]any{
|
|
"name": mc.Name,
|
|
"hosts": mc.MITM.Hosts,
|
|
"pii_enabled": mc.PIIIsEnabled(),
|
|
"backend": mc.Backend,
|
|
})
|
|
}
|
|
|
|
out := map[string]any{
|
|
"running": srv != nil,
|
|
"listen_addr": "",
|
|
"configured_addr": cfg.MITMListen,
|
|
"host_owners": app.MITMHostOwners(),
|
|
"host_conflicts": app.MITMHostConflicts(),
|
|
"models": mitmModels,
|
|
"ca_available": ca != nil,
|
|
"ca_cert_url": "",
|
|
}
|
|
if conflicts := app.MITMHostConflicts(); len(conflicts) > 0 {
|
|
out["error"] = "MITM listener disabled: duplicate host claims across model configs (see host_conflicts). Resolve by editing the conflicting model YAMLs so each host appears in at most one mitm.hosts list."
|
|
}
|
|
if srv != nil {
|
|
out["listen_addr"] = srv.Addr()
|
|
}
|
|
if ca != nil {
|
|
out["ca_cert_url"] = "/api/middleware/proxy-ca.crt"
|
|
}
|
|
return out
|
|
}
|
|
|
|
// buildAdmissionStatus reports each model's MaxConcurrent ceiling
|
|
// and current in-flight count. Models with no limit set are
|
|
// omitted — the dashboard view is "what's gated", not "every
|
|
// model in the loader".
|
|
func buildAdmissionStatus(app *application.Application) map[string]any {
|
|
limiter := app.AdmissionLimiter()
|
|
models := []map[string]any{}
|
|
if limiter == nil {
|
|
return map[string]any{"models": models}
|
|
}
|
|
for _, cfg := range app.ModelConfigLoader().GetAllModelsConfigs() {
|
|
if cfg.Limits.MaxConcurrent <= 0 {
|
|
continue
|
|
}
|
|
models = append(models, map[string]any{
|
|
"name": cfg.Name,
|
|
"max_concurrent": cfg.Limits.MaxConcurrent,
|
|
"retry_after_seconds": cfg.Limits.RetryAfterSeconds,
|
|
"in_flight": limiter.InFlight(cfg.Name),
|
|
})
|
|
}
|
|
return map[string]any{"models": models}
|
|
}
|
|
|
|
// buildPIIStatus builds the pii section of /api/middleware/status. It
|
|
// walks every model config and reports the resolved enabled state plus
|
|
// the NER detector models each one references — that's what the admin
|
|
// page renders so the operator can see at a glance which models are
|
|
// protected and by which detectors. The detection policy itself
|
|
// (entity→action, min score) lives on each detector model's
|
|
// pii_detection block.
|
|
func buildPIIStatus(app *application.Application) map[string]any {
|
|
appCfg := app.ApplicationConfig()
|
|
models := []map[string]any{}
|
|
for _, cfg := range app.ModelConfigLoader().GetAllModelsConfigs() {
|
|
// Only list models PII filtering can actually apply to (reachable
|
|
// through a text-accepting endpoint with a PII adapter wired).
|
|
// Skips VAD/STT/embedding/image-only models and the token_classify
|
|
// detector models themselves, which are the filters, not consumers.
|
|
if !cfg.PIIFilterApplies() {
|
|
continue
|
|
}
|
|
explicit := cfg.PII.Enabled != nil
|
|
ownDetectors := cfg.PIIDetectors()
|
|
// Resolve through the shared policy so the table reflects the EFFECTIVE
|
|
// state, including the instance-wide default detector — what the
|
|
// request path actually does.
|
|
enabled, detectors := app.ResolvePIIPolicy(&cfg)
|
|
|
|
entry := map[string]any{
|
|
"name": cfg.Name,
|
|
"backend": cfg.Backend,
|
|
"enabled": enabled,
|
|
"detectors": detectors,
|
|
"explicit": explicit,
|
|
// Why is this on? backend default (cloud-proxy) vs an explicit YAML
|
|
// toggle. Helps admins understand the resolved state without
|
|
// reading source.
|
|
"default_for_backend": !explicit && cfg.Backend == "cloud-proxy",
|
|
// The detectors came from the global default, not this model's YAML.
|
|
"detectors_from_default": enabled && len(ownDetectors) == 0 && len(detectors) > 0,
|
|
}
|
|
models = append(models, entry)
|
|
}
|
|
|
|
// Detector models: the token_classify "filter" models themselves (NER and
|
|
// in-process pattern matchers), which PIIFilterApplies deliberately omits
|
|
// from the consumer list above. The Filtering tab renders these as a table
|
|
// with a per-row toggle marking membership in the instance-wide default
|
|
// detector set, so admins manage defaults without retyping model names.
|
|
defaultSet := map[string]bool{}
|
|
for _, d := range appCfg.PIIDefaultDetectors {
|
|
defaultSet[d] = true
|
|
}
|
|
detectorModels := []map[string]any{}
|
|
for _, cfg := range app.ModelConfigLoader().GetAllModelsConfigs() {
|
|
if !cfg.HasUsecases(config.FLAG_TOKEN_CLASSIFY) {
|
|
continue
|
|
}
|
|
typ := "ner"
|
|
if cfg.IsPatternDetector() {
|
|
typ = "pattern"
|
|
}
|
|
detectorModels = append(detectorModels, map[string]any{
|
|
"name": cfg.Name,
|
|
"backend": cfg.Backend,
|
|
"type": typ,
|
|
// Whether this detector is in the instance-wide default set.
|
|
"default": defaultSet[cfg.Name],
|
|
})
|
|
delete(defaultSet, cfg.Name)
|
|
}
|
|
// Surface any default detector that names a model that is no longer loaded
|
|
// (or lost the token_classify usecase) so the admin can still toggle it off.
|
|
for name := range defaultSet {
|
|
detectorModels = append(detectorModels, map[string]any{
|
|
"name": name,
|
|
"backend": "",
|
|
"type": "unknown",
|
|
"default": true,
|
|
"missing": true,
|
|
})
|
|
}
|
|
|
|
recentCount := 0
|
|
if app.PIIEvents() != nil {
|
|
if n, err := app.PIIEvents().Count(context.Background()); err == nil {
|
|
recentCount = n
|
|
}
|
|
}
|
|
|
|
return map[string]any{
|
|
"enabled_globally": true,
|
|
"default_enabled_for_backends": []string{"cloud-proxy"},
|
|
"models": models,
|
|
"detector_models": detectorModels,
|
|
"recent_event_count": recentCount,
|
|
// Instance-wide default policy (the Default PII policy editor).
|
|
"default_detectors": appCfg.PIIDefaultDetectors,
|
|
}
|
|
}
|