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

+112
View File
@@ -0,0 +1,112 @@
package embedding
import (
"context"
"fmt"
"os"
"strconv"
"sync"
"academy/internal/models/utils"
"github.com/panjf2000/ants/v2"
)
type batchEmbedder struct {
pool *ants.Pool
}
func NewBatchEmbedder(pool *ants.Pool) EmbedderPooler {
return &batchEmbedder{pool: pool}
}
type textEmbedding struct {
text string
results []float32
}
func (e *batchEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
// Create goroutine pool for concurrent processing of document chunks
var wg sync.WaitGroup
var mu sync.Mutex // For synchronizing access to error
var firstErr error // Record the first error that occurs
batchSizeStr := os.Getenv("BATCH_EMBED_SIZE")
if batchSizeStr == "" {
batchSizeStr = "5"
}
batchSize, err := strconv.Atoi(batchSizeStr)
if err != nil {
return nil, err
}
textEmbeddings := utils.MapSlice(texts, func(text string) *textEmbedding {
return &textEmbedding{text: text}
})
// Function to process each document chunk
processChunk := func(texts []*textEmbedding) func() {
return func() {
defer wg.Done()
// If an error has already occurred, don't continue processing. The
// read takes mu for the same reason the writes below do: every pool
// worker evaluates this guard, so an unsynchronised read races with
// another worker's write. Beyond the detector, a worker that misses
// the write bills another provider request after the run has already
// failed, which is exactly what this guard exists to prevent.
mu.Lock()
aborted := firstErr != nil
mu.Unlock()
if aborted {
return
}
// Embed text
embedding, err := model.BatchEmbed(ctx, utils.MapSlice(texts, func(text *textEmbedding) string {
return text.text
}))
if err != nil {
mu.Lock()
if firstErr == nil {
firstErr = err
}
mu.Unlock()
return
}
if len(embedding) != len(texts) {
mu.Lock()
if firstErr == nil {
firstErr = fmt.Errorf("embedding model returned %d embeddings for %d inputs", len(embedding), len(texts))
}
mu.Unlock()
return
}
mu.Lock()
for i, text := range texts {
if text == nil {
continue
}
text.results = embedding[i]
}
mu.Unlock()
}
}
// Submit all tasks to the goroutine pool
for _, texts := range utils.ChunkSlice(textEmbeddings, batchSize) {
wg.Add(1)
err := e.pool.Submit(processChunk(texts))
if err != nil {
return nil, err
}
}
// Wait for all tasks to complete
wg.Wait()
// Check if any errors occurred
if firstErr != nil {
return nil, firstErr
}
results := utils.MapSlice(textEmbeddings, func(text *textEmbedding) []float32 {
return text.results
})
return results, nil
}
@@ -0,0 +1,145 @@
package embedding
import (
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
"github.com/panjf2000/ants/v2"
)
// flakyEmbedder fails the first sub-batch it is given and succeeds afterwards,
// so the pool has a failure to record while other sub-batches are still queued.
type flakyEmbedder struct {
calls atomic.Int32
}
func (f *flakyEmbedder) Embed(context.Context, string) ([]float32, error) {
return nil, errProviderDown
}
func (f *flakyEmbedder) BatchEmbed(_ context.Context, texts []string) ([][]float32, error) {
if f.calls.Add(1) == 1 {
return nil, errProviderDown
}
out := make([][]float32, len(texts))
for i := range out {
out[i] = []float32{1}
}
return out, nil
}
func (f *flakyEmbedder) GetModelName() string { return "flaky" }
func (f *flakyEmbedder) GetDimensions() int { return 1 }
func (f *flakyEmbedder) GetModelID() string { return "flaky" }
// BatchEmbedWithPool satisfies EmbedderPooler; the pool under test is the one
// passed explicitly to it, so this is never the path the tests exercise.
func (f *flakyEmbedder) BatchEmbedWithPool(
ctx context.Context, model Embedder, texts []string,
) ([][]float32, error) {
return model.BatchEmbed(ctx, texts)
}
var errProviderDown = errors.New("provider down")
// BatchEmbedWithPool fans a batch out over the ants pool, so with
// BATCH_EMBED_SIZE=1 every text becomes its own sub-batch and several workers
// run at once. When one of them fails, the remaining queued sub-batches read
// firstErr to decide whether to skip — a decision every worker makes
// concurrently with other workers' writes to that same variable.
//
// That read is only observable under the race detector: whether a particular
// worker happens to observe the write depends on scheduling, so no assertion on
// call counts can pin it without being flaky. Run this with -race:
//
// go test -race ./internal/models/embedding/ -run TestBatchEmbedWithPoolErrorPath
//
// Before the read was taken under mu, the detector reported a race between
// batch.go's guard and the write in the failure branch.
func TestBatchEmbedWithPoolErrorPath(t *testing.T) {
t.Setenv("BATCH_EMBED_SIZE", "1")
pool, err := ants.NewPool(8)
if err != nil {
t.Fatalf("new pool: %v", err)
}
t.Cleanup(pool.Release)
pooler := NewBatchEmbedder(pool)
// Repeat so the workers overlap in many different interleavings rather than
// relying on one lucky schedule.
for round := range 20 {
texts := make([]string, 64)
for i := range texts {
texts[i] = fmt.Sprintf("round-%d-chunk-%d", round, i)
}
model := &flakyEmbedder{}
got, err := pooler.BatchEmbedWithPool(context.Background(), model, texts)
if !errors.Is(err, errProviderDown) {
t.Fatalf("round %d: err = %v, want %v", round, err, errProviderDown)
}
if got != nil {
t.Fatalf("round %d: results = %v, want none alongside an error", round, got)
}
}
}
// A provider that returns fewer vectors than inputs is the second failure mode
// the pool records. It writes firstErr from the same branch, so it guards
// against the same regression.
func TestBatchEmbedWithPoolLengthMismatchPath(t *testing.T) {
t.Setenv("BATCH_EMBED_SIZE", "1")
pool, err := ants.NewPool(8)
if err != nil {
t.Fatalf("new pool: %v", err)
}
t.Cleanup(pool.Release)
pooler := NewBatchEmbedder(pool)
for round := range 20 {
texts := make([]string, 64)
for i := range texts {
texts[i] = fmt.Sprintf("round-%d-chunk-%d", round, i)
}
model := &shortEmbedder{}
got, err := pooler.BatchEmbedWithPool(context.Background(), model, texts)
if err == nil {
t.Fatalf("round %d: err = nil, want a length-mismatch error", round)
}
if got != nil {
t.Fatalf("round %d: results = %v, want none alongside an error", round, got)
}
}
}
// shortEmbedder always answers with one vector fewer than it was given.
type shortEmbedder struct{}
func (shortEmbedder) Embed(context.Context, string) ([]float32, error) {
return nil, fmt.Errorf("unexpected Embed call")
}
func (shortEmbedder) BatchEmbed(_ context.Context, texts []string) ([][]float32, error) {
out := make([][]float32, len(texts))
for i := range out {
out[i] = []float32{1}
}
return out[:len(out)-1], nil
}
func (shortEmbedder) GetModelName() string { return "short" }
func (shortEmbedder) GetDimensions() int { return 1 }
func (shortEmbedder) GetModelID() string { return "short" }
// BatchEmbedWithPool satisfies EmbedderPooler; see flakyEmbedder.
func (shortEmbedder) BatchEmbedWithPool(
ctx context.Context, model Embedder, texts []string,
) ([][]float32, error) {
return model.BatchEmbed(ctx, texts)
}
@@ -0,0 +1,105 @@
package embedding
import (
"context"
"net/url"
"strings"
"testing"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
// Exercise the production factory and HTTP transport for every embedding rule,
// including aliases, pattern entries and both query/document task modes.
func TestEveryCatalogEmbeddingTransport(t *testing.T) {
for _, v := range modelruntime.List() {
for _, m := range v.Models() {
if m.Type != types.ModelTypeEmbedding {
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(
strings.ReplaceAll(
v.GetDefaultURL(
types.ModelTypeEmbedding,
),
"{resource}",
"test-resource",
),
)
require.NoError(t, err)
cfg := Config{
Source: types.ModelSourceRemote,
Provider: v.ID,
ModelName: name,
ModelID: "row-id",
BaseURL: u.url + base.Path,
APIKey: "row-key",
AppID: "app",
AppSecret: "secret",
Dimensions: 256,
SupportsDimensionOverride: true,
}
client, err := newRemoteEmbedder(cfg, nil)
require.NoError(t, err)
for _, ctx := range []context.Context{
context.Background(),
types.WithEmbedQuery(
context.Background(),
),
} {
vectors, err := client.BatchEmbed(ctx, []string{"a", "中文"})
require.NoError(t, err)
require.Equal(t, [][]float32{{1}, {2}}, vectors)
}
require.NotEmpty(t, u.requests)
require.Equal(t, "row-id", client.GetModelID())
})
}
}
}
}
func TestStoredEmbeddingSpecReachesWire(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-embeddings",
"max_batch_size": 1,
"extra_body": map[string]any{
"custom_flag": true,
},
},
},
},
}
client, err := newRemoteEmbedder(ConfigFromModel(row, "", ""), nil)
require.NoError(t, err)
_, err = client.BatchEmbed(context.Background(), []string{"a", "b"})
require.NoError(t, err)
require.Len(t, u.requests, 2)
for _, req := range u.requests {
require.Equal(t, "/custom-embeddings", req.path)
require.Equal(t, true, req.body["custom_flag"])
require.Equal(t, "Bearer model-key", req.header.Get("Authorization"))
}
row.Parameters.Spec.Compat = map[string]any{"misspelled_option": true}
_, err = newRemoteEmbedder(ConfigFromModel(row, "", ""), nil)
require.ErrorContains(t, err, "unknown field")
}
@@ -0,0 +1,83 @@
package embedding
import (
"context"
"academy/internal/models/limiter"
)
// Embedding is the highest-volume background model call: document ingestion
// vectorises every chunk, so a single batch upload can burst the whole worker
// pool against one embedding provider. Like chat and vlm, embedding is governed
// at the client layer via the shared per-model concurrency governor. Only
// background (asynq worker) calls are throttled — see limiter.Gate /
// types.IsBackgroundTask; interactive query embedding is never gated.
//
// Placement note: unlike chat/vlm (outermost), this wrapper sits INNERMOST —
// directly around the real embedder, BELOW the debug/langfuse decorators.
// BatchEmbedWithPool fans a batch out into per-sub-batch BatchEmbed calls
// through the pooler, and the pooler invokes BatchEmbed on whichever Embedder
// was threaded down as `model`. Sitting innermost is what routes those
// per-sub-batch provider round-trips back through Gate, so the semaphore bounds
// real concurrent provider calls rather than one coarse per-document unit. The
// trade-off is that Gate wait time is included in debug/langfuse timing, which
// is acceptable for background ingestion.
type concurrencyEmbedder struct {
inner Embedder
// limit is this model's configured per-model background cap; 0 falls back
// to the process-wide default (see limiter.GateN).
limit int
}
func (w *concurrencyEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.Embed(ctx, text)
}
func (w *concurrencyEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.BatchEmbed(ctx, texts)
}
// BatchEmbedWithPool threads THIS wrapper down as the model so the pooler's
// per-sub-batch callbacks land on our gated BatchEmbed above, rather than on
// the raw embedder. The wait for each slot is held only around the actual
// per-sub-batch provider round-trip.
func (w *concurrencyEmbedder) BatchEmbedWithPool(
ctx context.Context, model Embedder, texts []string,
) ([][]float32, error) {
return w.inner.BatchEmbedWithPool(ctx, w, texts)
}
func (w *concurrencyEmbedder) AcceptsImages() bool {
_, ok := AsImageEmbedder(w.inner)
return ok
}
func (w *concurrencyEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(w.inner) }
func (w *concurrencyEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {
inner, err := imageSide(w.inner)
if err != nil {
return nil, err
}
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return inner.BatchEmbedImages(ctx, images)
}
func (w *concurrencyEmbedder) GetModelName() string { return w.inner.GetModelName() }
func (w *concurrencyEmbedder) GetDimensions() int { return w.inner.GetDimensions() }
func (w *concurrencyEmbedder) GetModelID() string { return w.inner.GetModelID() }
// wrapEmbeddingConcurrency installs the background concurrency governor directly
// around the real embedder. Always applied; a cheap passthrough when no limiter
// is installed or the call is interactive.
func wrapEmbeddingConcurrency(e Embedder, limit int) Embedder {
if e == nil {
return e
}
return &concurrencyEmbedder{inner: e, limit: limit}
}
@@ -0,0 +1,232 @@
package embedding
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"academy/internal/models/limiter"
"academy/internal/types"
"github.com/panjf2000/ants/v2"
)
// fakeEmbedder blocks every Embed/BatchEmbed call until release is closed and
// records the max number of calls it ever saw in flight simultaneously, so
// tests can assert the governor's per-model concurrency bound.
type fakeEmbedder struct {
id string
pooler EmbedderPooler // optional: exercises the BatchEmbedWithPool fan-out
inFlight int32
maxSeen int32
enter chan struct{} // one signal per call that reaches the provider
release chan struct{} // closed to unblock all (current + future) calls
}
func newFakeEmbedder(id string) *fakeEmbedder {
return &fakeEmbedder{
id: id,
enter: make(chan struct{}, 256),
release: make(chan struct{}),
}
}
func (f *fakeEmbedder) track() {
n := atomic.AddInt32(&f.inFlight, 1)
for {
old := atomic.LoadInt32(&f.maxSeen)
if n <= old || atomic.CompareAndSwapInt32(&f.maxSeen, old, n) {
break
}
}
f.enter <- struct{}{}
<-f.release
atomic.AddInt32(&f.inFlight, -1)
}
func (f *fakeEmbedder) Embed(ctx context.Context, _ string) ([]float32, error) {
f.track()
return []float32{1}, nil
}
func (f *fakeEmbedder) BatchEmbed(ctx context.Context, _ []string) ([][]float32, error) {
f.track()
return [][]float32{{1}}, nil
}
func (f *fakeEmbedder) BatchEmbedWithPool(
ctx context.Context, model Embedder, texts []string,
) ([][]float32, error) {
if f.pooler != nil {
return f.pooler.BatchEmbedWithPool(ctx, model, texts)
}
return model.BatchEmbed(ctx, texts)
}
func (f *fakeEmbedder) GetModelName() string { return f.id }
func (f *fakeEmbedder) GetDimensions() int { return 1 }
func (f *fakeEmbedder) GetModelID() string { return f.id }
// TestConcurrencyEmbedderBackgroundGated verifies background BatchEmbed calls
// are capped at the per-model limit.
func TestConcurrencyEmbedderBackgroundGated(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
limiter.SetGovernor(limiter.NewLocalLimiter(), 2)
f := newFakeEmbedder("emb-bg")
w := wrapEmbeddingConcurrency(f, 0)
ctx := types.WithBackgroundTask(context.Background())
const n = 5
var wg sync.WaitGroup
for range n {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = w.BatchEmbed(ctx, []string{"x"})
}()
}
// With limit=2 exactly two calls may reach the provider concurrently.
for i := range 2 {
select {
case <-f.enter:
case <-time.After(2 * time.Second):
t.Fatalf("expected call %d to enter, inFlight=%d", i, atomic.LoadInt32(&f.inFlight))
}
}
// A third must not sneak in while both slots are held.
select {
case <-f.enter:
t.Fatal("a third call entered while limit=2 slots were held")
case <-time.After(150 * time.Millisecond):
}
close(f.release)
wg.Wait()
if got := atomic.LoadInt32(&f.maxSeen); got > 2 {
t.Fatalf("max in-flight %d exceeded limit 2", got)
}
}
// TestConcurrencyEmbedderPerModelLimitOverridesDefault verifies a model's own
// configured limit takes precedence over the process-wide default.
func TestConcurrencyEmbedderPerModelLimitOverridesDefault(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
// Global default is generous (10), but this model is pinned to 1.
limiter.SetGovernor(limiter.NewLocalLimiter(), 10)
f := newFakeEmbedder("emb-permodel")
w := wrapEmbeddingConcurrency(f, 1)
ctx := types.WithBackgroundTask(context.Background())
const n = 3
var wg sync.WaitGroup
for range n {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = w.BatchEmbed(ctx, []string{"x"})
}()
}
// Only one may be in flight because the per-model limit is 1.
select {
case <-f.enter:
case <-time.After(2 * time.Second):
t.Fatalf("expected one call to enter, inFlight=%d", atomic.LoadInt32(&f.inFlight))
}
select {
case <-f.enter:
t.Fatal("a second call entered while per-model limit=1 slot was held")
case <-time.After(150 * time.Millisecond):
}
close(f.release)
wg.Wait()
if got := atomic.LoadInt32(&f.maxSeen); got > 1 {
t.Fatalf("max in-flight %d exceeded per-model limit 1", got)
}
}
// TestConcurrencyEmbedderInteractiveNotGated verifies interactive calls bypass
// the governor entirely, even at limit 1.
func TestConcurrencyEmbedderInteractiveNotGated(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
limiter.SetGovernor(limiter.NewLocalLimiter(), 1)
f := newFakeEmbedder("emb-interactive")
w := wrapEmbeddingConcurrency(f, 0)
ctx := context.Background() // no background marker
const n = 3
var wg sync.WaitGroup
for range n {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = w.Embed(ctx, "x")
}()
}
// All three must be able to run at once despite limit=1.
for i := range n {
select {
case <-f.enter:
case <-time.After(2 * time.Second):
t.Fatalf("interactive call %d did not enter (should be ungated), inFlight=%d",
i, atomic.LoadInt32(&f.inFlight))
}
}
close(f.release)
wg.Wait()
}
// TestConcurrencyEmbedderPoolFanOutGated verifies that BatchEmbedWithPool's
// per-sub-batch provider round-trips are individually gated — the reason the
// wrapper sits innermost.
func TestConcurrencyEmbedderPoolFanOutGated(t *testing.T) {
t.Setenv("BATCH_EMBED_SIZE", "1") // one provider round-trip per text
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
limiter.SetGovernor(limiter.NewLocalLimiter(), 2)
pool, err := ants.NewPool(16)
if err != nil {
t.Fatalf("new pool: %v", err)
}
defer pool.Release()
f := newFakeEmbedder("emb-pool")
f.pooler = NewBatchEmbedder(pool)
w := wrapEmbeddingConcurrency(f, 0)
ctx := types.WithBackgroundTask(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_, _ = w.BatchEmbedWithPool(ctx, w, []string{"a", "b", "c", "d", "e"})
}()
for i := range 2 {
select {
case <-f.enter:
case <-time.After(2 * time.Second):
t.Fatalf("expected sub-batch %d to enter, inFlight=%d", i, atomic.LoadInt32(&f.inFlight))
}
}
select {
case <-f.enter:
t.Fatal("a third sub-batch entered while limit=2 slots were held")
case <-time.After(150 * time.Millisecond):
}
close(f.release)
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("BatchEmbedWithPool did not complete after release")
}
if got := atomic.LoadInt32(&f.maxSeen); got > 2 {
t.Fatalf("max in-flight sub-batches %d exceeded limit 2", got)
}
}
@@ -0,0 +1,47 @@
package embedding
import (
"testing"
"academy/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "emb-1",
Name: "text-embedding-3-small",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "openai",
EmbeddingParameters: types.EmbeddingParameters{
Dimension: 1536,
TruncatePromptTokens: 512,
SupportsDimensionOverride: true,
},
ExtraConfig: map[string]string{"region": "us-east"},
CustomHeaders: map[string]string{"X-Gateway": "g1"},
},
}
cfg := ConfigFromModel(m, "app", "secret")
if cfg.ModelID != "emb-1" || cfg.ModelName != "text-embedding-3-small" {
t.Errorf("identity mismatch: %+v", cfg)
}
if cfg.Dimensions != 1536 || cfg.TruncatePromptTokens != 512 {
t.Errorf("embedding params mismatch: %+v", cfg)
}
if !cfg.SupportsDimensionOverride {
t.Errorf("SupportsDimensionOverride not propagated: %+v", cfg)
}
if cfg.CustomHeaders["X-Gateway"] != "g1" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
if cfg.ExtraConfig["region"] != "us-east" {
t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig)
}
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
t.Errorf("cloud creds mismatch: %+v", cfg)
}
}
+175
View File
@@ -0,0 +1,175 @@
package embedding
import (
"context"
"errors"
"fmt"
"strings"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/models/imageprep"
"academy/internal/models/utils/ollama"
"academy/internal/tracing/langfuse"
"academy/internal/types"
)
// Embedder defines the interface for text vectorization
type Embedder interface {
// Embed converts text to vector
Embed(ctx context.Context, text string) ([]float32, error)
// BatchEmbed converts multiple texts to vectors in batch
BatchEmbed(ctx context.Context, texts []string) ([][]float32, error)
// GetModelName returns the model name
GetModelName() string
// GetDimensions returns the vector dimensions
GetDimensions() int
// GetModelID returns the model ID
GetModelID() string
EmbedderPooler
}
// Image is one image to embed: its bytes and MIME type.
type Image = api.EmbedImage
// ErrImagesUnsupported is returned when an embedder is asked for an image
// vector its model or endpoint cannot produce.
var ErrImagesUnsupported = errors.New("embedding model does not accept images")
// ImageEmbedder is the image side of an Embedder whose model maps images into
// the same space as its text vectors, so that a text query can find an image.
// It is a separate interface because most embedders have no image side; use
// AsImageEmbedder rather than a type assertion, since every decorator
// implements it whether or not the model underneath does.
type ImageEmbedder interface {
// AcceptsImages reports whether both the model and its endpoint take
// images.
AcceptsImages() bool
// ImageLimits are the vendor's documented per-image limits. The caller
// shrinks or converts an image to fit; an image outside them is refused.
ImageLimits() ImageLimits
// BatchEmbedImages converts images to vectors comparable with Embed's.
BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error)
}
// ImageLimits describes what one image may be; see imageprep.Limits.
type ImageLimits = imageprep.Limits
// AsImageEmbedder returns e's image side when its model accepts images.
func AsImageEmbedder(e Embedder) (ImageEmbedder, bool) {
ie, ok := e.(ImageEmbedder)
if !ok || !ie.AcceptsImages() {
return nil, false
}
return ie, true
}
// imageSide is AsImageEmbedder for decorators, which must fail a call their
// inner embedder cannot serve.
func imageSide(e Embedder) (ImageEmbedder, error) {
if ie, ok := AsImageEmbedder(e); ok {
return ie, nil
}
return nil, fmt.Errorf("%s: %w", e.GetModelName(), ErrImagesUnsupported)
}
func imageLimitsOf(e Embedder) ImageLimits {
if ie, ok := AsImageEmbedder(e); ok {
return ie.ImageLimits()
}
return ImageLimits{}
}
type EmbedderPooler interface {
BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error)
}
// EmbedderType represents the embedder type
type EmbedderType string
// Config represents the embedder configuration
type Config struct {
Source types.ModelSource `json:"source"`
BaseURL string `json:"base_url"`
ModelName string `json:"model_name"`
APIKey string `json:"api_key"`
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
Dimensions int `json:"dimensions"`
SupportsDimensionOverride bool `json:"supports_dimension_override"`
ModelID string `json:"model_id"`
Provider string `json:"provider"`
// MaxConcurrency caps concurrent background calls to this model; 0 falls
// back to the process-wide default (see limiter.GateN).
MaxConcurrency int `json:"max_concurrency"`
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
ExtraConfig map[string]string `json:"extra_config"`
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string `json:"custom_headers"`
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
}
// ConfigFromModel 根据 types.Model 构造 embedding.Config。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// appID / appSecret 是已解密的 AcademyCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) Config {
if m == nil {
return Config{}
}
return Config{
Source: m.Source,
BaseURL: m.Parameters.BaseURL,
APIKey: m.Parameters.APIKey,
ModelID: m.ID,
ModelName: m.Name,
Dimensions: m.Parameters.EmbeddingParameters.Dimension,
SupportsDimensionOverride: m.Parameters.EmbeddingParameters.SupportsDimensionOverride,
TruncatePromptTokens: m.Parameters.EmbeddingParameters.TruncatePromptTokens,
Provider: m.Parameters.Provider,
MaxConcurrency: m.Parameters.MaxConcurrency,
Spec: m.Parameters.Spec,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
// NewEmbedder creates an embedder based on the configuration
func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
e, err := newEmbedder(config, pooler, ollamaService)
if err != nil {
return e, err
}
if setter, ok := e.(interface{ SetSupportsDimensionOverride(bool) }); ok {
setter.SetSupportsDimensionOverride(config.SupportsDimensionOverride)
}
// Innermost: gate the real provider round-trips (including the per-sub-batch
// pool callbacks) before debug/langfuse wrap for logging/tracing. See
// concurrencyEmbedder for why this sits below the observability decorators.
e = wrapEmbeddingConcurrency(e, config.MaxConcurrency)
if logger.LLMDebugEnabled() {
e = &debugEmbedder{inner: e}
}
if langfuse.GetManager().Enabled() {
e = &langfuseEmbedder{inner: e}
}
return e, nil
}
func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
switch strings.ToLower(string(config.Source)) {
case string(types.ModelSourceLocal):
return NewOllamaEmbedder(config.BaseURL,
config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler, ollamaService)
case string(types.ModelSourceRemote):
return newRemoteEmbedder(config, pooler)
default:
return nil, fmt.Errorf("unsupported embedder source: %s", config.Source)
}
}
@@ -0,0 +1,316 @@
package embedding
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, so each answer's vector names its image.
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 imageEmbedder(t *testing.T, up *upstream, provider, model, base string, spec *types.ModelSpecOverride) Embedder {
t.Helper()
e, err := NewEmbedder(Config{
Source: types.ModelSourceRemote, Provider: provider, ModelName: model,
BaseURL: up.url + base, APIKey: "k", Dimensions: 256, Spec: spec,
}, nil, nil)
require.NoError(t, err)
return e
}
// TestImageEmbeddingWireFormatPerVendor pins the image request each
// multimodal vendor is sent, and how a batch is split at the documented
// number of images per request. The image part of every body is the shape
// the vendor's reference gives, as cited on the protocol client.
func TestImageEmbeddingWireFormatPerVendor(t *testing.T) {
uri := "data:image/png;base64,iQ==" // one 0x89 byte
const dashPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
cases := []struct {
name, provider, model, base string
images int
wantPath string
wantRequests int
wantBody map[string]any // the first request's body, exactly
}{
{
name: "volcengine fuses, so one image per request", provider: "volcengine",
model: "doubao-embedding-vision-251215", base: "/api/v3", images: 2, wantRequests: 2,
wantPath: "/api/v3/embeddings/multimodal",
wantBody: map[string]any{
"model": "doubao-embedding-vision-251215", "encoding_format": "float",
"input": []any{map[string]any{"type": "image_url", "image_url": map[string]any{"url": uri}}},
},
},
{
name: "aliyun tongyi vision plus takes eight images", provider: "aliyun",
model: "tongyi-embedding-vision-plus", base: "/compatible-mode/v1", images: 9, wantRequests: 2,
wantPath: dashPath,
wantBody: map[string]any{
"model": "tongyi-embedding-vision-plus",
"input": map[string]any{"contents": func() []any {
out := []any{}
for _, img := range pngs(8) {
out = append(out, map[string]any{"image": img.DataURI()})
}
return out
}()},
},
},
{
name: "aliyun multimodal-embedding-v1 takes one image", provider: "aliyun",
model: "multimodal-embedding-v1", base: "/compatible-mode/v1", images: 2, wantRequests: 2,
wantPath: dashPath,
wantBody: map[string]any{
"model": "multimodal-embedding-v1",
"input": map[string]any{"contents": []any{map[string]any{"image": uri}}},
},
},
{
name: "gemini embeds each image as its own inlineData request", provider: "gemini",
model: "gemini-embedding-2", base: "/v1beta", images: 2, wantRequests: 1,
wantPath: "/v1beta/models/gemini-embedding-2:batchEmbedContents",
wantBody: map[string]any{"requests": []any{
map[string]any{
"model": "models/gemini-embedding-2",
"content": map[string]any{"parts": []any{
map[string]any{"inlineData": map[string]any{"mimeType": "image/png", "data": "iQ=="}},
}},
},
map[string]any{
"model": "models/gemini-embedding-2",
"content": map[string]any{"parts": []any{
map[string]any{"inlineData": map[string]any{"mimeType": "image/png", "data": "iYk="}},
}},
},
}},
},
{
name: "jina sends an image object in input", provider: "jina",
model: "jina-embeddings-v5-omni-small", base: "/v1", images: 2, wantRequests: 2,
wantPath: "/v1/embeddings",
wantBody: map[string]any{
"model": "jina-embeddings-v5-omni-small", "truncate": true,
"input": []any{map[string]any{"image": uri}},
},
},
{
name: "a generic (vLLM) row sends each image as a messages conversation", provider: "generic",
model: "TIGER-Lab/VLM2Vec-Full", base: "/v1", images: 2, wantRequests: 2,
wantPath: "/v1/embeddings",
wantBody: map[string]any{
"model": "TIGER-Lab/VLM2Vec-Full", "encoding_format": "float", "truncate_prompt_tokens": float64(511),
"messages": []any{map[string]any{"role": "user", "content": []any{
map[string]any{"type": "image_url", "image_url": map[string]any{"url": uri}},
}}},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
var spec *types.ModelSpecOverride
if tc.provider == "generic" {
spec = &types.ModelSpecOverride{Input: []string{"text", "image"}}
}
ie, ok := AsImageEmbedder(imageEmbedder(t, up, tc.provider, tc.model, tc.base, spec))
require.True(t, ok, "the catalog lists this model as taking images")
images := pngs(tc.images)
got, err := ie.BatchEmbedImages(context.Background(), images)
require.NoError(t, err)
want := make([][]float32, len(images))
for i, img := range images {
want[i] = []float32{float32(len(img.Data))}
}
assert.Equal(t, want, got, "every vector must come back in its own slot")
require.Len(t, up.requests, tc.wantRequests)
assert.Equal(t, tc.wantPath, up.requests[0].path)
assert.Equal(t, tc.wantBody, up.requests[0].body)
})
}
}
func TestImageEmbeddingNeedsBothTheModelAndTheEndpoint(t *testing.T) {
declare := &types.ModelSpecOverride{Input: []string{"text", "image"}}
cases := []struct {
name, provider, model string
spec *types.ModelSpecOverride
want bool
}{
{"text model on a vendor with an image field", "jina", "jina-embeddings-v3", nil, false},
{"text model on the OpenAI shape", "openai", "text-embedding-3-small", nil, false},
{"generic endpoint, image input not declared", "generic", "my-clip", nil, false},
{"declared on a generic (vLLM) endpoint", "generic", "my-clip", declare, true},
{"declared on the OpenAI provider", "openai", "my-clip", declare, true},
{"declared on LiteLLM", "litellm", "my-clip", declare, true},
{
"declared, but the row switched to an object format without a field", "generic", "my-clip",
&types.ModelSpecOverride{
Input: []string{"text", "image"}, Compat: map[string]any{"image_format": "object"},
},
false,
},
{"declared on a vendor that names one", "jina", "my-jina-omni", declare, true},
{
"the row narrows a multimodal catalog entry", "volcengine", "doubao-embedding-vision-251215",
&types.ModelSpecOverride{Input: []string{"text"}}, false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
e := imageEmbedder(t, up, tc.provider, tc.model, "/v1", tc.spec)
_, ok := AsImageEmbedder(e)
assert.Equal(t, tc.want, ok)
if !tc.want {
// Every decorator carries the method, so a caller that skips
// AsImageEmbedder still gets a refusal rather than a request.
_, err := e.(ImageEmbedder).BatchEmbedImages(context.Background(), pngs(1))
assert.True(t, errors.Is(err, ErrImagesUnsupported), "got %v", err)
assert.Empty(t, up.requests)
}
})
}
}
// Qwen3-VL-Embedding on vLLM matches its model card only when text and
// image both pass the chat template and the prompt ends in <|endoftext|>,
// the token its last-token pooling reads. A plain `input` string skips the
// template and lands in a different space from the images.
// An OpenAI-compatible gateway has no image field of its own. Declaring
// image input, and nothing else, must still send the picture: vLLM takes it
// as a messages conversation. The text request stays on input.
func TestDeclaredImageInputOnOpenAIGatewayUsesMessages(t *testing.T) {
up := newUpstream(t)
declare := &types.ModelSpecOverride{Input: []string{"text", "image"}}
e := imageEmbedder(t, up, "openai", "WeMM-Embedding-2B", "/v1", declare)
ie, ok := AsImageEmbedder(e)
require.True(t, ok)
_, err := e.BatchEmbed(context.Background(), []string{"bridge"})
require.NoError(t, err)
images, err := ie.BatchEmbedImages(context.Background(), pngs(1))
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}}, images)
require.Len(t, up.requests, 2)
assert.Equal(t, map[string]any{
"model": "WeMM-Embedding-2B", "encoding_format": "float",
"input": []any{"bridge"},
}, up.requests[0].body)
assert.Equal(t, map[string]any{
"model": "WeMM-Embedding-2B", "encoding_format": "float",
"messages": []any{map[string]any{"role": "user", "content": []any{
map[string]any{"type": "image_url", "image_url": map[string]any{"url": pngs(1)[0].DataURI()}},
}}},
}, up.requests[1].body)
}
func TestSelfHostedQwen3VLEmbeddingSendsTextAndImagesThroughTheTemplate(t *testing.T) {
up := newUpstream(t)
e := imageEmbedder(t, up, "generic", "Qwen/Qwen3-VL-Embedding-8B", "/v1", nil)
ie, ok := AsImageEmbedder(e)
require.True(t, ok, "the catalog declares image input without a row override")
got, err := e.BatchEmbed(types.WithEmbedQuery(context.Background()), []string{"ab", "c"})
require.NoError(t, err)
assert.Equal(t, [][]float32{{2}, {1}}, got)
images, err := ie.BatchEmbedImages(context.Background(), pngs(6))
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}, {3}, {4}, {5}, {6}}, images)
message := func(part map[string]any) map[string]any {
return map[string]any{
"model": "Qwen/Qwen3-VL-Embedding-8B", "encoding_format": "float",
"truncate_prompt_tokens": float64(511), "add_special_tokens": true,
"messages": []any{map[string]any{"role": "user", "content": []any{part}}},
}
}
textBatch := message(nil)
textBatch["messages"] = []any{
message(map[string]any{"type": "text", "text": "ab"})["messages"],
message(map[string]any{"type": "text", "text": "c"})["messages"],
}
imageMessage := func(img Image) map[string]any {
return message(map[string]any{"type": "image_url", "image_url": map[string]any{"url": img.DataURI()}})
}
imageBatch := message(nil)
conversations := make([]any, 5)
for i, img := range pngs(5) {
conversations[i] = imageMessage(img)["messages"]
}
imageBatch["messages"] = conversations
require.Len(t, up.requests, 3, "one text batch and image batches of five and one")
assert.Equal(t, textBatch, up.requests[0].body)
assert.Equal(t, imageBatch, up.requests[1].body)
assert.Equal(t, imageMessage(pngs(6)[5]), up.requests[2].body)
}
func TestSelfHostedQwenMessagesBatchCanBeDisabledForOlderServers(t *testing.T) {
up := newUpstream(t)
e := imageEmbedder(t, up, "generic", "Qwen/Qwen3-VL-Embedding-8B", "/v1",
&types.ModelSpecOverride{Compat: map[string]any{"batch_messages": false}})
got, err := e.BatchEmbed(context.Background(), []string{"ab", "c"})
require.NoError(t, err)
assert.Equal(t, [][]float32{{2}, {1}}, got)
require.Len(t, up.requests, 2)
assert.IsType(t, map[string]any{}, up.requests[0].body["messages"].([]any)[0])
}
func TestImageEmbeddingRefusesWhatTheVendorDocumentsItWillNotTake(t *testing.T) {
up := newUpstream(t)
gemini, ok := AsImageEmbedder(imageEmbedder(t, up, "gemini", "gemini-embedding-2", "/v1beta", nil))
require.True(t, ok)
assert.Equal(t, []string{"image/png", "image/jpeg"}, gemini.ImageLimits().MIMETypes)
_, err := gemini.BatchEmbedImages(context.Background(),
append(pngs(1), Image{Data: []byte{1}, MIMEType: "image/webp"}))
assert.ErrorContains(t, err, "image 1")
jina, ok := AsImageEmbedder(imageEmbedder(t, up, "jina", "jina-embeddings-v4", "/v1", nil))
require.True(t, ok)
limit := jina.ImageLimits().MaxBytes
require.Equal(t, 5_000_000, limit)
_, err = jina.BatchEmbedImages(context.Background(),
[]Image{{Data: make([]byte, limit+1), MIMEType: "image/png"}})
assert.ErrorContains(t, err, "limit")
_, err = jina.BatchEmbedImages(context.Background(), []Image{{MIMEType: "image/png"}})
assert.ErrorContains(t, err, "empty")
// Refused before sending anything: no half-embedded batch.
assert.Empty(t, up.requests)
}
// The factory adds the debug and Langfuse decorators only when those are
// switched on, so the image side through them is exercised here directly.
func TestImageEmbeddingPassesThroughEveryDecorator(t *testing.T) {
up := newUpstream(t)
inner := imageEmbedder(t, up, "jina", "jina-embeddings-v4", "/v1", nil)
wrapped := &debugEmbedder{inner: &langfuseEmbedder{inner: inner}}
ie, ok := AsImageEmbedder(wrapped)
require.True(t, ok)
assert.Equal(t, 5_000_000, ie.ImageLimits().MaxBytes)
got, err := ie.BatchEmbedImages(context.Background(), pngs(2))
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got)
textOnly := imageEmbedder(t, up, "openai", "text-embedding-3-small", "/v1", nil)
text := &debugEmbedder{inner: &langfuseEmbedder{inner: textOnly}}
_, ok = AsImageEmbedder(text)
assert.False(t, ok)
assert.Equal(t, ImageLimits{}, text.ImageLimits())
}
@@ -0,0 +1,179 @@
package embedding
import (
"context"
"academy/internal/tracing/langfuse"
)
// langfuseEmbedder wraps an Embedder and reports each call as a Langfuse
// generation observation. Input token counts are approximated from the text
// lengths when the underlying provider doesn't return usage data, because
// Langfuse's cost reports require non-zero input tokens.
type langfuseEmbedder struct {
inner Embedder
}
func (l *langfuseEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Embed(ctx, text)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "embedding.embed",
Model: l.inner.GetModelName(),
Input: text,
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"dimensions": l.inner.GetDimensions(),
},
})
result, err := l.inner.Embed(genCtx, text)
usage := approxEmbeddingUsage([]string{text})
var out interface{}
if len(result) > 0 {
out = map[string]interface{}{
"dimensions": len(result),
"vector_preview": result[:min(3, len(result))],
}
}
gen.Finish(out, usage, err)
return result, err
}
func (l *langfuseEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.BatchEmbed(ctx, texts)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "embedding.batch_embed",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"count": len(texts),
// Avoid sending megabytes of full text — Langfuse truncates but
// the network cost is still real. Keep a short preview instead.
"preview": previewTexts(texts, 5),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"dimensions": l.inner.GetDimensions(),
"batch_size": len(texts),
},
})
result, err := l.inner.BatchEmbed(genCtx, texts)
usage := approxEmbeddingUsage(texts)
var out interface{}
if len(result) > 0 {
out = map[string]interface{}{
"count": len(result),
"dimensions": len(result[0]),
}
}
gen.Finish(out, usage, err)
return result, err
}
func (l *langfuseEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
return l.inner.BatchEmbedWithPool(ctx, l, texts)
}
func (l *langfuseEmbedder) AcceptsImages() bool {
_, ok := AsImageEmbedder(l.inner)
return ok
}
func (l *langfuseEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(l.inner) }
func (l *langfuseEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {
inner, err := imageSide(l.inner)
if err != nil {
return nil, err
}
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return inner.BatchEmbedImages(ctx, images)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "embedding.batch_embed_images",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"count": len(images),
"preview": previewTexts(describeImages(images), 5),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"dimensions": l.inner.GetDimensions(),
"batch_size": len(images),
},
})
result, err := inner.BatchEmbedImages(genCtx, images)
var out interface{}
if len(result) > 0 {
out = map[string]interface{}{
"count": len(result),
"dimensions": len(result[0]),
}
}
// No usage: the text approximation has nothing to count, and a made-up
// token figure for an image would mislead the cost report.
gen.Finish(out, nil, err)
return result, err
}
func (l *langfuseEmbedder) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseEmbedder) GetDimensions() int { return l.inner.GetDimensions() }
func (l *langfuseEmbedder) GetModelID() string { return l.inner.GetModelID() }
// approxEmbeddingUsage estimates input tokens as ~rune_count / 4, matching the
// rule of thumb OpenAI uses in their tokenizer docs. This is purely for cost
// reporting — Langfuse lets users define per-model cost multipliers, so the
// approximation need only be proportional to length.
func approxEmbeddingUsage(texts []string) *langfuse.TokenUsage {
total := 0
for _, t := range texts {
runes := len([]rune(t))
if runes == 0 {
continue
}
total += runes/4 + 1
}
if total == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: total,
Total: total,
Unit: "TOKENS",
}
}
func previewTexts(texts []string, n int) []string {
if len(texts) <= n {
out := make([]string, len(texts))
for i, t := range texts {
out[i] = truncateRunes(t, 120)
}
return out
}
out := make([]string, n)
for i := 0; i < n; i++ {
out[i] = truncateRunes(texts[i], 120)
}
return out
}
func truncateRunes(s string, maxRunes int) string {
r := []rune(s)
if len(r) <= maxRunes {
return s
}
return string(r[:maxRunes]) + "..."
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+121
View File
@@ -0,0 +1,121 @@
package embedding
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/logger"
)
// debugEmbedder wraps an Embedder with LLM debug logging.
type debugEmbedder struct {
inner Embedder
}
func (d *debugEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
start := time.Now()
result, err := d.inner.Embed(ctx, text)
logEmbeddingDebug(ctx, d.inner.GetModelName(), []string{text}, singleToDouble(result), err, time.Since(start))
return result, err
}
func (d *debugEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
start := time.Now()
result, err := d.inner.BatchEmbed(ctx, texts)
logEmbeddingDebug(ctx, d.inner.GetModelName(), texts, result, err, time.Since(start))
return result, err
}
func (d *debugEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
return d.inner.BatchEmbedWithPool(ctx, d, texts)
}
func (d *debugEmbedder) AcceptsImages() bool {
_, ok := AsImageEmbedder(d.inner)
return ok
}
func (d *debugEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(d.inner) }
func (d *debugEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {
inner, err := imageSide(d.inner)
if err != nil {
return nil, err
}
start := time.Now()
result, err := inner.BatchEmbedImages(ctx, images)
logEmbeddingDebug(ctx, d.inner.GetModelName(), describeImages(images), result, err, time.Since(start))
return result, err
}
// describeImages stands in for the 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 *debugEmbedder) GetModelName() string { return d.inner.GetModelName() }
func (d *debugEmbedder) GetDimensions() int { return d.inner.GetDimensions() }
func (d *debugEmbedder) GetModelID() string { return d.inner.GetModelID() }
func singleToDouble(v []float32) [][]float32 {
if v == nil {
return nil
}
return [][]float32{v}
}
func logEmbeddingDebug(ctx context.Context, model string, inputs []string, outputs [][]float32, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Embedding",
Model: model,
Duration: dur,
}
// Input section: show each text with a preview
var inputBuf strings.Builder
inputBuf.WriteString(fmt.Sprintf("count=%d\n", len(inputs)))
for i, t := range inputs {
preview := strings.ReplaceAll(t, "\n", "\\n")
preview = logger.TruncateRunes(preview, 200)
inputBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(t)), preview))
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()})
// Output section
if outputs != nil {
var outBuf strings.Builder
outBuf.WriteString(fmt.Sprintf("count=%d\n", len(outputs)))
for i, vec := range outputs {
if len(vec) > 0 {
outBuf.WriteString(fmt.Sprintf("[%d] dims=%d, first_3=[%.6f, %.6f, %.6f]\n", i, len(vec),
safeIdx(vec, 0), safeIdx(vec, 1), safeIdx(vec, 2)))
} else {
outBuf.WriteString(fmt.Sprintf("[%d] empty\n", i))
}
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Output", Content: outBuf.String()})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
func safeIdx(v []float32, i int) float32 {
if i < len(v) {
return v[i]
}
return 0
}
@@ -0,0 +1,158 @@
package embedding
import (
"context"
"encoding/json"
"math"
"os"
"slices"
"testing"
"time"
"academy/internal/models/imageprep"
"academy/internal/types"
"github.com/panjf2000/ants/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Opt-in integration check against an operator-selected Qwen3-VL endpoint.
// The fixture contains {"texts":[...],"image_paths":[...]} and stays outside
// the repository. This only calls the embedding model; it never writes an index.
// ACADEMY_EMBEDDING_TEST_URL is the base URL including /v1.
// Private/IP endpoints need the usual explicit SSRF_WHITELIST setting.
// A server without batch-invariant computation can fail the strict numerical
// bounds below even when it accepts the batch and returns correctly ordered vectors.
func TestLiveQwenMessagesBatchParity(t *testing.T) {
base := os.Getenv("ACADEMY_EMBEDDING_TEST_URL")
fixture := os.Getenv("ACADEMY_EMBEDDING_TEST_FIXTURE")
if base == "" || fixture == "" {
t.Skip("set ACADEMY_EMBEDDING_TEST_URL and ACADEMY_EMBEDDING_TEST_FIXTURE for live parity checks")
}
var inputs struct {
Texts []string `json:"texts"`
ImagePaths []string `json:"image_paths"`
}
raw, err := os.ReadFile(fixture)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(raw, &inputs))
require.Greater(t, len(inputs.Texts), 1)
require.Greater(t, len(inputs.ImagePaths), 1)
t.Setenv("BATCH_EMBED_SIZE", "5")
pool, err := ants.NewPool(5)
require.NoError(t, err)
defer pool.Release()
config := Config{
Source: types.ModelSourceRemote, Provider: "generic", ModelName: "Qwen/Qwen3-VL-Embedding-8B",
BaseURL: base, APIKey: os.Getenv("ACADEMY_EMBEDDING_TEST_API_KEY"), Dimensions: 4096,
}
batched, err := NewEmbedder(config, NewBatchEmbedder(pool), nil)
require.NoError(t, err)
config.Spec = &types.ModelSpecOverride{Compat: map[string]any{"batch_messages": false}}
serial, err := NewEmbedder(config, NewBatchEmbedder(pool), nil)
require.NoError(t, err)
config.Spec = &types.ModelSpecOverride{Compat: map[string]any{
"batch_messages": true, "max_batch_size": 2, "max_image_batch_size": 2,
}}
smallBatch, err := NewEmbedder(config, NewBatchEmbedder(pool), nil)
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
t.Run("texts", func(t *testing.T) {
start := time.Now()
want, err := serial.BatchEmbed(ctx, inputs.Texts)
require.NoError(t, err)
serialTime := time.Since(start)
start = time.Now()
got, err := batched.BatchEmbedWithPool(ctx, batched, inputs.Texts)
require.NoError(t, err)
t.Logf("inputs=%d serial=%s batch=%s", len(want), serialTime, time.Since(start))
assertLiveVectorParity(t, want, got)
repeat, err := serial.BatchEmbed(ctx, inputs.Texts)
require.NoError(t, err)
t.Log("repeated serial control")
assertLiveVectorParity(t, want, repeat)
got, err = smallBatch.BatchEmbed(ctx, inputs.Texts)
require.NoError(t, err)
t.Log("batch size two")
assertLiveVectorParity(t, want, got)
reversed := slices.Clone(inputs.Texts)
slices.Reverse(reversed)
got, err = batched.BatchEmbedWithPool(ctx, batched, reversed)
require.NoError(t, err)
slices.Reverse(got)
t.Log("reversed batch")
assertLiveVectorParity(t, want, got)
})
t.Run("images", func(t *testing.T) {
imageBatch, ok := AsImageEmbedder(batched)
require.True(t, ok)
imageSerial, ok := AsImageEmbedder(serial)
require.True(t, ok)
images := make([]Image, len(inputs.ImagePaths))
for i, path := range inputs.ImagePaths {
data, err := os.ReadFile(path)
require.NoError(t, err)
images[i], err = imageprep.Prepare(data, imageBatch.ImageLimits())
require.NoError(t, err)
}
start := time.Now()
want, err := imageSerial.BatchEmbedImages(ctx, images)
require.NoError(t, err)
serialTime := time.Since(start)
start = time.Now()
got, err := imageBatch.BatchEmbedImages(ctx, images)
require.NoError(t, err)
t.Logf("inputs=%d serial=%s batch=%s", len(want), serialTime, time.Since(start))
assertLiveVectorParity(t, want, got)
repeat, err := imageSerial.BatchEmbedImages(ctx, images)
require.NoError(t, err)
t.Log("repeated serial control")
assertLiveVectorParity(t, want, repeat)
imageSmall, ok := AsImageEmbedder(smallBatch)
require.True(t, ok)
got, err = imageSmall.BatchEmbedImages(ctx, images)
require.NoError(t, err)
t.Log("batch size two")
assertLiveVectorParity(t, want, got)
slices.Reverse(images)
got, err = imageBatch.BatchEmbedImages(ctx, images)
require.NoError(t, err)
slices.Reverse(got)
t.Log("reversed batch")
assertLiveVectorParity(t, want, got)
})
}
func assertLiveVectorParity(t *testing.T, want, got [][]float32) {
t.Helper()
require.Len(t, got, len(want))
maxAbs, minCos, unequal := 0.0, 1.0, 0
for i := range want {
require.Len(t, want[i], 4096)
require.Len(t, got[i], 4096)
var dot, a2, b2 float64
for j, a := range want[i] {
b := got[i][j]
af, bf := float64(a), float64(b)
require.False(t, math.IsNaN(af) || math.IsNaN(bf) || math.IsInf(af, 0) || math.IsInf(bf, 0))
maxAbs = math.Max(maxAbs, math.Abs(af-bf))
if a != b {
unequal++
}
dot += af * bf
a2 += af * af
b2 += bf * bf
}
require.Greater(t, a2, 0.0)
require.Greater(t, b2, 0.0)
minCos = math.Min(minCos, dot/math.Sqrt(a2*b2))
}
t.Logf("vectors=%d dimensions=4096 unequal_components=%d max_abs_diff=%.9g min_cosine=%.12f",
len(got), unequal, maxAbs, minCos)
// GPU batching may change low-order bits; do not confuse numerical
// equivalence with bit-for-bit reproducibility.
assert.GreaterOrEqual(t, minCos, 0.99999)
assert.LessOrEqual(t, maxAbs, 0.001)
}
+135
View File
@@ -0,0 +1,135 @@
package embedding
import (
"context"
"fmt"
"time"
"academy/internal/logger"
"academy/internal/models/utils/ollama"
ollamaapi "github.com/ollama/ollama/api"
)
// OllamaEmbedder implements text vectorization functionality using Ollama
type OllamaEmbedder struct {
modelName string
truncatePromptTokens int
ollamaService *ollama.OllamaService
dimensions int
modelID string
supportsDimensionOverride bool
EmbedderPooler
}
// OllamaEmbedRequest represents an Ollama embedding request
type OllamaEmbedRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
}
// OllamaEmbedResponse represents an Ollama embedding response
type OllamaEmbedResponse struct {
Embedding []float32 `json:"embedding"`
}
// NewOllamaEmbedder creates a new Ollama embedder
func NewOllamaEmbedder(baseURL,
modelName string,
truncatePromptTokens int,
dimensions int,
modelID string,
pooler EmbedderPooler,
ollamaService *ollama.OllamaService,
) (*OllamaEmbedder, error) {
if modelName == "" {
modelName = "nomic-embed-text"
}
if truncatePromptTokens == 0 {
truncatePromptTokens = 511
}
return &OllamaEmbedder{
modelName: modelName,
truncatePromptTokens: truncatePromptTokens,
ollamaService: ollamaService,
EmbedderPooler: pooler,
dimensions: dimensions,
modelID: modelID,
}, nil
}
// ensureModelAvailable ensures that the model is available
func (e *OllamaEmbedder) ensureModelAvailable(ctx context.Context) error {
logger.GetLogger(ctx).Infof("Ensuring model %s is available", e.modelName)
return e.ollamaService.EnsureModelAvailable(ctx, e.modelName)
}
func (e *OllamaEmbedder) SetSupportsDimensionOverride(supported bool) {
e.supportsDimensionOverride = supported
}
// Embed converts text to vector
func (e *OllamaEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
embedding, err := e.BatchEmbed(ctx, []string{text})
if err != nil {
return nil, fmt.Errorf("failed to embed text: %w", err)
}
if len(embedding) == 0 {
return nil, fmt.Errorf("failed to embed text: %w", err)
}
return embedding[0], nil
}
// BatchEmbed converts multiple texts to vectors in batch
func (e *OllamaEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
// Ensure model is available
if err := e.ensureModelAvailable(ctx); err != nil {
return nil, err
}
// Create request
req := &ollamaapi.EmbedRequest{
Model: e.modelName,
Input: texts,
Options: make(map[string]interface{}),
}
if e.supportsDimensionOverride && e.dimensions > 0 {
req.Dimensions = e.dimensions
}
// Set truncation parameters
if e.truncatePromptTokens > 0 {
req.Options["num_ctx"] = e.truncatePromptTokens
truncate := true
req.Truncate = &truncate
}
// Send request
startTime := time.Now()
resp, err := e.ollamaService.Embeddings(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to get embedding vectors: %w", err)
}
logger.GetLogger(ctx).Debugf("Embedding vector retrieval took: %v", time.Since(startTime))
return resp.Embeddings, nil
}
// GetModelName returns the model name
func (e *OllamaEmbedder) GetModelName() string {
return e.modelName
}
// GetDimensions returns the vector dimensions
func (e *OllamaEmbedder) GetDimensions() int {
return e.dimensions
}
// GetModelID returns the model ID
func (e *OllamaEmbedder) GetModelID() string {
return e.modelID
}
+215
View File
@@ -0,0 +1,215 @@
package embedding
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/models/api"
"academy/internal/models/api/arkembeddings"
"academy/internal/models/api/dashscopeembeddings"
"academy/internal/models/api/googleembeddings"
"academy/internal/models/api/openaiembeddings"
"academy/internal/models/imageprep"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
)
// retryPolicy is the transport-error retry budget; tests shorten it.
var retryPolicy = api.DefaultRetryPolicy
// newRemoteEmbedder resolves the catalog and returns the protocol client for
// the configured model, wrapped in the shared batching layer. It mirrors
// rerank.newReranker: the vendor's facts decide the protocol, the URL and the
// credential, and this function knows no vendor names.
func newRemoteEmbedder(config Config, pooler EmbedderPooler) (Embedder, error) {
if strings.TrimSpace(config.ModelName) == "" {
return nil, fmt.Errorf("model name is required")
}
resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: config.Provider,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeEmbedding,
Extra: config.ExtraConfig,
Override: config.Spec,
TruncatePromptTokens: config.TruncatePromptTokens,
})
if err != nil {
return nil, err
}
if err := validateEmbeddingBaseURL(resolved.BaseURL); err != nil {
return nil, err
}
vendor := resolved.Vendor
endpoint, err := resolved.Endpoint(types.ModelTypeEmbedding, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey, AppID: config.AppID, AppSecret: config.AppSecret},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
Client: newEmbeddingHTTPClient(time.Duration(resolved.Embeddings.RequestTimeout) * time.Second),
})
if err != nil {
return nil, err
}
if endpoint.URL != "" {
if err := validateEmbeddingBaseURL(endpoint.URL); err != nil {
return nil, err
}
}
settings := resolved.Embeddings
// The width is the vendor's field but the operator's decision: a row
// that did not opt in keeps the model's native width even where the
// vendor could narrow it.
dimensions := 0
if config.SupportsDimensionOverride {
dimensions = config.Dimensions
}
retry := retryPolicy()
var client api.Embedder
switch resolved.EmbeddingAPI {
case api.EmbeddingOpenAI:
client = openaiembeddings.New(openaiembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingDashScope:
client = dashscopeembeddings.New(dashscopeembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingArk:
client = arkembeddings.New(arkembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingGoogle:
client = googleembeddings.New(googleembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
default:
return nil, fmt.Errorf("unsupported embedding api %q for provider %s", resolved.EmbeddingAPI, vendor.ID)
}
// Images need both halves: the catalog saying the model maps them into
// its text space, and a protocol that can carry one to this vendor.
var images api.ImageEmbedder
if ie, ok := client.(api.ImageEmbedder); ok && ie.AcceptsImages() && resolved.Spec.AcceptsImages() {
images = ie
}
return &protocolEmbedder{
inner: client,
images: images,
settings: settings,
modelName: config.ModelName,
modelID: config.ModelID,
dimensions: config.Dimensions,
EmbedderPooler: pooler,
}, nil
}
// protocolEmbedder adapts a protocol client to the Embedder interface and
// owns the two things every vendor needs and none of them should implement
// itself: splitting a batch that exceeds the documented per-request ceiling,
// and telling the vendor which side of a search a text is on.
type protocolEmbedder struct {
inner api.Embedder
// images is nil unless the model and the endpoint both take images.
images api.ImageEmbedder
settings api.EmbeddingsSettings
modelName string
modelID string
dimensions int
EmbedderPooler
}
func (e *protocolEmbedder) GetModelName() string { return e.modelName }
func (e *protocolEmbedder) GetModelID() string { return e.modelID }
func (e *protocolEmbedder) GetDimensions() int { return e.dimensions }
func (e *protocolEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
vectors, err := e.BatchEmbed(ctx, []string{text})
if err != nil {
return nil, err
}
return vectors[0], nil
}
func (e *protocolEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
if len(texts) == 0 {
return nil, nil
}
kind := api.EmbedDocument
if types.IsEmbedQuery(ctx) {
kind = api.EmbedQuery
}
batches, err := api.SplitBatches(texts, 0, e.settings.BatchLimits())
if err != nil {
return nil, fmt.Errorf("%s embedding: %w", e.modelName, err)
}
out := make([][]float32, len(texts))
// Serial on purpose. BatchEmbedWithPool and the per-model concurrency
// gate already bound how many requests are in flight; fanning out again
// here would multiply past both, and a one-text-per-request vendor would
// turn every pool chunk into a burst.
for _, batch := range batches {
vectors, err := e.inner.Embed(ctx, batch.Items, kind)
if err != nil {
return nil, err
}
if len(vectors) != len(batch.Items) {
return nil, fmt.Errorf(
"%s embedding: %d vectors for %d inputs", e.modelName, len(vectors), len(batch.Items),
)
}
copy(out[batch.Start:], vectors)
}
return out, nil
}
func (e *protocolEmbedder) AcceptsImages() bool { return e.images != nil }
func (e *protocolEmbedder) ImageLimits() ImageLimits {
return imageprep.LimitsOf(e.settings.ImageInput)
}
// BatchEmbedImages checks every image against the documented limits before
// sending any, so a batch never half-succeeds on an image the vendor was
// always going to refuse, then splits it at the documented images per
// request.
func (e *protocolEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {
if e.images == nil {
return nil, fmt.Errorf("%s: %w", e.modelName, ErrImagesUnsupported)
}
if len(images) == 0 {
return nil, nil
}
for i, img := range images {
if err := e.settings.CheckImage(img); err != nil {
return nil, fmt.Errorf("%s embedding: image %d: %w", e.modelName, i, err)
}
}
kind := api.EmbedDocument
if types.IsEmbedQuery(ctx) {
kind = api.EmbedQuery
}
limit := e.settings.ImageBatchLimit()
out := make([][]float32, len(images))
// Serial for the same reason as BatchEmbed.
for start := 0; start < len(images); start += limit {
batch := images[start:min(start+limit, len(images))]
vectors, err := e.images.EmbedImages(ctx, batch, kind)
if err != nil {
return nil, err
}
if len(vectors) != len(batch) {
return nil, fmt.Errorf(
"%s embedding: %d vectors for %d images", e.modelName, len(vectors), len(batch),
)
}
copy(out[start:], vectors)
}
return out, nil
}
+176
View File
@@ -0,0 +1,176 @@
package embedding
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"academy/internal/models/api"
"academy/internal/models/limiter"
"academy/internal/types"
"github.com/panjf2000/ants/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// An upstream that refuses connections must surface as an error from every
// protocol. The hand-written clients this replaced could each return
// (nil, nil) from their retry loop and dereference a nil response, which took
// the process down instead (Tencent/WeKnora#3484).
func TestUnreachableUpstreamIsAnErrorForEveryProtocol(t *testing.T) {
allowLoopback(t)
saved := retryPolicy
retryPolicy = func() api.RetryPolicy { return api.RetryPolicy{} }
t.Cleanup(func() { retryPolicy = saved })
// A server that is started and closed gives a URL whose port refuses.
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := server.URL
server.Close()
for _, tc := range []struct{ provider, model string }{
{"openai", "text-embedding-3-small"},
{"aliyun", "tongyi-embedding-vision-plus"},
{"volcengine", "doubao-embedding-vision-251215"},
{"gemini", "gemini-embedding-001"},
} {
t.Run(tc.provider, func(t *testing.T) {
embedder, err := newEmbedder(Config{
Source: types.ModelSourceRemote, Provider: tc.provider,
BaseURL: url, ModelName: tc.model, APIKey: "k",
}, nil, nil)
require.NoError(t, err)
_, err = embedder.BatchEmbed(context.Background(), []string{"a"})
assert.Error(t, err)
})
}
}
// A signing vendor without its identity pair would send unsigned requests
// and fail at the far end with a less useful error.
func TestSignedVendorNeedsItsIdentityPair(t *testing.T) {
_, err := newEmbedder(Config{
Source: types.ModelSourceRemote, Provider: "academycloud",
BaseURL: "https://weknora.weixin.qq.com", ModelName: "m", AppSecret: "s",
}, nil, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "AppID is required")
}
func TestModelNameIsRequired(t *testing.T) {
_, err := newEmbedder(Config{Source: types.ModelSourceRemote, Provider: "openai"}, nil, nil)
assert.Error(t, err)
}
// newPooledEmbedder builds the embedder the way NewEmbedder does for a
// background caller: behind the batch pool and the per-model gate.
func newPooledEmbedder(t *testing.T, handler http.HandlerFunc) Embedder {
t.Helper()
allowLoopback(t)
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
pool, err := ants.NewPool(4)
require.NoError(t, err)
t.Cleanup(pool.Release)
raw, err := newEmbedder(Config{
Source: types.ModelSourceRemote, Provider: "generic",
BaseURL: server.URL + "/v1", ModelName: "m", ModelID: "pooled",
}, NewBatchEmbedder(pool), nil)
require.NoError(t, err)
return wrapEmbeddingConcurrency(raw, 1)
}
func TestPoolBatchesAndPreservesOrder(t *testing.T) {
t.Setenv("BATCH_EMBED_SIZE", "2")
var mu sync.Mutex
var sizes []int
embedder := newPooledEmbedder(t, func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
mu.Lock()
sizes = append(sizes, len(body["input"].([]any)))
mu.Unlock()
_, _ = w.Write([]byte(answer(r.URL.Path, body)))
})
got, err := embedder.BatchEmbedWithPool(
context.Background(), embedder, []string{"a", "bb", "ccc", "dddd", "eeeee"})
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}, {3}, {4}, {5}}, got)
assert.Len(t, sizes, 3)
for _, size := range sizes {
assert.LessOrEqual(t, size, 2, "request size violates BATCH_EMBED_SIZE=2")
}
}
func TestPoolHonoursConcurrencyLimit(t *testing.T) {
t.Setenv("BATCH_EMBED_SIZE", "1")
limiter.SetGovernor(limiter.NewLocalLimiter(), 10)
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
entered := make(chan struct{}, 2)
release := make(chan struct{})
embedder := newPooledEmbedder(t, func(w http.ResponseWriter, _ *http.Request) {
entered <- struct{}{}
<-release
_, _ = fmt.Fprint(w, `{"data":[{"index":0,"embedding":[1]}]}`)
})
ctx := types.WithBackgroundTask(context.Background())
var wg sync.WaitGroup
var once sync.Once
unblock := func() { once.Do(func() { close(release) }) }
t.Cleanup(func() { unblock(); wg.Wait() })
errs := make(chan error, 2)
// Separate callers stand for simultaneous batches sharing one model.
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
_, err := embedder.BatchEmbedWithPool(ctx, embedder, []string{"x"})
errs <- err
}()
}
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("first request did not reach the upstream")
}
select {
case <-entered:
t.Error("two requests reached the upstream at once with a model limit of 1")
case <-time.After(150 * time.Millisecond):
}
unblock()
for range 2 {
select {
case err := <-errs:
assert.NoError(t, err)
case <-time.After(2 * time.Second):
t.Fatal("pooled embedding did not complete after release")
}
}
}
// Embedding a query is a single call that must carry the query mark all the
// way down; the retrieval pipeline reaches it through Embed, not BatchEmbed.
func TestEmbedCarriesTheQueryMark(t *testing.T) {
up := newUpstream(t)
embedder, err := newEmbedder(Config{
Source: types.ModelSourceRemote, Provider: "nvidia",
BaseURL: up.url + "/v1", ModelName: "nvidia/nemotron-3-embed-1b", APIKey: "k",
}, nil, nil)
require.NoError(t, err)
_, err = embedder.Embed(types.WithEmbedQuery(context.Background()), "what is it")
require.NoError(t, err)
_, err = embedder.Embed(context.Background(), strings.Repeat("passage ", 3))
require.NoError(t, err)
require.Len(t, up.requests, 2)
assert.Equal(t, "query", up.requests[0].body["input_type"])
assert.Equal(t, "passage", up.requests[1].body["input_type"])
}
+39
View File
@@ -0,0 +1,39 @@
package embedding
import (
"fmt"
"net/http"
"time"
secutils "academy/internal/utils"
)
// sharedEmbeddingHTTPTransport keeps a single SSRF-safe connection pool for
// all embedding clients. Embedders are recreated as model configuration changes,
// but their outbound connections can be safely reused across client instances,
// so the transport (and its keep-alive pool) is built once at package load.
var sharedEmbeddingHTTPTransport = secutils.NewSSRFSafeTransport(
secutils.DefaultSSRFSafeHTTPClientConfig(),
)
// validateEmbeddingBaseURL checks that a resolved embedding API base URL is safe
// for outbound requests. Empty URLs are allowed (callers apply provider defaults).
func validateEmbeddingBaseURL(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
}
// newEmbeddingHTTPClient returns an HTTP client with connection-level SSRF
// protection and redirect validation, aligned with internal/models/chat/transport.go.
// All clients share sharedEmbeddingHTTPTransport so keep-alive connections are
// pooled globally, while each keeps its own timeout.
func newEmbeddingHTTPClient(timeout time.Duration) *http.Client {
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
cfg.Timeout = timeout
return secutils.NewSSRFSafeHTTPClientWithTransport(cfg, sharedEmbeddingHTTPTransport)
}
@@ -0,0 +1,71 @@
package embedding
import (
"net/http"
"strings"
"testing"
"time"
"academy/internal/types"
secutils "academy/internal/utils"
)
func TestNewEmbeddingHTTPClient_ReusesTransport(t *testing.T) {
firstTimeout := 15 * time.Second
secondTimeout := 45 * time.Second
first := newEmbeddingHTTPClient(firstTimeout)
second := newEmbeddingHTTPClient(secondTimeout)
if first == second {
t.Fatal("expected distinct HTTP clients")
}
firstGuard, ok := first.Transport.(*secutils.SSRFValidatingRoundTripper)
if !ok {
t.Fatalf("expected SSRF-validating transport, got %T", first.Transport)
}
secondGuard, ok := second.Transport.(*secutils.SSRFValidatingRoundTripper)
if !ok {
t.Fatalf("expected SSRF-validating transport, got %T", second.Transport)
}
if firstGuard.Base != secondGuard.Base {
t.Fatal("expected embedding HTTP clients to share a base transport")
}
if firstGuard.Base != http.RoundTripper(sharedEmbeddingHTTPTransport) {
t.Fatal("expected embedding HTTP client to use the shared transport")
}
if first.Timeout != firstTimeout {
t.Fatalf("unexpected first client timeout: got %v, want %v", first.Timeout, firstTimeout)
}
if second.Timeout != secondTimeout {
t.Fatalf("unexpected second client timeout: got %v, want %v", second.Timeout, secondTimeout)
}
}
func TestValidateEmbeddingBaseURL_RejectsLoopback(t *testing.T) {
err := validateEmbeddingBaseURL("http://169.254.169.254/latest/meta-data")
if err == nil {
t.Fatal("expected SSRF error for link-local metadata URL")
}
if !strings.Contains(err.Error(), "SSRF") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestValidateEmbeddingBaseURL_AllowsEmpty(t *testing.T) {
if err := validateEmbeddingBaseURL(""); err != nil {
t.Fatalf("empty base URL should be allowed: %v", err)
}
}
func TestNewEmbedder_RejectsPrivateBaseURL(t *testing.T) {
_, err := NewEmbedder(Config{
Source: types.ModelSourceRemote,
Provider: "openai",
BaseURL: "http://169.254.169.254/latest/meta-data",
ModelName: "text-embedding-3-small",
APIKey: "test-key",
}, nil, nil)
if err == nil {
t.Fatal("expected SSRF rejection for link-local metadata URL")
}
}
+127
View File
@@ -0,0 +1,127 @@
package embedding
import (
"context"
"strings"
"testing"
"academy/internal/models/api"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
// WeMM's vLLM template appends the dedicated <embedding> pooling token.
// Both retrieval sides and images must use that template, including when
// vLLM exposes the local model path instead of the Hugging Face repository ID.
// https://huggingface.co/tencent/WeMM-Embedding-2B/blob/main/embedding_chat_template.jinja
func TestWeMMVLLMPresets(t *testing.T) {
vendor, ok := modelruntime.Get("generic")
require.True(t, ok)
listed := vendor.ModelsByType(types.ModelTypeEmbedding)
for _, tc := range []struct {
size string
dims int
}{{"2B", 2048}, {"4B", 2560}, {"9B", 4096}} {
short := "WeMM-Embedding-" + tc.size
id := "tencent/" + short
t.Run(tc.size, func(t *testing.T) {
visible := false
for _, entry := range listed {
if entry.ID == id {
visible = true
require.Equal(t, tc.dims, entry.Dimension)
}
}
require.True(t, visible, "preset must appear in the embedding picker")
for _, name := range []string{id, short, "/models/" + short, strings.ToLower(id)} {
t.Run(name, func(t *testing.T) {
resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: "generic", Model: name, ModelType: types.ModelTypeEmbedding,
})
require.NoError(t, err)
require.True(t, resolved.Cataloged)
require.Equal(t, tc.dims, resolved.Spec.Dimension)
require.Equal(t, api.EmbeddingOpenAI, resolved.EmbeddingAPI)
require.Equal(t, []string{"text", "image"}, resolved.Spec.Input)
require.True(t, resolved.Embeddings.BatchMessages)
require.Equal(t, 5, resolved.Embeddings.ImageBatchLimit())
up := newUpstream(t)
e, err := NewEmbedder(Config{
Source: types.ModelSourceRemote, Provider: "generic", ModelName: name,
BaseURL: up.url + "/v1", Dimensions: tc.dims, TruncatePromptTokens: 511,
}, nil, nil)
require.NoError(t, err)
require.Equal(t, tc.dims, e.GetDimensions())
ie, ok := AsImageEmbedder(e)
require.True(t, ok, "images must work without a row override")
contexts := []context.Context{context.Background(), types.WithEmbedQuery(context.Background())}
for _, ctx := range contexts {
vectors, err := e.BatchEmbed(ctx, []string{"ab", "c"})
require.NoError(t, err)
require.Equal(t, [][]float32{{2}, {1}}, vectors)
}
vectors, err := ie.BatchEmbedImages(context.Background(), pngs(6))
require.NoError(t, err)
require.Equal(t, [][]float32{{1}, {2}, {3}, {4}, {5}, {6}}, vectors)
conversation := func(part map[string]any) []any {
return []any{map[string]any{"role": "user", "content": []any{part}}}
}
textBatch := []any{
conversation(map[string]any{"type": "text", "text": "ab"}),
conversation(map[string]any{"type": "text", "text": "c"}),
}
imageBatch := []any{}
for _, img := range pngs(5) {
imageBatch = append(imageBatch, conversation(map[string]any{
"type": "image_url", "image_url": map[string]any{"url": img.DataURI()},
}))
}
messages := []any{textBatch, textBatch, imageBatch, conversation(map[string]any{
"type": "image_url", "image_url": map[string]any{"url": pngs(6)[5].DataURI()},
})}
require.Len(t, up.requests, len(messages), "batch texts and split six images into five and one")
for i, message := range messages {
require.Equal(t, "/v1/embeddings", up.requests[i].path)
require.Equal(t, map[string]any{
"model": name, "encoding_format": "float",
"messages": message,
}, up.requests[i].body, "no raw input, legacy truncation, or extra image prompt")
}
})
}
})
}
}
// vLLM reads matryoshka_dimensions from WeMM's config and truncates before
// normalizing. Text and image requests must use the same requested width.
func TestWeMMDimensionOverride(t *testing.T) {
for _, size := range []string{"2B", "4B", "9B"} {
t.Run(size, func(t *testing.T) {
up := newUpstream(t)
e, err := NewEmbedder(Config{
Source: types.ModelSourceRemote, Provider: "generic",
ModelName: "tencent/WeMM-Embedding-" + size, BaseURL: up.url + "/v1",
Dimensions: 1024, SupportsDimensionOverride: true,
}, nil, nil)
require.NoError(t, err)
_, err = e.Embed(types.WithEmbedQuery(context.Background()), "query")
require.NoError(t, err)
ie, ok := AsImageEmbedder(e)
require.True(t, ok)
_, err = ie.BatchEmbedImages(context.Background(), pngs(2))
require.NoError(t, err)
require.Len(t, up.requests, 2)
for _, req := range up.requests {
require.Equal(t, float64(1024), req.body["dimensions"])
require.NotContains(t, req.body, "truncate_prompt_tokens")
require.NotContains(t, req.body, "add_special_tokens")
require.NotContains(t, req.body, "add_generation_prompt")
require.NotContains(t, req.body, "use_activation")
}
})
}
}
+509
View File
@@ -0,0 +1,509 @@
package embedding
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"unicode/utf8"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recorded is one request as the upstream saw it.
type recorded struct {
path string
query string
header http.Header
body map[string]any
}
// upstream is a stand-in vendor. It answers in whichever shape the request's
// path asks for, one vector per input whose single value is the input's
// length in runes, so that a test can tell which vector went where.
type upstream struct {
mu sync.Mutex
requests []recorded
url string
}
func allowLoopback(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func newUpstream(t *testing.T) *upstream {
t.Helper()
allowLoopback(t)
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.URL.RawQuery, r.Header.Clone(), body})
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(answer(r.URL.Path, body)))
}))
t.Cleanup(server.Close)
u.url = server.URL
return u
}
func runeLen(v any) int { return utf8.RuneCountInString(v.(string)) }
// itemLen is the length of one input item whatever its shape: the runes of
// a text, or the decoded bytes of an inline image. Images in these tests
// differ in size, so the vector still tells which input it answers.
func itemLen(v any) int {
item, ok := v.(map[string]any)
if !ok {
return runeLen(v)
}
switch {
case item["text"] != nil:
return runeLen(item["text"])
case item["image"] != nil:
return dataURILen(item["image"].(string))
case item["image_url"] != nil:
return dataURILen(item["image_url"].(map[string]any)["url"].(string))
case item["inlineData"] != nil:
data, _ := base64.StdEncoding.DecodeString(item["inlineData"].(map[string]any)["data"].(string))
return len(data)
}
panic(fmt.Sprintf("unrecognised input item %v", item))
}
func dataURILen(uri string) int {
_, encoded, ok := strings.Cut(uri, ";base64,")
if !ok {
panic("not a base64 data URI: " + uri)
}
data, _ := base64.StdEncoding.DecodeString(encoded)
return len(data)
}
// answer replies in the protocol the path belongs to. The OpenAI and
// DashScope shapes are answered in reverse order so that placement by index
// is exercised on every request.
func answer(path string, body map[string]any) string {
var parts []string
switch {
case strings.HasSuffix(path, ":batchEmbedContents"):
for _, req := range body["requests"].([]any) {
part := req.(map[string]any)["content"].(map[string]any)["parts"].([]any)[0]
parts = append(parts, fmt.Sprintf(`{"values":[%d]}`, itemLen(part)))
}
return `{"embeddings":[` + strings.Join(parts, ",") + `]}`
case strings.HasSuffix(path, "/multimodal-embedding"):
contents := body["input"].(map[string]any)["contents"].([]any)
for i := len(contents) - 1; i >= 0; i-- {
n := itemLen(contents[i])
parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d],"type":"text"}`, i, n))
}
return `{"output":{"embeddings":[` + strings.Join(parts, ",") + `]}}`
case strings.HasSuffix(path, "/embeddings/multimodal"):
n := itemLen(body["input"].([]any)[0])
return fmt.Sprintf(`{"data":{"embedding":[%d],"object":"embedding"}}`, n)
case body["messages"] != nil:
messages := body["messages"].([]any)
conversations := []any{messages}
if _, batched := messages[0].([]any); batched {
conversations = messages
}
for i := len(conversations) - 1; i >= 0; i-- {
turn := conversations[i].([]any)[0].(map[string]any)
n := itemLen(turn["content"].([]any)[0])
parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, n))
}
return `{"data":[` + strings.Join(parts, ",") + `]}`
default:
input := body["input"].([]any)
for i := len(input) - 1; i >= 0; i-- {
parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, itemLen(input[i])))
}
return `{"data":[` + strings.Join(parts, ",") + `]}`
}
}
func texts(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = strings.Repeat("x", i+1)
}
return out
}
func strs(in []string) []any {
out := make([]any, len(in))
for i, s := range in {
out[i] = s
}
return out
}
// TestEmbeddingWireFormatPerVendor pins, for every embedding vendor in the
// catalog, the request the factory actually sends: URL, credential and the
// complete body. Each expectation traces to the vendor's reference as cited
// in its vendor.go; a field appears here only if that page documents it.
func TestEmbeddingWireFormatPerVendor(t *testing.T) {
three := []string{"a", "bb", "ccc"}
openAIBody := func(model string, input []string, extra map[string]any) map[string]any {
body := map[string]any{"model": model, "input": strs(input)}
for k, v := range extra {
body[k] = v
}
return body
}
arkBody := func(model, text string, extra map[string]any) map[string]any {
body := map[string]any{
"model": model,
"input": []any{map[string]any{"type": "text", "text": text}},
}
for k, v := range extra {
body[k] = v
}
return body
}
dashBody := func(model string, input []string, extra map[string]any) map[string]any {
contents := make([]any, len(input))
for i, s := range input {
contents[i] = map[string]any{"text": s}
}
body := map[string]any{"model": model, "input": map[string]any{"contents": contents}}
for k, v := range extra {
body[k] = v
}
return body
}
const dashPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
cases := []struct {
name string
provider string
model string
base string // appended to the upstream URL
extra map[string]string
override bool // supports_dimension_override with dimension 256
truncate int // embedding_parameters.truncate_prompt_tokens
query bool
texts []string
appID string
wantPath string
wantQuery string
wantAuth [2]string
wantRequests int
wantBody map[string]any // the first request's body, exactly
}{
{
name: "openai sends dimensions where the row opted in", provider: "openai",
model: "text-embedding-3-small", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-3-small", three,
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
},
{
name: "openai keeps the native width without the opt-in", provider: "openai",
model: "text-embedding-3-small", base: "/v1",
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-3-small", three, map[string]any{"encoding_format": "float"}),
},
{
name: "ada-002 has a fixed width", provider: "openai",
model: "text-embedding-ada-002", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-ada-002", three, map[string]any{"encoding_format": "float"}),
},
{
name: "generic keeps the historical truncation budget", provider: "generic",
model: "bge-m3", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("bge-m3", three, map[string]any{
"encoding_format": "float", "dimensions": float64(256), "truncate_prompt_tokens": float64(511),
}),
},
{
name: "generic honours the row's truncation budget", provider: "generic",
model: "bge-m3", base: "/v1", truncate: 256,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("bge-m3", three, map[string]any{
"encoding_format": "float", "truncate_prompt_tokens": float64(256),
}),
},
{
name: "gpustack is a vLLM runtime", provider: "gpustack",
model: "bge-m3", base: "/v1",
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("bge-m3", three, map[string]any{
"encoding_format": "float", "truncate_prompt_tokens": float64(511),
}),
},
{
name: "zhipu documents no encoding_format", provider: "zhipu",
model: "embedding-3", base: "/api/paas/v4", override: true, truncate: 300,
wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("embedding-3", three, map[string]any{"dimensions": float64(256)}),
},
{
name: "zhipu embedding-2 is fixed at 1024", provider: "zhipu",
model: "embedding-2", base: "/api/paas/v4", override: true,
wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("embedding-2", three, nil),
},
{
name: "jina truncates as it always has and sends no task", provider: "jina",
model: "jina-embeddings-v3", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("jina-embeddings-v3", three,
map[string]any{"dimensions": float64(256), "truncate": true}),
},
{
name: "nvidia embeds documents as passages", provider: "nvidia",
model: "nvidia/nemotron-3-embed-1b", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("nvidia/nemotron-3-embed-1b", three, map[string]any{
"encoding_format": "float", "input_type": "passage", "truncate": "END",
}),
},
{
name: "nvidia embeds a search query as a query", provider: "nvidia",
model: "nvidia/nemotron-3-embed-1b", base: "/v1", query: true, texts: []string{"q"},
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("nvidia/nemotron-3-embed-1b", []string{"q"}, map[string]any{
"encoding_format": "float", "input_type": "query", "truncate": "END",
}),
},
{
name: "hunyuan takes model and input only", provider: "hunyuan",
model: "hunyuan-embedding", base: "/v1", override: true, truncate: 300,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("hunyuan-embedding", three, nil),
},
{
name: "modelscope documents nothing beyond the baseline", provider: "modelscope",
model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three, nil),
},
{
name: "novita documents encoding_format only", provider: "novita",
model: "baai/bge-m3", base: "/openai/v1", override: true,
wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("baai/bge-m3", three, map[string]any{"encoding_format": "float"}),
},
{
name: "siliconflow narrows only the Qwen3 series", provider: "siliconflow",
model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three,
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
},
{
name: "siliconflow bge-m3 has a fixed width", provider: "siliconflow",
model: "BAAI/bge-m3", base: "/v1", override: true,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("BAAI/bge-m3", three, map[string]any{"encoding_format": "float"}),
},
{
name: "siliconflow takes up to thirty-two texts", provider: "siliconflow",
model: "BAAI/bge-m3", base: "/v1", texts: texts(33), wantRequests: 2,
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("BAAI/bge-m3", texts(32), map[string]any{"encoding_format": "float"}),
},
{
name: "aliyun text-embedding-v2 has a fixed width and takes 25", provider: "aliyun",
model: "text-embedding-v2", base: "/compatible-mode/v1", override: true,
texts: texts(26), wantRequests: 2,
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-v2", texts(25), map[string]any{"encoding_format": "float"}),
},
{
name: "openrouter", provider: "openrouter",
model: "openai/text-embedding-3-small", base: "/api/v1", override: true,
wantPath: "/api/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("openai/text-embedding-3-small", three,
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
},
{
name: "qianfan takes up to sixteen texts", provider: "qianfan",
model: "embedding-v1", base: "/v2", texts: texts(17), wantRequests: 2,
wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("embedding-v1", texts(16), map[string]any{"encoding_format": "float"}),
},
{
name: "qianfan tao-8k takes one text", provider: "qianfan",
model: "tao-8k", base: "/v2", wantRequests: 3,
wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("tao-8k", []string{"a"}, map[string]any{"encoding_format": "float"}),
},
{
name: "aliyun text models use the compatible endpoint", provider: "aliyun",
model: "text-embedding-v4", base: "/compatible-mode/v1", override: true,
texts: texts(12), wantRequests: 2,
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-v4", texts(10),
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
},
{
name: "aliyun text models from a bare host", provider: "aliyun",
model: "text-embedding-v4",
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("text-embedding-v4", three, map[string]any{"encoding_format": "float"}),
},
{
name: "aliyun text model not yet in the catalog", provider: "aliyun",
model: "qwen3.8-text-embedding", base: "/compatible-mode/v1",
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: openAIBody("qwen3.8-text-embedding", three, map[string]any{"encoding_format": "float"}),
},
{
name: "aliyun vision plus uses the native API at a fixed width", provider: "aliyun",
model: "tongyi-embedding-vision-plus", base: "/compatible-mode/v1", override: true,
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: dashBody("tongyi-embedding-vision-plus", three, nil),
},
{
name: "aliyun qwen3-vl-embedding narrows under parameters", provider: "aliyun",
model: "qwen3-vl-embedding", base: "/compatible-mode/v1", override: true,
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: dashBody("qwen3-vl-embedding", three,
map[string]any{"parameters": map[string]any{"dimension": float64(256)}}),
},
{
name: "aliyun qwen2.5-vl-embedding fuses, so one text per request", provider: "aliyun",
model: "qwen2.5-vl-embedding", base: "/compatible-mode/v1", wantRequests: 3,
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: dashBody("qwen2.5-vl-embedding", []string{"a"}, nil),
},
{
name: "volcengine fuses, so one text per request", provider: "volcengine",
model: "doubao-embedding-vision-251215", base: "/api/v3/embeddings/multimodal",
override: true, wantRequests: 3,
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: arkBody("doubao-embedding-vision-251215", "a",
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
},
{
name: "volcengine from the chat base URL", provider: "volcengine",
model: "doubao-embedding-vision-251215", base: "/api/v3", wantRequests: 3,
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),
},
{
name: "volcengine from a bare host", provider: "volcengine",
model: "doubao-embedding-vision-251215", wantRequests: 3,
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),
},
{
name: "volcengine retired text models keep their own endpoint", provider: "volcengine",
model: "doubao-embedding-text-240715", base: "/api/v3/embeddings/multimodal", override: true,
wantPath: "/api/v3/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
// The archived reference lists encoding_format too, and no dimensions.
wantBody: openAIBody("doubao-embedding-text-240715", three, map[string]any{"encoding_format": "float"}),
},
{
name: "gemini posts to the native method", provider: "gemini",
model: "gemini-embedding-001", base: "/v1beta", override: true, texts: []string{"a"},
wantPath: "/v1beta/models/gemini-embedding-001:batchEmbedContents",
wantAuth: [2]string{"X-Goog-Api-Key", "k"},
wantBody: map[string]any{"requests": []any{map[string]any{
"model": "models/gemini-embedding-001",
"content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},
"embedContentConfig": map[string]any{"outputDimensionality": float64(256)},
}}},
},
{
name: "gemini rows on the OpenAI facade still embed natively", provider: "gemini",
model: "gemini-embedding-2", base: "/v1beta/openai", texts: []string{"a"},
wantPath: "/v1beta/models/gemini-embedding-2:batchEmbedContents",
wantAuth: [2]string{"X-Goog-Api-Key", "k"},
wantBody: map[string]any{"requests": []any{map[string]any{
"model": "models/gemini-embedding-2",
"content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},
}}},
},
{
name: "azure without api_version uses the v1 data plane", provider: "azure_openai",
model: "my-deployment",
wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Api-Key", "k"},
wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),
},
{
name: "azure with api_version uses the deployments path", provider: "azure_openai",
model: "my-deployment", extra: map[string]string{"api_version": "2024-10-21"},
wantPath: "/openai/deployments/my-deployment/embeddings", wantQuery: "api-version=2024-10-21",
wantAuth: [2]string{"Api-Key", "k"},
wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),
},
{
name: "academycloud signs its own path", provider: "academycloud",
model: "cloud-embedding", appID: "app",
wantPath: "/api/v1/embeddings", wantAuth: [2]string{"X-Appid", "app"},
wantBody: openAIBody("cloud-embedding", three, nil),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
up := newUpstream(t)
input := tc.texts
if input == nil {
input = three
}
config := Config{
Source: types.ModelSourceRemote,
Provider: tc.provider,
BaseURL: up.url + tc.base,
ModelName: tc.model,
APIKey: "k",
Dimensions: 256,
SupportsDimensionOverride: tc.override,
TruncatePromptTokens: tc.truncate,
ExtraConfig: tc.extra,
AppID: tc.appID,
AppSecret: "secret",
}
embedder, err := newEmbedder(config, nil, nil)
require.NoError(t, err)
ctx := context.Background()
if tc.query {
ctx = types.WithEmbedQuery(ctx)
}
got, err := embedder.BatchEmbed(ctx, input)
require.NoError(t, err)
want := make([][]float32, len(input))
for i, s := range input {
want[i] = []float32{float32(utf8.RuneCountInString(s))}
}
assert.Equal(t, want, got, "every vector must come back in its own slot")
wantRequests := tc.wantRequests
if wantRequests == 0 {
wantRequests = 1
}
require.Len(t, up.requests, wantRequests)
first := up.requests[0]
assert.Equal(t, tc.wantPath, first.path)
assert.Equal(t, tc.wantQuery, first.query)
assert.Equal(t, tc.wantAuth[1], first.header.Get(tc.wantAuth[0]))
assert.Equal(t, tc.wantBody, first.body)
})
}
}