feat(rerank): add Cohere provider for the v2 rerank API

main
kwsYeager 2026-10-09 08:20:38 -05:00 committed by lyingbug
parent c6bfe81894
commit e5f9f9deab
11 changed files with 277 additions and 3 deletions

View File

@ -47,6 +47,38 @@ func newClient(t *testing.T, url string, settings api.RerankSettings) *Client {
})
}
// Cohere's v2 reference response, preserving every field and value:
// https://docs.cohere.com/v2/reference/rerank (2026-10-09).
// Unlike the other fixtures, it contains no echoed document.
const cohereV2Response = `{
"results": [
{"index": 3, "relevance_score": 0.999071},
{"index": 4, "relevance_score": 0.7867867},
{"index": 0, "relevance_score": 0.32713068}
],
"id": "07734bd2-2473-4f07-94e1-0d9f0e6843cf",
"meta": {
"api_version": {"version": "2", "is_experimental": false},
"billed_units": {"search_units": 1}
}
}`
func TestDecodesCohereV2ReferenceResponse(t *testing.T) {
server, path, _ := serve(t, cohereV2Response)
defer server.Close()
c := newClient(t, server.URL+"/v2", api.RerankSettings{})
// Only the response is the documented fixture; these five placeholder
// documents supply its index range, not the reference's example texts.
got, err := c.Rerank(context.Background(), "q", []string{"a", "b", "c", "d", "e"})
require.NoError(t, err)
assert.Equal(t, "/v2/rerank", *path)
assert.Equal(t, []api.RerankResult{
{Index: 3, Score: 0.999071},
{Index: 4, Score: 0.7867867},
{Index: 0, Score: 0.32713068},
}, got)
}
func serve(t *testing.T, payload string) (*httptest.Server, *string, *map[string]any) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")

View File

@ -6090,6 +6090,38 @@
"type": "ASR",
"source": "https://docs.bigmodel.cn/api-reference/模型-api/语音转文本"
}
],
"cohere": [
{
"id": "rerank-v4.0-pro",
"name": "rerank-v4.0-pro",
"type": "Rerank",
"input": [
"text"
],
"context_window": 32768,
"source": "https://docs.cohere.com/docs/models#rerank"
},
{
"id": "rerank-v4.0-fast",
"name": "rerank-v4.0-fast",
"type": "Rerank",
"input": [
"text"
],
"context_window": 32768,
"source": "https://docs.cohere.com/docs/models#rerank"
},
{
"id": "rerank-v3.5",
"name": "rerank-v3.5",
"type": "Rerank",
"input": [
"text"
],
"context_window": 4096,
"source": "https://docs.cohere.com/docs/models#rerank"
}
]
}
}

View File

@ -4717,6 +4717,38 @@
"type": "ASR",
"source": "https://docs.bigmodel.cn/api-reference/模型-api/语音转文本"
}
],
"cohere": [
{
"id": "rerank-v4.0-pro",
"name": "rerank-v4.0-pro",
"type": "Rerank",
"input": [
"text"
],
"context_window": 32768,
"source": "https://docs.cohere.com/docs/models#rerank"
},
{
"id": "rerank-v4.0-fast",
"name": "rerank-v4.0-fast",
"type": "Rerank",
"input": [
"text"
],
"context_window": 32768,
"source": "https://docs.cohere.com/docs/models#rerank"
},
{
"id": "rerank-v3.5",
"name": "rerank-v3.5",
"type": "Rerank",
"input": [
"text"
],
"context_window": 4096,
"source": "https://docs.cohere.com/docs/models#rerank"
}
]
}
}

View File

@ -84,6 +84,9 @@
"azure_openai/KnowledgeQA/o1snapshot": "932a1de3ec30ca2f61c26391d01e8053c167417818a347f1fff3968351992868",
"azure_openai/KnowledgeQA/o3snapshot": "06838afe2bf35d03ad99cdceb6b088f272fa83aa4cc25d461d3b0ad034573066",
"azure_openai/KnowledgeQA/o4snapshot": "5a234aaf785bf4b2835f8dbcc49b0f6ce886743ef6d429c68180ca247c9b5a3e",
"cohere/Rerank/rerank-v3.5": "330a5f690caa4a82f03e0da50c8c84b18eeb7010b2af12cc6acbe0bdbcca0799",
"cohere/Rerank/rerank-v4.0-fast": "be4565dc043f51aa21ca3117c6785ad5012cf8a3edbc83ed4c57e676cfc0b7a2",
"cohere/Rerank/rerank-v4.0-pro": "71fc9aaab7c45cdd102331ccc3bb7d238d9cb23e7f72489bd395d94c7aff1f01",
"deepseek/KnowledgeQA/deepseek-chat": "07512b23255f3d8ca9b19123617f7fecdf0da538b6d4c3ea7773ccc73a08be00",
"deepseek/KnowledgeQA/deepseek-flash": "77d77b5c366570d4ba6e9b088c2690e8970e0284af7f5a6b4c114ff2024afdd3",
"deepseek/KnowledgeQA/deepseek-reasoner": "0765764d483664d8df1d1fe2c708671a74eb355764cec3e7a3e1cfe0a1b6e89a",

