feat(rerank): support Pinecone Inference protocol (#3957)
* feat(rerank): support Pinecone Inference protocol * test(rerank): align Pinecone catalog baseline and lint * test(models): expect 29 built-in vendors with Pinecone and TEI --------- Co-authored-by: bigdu332 <bigdu332@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
ea7cf8d5d7
commit
5a25e26142
|
|
@ -0,0 +1,132 @@
|
|||
// Package pineconerank implements Pinecone Inference's standalone rerank API.
|
||||
// https://docs.pinecone.io/guides/search/rerank-results
|
||||
package pineconerank
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
)
|
||||
|
||||
// Config holds the Pinecone endpoint and rerank request settings.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings api.RerankSettings
|
||||
}
|
||||
|
||||
// Client calls Pinecone's standalone rerank API.
|
||||
type Client struct{ cfg Config }
|
||||
|
||||
// New creates a Pinecone rerank client.
|
||||
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 document struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type request struct {
|
||||
Model string `json:"model"`
|
||||
Query string `json:"query"`
|
||||
Documents []document `json:"documents"`
|
||||
TopN int `json:"top_n"`
|
||||
RankFields []string `json:"rank_fields"`
|
||||
ReturnDocuments bool `json:"return_documents"`
|
||||
Parameters map[string]any `json:"parameters,omitempty"`
|
||||
}
|
||||
|
||||
// BuildRequestBody constructs the native Pinecone body. Asking for every
|
||||
// candidate and suppressing echoed documents preserves WeKnora's index mapping
|
||||
// while avoiding unnecessary response bytes.
|
||||
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
|
||||
docs := make([]document, len(documents))
|
||||
for i, text := range documents {
|
||||
docs[i] = document{Text: text}
|
||||
}
|
||||
body := request{
|
||||
Model: c.cfg.Endpoint.Model, Query: query, Documents: docs,
|
||||
TopN: len(documents), RankFields: []string{"text"},
|
||||
}
|
||||
if c.cfg.Settings.Truncate != "" {
|
||||
body.Parameters = map[string]any{"truncate": c.cfg.Settings.Truncate}
|
||||
}
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
for key, value := range c.cfg.Settings.ExtraBody {
|
||||
if _, exists := out[key]; !exists {
|
||||
out[key] = value
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type response struct {
|
||||
Data *[]result `json:"data"`
|
||||
}
|
||||
|
||||
type result struct {
|
||||
Index *int `json:"index"`
|
||||
Score *float64 `json:"score"`
|
||||
}
|
||||
|
||||
// Rerank returns scores for the supplied documents in Pinecone's ranked order.
|
||||
func (c *Client) Rerank(
|
||||
ctx context.Context, query string, documents []string,
|
||||
) ([]api.RerankResult, error) {
|
||||
body, err := c.BuildRequestBody(query, documents)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var decoded response
|
||||
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), body, &decoded); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if decoded.Data == nil {
|
||||
return nil, fmt.Errorf("pinecone rerank response has no data array")
|
||||
}
|
||||
if len(*decoded.Data) != len(documents) {
|
||||
return nil, fmt.Errorf(
|
||||
"pinecone rerank returned %d scores for %d documents", len(*decoded.Data), len(documents),
|
||||
)
|
||||
}
|
||||
out := make([]api.RerankResult, 0, len(*decoded.Data))
|
||||
seen := make([]bool, len(documents))
|
||||
for _, item := range *decoded.Data {
|
||||
if item.Index == nil || item.Score == nil {
|
||||
return nil, fmt.Errorf("pinecone rerank result is missing index or score")
|
||||
}
|
||||
if *item.Index < 0 || *item.Index >= len(documents) {
|
||||
return nil, fmt.Errorf("rerank index %d out of range for %d documents", *item.Index, len(documents))
|
||||
}
|
||||
if seen[*item.Index] {
|
||||
return nil, fmt.Errorf("pinecone rerank returned duplicate index %d", *item.Index)
|
||||
}
|
||||
seen[*item.Index] = true
|
||||
out = append(out, api.RerankResult{
|
||||
Index: *item.Index, Score: *item.Score, Text: documents[*item.Index],
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
package pineconerank
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The four result indexes and scores are from Pinecone's current standalone
|
||||
// rerank guide, "Rerank results on the default field":
|
||||
// https://docs.pinecone.io/guides/search/rerank-results
|
||||
const guideResponse = `{
|
||||
"data": [
|
||||
{"index": 2, "score": 0.48357219, "document": {"id": "vec3", "text": "Apple Inc."}},
|
||||
{"index": 0, "score": 0.048405956, "document": {"id": "vec1", "text": "Apple fruit"}},
|
||||
{"index": 3, "score": 0.007846239, "document": {"id": "vec4", "text": "Apple saying"}},
|
||||
{"index": 1, "score": 0.0006563728, "document": {"id": "vec2", "text": "Apple snack"}}
|
||||
],
|
||||
"model": "bge-reranker-v2-m3",
|
||||
"usage": {"rerank_units": 1}
|
||||
}`
|
||||
|
||||
func newClient(t *testing.T, base string, settings api.RerankSettings) *Client {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
return New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: base, Model: "bge-reranker-v2-m3", Auth: api.HeaderAuth("Api-Key", "key")},
|
||||
Settings: settings,
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestUsesThePineconeShape(t *testing.T) {
|
||||
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{Truncate: "END"})
|
||||
body, err := c.BuildRequestBody("Apple", []string{"fruit", "company"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]any{
|
||||
"model": "bge-reranker-v2-m3", "query": "Apple",
|
||||
"documents": []any{map[string]any{"text": "fruit"}, map[string]any{"text": "company"}},
|
||||
"top_n": float64(2), "rank_fields": []any{"text"}, "return_documents": false,
|
||||
"parameters": map[string]any{"truncate": "END"},
|
||||
}, body)
|
||||
}
|
||||
|
||||
func TestDoesNotSendAnUnspecifiedModelParameter(t *testing.T) {
|
||||
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{})
|
||||
body, err := c.BuildRequestBody("q", []string{"d"})
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, body, "parameters")
|
||||
}
|
||||
|
||||
func TestDecodesOfficialIndexesAndKeepsOriginalTexts(t *testing.T) {
|
||||
var gotPath, gotKey string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath, gotKey = r.URL.Path, r.Header.Get("Api-Key")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(guideResponse))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, api.RerankSettings{})
|
||||
docs := []string{"fruit", "snack", "company", "saying"}
|
||||
got, err := c.Rerank(context.Background(), "Apple", docs)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/rerank", gotPath)
|
||||
assert.Equal(t, "key", gotKey)
|
||||
assert.Equal(t, []api.RerankResult{
|
||||
{Index: 2, Score: 0.48357219, Text: "company"},
|
||||
{Index: 0, Score: 0.048405956, Text: "fruit"},
|
||||
{Index: 3, Score: 0.007846239, Text: "saying"},
|
||||
{Index: 1, Score: 0.0006563728, Text: "snack"},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestFullEndpointIsNotDoubled(t *testing.T) {
|
||||
var path string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
_, _ = w.Write([]byte(`{"data":[{"index":0,"score":0.5}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL+"/rerank", api.RerankSettings{})
|
||||
_, err := c.Rerank(context.Background(), "q", []string{"d"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/rerank", path)
|
||||
}
|
||||
|
||||
func TestMapsDuplicateTextsWithoutEchoedDocuments(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"data":[{"index":2,"score":0.8},{"index":0,"score":0.6},{"index":1,"score":0.1}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, api.RerankSettings{})
|
||||
got, err := c.Rerank(context.Background(), "q", []string{"same", "other", "same"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []api.RerankResult{
|
||||
{Index: 2, Score: 0.8, Text: "same"},
|
||||
{Index: 0, Score: 0.6, Text: "same"},
|
||||
{Index: 1, Score: 0.1, Text: "other"},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestRejectsMalformedResults(t *testing.T) {
|
||||
for _, tc := range []struct{ name, reply, errorText string }{
|
||||
{"missing data", `{}`, "no data"},
|
||||
{"short reply", `{"data":[]}`, "returned 0 scores"},
|
||||
{"missing index", `{"data":[{"score":0.5}]}`, "missing index"},
|
||||
{"missing score", `{"data":[{"index":0}]}`, "missing index or score"},
|
||||
{"out of range", `{"data":[{"index":9,"score":0.5}]}`, "out of range"},
|
||||
{"duplicate index", `{"data":[{"index":0,"score":0.5},{"index":0,"score":0.4}]}`, "duplicate index"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.reply))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, api.RerankSettings{})
|
||||
docs := []string{"a"}
|
||||
if tc.name == "duplicate index" {
|
||||
docs = []string{"a", "b"}
|
||||
}
|
||||
_, err := c.Rerank(context.Background(), "q", docs)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tc.errorText)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSurfacesVendorError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid model"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, api.RerankSettings{})
|
||||
_, err := c.Rerank(context.Background(), "q", []string{"d"})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid model")
|
||||
}
|
||||
|
|
@ -23,6 +23,9 @@ const (
|
|||
// array, and rankings carrying an unbounded logit instead of a
|
||||
// probability.
|
||||
RerankNIM RerankAPI = "nim-rerank"
|
||||
// RerankPinecone is Pinecone Inference's standalone /rerank endpoint:
|
||||
// documents are objects and results live under data with a score field.
|
||||
RerankPinecone RerankAPI = "pinecone-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"
|
||||
|
|
@ -37,7 +40,7 @@ const (
|
|||
// Known reports whether the value names a protocol this build implements.
|
||||
func (a RerankAPI) Known() bool {
|
||||
switch a {
|
||||
case RerankCohere, RerankDashScope, RerankNIM, RerankTEI,
|
||||
case RerankCohere, RerankDashScope, RerankNIM, RerankPinecone, RerankTEI,
|
||||
RerankTencentLKEAP, RerankVolcengineKnowledge:
|
||||
return true
|
||||
}
|
||||
|
|
@ -49,7 +52,7 @@ func (a RerankAPI) Known() bool {
|
|||
// vendor SDKs are imported.
|
||||
func (a RerankAPI) HTTPServed() bool {
|
||||
switch a {
|
||||
case RerankCohere, RerankDashScope, RerankNIM, RerankTEI:
|
||||
case RerankCohere, RerankDashScope, RerankNIM, RerankPinecone, RerankTEI:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
|
|
|||
|
|
@ -4379,6 +4379,30 @@
|
|||
"source": "https://openrouter.ai/docs/api/api-reference/stt/create-transcription"
|
||||
}
|
||||
],
|
||||
"pinecone": [
|
||||
{
|
||||
"id": "bge-reranker-v2-m3",
|
||||
"name": "BGE Reranker v2 M3 (Pinecone)",
|
||||
"type": "Rerank",
|
||||
"context_window": 1024,
|
||||
"source": "https://docs.pinecone.io/reference/api/2025-10/inference/list_models",
|
||||
"compat": {
|
||||
"max_documents": 100,
|
||||
"truncate": "END"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "pinecone-rerank-v0",
|
||||
"name": "Pinecone Rerank v0",
|
||||
"type": "Rerank",
|
||||
"context_window": 512,
|
||||
"source": "https://docs.pinecone.io/reference/api/2025-10/inference/list_models",
|
||||
"compat": {
|
||||
"max_documents": 100,
|
||||
"truncate": "END"
|
||||
}
|
||||
}
|
||||
],
|
||||
"qianfan": [
|
||||
{
|
||||
"id": "ernie-5.0-thinking-preview",
|
||||
|
|
|
|||
|
|
@ -1535,6 +1535,24 @@
|
|||
}
|
||||
}
|
||||
],
|
||||
"pinecone": [
|
||||
{
|
||||
"id": "bge-reranker-v2-m3",
|
||||
"type": "Rerank",
|
||||
"compat": {
|
||||
"max_documents": 100,
|
||||
"truncate": "END"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "pinecone-rerank-v0",
|
||||
"type": "Rerank",
|
||||
"compat": {
|
||||
"max_documents": 100,
|
||||
"truncate": "END"
|
||||
}
|
||||
}
|
||||
],
|
||||
"qianfan": [
|
||||
{
|
||||
"id": "ernie-x1-turbo-32k",
|
||||
|
|
|
|||
|
|
@ -3352,6 +3352,22 @@
|
|||
"source": "https://openrouter.ai/docs/api/api-reference/stt/create-transcription"
|
||||
}
|
||||
],
|
||||
"pinecone": [
|
||||
{
|
||||
"id": "bge-reranker-v2-m3",
|
||||
"name": "BGE Reranker v2 M3 (Pinecone)",
|
||||
"type": "Rerank",
|
||||
"context_window": 1024,
|
||||
"source": "https://docs.pinecone.io/reference/api/2025-10/inference/list_models"
|
||||
},
|
||||
{
|
||||
"id": "pinecone-rerank-v0",
|
||||
"name": "Pinecone Rerank v0",
|
||||
"type": "Rerank",
|
||||
"context_window": 512,
|
||||
"source": "https://docs.pinecone.io/reference/api/2025-10/inference/list_models"
|
||||
}
|
||||
],
|
||||
"qianfan": [
|
||||
{
|
||||
"id": "ernie-5.0-thinking-preview",
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ func TestRerankProtocolAssignment(t *testing.T) {
|
|||
for id, want := range map[string]api.RerankAPI{
|
||||
"aliyun": api.RerankDashScope,
|
||||
"nvidia": api.RerankNIM,
|
||||
"pinecone": api.RerankPinecone,
|
||||
"huggingface_tei": api.RerankTEI,
|
||||
"lkeap": api.RerankTencentLKEAP,
|
||||
"volcengine": api.RerankVolcengineKnowledge,
|
||||
|
|
|
|||
|
|
@ -255,6 +255,8 @@
|
|||
"openrouter/KnowledgeQA/x-ai/grok-4.6": "b43bad43581cfc02bb2f7c8e56fbfea372edf6e4e6b1a34d15442efab0a0b0f4",
|
||||
"openrouter/KnowledgeQA/z-ai/glm-5.3": "d629d890b3e68a3e95a37d320390c60fe44019ff3bd80f9bb4bd897edcfa425c",
|
||||
"openrouter/Rerank/cohere/rerank-v3.5": "35f701fdcf196b6de1e71dc677dd3cdecf1a2a9b4fd71f08f2fb5cbc78601fc5",
|
||||
"pinecone/Rerank/bge-reranker-v2-m3": "b7e3f9e779e7aaf8176a248cdc02f839e1fb0e224e0b99f8571c4522d5a04b45",
|
||||
"pinecone/Rerank/pinecone-rerank-v0": "4edec140b7fb93c950ca8d6f8482e05f412b919e5269889d0919b60af6928835",
|
||||
"qianfan/Embedding/bge-large-zh": "121f5c8566989713874cba0044039f9e02cf53fe23db739709e122459b9a3fda",
|
||||
"qianfan/Embedding/embedding-v1": "cc6b2807cbedb3422ba1982e04cae952c7ddffbba2685e4b53f90774d56aeab0",
|
||||
"qianfan/Embedding/tao-8k": "af316a1f4b9f96f93088f52a3e7e4292b6e30b5aa6f49243830890f4f4043058",
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none"><path d="M12 2.5 3.5 17h17L12 2.5Z" fill="#007F55"/><path d="M12 7.5 7 16h10l-5-8.5Z" fill="#F1FFF8"/><path d="M12 12 9.6 16h4.8L12 12Z" fill="#007F55"/><path d="M12 16v5" stroke="#007F55" stroke-width="2" stroke-linecap="round"/></svg>
|
||||
|
After Width: | Height: | Size: 332 B |
|
|
@ -26,6 +26,7 @@ func Builtins() []*Definition {
|
|||
newNvidiaProvider(),
|
||||
newOpenaiProvider(),
|
||||
newOpenrouterProvider(),
|
||||
newPineconeProvider(),
|
||||
newQianfanProvider(),
|
||||
newQiniuProvider(),
|
||||
newRequestyProvider(),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
// Package providers registers Pinecone's standalone hosted rerank endpoint.
|
||||
// https://docs.pinecone.io/guides/search/rerank-results
|
||||
package providers
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
//go:embed assets/pinecone.svg
|
||||
var pineconeIcon []byte
|
||||
|
||||
// PineconeID identifies the Pinecone provider in the model catalog.
|
||||
const PineconeID = "pinecone"
|
||||
|
||||
// PineconeRerankBaseURL is the default Pinecone Inference API endpoint.
|
||||
const PineconeRerankBaseURL = "https://api.pinecone.io"
|
||||
|
||||
func newPineconeProvider() *Definition {
|
||||
return &Definition{
|
||||
ID: PineconeID, Name: "Pinecone",
|
||||
Description: "Pinecone Inference standalone reranking (bge-reranker-v2-m3, pinecone-rerank-v0)",
|
||||
Website: "https://www.pinecone.io", Icon: pineconeIcon,
|
||||
API: api.APIOpenAICompletions, RerankAPI: api.RerankPinecone,
|
||||
Order: 56, RequiresAuth: true, Auth: AuthAPIKeyHeader,
|
||||
URLPatterns: []string{"api.pinecone.io"},
|
||||
DefaultBaseURLs: map[types.ModelType]string{types.ModelTypeRerank: PineconeRerankBaseURL},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeRerank},
|
||||
Headers: map[string]string{"X-Pinecone-Api-Version": "2026-07"},
|
||||
}
|
||||
}
|
||||
|
|
@ -18,13 +18,13 @@ var expectedIDs = []string{
|
|||
"aliyun", "zhipu", "volcengine", "hunyuan", "siliconflow", "deepseek",
|
||||
"minimax", "moonshot", "mimo", "modelscope", "qianfan", "qiniu", "longcat", "lkeap",
|
||||
"openai", "azure_openai", "anthropic", "gemini",
|
||||
"openrouter", "litellm", "requesty",
|
||||
"openrouter", "litellm", "requesty", "pinecone",
|
||||
"jina", "nvidia", "novita", "gpustack",
|
||||
}
|
||||
|
||||
func TestAllVendorsRegistered(t *testing.T) {
|
||||
if len(expectedIDs) != 28 {
|
||||
t.Fatalf("expected 28 vendor ids in the spec, got %d", len(expectedIDs))
|
||||
if len(expectedIDs) != 29 {
|
||||
t.Fatalf("expected 29 vendor ids in the spec, got %d", len(expectedIDs))
|
||||
}
|
||||
for _, id := range expectedIDs {
|
||||
v, ok := modelruntime.Get(id)
|
||||
|
|
|
|||
|
|
@ -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/pineconerank"
|
||||
"github.com/Tencent/WeKnora/internal/models/api/teirank"
|
||||
modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"
|
||||
|
||||
|
|
@ -202,6 +203,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.RerankPinecone:
|
||||
client = pineconerank.New(pineconerank.Config{Endpoint: endpoint, Settings: resolved.Rerank})
|
||||
case api.RerankTEI:
|
||||
client = teirank.New(teirank.Config{Endpoint: endpoint, Settings: resolved.Rerank})
|
||||
case api.RerankTencentLKEAP:
|
||||
|
|
|
|||
|
|
@ -125,6 +125,12 @@ func answer(r *http.Request, body map[string]any) string {
|
|||
parts = append(parts, fmt.Sprintf(`{"index":%d,"relevance_score":%v}`, i, probability(docs[i])))
|
||||
}
|
||||
return `{"output":{"results":[` + strings.Join(parts, ",") + `]}}`
|
||||
case r.Header.Get("X-Pinecone-Api-Version") != "": // Pinecone Inference
|
||||
docs := texts(body["documents"])
|
||||
for i := len(docs) - 1; i >= 0; i-- {
|
||||
parts = append(parts, fmt.Sprintf(`{"index":%d,"score":%v}`, i, probability(docs[i])))
|
||||
}
|
||||
return `{"data":[` + strings.Join(parts, ",") + `]}`
|
||||
default: // Cohere
|
||||
docs := texts(body["documents"])
|
||||
score := probability
|
||||
|
|
@ -188,6 +194,7 @@ func TestRerankWireFormatPerVendor(t *testing.T) {
|
|||
|
||||
wantPath string
|
||||
wantAuth [2]string // header, a substring its value must contain
|
||||
wantVersion string
|
||||
wantRequests int
|
||||
// wantBody is one request's body, exactly. Batches go out
|
||||
// concurrently, so it is matched against every request rather than
|
||||
|
|
@ -215,6 +222,18 @@ func TestRerankWireFormatPerVendor(t *testing.T) {
|
|||
wantPath: "/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
|
||||
wantBody: cohere("BAAI/bge-reranker-v2-m3", three, nil),
|
||||
},
|
||||
{
|
||||
name: "pinecone native objects and version", provider: "pinecone", model: "bge-reranker-v2-m3",
|
||||
wantPath: "/rerank", wantAuth: [2]string{"Api-Key", "k"}, wantVersion: "2026-07",
|
||||
wantBody: map[string]any{
|
||||
"model": "bge-reranker-v2-m3", "query": query,
|
||||
"documents": []any{
|
||||
map[string]any{"text": "a"}, map[string]any{"text": "bbb"}, map[string]any{"text": "cc"},
|
||||
},
|
||||
"top_n": float64(3), "rank_fields": []any{"text"}, "return_documents": false,
|
||||
"parameters": map[string]any{"truncate": "END"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "qianfan splits at 64 documents", provider: "qianfan", model: "bce-reranker-base", base: "/v2",
|
||||
docs: documents(65), wantRequests: 2,
|
||||
|
|
@ -344,6 +363,9 @@ func TestRerankWireFormatPerVendor(t *testing.T) {
|
|||
for _, req := range up.requests {
|
||||
assert.Equal(t, tc.wantPath, req.path)
|
||||
assert.Contains(t, req.header.Get(tc.wantAuth[0]), tc.wantAuth[1])
|
||||
if tc.wantVersion != "" {
|
||||
assert.Equal(t, tc.wantVersion, req.header.Get("X-Pinecone-Api-Version"))
|
||||
}
|
||||
if tc.appSecret != "" {
|
||||
assert.NotContains(t, req.header.Get("Authorization"), tc.appSecret,
|
||||
"a secret key signs the request and must never travel")
|
||||
|
|
@ -382,3 +404,24 @@ func TestOpenAIDoesNotOfferRerank(t *testing.T) {
|
|||
require.True(t, ok)
|
||||
assert.False(t, v.SupportsType(types.ModelTypeRerank))
|
||||
}
|
||||
|
||||
func TestPineconeCatalogLimitSplitsAt100Documents(t *testing.T) {
|
||||
u := newUpstream(t)
|
||||
docs := documents(101)
|
||||
r, err := NewReranker(&RerankerConfig{
|
||||
Source: types.ModelSourceRemote, Provider: "pinecone", ModelName: "bge-reranker-v2-m3",
|
||||
BaseURL: u.url, APIKey: "k",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
got, err := r.Rerank(context.Background(), "q", docs)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, len(docs))
|
||||
require.Len(t, u.requests, 2)
|
||||
counts := []int{len(u.requests[0].body["documents"].([]any)), len(u.requests[1].body["documents"].([]any))}
|
||||
sort.Ints(counts)
|
||||
assert.Equal(t, []int{1, 100}, counts)
|
||||
for _, req := range u.requests {
|
||||
assert.Equal(t, float64(len(req.body["documents"].([]any))), req.body["top_n"])
|
||||
assert.Equal(t, "2026-07", req.header.Get("X-Pinecone-Api-Version"))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue