diff --git a/internal/models/api/rerank.go b/internal/models/api/rerank.go index e2465a05..6463f878 100644 --- a/internal/models/api/rerank.go +++ b/internal/models/api/rerank.go @@ -23,6 +23,9 @@ const ( // array, and rankings carrying an unbounded logit instead of a // probability. RerankNIM RerankAPI = "nim-rerank" + // RerankTEI is the native Text Embeddings Inference shape: POST /rerank + // with {query, texts}, answering a bare array of {index, score}. + RerankTEI RerankAPI = "tei-rerank" // RerankTencentLKEAP is Tencent Cloud's RunRerank action, reached through // the official SDK because it is TC3-signed rather than key-authenticated. RerankTencentLKEAP RerankAPI = "tencent-lkeap" @@ -34,7 +37,7 @@ const ( // Known reports whether the value names a protocol this build implements. func (a RerankAPI) Known() bool { switch a { - case RerankCohere, RerankDashScope, RerankNIM, + case RerankCohere, RerankDashScope, RerankNIM, RerankTEI, RerankTencentLKEAP, RerankVolcengineKnowledge: return true } @@ -46,7 +49,7 @@ func (a RerankAPI) Known() bool { // vendor SDKs are imported. func (a RerankAPI) HTTPServed() bool { switch a { - case RerankCohere, RerankDashScope, RerankNIM: + case RerankCohere, RerankDashScope, RerankNIM, RerankTEI: return true } return false diff --git a/internal/models/api/teirank/client.go b/internal/models/api/teirank/client.go new file mode 100644 index 00000000..3057a257 --- /dev/null +++ b/internal/models/api/teirank/client.go @@ -0,0 +1,97 @@ +// Package teirank implements the native Text Embeddings Inference rerank +// protocol. It sends {query, texts} to /rerank and reads a bare array of +// {index, score}; the deployed model is selected by the TEI server, not by +// a model field in each request. +package teirank + +import ( + "context" + "fmt" + "strings" + + "github.com/Tencent/WeKnora/internal/models/api" +) + +// Config supplies the endpoint and wire-level settings for a TEI reranker. +type Config struct { + Endpoint api.Endpoint + Settings api.RerankSettings +} + +// Client sends rerank requests to a Text Embeddings Inference server. +type Client struct{ cfg Config } + +// New creates a TEI rerank client for the supplied endpoint. +func New(cfg Config) *Client { return &Client{cfg: cfg} } + +func (c *Client) url() string { + if c.cfg.Endpoint.URL != "" { + return c.cfg.Endpoint.Resolve("") + } + path := c.cfg.Settings.Path + if path == "" { + path = "/rerank" + } + if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) { + path = "" + } + return c.cfg.Endpoint.Resolve(path) +} + +type rank struct { + Index *int `json:"index"` + Score *float64 `json:"score"` + Text string `json:"text"` +} + +// BuildRequestBody returns the native TEI request. raw_scores is explicit: +// false makes a single-class reranker's logits comparable with WeKnora's +// 0..1 relevance threshold. The model name is configured when TEI starts. +// +// Settings.ExtraBody is merged in but cannot replace query, texts or +// raw_scores. truncate defaults to true and may be overridden there: TEI +// before 1.9 starts with --auto-truncate=false and rejects the whole batch +// when one passage exceeds the model's input length. +func (c *Client) BuildRequestBody(query string, documents []string) map[string]any { + out := map[string]any{ + "query": query, + "texts": documents, + "raw_scores": false, + } + for k, v := range c.cfg.Settings.ExtraBody { + if _, exists := out[k]; !exists { + out[k] = v + } + } + if _, set := out["truncate"]; !set { + out["truncate"] = true + } + return out +} + +// Rerank scores documents with TEI and preserves their original indexes. +func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) { + var decoded []rank + if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), c.BuildRequestBody(query, documents), &decoded); err != nil { + return nil, err + } + if len(decoded) != len(documents) { + return nil, fmt.Errorf("TEI returned %d ranks for %d documents", len(decoded), len(documents)) + } + out := make([]api.RerankResult, 0, len(decoded)) + seen := make([]bool, len(documents)) + for _, item := range decoded { + if item.Index == nil || *item.Index < 0 || *item.Index >= len(documents) { + return nil, fmt.Errorf("TEI rerank index is missing or out of range for %d documents", len(documents)) + } + if seen[*item.Index] { + return nil, fmt.Errorf("TEI returned duplicate rerank index %d", *item.Index) + } + if item.Score == nil { + return nil, fmt.Errorf("TEI rerank score is missing for index %d", *item.Index) + } + seen[*item.Index] = true + out = append(out, api.RerankResult{Index: *item.Index, Score: *item.Score, Text: item.Text}) + } + return out, nil +} diff --git a/internal/models/api/teirank/golden_test.go b/internal/models/api/teirank/golden_test.go new file mode 100644 index 00000000..fdb2c106 --- /dev/null +++ b/internal/models/api/teirank/golden_test.go @@ -0,0 +1,117 @@ +package teirank + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Tencent/WeKnora/internal/models/api" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The TEI OpenAPI defines RerankResponse as a bare array of Rank, and gives +// these exact example values for Rank's index, score and optional text: +// https://github.com/huggingface/text-embeddings-inference/blob/main/docs/openapi.json#L1628-L1704 +const openAPIRankExample = `[{"index":0,"score":1.0,"text":"Deep Learning is ..."}]` + +func TestOpenAPIRankExampleAndNativeRequest(t *testing.T) { + t.Setenv("SSRF_WHITELIST", "127.0.0.1") + var path, authorization string + var body map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, authorization = r.URL.Path, r.Header.Get("Authorization") + _ = json.NewDecoder(r.Body).Decode(&body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(openAPIRankExample)) + })) + defer server.Close() + + c := New(Config{Endpoint: api.Endpoint{ + BaseURL: server.URL, Model: "BAAI/bge-reranker-large", Auth: api.BearerAuth(""), + }}) + got, err := c.Rerank(context.Background(), "What is Deep Learning?", []string{"Deep Learning is ..."}) + require.NoError(t, err) + assert.Equal(t, "/rerank", path) + assert.Empty(t, authorization, "TEI works without an API key by default") + assert.Equal(t, map[string]any{ + "query": "What is Deep Learning?", "texts": []any{"Deep Learning is ..."}, + "raw_scores": false, "truncate": true, + }, body) + assert.NotContains(t, body, "model", "TEI chooses the model at server startup") + assert.Equal(t, []api.RerankResult{{Index: 0, Score: 1.0, Text: "Deep Learning is ..."}}, got) +} + +func TestRankIndicesAndOptionalBearer(t *testing.T) { + t.Setenv("SSRF_WHITELIST", "127.0.0.1") + var path, authorization string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, authorization = r.URL.Path, r.Header.Get("Authorization") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"index":2,"score":0.91},{"index":0,"score":0.62},{"index":1,"score":0.03}]`)) + })) + defer server.Close() + + c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL + "/rerank", Auth: api.BearerAuth("secret")}}) + got, err := c.Rerank(context.Background(), "q", []string{"same", "same", "relevant"}) + require.NoError(t, err) + assert.Equal(t, "/rerank", path, "a pasted full endpoint must not gain a second /rerank") + assert.Equal(t, "Bearer secret", authorization) + assert.Equal(t, []api.RerankResult{ + {Index: 2, Score: 0.91}, {Index: 0, Score: 0.62}, {Index: 1, Score: 0.03}, + }, got, "the index, not echoed text, identifies duplicate candidate texts") +} + +func TestRejectsMalformedRanks(t *testing.T) { + for _, tc := range []struct { + name, reply, want string + documents []string + }{ + {"missing score", `[{"index":0}]`, "score is missing", []string{"d"}}, + {"missing index", `[{"score":0.5}]`, "index is missing", []string{"d"}}, + {"out of range", `[{"index":3,"score":0.5}]`, "out of range", []string{"d"}}, + {"partial response", `[]`, "0 ranks for 1", []string{"d"}}, + {"duplicate index", `[{"index":0,"score":0.5},{"index":0,"score":0.4}]`, "duplicate", []string{"a", "b"}}, + } { + t.Run(tc.name, func(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(tc.reply)) + })) + defer server.Close() + c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}}) + _, err := c.Rerank(context.Background(), "q", tc.documents) + require.ErrorContains(t, err, tc.want) + }) + } +} + +func TestSurfacesTEIError(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.StatusUnprocessableEntity) + _, _ = w.Write([]byte(`{"error":"Tokenization error","error_type":"tokenizer"}`)) + })) + defer server.Close() + c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}}) + _, err := c.Rerank(context.Background(), "q", []string{"d"}) + require.ErrorContains(t, err, "Tokenization error") +} + +// compat.extra_body reaches TEI like every other HTTP rerank protocol, but it +// cannot replace the fields the client owns. truncate is only a default. +func TestExtraBodyMergesWithoutReplacingCoreFields(t *testing.T) { + c := New(Config{Settings: api.RerankSettings{ExtraBody: map[string]any{ + "query": "x", + "texts": []string{"x"}, + "raw_scores": true, + "truncate": false, + "truncation_direction": "Left", + }}}) + assert.Equal(t, map[string]any{ + "query": "q", "texts": []string{"d"}, "raw_scores": false, + "truncate": false, "truncation_direction": "Left", + }, c.BuildRequestBody("q", []string{"d"})) +} diff --git a/internal/models/catalog/data/models.generated.json b/internal/models/catalog/data/models.generated.json index 8978688c..0a6ef781 100644 --- a/internal/models/catalog/data/models.generated.json +++ b/internal/models/catalog/data/models.generated.json @@ -1933,6 +1933,7 @@ } ], "gpustack": [], + "huggingface_tei": [], "hunyuan": [ { "name": "Hunyuan T1 family (always-on reasoning)", diff --git a/internal/models/catalog/data/seed.json b/internal/models/catalog/data/seed.json index 9b452d10..f8cf9e0e 100644 --- a/internal/models/catalog/data/seed.json +++ b/internal/models/catalog/data/seed.json @@ -1315,6 +1315,7 @@ } ], "gpustack": [], + "huggingface_tei": [], "hunyuan": [ { "name": "Hunyuan T1 family (always-on reasoning)", diff --git a/internal/models/parity/rerank_test.go b/internal/models/parity/rerank_test.go index e2f81f48..560095ea 100644 --- a/internal/models/parity/rerank_test.go +++ b/internal/models/parity/rerank_test.go @@ -36,9 +36,9 @@ func TestEveryRerankVendorResolvesToAKnownProtocol(t *testing.T) { require.NoError(t, err) assert.True(t, resolved.RerankAPI.Known(), "unknown rerank protocol %q", resolved.RerankAPI) - // The catch-all vendor has no endpoint of its own: the operator - // supplies one, and Validate requires it. - if v.ID != providers.GenericID { + // Generic and self-hosted TEI have no endpoint of their own: + // the operator supplies one, and Validate requires it. + if v.ID != providers.GenericID && v.ID != providers.HuggingFaceTEIID { assert.NotEmpty(t, resolved.BaseURL, "rerank vendors need a default endpoint") } @@ -59,20 +59,21 @@ func TestEveryRerankVendorResolvesToAKnownProtocol(t *testing.T) { // every rerank call for that vendor. func TestRerankProtocolAssignment(t *testing.T) { for id, want := range map[string]api.RerankAPI{ - "aliyun": api.RerankDashScope, - "nvidia": api.RerankNIM, - "lkeap": api.RerankTencentLKEAP, - "volcengine": api.RerankVolcengineKnowledge, - "zhipu": api.RerankCohere, - "jina": api.RerankCohere, - "siliconflow": api.RerankCohere, - "qianfan": api.RerankCohere, - "gpustack": api.RerankCohere, - "generic": api.RerankCohere, - "weknoracloud": api.RerankCohere, - "novita": api.RerankCohere, - "openrouter": api.RerankCohere, - "litellm": api.RerankCohere, + "aliyun": api.RerankDashScope, + "nvidia": api.RerankNIM, + "huggingface_tei": api.RerankTEI, + "lkeap": api.RerankTencentLKEAP, + "volcengine": api.RerankVolcengineKnowledge, + "zhipu": api.RerankCohere, + "jina": api.RerankCohere, + "siliconflow": api.RerankCohere, + "qianfan": api.RerankCohere, + "gpustack": api.RerankCohere, + "generic": api.RerankCohere, + "weknoracloud": api.RerankCohere, + "novita": api.RerankCohere, + "openrouter": api.RerankCohere, + "litellm": api.RerankCohere, } { t.Run(id, func(t *testing.T) { resolved, err := modelruntime.Resolve(modelruntime.Ref{ @@ -285,6 +286,8 @@ func TestRerankCeilingsAreTheDocumentedOnes(t *testing.T) { // help.aliyun.com text-rerank: 500 documents per request. Its length // limits are stated in tokens, which runes cannot express. "aliyun": {MaxDocuments: 500}, + // TEI router: --max-client-batch-size defaults to 32. + "huggingface_tei": {MaxDocuments: 32}, } { t.Run(id, func(t *testing.T) { resolved, err := modelruntime.Resolve(modelruntime.Ref{ diff --git a/internal/models/providers/builtin.go b/internal/models/providers/builtin.go index 8a59435d..7adaeed8 100644 --- a/internal/models/providers/builtin.go +++ b/internal/models/providers/builtin.go @@ -12,6 +12,7 @@ func Builtins() []*Definition { newGeminiProvider(), newGenericProvider(), newGpustackProvider(), + newHuggingFaceTEIProvider(), newHunyuanProvider(), newJinaProvider(), newLitellmProvider(), diff --git a/internal/models/providers/huggingface_tei.go b/internal/models/providers/huggingface_tei.go new file mode 100644 index 00000000..51362388 --- /dev/null +++ b/internal/models/providers/huggingface_tei.go @@ -0,0 +1,53 @@ +// Package providers includes Hugging Face Text Embeddings Inference, which +// serves a model chosen at startup. +// Its native rerank route is POST /rerank with query/texts and a bare array +// response; it does not accept a model field or use the OpenAI /v1 prefix. +// https://huggingface.co/docs/text-embeddings-inference/quick_tour#re-rankers +// https://github.com/huggingface/text-embeddings-inference/blob/main/docs/openapi.json +package providers + +import ( + "fmt" + "strings" + + "github.com/Tencent/WeKnora/internal/models/api" + "github.com/Tencent/WeKnora/internal/types" +) + +// HuggingFaceTEIID is the provider ID for self-hosted TEI rerank models. +const HuggingFaceTEIID = "huggingface_tei" + +func newHuggingFaceTEIProvider() *Definition { + return &Definition{ + ID: HuggingFaceTEIID, + Name: "Hugging Face TEI", + Names: map[string]string{"zh-CN": "Hugging Face TEI"}, + Description: "Self-hosted reranker served by Text Embeddings Inference", + Descriptions: map[string]string{"zh-CN": "通过 Text Embeddings Inference 自部署的重排模型"}, + Website: "https://huggingface.co/docs/text-embeddings-inference", + Icon: genericIcon, + API: api.APIOpenAICompletions, + RerankAPI: api.RerankTEI, + Order: 61, + RequiresAuth: false, + Auth: AuthBearer, // Only TEI servers started with --api-key need this. + ModelTypes: []types.ModelType{types.ModelTypeRerank}, + Compat: VendorCompat{Rerank: api.RerankCompat{ + // TEI rejects requests above --max-client-batch-size, which + // defaults to 32. + MaxDocuments: api.Ptr(32), + }}, + Validate: func(cfg *Config) error { + if cfg == nil { + return fmt.Errorf("config is nil") + } + if strings.TrimSpace(cfg.BaseURL) == "" { + return fmt.Errorf("base URL is required for Hugging Face TEI provider") + } + if strings.TrimSpace(cfg.ModelName) == "" { + return fmt.Errorf("model name is required") + } + return nil + }, + } +} diff --git a/internal/models/providers/providers_test.go b/internal/models/providers/providers_test.go index 465c1c56..b4579fa2 100644 --- a/internal/models/providers/providers_test.go +++ b/internal/models/providers/providers_test.go @@ -14,7 +14,7 @@ import ( // expectedIDs is every built-in vendor this package links. var expectedIDs = []string{ - "generic", "weknoracloud", + "generic", "weknoracloud", "huggingface_tei", "aliyun", "zhipu", "volcengine", "hunyuan", "siliconflow", "deepseek", "minimax", "moonshot", "mimo", "modelscope", "qianfan", "qiniu", "longcat", "lkeap", "openai", "azure_openai", "anthropic", "gemini", @@ -23,8 +23,8 @@ var expectedIDs = []string{ } func TestAllVendorsRegistered(t *testing.T) { - if len(expectedIDs) != 27 { - t.Fatalf("expected 27 vendor ids in the spec, got %d", len(expectedIDs)) + if len(expectedIDs) != 28 { + t.Fatalf("expected 28 vendor ids in the spec, got %d", len(expectedIDs)) } for _, id := range expectedIDs { v, ok := modelruntime.Get(id) @@ -71,6 +71,21 @@ func TestAllVendorsRegistered(t *testing.T) { } } +func TestHuggingFaceTEIRequiresURLButNotAPIKey(t *testing.T) { + v, ok := modelruntime.Get(providers.HuggingFaceTEIID) + if !ok { + t.Fatal("Hugging Face TEI provider not registered") + } + if err := v.ValidateConfig(&providers.Config{ + BaseURL: "http://tei.internal:8080", ModelName: "BAAI/bge-reranker-large", + }); err != nil { + t.Fatalf("a self-hosted TEI server should not require an API key: %v", err) + } + if err := v.ValidateConfig(&providers.Config{ModelName: "BAAI/bge-reranker-large"}); err == nil { + t.Fatal("TEI provider accepted a missing base URL") + } +} + func TestEveryCatalogEntryResolves(t *testing.T) { for _, id := range expectedIDs { v, ok := modelruntime.Get(id) diff --git a/internal/models/rerank/reranker.go b/internal/models/rerank/reranker.go index b60c75a0..a2137326 100644 --- a/internal/models/rerank/reranker.go +++ b/internal/models/rerank/reranker.go @@ -12,6 +12,7 @@ import ( "github.com/Tencent/WeKnora/internal/models/api/cohererank" "github.com/Tencent/WeKnora/internal/models/api/dashscoperank" "github.com/Tencent/WeKnora/internal/models/api/nimrerank" + "github.com/Tencent/WeKnora/internal/models/api/teirank" modelruntime "github.com/Tencent/WeKnora/internal/models/runtime" // modelruntime.Resolve answers from the vendor catalog, which is empty until @@ -201,6 +202,8 @@ func newReranker(config *RerankerConfig) (Reranker, error) { client = dashscoperank.New(dashscoperank.Config{Endpoint: endpoint, Settings: resolved.Rerank}) case api.RerankNIM: client = nimrerank.New(nimrerank.Config{Endpoint: endpoint, Settings: resolved.Rerank}) + case api.RerankTEI: + client = teirank.New(teirank.Config{Endpoint: endpoint, Settings: resolved.Rerank}) case api.RerankTencentLKEAP: client, err = newLKEAPClient(config, resolved) case api.RerankVolcengineKnowledge: diff --git a/internal/models/rerank/wire_test.go b/internal/models/rerank/wire_test.go index bb6b1ddd..cb996807 100644 --- a/internal/models/rerank/wire_test.go +++ b/internal/models/rerank/wire_test.go @@ -106,6 +106,19 @@ func answer(r *http.Request, body map[string]any) string { parts = append(parts, fmt.Sprintf(`{"index":%d,"logit":%v}`, i, logit(docs[i]))) } return `{"rankings":[` + strings.Join(parts, ",") + `]}` + case body["texts"] != nil: // Text Embeddings Inference + docs := texts(body["texts"]) + indices := make([]int, len(docs)) + for i := range indices { + indices[i] = i + } + sort.SliceStable(indices, func(i, j int) bool { + return utf8.RuneCountInString(docs[indices[i]]) > utf8.RuneCountInString(docs[indices[j]]) + }) + for _, i := range indices { + parts = append(parts, fmt.Sprintf(`{"index":%d,"score":%v}`, i, probability(docs[i]))) + } + return `[` + strings.Join(parts, ",") + `]` case strings.Contains(r.URL.Path, "/text-rerank"): // DashScope docs := texts(body["input"].(map[string]any)["documents"]) for i := len(docs) - 1; i >= 0; i-- { @@ -221,6 +234,19 @@ func TestRerankWireFormatPerVendor(t *testing.T) { wantPath: "/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"}, wantBody: cohere("bge-reranker-v2-m3", three, nil), }, + { + name: "Hugging Face TEI", provider: "huggingface_tei", model: "BAAI/bge-reranker-large", + wantPath: "/rerank", wantAuth: [2]string{"Authorization", "Bearer k"}, + wantBody: map[string]any{"query": query, "texts": anyStrings(three), "raw_scores": false, "truncate": true}, + }, + { + name: "Hugging Face TEI splits at 32 documents", provider: "huggingface_tei", + model: "BAAI/bge-reranker-large", docs: documents(33), wantRequests: 2, + wantPath: "/rerank", wantAuth: [2]string{"Authorization", "Bearer k"}, + wantBody: map[string]any{ + "query": query, "texts": anyStrings(documents(32)), "raw_scores": false, "truncate": true, + }, + }, { name: "novita", provider: "novita", model: "baai/bge-reranker-v2-m3", base: "/openai/v1", wantPath: "/openai/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},