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

+132
View File
@@ -0,0 +1,132 @@
// Package pineconerank implements Pinecone Inference's standalone rerank API.
// https://docs.pinecone.io/guides/search/rerank-results
package pineconerank
import (
"context"
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config holds the Pinecone endpoint and rerank request settings.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client calls Pinecone's standalone rerank API.
type Client struct{ cfg Config }
// New creates a Pinecone rerank client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = "/rerank"
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type document struct {
Text string `json:"text"`
}
type request struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []document `json:"documents"`
TopN int `json:"top_n"`
RankFields []string `json:"rank_fields"`
ReturnDocuments bool `json:"return_documents"`
Parameters map[string]any `json:"parameters,omitempty"`
}
// BuildRequestBody constructs the native Pinecone body. Asking for every
// candidate and suppressing echoed documents preserves Academy's index mapping
// while avoiding unnecessary response bytes.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
docs := make([]document, len(documents))
for i, text := range documents {
docs[i] = document{Text: text}
}
body := request{
Model: c.cfg.Endpoint.Model, Query: query, Documents: docs,
TopN: len(documents), RankFields: []string{"text"},
}
if c.cfg.Settings.Truncate != "" {
body.Parameters = map[string]any{"truncate": c.cfg.Settings.Truncate}
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for key, value := range c.cfg.Settings.ExtraBody {
if _, exists := out[key]; !exists {
out[key] = value
}
}
return out, nil
}
type response struct {
Data *[]result `json:"data"`
}
type result struct {
Index *int `json:"index"`
Score *float64 `json:"score"`
}
// Rerank returns scores for the supplied documents in Pinecone's ranked order.
func (c *Client) Rerank(
ctx context.Context, query string, documents []string,
) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
var decoded response
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), body, &decoded); err != nil {
return nil, err
}
if decoded.Data == nil {
return nil, fmt.Errorf("pinecone rerank response has no data array")
}
if len(*decoded.Data) != len(documents) {
return nil, fmt.Errorf(
"pinecone rerank returned %d scores for %d documents", len(*decoded.Data), len(documents),
)
}
out := make([]api.RerankResult, 0, len(*decoded.Data))
seen := make([]bool, len(documents))
for _, item := range *decoded.Data {
if item.Index == nil || item.Score == nil {
return nil, fmt.Errorf("pinecone rerank result is missing index or score")
}
if *item.Index < 0 || *item.Index >= len(documents) {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", *item.Index, len(documents))
}
if seen[*item.Index] {
return nil, fmt.Errorf("pinecone rerank returned duplicate index %d", *item.Index)
}
seen[*item.Index] = true
out = append(out, api.RerankResult{
Index: *item.Index, Score: *item.Score, Text: documents[*item.Index],
})
}
return out, nil
}
@@ -0,0 +1,143 @@
package pineconerank
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The four result indexes and scores are from Pinecone's current standalone
// rerank guide, "Rerank results on the default field":
// https://docs.pinecone.io/guides/search/rerank-results
const guideResponse = `{
"data": [
{"index": 2, "score": 0.48357219, "document": {"id": "vec3", "text": "Apple Inc."}},
{"index": 0, "score": 0.048405956, "document": {"id": "vec1", "text": "Apple fruit"}},
{"index": 3, "score": 0.007846239, "document": {"id": "vec4", "text": "Apple saying"}},
{"index": 1, "score": 0.0006563728, "document": {"id": "vec2", "text": "Apple snack"}}
],
"model": "bge-reranker-v2-m3",
"usage": {"rerank_units": 1}
}`
func newClient(t *testing.T, base string, settings api.RerankSettings) *Client {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
return New(Config{
Endpoint: api.Endpoint{BaseURL: base, Model: "bge-reranker-v2-m3", Auth: api.HeaderAuth("Api-Key", "key")},
Settings: settings,
})
}
func TestRequestUsesThePineconeShape(t *testing.T) {
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{Truncate: "END"})
body, err := c.BuildRequestBody("Apple", []string{"fruit", "company"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "bge-reranker-v2-m3", "query": "Apple",
"documents": []any{map[string]any{"text": "fruit"}, map[string]any{"text": "company"}},
"top_n": float64(2), "rank_fields": []any{"text"}, "return_documents": false,
"parameters": map[string]any{"truncate": "END"},
}, body)
}
func TestDoesNotSendAnUnspecifiedModelParameter(t *testing.T) {
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.NotContains(t, body, "parameters")
}
func TestDecodesOfficialIndexesAndKeepsOriginalTexts(t *testing.T) {
var gotPath, gotKey string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath, gotKey = r.URL.Path, r.Header.Get("Api-Key")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(guideResponse))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
docs := []string{"fruit", "snack", "company", "saying"}
got, err := c.Rerank(context.Background(), "Apple", docs)
require.NoError(t, err)
assert.Equal(t, "/rerank", gotPath)
assert.Equal(t, "key", gotKey)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.48357219, Text: "company"},
{Index: 0, Score: 0.048405956, Text: "fruit"},
{Index: 3, Score: 0.007846239, Text: "saying"},
{Index: 1, Score: 0.0006563728, Text: "snack"},
}, got)
}
func TestFullEndpointIsNotDoubled(t *testing.T) {
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(`{"data":[{"index":0,"score":0.5}]}`))
}))
defer server.Close()
c := newClient(t, server.URL+"/rerank", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/rerank", path)
}
func TestMapsDuplicateTextsWithoutEchoedDocuments(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"data":[{"index":2,"score":0.8},{"index":0,"score":0.6},{"index":1,"score":0.1}]}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"same", "other", "same"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.8, Text: "same"},
{Index: 0, Score: 0.6, Text: "same"},
{Index: 1, Score: 0.1, Text: "other"},
}, got)
}
func TestRejectsMalformedResults(t *testing.T) {
for _, tc := range []struct{ name, reply, errorText string }{
{"missing data", `{}`, "no data"},
{"short reply", `{"data":[]}`, "returned 0 scores"},
{"missing index", `{"data":[{"score":0.5}]}`, "missing index"},
{"missing score", `{"data":[{"index":0}]}`, "missing index or score"},
{"out of range", `{"data":[{"index":9,"score":0.5}]}`, "out of range"},
{"duplicate index", `{"data":[{"index":0,"score":0.5},{"index":0,"score":0.4}]}`, "duplicate index"},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.reply))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
docs := []string{"a"}
if tc.name == "duplicate index" {
docs = []string{"a", "b"}
}
_, err := c.Rerank(context.Background(), "q", docs)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.errorText)
})
}
}
func TestSurfacesVendorError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid model"}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid model")
}