Files
magpie/internal/gateway/draw_dashscope_test.go
T
yetone 03f3e1528b gateway: Qwen-Image and Wan 2.7 image models draw on DashScope's own API, so qwen-image-3.0-pro no longer draws nothing (judi0713)
judi0713 on Discord (v0.1.2288): qwen-image-3.0-pro draws when called
directly, but through magpie answers 502 "qwen-image-3.0-pro drew
nothing". DashScope documents its Qwen-Image and Wan 2.7 image models on
its own multimodal-generation API only (docs.qwencloud.com "Qwen-Image
text-to-image", and the Token Plan's "Integrate multimodal generation"):
a POST to <host>/api/v1/services/aigc/multimodal-generation/generation,
answered with the images at output.choices[].message.content[].image.
magpie sent them to the OpenAI images API at /compatible-mode/v1 and, on
its 404, to chat completions, whose answer holds no image it reads. Which
of the two answered the reporter is not seen from here.

Now, on a DashScope provider (dashScope(): Bailian, Model Studio, the Qwen
AI platform and Qwen Cloud, pay as you go and Token Plan, by preset or
host) a model named qwen-image* or wan2.7-image* draws there
(draw_dashscope.go, from drawImages):
- the prompt and any input images (data URLs) as one user message,
  parameters watermark false, n when over 1, size as W*H;
- every image of every choice is read; with none, the error says what
  DashScope said (message and code), the model's text, or the
  finish_reason;
- a mask or a ratio size is a 400 saying what to send instead, with no
  request made.
The root is the provider's Chat (or Anthropic) base cut at
/compatible-mode/, /apps/ or /api/v1. Every other provider and model is
unchanged (TestDashScopeDrawsScoped). /v1/images/generations and
/v1/images/edits both go through drawImages, and magpie's generate_image
MCP draws through those two, so all three are covered.

The fixtures are the documented response bytes, not a live answer.

Run (mote, at b06df2557 on 3e5aa1151):
- gofmt -l: clean.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui ./... -timeout 45m -count=1: every package ok
  (gateway 745s) except two reds already filed, in code this doesn't
  touch: internal/gui TestColdTurnsTaken (#4510) and internal/proc
  TestNoCommandBypassesProc (claudetui/child_unix.go, #4491).

Broken by hand: drawImages' dispatch made `if false && dashScopeDraws`:
TestDashScopeDrawsOnItsOwnAPI, TestDashScopeEdits and TestDashScopeSaysWhy
go red (the fake answers 404 off its native path).

Not tried:
- No real Qwen Cloud or DashScope account: no request reached Alibaba.
- The chat fallback's parse of a {"image": ...} part is unchanged.
- Older Wan text-to-image models (an asynchronous task API) and video
  are left as they were.
- No GUI change, so no GUI run.
2026-10-31 10:15:15 +08:00

247 lines
10 KiB
Go

package gateway
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// dashScopeImages stands in for a DashScope host as Qwen Cloud's Token
// Plan is documented (docs.qwencloud.com: "Qwen-Image text-to-image", the
// Token Plan's "Integrate multimodal generation"): the multimodal-
// generation API at /api/v1/services/aigc/multimodal-generation/generation,
// answering with its documented bytes, and no images API under
// /compatible-mode/v1. No real DashScope or Qwen Cloud account was asked.
type dashScopeImages struct {
mu sync.Mutex
paths []string
bodies []string
answer string // what the native API answers, its documented one if ""
status int
}
const dashScopeOneImage = `{"status_code":200,"request_id":"d2d1a8c0-325f-9b9d-8b90-xxxxxx","code":"","message":"","output":{"text":null,"finish_reason":null,"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":[{"image":"https://dashscope-result-intl.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"}]}}]},"usage":{"output_height":2048,"output_width":2048,"input_image_count":0,"input_image_type":"qima_input_2k","output_image_count":1,"output_image_type":"qima_output_2k"}}`
// the image-editing example's answer for n=2: one choice, two images
const dashScopeTwoImages = `{"status_code":200,"request_id":"fa41f9f9-3cb6-434d-a95d-xxxxxx","code":"","message":"","output":{"text":null,"finish_reason":null,"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":[{"image":"https://dashscope-result-intl.oss-cn-shanghai.aliyuncs.com/a.png?Expires=xxx"},{"image":"https://dashscope-result-intl.oss-cn-shanghai.aliyuncs.com/b.png?Expires=xxx"}]}}]},"usage":{"width":1024,"height":1024,"image_count":2}}`
func (d *dashScopeImages) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
body, _ := io.ReadAll(r.Body)
d.mu.Lock()
d.paths = append(d.paths, r.URL.Path)
d.bodies = append(d.bodies, string(body))
answer, status := d.answer, d.status
d.mu.Unlock()
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
}
if r.Method != "POST" || r.URL.Path != "/api/v1/services/aigc/multimodal-generation/generation" {
w.WriteHeader(404)
return
}
if status != 0 {
w.WriteHeader(status)
}
if answer == "" {
answer = dashScopeOneImage
}
io.WriteString(w, answer)
}
func (d *dashScopeImages) sent(t *testing.T) map[string]any {
t.Helper()
d.mu.Lock()
defer d.mu.Unlock()
if len(d.bodies) == 0 {
t.Fatal("nothing sent")
}
var m map[string]any
if err := json.Unmarshal([]byte(d.bodies[len(d.bodies)-1]), &m); err != nil {
t.Fatalf("sent %s: %v", d.bodies[len(d.bodies)-1], err)
}
return m
}
func dashScoped(t *testing.T, p provider.Provider) (*Server, *dashScopeImages) {
t.Helper()
fresh(t)
d := &dashScopeImages{}
up := httptest.NewServer(d)
t.Cleanup(up.Close)
p.Chat, p.Anthropic = up.URL+"/compatible-mode/v1", up.URL+"/apps/anthropic"
if p.Key == "" {
p.Key = "sk-sp-key"
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return New(), d
}
func imageURLs(t *testing.T, raw string) []string {
t.Helper()
var a struct {
Data []struct {
URL string `json:"url"`
} `json:"data"`
}
json.Unmarshal([]byte(raw), &a)
var out []string
for _, e := range a.Data {
out = append(out, e.URL)
}
return out
}
// qwen-image-3.0-pro on a Qwen Token Plan drew nothing (judi0713 on
// Discord): its host has no OpenAI images API, and the chat completions it
// went on to answer with no image magpie reads. It is asked on DashScope's
// own API, and its image read from output.choices[].message.content[].image.
func TestDashScopeDrawsOnItsOwnAPI(t *testing.T) {
s, d := dashScoped(t, provider.Provider{ID: "qwen", Name: "Qwen Token Plan", Preset: "qwen-token-plan", Models: []string{"qwen3.8-max", "qwen-image-3.0-pro"}})
code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"一只喜鹊","size":"1024x1024"}`)
if code != 200 {
t.Fatalf("%d %s (asked %v)", code, raw, d.paths)
}
if got := imageURLs(t, raw); len(got) != 1 || got[0] != "https://dashscope-result-intl.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx" {
t.Fatalf("images %v: %s", got, raw)
}
m := d.sent(t)
params, _ := m["parameters"].(map[string]any)
if m["model"] != "qwen-image-3.0-pro" || params["size"] != "1024*1024" || params["watermark"] != false {
t.Fatalf("sent %v", m)
}
if _, ok := params["n"]; ok {
t.Fatalf("sent n for one image: %v", m)
}
msgs, _ := m["input"].(map[string]any)["messages"].([]any)
if len(msgs) != 1 {
t.Fatalf("sent %v", m)
}
content, _ := msgs[0].(map[string]any)["content"].([]any)
if len(content) != 1 || content[0].(map[string]any)["text"] != "一只喜鹊" {
t.Fatalf("sent content %v", content)
}
// several images come in one choice's content, each read
d.mu.Lock()
d.answer = dashScopeTwoImages
d.mu.Unlock()
code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"两只喜鹊","n":2}`)
if got := imageURLs(t, raw); code != 200 || len(got) != 2 || !strings.Contains(got[1], "/b.png") {
t.Fatalf("%d %v: %s", code, got, raw)
}
params, _ = d.sent(t)["parameters"].(map[string]any)
if params["n"] != float64(2) {
t.Fatalf("sent %v", d.sent(t))
}
if _, ok := params["size"]; ok {
t.Fatalf("sent a size with none asked: %v", params)
}
}
// An edit's images go before the prompt in the same content, as data URLs
// or the URLs given; a mask, which DashScope doesn't take, is turned away
// before it is asked.
func TestDashScopeEdits(t *testing.T) {
s, d := dashScoped(t, provider.Provider{ID: "qwen", Name: "Qwen", Preset: "qwen", Models: []string{"qwen3.8-max", "qwen-image-3.0-pro"}})
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
mw.WriteField("model", "qwen/qwen-image-3.0-pro")
mw.WriteField("prompt", "make it night")
part, _ := mw.CreateFormFile("image", "a.png")
part.Write(pngBytes)
mw.Close()
code, _, raw := postImages(t, s, "/v1/images/edits", mw.FormDataContentType(), buf.String())
if code != 200 || len(imageURLs(t, raw)) != 1 {
t.Fatalf("%d %s", code, raw)
}
msgs, _ := d.sent(t)["input"].(map[string]any)["messages"].([]any)
content, _ := msgs[0].(map[string]any)["content"].([]any)
if len(content) != 2 || content[0].(map[string]any)["image"] != "data:image/png;base64,"+base64.StdEncoding.EncodeToString(pngBytes) ||
content[1].(map[string]any)["text"] != "make it night" {
t.Fatalf("sent content %v", content)
}
code, _, raw = postImages(t, s, "/v1/images/edits", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"merge","image":["https://example.com/a.png","https://example.com/b.png"]}`)
msgs, _ = d.sent(t)["input"].(map[string]any)["messages"].([]any)
content, _ = msgs[0].(map[string]any)["content"].([]any)
if code != 200 || len(content) != 3 || content[1].(map[string]any)["image"] != "https://example.com/b.png" {
t.Fatalf("%d %s, sent %v", code, raw, content)
}
before := len(d.paths)
buf.Reset()
mw = multipart.NewWriter(&buf)
mw.WriteField("model", "qwen/qwen-image-3.0-pro")
mw.WriteField("prompt", "change the sky")
part, _ = mw.CreateFormFile("image", "a.png")
part.Write(pngBytes)
part, _ = mw.CreateFormFile("mask", "m.png")
part.Write(pngBytes)
mw.Close()
code, _, raw = postImages(t, s, "/v1/images/edits", mw.FormDataContentType(), buf.String())
if code != 400 || !strings.Contains(raw, "no mask") || len(d.paths) != before {
t.Fatalf("a mask: %d %s, asked %v", code, raw, d.paths[before:])
}
}
// DashScope's refusal, and an answer with no image, say DashScope's own
// words; a ratio is turned away with what to send.
func TestDashScopeSaysWhy(t *testing.T) {
s, d := dashScoped(t, provider.Provider{ID: "qwen", Name: "Qwen Token Plan", Preset: "qwen-token-plan", Models: []string{"qwen3.8-max", "qwen-image-3.0-pro"}})
d.answer, d.status = `{"request_id":"1","code":"InvalidParameter","message":"The size is not match the allowed size"}`, 400
code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"a","size":"9000x9000"}`)
if code != 400 || !strings.Contains(raw, "The size is not match the allowed size (InvalidParameter)") {
t.Fatalf("%d %s", code, raw)
}
d.answer, d.status = `{"status_code":200,"request_id":"2","code":"","message":"","output":{"choices":[{"finish_reason":"content_filter","message":{"role":"assistant","content":[]}}]}}`, 0
code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"a"}`)
if code < 400 || !strings.Contains(raw, "no image") || !strings.Contains(raw, "content_filter") {
t.Fatalf("%d %s", code, raw)
}
code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"qwen/qwen-image-3.0-pro","prompt":"a","size":"16:9"}`)
if code != 400 || !strings.Contains(raw, "WIDTHxHEIGHT") {
t.Fatalf("%d %s", code, raw)
}
}
// The native API is DashScope's alone, and for its Qwen-Image and Wan 2.7
// image models: a relay serving qwen-image, or another Wan model on
// DashScope, is asked on the images API as before.
func TestDashScopeDrawsScoped(t *testing.T) {
ds := provider.Provider{Preset: "qwen-token-plan", Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1"}
for _, m := range []string{"qwen-image-3.0-pro", "qwen-image-edit-plus", "wan2.7-image", "wan2.7-image-pro"} {
if !dashScopeDraws(ds, m) {
t.Errorf("%s isn't drawn natively", m)
}
}
if dashScopeDraws(ds, "wan2.2-t2i-flash") {
t.Error("an older Wan model is drawn on the multimodal API")
}
if dashScopeDraws(provider.Provider{Chat: "https://relay.example.com/v1"}, "qwen-image-3.0-pro") {
t.Error("a relay is drawn on DashScope's API")
}
for base, want := range map[string]string{
"https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1": "https://token-plan.maas.qianwenaiapi.com",
"https://dashscope-intl.aliyuncs.com/api/v1": "https://dashscope-intl.aliyuncs.com",
"https://dashscope.aliyuncs.com": "https://dashscope.aliyuncs.com",
} {
if got := dashScopeRoot(provider.Provider{Chat: base}); got != want {
t.Errorf("root of %s: %s, want %s", base, got, want)
}
}
}