Skip to content

Commit 00fcf69

Browse files
walcz-declaude
andauthored
fix: implement encoding_format=base64 for embeddings endpoint (#9135)
The OpenAI Node.js SDK v4+ sends encoding_format=base64 by default. LocalAI previously ignored this parameter and always returned a float JSON array, causing a silent data corruption bug in any Node.js client (AnythingLLM Desktop, LangChain.js, LlamaIndex.TS, …): // What the client does when it expects base64 but receives a float array: Buffer.from(floatArray, 'base64') Node.js treats a non-string first argument as a byte array — each float32 value is truncated to a single byte — and Float32Array then reads those bytes as floats, yielding dims/4 values. Vector databases (Qdrant, pgvector, …) then create collections with the wrong dimension, causing all similarity searches to fail silently. e.g. granite-embedding-107m (384 dims) → 96 stored in Qdrant jina-embeddings-v3 (1024 dims) → 256 stored in Qdrant Changes: - core/schema/prediction.go: add EncodingFormat string field to PredictionOptions so the request parameter is parsed and available throughout the request pipeline - core/schema/openai.go: add EmbeddingBase64 string field to Item; add MarshalJSON so the "embedding" JSON key emits either []float32 or a base64 string depending on which field is populated — all other Item consumers (image, video endpoints) are unaffected - core/http/endpoints/openai/embeddings.go: add floatsToBase64() which packs a float32 slice as little-endian bytes and base64-encodes it; add embeddingItem() helper; both InputToken and InputStrings loops now honour encoding_format=base64 Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 26384c5 commit 00fcf69

3 files changed

Lines changed: 60 additions & 5 deletions

File tree

core/http/endpoints/openai/embeddings.go

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package openai
22

33
import (
4+
"encoding/base64"
5+
"encoding/binary"
46
"encoding/json"
7+
"math"
58
"time"
69

710
"github.com/labstack/echo/v4"
@@ -16,6 +19,27 @@ import (
1619
"github.com/mudler/xlog"
1720
)
1821

22+
// floatsToBase64 packs a float32 slice as little-endian bytes and returns a base64 string.
23+
// This matches the OpenAI API encoding_format=base64 contract expected by the Node.js SDK.
24+
func floatsToBase64(floats []float32) string {
25+
buf := make([]byte, len(floats)*4)
26+
for i, f := range floats {
27+
binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(f))
28+
}
29+
return base64.StdEncoding.EncodeToString(buf)
30+
}
31+
32+
// embeddingItem builds a schema.Item for an embedding, encoding as base64 when requested.
33+
// The OpenAI Node.js SDK (v4+) sends encoding_format=base64 by default and expects a base64
34+
// string in the response; returning a float array causes Buffer.from(array,'base64') to
35+
// interpret each float as a single byte, yielding dims/4 values in Qdrant.
36+
func embeddingItem(embeddings []float32, index int, encodingFormat string) schema.Item {
37+
if encodingFormat == "base64" {
38+
return schema.Item{EmbeddingBase64: floatsToBase64(embeddings), Index: index, Object: "embedding"}
39+
}
40+
return schema.Item{Embedding: embeddings, Index: index, Object: "embedding"}
41+
}
42+
1943
// EmbeddingsEndpoint is the OpenAI Embeddings API endpoint https://platform.openai.com/docs/api-reference/embeddings
2044
// @Summary Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
2145
// @Param request body schema.OpenAIRequest true "query params"
@@ -47,7 +71,7 @@ func EmbeddingsEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, app
4771
if err != nil {
4872
return err
4973
}
50-
items = append(items, schema.Item{Embedding: embeddings, Index: i, Object: "embedding"})
74+
items = append(items, embeddingItem(embeddings, i, input.EncodingFormat))
5175
}
5276

5377
for i, s := range config.InputStrings {
@@ -61,7 +85,7 @@ func EmbeddingsEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, app
6185
if err != nil {
6286
return err
6387
}
64-
items = append(items, schema.Item{Embedding: embeddings, Index: i, Object: "embedding"})
88+
items = append(items, embeddingItem(embeddings, i, input.EncodingFormat))
6589
}
6690

6791
id := uuid.New().String()

core/schema/openai.go

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package schema
22

33
import (
44
"context"
5+
"encoding/json"
56

67
functions "github.com/mudler/LocalAI/pkg/functions"
78
)
@@ -37,15 +38,42 @@ type OpenAIUsage struct {
3738
}
3839

3940
type Item struct {
40-
Embedding []float32 `json:"embedding"`
41-
Index int `json:"index"`
42-
Object string `json:"object,omitempty"`
41+
Embedding []float32 `json:"-"`
42+
EmbeddingBase64 string `json:"-"`
43+
Index int `json:"index"`
44+
Object string `json:"object,omitempty"`
4345

4446
// Images
4547
URL string `json:"url,omitempty"`
4648
B64JSON string `json:"b64_json,omitempty"`
4749
}
4850

51+
// MarshalJSON serialises Item so that the "embedding" field is either a float array
52+
// or a base64 string depending on which field is populated. This satisfies the
53+
// OpenAI API encoding_format contract: the Node.js SDK (v4+) sends
54+
// encoding_format=base64 by default and expects a base64 string back.
55+
func (item Item) MarshalJSON() ([]byte, error) {
56+
type itemFields struct {
57+
Embedding interface{} `json:"embedding,omitempty"`
58+
Index int `json:"index"`
59+
Object string `json:"object,omitempty"`
60+
URL string `json:"url,omitempty"`
61+
B64JSON string `json:"b64_json,omitempty"`
62+
}
63+
f := itemFields{
64+
Index: item.Index,
65+
Object: item.Object,
66+
URL: item.URL,
67+
B64JSON: item.B64JSON,
68+
}
69+
if item.EmbeddingBase64 != "" {
70+
f.Embedding = item.EmbeddingBase64
71+
} else {
72+
f.Embedding = item.Embedding
73+
}
74+
return json.Marshal(f)
75+
}
76+
4977
type OpenAIResponse struct {
5078
Created int `json:"created,omitempty"`
5179
Object string `json:"object,omitempty"`

core/schema/prediction.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,7 @@ type PredictionOptions struct {
133133

134134
// RWKV (?)
135135
Tokenizer string `json:"tokenizer,omitempty" yaml:"tokenizer,omitempty"`
136+
137+
// Embedding encoding format: "float" (default) or "base64" (OpenAI Node.js SDK default)
138+
EncodingFormat string `json:"encoding_format,omitempty" yaml:"encoding_format,omitempty"`
136139
}

0 commit comments

Comments
 (0)