View File

@ -8,6 +8,7 @@ func Builtins() []*Definition {
newAliyunProvider(),
newAnthropicProvider(),
newAzureOpenaiProvider(),
newCohereProvider(),
newDeepseekProvider(),
newGeminiProvider(),
newGenericProvider(),

View File

@ -0,0 +1,34 @@
// Package providers registers Cohere's hosted text rerank API.
// https://docs.cohere.com/v2/reference/rerank
package providers
import (
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/types"
)
// CohereID identifies Cohere in stored model configurations.
const CohereID = "cohere"
// CohereRerankBaseURL serves Cohere's v2 rerank API.
const CohereRerankBaseURL = "https://api.cohere.com/v2"
func newCohereProvider() *Definition {
return &Definition{
ID: CohereID, Name: "Cohere",
Description: "Cohere text reranking (rerank-v4.0-pro, rerank-v4.0-fast, rerank-v3.5)",
Website: "https://cohere.com", Icon: genericIcon,
API: api.APIOpenAICompletions, RerankAPI: api.RerankCohere,
Order: 57, RequiresAuth: true, Auth: AuthBearer,
URLPatterns: []string{"api.cohere.com"},
DefaultBaseURLs: map[types.ModelType]string{types.ModelTypeRerank: CohereRerankBaseURL},
ModelTypes: []types.ModelType{types.ModelTypeRerank},
Compat: VendorCompat{Rerank: api.RerankCompat{
// The reference recommends no more than 1,000 documents per
// request; use that as our batch size, not a claimed hard limit.
// Omitting top_n returns all results. v2 does not need echoed
// documents: the caller restores their text by result index.
MaxDocuments: api.Ptr(1000),
}},
}
}

View File

@ -0,0 +1,34 @@
package providers_test
import (
"testing"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/providers"
modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCohereRerankCatalog(t *testing.T) {
v, ok := modelruntime.Get("cohere")
require.True(t, ok)
assert.Equal(t, []types.ModelType{types.ModelTypeRerank}, v.ModelTypes)
assert.Equal(t, "https://api.cohere.com/v2", v.GetDefaultURL(types.ModelTypeRerank))
assert.Equal(t, "cohere", modelruntime.DetectByURL("https://api.cohere.com/v2/rerank"))
assert.Error(t, v.ValidateConfig(&providers.Config{ModelName: "rerank-v4.0-pro"}))
assert.NoError(t, v.ValidateConfig(&providers.Config{ModelName: "rerank-v4.0-pro", APIKey: "k"}))
for _, model := range []string{"rerank-v4.0-pro", "rerank-v4.0-fast", "rerank-v3.5"} {
r, err := modelruntime.Resolve(modelruntime.Ref{
Provider: "cohere", Model: model, ModelType: types.ModelTypeRerank,
})
require.NoError(t, err)
assert.True(t, r.Cataloged, model)
assert.Equal(t, api.RerankCohere, r.RerankAPI)
assert.Equal(t, 1000, r.Rerank.MaxDocuments)
assert.Equal(t, api.ScoreProbability, r.Rerank.ScoreScale)
assert.False(t, r.Rerank.SendTopN)
assert.False(t, r.Rerank.SendReturnDocs)
}
}

View File

@ -21,7 +21,7 @@ var expectedIDs = []string{
"minimax", "moonshot", "mimo", "modelscope", "qianfan", "qiniu", "longcat", "lkeap",
"openai", "azure_openai", "anthropic", "gemini",
"openrouter", "litellm", "requesty", "pinecone",
"jina", "nvidia", "novita", "gpustack",
"jina", "nvidia", "novita", "gpustack", "cohere",
}
func TestMinimaxOfficialDefaultURLs(t *testing.T) {
@ -84,8 +84,8 @@ func TestBuiltinDefaultURLsAcrossModelTypes(t *testing.T) {
}
func TestAllVendorsRegistered(t *testing.T) {
if len(expectedIDs) != 29 {
t.Fatalf("expected 29 vendor ids in the spec, got %d", len(expectedIDs))
if len(expectedIDs) != 30 {
t.Fatalf("expected 30 vendor ids in the spec, got %d", len(expectedIDs))
}
for _, id := range expectedIDs {
v, ok := modelruntime.Get(id)

View File

@ -0,0 +1,69 @@
package rerank
import (
"context"
"net/http"
"net/http/httptest"
"sort"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCohereBatchesAtRecommendedDocumentCount(t *testing.T) {
u := newUpstream(t)
docs := documents(1001)
r, err := NewReranker(&RerankerConfig{
Source: types.ModelSourceRemote, Provider: "cohere", ModelName: "rerank-v4.0-pro",
BaseURL: u.url + "/v2", 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)
var counts []int
for _, req := range u.requests {
counts = append(counts, len(req.body["documents"].([]any)))
assert.Equal(t, "/v2/rerank", req.path)
assert.Equal(t, "Bearer k", req.header.Get("Authorization"))
assert.NotContains(t, req.body, "top_n")
assert.NotContains(t, req.body, "return_documents")
}
sort.Ints(counts)
assert.Equal(t, []int{1, 1000}, counts)
seen := make(map[int]bool, len(got))
for _, result := range got {
require.GreaterOrEqual(t, result.Index, 0)
require.Less(t, result.Index, len(docs))
assert.False(t, seen[result.Index], "duplicate index %d", result.Index)
seen[result.Index] = true
assert.Equal(t, docs[result.Index], result.Document.Text)
assert.Equal(t, probability(docs[result.Index]), result.RelevanceScore)
}
}
func TestCohereRestoresDuplicateTextByIndexAndPreservesZero(t *testing.T) {
withRerankSSRFWhitelist(t, "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(`{"results":[{"index":1,"relevance_score":0.8},{"index":0,"relevance_score":0}]}`))
}))
defer server.Close()
r, err := NewReranker(&RerankerConfig{
Source: types.ModelSourceRemote, Provider: "cohere", ModelName: "rerank-v4.0-pro",
BaseURL: server.URL + "/v2", APIKey: "k",
})
require.NoError(t, err)
got, err := r.Rerank(context.Background(), "q", []string{"same", "same"})
require.NoError(t, err)
require.Len(t, got, 2)
assert.Equal(t, 1, got[0].Index)
assert.Equal(t, 0.8, got[0].RelevanceScore)
assert.Equal(t, 0, got[1].Index)
assert.Zero(t, got[1].RelevanceScore)
assert.Equal(t, "same", got[0].Document.Text)
assert.Equal(t, "same", got[1].Document.Text)
}

View File

@ -213,6 +213,16 @@ func TestRerankWireFormatPerVendor(t *testing.T) {
wantPath: "/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("jina-reranker-v3", three, map[string]any{"return_documents": true}),
},
{
name: "cohere v2", provider: "cohere", model: "rerank-v4.0-pro", base: "/v2",
wantPath: "/v2/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("rerank-v4.0-pro", three, nil),
},
{
name: "cohere full endpoint", provider: "cohere", model: "rerank-v3.5", base: "/v2/rerank",
wantPath: "/v2/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("rerank-v3.5", three, nil),
},
{
name: "zhipu on its full rerank URL", provider: "zhipu", model: "rerank", base: "/api/paas/v4/rerank",
wantPath: "/api/paas/v4/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},

View File

@ -274,11 +274,38 @@
| GPUStack | `gpustack` | ✓ | ✓ | ✓ | ✓ | ✓ |
| Hugging Face TEI | `huggingface_tei` | | | ✓ | | |
| Pinecone | `pinecone` | | | ✓ | | |
| Cohere | `cohere` | | | ✓ | | |
表中的「视觉」指可在视觉模型类型下选择该厂商;对话模型本身是否接受图片,以模型目录和「支持视觉/多模态」开关为准。WeKnora 云服务需先在设置中保存云服务凭证,模型名称可选 `chat`、`embedding`、`rerank`、`vlm`。
厂商列表、默认地址和模型目录由服务端下发(`GET /api/v1/models/providers`),运维可以通过[部署叠加](#部署叠加-config-models-json)修改或新增厂商。
### Cohere 重排
新增远程重排模型时,选择 **Cohere**,填写 Cohere API Key,并选择
`rerank-v4.0-pro`、`rerank-v4.0-fast` 或 `rerank-v3.5`。默认地址为
`https://api.cohere.com/v2`,也可填写完整的 `/v2/rerank` 地址。
通过 `POST /api/v1/models` 创建时,请求体示例:
```json
{
"name": "rerank-v4.0-pro",
"type": "Rerank",
"source": "remote",
"parameters": {
"provider": "cohere",
"base_url": "https://api.cohere.com/v2",
"api_key": "your-cohere-api-key"
}
}
```
请求仅发送文本查询和文档,按响应索引恢复原文。WeKnora 遵循
[Cohere API 建议](https://docs.cohere.com/v2/reference/rerank),将超过 1000 篇的候选集
拆成多个请求;1000 是采用的推荐批次大小。省略 `top_n` 以获取全部候选的分数,
超长文档沿用服务端默认截断行为。本接入仅提供 Cohere 文本重排。
## 查看引用与调整配置
知识库和智能体保存对模型的引用。删除模型前需检查依赖详情;内置模型由 YAML 配置管理,应在配置文件中维护。