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

+244
View File
@@ -0,0 +1,244 @@
// Package cohererank implements the rerank shape Cohere defined and almost
// every other vendor copied: POST {base}/rerank with {model, query,
// documents} answering {results: [{index, relevance_score, document}]}.
// A bare array of the same result objects is accepted too: self-hosted
// runtimes such as SGLang return that shape instead of the envelope.
//
// Jina, Zhipu, SiliconFlow, Qianfan, GPUStack, Academy Cloud and any
// OpenAI-compatible gateway that serves rerank all speak it. Their
// differences — which optional fields are accepted, where the endpoint sits,
// what the documented ceilings are — arrive as api.RerankSettings; this
// package contains no vendor names.
package cohererank
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client talks the Cohere rerank shape to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const defaultPath = "/rerank"
// url resolves the endpoint. A vendor whose default base URL already names
// the full rerank endpoint — and an operator who pasted one — must not have
// the path appended twice.
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = defaultPath
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type request struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []string `json:"documents"`
TopN int `json:"top_n,omitempty"`
// TruncatePromptTokens is a vLLM extension, not part of any vendor's
// documented schema. It is sent only when the operator opted in, because
// a gateway that does not implement it rejects the unknown field.
TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`
ReturnDocuments *bool `json:"return_documents,omitempty"`
}
type response struct {
Results []result `json:"results"`
}
type result struct {
Index int `json:"index"`
RelevanceScore *float64 `json:"relevance_score"`
Score *float64 `json:"score"`
Document document `json:"document"`
}
// document is the echoed text, which vendors spell either as a bare string
// or as an object with a text field.
type document struct {
Text string
}
func (d *document) UnmarshalJSON(data []byte) error {
var text string
if err := json.Unmarshal(data, &text); err == nil {
d.Text = text
return nil
}
var obj struct {
Text string `json:"text"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return fmt.Errorf("decode document: %w", err)
}
d.Text = obj.Text
return nil
}
// BuildRequestBody is the golden-test entry point: it returns the exact JSON
// object that would be sent.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
body := request{
Model: c.cfg.Endpoint.Model,
Query: query,
Documents: documents,
}
if c.cfg.Settings.AcceptsTruncatePromptTokens {
body.TruncatePromptTokens = c.cfg.Settings.TruncatePromptTokens
}
if c.cfg.Settings.SendTopN {
body.TopN = len(documents)
}
if c.cfg.Settings.SendReturnDocs {
enabled := true
body.ReturnDocuments = &enabled
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
return out, nil
}
// BuildImageRequestBody is the golden-test entry point for image documents.
// The shape has no standard image document; a vendor that extends it names
// the key of the object that carries one. Jina's reranker reference gives
// {"image": URL or base64} documents; it shows no base64 example, so the
// data URI its embeddings reference documents is used (unverified for
// rerank). The request carries images only, so text documents never change
// shape.
func (c *Client) BuildImageRequestBody(query string, images []api.EmbedImage) (map[string]any, error) {
documents := make([]any, len(images))
for i, img := range images {
documents[i] = map[string]any{c.cfg.Settings.ImageField: img.DataURI()}
}
body, err := c.BuildRequestBody(query, nil)
if err != nil {
return nil, err
}
body["documents"] = documents
if c.cfg.Settings.SendTopN {
body["top_n"] = len(images)
}
// Results are matched by index; an echoed image document would carry its
// whole base64 payload back for nothing.
if _, asked := body["return_documents"]; asked {
body["return_documents"] = false
}
return body, nil
}
// AcceptsImages reports whether the vendor names an image field; without one
// a Cohere-shaped endpoint takes text documents only.
func (c *Client) AcceptsImages() bool { return c.cfg.Settings.ImageField != "" }
// Rerank scores documents against the query, in the order they were given.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
return c.post(ctx, body, len(documents))
}
// RerankImages scores image documents against the query; indices refer to
// images.
func (c *Client) RerankImages(ctx context.Context, query string, images []api.EmbedImage) ([]api.RerankResult, error) {
if !c.AcceptsImages() {
return nil, fmt.Errorf("this rerank endpoint declares no image documents")
}
body, err := c.BuildImageRequestBody(query, images)
if err != nil {
return nil, err
}
return c.post(ctx, body, len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, count int) ([]api.RerankResult, error) {
// Decode into raw JSON first: some Cohere-shaped runtimes (SGLang, for
// one) answer the same request with a bare array instead of the
// {"results": [...]} envelope. Both shapes mean the same thing, so the
// envelope is not part of the contract callers may rely on.
var raw json.RawMessage
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), body, &raw); err != nil {
return nil, err
}
results, err := decodeResults(raw)
if err != nil {
return nil, err
}
out := make([]api.RerankResult, 0, len(results))
for _, item := range results {
if item.Index < 0 || item.Index >= count {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", item.Index, count)
}
out = append(out, api.RerankResult{
Index: item.Index,
Score: firstNonNil(item.RelevanceScore, item.Score),
Text: item.Document.Text,
})
}
return out, nil
}
// decodeResults accepts both documented envelopes: the Cohere object
// {"results": [...]} and the bare array some self-hosted runtimes return.
func decodeResults(raw []byte) ([]result, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) > 0 && trimmed[0] == '[' {
var results []result
if err := json.Unmarshal(trimmed, &results); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return results, nil
}
var decoded response
if err := json.Unmarshal(trimmed, &decoded); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return decoded.Results, nil
}
// firstNonNil picks relevance_score, falling back to score: the field is
// spelled both ways across vendors that otherwise share this shape.
func firstNonNil(values ...*float64) float64 {
for _, v := range values {
if v != nil {
return *v
}
}
return 0
}
@@ -0,0 +1,275 @@
package cohererank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// zhipuResponse is the documented response of Zhipu's rerank endpoint, whose
// result objects carry document / index / relevance_score and whose envelope
// adds id, request_id, created and usage:
// https://docs.bigmodel.cn/api-reference/模型-api/文本重排序
const zhipuResponse = `{
"id": "8305283656248111323",
"request_id": "8305283656248111323",
"created": 1769040000,
"results": [
{"index": 1, "relevance_score": 0.9819, "document": "上海气候"},
{"index": 0, "relevance_score": 0.0021, "document": "北京美食"}
],
"usage": {"prompt_tokens": 24, "total_tokens": 24}
}`
// jinaResponse spells the echoed document as an object instead of a string,
// which is the other shape vendors use for the same field:
// https://jina.ai/reranker/
const jinaResponse = `{
"model": "jina-reranker-v3.5",
"results": [
{"index": 0, "relevance_score": 0.95, "document": {"text": "上海气候"}},
{"index": 1, "relevance_score": 0.11, "document": {"text": "北京美食"}}
],
"usage": {"total_tokens": 32}
}`
func newClient(t *testing.T, url string, settings api.RerankSettings) *Client {
t.Helper()
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "rerank", Auth: api.BearerAuth("k")},
Settings: settings,
})
}
// 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")
path := new(string)
body := new(map[string]any)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*path = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(payload))
}))
return server, path, body
}
func TestRequestBodyCarriesOnlyWhatTheVendorDeclares(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{})
body, err := c.BuildRequestBody("上海天气", []string{"上海气候", "北京美食"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "rerank",
"query": "上海天气",
"documents": []any{"上海气候", "北京美食"},
}, body, "optional fields must be absent unless the vendor asked for them")
}
func TestRequestBodyAddsTheOptionalFieldsAVendorDeclares(t *testing.T) {
c := newClient(t, "https://example.invalid/v1",
api.RerankSettings{SendTopN: true, SendReturnDocs: true})
body, err := c.BuildRequestBody("q", []string{"a", "b", "c"})
require.NoError(t, err)
assert.Equal(t, float64(3), body["top_n"], "top_n asks for every document back")
assert.Equal(t, true, body["return_documents"])
}
func TestDecodesAStringDocument(t *testing.T) {
server, _, _ := serve(t, zhipuResponse)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "上海天气", []string{"北京美食", "上海气候"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 1, Score: 0.9819, Text: "上海气候"},
{Index: 0, Score: 0.0021, Text: "北京美食"},
}, got)
}
func TestDecodesAnObjectDocument(t *testing.T) {
server, _, _ := serve(t, jinaResponse)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "上海天气", []string{"上海气候", "北京美食"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 0, Score: 0.95, Text: "上海气候"},
{Index: 1, Score: 0.11, Text: "北京美食"},
}, got)
}
// Some gateways serving this shape spell the score `score`. The pre-catalog
// client accepted both and so does this one.
func TestDecodesTheScoreAlias(t *testing.T) {
server, _, _ := serve(t, `{"results":[{"index":0,"score":0.42}]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
require.Len(t, got, 1)
assert.InDelta(t, 0.42, got[0].Score, 1e-9)
}
// sglangBareArrayResponse is what SGLang's /v1/rerank answers to the same
// request: a bare array with score/document instead of the Cohere envelope.
// Self-hosted Qwen3-Reranker deployments are commonly served this way.
const sglangBareArrayResponse = `[
{"score": 0.0015978454940173438, "document": "doc one", "index": 0, "meta_info": null},
{"score": 0.0011695108220694027, "document": "doc two", "index": 1, "meta_info": null}
]`
func TestDecodesABareArrayResponse(t *testing.T) {
server, _, _ := serve(t, sglangBareArrayResponse)
defer server.Close()
c := newClient(t, server.URL+"/v1", api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"doc one", "doc two"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 0, Score: 0.0015978454940173438, Text: "doc one"},
{Index: 1, Score: 0.0011695108220694027, Text: "doc two"},
}, got)
}
func TestBareArrayResponseStillValidatesIndexes(t *testing.T) {
server, _, _ := serve(t, `[{"index":5,"score":0.5,"document":"d"}]`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "out of range")
}
func TestRejectsAnUnsupportedResponseEnvelope(t *testing.T) {
server, _, _ := serve(t, `"not a rerank response"`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "decode response")
}
func TestAppendsTheRerankPathToABareBaseURL(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL+"/v1", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/v1/rerank", *path)
}
// Zhipu's default base URL already ends in /rerank, and operators paste full
// endpoints too. Appending the path again would 404.
func TestDoesNotDoubleTheRerankPath(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL+"/api/paas/v4/rerank", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/api/paas/v4/rerank", *path)
}
// Academy Cloud serves the same shape on its own path.
func TestHonoursAVendorDeclaredPath(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{Path: "/api/v1/rerank"})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/api/v1/rerank", *path)
}
func TestRejectsAnOutOfRangeIndex(t *testing.T) {
server, _, _ := serve(t, `{"results":[{"index":9,"relevance_score":0.5}]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "out of range")
}
func TestSurfacesTheVendorErrorBody(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":{"message":"documents exceeds the limit"}}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "documents exceeds the limit")
}
// truncate_prompt_tokens is a vLLM extension that appears in no managed
// vendor's documented schema. It is sent only where the vendor declared it
// and the operator opted in, and never by default — sending it unasked is how
// an undocumented field ends up on every request to every gateway.
func TestTruncatePromptTokensIsAbsentByDefault(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.NotContains(t, body, "truncate_prompt_tokens")
}
func TestTruncatePromptTokensIsSentWhenTheRowOptedIn(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{
AcceptsTruncatePromptTokens: true, TruncatePromptTokens: 512,
})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, float64(512), body["truncate_prompt_tokens"])
}