chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,89 @@
package rerank
import (
"context"
"net/url"
"strings"
"testing"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestEveryCatalogRerankTransport(t *testing.T) {
for _, v := range modelruntime.List() {
for _, m := range v.Models() {
if m.Type != types.ModelTypeRerank {
continue
}
names := append([]string{m.ID}, m.Aliases...)
if m.ID == "" {
names[0] = strings.ReplaceAll(m.Match, "*", "snapshot")
}
for _, name := range names {
t.Run(v.ID+"/"+name, func(t *testing.T) {
u := newUpstream(t)
base, err := url.Parse(v.GetDefaultURL(types.ModelTypeRerank))
require.NoError(t, err)
cfg := &RerankerConfig{
Source: types.ModelSourceRemote,
Provider: v.ID,
ModelName: name,
ModelID: "row-id",
BaseURL: u.url + base.Path,
APIKey: "row-key",
AppID: "app",
AppSecret: "secret",
}
client, err := newReranker(cfg)
if strings.Contains(string(m.Compat), "unsupported_reason") {
require.ErrorContains(t, err, "does not serve")
require.Empty(t, u.requests)
return
}
require.NoError(t, err)
result, err := client.Rerank(context.Background(), "q", []string{"a", "中文"})
require.NoError(t, err)
require.Len(t, result, 2)
require.NotEmpty(t, u.requests)
})
}
}
}
}
func TestStoredRerankSpecReachesWire(t *testing.T) {
u := newUpstream(t)
row := &types.Model{
ID: "stable-id",
Name: "custom",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "generic",
BaseURL: u.url,
APIKey: "model-key",
Spec: &types.ModelSpecOverride{
Compat: map[string]any{
"path": "/custom-rerank",
"send_top_n": true,
"extra_body": map[string]any{
"custom_flag": true,
},
},
},
},
}
client, err := newReranker(ConfigFromModel(row, "", ""))
require.NoError(t, err)
_, err = client.Rerank(context.Background(), "q", []string{"a", "bb"})
require.NoError(t, err)
require.Len(t, u.requests, 1)
req := u.requests[0]
require.Equal(t, "/custom-rerank", req.path)
require.Equal(t, true, req.body["custom_flag"])
require.Equal(t, float64(2), req.body["top_n"])
row.Parameters.Spec.Compat = map[string]any{"misspelled_option": true}
_, err = newReranker(ConfigFromModel(row, "", ""))
require.ErrorContains(t, err, "unknown field")
}
+69
View File
@@ -0,0 +1,69 @@
package rerank
import (
"context"
"net/http"
"net/http/httptest"
"sort"
"testing"
"academy/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)
}
@@ -0,0 +1,32 @@
package rerank
import (
"testing"
"academy/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "rr-1",
Name: "bge-reranker-v2-m3",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "siliconflow",
ExtraConfig: map[string]string{"flag": "on"},
CustomHeaders: map[string]string{"X-Gateway": "g"},
},
}
cfg := ConfigFromModel(m, "app", "secret")
if cfg == nil || cfg.ModelID != "rr-1" || cfg.ModelName != "bge-reranker-v2-m3" {
t.Fatalf("identity mismatch: %+v", cfg)
}
if cfg.Provider != "siliconflow" || cfg.CustomHeaders["X-Gateway"] != "g" {
t.Errorf("provider/headers not propagated: %+v", cfg)
}
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
t.Errorf("cloud creds mismatch: %+v", cfg)
}
}
+189
View File
@@ -0,0 +1,189 @@
package rerank
import (
"context"
"errors"
"fmt"
"sort"
"academy/internal/models/api"
"academy/internal/models/imageprep"
"academy/internal/tracing/langfuse"
"golang.org/x/sync/errgroup"
)
// Image is one image document: its bytes and MIME type.
type Image = api.EmbedImage
// ErrImagesUnsupported is returned when a reranker is asked to score images
// its model or endpoint cannot take.
var ErrImagesUnsupported = errors.New("rerank model does not accept images")
// ImageReranker is the image side of a Reranker whose model scores an image
// against a text query by what it shows. Most rerankers have none; use
// AsImageReranker rather than a type assertion, since every decorator
// implements it whether or not the model underneath does.
type ImageReranker interface {
// AcceptsImages reports whether both the model and its endpoint take
// image documents.
AcceptsImages() bool
// ImageLimits are the vendor's documented per-image limits. The caller
// prepares an image to fit; one outside them is refused.
ImageLimits() imageprep.Limits
// RerankImages scores images against the query on the same scale as
// Rerank scores text, best first; indices refer to images.
RerankImages(ctx context.Context, query string, images []Image) ([]RankResult, error)
}
// AsImageReranker returns r's image side when its model scores images.
func AsImageReranker(r Reranker) (ImageReranker, bool) {
ir, ok := r.(ImageReranker)
if !ok || !ir.AcceptsImages() {
return nil, false
}
return ir, true
}
// imageSide is AsImageReranker for decorators, which must fail a call their
// inner reranker cannot serve.
func imageSide(r Reranker) (ImageReranker, error) {
if ir, ok := AsImageReranker(r); ok {
return ir, nil
}
return nil, fmt.Errorf("%s: %w", r.GetModelName(), ErrImagesUnsupported)
}
func imageLimitsOf(r Reranker) imageprep.Limits {
if ir, ok := AsImageReranker(r); ok {
return ir.ImageLimits()
}
return imageprep.Limits{}
}
func (r *protocolReranker) AcceptsImages() bool { return r.images != nil }
func (r *protocolReranker) ImageLimits() imageprep.Limits {
return imageprep.LimitsOf(r.settings.ImageInput)
}
// RerankImages checks every image against the documented limits before
// sending any, splits them at the documented images per request, and puts
// the scores on the scale Rerank uses.
func (r *protocolReranker) RerankImages(ctx context.Context, query string, images []Image) ([]RankResult, error) {
if r.images == nil {
return nil, fmt.Errorf("%s: %w", r.modelName, ErrImagesUnsupported)
}
if len(images) == 0 {
return nil, nil
}
for i, img := range images {
if err := r.settings.CheckImage(img); err != nil {
return nil, fmt.Errorf("%s rerank: image %d: %w", r.modelName, i, err)
}
}
limit := r.settings.ImageBatchLimit()
type batch struct{ start, end int }
var batches []batch
for start := 0; start < len(images); start += limit {
batches = append(batches, batch{start, min(start+limit, len(images))})
}
scored := make([][]api.RerankResult, len(batches))
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(r.concurrency())
for i, b := range batches {
group.Go(func() error {
out, err := r.images.RerankImages(groupCtx, query, images[b.start:b.end])
if err != nil {
return err
}
for j := range out {
out[j].Index += b.start
}
scored[i] = out
return nil
})
}
if err := group.Wait(); err != nil {
return nil, err
}
results := make([]RankResult, 0, len(images))
for _, b := range scored {
for _, item := range b {
if item.Index < 0 || item.Index >= len(images) {
return nil, fmt.Errorf("%s rerank: index %d out of range for %d images",
r.modelName, item.Index, len(images))
}
results = append(results, RankResult{
Index: item.Index,
RelevanceScore: normalizeScore(item.Score, r.settings.ScoreScale),
})
}
}
sort.SliceStable(results, func(i, j int) bool {
return results[i].RelevanceScore > results[j].RelevanceScore
})
return results, nil
}
// describeImages stands in for images in logs and traces, which must not
// carry their bytes.
func describeImages(images []Image) []string {
out := make([]string, len(images))
for i, img := range images {
out[i] = fmt.Sprintf("<%s, %d bytes>", img.MIMEType, len(img.Data))
}
return out
}
func (d *debugReranker) AcceptsImages() bool {
_, ok := AsImageReranker(d.inner)
return ok
}
func (d *debugReranker) ImageLimits() imageprep.Limits { return imageLimitsOf(d.inner) }
func (d *debugReranker) RerankImages(ctx context.Context, query string, images []Image) ([]RankResult, error) {
inner, err := imageSide(d.inner)
if err != nil {
return nil, err
}
result, err := inner.RerankImages(ctx, query, images)
logRerankDebug(ctx, d.inner.GetModelName(), query, describeImages(images), result, err, 0)
return result, err
}
func (l *langfuseReranker) AcceptsImages() bool {
_, ok := AsImageReranker(l.inner)
return ok
}
func (l *langfuseReranker) ImageLimits() imageprep.Limits { return imageLimitsOf(l.inner) }
func (l *langfuseReranker) RerankImages(ctx context.Context, query string, images []Image) ([]RankResult, error) {
inner, err := imageSide(l.inner)
if err != nil {
return nil, err
}
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return inner.RerankImages(ctx, query, images)
}
described := describeImages(images)
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "rerank.images",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"query": query,
"document_count": len(images),
"images": previewDocs(described, langfuseRerankPreviewDocs),
},
Metadata: map[string]interface{}{"model_id": l.inner.GetModelID()},
})
results, err := inner.RerankImages(genCtx, query, images)
gen.Finish(map[string]interface{}{
"results": summarizeResults(results, described, langfuseRerankMaxScores),
"total_count": len(results),
"score_stats": scoreStats(results),
}, nil, err)
return results, err
}
+144
View File
@@ -0,0 +1,144 @@
package rerank
import (
"bytes"
"context"
"errors"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pngs returns n images of 1..n bytes; the stand-in upstream scores an image
// by its size, so the largest ranks first.
func pngs(n int) []Image {
out := make([]Image, n)
for i := range out {
out[i] = Image{Data: bytes.Repeat([]byte{0x89}, i+1), MIMEType: "image/png"}
}
return out
}
func newImageReranker(t *testing.T, up *upstream, provider, model, base string) Reranker {
t.Helper()
r, err := NewReranker(&RerankerConfig{
Source: types.ModelSourceRemote, Provider: provider, ModelName: model,
BaseURL: up.url + base, APIKey: "k",
})
require.NoError(t, err)
return r
}
// TestRerankImagesWireFormatPerVendor pins the image request each multimodal
// reranker is sent. The image part is the shape the vendor's reference gives,
// as cited on the vendor's rerank compat.
func TestRerankImagesWireFormatPerVendor(t *testing.T) {
const query = "which chart shows revenue"
uri := "data:image/png;base64,iQ==" // one 0x89 byte
cases := []struct {
name, provider, model, base string
wantPath string
wantRequests int
wantBody map[string]any // the first request's body, exactly
}{
{
name: "jina m0 sends image documents, one per request", provider: "jina",
model: "jina-reranker-m0", base: "/v1", wantPath: "/v1/rerank", wantRequests: 3,
wantBody: map[string]any{
"model": "jina-reranker-m0", "query": query, "return_documents": false,
"documents": []any{map[string]any{"image": uri}},
},
},
{
name: "nvidia vl sends image-only passages without text", provider: "nvidia",
model: "nvidia/llama-nemotron-rerank-vl-1b-v2", base: "/v1/retrieval/nvidia/reranking",
wantPath: "/v1/retrieval/nvidia/reranking", wantRequests: 1,
wantBody: map[string]any{
"model": "nvidia/llama-nemotron-rerank-vl-1b-v2", "query": map[string]any{"text": query},
"truncate": "END",
"passages": []any{
map[string]any{"image": uri},
map[string]any{"image": "data:image/png;base64,iYk="},
map[string]any{"image": "data:image/png;base64,iYmJ"},
},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
ir, ok := AsImageReranker(newImageReranker(t, up, tc.provider, tc.model, tc.base))
require.True(t, ok, "the catalog lists this model as scoring images")
got, err := ir.RerankImages(context.Background(), query, pngs(3))
require.NoError(t, err)
require.Len(t, up.requests, tc.wantRequests)
assert.Equal(t, tc.wantPath, up.requests[0].path)
bodies := make([]map[string]any, len(up.requests))
for i, req := range up.requests {
bodies[i] = req.body
}
assert.Contains(t, bodies, tc.wantBody)
// Ranked best first, indices into the images, on the 0..1 scale.
require.Len(t, got, 3)
assert.Equal(t, []int{2, 1, 0}, []int{got[0].Index, got[1].Index, got[2].Index})
for _, r := range got {
assert.GreaterOrEqual(t, r.RelevanceScore, 0.0)
assert.LessOrEqual(t, r.RelevanceScore, 1.0)
}
})
}
}
func TestRerankImagesNeedsBothTheModelAndTheEndpoint(t *testing.T) {
cases := []struct{ name, provider, model, base string }{
{"text model on a vendor with an image field", "jina", "jina-reranker-v3", "/v1"},
{"text model on the NIM shape", "nvidia", "nvidia/nv-rerankqa-mistral-4b-v3", "/v1/retrieval/nvidia/reranking"},
{"generic Cohere-shaped endpoint", "generic", "bge-reranker-v2-m3", "/v1"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
r := newImageReranker(t, up, tc.provider, tc.model, tc.base)
_, ok := AsImageReranker(r)
assert.False(t, ok)
// Every decorator carries the method; skipping AsImageReranker
// still gets a refusal rather than a request.
_, err := r.(ImageReranker).RerankImages(context.Background(), "q", pngs(1))
assert.True(t, errors.Is(err, ErrImagesUnsupported), "got %v", err)
assert.Empty(t, up.requests)
})
}
}
func TestRerankImagesRefusesFormatsTheVendorDoesNotList(t *testing.T) {
up := newUpstream(t)
ir, ok := AsImageReranker(newImageReranker(t, up, "nvidia",
"nvidia/llama-nemotron-rerank-vl-1b-v2", "/v1/retrieval/nvidia/reranking"))
require.True(t, ok)
assert.Contains(t, ir.ImageLimits().MIMETypes, "image/webp")
_, err := ir.RerankImages(context.Background(), "q",
append(pngs(1), Image{Data: []byte{1}, MIMEType: "image/svg+xml"}))
assert.ErrorContains(t, err, "image 1")
assert.Empty(t, up.requests, "refused before sending anything")
}
// The factory adds the debug decorator only when LLM debug logging is on.
func TestRerankImagesPassesThroughEveryDecorator(t *testing.T) {
up := newUpstream(t)
inner := newImageReranker(t, up, "jina", "jina-reranker-m0", "/v1")
wrapped := &debugReranker{inner: &langfuseReranker{inner: inner}}
ir, ok := AsImageReranker(wrapped)
require.True(t, ok)
got, err := ir.RerankImages(context.Background(), "q", pngs(2))
require.NoError(t, err)
assert.Equal(t, 1, got[0].Index)
text := &debugReranker{inner: newImageReranker(t, up, "jina", "jina-reranker-v3", "/v1")}
_, ok = AsImageReranker(text)
assert.False(t, ok)
}
+173
View File
@@ -0,0 +1,173 @@
package rerank
import (
"context"
"academy/internal/tracing/langfuse"
)
const (
langfuseRerankPreviewDocs = 8
langfuseRerankMaxScores = 50
)
// langfuseReranker wraps a Reranker and reports each rerank call as a
// Langfuse generation observation. Rerankers don't return token usage, but
// the call still incurs cost (billed per 1K documents by most vendors); we
// estimate input tokens from the query + documents so the Langfuse cost
// dashboard gets a proportional signal.
type langfuseReranker struct {
inner Reranker
}
func (l *langfuseReranker) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseReranker) GetModelID() string { return l.inner.GetModelID() }
// MaxPassageRunes forwards the wrapped reranker's limit.
func (l *langfuseReranker) MaxPassageRunes(query string) int { return MaxPassageRunes(l.inner, query) }
func (l *langfuseReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Rerank(ctx, query, documents)
}
totalChars := len([]rune(query))
for _, doc := range documents {
totalChars += len([]rune(doc))
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "rerank",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"query": query,
"document_count": len(documents),
"documents_preview": previewDocs(documents, langfuseRerankPreviewDocs),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"num_queries": 1,
"total_chars": totalChars,
"avg_doc_chars": avgDocChars(documents),
},
})
results, err := l.inner.Rerank(genCtx, query, documents)
output := map[string]interface{}{
"results": summarizeResults(results, documents, langfuseRerankMaxScores),
"total_count": len(results),
"score_stats": scoreStats(results),
}
if len(results) > langfuseRerankMaxScores {
output["truncated"] = len(results) - langfuseRerankMaxScores
}
gen.Finish(output, approxRerankUsage(query, documents), err)
return results, err
}
func avgDocChars(documents []string) int {
if len(documents) == 0 {
return 0
}
total := 0
for _, doc := range documents {
total += len([]rune(doc))
}
return total / len(documents)
}
func scoreStats(results []RankResult) map[string]interface{} {
if len(results) == 0 {
return nil
}
minScore := results[0].RelevanceScore
maxScore := results[0].RelevanceScore
sum := 0.0
for _, r := range results {
if r.RelevanceScore < minScore {
minScore = r.RelevanceScore
}
if r.RelevanceScore > maxScore {
maxScore = r.RelevanceScore
}
sum += r.RelevanceScore
}
return map[string]interface{}{
"min": minScore,
"max": maxScore,
"avg": sum / float64(len(results)),
}
}
func approxRerankUsage(query string, documents []string) *langfuse.TokenUsage {
total := len([]rune(query))/4 + 1
for _, d := range documents {
total += len([]rune(d))/4 + 1
}
if total == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: total,
Total: total,
Unit: "TOKENS",
}
}
func previewDocs(docs []string, n int) []map[string]interface{} {
if len(docs) < n {
n = len(docs)
}
out := make([]map[string]interface{}, 0, n)
for i := 0; i < n; i++ {
out = append(out, map[string]interface{}{
"index": i,
"preview": truncateRunes(docs[i], 160),
"length": len([]rune(docs[i])),
})
}
return out
}
func summarizeResults(results []RankResult, documents []string, n int) []map[string]interface{} {
if len(results) < n {
n = len(results)
}
out := make([]map[string]interface{}, 0, n)
for i := 0; i < n; i++ {
row := map[string]interface{}{
"rank": i + 1,
"index": results[i].Index,
"model_score": results[i].RelevanceScore,
}
idx := results[i].Index
if idx >= 0 && idx < len(documents) {
row["preview"] = truncateRunes(documents[idx], 160)
}
out = append(out, row)
}
return out
}
func truncateRunes(s string, maxRunes int) string {
r := []rune(s)
if len(r) <= maxRunes {
return s
}
return string(r[:maxRunes]) + "..."
}
// wrapRerankerLangfuse applies the Langfuse decorator when the manager is
// enabled. Called from NewReranker after the debug wrapper so both sinks see
// the same calls.
func wrapRerankerLangfuse(r Reranker, err error) (Reranker, error) {
if err != nil || r == nil {
return r, err
}
if !langfuse.GetManager().Enabled() {
return r, nil
}
return &langfuseReranker{inner: r}, nil
}
+36
View File
@@ -0,0 +1,36 @@
package rerank
import (
"strings"
"academy/internal/models/api"
"academy/internal/models/api/tencentlkeap"
modelruntime "academy/internal/models/runtime"
)
// Tencent action defaults retained for existing callers.
const (
LKEAPRerankEndpoint = tencentlkeap.LKEAPRerankEndpoint
LKEAPDefaultRegion = tencentlkeap.LKEAPDefaultRegion
LKEAPDefaultRerankModel = tencentlkeap.LKEAPDefaultRerankModel
)
// Test composition may route the action SDK to a local stand-in.
var lkeapEndpoint, lkeapScheme = LKEAPRerankEndpoint, "HTTPS"
func newLKEAPClient(config *RerankerConfig, resolved *modelruntime.Resolved) (api.Reranker, error) {
secret := strings.TrimSpace(config.AppSecret)
if secret == "" {
secret = config.ExtraConfig["secret_key"]
}
return tencentlkeap.New(
tencentlkeap.Config{
SecretID: config.APIKey,
SecretKey: secret,
Region: config.ExtraConfig["region"],
Model: resolved.RemoteModel,
Endpoint: lkeapEndpoint,
Scheme: lkeapScheme,
},
)
}
+73
View File
@@ -0,0 +1,73 @@
package rerank
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/logger"
)
// debugReranker wraps a Reranker with LLM debug logging.
type debugReranker struct {
inner Reranker
}
func (d *debugReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
start := time.Now()
result, err := d.inner.Rerank(ctx, query, documents)
logRerankDebug(ctx, d.inner.GetModelName(), query, documents, result, err, time.Since(start))
return result, err
}
func (d *debugReranker) GetModelName() string { return d.inner.GetModelName() }
func (d *debugReranker) GetModelID() string { return d.inner.GetModelID() }
// MaxPassageRunes forwards the wrapped reranker's limit.
func (d *debugReranker) MaxPassageRunes(query string) int { return MaxPassageRunes(d.inner, query) }
func logRerankDebug(ctx context.Context, model string, query string, documents []string, results []RankResult, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Rerank",
Model: model,
Duration: dur,
}
// Query section
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Query",
Content: query,
})
// Documents section
var docBuf strings.Builder
docBuf.WriteString(fmt.Sprintf("count=%d\n", len(documents)))
for i, doc := range documents {
preview := strings.ReplaceAll(doc, "\n", "\\n")
preview = logger.TruncateRunes(preview, 200)
docBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(doc)), preview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Documents", Content: docBuf.String()})
// Results section
if results != nil {
var resBuf strings.Builder
resBuf.WriteString(fmt.Sprintf("count=%d\n", len(results)))
for _, r := range results {
docPreview := strings.ReplaceAll(r.Document.Text, "\n", "\\n")
docPreview = logger.TruncateRunes(docPreview, 200)
resBuf.WriteString(fmt.Sprintf(" [%d] score=%.6f %s\n", r.Index, r.RelevanceScore, docPreview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Results", Content: resBuf.String()})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
+42
View File
@@ -0,0 +1,42 @@
package rerank
import (
"encoding/json"
"fmt"
"strings"
"unicode/utf8"
)
const (
maxLogDocuments = 3
maxLogTextRunes = 120
)
func buildRerankRequestDebug(model, endpoint, query string, documents []string) string {
previews := make([]string, 0, maxLogDocuments)
for i, doc := range documents {
if i >= maxLogDocuments {
break
}
previews = append(previews, compactForLog(doc, maxLogTextRunes))
}
previewJSON, _ := json.Marshal(previews)
return fmt.Sprintf(
"rerank request endpoint=%s model=%s query_preview=%q query_runes=%d documents=%d preview_docs=%s",
endpoint,
model,
compactForLog(query, maxLogTextRunes),
utf8.RuneCountInString(query),
len(documents),
string(previewJSON),
)
}
func compactForLog(text string, maxRunes int) string {
normalized := strings.Join(strings.Fields(strings.TrimSpace(text)), " ")
if utf8.RuneCountInString(normalized) <= maxRunes {
return normalized
}
return string([]rune(normalized)[:maxRunes]) + "...(truncated)"
}
@@ -0,0 +1,40 @@
package rerank
import (
"testing"
"time"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
)
func TestMaxPassageRunesFromSettings(t *testing.T) {
t.Parallel()
cases := []struct {
name string
settings api.RerankSettings
query string
want int
}{
{"no limits", api.RerankSettings{}, "query", 0},
{"per document", api.RerankSettings{MaxDocumentChars: 4096}, "query", 4096},
{"request budget minus query", api.RerankSettings{MaxRequestChars: 2000}, "查询内容", 1996},
{"tighter of the two", api.RerankSettings{MaxDocumentChars: 500, MaxRequestChars: 2000}, "q", 500},
{"request budget tighter", api.RerankSettings{MaxDocumentChars: 4096, MaxRequestChars: 2000}, "q", 1999},
{"query fills the budget", api.RerankSettings{MaxRequestChars: 3}, "long query", 1},
}
for _, tc := range cases {
r := newWrapped(&fakeProtocol{}, tc.settings)
assert.Equal(t, tc.want, r.MaxPassageRunes(tc.query), tc.name)
// Wrappers must not hide the limit.
for _, wrapped := range []Reranker{&debugReranker{inner: r}, &langfuseReranker{inner: r}} {
assert.Equal(t, tc.want, MaxPassageRunes(wrapped, tc.query), tc.name+" via %T", wrapped)
}
}
}
func TestRerankHTTPClientHasDefaultTimeout(t *testing.T) {
t.Parallel()
assert.Equal(t, defaultRerankRequestTimeout, newRerankHTTPClient(0).Timeout)
assert.Equal(t, 5*time.Second, newRerankHTTPClient(5*time.Second).Timeout)
}
+159
View File
@@ -0,0 +1,159 @@
package rerank
import (
"context"
"fmt"
"math"
"sort"
"unicode/utf8"
"academy/internal/logger"
"academy/internal/models/api"
"golang.org/x/sync/errgroup"
)
// protocolReranker adapts a protocol client to the Reranker interface and
// owns the two things every vendor needs and none of them should implement
// itself: splitting a candidate set that exceeds the documented per-request
// ceilings, and putting the returned scores on one scale.
type protocolReranker struct {
inner api.Reranker
// images is nil unless the model and the endpoint both take images.
images api.ImageReranker
settings api.RerankSettings
endpoint string
modelName string
modelID string
}
// defaultBatchConcurrency bounds in-flight batches when a vendor declares no
// preference, so a large embedding_top_k cannot fan out into an unbounded
// burst of requests.
const defaultBatchConcurrency = 4
func (r *protocolReranker) GetModelName() string { return r.modelName }
func (r *protocolReranker) GetModelID() string { return r.modelID }
func (r *protocolReranker) Rerank(
ctx context.Context, query string, documents []string,
) ([]RankResult, error) {
if len(documents) == 0 {
return nil, nil
}
logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, r.endpoint, query, documents))
// The query travels in every request, so an over-long one cannot be made
// to fit by splitting the documents. SplitBatches charges it to each
// batch but only against a whole-request budget; a vendor that caps the
// query on its own is checked here.
if limit := r.settings.MaxQueryChars; limit > 0 {
if length := utf8.RuneCountInString(query); length > limit {
return nil, fmt.Errorf(
"%s rerank: query is %d characters; the limit is %d",
r.modelName, length, limit,
)
}
}
batches, err := api.SplitBatches(documents, utf8.RuneCountInString(query), r.settings.BatchLimits())
if err != nil {
return nil, fmt.Errorf("%s rerank: %w", r.modelName, err)
}
// Each batch is scored against the same query independently, so the
// per-batch results are comparable and are merged and re-ranked below.
scored := make([][]api.RerankResult, len(batches))
group, groupCtx := errgroup.WithContext(ctx)
group.SetLimit(r.concurrency())
for i, batch := range batches {
group.Go(func() error {
out, err := r.inner.Rerank(groupCtx, query, batch.Items)
if err != nil {
return err
}
for j := range out {
out[j].Index += batch.Start
}
scored[i] = out
return nil
})
}
if err := group.Wait(); err != nil {
return nil, err
}
results := make([]RankResult, 0, len(documents))
for _, batch := range scored {
for _, item := range batch {
if item.Index < 0 || item.Index >= len(documents) {
return nil, fmt.Errorf(
"%s rerank: index %d out of range for %d documents",
r.modelName, item.Index, len(documents),
)
}
text := item.Text
if text == "" {
text = documents[item.Index]
}
results = append(results, RankResult{
Index: item.Index,
Document: DocumentInfo{Text: text},
RelevanceScore: normalizeScore(item.Score, r.settings.ScoreScale),
})
}
}
// A single request comes back ranked, and the retrieval pipeline reads
// the slice as ranked: it takes results[0] as the best candidate for its
// threshold fallback. Concatenating per-batch results would make that the
// best of the first batch only, so the merged set is ordered once here.
// Ties keep the lower index, which keeps the order stable.
sort.SliceStable(results, func(i, j int) bool {
return results[i].RelevanceScore > results[j].RelevanceScore
})
return results, nil
}
// MaxPassageRunes implements PassageLimiter from the documented per-document
// and per-request ceilings; the query is charged against the latter because
// every request repeats it.
func (r *protocolReranker) MaxPassageRunes(query string) int {
limit := r.settings.MaxDocumentChars
if total := r.settings.MaxRequestChars; total > 0 {
// A query that leaves no room fails in Rerank with its own error;
// 1 keeps the limit meaningful rather than reading as "no limit".
room := max(total-utf8.RuneCountInString(query), 1)
if limit <= 0 || room < limit {
limit = room
}
}
return max(limit, 0)
}
func (r *protocolReranker) concurrency() int {
if r.settings.MaxConcurrency > 0 {
return r.settings.MaxConcurrency
}
return defaultBatchConcurrency
}
// normalizeScore puts every vendor's score on the 0..1 scale the retrieval
// pipeline compares against RerankThreshold.
//
// Most protocols already return a relevance probability. NIM returns the raw
// logit of its relevance head instead — unbounded and routinely negative —
// so a threshold tuned for probabilities would reject almost everything on
// that vendor. The logistic function is the inverse of a log-odds, so this is
// a unit conversion rather than a heuristic: it maps the vendor's own ranking
// onto the scale the rest of the system already speaks, order preserved.
func normalizeScore(score float64, scale api.ScoreScale) float64 {
if scale != api.ScoreLogit {
return score
}
// Two branches so neither exponential overflows: this is the form the
// pre-catalog NVIDIA client used, kept verbatim.
if score >= 0 {
return 1 / (1 + math.Exp(-score))
}
exp := math.Exp(score)
return exp / (1 + exp)
}
+186
View File
@@ -0,0 +1,186 @@
package rerank
import (
"context"
"fmt"
"math"
"strings"
"sync"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeProtocol records every batch it was handed and scores documents by
// their position within the batch, so a wrong offset shows up immediately.
type fakeProtocol struct {
mu sync.Mutex
batches [][]string
err error
}
func (f *fakeProtocol) Rerank(
_ context.Context, _ string, documents []string,
) ([]api.RerankResult, error) {
f.mu.Lock()
f.batches = append(f.batches, append([]string(nil), documents...))
f.mu.Unlock()
if f.err != nil {
return nil, f.err
}
out := make([]api.RerankResult, len(documents))
for i, doc := range documents {
out[i] = api.RerankResult{Index: i, Score: float64(i), Text: doc}
}
return out, nil
}
func newWrapped(inner api.Reranker, settings api.RerankSettings) *protocolReranker {
return &protocolReranker{
inner: inner, settings: settings,
endpoint: "https://example.invalid", modelName: "m", modelID: "id",
}
}
// The documented per-request ceilings live on the vendor, and one shared
// layer enforces them. Indices must come back pointing into the caller's
// original slice, not into the batch.
func TestBatchingSplitsAndRestoresGlobalIndices(t *testing.T) {
fake := &fakeProtocol{}
r := newWrapped(fake, api.RerankSettings{MaxDocuments: 2, MaxConcurrency: 1})
docs := []string{"d0", "d1", "d2", "d3", "d4"}
got, err := r.Rerank(context.Background(), "q", docs)
require.NoError(t, err)
require.Len(t, fake.batches, 3, "5 documents at 2 per request is 3 requests")
indices := make([]int, 0, len(got))
for _, item := range got {
indices = append(indices, item.Index)
assert.Equal(t, docs[item.Index], item.Document.Text, "index must address the caller's slice")
}
assert.ElementsMatch(t, []int{0, 1, 2, 3, 4}, indices)
}
func TestBatchingIsSkippedWhenTheVendorDeclaresNoLimit(t *testing.T) {
fake := &fakeProtocol{}
r := newWrapped(fake, api.RerankSettings{})
_, err := r.Rerank(context.Background(), "q", []string{"a", "b", "c", "d"})
require.NoError(t, err)
assert.Len(t, fake.batches, 1)
}
// A document over the vendor's per-document ceiling cannot be scored. Saying
// so beats sending a prefix and returning a number for text nobody asked
// about.
func TestAnOversizedDocumentIsAnError(t *testing.T) {
r := newWrapped(&fakeProtocol{}, api.RerankSettings{MaxDocumentChars: 10})
_, err := r.Rerank(context.Background(), "q", []string{"ok", strings.Repeat("x", 99)})
require.Error(t, err)
assert.Contains(t, err.Error(), "index 1")
}
func TestBatchErrorsPropagate(t *testing.T) {
r := newWrapped(&fakeProtocol{err: fmt.Errorf("upstream exploded")}, api.RerankSettings{})
_, err := r.Rerank(context.Background(), "q", []string{"a"})
require.Error(t, err)
assert.Contains(t, err.Error(), "upstream exploded")
}
func TestEmptyInputMakesNoRequest(t *testing.T) {
fake := &fakeProtocol{}
r := newWrapped(fake, api.RerankSettings{})
got, err := r.Rerank(context.Background(), "q", nil)
require.NoError(t, err)
assert.Empty(t, got)
assert.Empty(t, fake.batches)
}
// NIM returns the raw logit of its relevance head. The retrieval pipeline
// compares scores against RerankThreshold, which is tuned for probabilities,
// so the logit is converted rather than passed through — otherwise the
// default threshold of 0.2 keeps only documents whose logit is positive.
func TestLogitScoresBecomeProbabilities(t *testing.T) {
for _, tc := range []struct {
logit float64
want float64
}{
{logit: 0.226318359375, want: 0.5563},
{logit: -1.171875, want: 0.2366},
{logit: -6.3125, want: 0.0018},
{logit: 0, want: 0.5},
} {
assert.InDelta(t, tc.want, normalizeScore(tc.logit, api.ScoreLogit), 1e-4,
"logit %v", tc.logit)
}
}
// The conversion is monotonic, so it re-scales without reordering.
func TestLogitConversionPreservesOrder(t *testing.T) {
logits := []float64{-6.3125, -1.171875, 0.226318359375, 4}
previous := -1.0
for _, logit := range logits {
got := normalizeScore(logit, api.ScoreLogit)
assert.Greater(t, got, previous)
previous = got
}
}
func TestProbabilityScoresPassThroughUntouched(t *testing.T) {
assert.Equal(t, 0.9819, normalizeScore(0.9819, api.ScoreProbability))
assert.Equal(t, 0.9819, normalizeScore(0.9819, ""))
}
// A vendor that caps the query cannot be satisfied by splitting documents,
// so the query is checked on its own before any request goes out.
func TestAnOversizedQueryIsAnError(t *testing.T) {
fake := &fakeProtocol{}
r := newWrapped(fake, api.RerankSettings{MaxQueryChars: 10})
_, err := r.Rerank(context.Background(), strings.Repeat("q", 11), []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "query is 11 characters")
assert.Empty(t, fake.batches, "nothing should reach the vendor")
}
func TestAQueryWithinTheLimitPasses(t *testing.T) {
r := newWrapped(&fakeProtocol{}, api.RerankSettings{MaxQueryChars: 10})
_, err := r.Rerank(context.Background(), strings.Repeat("中", 10), []string{"d"})
require.NoError(t, err, "runes, not bytes")
}
// The retrieval pipeline reads results[0] as the best candidate. Batches come
// back each individually ranked, so the merged set has to be re-ranked or the
// caller would see the best of the first batch only.
func TestMergedBatchesAreRankedGlobally(t *testing.T) {
// Scores are the position within the batch, so batch 2 holds the highest.
r := newWrapped(&fakeProtocol{}, api.RerankSettings{MaxDocuments: 2, MaxConcurrency: 1})
got, err := r.Rerank(context.Background(), "q", []string{"d0", "d1", "d2", "d3", "d4"})
require.NoError(t, err)
require.Len(t, got, 5)
for i := 1; i < len(got); i++ {
assert.GreaterOrEqual(t, got[i-1].RelevanceScore, got[i].RelevanceScore,
"results must be ranked across batches, not concatenated")
}
}
// The pre-catalog NVIDIA client used a two-branch logistic so neither
// exponential overflows. These are the values its own test pinned.
func TestLogitConversionHandlesExtremes(t *testing.T) {
for _, logit := range []float64{23, 0, -23} {
got := normalizeScore(logit, api.ScoreLogit)
assert.InDelta(t, 1/(1+math.Exp(-logit)), got, 1e-12, "logit %v", logit)
assert.Greater(t, got, 0.0)
assert.Less(t, got, 1.0)
}
assert.False(t, math.IsNaN(normalizeScore(-1000, api.ScoreLogit)))
assert.False(t, math.IsNaN(normalizeScore(1000, api.ScoreLogit)))
}
@@ -0,0 +1,31 @@
package rerank
import (
"testing"
"academy/internal/models/providers"
modelruntime "academy/internal/models/runtime"
)
// TestDetectByURLSeesVendorCatalog guards the blank import of
// runtime composition.
//
// modelruntime.DetectByURL returns "generic" for every URL while the catalog is
// empty. Without the vendor packages linked in, a stored rerank row that
// carries no provider id resolves to the generic Cohere client: LKEAP and
// Volcengine lose their signed SDK clients and Aliyun its native protocol.
func TestDetectByURLSeesVendorCatalog(t *testing.T) {
cases := map[string]string{
"https://api.lkeap.cloud.tencent.com/v1": "lkeap",
"https://api-knowledgebase.mlp.cn-beijing.volces.com": "volcengine",
"https://api.jina.ai/v1": "jina",
"https://open.bigmodel.cn/api/paas/v4": "zhipu",
"https://dashscope.aliyuncs.com/compatible-mode/v1": "aliyun",
"https://some-self-hosted-gateway.example.internal/v1": providers.GenericID,
}
for baseURL, want := range cases {
if got := modelruntime.DetectByURL(baseURL); got != want {
t.Errorf("DetectByURL(%q) = %q, want %q", baseURL, got, want)
}
}
}
+236
View File
@@ -0,0 +1,236 @@
// Package rerank adapts rerank protocols to application batching and score semantics.
package rerank
import (
"context"
"encoding/json"
"fmt"
"time"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/models/api/cohererank"
"academy/internal/models/api/dashscoperank"
"academy/internal/models/api/nimrerank"
"academy/internal/models/api/pineconerank"
"academy/internal/models/api/teirank"
modelruntime "academy/internal/models/runtime"
// modelruntime.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: LKEAP and Volcengine would lose their
// signed clients and Aliyun its native protocol.
"academy/internal/types"
)
// Reranker defines the interface for document reranking
type Reranker interface {
// Rerank reranks documents based on relevance to the query
Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error)
// GetModelName returns the model name
GetModelName() string
// GetModelID returns the model ID
GetModelID() string
}
// PassageLimiter is implemented by rerankers whose vendor documents how large
// a document may be. The rerank stage builds its passages itself (title,
// chunk body, captions, OCR text, generated questions), so it can fit them to
// the limit instead of letting one oversized candidate fail the whole
// request, which the protocol layer rightly refuses to truncate on its own.
type PassageLimiter interface {
// MaxPassageRunes returns the longest document, in runes, one request
// can carry beside query. 0 means no documented limit.
MaxPassageRunes(query string) int
}
// MaxPassageRunes reports r's passage limit for query, or 0 when r documents
// none.
func MaxPassageRunes(r Reranker, query string) int {
if limiter, ok := r.(PassageLimiter); ok {
return limiter.MaxPassageRunes(query)
}
return 0
}
type RankResult struct {
Index int `json:"index"`
Document DocumentInfo `json:"document"`
RelevanceScore float64 `json:"relevance_score"`
}
// Handles the RelevanceScore field by checking if RelevanceScore exists first, otherwise falls back to Score field
func (r *RankResult) UnmarshalJSON(data []byte) error {
var temp struct {
Index int `json:"index"`
Document DocumentInfo `json:"document"`
RelevanceScore *float64 `json:"relevance_score"`
Score *float64 `json:"score"`
}
if err := json.Unmarshal(data, &temp); err != nil {
return fmt.Errorf("failed to unmarshal rank result: %w", err)
}
r.Index = temp.Index
r.Document = temp.Document
if temp.RelevanceScore != nil {
r.RelevanceScore = *temp.RelevanceScore
} else if temp.Score != nil {
r.RelevanceScore = *temp.Score
}
return nil
}
type DocumentInfo struct {
Text string `json:"text"`
}
// UnmarshalJSON handles both string and object formats for DocumentInfo
func (d *DocumentInfo) UnmarshalJSON(data []byte) error {
// First try to unmarshal as a string
var text string
if err := json.Unmarshal(data, &text); err == nil {
d.Text = text
return nil
}
// If that fails, try to unmarshal as an object with text field
var temp struct {
Text string `json:"text"`
}
if err := json.Unmarshal(data, &temp); err != nil {
return fmt.Errorf("failed to unmarshal DocumentInfo: %w", err)
}
d.Text = temp.Text
return nil
}
type RerankerConfig struct {
APIKey string
BaseURL string
ModelName string
Source types.ModelSource
ModelID string
Provider string // Provider identifier: openai, aliyun, zhipu, siliconflow, jina, generic
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
ExtraConfig map[string]string
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
}
// ConfigFromModel 根据 types.Model 构造 RerankerConfig。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// appID / appSecret 是已解密的 AcademyCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) *RerankerConfig {
if m == nil {
return nil
}
return &RerankerConfig{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
Spec: m.Parameters.Spec,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
// NewReranker creates a reranker based on the configuration
func NewReranker(config *RerankerConfig) (Reranker, error) {
r, err := newReranker(config)
if err != nil {
return r, err
}
if logger.LLMDebugEnabled() {
r = &debugReranker{inner: r}
}
return wrapRerankerLangfuse(r, nil)
}
// newReranker resolves the catalog and returns the protocol client for the
// configured model, wrapped in the shared batching and score-scaling layer.
// It mirrors chat.NewRemoteChat: the vendor's facts decide the protocol, the
// URL and the credential, and this function knows no vendor names.
func newReranker(config *RerankerConfig) (Reranker, error) {
if config == nil {
return nil, fmt.Errorf("rerank config is nil")
}
resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: config.Provider,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeRerank,
Extra: config.ExtraConfig,
Override: config.Spec,
})
if err != nil {
return nil, err
}
if err := validateRerankBaseURL(resolved.BaseURL); err != nil {
return nil, err
}
vendor := resolved.Vendor
endpoint, err := resolved.Endpoint(types.ModelTypeRerank, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey, AppID: config.AppID, AppSecret: config.AppSecret},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
Client: newRerankHTTPClient(time.Duration(resolved.Rerank.RequestTimeout) * time.Second),
})
if err != nil {
return nil, err
}
var client api.Reranker
switch resolved.RerankAPI {
case api.RerankCohere:
client = cohererank.New(cohererank.Config{Endpoint: endpoint, Settings: resolved.Rerank})
case api.RerankDashScope:
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:
client, err = newLKEAPClient(config, resolved)
case api.RerankVolcengineKnowledge:
client, err = newVolcengineClient(config, resolved)
default:
return nil, fmt.Errorf("unsupported rerank api %q for provider %s", resolved.RerankAPI, vendor.ID)
}
if err != nil {
return nil, err
}
// Images need both halves: the catalog saying the model scores them, and
// a protocol that can carry one to this vendor.
var images api.ImageReranker
if ir, ok := client.(api.ImageReranker); ok && ir.AcceptsImages() && resolved.Spec.AcceptsImages() {
images = ir
}
return &protocolReranker{
inner: client,
images: images,
settings: resolved.Rerank,
endpoint: resolved.BaseURL,
modelName: config.ModelName,
modelID: config.ModelID,
}, nil
}
+156
View File
@@ -0,0 +1,156 @@
package rerank
import (
"encoding/json"
"testing"
)
func TestRankResultUnmarshalJSON(t *testing.T) {
tests := []struct {
name string
input string
expectedText string
expectedIndex int
expectedScore float64
expectError bool
}{
{
name: "document as string with relevance_score",
input: `{"index": 0, "document": "This is a document", "relevance_score": 0.95}`,
expectedText: "This is a document",
expectedIndex: 0,
expectedScore: 0.95,
expectError: false,
},
{
name: "document as object with relevance_score",
input: `{"index": 1, "document": {"text": "This is a document"}, "relevance_score": 0.87}`,
expectedText: "This is a document",
expectedIndex: 1,
expectedScore: 0.87,
expectError: false,
},
{
name: "document as string with score field",
input: `{"index": 2, "document": "This is a document", "score": 0.92}`,
expectedText: "This is a document",
expectedIndex: 2,
expectedScore: 0.92,
expectError: false,
},
{
name: "document as object with score field",
input: `{"index": 3, "document": {"text": "This is a document"}, "score": 0.78}`,
expectedText: "This is a document",
expectedIndex: 3,
expectedScore: 0.78,
expectError: false,
},
{
name: "document as string with both score fields - relevance_score takes priority",
input: `{"index": 4, "document": "This is a document", "relevance_score": 0.95, "score": 0.80}`,
expectedText: "This is a document",
expectedIndex: 4,
expectedScore: 0.95,
expectError: false,
},
{
name: "document as object with both score fields - relevance_score takes priority",
input: `{"index": 5, "document": {"text": "This is a document"}, "relevance_score": 0.88, "score": 0.75}`,
expectedText: "This is a document",
expectedIndex: 5,
expectedScore: 0.88,
expectError: false,
},
{
name: "document as string with no score fields",
input: `{"index": 6, "document": "This is a document"}`,
expectedText: "This is a document",
expectedIndex: 6,
expectedScore: 0.0,
expectError: false,
},
{
name: "document as object with no score fields",
input: `{"index": 7, "document": {"text": "This is a document"}}`,
expectedText: "This is a document",
expectedIndex: 7,
expectedScore: 0.0,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var result RankResult
err := json.Unmarshal([]byte(tt.input), &result)
if tt.expectError {
if err == nil {
t.Errorf("Expected error but got none")
}
return
}
if err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if result.Document.Text != tt.expectedText {
t.Errorf("Expected document text %q, got %q", tt.expectedText, result.Document.Text)
}
if result.Index != tt.expectedIndex {
t.Errorf("Expected index %d, got %d", tt.expectedIndex, result.Index)
}
if result.RelevanceScore != tt.expectedScore {
t.Errorf("Expected score %f, got %f", tt.expectedScore, result.RelevanceScore)
}
})
}
}
// TestDocumentInfoMarshalJSON tests that DocumentInfo can be marshaled back to JSON
func TestDocumentInfoMarshalJSON(t *testing.T) {
doc := DocumentInfo{Text: "Test document content"}
data, err := json.Marshal(doc)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
expected := `{"text":"Test document content"}`
if string(data) != expected {
t.Errorf("Expected %s, got %s", expected, string(data))
}
}
// TestRankResultMarshalJSON tests that RankResult can be marshaled back to JSON
func TestRankResultMarshalJSON(t *testing.T) {
result := RankResult{
Index: 1,
Document: DocumentInfo{Text: "Test document"},
RelevanceScore: 0.95,
}
data, err := json.Marshal(result)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
// Parse back to verify structure
var parsed RankResult
err = json.Unmarshal(data, &parsed)
if err != nil {
t.Fatalf("Round-trip unmarshal failed: %v", err)
}
if parsed.Index != result.Index {
t.Errorf("Index mismatch: expected %d, got %d", result.Index, parsed.Index)
}
if parsed.Document.Text != result.Document.Text {
t.Errorf("Document text mismatch: expected %q, got %q", result.Document.Text, parsed.Document.Text)
}
if parsed.RelevanceScore != result.RelevanceScore {
t.Errorf("Score mismatch: expected %f, got %f", result.RelevanceScore, parsed.RelevanceScore)
}
}
+156
View File
@@ -0,0 +1,156 @@
package rerank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
modelruntime "academy/internal/models/runtime"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The two SDK-backed vendors have no protocol package, so their outbound
// shape is not covered by a golden test. These pin what the SDK actually puts
// on the wire, which is what the per-client tests did before the migration.
const volcengineRerankPath = "/api/knowledge/service/rerank"
func TestVolcengineClientOutboundShape(t *testing.T) {
withRerankSSRFWhitelist(t, "127.0.0.1")
var request struct {
Datas []struct {
Query string `json:"query"`
Content *string `json:"content"`
} `json:"datas"`
RerankModel *string `json:"rerank_model"`
RerankInstruction *string `json:"rerank_instruction"`
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, volcengineRerankPath, r.URL.Path)
// The access key identifies the caller in the signature; the secret
// signs it and must never travel.
assert.Contains(t, r.Header.Get("Authorization"), "AKLT-test")
assert.NotContains(t, r.Header.Get("Authorization"), "secret-test")
require.NoError(t, json.NewDecoder(r.Body).Decode(&request))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"code":0,"message":"success","data":{"scores":[0.91,0.27]}}`))
}))
defer server.Close()
client, err := newVolcengineClient(
&RerankerConfig{APIKey: "AKLT-test", AppSecret: "secret-test"},
&modelruntime.Resolved{BaseURL: server.URL, RemoteModel: "doubao-seed-rerank"},
)
require.NoError(t, err)
got, err := client.Rerank(context.Background(), "保留对话数据吗", []string{"会保留", "不会保留"})
require.NoError(t, err)
require.Len(t, got, 2)
assert.Equal(t, 0, got[0].Index)
assert.Equal(t, "会保留", got[0].Text)
assert.InDelta(t, 0.91, got[0].Score, 1e-4)
assert.Equal(t, 1, got[1].Index)
assert.InDelta(t, 0.27, got[1].Score, 1e-4)
require.NotNil(t, request.RerankModel)
assert.Equal(t, "doubao-seed-rerank", *request.RerankModel)
require.Len(t, request.Datas, 2)
assert.Equal(t, "保留对话数据吗", request.Datas[0].Query)
require.NotNil(t, request.Datas[0].Content)
assert.Equal(t, "会保留", *request.Datas[0].Content)
require.NotNil(t, request.RerankInstruction)
// The console's default, verbatim, so results match what the console shows.
assert.Equal(t, volcengineRerankDefaultInstruction, *request.RerankInstruction)
assert.Equal(t, "Whether the document answers the query or matches the content retrieval intent",
*request.RerankInstruction)
}
func TestVolcengineClientSurfacesAnInBodyErrorCode(t *testing.T) {
withRerankSSRFWhitelist(t, "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":1000030,"message":"quota exceeded","data":{}}`))
}))
defer server.Close()
client, err := newVolcengineClient(
&RerankerConfig{APIKey: "AKLT-test", AppSecret: "secret-test"},
&modelruntime.Resolved{BaseURL: server.URL, RemoteModel: "doubao-seed-rerank"},
)
require.NoError(t, err)
_, err = client.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "quota exceeded")
}
// A score list that does not line up with the documents cannot be mapped back
// onto them, so it is an error rather than a partially filled result.
func TestVolcengineClientRejectsAScoreCountMismatch(t *testing.T) {
withRerankSSRFWhitelist(t, "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":0,"data":{"scores":[0.5]}}`))
}))
defer server.Close()
client, err := newVolcengineClient(
&RerankerConfig{APIKey: "AKLT-test", AppSecret: "secret-test"},
&modelruntime.Resolved{BaseURL: server.URL, RemoteModel: "doubao-seed-rerank"},
)
require.NoError(t, err)
_, err = client.Rerank(context.Background(), "q", []string{"d0", "d1"})
require.Error(t, err)
assert.Contains(t, err.Error(), "score count mismatch")
}
func TestVolcengineClientRequiresAKAndSK(t *testing.T) {
for _, cfg := range []*RerankerConfig{
{AppSecret: "sk"},
{APIKey: "ak"},
} {
_, err := newVolcengineClient(cfg, &modelruntime.Resolved{BaseURL: "https://example.invalid"})
require.Error(t, err)
assert.Contains(t, err.Error(), "access key and secret key are required")
}
}
func TestLKEAPClientRequiresCredentials(t *testing.T) {
for _, cfg := range []*RerankerConfig{
{AppSecret: "sk"},
{APIKey: "id"},
} {
_, err := newLKEAPClient(cfg, &modelruntime.Resolved{})
require.Error(t, err)
assert.Contains(t, err.Error(), "secret_id and secret_key are required")
}
}
// The secret key has always been accepted from extra_config as well, because
// the model editor stores it there for this vendor.
func TestLKEAPClientTakesTheSecretKeyFromExtraConfig(t *testing.T) {
client, err := newLKEAPClient(
&RerankerConfig{APIKey: "AKIDxxx", ExtraConfig: map[string]string{"secret_key": "sk"}},
&modelruntime.Resolved{RemoteModel: "lke-reranker-base"},
)
require.NoError(t, err)
require.NotNil(t, client)
}
func TestLKEAPClientFallsBackToTheDefaultModel(t *testing.T) {
upstream := newUpstream(t)
client, err := newLKEAPClient(
&RerankerConfig{APIKey: "AKIDxxx", AppSecret: "sk"},
&modelruntime.Resolved{},
)
require.NoError(t, err)
_, err = client.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
require.Len(t, upstream.requests, 1)
assert.Equal(t, LKEAPDefaultRerankModel, upstream.requests[0].body["Model"])
}
+46
View File
@@ -0,0 +1,46 @@
package rerank
import (
"fmt"
"net/http"
"time"
secutils "academy/internal/utils"
)
func validateRerankBaseURL(baseURL string) error {
if baseURL == "" {
return nil
}
if err := secutils.ValidateURLForSSRF(baseURL); err != nil {
return fmt.Errorf("base URL SSRF check failed: %w", err)
}
return nil
}
// sharedRerankHTTPTransport keeps a single SSRF-safe connection pool for all
// rerank clients. Rerankers are recreated on every GetRerankModel call, but
// their outbound connections can be safely reused, so the transport (and its
// keep-alive pool) is built once at package load.
var sharedRerankHTTPTransport = secutils.NewSSRFSafeTransport(
secutils.DefaultSSRFSafeHTTPClientConfig(),
)
// defaultRerankRequestTimeout caps one rerank request when the catalog sets
// no timeout. Chat and agent contexts carry no deadline of their own, so a
// stalled self-hosted rerank server used to hold the turn open until the
// client disconnected. A failed call degrades to retrieval order.
const defaultRerankRequestTimeout = 60 * time.Second
// newRerankHTTPClient returns an HTTP client with connection-level SSRF
// protection and redirect validation. All clients share
// sharedRerankHTTPTransport so keep-alive connections are pooled globally,
// while each keeps its own timeout.
func newRerankHTTPClient(timeout time.Duration) *http.Client {
if timeout <= 0 {
timeout = defaultRerankRequestTimeout
}
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
cfg.Timeout = timeout
return secutils.NewSSRFSafeHTTPClientWithTransport(cfg, sharedRerankHTTPTransport)
}
@@ -0,0 +1,52 @@
package rerank
import (
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
secutils "academy/internal/utils"
)
func withRerankSSRFWhitelist(t *testing.T, raw string) {
t.Helper()
t.Setenv("SSRF_WHITELIST", raw)
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestRerankerRejectsInternalBaseURL(t *testing.T) {
withRerankSSRFWhitelist(t, "")
_, err := NewReranker(&RerankerConfig{
BaseURL: "http://169.254.169.254/latest/meta-data/",
ModelName: "rerank-test",
})
if err == nil {
t.Fatalf("NewReranker returned nil error for blocked internal BaseURL")
}
}
func TestRerankerBlocksRedirectToInternalURL(t *testing.T) {
withRerankSSRFWhitelist(t, "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer server.Close()
reranker, err := NewReranker(&RerankerConfig{
BaseURL: server.URL,
ModelName: "rerank-test",
APIKey: "sk-test",
})
if err != nil {
t.Fatalf("NewReranker: %v", err)
}
_, err = reranker.Rerank(t.Context(), "query", []string{"doc"})
if !stderrors.Is(err, secutils.ErrSSRFRedirectBlocked) {
t.Fatalf("Rerank error = %v, want ErrSSRFRedirectBlocked", err)
}
}
@@ -0,0 +1,36 @@
package rerank
import (
"strings"
"time"
"academy/internal/models/api"
"academy/internal/models/api/volcengineknowledge"
modelruntime "academy/internal/models/runtime"
)
const (
volcengineRerankDefaultModel = volcengineknowledge.DefaultModel
volcengineRerankDefaultRegion = volcengineknowledge.DefaultRegion
volcengineRerankDefaultInstruction = volcengineknowledge.DefaultInstruction
)
func newVolcengineClient(config *RerankerConfig, resolved *modelruntime.Resolved) (api.Reranker, error) {
secret := strings.TrimSpace(config.AppSecret)
if secret == "" {
secret = config.ExtraConfig["secret_key"]
}
return volcengineknowledge.New(
volcengineknowledge.Config{
AccessKey: config.APIKey,
SecretKey: secret,
BaseURL: resolved.BaseURL,
Model: resolved.RemoteModel,
Region: config.ExtraConfig["region"],
Instruction: config.ExtraConfig["instruction"],
Client: newRerankHTTPClient(
30 * time.Second,
),
},
)
}
+444
View File
@@ -0,0 +1,444 @@
package rerank
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"testing"
"unicode/utf8"
"academy/internal/models"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recorded is one request as the upstream saw it.
type recorded struct {
path string
header http.Header
body map[string]any
}
// upstream is a stand-in for every rerank vendor at once. It answers in
// whichever shape the request belongs to, scoring each document by its
// length so that the expected ranking is known: longer is more relevant.
// Probability vendors get length/100, logit vendors length-3, which puts the
// shortest documents below zero the way a real NIM reply does.
type upstream struct {
mu sync.Mutex
requests []recorded
url string
}
func newUpstream(t *testing.T) *upstream {
t.Helper()
withRerankSSRFWhitelist(t, "127.0.0.1")
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.Header.Clone(), body})
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(answer(r, body)))
}))
t.Cleanup(server.Close)
u.url = server.URL
// LKEAP's SDK always calls the public API host; point it here.
savedEndpoint, savedScheme := lkeapEndpoint, lkeapScheme
lkeapEndpoint, lkeapScheme = strings.TrimPrefix(server.URL, "http://"), "HTTP"
t.Cleanup(func() { lkeapEndpoint, lkeapScheme = savedEndpoint, savedScheme })
return u
}
// texts pulls the documents out of whichever shape carried them.
func texts(v any) []string {
var out []string
for _, item := range v.([]any) {
switch d := item.(type) {
case string:
out = append(out, d)
case map[string]any: // NIM passages, Volcengine datas
if image, ok := d["image"].(string); ok {
// An image scores by its decoded size, so a test can tell
// which image a score belongs to.
_, encoded, _ := strings.Cut(image, ";base64,")
raw, _ := base64.StdEncoding.DecodeString(encoded)
out = append(out, strings.Repeat("i", len(raw)))
} else if text, ok := d["text"].(string); ok {
out = append(out, text)
} else {
out = append(out, d["content"].(string))
}
}
}
return out
}
func probability(doc string) float64 { return float64(utf8.RuneCountInString(doc)) / 100 }
func logit(doc string) float64 { return float64(utf8.RuneCountInString(doc)) - 3 }
// answer replies in the protocol the request belongs to. The indexed shapes
// come back in reverse order so that placement by index is exercised.
func answer(r *http.Request, body map[string]any) string {
var parts []string
switch {
case r.Header.Get("X-TC-Action") == "RunRerank": // LKEAP: scores in input order
for _, doc := range texts(body["Docs"]) {
parts = append(parts, fmt.Sprint(probability(doc)))
}
return `{"Response":{"ScoreList":[` + strings.Join(parts, ",") + `],"RequestId":"r"}}`
case strings.HasSuffix(r.URL.Path, "/api/knowledge/service/rerank"): // Volcengine
for _, doc := range texts(body["datas"]) {
parts = append(parts, fmt.Sprint(probability(doc)))
}
return `{"code":0,"message":"success","data":{"scores":[` + strings.Join(parts, ",") + `]}}`
case strings.HasSuffix(r.URL.Path, "/reranking"): // NIM
docs := texts(body["passages"])
for i := len(docs) - 1; i >= 0; i-- {
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-- {
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
if r.Header.Get("X-Test-Scale") == "logit" {
score = logit
}
for i := len(docs) - 1; i >= 0; i-- {
parts = append(parts, fmt.Sprintf(`{"index":%d,"relevance_score":%v}`, i, score(docs[i])))
}
return `{"results":[` + strings.Join(parts, ",") + `]}`
}
}
func documents(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = strings.Repeat("d", i%7+1) + fmt.Sprint(i)
}
return out
}
func anyStrings(in []string) []any {
out := make([]any, len(in))
for i, s := range in {
out[i] = s
}
return out
}
// TestRerankWireFormatPerVendor pins, for every rerank vendor in the catalog,
// the request the factory actually sends — URL, credential and the complete
// body — and that the answer comes back ranked on the 0..1 scale the
// retrieval threshold assumes. Each expectation traces to the vendor's
// reference as cited in its vendor.go.
func TestRerankWireFormatPerVendor(t *testing.T) {
const query = "q"
three := []string{"a", "bbb", "cc"}
cohere := func(model string, docs []string, extra map[string]any) map[string]any {
body := map[string]any{"model": model, "query": query, "documents": anyStrings(docs)}
for k, v := range extra {
body[k] = v
}
return body
}
const volcInstruction = "Whether the document answers the query or matches the content retrieval intent"
cases := []struct {
name string
provider string
model string
base string // appended to the upstream URL
extra map[string]string
appID string
appSecret string
docs []string
logitScale bool // the protocol answers raw logits (NIM)
// cohereLogs marks a Cohere-shape vendor that declares a logit scale
// (GPUStack). The shape cannot tell the stub which scale to answer
// in, so the case asks for logits through a test-only header.
cohereLogs bool
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
// the first to arrive.
wantBody map[string]any
}{
{
name: "jina echoes documents", provider: "jina", model: "jina-reranker-v3", base: "/v1",
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"},
wantBody: cohere("rerank", three, map[string]any{"return_documents": true}),
},
{
name: "zhipu splits at 128 documents", provider: "zhipu", model: "rerank", base: "/api/paas/v4/rerank",
docs: documents(129), wantRequests: 2,
wantPath: "/api/paas/v4/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("rerank", documents(128), map[string]any{"return_documents": true}),
},
{
name: "siliconflow", provider: "siliconflow", model: "BAAI/bge-reranker-v2-m3", base: "/v1",
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,
wantPath: "/v2/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("bce-reranker-base", documents(64), nil),
},
{
name: "gpustack sends the row's truncation budget and answers logits", provider: "gpustack",
model: "bge-reranker-v2-m3", base: "/v1",
extra: map[string]string{models.ExtraTruncatePromptTokens: "256"},
cohereLogs: true,
wantPath: "/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("bge-reranker-v2-m3", three, map[string]any{"truncate_prompt_tokens": float64(256)}),
},
{
name: "generic", provider: "generic", model: "bge-reranker-v2-m3", base: "/v1",
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"},
wantBody: cohere("baai/bge-reranker-v2-m3", three, nil),
},
{
name: "openrouter", provider: "openrouter", model: "cohere/rerank-v3.5", base: "/api/v1",
wantPath: "/api/v1/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("cohere/rerank-v3.5", three, nil),
},
{
name: "litellm on the proxy root", provider: "litellm", model: "cohere/rerank-v3.5",
wantPath: "/rerank", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: cohere("cohere/rerank-v3.5", three, nil),
},
{
name: "academycloud signs its own path", provider: "academycloud", model: "rerank",
appID: "app", appSecret: "s",
wantPath: "/api/v1/rerank", wantAuth: [2]string{"X-APPID", "app"},
wantBody: cohere("rerank", three, nil),
},
{
name: "aliyun wraps input and parameters", provider: "aliyun", model: "gte-rerank-v2",
base: "/api/v1/services/rerank/text-rerank/text-rerank",
wantPath: "/api/v1/services/rerank/text-rerank/text-rerank",
wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: map[string]any{
"model": "gte-rerank-v2",
"input": map[string]any{"query": query, "documents": anyStrings(three)},
"parameters": map[string]any{"return_documents": true, "top_n": float64(3)},
},
},
{
name: "nvidia sends passages and answers logits", provider: "nvidia",
model: "nvidia/nv-rerankqa-mistral-4b-v3", base: "/v1/retrieval/nvidia/reranking", logitScale: true,
wantPath: "/v1/retrieval/nvidia/reranking", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: map[string]any{
"model": "nvidia/nv-rerankqa-mistral-4b-v3",
"query": map[string]any{"text": query},
"passages": []any{
map[string]any{"text": "a"}, map[string]any{"text": "bbb"}, map[string]any{"text": "cc"},
},
"truncate": "END",
},
},
{
name: "volcengine through the Knowledge Service SDK", provider: "volcengine", model: "doubao-seed-rerank",
appSecret: "secret-test",
wantPath: "/api/knowledge/service/rerank", wantAuth: [2]string{"Authorization", "Credential=k/"},
wantBody: map[string]any{
"rerank_model": "doubao-seed-rerank",
"rerank_instruction": volcInstruction,
"datas": []any{
map[string]any{"query": query, "content": "a"},
map[string]any{"query": query, "content": "bbb"},
map[string]any{"query": query, "content": "cc"},
},
},
},
{
name: "lkeap through the Tencent Cloud SDK", provider: "lkeap", model: "lke-reranker-base",
appSecret: "secret-test",
wantPath: "/", wantAuth: [2]string{"Authorization", "Credential=k/"},
wantBody: map[string]any{"Query": query, "Docs": anyStrings(three), "Model": "lke-reranker-base"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
docs := tc.docs
if docs == nil {
docs = three
}
headers := map[string]string{}
if tc.cohereLogs {
headers["X-Test-Scale"] = "logit"
}
reranker, err := NewReranker(&RerankerConfig{
Source: types.ModelSourceRemote, Provider: tc.provider, ModelName: tc.model,
BaseURL: up.url + tc.base, APIKey: "k", ExtraConfig: tc.extra,
AppID: tc.appID, AppSecret: tc.appSecret, CustomHeaders: headers,
})
require.NoError(t, err)
got, err := reranker.Rerank(context.Background(), query, docs)
require.NoError(t, err)
wantRequests := tc.wantRequests
if wantRequests == 0 {
wantRequests = 1
}
require.Len(t, up.requests, wantRequests)
bodies := make([]map[string]any, 0, len(up.requests))
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")
}
bodies = append(bodies, req.body)
}
assert.Contains(t, bodies, tc.wantBody)
// Every document comes back once, ranked by the upstream's score,
// and on the probability scale.
require.Len(t, got, len(docs))
want := append([]string(nil), docs...)
sort.SliceStable(want, func(i, j int) bool {
return utf8.RuneCountInString(want[i]) > utf8.RuneCountInString(want[j])
})
for i, r := range got {
assert.Equal(t, docs[r.Index], r.Document.Text, "result %d carries the wrong text", i)
assert.Equal(t, utf8.RuneCountInString(want[i]), utf8.RuneCountInString(r.Document.Text),
"result %d is out of rank", i)
assert.GreaterOrEqual(t, r.RelevanceScore, 0.0)
assert.LessOrEqual(t, r.RelevanceScore, 1.0)
}
if tc.logitScale || tc.cohereLogs {
// length 1 is a logit of -2: well below one half once converted.
last := got[len(got)-1]
assert.InDelta(t, 1/(1+math.Exp(2)), last.RelevanceScore, 1e-9,
"a logit must be converted, not passed through")
}
})
}
}
// OpenAI has no rerank API, so the vendor does not offer the type.
func TestOpenAIDoesNotOfferRerank(t *testing.T) {
v, ok := modelruntime.Get("openai")
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"))
}
}