mirror of
https://github.com/mudler/LocalAI.git
synced 2026-06-01 20:53:15 -04:00
* feat(distributed): add per-request node ID context holder Introduce pkg/distributedhdr, a leaf package carrying a per-request *atomic.Value holder for the picked worker node ID from the SmartRouter (core/services/nodes) up to the HTTP response writer wrapper (core/http/middleware). Avoids the import cycle that a shared key in either consumer would create. Exposes NewHolder, WithHolder, Holder, Stamp, Load, Inherit. The holder is atomic.Value so cross-goroutine publish from the router to the response writer wrapper is race-clean. Assisted-by: Claude:claude-opus-4-7[1m] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * feat(distributed): add ExposeNodeHeader middleware + response writer wrapper New ApplicationConfig.ExposeNodeHeader bool + --expose-node-header CLI flag / LOCALAI_EXPOSE_NODE_HEADER env var (default off; the node ID reveals internal topology and is opt-in). The middleware creates a per-request *atomic.Value holder, attaches it to c.Request().Context() via distributedhdr.WithHolder, and wraps c.Response().Writer with a custom http.ResponseWriter that sets the X-LocalAI-Node header on first Write / WriteHeader / Flush by reading the holder. Implements http.Flusher, http.Hijacker, Unwrap so it composes cleanly with Echo and http.NewResponseController. request.go propagates the holder onto derived contexts via distributedhdr.Inherit so the holder survives the correlation-ID context replacement. Unit + race-clean concurrency + integration specs. Assisted-by: Claude:claude-opus-4-7[1m] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * feat(distributed): stamp node ID in router and wire middleware to inference routes ModelRouterAdapter.Route stamps the picked node ID into the per-request holder via distributedhdr.Stamp(ctx, result.Node.ID) right after replica selection. Wire ExposeNodeHeader middleware to: - OpenAI chat/completion/embeddings + audio transcriptions/speech + image generations/inpainting - Anthropic /v1/messages - Ollama /api/chat, /api/generate, /api/embed, /api/embeddings - Jina /v1/rerank - LocalAI /v1/vad The middleware's wrapper reads the holder on first byte and sets the X-LocalAI-Node response header before delegating to the underlying writer. Per-request scope means no race under concurrent multi-replica routing. Assisted-by: Claude:claude-opus-4-7[1m] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(distributed): thread request context through backend Load + cover ctx propagation Five non-OpenAI backend helpers were silently using app.Context instead of the request context for the gRPC backend call: transcription, TTS, image generation, rerank, VAD. Effect: distributedhdr.Stamp in the router callback was a silent no-op for these paths, AND client cancellation didn't propagate to in-flight inference. Thread c.Request().Context() (or the equivalent input.Context after the request middleware has installed the correlation-ID derived context) through each helper and into ModelOptions via model.WithContext(ctx). ImageGeneration's signature gains a leading ctx parameter; in-tree callers (openai image, openai inpainting, openai inpainting_test) are updated to match. ModelEmbedding gains a leading ctx parameter for the same reason; the openai and ollama embedding handlers pass the request context through. chat_stream_workers.go defers the initial role=assistant chunk emission until the first token callback so the wrapper's lazy X-LocalAI-Node lookup against the loader runs AFTER ml.Load has stamped the per-modelID node ID; semantically identical for clients (role still arrives before any text). Regression test core/backend/ctx_propagation_test.go pins ctx propagation for all five helpers. Docs updated to enumerate the full endpoint coverage of the --expose-node-header flag. Assisted-by: Claude:claude-opus-4-7[1m] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
118 lines
4.1 KiB
Go
118 lines
4.1 KiB
Go
package openai
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"math"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/mudler/LocalAI/core/backend"
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/core/http/middleware"
|
|
"github.com/mudler/LocalAI/pkg/model"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
// floatsToBase64 packs a float32 slice as little-endian bytes and returns a base64 string.
|
|
// This matches the OpenAI API encoding_format=base64 contract expected by the Node.js SDK.
|
|
func floatsToBase64(floats []float32) string {
|
|
buf := make([]byte, len(floats)*4)
|
|
for i, f := range floats {
|
|
binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(f))
|
|
}
|
|
return base64.StdEncoding.EncodeToString(buf)
|
|
}
|
|
|
|
// embeddingItem builds a schema.Item for an embedding, encoding as base64 when requested.
|
|
// The OpenAI Node.js SDK (v4+) sends encoding_format=base64 by default and expects a base64
|
|
// string in the response; returning a float array causes Buffer.from(array,'base64') to
|
|
// interpret each float as a single byte, yielding dims/4 values in Qdrant.
|
|
func embeddingItem(embeddings []float32, index int, encodingFormat string) schema.Item {
|
|
if encodingFormat == "base64" {
|
|
return schema.Item{EmbeddingBase64: floatsToBase64(embeddings), Index: index, Object: "embedding"}
|
|
}
|
|
return schema.Item{Embedding: embeddings, Index: index, Object: "embedding"}
|
|
}
|
|
|
|
// EmbeddingsEndpoint is the OpenAI Embeddings API endpoint https://platform.openai.com/docs/api-reference/embeddings
|
|
// @Summary Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
|
|
// @Tags embeddings
|
|
// @Param request body schema.OpenAIRequest true "query params"
|
|
// @Success 200 {object} schema.OpenAIResponse "Response"
|
|
// @Router /v1/embeddings [post]
|
|
func EmbeddingsEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, appConfig *config.ApplicationConfig) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
input, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST).(*schema.OpenAIRequest)
|
|
if !ok || input.Model == "" {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
config, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig)
|
|
if !ok || config == nil {
|
|
return echo.ErrBadRequest
|
|
}
|
|
|
|
xlog.Debug("Parameter Config", "config", config)
|
|
items := []schema.Item{}
|
|
|
|
for i, s := range config.InputToken {
|
|
// get the model function to call for the result
|
|
embedFn, err := backend.ModelEmbedding(input.Context, "", s, ml, *config, appConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
embeddings, err := embedFn()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
items = append(items, embeddingItem(embeddings, i, input.EncodingFormat))
|
|
}
|
|
|
|
for i, s := range config.InputStrings {
|
|
// get the model function to call for the result
|
|
embedFn, err := backend.ModelEmbedding(input.Context, s, []int{}, ml, *config, appConfig)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
embeddings, err := embedFn()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
items = append(items, embeddingItem(embeddings, i, input.EncodingFormat))
|
|
}
|
|
|
|
id := uuid.New().String()
|
|
created := int(time.Now().Unix())
|
|
resp := &schema.OpenAIResponse{
|
|
ID: id,
|
|
Created: created,
|
|
Model: input.Model, // we have to return what the user sent here, due to OpenAI spec.
|
|
Data: items,
|
|
Object: "list",
|
|
}
|
|
|
|
jsonResult, _ := json.Marshal(resp)
|
|
xlog.Debug("Response", "response", string(jsonResult))
|
|
|
|
// LocalAI's embeddings endpoint does not currently track per-call
|
|
// token counts (the gRPC Embedding RPC returns a vector, not a
|
|
// usage block), so we stamp with zeros. The point of stamping is
|
|
// that the billing pipeline still sees the request and emits the
|
|
// localai_billed_requests_total counter; without this the call
|
|
// would be silently dropped by the unrecorded-counter path. When
|
|
// embeddings learn to report usage, swap the zeros for real counts.
|
|
middleware.StampUsage(c, input.Model, 0, 0)
|
|
|
|
// Return the prediction in the response body
|
|
return c.JSON(200, resp)
|
|
}
|
|
}
|