gateway: MiniMax's image-01 draws on its own image_generation API (rocbomb123 on X)

minimax-cn/image-01 went to chat completions (catalog.ImagesAPI doesn't
know image-01), and MiniMax answered "invalid params, unknown model
'image-01' (2013)". MiniMax draws only on POST <host>/v1/image_generation
(platform.minimax.io and platform.minimax.cn API reference, t2i and i2i,
checked against the docs, not the report).

- draw_minimax.go: a MiniMax API key (filmsMiniMax: the minimax and
  minimax-cn presets, or any provider at api.minimax.io, api.minimaxi.com
  or api.minimax.cn) lists image-01 and image-01-live as drawers and
  draws them at its own host: size -> aspect_ratio (a listed ratio or its
  size; else image-01's width/height in 512..2048 by 8; else the nearest
  ratio; 21:9 image-01 only), n, response_format base64, edit images as
  subject_reference type character, the caller's seed, prompt_optimizer,
  aigc_watermark and style passed on; mask and markup refused before
  asking. data.image_base64 / image_urls are read; base_resp failures in
  a 200 are told by code (1004/2049 key 401, 1008 balance 402, 1026
  content 400, 1002 rate 429, 2013 400), and all images held back
  (metadata.failed_count) says so.
- draw.go: viaFor sends them to the images path, drawImages to
  drawMiniMax, DrawersOf adds them for a MiniMax key.
- A relay serving MiniMax models under another host is unchanged. The
  minimax-code plugin sign-ins are not API keys and are untouched.

Run (mote, at e6f151507 + this change; after the rebase onto
origin/main, which touched no gateway file, -run 'MiniMax|Draw'
./internal/gateway again at the pushed tree: ok):
- go test -count=1 -timeout 45m ./internal/gateway: ok (947s)
- go vet ./internal/gateway on darwin, GOOS=linux -tags nogui, and
  GOOS=windows: ok; gofmt -l clean.
