diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 28a9ded63..dc3b7dd23 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -38,7 +38,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | 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`) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (`lanes.freed`, signalled by the releaser, `Unrest` and `UnrestAll`), and when the soonest rest among the others runs out (at most every `laneRecheck`), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (`waitMate`, `keepAtOnce` re-derived over the provider's candidates, `errMoved`). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; `TestWaitingRequestGoesToAccountBackFromRest` under Smart and In turn, with Stays on and off, `TestWaitingRequestTakesSlotGivenBackElsewhere` under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (`TestFullMemberGivesWay`). 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) | | 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) | -| 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`. 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; video keeps `FindGroup`), and the group is no model agents are offered. `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 → 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 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`. 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`. `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 → 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`): the agent's session header, else 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 finds dsh's sessions by (`dshConvs`). 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)). 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, 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) | | 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/embeddings.go b/internal/gateway/embeddings.go index fb682b3ff..71adbc9f4 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -98,7 +98,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op return } p, model, ok := resolveRetrievalModel(asked) - if _, _, isGroup := provider.FindGroup(asked); ok && !isGroup { + if _, _, isGroup := mediaMembers(asked); ok && !isGroup { if msg, off := modelOff(p, model, asked); off { call.Status, call.Error = 403, msg writeError(w, provider.Chat, 403, msg) @@ -116,7 +116,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op s.record(call) return } - g, ms, isGroup := provider.FindGroup(asked) + g, ms, isGroup := mediaMembers(asked) if isGroup { r = heldByGroup(r, g) // held to the group's accounts, if it is } @@ -323,6 +323,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op // bare id. Such models stay out of agents' chat-model lists, so the general // resolver does not otherwise see them there. func resolveRetrievalModel(id string) (provider.Provider, string, bool) { + if p, model, ok := mediaGroupFirst(id); ok { + return p, model, true + } if p, model, ok := provider.Resolve(id); ok { return p, model, true } diff --git a/internal/gateway/media_group.go b/internal/gateway/media_group.go new file mode 100644 index 000000000..ff5e68b2c --- /dev/null +++ b/internal/gateway/media_group.go @@ -0,0 +1,41 @@ +package gateway + +import ( + "slices" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// mediaMembers is the routing group ref with its members ready now for +// an API that is no chat: embeddings, rerank, speech, transcriptions and +// videos. A provider's picks are of its chat models, and these models are +// in no chat list (catalog's textModel and pluginTalks leave embeddings, +// rerankers and speech models out when a list is fetched; videos are +// apart), so a member of a provider with picks was dropped as unpicked +// and a group of them was a 404 (XYenon on Discord). Such a member is +// kept, as a drawing's image models are (FindDrawingGroup, jzw690 on X). +// A chat model the user unticked (#3911) is on its provider's list and +// still stays out. +func mediaMembers(ref string) (provider.Group, []provider.Member, bool) { + return provider.FindGroupAlso(ref, offChatList) +} + +// offChatList is whether p's list of models to chat with lacks model: +// one made for another API, which no pick can name. +func offChatList(p provider.Provider, model string) bool { + return !slices.ContainsFunc(provider.KeptListing(p).Available, func(m catalog.Model) bool { return m.ID == model }) +} + +// mediaGroupFirst is the first member of the group ref for an API that is +// no chat (mediaMembers): such a group is no model agents are offered, so +// Resolve, which reads their catalog, doesn't take it. +func mediaGroupFirst(ref string) (provider.Provider, string, bool) { + if !provider.IsGroupRef(ref) { + return provider.Provider{}, "", false + } + if _, ms, ok := mediaMembers(ref); ok && len(ms) > 0 { + return ms[0].Provider, ms[0].Model, true + } + return provider.Provider{}, "", false +} diff --git a/internal/gateway/media_group_test.go b/internal/gateway/media_group_test.go new file mode 100644 index 000000000..920e6fd33 --- /dev/null +++ b/internal/gateway/media_group_test.go @@ -0,0 +1,120 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// busyVendor answers every request 429, out of quota, and counts them. +func busyVendor(t *testing.T) (string, func() []string) { + t.Helper() + var mu sync.Mutex + var asked []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + asked = append(asked, r.Method+" "+r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(429) + io.WriteString(w, `{"error":{"message":"quota exceeded"}}`) + })) + t.Cleanup(up.Close) + return up.URL, func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), asked...) } +} + +// XYenon on Discord: a routing group of embedding models made by hand +// was a 404 when its providers had chat models picked, as most do. Picks +// are of chat models, and an embedding, reranker or speech model is in no +// chat list (it is left out when the list is fetched), so each member was +// dropped as unpicked (#3911's rule). The members are the group's, and +// the first one out of quota passes the request to the next — for +// embeddings, rerank, speech and transcriptions alike. The sibling of +// 1d8658abc, which kept a drawing group's image models. +func TestMediaGroupOfProvidersWithChatPicks(t *testing.T) { + fresh(t) + busy, busyAsked := busyVendor(t) + l, sp, sc := &library{}, &speaker{more: make(chan struct{})}, &scribe{} + lib, voice, ears := httptest.NewServer(l), httptest.NewServer(sp), httptest.NewServer(sc) + t.Cleanup(lib.Close) + t.Cleanup(voice.Close) + t.Cleanup(ears.Close) + // every provider has picks, and none of them is the media model + for _, p := range []provider.Provider{ + {ID: "busy", Name: "Busy", Chat: busy + "/v1", Key: "k", Models: []string{"chat-model"}}, + {ID: "lib", Name: "Lib", Chat: lib.URL + "/v1", Key: "key", Models: []string{"chat-model"}}, + {ID: "voice", Name: "Voice", Chat: voice.URL + "/v1", Key: "key", Models: []string{"chat-model"}}, + {ID: "ears", Name: "Ears", Chat: ears.URL + "/v1", Key: "key", Models: []string{"chat-model"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + for _, g := range []provider.Group{ + {ID: "emb", Name: "emb", Members: []string{"busy/embed-1", "lib/embed-1"}, Routing: "order"}, + {ID: "rr", Name: "rr", Members: []string{"busy/rerank-1", "lib/rerank-1"}, Routing: "order"}, + {ID: "tts", Name: "tts", Members: []string{"busy/tts-1", "voice/gpt-4o-mini-tts"}, Routing: "order"}, + {ID: "stt", Name: "stt", Members: []string{"busy/whisper-1", "ears/whisper-1"}, Routing: "order"}, + // a chat model the user unticked stays out (#3911): a group of it alone has none + {ID: "unticked", Name: "unticked", Members: []string{"lib/chat-model-old"}, Routing: "order"}, + } { + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + } + // lib's list has a chat model the user left unticked + if err := catalog.SaveLive("lib", lib.URL+"/v1", []catalog.Model{{ID: "chat-model"}, {ID: "chat-model-old"}}); err != nil { + t.Fatal(err) + } + s := New() + if code, raw := postRetrieval(t, s, "/v1/embeddings", `{"model":"group/emb","input":"hi"}`); code != 200 || !strings.Contains(raw, `"embedding":[0.1,-0.2]`) { + t.Fatalf("embeddings: %d %s", code, raw) + } + if sent := l.got("/v1/embeddings"); len(sent) != 1 || !strings.Contains(sent[0], `"model":"embed-1"`) { + t.Fatalf("lib was sent %v", sent) + } + if code, raw := postRetrieval(t, s, "/v1/rerank", `{"model":"group/rr","query":"q","documents":["a","b"]}`); code != 200 || !strings.Contains(raw, `"relevance_score":0.9`) { + t.Fatalf("rerank: %d %s", code, raw) + } + if code, _, raw := postSpeech(t, s, "/v1/audio/speech", `{"model":"group/tts","input":"hello","voice":"alloy"}`); code != 200 || string(raw) != string(mp3) { + t.Fatalf("speech: %d %.200s", code, raw) + } + body, ctype := audioFormBody(t, "model", "group/stt") + if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 200 || !strings.Contains(raw, "Hello from the magpie.") { + t.Fatalf("transcription: %d %s", code, raw) + } + want := []string{"POST /v1/embeddings", "POST /v1/rerank", "POST /v1/audio/speech", "POST /v1/audio/transcriptions"} + if got := busyAsked(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("the busy member was asked %v, want %v", got, want) + } + if code, raw := postRetrieval(t, s, "/v1/embeddings", `{"model":"group/unticked","input":"hi"}`); code != 404 || len(l.got("/v1/embeddings")) != 1 { + t.Fatalf("a group of a chat model the user unticked was asked: %d %s", code, raw) + } +} + +// A video group made by hand of two providers with chat models picked +// makes its video, the first member that serves no such model passing it +// on: its video models are no chat model, so no pick names them. +func TestVideoGroupOfProvidersWithChatPicks(t *testing.T) { + fresh(t) + a, b := newOpenAIVideos(t), newOpenAIVideos(t) + a.lacks = "sk-a" + saveFetched(t, provider.Provider{ID: "a", Name: "A", Chat: a.URL + "/v1", Key: "sk-a", Models: []string{"gpt-5.5"}}) + saveFetched(t, provider.Provider{ID: "b", Name: "B", Chat: b.URL + "/v1", Key: "sk-b", Models: []string{"gpt-5.5"}}) + if err := provider.SaveGroup(provider.Group{ID: "vid", Name: "vid", Members: []string{"a/vid-1", "b/vid-1"}, Routing: "order"}); err != nil { + t.Fatal(err) + } + code, obj, raw := asKey(t, New().Handler(), "", "POST", "/v1/videos", `{"model":"group/vid","prompt":"a cat on a fence"}`) + if code != 200 || obj["model"] != "b/vid-1" { + t.Fatalf("video: %d %s", code, raw) + } + if got := strings.Join(a.log(), ","); !strings.Contains(got, "POST /v1/videos sk-a") { + t.Fatalf("the first member was never asked: %v", a.log()) + } +} diff --git a/internal/gateway/video.go b/internal/gateway/video.go index cfb5fc332..32e8bb969 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -1024,7 +1024,10 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { } f.Model, call.Model = m, m } - p, model, ok := provider.Resolve(f.Model) + p, model, ok := mediaGroupFirst(f.Model) + if !ok { + p, model, ok = provider.Resolve(f.Model) + } if !ok { p, model, ok = bareVideomaker(f.Model) } @@ -1036,7 +1039,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { fail(404, fmt.Sprintf("magpie knows no model %q to make videos with", f.Model)) return } - g, ms, isGroup := groupToMake(f.Model, p, model, provider.FindGroup) + g, ms, isGroup := groupToMake(f.Model, p, model, mediaMembers) if isGroup { r = heldByGroup(r, g) // held to the group's accounts, if it is } diff --git a/internal/provider/group.go b/internal/provider/group.go index e236ae873..b5e2f0454 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -1034,6 +1034,15 @@ func GroupFinder() func(id string) (Group, []Member, bool) { // beside them (jzw690 on X), so a group of image models draws on its // members without any of them being a model agents are offered. func FindDrawingGroup(id string, draws func(p Provider, model string) bool) (Group, []Member, bool) { + return FindGroupAlso(id, draws) +} + +// FindGroupAlso is FindGroup with a member also says is the group's kept +// where its provider's picks leave it out: picks are of chat models, so a +// group of models made for another API (images, embeddings, speech, +// video) keeps those of a provider with picks only so (FindDrawingGroup, +// the gateway's media groups). +func FindGroupAlso(id string, also func(p Provider, model string) bool) (Group, []Member, bool) { gid, ok := GroupIDOf(id) if !ok { return Group{}, nil, false @@ -1041,7 +1050,7 @@ func FindDrawingGroup(id string, draws func(p Provider, model string) bool) (Gro entries := providerEntries() all := groupsIn(entries) if g, ok := groupOf(all, gid); ok && !g.Disabled { - return g, membersFound(entries, entriesBy(entries), all, g, disabledNow(), draws), true + return g, membersFound(entries, entriesBy(entries), all, g, disabledNow(), also), true } return Group{}, nil, false }