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

+93
View File
@@ -0,0 +1,93 @@
package asr
import (
"context"
"strings"
"academy/internal/types"
)
// Segment represents a transcribed segment with timestamps.
type Segment struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Text string `json:"text"`
}
// TranscriptionResult holds the full text and its segments.
type TranscriptionResult struct {
Text string `json:"text"`
Segments []Segment `json:"segments,omitempty"`
// Duration is the audio length in seconds when the vendor reports it,
// which several do without segments; 0 when unknown.
Duration float64 `json:"duration,omitempty"`
}
type languageKey struct{}
// WithLanguage attaches the operator's language hint (for example "zh") to
// a transcription. Empty and "auto" mean auto-detection, which is every
// vendor's default, and send nothing.
func WithLanguage(ctx context.Context, language string) context.Context {
return context.WithValue(ctx, languageKey{}, language)
}
func languageFrom(ctx context.Context) string {
language, _ := ctx.Value(languageKey{}).(string)
language = strings.TrimSpace(language)
if strings.EqualFold(language, "auto") {
return ""
}
return language
}
// ASR defines the interface for Automatic Speech Recognition model operations.
type ASR interface {
// Transcribe sends audio bytes to the ASR model and returns the transcribed text and segments.
Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error)
GetModelName() string
GetModelID() string
}
// Config holds the configuration needed to create an ASR instance.
type Config struct {
Source types.ModelSource
BaseURL string
ModelName string
APIKey string
ModelID string
// Provider is the vendor id stored on the row; empty detects it from
// BaseURL.
Provider string
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
ExtraConfig map[string]string
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
}
// ConfigFromModel 根据 types.Model 构造 asr.Config。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// 当前 ASR 不涉及 AcademyCloud 凭证,所以签名不含 appID/appSecret。
func ConfigFromModel(m *types.Model) *Config {
if m == nil {
return nil
}
return &Config{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
Spec: m.Parameters.Spec,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
}
}
// NewASR creates an ASR instance based on the provided configuration.
func NewASR(config *Config) (ASR, error) {
a, err := newASR(config)
return wrapASRLangfuse(a, err)
}
@@ -0,0 +1,95 @@
package asr
import (
"context"
"net/url"
"strings"
"testing"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestEveryCatalogASRTransport(t *testing.T) {
for _, v := range modelruntime.List() {
for _, m := range v.Models() {
if m.Type != types.ModelTypeASR {
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) {
address, _, calls := upstream(t)
base, err := url.Parse(v.GetDefaultURL(types.ModelTypeASR))
require.NoError(t, err)
client, err := newASR(
&Config{
Source: types.ModelSourceRemote,
Provider: v.ID,
ModelName: name,
ModelID: "row-id",
BaseURL: address + base.Path,
APIKey: "row-key",
},
)
if strings.Contains(string(m.Compat), "unsupported_reason") {
require.Error(t, err)
require.Zero(t, calls.Load())
return
}
require.NoError(t, err)
result, err := client.Transcribe(
WithLanguage(
context.Background(),
"zh",
),
[]byte(
"RIFF",
),
"sample.wav",
)
require.NoError(t, err)
require.Equal(t, "hello", strings.TrimSpace(result.Text))
require.EqualValues(t, 1, calls.Load())
require.Equal(t, "row-id", client.GetModelID())
})
}
}
}
}
func TestStoredASRSpecReachesWire(t *testing.T) {
address, got, _ := upstream(t)
row := &types.Model{
ID: "stable-id",
Name: "custom",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "generic",
BaseURL: address,
APIKey: "model-key",
Spec: &types.ModelSpecOverride{
Compat: map[string]any{
"path": "/custom-transcriptions",
"response_format": "verbose_json",
"language_param": "header",
},
},
},
}
client, err := newASR(ConfigFromModel(row))
require.NoError(t, err)
result, err := client.Transcribe(WithLanguage(context.Background(), "zh"), []byte("RIFF"), "sample.wav")
require.NoError(t, err)
require.Equal(t, "/custom-transcriptions", got.path)
require.Equal(t, "verbose_json", got.fields["response_format"])
require.Equal(t, "zh", got.language)
require.Len(t, result.Segments, 1)
row.Parameters.Spec.Compat = map[string]any{"misspelled_option": true}
_, err = newASR(ConfigFromModel(row))
require.ErrorContains(t, err, "unknown field")
}
@@ -0,0 +1,43 @@
package asr
import (
"testing"
"academy/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "asr-1",
Name: "whisper-1",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk",
Provider: "siliconflow",
ExtraConfig: map[string]string{"remote_model_name": "r"},
CustomHeaders: map[string]string{"X": "y"},
},
}
cfg := ConfigFromModel(m)
if cfg == nil || cfg.ModelID != "asr-1" || cfg.ModelName != "whisper-1" {
t.Fatalf("identity mismatch: %+v", cfg)
}
if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk" {
t.Errorf("connection fields mismatch: %+v", cfg)
}
// The vendor decides the wire format; without it every row resolves to
// the generic runtime.
if cfg.Provider != "siliconflow" || cfg.ExtraConfig["remote_model_name"] != "r" {
t.Errorf("vendor fields not propagated: %+v", cfg)
}
if cfg.CustomHeaders["X"] != "y" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
}
func TestConfigFromModel_Nil(t *testing.T) {
if got := ConfigFromModel(nil); got != nil {
t.Fatalf("expected nil, got %+v", got)
}
}
+85
View File
@@ -0,0 +1,85 @@
package asr
import (
"context"
"academy/internal/tracing/langfuse"
)
// langfuseASR wraps an ASR implementation and reports each Transcribe call
// as a Langfuse generation observation. Audio bytes are not uploaded — we
// record file name, audio size and duration (as the vendor reports it, or
// from segment end times)
// so usage can be billed by second/minute, which is how most ASR providers
// price their services.
type langfuseASR struct {
inner ASR
}
func (l *langfuseASR) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseASR) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Transcribe(ctx, audioBytes, fileName)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "asr.transcribe",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"file_name": fileName,
"audio_size": len(audioBytes),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"audio_size": len(audioBytes),
},
})
result, err := l.inner.Transcribe(genCtx, audioBytes, fileName)
output := map[string]interface{}{}
var duration float64
if result != nil {
output["text"] = result.Text
output["segment_count"] = len(result.Segments)
// The vendor's own figure when it gives one; otherwise the end of
// the last segment, which only verbose replies carry.
duration = result.Duration
if n := len(result.Segments); duration == 0 && n > 0 {
duration = result.Segments[n-1].End
}
if duration > 0 {
output["duration_seconds"] = duration
}
}
// ASR is billed per second; we emit the audio duration (when available)
// in the "Output" side of usage so users can configure per-model pricing
// in Langfuse (e.g. $0.006 per minute for Whisper-1).
var usage *langfuse.TokenUsage
if duration > 0 {
seconds := int(duration + 0.5)
usage = &langfuse.TokenUsage{
Output: seconds,
Total: seconds,
Unit: "SECONDS",
}
}
gen.Finish(output, usage, err)
return result, err
}
// wrapASRLangfuse applies the Langfuse decorator when the manager is enabled.
func wrapASRLangfuse(a ASR, err error) (ASR, error) {
if err != nil || a == nil {
return a, err
}
if !langfuse.GetManager().Enabled() {
return a, nil
}
return &langfuseASR{inner: a}, nil
}
+163
View File
@@ -0,0 +1,163 @@
package asr
import (
"context"
"fmt"
"path/filepath"
"slices"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/models/api/openaichataudio"
"academy/internal/models/api/openaitranscriptions"
"academy/internal/models/providers"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
)
// retryPolicy is the transport-error retry budget, which is none. The
// knowledge pipeline retries a failed transcription as a whole task, and a
// client-level retry on top would turn one hung 300-second upload into
// several.
var retryPolicy = func() api.RetryPolicy { return api.RetryPolicy{} }
// newASR resolves the catalog and returns the protocol client for the
// configured model. It mirrors rerank.newReranker and
// embedding.newRemoteEmbedder: the vendor's facts decide the protocol, the
// URL and the credential, and this function knows no vendor names.
func newASR(config *Config) (ASR, error) {
if config == nil {
return nil, fmt.Errorf("asr config is nil")
}
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.ModelTypeASR,
Extra: config.ExtraConfig,
Override: config.Spec,
})
if err != nil {
return nil, err
}
// A vendor that does not declare speech recognition has not been checked
// for it, and its Endpoint hook may still compute a path — Azure's does.
// A row that named the vendor is refused; a row that named none and was
// matched by its URL is what the pre-catalog client served: an
// OpenAI-compatible endpoint at that URL.
if !resolved.Vendor.SupportsType(types.ModelTypeASR) {
if strings.TrimSpace(config.Provider) != "" {
return nil, fmt.Errorf("%s does not offer speech recognition in this build", resolved.Vendor.Name)
}
resolved, err = modelruntime.Resolve(modelruntime.Ref{
Provider: providers.GenericID,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeASR,
Extra: config.ExtraConfig,
Override: config.Spec,
})
if err != nil {
return nil, err
}
}
if err := validateASRBaseURL(resolved.BaseURL); err != nil {
return nil, err
}
vendor := resolved.Vendor
endpoint, err := resolved.Endpoint(types.ModelTypeASR, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
Client: newASRHTTPClient(time.Duration(resolved.Transcriptions.RequestTimeout) * time.Second),
})
if err != nil {
return nil, err
}
if endpoint.URL != "" {
if err := validateASRBaseURL(endpoint.URL); err != nil {
return nil, err
}
}
settings := resolved.Transcriptions
var client api.Transcriber
switch resolved.TranscriptionAPI {
case api.TranscriptionOpenAI:
client = openaitranscriptions.New(openaitranscriptions.Config{
Endpoint: endpoint, Settings: settings, Retry: retryPolicy(),
})
case api.TranscriptionChatAudio:
client = openaichataudio.New(openaichataudio.Config{
Endpoint: endpoint, Settings: settings, Retry: retryPolicy(),
})
default:
return nil, fmt.Errorf("unsupported transcription api %q for provider %s",
resolved.TranscriptionAPI, vendor.ID)
}
return &protocolASR{
inner: client,
settings: settings,
vendor: vendor.Name,
endpoint: resolved.BaseURL,
modelName: config.ModelName,
modelID: config.ModelID,
}, nil
}
// protocolASR adapts a protocol client to the ASR interface and refuses an
// upload the vendor has documented it will not take, before sending it.
type protocolASR struct {
inner api.Transcriber
settings api.TranscriptionsSettings
vendor string
endpoint string
modelName string
modelID string
}
func (a *protocolASR) GetModelName() string { return a.modelName }
func (a *protocolASR) GetModelID() string { return a.modelID }
func (a *protocolASR) Transcribe(ctx context.Context, audio []byte, fileName string) (*TranscriptionResult, error) {
if len(audio) == 0 {
return nil, fmt.Errorf("audio bytes are empty")
}
if limit := a.settings.MaxFileBytes; limit > 0 && len(audio) > limit {
return nil, fmt.Errorf("%s transcription: the audio is %.1f MB; %s accepts at most %d MB per file",
a.modelName, float64(len(audio))/(1<<20), a.vendor, limit>>20)
}
// The server identifies the format from the extension.
if fileName == "" {
fileName = "audio.mp3"
}
if formats := a.settings.Formats; len(formats) > 0 {
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(fileName)), ".")
if !slices.Contains(formats, ext) {
return nil, fmt.Errorf("%s transcription: %s accepts %s audio, not %q",
a.modelName, a.vendor, strings.Join(formats, "/"), fileName)
}
}
logger.Infof(ctx, "[ASR] transcribing model=%s endpoint=%s size=%d file=%s",
a.modelName, a.endpoint, len(audio), fileName)
out, err := a.inner.Transcribe(ctx, api.TranscriptionRequest{
Audio: audio, FileName: fileName, Language: languageFrom(ctx),
})
if err != nil {
return nil, fmt.Errorf("ASR transcription request failed: %w", err)
}
result := &TranscriptionResult{Text: out.Text, Duration: out.Duration}
for _, s := range out.Segments {
result.Segments = append(result.Segments, Segment{Start: s.Start, End: s.End, Text: s.Text})
}
logger.Infof(ctx, "[ASR] transcription completed, text length=%d", len(result.Text))
return result, nil
}
+25
View File
@@ -0,0 +1,25 @@
package asr
import (
"fmt"
"net/http"
"time"
secutils "academy/internal/utils"
)
func validateASRBaseURL(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
}
func newASRHTTPClient(timeout time.Duration) *http.Client {
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
cfg.Timeout = timeout
return secutils.NewSSRFSafeHTTPClient(cfg)
}
+356
View File
@@ -0,0 +1,356 @@
package asr
import (
"context"
"encoding/json"
"io"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func allowLoopback(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
type form struct {
path string
auth string
fields map[string]string
fileName string
language string // the language request header
// body is set instead of fields when the request was JSON: the
// chat-served recognisers take the audio as a data URI.
body map[string]any
}
// upstream records the form it receives and answers the documented json
// shape, adding a segment when verbose_json was asked for.
func upstream(t *testing.T) (string, *form, *atomic.Int32) {
t.Helper()
allowLoopback(t)
got := &form{fields: map[string]string{}}
calls := &atomic.Int32{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
got.path, got.auth, got.language = r.URL.Path, r.Header.Get("Authorization"), r.Header.Get("language")
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
require.NoError(t, err)
if mediaType == "application/json" {
require.NoError(t, json.NewDecoder(r.Body).Decode(&got.body))
_, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":" hello "}}]}`))
return
}
reader := multipart.NewReader(r.Body, params["boundary"])
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
require.NoError(t, err)
data, _ := io.ReadAll(part)
if part.FormName() == "file" {
got.fileName = part.FileName()
continue
}
got.fields[part.FormName()] = string(data)
}
if got.fields["response_format"] == "verbose_json" {
_, _ = w.Write([]byte(`{"text":" hello ","segments":[{"start":0,"end":1.5,"text":" hello "}]}`))
return
}
_, _ = w.Write([]byte(`{"text":" hello "}`))
}))
t.Cleanup(server.Close)
return server.URL, got, calls
}
// TestTranscriptionWireFormatPerVendor pins the form each ASR vendor is sent.
// response_format appears only where the vendor documents it for that model:
// the pre-catalog client sent verbose_json to every one of them, which
// gpt-4o-transcribe rejects ("the only supported format is json") and which
// vox-box's FunASR backend answers with an undecodable bare string.
func TestTranscriptionWireFormatPerVendor(t *testing.T) {
chatAudio := func(model string) map[string]any {
return map[string]any{
"model": model,
"messages": []any{map[string]any{
"role": "user",
"content": []any{map[string]any{
"type": "input_audio",
"input_audio": map[string]any{"data": "data:audio/wav;base64,UklGRg=="},
}},
}},
}
}
cases := []struct {
name, provider, model, base string
wantPath string
wantFields map[string]string
wantBody map[string]any
wantSegments int
}{
{
name: "openai whisper-1 serves segments", provider: "openai", model: "whisper-1", base: "/v1",
wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "whisper-1", "response_format": "verbose_json"},
wantSegments: 1,
},
{
name: "openai gpt-4o-transcribe accepts only json", provider: "openai", model: "gpt-4o-transcribe",
base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "gpt-4o-transcribe"},
},
{
name: "openai model not yet in the catalog", provider: "openai", model: "gpt-5-transcribe",
base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "gpt-5-transcribe"},
},
{
name: "siliconflow documents file and model only", provider: "siliconflow",
model: "FunAudioLLM/SenseVoiceSmall", base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "FunAudioLLM/SenseVoiceSmall"},
},
{
name: "gpustack stays on json for its FunASR backend", provider: "gpustack",
model: "SenseVoiceSmall", base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "SenseVoiceSmall"},
},
{
name: "generic stays on json", provider: "generic", model: "whisper-large-v3",
base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "whisper-large-v3"},
},
{
name: "zhipu glm-asr on the OpenAI shape", provider: "zhipu", model: "glm-asr-2512",
base: "/api/paas/v4", wantPath: "/api/paas/v4/audio/transcriptions",
wantFields: map[string]string{"model": "glm-asr-2512"},
},
{
name: "minimax on its own path", provider: "minimax", model: "asr-1.0",
base: "/v1", wantPath: "/v1/speech_to_text",
wantFields: map[string]string{"model": "asr-1.0"},
},
{
name: "openrouter", provider: "openrouter", model: "openai/whisper-large-v3",
base: "/api/v1", wantPath: "/api/v1/audio/transcriptions",
wantFields: map[string]string{"model": "openai/whisper-large-v3"},
},
{
name: "requesty whisper-1 serves segments", provider: "requesty", model: "openai/whisper-1",
base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "openai/whisper-1", "response_format": "verbose_json"},
wantSegments: 1,
},
{
name: "litellm proxy", provider: "litellm", model: "whisper",
base: "/v1", wantPath: "/v1/audio/transcriptions",
wantFields: map[string]string{"model": "whisper"},
},
{
name: "aliyun qwen3-asr-flash is served on chat", provider: "aliyun", model: "qwen3-asr-flash",
base: "/compatible-mode/v1", wantPath: "/compatible-mode/v1/chat/completions",
wantBody: chatAudio("qwen3-asr-flash"),
},
{
name: "mimo asr is served on chat", provider: "mimo", model: "mimo-v2.5-asr",
base: "/v1", wantPath: "/v1/chat/completions",
wantBody: chatAudio("mimo-v2.5-asr"),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
url, got, _ := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: tc.provider, BaseURL: url + tc.base,
ModelName: tc.model, APIKey: "k",
})
require.NoError(t, err)
out, err := a.Transcribe(context.Background(), []byte("RIFF"), "meeting.wav")
require.NoError(t, err)
assert.Equal(t, tc.wantPath, got.path)
assert.Equal(t, "Bearer k", got.auth)
if tc.wantBody != nil {
assert.Equal(t, tc.wantBody, got.body)
} else {
assert.Equal(t, tc.wantFields, got.fields)
assert.Equal(t, "meeting.wav", got.fileName)
}
assert.Equal(t, "hello", out.Text)
assert.Len(t, out.Segments, tc.wantSegments)
})
}
}
// A file over the documented ceiling is refused before it is uploaded: the
// vendor would reject it anyway, after the whole upload.
func TestOversizedAudioIsRefusedBeforeUpload(t *testing.T) {
url, _, calls := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "openai", BaseURL: url + "/v1",
ModelName: "whisper-1", APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(context.Background(), make([]byte, 25<<20+1), "long.mp3")
require.Error(t, err)
assert.Contains(t, err.Error(), "at most 25 MB")
assert.Zero(t, calls.Load(), "nothing should have been sent")
_, err = a.Transcribe(context.Background(), make([]byte, 25<<20), "exactly.mp3")
require.NoError(t, err, "the ceiling itself is allowed")
}
// The chat-served recognisers cap the data URI as sent at 10 MB, prefix
// included, so three quarters of 10 MB of audio is already too much.
func TestChatServedCeilingCountsTheWholeDataURI(t *testing.T) {
url, _, calls := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "aliyun", BaseURL: url + "/compatible-mode/v1",
ModelName: "qwen3-asr-flash", APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(context.Background(), make([]byte, 10<<20*3/4), "long.wav")
require.Error(t, err)
assert.Zero(t, calls.Load())
prefix := len("data:audio/wav;base64,")
_, err = a.Transcribe(context.Background(), make([]byte, (10<<20-prefix)/4*3), "fits.wav")
require.NoError(t, err)
}
// Only qwen3-asr-flash takes the audio in the request. Alibaba's other
// recognition models want a public URL or an asynchronous task, so a row
// naming one is refused with the reason rather than sent a chat request.
func TestAlibabaRecognitionModelsOtherThanQwenASRFlashAreRefused(t *testing.T) {
_, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "aliyun",
BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", ModelName: "paraformer-v2", APIKey: "k",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "public file URL")
}
// A vendor that does not declare speech recognition is not trusted with it.
// Azure's Endpoint hook still knows a transcription path, but nobody has
// verified it; a row that names Azure is refused, and a row that names no
// vendor gets what the pre-catalog client sent: the OpenAI shape at its URL.
func TestVendorsWithoutASRAreNotRoutedThroughTheirHooks(t *testing.T) {
_, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "azure_openai",
BaseURL: "https://example.openai.azure.com", ModelName: "whisper", APIKey: "k",
})
require.Error(t, err)
// Detection matches URL patterns as substrings, so a path carrying Azure's
// host detects as Azure while the request still reaches the test server.
url, got, _ := upstream(t)
base := url + "/openai.azure.com/v1"
require.Equal(t, "azure_openai", modelruntime.DetectByURL(base))
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, BaseURL: base, ModelName: "whisper", APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(context.Background(), []byte("RIFF"), "a.wav")
require.NoError(t, err)
assert.Equal(t, "/openai.azure.com/v1/audio/transcriptions", got.path, "not Azure's /openai/v1 path")
assert.Equal(t, "Bearer k", got.auth, "not Azure's api-key header")
}
// A format the vendor does not list is refused before upload.
func TestUndocumentedFormatIsRefusedBeforeUpload(t *testing.T) {
url, _, calls := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "zhipu", BaseURL: url + "/api/paas/v4",
ModelName: "glm-asr-2512", APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(context.Background(), []byte("x"), "memo.m4a")
require.Error(t, err)
assert.Contains(t, err.Error(), "wav/mp3")
assert.Zero(t, calls.Load())
}
// The knowledge base's language hint reaches each vendor where its reference
// puts it, and nowhere for a vendor that documents none.
func TestLanguageHintGoesWhereEachVendorDocumentsIt(t *testing.T) {
for _, tc := range []struct {
name, provider, model, base string
check func(t *testing.T, got *form)
}{
{"openai form field", "openai", "whisper-1", "/v1", func(t *testing.T, got *form) {
assert.Equal(t, "zh", got.fields["language"])
assert.Empty(t, got.language)
}},
{"minimax header", "minimax", "asr-1.0", "/v1", func(t *testing.T, got *form) {
assert.Equal(t, "zh", got.language)
assert.NotContains(t, got.fields, "language")
}},
{"aliyun asr_options", "aliyun", "qwen3-asr-flash", "/compatible-mode/v1", func(t *testing.T, got *form) {
assert.Equal(t, map[string]any{"language": "zh"}, got.body["asr_options"])
}},
{
"siliconflow documents none", "siliconflow", "FunAudioLLM/SenseVoiceSmall", "/v1",
func(t *testing.T, got *form) {
assert.NotContains(t, got.fields, "language")
assert.Empty(t, got.language)
},
},
} {
t.Run(tc.name, func(t *testing.T) {
url, got, _ := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: tc.provider, BaseURL: url + tc.base,
ModelName: tc.model, APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(WithLanguage(context.Background(), "zh"), []byte("RIFF"), "a.wav")
require.NoError(t, err)
tc.check(t, got)
})
}
// "auto" is every vendor's default and is not sent.
url, got, _ := upstream(t)
a, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "openai", BaseURL: url + "/v1", ModelName: "whisper-1", APIKey: "k",
})
require.NoError(t, err)
_, err = a.Transcribe(WithLanguage(context.Background(), "auto"), []byte("RIFF"), "a.wav")
require.NoError(t, err)
assert.NotContains(t, got.fields, "language")
}
func TestEmptyAudioIsAnError(t *testing.T) {
url, _, calls := upstream(t)
a, err := NewASR(&Config{Source: types.ModelSourceRemote, Provider: "generic", BaseURL: url, ModelName: "m"})
require.NoError(t, err)
_, err = a.Transcribe(context.Background(), nil, "a.wav")
assert.Error(t, err)
assert.Zero(t, calls.Load())
}
func TestInternalBaseURLIsRefused(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
_, err := NewASR(&Config{
Source: types.ModelSourceRemote, Provider: "generic",
BaseURL: "http://169.254.169.254/latest/meta-data/", ModelName: "asr-test",
})
assert.Error(t, err)
}