mirror of
https://github.com/mudler/LocalAI.git
synced 2026-07-08 07:18:31 -04:00
Squashed feat/pii-ner-tier-engine rebased onto master (was 45 commits; see backup/pii-ner-tier-engine-prerebase). Net change: - privacy-filter.cpp: standalone GGML engine for the openai-privacy-filter PII/NER token classifier, wired as a LocalAI gRPC backend (CPU/CUDA/Vulkan). TokenClassify moves off the patched llama.cpp path onto this backend. - PII filter reworked to be NER-centric (encoder/NER detection tier scanning whole conversations as one document), with a recreated bounded restricted- regex secret-matching pattern detector tier alongside it (per-model pii_detection.builtins / .patterns + core/services/routing/piipattern). - Detection labelled by source (ner vs pattern); backend trace / confidence / debug observability; analyze/redact exposed as a synchronous API. - Instance-wide default detector policy + per-usecase default-on; request filtering extended to completions, embeddings, edits & Ollama. - React UI: NER-centric PII editor, detector-models table, pattern/builtins editor, middleware default-policy UI. - Gallery: privacy-filter-multilingual token-classify model + NER install filter; token_classify known_usecase; batch sized to context for NER models. privacy-filter backend registered in the backend gallery (cpu/vulkan/cuda-13 meta + image entries with a capabilities map) matching its CI matrix jobs, and an /import-model auto-detect importer (PrivacyFilterImporter, narrow privacy-filter GGUF detection) replacing the prior pref-only registration. Reconciled against master's independent evolution: - Dropped master's PIIPatternOverrides feature (global-pattern runtime overrides + /api/pii/patterns API + runtime_settings.json persistence). The per-model NER + pattern-detector design supersedes it; it was built on the global redactor pattern set this branch replaced. - Reverted the llama.cpp Score carry-patch (0006-server-task-type-score): removed the patch and restored master's grpc-server.cpp Score RPC (direct llama_decode, slot-loop bypass) and LLAMA_VERSION pin, plus master's model_config validation forbidding score + chat/completion/embeddings on llama-cpp. token_classify is unaffected (it runs on the privacy-filter backend, not llama-cpp). Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Richard Palethorpe <io@richiejp.com>
178 lines
6.9 KiB
Go
178 lines
6.9 KiB
Go
package routes
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/mudler/LocalAI/core/application"
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/core/http/endpoints/ollama"
|
|
"github.com/mudler/LocalAI/core/http/middleware"
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
"github.com/mudler/LocalAI/core/services/routing/pii"
|
|
"github.com/mudler/LocalAI/core/services/routing/piiadapter"
|
|
"github.com/mudler/LocalAI/pkg/distributedhdr"
|
|
)
|
|
|
|
func RegisterOllamaRoutes(app *echo.Echo,
|
|
re *middleware.RequestExtractor,
|
|
application *application.Application,
|
|
) {
|
|
traceMiddleware := middleware.TraceMiddleware(application)
|
|
usageMiddleware := middleware.UsageMiddleware(application.StatsRecorder(), application.FallbackUser())
|
|
nodeHeaderMiddleware := middleware.ExposeNodeHeader(application.ApplicationConfig())
|
|
|
|
// Chat endpoint: POST /api/chat
|
|
chatHandler := ollama.ChatEndpoint(
|
|
application.ModelConfigLoader(),
|
|
application.ModelLoader(),
|
|
application.TemplatesEvaluator(),
|
|
application.ApplicationConfig(),
|
|
)
|
|
chatMiddleware := []echo.MiddlewareFunc{
|
|
nodeHeaderMiddleware,
|
|
usageMiddleware,
|
|
traceMiddleware,
|
|
re.BuildFilteredFirstAvailableDefaultModel(config.BuildUsecaseFilterFn(config.FLAG_CHAT)),
|
|
re.SetModelAndConfig(func() schema.LocalAIRequest { return new(schema.OllamaChatRequest) }),
|
|
setOllamaChatRequestContext(application.ApplicationConfig()),
|
|
pii.RequestMiddleware(application.PIIRedactor(), application.PIIEvents(), piiadapter.OllamaChat(), application.FallbackUser(), pii.WithNERResolver(application.PIINERResolver()), pii.WithPolicyResolver(application.PIIPolicyResolver())),
|
|
}
|
|
app.POST("/api/chat", chatHandler, chatMiddleware...)
|
|
|
|
// Generate endpoint: POST /api/generate
|
|
generateHandler := ollama.GenerateEndpoint(
|
|
application.ModelConfigLoader(),
|
|
application.ModelLoader(),
|
|
application.TemplatesEvaluator(),
|
|
application.ApplicationConfig(),
|
|
)
|
|
generateMiddleware := []echo.MiddlewareFunc{
|
|
nodeHeaderMiddleware,
|
|
usageMiddleware,
|
|
traceMiddleware,
|
|
re.BuildFilteredFirstAvailableDefaultModel(config.BuildUsecaseFilterFn(config.FLAG_CHAT)),
|
|
re.SetModelAndConfig(func() schema.LocalAIRequest { return new(schema.OllamaGenerateRequest) }),
|
|
setOllamaGenerateRequestContext(application.ApplicationConfig()),
|
|
pii.RequestMiddleware(application.PIIRedactor(), application.PIIEvents(), piiadapter.OllamaGenerate(), application.FallbackUser(), pii.WithNERResolver(application.PIINERResolver()), pii.WithPolicyResolver(application.PIIPolicyResolver())),
|
|
}
|
|
app.POST("/api/generate", generateHandler, generateMiddleware...)
|
|
|
|
// Embed endpoints: POST /api/embed and /api/embeddings
|
|
embedHandler := ollama.EmbedEndpoint(
|
|
application.ModelConfigLoader(),
|
|
application.ModelLoader(),
|
|
application.ApplicationConfig(),
|
|
)
|
|
embedMiddleware := []echo.MiddlewareFunc{
|
|
nodeHeaderMiddleware,
|
|
usageMiddleware,
|
|
traceMiddleware,
|
|
re.BuildFilteredFirstAvailableDefaultModel(config.BuildUsecaseFilterFn(config.FLAG_EMBEDDINGS)),
|
|
re.SetModelAndConfig(func() schema.LocalAIRequest { return new(schema.OllamaEmbedRequest) }),
|
|
pii.RequestMiddleware(application.PIIRedactor(), application.PIIEvents(), piiadapter.OllamaEmbed(), application.FallbackUser(), pii.WithNERResolver(application.PIINERResolver()), pii.WithPolicyResolver(application.PIIPolicyResolver())),
|
|
}
|
|
app.POST("/api/embed", embedHandler, embedMiddleware...)
|
|
app.POST("/api/embeddings", embedHandler, embedMiddleware...)
|
|
|
|
// Model management endpoints (no model-specific middleware needed)
|
|
app.GET("/api/tags", ollama.ListModelsEndpoint(application.ModelConfigLoader(), application.ModelLoader()))
|
|
app.HEAD("/api/tags", ollama.ListModelsEndpoint(application.ModelConfigLoader(), application.ModelLoader()))
|
|
app.POST("/api/show", ollama.ShowModelEndpoint(application.ModelConfigLoader()))
|
|
app.GET("/api/ps", ollama.ListRunningEndpoint(application.ModelConfigLoader(), application.ModelLoader()))
|
|
app.GET("/api/version", ollama.VersionEndpoint())
|
|
app.HEAD("/api/version", ollama.VersionEndpoint())
|
|
}
|
|
|
|
// RegisterOllamaRootEndpoint registers the Ollama "/" health check.
|
|
// This is separate because it conflicts with the web UI and is gated behind a CLI flag.
|
|
func RegisterOllamaRootEndpoint(app *echo.Echo) {
|
|
app.GET("/", ollama.HeartbeatEndpoint())
|
|
app.HEAD("/", ollama.HeartbeatEndpoint())
|
|
}
|
|
|
|
// setOllamaChatRequestContext sets up context and cancellation for Ollama chat requests
|
|
func setOllamaChatRequestContext(appConfig *config.ApplicationConfig) echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
input, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST).(*schema.OllamaChatRequest)
|
|
if !ok || input.Model == "" {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
cfg, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig)
|
|
if !ok || cfg == nil {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
correlationID := uuid.New().String()
|
|
c.Response().Header().Set("X-Correlation-ID", correlationID)
|
|
|
|
reqCtx := c.Request().Context()
|
|
c1, cancel := context.WithCancel(appConfig.Context)
|
|
stop := context.AfterFunc(reqCtx, cancel)
|
|
defer func() {
|
|
stop()
|
|
cancel()
|
|
}()
|
|
|
|
ctxWithCorrelationID := context.WithValue(c1, middleware.CorrelationIDKey, correlationID)
|
|
ctxWithCorrelationID = distributedhdr.Inherit(ctxWithCorrelationID, reqCtx)
|
|
input.Context = ctxWithCorrelationID
|
|
input.Cancel = cancel
|
|
|
|
if cfg.Model == "" {
|
|
cfg.Model = input.Model
|
|
}
|
|
|
|
c.Set(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST, input)
|
|
c.Set(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG, cfg)
|
|
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|
|
|
|
// setOllamaGenerateRequestContext sets up context and cancellation for Ollama generate requests
|
|
func setOllamaGenerateRequestContext(appConfig *config.ApplicationConfig) echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
input, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST).(*schema.OllamaGenerateRequest)
|
|
if !ok || input.Model == "" {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
cfg, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig)
|
|
if !ok || cfg == nil {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
correlationID := uuid.New().String()
|
|
c.Response().Header().Set("X-Correlation-ID", correlationID)
|
|
|
|
reqCtx := c.Request().Context()
|
|
c1, cancel := context.WithCancel(appConfig.Context)
|
|
stop := context.AfterFunc(reqCtx, cancel)
|
|
defer func() {
|
|
stop()
|
|
cancel()
|
|
}()
|
|
|
|
ctxWithCorrelationID := context.WithValue(c1, middleware.CorrelationIDKey, correlationID)
|
|
ctxWithCorrelationID = distributedhdr.Inherit(ctxWithCorrelationID, reqCtx)
|
|
input.Ctx = ctxWithCorrelationID
|
|
input.Cancel = cancel
|
|
|
|
if cfg.Model == "" {
|
|
cfg.Model = input.Model
|
|
}
|
|
|
|
c.Set(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST, input)
|
|
c.Set(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG, cfg)
|
|
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|