Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(embedding): move the wire formats into protocol packages, and correct the vendor facts (#3500)
lyingbug9030f556f2da
diff --git a/Makefile b/Makefileindex 862960a98..816ea5015 100644--- a/Makefile+++ b/Makefile@@ -116,7 +116,8 @@ test:# Run this after adding a vendor or editing any models.json..PHONY: model-catalog-checkmodel-catalog-check:- go test ./internal/models/parity/ ./internal/models/vendors/ ./internal/models/catalog/ ./internal/models/api/...+ go test ./internal/models/parity/ ./internal/models/vendors/ ./internal/models/catalog/ ./internal/models/api/... \+ ./internal/models/rerank/ ./internal/models/embedding/# Vendor catalog: report where our model metadata differs from models.dev.# Development aid only — nothing is fetched at runtime and nothing is writtendiff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vueindex 8a1f7a3fc..cdb63d964 100644--- a/frontend/src/components/ModelEditorDialog.vue+++ b/frontend/src/components/ModelEditorDialog.vue@@ -549,7 +549,11 @@</button><template v-if="advancedOpen">- <div class="form-item">+ <!--+ extra_config.api 只选对话协议。embedding / rerank 行不读它:+ embedding 的协议覆盖写在下面的 compat JSON 里("api"),取值是向量协议。+ -->+ <div v-if="isChatLike" class="form-item"><label class="form-label">{{ $t('model.editor.advanced.api.label') }}</label><t-select :model-value="formData.extraConfig.api || ''" clearable@update:model-value="(v: string) => setExtraConfig('api', v)">diff --git a/frontend/src/components/modelEditorFlow.test.ts b/frontend/src/components/modelEditorFlow.test.tsindex 764a52f9a..9ca219a93 100644--- a/frontend/src/components/modelEditorFlow.test.ts+++ b/frontend/src/components/modelEditorFlow.test.ts@@ -855,6 +855,15 @@ test('every vendor-declared string in the form goes through a locale resolver',assert.ok(template.includes('extraFieldDisplayPlaceholder('), 'placeholders must use the resolver')})+test('the chat protocol override is offered only on chat and vision rows', () => {+ const template = descriptor.template?.content ?? ''+ // extra_config.api names a chat protocol. Embedding and rerank rows never+ // read it, so offering it there is a control that silently does nothing.+ const select = /<div([^>]*)>\s*<label[^>]*>\{\{ \$t\('model\.editor\.advanced\.api\.label'\) \}\}/.exec(template)+ assert.ok(select, 'the protocol override should still be in the template')+ assert.match(select[1], /v-if="isChatLike"/, 'the protocol override must be scoped to chat-like rows')+})+test('extraFieldDisplayPlaceholder resolves the vendor placeholder for the active locale', async () => {const f = await fixture({ type: 'rerank', providers: catalogProviders })try {diff --git a/internal/application/service/knowledgebase_search.go b/internal/application/service/knowledgebase_search.goindex cca50c9a1..5970777fd 100644--- a/internal/application/service/knowledgebase_search.go+++ b/internal/application/service/knowledgebase_search.go@@ -42,7 +42,7 @@ func (s *knowledgeBaseService) GetQueryEmbedding(ctx context.Context, kbID strinreturn nil, err}- vector, err := embeddingModel.Embed(ctx, queryText)+ vector, err := embeddingModel.Embed(types.WithEmbedQuery(ctx), queryText)if err != nil {return nil, err}@@ -505,7 +505,7 @@ func (s *knowledgeBaseService) resolveQueryEmbedding(logger.Infof(ctx, "Embedding model retrieved: %v", embeddingModel)logger.Info(ctx, "Starting to generate query embedding")- queryEmbedding, err := embeddingModel.Embed(ctx, params.QueryText)+ queryEmbedding, err := embeddingModel.Embed(types.WithEmbedQuery(ctx), params.QueryText)if err != nil {logger.Errorf(ctx, "Failed to embed query text, query text: %s, error: %v", params.QueryText, err)return nil, errdiff --git a/internal/application/service/memory/vector.go b/internal/application/service/memory/vector.goindex f25112a4a..ad7038fe4 100644--- a/internal/application/service/memory/vector.go+++ b/internal/application/service/memory/vector.go@@ -209,7 +209,7 @@ func (s *Service) vectorSearch(if !ok {return nil, "vector_disabled"}- queryVector := s.embedText(ctx, modelID, query, embedTimeout)+ queryVector := s.embedText(types.WithEmbedQuery(ctx), modelID, query, embedTimeout)if len(queryVector) == 0 {return nil, "embed_failed"}diff --git a/internal/handler/model.go b/internal/handler/model.goindex b7b99daef..c2f2a330e 100644--- a/internal/handler/model.go+++ b/internal/handler/model.go@@ -759,7 +759,8 @@ func (h *ModelHandler) DeleteModel(c *gin.Context) {// validateCatalogParameters rejects protocol / compat overrides the catalog// cannot interpret (unknown extra_config.api, unknown compat keys, bad// reasoning levels) so a typo fails at save time instead of at the first-// chat call. Only chat and VLM rows carry these fields.+// call. Chat, VLM, embedding and rerank rows are checked; see+// catalog.ValidateRow.func validateCatalogParameters(name string, modelType types.ModelType, params *types.ModelParameters) error {return catalog.ValidateRow(name, modelType, params)}diff --git a/internal/handler/model_catalog.go b/internal/handler/model_catalog.goindex 461db25f1..a1f787967 100644--- a/internal/handler/model_catalog.go+++ b/internal/handler/model_catalog.go@@ -301,11 +301,12 @@ func (h *ModelHandler) ResolveModelCatalog(c *gin.Context) {// path this endpoint would have to guess.if resolved.Vendor.Endpoint != nil {endpointURL, query := resolved.Vendor.Endpoint(catalog.EndpointRequest{- BaseURL: resolved.BaseURL,- Model: resolved.RemoteModel,- ModelType: modelType,- API: resolved.API,- Extra: extra,+ BaseURL: resolved.BaseURL,+ Model: resolved.RemoteModel,+ ModelType: modelType,+ API: resolved.API,+ EmbeddingAPI: resolved.EmbeddingAPI,+ Extra: extra,})if endpointURL != "" {data["url"] = api.Endpoint{URL: endpointURL, Query: query}.Resolve("")diff --git a/internal/models/api/arkembeddings/client.go b/internal/models/api/arkembeddings/client.gonew file mode 100644index 000000000..e9bdffd3a--- /dev/null+++ b/internal/models/api/arkembeddings/client.go@@ -0,0 +1,106 @@+// Package arkembeddings implements Volcengine Ark's multimodal embedding+// shape: an input array of typed parts answering a single `data` object.+//+// The response is one fused vector for the whole input, not one per element —+// the reference's own example returns+//+// "data": { "embedding": [...], "object": "embedding" }+//+// for a request carrying a video, an image and a text. So a batch of N texts+// is N requests, which the vendor declares as a batch size of one rather than+// this package looping.+//+// It is the only embedding API Ark still documents. Its retired text+// endpoint (/api/v3/embeddings) was the plain OpenAI shape, which is why rows+// naming a text model resolve to that protocol instead.+//+// https://docs.volcengine.com/docs/ark/multimodal-vectorization-api+package arkembeddings++import (+ "context"+ "fmt"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+)++// Config is everything the client needs, already resolved by the catalog.+type Config struct {+ Endpoint api.Endpoint+ Settings catalog.EmbeddingsSettings+ Dimensions int+ Retry api.RetryPolicy+}++// Client talks Ark's multimodal embedding to one endpoint.+type Client struct {+ cfg Config+}++// New builds a client.+func New(cfg Config) *Client { return &Client{cfg: cfg} }++type response struct {+ Data struct {+ Embedding []float32 `json:"embedding"`+ Object string `json:"object"`+ } `json:"data"`+ Error *struct {+ Code string `json:"code"`+ Message string `json:"message"`+ } `json:"error,omitempty"`+}++// BuildRequestBody is the golden-test entry point.+func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {+ input := make([]any, 0, len(texts))+ for _, text := range texts {+ input = append(input, map[string]any{"type": "text", "text": text})+ }+ body := map[string]any{+ "model": c.cfg.Endpoint.Model,+ "input": input,+ }+ if c.cfg.Settings.SendEncodingFormat {+ body["encoding_format"] = "float"+ }+ if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {+ body[c.cfg.Settings.DimensionsField] = c.cfg.Dimensions+ }+ for k, v := range c.cfg.Settings.ExtraBody {+ if _, exists := body[k]; !exists {+ body[k] = v+ }+ }+ return body+}++// Embed vectorizes one input. The vendor fuses everything it is sent into a+// single vector, so the caller must hand over exactly one text; the shared+// batching layer guarantees that through the declared batch size.+func (c *Client) Embed(+ ctx context.Context, texts []string, kind api.EmbedInputType,+) ([][]float32, error) {+ if len(texts) != 1 {+ return nil, fmt.Errorf(+ "ark embedding fuses its input into one vector, so it takes one text per request, got %d",+ len(texts),+ )+ }+ var decoded response+ url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)+ err := c.cfg.Endpoint.PostJSONWithRetry(+ ctx, url, c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",+ )+ if err != nil {+ return nil, err+ }+ if decoded.Error != nil && decoded.Error.Message != "" {+ return nil, fmt.Errorf("ark embedding error %s: %s", decoded.Error.Code, decoded.Error.Message)+ }+ if len(decoded.Data.Embedding) == 0 {+ return nil, fmt.Errorf("ark embedding returned no vector")+ }+ return [][]float32{decoded.Data.Embedding}, nil+}diff --git a/internal/models/api/arkembeddings/golden_test.go b/internal/models/api/arkembeddings/golden_test.gonew file mode 100644index 000000000..9fe8a313e--- /dev/null+++ b/internal/models/api/arkembeddings/golden_test.go@@ -0,0 +1,89 @@+package arkembeddings++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// documentedResponse is the response example from Volcengine's multimodal+// embedding reference, copied from the rendered page:+// https://docs.volcengine.com/docs/ark/multimodal-vectorization-api+//+// `data` is one object, not an array. The request that produced it carried a+// video, an image and a text; the answer is a single fused vector.+const documentedResponse = `{+ "created": 1743575029,+ "data": {+ "embedding": [-0.123046875, -0.35546875, -0.318359375],+ "object": "embedding"+ },+ "id": "021743575029461acbe49a31755bec77b2f09448eb15fa9a88e47",+ "model": "doubao-embedding-vision-251215",+ "object": "list",+ "usage": {"prompt_tokens": 13987, "total_tokens": 13987}+}`++const endpoint = "/api/v3/embeddings/multimodal"++func newClient(url string, dims int) *Client {+ return New(Config{+ Endpoint: api.Endpoint{BaseURL: url, Model: "doubao-embedding-vision-251215", Auth: api.BearerAuth("k")},+ Settings: catalog.EmbeddingsSettings{+ SendEncodingFormat: true, DimensionsField: "dimensions",+ },+ Dimensions: dims,+ })+}++func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {+ body := newClient("https://ark.cn-beijing.volces.com"+endpoint, 2048).+ BuildRequestBody([]string{"视频和图片里有什么"}, api.EmbedDocument)+ assert.Equal(t, map[string]any{+ "model": "doubao-embedding-vision-251215",+ "encoding_format": "float",+ "dimensions": 2048,+ "input": []any{map[string]any{"type": "text", "text": "视频和图片里有什么"}},+ }, body)+}++func TestDecodesTheDocumentedResponse(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ var path string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path = r.URL.Path+ _, _ = w.Write([]byte(documentedResponse))+ }))+ defer server.Close()++ got, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{-0.123046875, -0.35546875, -0.318359375}}, got)+ assert.Equal(t, endpoint, path)+}++// The vendor fuses everything it is sent. Handing it two texts would return+// one vector for both, silently, so the protocol refuses rather than guess.+func TestRefusesMoreThanOneText(t *testing.T) {+ _, err := newClient("https://ark.cn-beijing.volces.com"+endpoint, 0).+ Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "one text per request")+}++func TestEmptyVectorIsAnError(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":{"embedding":[],"object":"embedding"}}`))+ }))+ defer server.Close()++ _, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)+ require.Error(t, err)+}diff --git a/internal/models/api/dashscopeembeddings/client.go b/internal/models/api/dashscopeembeddings/client.gonew file mode 100644index 000000000..358838233--- /dev/null+++ b/internal/models/api/dashscopeembeddings/client.go@@ -0,0 +1,94 @@+// Package dashscopeembeddings implements Alibaba Model Studio's native+// multimodal embedding shape: input.contents, parameters.dimension, and+// results under output.embeddings.+//+// Only the multimodal models use it. DashScope's text embeddings are served+// on the OpenAI-compatible endpoint, which is why the vendor's default+// protocol is the OpenAI one and the multimodal entries override it.+//+// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference+package dashscopeembeddings++import (+ "context"+ "fmt"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+)++// Config is everything the client needs, already resolved by the catalog.+type Config struct {+ Endpoint api.Endpoint+ Settings catalog.EmbeddingsSettings+ Dimensions int+ Retry api.RetryPolicy+}++// Client talks DashScope's native multimodal embedding to one endpoint.+type Client struct {+ cfg Config+}++// New builds a client.+func New(cfg Config) *Client { return &Client{cfg: cfg} }++type response struct {+ Output struct {+ Embeddings []struct {+ // The position field is `index`. DashScope's *text* embedding API+ // one page over calls it `text_index`, and decoding that name+ // here yields 0 for every element, collapsing a whole batch onto+ // slot 0 (Tencent/WeKnora#3484).+ Index int `json:"index"`+ Embedding []float32 `json:"embedding"`+ Type string `json:"type"`+ } `json:"embeddings"`+ } `json:"output"`+ Code string `json:"code"`+ Message string `json:"message"`+}++// BuildRequestBody is the golden-test entry point.+func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {+ contents := make([]any, 0, len(texts))+ for _, text := range texts {+ contents = append(contents, map[string]any{"text": text})+ }+ body := map[string]any{+ "model": c.cfg.Endpoint.Model,+ "input": map[string]any{"contents": contents},+ }+ // The width lives under parameters, not at the top level, and the field+ // is singular: `dimension`.+ if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {+ body["parameters"] = map[string]any{c.cfg.Settings.DimensionsField: c.cfg.Dimensions}+ }+ for k, v := range c.cfg.Settings.ExtraBody {+ if _, exists := body[k]; !exists {+ body[k] = v+ }+ }+ return body+}++// Embed vectorizes one batch.+func (c *Client) Embed(+ ctx context.Context, texts []string, kind api.EmbedInputType,+) ([][]float32, error) {+ var decoded response+ url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)+ err := c.cfg.Endpoint.PostJSONWithRetry(+ ctx, url, c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",+ )+ if err != nil {+ return nil, err+ }+ // DashScope reports some failures in the body with a 200.+ if decoded.Code != "" {+ return nil, fmt.Errorf("DashScope embedding error %s: %s", decoded.Code, decoded.Message)+ }+ return api.PlaceEmbeddings(len(texts), len(decoded.Output.Embeddings), func(i int) (int, []float32) {+ return decoded.Output.Embeddings[i].Index, decoded.Output.Embeddings[i].Embedding+ })+}diff --git a/internal/models/api/dashscopeembeddings/golden_test.go b/internal/models/api/dashscopeembeddings/golden_test.gonew file mode 100644index 000000000..1cc924515--- /dev/null+++ b/internal/models/api/dashscopeembeddings/golden_test.go@@ -0,0 +1,91 @@+package dashscopeembeddings++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// documentedResponse is the response example from DashScope's multimodal+// embedding reference, copied verbatim so the decoder is pinned against the+// vendor's own document:+// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference+//+// The position field is `index`. Reading `text_index` — the name used by+// DashScope's text embedding API — put a whole batch in slot 0 (#3484).+const documentedResponse = `{+ "output": {+ "embeddings": [+ {"index": 0, "embedding": [-0.026611328125, -0.016571044921875], "type": "text"},+ {"index": 1, "embedding": [0.051544189453125, 0.007717132568359375], "type": "text"}+ ]+ },+ "usage": {"input_tokens": 10, "total_tokens": 10},+ "request_id": "1fff9502-a6c5-9472-9ee1-73930fdd04c5"+}`++const endpoint = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"++func newClient(url string, dims int) *Client {+ return New(Config{+ Endpoint: api.Endpoint{BaseURL: url, Model: "tongyi-embedding-vision-plus", Auth: api.BearerAuth("k")},+ Settings: catalog.EmbeddingsSettings{DimensionsField: "dimension"},+ Dimensions: dims,+ })+}++func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {+ body := newClient("https://dashscope.aliyuncs.com"+endpoint, 1152).+ BuildRequestBody([]string{"a", "b"}, api.EmbedDocument)+ assert.Equal(t, map[string]any{+ "model": "tongyi-embedding-vision-plus",+ "input": map[string]any{"contents": []any{+ map[string]any{"text": "a"}, map[string]any{"text": "b"},+ }},+ // Under parameters, and singular.+ "parameters": map[string]any{"dimension": 1152},+ }, body)+}++func TestNoParametersWithoutARequestedWidth(t *testing.T) {+ body := newClient("https://dashscope.aliyuncs.com"+endpoint, 0).+ BuildRequestBody([]string{"a"}, api.EmbedDocument)+ assert.NotContains(t, body, "parameters")+}++func TestDecodesTheDocumentedResponse(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ var path string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path = r.URL.Path+ _, _ = w.Write([]byte(documentedResponse))+ }))+ defer server.Close()++ got, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{+ {-0.026611328125, -0.016571044921875},+ {0.051544189453125, 0.007717132568359375},+ }, got, "each vector must land in its own slot, by index")+ assert.Equal(t, endpoint, path, "the base URL already names the endpoint")+}++// DashScope answers some failures with a 200 and a code in the body.+func TestSurfacesAnInBodyError(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"code":"InvalidParameter","message":"contents exceeds 20"}`))+ }))+ defer server.Close()++ _, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "contents exceeds 20")+}diff --git a/internal/models/api/embeddings.go b/internal/models/api/embeddings.gonew file mode 100644index 000000000..d0b6d972c--- /dev/null+++ b/internal/models/api/embeddings.go@@ -0,0 +1,89 @@+package api++import (+ "context"+ "fmt"+)++// EmbeddingAPI names an embedding wire protocol. Like RerankAPI it is its own+// type, so a chat row's extra_config.api cannot name an embedding dialect and+// pass validation.+type EmbeddingAPI string++// The embedding protocols WeKnora speaks.+const (+ // EmbeddingOpenAI is POST {base}/embeddings with {model, input[]} answering+ // {data: [{embedding, index}]} — the shape OpenAI defined and every+ // compatible gateway copied. Jina, NVIDIA, Azure and WeKnora Cloud speak+ // it too, with their own optional fields, URL or credential.+ EmbeddingOpenAI EmbeddingAPI = "openai-embeddings"+ // EmbeddingDashScope is Alibaba Model Studio's native multimodal shape:+ // input.contents, parameters.dimension, output.embeddings.+ EmbeddingDashScope EmbeddingAPI = "dashscope-embeddings"+ // EmbeddingArk is Volcengine Ark's multimodal shape, which fuses every+ // input into one vector and therefore embeds one text per request.+ EmbeddingArk EmbeddingAPI = "ark-embeddings"+ // EmbeddingGoogle is Gemini's batchEmbedContents.+ EmbeddingGoogle EmbeddingAPI = "google-embeddings"+)++// Known reports whether the value names a protocol this build implements.+func (a EmbeddingAPI) Known() bool {+ switch a {+ case EmbeddingOpenAI, EmbeddingDashScope, EmbeddingArk, EmbeddingGoogle:+ return true+ }+ return false+}++// EmbedInputType distinguishes the two sides of a retrieval pair. Several+// vendors score them differently and want to be told which one they are+// embedding; the field they want it in differs, so the catalog names it.+type EmbedInputType string++const (+ // EmbedDocument is text being indexed.+ EmbedDocument EmbedInputType = "document"+ // EmbedQuery is text being searched with.+ EmbedQuery EmbedInputType = "query"+)++// Embedder is what every embedding protocol package implements. Callers pass+// the whole batch; splitting it to the vendor's documented ceiling is the+// shared layer's job, not the protocol's.+type Embedder interface {+ Embed(ctx context.Context, texts []string, kind EmbedInputType) ([][]float32, error)+}++// PlaceEmbeddings puts returned vectors back in the order the texts were+// sent, using the index each vendor reports, and refuses a response that does+// not cover every input.+//+// Both halves matter. A vendor is free to answer out of order, so the index+// has to be honoured rather than assumed — and reading the wrong field for it+// silently collapses a whole batch onto slot 0, which is what+// Tencent/WeKnora#3484 was. An unfilled slot then reaches the index as an+// empty vector, where it is stored and poisons retrieval without anything+// failing, so a gap is an error instead. So is an index reported twice: one+// of the two vectors belongs to some other input.+func PlaceEmbeddings(want, got int, at func(i int) (int, []float32)) ([][]float32, error) {+ out := make([][]float32, want)+ seen := make([]bool, want)+ for i := 0; i < got; i++ {+ index, vector := at(i)+ if index < 0 || index >= want {+ return nil, fmt.Errorf("embedding index %d out of range for %d inputs", index, want)+ }+ if seen[index] {+ return nil, fmt.Errorf("embedding index %d returned twice", index)+ }+ seen[index] = true+ out[index] = vector+ }+ for i, vector := range out {+ if len(vector) == 0 {+ return nil, fmt.Errorf("no embedding returned for input %d of %d", i, want)+ }+ }+ return out, nil+}diff --git a/internal/models/api/embeddings_test.go b/internal/models/api/embeddings_test.gonew file mode 100644index 000000000..868175552--- /dev/null+++ b/internal/models/api/embeddings_test.go@@ -0,0 +1,43 @@+package api++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type placed struct {+ index int+ vector []float32+}++func place(want int, reply []placed) ([][]float32, error) {+ return PlaceEmbeddings(want, len(reply), func(i int) (int, []float32) {+ return reply[i].index, reply[i].vector+ })+}++func TestPlaceEmbeddingsHonoursTheReportedIndex(t *testing.T) {+ got, err := place(2, []placed{{1, []float32{2}}, {0, []float32{1}}})+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{1}, {2}}, got)+}++// Every way a reply can fail to cover the inputs exactly once is an error:+// each of them would otherwise store a vector under the wrong chunk or an+// empty one.+func TestPlaceEmbeddingsRefusesAReplyThatDoesNotCoverEachInputOnce(t *testing.T) {+ cases := map[string][]placed{+ "short": {{0, []float32{1}}},+ "out of range": {{0, []float32{1}}, {2, []float32{2}}},+ "duplicate": {{0, []float32{1}}, {0, []float32{2}}, {1, []float32{3}}},+ "empty vector": {{0, []float32{1}}, {1, nil}},+ }+ for name, reply := range cases {+ t.Run(name, func(t *testing.T) {+ _, err := place(2, reply)+ assert.Error(t, err)+ })+ }+}diff --git a/internal/models/api/googleembeddings/client.go b/internal/models/api/googleembeddings/client.gonew file mode 100644index 000000000..60db1330a--- /dev/null+++ b/internal/models/api/googleembeddings/client.go@@ -0,0 +1,131 @@+// Package googleembeddings implements Gemini's batchEmbedContents: one POST+// carrying a request per text, answering embeddings[].values in order.+//+// Three facts shape it. The per-request `model` must be the fully qualified+// `models/{id}`, not the bare id the URL already carries. The per-request+// options — `taskType`, `outputDimensionality` — belong inside+// `embedContentConfig`; the reference marks the same names at the top level+// of the request "Deprecated: Please use EmbedContentConfig…". And+// `taskType` exists on gemini-embedding-001 but not on gemini-embedding-2,+// which takes its task instruction in the prompt instead — so the field is+// declared per model rather than for the vendor.+//+// Each text is its own request with a single part: gemini-embedding-2 fuses+// the parts of one Content into one vector.+//+// https://ai.google.dev/api/embeddings+package googleembeddings++import (+ "context"+ "fmt"+ "strings"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+)++// Config is everything the client needs, already resolved by the catalog.+type Config struct {+ Endpoint api.Endpoint+ Settings catalog.EmbeddingsSettings+ Dimensions int+ Retry api.RetryPolicy+}++// Client talks batchEmbedContents to one endpoint.+type Client struct {+ cfg Config+}++// New builds a client.+func New(cfg Config) *Client { return &Client{cfg: cfg} }++const method = ":batchEmbedContents"++// configField holds the per-request options.+const configField = "embedContentConfig"++// qualifiedModel is the `models/{id}` form the per-request model field needs.+func (c *Client) qualifiedModel() string {+ return "models/" + strings.TrimPrefix(c.cfg.Endpoint.Model, "models/")+}++// openAIFacade is the sub-path of the same API version that serves the+// OpenAI-compatible surface. Rows that chat through it carry it in their base+// URL; the native method lives one level up.+const openAIFacade = "/openai"++// url is {base}/models/{id}:batchEmbedContents.+func (c *Client) url() string {+ if c.cfg.Endpoint.URL != "" {+ return c.cfg.Endpoint.Resolve("")+ }+ endpoint := c.cfg.Endpoint+ endpoint.BaseURL = strings.TrimSuffix(strings.TrimRight(endpoint.BaseURL, "/"), openAIFacade)+ return endpoint.Resolve("/" + c.qualifiedModel() + method)+}++type response struct {+ Embeddings []struct {+ Values []float32 `json:"values"`+ } `json:"embeddings"`+ Error *struct {+ Message string `json:"message"`+ } `json:"error,omitempty"`+}++// BuildRequestBody is the golden-test entry point.+func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {+ s := c.cfg.Settings+ requests := make([]any, 0, len(texts))+ for _, text := range texts {+ req := map[string]any{+ "model": c.qualifiedModel(),+ "content": map[string]any{"parts": []any{map[string]any{"text": text}}},+ }+ config := map[string]any{}+ if field := s.InputTypeField; field != "" {+ config[field] = s.InputTypeValue(kind)+ }+ if s.DimensionsField != "" && c.cfg.Dimensions > 0 {+ config[s.DimensionsField] = c.cfg.Dimensions+ }+ if len(config) > 0 {+ req[configField] = config+ }+ requests = append(requests, req)+ }+ body := map[string]any{"requests": requests}+ for k, v := range s.ExtraBody {+ if _, exists := body[k]; !exists {+ body[k] = v+ }+ }+ return body+}++// Embed vectorizes one batch. The reply carries no index: embeddings come+// back positionally, one per request, so a short reply is an error rather+// than a partially filled result.+func (c *Client) Embed(+ ctx context.Context, texts []string, kind api.EmbedInputType,+) ([][]float32, error) {+ var decoded response+ err := c.cfg.Endpoint.PostJSONWithRetry(+ ctx, c.url(), c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",+ )+ if err != nil {+ return nil, err+ }+ if decoded.Error != nil && decoded.Error.Message != "" {+ return nil, fmt.Errorf("gemini embedding error: %s", decoded.Error.Message)+ }+ if len(decoded.Embeddings) != len(texts) {+ return nil, fmt.Errorf(+ "gemini returned %d embeddings for %d inputs", len(decoded.Embeddings), len(texts))+ }+ return api.PlaceEmbeddings(len(texts), len(decoded.Embeddings), func(i int) (int, []float32) {+ return i, decoded.Embeddings[i].Values+ })+}diff --git a/internal/models/api/googleembeddings/golden_test.go b/internal/models/api/googleembeddings/golden_test.gonew file mode 100644index 000000000..40f8f93af--- /dev/null+++ b/internal/models/api/googleembeddings/golden_test.go@@ -0,0 +1,101 @@+package googleembeddings++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// documentedResponse is the batchEmbedContents response shape:+// https://ai.google.dev/api/embeddings — embeddings[].values, positional.+const documentedResponse = `{"embeddings":[{"values":[0.1,0.2]},{"values":[0.3,0.4]}]}`++var retrievalTasks = map[string]string{"document": "RETRIEVAL_DOCUMENT", "query": "RETRIEVAL_QUERY"}++func newClient(url, model string, settings catalog.EmbeddingsSettings, dims int) *Client {+ return New(Config{+ Endpoint: api.Endpoint{BaseURL: url, Model: model, Auth: api.HeaderAuth("x-goog-api-key", "k")},+ Settings: settings,+ Dimensions: dims,+ })+}++// gemini-embedding-001 takes taskType, and each request's model must be the+// fully qualified models/{id}.+func TestRequestBodyForATaskTypeModel(t *testing.T) {+ c := newClient("https://generativelanguage.googleapis.com/v1beta", "gemini-embedding-001",+ catalog.EmbeddingsSettings{+ InputTypeField: "taskType", InputTypeValues: retrievalTasks,+ DimensionsField: "outputDimensionality",+ }, 768)++ // The options sit in embedContentConfig: the same names at the top level+ // of the request are marked deprecated in the reference.+ body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)+ assert.Equal(t, map[string]any{"requests": []any{map[string]any{+ "model": "models/gemini-embedding-001",+ "content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},+ "embedContentConfig": map[string]any{+ "taskType": "RETRIEVAL_DOCUMENT",+ "outputDimensionality": 768,+ },+ }}}, body)++ q := c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["requests"].([]any)[0].(map[string]any)+ assert.Equal(t, "RETRIEVAL_QUERY", q["embedContentConfig"].(map[string]any)["taskType"])+}++// gemini-embedding-2 does not support task_type: its reference says to put+// the task instruction in the text instead. Sending the field anyway is an+// undocumented parameter, so a model that declares none sends none.+func TestNoTaskTypeWhereTheModelHasNone(t *testing.T) {+ c := newClient("https://generativelanguage.googleapis.com/v1beta", "gemini-embedding-2",+ catalog.EmbeddingsSettings{}, 0)+ req := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)["requests"].([]any)[0].(map[string]any)+ assert.NotContains(t, req, "embedContentConfig", "no option declared, so no config object")+ assert.NotContains(t, req, "taskType")+}++func TestPostsToTheModelsMethod(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ var path string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path = r.URL.Path+ _, _ = w.Write([]byte(documentedResponse))+ }))+ defer server.Close()++ // An id stored with the prefix must not become models/models/…+ c := newClient(server.URL+"/v1beta", "models/gemini-embedding-001", catalog.EmbeddingsSettings{}, 0)+ got, err := c.Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{0.1, 0.2}, {0.3, 0.4}}, got)+ assert.Equal(t, "/v1beta/models/gemini-embedding-001:batchEmbedContents", path)++ // A row that chats through the OpenAI-compatible facade stores+ // .../v1beta/openai; its embeddings still go to the native method.+ c = newClient(server.URL+"/v1beta/openai/", "gemini-embedding-001", catalog.EmbeddingsSettings{}, 0)+ _, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, "/v1beta/models/gemini-embedding-001:batchEmbedContents", path)+}++// The reply is positional with no index, so a short one cannot be mapped back.+func TestShortReplyIsAnError(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"embeddings":[{"values":[0.1]}]}`))+ }))+ defer server.Close()++ _, err := newClient(server.URL+"/v1beta", "gemini-embedding-001", catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "1 embeddings for 2 inputs")+}diff --git a/internal/models/api/openaiembeddings/client.go b/internal/models/api/openaiembeddings/client.gonew file mode 100644index 000000000..94de9b606--- /dev/null+++ b/internal/models/api/openaiembeddings/client.go@@ -0,0 +1,131 @@+// Package openaiembeddings implements the embedding shape OpenAI defined and+// every compatible gateway copied: POST {base}/embeddings with {model, input}+// answering {data: [{embedding, index}]}.+//+// The vendors that speak it disagree about everything optional, so nothing+// optional is sent unless catalog.EmbeddingsSettings says the vendor+// documents it:+//+// - `dimensions` does not exist on NVIDIA NIM or Volcengine's text endpoint;+// - `encoding_format` is absent from Zhipu's reference;+// - the parameter that separates a search query from an indexed document is+// `input_type` on NIM, `task` on Jina and `taskType` on Gemini, and most+// vendors have none.+//+// This package contains no vendor names.+package openaiembeddings++import (+ "context"+ "fmt"+ "strings"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+)++// Config is everything the client needs, already resolved by the catalog.+type Config struct {+ Endpoint api.Endpoint+ Settings catalog.EmbeddingsSettings+ // Dimensions is the width the row asked for; it is sent only when the+ // vendor names a field for it.+ Dimensions int+ Retry api.RetryPolicy+}++// Client talks the OpenAI embedding shape to one endpoint.+type Client struct {+ cfg Config+}++// New builds a client.+func New(cfg Config) *Client { return &Client{cfg: cfg} }++const defaultPath = "/embeddings"++func (c *Client) url() string {+ if c.cfg.Endpoint.URL != "" {+ return c.cfg.Endpoint.Resolve("")+ }+ path := c.cfg.Settings.Path+ if path == "" {+ path = defaultPath+ }+ if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {+ path = ""+ }+ return c.cfg.Endpoint.Resolve(path)+}++type response struct {+ Data []struct {+ Embedding []float32 `json:"embedding"`+ // Index is a pointer so that an absent field reads as absent rather+ // than as 0. OpenAI, vLLM and TEI send it; some minimal compatible+ // servers answer in order and leave it out, and the pre-catalog+ // client read those positionally. Decoded as a plain int, every+ // element of such a reply would claim slot 0.+ Index *int `json:"index"`+ } `json:"data"`+ Error *struct {+ Message string `json:"message"`+ } `json:"error,omitempty"`+}++// BuildRequestBody is the golden-test entry point: it returns the exact JSON+// object that would be sent.+func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {+ s := c.cfg.Settings+ body := map[string]any{+ "model": c.cfg.Endpoint.Model,+ "input": texts,+ }+ if s.SendEncodingFormat {+ body["encoding_format"] = "float"+ }+ if s.DimensionsField != "" && c.cfg.Dimensions > 0 {+ body[s.DimensionsField] = c.cfg.Dimensions+ }+ if field := s.InputTypeField; field != "" {+ body[field] = s.InputTypeValue(kind)+ }+ if s.TruncateField != "" {+ if s.TruncateValue == "true" || s.TruncateValue == "false" {+ body[s.TruncateField] = s.TruncateValue == "true"+ } else {+ body[s.TruncateField] = s.TruncateValue+ }+ }+ if s.TruncatePromptTokens > 0 && s.AcceptsTruncatePromptTokens {+ body["truncate_prompt_tokens"] = s.TruncatePromptTokens+ }+ for k, v := range s.ExtraBody {+ if _, exists := body[k]; !exists {+ body[k] = v+ }+ }+ return body+}++// Embed vectorizes one batch, in the order it was given.+func (c *Client) Embed(+ ctx context.Context, texts []string, kind api.EmbedInputType,+) ([][]float32, error) {+ var decoded response+ err := c.cfg.Endpoint.PostJSONWithRetry(+ ctx, c.url(), c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",+ )+ if err != nil {+ return nil, err+ }+ if decoded.Error != nil && decoded.Error.Message != "" {+ return nil, fmt.Errorf("embedding API error: %s", decoded.Error.Message)+ }+ return api.PlaceEmbeddings(len(texts), len(decoded.Data), func(i int) (int, []float32) {+ if decoded.Data[i].Index == nil {+ return i, decoded.Data[i].Embedding+ }+ return *decoded.Data[i].Index, decoded.Data[i].Embedding+ })+}diff --git a/internal/models/api/openaiembeddings/golden_test.go b/internal/models/api/openaiembeddings/golden_test.gonew file mode 100644index 000000000..723984271--- /dev/null+++ b/internal/models/api/openaiembeddings/golden_test.go@@ -0,0 +1,218 @@+package openaiembeddings++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/catalog"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// arkTextResponse is the response example from Volcengine's text embedding+// reference (POST /api/v3/embeddings), now filed under its retired+// documentation: https://docs.volcengine.com/docs/ark/TextVectorizationAPI+//+// It is the OpenAI shape exactly — data is an array whose elements carry an+// index — which is why rows that still name a doubao-embedding text model+// speak this protocol rather than Ark's multimodal one.+const arkTextResponse = `{+ "created": 1743575029,+ "id": "0217435750294",+ "data": [+ {"embedding": [0.11, 0.12], "index": 0, "object": "embedding"},+ {"embedding": [0.21, 0.22], "index": 1, "object": "embedding"}+ ],+ "model": "doubao-embedding-text-240515",+ "object": "list",+ "usage": {"prompt_tokens": 7, "total_tokens": 7}+}`++// nimResponse is the response shape of NVIDIA's embedding reference:+// https://docs.api.nvidia.com/nim/reference/nvidia-nv-embedqa-e5-v5-infer+const nimResponse = `{+ "object": "list",+ "data": [{"object": "embedding", "embedding": [0.5, 0.6], "index": 0}],+ "model": "nvidia/nv-embedqa-e5-v5",+ "usage": {"prompt_tokens": 4, "total_tokens": 4}+}`++func newClient(url string, settings catalog.EmbeddingsSettings, dims int) *Client {+ return New(Config{+ Endpoint: api.Endpoint{BaseURL: url, Model: "m", Auth: api.BearerAuth("k")},+ Settings: settings,+ Dimensions: dims,+ Retry: api.RetryPolicy{},+ })+}++func serve(t *testing.T, payload string) (*httptest.Server, *string, *map[string]any) {+ t.Helper()+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ path, body := new(string), new(map[string]any)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ *path = r.URL.Path+ _ = json.NewDecoder(r.Body).Decode(body)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(payload))+ }))+ return server, path, body+}++// The baseline sends model and input and nothing else: those are the only two+// fields every vendor in the catalog documents.+func TestBaselineSendsOnlyModelAndInput(t *testing.T) {+ c := newClient("https://example.invalid/v1", catalog.EmbeddingsSettings{}, 1024)+ body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)+ assert.Equal(t, map[string]any{"model": "m", "input": []string{"a"}}, body,+ "a width the row asked for must not be sent to a vendor that names no field for it")+}++// NIM documents no `dimensions`, requires `input_type` and defaults+// `truncate` to NONE, which fails a request on over-long input.+func TestNIMRequestMatchesItsReference(t *testing.T) {+ c := newClient("https://integrate.api.nvidia.com/v1", catalog.EmbeddingsSettings{+ SendEncodingFormat: true,+ InputTypeField: "input_type",+ InputTypeValues: map[string]string{"document": "passage", "query": "query"},+ TruncateField: "truncate",+ TruncateValue: "END",+ }, 1024)++ doc := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)+ assert.Equal(t, "passage", doc["input_type"])+ assert.Equal(t, "END", doc["truncate"])+ assert.Equal(t, "float", doc["encoding_format"])+ assert.NotContains(t, doc, "dimensions", "NIM's schema has no dimensions field")++ assert.Equal(t, "query", c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["input_type"])+}++// Jina spells the same idea `task`, and its truncate is a boolean.+func TestJinaRequestMatchesItsReference(t *testing.T) {+ c := newClient("https://api.jina.ai/v1", catalog.EmbeddingsSettings{+ DimensionsField: "dimensions",+ InputTypeField: "task",+ InputTypeValues: map[string]string{"document": "retrieval.passage", "query": "retrieval.query"},+ TruncateField: "truncate",+ TruncateValue: "true",+ }, 512)++ body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)+ assert.Equal(t, "retrieval.passage", body["task"])+ assert.Equal(t, true, body["truncate"], "a boolean, not the string \"true\"")+ assert.Equal(t, 512, body["dimensions"])+ assert.Equal(t, "retrieval.query", c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["task"])+}++// truncate_prompt_tokens is a vLLM extension. It appears in no managed+// vendor's schema and used to be sent to every one of them, hardcoded to 511.+func TestTruncatePromptTokensReachesOnlyVLLMClassRuntimes(t *testing.T) {+ managed := newClient("https://api.openai.com/v1", catalog.EmbeddingsSettings{+ TruncatePromptTokens: 511,+ }, 0)+ assert.NotContains(t, managed.BuildRequestBody([]string{"a"}, api.EmbedDocument), "truncate_prompt_tokens")++ vllm := newClient("http://vllm.internal/v1", catalog.EmbeddingsSettings{+ AcceptsTruncatePromptTokens: true, TruncatePromptTokens: 512,+ }, 0)+ assert.Equal(t, 512, vllm.BuildRequestBody([]string{"a"}, api.EmbedDocument)["truncate_prompt_tokens"])+}++func TestDecodesArkTextResponse(t *testing.T) {+ server, path, body := serve(t, arkTextResponse)+ defer server.Close()++ c := newClient(server.URL+"/api/v3", catalog.EmbeddingsSettings{SendEncodingFormat: true}, 0)+ got, err := c.Embed(context.Background(), []string{"天很蓝", "海很深"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{0.11, 0.12}, {0.21, 0.22}}, got)+ assert.Equal(t, "/api/v3/embeddings", *path)+ assert.NotContains(t, *body, "dimensions", "Ark's text endpoint documents no dimensions")+}++func TestDecodesNIMResponse(t *testing.T) {+ server, _, _ := serve(t, nimResponse)+ defer server.Close()++ c := newClient(server.URL+"/v1", catalog.EmbeddingsSettings{}, 0)+ got, err := c.Embed(context.Background(), []string{"a"}, api.EmbedQuery)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{0.5, 0.6}}, got)+}++// A vendor may answer out of order; the index decides the slot.+func TestOutOfOrderIndicesArePlacedByIndex(t *testing.T) {+ server, _, _ := serve(t, `{"data":[+ {"embedding":[2],"index":1},+ {"embedding":[1],"index":0}+ ]}`)+ defer server.Close()++ got, err := newClient(server.URL, catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{1}, {2}}, got)+}++// A server that answers in order without an index is read positionally, as+// the pre-catalog client read it, rather than as every vector claiming 0.+func TestReplyWithoutIndicesIsReadInOrder(t *testing.T) {+ server, _, _ := serve(t, `{"data":[{"embedding":[1]},{"embedding":[2]},{"embedding":[3]}]}`)+ defer server.Close()++ got, err := newClient(server.URL, catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a", "b", "c"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{1}, {2}, {3}}, got)+}++// An index that is present but repeated is still refused: that reply really+// does leave an input without its vector.+func TestRepeatedIndexIsStillAnError(t *testing.T) {+ server, _, _ := serve(t, `{"data":[{"embedding":[1],"index":0},{"embedding":[2],"index":0}]}`)+ defer server.Close()++ _, err := newClient(server.URL, catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ assert.Error(t, err)+}++// A reply covering fewer inputs than were sent would store an empty vector.+func TestShortReplyIsAnError(t *testing.T) {+ server, _, _ := serve(t, `{"data":[{"embedding":[1],"index":0}]}`)+ defer server.Close()++ _, err := newClient(server.URL, catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "no embedding returned for input 1")+}++func TestDoesNotDoubleTheEmbeddingsPath(t *testing.T) {+ server, path, _ := serve(t, `{"data":[{"embedding":[1],"index":0}]}`)+ defer server.Close()++ _, err := newClient(server.URL+"/openai/v1/embeddings", catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a"}, api.EmbedDocument)+ require.NoError(t, err)+ assert.Equal(t, "/openai/v1/embeddings", *path)+}++func TestSurfacesTheVendorErrorBody(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":{"message":"input exceeds 4096 characters"}}`))+ }))+ defer server.Close()++ _, err := newClient(server.URL, catalog.EmbeddingsSettings{}, 0).+ Embed(context.Background(), []string{"a"}, api.EmbedDocument)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "input exceeds 4096 characters")+}diff --git a/internal/models/api/retry.go b/internal/models/api/retry.gonew file mode 100644index 000000000..2dd9a02e8--- /dev/null+++ b/internal/models/api/retry.go@@ -0,0 +1,81 @@+package api++import (+ "context"+ "errors"+ "fmt"+ "time"++ "github.com/Tencent/WeKnora/internal/logger"+)++// RetryPolicy describes how often to retry a failed request and how long to+// wait between attempts. The zero value performs one attempt and no waiting.+type RetryPolicy struct {+ // MaxRetries is the number of retries after the first attempt.+ MaxRetries int+ // BaseDelay is the wait before the first retry; it doubles each time.+ BaseDelay time.Duration+ // MaxDelay caps the backoff.+ MaxDelay time.Duration+}++// DefaultRetryPolicy is three retries with 1s, 2s, 4s backoff, which is what+// every embedding client used before this helper existed.+func DefaultRetryPolicy() RetryPolicy {+ return RetryPolicy{MaxRetries: 3, BaseDelay: time.Second, MaxDelay: 10 * time.Second}+}++func (p RetryPolicy) delay(attempt int) time.Duration {+ if p.BaseDelay <= 0 {+ return 0+ }+ wait := p.BaseDelay << uint(attempt-1)+ if p.MaxDelay > 0 && wait > p.MaxDelay {+ return p.MaxDelay+ }+ return wait+}++// PostJSONWithRetry sends one authenticated JSON request, retrying transport+// failures, and decodes the reply into out.+//+// It never returns a nil error without decoding: the eight hand-written+// retry loops this replaces kept `resp` and `err` in the enclosing scope and+// returned `(nil, err)` at the end, so writing `req, err := ...` inside the+// loop shadowed the error, left the outer one nil, and handed the caller a+// nil response with no error to check — a nil-pointer panic that took the+// process down instead of reporting "connection refused" (Tencent/WeKnora#3484).+// Here the last error is captured in the enclosing scope on purpose and the+// function cannot fall through without it.+//+// Only transport failures are retried. A non-2xx reply is the vendor+// answering, and repeating a rejected request neither fixes it nor tells the+// operator anything new.+func (e Endpoint) PostJSONWithRetry(+ ctx context.Context, url string, body, out any, policy RetryPolicy, label string,+) error {+ var lastErr error+ for attempt := 0; attempt <= policy.MaxRetries; attempt++ {+ if attempt > 0 {+ wait := policy.delay(attempt)+ logger.Infof(ctx, "[%s] retrying (%d/%d) after %v: %v",+ label, attempt, policy.MaxRetries, wait, lastErr)+ select {+ case <-time.After(wait):+ case <-ctx.Done():+ return ctx.Err()+ }+ }+ err := e.PostJSON(ctx, url, body, out)+ if err == nil {+ return nil+ }+ var httpErr *HTTPError+ if errors.As(err, &httpErr) {+ return err+ }+ lastErr = err+ }+ return fmt.Errorf("%s: %w", label, lastErr)+}diff --git a/internal/models/api/retry_test.go b/internal/models/api/retry_test.gonew file mode 100644index 000000000..4d7c8d142--- /dev/null+++ b/internal/models/api/retry_test.go@@ -0,0 +1,103 @@+package api++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func fastPolicy() RetryPolicy { return RetryPolicy{MaxRetries: 3} }++// The failure this helper exists to make impossible: every attempt fails at+// the transport, and the caller gets an error rather than a nil response with+// a nil error to check. The eight hand-written loops it replaces returned+// (nil, nil) here whenever a `:=` shadowed the enclosing error.+func TestPostJSONWithRetryAlwaysReportsAnUnreachableUpstream(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))+ url := server.URL+ server.Close()++ var out map[string]any+ err := Endpoint{}.PostJSONWithRetry(+ context.Background(), url, map[string]any{"a": 1}, &out, fastPolicy(), "test",+ )+ require.Error(t, err)+ assert.Contains(t, err.Error(), "test")+}++func TestPostJSONWithRetrySucceedsAfterATransportFailure(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ attempts := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ attempts+++ if attempts == 1 {+ // Hang up mid-request so the client sees a transport error.+ hijacker, ok := w.(http.Hijacker)+ require.True(t, ok)+ conn, _, err := hijacker.Hijack()+ require.NoError(t, err)+ _ = conn.Close()+ return+ }+ _, _ = w.Write([]byte(`{"ok":true}`))+ }))+ defer server.Close()++ var out map[string]any+ err := Endpoint{}.PostJSONWithRetry(+ context.Background(), server.URL, map[string]any{}, &out, fastPolicy(), "test",+ )+ require.NoError(t, err)+ assert.Equal(t, true, out["ok"])+ assert.Equal(t, 2, attempts)+}++// A non-2xx reply is the vendor answering. Repeating a rejected request costs+// quota, delays the error, and cannot change the answer.+func TestPostJSONWithRetryDoesNotRetryAVendorRejection(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ attempts := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ attempts+++ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"input too long"}`))+ }))+ defer server.Close()++ err := Endpoint{}.PostJSONWithRetry(+ context.Background(), server.URL, map[string]any{}, nil, fastPolicy(), "test",+ )+ require.Error(t, err)+ assert.Contains(t, err.Error(), "input too long")+ assert.Equal(t, 1, attempts, "a rejection must not be repeated")+}++func TestPostJSONWithRetryStopsWhenTheContextIsDone(t *testing.T) {+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))+ url := server.URL+ server.Close()++ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ err := Endpoint{}.PostJSONWithRetry(+ ctx, url, map[string]any{}, nil,+ RetryPolicy{MaxRetries: 3, BaseDelay: time.Minute}, "test",+ )+ require.Error(t, err)+}++func TestRetryPolicyBackoffDoublesAndIsCapped(t *testing.T) {+ p := RetryPolicy{MaxRetries: 5, BaseDelay: time.Second, MaxDelay: 4 * time.Second}+ assert.Equal(t, time.Second, p.delay(1))+ assert.Equal(t, 2*time.Second, p.delay(2))+ assert.Equal(t, 4*time.Second, p.delay(3))+ assert.Equal(t, 4*time.Second, p.delay(4), "capped")+ assert.Zero(t, RetryPolicy{MaxRetries: 2}.delay(1), "no base delay means no waiting")+}diff --git a/internal/models/catalog/catalog_test.go b/internal/models/catalog/catalog_test.goindex e27711f4b..bfc675e8b 100644--- a/internal/models/catalog/catalog_test.go+++ b/internal/models/catalog/catalog_test.go@@ -67,22 +67,53 @@ func TestFindModel_ExactAliasAndGlob(t *testing.T) {registerTestVendors(t)v, _ := Get("acme")- m, ok := v.FindModel("ACME-PRO")+ chat := types.ModelTypeKnowledgeQA+ m, ok := v.FindModel("ACME-PRO", chat)require.True(t, ok)assert.Equal(t, "acme-pro", m.ID)- m, ok = v.FindModel("acme-lite-2")+ m, ok = v.FindModel("acme-lite-2", chat)require.True(t, ok)assert.Equal(t, "acme-lite*", m.Match)- m, ok = v.FindModel("acme-lite-vision-2")+ m, ok = v.FindModel("acme-lite-vision-2", chat)require.True(t, ok, "longest literal prefix wins")assert.Equal(t, "acme-lite-vision*", m.Match)- _, ok = v.FindModel("unknown")+ _, ok = v.FindModel("unknown", chat)assert.False(t, ok)}+// A lookup only sees entries of the row's own type. A VLM row is a chat+// model that accepts images, so it sees the chat entries.+func TestFindModel_IsTyped(t *testing.T) {+ registerTestVendors(t)+ v, _ := Get("acme")++ _, ok := v.FindModel("acme-embed", types.ModelTypeKnowledgeQA)+ assert.False(t, ok, "a chat row must not pick up an embedding entry")+ m, ok := v.FindModel("acme-embed", types.ModelTypeEmbedding)+ require.True(t, ok)+ assert.Equal(t, "acme-embed", m.ID)++ _, ok = v.FindModel("acme-lite-embed", types.ModelTypeEmbedding)+ assert.False(t, ok, "an embedding row must not pick up a chat glob")+ _, ok = v.FindModel("acme-lite-2", types.ModelTypeVLLM)+ assert.True(t, ok)+}++// The failure a typed lookup prevents: a chat family's glob carries chat+// compat, and handing it to an embedding or rerank row fails the strict+// overlay decode, so the row could not be built at all.+func TestResolve_ModelNameInsideAChatGlobStillResolvesForOtherTypes(t *testing.T) {+ registerTestVendors(t)+ for _, modelType := range []types.ModelType{types.ModelTypeEmbedding, types.ModelTypeRerank} {+ r, err := Resolve(Ref{Provider: "acme", Model: "acme-lite-embed", ModelType: modelType})+ require.NoError(t, err, modelType)+ assert.False(t, r.Cataloged, modelType)+ }+}+func TestDetectByURL_LongestPatternWins(t *testing.T) {registerTestVendors(t)assert.Equal(t, "tencent-lkeap", DetectByURL("https://api.lkeap.cloud.tencent.com/v1"))diff --git a/internal/models/catalog/compat.go b/internal/models/catalog/compat.goindex d69566559..234d8a2b6 100644--- a/internal/models/catalog/compat.go+++ b/internal/models/catalog/compat.go@@ -344,6 +344,8 @@ type VendorCompat struct {// Rerank is the rerank protocol overlay. It has no per-protocol variants:// a vendor serves exactly one rerank dialect.Rerank RerankCompat `json:"rerank,omitempty"`+ // Embeddings is the embedding protocol overlay, likewise one per vendor.+ Embeddings EmbeddingsCompat `json:"embeddings,omitempty"`}// apply writes the set fields of an overlay struct onto a settings structdiff --git a/internal/models/catalog/embeddings.go b/internal/models/catalog/embeddings.gonew file mode 100644index 000000000..87b12b0f9--- /dev/null+++ b/internal/models/catalog/embeddings.go@@ -0,0 +1,104 @@+package catalog++import "github.com/Tencent/WeKnora/internal/models/api"++// EmbeddingsCompat is the overlay form (every field optional) of the+// embedding settings. JSON keys are the documented names used in models.json+// and config/models.json.+type EmbeddingsCompat struct {+ // API overrides the vendor's embedding protocol for one model. Aliyun and+ // Volcengine each serve two: a text endpoint in the OpenAI shape and a+ // multimodal one of their own, chosen by which model the row names.+ API *api.EmbeddingAPI `json:"api,omitempty"`+ Path *string `json:"path,omitempty"`+ SendEncodingFormat *bool `json:"send_encoding_format,omitempty"`+ DimensionsField *string `json:"dimensions_field,omitempty"`+ TruncateField *string `json:"truncate_field,omitempty"`+ TruncateValue *string `json:"truncate_value,omitempty"`+ InputTypeField *string `json:"input_type_field,omitempty"`+ InputTypeValues map[string]string `json:"input_type_values,omitempty"`+ MaxBatchSize *int `json:"max_batch_size,omitempty"`+ MaxInputChars *int `json:"max_input_chars,omitempty"`+ // AcceptsTruncatePromptTokens marks a vLLM-class runtime, the only kind+ // that implements the `truncate_prompt_tokens` extension.+ AcceptsTruncatePromptTokens *bool `json:"accepts_truncate_prompt_tokens,omitempty"`+ RequestTimeout *int `json:"request_timeout_seconds,omitempty"`+ ExtraBody map[string]any `json:"extra_body,omitempty"`+}++// EmbeddingsSettings is the resolved (fully defaulted) form.+type EmbeddingsSettings struct {+ // API is the protocol this model speaks, which may differ from the+ // vendor's default.+ API api.EmbeddingAPI+ // Path is appended to the base URL; vendors whose default base URL names+ // the full endpoint leave it empty.+ Path string+ // SendEncodingFormat sends encoding_format: "float". OpenAI documents it;+ // several compatible gateways do not list it at all.+ SendEncodingFormat bool+ // DimensionsField carries the requested vector width: "dimensions" on the+ // OpenAI shape, "dimension" on DashScope (nested under parameters),+ // "outputDimensionality" on Gemini, and empty where the vendor does not+ // let a request choose. It is sent only when the row opted in with+ // supports_dimension_override; the field name is the vendor's fact, the+ // decision to narrow the vector is the operator's.+ DimensionsField string+ // TruncateField and TruncateValue are the vendor's server-side truncation+ // switch for over-long input: a boolean on Jina, an enum on NIM. Empty+ // sends nothing.+ TruncateField string+ TruncateValue string+ // InputTypeField names the parameter that distinguishes an indexed+ // document from a search query, and InputTypeValues maps the neutral+ // api.EmbedInputType values onto the vendor's vocabulary. Asymmetric+ // models score the two sides differently and are measurably worse when+ // both are embedded the same way.+ InputTypeField string+ InputTypeValues map[string]string+ // MaxBatchSize and MaxInputChars are the documented per-request ceilings.+ MaxBatchSize int+ MaxInputChars int+ // AcceptsTruncatePromptTokens reports a vLLM-class runtime. The extension+ // appears in no managed vendor's schema, so it must never be sent to one.+ AcceptsTruncatePromptTokens bool+ // TruncatePromptTokens is the budget the operator opted into on this row,+ // honoured only where the vendor accepts the extension.+ TruncatePromptTokens int+ // RequestTimeout caps one request, in seconds. 0 leaves the client+ // without its own deadline and lets the caller's context govern.+ RequestTimeout int+ ExtraBody map[string]any+}++// BatchLimits renders the documented ceilings for api.SplitBatches.+func (s EmbeddingsSettings) BatchLimits() api.BatchLimits {+ return api.BatchLimits{MaxItems: s.MaxBatchSize, MaxItemRunes: s.MaxInputChars}+}++// InputTypeValue maps a neutral input kind onto the vendor's vocabulary,+// returning "" when this vendor does not distinguish the two sides.+func (s EmbeddingsSettings) InputTypeValue(kind api.EmbedInputType) string {+ if s.InputTypeField == "" {+ return ""+ }+ if v, ok := s.InputTypeValues[string(kind)]; ok {+ return v+ }+ return string(kind)+}++// DefaultEmbeddings is the protocol baseline, and it is deliberately bare:+// `model` and `input` are the only two fields every vendor in this catalog+// documents. The rest disagree — NVIDIA NIM and Volcengine's text endpoint+// have no `dimensions` at all, Zhipu has no `encoding_format`, and the+// parameter that separates a query from a document is spelled three+// different ways. A vendor that documents one declares it; nothing is sent+// on the assumption that an OpenAI-shaped endpoint accepts every OpenAI+// field.+//+// The one non-wire default is the request deadline: every pre-catalog+// embedding client carried 60 seconds.+func DefaultEmbeddings() EmbeddingsSettings {+ return EmbeddingsSettings{RequestTimeout: 60}+}diff --git a/internal/models/catalog/legacy_rows_test.go b/internal/models/catalog/legacy_rows_test.goindex 14a0a4f19..f51f4cba9 100644--- a/internal/models/catalog/legacy_rows_test.go+++ b/internal/models/catalog/legacy_rows_test.go@@ -6,6 +6,7 @@ package catalog_test// means an existing deployment breaks on upgrade without a migration.import (+ "bytes""testing""github.com/Tencent/WeKnora/internal/models/api"@@ -194,15 +195,21 @@ func TestLegacyRowsValidateAndResolve(t *testing.T) {if resolved.Vendor == nil {t.Fatal("resolved with a nil vendor")}- // Rerank rows resolve to a rerank protocol; everything else- // resolves to a chat one. The two vocabularies are separate- // types so a row can never land on the wrong one.- if row.typ == types.ModelTypeRerank {+ // Each model type resolves to its own protocol vocabulary. They+ // are separate Go types, so a row can never land on the wrong one.+ switch row.typ {+ case types.ModelTypeRerank:if !resolved.RerankAPI.Known() {t.Fatalf("resolved to an unknown rerank protocol %q", resolved.RerankAPI)}- } else if !resolved.API.Known() {- t.Fatalf("resolved to an unknown protocol %q", resolved.API)+ case types.ModelTypeEmbedding:+ if !resolved.EmbeddingAPI.Known() {+ t.Fatalf("resolved to an unknown embedding protocol %q", resolved.EmbeddingAPI)+ }+ default:+ if !resolved.API.Known() {+ t.Fatalf("resolved to an unknown protocol %q", resolved.API)+ }}if resolved.RemoteModel == "" && row.model != "" {t.Fatal("resolved to an empty remote model id")@@ -220,6 +227,11 @@ func TestEveryCataloguedModelResolves(t *testing.T) {if m.ID == "" {continue}+ // An entry that declares this build cannot serve it must refuse,+ // on save as at construction; vendors_test pins that it does.+ if bytes.Contains(m.Compat, []byte("unsupported_reason")) {+ continue+ }modelType := m.Typeif modelType == "" {modelType = types.ModelTypeKnowledgeQAdiff --git a/internal/models/catalog/registry.go b/internal/models/catalog/registry.goindex b073762ec..91767fde5 100644--- a/internal/models/catalog/registry.go+++ b/internal/models/catalog/registry.go@@ -34,6 +34,9 @@ func Register(v *Vendor) {if v.RerankAPI == "" && v.SupportsType(types.ModelTypeRerank) {v.RerankAPI = api.RerankCohere}+ if v.EmbeddingAPI == "" && v.SupportsType(types.ModelTypeEmbedding) {+ v.EmbeddingAPI = api.EmbeddingOpenAI+ }for i := range v.Models {if v.Models[i].Type == "" {v.Models[i].Type = types.ModelTypeKnowledgeQA@@ -161,20 +164,34 @@ func (v *Vendor) ModelsByType(modelType types.ModelType) []ModelSpec {return out}-// FindModel looks a model name up in the vendor catalog: exact id, then-// aliases, then glob patterns (longest literal prefix wins). Matching is-// case-insensitive.-func (v *Vendor) FindModel(name string) (ModelSpec, bool) {+// FindModel looks a model name up among the vendor's entries of one model+// type: exact id, then aliases, then glob patterns (longest literal prefix+// wins). Matching is case-insensitive.+//+// The type is part of the key because families share prefixes across types.+// Aliyun's qwen3* chat glob also matches qwen3.8-text-embedding, and gpt-5*+// matches gpt-5-embed; an untyped lookup would hand an embedding row the chat+// family's compat, which the embedding overlay rejects, and the row could not+// be built at all. A VLM row is a chat model that accepts images, so it looks+// among the chat entries.+func (v *Vendor) FindModel(name string, modelType types.ModelType) (ModelSpec, bool) {needle := strings.ToLower(strings.TrimSpace(name))if needle == "" {return ModelSpec{}, false}+ want := entryType(modelType)+ var candidates []ModelSpecfor _, m := range v.Models {+ if entryType(m.Type) == want {+ candidates = append(candidates, m)+ }+ }+ for _, m := range candidates {if strings.ToLower(m.ID) == needle {return m, true}}- for _, m := range v.Models {+ for _, m := range candidates {for _, alias := range m.Aliases {if strings.ToLower(alias) == needle {return m, true@@ -183,7 +200,7 @@ func (v *Vendor) FindModel(name string) (ModelSpec, bool) {}var best ModelSpecbestScore := -1- for _, m := range v.Models {+ for _, m := range candidates {if m.Match == "" {continue}@@ -200,6 +217,15 @@ func (v *Vendor) FindModel(name string) (ModelSpec, bool) {return ModelSpec{}, false}+// entryType folds a model type onto the catalog entries that describe it:+// chat entries leave Type empty, and VLM rows use them too.+func entryType(t types.ModelType) types.ModelType {+ if t == "" || t == types.ModelTypeVLLM {+ return types.ModelTypeKnowledgeQA+ }+ return t+}+// globMatch supports '*' wildcards only.func globMatch(pattern, s string) bool {parts := strings.Split(pattern, "*")diff --git a/internal/models/catalog/resolve.go b/internal/models/catalog/resolve.goindex bae3227be..ef6202278 100644--- a/internal/models/catalog/resolve.go+++ b/internal/models/catalog/resolve.go@@ -26,6 +26,9 @@ const (// budget for rerank, opt-in per row. It is never sent unless the operator// set it: vendors that do not implement it reject the unknown field.ExtraTruncatePromptTokens = "truncate_prompt_tokens"+ // LegacyTruncatePromptTokens is the embedding truncation budget the+ // pre-catalog OpenAI-compatible client sent whenever a row left it at 0.+ LegacyTruncatePromptTokens = 511// ExtraScoreScale overrides the vendor rerank score scale for one row.// A self-hosted gateway serves whatever reranker was deployed behind it// and the two families disagree: BGE-class models answer a 0..1@@ -42,6 +45,11 @@ type Ref struct {ModelType types.ModelTypeExtra map[string]stringOverride *types.ModelSpecOverride+ // TruncatePromptTokens is an embedding row's+ // embedding_parameters.truncate_prompt_tokens. It is a first-class column+ // rather than an extra_config key, which is why it arrives here instead+ // of in Extra.+ TruncatePromptTokens int}// Resolved is the fully merged view of one model: which vendor, which@@ -68,6 +76,11 @@ type Resolved struct {// rerank overlay is not merged for it.RerankAPI api.RerankAPIRerank RerankSettings++ // EmbeddingAPI and Embeddings are filled only for an embedding reference,+ // for the same reason.+ EmbeddingAPI api.EmbeddingAPI+ Embeddings EmbeddingsSettings}// Resolve merges the vendor, catalog entry, extra-config and per-row@@ -92,9 +105,9 @@ func Resolve(ref Ref) (*Resolved, error) {baseURL = strings.TrimRight(vendor.GetDefaultURL(modelType), "/")}- spec, cataloged := vendor.FindModel(ref.Model)+ spec, cataloged := vendor.FindModel(ref.Model, modelType)if !cataloged {- spec = ModelSpec{ID: ref.Model, Type: types.ModelTypeKnowledgeQA}+ spec = ModelSpec{ID: ref.Model, Type: entryType(modelType)}}if spec.API == "" {spec.API = vendor.API@@ -106,6 +119,9 @@ func Resolve(ref Ref) (*Resolved, error) {if modelType == types.ModelTypeRerank {return resolveRerank(ref, vendor, spec, cataloged, baseURL)}+ if modelType == types.ModelTypeEmbedding {+ return resolveEmbeddings(ref, vendor, spec, cataloged, baseURL)+ }resolvedAPI := spec.APIif forced := strings.TrimSpace(ref.Extra[ExtraAPI]); forced != "" {@@ -448,3 +464,76 @@ func resolveRerank(}return out, nil}++// resolveEmbeddings merges the embedding layers, in the same order as+// resolveRerank: protocol default, vendor, model entry, row spec override,+// then extra_config, which is the operator speaking about this one row.+func resolveEmbeddings(+ ref Ref, vendor *Vendor, spec ModelSpec, cataloged bool, baseURL string,+) (*Resolved, error) {+ protocol := vendor.EmbeddingAPI+ if protocol == "" {+ protocol = api.EmbeddingOpenAI+ }+ if !protocol.Known() {+ return nil, fmt.Errorf("catalog: unknown embedding api %q for provider %s", protocol, vendor.ID)+ }++ settings := DefaultEmbeddings()+ apply(&settings, &vendor.Compat.Embeddings)+ if len(spec.Compat) > 0 {+ overlay := &EmbeddingsCompat{}+ if err := decodeCompat(spec.Compat, overlay); err != nil {+ return nil, fmt.Errorf("embeddings compat: %w", err)+ }+ apply(&settings, overlay)+ }+ if raw := ref.Override.CompatJSON(); len(raw) > 0 {+ overlay := &EmbeddingsCompat{}+ if err := decodeCompat(raw, overlay); err != nil {+ return nil, fmt.Errorf("embeddings compat: %w", err)+ }+ apply(&settings, overlay)+ }+ // The row may carry a truncation budget, but the extension is vLLM's and+ // appears in no managed vendor's schema. Dropping it where the vendor+ // does not implement it is the quiet direction on purpose: unlike the+ // rerank opt-in, this field has a UI control that every embedding row+ // has always carried, so refusing to resolve would break rows whose only+ // mistake is a non-zero default.+ //+ // Where it is accepted, an unset row keeps the budget the pre-catalog+ // client always sent. A self-hosted index was built with long chunks cut+ // at that length; embedding new chunks uncut would put them in a+ // different place from the old ones without anything failing.+ if settings.AcceptsTruncatePromptTokens {+ settings.TruncatePromptTokens = ref.TruncatePromptTokens+ if settings.TruncatePromptTokens <= 0 {+ settings.TruncatePromptTokens = LegacyTruncatePromptTokens+ }+ }++ // A model entry may name a different dialect than the vendor default.+ if settings.API != "" {+ if !settings.API.Known() {+ return nil, fmt.Errorf(+ "catalog: unknown embedding api %q on %s/%s", settings.API, vendor.ID, spec.ID)+ }+ protocol = settings.API+ }+ settings.API = protocol++ out := &Resolved{+ Vendor: vendor,+ Spec: spec,+ Cataloged: cataloged,+ BaseURL: baseURL,+ RemoteModel: ref.Model,+ EmbeddingAPI: protocol,+ Embeddings: settings,+ }+ if override := strings.TrimSpace(ref.Extra[ExtraRemoteModelName]); override != "" {+ out.RemoteModel = override+ }+ return out, nil+}diff --git a/internal/models/catalog/types.go b/internal/models/catalog/types.goindex 24e217d23..90856f424 100644--- a/internal/models/catalog/types.go+++ b/internal/models/catalog/types.go@@ -221,7 +221,12 @@ type EndpointRequest struct {Model stringModelType types.ModelTypeAPI api.API- Extra map[string]string+ // EmbeddingAPI is the resolved embedding protocol on an embedding+ // request. Aliyun and Volcengine each serve their text and multimodal+ // embeddings on different paths under one base URL, so the hook has to+ // know which one the model speaks.+ EmbeddingAPI api.EmbeddingAPI+ Extra map[string]string}// Vendor is one model vendor / gateway / self-hosted runtime.@@ -242,6 +247,10 @@ type Vendor struct {// RerankAPI is the rerank protocol. Register defaults it to the Cohere// shape for any vendor that serves rerank without naming another.RerankAPI api.RerankAPI+ // EmbeddingAPI is the embedding protocol. Register defaults it to the+ // OpenAI shape for any vendor that serves embeddings without naming+ // another.+ EmbeddingAPI api.EmbeddingAPI// DefaultBaseURLs by model type; GetDefaultURL falls back to chat.DefaultBaseURLs map[types.ModelType]stringModelTypes []types.ModelTypediff --git a/internal/models/catalog/validate.go b/internal/models/catalog/validate.goindex 5851cffdf..eaff1ce68 100644--- a/internal/models/catalog/validate.go+++ b/internal/models/catalog/validate.go@@ -14,14 +14,12 @@ import (// protocol, a bad compat key or an invalid thinking level is rejected where// it is written instead of surfacing as a failed chat call much later.//-// Embedding, rerank and ASR rows return nil without being checked, and that-// is deliberate rather than an oversight: those clients do not resolve-// through the catalog at all (they read the provider and base URL directly),-// so there is no protocol or compat for a spec to be wrong about. The-// consequence worth knowing is that a spec stored on such a row is inert —-// it is neither validated nor applied.+// Chat, VLM, embedding and rerank rows are checked; all four are built from+// catalog.Resolve, so a row that does not resolve cannot be used. ASR rows+// return nil: the ASR client does not resolve through the catalog yet, so a+// spec stored on such a row is inert — neither validated nor applied.func ValidateRow(modelName string, modelType types.ModelType, params *types.ModelParameters) error {- if params == nil || (modelType != types.ModelTypeKnowledgeQA && modelType != types.ModelTypeVLLM) {+ if params == nil || !resolvesThroughCatalog(modelType) {return nil}if params.Spec != nil {@@ -43,3 +41,11 @@ func ValidateRow(modelName string, modelType types.ModelType, params *types.Mode}return nil}++func resolvesThroughCatalog(modelType types.ModelType) bool {+ switch modelType {+ case types.ModelTypeKnowledgeQA, types.ModelTypeVLLM, types.ModelTypeEmbedding, types.ModelTypeRerank:+ return true+ }+ return false+}diff --git a/internal/models/catalog/validate_test.go b/internal/models/catalog/validate_test.goindex 5f356ea84..0e6186f96 100644--- a/internal/models/catalog/validate_test.go+++ b/internal/models/catalog/validate_test.go@@ -20,9 +20,45 @@ func TestValidateRow(t *testing.T) {name: "nil parameters", modelName: "x", modelType: types.ModelTypeKnowledgeQA,},{- name: "embedding rows carry no catalog parameters", modelName: "text-embedding-v4",+ name: "a catalogued embedding row resolves", modelName: "text-embedding-v4",modelType: types.ModelTypeEmbedding,- params: &types.ModelParameters{Provider: "aliyun", Spec: &types.ModelSpecOverride{API: "nope"}},+ params: &types.ModelParameters{Provider: "aliyun"},+ },+ {+ // Embedding is built from Resolve too, so a bad overlay fails+ // every call; it must fail the save instead.+ name: "unknown embedding compat key is rejected", modelName: "text-embedding-v4",+ modelType: types.ModelTypeEmbedding,+ params: &types.ModelParameters{+ Provider: "aliyun", Spec: &types.ModelSpecOverride{Compat: map[string]any{"max_tokens_field": "x"}},+ },+ wantErr: true,+ },+ {+ name: "unknown embedding protocol is rejected", modelName: "text-embedding-v4",+ modelType: types.ModelTypeEmbedding,+ params: &types.ModelParameters{+ Provider: "aliyun", Spec: &types.ModelSpecOverride{Compat: map[string]any{"api": "openai-completions"}},+ },+ wantErr: true,+ },+ {+ name: "an embedding name inside a chat glob is accepted", modelName: "qwen3.8-text-embedding",+ modelType: types.ModelTypeEmbedding,+ params: &types.ModelParameters{Provider: "aliyun"},+ },+ {+ name: "rerank truncation on a vendor without the extension is rejected", modelName: "gte-rerank-v2",+ modelType: types.ModelTypeRerank,+ params: &types.ModelParameters{+ Provider: "aliyun", ExtraConfig: map[string]string{"truncate_prompt_tokens": "512"},+ },+ wantErr: true,+ },+ {+ name: "asr rows are not resolved through the catalog", modelName: "whisper-1",+ modelType: types.ModelTypeASR,+ params: &types.ModelParameters{Provider: "openai", Spec: &types.ModelSpecOverride{API: "nope"}},},{name: "a catalogued chat row resolves", modelName: "deepseek-v4-pro",diff --git a/internal/models/embedding/aliyun.go b/internal/models/embedding/aliyun.godeleted file mode 100644index 957616b7d..000000000--- a/internal/models/embedding/aliyun.go+++ /dev/null@@ -1,294 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "strings"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--const (- // AliyunMultimodalEmbeddingEndpoint 阿里云 DashScope 多模态 Embedding API 端点- AliyunMultimodalEmbeddingEndpoint = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"-)--// AliyunEmbedder implements text vectorization using Aliyun DashScope multimodal embedding API-type AliyunEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-func (e *AliyunEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *AliyunEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// AliyunEmbedParameters represents the parameters for Aliyun DashScope multimodal embedding-type AliyunEmbedParameters struct {- Dimension int `json:"dimension,omitempty"`-}--// AliyunEmbedRequest represents an Aliyun DashScope multimodal embedding request-type AliyunEmbedRequest struct {- Model string `json:"model"`- Input AliyunEmbedInput `json:"input"`- Parameters *AliyunEmbedParameters `json:"parameters,omitempty"`-}--// AliyunEmbedInput represents the input structure for Aliyun embedding-type AliyunEmbedInput struct {- Contents []AliyunContent `json:"contents"`-}--// AliyunContent represents a single content item in the input-type AliyunContent struct {- Text string `json:"text,omitempty"`-}--// AliyunEmbedResponse represents an Aliyun DashScope embedding response.-//-// The position field is `index`, not the `text_index` of DashScope's-// text-embedding API (/services/embeddings/text-embedding/text-embedding).-// The two interfaces are neighbours in the docs and the wrong name was-// carried over: a missing field decodes as 0, so every vector in a batch-// landed in slot 0 and the rest stayed empty.-// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference-type AliyunEmbedResponse struct {- Output struct {- Embeddings []struct {- Embedding []float32 `json:"embedding"`- Index int `json:"index"`- } `json:"embeddings"`- } `json:"output"`- Usage struct {- TotalTokens int `json:"total_tokens"`- } `json:"usage"`- RequestID string `json:"request_id"`-}--// AliyunErrorResponse represents an error response from Aliyun DashScope-type AliyunErrorResponse struct {- Code string `json:"code"`- Message string `json:"message"`- RequestID string `json:"request_id"`-}--// NewAliyunEmbedder creates a new Aliyun DashScope embedder-func NewAliyunEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*AliyunEmbedder, error) {- if baseURL == "" {- baseURL = "https://dashscope.aliyuncs.com"- }-- // Remove trailing slash and any existing path suffix- baseURL = strings.TrimRight(baseURL, "/")- // If baseURL contains /compatible-mode/v1, strip it for multimodal API- if strings.Contains(baseURL, "/compatible-mode/v1") {- baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1)- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &AliyunEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- truncatePromptTokens: truncatePromptTokens,- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3,- }, nil-}--// Embed converts text to vector-func (e *AliyunEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *AliyunEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + AliyunMultimodalEmbeddingEndpoint-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("AliyunEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- // Declare req separately: with `req, err := ...` the `:=` introduces a- // loop-local err, so the `resp, err = client.Do(req)` below writes to- // that copy and the outer err stays nil. Every retry failing then- // returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("AliyunEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("AliyunEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *AliyunEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- // Build contents array from texts- contents := make([]AliyunContent, 0, len(texts))- for _, text := range texts {- contents = append(contents, AliyunContent{Text: text})- }-- // Create request body- reqBody := AliyunEmbedRequest{- Model: e.modelName,- Input: AliyunEmbedInput{- Contents: contents,- },- }- if e.supportsDimensionsParam() {- reqBody.Parameters = &AliyunEmbedParameters{Dimension: e.dimensions}- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- // Try to parse error response- var errResp AliyunErrorResponse- if json.Unmarshal(body, &errResp) == nil && errResp.Message != "" {- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed API error: %s - %s", errResp.Code, errResp.Message)- return nil, fmt.Errorf("API error: %s - %s", errResp.Code, errResp.Message)- }- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed API error: Http Status %s", resp.Status)- return nil, fmt.Errorf("BatchEmbed API error: Http Status %s", resp.Status)- }-- // Parse response- var response AliyunEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- // Extract embedding vectors, restoring input order from `index`.- embeddings := make([][]float32, len(texts))- for _, emb := range response.Output.Embeddings {- if emb.Index < 0 || emb.Index >= len(embeddings) {- return nil, fmt.Errorf("embedding index %d out of range for %d inputs", emb.Index, len(texts))- }- embeddings[emb.Index] = emb.Embedding- }- // An unfilled slot means the response did not cover every input. Returning- // it would store an empty vector and silently poison retrieval, so fail- // instead: the caller can retry or surface the error.- for i, embedding := range embeddings {- if len(embedding) == 0 {- return nil, fmt.Errorf("no embedding returned for input %d of %d", i, len(texts))- }- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *AliyunEmbedder) GetModelName() string {- return e.modelName-}--func (e *AliyunEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--// GetDimensions returns the vector dimensions-func (e *AliyunEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *AliyunEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/aliyun_test.go b/internal/models/embedding/aliyun_test.godeleted file mode 100644index f2ec1018c..000000000--- a/internal/models/embedding/aliyun_test.go+++ /dev/null@@ -1,84 +0,0 @@-package embedding--import (- "context"- "net/http"- "net/http/httptest"- "testing"-)--// documentedMultimodalResponse is the response body of DashScope's multimodal-// embedding API, copied from the reference page so the decoder is pinned-// against the vendor's own example rather than against our structs:-// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference-//-// The position field is `index`. DashScope's *text* embedding API, one page-// over, calls it `text_index`; decoding that name here silently yields 0 for-// every element, which used to collapse a whole batch onto slot 0.-const documentedMultimodalResponse = `{- "output": {- "embeddings": [- {"index": 0, "embedding": [0.1, 0.11], "type": "text"},- {"index": 1, "embedding": [0.2, 0.22], "type": "text"},- {"index": 2, "embedding": [0.3, 0.33], "type": "text"}- ]- },- "usage": {"input_tokens": 3, "output_tokens": 0, "total_tokens": 3},- "request_id": "1fff9502-a6c5-9472-9ee1-73930fdd04c5"-}`--func TestAliyunEmbedderRestoresBatchOrder(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(documentedMultimodalResponse))- }))- defer server.Close()-- embedder, err := NewAliyunEmbedder("key", server.URL, "tongyi-embedding-vision-plus", 0, 0, "model-id", nil)- if err != nil {- t.Fatalf("NewAliyunEmbedder: %v", err)- }-- got, err := embedder.BatchEmbed(context.Background(), []string{"a", "b", "c"})- if err != nil {- t.Fatalf("BatchEmbed: %v", err)- }-- want := [][]float32{{0.1, 0.11}, {0.2, 0.22}, {0.3, 0.33}}- if len(got) != len(want) {- t.Fatalf("got %d embeddings, want %d", len(got), len(want))- }- for i := range want {- if len(got[i]) != len(want[i]) {- t.Fatalf("embedding %d: got %v, want %v", i, got[i], want[i])- }- for j := range want[i] {- if got[i][j] != want[i][j] {- t.Fatalf("embedding %d: got %v, want %v", i, got[i], want[i])- }- }- }-}--// A response that skips an input must fail rather than hand back an empty-// vector: an empty vector is stored and poisons retrieval silently.-func TestAliyunEmbedderFailsOnMissingEmbedding(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"output":{"embeddings":[{"index":0,"embedding":[0.1],"type":"text"}]}}`))- }))- defer server.Close()-- embedder, err := NewAliyunEmbedder("key", server.URL, "tongyi-embedding-vision-plus", 0, 0, "model-id", nil)- if err != nil {- t.Fatalf("NewAliyunEmbedder: %v", err)- }-- if _, err := embedder.BatchEmbed(context.Background(), []string{"a", "b"}); err == nil {- t.Fatal("expected an error when the response covers fewer inputs than requested")- }-}diff --git a/internal/models/embedding/azure_openai.go b/internal/models/embedding/azure_openai.godeleted file mode 100644index 328ea8faa..000000000--- a/internal/models/embedding/azure_openai.go+++ /dev/null@@ -1,233 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "net/url"- "strings"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- "github.com/Tencent/WeKnora/internal/models/api"- "github.com/Tencent/WeKnora/internal/models/catalog"- "github.com/Tencent/WeKnora/internal/models/provider"- "github.com/Tencent/WeKnora/internal/types"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--// AzureOpenAIEmbedder implements text vectorization using Azure OpenAI API-type AzureOpenAIEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- // apiVersion is the stored extra_config.api_version, empty for the v1- // GA data plane. It only selects requestURL; see azureEmbeddingURL.- apiVersion string- requestURL string- httpClient *http.Client- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-func (e *AzureOpenAIEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *AzureOpenAIEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--type azureOpenAIEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- EncodingFormat string `json:"encoding_format,omitempty"`- Dimensions int `json:"dimensions,omitempty"`-}--// NewAzureOpenAIEmbedder creates a new Azure OpenAI embedder-func NewAzureOpenAIEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string,- apiVersion string, pooler EmbedderPooler,-) (*AzureOpenAIEmbedder, error) {- if baseURL == "" {- return nil, fmt.Errorf("Azure resource endpoint (base URL) is required")- }- if modelName == "" {- return nil, fmt.Errorf("deployment name (model name) is required")- }- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &AzureOpenAIEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- truncatePromptTokens: truncatePromptTokens,- dimensions: dimensions,- modelID: modelID,- apiVersion: apiVersion,- requestURL: azureEmbeddingURL(baseURL, modelName, apiVersion),- httpClient: newEmbeddingHTTPClient(60 * time.Second),- maxRetries: 3,- EmbedderPooler: pooler,- }, nil-}--// azureEmbeddingURL resolves the embeddings URL through the catalog's Azure-// vendor, so one stored row lands on the same data plane for embedding as it-// does for chat and VLM (which both go through catalog.Vendor.Endpoint via-// internal/models/chat): an empty api_version means the v1 GA path-// {base}/openai/v1/embeddings with the deployment name in the body's `model`-// field, and a non-empty one means the dated-// {base}/openai/deployments/{deployment}/embeddings?api-version=... path.-// See the package comment of internal/models/vendors/azure_openai for the-// documentation behind that rule.-//-// The literal fallback below only runs if the vendor package was not linked-// in; embedder.go blank-imports internal/models/vendors so it normally is.-func azureEmbeddingURL(baseURL, deployment, apiVersion string) string {- root := strings.TrimRight(strings.TrimSpace(baseURL), "/")- extra := map[string]string{}- version := strings.TrimSpace(apiVersion)- if version != "" {- extra[catalog.ExtraAPIVersion] = version- }- if vendor, ok := catalog.Get(string(provider.ProviderAzureOpenAI)); ok && vendor.Endpoint != nil {- target, query := vendor.Endpoint(catalog.EndpointRequest{- BaseURL: root,- Model: deployment,- ModelType: types.ModelTypeEmbedding,- API: api.APIOpenAICompletions,- Extra: extra,- })- if target != "" {- return api.Endpoint{URL: target, Query: query}.Resolve("")- }- }- if version != "" {- return root + "/openai/deployments/" + url.PathEscape(deployment) +- "/embeddings?api-version=" + version- }- return root + "/openai/v1/embeddings"-}--func (e *AzureOpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *AzureOpenAIEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- reqBody := azureOpenAIEmbedRequest{- Model: e.modelName,- Input: texts,- EncodingFormat: "float",- }- if e.supportsDimensionsParam() {- reqBody.Dimensions = e.dimensions- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- return nil, fmt.Errorf("marshal request: %w", err)- }-- logger.GetLogger(ctx).Debugf("AzureOpenAIEmbedder BatchEmbed: model=%s, input_count=%d",- e.modelName, len(texts))-- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- body, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- bodyStr := string(body)- if len(bodyStr) > 1000 {- bodyStr = bodyStr[:1000] + "... (truncated)"- }- return nil, fmt.Errorf("Azure Embedding API error: Http Status %s, Response: %s", resp.Status, bodyStr)- }-- var response OpenAIEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- embeddings := make([][]float32, 0, len(response.Data))- for _, data := range response.Data {- embeddings = append(embeddings, data.Embedding)- }- return embeddings, nil-}--func (e *AzureOpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- req, reqErr := http.NewRequestWithContext(ctx, "POST", e.requestURL, bytes.NewReader(jsonData))- if reqErr != nil {- err = reqErr- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("api-key", e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }- }- return nil, err-}--func (e *AzureOpenAIEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--func (e *AzureOpenAIEmbedder) GetModelName() string { return e.modelName }-func (e *AzureOpenAIEmbedder) GetDimensions() int { return e.dimensions }-func (e *AzureOpenAIEmbedder) GetModelID() string { return e.modelID }diff --git a/internal/models/embedding/azure_openai_test.go b/internal/models/embedding/azure_openai_test.godeleted file mode 100644index f84a698cf..000000000--- a/internal/models/embedding/azure_openai_test.go+++ /dev/null@@ -1,266 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "io"- "net/http"- "testing"-- "github.com/Tencent/WeKnora/internal/models/api"- "github.com/Tencent/WeKnora/internal/models/catalog"- "github.com/Tencent/WeKnora/internal/types"-)--func TestAzureOpenAIEmbedderBatchEmbedSendsConfiguredDimensions(t *testing.T) {- t.Parallel()-- var requestBody map[string]any- transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {- if r.Method != http.MethodPost {- t.Fatalf("expected POST request, got %s", r.Method)- }-- if got, want := r.URL.String(),- "https://example-resource.openai.azure.com/openai/deployments/text-embedding-3-large-deployment/embeddings?api-version=2024-10-21"; got != want {- t.Fatalf("unexpected request path: got %s want %s", got, want)- }-- if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {- t.Fatalf("decode request body: %v", err)- }-- return &http.Response{- StatusCode: http.StatusOK,- Header: make(http.Header),- Body: io.NopCloser(bytes.NewBufferString(`{"data":[{"embedding":[0.1,0.2],"index":0}]}`)),- }, nil- })-- embedder, err := NewAzureOpenAIEmbedder(- "test-key",- "https://example-resource.openai.azure.com",- "text-embedding-3-large-deployment",- 511,- 256,- "text-embedding-3-large",- "2024-10-21",- nil,- )- if err != nil {- t.Fatalf("create embedder: %v", err)- }- embedder.SetSupportsDimensionOverride(true)- embedder.httpClient = &http.Client{Transport: transport}-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed returned error: %v", err)- }-- got, ok := requestBody["dimensions"]- if !ok {- t.Fatalf("expected request body to include dimensions, got %v", requestBody)- }-- if got != float64(256) {- t.Fatalf("unexpected dimensions value: got %v want 256", got)- }-}--func TestAzureOpenAIEmbedderBatchEmbedOmitsDimensionsByDefault(t *testing.T) {- t.Parallel()-- var requestBody map[string]any- transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {- if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {- t.Fatalf("decode request body: %v", err)- }-- return &http.Response{- StatusCode: http.StatusOK,- Header: make(http.Header),- Body: io.NopCloser(bytes.NewBufferString(`{"data":[{"embedding":[0.1,0.2],"index":0}]}`)),- }, nil- })-- embedder, err := NewAzureOpenAIEmbedder(- "test-key",- "https://example-resource.openai.azure.com",- "ada-002-deployment",- 511,- 1536,- "text-embedding-ada-002",- "2024-10-21",- nil,- )- if err != nil {- t.Fatalf("create embedder: %v", err)- }- embedder.httpClient = &http.Client{Transport: transport}-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed returned error: %v", err)- }-- if _, ok := requestBody["dimensions"]; ok {- t.Fatalf("expected request body to omit dimensions for fixed-size model, got %v", requestBody)- }-}--func TestAzureOpenAIEmbedderBatchEmbedSendsDimensionsWhenOverrideEnabledRegardlessOfAPIVersion(t *testing.T) {- t.Parallel()-- var requestBody map[string]any- transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {- if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {- t.Fatalf("decode request body: %v", err)- }-- return &http.Response{- StatusCode: http.StatusOK,- Header: make(http.Header),- Body: io.NopCloser(bytes.NewBufferString(`{"data":[{"embedding":[0.1,0.2],"index":0}]}`)),- }, nil- })-- embedder, err := NewAzureOpenAIEmbedder(- "test-key",- "https://example-resource.openai.azure.com",- "text-embedding-3-large-deployment",- 511,- 256,- "text-embedding-3-large",- "2024-02-15-preview",- nil,- )- if err != nil {- t.Fatalf("create embedder: %v", err)- }- embedder.SetSupportsDimensionOverride(true)- embedder.httpClient = &http.Client{Transport: transport}-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed returned error: %v", err)- }-- got, ok := requestBody["dimensions"]- if !ok {- t.Fatalf("expected request body to include dimensions when override is enabled, got %v", requestBody)- }- if got != float64(256) {- t.Fatalf("unexpected dimensions value: got %v want 256", got)- }-}--// TestAzureOpenAIEmbedderURLFollowsAPIVersionRule pins the one rule a stored-// Azure row picks its data plane by, the same rule the catalog's Endpoint-// hook applies to that row's chat and VLM clients: an empty api_version means-// the v1 GA path with the deployment name in the body, a non-empty one means-// the dated deployments path. Before the catalog, embedding hard-defaulted to-// 2024-10-21 here and put one row on two different data planes.-func TestAzureOpenAIEmbedderURLFollowsAPIVersionRule(t *testing.T) {- t.Parallel()-- const (- baseURL = "https://example-resource.openai.azure.com"- deployment = "text-embedding-3-large-deployment"- )-- for _, tc := range []struct {- name string- apiVersion string- wantURL string- }{- {- name: "row without api_version uses the v1 GA data plane",- apiVersion: "",- wantURL: baseURL + "/openai/v1/embeddings",- },- {- name: "row with the legacy GA api_version keeps the deployments path",- apiVersion: "2024-10-21",- wantURL: baseURL + "/openai/deployments/" + deployment +- "/embeddings?api-version=2024-10-21",- },- {- name: "row with a preview api_version keeps the deployments path",- apiVersion: "2025-04-01-preview",- wantURL: baseURL + "/openai/deployments/" + deployment +- "/embeddings?api-version=2025-04-01-preview",- },- } {- t.Run(tc.name, func(t *testing.T) {- t.Parallel()-- var gotURL string- var requestBody map[string]any- transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {- gotURL = r.URL.String()- if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {- t.Errorf("decode request body: %v", err)- }- return &http.Response{- StatusCode: http.StatusOK,- Header: make(http.Header),- Body: io.NopCloser(bytes.NewBufferString(- `{"data":[{"embedding":[0.1,0.2],"index":0}]}`)),- }, nil- })-- embedder, err := NewAzureOpenAIEmbedder("test-key", baseURL, deployment,- 511, 256, "text-embedding-3-large", tc.apiVersion, nil)- if err != nil {- t.Fatalf("create embedder: %v", err)- }- embedder.httpClient = &http.Client{Transport: transport}-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed returned error: %v", err)- }- if gotURL != tc.wantURL {- t.Fatalf("request URL = %q, want %q", gotURL, tc.wantURL)- }- // Both shapes carry the deployment name in the body; the v1- // path has nowhere else to put it.- if requestBody["model"] != deployment {- t.Fatalf("request body model = %v, want %q", requestBody["model"], deployment)- }- })- }-}--// TestAzureEmbeddingURLMatchesVendorHook pins that the embedding URL is the-// vendor hook's answer and not a second, parallel implementation of the rule.-func TestAzureEmbeddingURLMatchesVendorHook(t *testing.T) {- t.Parallel()-- vendor, ok := catalog.Get("azure_openai")- if !ok {- t.Fatal("azure_openai vendor is not registered")- }- for _, version := range []string{"", "2024-10-21"} {- extra := map[string]string{}- if version != "" {- extra[catalog.ExtraAPIVersion] = version- }- target, query := vendor.Endpoint(catalog.EndpointRequest{- BaseURL: "https://example-resource.openai.azure.com",- Model: "embed deploy",- ModelType: types.ModelTypeEmbedding,- API: api.APIOpenAICompletions,- Extra: extra,- })- want := api.Endpoint{URL: target, Query: query}.Resolve("")- got := azureEmbeddingURL("https://example-resource.openai.azure.com/", "embed deploy", version)- if got != want {- t.Fatalf("azureEmbeddingURL(api_version=%q) = %q, want the hook's %q", version, got, want)- }- }-}--type roundTripFunc func(*http.Request) (*http.Response, error)--func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {- return f(r)-}diff --git a/internal/models/embedding/dimensions_policy_test.go b/internal/models/embedding/dimensions_policy_test.godeleted file mode 100644index 2353bcb99..000000000--- a/internal/models/embedding/dimensions_policy_test.go+++ /dev/null@@ -1,70 +0,0 @@-package embedding--import "testing"--func TestEmbeddingDimensionsParamRequiresExplicitOverride(t *testing.T) {- tests := []struct {- name string- supports func(bool) bool- }{- {- name: "aliyun",- supports: func(enabled bool) bool {- e := &AliyunEmbedder{dimensions: 1024}- e.SetSupportsDimensionOverride(enabled)- return e.supportsDimensionsParam()- },- },- {- name: "nvidia",- supports: func(enabled bool) bool {- e := &NvidiaEmbedder{dimensions: 1024}- e.SetSupportsDimensionOverride(enabled)- return e.supportsDimensionsParam()- },- },- {- name: "volcengine",- supports: func(enabled bool) bool {- e := &VolcengineEmbedder{dimensions: 1024}- e.SetSupportsDimensionOverride(enabled)- return e.supportsDimensionsParam()- },- },- {- name: "zhipu",- supports: func(enabled bool) bool {- e := &ZhipuEmbedder{dimensions: 1024}- e.SetSupportsDimensionOverride(enabled)- return e.supportsDimensionsParam()- },- },- {- name: "azure_openai",- supports: func(enabled bool) bool {- e := &AzureOpenAIEmbedder{dimensions: 1024}- e.SetSupportsDimensionOverride(enabled)- return e.supportsDimensionsParam()- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := tt.supports(false); got {- t.Fatalf("supportsDimensionsParam() = true with override disabled")- }- if got := tt.supports(true); !got {- t.Fatalf("supportsDimensionsParam() = false with override enabled")- }- })- }-}--func TestEmbeddingDimensionsParamRequiresPositiveDimension(t *testing.T) {- e := &OpenAIEmbedder{dimensions: 0}- e.SetSupportsDimensionOverride(true)- if e.supportsDimensionsParam() {- t.Fatal("expected dimensions param to be omitted when configured dimension is zero")- }-}diff --git a/internal/models/embedding/embedder.go b/internal/models/embedding/embedder.goindex 2c5434996..4e2502cbe 100644--- a/internal/models/embedding/embedder.go+++ b/internal/models/embedding/embedder.go@@ -6,13 +6,11 @@ import ("strings""github.com/Tencent/WeKnora/internal/logger"- "github.com/Tencent/WeKnora/internal/models/provider""github.com/Tencent/WeKnora/internal/models/utils/ollama"- // provider.DetectProvider answers from the vendor catalog, which is empty- // until the vendor packages have run their init. Without this import every- // URL detects as "generic" and the per-vendor embedders below are never- // selected — silently, and only in builds that do not already link the- // container (leaf tests, future tools).+ // catalog.Resolve answers from the vendor catalog, which is empty until+ // the vendor packages have run their init. Without this import every row+ // resolves to the generic vendor — silently, and only in builds that do+ // not already link the container (leaf tests, future tools)._ "github.com/Tencent/WeKnora/internal/models/vendors""github.com/Tencent/WeKnora/internal/tracing/langfuse""github.com/Tencent/WeKnora/internal/types"@@ -114,175 +112,12 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll}func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {- var embedder Embedder- var err errorswitch strings.ToLower(string(config.Source)) {case string(types.ModelSourceLocal):- embedder, err = NewOllamaEmbedder(config.BaseURL,+ return NewOllamaEmbedder(config.BaseURL,config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler, ollamaService)- return embedder, errcase string(types.ModelSourceRemote):- // Detect or use configured provider for routing- providerName := provider.ProviderName(config.Provider)- if providerName == "" {- providerName = provider.DetectProvider(config.BaseURL)- }-- // Route to provider-specific embedders- switch providerName {- case provider.ProviderAliyun:- // 检查是否是多模态嵌入模型- // 多模态模型: tongyi-embedding-vision-*, multimodal-embedding-*- // tex-only模型: text-embedding-v1/v2/v3/v4 应该使用 OpenAI 兼容接口,否则响应格式不匹配、embedding 返回空数组- isMultimodalModel := strings.Contains(strings.ToLower(config.ModelName), "vision") ||- strings.Contains(strings.ToLower(config.ModelName), "multimodal")-- if isMultimodalModel {- // 多模态模型需要使用DashScope专用 API 端点- // 如果用户填写了 OpenAI 兼容模式的 URL,自动修正为多模态 API 的baseURL- baseURL := config.BaseURL- if baseURL == "" {- baseURL = "https://dashscope.aliyuncs.com"- } else if strings.Contains(baseURL, "/compatible-mode/") {- // 移除 compatible-mode 路径,AliyunEmbedder 会自动添加多模态端点- baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1)- baseURL = strings.Replace(baseURL, "/compatible-mode", "", 1)- }- aliyunEmb, aErr := NewAliyunEmbedder(config.APIKey,- baseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if aliyunEmb != nil {- aliyunEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = aliyunEmb, aErr- } else {- baseURL := config.BaseURL- if baseURL == "" || !strings.Contains(baseURL, "/compatible-mode/") {- baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"- }- openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey,- baseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if openaiEmb != nil {- openaiEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = openaiEmb, oErr- }- return embedder, err- case provider.ProviderVolcengine:- // Volcengine Ark uses multimodal embedding API- volcEmb, vErr := NewVolcengineEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if volcEmb != nil {- volcEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = volcEmb, vErr- return embedder, err- case provider.ProviderJina:- // Jina AI uses different API format (truncate instead of truncate_prompt_tokens)- jinaEmb, jErr := NewJinaEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if jinaEmb != nil {- jinaEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = jinaEmb, jErr- return embedder, err- case provider.ProviderAzureOpenAI:- // No default: an empty api_version means the v1 GA data- // plane, exactly as it does for this row's chat and VLM- // clients. Filling in a dated version here would put the- // same stored row on two different data planes.- var apiVersion string- if config.ExtraConfig != nil {- apiVersion = config.ExtraConfig["api_version"]- }- azureEmb, azErr := NewAzureOpenAIEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- apiVersion,- pooler)- if azureEmb != nil {- azureEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = azureEmb, azErr- return embedder, err- case provider.ProviderNvidia:- nvEmb, nErr := NewNvidiaEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.Dimensions,- config.ModelID,- pooler)- if nvEmb != nil {- nvEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = nvEmb, nErr- return embedder, err- case provider.ProviderGemini:- geminiEmb, gErr := NewGeminiEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if geminiEmb != nil {- geminiEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = geminiEmb, gErr- return embedder, err- case provider.ProviderZhipu:- zhipuEmb, zErr := NewZhipuEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if zhipuEmb != nil {- zhipuEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = zhipuEmb, zErr- return embedder, err- case provider.ProviderWeKnoraCloud:- embedder, err = NewWeKnoraCloudEmbedder(config, pooler)- return embedder, err- default:- // Use OpenAI-compatible embedder for other providers- openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey,- config.BaseURL,- config.ModelName,- config.TruncatePromptTokens,- config.Dimensions,- config.ModelID,- pooler)- if openaiEmb != nil {- openaiEmb.SetCustomHeaders(config.CustomHeaders)- }- embedder, err = openaiEmb, oErr- return embedder, err- }+ return newRemoteEmbedder(config, pooler)default:return nil, fmt.Errorf("unsupported embedder source: %s", config.Source)}diff --git a/internal/models/embedding/gemini.go b/internal/models/embedding/gemini.godeleted file mode 100644index 1239d6fb5..000000000--- a/internal/models/embedding/gemini.go+++ /dev/null@@ -1,240 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "strings"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--const geminiEmbeddingBaseURL = "https://generativelanguage.googleapis.com/v1beta"--// GeminiEmbedder implements text vectorization using the native Gemini-// embedContent / batchEmbedContents REST API.-type GeminiEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--type geminiBatchEmbedRequest struct {- Requests []geminiEmbedRequest `json:"requests"`-}--type geminiEmbedRequest struct {- Model string `json:"model"`- Content geminiContent `json:"content"`- TaskType string `json:"taskType,omitempty"`- OutputDimensionality int `json:"output_dimensionality,omitempty"`-}--type geminiContent struct {- Parts []geminiPart `json:"parts"`-}--type geminiPart struct {- Text string `json:"text"`-}--type geminiBatchEmbedResponse struct {- Embeddings []geminiEmbedding `json:"embeddings"`-}--type geminiEmbedding struct {- Values []float32 `json:"values"`-}--func NewGeminiEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*GeminiEmbedder, error) {- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }- if baseURL == "" {- baseURL = geminiEmbeddingBaseURL- }-- baseURL = strings.TrimRight(baseURL, "/")- if strings.HasSuffix(baseURL, "/openai") {- baseURL = strings.TrimSuffix(baseURL, "/openai")- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &GeminiEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: strings.TrimPrefix(modelName, "models/"),- truncatePromptTokens: truncatePromptTokens,- dimensions: dimensions,- modelID: modelID,- httpClient: newEmbeddingHTTPClient(timeout),- timeout: timeout,- maxRetries: 3,- EmbedderPooler: pooler,- }, nil-}--func (e *GeminiEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *GeminiEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--func (e *GeminiEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) == 0 {- return nil, fmt.Errorf("no embedding returned")- }- return embeddings[0], nil-}--func (e *GeminiEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- if len(texts) == 0 {- return nil, nil- }-- requests := make([]geminiEmbedRequest, 0, len(texts))- for _, text := range texts {- req := geminiEmbedRequest{- Model: "models/" + e.modelName,- Content: geminiContent{Parts: []geminiPart{- {Text: text},- }},- }- if e.supportsDimensionOverride && e.dimensions > 0 {- req.OutputDimensionality = e.dimensions- }- requests = append(requests, req)- }-- jsonData, err := json.Marshal(geminiBatchEmbedRequest{Requests: requests})- if err != nil {- logger.GetLogger(ctx).Errorf("GeminiEmbedder BatchEmbed marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- logger.GetLogger(ctx).Debugf("GeminiEmbedder BatchEmbed: model=%s, input_count=%d",- e.modelName, len(texts))-- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("GeminiEmbedder BatchEmbed send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("GeminiEmbedder BatchEmbed read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- bodyStr := string(body)- if len(bodyStr) > 1000 {- bodyStr = bodyStr[:1000] + "... (truncated)"- }- logger.GetLogger(ctx).Errorf("GeminiEmbedder BatchEmbed API error: Http Status %s, Response Body: %s", resp.Status, bodyStr)- return nil, fmt.Errorf("Gemini BatchEmbed API error: Http Status %s, Response: %s", resp.Status, bodyStr)- }-- var response geminiBatchEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("GeminiEmbedder BatchEmbed unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }- if len(response.Embeddings) != len(texts) {- return nil, fmt.Errorf("Gemini BatchEmbed returned %d embeddings for %d inputs", len(response.Embeddings), len(texts))- }-- embeddings := make([][]float32, 0, len(response.Embeddings))- for _, embedding := range response.Embeddings {- embeddings = append(embeddings, embedding.Values)- }- return embeddings, nil-}--func (e *GeminiEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := fmt.Sprintf("%s/models/%s:batchEmbedContents", e.baseURL, e.modelName)-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("GeminiEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("GeminiEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("x-goog-api-key", e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("GeminiEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *GeminiEmbedder) GetModelName() string {- return e.modelName-}--func (e *GeminiEmbedder) GetDimensions() int {- return e.dimensions-}--func (e *GeminiEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/gemini_test.go b/internal/models/embedding/gemini_test.godeleted file mode 100644index 29562ab1a..000000000--- a/internal/models/embedding/gemini_test.go+++ /dev/null@@ -1,116 +0,0 @@-package embedding--import (- "context"- "encoding/json"- "net/http"- "net/http/httptest"- "strings"- "testing"-)--func TestGeminiEmbedderBatchEmbedUsesNativeAPI(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- var gotPath string- var gotAPIKey string- var gotReq geminiBatchEmbedRequest-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- gotPath = r.URL.Path- gotAPIKey = r.Header.Get("x-goog-api-key")- if err := json.NewDecoder(r.Body).Decode(&gotReq); err != nil {- t.Fatalf("decode request: %v", err)- }-- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{- "embeddings": [- {"values": [0.1, 0.2]},- {"values": [0.3, 0.4]}- ]- }`))- }))- defer server.Close()-- embedder, err := NewGeminiEmbedder("test-key", server.URL+"/openai", "gemini-embedding-2",- 0, 768, "model-id", nil)- if err != nil {- t.Fatalf("NewGeminiEmbedder: %v", err)- }-- embeddings, err := embedder.BatchEmbed(context.Background(), []string{"hello", "world"})- if err != nil {- t.Fatalf("BatchEmbed: %v", err)- }-- if gotPath != "/models/gemini-embedding-2:batchEmbedContents" {- t.Fatalf("path = %q, want native batchEmbedContents path", gotPath)- }- if gotAPIKey != "test-key" {- t.Fatalf("x-goog-api-key = %q", gotAPIKey)- }- if len(gotReq.Requests) != 2 {- t.Fatalf("requests len = %d", len(gotReq.Requests))- }- if gotReq.Requests[0].Model != "models/gemini-embedding-2" {- t.Fatalf("request model = %q", gotReq.Requests[0].Model)- }- if gotReq.Requests[0].OutputDimensionality != 0 {- t.Fatalf("output_dimensionality = %d, want omitted by default", gotReq.Requests[0].OutputDimensionality)- }- if gotReq.Requests[0].Content.Parts[0].Text != "hello" {- t.Fatalf("first text = %q", gotReq.Requests[0].Content.Parts[0].Text)- }- if len(embeddings) != 2 || len(embeddings[0]) != 2 || embeddings[1][1] != 0.4 {- t.Fatalf("unexpected embeddings: %#v", embeddings)- }-}--func TestGeminiEmbedderBatchEmbedSendsOutputDimensionalityWhenOverrideEnabled(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- var gotReq geminiBatchEmbedRequest- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if err := json.NewDecoder(r.Body).Decode(&gotReq); err != nil {- t.Fatalf("decode request: %v", err)- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"embeddings":[{"values":[0.1,0.2]}]}`))- }))- defer server.Close()-- embedder, err := NewGeminiEmbedder("test-key", server.URL, "gemini-embedding-2",- 0, 768, "model-id", nil)- if err != nil {- t.Fatalf("NewGeminiEmbedder: %v", err)- }- embedder.SetSupportsDimensionOverride(true)-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed: %v", err)- }- if gotReq.Requests[0].OutputDimensionality != 768 {- t.Fatalf("output_dimensionality = %d, want 768", gotReq.Requests[0].OutputDimensionality)- }-}--func TestGeminiEmbedderReturnsAPIErrorBody(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- http.Error(w, `{"error":"not found"}`, http.StatusNotFound)- }))- defer server.Close()-- embedder, err := NewGeminiEmbedder("test-key", server.URL, "gemini-embedding-2",- 0, 0, "model-id", nil)- if err != nil {- t.Fatalf("NewGeminiEmbedder: %v", err)- }-- _, err = embedder.BatchEmbed(context.Background(), []string{"hello"})- if err == nil || !strings.Contains(err.Error(), "404") {- t.Fatalf("expected 404 error, got %v", err)- }-}diff --git a/internal/models/embedding/jina.go b/internal/models/embedding/jina.godeleted file mode 100644index 3a31e5d15..000000000--- a/internal/models/embedding/jina.go+++ /dev/null@@ -1,219 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--// JinaEmbedder implements text vectorization functionality using Jina AI API-// Jina API is mostly OpenAI-compatible but does NOT support truncate_prompt_tokens-type JinaEmbedder struct {- apiKey string- baseURL string- modelName string- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-func (e *JinaEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *JinaEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// JinaEmbedRequest represents a Jina embedding request-// Note: Jina uses 'truncate' (boolean) instead of 'truncate_prompt_tokens' (integer)-type JinaEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- Truncate bool `json:"truncate,omitempty"` // Whether to truncate text exceeding max token length- Dimensions int `json:"dimensions,omitempty"` // Output embedding dimensions (for models that support it)-}--// JinaEmbedResponse represents a Jina embedding response-type JinaEmbedResponse struct {- Data []struct {- Embedding []float32 `json:"embedding"`- Index int `json:"index"`- } `json:"data"`-}--// NewJinaEmbedder creates a new Jina embedder-func NewJinaEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*JinaEmbedder, error) {- if baseURL == "" {- baseURL = "https://api.jina.ai/v1"- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &JinaEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3,- }, nil-}--// Embed converts text to vector-func (e *JinaEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *JinaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + "/embeddings"-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("JinaEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- // Rebuild request each time to ensure Body is valid.- // Declare req separately: with `req, err := ...` the `:=` introduces a- // loop-local err, so the `resp, err = client.Do(req)` below writes to- // that copy and the outer err stays nil. Every retry failing then- // returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("JinaEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("JinaEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *JinaEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- // Create request body - Jina uses 'truncate' boolean instead of 'truncate_prompt_tokens'- reqBody := JinaEmbedRequest{- Model: e.modelName,- Input: texts,- Truncate: true, // Enable truncation for long texts- }-- if e.supportsDimensionOverride && e.dimensions > 0 {- reqBody.Dimensions = e.dimensions- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- // Send request- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- // Read response- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch API error: Http Status %s, Body: %s", resp.Status, string(body))- return nil, fmt.Errorf("EmbedBatch API error: Http Status %s", resp.Status)- }-- // Parse response- var response JinaEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- // Extract embedding vectors- embeddings := make([][]float32, 0, len(response.Data))- for _, data := range response.Data {- embeddings = append(embeddings, data.Embedding)- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *JinaEmbedder) GetModelName() string {- return e.modelName-}--// GetDimensions returns the vector dimensions-func (e *JinaEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *JinaEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/nvidia.go b/internal/models/embedding/nvidia.godeleted file mode 100644index 560967cf3..000000000--- a/internal/models/embedding/nvidia.go+++ /dev/null@@ -1,228 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- "github.com/Tencent/WeKnora/internal/types"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--// NvidiaEmbedder implements text vectorization functionality using NVIDIA API-type NvidiaEmbedder struct {- apiKey string- baseURL string- modelName string- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-func (e *NvidiaEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *NvidiaEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// NvidiaEmbedRequest represents an NVIDIA embedding request-type NvidiaEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- EncodingFormat string `json:"encoding_format,omitempty"`- Dimensions int `json:"dimensions,omitempty"`- TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`- InputType string `json:"input_type,omitempty"`-}--// NvidiaEmbedResponse represents an NVIDIA embedding response-type NvidiaEmbedResponse struct {- Data []struct {- Embedding []float32 `json:"embedding"`- Index int `json:"index"`- } `json:"data"`-}--// NewNvidiaEmbedder creates a new NVIDIA embedder-func NewNvidiaEmbedder(apiKey, baseURL, modelName string,- dimensions int, modelID string, pooler EmbedderPooler,-) (*NvidiaEmbedder, error) {- if baseURL == "" {- baseURL = "https://integrate.api.nvidia.com/v1"- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &NvidiaEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3, // Maximum retry count- }, nil-}--// Embed converts text to vector-func (e *NvidiaEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *NvidiaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + "/embeddings"-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("NvidiaEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- // Rebuild request each time to ensure Body is valid.- // Declare req separately: with `req, err := ...` the `:=` introduces a- // loop-local err, so the `resp, err = client.Do(req)` below writes to- // that copy and the outer err stays nil. Every retry failing then- // returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("NvidiaEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *NvidiaEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- // Create request body- reqBody := NvidiaEmbedRequest{- Model: e.modelName,- Input: texts,- EncodingFormat: "float",- InputType: "passage",- }- if e.supportsDimensionsParam() {- reqBody.Dimensions = e.dimensions- }- isQuery, _ := ctx.Value(types.EmbedQueryContextKey).(bool)- if isQuery {- reqBody.InputType = "query"- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder EmbedBatch marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- // Send request (passing jsonData instead of constructing http.Request)- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder EmbedBatch send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- // Read response- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder EmbedBatch read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder EmbedBatch API error: Http Status %s", resp.Status)- return nil, fmt.Errorf("EmbedBatch API error: Http Status %s", resp.Status)- }-- // Parse response- var response NvidiaEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("NvidiaEmbedder EmbedBatch unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- // Extract embedding vectors- embeddings := make([][]float32, 0, len(response.Data))- for _, data := range response.Data {- embeddings = append(embeddings, data.Embedding)- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *NvidiaEmbedder) GetModelName() string {- return e.modelName-}--func (e *NvidiaEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--// GetDimensions returns the vector dimensions-func (e *NvidiaEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *NvidiaEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/openai.go b/internal/models/embedding/openai.godeleted file mode 100644index e55c3070d..000000000--- a/internal/models/embedding/openai.go+++ /dev/null@@ -1,269 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--// OpenAIEmbedder implements text vectorization functionality using OpenAI API-type OpenAIEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// OpenAIEmbedRequest represents an OpenAI embedding request-type OpenAIEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- EncodingFormat string `json:"encoding_format,omitempty"`- Dimensions int `json:"dimensions,omitempty"`- TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`-}--// OpenAIEmbedResponse represents an OpenAI embedding response-type OpenAIEmbedResponse struct {- Data []struct {- Embedding []float32 `json:"embedding"`- Index int `json:"index"`- } `json:"data"`-}--// NewOpenAIEmbedder creates a new OpenAI embedder-func NewOpenAIEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*OpenAIEmbedder, error) {- if baseURL == "" {- baseURL = "https://api.openai.com/v1"- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &OpenAIEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- truncatePromptTokens: truncatePromptTokens,- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3, // Maximum retry count- }, nil-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-// 保留头(Authorization、Content-Type 等)会在发送时被自动跳过。-func (e *OpenAIEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *OpenAIEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// Embed converts text to vector-func (e *OpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *OpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + "/embeddings"-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("OpenAIEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- // Rebuild request each time to ensure Body is valid.- // IMPORTANT: declare `req` separately (var) so the assignment to `err`- // below uses the outer-scope variable, not a fresh loop-local one.- // Previously this read `req, err := http.NewRequestWithContext(...)`,- // where `:=` introduced a new `err` shadowing the outer one. The- // `resp, err = httpClient.Do(req)` line then wrote to the shadowed- // `err` only, so when all retries failed with connection errors the- // outer `err` stayed nil. The function returned `(nil, nil)`, and- // callers (BatchEmbed line 195) blindly dereferenced `resp.Body` →- // SIGSEGV nil-pointer panic that took down the whole process.- // Reproduce: stop the embedding upstream (e.g. localhost:3130), make- // any RAG query → backend SIGSEGV instead of returning HTTP 500.- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("OpenAIEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *OpenAIEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- // Create request body- reqBody := OpenAIEmbedRequest{- Model: e.modelName,- Input: texts,- EncodingFormat: "float",- TruncatePromptTokens: e.truncatePromptTokens,- }- if e.supportsDimensionsParam() {- reqBody.Dimensions = e.dimensions- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- // Log request details for debugging- logger.GetLogger(ctx).Debugf("OpenAIEmbedder BatchEmbed: model=%s, input_count=%d, truncate_tokens=%d",- e.modelName, len(texts), e.truncatePromptTokens)-- // Check for invalid input lengths and log details- hasInvalidLength := false- for i, text := range texts {- textLen := len(text)- textPreview := text- if len(textPreview) > 200 {- textPreview = textPreview[:200] + "..."- }-- // Log warning if length is outside valid range [1, 8192]- if textLen == 0 || textLen > 8192 {- hasInvalidLength = true- logger.GetLogger(ctx).Errorf("OpenAIEmbedder BatchEmbed input[%d]: INVALID length=%d (must be [1, 8192]), preview=%s",- i, textLen, textPreview)- } else {- logger.GetLogger(ctx).Debugf("OpenAIEmbedder BatchEmbed input[%d]: length=%d, preview=%s",- i, textLen, textPreview)- }- }-- if hasInvalidLength {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder BatchEmbed: Found invalid input lengths, this will likely cause API error")- }-- // Send request (passing jsonData instead of constructing http.Request)- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- // Read response- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- // Log detailed error response from OpenAI API- bodyStr := string(body)- if len(bodyStr) > 1000 {- bodyStr = bodyStr[:1000] + "... (truncated)"- }- logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch API error: Http Status %s, Response Body: %s", resp.Status, bodyStr)- return nil, fmt.Errorf("EmbedBatch API error: Http Status %s, Response: %s", resp.Status, bodyStr)- }-- // Parse response- var response OpenAIEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("OpenAIEmbedder EmbedBatch unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- // Extract embedding vectors- embeddings := make([][]float32, 0, len(response.Data))- for _, data := range response.Data {- embeddings = append(embeddings, data.Embedding)- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *OpenAIEmbedder) GetModelName() string {- return e.modelName-}--func (e *OpenAIEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--// GetDimensions returns the vector dimensions-func (e *OpenAIEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *OpenAIEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/openai_test.go b/internal/models/embedding/openai_test.godeleted file mode 100644index c9650c161..000000000--- a/internal/models/embedding/openai_test.go+++ /dev/null@@ -1,83 +0,0 @@-package embedding--import (- "context"- "encoding/json"- "net/http"- "net/http/httptest"- "testing"-)--func TestOpenAIEmbedderBatchEmbedOmitsDimensionsByDefault(t *testing.T) {- requestBody := captureOpenAIEmbeddingRequest(t, "text-embedding-3-small", 256, false)-- if _, ok := requestBody["dimensions"]; ok {- t.Fatalf("expected request body to omit dimensions by default, got %v", requestBody)- }-}--func TestOpenAIEmbedderBatchEmbedSendsDimensionsWhenOverrideEnabled(t *testing.T) {- requestBody := captureOpenAIEmbeddingRequest(t, "text-embedding-3-small", 256, true)-- got, ok := requestBody["dimensions"]- if !ok {- t.Fatalf("expected request body to include dimensions, got %v", requestBody)- }- if got != float64(256) {- t.Fatalf("unexpected dimensions value: got %v want 256", got)- }-}--func TestOpenAIEmbedderBatchEmbedOmitsDimensionsForOpenAICompatibleModels(t *testing.T) {- requestBody := captureOpenAIEmbeddingRequest(t, "text-embedding-v3", 1024, false)-- if _, ok := requestBody["dimensions"]; ok {- t.Fatalf("expected request body to omit dimensions for OpenAI-compatible model, got %v", requestBody)- }-}--func TestOpenAIEmbedderBatchEmbedOmitsDimensionsForFixedSizeModels(t *testing.T) {- requestBody := captureOpenAIEmbeddingRequest(t, "text-embedding-ada-002", 1536, false)-- if _, ok := requestBody["dimensions"]; ok {- t.Fatalf("expected request body to omit dimensions for fixed-size model, got %v", requestBody)- }-}--func captureOpenAIEmbeddingRequest(t *testing.T, modelName string, dimensions int, supportsDimensionOverride bool) map[string]any {- t.Helper()- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- requestBody := map[string]any{}- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/embeddings" {- t.Fatalf("unexpected request path: %s", r.URL.Path)- }- if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {- t.Fatalf("decode request body: %v", err)- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"data":[{"embedding":[0.1,0.2],"index":0}]}`))- }))- defer server.Close()-- embedder, err := NewOpenAIEmbedder(- "test-key",- server.URL,- modelName,- 511,- dimensions,- "8f7d6082-5a15-4f84-ae55-88b2bdac4ba0",- nil,- )- if err != nil {- t.Fatalf("NewOpenAIEmbedder: %v", err)- }- embedder.SetSupportsDimensionOverride(supportsDimensionOverride)-- if _, err := embedder.BatchEmbed(context.Background(), []string{"hello"}); err != nil {- t.Fatalf("BatchEmbed: %v", err)- }-- return requestBody-}diff --git a/internal/models/embedding/protocol.go b/internal/models/embedding/protocol.gonew file mode 100644index 000000000..764e88f71--- /dev/null+++ b/internal/models/embedding/protocol.go@@ -0,0 +1,189 @@+package embedding++import (+ "context"+ "fmt"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/api/arkembeddings"+ "github.com/Tencent/WeKnora/internal/models/api/dashscopeembeddings"+ "github.com/Tencent/WeKnora/internal/models/api/googleembeddings"+ "github.com/Tencent/WeKnora/internal/models/api/openaiembeddings"+ "github.com/Tencent/WeKnora/internal/models/catalog"+ "github.com/Tencent/WeKnora/internal/types"+)++// retryPolicy is the transport-error retry budget; tests shorten it.+var retryPolicy = api.DefaultRetryPolicy++// newRemoteEmbedder resolves the catalog and returns the protocol client for+// the configured model, wrapped in the shared batching layer. It mirrors+// rerank.newReranker: the vendor's facts decide the protocol, the URL and the+// credential, and this function knows no vendor names.+func newRemoteEmbedder(config Config, pooler EmbedderPooler) (Embedder, error) {+ if strings.TrimSpace(config.ModelName) == "" {+ return nil, fmt.Errorf("model name is required")+ }+ resolved, err := catalog.Resolve(catalog.Ref{+ Provider: config.Provider,+ Model: config.ModelName,+ BaseURL: config.BaseURL,+ ModelType: types.ModelTypeEmbedding,+ Extra: config.ExtraConfig,+ TruncatePromptTokens: config.TruncatePromptTokens,+ })+ if err != nil {+ return nil, err+ }+ if err := validateEmbeddingBaseURL(resolved.BaseURL); err != nil {+ return nil, err+ }++ vendor := resolved.Vendor+ creds := catalog.Credentials{APIKey: config.APIKey, AppID: config.AppID, AppSecret: config.AppSecret}+ if creds.APIKey == "" {+ creds.APIKey = vendor.DefaultAPIKey+ }+ // A signing vendor with no identity pair would otherwise send unsigned+ // requests and fail at the far end, which is a worse error than this one.+ if vendor.Auth == catalog.AuthSigned {+ if creds.AppID == "" {+ return nil, fmt.Errorf("%s embedding: AppID is required", vendor.Name)+ }+ if creds.AppSecret == "" {+ return nil, fmt.Errorf("%s embedding: AppSecret is required", vendor.Name)+ }+ }+ // Vendor headers first so a user header cannot silently replace a vendor+ // beta flag, matching chat.NewRemoteChat.+ headers := make(map[string]string, len(vendor.Headers)+len(config.CustomHeaders))+ for k, v := range vendor.Headers {+ headers[k] = v+ }+ for k, v := range config.CustomHeaders {+ headers[k] = v+ }+ settings := resolved.Embeddings+ endpoint := api.Endpoint{+ BaseURL: resolved.BaseURL,+ Model: resolved.RemoteModel,+ ModelID: config.ModelID,+ Auth: vendor.AuthFunc(vendor.API, creds),+ Headers: headers,+ Client: newEmbeddingHTTPClient(time.Duration(settings.RequestTimeout) * time.Second),+ }+ if vendor.Endpoint != nil {+ if url, query := vendor.Endpoint(catalog.EndpointRequest{+ BaseURL: resolved.BaseURL,+ Model: resolved.RemoteModel,+ ModelType: types.ModelTypeEmbedding,+ API: vendor.API,+ EmbeddingAPI: resolved.EmbeddingAPI,+ Extra: config.ExtraConfig,+ }); url != "" {+ if err := validateEmbeddingBaseURL(url); err != nil {+ return nil, err+ }+ endpoint.URL, endpoint.Query = url, query+ }+ }++ // The width is the vendor's field but the operator's decision: a row+ // that did not opt in keeps the model's native width even where the+ // vendor could narrow it.+ dimensions := 0+ if config.SupportsDimensionOverride {+ dimensions = config.Dimensions+ }+ retry := retryPolicy()++ var client api.Embedder+ switch resolved.EmbeddingAPI {+ case api.EmbeddingOpenAI:+ client = openaiembeddings.New(openaiembeddings.Config{+ Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,+ })+ case api.EmbeddingDashScope:+ client = dashscopeembeddings.New(dashscopeembeddings.Config{+ Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,+ })+ case api.EmbeddingArk:+ client = arkembeddings.New(arkembeddings.Config{+ Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,+ })+ case api.EmbeddingGoogle:+ client = googleembeddings.New(googleembeddings.Config{+ Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,+ })+ default:+ return nil, fmt.Errorf("unsupported embedding api %q for provider %s", resolved.EmbeddingAPI, vendor.ID)+ }++ return &protocolEmbedder{+ inner: client,+ settings: settings,+ modelName: config.ModelName,+ modelID: config.ModelID,+ dimensions: config.Dimensions,+ EmbedderPooler: pooler,+ }, nil+}++// protocolEmbedder adapts a protocol client to the Embedder interface and+// owns the two things every vendor needs and none of them should implement+// itself: splitting a batch that exceeds the documented per-request ceiling,+// and telling the vendor which side of a search a text is on.+type protocolEmbedder struct {+ inner api.Embedder+ settings catalog.EmbeddingsSettings+ modelName string+ modelID string+ dimensions int+ EmbedderPooler+}++func (e *protocolEmbedder) GetModelName() string { return e.modelName }+func (e *protocolEmbedder) GetModelID() string { return e.modelID }+func (e *protocolEmbedder) GetDimensions() int { return e.dimensions }++func (e *protocolEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {+ vectors, err := e.BatchEmbed(ctx, []string{text})+ if err != nil {+ return nil, err+ }+ return vectors[0], nil+}++func (e *protocolEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {+ if len(texts) == 0 {+ return nil, nil+ }+ kind := api.EmbedDocument+ if types.IsEmbedQuery(ctx) {+ kind = api.EmbedQuery+ }+ batches, err := api.SplitBatches(texts, 0, e.settings.BatchLimits())+ if err != nil {+ return nil, fmt.Errorf("%s embedding: %w", e.modelName, err)+ }+ out := make([][]float32, len(texts))+ // Serial on purpose. BatchEmbedWithPool and the per-model concurrency+ // gate already bound how many requests are in flight; fanning out again+ // here would multiply past both, and a one-text-per-request vendor would+ // turn every pool chunk into a burst.+ for _, batch := range batches {+ vectors, err := e.inner.Embed(ctx, batch.Items, kind)+ if err != nil {+ return nil, err+ }+ if len(vectors) != len(batch.Items) {+ return nil, fmt.Errorf(+ "%s embedding: %d vectors for %d inputs", e.modelName, len(vectors), len(batch.Items),+ )+ }+ copy(out[batch.Start:], vectors)+ }+ return out, nil+}diff --git a/internal/models/embedding/protocol_test.go b/internal/models/embedding/protocol_test.gonew file mode 100644index 000000000..05904b3b2--- /dev/null+++ b/internal/models/embedding/protocol_test.go@@ -0,0 +1,176 @@+package embedding++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/models/api"+ "github.com/Tencent/WeKnora/internal/models/limiter"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/panjf2000/ants/v2"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// An upstream that refuses connections must surface as an error from every+// protocol. The hand-written clients this replaced could each return+// (nil, nil) from their retry loop and dereference a nil response, which took+// the process down instead (Tencent/WeKnora#3484).+func TestUnreachableUpstreamIsAnErrorForEveryProtocol(t *testing.T) {+ allowLoopback(t)+ saved := retryPolicy+ retryPolicy = func() api.RetryPolicy { return api.RetryPolicy{} }+ t.Cleanup(func() { retryPolicy = saved })++ // A server that is started and closed gives a URL whose port refuses.+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))+ url := server.URL+ server.Close()++ for _, tc := range []struct{ provider, model string }{+ {"openai", "text-embedding-3-small"},+ {"aliyun", "tongyi-embedding-vision-plus"},+ {"volcengine", "doubao-embedding-vision-251215"},+ {"gemini", "gemini-embedding-001"},+ } {+ t.Run(tc.provider, func(t *testing.T) {+ embedder, err := newEmbedder(Config{+ Source: types.ModelSourceRemote, Provider: tc.provider,+ BaseURL: url, ModelName: tc.model, APIKey: "k",+ }, nil, nil)+ require.NoError(t, err)+ _, err = embedder.BatchEmbed(context.Background(), []string{"a"})+ assert.Error(t, err)+ })+ }+}++// A signing vendor without its identity pair would send unsigned requests+// and fail at the far end with a less useful error.+func TestSignedVendorNeedsItsIdentityPair(t *testing.T) {+ _, err := newEmbedder(Config{+ Source: types.ModelSourceRemote, Provider: "weknoracloud",+ BaseURL: "https://weknora.weixin.qq.com", ModelName: "m", AppSecret: "s",+ }, nil, nil)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "AppID is required")+}++func TestModelNameIsRequired(t *testing.T) {+ _, err := newEmbedder(Config{Source: types.ModelSourceRemote, Provider: "openai"}, nil, nil)+ assert.Error(t, err)+}++// newPooledEmbedder builds the embedder the way NewEmbedder does for a+// background caller: behind the batch pool and the per-model gate.+func newPooledEmbedder(t *testing.T, handler http.HandlerFunc) Embedder {+ t.Helper()+ allowLoopback(t)+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)+ pool, err := ants.NewPool(4)+ require.NoError(t, err)+ t.Cleanup(pool.Release)+ raw, err := newEmbedder(Config{+ Source: types.ModelSourceRemote, Provider: "generic",+ BaseURL: server.URL + "/v1", ModelName: "m", ModelID: "pooled",+ }, NewBatchEmbedder(pool), nil)+ require.NoError(t, err)+ return wrapEmbeddingConcurrency(raw, 1)+}++func TestPoolBatchesAndPreservesOrder(t *testing.T) {+ t.Setenv("BATCH_EMBED_SIZE", "2")+ var mu sync.Mutex+ var sizes []int+ embedder := newPooledEmbedder(t, func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ mu.Lock()+ sizes = append(sizes, len(body["input"].([]any)))+ mu.Unlock()+ _, _ = w.Write([]byte(answer(r.URL.Path, body)))+ })+ got, err := embedder.BatchEmbedWithPool(+ context.Background(), embedder, []string{"a", "bb", "ccc", "dddd", "eeeee"})+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{1}, {2}, {3}, {4}, {5}}, got)+ assert.Len(t, sizes, 3)+ for _, size := range sizes {+ assert.LessOrEqual(t, size, 2, "request size violates BATCH_EMBED_SIZE=2")+ }+}++func TestPoolHonoursConcurrencyLimit(t *testing.T) {+ t.Setenv("BATCH_EMBED_SIZE", "1")+ limiter.SetGovernor(limiter.NewLocalLimiter(), 10)+ t.Cleanup(func() { limiter.SetGovernor(nil, 0) })+ entered := make(chan struct{}, 2)+ release := make(chan struct{})+ embedder := newPooledEmbedder(t, func(w http.ResponseWriter, _ *http.Request) {+ entered <- struct{}{}+ <-release+ _, _ = fmt.Fprint(w, `{"data":[{"index":0,"embedding":[1]}]}`)+ })+ ctx := types.WithBackgroundTask(context.Background())+ var wg sync.WaitGroup+ var once sync.Once+ unblock := func() { once.Do(func() { close(release) }) }+ t.Cleanup(func() { unblock(); wg.Wait() })+ errs := make(chan error, 2)+ // Separate callers stand for simultaneous batches sharing one model.+ for range 2 {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := embedder.BatchEmbedWithPool(ctx, embedder, []string{"x"})+ errs <- err+ }()+ }+ select {+ case <-entered:+ case <-time.After(2 * time.Second):+ t.Fatal("first request did not reach the upstream")+ }+ select {+ case <-entered:+ t.Error("two requests reached the upstream at once with a model limit of 1")+ case <-time.After(150 * time.Millisecond):+ }+ unblock()+ for range 2 {+ select {+ case err := <-errs:+ assert.NoError(t, err)+ case <-time.After(2 * time.Second):+ t.Fatal("pooled embedding did not complete after release")+ }+ }+}++// Embedding a query is a single call that must carry the query mark all the+// way down; the retrieval pipeline reaches it through Embed, not BatchEmbed.+func TestEmbedCarriesTheQueryMark(t *testing.T) {+ up := newUpstream(t)+ embedder, err := newEmbedder(Config{+ Source: types.ModelSourceRemote, Provider: "nvidia",+ BaseURL: up.url + "/v1", ModelName: "nvidia/nemotron-3-embed-1b", APIKey: "k",+ }, nil, nil)+ require.NoError(t, err)++ _, err = embedder.Embed(types.WithEmbedQuery(context.Background()), "what is it")+ require.NoError(t, err)+ _, err = embedder.Embed(context.Background(), strings.Repeat("passage ", 3))+ require.NoError(t, err)++ require.Len(t, up.requests, 2)+ assert.Equal(t, "query", up.requests[0].body["input_type"])+ assert.Equal(t, "passage", up.requests[1].body["input_type"])+}diff --git a/internal/models/embedding/provider_detection_test.go b/internal/models/embedding/provider_detection_test.godeleted file mode 100644index 682a09ca9..000000000--- a/internal/models/embedding/provider_detection_test.go+++ /dev/null@@ -1,31 +0,0 @@-package embedding--import (- "testing"-- "github.com/Tencent/WeKnora/internal/models/provider"-)--// TestDetectProviderSeesVendorCatalog guards the blank import of-// internal/models/vendors in embedder.go.-//-// provider.DetectProvider is a thin wrapper over catalog.DetectByURL, which-// returns "generic" for every URL while the catalog is empty. Without the-// vendor packages linked in, a stored embedding row that carries no explicit-// provider id falls through newEmbedder's switch to the plain OpenAI-compatible-// embedder: an Azure row loses its api-version/deployment URL, an Aliyun-// multimodal row loses the DashScope endpoint, and both fail at call time.-func TestDetectProviderSeesVendorCatalog(t *testing.T) {- cases := map[string]provider.ProviderName{- "https://my-resource.openai.azure.com": provider.ProviderAzureOpenAI,- "https://dashscope.aliyuncs.com/compatible-mode/v1": provider.ProviderAliyun,- "https://open.bigmodel.cn/api/paas/v4": provider.ProviderZhipu,- "https://api.jina.ai/v1": provider.ProviderJina,- "https://self-hosted-gateway.example.internal/v1": provider.ProviderGeneric,- }- for baseURL, want := range cases {- if got := provider.DetectProvider(baseURL); got != want {- t.Errorf("DetectProvider(%q) = %q, want %q", baseURL, got, want)- }- }-}diff --git a/internal/models/embedding/transport_test.go b/internal/models/embedding/transport_test.goindex 5ea3358aa..7421ac8da 100644--- a/internal/models/embedding/transport_test.go+++ b/internal/models/embedding/transport_test.go@@ -6,6 +6,7 @@ import ("testing""time"+ "github.com/Tencent/WeKnora/internal/types"secutils "github.com/Tencent/WeKnora/internal/utils")@@ -56,16 +57,14 @@ func TestValidateEmbeddingBaseURL_AllowsEmpty(t *testing.T) {}}-func TestNewOpenAIEmbedder_RejectsPrivateBaseURL(t *testing.T) {- _, err := NewOpenAIEmbedder(- "test-key",- "http://169.254.169.254/latest/meta-data",- "text-embedding-3-small",- 511,- 256,- "model-id",- nil,- )+func TestNewEmbedder_RejectsPrivateBaseURL(t *testing.T) {+ _, err := NewEmbedder(Config{+ Source: types.ModelSourceRemote,+ Provider: "openai",+ BaseURL: "http://169.254.169.254/latest/meta-data",+ ModelName: "text-embedding-3-small",+ APIKey: "test-key",+ }, nil, nil)if err == nil {t.Fatal("expected SSRF rejection for link-local metadata URL")}diff --git a/internal/models/embedding/unreachable_upstream_test.go b/internal/models/embedding/unreachable_upstream_test.godeleted file mode 100644index 2ee52030e..000000000--- a/internal/models/embedding/unreachable_upstream_test.go+++ /dev/null@@ -1,112 +0,0 @@-package embedding--import (- "context"- "net/http"- "net/http/httptest"- "testing"-)--// TestEmbeddersReportUnreachableUpstream guards a crash that every-// OpenAI-style embedder here is one keystroke away from.-//-// Each doRequestWithRetry keeps `resp` and `err` in the enclosing scope and-// returns `(nil, err)` once the retries run out. Writing-// `req, err := http.NewRequestWithContext(...)` inside the loop introduces a-// loop-local `err`, so `resp, err = client.Do(req)` updates that copy only and-// the enclosing `err` stays nil. The function then returns `(nil, nil)`,-// BatchEmbed's `if err != nil` does not fire, and the next line dereferences-// `resp.Body` — a nil-pointer panic that takes the process down instead of-// surfacing "connection refused". It was found, documented and fixed in-// openai.go, then re-fixed in zhipu.go and azure_openai.go, while jina.go,-// nvidia.go, aliyun.go and volcengine.go kept the original spelling.-//-// The retry budget is zeroed so the table runs without the backoff sleeps.-func TestEmbeddersReportUnreachableUpstream(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1")-- // A server that is started and immediately closed gives a reachable-looking- // URL whose port refuses connections.- server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))- url := server.URL- server.Close()-- cases := []struct {- name string- make func() (Embedder, error)- }{- {"openai", func() (Embedder, error) {- e, err := NewOpenAIEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"zhipu", func() (Embedder, error) {- e, err := NewZhipuEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"jina", func() (Embedder, error) {- e, err := NewJinaEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"nvidia", func() (Embedder, error) {- e, err := NewNvidiaEmbedder("k", url, "m", 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"gemini", func() (Embedder, error) {- e, err := NewGeminiEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"aliyun", func() (Embedder, error) {- e, err := NewAliyunEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"volcengine", func() (Embedder, error) {- e, err := NewVolcengineEmbedder("k", url, "m", 0, 0, "id", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- {"azure_openai", func() (Embedder, error) {- e, err := NewAzureOpenAIEmbedder("k", url, "m", 0, 0, "id", "", nil)- if e != nil {- e.maxRetries = 0- }- return e, err- }},- }-- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- embedder, err := tc.make()- if err != nil {- t.Fatalf("constructor: %v", err)- }- defer func() {- if r := recover(); r != nil {- t.Fatalf("BatchEmbed panicked instead of returning an error: %v", r)- }- }()- if _, err := embedder.BatchEmbed(context.Background(), []string{"a"}); err == nil {- t.Fatal("expected an error when the upstream refuses connections")- }- })- }-}diff --git a/internal/models/embedding/volcengine.go b/internal/models/embedding/volcengine.godeleted file mode 100644index 59ca449be..000000000--- a/internal/models/embedding/volcengine.go+++ /dev/null@@ -1,278 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "strings"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--const (- // VolcengineMultimodalEmbeddingPath 火山引擎 Ark 多模态 Embedding API 路径- VolcengineMultimodalEmbeddingPath = "/api/v3/embeddings/multimodal"-)--// VolcengineEmbedder implements text vectorization using Volcengine Ark multimodal embedding API-type VolcengineEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。-func (e *VolcengineEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *VolcengineEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// VolcengineEmbedRequest represents a Volcengine Ark multimodal embedding request-type VolcengineEmbedRequest struct {- Model string `json:"model"`- Input []VolcengineInputContent `json:"input"`- Dimensions int `json:"dimensions,omitempty"`-}--// VolcengineInputContent represents a single input item for Volcengine-type VolcengineInputContent struct {- Type string `json:"type"`- Text string `json:"text,omitempty"`- ImageURL *VolcengineImageURL `json:"image_url,omitempty"`-}--// VolcengineImageURL represents the image URL structure for Volcengine-type VolcengineImageURL struct {- URL string `json:"url"`-}--// VolcengineEmbedResponse represents a Volcengine Ark multimodal embedding response-// Multimodal API returns data as an object with embedding array directly-type VolcengineEmbedResponse struct {- Object string `json:"object"`- Data struct {- Embedding []float32 `json:"embedding"`- } `json:"data"`- Model string `json:"model"`- Usage struct {- PromptTokens int `json:"prompt_tokens"`- TotalTokens int `json:"total_tokens"`- } `json:"usage"`-}--// VolcengineErrorResponse represents an error response from Volcengine-type VolcengineErrorResponse struct {- Error struct {- Code string `json:"code"`- Message string `json:"message"`- Type string `json:"type"`- } `json:"error"`-}--// NewVolcengineEmbedder creates a new Volcengine Ark embedder-func NewVolcengineEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*VolcengineEmbedder, error) {- if baseURL == "" {- baseURL = "https://ark.cn-beijing.volces.com"- }-- // Remove trailing slash- baseURL = strings.TrimRight(baseURL, "/")-- // Extract base host if URL contains the full multimodal path- if strings.Contains(baseURL, "/embeddings/multimodal") {- // Strip the path to get base URL- if idx := strings.Index(baseURL, "/api/"); idx != -1 {- baseURL = baseURL[:idx]- }- } else if strings.HasSuffix(baseURL, "/api/v3") {- // If it ends with /api/v3, keep just the host- baseURL = strings.TrimSuffix(baseURL, "/api/v3")- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &VolcengineEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- truncatePromptTokens: truncatePromptTokens,- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3,- }, nil-}--// Embed converts text to vector-func (e *VolcengineEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *VolcengineEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + VolcengineMultimodalEmbeddingPath-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("VolcengineEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- // Declare req separately: with `req, err := ...` the `:=` introduces a- // loop-local err, so the `resp, err = client.Do(req)` below writes to- // that copy and the outer err stays nil. Every retry failing then- // returns (nil, nil) and the caller dereferences resp.Body → SIGSEGV.- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("VolcengineEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *VolcengineEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- embeddings := make([][]float32, len(texts))-- // Volcengine multimodal API returns a single combined embedding for all inputs,- // so we need to call the API once per text for proper batch embedding- for i, text := range texts {- input := []VolcengineInputContent{- {- Type: "text",- Text: text,- },- }-- reqBody := VolcengineEmbedRequest{- Model: e.modelName,- Input: input,- }- if e.supportsDimensionsParam() {- reqBody.Dimensions = e.dimensions- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }-- body, err := io.ReadAll(resp.Body)- resp.Body.Close()- if err != nil {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- var errResp VolcengineErrorResponse- if json.Unmarshal(body, &errResp) == nil && errResp.Error.Message != "" {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed API error: %s - %s", errResp.Error.Code, errResp.Error.Message)- return nil, fmt.Errorf("API error: %s - %s", errResp.Error.Code, errResp.Error.Message)- }- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed API error: Http Status %s", resp.Status)- return nil, fmt.Errorf("BatchEmbed API error: Http Status %s", resp.Status)- }-- var response VolcengineEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- embeddings[i] = response.Data.Embedding- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *VolcengineEmbedder) GetModelName() string {- return e.modelName-}--func (e *VolcengineEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--// GetDimensions returns the vector dimensions-func (e *VolcengineEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *VolcengineEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/embedding/weknoracloud.go b/internal/models/embedding/weknoracloud.godeleted file mode 100644index c521753d4..000000000--- a/internal/models/embedding/weknoracloud.go+++ /dev/null@@ -1,170 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "strings"- "time"-- "github.com/Tencent/WeKnora/internal/models/provider"- "github.com/Tencent/WeKnora/internal/models/utils"- "github.com/google/uuid"-)--const weKnoraCloudEmbedPath = "/api/v1/embeddings"--// WeKnoraCloudEmbedder 实现 embedding.Embedder 接口,对接 WeKnoraCloud /api/v1/embeddings-type WeKnoraCloudEmbedder struct {- modelName string- remoteModelName string- modelID string- appID string- apiKey string- baseURL string- dimensions int- supportsDimensionOverride bool- client *http.Client- EmbedderPooler-}--// NewWeKnoraCloudEmbedder 构造 WeKnoraCloudEmbedder-func NewWeKnoraCloudEmbedder(config Config, pooler EmbedderPooler) (*WeKnoraCloudEmbedder, error) {- if config.AppID == "" {- return nil, fmt.Errorf("WeKnoraCloud embedder: AppID is required")- }- if config.AppSecret == "" {- return nil, fmt.Errorf("WeKnoraCloud embedder: AppSecret is required")- }- remoteModelName := ""- if config.ExtraConfig != nil {- remoteModelName = strings.TrimSpace(config.ExtraConfig["remote_model_name"])- }- baseURL := strings.TrimRight(config.BaseURL, "/")- if baseURL == "" {- baseURL = provider.WeKnoraCloudBaseURL- }- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }- return &WeKnoraCloudEmbedder{- modelName: config.ModelName,- remoteModelName: remoteModelName,- modelID: config.ModelID,- appID: config.AppID,- apiKey: config.AppSecret,- baseURL: baseURL,- dimensions: config.Dimensions,- supportsDimensionOverride: config.SupportsDimensionOverride,- client: newEmbeddingHTTPClient(60 * time.Second),- EmbedderPooler: pooler,- }, nil-}--type weKnoraCloudEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- Dimensions int `json:"dimensions,omitempty"`- TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`-}--type weKnoraCloudEmbedResponse struct {- Data []struct {- Index int `json:"index"`- Embedding []float32 `json:"embedding"`- } `json:"data"`-}--func (e *WeKnoraCloudEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- results, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(results) == 0 {- return nil, fmt.Errorf("weknoracloud embedder: empty response")- }- return results[0], nil-}--func (e *WeKnoraCloudEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- reqBody := weKnoraCloudEmbedRequest{Model: e.effectiveModelName(), Input: texts}- if e.supportsDimensionOverride && e.dimensions > 0 {- reqBody.Dimensions = e.dimensions- }- bodyBytes, err := json.Marshal(reqBody)- if err != nil {- return nil, fmt.Errorf("weknoracloud embedder: marshal: %w", err)- }-- requestID := uuid.New().String()- headers := utils.Sign(e.appID, e.apiKey, requestID, string(bodyBytes))-- req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.baseURL+weKnoraCloudEmbedPath, bytes.NewReader(bodyBytes))- if err != nil {- return nil, fmt.Errorf("weknoracloud embedder: create request: %w", err)- }- req.Header.Set("Content-Type", "application/json")- for k, v := range headers {- req.Header.Set(k, v)- }-- resp, err := e.client.Do(req)- if err != nil {- return nil, fmt.Errorf("weknoracloud embedder: do request: %w", err)- }- defer resp.Body.Close()-- respBytes, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("weknoracloud embedder: read response: %w", err)- }- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("weknoracloud embedder: status %d: %s", resp.StatusCode, string(respBytes))- }-- var embedResp weKnoraCloudEmbedResponse- if err := json.Unmarshal(respBytes, &embedResp); err != nil {- return nil, fmt.Errorf("weknoracloud embedder: unmarshal: %w", err)- }-- result := make([][]float32, len(texts))- seen := make([]bool, len(texts))- for _, item := range embedResp.Data {- if item.Index < 0 || item.Index >= len(result) {- return nil, fmt.Errorf(- "weknoracloud embedder: response index %d out of range for %d inputs",- item.Index,- len(texts),- )- }- if seen[item.Index] {- return nil, fmt.Errorf("weknoracloud embedder: duplicate response index %d", item.Index)- }- result[item.Index] = item.Embedding- seen[item.Index] = true- }- for index, found := range seen {- if !found {- return nil, fmt.Errorf("weknoracloud embedder: missing embedding for input index %d", index)- }- }- return result, nil-}--func (e *WeKnoraCloudEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--func (e *WeKnoraCloudEmbedder) effectiveModelName() string {- if e.remoteModelName != "" {- return e.remoteModelName- }- return e.modelName-}--func (e *WeKnoraCloudEmbedder) GetModelName() string { return e.modelName }-func (e *WeKnoraCloudEmbedder) GetModelID() string { return e.modelID }-func (e *WeKnoraCloudEmbedder) GetDimensions() int { return e.dimensions }diff --git a/internal/models/embedding/weknoracloud_batch_test.go b/internal/models/embedding/weknoracloud_batch_test.godeleted file mode 100644index cb8291b03..000000000--- a/internal/models/embedding/weknoracloud_batch_test.go+++ /dev/null@@ -1,142 +0,0 @@-package embedding--import (- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "reflect"- "strings"- "sync"- "testing"- "time"-- "github.com/Tencent/WeKnora/internal/models/limiter"- "github.com/Tencent/WeKnora/internal/models/provider"- "github.com/Tencent/WeKnora/internal/types"- secutils "github.com/Tencent/WeKnora/internal/utils"- "github.com/panjf2000/ants/v2"-)--type cloudBatchTestTransport func(*http.Request) (*http.Response, error)--func (f cloudBatchTestTransport) RoundTrip(r *http.Request) (*http.Response, error) {- return f(r)-}--// Exercise the factory's pool wiring and the concurrency wrapper with an-// in-memory transport; no requests reach the configured address.-func newCloudBatchTestEmbedder(t *testing.T, transport cloudBatchTestTransport) Embedder {- t.Helper()- t.Setenv("SSRF_WHITELIST", "cloud-batch.invalid")- secutils.ResetSSRFWhitelistForTest()- t.Cleanup(secutils.ResetSSRFWhitelistForTest)- pool, err := ants.NewPool(4)- if err != nil {- t.Fatal(err)- }- t.Cleanup(pool.Release)- raw, err := newEmbedder(Config{- Source: types.ModelSourceRemote, Provider: string(provider.ProviderWeKnoraCloud),- BaseURL: "https://cloud-batch.invalid", ModelID: "cloud-batch-test", ModelName: "test",- AppID: "test-app", AppSecret: "test-secret",- }, NewBatchEmbedder(pool), nil)- if err != nil {- t.Fatal(err)- }- raw.(*WeKnoraCloudEmbedder).client = &http.Client{Transport: transport}- return wrapEmbeddingConcurrency(raw, 1)-}--func TestWeKnoraCloudPoolBatchesAndPreservesOrder(t *testing.T) {- t.Setenv("BATCH_EMBED_SIZE", "2")- var mu sync.Mutex- var sizes []int- embedder := newCloudBatchTestEmbedder(t, func(r *http.Request) (*http.Response, error) {- var input weKnoraCloudEmbedRequest- if err := json.NewDecoder(r.Body).Decode(&input); err != nil {- return nil, err- }- mu.Lock()- sizes = append(sizes, len(input.Input))- mu.Unlock()- // Return provider entries in reverse order to exercise both index- // restoration within a batch and ordered reassembly across batches.- entries := make([]string, 0, len(input.Input))- for i := len(input.Input) - 1; i >= 0; i-- {- entries = append(entries, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, len(input.Input[i])))- }- return &http.Response{- StatusCode: http.StatusOK,- Body: io.NopCloser(strings.NewReader(`{"data":[` + strings.Join(entries, ",") + `]}`)),- }, nil- })- got, err := embedder.BatchEmbedWithPool(context.Background(), embedder, []string{"a", "bb", "ccc", "dddd", "eeeee"})- if err != nil {- t.Fatal(err)- }- if want := [][]float32{{1}, {2}, {3}, {4}, {5}}; !reflect.DeepEqual(got, want) {- t.Fatalf("embeddings = %v, want %v", got, want)- }- if len(sizes) != 3 {- t.Fatalf("request sizes = %v, want three batches", sizes)- }- for _, size := range sizes {- if size < 1 || size > 2 {- t.Fatalf("request size %d violates BATCH_EMBED_SIZE=2", size)- }- }-}--func TestWeKnoraCloudPoolHonoursConcurrencyLimit(t *testing.T) {- t.Setenv("BATCH_EMBED_SIZE", "1")- limiter.SetGovernor(limiter.NewLocalLimiter(), 10)- t.Cleanup(func() { limiter.SetGovernor(nil, 0) })- entered := make(chan struct{}, 2)- release := make(chan struct{})- embedder := newCloudBatchTestEmbedder(t, func(*http.Request) (*http.Response, error) {- entered <- struct{}{}- <-release- return &http.Response{- StatusCode: http.StatusOK,- Body: io.NopCloser(strings.NewReader(`{"data":[{"index":0,"embedding":[1]}]}`)),- }, nil- })- ctx := types.WithBackgroundTask(context.Background())- var wg sync.WaitGroup- var once sync.Once- unblock := func() { once.Do(func() { close(release) }) }- t.Cleanup(func() { unblock(); wg.Wait() })- errs := make(chan error, 2)- // Separate callers represent simultaneous wiki batches sharing a model.- for range 2 {- wg.Add(1)- go func() {- defer wg.Done()- _, err := embedder.BatchEmbedWithPool(ctx, embedder, []string{"x"})- errs <- err- }()- }- select {- case <-entered:- case <-time.After(2 * time.Second):- t.Fatal("first provider request did not enter")- }- select {- case <-entered:- t.Error("two provider requests entered concurrently with model limit=1")- case <-time.After(150 * time.Millisecond):- }- unblock()- for range 2 {- select {- case err := <-errs:- if err != nil {- t.Error(err)- }- case <-time.After(2 * time.Second):- t.Fatal("pooled embedding did not complete after release")- }- }-}diff --git a/internal/models/embedding/weknoracloud_test.go b/internal/models/embedding/weknoracloud_test.godeleted file mode 100644index fe221c4e7..000000000--- a/internal/models/embedding/weknoracloud_test.go+++ /dev/null@@ -1,100 +0,0 @@-package embedding--import (- "context"- "fmt"- "net/http"- "net/http/httptest"- "reflect"- "strings"- "testing"-)--func newWeKnoraCloudEmbedderTestServer(t *testing.T, response string) *WeKnoraCloudEmbedder {- t.Helper()-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != weKnoraCloudEmbedPath {- http.Error(w, fmt.Sprintf("request path = %q, want %q", r.URL.Path, weKnoraCloudEmbedPath), http.StatusNotFound)- return- }- w.Header().Set("Content-Type", "application/json")- _, _ = fmt.Fprint(w, response)- }))- t.Cleanup(server.Close)-- return &WeKnoraCloudEmbedder{- modelName: "test-embedding",- modelID: "test-model-id",- appID: "test-app-id",- apiKey: "test-api-key",- baseURL: server.URL,- client: server.Client(),- }-}--func TestWeKnoraCloudBatchEmbedPreservesInputOrder(t *testing.T) {- embedder := newWeKnoraCloudEmbedderTestServer(t, `{- "data": [- {"index": 1, "embedding": [0.3, 0.4]},- {"index": 0, "embedding": [0.1, 0.2]}- ]- }`)-- got, err := embedder.BatchEmbed(context.Background(), []string{"first", "second"})- if err != nil {- t.Fatalf("BatchEmbed returned error: %v", err)- }- want := [][]float32{{0.1, 0.2}, {0.3, 0.4}}- if !reflect.DeepEqual(got, want) {- t.Fatalf("BatchEmbed result = %v, want %v", got, want)- }-}--func TestWeKnoraCloudBatchEmbedRejectsMalformedResponse(t *testing.T) {- tests := []struct {- name string- response string- texts []string- wantErrMsg string- }{- {- name: "negative index",- response: `{"data": [{"index": -1, "embedding": [0.1, 0.2]}]}`,- texts: []string{"first"},- wantErrMsg: "response index -1 out of range",- },- {- name: "index above input range",- response: `{"data": [{"index": 1, "embedding": [0.1, 0.2]}]}`,- texts: []string{"first"},- wantErrMsg: "response index 1 out of range",- },- {- name: "duplicate index",- response: `{"data": [{"index": 0, "embedding": [0.1]}, {"index": 0, "embedding": [0.2]}]}`,- texts: []string{"first"},- wantErrMsg: "duplicate response index 0",- },- {- name: "missing result",- response: `{"data": [{"index": 0, "embedding": [0.1, 0.2]}]}`,- texts: []string{"first", "second"},- wantErrMsg: "missing embedding for input index 1",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- embedder := newWeKnoraCloudEmbedderTestServer(t, tt.response)-- _, err := embedder.BatchEmbed(context.Background(), tt.texts)- if err == nil {- t.Fatalf("BatchEmbed returned nil error, want error containing %q", tt.wantErrMsg)- }- if !strings.Contains(err.Error(), tt.wantErrMsg) {- t.Fatalf("BatchEmbed error = %q, want it to contain %q", err, tt.wantErrMsg)- }- })- }-}diff --git a/internal/models/embedding/wire_test.go b/internal/models/embedding/wire_test.gonew file mode 100644index 000000000..f9ab4982c--- /dev/null+++ b/internal/models/embedding/wire_test.go@@ -0,0 +1,465 @@+package embedding++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "unicode/utf8"++ "github.com/Tencent/WeKnora/internal/types"+ secutils "github.com/Tencent/WeKnora/internal/utils"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// recorded is one request as the upstream saw it.+type recorded struct {+ path string+ query string+ header http.Header+ body map[string]any+}++// upstream is a stand-in vendor. It answers in whichever shape the request's+// path asks for, one vector per input whose single value is the input's+// length in runes, so that a test can tell which vector went where.+type upstream struct {+ mu sync.Mutex+ requests []recorded+ url string+}++func allowLoopback(t *testing.T) {+ t.Helper()+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ secutils.ResetSSRFWhitelistForTest()+ t.Cleanup(secutils.ResetSSRFWhitelistForTest)+}++func newUpstream(t *testing.T) *upstream {+ t.Helper()+ allowLoopback(t)+ u := &upstream{}+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ u.mu.Lock()+ u.requests = append(u.requests, recorded{r.URL.Path, r.URL.RawQuery, r.Header.Clone(), body})+ u.mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(answer(r.URL.Path, body)))+ }))+ t.Cleanup(server.Close)+ u.url = server.URL+ return u+}++func runeLen(v any) int { return utf8.RuneCountInString(v.(string)) }++// answer replies in the protocol the path belongs to. The OpenAI and+// DashScope shapes are answered in reverse order so that placement by index+// is exercised on every request.+func answer(path string, body map[string]any) string {+ var parts []string+ switch {+ case strings.HasSuffix(path, ":batchEmbedContents"):+ for _, req := range body["requests"].([]any) {+ text := req.(map[string]any)["content"].(map[string]any)["parts"].([]any)[0].(map[string]any)["text"]+ parts = append(parts, fmt.Sprintf(`{"values":[%d]}`, runeLen(text)))+ }+ return `{"embeddings":[` + strings.Join(parts, ",") + `]}`+ case strings.HasSuffix(path, "/multimodal-embedding"):+ contents := body["input"].(map[string]any)["contents"].([]any)+ for i := len(contents) - 1; i >= 0; i-- {+ n := runeLen(contents[i].(map[string]any)["text"])+ parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d],"type":"text"}`, i, n))+ }+ return `{"output":{"embeddings":[` + strings.Join(parts, ",") + `]}}`+ case strings.HasSuffix(path, "/embeddings/multimodal"):+ n := runeLen(body["input"].([]any)[0].(map[string]any)["text"])+ return fmt.Sprintf(`{"data":{"embedding":[%d],"object":"embedding"}}`, n)+ default:+ input := body["input"].([]any)+ for i := len(input) - 1; i >= 0; i-- {+ parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, runeLen(input[i])))+ }+ return `{"data":[` + strings.Join(parts, ",") + `]}`+ }+}++func texts(n int) []string {+ out := make([]string, n)+ for i := range out {+ out[i] = strings.Repeat("x", i+1)+ }+ return out+}++func strs(in []string) []any {+ out := make([]any, len(in))+ for i, s := range in {+ out[i] = s+ }+ return out+}++// TestEmbeddingWireFormatPerVendor pins, for every embedding vendor in the+// catalog, the request the factory actually sends: URL, credential and the+// complete body. Each expectation traces to the vendor's reference as cited+// in its vendor.go; a field appears here only if that page documents it.+func TestEmbeddingWireFormatPerVendor(t *testing.T) {+ three := []string{"a", "bb", "ccc"}+ openAIBody := func(model string, input []string, extra map[string]any) map[string]any {+ body := map[string]any{"model": model, "input": strs(input)}+ for k, v := range extra {+ body[k] = v+ }+ return body+ }+ arkBody := func(model, text string, extra map[string]any) map[string]any {+ body := map[string]any{+ "model": model,+ "input": []any{map[string]any{"type": "text", "text": text}},+ }+ for k, v := range extra {+ body[k] = v+ }+ return body+ }+ dashBody := func(model string, input []string, extra map[string]any) map[string]any {+ contents := make([]any, len(input))+ for i, s := range input {+ contents[i] = map[string]any{"text": s}+ }+ body := map[string]any{"model": model, "input": map[string]any{"contents": contents}}+ for k, v := range extra {+ body[k] = v+ }+ return body+ }+ const dashPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"++ cases := []struct {+ name string+ provider string+ model string+ base string // appended to the upstream URL+ extra map[string]string+ override bool // supports_dimension_override with dimension 256+ truncate int // embedding_parameters.truncate_prompt_tokens+ query bool+ texts []string+ appID string++ wantPath string+ wantQuery string+ wantAuth [2]string+ wantRequests int+ wantBody map[string]any // the first request's body, exactly+ }{+ {+ name: "openai sends dimensions where the row opted in", provider: "openai",+ model: "text-embedding-3-small", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-3-small", three,+ map[string]any{"encoding_format": "float", "dimensions": float64(256)}),+ },+ {+ name: "openai keeps the native width without the opt-in", provider: "openai",+ model: "text-embedding-3-small", base: "/v1",+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-3-small", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "ada-002 has a fixed width", provider: "openai",+ model: "text-embedding-ada-002", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-ada-002", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "generic keeps the historical truncation budget", provider: "generic",+ model: "bge-m3", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("bge-m3", three, map[string]any{+ "encoding_format": "float", "dimensions": float64(256), "truncate_prompt_tokens": float64(511),+ }),+ },+ {+ name: "generic honours the row's truncation budget", provider: "generic",+ model: "bge-m3", base: "/v1", truncate: 256,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("bge-m3", three, map[string]any{+ "encoding_format": "float", "truncate_prompt_tokens": float64(256),+ }),+ },+ {+ name: "gpustack is a vLLM runtime", provider: "gpustack",+ model: "bge-m3", base: "/v1",+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("bge-m3", three, map[string]any{+ "encoding_format": "float", "truncate_prompt_tokens": float64(511),+ }),+ },+ {+ name: "zhipu documents no encoding_format", provider: "zhipu",+ model: "embedding-3", base: "/api/paas/v4", override: true, truncate: 300,+ wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("embedding-3", three, map[string]any{"dimensions": float64(256)}),+ },+ {+ name: "zhipu embedding-2 is fixed at 1024", provider: "zhipu",+ model: "embedding-2", base: "/api/paas/v4", override: true,+ wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("embedding-2", three, nil),+ },+ {+ name: "jina truncates as it always has and sends no task", provider: "jina",+ model: "jina-embeddings-v3", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("jina-embeddings-v3", three,+ map[string]any{"dimensions": float64(256), "truncate": true}),+ },+ {+ name: "nvidia embeds documents as passages", provider: "nvidia",+ model: "nvidia/nemotron-3-embed-1b", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("nvidia/nemotron-3-embed-1b", three, map[string]any{+ "encoding_format": "float", "input_type": "passage", "truncate": "END",+ }),+ },+ {+ name: "nvidia embeds a search query as a query", provider: "nvidia",+ model: "nvidia/nemotron-3-embed-1b", base: "/v1", query: true, texts: []string{"q"},+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("nvidia/nemotron-3-embed-1b", []string{"q"}, map[string]any{+ "encoding_format": "float", "input_type": "query", "truncate": "END",+ }),+ },+ {+ name: "hunyuan takes model and input only", provider: "hunyuan",+ model: "hunyuan-embedding", base: "/v1", override: true, truncate: 300,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("hunyuan-embedding", three, nil),+ },+ {+ name: "modelscope documents nothing beyond the baseline", provider: "modelscope",+ model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three, nil),+ },+ {+ name: "novita documents encoding_format only", provider: "novita",+ model: "baai/bge-m3", base: "/openai/v1", override: true,+ wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("baai/bge-m3", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "siliconflow narrows only the Qwen3 series", provider: "siliconflow",+ model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three,+ map[string]any{"encoding_format": "float", "dimensions": float64(256)}),+ },+ {+ name: "siliconflow bge-m3 has a fixed width", provider: "siliconflow",+ model: "BAAI/bge-m3", base: "/v1", override: true,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("BAAI/bge-m3", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "siliconflow takes up to thirty-two texts", provider: "siliconflow",+ model: "BAAI/bge-m3", base: "/v1", texts: texts(33), wantRequests: 2,+ wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("BAAI/bge-m3", texts(32), map[string]any{"encoding_format": "float"}),+ },+ {+ name: "aliyun text-embedding-v2 has a fixed width and takes 25", provider: "aliyun",+ model: "text-embedding-v2", base: "/compatible-mode/v1", override: true,+ texts: texts(26), wantRequests: 2,+ wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-v2", texts(25), map[string]any{"encoding_format": "float"}),+ },+ {+ name: "openrouter", provider: "openrouter",+ model: "openai/text-embedding-3-small", base: "/api/v1", override: true,+ wantPath: "/api/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("openai/text-embedding-3-small", three,+ map[string]any{"encoding_format": "float", "dimensions": float64(256)}),+ },+ {+ name: "qianfan takes up to sixteen texts", provider: "qianfan",+ model: "embedding-v1", base: "/v2", texts: texts(17), wantRequests: 2,+ wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("embedding-v1", texts(16), map[string]any{"encoding_format": "float"}),+ },+ {+ name: "qianfan tao-8k takes one text", provider: "qianfan",+ model: "tao-8k", base: "/v2", wantRequests: 3,+ wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("tao-8k", []string{"a"}, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "aliyun text models use the compatible endpoint", provider: "aliyun",+ model: "text-embedding-v4", base: "/compatible-mode/v1", override: true,+ texts: texts(12), wantRequests: 2,+ wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-v4", texts(10),+ map[string]any{"encoding_format": "float", "dimensions": float64(256)}),+ },+ {+ name: "aliyun text models from a bare host", provider: "aliyun",+ model: "text-embedding-v4",+ wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("text-embedding-v4", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "aliyun text model not yet in the catalog", provider: "aliyun",+ model: "qwen3.8-text-embedding", base: "/compatible-mode/v1",+ wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: openAIBody("qwen3.8-text-embedding", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "aliyun vision plus uses the native API at a fixed width", provider: "aliyun",+ model: "tongyi-embedding-vision-plus", base: "/compatible-mode/v1", override: true,+ wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: dashBody("tongyi-embedding-vision-plus", three, nil),+ },+ {+ name: "aliyun qwen3-vl-embedding narrows under parameters", provider: "aliyun",+ model: "qwen3-vl-embedding", base: "/compatible-mode/v1", override: true,+ wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: dashBody("qwen3-vl-embedding", three,+ map[string]any{"parameters": map[string]any{"dimension": float64(256)}}),+ },+ {+ name: "aliyun qwen2.5-vl-embedding fuses, so one text per request", provider: "aliyun",+ model: "qwen2.5-vl-embedding", base: "/compatible-mode/v1", wantRequests: 3,+ wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: dashBody("qwen2.5-vl-embedding", []string{"a"}, nil),+ },+ {+ name: "volcengine fuses, so one text per request", provider: "volcengine",+ model: "doubao-embedding-vision-251215", base: "/api/v3/embeddings/multimodal",+ override: true, wantRequests: 3,+ wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: arkBody("doubao-embedding-vision-251215", "a",+ map[string]any{"encoding_format": "float", "dimensions": float64(256)}),+ },+ {+ name: "volcengine from the chat base URL", provider: "volcengine",+ model: "doubao-embedding-vision-251215", base: "/api/v3", wantRequests: 3,+ wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),+ },+ {+ name: "volcengine from a bare host", provider: "volcengine",+ model: "doubao-embedding-vision-251215", wantRequests: 3,+ wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},+ wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),+ },+ {+ name: "volcengine retired text models keep their own endpoint", provider: "volcengine",+ model: "doubao-embedding-text-240715", base: "/api/v3/embeddings/multimodal", override: true,+ wantPath: "/api/v3/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},+ // The archived reference lists encoding_format too, and no dimensions.+ wantBody: openAIBody("doubao-embedding-text-240715", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "gemini posts to the native method", provider: "gemini",+ model: "gemini-embedding-001", base: "/v1beta", override: true, texts: []string{"a"},+ wantPath: "/v1beta/models/gemini-embedding-001:batchEmbedContents",+ wantAuth: [2]string{"X-Goog-Api-Key", "k"},+ wantBody: map[string]any{"requests": []any{map[string]any{+ "model": "models/gemini-embedding-001",+ "content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},+ "embedContentConfig": map[string]any{"outputDimensionality": float64(256)},+ }}},+ },+ {+ name: "gemini rows on the OpenAI facade still embed natively", provider: "gemini",+ model: "gemini-embedding-2", base: "/v1beta/openai", texts: []string{"a"},+ wantPath: "/v1beta/models/gemini-embedding-2:batchEmbedContents",+ wantAuth: [2]string{"X-Goog-Api-Key", "k"},+ wantBody: map[string]any{"requests": []any{map[string]any{+ "model": "models/gemini-embedding-2",+ "content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},+ }}},+ },+ {+ name: "azure without api_version uses the v1 data plane", provider: "azure_openai",+ model: "my-deployment",+ wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Api-Key", "k"},+ wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "azure with api_version uses the deployments path", provider: "azure_openai",+ model: "my-deployment", extra: map[string]string{"api_version": "2024-10-21"},+ wantPath: "/openai/deployments/my-deployment/embeddings", wantQuery: "api-version=2024-10-21",+ wantAuth: [2]string{"Api-Key", "k"},+ wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),+ },+ {+ name: "weknoracloud signs its own path", provider: "weknoracloud",+ model: "cloud-embedding", appID: "app",+ wantPath: "/api/v1/embeddings", wantAuth: [2]string{"X-Appid", "app"},+ wantBody: openAIBody("cloud-embedding", three, nil),+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ up := newUpstream(t)+ input := tc.texts+ if input == nil {+ input = three+ }+ config := Config{+ Source: types.ModelSourceRemote,+ Provider: tc.provider,+ BaseURL: up.url + tc.base,+ ModelName: tc.model,+ APIKey: "k",+ Dimensions: 256,+ SupportsDimensionOverride: tc.override,+ TruncatePromptTokens: tc.truncate,+ ExtraConfig: tc.extra,+ AppID: tc.appID,+ AppSecret: "secret",+ }+ embedder, err := newEmbedder(config, nil, nil)+ require.NoError(t, err)++ ctx := context.Background()+ if tc.query {+ ctx = types.WithEmbedQuery(ctx)+ }+ got, err := embedder.BatchEmbed(ctx, input)+ require.NoError(t, err)++ want := make([][]float32, len(input))+ for i, s := range input {+ want[i] = []float32{float32(utf8.RuneCountInString(s))}+ }+ assert.Equal(t, want, got, "every vector must come back in its own slot")++ wantRequests := tc.wantRequests+ if wantRequests == 0 {+ wantRequests = 1+ }+ require.Len(t, up.requests, wantRequests)+ first := up.requests[0]+ assert.Equal(t, tc.wantPath, first.path)+ assert.Equal(t, tc.wantQuery, first.query)+ assert.Equal(t, tc.wantAuth[1], first.header.Get(tc.wantAuth[0]))+ assert.Equal(t, tc.wantBody, first.body)+ })+ }+}diff --git a/internal/models/embedding/zhipu.go b/internal/models/embedding/zhipu.godeleted file mode 100644index 513487dc0..000000000--- a/internal/models/embedding/zhipu.go+++ /dev/null@@ -1,256 +0,0 @@-package embedding--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "time"-- "github.com/Tencent/WeKnora/internal/logger"- "github.com/Tencent/WeKnora/internal/models/provider"- secutils "github.com/Tencent/WeKnora/internal/utils"-)--// ZhipuEmbedder implements text vectorization functionality using Zhipu AI API-type ZhipuEmbedder struct {- apiKey string- baseURL string- modelName string- truncatePromptTokens int- dimensions int- modelID string- httpClient *http.Client- timeout time.Duration- maxRetries int- customHeaders map[string]string- supportsDimensionOverride bool- EmbedderPooler-}--// ZhipuEmbedRequest represents a Zhipu embedding request-type ZhipuEmbedRequest struct {- Model string `json:"model"`- Input []string `json:"input"`- Dimensions int `json:"dimensions,omitempty"`- TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`-}--// ZhipuEmbedResponse represents a Zhipu embedding response-type ZhipuEmbedResponse struct {- Data []struct {- Embedding []float32 `json:"embedding"`- Index int `json:"index"`- } `json:"data"`- Model string `json:"model"`-}--// NewZhipuEmbedder creates a new Zhipu embedder-func NewZhipuEmbedder(apiKey, baseURL, modelName string,- truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,-) (*ZhipuEmbedder, error) {- if baseURL == "" {- baseURL = provider.ZhipuEmbeddingBaseURL- }-- if modelName == "" {- return nil, fmt.Errorf("model name is required")- }-- if truncatePromptTokens == 0 {- truncatePromptTokens = 511- }-- timeout := 60 * time.Second-- if err := validateEmbeddingBaseURL(baseURL); err != nil {- return nil, err- }-- return &ZhipuEmbedder{- apiKey: apiKey,- baseURL: baseURL,- modelName: modelName,- httpClient: newEmbeddingHTTPClient(timeout),- truncatePromptTokens: truncatePromptTokens,- EmbedderPooler: pooler,- dimensions: dimensions,- modelID: modelID,- timeout: timeout,- maxRetries: 3, // Maximum retry count- }, nil-}--// SetCustomHeaders sets custom HTTP headers for the embedder-func (e *ZhipuEmbedder) SetCustomHeaders(headers map[string]string) {- e.customHeaders = headers-}--func (e *ZhipuEmbedder) SetSupportsDimensionOverride(supported bool) {- e.supportsDimensionOverride = supported-}--// Embed converts text to vector-func (e *ZhipuEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {- for range 3 {- embeddings, err := e.BatchEmbed(ctx, []string{text})- if err != nil {- return nil, err- }- if len(embeddings) > 0 {- return embeddings[0], nil- }- }- return nil, fmt.Errorf("no embedding returned")-}--func (e *ZhipuEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {- var resp *http.Response- var err error- url := e.baseURL + "/embeddings"-- for i := 0; i <= e.maxRetries; i++ {- if i > 0 {- backoffTime := time.Duration(1<<uint(i-1)) * time.Second- if backoffTime > 10*time.Second {- backoffTime = 10 * time.Second- }- logger.GetLogger(ctx).- Infof("ZhipuEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)-- select {- case <-time.After(backoffTime):- case <-ctx.Done():- return nil, ctx.Err()- }- }-- var req *http.Request- req, err = http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))- if err != nil {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder failed to create request: %v", err)- continue- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+e.apiKey)- secutils.ApplyCustomHeaders(req, e.customHeaders)-- resp, err = e.httpClient.Do(req)- if err == nil {- return resp, nil- }-- logger.GetLogger(ctx).Errorf("ZhipuEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)- }-- return nil, err-}--func (e *ZhipuEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {- // Create request body- reqBody := ZhipuEmbedRequest{- Model: e.modelName,- Input: texts,- TruncatePromptTokens: e.truncatePromptTokens,- }- if e.supportsDimensionsParam() {- reqBody.Dimensions = e.dimensions- }-- jsonData, err := json.Marshal(reqBody)- if err != nil {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed marshal request error: %v", err)- return nil, fmt.Errorf("marshal request: %w", err)- }-- // Log request details for debugging- logger.GetLogger(ctx).Debugf("ZhipuEmbedder BatchEmbed: model=%s, input_count=%d, truncate_tokens=%d",- e.modelName, len(texts), e.truncatePromptTokens)-- // Check for invalid input lengths and log details- hasInvalidLength := false- for i, text := range texts {- textLen := len(text)- textPreview := text- if len(textPreview) > 200 {- textPreview = textPreview[:200] + "..."- }-- // Log warning if length is outside valid range [1, 8192]- if textLen == 0 || textLen > 8192 {- hasInvalidLength = true- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed input[%d]: INVALID length=%d (must be [1, 8192]), preview=%s",- i, textLen, textPreview)- } else {- logger.GetLogger(ctx).Debugf("ZhipuEmbedder BatchEmbed input[%d]: length=%d, preview=%s",- i, textLen, textPreview)- }- }-- if hasInvalidLength {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed: Found invalid input lengths, this will likely cause API error")- }-- // Send request (passing jsonData instead of constructing http.Request)- resp, err := e.doRequestWithRetry(ctx, jsonData)- if err != nil {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed send request error: %v", err)- return nil, fmt.Errorf("send request: %w", err)- }- if resp.Body != nil {- defer resp.Body.Close()- }-- // Read response- body, err := io.ReadAll(resp.Body)- if err != nil {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed read response error: %v", err)- return nil, fmt.Errorf("read response: %w", err)- }-- if resp.StatusCode != http.StatusOK {- // Log detailed error response from OpenAI API- bodyStr := string(body)- if len(bodyStr) > 1000 {- bodyStr = bodyStr[:1000] + "... (truncated)"- }- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed API error: Http Status %s, Response Body: %s", resp.Status, bodyStr)- return nil, fmt.Errorf("BatchEmbed API error: Http Status %s, Response: %s", resp.Status, bodyStr)- }-- // Parse response- var response ZhipuEmbedResponse- if err := json.Unmarshal(body, &response); err != nil {- logger.GetLogger(ctx).Errorf("ZhipuEmbedder BatchEmbed unmarshal response error: %v", err)- return nil, fmt.Errorf("unmarshal response: %w", err)- }-- // Extract embedding vectors- embeddings := make([][]float32, 0, len(response.Data))- for _, data := range response.Data {- embeddings = append(embeddings, data.Embedding)- }-- return embeddings, nil-}--// GetModelName returns the model name-func (e *ZhipuEmbedder) GetModelName() string {- return e.modelName-}--func (e *ZhipuEmbedder) supportsDimensionsParam() bool {- return e.supportsDimensionOverride && e.dimensions > 0-}--// GetDimensions returns the vector dimensions-func (e *ZhipuEmbedder) GetDimensions() int {- return e.dimensions-}--// GetModelID returns the model ID-func (e *ZhipuEmbedder) GetModelID() string {- return e.modelID-}diff --git a/internal/models/vendors/aliyun/models.json b/internal/models/vendors/aliyun/models.jsonindex efb3f0807..bff7b78f8 100644--- a/internal/models/vendors/aliyun/models.json+++ b/internal/models/vendors/aliyun/models.json@@ -42,11 +42,18 @@{"id": "kimi-k2.6", "name": "Kimi K2.6", "reasoning": true, "input": ["text", "image", "video"], "context_window": 262144, "max_output_tokens": 16384, "cost": {"input": 0.929, "output": 3.858}, "compat": {"thinking_always_send": true, "thinking_disable_on_non_stream": true}},{"id": "glm-5.3", "name": "GLM-5.3", "reasoning": true, "input": ["text"], "context_window": 1000000, "max_output_tokens": 131072, "cost": {"input": 1.1, "output": 3.851, "cache_read": 0.275}, "compat": {"thinking_always_send": true, "thinking_disable_on_non_stream": true, "supports_reasoning_effort": true}, "thinking_levels": {"off": null, "minimal": "low", "low": "low", "medium": "high", "high": "high", "xhigh": "max", "max": "max"}, "source": "https://docs.bigmodel.cn/cn/guide/models/text/glm-5.3"},- {"id": "qwen3.7-text-embedding", "name": "Qwen3.7 Text Embedding", "type": "Embedding", "dimension": 1024, "source": "https://help.aliyun.com/zh/model-studio/embedding"},- {"id": "qwen3.7-text-embedding-flash", "name": "Qwen3.7 Text Embedding Flash", "type": "Embedding", "dimension": 1024, "source": "https://help.aliyun.com/zh/model-studio/embedding"},- {"id": "text-embedding-v4", "name": "Tongyi text-embedding-v4", "type": "Embedding", "dimension": 1024, "source": "https://help.aliyun.com/zh/model-studio/embedding"},- {"id": "text-embedding-v3", "name": "Tongyi text-embedding-v3", "type": "Embedding", "dimension": 1024, "source": "https://help.aliyun.com/zh/model-studio/embedding"},- {"id": "tongyi-embedding-vision-plus", "name": "Tongyi Embedding Vision Plus", "type": "Embedding", "dimension": 1152, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api"},+ {"id": "qwen3.7-text-embedding", "name": "Qwen3.7 Text Embedding", "type": "Embedding", "dimension": 1024, "compat": {"max_batch_size": 20}, "source": "https://help.aliyun.com/zh/model-studio/embedding"},+ {"id": "qwen3.7-text-embedding-flash", "name": "Qwen3.7 Text Embedding Flash", "type": "Embedding", "dimension": 1024, "compat": {"max_batch_size": 20}, "source": "https://help.aliyun.com/zh/model-studio/embedding"},+ {"id": "text-embedding-v4", "name": "Tongyi text-embedding-v4", "type": "Embedding", "dimension": 1024, "compat": {"max_batch_size": 10}, "source": "https://help.aliyun.com/zh/model-studio/embedding"},+ {"id": "text-embedding-v3", "name": "Tongyi text-embedding-v3", "type": "Embedding", "dimension": 1024, "compat": {"max_batch_size": 10}, "source": "https://help.aliyun.com/zh/model-studio/embedding"},+ {"name": "text-embedding-v2 (fixed 1536 dimensions)", "match": "text-embedding-v2", "type": "Embedding", "compat": {"dimensions_field": "", "max_batch_size": 25}, "source": "https://help.aliyun.com/zh/model-studio/embedding-interfaces-compatible-with-openai"},+ {"name": "text-embedding-v1 (fixed 1536 dimensions)", "match": "text-embedding-v1", "type": "Embedding", "compat": {"dimensions_field": "", "max_batch_size": 25}, "source": "https://help.aliyun.com/zh/model-studio/embedding-interfaces-compatible-with-openai"},+ {"id": "tongyi-embedding-vision-plus", "name": "Tongyi Embedding Vision Plus", "type": "Embedding", "dimension": 1152, "compat": {"api": "dashscope-embeddings", "dimensions_field": ""}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},+ {"name": "tongyi-embedding-vision-flash (fixed 768 dimensions)", "match": "tongyi-embedding-vision-flash", "type": "Embedding", "compat": {"api": "dashscope-embeddings", "dimensions_field": ""}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},+ {"name": "tongyi-embedding-vision snapshots", "match": "tongyi-embedding-vision*", "type": "Embedding", "compat": {"api": "dashscope-embeddings", "dimensions_field": "dimension", "max_batch_size": 20}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},+ {"name": "qwen3-vl-embedding (independent vectors by default)", "match": "qwen3-vl-embedding*", "type": "Embedding", "compat": {"api": "dashscope-embeddings", "dimensions_field": "dimension", "max_batch_size": 20}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},+ {"name": "qwen2.5-vl-embedding (fused vectors only)", "match": "qwen2.5-vl-embedding*", "type": "Embedding", "compat": {"api": "dashscope-embeddings", "dimensions_field": "dimension", "max_batch_size": 1}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},+ {"name": "multimodal-embedding-v1", "match": "multimodal-embedding*", "type": "Embedding", "compat": {"api": "dashscope-embeddings", "dimensions_field": "", "max_batch_size": 20}, "source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{"id": "qwen3-rerank", "name": "Qwen3 Rerank (separate endpoint, not implemented)", "type": "Rerank", "deprecated": true, "compat": {"unsupported_reason": "qwen3-rerank speaks a different protocol (/compatible-api/v1/reranks, flat request, results at the top level) that no protocol package implements yet"}, "source": "https://help.aliyun.com/zh/model-studio/text-rerank-api"},{"id": "gte-rerank-v2", "name": "GTE Rerank v2", "type": "Rerank", "source": "https://help.aliyun.com/zh/model-studio/text-rerank-api"}]diff --git a/internal/models/vendors/aliyun/vendor.go b/internal/models/vendors/aliyun/vendor.goindex 0421dba26..36d9da82d 100644--- a/internal/models/vendors/aliyun/vendor.go+++ b/internal/models/vendors/aliyun/vendor.go@@ -82,6 +82,7 @@ package aliyunimport (_ "embed"+ "strings""github.com/Tencent/WeKnora/internal/models/api""github.com/Tencent/WeKnora/internal/models/catalog"@@ -107,6 +108,10 @@ const RerankBaseURL = "https://dashscope.aliyuncs.com/api/v1/services/rerank/tex// default for this vendor; operators who want it configure it explicitly.const AnthropicBaseURL = "https://dashscope.aliyuncs.com/apps/anthropic"+// multimodalEmbeddingPath is the native multimodal embedding method+// (https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference).+const multimodalEmbeddingPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"+func init() {catalog.Register(&catalog.Vendor{ID: ID,@@ -133,7 +138,39 @@ func init() {types.ModelTypeVLLM,},RerankAPI: api.RerankDashScope,+ // Text and multimodal embeddings live under different roots of the+ // same host — /compatible-mode/v1 and /api/v1 — and a row stores one+ // base URL for both, so the request is placed from the host. A base+ // URL without either root is taken as the host itself, which keeps a+ // workspace or international domain instead of replacing it with the+ // Beijing default as the pre-catalog client did.+ Endpoint: func(r catalog.EndpointRequest) (string, map[string]string) {+ if r.ModelType != types.ModelTypeEmbedding {+ return "", nil+ }+ root := strings.TrimRight(r.BaseURL, "/")+ for _, marker := range []string{"/compatible-mode", "/api/v1"} {+ if i := strings.Index(root, marker); i >= 0 {+ root = root[:i]+ }+ }+ if r.EmbeddingAPI == api.EmbeddingDashScope {+ return root + multimodalEmbeddingPath, nil+ }+ return root + "/compatible-mode/v1/embeddings", nil+ },Compat: catalog.VendorCompat{+ // Text models: the OpenAI-compatible endpoint+ // (https://help.aliyun.com/zh/model-studio/embedding-interfaces-compatible-with-openai),+ // which takes model, input, dimensions and encoding_format.+ // Multimodal models "不支持OpenAI兼容接口" and override the protocol+ // in models.json. The native APIs' text_type / instruct are not+ // declared: both change the document vectors+ // (Tencent/WeKnora#1401).+ Embeddings: catalog.EmbeddingsCompat{+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ },Rerank: catalog.RerankCompat{SendReturnDocs: catalog.Ptr(true),// 500 documents per request for the native text-rerank models.diff --git a/internal/models/vendors/azure_openai/vendor.go b/internal/models/vendors/azure_openai/vendor.goindex 566c3a7f1..8c3e34188 100644--- a/internal/models/vendors/azure_openai/vendor.go+++ b/internal/models/vendors/azure_openai/vendor.go@@ -154,6 +154,12 @@ func init() {},},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // The same body as OpenAI's; the Endpoint hook below supplies the+ // v1 or deployments URL.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatOpenAI),SupportsReasoningEffort: catalog.Ptr(true),diff --git a/internal/models/vendors/gemini/vendor.go b/internal/models/vendors/gemini/vendor.goindex fb36f668f..7694f0261 100644--- a/internal/models/vendors/gemini/vendor.go+++ b/internal/models/vendors/gemini/vendor.go@@ -84,6 +84,7 @@ func init() {Website: "https://aistudio.google.com",Icon: icon,API: api.APIGoogleGenerativeAI,+ EmbeddingAPI: api.EmbeddingGoogle,Order: 33,RequiresAuth: true,Auth: catalog.AuthGoogleAPIKey,@@ -104,6 +105,18 @@ func init() {types.ModelTypeEmbedding,},Compat: catalog.VendorCompat{+ // https://ai.google.dev/api/embeddings: per request model, content+ // and embedContentConfig {taskType, title, outputDimensionality,+ // autoTruncate, …}; the same option names at the top level of the+ // request are marked deprecated. The pre-catalog client sent the+ // width top-level as output_dimensionality, which the proto JSON+ // parser reads as the same field. taskType exists on+ // gemini-embedding-001 only and is deliberately not declared: it+ // changes the document vectors, so turning it on would split every+ // existing index across two spaces (Tencent/WeKnora#1401).+ Embeddings: catalog.EmbeddingsCompat{+ DimensionsField: catalog.Ptr("outputDimensionality"),+ },// Used when the operator points base_url at the /openai facade.OpenAICompletions: catalog.OpenAICompletionsCompat{ToolCallExtraFields: []string{"extra_content"},diff --git a/internal/models/vendors/generic/vendor.go b/internal/models/vendors/generic/vendor.goindex 41c7d9611..8b7a0424b 100644--- a/internal/models/vendors/generic/vendor.go+++ b/internal/models/vendors/generic/vendor.go@@ -108,6 +108,15 @@ func init() {ModelTypes: []types.ModelType{types.ModelTypeRerank},}},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // Whatever the operator runs. Everything the pre-catalog client+ // sent stays: vLLM, SGLang, TEI and Ollama's OpenAI route all+ // accept it, and dimensions still goes out only when the row+ // asks for a width.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ AcceptsTruncatePromptTokens: catalog.Ptr(true),+ },Rerank: catalog.RerankCompat{// Any OpenAI-compatible endpoint an operator points here is most// often a vLLM or SGLang server, which is wherediff --git a/internal/models/vendors/gpustack/vendor.go b/internal/models/vendors/gpustack/vendor.goindex cae8ee7c2..89f24dc0d 100644--- a/internal/models/vendors/gpustack/vendor.go+++ b/internal/models/vendors/gpustack/vendor.go@@ -118,6 +118,13 @@ func init() {ModelTypes: []types.ModelType{types.ModelTypeRerank},}},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // vLLM's embedding server: dimensions for Matryoshka models, the+ // row's truncation budget, and encoding_format.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ AcceptsTruncatePromptTokens: catalog.Ptr(true),+ },Rerank: catalog.RerankCompat{// GPUStack's built-in backends are vLLM, SGLang, Ascend MindIE and// VoxBox, so the vLLM rerank extension reaches the model.diff --git a/internal/models/vendors/hunyuan/vendor.go b/internal/models/vendors/hunyuan/vendor.goindex 9ab41cd64..8dfc85733 100644--- a/internal/models/vendors/hunyuan/vendor.go+++ b/internal/models/vendors/hunyuan/vendor.go@@ -96,6 +96,9 @@ func init() {types.ModelTypeEmbedding,},Compat: catalog.VendorCompat{+ // Embeddings keeps the bare baseline on purpose: "Embedding 接口目前仅+ // 支持 input 和 model 参数 … dimensions 固定为 1024"+ // (https://cloud.tencent.com/document/product/1729/111007).OpenAICompletions: catalog.OpenAICompletionsCompat{MaxTokensField: catalog.Ptr("max_tokens"),ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatEnableThinking),diff --git a/internal/models/vendors/jina/vendor.go b/internal/models/vendors/jina/vendor.goindex d09eaf371..0d1b4191c 100644--- a/internal/models/vendors/jina/vendor.go+++ b/internal/models/vendors/jina/vendor.go@@ -64,6 +64,19 @@ func init() {types.ModelTypeRerank,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://jina.ai/embeddings/: model, input, an optional task,+ // dimensions, embedding_type, normalized, late_chunking and a+ // boolean truncate that defaults to false (an over-long input is+ // an error). truncate: true is what this vendor has always been+ // sent. task is deliberately not declared: the adapter it selects+ // changes the document vectors, so turning it on would leave every+ // existing index half in one space and half in another+ // (Tencent/WeKnora#1401).+ DimensionsField: catalog.Ptr("dimensions"),+ TruncateField: catalog.Ptr("truncate"),+ TruncateValue: catalog.Ptr("true"),+ },Rerank: catalog.RerankCompat{// return_documents echoes the text back. Results are matched// by index, so this is not needed to map them; it is keptdiff --git a/internal/models/vendors/litellm/vendor.go b/internal/models/vendors/litellm/vendor.goindex 3e40ef00a..02d0d96b3 100644--- a/internal/models/vendors/litellm/vendor.go+++ b/internal/models/vendors/litellm/vendor.go@@ -104,6 +104,13 @@ func init() {ModelTypes: []types.ModelType{types.ModelTypeRerank},}},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://docs.litellm.ai/docs/embedding/supported_embedding:+ // model, input, user, dimensions, encoding_format; anything else+ // is forwarded to the upstream as a provider-specific kwarg.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatOpenAI),SupportsReasoningEffort: catalog.Ptr(true),diff --git a/internal/models/vendors/modelscope/vendor.go b/internal/models/vendors/modelscope/vendor.goindex 382c91479..2c8630574 100644--- a/internal/models/vendors/modelscope/vendor.go+++ b/internal/models/vendors/modelscope/vendor.go@@ -78,6 +78,8 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ // Embeddings keeps the bare baseline: /v1/embeddings answers, but no+ // ModelScope page documents a single parameter of it.OpenAICompletions: catalog.OpenAICompletionsCompat{MaxTokensField: catalog.Ptr("max_tokens"),ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatEnableThinking),diff --git a/internal/models/vendors/novita/vendor.go b/internal/models/vendors/novita/vendor.goindex 0fee0ecd5..05f38477c 100644--- a/internal/models/vendors/novita/vendor.go+++ b/internal/models/vendors/novita/vendor.go@@ -75,6 +75,11 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://novita.ai/docs/api-reference/model-apis-llm-create-embeddings:+ // input, model, encoding_format. Nothing else.+ SendEncodingFormat: catalog.Ptr(true),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{MaxTokensField: catalog.Ptr("max_tokens"),ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatEnableThinking),diff --git a/internal/models/vendors/nvidia/models.json b/internal/models/vendors/nvidia/models.jsonindex 23d11d528..06e6e9e70 100644--- a/internal/models/vendors/nvidia/models.json+++ b/internal/models/vendors/nvidia/models.json@@ -11,10 +11,7 @@{"id": "moonshotai/kimi-k3", "name": "Kimi K3", "reasoning": true, "input": ["text", "image", "video"], "context_window": 1048576, "max_output_tokens": 131072, "cost": {"input": 0, "output": 0}, "compat": {"max_tokens_field": "max_completion_tokens", "thinking_format": "openai", "supports_reasoning_effort": true}, "thinking_levels": {"off": null, "minimal": "low", "medium": "high", "xhigh": "max", "max": "max"}},{"id": "moonshotai/kimi-k2.6", "name": "Kimi K2.6", "reasoning": true, "input": ["text", "image", "video"], "context_window": 262144, "max_output_tokens": 262144, "cost": {"input": 0, "output": 0}},{"id": "google/gemma-4-31b-it", "name": "Gemma 4 31B IT", "reasoning": true, "input": ["text", "image", "video"], "context_window": 256000, "max_output_tokens": 16384, "cost": {"input": 0, "output": 0}, "compat": {"max_tokens_field": "max_completion_tokens", "thinking_format": "none"}},- {"id": "nvidia/nv-embed-v1", "name": "NV-Embed v1", "type": "Embedding", "dimension": 4096, "context_window": 32768},- {"id": "nvidia/nemotron-3-embed-1b", "name": "Nemotron 3 Embed 1B", "type": "Embedding", "dimension": 2048, "context_window": 32768},- {"id": "nvidia/llama-3.2-nemoretriever-300m-embed-v1", "name": "Llama 3.2 NemoRetriever 300M Embed v1", "type": "Embedding", "dimension": 2048, "context_window": 8192},- {"id": "baai/bge-m3", "name": "BGE-M3", "type": "Embedding", "dimension": 1024, "context_window": 8192},+ {"id": "nvidia/nemotron-3-embed-1b", "name": "Nemotron 3 Embed 1B", "type": "Embedding", "dimension": 2048, "context_window": 4096, "source": "https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-embed-1b-infer"},{"id": "nvidia/llama-nemotron-rerank-vl-1b-v2", "name": "Llama Nemotron Rerank VL 1B v2", "type": "Rerank"},{"id": "nvidia/nv-rerankqa-mistral-4b-v3", "name": "NV-RerankQA Mistral 4B v3", "type": "Rerank"}]diff --git a/internal/models/vendors/nvidia/vendor.go b/internal/models/vendors/nvidia/vendor.goindex b940562b6..e602adc89 100644--- a/internal/models/vendors/nvidia/vendor.go+++ b/internal/models/vendors/nvidia/vendor.go@@ -26,12 +26,15 @@// without it the vendor default would emit a chat-template switch and// drop the level, leaving the picker's rungs inert;// - most hosted endpoints are metered at zero cost; the Nemotron and-// DeepSeek endpoints are priced.+// DeepSeek endpoints are priced;+// - nemotron-3-embed-1b is the one embedding endpoint here that+// build.nvidia.com does not mark deprecated: nv-embed-v1,+// llama-3_2-nemoretriever-300m-embed-v1 (and its v2) and baai/bge-m3 all+// carry "This NIM Endpoint has been deprecated", so their entries were+// removed. Its reference caps input at 4096 tokens; the 2048-wide vector+// is from the Nemotron-3-Embed-1B model card on Hugging Face.//// Unverified:-// - embedding dimensions (nv-embed-v1 4096, nemoretriever-300m 2048,-// nemotron-3-embed-1b 2048, bge-m3 1024) come from the model cards;-// nv-embed-v1's 32768 context is not restated in the current card;// - `minimaxai/minimax-m3`, `minimaxai/minimax-m2.7` and// `mistralai/mistral-medium-3.5-128b` have live build.nvidia.com pages// whose samples ship an empty `model=""`, so the exact org-prefixed id@@ -78,7 +81,7 @@ func init() {Name: "NVIDIA",Names: map[string]string{"zh-CN": "NVIDIA"},Description: "nvidia/nemotron-3-ultra-550b-a55b, deepseek-ai/deepseek-v4-pro-0813, " +- "nvidia/nv-embed-v1, nvidia/nv-rerankqa-mistral-4b-v3, etc.",+ "nvidia/nemotron-3-embed-1b, nvidia/nv-rerankqa-mistral-4b-v3, etc.",Website: "https://build.nvidia.com",Icon: icon,API: api.APIOpenAICompletions,@@ -100,6 +103,24 @@ func init() {},RerankAPI: api.RerankNIM,Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-embed-1b-infer:+ // input, model, input_type (passage | query), encoding_format,+ // truncate (NONE | START | END, default NONE), user. There is no+ // dimensions field. input_type is required and passage is what+ // this vendor has always been sent for documents, so the indexed+ // side is unchanged; queries now get query, as the reference+ // insists they must. This is the hosted API: a self-hosted NIM+ // (https://docs.nvidia.com/nim/nemo-retriever/embedding/latest/reference.html)+ // does take dimensions, and belongs on a generic row pointed at it.+ SendEncodingFormat: catalog.Ptr(true),+ InputTypeField: catalog.Ptr("input_type"),+ InputTypeValues: map[string]string{"document": "passage", "query": "query"},+ // NONE fails the request on an over-long input instead of+ // cutting it.+ TruncateField: catalog.Ptr("truncate"),+ TruncateValue: catalog.Ptr("END"),+ },Rerank: catalog.RerankCompat{// rankings[].logit is unbounded and routinely negative, so the// caller must be told this is not a 0..1 relevance score.diff --git a/internal/models/vendors/openai/models.json b/internal/models/vendors/openai/models.jsonindex 89b805427..be7775ce5 100644--- a/internal/models/vendors/openai/models.json+++ b/internal/models/vendors/openai/models.json@@ -29,6 +29,6 @@{"id": "text-embedding-3-small", "name": "text-embedding-3-small", "type": "Embedding", "dimension": 1536, "context_window": 8191, "cost": {"input": 0.02, "output": 0}},{"id": "text-embedding-3-large", "name": "text-embedding-3-large", "type": "Embedding", "dimension": 3072, "context_window": 8191, "cost": {"input": 0.13, "output": 0}},- {"id": "text-embedding-ada-002", "name": "text-embedding-ada-002", "type": "Embedding", "dimension": 1536, "context_window": 8192, "cost": {"input": 0.1, "output": 0}}+ {"id": "text-embedding-ada-002", "name": "text-embedding-ada-002", "type": "Embedding", "dimension": 1536, "context_window": 8192, "cost": {"input": 0.1, "output": 0}, "compat": {"dimensions_field": ""}}]}diff --git a/internal/models/vendors/openai/vendor.go b/internal/models/vendors/openai/vendor.goindex cf23b5308..a6f99249d 100644--- a/internal/models/vendors/openai/vendor.go+++ b/internal/models/vendors/openai/vendor.go@@ -97,6 +97,15 @@ func init() {types.ModelTypeASR,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://developers.openai.com/api/reference/resources/embeddings/methods/create:+ // model, input, dimensions (text-embedding-3 and later; the ada-002+ // entry turns it off), encoding_format, user. An input array+ // "must be 2048 dimensions or less" — elements, despite the word.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ MaxBatchSize: catalog.Ptr(2048),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatOpenAI),SupportsReasoningEffort: catalog.Ptr(true),diff --git a/internal/models/vendors/openrouter/vendor.go b/internal/models/vendors/openrouter/vendor.goindex fddf72c1a..c475ea4e7 100644--- a/internal/models/vendors/openrouter/vendor.go+++ b/internal/models/vendors/openrouter/vendor.go@@ -77,6 +77,18 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://openrouter.ai/docs/api/api-reference/embeddings/create-embeddings:+ // model, input, dimensions, encoding_format, input_type, provider,+ // user. input_type is a free-form string handed to whichever+ // upstream serves the model ("e.g. search_query,+ // search_document"), so its vocabulary is the upstream's, and on+ // an asymmetric model it changes the document vectors. Not+ // declared, for the reason Jina's task is not+ // (Tencent/WeKnora#1401).+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatOpenRouter),SupportsReasoningEffort: catalog.Ptr(true),diff --git a/internal/models/vendors/qianfan/models.json b/internal/models/vendors/qianfan/models.jsonindex c0abc74ad..ba23dc465 100644--- a/internal/models/vendors/qianfan/models.json+++ b/internal/models/vendors/qianfan/models.json@@ -9,7 +9,7 @@{"id": "deepseek-v3.2", "name": "DeepSeek V3.2 (Qianfan)", "reasoning": true, "input": ["text"], "context_window": 128000, "max_output_tokens": 32000, "compat": {"thinking_format": "thinking-type"}, "source": "https://cloud.baidu.com/doc/qianfan-docs/s/Wm95lyynv"},{"id": "embedding-v1", "name": "Embedding-V1", "type": "Embedding", "dimension": 384, "source": "https://cloud.baidu.com/doc/qianfan-api/s/Fm7u3ropn"},{"id": "bge-large-zh", "name": "BGE Large ZH", "type": "Embedding", "dimension": 1024, "source": "https://cloud.baidu.com/doc/qianfan-api/s/Fm7u3ropn"},- {"id": "tao-8k", "name": "Tao-8K", "type": "Embedding", "dimension": 1024, "source": "https://cloud.baidu.com/doc/qianfan-api/s/Fm7u3ropn"},+ {"id": "tao-8k", "name": "Tao-8K", "type": "Embedding", "dimension": 1024, "compat": {"max_batch_size": 1}, "source": "https://cloud.baidu.com/doc/qianfan/s/rmh4stp0j"},{"id": "bce-reranker-base", "name": "BCE Reranker Base", "type": "Rerank"}]}diff --git a/internal/models/vendors/qianfan/vendor.go b/internal/models/vendors/qianfan/vendor.goindex ee0c55888..0e0aad576 100644--- a/internal/models/vendors/qianfan/vendor.go+++ b/internal/models/vendors/qianfan/vendor.go@@ -101,6 +101,14 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://cloud.baidu.com/doc/qianfan-api/s/Fm7u3ropn: model,+ // input, user, encoding_format ("当前只支持float"). The model list+ // (https://cloud.baidu.com/doc/qianfan/s/rmh4stp0j) caps a request+ // at 16 texts; tao-8k takes one.+ SendEncodingFormat: catalog.Ptr(true),+ MaxBatchSize: catalog.Ptr(16),+ },Rerank: catalog.RerankCompat{// "文本数量不超过64"; query "长度不超过1600个字符"; each document// "长度不超过4096个字符".diff --git a/internal/models/vendors/requesty/vendor.go b/internal/models/vendors/requesty/vendor.goindex 3076f4e9e..283f44c83 100644--- a/internal/models/vendors/requesty/vendor.go+++ b/internal/models/vendors/requesty/vendor.go@@ -79,6 +79,12 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://docs.requesty.ai/api-reference/endpoint/embeddings-create:+ // model, input, encoding_format, dimensions.+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{MaxTokensField: catalog.Ptr("max_tokens"),ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatOpenAI),diff --git a/internal/models/vendors/siliconflow/models.json b/internal/models/vendors/siliconflow/models.jsonindex 2d3f25a3e..e51084c6e 100644--- a/internal/models/vendors/siliconflow/models.json+++ b/internal/models/vendors/siliconflow/models.json@@ -18,10 +18,10 @@{"id": "deepseek-ai/DeepSeek-V3.2", "name": "DeepSeek V3.2", "reasoning": true, "input": ["text"], "context_window": 164000, "max_output_tokens": 164000, "cost": {"input": 0.27, "output": 0.42}, "compat": {"supports_reasoning_effort": false}},{"id": "Pro/MiniMaxAI/MiniMax-M2.5", "name": "MiniMax M2.5 (Pro)", "reasoning": true, "input": ["text"], "context_window": 204800, "max_output_tokens": 131000, "cost": {"input": 0.3, "output": 1.22}, "compat": {"supports_reasoning_effort": false}, "source": "https://platform.minimax.io/docs/api-reference/text-openai-api"},{"id": "Qwen/Qwen3-VL-32B-Instruct", "name": "Qwen3 VL 32B Instruct", "reasoning": false, "input": ["text", "image"], "context_window": 262000, "max_output_tokens": 262000, "cost": {"input": 0.2, "output": 0.6}},- {"id": "BAAI/bge-m3", "name": "BGE-M3", "type": "Embedding", "dimension": 1024, "source": "https://docs.siliconflow.cn/cn/api-reference/embeddings/create-embeddings"},- {"id": "Qwen/Qwen3-Embedding-8B", "name": "Qwen3 Embedding 8B", "type": "Embedding", "dimension": 4096, "source": "https://docs.siliconflow.cn/cn/api-reference/embeddings/create-embeddings"},- {"id": "Qwen/Qwen3-Embedding-4B", "name": "Qwen3 Embedding 4B", "type": "Embedding", "dimension": 2560, "source": "https://docs.siliconflow.cn/cn/api-reference/embeddings/create-embeddings"},- {"id": "Qwen/Qwen3-Embedding-0.6B", "name": "Qwen3 Embedding 0.6B", "type": "Embedding", "dimension": 1024, "source": "https://docs.siliconflow.cn/cn/api-reference/embeddings/create-embeddings"},+ {"id": "BAAI/bge-m3", "name": "BGE-M3", "type": "Embedding", "dimension": 1024, "compat": {"dimensions_field": ""}, "source": "https://api-docs.siliconflow.cn/docs/api/embeddings-post"},+ {"id": "Qwen/Qwen3-Embedding-8B", "name": "Qwen3 Embedding 8B", "type": "Embedding", "dimension": 4096, "source": "https://api-docs.siliconflow.cn/docs/api/embeddings-post"},+ {"id": "Qwen/Qwen3-Embedding-4B", "name": "Qwen3 Embedding 4B", "type": "Embedding", "dimension": 2560, "source": "https://api-docs.siliconflow.cn/docs/api/embeddings-post"},+ {"id": "Qwen/Qwen3-Embedding-0.6B", "name": "Qwen3 Embedding 0.6B", "type": "Embedding", "dimension": 1024, "source": "https://api-docs.siliconflow.cn/docs/api/embeddings-post"},{"id": "BAAI/bge-reranker-v2-m3", "name": "BGE Reranker v2 M3", "type": "Rerank", "source": "https://docs.siliconflow.cn/cn/api-reference/rerank/create-rerank"},{"id": "Qwen/Qwen3-Reranker-8B", "name": "Qwen3 Reranker 8B", "type": "Rerank", "source": "https://docs.siliconflow.cn/cn/api-reference/rerank/create-rerank"},{"id": "FunAudioLLM/SenseVoiceSmall", "name": "SenseVoice Small", "type": "ASR", "source": "https://docs.siliconflow.cn/cn/api-reference/audio/create-audio-transcriptions"}diff --git a/internal/models/vendors/siliconflow/vendor.go b/internal/models/vendors/siliconflow/vendor.goindex d9c5c38c6..f332e6fce 100644--- a/internal/models/vendors/siliconflow/vendor.go+++ b/internal/models/vendors/siliconflow/vendor.go@@ -77,6 +77,15 @@ func init() {types.ModelTypeASR,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://api-docs.siliconflow.cn/docs/api/embeddings-post: model,+ // input, encoding_format, and dimensions "仅 Qwen/Qwen3 系列支持"+ // — the bge-m3 entry turns it off. The input array schema says+ // "当前最大数组大小为 32" (maxItems 32).+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ MaxBatchSize: catalog.Ptr(32),+ },OpenAICompletions: catalog.OpenAICompletionsCompat{MaxTokensField: catalog.Ptr("max_tokens"),ThinkingFormat: catalog.Ptr(catalog.ThinkingFormatEnableThinking),diff --git a/internal/models/vendors/vendors_test.go b/internal/models/vendors/vendors_test.goindex e7e5ace94..452e6c390 100644--- a/internal/models/vendors/vendors_test.go+++ b/internal/models/vendors/vendors_test.go@@ -110,6 +110,9 @@ func TestEveryCatalogEntryResolves(t *testing.T) {if modelType == types.ModelTypeKnowledgeQA && !r.API.Known() {t.Errorf("%s/%s: resolved to unknown API %q", id, name, r.API)}+ if modelType == types.ModelTypeEmbedding && !r.EmbeddingAPI.Known() {+ t.Errorf("%s/%s: resolved to unknown embedding API %q", id, name, r.EmbeddingAPI)+ }if modelType == types.ModelTypeEmbedding && m.ID != "" && m.Dimension <= 0 {t.Logf("%s/%s: embedding entry without dimension", id, name)}@@ -117,6 +120,35 @@ func TestEveryCatalogEntryResolves(t *testing.T) {}}+// Model names that fall inside a chat family's glob must still resolve as+// embedding and rerank rows. The families that caught them carry chat compat+// (thinking_always_send on Aliyun's qwen3*, max_tokens_field and+// supports_temperature on gpt-5*), which the embedding and rerank overlays+// reject, so an untyped lookup made these rows impossible to build — new ids+// and dated snapshots first of all, since they are never in models.json yet.+func TestNamesInsideChatGlobsResolveForOtherTypes(t *testing.T) {+ names := []struct{ provider, model string }{+ {"aliyun", "qwen3.8-text-embedding"},+ {"aliyun", "qwen3-embedding"},+ {"aliyun", "qwen3.7-text-embedding-20260601"},+ {"generic", "gpt-5-embed"},+ {"openai", "gpt-5-embed"},+ }+ for _, n := range names {+ for _, modelType := range []types.ModelType{types.ModelTypeEmbedding, types.ModelTypeRerank} {+ r, err := catalog.Resolve(catalog.Ref{Provider: n.provider, Model: n.model, ModelType: modelType})+ if err != nil {+ t.Errorf("%s/%s as %s: %v", n.provider, n.model, modelType, err)+ continue+ }+ if r.Cataloged {+ t.Errorf("%s/%s as %s matched %q, which is not an entry of that type",+ n.provider, n.model, modelType, r.Spec.Name)+ }+ }+ }+}+func TestDetectByURLRoundTrip(t *testing.T) {for _, id := range expectedIDs {v, _ := catalog.Get(id)diff --git a/internal/models/vendors/volcengine/models.json b/internal/models/vendors/volcengine/models.jsonindex 27c7a3dcc..9140c8c63 100644--- a/internal/models/vendors/volcengine/models.json+++ b/internal/models/vendors/volcengine/models.json@@ -18,7 +18,8 @@{"id": "deepseek-v4-flash-ga-260731", "name": "DeepSeek V4 Flash (Ark)", "reasoning": true, "input": ["text"], "context_window": 1000000, "max_output_tokens": 393216, "cost": {"input": 0.4453, "output": 1.3359, "cache_read": 0.01484}},{"id": "glm-5-3-flash-260828", "name": "GLM-5.3 Flash (Ark)", "reasoning": true, "input": ["text", "image", "video"], "context_window": 1000000, "max_output_tokens": 131072, "cost": {"input": 0.11875, "output": 0.41563, "cache_read": 0.03414}, "thinking_levels": {"off": null, "minimal": "low", "low": "low", "medium": "high", "high": "high", "xhigh": "max", "max": "max"}, "source": "https://docs.volcengine.com/docs/ark/deep-thinking?lang=zh"},{"id": "glm-5-2-260617", "name": "GLM-5.2 (Ark)", "reasoning": true, "input": ["text"], "context_window": 1000000, "max_output_tokens": 131072, "cost": {"input": 1.18747, "output": 4.15615, "cache_read": 0.29687}},- {"id": "doubao-embedding-large-text-250515", "name": "Doubao Embedding Large Text", "type": "Embedding", "dimension": 2048, "source": "https://www.volcengine.com/docs/82379/1302003"},+ {"name": "Retired doubao-embedding text models", "match": "doubao-embedding-text*", "type": "Embedding", "compat": {"api": "openai-embeddings", "dimensions_field": "", "max_batch_size": 4}, "source": "https://docs.volcengine.com/docs/ark/TextVectorizationAPI?lang=zh"},+ {"name": "Retired doubao-embedding-large text models", "match": "doubao-embedding-large-text*", "type": "Embedding", "compat": {"api": "openai-embeddings", "dimensions_field": "", "max_batch_size": 4}, "source": "https://docs.volcengine.com/docs/ark/TextVectorizationAPI?lang=zh"},{"id": "doubao-embedding-vision-251215", "name": "Doubao Embedding Vision (251215)", "type": "Embedding", "dimension": 2048, "source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},{"id": "doubao-embedding-vision-250615", "name": "Doubao Embedding Vision", "type": "Embedding", "dimension": 2048, "source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},{"id": "doubao-seed-rerank", "name": "Doubao Seed Rerank", "type": "Rerank", "source": "https://www.volcengine.com/docs/84313/1254474"},diff --git a/internal/models/vendors/volcengine/vendor.go b/internal/models/vendors/volcengine/vendor.goindex f878bceec..c48a88347 100644--- a/internal/models/vendors/volcengine/vendor.go+++ b/internal/models/vendors/volcengine/vendor.go@@ -40,9 +40,15 @@// - in tool-calling turns Ark also returns `encrypted_content` next to// `reasoning_content` and asks for it to be replayed; omitting it is not// an error but degrades multi-turn agent quality;-// - multimodal embeddings post to /api/v3/embeddings/multimodal with-// `dimensions` defaulting to 2048-// (https://docs.volcengine.com/docs/ark/multimodal-vectorization-api);+// - embeddings post to /api/v3/embeddings/multimodal with `dimensions`+// defaulting to 2048, and answer one fused vector for the whole input+// (https://docs.volcengine.com/docs/ark/multimodal-vectorization-api).+// It is the only embedding API the current docs list, and the 向量化 model+// list names only the two doubao-embedding-vision snapshots. The text+// endpoint, /api/v3/embeddings in the OpenAI shape, now sits under+// 下线文档归档 (retired documentation), so doubao-embedding-large-text was+// removed from models.json; rows that still name a doubao-embedding text+// model are routed to that endpoint by pattern;// - rerank is the VikingDB Knowledge Base service signed with AK/SK at// https://api-knowledgebase.mlp.cn-beijing.volces.com/api/knowledge/service/rerank// (the API key field carries the access key; the secret key, region and@@ -54,12 +60,9 @@// auth. This package configures OpenAI Chat Completions, which is the// surface every model page documents first.//-// unverified: text-only embedding models post to /api/v3/embeddings, not the-// multimodal path this vendor defaults to, and WeKnora's Ark embedder pins-// the multimodal path regardless of the configured base URL. The default is-// left alone; doubao-embedding-large-text-250515 is kept because no-// retirement notice was found, even though the current 向量化 model list only-// names the two doubao-embedding-vision snapshots.+// unverified: whether the retired text endpoint still answers for accounts+// that used it. Rows naming a text model reach it either way; before the+// catalog they were sent to the multimodal path.//// unverified: the model list spells lengths as "256k" / "1024k" without// saying whether k is 1000 or 1024, so the context windows in models.json are@@ -75,6 +78,7 @@ package volcengineimport (_ "embed"+ "strings""github.com/Tencent/WeKnora/internal/models/api""github.com/Tencent/WeKnora/internal/models/catalog"@@ -96,6 +100,11 @@ const BaseURL = "https://ark.cn-beijing.volces.com/api/v3"// EmbeddingBaseURL is the Ark multimodal embedding endpoint.const EmbeddingBaseURL = "https://ark.cn-beijing.volces.com/api/v3/embeddings/multimodal"+const (+ multimodalEmbeddingPath = "/api/v3/embeddings/multimodal"+ textEmbeddingPath = "/api/v3/embeddings"+)+// RerankBaseURL is the Knowledge Base managed rerank endpoint.const RerankBaseURL = "https://api-knowledgebase.mlp.cn-beijing.volces.com"@@ -178,8 +187,41 @@ func init() {ModelTypes: rerankOnly,},},- RerankAPI: api.RerankVolcengineKnowledge,+ RerankAPI: api.RerankVolcengineKnowledge,+ EmbeddingAPI: api.EmbeddingArk,+ // Embedding rows have stored three shapes of base URL: the full+ // multimodal URL that was the default, .../api/v3 like chat, and the+ // bare host. All of them name the same service, so the request is+ // placed from the host.+ Endpoint: func(r catalog.EndpointRequest) (string, map[string]string) {+ if r.ModelType != types.ModelTypeEmbedding {+ return "", nil+ }+ root := strings.TrimRight(r.BaseURL, "/")+ if i := strings.Index(root, "/api/"); i >= 0 {+ root = root[:i]+ }+ if r.EmbeddingAPI == api.EmbeddingOpenAI {+ // The retired doubao-embedding text models, whose archived+ // reference still names this endpoint.+ return root + textEmbeddingPath, nil+ }+ return root + multimodalEmbeddingPath, nil+ },Compat: catalog.VendorCompat{+ // https://docs.volcengine.com/docs/ark/multimodal-vectorization-api:+ // the only embedding API Ark still lists. It fuses everything in+ // one request into a single vector, so a request carries one text.+ // dimensions defaults to 2048 and the current models also serve+ // 1024; encoding_format defaults to float and the reference's own+ // curl sends it. `instructions` is documented too and deliberately+ // not declared: like Jina's task it changes the document vectors+ // (Tencent/WeKnora#1401).+ Embeddings: catalog.EmbeddingsCompat{+ SendEncodingFormat: catalog.Ptr(true),+ DimensionsField: catalog.Ptr("dimensions"),+ MaxBatchSize: catalog.Ptr(1),+ },Rerank: catalog.RerankCompat{MaxDocuments: catalog.Ptr(50),MaxConcurrency: catalog.Ptr(4),diff --git a/internal/models/vendors/weknoracloud/vendor.go b/internal/models/vendors/weknoracloud/vendor.goindex 7895da548..9488ea3f5 100644--- a/internal/models/vendors/weknoracloud/vendor.go+++ b/internal/models/vendors/weknoracloud/vendor.go@@ -90,6 +90,13 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // The OpenAI body on the service's own path, signed like the+ // rest of it.+ Path: catalog.Ptr("/api/v1/embeddings"),+ DimensionsField: catalog.Ptr("dimensions"),+ RequestTimeout: catalog.Ptr(60),+ },Rerank: catalog.RerankCompat{Path: catalog.Ptr("/api/v1/rerank"),// The only rerank vendor that has ever had a client deadlinediff --git a/internal/models/vendors/zhipu/models.json b/internal/models/vendors/zhipu/models.jsonindex 05f578eda..62c15a1eb 100644--- a/internal/models/vendors/zhipu/models.json+++ b/internal/models/vendors/zhipu/models.json@@ -13,8 +13,8 @@{"id": "glm-4.6v", "name": "GLM-4.6V", "reasoning": true, "input": ["text", "image", "video"], "context_window": 128000, "max_output_tokens": 32768, "cost": {"input": 0.3, "output": 0.9}, "compat": {"supports_reasoning_effort": false}},{"id": "glm-4.6", "name": "GLM-4.6", "reasoning": true, "input": ["text"], "context_window": 204800, "max_output_tokens": 131072, "cost": {"input": 0.6, "output": 2.2, "cache_read": 0.11}, "compat": {"supports_reasoning_effort": false}},{"id": "glm-4.5-air", "name": "GLM-4.5 Air", "reasoning": true, "input": ["text"], "context_window": 131072, "max_output_tokens": 98304, "cost": {"input": 0.2, "output": 1.1, "cache_read": 0.03}, "compat": {"supports_reasoning_effort": false}},- {"id": "embedding-3", "name": "Embedding-3", "type": "Embedding", "dimension": 2048, "source": "https://docs.bigmodel.cn/api-reference/模型-api/文本嵌入"},- {"id": "embedding-2", "name": "Embedding-2", "type": "Embedding", "dimension": 1024, "source": "https://docs.bigmodel.cn/api-reference/模型-api/文本嵌入"},+ {"id": "embedding-3", "name": "Embedding-3", "type": "Embedding", "dimension": 2048, "compat": {"max_batch_size": 64}, "source": "https://docs.bigmodel.cn/api-reference/模型-api/文本嵌入"},+ {"id": "embedding-2", "name": "Embedding-2", "type": "Embedding", "dimension": 1024, "compat": {"dimensions_field": ""}, "source": "https://docs.bigmodel.cn/api-reference/模型-api/文本嵌入"},{"id": "rerank", "name": "Rerank", "type": "Rerank", "source": "https://docs.bigmodel.cn/api-reference/模型-api/文本重排序"}]}diff --git a/internal/models/vendors/zhipu/vendor.go b/internal/models/vendors/zhipu/vendor.goindex 99bafb212..bf9942fa3 100644--- a/internal/models/vendors/zhipu/vendor.go+++ b/internal/models/vendors/zhipu/vendor.go@@ -109,6 +109,13 @@ func init() {types.ModelTypeVLLM,},Compat: catalog.VendorCompat{+ Embeddings: catalog.EmbeddingsCompat{+ // https://docs.bigmodel.cn/api-reference/模型-api/文本嵌入: model,+ // input, dimensions — no encoding_format. embedding-2 is fixed at+ // 1024 and its entry turns dimensions off; embedding-3 takes at+ // most 64 inputs per request.+ DimensionsField: catalog.Ptr("dimensions"),+ },Rerank: catalog.RerankCompat{// The reference gives 最大长度为 4096 字符 for the query and for each// document, and caps documents at 128 per request.diff --git a/internal/types/const.go b/internal/types/const.goindex 9ea930d28..e20a2a067 100644--- a/internal/types/const.go+++ b/internal/types/const.go@@ -55,7 +55,8 @@ const (// distinct key from SessionTenantIDContextKey, which also re-scopes// session/message repository lookups. See SandboxTenantIDFromContext.SandboxTenantIDContextKey ContextKey = "SandboxTenantID"- // EmbedQueryContextKey is the context key for embedding query text+ // EmbedQueryContextKey marks an embedding call as a search query; see+ // WithEmbedQuery.EmbedQueryContextKey ContextKey = "EmbedQuery"// WikiEditSourceContextKey carries who is authoring the current wiki// page write (user / agent / revert). Absent means the wiki ingestdiff --git a/internal/types/context_helpers.go b/internal/types/context_helpers.goindex 0c0ee2660..35cdab262 100644--- a/internal/types/context_helpers.go+++ b/internal/types/context_helpers.go@@ -69,6 +69,20 @@ func WikiEditSourceFromContext(ctx context.Context) string {return NormalizeWikiEditSource(v)}+// WithEmbedQuery marks ctx as embedding a search query rather than content+// being indexed. Asymmetric retrieval models encode the two sides differently+// and lose accuracy when a query is embedded as a passage; the embedding+// layer turns the mark into the vendor's own parameter where it has one.+func WithEmbedQuery(ctx context.Context) context.Context {+ return context.WithValue(ctx, EmbedQueryContextKey, true)+}++// IsEmbedQuery reports whether ctx was marked with WithEmbedQuery.+func IsEmbedQuery(ctx context.Context) bool {+ v, _ := ctx.Value(EmbedQueryContextKey).(bool)+ return v+}+// TaskInitiator is the authenticated caller that submitted an asynchronous// task. Workers restore it into their context so audit entries describe who// initiated the operation, while tasks created by schedulers remaindiff --git a/website-docs/03-features/06-models.md b/website-docs/03-features/06-models.mdindex d236d6090..e0af171a1 100644--- a/website-docs/03-features/06-models.md+++ b/website-docs/03-features/06-models.md@@ -72,8 +72,8 @@ const (| `api_key` | string | 空 | API 密钥,**AES-256-GCM 加密落库**(`ModelParameters.Value/Scan`),仅通过 `PUT /models/:id/credentials` 子资源修改 || `interface_type` | string | 空(VLM:local 默认 `ollama`,remote 默认 `openai`) | 接口协议类型 || `embedding_parameters.dimension` | int | 0 | 向量维度 |-| `embedding_parameters.truncate_prompt_tokens` | int | 0 | 输入截断 token 数 |-| `embedding_parameters.supports_dimension_override` | bool | false | 是否支持请求级维度覆盖(`dimensions` 参数) |+| `embedding_parameters.truncate_prompt_tokens` | int | 0 | 服务端截断 token 数。这是 vLLM 的扩展参数,只发给 `generic`、`gpustack`(为 0 时沿用历史值 511);托管厂商的文档里没有它,一律不发 |+| `embedding_parameters.supports_dimension_override` | bool | false | 是否在请求里指定向量维度。字段名由厂商决定(OpenAI 系 `dimensions`、Gemini `outputDimensionality`、百炼多模态 `parameters.dimension`);厂商文档里没有该参数的模型(NVIDIA NIM、混元、Novita、ada-002 等)即使勾选也不发 || `parameter_size` | string | 空 | Ollama 模型参数规模(如 "7B"),后端维护、前端不可改 || `provider` | string | 空(按 BaseURL 自动检测) | 厂商标识 || `extra_config` | map[string]string | nil | 厂商专属配置(由厂商定义的 `extraFields` 驱动,如 Azure 的 `api_version`);保留键 `api`(强制协议)、`remote_model_name`、`thinking_control`(旧版) |@@ -176,7 +176,7 @@ builtin_models:| 层 | 位置 | 职责 ||----|------|------|-| 协议层 | `internal/models/api/<protocol>` | 一个 wire 协议一个包:`openaicompletions`、`openairesponses`、`anthropicmessages`、`googlegenai`。各自持有请求/响应结构、SSE 解析与 usage 解析,不含任何厂商名 |+| 协议层 | `internal/models/api/<protocol>` | 一个 wire 协议一个包。对话:`openaicompletions`、`openairesponses`、`anthropicmessages`、`googlegenai`;重排:`cohererank`、`dashscoperank`、`nimrerank`;向量:`openaiembeddings`、`dashscopeembeddings`、`arkembeddings`、`googleembeddings`。各自持有请求/响应结构与解析,不含任何厂商名 || 厂商层 | `internal/models/vendors/<id>/` | 一个厂商一个目录:`vendor.go`(注册 `catalog.Vendor`)、`models.json`(模型目录)、`icon.svg`(品牌图标,`go:embed` 进二进制) || 目录层 | `internal/models/catalog` | 合并厂商定义、模型条目、部署叠加与单行覆盖,`Resolve` 得出「这个模型到底怎么发请求」 |@@ -211,7 +211,9 @@ builtin_models:`GET /api/v1/models/providers?model_type=chat` 返回全部厂商定义(图标 data URI、默认地址、额外字段、内置模型与思考能力),前端完全据此动态渲染,没有本地厂商表。目前内置 27 个厂商:`generic`、`weknoracloud`、`aliyun`、`zhipu`、`volcengine`、`hunyuan`、`siliconflow`、`deepseek`、`minimax`、`moonshot`、`mimo`、`modelscope`、`qianfan`、`qiniu`、`longcat`、`lkeap`、`openai`、`azure_openai`、`anthropic`、`gemini`、`openrouter`、`litellm`、`requesty`、`jina`、`nvidia`、`novita`、`gpustack`;Ollama 走 `source=local` 独立路径。-协议选择:Anthropic 走 Messages 协议;Gemini 默认走原生 `generateContent`(`base_url` 指向 `/v1beta/openai` 则保持 OpenAI 兼容);OpenAI 在 `api.openai.com` 上走 Responses 协议,中转/代理保持 Chat Completions;任何厂商 `base_url` 以 `/anthropic` 结尾时自动切到 Messages 协议(MiniMax、智谱、Kimi 的 Anthropic 兼容口)。`extra_config.api` 可强制指定。+协议选择:Anthropic 走 Messages 协议;Gemini 默认走原生 `generateContent`(`base_url` 指向 `/v1beta/openai` 则保持 OpenAI 兼容);OpenAI 在 `api.openai.com` 上走 Responses 协议,中转/代理保持 Chat Completions;任何厂商 `base_url` 以 `/anthropic` 结尾时自动切到 Messages 协议(MiniMax、智谱、Kimi 的 Anthropic 兼容口)。`extra_config.api` 可强制指定对话协议,只对 chat / VLM 行生效;embedding 行的协议覆盖写在 `spec.compat` 的 `"api"` 里,取值是向量协议(`openai-embeddings`、`dashscope-embeddings`、`ark-embeddings`、`google-embeddings`)。++目录条目按模型类型查找:embedding 行只匹配 embedding 条目,不会被同名前缀的对话通配(如百炼的 `qwen3*`、OpenAI 的 `gpt-5*`)套上对话的 compat。目录里还没有的新 id、带日期的快照照常按厂商默认解析。#### 新增厂商@@ -233,7 +235,7 @@ make model-catalog-check前端不需要任何改动:厂商下拉、图标、额外字段、内置模型列表都由 `GET /api/v1/models/providers` 动态渲染。-写入侧也有一道闸:`catalog.ValidateRow` 会在创建 / 更新模型(REST)和加载 `config/builtin_models.yaml`(启动)时解析这行配置,未知协议、拼错的 compat 键、非法的思考档位在写入时就被拒绝(YAML 行只打 WARN 不阻塞启动,避免一次重启把线上模型下线)。+写入侧也有一道闸:`catalog.ValidateRow` 会在创建 / 更新模型(REST)和加载 `config/builtin_models.yaml`(启动)时解析这行配置(chat、VLM、embedding、rerank 四类;ASR 还没进目录),未知协议、拼错的 compat 键、非法的思考档位在写入时就被拒绝(YAML 行只打 WARN 不阻塞启动,避免一次重启把线上模型下线)。#### 厂商更新了模型怎么办@@ -267,6 +269,17 @@ make model-catalog-diff VENDOR=deepseek # 只看一家3. **`api.openai.com` 的一方流量改走 Responses 协议**(`PreferAPI` 只对官方域生效)。各类中转 / 网关仍走 Chat Completions,`parity` 包里有断言钉住这一点。4. **7 家厂商的输出上限字段按文档纠正**:hunyuan、modelscope、qiniu、requesty、longcat、novita 由 `max_completion_tokens` 改回 `max_tokens`,moonshot 反向改为 `max_completion_tokens`。每一处在 `internal/models/parity/parity_test.go` 里都记了变更理由与厂商文档。aliyun 保持 `max_completion_tokens` 不变:兼容模式两个字段都收,但 DashScope 的参数表已经把 `max_tokens` 标为即将废弃并指名了继任者。+Embedding 行也有几处按厂商文档纠正的行为变化(逐厂商的出站请求由 `internal/models/embedding/wire_test.go` 钉住):++1. **托管厂商不再收到 `truncate_prompt_tokens`**。此前所有 OpenAI 兼容厂商都被塞了一个 511,它只是 vLLM 的扩展参数;`generic`、`gpustack` 照旧发送。+2. **NVIDIA NIM 的检索查询改用 `input_type: query`**。文档侧照旧是 `passage`,已有索引不受影响;这一标记在一次检索重构里丢失过,现在由 `types.WithEmbedQuery` 在三处查询入口设置。超长输入改为 `truncate: END` 截断而不是报错;`dimensions` 不再发送(NIM 没有这个参数)。目录里已被 NVIDIA 标记下线的 `nv-embed-v1`、`llama-3.2-nemoretriever-300m-embed-v1`、`baai/bge-m3` 已移除。+3. **阿里云按模型分流**:文本模型走 `/compatible-mode/v1/embeddings`,`qwen3-vl-embedding`、`qwen2.5-vl-embedding`、`tongyi-embedding-vision*`、`multimodal-embedding*` 走原生多模态接口。`base_url` 只填主机、国际站或业务空间域名时保留该主机,不再被替换成北京默认地址。+4. **火山方舟的文本向量接口已归档下线**,当前只有多模态接口。沿用老的 `doubao-embedding-text*` / `doubao-embedding-large-text*` 的行改发到它们归档文档里的 `/api/v3/embeddings`;此前它们被发往多模态接口。+5. **Gemini 的缩维放进 `embedContentConfig.outputDimensionality`**。请求顶层的同名字段已被文档标为 deprecated;旧实现发的是顶层 `output_dimensionality`。+6. **SiliconFlow 每次最多 32 条、百炼 `text-embedding-v1/v2` 最多 25 条**,超出时自动拆批;v1/v2 固定 1536 维,不发 `dimensions`。+7. **OpenAI 兼容回复里没有 `index` 时按顺序取**(和旧实现一致);有 `index` 就按它放回,重复或缺位报错。+8. **Jina 的 `task`、Gemini 的 `taskType`、OpenRouter 的 `input_type`、火山的 `instructions`、百炼原生接口的 `text_type` / `instruct` 都不发**。它们会改变文档侧向量,开启后同一个知识库里新旧向量不在同一空间;需要按行显式开启的设计另见 Tencent/WeKnora#1401。+另外 Azure OpenAI 不再声明支持 ASR(ASR 客户端只会构造标准 OpenAI 客户端,根本无法带上 Azure 的 `api-key` 头和部署路径,这类行此前就调不通)。### 模型调用链