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

+97
View File
@@ -0,0 +1,97 @@
// Package teirank implements the native Text Embeddings Inference rerank
// protocol. It sends {query, texts} to /rerank and reads a bare array of
// {index, score}; the deployed model is selected by the TEI server, not by
// a model field in each request.
package teirank
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config supplies the endpoint and wire-level settings for a TEI reranker.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client sends rerank requests to a Text Embeddings Inference server.
type Client struct{ cfg Config }
// New creates a TEI rerank client for the supplied endpoint.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = "/rerank"
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type rank struct {
Index *int `json:"index"`
Score *float64 `json:"score"`
Text string `json:"text"`
}
// BuildRequestBody returns the native TEI request. raw_scores is explicit:
// false makes a single-class reranker's logits comparable with Academy's
// 0..1 relevance threshold. The model name is configured when TEI starts.
//
// Settings.ExtraBody is merged in but cannot replace query, texts or
// raw_scores. truncate defaults to true and may be overridden there: TEI
// before 1.9 starts with --auto-truncate=false and rejects the whole batch
// when one passage exceeds the model's input length.
func (c *Client) BuildRequestBody(query string, documents []string) map[string]any {
out := map[string]any{
"query": query,
"texts": documents,
"raw_scores": false,
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
if _, set := out["truncate"]; !set {
out["truncate"] = true
}
return out
}
// Rerank scores documents with TEI and preserves their original indexes.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
var decoded []rank
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), c.BuildRequestBody(query, documents), &decoded); err != nil {
return nil, err
}
if len(decoded) != len(documents) {
return nil, fmt.Errorf("TEI returned %d ranks for %d documents", len(decoded), len(documents))
}
out := make([]api.RerankResult, 0, len(decoded))
seen := make([]bool, len(documents))
for _, item := range decoded {
if item.Index == nil || *item.Index < 0 || *item.Index >= len(documents) {
return nil, fmt.Errorf("TEI rerank index is missing or out of range for %d documents", len(documents))
}
if seen[*item.Index] {
return nil, fmt.Errorf("TEI returned duplicate rerank index %d", *item.Index)
}
if item.Score == nil {
return nil, fmt.Errorf("TEI rerank score is missing for index %d", *item.Index)
}
seen[*item.Index] = true
out = append(out, api.RerankResult{Index: *item.Index, Score: *item.Score, Text: item.Text})
}
return out, nil
}
+117
View File
@@ -0,0 +1,117 @@
package teirank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The TEI OpenAPI defines RerankResponse as a bare array of Rank, and gives
// these exact example values for Rank's index, score and optional text:
// https://github.com/huggingface/text-embeddings-inference/blob/main/docs/openapi.json#L1628-L1704
const openAPIRankExample = `[{"index":0,"score":1.0,"text":"Deep Learning is ..."}]`
func TestOpenAPIRankExampleAndNativeRequest(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path, authorization string
var body map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path, authorization = r.URL.Path, r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(openAPIRankExample))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{
BaseURL: server.URL, Model: "BAAI/bge-reranker-large", Auth: api.BearerAuth(""),
}})
got, err := c.Rerank(context.Background(), "What is Deep Learning?", []string{"Deep Learning is ..."})
require.NoError(t, err)
assert.Equal(t, "/rerank", path)
assert.Empty(t, authorization, "TEI works without an API key by default")
assert.Equal(t, map[string]any{
"query": "What is Deep Learning?", "texts": []any{"Deep Learning is ..."},
"raw_scores": false, "truncate": true,
}, body)
assert.NotContains(t, body, "model", "TEI chooses the model at server startup")
assert.Equal(t, []api.RerankResult{{Index: 0, Score: 1.0, Text: "Deep Learning is ..."}}, got)
}
func TestRankIndicesAndOptionalBearer(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path, authorization string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path, authorization = r.URL.Path, r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"index":2,"score":0.91},{"index":0,"score":0.62},{"index":1,"score":0.03}]`))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL + "/rerank", Auth: api.BearerAuth("secret")}})
got, err := c.Rerank(context.Background(), "q", []string{"same", "same", "relevant"})
require.NoError(t, err)
assert.Equal(t, "/rerank", path, "a pasted full endpoint must not gain a second /rerank")
assert.Equal(t, "Bearer secret", authorization)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.91}, {Index: 0, Score: 0.62}, {Index: 1, Score: 0.03},
}, got, "the index, not echoed text, identifies duplicate candidate texts")
}
func TestRejectsMalformedRanks(t *testing.T) {
for _, tc := range []struct {
name, reply, want string
documents []string
}{
{"missing score", `[{"index":0}]`, "score is missing", []string{"d"}},
{"missing index", `[{"score":0.5}]`, "index is missing", []string{"d"}},
{"out of range", `[{"index":3,"score":0.5}]`, "out of range", []string{"d"}},
{"partial response", `[]`, "0 ranks for 1", []string{"d"}},
{"duplicate index", `[{"index":0,"score":0.5},{"index":0,"score":0.4}]`, "duplicate", []string{"a", "b"}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.reply))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}})
_, err := c.Rerank(context.Background(), "q", tc.documents)
require.ErrorContains(t, err, tc.want)
})
}
}
func TestSurfacesTEIError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"error":"Tokenization error","error_type":"tokenizer"}`))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.ErrorContains(t, err, "Tokenization error")
}
// compat.extra_body reaches TEI like every other HTTP rerank protocol, but it
// cannot replace the fields the client owns. truncate is only a default.
func TestExtraBodyMergesWithoutReplacingCoreFields(t *testing.T) {
c := New(Config{Settings: api.RerankSettings{ExtraBody: map[string]any{
"query": "x",
"texts": []string{"x"},
"raw_scores": true,
"truncate": false,
"truncation_direction": "Left",
}}})
assert.Equal(t, map[string]any{
"query": "q", "texts": []string{"d"}, "raw_scores": false,
"truncate": false, "truncation_direction": "Left",
}, c.BuildRequestBody("q", []string{"d"}))
}