diff --git a/docs/reference.md b/docs/reference.md index ada02e996..4ff12e79a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1656,6 +1656,34 @@ as broken. An image model is the exception that follows the rule above: it is tested by the name magpie knows it by, on the images API and on the chat it falls back to, because that is how a drawing is asked for. +### The API a model is asked on + +A relay whose one key serves some models on chat completions and others on +Responses, Anthropic's messages or Gemini's generateContent can be told which +API each model is asked on. It is the provider editor's **API this model is +asked on**, under Names, prices & levels, and `magpie model api` sets the same +setting from the terminal, so a script can set many models: + +```sh +magpie model api relay/gpt-5.5 # what it is asked on, and what the provider has +magpie model api relay/gpt-5.5 responses # chat, responses, anthropic, gemini or auto +magpie model api relay/claude-opus-5-5 relay/claude-sonnet-5 anthropic # several at once +magpie model api relay/gpt-5.5 --reset # auto again: the vendor's list and every URL +magpie model apis # the models you set an API for +magpie model apis relay # each of relay's models and its API +``` + +It is saved as the editor's Save saves it (`provider.SetModelPrefs`, into +`modelAPIs` in settings.json), so a running gateway asks the model on that +API from its next request, and the model lists magpie writes into the agents +are brought up to date. The provider needs a URL for the API (More endpoints +in its editor) and at least two of the four for there to be a choice; Vertex +AI's model ids say their own. An API that isn't one, an API the provider has +no URL for, a model the provider doesn't list, or a flag in place of a model +is refused, and when several models are named all are checked first, so a +refused command writes nothing. A setting kept for a model the vendor no +longer lists can still be taken off with `--reset`. + ### Routing groups A routing group is several models, from one provider or many, that an agent diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b9c1ace71..eeaf1b554 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). | 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) | | 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; 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) | +| 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`). | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | diff --git a/internal/cli/main.go b/internal/cli/main.go index 85cf570e0..e5a3090a3 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -90,6 +90,7 @@ const usage = `magpie — one place to pick every agent's model magpie models [] every model agents can pick, as provider/model; an agent's, and why others aren't magpie model name |--reset the name a model goes by, everywhere magpie model efforts ,|--reset the reasoning levels a model offers (magpie model help) + magpie model api chat|responses|anthropic|gemini|auto the API a model is asked on magpie visible [ ,… | all | --only-picked | --show-new] which models an agent is shown: families (magpie provider/group set family=…), or only the models ticked for it, a new one off until it is ticked diff --git a/internal/cli/model_api_cli.go b/internal/cli/model_api_cli.go new file mode 100644 index 000000000..3a5ea0985 --- /dev/null +++ b/internal/cli/model_api_cli.go @@ -0,0 +1,268 @@ +package cli + +import ( + "fmt" + "maps" + "slices" + "strings" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// magpie model api: the one API a provider's model is asked on, the +// setting the provider editor's Names, prices & levels picks ("API this +// model is asked on"), for a relay whose one key serves its models on +// different APIs, set from a script (yew_fence_931206 on Discord). It is +// saved through provider.SetModelPrefs, the editor's Save, into settings' +// modelAPIs, which a running gateway reads for each request. + +const apiUsage = `usage: + magpie model api the API the model is asked on, and the ones its provider has + magpie model api ... ask the model(s) on this API: chat, responses, anthropic or + gemini; auto leaves it to the vendor's list and every URL the + provider has, as by default + magpie model api ... --reset the same as auto + magpie model apis [] the models you set an API for; with a provider, each of its + models and the API it is asked on + + It is the provider editor's "API this model is asked on", under Names, prices & levels, and is + saved the same way: the app, a running gateway and the agents' model lists go by it at once. + The provider needs a URL for the API (More endpoints in its editor), and at least two of + chat, responses, anthropic and gemini, for there to be a choice. Several models in one command + are all checked first: a model the provider doesn't list, or an API it has no URL for, refuses + the whole command, and nothing is written. + + e.g. magpie model api relay/gpt-5.5 responses + magpie model api relay/claude-opus-5-5 relay/claude-sonnet-5 anthropic + magpie model api relay/gpt-5.5 --reset + magpie model apis relay` + +// apiNames are the APIs a model can be set to be asked on, in the +// editor's order. +var apiNames = []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini} + +// apiLabels are the editor's names of them. +var apiLabels = map[provider.Protocol]string{ + provider.Chat: "Chat", provider.Responses: "Responses", provider.Anthropic: "Anthropic", provider.Gemini: "Gemini", +} + +// apiChoices are the APIs one of p's models can be asked on alone, as the +// editor offers them (modelAPIs in app.js): those p has a URL for, when it +// has more than one. Vertex AI's model id says its one API. +func apiChoices(p *provider.Provider) []provider.Protocol { + if p.IsVertex() { + return nil + } + var out []provider.Protocol + for _, a := range apiNames { + if strings.TrimSpace(p.Base(a)) != "" { + out = append(out, a) + } + } + if len(out) < 2 { + return nil + } + return out +} + +func apiList(as []provider.Protocol) string { + s := make([]string, len(as)) + for i, a := range as { + s[i] = string(a) + } + return strings.Join(s, ", ") +} + +func modelAPICmd(args []string) error { + if len(args) == 0 { + return fmt.Errorf("%s", apiUsage) + } + if slices.ContainsFunc(args, isHelp) { + fmt.Println(apiUsage) + return nil + } + if len(args) == 1 { + return showModelAPI(args[0]) + } + refs, val := args[:len(args)-1], strings.ToLower(strings.TrimSpace(args[len(args)-1])) + if isReset([]string{val}) || val == provider.Auto { + val = "" + } else if !slices.Contains(apiNames, provider.Protocol(val)) { + return fmt.Errorf("a model's API is chat, responses, anthropic, gemini or auto, not %q\n\n%s", args[len(args)-1], apiUsage) + } + // every model is checked before any is written + type one struct { + p *provider.Provider + model string + } + var todo []one + set := settings.Load().ModelAPIs + for _, ref := range refs { + if strings.HasPrefix(ref, "-") { + return fmt.Errorf("%q is not a model: name each as provider/model, then the API\n\n%s", ref, apiUsage) + } + p, model, err := modelRef(ref) + if err != nil { + return err + } + _, had := set[p.ID+"/"+model] + // a setting kept for a model the vendor no longer lists can still + // be taken off + if !provider.ServesModel(*p, model) && !(val == "" && had) { + return fmt.Errorf("%s has no model %s (magpie provider models %s lists them)", p.ID, model, p.ID) + } + if val != "" { + choices := apiChoices(p) + if len(choices) == 0 { + return fmt.Errorf("%s has one API only, so each of its models is asked on it: add another URL under More endpoints in its editor first", p.ID) + } + if !slices.Contains(choices, provider.Protocol(val)) { + return fmt.Errorf("%s has no %s URL to ask %s on (it has %s): add it under More endpoints in its editor first", p.ID, val, model, apiList(choices)) + } + } + todo = append(todo, one{p, model}) + } + // by provider, as the editor's Save sends them + prefs := map[string]map[string]provider.ModelPref{} + for _, o := range todo { + if prefs[o.p.ID] == nil { + prefs[o.p.ID] = map[string]provider.ModelPref{} + } + v := val + prefs[o.p.ID][o.model] = provider.ModelPref{API: &v} + } + for _, pid := range slices.Sorted(maps.Keys(prefs)) { + if err := provider.SetModelPrefs(pid, prefs[pid]); err != nil { + return err + } + } + for _, o := range todo { + ref := o.p.ID + "/" + o.model + before := set[ref] + switch { + case before == val && val == "": + fmt.Println(muted.Render(ref + " is asked as its vendor's list says already (auto)")) + case before == val: + fmt.Println(muted.Render(ref + " is asked on " + apiLabels[provider.Protocol(val)] + " already")) + case val == "": + fmt.Println(green.Render("✓"), ref, muted.Render("· auto: asked as its vendor's list says, on the URLs "+o.p.ID+" has")) + default: + fmt.Println(green.Render("✓"), ref, muted.Render("· asked on "+apiLabels[provider.Protocol(val)])) + } + } + return nil +} + +// showModelAPI says what one model is asked on. +func showModelAPI(ref string) error { + if strings.HasPrefix(ref, "-") { + return fmt.Errorf("name the model first, as provider/model, not %q\n\n%s", ref, apiUsage) + } + p, model, err := modelRef(ref) + if err != nil { + return err + } + saved, had := settings.Load().ModelAPIs[p.ID+"/"+model] + if !provider.ServesModel(*p, model) && !had { + return fmt.Errorf("%s has no model %s (magpie provider models %s lists them)", p.ID, model, p.ID) + } + choices := apiChoices(p) + id := p.ID + "/" + model + if api, ok := p.ModelAPI(model); ok { + fmt.Println(bold.Render(id), muted.Render("· asked on "+apiLabels[api]+" · set by you")) + } else { + fmt.Println(bold.Render(id), muted.Render("· auto"+listedNote(p, model))) + if had { + fmt.Println(muted.Render(" your " + saved + " is not in force: " + p.ID + " has no " + saved + " URL now, or only one API")) + } + } + if len(choices) == 0 { + fmt.Println(faint.Render(" · " + p.ID + " has one API only, so there is nothing to pick")) + return nil + } + fmt.Println(faint.Render(" · " + p.ID + " has " + apiList(choices) + " · magpie model api " + id + " to pick one")) + return nil +} + +// listedNote is what auto means for p's model: the APIs its vendor's list +// says it is served on, when it says. +func listedNote(p *provider.Provider, model string) string { + var on []provider.Protocol + for _, a := range p.ListedAPIs(model) { + if slices.Contains(apiNames, a) { + on = append(on, a) + } + } + if len(on) == 0 { + return ": each API the provider has, as it answers" + } + return ": as its vendor's list says, " + apiList(on) +} + +// modelAPIs is `magpie model apis`: the models the user set an API for; +// with a provider, each of its models and the API it is asked on, for a +// script to read. +func modelAPIs(args []string) error { + if len(args) > 0 && isHelp(args[0]) { + fmt.Println(apiUsage) + return nil + } + if len(args) > 1 || (len(args) == 1 && strings.HasPrefix(args[0], "-")) { + return fmt.Errorf("%s", apiUsage) + } + set := settings.Load().ModelAPIs + if len(args) == 1 { + p, err := provider.Find(strings.TrimSuffix(args[0], "/")) + if err != nil { + return err + } + var models []string + for _, m := range p.Available() { + if !slices.Contains(models, m.ID) { + models = append(models, m.ID) + } + } + for k := range set { + if model, ok := strings.CutPrefix(k, p.ID+"/"); ok && !slices.Contains(models, model) { + models = append(models, model) + } + } + if len(models) == 0 { + fmt.Println(muted.Render(p.ID + " lists no models yet · magpie provider models " + p.ID)) + return nil + } + w := 0 + for _, m := range models { + w = max(w, len(p.ID)+1+len(m)) + } + for _, m := range models { + api := provider.Auto + if a, ok := p.ModelAPI(m); ok { + api = string(a) + } + note := "" + if s, ok := set[p.ID+"/"+m]; ok && api == provider.Auto { + note = muted.Render(" (your " + s + " is not in force: no " + s + " URL now, or only one API)") + } + fmt.Printf("%-*s %s%s\n", w, p.ID+"/"+m, api, note) + } + if len(apiChoices(p)) == 0 { + fmt.Println(faint.Render(" · " + p.ID + " has one API only, so each model is asked on it")) + } + return nil + } + keys := slices.Sorted(maps.Keys(set)) + if len(keys) == 0 { + fmt.Println(muted.Render("no model has an API of yours yet · magpie model api ")) + return nil + } + w := 0 + for _, k := range keys { + w = max(w, len(k)) + } + for _, k := range keys { + fmt.Printf("%-*s %s\n", w, k, set[k]) + } + return nil +} diff --git a/internal/cli/model_api_cli_test.go b/internal/cli/model_api_cli_test.go new file mode 100644 index 000000000..c785b0bd1 --- /dev/null +++ b/internal/cli/model_api_cli_test.go @@ -0,0 +1,180 @@ +package cli + +import ( + "io" + "maps" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// apiHome is groupsHome with a relay whose one key serves its models on +// three APIs, and a provider with one. +func apiHome(t *testing.T, chat, anthropic string) { + t.Helper() + groupsHome(t) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Chat: chat, Responses: "http://127.0.0.1:1/v1", Anthropic: anthropic, Models: []string{"gpt-x", "claude-y", "mixed"}}, + {ID: "solo", Name: "Solo", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } +} + +// magpie model api sets the API a model is asked on, as the provider +// editor's picker does, for several models at once (yew_fence_931206 on +// Discord: a script setting each model of one key's relay); apis lists +// them, and --reset or auto takes them off. --help prints the usage, and a +// flag, an unknown API, a model the provider doesn't list or an API it +// has no URL for is refused with nothing written, the other models of the +// same command included. +func TestModelAPICmd(t *testing.T) { + apiHome(t, "http://127.0.0.1:1/v1", "http://127.0.0.1:1") + if out, err := runOut(t, "model", "apis"); err != nil || !strings.Contains(out, "no model has an API of yours yet") { + t.Fatalf("empty list: %q %v", out, err) + } + if out, err := runOut(t, "model", "api", "relay/gpt-x", "relay/mixed", "responses"); err != nil || !strings.Contains(out, "relay/gpt-x") || !strings.Contains(out, "relay/mixed") || !strings.Contains(out, "asked on Responses") { + t.Fatalf("set: %q %v", out, err) + } + if out, err := runOut(t, "model", "api", "relay/claude-y", "Anthropic"); err != nil || !strings.Contains(out, "asked on Anthropic") { + t.Fatalf("set: %q %v", out, err) + } + want := map[string]string{"relay/gpt-x": "responses", "relay/mixed": "responses", "relay/claude-y": "anthropic"} + if got := settings.Load().ModelAPIs; !maps.Equal(got, want) { + t.Fatalf("settings: %v", got) + } + p, err := provider.Find("relay") + if err != nil { + t.Fatal(err) + } + if api, ok := p.ModelAPI("gpt-x"); !ok || api != provider.Responses { + t.Fatalf("relay/gpt-x is asked on %q %v", api, ok) + } + if out, err := runOut(t, "model", "api", "relay/gpt-x"); err != nil || !strings.Contains(out, "asked on Responses") || !strings.Contains(out, "chat, responses, anthropic") { + t.Fatalf("show: %q %v", out, err) + } + if out, err := runOut(t, "model", "apis"); err != nil || !strings.Contains(out, "relay/claude-y anthropic") || !strings.Contains(out, "relay/gpt-x responses") { + t.Fatalf("list: %q %v", out, err) + } + if out, err := runOut(t, "model", "apis", "relay"); err != nil || !strings.Contains(out, "relay/mixed responses") || !strings.Contains(out, "relay/claude-y anthropic") { + t.Fatalf("list relay: %q %v", out, err) + } + for _, bad := range [][]string{ + {"model", "api"}, + {"model", "api", "--reset"}, + {"model", "api", "relay/gpt-x", "--force"}, + {"model", "api", "relay/gpt-x", "openai"}, + {"model", "api", "relay/gpt-x", "two words"}, + {"model", "api", "relay/nope", "chat"}, + {"model", "api", "relay/nope", "--reset"}, + {"model", "api", "relay/gpt-x", "relay/nope", "chat"}, + {"model", "api", "relay/mixed", "--force", "chat"}, + {"model", "api", "relay/mixed", "gemini"}, // no Gemini URL + {"model", "api", "solo/m", "chat"}, // one API only + {"model", "api", "nobody/m", "chat"}, + {"model", "api", "gpt-x", "chat"}, + {"model", "apis", "nobody"}, + {"model", "apis", "--force"}, + } { + if _, err := runOut(t, bad...); err == nil { + t.Errorf("took %v", bad) + } + } + for _, help := range [][]string{ + {"model", "api", "--help"}, + {"model", "api", "relay/gpt-x", "chat", "--help"}, + {"model", "api", "-h"}, + {"model", "apis", "--help"}, + } { + if out, err := runOut(t, help...); err != nil || !strings.Contains(out, "magpie model api ... ") { + t.Errorf("%v: %q %v", help, out, err) + } + } + if got := settings.Load().ModelAPIs; !maps.Equal(got, want) { + t.Fatalf("a refused command wrote: %v", got) + } + if out, err := runOut(t, "model", "api", "relay/gpt-x", "--reset"); err != nil || !strings.Contains(out, "auto") { + t.Fatalf("reset: %q %v", out, err) + } + if out, err := runOut(t, "model", "api", "relay/mixed", "relay/claude-y", "auto"); err != nil || strings.Count(out, "✓") != 2 { + t.Fatalf("auto: %q %v", out, err) + } + if got := settings.Load().ModelAPIs; len(got) != 0 { + t.Fatalf("after reset: %v", got) + } + if out, err := runOut(t, "model", "api", "relay/gpt-x"); err != nil || !strings.Contains(out, "auto") { + t.Fatalf("show after reset: %q %v", out, err) + } +} + +// The API set from the terminal reaches a gateway already running, as a +// save in the editor does: a model asked on chat completions goes to +// Anthropic's messages from the next request on, and back after --reset. +func TestModelAPIReachesTheRunningGateway(t *testing.T) { + var mu sync.Mutex + var hits []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + hits = append(hits, r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/v1/chat/completions": + io.WriteString(w, `{"id":"c","object":"chat.completion","model":"mixed","choices":[{"index":0,"message":{"role":"assistant","content":"from chat"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`) + case "/v1/messages": + // asked translated, it is asked to stream + w.Header().Set("Content-Type", "text/event-stream") + for _, e := range []string{ + `event: message_start` + "\n" + `data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"mixed","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}`, + `event: content_block_start` + "\n" + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta` + "\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from messages"}}`, + `event: content_block_stop` + "\n" + `data: {"type":"content_block_stop","index":0}`, + `event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `event: message_stop` + "\n" + `data: {"type":"message_stop"}`, + } { + io.WriteString(w, e+"\n\n") + } + default: + http.NotFound(w, r) + } + })) + defer up.Close() + apiHome(t, up.URL+"/v1", up.URL) + gw := httptest.NewServer(gateway.New().Handler()) + defer gw.Close() + ask := func(want, path string) { + t.Helper() + mu.Lock() + hits = nil + mu.Unlock() + res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"relay/mixed","messages":[{"role":"user","content":"hi"}]}`)) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + mu.Lock() + h := append([]string(nil), hits...) + mu.Unlock() + if res.StatusCode != 200 || !strings.Contains(string(b), want) || len(h) != 1 || h[0] != path { + t.Fatalf("%d %s, upstream asked %v; want %s at %s", res.StatusCode, b, h, want, path) + } + } + ask("from chat", "/v1/chat/completions") + if _, err := runOut(t, "model", "api", "relay/mixed", "anthropic"); err != nil { + t.Fatal(err) + } + ask("from messages", "/v1/messages") + if _, err := runOut(t, "model", "api", "relay/mixed", "--reset"); err != nil { + t.Fatal(err) + } + ask("from chat", "/v1/chat/completions") +} diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go index 6ca994c29..020f48a78 100644 --- a/internal/cli/model_cli.go +++ b/internal/cli/model_cli.go @@ -70,6 +70,10 @@ const modelUsage = `usage: your own (a key) only magpie model id --reset list it by the provider's own id again magpie model ids the models you list by an id of your own + magpie model api ... ask the model(s) on one API of the provider's: chat, + responses, anthropic, gemini, or auto (--reset) for the + vendor's list and every URL it has (magpie model api --help) + magpie model apis [] the models you set an API for, or each of a provider's magpie model names the models you named or narrowed magpie model alias count the model's usage under another model id in Usage, Sessions and the usage summaries, e.g. deepseek-v4.1-flash @@ -155,6 +159,10 @@ func modelCmd(args []string) error { return modelSpecs() case "id": return modelID(args[1:]) + case "api", "protocol": + return modelAPICmd(args[1:]) + case "apis", "protocols": + return modelAPIs(args[1:]) case "ids": return modelIDs() case "alias":