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.
This commit is contained in:
yetone
2026-10-31 10:15:15 +08:00
parent 0d5df496aa
commit 03f3e1528b
4 changed files with 424 additions and 1 deletions
File diff suppressed because one or more lines are too long
+3
View File
@@ -1302,6 +1302,9 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri
if isArk(p) {
return s.drawArk(ctx, p, model, d)
}
if dashScopeDraws(p, model) {
return s.drawDashScope(ctx, p, model, d)
}
base := strings.TrimRight(p.Base(provider.Chat), "/")
if base == "" {
// a Responses-only relay serves the images API under the same root
+174
View File
@@ -0,0 +1,174 @@
package gateway
// DashScope (Alibaba Cloud Model Studio, Bailian, the Qwen AI platform and
// Qwen Cloud, pay as you go and Token Plan alike) draws its Qwen-Image and
// Wan 2.7 image models on its own API, not the OpenAI images API: a POST to
// <host>/api/v1/services/aigc/multimodal-generation/generation, Bearer the
// same key, of
//
// {"model": …, "input": {"messages": [{"role": "user", "content":
// [{"image": <URL or data URL>}…, {"text": <prompt>}]}]},
// "parameters": {"n": …, "size": "W*H", "watermark": false}}
//
// answered with the images in output.choices[*].message.content[*].image,
// each a URL kept for 24 hours (docs.qwencloud.com, "Qwen-Image text-to-
// image" and the Token Plan's "Integrate multimodal generation"), the only
// API documented for them. magpie sent them to the OpenAI images API at
// /compatible-mode/v1, and on its 404 to chat completions, whose answer has
// no image magpie reads: "qwen-image-3.0-pro drew nothing" (judi0713 on
// Discord; which of the two answered is not seen from here).
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// dashScopeDraws is whether model draws on DashScope's multimodal-
// generation API: the Qwen-Image models (qwen-image-3.0-pro, qwen-image-
// edit-plus…) and Wan 2.7's image ones. Older Wan text-to-image models
// draw on another, asynchronous API and are left as they were.
func dashScopeDraws(p provider.Provider, model string) bool {
m := strings.ToLower(model)
return dashScope(p) && (strings.HasPrefix(m, "qwen-image") || strings.HasPrefix(m, "wan2.7-image"))
}
// dashScopeRoot is the host's root the native API is under: the base given
// with its compatible-mode, Anthropic or native path cut off.
func dashScopeRoot(p provider.Provider) string {
base := strings.TrimRight(p.Base(provider.Chat), "/")
if base == "" {
base = strings.TrimRight(p.Base(provider.Anthropic), "/")
}
for _, cut := range []string{"/compatible-mode/", "/apps/", "/api/v1"} {
if i := strings.Index(base, cut); i >= 0 {
return base[:i]
}
}
return base
}
// dashScopeSize is size as DashScope takes it, W*H, or "" for the model's
// own pick. A ratio is an error saying what to send instead.
func dashScopeSize(size string) (string, error) {
size = strings.TrimSpace(size)
switch {
case size == "" || strings.EqualFold(size, "auto"):
return "", nil
case strings.Contains(size, ":"):
return "", fmt.Errorf("DashScope's image models take no aspect ratio as size: give WIDTHxHEIGHT (e.g. 1328x1328, at most 2048x2048 in pixels), or leave size out for the model to pick one from the prompt")
}
return strings.ReplaceAll(strings.ToLower(size), "x", "*"), nil
}
// dashScopeBody is d as the multimodal-generation API takes it.
func dashScopeBody(model string, d drawing) ([]byte, error) {
if d.Mask != nil {
return nil, errors.New("DashScope's image models take no mask: say in the prompt which part of the image to change")
}
size, err := dashScopeSize(d.Size)
if err != nil {
return nil, err
}
var content []map[string]string
for _, pic := range d.Images {
content = append(content, map[string]string{"image": pic.dataURL()})
}
content = append(content, map[string]string{"text": d.Prompt})
params := map[string]any{"watermark": false}
if d.N > 1 {
params["n"] = d.N
}
if size != "" {
params["size"] = size
}
return json.Marshal(map[string]any{
"model": model,
"input": map[string]any{"messages": []map[string]any{{"role": "user", "content": content}}},
"parameters": params,
})
}
func (s *Server) drawDashScope(ctx context.Context, p provider.Provider, model string, d drawing) (drawn, int, error) {
body, err := dashScopeBody(model, d)
if err != nil {
return drawn{}, http.StatusBadRequest, err
}
url := dashScopeRoot(p) + "/api/v1/services/aigc/multimodal-generation/generation"
b, code, err := s.send(ctx, p, url, "application/json", body, true)
if err != nil {
if said := dashScopeSaid(b); said != "" {
err = fmt.Errorf("%s: %d %s: %s", provider.HostOf(url), code, http.StatusText(code), said)
}
return drawn{}, code, err
}
return readDashScopeAnswer(url, b, code)
}
// dashScopeSaid is a DashScope error's words, {"code", "message"}, or "".
func dashScopeSaid(b []byte) string {
var e struct {
Code string `json:"code"`
Message string `json:"message"`
}
if json.Unmarshal(b, &e) != nil || e.Code == "" && e.Message == "" {
return ""
}
if e.Code == "" {
return e.Message
}
return e.Message + " (" + e.Code + ")"
}
// readDashScopeAnswer takes every image of every choice; an answer with
// none says what DashScope said, or how it ended.
func readDashScopeAnswer(url string, b []byte, code int) (drawn, int, error) {
var res struct {
Output struct {
Choices []struct {
FinishReason string `json:"finish_reason"`
Message struct {
Content []struct {
Image string `json:"image"`
Text string `json:"text"`
} `json:"content"`
} `json:"message"`
} `json:"choices"`
} `json:"output"`
}
if err := json.Unmarshal(b, &res); err != nil {
return drawn{}, 502, fmt.Errorf("%s's answer isn't DashScope's: %v", provider.HostOf(url), err)
}
var out drawn
var texts, ends []string
for _, c := range res.Output.Choices {
for _, part := range c.Message.Content {
switch {
case part.Image != "":
out.Images = append(out.Images, picture{URL: part.Image})
case strings.TrimSpace(part.Text) != "":
texts = append(texts, part.Text)
}
}
if c.FinishReason != "" && c.FinishReason != "stop" {
ends = append(ends, c.FinishReason)
}
}
out.Text = strings.Join(texts, "\n")
if len(out.Images) == 0 {
said := dashScopeSaid(b)
if said == "" {
said = out.Text
}
if said == "" && len(ends) > 0 {
said = "it ended with " + strings.Join(ends, ", ")
}
return out, saidStatus(said), fmt.Errorf("%s answered with no image%s", provider.HostOf(url), vendorSaid(said))
}
return out, code, nil
}
+246
View File
@@ -0,0 +1,246 @@
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)
}
}
}