gateway: a Qwen Token Plan's TTS, ASR and video models are served on OpenAI's routes
gaubeebangeel on X (tweet 2122991088017477954) asked for every kind of model Alibaba's Token Plan sells, each on its own DashScope endpoint. Before this, magpie served the plan's text (Anthropic and chat completions), its realtime voice (/v1/realtime, realtime.go) and its Qwen-Image drawing (draw_dashscope.go). The plan's text list lacked deepseek-v4.1-flash-1017, and nothing served its TTS, ASR or video models. - presets: alibabaPlanModels as the four plans' overviews list them on 11-18 (qwen4-max, qwen4-max-preview, deepseek-v4.1-flash-1017 added). PresetDef gains Drawers, Videos, Speakers and Transcribers, Region gains Speakers and Transcribers, and the four Token Plans (qwen-token-plan, bailian-token-plan, alibaba-token-plan, qwencloud-token-plan) name qwen-image-3.0-pro and wan2.7-image(-pro), wan3.0-video and happyhorse-1.1-t2v/-i2v/-r2v, qwen-audio-3.0-tts-plus and qwen-audio-3.0-asr-flash. PlanSpeakers and PlanTranscribers feed PlanRetrieval, so the router knows which provider speaks and transcribes. - /v1/audio/speech (speech_dashscope.go): a plan key's qwen-audio TTS model is asked on <root>/api/v1/services/audio/tts/SpeechSynthesizer, every field under input as the docs have them. An OpenAI voice name becomes the model's own first voice (longanlingxin for -plus, longanhuan_v3.6 for -flash), speed goes as rate (0.5 to 2), and instructions as instruction. mp3, wav, pcm and opus are served; aac, flac and stream_format sse are 400s before DashScope is asked. The answer's output.audio.url is fetched (or data decoded) and served with the format's type. - /v1/audio/transcriptions: a plan key's qwen-audio ASR model goes to multimodal-generation with the file as an input_audio data URI, its format from the file's name or type, and language as language_hints. The answer is given back as OpenAI's json, text or verbose_json; srt, vtt and translations are 400s. The form's file is read only on this path (audioForm.file), so a form passed on as sent is never copied. - /v1/videos (video_dashscope.go): Wan 3.0 and HappyHorse start at video-synthesis with X-DashScope-Async: enable and are polled at /api/v1/tasks/<id>. The id carries the model and the key's mark, as MiniMax's does. vendorAsk.answer now takes the request's context, so the TTS answer's audio URL is fetched under it. Hosts, paths, fields and voices were checked against Alibaba's docs (help.aliyun.com model-studio qwen-audio-tts/asr HTTP API and Wan 3.0 video reference, docs.qwencloud.com Token Plan multimodal pages, platform.qianwenai.com token-plan), not against the tweet. Not tried against the real API: the owner's magpie has no Token Plan provider. The tests use a fake DashScope serving the docs' shapes. Run (on mote via mote-run, tree at8634c4ad0plus this diff): - gofmt -l internal/: nothing. - go test -count=1 -run 'TokenPlan|DashScope|Speech|Transcri|Video|Plan|Qwen|Qianwen|Alibaba' ./internal/gateway ./internal/provider ./internal/gui: ok, ok, ok. - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: all ok. - go test -count=1 -timeout 45m ./...: 101 packages ok; internal/cli and internal/gui red on TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr, TestUpdateFindsAMagpieThatWroteNoRecord (#6223, #6471) and TestLaneLimitRoutes (#5150). mote has an ssh forward listening on 127.0.0.1:3425, which those tests read. All four are red the same way, run alone on mote, at a just-fetched origin/main589e4ba6d. - Broken by hand: with the X-DashScope-Async header dropped, TestTokenPlanMakesVideos goes red (403 "does not support synchronous calls"); with -plus's default voice changed to alloy, TestTokenPlanSpeaks goes red. - GUI: no asset changed, and the .cjs files run app.js on fixtures, so none can be reached. The Go GUI API that lists the plans' models ran in ./internal/gui above. - Rebased on origin/main589e4ba6d(6 commits, none touching these files) and run again at this head on mote: gofmt -l nothing; the targeted run above ok, ok, ok; vet (darwin, linux nogui, windows) of ./internal/gateway ./internal/provider and the three builds ok.
This commit is contained in:
@@ -1158,7 +1158,7 @@ Each vendor is sent its own request:
|
||||
| Volcengine Ark (`isArk`) | `/images/generations`, `watermark: false` unless sent, one request per image, ratio as the doc's 2K size, the caller's other fields as sent (`stream: true` is a 400 pointing to the native route) | the same endpoint, images as JSON `image` (URL or data URL); a mask is a 400 that says to describe it in the prompt | Seedance at `/contents/generations/tasks` (below) |
|
||||
| Gemini at Google, a Google sign-in | `generateContent` asking for images | the images as inline parts | a plugin's Veo through its fetch |
|
||||
| OpenRouter | `/images` for image-only models, chat with modalities for the others | `input_references` | none |
|
||||
| DashScope, ModelScope | their own asynchronous image APIs (`draw_dashscope.go`, `draw_modelscope.go`) | their image fields | none |
|
||||
| DashScope, ModelScope | their own asynchronous image APIs (`draw_dashscope.go`, `draw_modelscope.go`) | their image fields | a Token Plan's Wan 3.0 and HappyHorse at `/api/v1/services/aigc/video-generation/video-synthesis` (below); none for ModelScope |
|
||||
| MiniMax API key | | | H3 at `/v2/video_generation` (below) |
|
||||
| Another magpie | its images API | its images API | its videos API, ids wrapped |
|
||||
|
||||
@@ -1355,6 +1355,58 @@ when nothing else makes videos. Covered by `TestMiniMaxKeysMakeH3Videos`,
|
||||
`TestMiniMaxComesAfterOtherVideomakers` and
|
||||
`TestMiniMaxVideoMovesPastATokenPlanKey`.
|
||||
|
||||
Alibaba's Token Plans (`qwen-token-plan`, `bailian-token-plan`,
|
||||
`alibaba-token-plan`, `qwencloud-token-plan`) name every kind of model the
|
||||
plan serves, each in its own list on the preset (`PresetDef.Drawers`,
|
||||
`Videos`, `Speakers`, `Transcribers`, read by `PlanDrawers`, `PlanVideos`,
|
||||
`PlanSpeakers`, `PlanTranscribers`): Qwen-Image and Wan 2.7 images
|
||||
(drawn as above), Wan 3.0 and HappyHorse 1.1 videos, qwen-audio TTS and
|
||||
ASR, beside the chat models (@gaubeebangeel on X). A key of such a plan
|
||||
(no account, not a plugin or another magpie, `dashScope`) is asked on
|
||||
DashScope's own APIs at its host's root (`dashScopeRoot`), since the
|
||||
plan's host has no OpenAI-style videos or audio API:
|
||||
|
||||
- **Video** ([`video_dashscope.go`](../../internal/gateway/video_dashscope.go),
|
||||
`filmsDashScope`, `makesDashScopeVideo`): `POST
|
||||
<root>/api/v1/services/aigc/video-generation/video-synthesis` with
|
||||
`X-DashScope-Async: enable`, polled at `GET <root>/api/v1/tasks/<id>`,
|
||||
its MP4 `output.video_url` fetched through `vendorClient`.
|
||||
`dashScopeVideoBody` puts the prompt and `negative_prompt` in `input`,
|
||||
`input_reference`, `last_frame` and `reference_images` as `media` items
|
||||
of type `first_frame`, `last_frame` and `reference_image` (at most 10),
|
||||
`size` as `resolution` (1080P/720P/480P by its shorter side) and the
|
||||
nearest `ratio`, `seconds` as a whole `duration`, `watermark: false`
|
||||
unless sent, and the caller's other fields in `parameters` as sent. The
|
||||
task answer names no model, so the vendor id is the model and task in
|
||||
base64url (`dashScopeStarted`, `dashScopeTask`). PENDING, RUNNING,
|
||||
SUCCEEDED, FAILED/UNKNOWN and CANCELED are read as queued, in_progress,
|
||||
completed and failed (`dashScopeVideoStatus`). Ids carry the key's mark
|
||||
and polls go on that key, as MiniMax's do.
|
||||
- **Text to speech** ([`speech_dashscope.go`](../../internal/gateway/speech_dashscope.go),
|
||||
`dashScopeAudio`, `speechRequest.dashScopeSpeech`, a `nativeRetrieval`
|
||||
as Gemini's speech is): `/v1/audio/speech` goes to `POST
|
||||
<root>/api/v1/services/audio/tts/SpeechSynthesizer` with `input.text`,
|
||||
`voice` (an OpenAI name, or none, is the model's own first voice:
|
||||
`longanlingxin` for -plus, `longanhuan_v3.6` for -flash), `format`
|
||||
(mp3 by default, wav, pcm, opus; aac, flac and `stream_format: sse` are
|
||||
400s before DashScope is asked), `instructions` as `instruction` and
|
||||
`speed` as `rate` (0.5 to 2). The answer's `output.audio.url` is fetched
|
||||
(`fetchVendorFile`), or `output.audio.data` decoded, and served with the
|
||||
format's type; `usage.characters` is the input counted.
|
||||
- **Speech to text** (`audioForm.nativeAt`,
|
||||
`dashScopeTranscription`): `/v1/audio/transcriptions` goes to `POST
|
||||
<root>/api/v1/services/aigc/multimodal-generation/generation`, the
|
||||
form's file as an `input_audio` data URI, its `format` from the file's
|
||||
name or type, `language` as `language_hints`; the prompt has no field
|
||||
there and isn't sent. `output.text` is answered as OpenAI's json, text or
|
||||
verbose_json; srt, vtt and `/v1/audio/translations` are 400s.
|
||||
|
||||
The plan's Qwen-Omni realtime (`wss://<root>/api-ws/v1/realtime`) is
|
||||
served by the realtime route as other DashScope hosts are. Covered by
|
||||
`TestTokenPlansNameEveryKind`, `TestTokenPlanSpeaks`,
|
||||
`TestTokenPlanTranscribes`, `TestTokenPlanMakesVideos` and
|
||||
`TestDashScopeVideoBody`.
|
||||
|
||||
## A key's model patterns and names
|
||||
|
||||
A gateway key's models (`Key.Models`, [`access/models.go`](../../internal/access/models.go), tsingchao on X) are named one by one (`provider/model`), by a provider's whole list (`provider/*`), or by a pattern: an entry that starts with `re:` is a regular expression, RE2 syntax (Go's `regexp`), case-insensitive and not anchored (`re:^gpt-`, `re:claude.*(sonnet|opus)`). It is tried on the whole `provider/model` id and on the model part alone, so `re:^gpt-` and `re:^openai/gpt-` both take `openai/gpt-5`. It never takes a routing group (`group/…`), which a key names itself. Every route that holds a key to its models asks `access.ModelAllowed` (through `Identity.Allows`, `allows`, `modelAllowed`, `keyAllowed`), so a pattern holds chat, Responses, Messages, `count_tokens`, Gemini's path, `/v1/systemone`, the decision models and every list alike (`TestGatewayKeyModelPatternHoldsEveryRoute`). `CleanModels` compiles a pattern when a key is saved and refuses one that is empty or isn't a regular expression; one that fails to compile later (a hand-edited file) matches nothing, never every model. A pattern is for the keys the user makes: `IssueKey` refuses one, since an issued key's models are named one by one or with `*`. The model picker (Gateway page, the key's models badge) has a search box over a model's name and id; typing `re:` and a pattern and pressing Enter adds the pattern; `magpie gateway-key models <id> 're:^gpt-'` does the same.
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// fakeDashScopeMedia stands in for a Token Plan's DashScope host as
|
||||
// Alibaba documents it (help.aliyun.com/zh/model-studio/
|
||||
// qwen-audio-tts-http-api, qwen-audio-asr-http-api and
|
||||
// wan3-video-generation-api-reference, read 11-18): the speech synthesizer
|
||||
// answering with a URL to the audio, the multimodal generation API with a
|
||||
// transcript, the video-synthesis API with a task, and the task API with
|
||||
// its state. No real DashScope account was asked.
|
||||
type fakeDashScopeMedia struct {
|
||||
*httptest.Server
|
||||
mu sync.Mutex
|
||||
paths []string
|
||||
bodies []string
|
||||
async []string
|
||||
polls int
|
||||
answer string // the next ASR or TTS answer, its documented one if ""
|
||||
}
|
||||
|
||||
const (
|
||||
dashScopeTTSAnswer = `{"request_id":"5c1b1e42-xxxx","output":{"finish_reason":"stop","audio":{"data":"","url":"AUDIO_URL","id":"audio_5c1b1e42","expires_at":1784342400}},"usage":{"characters":12}}`
|
||||
dashScopeASRAnswer = `{"request_id":"9d3c-xxxx","output":{"text":"欢迎使用喜鹊。","sentence":{"sentence_id":0,"sentence_end":true,"begin_time":0,"end_time":1820,"text":"欢迎使用喜鹊。","channel_id":0,"words":[]}},"usage":{"duration":2}}`
|
||||
dashScopeTaskStarted = `{"request_id":"4909100c-xxxx","output":{"task_id":"0385dc79-5ff8-4d82-bcb6-xxxxxx","task_status":"PENDING"}}`
|
||||
dashScopeTaskDone = `{"request_id":"caa62a12-xxxx","output":{"task_id":"0385dc79-5ff8-4d82-bcb6-xxxxxx","task_status":"SUCCEEDED","submit_time":"2026-11-18 10:00:00.000","scheduled_time":"2026-11-18 10:00:05.000","end_time":"2026-11-18 10:02:40.000","orig_prompt":"一只喜鹊落在枝头","video_url":"VIDEO_URL"},"usage":{"duration":5,"video_count":1,"SR":720}}`
|
||||
dashScopeTaskFailed = `{"request_id":"e5d70b02-xxxx","output":{"task_id":"86ecf553-xxxx","task_status":"FAILED","code":"DataInspectionFailed","message":"Input data may contain inappropriate content."}}`
|
||||
)
|
||||
|
||||
func newFakeDashScopeMedia(t *testing.T) *fakeDashScopeMedia {
|
||||
f := &fakeDashScopeMedia{}
|
||||
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
f.mu.Lock()
|
||||
f.paths = append(f.paths, r.Method+" "+r.URL.Path)
|
||||
f.bodies = append(f.bodies, string(body))
|
||||
f.async = append(f.async, r.Header.Get("X-DashScope-Async"))
|
||||
answer := f.answer
|
||||
f.answer = ""
|
||||
f.mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/oss/speech.mp3":
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
io.WriteString(w, "ID3-mp3-bytes")
|
||||
return
|
||||
case "/oss/video.mp4":
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
io.WriteString(w, "wan-mp4-bytes")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Header.Get("Authorization") != "Bearer sk-sp-key" {
|
||||
w.WriteHeader(401)
|
||||
io.WriteString(w, `{"request_id":"1","code":"InvalidApiKey","message":"Invalid API-key provided."}`)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.Method == "POST" && r.URL.Path == "/api/v1/services/audio/tts/SpeechSynthesizer":
|
||||
if answer == "" {
|
||||
answer = strings.Replace(dashScopeTTSAnswer, "AUDIO_URL", f.URL+"/oss/speech.mp3", 1)
|
||||
}
|
||||
case r.Method == "POST" && r.URL.Path == "/api/v1/services/aigc/multimodal-generation/generation":
|
||||
if answer == "" {
|
||||
answer = dashScopeASRAnswer
|
||||
}
|
||||
case r.Method == "POST" && r.URL.Path == "/api/v1/services/aigc/video-generation/video-synthesis":
|
||||
if r.Header.Get("X-DashScope-Async") != "enable" {
|
||||
w.WriteHeader(403)
|
||||
io.WriteString(w, `{"request_id":"2","code":"AccessDenied","message":"current user api does not support synchronous calls"}`)
|
||||
return
|
||||
}
|
||||
if strings.Contains(string(body), "FAILING") {
|
||||
answer = strings.Replace(dashScopeTaskStarted, "0385dc79-5ff8-4d82-bcb6-xxxxxx", "86ecf553-xxxx", 1)
|
||||
} else {
|
||||
answer = dashScopeTaskStarted
|
||||
}
|
||||
case r.Method == "GET" && r.URL.Path == "/api/v1/tasks/0385dc79-5ff8-4d82-bcb6-xxxxxx":
|
||||
f.mu.Lock()
|
||||
f.polls++
|
||||
n := f.polls
|
||||
f.mu.Unlock()
|
||||
switch n {
|
||||
case 1:
|
||||
answer = strings.Replace(dashScopeTaskStarted, `"PENDING"`, `"PENDING","submit_time":"2026-11-18 10:00:00.000"`, 1)
|
||||
case 2:
|
||||
answer = strings.Replace(dashScopeTaskStarted, `"PENDING"`, `"RUNNING"`, 1)
|
||||
default:
|
||||
answer = strings.Replace(dashScopeTaskDone, "VIDEO_URL", f.URL+"/oss/video.mp4", 1)
|
||||
}
|
||||
case r.Method == "GET" && r.URL.Path == "/api/v1/tasks/86ecf553-xxxx":
|
||||
answer = dashScopeTaskFailed
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
io.WriteString(w, `{"request_id":"3","code":"NotFound","message":"unexpected path"}`)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, answer)
|
||||
}))
|
||||
t.Cleanup(f.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeDashScopeMedia) seen() (paths, bodies, async []string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.paths...), append([]string(nil), f.bodies...), append([]string(nil), f.async...)
|
||||
}
|
||||
|
||||
// tokenPlan saves a Token Plan key of preset pointed at the fake.
|
||||
func tokenPlan(t *testing.T, preset string, up *fakeDashScopeMedia) provider.Provider {
|
||||
t.Helper()
|
||||
fresh(t)
|
||||
p, err := provider.FromPreset(preset)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.ID, p.Key = "qwen", "sk-sp-key"
|
||||
p.Chat, p.Anthropic = up.URL+"/compatible-mode/v1", up.URL+"/apps/anthropic"
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Every Token Plan names the plan's text, image, video, speech and
|
||||
// transcription models, each kind in its own list (@gaubeebangeel on X:
|
||||
// the plan's console lists the six kinds and their endpoints).
|
||||
func TestTokenPlansNameEveryKind(t *testing.T) {
|
||||
fresh(t)
|
||||
ids := func(ms []catalog.Model) []string {
|
||||
var out []string
|
||||
for _, m := range ms {
|
||||
out = append(out, m.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
for _, preset := range []string{"qwen-token-plan", "bailian-token-plan", "alibaba-token-plan", "qwencloud-token-plan"} {
|
||||
p, err := provider.FromPreset(preset)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.ID, p.Key = preset, "sk-sp-key"
|
||||
if chat := provider.Preset(preset).Models; !slices.Contains(chat, "deepseek-v4.1-flash-1017") {
|
||||
t.Fatalf("%s chats with %v", preset, chat)
|
||||
}
|
||||
if got := ids(p.PlanDrawers()); !strings.Contains(strings.Join(got, ","), "qwen-image-3.0-pro") {
|
||||
t.Fatalf("%s draws with %v", preset, got)
|
||||
}
|
||||
if got := ids(p.PlanVideos()); strings.Join(got, ",") != "wan3.0-video,happyhorse-1.1-t2v,happyhorse-1.1-i2v,happyhorse-1.1-r2v" {
|
||||
t.Fatalf("%s films with %v", preset, got)
|
||||
}
|
||||
if got := ids(p.PlanSpeakers()); strings.Join(got, ",") != "qwen-audio-3.0-tts-plus" {
|
||||
t.Fatalf("%s speaks with %v", preset, got)
|
||||
}
|
||||
if got := ids(p.PlanTranscribers()); strings.Join(got, ",") != "qwen-audio-3.0-asr-flash" {
|
||||
t.Fatalf("%s transcribes with %v", preset, got)
|
||||
}
|
||||
if !filmsDashScope(p) || !makesDashScopeVideo(p, "wan3.0-video") || makesDashScopeVideo(p, "qwen3.8-max") {
|
||||
t.Fatalf("%s isn't asked for videos at DashScope", preset)
|
||||
}
|
||||
if !dashScopeAudio(p, "qwen-audio-3.0-tts-plus", catalog.ServesSpeech) || !dashScopeAudio(p, "qwen-audio-3.0-asr-flash", catalog.ServesTranscription) || dashScopeAudio(p, "qwen-audio-3.0-asr-flash", catalog.ServesSpeech) {
|
||||
t.Fatalf("%s's audio models aren't asked at DashScope", preset)
|
||||
}
|
||||
}
|
||||
// another vendor's key, and a relay that serves Qwen's models: neither
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "x", Chat: "https://api.deepseek.com/v1", Key: "k"},
|
||||
{ID: "relay", Chat: "https://relay.example.com/qwen/v1", Key: "k"},
|
||||
} {
|
||||
if filmsDashScope(p) || dashScopeAudio(p, "qwen-audio-3.0-tts-plus", catalog.ServesSpeech) {
|
||||
t.Fatalf("%s is asked as DashScope", p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /v1/audio/speech with a Token Plan's qwen-audio TTS model goes to
|
||||
// DashScope's speech synthesizer, the input read in the model's own voice
|
||||
// for an OpenAI name, the instructions and speed as its instruction and
|
||||
// rate, and the audio fetched from the URL it answers with.
|
||||
func TestTokenPlanSpeaks(t *testing.T) {
|
||||
up := newFakeDashScopeMedia(t)
|
||||
tokenPlan(t, "qwen-token-plan", up)
|
||||
s := New()
|
||||
code, h, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"qwen/qwen-audio-3.0-tts-plus","input":"欢迎使用喜鹊。","voice":"alloy","instructions":"用开心的语气","speed":3}`)
|
||||
if code != 200 || string(got) != "ID3-mp3-bytes" || h.Get("Content-Type") != "audio/mpeg" {
|
||||
t.Fatalf("%d %v %q", code, h, got)
|
||||
}
|
||||
paths, bodies, _ := up.seen()
|
||||
if paths[0] != "POST /api/v1/services/audio/tts/SpeechSynthesizer" || paths[1] != "GET /oss/speech.mp3" {
|
||||
t.Fatalf("paths %v", paths)
|
||||
}
|
||||
var sent struct {
|
||||
Model string `json:"model"`
|
||||
Input map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal([]byte(bodies[0]), &sent)
|
||||
in := sent.Input
|
||||
if sent.Model != "qwen-audio-3.0-tts-plus" || in["text"] != "欢迎使用喜鹊。" || in["voice"] != "longanlingxin" || in["format"] != "mp3" || in["instruction"] != "用开心的语气" || in["rate"] != float64(2) {
|
||||
t.Fatalf("sent %s", bodies[0])
|
||||
}
|
||||
|
||||
// its own voice and a WAV; audio in data is decoded, not fetched
|
||||
up.mu.Lock()
|
||||
up.answer = `{"output":{"audio":{"data":"` + base64.StdEncoding.EncodeToString([]byte("RIFF-wav")) + `","url":""}},"usage":{"characters":3}}`
|
||||
up.mu.Unlock()
|
||||
code, h, got = postSpeech(t, s, "/v1/audio/speech", `{"model":"qwen/qwen-audio-3.0-tts-plus","input":"你好","voice":"longanlufeng","response_format":"wav"}`)
|
||||
if code != 200 || string(got) != "RIFF-wav" || h.Get("Content-Type") != "audio/wav" {
|
||||
t.Fatalf("%d %v %q", code, h, got)
|
||||
}
|
||||
_, bodies, _ = up.seen()
|
||||
if !strings.Contains(bodies[len(bodies)-1], `"voice":"longanlufeng"`) || !strings.Contains(bodies[len(bodies)-1], `"format":"wav"`) {
|
||||
t.Fatalf("sent %s", bodies[len(bodies)-1])
|
||||
}
|
||||
|
||||
// what DashScope doesn't make is turned away before it is asked
|
||||
n := len(bodies)
|
||||
for body, want := range map[string]string{
|
||||
`{"model":"qwen/qwen-audio-3.0-tts-plus","input":"x","response_format":"flac"}`: "mp3 (the default), wav, pcm or opus",
|
||||
`{"model":"qwen/qwen-audio-3.0-tts-plus","input":"x","stream_format":"sse"}`: "without stream_format sse",
|
||||
`{"model":"qwen/qwen-audio-3.0-tts-plus","input":" "}`: "nothing to read aloud",
|
||||
} {
|
||||
if code, _, got := postSpeech(t, s, "/v1/audio/speech", body); code != 400 || !strings.Contains(string(got), want) {
|
||||
t.Fatalf("%s: %d %s", body, code, got)
|
||||
}
|
||||
}
|
||||
if _, bodies, _ = up.seen(); len(bodies) != n {
|
||||
t.Fatalf("a refused request was sent: %v", bodies[n:])
|
||||
}
|
||||
|
||||
// DashScope's error says why
|
||||
up.mu.Lock()
|
||||
up.answer = `{"request_id":"7","code":"InvalidParameter","message":"Voice not supported for this model."}`
|
||||
up.mu.Unlock()
|
||||
if code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"qwen/qwen-audio-3.0-tts-plus","input":"x","voice":"nobody"}`); code != 502 || !strings.Contains(string(got), "Voice not supported") {
|
||||
t.Fatalf("%d %s", code, got)
|
||||
}
|
||||
}
|
||||
|
||||
// /v1/audio/transcriptions with a Token Plan's qwen-audio ASR model sends
|
||||
// the file to DashScope's multimodal generation API as a data URI, its
|
||||
// format from the file's name and the language as a hint, and answers in
|
||||
// OpenAI's shapes; a translation and srt are turned away.
|
||||
func TestTokenPlanTranscribes(t *testing.T) {
|
||||
up := newFakeDashScopeMedia(t)
|
||||
tokenPlan(t, "bailian-token-plan", up)
|
||||
s := New()
|
||||
body, ctype := audioFormBody(t, "model", "qwen/qwen-audio-3.0-asr-flash", "language", "zh", "prompt", "喜鹊")
|
||||
code, h, got := postAudio(t, s, "/v1/audio/transcriptions", ctype, body)
|
||||
if code != 200 || got != `{"text":"欢迎使用喜鹊。"}` || !strings.HasPrefix(h.Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("%d %v %s", code, h, got)
|
||||
}
|
||||
paths, bodies, _ := up.seen()
|
||||
if len(paths) != 1 || paths[0] != "POST /api/v1/services/aigc/multimodal-generation/generation" {
|
||||
t.Fatalf("paths %v", paths)
|
||||
}
|
||||
var sent struct {
|
||||
Model string `json:"model"`
|
||||
Input struct {
|
||||
Messages []struct {
|
||||
Role string `json:"role"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
InputAudio map[string]string `json:"input_audio"`
|
||||
} `json:"content"`
|
||||
} `json:"messages"`
|
||||
} `json:"input"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(bodies[0]), &sent); err != nil || len(sent.Input.Messages) != 1 || len(sent.Input.Messages[0].Content) != 1 {
|
||||
t.Fatalf("sent %.300s: %v", bodies[0], err)
|
||||
}
|
||||
c := sent.Input.Messages[0].Content[0]
|
||||
if sent.Model != "qwen-audio-3.0-asr-flash" || c.Type != "input_audio" || c.InputAudio["data"] != "data:audio/webm;base64,"+base64.StdEncoding.EncodeToString(voice) {
|
||||
t.Fatalf("sent %.300s", bodies[0])
|
||||
}
|
||||
if sent.Parameters["format"] != "webm" || strings.Join(anyStrings(sent.Parameters["language_hints"]), ",") != "zh" {
|
||||
t.Fatalf("parameters %v", sent.Parameters)
|
||||
}
|
||||
if strings.Contains(bodies[0], "喜鹊\"") {
|
||||
t.Fatalf("the prompt was sent: %.300s", bodies[0])
|
||||
}
|
||||
|
||||
body, ctype = audioFormBody(t, "model", "qwen/qwen-audio-3.0-asr-flash", "response_format", "text")
|
||||
if code, h, got := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 200 || got != "欢迎使用喜鹊。" || !strings.HasPrefix(h.Get("Content-Type"), "text/plain") {
|
||||
t.Fatalf("text: %d %v %s", code, h, got)
|
||||
}
|
||||
body, ctype = audioFormBody(t, "model", "qwen/qwen-audio-3.0-asr-flash", "response_format", "verbose_json")
|
||||
if code, _, got := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 200 || !strings.Contains(got, `"duration":2`) || !strings.Contains(got, `"text":"欢迎使用喜鹊。"`) {
|
||||
t.Fatalf("verbose_json: %d %s", code, got)
|
||||
}
|
||||
|
||||
_, bodies, _ = up.seen()
|
||||
n := len(bodies)
|
||||
body, ctype = audioFormBody(t, "model", "qwen/qwen-audio-3.0-asr-flash", "response_format", "srt")
|
||||
if code, _, got := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 400 || !strings.Contains(got, "json (the default), text or verbose_json") {
|
||||
t.Fatalf("srt: %d %s", code, got)
|
||||
}
|
||||
body, ctype = audioFormBody(t, "model", "qwen/qwen-audio-3.0-asr-flash")
|
||||
if code, _, got := postAudio(t, s, "/v1/audio/translations", ctype, body); code != 400 || !strings.Contains(got, "no translation") {
|
||||
t.Fatalf("translation: %d %s", code, got)
|
||||
}
|
||||
if _, bodies, _ = up.seen(); len(bodies) != n {
|
||||
t.Fatalf("a refused request was sent: %d", len(bodies)-n)
|
||||
}
|
||||
}
|
||||
|
||||
func anyStrings(v any) []string {
|
||||
var out []string
|
||||
for _, e := range v.([]any) {
|
||||
out = append(out, e.(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// /v1/videos with a Token Plan's Wan model starts a DashScope task with
|
||||
// X-DashScope-Async, is asked after at /api/v1/tasks/<id> until it has
|
||||
// succeeded, and its MP4 is fetched from video_url; the size becomes the
|
||||
// resolution and ratio, seconds the duration, and the image the first
|
||||
// frame.
|
||||
func TestTokenPlanMakesVideos(t *testing.T) {
|
||||
up := newFakeDashScopeMedia(t)
|
||||
tokenPlan(t, "qwencloud-token-plan", up)
|
||||
s := New()
|
||||
png := "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("png"))
|
||||
code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"qwen/wan3.0-video","prompt":"一只喜鹊落在枝头","seconds":"8","size":"1280x720","input_reference":{"image_url":"`+png+`"}}`)
|
||||
if code != 200 || obj["status"] != "queued" || obj["model"] != "qwen/wan3.0-video" {
|
||||
t.Fatalf("create: %d %s", code, raw)
|
||||
}
|
||||
id, _ := obj["id"].(string)
|
||||
if !strings.HasSuffix(id, "."+keyMark(provider.Provider{Key: "sk-sp-key"})) {
|
||||
t.Fatalf("id %q", id)
|
||||
}
|
||||
for _, want := range []string{"queued", "in_progress"} {
|
||||
code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "")
|
||||
if code != 200 || obj["status"] != want {
|
||||
t.Fatalf("want %s: %d %s", want, code, raw)
|
||||
}
|
||||
}
|
||||
code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "")
|
||||
if code != 200 || obj["status"] != "completed" || obj["model"] != "qwen/wan3.0-video" {
|
||||
t.Fatalf("succeeded: %d %s", code, raw)
|
||||
}
|
||||
code, _, raw, head := request(t, s, http.MethodGet, "/v1/videos/"+id+"/content", "", "")
|
||||
if code != 200 || string(raw) != "wan-mp4-bytes" || head.Get("Content-Type") != "video/mp4" {
|
||||
t.Fatalf("content: %d %q %v", code, raw, head)
|
||||
}
|
||||
paths, bodies, async := up.seen()
|
||||
if paths[0] != "POST /api/v1/services/aigc/video-generation/video-synthesis" || async[0] != "enable" || paths[1] != "GET /api/v1/tasks/0385dc79-5ff8-4d82-bcb6-xxxxxx" || paths[len(paths)-1] != "GET /oss/video.mp4" {
|
||||
t.Fatalf("paths %v async %v", paths, async)
|
||||
}
|
||||
var sent struct {
|
||||
Model string `json:"model"`
|
||||
Input struct {
|
||||
Prompt string `json:"prompt"`
|
||||
Media []map[string]string `json:"media"`
|
||||
} `json:"input"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
}
|
||||
json.Unmarshal([]byte(bodies[0]), &sent)
|
||||
pm := sent.Parameters
|
||||
if sent.Model != "wan3.0-video" || sent.Input.Prompt != "一只喜鹊落在枝头" || pm["resolution"] != "720P" || pm["ratio"] != "16:9" || pm["duration"] != float64(8) || pm["watermark"] != false {
|
||||
t.Fatalf("create body %s", bodies[0])
|
||||
}
|
||||
if len(sent.Input.Media) != 1 || sent.Input.Media[0]["type"] != "first_frame" || sent.Input.Media[0]["url"] != png {
|
||||
t.Fatalf("media %v", sent.Input.Media)
|
||||
}
|
||||
|
||||
// a failed task says why
|
||||
code, obj, raw, _ = request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"qwen/wan3.0-video","prompt":"FAILING"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("create: %d %s", code, raw)
|
||||
}
|
||||
code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+obj["id"].(string), "", "")
|
||||
if code != 200 || obj["status"] != "failed" || !strings.Contains(string(raw), "inappropriate content") {
|
||||
t.Fatalf("failed: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// The body as DashScope's video API takes it: an "a:b" size is the ratio,
|
||||
// first and last frames and references each with their type, and the
|
||||
// caller's own fields where DashScope reads them.
|
||||
func TestDashScopeVideoBody(t *testing.T) {
|
||||
png := picture{Mime: "image/png", Data: []byte("png")}
|
||||
end := picture{URL: "https://example.com/end.png"}
|
||||
b, err := dashScopeVideoBody("wan3.0-video", filming{Prompt: "p", Size: "9:16", Start: &png, End: &end, References: []picture{end}, Extra: map[string]any{"resolution": "1080p", "negative_prompt": "blur", "audio": true}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Input map[string]any `json:"input"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
}
|
||||
json.Unmarshal(b, &m)
|
||||
media, _ := m.Input["media"].([]any)
|
||||
if len(media) != 3 || media[0].(map[string]any)["type"] != "first_frame" || media[1].(map[string]any)["type"] != "last_frame" || media[2].(map[string]any)["url"] != "https://example.com/end.png" {
|
||||
t.Fatalf("media %v", media)
|
||||
}
|
||||
if m.Input["negative_prompt"] != "blur" || m.Parameters["resolution"] != "1080P" || m.Parameters["ratio"] != "9:16" || m.Parameters["audio"] != true {
|
||||
t.Fatalf("body %s", b)
|
||||
}
|
||||
if _, ok := m.Parameters["duration"]; ok {
|
||||
t.Fatalf("a duration with none asked: %s", b)
|
||||
}
|
||||
if _, err := dashScopeVideoBody("wan3.0-video", filming{Prompt: "p", Seconds: "4.5"}); err == nil {
|
||||
t.Fatal("4.5 seconds was taken")
|
||||
}
|
||||
if _, _, ok := dashScopeTask("not-base64!"); ok {
|
||||
t.Fatal("a foreign id was read as a task")
|
||||
}
|
||||
if _, _, ok := dashScopeTask(base64.RawURLEncoding.EncodeToString([]byte("wan3.0-video ../../x"))); ok {
|
||||
t.Fatal("a task with a path was read")
|
||||
}
|
||||
}
|
||||
@@ -309,7 +309,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
|
||||
} else if nat != nil {
|
||||
// whole, then put in the client's shape
|
||||
if b, got, code, err = s.retrieveAs(ctx, c.p, nat.proto, nat.url, ctype, out); err == nil {
|
||||
if b, got, natIn, natOut, err = nat.answer(b); err != nil {
|
||||
if b, got, natIn, natOut, err = nat.answer(ctx, b); err != nil {
|
||||
code, err = 502, fmt.Errorf("%s: %v", provider.HostOf(nat.url), err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
package gateway
|
||||
|
||||
// Alibaba's Token Plan (the Qwen AI platform's, Bailian's, Model Studio's
|
||||
// and Qwen Cloud's) reads text aloud and transcribes audio with its
|
||||
// qwen-audio models at DashScope's own API, which has no OpenAI-style
|
||||
// /audio/speech or /audio/transcriptions (help.aliyun.com/zh/model-studio/
|
||||
// qwen-audio-tts-http-api and qwen-audio-asr-http-api, read 11-18):
|
||||
//
|
||||
// POST <root>/api/v1/services/audio/tts/SpeechSynthesizer
|
||||
// {"model": …, "input": {"text": …, "voice": …, "format": "mp3"|"wav"|
|
||||
// "pcm"|"opus", "instruction": …, "rate": 0.5–2}}
|
||||
// → {"output": {"audio": {"url": <the whole file, kept 24 hours>,
|
||||
// "data": ""}}, "usage": {"characters": n}}
|
||||
//
|
||||
// POST <root>/api/v1/services/aigc/multimodal-generation/generation
|
||||
// {"model": …, "input": {"messages": [{"role": "user", "content":
|
||||
// [{"type": "input_audio", "input_audio": {"data": <data URI>}}]}]},
|
||||
// "parameters": {"format": "wav"…, "language_hints": ["zh"]}}
|
||||
// → {"output": {"text": …}, "usage": {"duration": seconds}}
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// dashScopeAudio is whether p is asked for model, a qwen-audio model of
|
||||
// the kind given, at DashScope's own API: a key (not a subscription's
|
||||
// account, another magpie or a plugin) of a DashScope provider whose plan
|
||||
// names the model, or names it qwen-audio-…-tts/-asr.
|
||||
func dashScopeAudio(p provider.Provider, model, kind string) bool {
|
||||
if p.Account != nil || p.IsPlugin() || p.IsRemoteMagpie() || !dashScope(p) {
|
||||
return false
|
||||
}
|
||||
listed := p.PlanSpeakers()
|
||||
tag := "tts"
|
||||
if kind == catalog.ServesTranscription {
|
||||
listed, tag = p.PlanTranscribers(), "asr"
|
||||
}
|
||||
if slices.ContainsFunc(listed, func(m catalog.Model) bool { return m.ID == model }) {
|
||||
return true
|
||||
}
|
||||
m := strings.ToLower(model)
|
||||
return strings.HasPrefix(m, "qwen-audio") && strings.Contains(m, "-"+tag)
|
||||
}
|
||||
|
||||
// dashScopeVoice is the voice DashScope reads in: the caller's own, or the
|
||||
// model's first listed one for none and for OpenAI's names (alloy, nova…),
|
||||
// which no qwen-audio model has. A voice belongs to its model, and another
|
||||
// model's is refused (the voice list: qwen-audio-3.0-tts-plus has
|
||||
// longanlingxin and longanlufeng, -flash longanhuan_v3.6 and others).
|
||||
func dashScopeVoice(model, voice string) string {
|
||||
if v := strings.TrimSpace(voice); v != "" {
|
||||
if _, openai := openAIVoices[strings.ToLower(v)]; !openai {
|
||||
return v
|
||||
}
|
||||
}
|
||||
if strings.Contains(strings.ToLower(model), "flash") {
|
||||
return "longanhuan_v3.6"
|
||||
}
|
||||
return "longanlingxin"
|
||||
}
|
||||
|
||||
// dashScopeSpeechTypes are the formats DashScope's speech is given in, with
|
||||
// the Content-Type each goes back with.
|
||||
var dashScopeSpeechTypes = map[string]string{"mp3": "audio/mpeg", "wav": "audio/wav", "pcm": "audio/pcm", "opus": "audio/ogg"}
|
||||
|
||||
// dashScopeSpeech asks a qwen-audio TTS model: the input read in the
|
||||
// voice, OpenAI's instructions as DashScope's instruction, speed as its
|
||||
// rate, in the format asked (mp3 by default, as OpenAI's), answered with
|
||||
// the file at the URL DashScope gives. aac and flac, which it doesn't
|
||||
// make, and a streamed answer (stream_format sse) are turned away.
|
||||
func (sp *speechRequest) dashScopeSpeech(p provider.Provider, model string) (*vendorAsk, string) {
|
||||
str := func(k string) string {
|
||||
var v string
|
||||
json.Unmarshal(sp.req[k], &v)
|
||||
return v
|
||||
}
|
||||
format := strings.ToLower(str("response_format"))
|
||||
if format == "" {
|
||||
format = "mp3"
|
||||
}
|
||||
ctype, ok := dashScopeSpeechTypes[format]
|
||||
if !ok {
|
||||
return nil, fmt.Sprintf("response_format %q isn't one DashScope's speech is made in: mp3 (the default), wav, pcm or opus", format)
|
||||
}
|
||||
if str("stream_format") == "sse" {
|
||||
return nil, "DashScope's speech is answered whole here: ask without stream_format sse"
|
||||
}
|
||||
text := str("input")
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return nil, "\"input\" is empty: there is nothing to read aloud"
|
||||
}
|
||||
input := map[string]any{"text": text, "voice": dashScopeVoice(model, str("voice")), "format": format}
|
||||
if how := strings.TrimSpace(str("instructions")); how != "" {
|
||||
input["instruction"] = how
|
||||
}
|
||||
var speed float64
|
||||
if json.Unmarshal(sp.req["speed"], &speed) == nil && speed > 0 {
|
||||
input["rate"] = min(max(speed, 0.5), 2)
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{"model": model, "input": input})
|
||||
return &vendorAsk{url: dashScopeRoot(p) + "/api/v1/services/audio/tts/SpeechSynthesizer", body: body, proto: provider.Chat,
|
||||
answer: func(ctx context.Context, b []byte) ([]byte, string, int, int, error) {
|
||||
var res struct {
|
||||
Output struct {
|
||||
Audio struct {
|
||||
URL string `json:"url"`
|
||||
Data string `json:"data"`
|
||||
} `json:"audio"`
|
||||
} `json:"output"`
|
||||
Usage struct {
|
||||
Characters int `json:"characters"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal(b, &res) != nil {
|
||||
return nil, "", 0, 0, fmt.Errorf("the answer isn't DashScope's speech: %.200s", b)
|
||||
}
|
||||
a := res.Output.Audio
|
||||
if a.Data != "" {
|
||||
out, err := base64.StdEncoding.DecodeString(a.Data)
|
||||
if err != nil {
|
||||
return nil, "", 0, 0, errors.New("the speech's audio.data isn't base64")
|
||||
}
|
||||
return out, ctype, res.Usage.Characters, 0, nil
|
||||
}
|
||||
if a.URL == "" {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
return nil, "", 0, 0, errors.New(said)
|
||||
}
|
||||
return nil, "", 0, 0, fmt.Errorf("the answer has no audio: %.200s", b)
|
||||
}
|
||||
out, err := fetchVendorFile(ctx, p, a.URL, maxSpeechBytes)
|
||||
if err != nil {
|
||||
return nil, "", 0, 0, fmt.Errorf("the speech couldn't be fetched: %v", err)
|
||||
}
|
||||
return out, ctype, res.Usage.Characters, 0, nil
|
||||
}}, ""
|
||||
}
|
||||
|
||||
// maxSpeechBytes bounds a speech file fetched from a vendor's URL: an hour
|
||||
// of 48 kHz WAV is ~350MB, and a TTS request reads far less than that.
|
||||
const maxSpeechBytes = 256 << 20
|
||||
|
||||
// fetchVendorFile is the file at url, a URL a vendor's answer gave: fetched
|
||||
// as one a caller names is, from a public address or the vendor's own host
|
||||
// (vendorClient), through p's proxy, at most limit bytes.
|
||||
func fetchVendorFile(ctx context.Context, p provider.Provider, url string, limit int64) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(p.Via(ctx), http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := vendorClient(p).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(res.Body, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(b)) > limit {
|
||||
return nil, fmt.Errorf("it is over %d MB", limit>>20)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// nativeAt asks a DashScope plan's qwen-audio ASR model on its own API;
|
||||
// any other is asked at OpenAI's /audio/transcriptions as the form came.
|
||||
func (a *audioForm) nativeAt(p provider.Provider, model string) (*vendorAsk, string) {
|
||||
if !dashScopeAudio(p, model, catalog.ServesTranscription) {
|
||||
return nil, ""
|
||||
}
|
||||
return a.dashScopeTranscription(p, model)
|
||||
}
|
||||
|
||||
// dashScopeTranscription asks a qwen-audio ASR model: the form's file as
|
||||
// a data URI, in the format its name or type says (wav by default), and
|
||||
// its language as DashScope's hint. The transcript is given back as
|
||||
// OpenAI's json (the default), text or verbose_json; srt and vtt, which
|
||||
// need timings DashScope's whole answer doesn't give per segment, and a
|
||||
// translation, which it doesn't make, are turned away. The prompt has no
|
||||
// field on DashScope's API and isn't sent.
|
||||
func (a *audioForm) dashScopeTranscription(p provider.Provider, model string) (*vendorAsk, string) {
|
||||
if a.op == "translations" {
|
||||
return nil, model + " transcribes in the language spoken; DashScope's ASR makes no translation: ask /v1/audio/transcriptions"
|
||||
}
|
||||
format := strings.ToLower(a.format)
|
||||
switch format {
|
||||
case "", "json", "text", "verbose_json":
|
||||
default:
|
||||
return nil, fmt.Sprintf("response_format %q isn't one DashScope's transcript can be given back in: json (the default), text or verbose_json", a.format)
|
||||
}
|
||||
audio, name, ftype, err := a.file()
|
||||
if err != nil {
|
||||
return nil, err.Error()
|
||||
}
|
||||
if len(audio) == 0 {
|
||||
return nil, "the form has no \"file\": send the audio as its file part"
|
||||
}
|
||||
kind := strings.TrimPrefix(strings.ToLower(path.Ext(name)), ".")
|
||||
mt, _, _ := mime.ParseMediaType(ftype)
|
||||
if kind == "" {
|
||||
if sub, ok := strings.CutPrefix(mt, "audio/"); ok {
|
||||
kind = strings.TrimPrefix(sub, "x-")
|
||||
}
|
||||
}
|
||||
switch kind {
|
||||
case "", "wave":
|
||||
kind = "wav"
|
||||
case "mpeg", "mpga":
|
||||
kind = "mp3"
|
||||
case "ogg", "oga":
|
||||
kind = "opus"
|
||||
}
|
||||
if !strings.HasPrefix(mt, "audio/") {
|
||||
mt = "audio/" + kind
|
||||
}
|
||||
params := map[string]any{"format": kind}
|
||||
if l := strings.TrimSpace(a.language); l != "" {
|
||||
params["language_hints"] = []string{l}
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"model": model,
|
||||
"input": map[string]any{"messages": []map[string]any{{"role": "user", "content": []map[string]any{{
|
||||
"type": "input_audio", "input_audio": map[string]string{"data": "data:" + mt + ";base64," + base64.StdEncoding.EncodeToString(audio)},
|
||||
}}}}},
|
||||
"parameters": params,
|
||||
})
|
||||
return &vendorAsk{url: dashScopeRoot(p) + "/api/v1/services/aigc/multimodal-generation/generation", body: body, proto: provider.Chat,
|
||||
answer: func(_ context.Context, b []byte) ([]byte, string, int, int, error) {
|
||||
var res struct {
|
||||
Output struct {
|
||||
Text string `json:"text"`
|
||||
Sentence struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"sentence"`
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
} `json:"output"`
|
||||
Usage struct {
|
||||
Duration float64 `json:"duration"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal(b, &res) != nil {
|
||||
return nil, "", 0, 0, fmt.Errorf("the answer isn't DashScope's transcript: %.200s", b)
|
||||
}
|
||||
text := res.Output.Text
|
||||
if text == "" {
|
||||
text = res.Output.Sentence.Text
|
||||
}
|
||||
if text == "" && len(res.Output.Choices) > 0 {
|
||||
text = chatContentText(res.Output.Choices[0].Message.Content)
|
||||
}
|
||||
if text == "" && !bytes.Contains(b, []byte(`"output"`)) {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
return nil, "", 0, 0, errors.New(said)
|
||||
}
|
||||
return nil, "", 0, 0, fmt.Errorf("the answer has no transcript: %.200s", b)
|
||||
}
|
||||
switch format {
|
||||
case "text":
|
||||
return []byte(text), "text/plain; charset=utf-8", 0, 0, nil
|
||||
case "verbose_json":
|
||||
out, _ := json.Marshal(map[string]any{"task": "transcribe", "language": a.language, "duration": res.Usage.Duration, "text": text, "segments": []any{}})
|
||||
return out, "application/json", 0, 0, nil
|
||||
}
|
||||
out, _ := json.Marshal(map[string]string{"text": text})
|
||||
return out, "application/json", 0, 0, nil
|
||||
}}, ""
|
||||
}
|
||||
|
||||
// chatContentText is a chat message's content as text: a string, or its
|
||||
// text parts one after another (DashScope's multimodal answer gives
|
||||
// [{"text": …}]).
|
||||
func chatContentText(raw json.RawMessage) string {
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return s
|
||||
}
|
||||
var parts []struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
json.Unmarshal(raw, &parts)
|
||||
var b strings.Builder
|
||||
for _, p := range parts {
|
||||
b.WriteString(p.Text)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
@@ -30,10 +31,12 @@ type nativeRetrieval interface {
|
||||
// turned into what the client is given (bytes, Content-Type and the
|
||||
// tokens it counted).
|
||||
type vendorAsk struct {
|
||||
url string
|
||||
body []byte
|
||||
proto provider.Protocol
|
||||
answer func(b []byte) (out []byte, ctype string, in, outTokens int, err error)
|
||||
url string
|
||||
body []byte
|
||||
proto provider.Protocol
|
||||
// answer is given the request's context, for an answer that is a URL
|
||||
// to fetch the audio from (DashScope's)
|
||||
answer func(ctx context.Context, b []byte) (out []byte, ctype string, in, outTokens int, err error)
|
||||
}
|
||||
|
||||
// geminiSpeechBase is the Gemini API base p is asked for model at, a
|
||||
@@ -100,7 +103,8 @@ func geminiVoice(v string) string {
|
||||
return defaultGeminiVoice
|
||||
}
|
||||
|
||||
// nativeAt asks a Gemini TTS model on generateContent: the input to read,
|
||||
// nativeAt asks a DashScope plan's qwen-audio TTS model on its own API
|
||||
// (speech_dashscope.go), and a Gemini TTS model on generateContent: the input to read,
|
||||
// after the instructions on how (Gemini takes them in the prompt: "Say
|
||||
// cheerfully: …"), in one prebuilt voice, answered with audio alone. speed
|
||||
// has no Gemini field and is left out. The answer is 24 kHz PCM, given back
|
||||
@@ -110,6 +114,9 @@ func geminiVoice(v string) string {
|
||||
// fail them all, while players read a WAV by its header). A streamed
|
||||
// answer (stream_format sse) is turned away: generateContent's is whole.
|
||||
func (sp *speechRequest) nativeAt(p provider.Provider, model string) (*vendorAsk, string) {
|
||||
if dashScopeAudio(p, model, catalog.ServesSpeech) {
|
||||
return sp.dashScopeSpeech(p, model)
|
||||
}
|
||||
base := strings.TrimRight(geminiSpeechBase(p, model), "/")
|
||||
if base == "" {
|
||||
return nil, ""
|
||||
@@ -147,7 +154,7 @@ func (sp *speechRequest) nativeAt(p provider.Provider, model string) (*vendorAsk
|
||||
if p.IsVertex() {
|
||||
url = base + provider.VertexWholePath(model)
|
||||
}
|
||||
return &vendorAsk{url: url, body: body, proto: provider.Gemini, answer: func(b []byte) ([]byte, string, int, int, error) {
|
||||
return &vendorAsk{url: url, body: body, proto: provider.Gemini, answer: func(_ context.Context, b []byte) ([]byte, string, int, int, error) {
|
||||
return geminiAudio(b, format == "pcm")
|
||||
}}, ""
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ func (s *Server) transcribe(path, operation string) http.HandlerFunc {
|
||||
writeError(w, provider.Chat, 400, err.Error())
|
||||
return
|
||||
}
|
||||
a.op = operation
|
||||
if a.model == "" {
|
||||
writeError(w, provider.Chat, 400, "name the model: the form's \"model\" is a magpie model id, provider/model (openai/whisper-1, groq/whisper-large-v3)")
|
||||
return
|
||||
@@ -52,6 +53,11 @@ type audioForm struct {
|
||||
boundary string
|
||||
model string
|
||||
prompt string
|
||||
// op is the API asked: transcriptions or translations
|
||||
op string
|
||||
// language and format are the form's language and response_format,
|
||||
// for a vendor asked in its own shape (DashScope's, speech_dashscope.go)
|
||||
language, format string
|
||||
// masked is the prompt as it goes to a vendor, when masking changed it
|
||||
masked *string
|
||||
}
|
||||
@@ -74,7 +80,7 @@ func readAudioForm(ctype string, body []byte) (*audioForm, error) {
|
||||
return nil, errors.New("the multipart form doesn't parse: " + err.Error())
|
||||
}
|
||||
switch p.FormName() {
|
||||
case "model", "prompt":
|
||||
case "model", "prompt", "language", "response_format":
|
||||
if p.FileName() != "" {
|
||||
continue
|
||||
}
|
||||
@@ -82,16 +88,45 @@ func readAudioForm(ctype string, body []byte) (*audioForm, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("the multipart form doesn't parse: " + err.Error())
|
||||
}
|
||||
if p.FormName() == "model" {
|
||||
switch p.FormName() {
|
||||
case "model":
|
||||
a.model = strings.TrimSpace(string(v))
|
||||
} else {
|
||||
case "prompt":
|
||||
a.prompt = string(v)
|
||||
case "language":
|
||||
a.language = strings.TrimSpace(string(v))
|
||||
default:
|
||||
a.format = strings.TrimSpace(string(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// file is the form's first file part: its bytes, name and type. It is read
|
||||
// only for a vendor that takes the audio in a shape of its own, so a form
|
||||
// passed on as sent is never copied.
|
||||
func (a *audioForm) file() (audio []byte, name, ctype string, err error) {
|
||||
mr := multipart.NewReader(bytes.NewReader(a.raw), a.boundary)
|
||||
for {
|
||||
p, err := mr.NextRawPart()
|
||||
if err == io.EOF {
|
||||
return nil, "", "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", "", errors.New("the multipart form doesn't parse: " + err.Error())
|
||||
}
|
||||
if p.FormName() != "file" {
|
||||
continue
|
||||
}
|
||||
v, err := io.ReadAll(p)
|
||||
if err != nil {
|
||||
return nil, "", "", errors.New("the multipart form doesn't parse: " + err.Error())
|
||||
}
|
||||
return v, p.FileName(), p.Header.Get("Content-Type"), nil
|
||||
}
|
||||
}
|
||||
|
||||
// mask masks the prompt, the form's only text a vendor is sent; the
|
||||
// audio can't be, and the transcript gets the masked values back.
|
||||
func (a *audioForm) mask(ctx context.Context, w http.ResponseWriter) (http.ResponseWriter, func(), maskHits, string, error) {
|
||||
|
||||
@@ -904,8 +904,8 @@ func videoMaker(id string) (p provider.Provider, vendorID string, started time.T
|
||||
return p, "", started, fmt.Errorf("%q isn't the id of a video magpie is making", id)
|
||||
}
|
||||
found, ferr := provider.Find(pid)
|
||||
if ferr == nil && filmsMiniMax(*found) {
|
||||
// a MiniMax task is its key's account's: asked on that key
|
||||
if ferr == nil && (filmsMiniMax(*found) || filmsDashScope(*found)) {
|
||||
// a MiniMax or DashScope task is its key's account's: asked on that key
|
||||
q, ok := markedKey(*found, by)
|
||||
if !ok {
|
||||
return p, "", started, fmt.Errorf("this video was started with a key of %s that is no longer on: turn it back on to get the video", found.Name)
|
||||
@@ -1034,6 +1034,9 @@ func (s *Server) videoStatus(ctx context.Context, p provider.Provider, vendorID
|
||||
if filmsMiniMax(p) {
|
||||
return s.minimaxVideoStatus(ctx, p, vendorID)
|
||||
}
|
||||
if filmsDashScope(p) {
|
||||
return s.dashScopeVideoStatus(ctx, p, vendorID)
|
||||
}
|
||||
var st videoState
|
||||
at := grokVideosRoot(p) + "/videos/" + url.PathEscape(vendorID)
|
||||
ark := p.Preset == "volcengine" || isArk(p)
|
||||
@@ -1305,10 +1308,11 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
|
||||
// the key, as a plan's does, and it is asked after there; an xAI
|
||||
// key's request likewise
|
||||
onKey = isArk(p) || filmsXAI(p, model)
|
||||
} else if makesMiniMaxVideo(p, model) {
|
||||
} else if makesMiniMaxVideo(p, model) || makesDashScopeVideo(p, model) {
|
||||
// on the first key a chat for the model would go to that the
|
||||
// calling key may use, the next while one's plan doesn't make H3
|
||||
// (a Token Plan's); the video's id names the key it is asked on
|
||||
// (a Token Plan's); the video's id names the key it is asked on,
|
||||
// as a DashScope task is its key's
|
||||
cs, code, msg := s.onKeys(r, p, model, f.Model)
|
||||
if code != 0 {
|
||||
return videoStart{p: p}, code, errors.New(msg)
|
||||
@@ -1342,10 +1346,11 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
|
||||
xai := !v.remote && filmsXAI(p, model)
|
||||
v.custom = !v.remote && !volcengine && !xai && filmsCustom(p, model)
|
||||
minimax := !v.remote && !v.custom && makesMiniMaxVideo(p, model)
|
||||
dashscope := !v.remote && !v.custom && !minimax && makesDashScopeVideo(p, model)
|
||||
// any grok-imagine-video*, not only those listed: the vendor's newer ones work before magpie names them
|
||||
if !v.remote && !v.custom && !volcengine && !minimax && !xai && (!drawsGrok(p) || !strings.HasPrefix(model, grokVideoFamily)) {
|
||||
if !v.remote && !v.custom && !volcengine && !minimax && !dashscope && !xai && (!drawsGrok(p) || !strings.HasPrefix(model, grokVideoFamily)) {
|
||||
v.unfit = true
|
||||
return v, 400, fmt.Errorf(`%s/%s can't make videos: magpie makes videos with a Grok subscription's or an xAI API key's grok-imagine-video, Volcengine Agent Plan's or an Ark key's Seedance models, a MiniMax API key's MiniMax-H3 models, another magpie's, and a provider's models its own model list marks "kind": "video" or that you mark a Video model (right-click the model in the provider's editor: Makes…)`, p.ID, model)
|
||||
return v, 400, fmt.Errorf(`%s/%s can't make videos: magpie makes videos with a Grok subscription's or an xAI API key's grok-imagine-video, Volcengine Agent Plan's or an Ark key's Seedance models, a MiniMax API key's MiniMax-H3 models, an Alibaba Token Plan's Wan 3.0 and HappyHorse models, another magpie's, and a provider's models its own model list marks "kind": "video" or that you mark a Video model (right-click the model in the provider's editor: Makes…)`, p.ID, model)
|
||||
}
|
||||
// another magpie is asked at its videos API, which says itself what
|
||||
// it can't make
|
||||
@@ -1364,6 +1369,12 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
|
||||
return v, 400, err
|
||||
}
|
||||
at, field = minimaxHost(p)+"/v2/video_generation", "task_id"
|
||||
case dashscope:
|
||||
var err error
|
||||
if body, err = dashScopeVideoBody(model, f); err != nil {
|
||||
return v, 400, err
|
||||
}
|
||||
at, field = dashScopeVideoURL(p), "task_id"
|
||||
default:
|
||||
var err error
|
||||
if body, err = grokVideoBody(model, f); err != nil {
|
||||
@@ -1371,12 +1382,25 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
|
||||
}
|
||||
}
|
||||
v.field, v.asked = field, true
|
||||
b, code, err := s.send(ctx, p, at, "application/json", body, true)
|
||||
var extra http.Header
|
||||
if dashscope {
|
||||
extra = dashScopeAsync
|
||||
}
|
||||
b, code, err := s.sendWith(ctx, p, http.MethodPost, at, "application/json", body, true, extra)
|
||||
// a key answering 404 that it doesn't serve the model hands it to the
|
||||
// next (#1657), as a drawing does; the id names the key that started it
|
||||
for ; err != nil && len(keys) > 0 && ctx.Err() == nil && (keyLacksModel(code, err) || minimax && minimaxLacksH3(b)); keys = keys[1:] {
|
||||
p = keys[0].p
|
||||
b, code, err = s.send(ctx, p, at, "application/json", body, true)
|
||||
b, code, err = s.sendWith(ctx, p, http.MethodPost, at, "application/json", body, true, extra)
|
||||
}
|
||||
if dashscope {
|
||||
if err != nil {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
err = fmt.Errorf("%s: %d %s: %s", provider.HostOf(at), code, http.StatusText(code), said)
|
||||
}
|
||||
} else if b, err = dashScopeStarted(p, model, b); err != nil {
|
||||
code = 502
|
||||
}
|
||||
}
|
||||
if minimax {
|
||||
if err != nil {
|
||||
@@ -1402,7 +1426,7 @@ func videoAsker(r *http.Request, p provider.Provider) (provider.Provider, string
|
||||
if !held {
|
||||
return p, ""
|
||||
}
|
||||
if !p.IsRemoteMagpie() && (filmsOpenAI(p) || filmsMiniMax(p) || isArk(p) && len(customVideomakers(p)) > 0) {
|
||||
if !p.IsRemoteMagpie() && (filmsOpenAI(p) || filmsMiniMax(p) || filmsDashScope(p) || isArk(p) && len(customVideomakers(p)) > 0) {
|
||||
if p.Key == "" && p.Account == nil || accountAllowed(who, candidate{p: p}) {
|
||||
return p, ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package gateway
|
||||
|
||||
// Alibaba's Token Plan (the Qwen AI platform's, Bailian's, Model Studio's
|
||||
// and Qwen Cloud's) makes videos with Wan 3.0 and HappyHorse 1.1 at
|
||||
// DashScope's own asynchronous API (help.aliyun.com/zh/model-studio/
|
||||
// wan3-video-generation-api-reference, docs.qwencloud.com's Token Plan
|
||||
// "Integrate multimodal generation", read 11-18):
|
||||
//
|
||||
// POST <root>/api/v1/services/aigc/video-generation/video-synthesis
|
||||
// X-DashScope-Async: enable
|
||||
// {"model": …, "input": {"prompt": …, "media": [{"type": "first_frame"|
|
||||
// "last_frame"|"reference_image", "url": <URL or data URL>}…]},
|
||||
// "parameters": {"resolution": "1080P"|"720P"|"480P", "ratio": "16:9"…,
|
||||
// "duration": 5, "watermark": false…}}
|
||||
//
|
||||
// answers with output.task_id; GET <root>/api/v1/tasks/<task_id> with
|
||||
// output.task_status (PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED,
|
||||
// UNKNOWN) and, once it has succeeded, output.video_url, an MP4 kept for 24
|
||||
// hours. The task answer names no model, so the video's id carries it.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// filmsDashScope is whether p is a key of a DashScope plan that names video
|
||||
// models (the Token Plans' Wan 3.0 and HappyHorse): not a subscription's
|
||||
// account, another magpie or a plugin.
|
||||
func filmsDashScope(p provider.Provider) bool {
|
||||
return p.Account == nil && !p.IsPlugin() && !p.IsRemoteMagpie() && dashScope(p) && len(p.PlanVideos()) > 0
|
||||
}
|
||||
|
||||
// makesDashScopeVideo is whether model is one of p's plan's video models.
|
||||
func makesDashScopeVideo(p provider.Provider, model string) bool {
|
||||
return filmsDashScope(p) && slices.ContainsFunc(p.PlanVideos(), func(m catalog.Model) bool { return m.ID == model })
|
||||
}
|
||||
|
||||
// dashScopeVideoRatios are the ratios DashScope's video API takes, besides
|
||||
// adaptive (the first frame's own, its default).
|
||||
var dashScopeVideoRatios = []string{"21:9", "16:9", "4:3", "1:1", "3:4", "9:16"}
|
||||
|
||||
// dashScopeInput are the fields of the caller's own that go in input, not
|
||||
// parameters.
|
||||
var dashScopeInput = []string{"negative_prompt"}
|
||||
|
||||
// dashScopeVideoBody is f as DashScope's video-synthesis API takes it: the
|
||||
// prompt and images in input, each image's type saying what it is, the
|
||||
// resolution and ratio from size unless the caller named their own, the
|
||||
// length in whole seconds, and the caller's other fields as they came
|
||||
// (watermark, audio, prompt_extend, seed…), DashScope's own.
|
||||
func dashScopeVideoBody(model string, f filming) ([]byte, error) {
|
||||
if len(f.References) > 10 {
|
||||
return nil, fmt.Errorf("DashScope takes at most 10 reference images, not %d", len(f.References))
|
||||
}
|
||||
input := map[string]any{"prompt": f.Prompt}
|
||||
params := map[string]any{}
|
||||
for k, v := range f.Extra {
|
||||
if f.Form {
|
||||
v = formValue(k, v, []string{"resolution", "ratio", "negative_prompt"})
|
||||
}
|
||||
if slices.Contains(dashScopeInput, k) {
|
||||
input[k] = v
|
||||
} else {
|
||||
params[k] = v
|
||||
}
|
||||
}
|
||||
var media []map[string]string
|
||||
add := func(pic picture, kind string) {
|
||||
media = append(media, map[string]string{"type": kind, "url": pic.dataURL()})
|
||||
}
|
||||
if f.Start != nil {
|
||||
add(*f.Start, "first_frame")
|
||||
}
|
||||
if f.End != nil {
|
||||
add(*f.End, "last_frame")
|
||||
}
|
||||
for _, pic := range f.References {
|
||||
add(pic, "reference_image")
|
||||
}
|
||||
if len(media) > 0 {
|
||||
input["media"] = media
|
||||
}
|
||||
if _, ok := params["resolution"]; !ok {
|
||||
if r := pixelResolution(f.Size); r != "" {
|
||||
params["resolution"] = strings.ToUpper(r)
|
||||
}
|
||||
} else if s, ok := params["resolution"].(string); ok {
|
||||
params["resolution"] = strings.ToUpper(strings.TrimSpace(s))
|
||||
}
|
||||
if _, ok := params["ratio"]; !ok {
|
||||
size := strings.TrimSpace(f.Size)
|
||||
if a, b, ok := strings.Cut(size, ":"); ok {
|
||||
size = a + "x" + b
|
||||
}
|
||||
if r := aspectAmong(size, dashScopeVideoRatios); r != "" {
|
||||
params["ratio"] = r
|
||||
}
|
||||
}
|
||||
if f.Seconds != "" {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(f.Seconds))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seconds %q isn't a whole number of seconds, as DashScope's video models take", f.Seconds)
|
||||
}
|
||||
params["duration"] = n
|
||||
}
|
||||
if _, ok := params["watermark"]; !ok {
|
||||
params["watermark"] = false
|
||||
}
|
||||
return json.Marshal(map[string]any{"model": model, "input": input, "parameters": params})
|
||||
}
|
||||
|
||||
// dashScopeVideoURL is where p starts a video.
|
||||
func dashScopeVideoURL(p provider.Provider) string {
|
||||
return dashScopeRoot(p) + "/api/v1/services/aigc/video-generation/video-synthesis"
|
||||
}
|
||||
|
||||
// dashScopeAsync is the header DashScope starts a task with, and without
|
||||
// which its video API answers that it takes none but async calls.
|
||||
var dashScopeAsync = http.Header{"X-DashScope-Async": {"enable"}}
|
||||
|
||||
// dashScopeStarted is the task DashScope's answer b starts, as videosCreate
|
||||
// reads one: {"task_id": <the video's vendor id>}, the model put in it as
|
||||
// dashScopeTask reads it back. An answer with no task says what DashScope
|
||||
// said.
|
||||
func dashScopeStarted(p provider.Provider, model string, b []byte) ([]byte, error) {
|
||||
var res struct {
|
||||
Output struct {
|
||||
TaskID string `json:"task_id"`
|
||||
} `json:"output"`
|
||||
}
|
||||
if json.Unmarshal(b, &res) != nil || res.Output.TaskID == "" {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
return nil, fmt.Errorf("%s: %s", p.Name, said)
|
||||
}
|
||||
return nil, fmt.Errorf("%s started no video: its answer had no output.task_id: %.200s", p.Name, b)
|
||||
}
|
||||
out, _ := json.Marshal(map[string]string{"task_id": base64.RawURLEncoding.EncodeToString([]byte(model + " " + res.Output.TaskID))})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// dashScopeTask is the model and DashScope's task id a video's vendor id
|
||||
// holds (dashScopeStarted).
|
||||
func dashScopeTask(vendorID string) (model, task string, ok bool) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(vendorID)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
model, task, ok = strings.Cut(string(b), " ")
|
||||
return model, task, ok && task != "" && !strings.ContainsAny(task, "/?#")
|
||||
}
|
||||
|
||||
// dashScopeVideoStatus asks DashScope how a video task is going, as a
|
||||
// videoState.
|
||||
func (s *Server) dashScopeVideoStatus(ctx context.Context, p provider.Provider, vendorID string) (videoState, int, error) {
|
||||
var st videoState
|
||||
model, task, ok := dashScopeTask(vendorID)
|
||||
if !ok {
|
||||
return st, 404, errors.New("this isn't the id of a video magpie started at DashScope")
|
||||
}
|
||||
at := dashScopeRoot(p) + "/api/v1/tasks/" + url.PathEscape(task)
|
||||
b, code, err := s.sendAs(ctx, p, http.MethodGet, at, "", nil, true)
|
||||
if err != nil {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
err = fmt.Errorf("%s: %d %s: %s", provider.HostOf(at), code, http.StatusText(code), said)
|
||||
}
|
||||
return st, code, err
|
||||
}
|
||||
var res struct {
|
||||
Output struct {
|
||||
Status string `json:"task_status"`
|
||||
VideoURL string `json:"video_url"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"output"`
|
||||
Usage struct {
|
||||
Duration float64 `json:"duration"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &res); err != nil || res.Output.Status == "" {
|
||||
if said := dashScopeSaid(b); said != "" {
|
||||
return st, 502, fmt.Errorf("%s: %s", p.Name, said)
|
||||
}
|
||||
return st, 502, fmt.Errorf("%s's answer isn't a video task's: %.200s", p.Name, b)
|
||||
}
|
||||
st.Model, st.Duration = model, res.Usage.Duration
|
||||
switch res.Output.Status {
|
||||
case "SUCCEEDED":
|
||||
st.Status, st.Video.URL = "succeeded", res.Output.VideoURL
|
||||
case "RUNNING":
|
||||
st.Status = "running"
|
||||
case "FAILED", "UNKNOWN":
|
||||
// UNKNOWN: a task DashScope no longer has, past its 24 hours
|
||||
st.Status = "failed"
|
||||
st.Error.Code, st.Error.Message = res.Output.Code, res.Output.Message
|
||||
if res.Output.Status == "UNKNOWN" && st.Error.Message == "" {
|
||||
st.Status, st.Error.Code = "expired", "expired"
|
||||
}
|
||||
case "CANCELED":
|
||||
st.Status = "cancelled"
|
||||
default: // PENDING
|
||||
st.Status = "queued"
|
||||
}
|
||||
return st, 200, nil
|
||||
}
|
||||
@@ -1330,14 +1330,31 @@ func (p Provider) PlanRerankers() []catalog.Model {
|
||||
return p.planMedia(func(r *Region) []string { return r.Rerankers }, false, false, catalog.ServesRerank)
|
||||
}
|
||||
|
||||
// PlanRetrieval are the preset's models of kind's (catalog.ServesEmbedding
|
||||
// or ServesRerank), or both for "".
|
||||
// PlanSpeakers are the text-to-speech models the preset names, served on
|
||||
// /v1/audio/speech.
|
||||
func (p Provider) PlanSpeakers() []catalog.Model {
|
||||
return p.planMedia(func(r *Region) []string { return r.Speakers }, false, false, catalog.ServesSpeech)
|
||||
}
|
||||
|
||||
// PlanTranscribers are the speech-to-text models the preset names, served
|
||||
// on /v1/audio/transcriptions.
|
||||
func (p Provider) PlanTranscribers() []catalog.Model {
|
||||
return p.planMedia(func(r *Region) []string { return r.Transcribers }, false, false, catalog.ServesTranscription)
|
||||
}
|
||||
|
||||
// PlanRetrieval are the preset's models of kind's (catalog.ServesEmbedding,
|
||||
// ServesRerank, ServesSpeech or ServesTranscription), or its embedding and
|
||||
// rerank models for "".
|
||||
func (p Provider) PlanRetrieval(kind string) []catalog.Model {
|
||||
switch kind {
|
||||
case catalog.ServesEmbedding:
|
||||
return p.PlanEmbeddings()
|
||||
case catalog.ServesRerank:
|
||||
return p.PlanRerankers()
|
||||
case catalog.ServesSpeech:
|
||||
return p.PlanSpeakers()
|
||||
case catalog.ServesTranscription:
|
||||
return p.PlanTranscribers()
|
||||
case "":
|
||||
return append(p.PlanEmbeddings(), p.PlanRerankers()...)
|
||||
}
|
||||
@@ -1362,7 +1379,8 @@ func (p Provider) planMedia(ids func(*Region) []string, draws, films bool, serve
|
||||
return nil
|
||||
}
|
||||
// a preset with no regions names its own (Voyage AI's)
|
||||
own := &Region{Embeddings: pr.Embeddings, Rerankers: pr.Rerankers}
|
||||
own := &Region{Embeddings: pr.Embeddings, Rerankers: pr.Rerankers, Drawers: pr.Drawers, Videos: pr.Videos,
|
||||
Speakers: pr.Speakers, Transcribers: pr.Transcribers}
|
||||
// keys on plans of their own (KeyAccount.Plan): each plan's, once
|
||||
views := []Provider{p}
|
||||
if p.plansMixed() {
|
||||
|
||||
@@ -80,6 +80,15 @@ type PresetDef struct {
|
||||
// A Region's own lists stand over them.
|
||||
Embeddings []string `json:"embeddings,omitempty"`
|
||||
Rerankers []string `json:"rerankers,omitempty"`
|
||||
// Drawers, Videos, Speakers and Transcribers are the image, video,
|
||||
// text-to-speech and speech-to-text models of a plan that names them
|
||||
// beside its text models (Alibaba's Token Plans), for a preset with no
|
||||
// regions: served on /v1/images, /v1/videos, /v1/audio/speech and
|
||||
// /v1/audio/transcriptions, kept out of agents' model pickers.
|
||||
Drawers []string `json:"drawers,omitempty"`
|
||||
Videos []string `json:"videos,omitempty"`
|
||||
Speakers []string `json:"speakers,omitempty"`
|
||||
Transcribers []string `json:"transcribers,omitempty"`
|
||||
}
|
||||
|
||||
// Region is one base-URL option of a preset that offers several. The first
|
||||
@@ -113,6 +122,10 @@ type Region struct {
|
||||
Rerankers []string `json:"rerankers,omitempty"`
|
||||
Drawers []string `json:"drawers,omitempty"`
|
||||
Videos []string `json:"videos,omitempty"`
|
||||
// Speakers and Transcribers are its text-to-speech and speech-to-text
|
||||
// models, as PresetDef's.
|
||||
Speakers []string `json:"speakers,omitempty"`
|
||||
Transcribers []string `json:"transcribers,omitempty"`
|
||||
// Images says which of Models take images, as the vendor's own list
|
||||
// says, for a plan whose /models doesn't list its models: a model
|
||||
// it leaves out is judged as before (models.dev, the user's say).
|
||||
@@ -162,9 +175,25 @@ var arkPlanImages = map[string]bool{
|
||||
}
|
||||
|
||||
// alibabaPlanModels are the text models of Alibaba's Token Plan, the same
|
||||
// on the Qwen AI platform's and on Bailian's, as their overviews list them.
|
||||
var alibabaPlanModels = []string{"auto", "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash",
|
||||
"deepseek-v4.1-flash", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "glm-5.3", "glm-5.2"}
|
||||
// on the Qwen AI platform's, on Bailian's, on Model Studio's and on Qwen
|
||||
// Cloud's, as their overviews list them (read 11-18).
|
||||
var alibabaPlanModels = []string{"auto", "qwen4-max", "qwen4-max-preview", "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash",
|
||||
"deepseek-v4.1-flash", "deepseek-v4.1-flash-1017", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "glm-5.3", "glm-5.2"}
|
||||
|
||||
// The Token Plan's other models, the same on its four hosts, each asked on
|
||||
// DashScope's own API at the host's root (gateway: draw_dashscope.go,
|
||||
// speech_dashscope.go, video_dashscope.go): image generation on
|
||||
// multimodal-generation, video on video-synthesis polled at /api/v1/tasks,
|
||||
// speech on audio/tts/SpeechSynthesizer and transcription on
|
||||
// multimodal-generation. Its realtime model is on /api-ws/v1/realtime,
|
||||
// which /v1/realtime reaches (realtime.go). Qwen Cloud's plan also draws
|
||||
// with Qwen-Image 2.0.
|
||||
var (
|
||||
alibabaPlanDrawers = []string{"qwen-image-3.0-pro", "wan2.7-image", "wan2.7-image-pro"}
|
||||
alibabaPlanVideos = []string{"wan3.0-video", "happyhorse-1.1-t2v", "happyhorse-1.1-i2v", "happyhorse-1.1-r2v"}
|
||||
alibabaPlanSpeakers = []string{"qwen-audio-3.0-tts-plus"}
|
||||
alibabaPlanTranscribers = []string{"qwen-audio-3.0-asr-flash"}
|
||||
)
|
||||
|
||||
// presets are ordered as they appear in the picker.
|
||||
var presets = []PresetDef{
|
||||
@@ -420,7 +449,8 @@ var presets = []PresetDef{
|
||||
Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic",
|
||||
Note: "Qwen AI platform · subscription",
|
||||
Website: "https://platform.qianwenai.com/docs/token-plan/overview", KeysURL: "https://platform.qianwenai.com/home/analytics/token-plan/individual",
|
||||
Models: alibabaPlanModels},
|
||||
Models: alibabaPlanModels,
|
||||
Drawers: alibabaPlanDrawers, Videos: alibabaPlanVideos, Speakers: alibabaPlanSpeakers, Transcribers: alibabaPlanTranscribers},
|
||||
// Bailian's also answers its decision model, decision-model-preview, on
|
||||
// System One at /compatible-mode/v1/systemone with the same key
|
||||
// (token-plan-decision-model; the personal plan only), so a routing
|
||||
@@ -430,7 +460,8 @@ var presets = []PresetDef{
|
||||
Decide: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
|
||||
Note: "Alibaba Cloud Bailian · subscription",
|
||||
Website: "https://help.aliyun.com/zh/model-studio/token-plan-overview", KeysURL: "https://bailian.console.aliyun.com/cn-beijing/subscription/token-plan/personal",
|
||||
Models: alibabaPlanModels},
|
||||
Models: alibabaPlanModels,
|
||||
Drawers: alibabaPlanDrawers, Videos: alibabaPlanVideos, Speakers: alibabaPlanSpeakers, Transcribers: alibabaPlanTranscribers},
|
||||
// Alibaba Cloud's international Token Plan, the same plan at the
|
||||
// Singapore host (sk-sp- keys, #2940). Its quota is read like Bailian's,
|
||||
// with the account's AccessKey (alibaba_usage.go).
|
||||
@@ -438,7 +469,8 @@ var presets = []PresetDef{
|
||||
Chat: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", Anthropic: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
|
||||
Note: "Alibaba Cloud Model Studio · subscription",
|
||||
Website: "https://www.alibabacloud.com/help/en/model-studio/token-plan-personal-quick-start", KeysURL: "https://modelstudio.console.alibabacloud.com/ap-southeast-1/?tab=globalset#/efm/token_plan",
|
||||
Models: alibabaPlanModels},
|
||||
Models: alibabaPlanModels,
|
||||
Drawers: alibabaPlanDrawers, Videos: alibabaPlanVideos, Speakers: alibabaPlanSpeakers, Transcribers: alibabaPlanTranscribers},
|
||||
// Qwen Cloud (qwencloud.com) is Alibaba's international Qwen platform,
|
||||
// on keys of its own made at home.qwencloud.com, at
|
||||
// {region}.maas.qwencloudapi.com (docs.qwencloud.com, "Regions and
|
||||
@@ -451,9 +483,9 @@ var presets = []PresetDef{
|
||||
Chat: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", Anthropic: "https://token-plan.maas.qwencloudapi.com/apps/anthropic",
|
||||
Note: "Qwen Cloud · subscription",
|
||||
Website: "https://docs.qwencloud.com/token-plan/overview", KeysURL: "https://home.qwencloud.com/analytics/token-plan/individual",
|
||||
Models: []string{"auto", "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash",
|
||||
"deepseek-v4.1-flash", "deepseek-v4.1-flash-1017", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731",
|
||||
"glm-5.3", "glm-5.2"}},
|
||||
Models: alibabaPlanModels,
|
||||
Drawers: append(slices.Clone(alibabaPlanDrawers), "qwen-image-2.0-pro", "qwen-image-2.0"), Videos: alibabaPlanVideos,
|
||||
Speakers: alibabaPlanSpeakers, Transcribers: alibabaPlanTranscribers},
|
||||
{ID: "qwencloud", Name: "Qwen Cloud", Icon: "qwen-color", Kind: KindVendor, Catalog: "alibaba",
|
||||
Chat: qwenCloudChat("ap-southeast-1"), Anthropic: qwenCloudAnthropic("ap-southeast-1"),
|
||||
Note: "Qwen Cloud · pay as you go",
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestQwenTokenPlan(t *testing.T) {
|
||||
if p.Chat != "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1" || p.Anthropic != "https://token-plan.maas.qianwenaiapi.com/apps/anthropic" || p.Responses != "" {
|
||||
t.Fatalf("endpoints: %q %q %q", p.Chat, p.Responses, p.Anthropic)
|
||||
}
|
||||
if got := p.planModels(nil); len(got) != len(Preset("qwen-token-plan").Models) || got[1].ID != "qwen3.8-max" {
|
||||
if got := p.planModels(nil); len(got) != len(Preset("qwen-token-plan").Models) || got[1].ID != "qwen4-max" {
|
||||
t.Fatalf("plan's: %+v", got)
|
||||
}
|
||||
im, _ := imported("Qwen", "sk-sp-x", endpoints{chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1"}, nil)
|
||||
@@ -60,7 +60,7 @@ func TestBailianTokenPlan(t *testing.T) {
|
||||
if pr := Preset("bailian-token-plan"); pr.Icon != "bailian-color" || !slices.Equal(pr.Models, Preset("qwen-token-plan").Models) {
|
||||
t.Fatalf("preset: %+v", pr)
|
||||
}
|
||||
if got := p.planModels(nil); len(got) != len(alibabaPlanModels) || got[1].ID != "qwen3.8-max" {
|
||||
if got := p.planModels(nil); len(got) != len(alibabaPlanModels) || got[1].ID != "qwen4-max" {
|
||||
t.Fatalf("plan's: %+v", got)
|
||||
}
|
||||
im, _ := imported("Bailian", "sk-sp-x", endpoints{chat: root + "/compatible-mode/v1"}, nil)
|
||||
|
||||
Reference in New Issue
Block a user