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,119 @@
// Package dashscopeembeddings implements Alibaba Model Studio's native
// multimodal embedding shape: input.contents, parameters.dimension, and
// results under output.embeddings.
//
// Only the multimodal models use it. DashScope's text embeddings are served
// on the OpenAI-compatible endpoint, which is why the vendor's default
// protocol is the OpenAI one and the multimodal entries override it.
//
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
package dashscopeembeddings
import (
"context"
"fmt"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
Dimensions int
Retry api.RetryPolicy
}
// Client talks DashScope's native multimodal embedding to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type response struct {
Output struct {
Embeddings []struct {
// The position field is `index`. DashScope's *text* embedding API
// one page over calls it `text_index`, and decoding that name
// here yields 0 for every element, collapsing a whole batch onto
// slot 0 (Tencent/WeKnora#3484).
Index int `json:"index"`
Embedding []float32 `json:"embedding"`
Type string `json:"type"`
} `json:"embeddings"`
} `json:"output"`
Code string `json:"code"`
Message string `json:"message"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(texts))
for _, text := range texts {
contents = append(contents, map[string]any{"text": text})
}
return c.body(contents)
}
// BuildImageRequestBody is the golden-test entry point for images. Each
// content is {"image": URL or "data:image/{format};base64,{data}"}.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(images))
for _, img := range images {
contents = append(contents, map[string]any{"image": img.DataURI()})
}
return c.body(contents)
}
func (c *Client) body(contents []any) map[string]any {
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"input": map[string]any{"contents": contents},
}
// The width lives under parameters, not at the top level, and the field
// is singular: `dimension`.
if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {
body["parameters"] = map[string]any{c.cfg.Settings.DimensionsField: c.cfg.Dimensions}
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one batch.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))
}
// AcceptsImages is always true: the image part is part of the schema.
func (c *Client) AcceptsImages() bool { return true }
// EmbedImages vectorizes one batch of images, each its own vector.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
// DashScope reports some failures in the body with a 200.
if decoded.Code != "" {
return nil, fmt.Errorf("DashScope embedding error %s: %s", decoded.Code, decoded.Message)
}
return api.PlaceEmbeddings(want, len(decoded.Output.Embeddings), func(i int) (int, []float32) {
return decoded.Output.Embeddings[i].Index, decoded.Output.Embeddings[i].Embedding
})
}
@@ -0,0 +1,90 @@
package dashscopeembeddings
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the response example from DashScope's multimodal
// embedding reference, copied verbatim so the decoder is pinned against the
// vendor's own document:
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
//
// The position field is `index`. Reading `text_index` — the name used by
// DashScope's text embedding API — put a whole batch in slot 0 (#3484).
const documentedResponse = `{
"output": {
"embeddings": [
{"index": 0, "embedding": [-0.026611328125, -0.016571044921875], "type": "text"},
{"index": 1, "embedding": [0.051544189453125, 0.007717132568359375], "type": "text"}
]
},
"usage": {"input_tokens": 10, "total_tokens": 10},
"request_id": "1fff9502-a6c5-9472-9ee1-73930fdd04c5"
}`
const endpoint = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
func newClient(url string, dims int) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "tongyi-embedding-vision-plus", Auth: api.BearerAuth("k")},
Settings: api.EmbeddingsSettings{DimensionsField: "dimension"},
Dimensions: dims,
})
}
func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {
body := newClient("https://dashscope.aliyuncs.com"+endpoint, 1152).
BuildRequestBody([]string{"a", "b"}, api.EmbedDocument)
assert.Equal(t, map[string]any{
"model": "tongyi-embedding-vision-plus",
"input": map[string]any{"contents": []any{
map[string]any{"text": "a"}, map[string]any{"text": "b"},
}},
// Under parameters, and singular.
"parameters": map[string]any{"dimension": 1152},
}, body)
}
func TestNoParametersWithoutARequestedWidth(t *testing.T) {
body := newClient("https://dashscope.aliyuncs.com"+endpoint, 0).
BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.NotContains(t, body, "parameters")
}
func TestDecodesTheDocumentedResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
got, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{
{-0.026611328125, -0.016571044921875},
{0.051544189453125, 0.007717132568359375},
}, got, "each vector must land in its own slot, by index")
assert.Equal(t, endpoint, path, "the base URL already names the endpoint")
}
// DashScope answers some failures with a 200 and a code in the body.
func TestSurfacesAnInBodyError(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(`{"code":"InvalidParameter","message":"contents exceeds 20"}`))
}))
defer server.Close()
_, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "contents exceeds 20")
}