Broken by hand: with the viaFor case and the drawImages hook removed,
TestMiniMaxDrawsOnImageGeneration fails for minimax and minimax-cn with
the reporter's exact "unknown model 'image-01' (2013)".
Not tried: a real MiniMax key (no account here); the fake answers with
the documented bytes. GUI suite not run (no GUI file changed; the
Providers page reads Drawers from the API). Full ./... suite runs after
the tag.
This commit is contained in:
yetone
2026-11-10 21:47:45 +08:00
parent a1ba92ad8c
commit ca7a392919
4 changed files with 439 additions and 1 deletions
File diff suppressed because one or more lines are too long
+10
View File
@@ -391,6 +391,10 @@ func DrawersOf(p provider.Provider, avail func() []catalog.Model) []catalog.Mode
return nil
}
out := p.PlanDrawers()
if filmsMiniMax(p) {
// a MiniMax key's image-01 models, which no list names
out = append(out, minimaxDrawers(p)...)
}
have := make(map[string]bool, len(out))
for _, m := range out {
have[m.ID] = true
@@ -1140,6 +1144,9 @@ func viaFor(p provider.Provider, model string) drawVia {
// another magpie's images API asks the model's vendor the way
// that model draws there
return viaImages
case drawsMiniMax(p, model):
// MiniMax's image_generation, which drawImages asks (rocbomb123 on X)
return viaImages
case isGoogle(p) && strings.Contains(strings.ToLower(model), "gemini"):
return viaGemini
case p.ModelKind(model) == provider.KindImage:
@@ -1576,6 +1583,9 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri
if dashScopeDraws(p, model) {
return s.drawDashScope(ctx, p, model, d)
}
if drawsMiniMax(p, model) {
return s.drawMiniMax(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
+223
View File
@@ -0,0 +1,223 @@
package gateway
// MiniMax draws its image-01 and image-01-live models on its own API, not
// the OpenAI images API (platform.minimax.io/docs/api-reference/
// image-generation-t2i and -i2i; platform.minimax.cn the same): a POST to
// <host>/v1/image_generation, Bearer the same key, of
//
// {"model": "image-01", "prompt": …, "aspect_ratio": "16:9" | "width":
// W, "height": H, "n": 1…9, "response_format": "base64",
// "subject_reference": [{"type": "character", "image_file": <URL or
// data URL>}]}
//
// answered with data.image_base64 (or data.image_urls), metadata's
// success_count and failed_count (those blocked as unsafe), and base_resp
// {status_code, status_msg}, 0 when it went well. magpie sent image-01 to
// chat completions, whose answer was "invalid params, unknown model
// 'image-01' (2013)" (rocbomb123 on X, minimax-cn).
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// minimaxDrawModels are the image models every MiniMax API key draws with.
// image-01 draws from a prompt, or a portrait as its subject reference;
// image-01-live is the same in a style (style.style_type).
var minimaxDrawModels = []catalog.Model{
{ID: "image-01", Name: "MiniMax Image-01", Draws: true, Images: true},
{ID: "image-01-live", Name: "MiniMax Image-01 Live", Draws: true, Images: true},
}
// minimaxDrawRatios are the aspect ratios image_generation takes, each with
// the size it draws; 21:9 is image-01's alone.
var minimaxDrawRatios = map[string]string{
"1:1": "1024x1024", "16:9": "1280x720", "4:3": "1152x864", "3:2": "1248x832",
"2:3": "832x1248", "3:4": "864x1152", "9:16": "720x1280", "21:9": "1344x576",
}
// drawsMiniMax is whether model is one of a MiniMax API key's image models,
// drawn on its image_generation API.
func drawsMiniMax(p provider.Provider, model string) bool {
return filmsMiniMax(p) && slices.ContainsFunc(minimaxDrawModels, func(m catalog.Model) bool { return strings.EqualFold(m.ID, model) })
}
// minimaxDrawers are the image models as p's.
func minimaxDrawers(p provider.Provider) []catalog.Model {
out := slices.Clone(minimaxDrawModels)
for i := range out {
out[i].Provider = p.ID
}
return out
}
// minimaxShape is the size field as image_generation takes it: a ratio it
// lists (by the ratio, or the size it draws for one), else for image-01 a
// WIDTHxHEIGHT it can draw (512 to 2048, each a multiple of 8), else the
// nearest of its ratios. nil for none asked: the vendor's 1:1.
func minimaxShape(model, size string) map[string]any {
size = strings.ToLower(strings.TrimSpace(size))
if size == "" || size == "auto" {
return nil
}
ratios := make([]string, 0, len(minimaxDrawRatios))
for r, at := range minimaxDrawRatios {
if r == "21:9" && model != "image-01" {
continue
}
if size == r || size == at {
return map[string]any{"aspect_ratio": r}
}
ratios = append(ratios, r)
}
slices.Sort(ratios)
if w, h, ok := strings.Cut(size, "x"); ok && model == "image-01" {
x, err1 := strconv.Atoi(w)
y, err2 := strconv.Atoi(h)
fits := func(n int) bool { return n >= 512 && n <= 2048 && n%8 == 0 }
if err1 == nil && err2 == nil && fits(x) && fits(y) {
return map[string]any{"width": x, "height": y}
}
}
if r := aspectAmong(size, ratios); r != "" && slices.Contains(ratios, r) {
return map[string]any{"aspect_ratio": r}
}
return nil
}
// minimaxDrawBody is d as image_generation takes it. What it can't take (a
// mask, a markup layer) is said before it is asked.
func minimaxDrawBody(model string, d drawing) ([]byte, error) {
if d.Mask != nil {
return nil, errors.New("MiniMax's image models take no mask: say in the prompt what to change")
}
if d.Markup != nil {
return nil, errors.New("MiniMax's image models take no markup layer: say in the prompt what to change")
}
req := map[string]any{"model": model, "prompt": d.Prompt, "n": max(d.N, 1), "response_format": "base64"}
for k, v := range minimaxShape(model, d.Size) {
req[k] = v
}
if len(d.Images) > 0 {
// a portrait the image is drawn of: MiniMax's only kind of reference
var refs []map[string]string
for _, pic := range d.Images {
refs = append(refs, map[string]string{"type": "character", "image_file": pic.dataURL()})
}
req["subject_reference"] = refs
}
// what the caller set of MiniMax's own fields
for _, k := range []string{"seed", "prompt_optimizer", "aigc_watermark", "style"} {
if v, ok := d.Extra[k]; ok {
req[k] = v
}
}
return json.Marshal(req)
}
func (s *Server) drawMiniMax(ctx context.Context, p provider.Provider, model string, d drawing) (drawn, int, error) {
body, err := minimaxDrawBody(model, d)
if err != nil {
return drawn{}, http.StatusBadRequest, err
}
url := minimaxHost(p) + "/v1/image_generation"
b, code, err := s.send(ctx, p, url, "application/json", body, true)
if err != nil {
return drawn{}, code, minimaxDrawError(code, b, err)
}
return readMiniMaxDrawing(url, b, code)
}
// minimaxDrawWhy is what a MiniMax error code means for a drawing, and the
// status it is answered with; "" for one that says enough itself.
func minimaxDrawWhy(code string, status int) (string, int) {
switch {
case code == "1004" || code == "2049" || code == "" && status == http.StatusUnauthorized:
return "MiniMax turned the API key away: it is wrong, or was deleted. Put a working key in the MiniMax provider", http.StatusUnauthorized
case code == "1008" || code == "" && status == http.StatusPaymentRequired:
return "the MiniMax account is out of balance: top it up on MiniMax's platform", http.StatusPaymentRequired
case code == "1026":
return "MiniMax refused the prompt as sensitive content: change what the image asks for", http.StatusBadRequest
case code == "1002" || code == "" && status == http.StatusTooManyRequests:
return "MiniMax was asked for images too often: try again shortly", http.StatusTooManyRequests
case code == "2013":
return "", http.StatusBadRequest
}
return "", 0
}
// minimaxDrawError is err (MiniMax turning a drawing away with status and
// body b) with what it means first.
func minimaxDrawError(status int, b []byte, err error) error {
_, code := minimaxSaid(b)
if why, _ := minimaxDrawWhy(code, status); why != "" {
return fmt.Errorf("%s — %w", why, err)
}
return err
}
// readMiniMaxDrawing takes every image of an image_generation answer. Its
// base_resp says a failure in a 200; an answer with no image says why: the
// vendor's words, or that its safety check held them all back.
func readMiniMaxDrawing(url string, b []byte, code int) (drawn, int, error) {
var res struct {
Data struct {
Base64 []string `json:"image_base64"`
URLs []string `json:"image_urls"`
} `json:"data"`
Metadata struct {
// numbers, or numbers in strings, as the docs' example has them
Failed json.RawMessage `json:"failed_count"`
} `json:"metadata"`
BaseResp struct {
StatusCode int `json:"status_code"`
StatusMsg string `json:"status_msg"`
} `json:"base_resp"`
}
if err := json.Unmarshal(b, &res); err != nil {
return drawn{}, 502, fmt.Errorf("%s's answer isn't MiniMax's: %v", provider.HostOf(url), err)
}
if c := res.BaseResp.StatusCode; c != 0 {
mcode := strconv.Itoa(c)
said := res.BaseResp.StatusMsg + codeUnlessSaid(res.BaseResp.StatusMsg, mcode)
err := fmt.Errorf("%s: MiniMax: %s", provider.HostOf(url), said)
why, status := minimaxDrawWhy(mcode, 0)
if why != "" {
err = fmt.Errorf("%s — %w", why, err)
}
if status == 0 {
status = saidStatus(said)
}
return drawn{}, status, err
}
var out drawn
for _, s := range res.Data.Base64 {
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))
if err != nil || len(raw) == 0 {
continue
}
out.Images = append(out.Images, picture{Mime: http.DetectContentType(raw), Data: raw})
}
for _, u := range res.Data.URLs {
if u != "" {
out.Images = append(out.Images, picture{URL: u})
}
}
if len(out.Images) == 0 {
if n, _ := strconv.Atoi(strings.Trim(string(res.Metadata.Failed), `"`)); n > 0 {
return out, http.StatusBadRequest, fmt.Errorf("%s answered with no image: MiniMax held back %d as sensitive content; change what the image asks for", provider.HostOf(url), n)
}
return out, 502, fmt.Errorf("%s answered with no image%s", provider.HostOf(url), vendorSaid(res.BaseResp.StatusMsg))
}
return out, code, nil
}
+205
View File
@@ -0,0 +1,205 @@
package gateway
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// minimaxImages stands in for a MiniMax host as its image_generation API
// is documented (platform.minimax.io/docs/api-reference/image-generation-
// t2i, platform.minimax.cn the same): POST /v1/image_generation answering
// data.image_base64 and base_resp, and, as the reporter's minimax-cn key
// was answered, chat completions refusing image-01 with 2013. No real
// MiniMax account was asked.
type minimaxImages struct {
mu sync.Mutex
paths []string
bodies []string
answer string // what image_generation answers, one image if ""
}
func (f *minimaxImages) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
f.paths = append(f.paths, r.URL.Path)
f.bodies = append(f.bodies, string(body))
answer := f.answer
f.mu.Unlock()
if r.Header.Get("Authorization") != "Bearer key" {
io.WriteString(w, `{"base_resp":{"status_code":1004,"status_msg":"login fail: Please carry the API secret key in the 'Authorization' field of the request header"}}`)
return
}
switch r.URL.Path {
case "/v1/image_generation":
if answer == "" {
answer = `{"id":"03ff3cd0820949eb8a410056b5f21d38","data":{"image_base64":["` + base64.StdEncoding.EncodeToString(pngBytes) + `"]},"metadata":{"failed_count":"0","success_count":"1"},"base_resp":{"status_code":0,"status_msg":"success"}}`
}
io.WriteString(w, answer)
case "/v1/chat/completions":
w.WriteHeader(400)
io.WriteString(w, `{"type":"error","error":{"type":"bad_request_error","message":"invalid params, unknown model 'image-01' (2013)","http_code":"400"},"request_id":"1"}`)
default:
w.WriteHeader(404)
}
}
func (f *minimaxImages) sent(t *testing.T) map[string]any {
t.Helper()
f.mu.Lock()
defer f.mu.Unlock()
if len(f.bodies) == 0 {
t.Fatal("nothing sent")
}
var m map[string]any
if err := json.Unmarshal([]byte(f.bodies[len(f.bodies)-1]), &m); err != nil {
t.Fatalf("sent %s: %v", f.bodies[len(f.bodies)-1], err)
}
return m
}
// minimaxDrawing saves a MiniMax key from preset pointed at a fake host.
func minimaxDrawing(t *testing.T, preset string) (*Server, *minimaxImages, provider.Provider) {
t.Helper()
fresh(t)
f := &minimaxImages{}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
was := isMiniMaxHost
t.Cleanup(func() { isMiniMaxHost = was })
host := strings.TrimPrefix(up.URL, "http://")
isMiniMaxHost = func(h string) bool { return h == host || was(h) }
p, err := provider.FromPreset(preset)
if err != nil {
t.Fatal(err)
}
p.ID, p.Key = preset, "key"
p.Chat, p.Anthropic = up.URL+"/v1", up.URL+"/anthropic"
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return New(), f, p
}
// rocbomb123 on X: minimax-cn/image-01 went to chat completions, which
// answered "invalid params, unknown model 'image-01' (2013)". A MiniMax
// key, intl and CN alike, draws image-01 on its image_generation API, its
// size as an aspect ratio, its image read from data.image_base64.
func TestMiniMaxDrawsOnImageGeneration(t *testing.T) {
for _, preset := range []string{"minimax-cn", "minimax"} {
t.Run(preset, func(t *testing.T) {
s, f, p := minimaxDrawing(t, preset)
var ids []string
for _, m := range Drawers(p) {
ids = append(ids, m.ID)
}
if !strings.Contains(","+strings.Join(ids, ",")+",", ",image-01,image-01-live,") {
t.Fatalf("%s draws with %v", preset, ids)
}
if len(catalog.Chat(minimaxDrawers(p))) != 0 {
t.Fatal("image-01 is a chat model")
}
code, a, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"`+preset+`/image-01","prompt":"a cat","n":1,"size":"1024x1024"}`)
if code != 200 || len(a.Data) != 1 {
t.Fatalf("%d %s (asked %v)", code, raw, f.paths)
}
if got, _ := base64.StdEncoding.DecodeString(a.Data[0].B64); string(got) != string(pngBytes) {
t.Fatalf("image %q", got)
}
if strings.Join(f.paths, ",") != "/v1/image_generation" {
t.Fatalf("asked %v", f.paths)
}
m := f.sent(t)
if m["model"] != "image-01" || m["prompt"] != "a cat" || m["aspect_ratio"] != "1:1" || m["response_format"] != "base64" || m["n"] != float64(1) {
t.Fatalf("sent %v", m)
}
if _, ok := m["size"]; ok {
t.Fatalf("sent OpenAI's size: %v", m)
}
})
}
}
// A size is a ratio MiniMax lists, or what it draws for one, else
// image-01's own width and height, else the nearest ratio; a portrait to
// draw from goes as subject_reference; what it can't take is said first.
func TestMiniMaxDrawingFields(t *testing.T) {
for _, c := range []struct{ model, size, want string }{
{"image-01", "16:9", `{"aspect_ratio":"16:9"}`},
{"image-01", "720x1280", `{"aspect_ratio":"9:16"}`},
{"image-01", "1536x1024", `{"height":1024,"width":1536}`},
{"image-01", "4096x4096", `{"aspect_ratio":"1:1"}`},
{"image-01-live", "1344x576", `{"aspect_ratio":"16:9"}`},
{"image-01-live", "1536x1024", `{"aspect_ratio":"3:2"}`},
{"image-01", "auto", `null`},
{"image-01", "", `null`},
} {
b, _ := json.Marshal(minimaxShape(c.model, c.size))
if string(b) != c.want {
t.Errorf("%s %s: %s, want %s", c.model, c.size, b, c.want)
}
}
s, f, _ := minimaxDrawing(t, "minimax-cn")
code, _, raw := postImages(t, s, "/v1/images/edits", "application/json", `{"model":"minimax-cn/image-01","prompt":"in a garden","image":["https://example.com/me.jpg"],"seed":7,"prompt_optimizer":true}`)
if code != 200 {
t.Fatalf("%d %s", code, raw)
}
m := f.sent(t)
refs, _ := m["subject_reference"].([]any)
if len(refs) != 1 || refs[0].(map[string]any)["type"] != "character" || refs[0].(map[string]any)["image_file"] != "https://example.com/me.jpg" ||
m["seed"] != float64(7) || m["prompt_optimizer"] != true {
t.Fatalf("sent %v", m)
}
code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"minimax-cn/image-01","prompt":"cats","n":3,"size":"21:9"}`)
if m = f.sent(t); code != 200 || m["n"] != float64(3) || m["aspect_ratio"] != "21:9" {
t.Fatalf("%d %s, sent %v", code, raw, m)
}
}
// MiniMax says a failure in a 200's base_resp; it is told for what it is,
// and an answer whose images were all held back says so.
func TestMiniMaxDrawingErrors(t *testing.T) {
s, f, _ := minimaxDrawing(t, "minimax")
for _, c := range []struct {
answer, want string
code int
}{
{`{"base_resp":{"status_code":1008,"status_msg":"insufficient balance"}}`, "out of balance", 402},
{`{"base_resp":{"status_code":1026,"status_msg":"input new_sensitive"}}`, "sensitive", 400},
{`{"base_resp":{"status_code":2013,"status_msg":"invalid params, aspect_ratio"}}`, "invalid params, aspect_ratio (2013)", 400},
{`{"data":{"image_base64":[]},"metadata":{"failed_count":"1","success_count":"0"},"base_resp":{"status_code":0,"status_msg":"success"}}`, "held back 1", 400},
} {
f.mu.Lock()
f.answer = c.answer
f.mu.Unlock()
code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"minimax/image-01","prompt":"a cat"}`)
if code != c.code || !strings.Contains(raw, c.want) {
t.Errorf("%s: %d %s", c.answer, code, raw)
}
}
}
// A relay serving MiniMax's models under another host is not MiniMax's
// API: image-01 there is asked as before.
func TestMiniMaxDrawingOnlyAtMiniMax(t *testing.T) {
p := provider.Provider{ID: "relay", Chat: "https://relay.example.com/minimax/v1", Key: "k"}
if drawsMiniMax(p, "image-01") {
t.Fatal("a relay draws on MiniMax's API")
}
if !drawsMiniMax(provider.Provider{ID: "minimax-cn", Chat: "https://api.minimaxi.com/v1", Key: "k"}, "image-01") ||
!drawsMiniMax(provider.Provider{ID: "mm", Chat: "https://api.minimax.cn/v1", Key: "k"}, "image-01-live") ||
drawsMiniMax(provider.Provider{ID: "minimax", Chat: "https://api.minimax.io/v1", Key: "k"}, "MiniMax-M3") {
t.Fatal("drawsMiniMax")
}
}