From ca7a3929199bcc767759d514c780adcee8fea28e Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 21:34:57 +0800 Subject: [PATCH] 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 /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. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/draw.go | 10 ++ internal/gateway/draw_minimax.go | 223 ++++++++++++++++++++++++++ internal/gateway/draw_minimax_test.go | 205 +++++++++++++++++++++++ 4 files changed, 439 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/draw_minimax.go create mode 100644 internal/gateway/draw_minimax_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index be6ffa6c5..0381763c5 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -40,7 +40,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Group defaults | What a group does when a member is rate limited (Sink), slow to start (FirstToken) or every member is busy (Patience) is set once for every group in settings (`groupSink`, `groupFirstToken`, `groupPatience`; `settings.SetGroupDefaults`, POST `/api/groups/defaults`, the Routing groups page's Settings card; jiezhengj on Discord). A group follows the default for each it leaves unset, and its own value wins: `Sinks()` is `Sink`, or the default unless `NoSink` (Keeps its place); `FirstTokenOr()` is its own `FirstToken` (`FirstTokenWait`, -1, is its own Wait), else the default; `Waits()` reads the default when `Patience` is 0 (60 is its own 1 min). The group editor's rows open on Default for a group that sets none, the hint naming the value it follows. Groups saved before kept 0 and no `NoSink`, so they follow the default, which starts at magpie's own (keep its place, wait, 60s). `TestGroupDefaultsUnlessItsOwn`, `TestGroupFirstTokenFollowsTheDefault`, `TestGroupSinkFollowsTheDefault`, `TestGroupDefaultsSaved`, `group-defaults.test.cjs`. | [`group.go`](../../internal/provider/group.go), [`groups.go`](../../internal/gui/groups.go) | -| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Models → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Models → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | +| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). 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` among its drawers (`minimaxDrawers`) and draws them on MiniMax's own `/v1/image_generation` (`drawMiniMax`), as platform.minimax.io gives it: `aspect_ratio` from `size` (one MiniMax lists, or the size it draws for one; else for image-01 a `width`/`height` in 512 to 2048 by 8; else the nearest ratio), `n`, `response_format: base64`, an edit's images as `subject_reference` (`type: character`), and the caller's `seed`, `prompt_optimizer`, `aigc_watermark` and `style`; no mask. The images are read from `data.image_base64` (or `image_urls`), and a `base_resp` failure in a 200 is told by its code (1004/2049 key, 1008 balance, 1026 content, 1002 rate) with its status (`readMiniMaxDrawing`). It went to chat completions before and was answered "unknown model 'image-01' (2013)" (rocbomb123 on X, `TestMiniMaxDrawsOnImageGeneration`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Models → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Models → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | | Decisions | `POST /v1/decisions` (and `/decisions`) is OpenAI's Decisions API, checked against openai-python's `decisions.create` (`DecisionCreateParams`, `Decision`): `model` (gpt-6-luna), `input` (a string, or messages and items whose parts are `input_text`, `input_image` with a data or http(s) URL, JSON), `questions` (1 to 400 predicate, choice or score questions), and `prompt_cache_key`, `prompt_cache_options`, `safety_identifier`. The answer is `{answers, model, usage}`, never streamed. `decide` passes the body through `serveRetrieval` as embeddings' is, with only `model` changed, so model resolution, a disabled model, a key's models, accounts and spent limits, pause rules, the provider's keys or accounts, masking (a data URL's image is left as it is) and the Routing page hold as on every route. It goes only to a provider `canDecide` takes: an OpenAI API key on `api.openai.com`, Azure OpenAI (`IsAzure`, at its v1 API's `/openai/v1/decisions`, the model in the body as the deployment's name), or another magpie, which routes it on. Any other, a relay, a plugin or a ChatGPT sign-in whatever its list says, is never sent it: the try is refused 400 with who serves it (`decisionRequest.refuses`, next to the no-OpenAI-API check), and a group moves on to its next member. A bare `gpt-6-luna` is the kind group `decision` (`servesDecision`: a provider `canDecide` takes that lists the model, or an OpenAI key, as the API takes it without it on the key's chat list), so a relay listing the same id is never its member. Usage is recorded as `decisions` from the answer's `usage` (`decisionRequest.counted`): `input_tokens` less `input_tokens_details`' `cached_tokens` and `cache_write_tokens` as input, those two as cache read and write, and no output, as OpenAI bills none, so gpt-6-luna's own rates price it. `native_endpoints` is about the chat APIs a model is relayed on, and stays chat/completions and responses. A model that answers System One (`systemOneTargets`: a decision group's members, else `provider.RouteDecider`'s, none of them a provider `canDecide` takes, so another magpie still gets the Decisions body) is asked there instead (wudi_boy on Discord: Qwen's decision-model-preview on Decisions was refused): `decisionsAsSystemOne` turns predicate into `noul`, choice into a criteria map (a boolean value as "true"/"false"), score into a criteria list of `label: description` least first, an unnamed question into `question_N` answered with a null name, and `input` into the state (a string, or `{"messages":[{role, content, refusal}]}` with `input_json` as its JSON text); `serveSystemOneBody` serves it, and `systemOneAsDecision` gives the Decisions answer (a choice's value typed back, a score's probabilities by index or label, a missing answer a `refusal`, usage input and output with no cache split). The prompt-cache hints and `safety_identifier` change no answer and are left out; anything else with no counterpart is a 400 naming it before a vendor is asked (`untranslated`: an image unless every target is a Clef or another magpie, an http image, a function or custom tool call or its output, an image or refusal in a question, any other field or question type). The reverse: `/v1/systemone` whose `RouteDecider` finds no System One provider (its 404) but `resolveRetrievalModel` resolves the model is `systemOneByDecisions`, sent through `serveRetrieval` as above (`systemOneAsDecisions`, `decisionAsSystemOne`). A vendor's error passes through as it was said. `TestDecisionsAskSystemOne`, `TestDecisionsMessagesAsSystemOneState`, `TestDecisionsUntranslatableRefused`, `TestDecisionsImagesToClef`, `TestSystemOneAsksDecisions`. `TestDecisionsReachOpenAIAndAzure`, `TestDecisionsRefusedWhereNotServed`, `TestCanDecide`, `TestDecisionsThroughAnotherMagpie`, `TestDecisionsHeldByKeysAndRules`. | [`decisions.go`](../../internal/gateway/decisions.go), [`decisions_systemone.go`](../../internal/gateway/decisions_systemone.go), [`embeddings.go`](../../internal/gateway/embeddings.go), [`media_group.go`](../../internal/gateway/media_group.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one silent for 10s (no HEADERS or DATA from the vendor since the last request) is pinged, and dropped when no answer comes within 10s, so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A silence answered is pinged again only 5 minutes on (`netproxy.CalmHTTP2`, `PingAgain`): Go's own health check pings it every 10s, its ping's answer restarting its clock, and Google's front end, holding clients to gRPC's ping policy (a ping within 5 minutes of the last with nothing sent between is a strike, and the third ends the connection), ended a turn of gemini thinking through Antigravity at ~235s with GOAWAY ENHANCE_YOUR_CALM "too_many_pings" (zdevoz on Discord; `TestLongSilenceIsNotPingedIntoGoaway`, `TestCalmFindsAPathDeadLaterInTheSilence`). The try after a GOAWAY goes on a new connection (`TestTryAfterGoawayDialsAnew`). `http.DefaultTransport`, whose requests are short, keeps Go's (`netproxy.HTTP2Health`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 2492f8565..79a8b187e 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -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 diff --git a/internal/gateway/draw_minimax.go b/internal/gateway/draw_minimax.go new file mode 100644 index 000000000..0772b1529 --- /dev/null +++ b/internal/gateway/draw_minimax.go @@ -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 +// /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": }]} +// +// 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 +} diff --git a/internal/gateway/draw_minimax_test.go b/internal/gateway/draw_minimax_test.go new file mode 100644 index 000000000..25b7bdd20 --- /dev/null +++ b/internal/gateway/draw_minimax_test.go @@ -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") + } +}