diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7c5b41d94..237e75489 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -36,7 +36,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.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) | -| 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`). 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). 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 → 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`. 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 → 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), [`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 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). 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 → 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`. 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 → 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) | | 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 (`conversationID`), and a Claude Code subagent's 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 sealed reasoning was 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)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), 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 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; 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) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). | diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 7def0ec7e..9fe0b1a69 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -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 diff --git a/internal/gateway/draw_dashscope.go b/internal/gateway/draw_dashscope.go new file mode 100644 index 000000000..9b4cbf8d8 --- /dev/null +++ b/internal/gateway/draw_dashscope.go @@ -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 +// /api/v1/services/aigc/multimodal-generation/generation, Bearer the +// same key, of +// +// {"model": …, "input": {"messages": [{"role": "user", "content": +// [{"image": }…, {"text": }]}]}, +// "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 +} diff --git a/internal/gateway/draw_dashscope_test.go b/internal/gateway/draw_dashscope_test.go new file mode 100644 index 000000000..5250419b0 --- /dev/null +++ b/internal/gateway/draw_dashscope_test.go @@ -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) + } + } +}