From 191f3c0af1934fbbec87dc589fddf26913699aa9 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 7 Nov 2026 16:05:37 +0800 Subject: [PATCH] gateway: POST /v1/decisions goes to OpenAI, Azure OpenAI or another magpie A Discord user's POST /v1/decisions was answered 404 ("magpie serves /v1/chat/completions, ..."). It is OpenAI's Decisions API (gpt-6-luna): one input, up to 400 questions, typed answers, input tokens billed only. The shape was taken from openai-python (resources/decisions.py, types/decision_create_params.py, types/decision.py, added in #4033 on 10-06) and the Decisions guide, not guessed: POST /v1/decisions, a JSON body of model, input (a string or messages/items with input_text, input_image as a data or http(s) URL, JSON parts; function and custom tool calls and their outputs), questions (predicate / choice / score), and optional prompt_cache_key, prompt_cache_options, safety_identifier. The answer is {answers, model, usage}, not streamed; usage.input_tokens includes input_tokens_details.cached_tokens and cache_write_tokens. The Azure client sends it on the v1 API (/openai/v1/decisions), the model in the body. - decide (decisions.go) goes through serveRetrieval as embeddings and rerank do, body as sent with only model changed. So a disabled model, a key's models, accounts and spent limits, pause rules, keys/accounts of the provider, masking and the Routing page hold here as on every route. - Only a provider canDecide takes is sent it: an OpenAI API key on api.openai.com, Azure OpenAI (IsAzure, at its OpenAIBase, so /openai/v1/decisions with api-key), or another magpie. Anyone else (a relay, a plugin, a ChatGPT sign-in) gets a 400 that says who serves it, checked in serveRetrieval's try loop beside the no-OpenAI-API check (refusingRetrieval), never the vendor's 404; a group moves on. - A bare gpt-6-luna is a kind group "decision" (servesDecision), so a relay that lists the same id is never its member. - Usage is recorded as "decisions" (countedRetrieval): input less the cached and cache-written tokens, those as CacheRead/CacheWrite, and no output, so gpt-6-luna's own models.dev rates price it as OpenAI bills ($0.10/1M input, cache read/write at their rates). - /decisions joins the one-port client prefixes, another magpie's URL suffixes, the 404's route list and info's apis. The readonly, LAN and CORS guard tests list the route. - native_endpoints is left alone: it names the chat APIs a model is relayed on (Cursor's names, a remote's API choice). - docs: gateway-routing.md has a Decisions row; reference.md a section. Run on mote at this tree (mote-run): gofmt -l clean; go vet of gateway and provider; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build ./..., linux nogui and windows builds ok; go test -count=1 -timeout 45m ./internal/gateway ./internal/provider ./internal/usage: ok (gateway 413s, provider 88s, usage 18s). Red on the old code (e0930b1de, the new tests copied in): every TestDecisions* is red with magpie's 404. Broken by hand, each red: refuses always "" (the relay is sent it: TestDecisionsRefusedWhereNotServed); the cache split not read (Input 1200, CacheRead 0: TestDecisionsReachOpenAIAndAzure); canDecide without the api.openai.com check (TestCanDecide, the relay sent it); /v1/decisions out of the remote suffixes (TestRemoteMagpie). Not tried: a real OpenAI Decisions request, or a real Azure resource. Tests reach only httptest servers (OpenAI's host through the provider's proxy). --- docs/reference.md | 16 ++ docs/subsystems/gateway-routing.md | 3 +- internal/gateway/cors_test.go | 2 + internal/gateway/decisions.go | 111 +++++++++ internal/gateway/decisions_test.go | 293 ++++++++++++++++++++++++ internal/gateway/embeddings.go | 31 ++- internal/gateway/gateway.go | 7 +- internal/gateway/lan_test.go | 2 +- internal/gateway/media_group.go | 7 +- internal/gateway/oneport.go | 2 +- internal/gateway/readonly_test.go | 1 + internal/provider/remote_magpie.go | 2 +- internal/provider/remote_magpie_test.go | 1 + 13 files changed, 468 insertions(+), 10 deletions(-) create mode 100644 internal/gateway/decisions.go create mode 100644 internal/gateway/decisions_test.go diff --git a/docs/reference.md b/docs/reference.md index 84714e30d..6a743b0aa 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1040,6 +1040,22 @@ curl localhost:3425/v1/rerank -H "Authorization: Bearer $MAGPIE_KEY" \ -d '{"model":"voyage/rerank-3","query":"what eats seeds","documents":["a magpie","a stone"],"top_k":1}' ``` +### Decisions + +`/v1/decisions` (also without `/v1`) is OpenAI's Decisions API: a model +(`gpt-6-luna`), an `input` every question shares (text, images, a +conversation), and `questions`, each answered with a probability, a choice +or a score. It takes the gateway's key, as chat does, and is sent as given, +only `model` changed, to an OpenAI API key, to Azure OpenAI (at +`/openai/v1/decisions`, the model your deployment's name) or to another +magpie. Any other provider is refused with a 400 that says so. Only input +tokens are counted, cached ones apart. + +```sh +curl localhost:3425/v1/decisions -H "Authorization: Bearer $MAGPIE_KEY" \ + -d '{"model":"gpt-6-luna","input":"The parcel arrived torn open.","questions":[{"type":"predicate","name":"damaged","instructions":"Was the parcel damaged?"}]}' +``` + ### Google Vertex AI Google Vertex AI (`google-vertex`), which Google's documentation now calls diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 53d783ec3..826d7bd63 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -39,6 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | +| Decisions | `POST /v1/decisions` (and `/decisions`) is OpenAI's Decisions API, checked against openai-python's `decisions.create` (`DecisionCreateParams`, `Decision`): `model` (gpt-6-luna), `input` (a string, or messages and items whose parts are `input_text`, `input_image` with a data or http(s) URL, JSON), `questions` (1 to 400 predicate, choice or score questions), and `prompt_cache_key`, `prompt_cache_options`, `safety_identifier`. The answer is `{answers, model, usage}`, never streamed. `decide` passes the body through `serveRetrieval` as embeddings' is, with only `model` changed, so model resolution, a disabled model, a key's models, accounts and spent limits, pause rules, the provider's keys or accounts, masking (a data URL's image is left as it is) and the Routing page hold as on every route. It goes only to a provider `canDecide` takes: an OpenAI API key on `api.openai.com`, Azure OpenAI (`IsAzure`, at its v1 API's `/openai/v1/decisions`, the model in the body as the deployment's name), or another magpie, which routes it on. Any other, a relay, a plugin or a ChatGPT sign-in whatever its list says, is never sent it: the try is refused 400 with who serves it (`decisionRequest.refuses`, next to the no-OpenAI-API check), and a group moves on to its next member. A bare `gpt-6-luna` is the kind group `decision` (`servesDecision`: a provider `canDecide` takes that lists the model, or an OpenAI key, as the API takes it without it on the key's chat list), so a relay listing the same id is never its member. Usage is recorded as `decisions` from the answer's `usage` (`decisionRequest.counted`): `input_tokens` less `input_tokens_details`' `cached_tokens` and `cache_write_tokens` as input, those two as cache read and write, and no output, as OpenAI bills none, so gpt-6-luna's own rates price it. `native_endpoints` is about the chat APIs a model is relayed on, and stays chat/completions and responses. `TestDecisionsReachOpenAIAndAzure`, `TestDecisionsRefusedWhereNotServed`, `TestCanDecide`, `TestDecisionsThroughAnotherMagpie`, `TestDecisionsHeldByKeysAndRules`. | [`decisions.go`](../../internal/gateway/decisions.go), [`embeddings.go`](../../internal/gateway/embeddings.go), [`media_group.go`](../../internal/gateway/media_group.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one 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`). | @@ -623,7 +624,7 @@ read-only and held key, and expects nothing spent until the full key asks. A remote provider serves the conversation, token-counting, System One, -embeddings, rerank, speech-to-text, image generation/edit and video +embeddings, rerank, Decisions, speech-to-text, image generation/edit and video creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the same model routing as other conversation clients. Responses is served over HTTP/SSE and over a WebSocket ([A Responses diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index e5bcb8d23..6dfc97cec 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -238,6 +238,7 @@ func TestForeignPagesRefused(t *testing.T) { {"POST", "/v1beta/models/plan/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, {"POST", "/v1/embeddings", `{"model":"plan/m1","input":"hi"}`}, {"POST", "/v1/rerank", `{"model":"plan/m1","query":"hi","documents":["a"]}`}, + {"POST", "/v1/decisions", `{"model":"plan/m1","input":"hi","questions":[{"type":"predicate","instructions":"is it?"}]}`}, {"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"}, {"POST", "/v1/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`}, {"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`}, @@ -355,6 +356,7 @@ func TestOpaqueOriginNeedsAKey(t *testing.T) { {"POST", "/v1/messages"}, {"POST", "/v1/images/generations"}, {"POST", "/v1/embeddings"}, + {"POST", "/v1/decisions"}, {"GET", "/v1/models"}, } { if w := do(p.method, p.path, "null", ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "gateway key") || w.Header().Get("Access-Control-Allow-Origin") != "" { diff --git a/internal/gateway/decisions.go b/internal/gateway/decisions.go new file mode 100644 index 000000000..7ac0b47e1 --- /dev/null +++ b/internal/gateway/decisions.go @@ -0,0 +1,111 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// kindDecision is the kind of model OpenAI's Decisions API is asked of +// (serveRetrieval's "decisions"): a group of it is the providers that +// can serve the API and list the model (servesKind). +const kindDecision = "decision" + +// decisionModels are the models OpenAI's Decisions API takes +// (openai-python's DecisionCreateParams.model: gpt-6-luna alone), served +// by a provider that can serve the API even when its list of models to +// chat with leaves them out. +var decisionModels = []string{"gpt-6-luna"} + +// decide serves POST /v1/decisions, OpenAI's Decisions API: a model, an +// input shared by every question (text, images, a conversation's items) +// and up to 400 questions, each answered with a probability, a choice or +// a score. Like embeddings it is no chat, so it is not translated: the +// body goes as the agent sent it to a provider that can serve the API +// (canDecide), at its OpenAI-style base + /decisions (Azure's +// /openai/v1/decisions), and the answer comes back as it said it. The +// API isn't streamed, and bills input tokens only. +func (s *Server) decide(w http.ResponseWriter, r *http.Request) { + body, admitted := s.requestBody(w, r, provider.Chat) + if !admitted { + return + } + start := time.Now() + var req map[string]json.RawMessage + if json.Unmarshal(body, &req) != nil || req == nil { + writeError(w, provider.Chat, 400, "the body isn't a JSON object") + return + } + var asked string + json.Unmarshal(req["model"], &asked) + if asked == "" { + writeError(w, provider.Chat, 400, "name the model: \"model\" is a magpie model id, as /v1/models lists them (OpenAI's Decisions API takes gpt-6-luna)") + return + } + s.serveRetrieval(w, r, "/decisions", "decisions", start, asked, &decisionRequest{jsonRetrieval{req: req}}) +} + +// decisionRequest is a Decisions API body: a JSON object, sent only to +// a provider that can serve the API, and counted by its own usage. +type decisionRequest struct{ jsonRetrieval } + +// refuses is why p can't be sent the request, "" when it can. +func (d *decisionRequest) refuses(p provider.Provider) string { + if canDecide(p) { + return "" + } + return fmt.Sprintf("%s can't serve OpenAI's Decisions API (/v1/decisions): only an OpenAI API key, Azure OpenAI and another magpie serve it", p.Name) +} + +// counted is what the answer's usage says: input_tokens has the cached +// and cache-written tokens in it (input_tokens_details), told apart so +// each is priced at its rate; no output is billed. +func (d *decisionRequest) counted(b []byte) Usage { + var a struct { + Usage struct { + Input int `json:"input_tokens"` + Details struct { + Cached int `json:"cached_tokens"` + Write int `json:"cache_write_tokens"` + } `json:"input_tokens_details"` + } `json:"usage"` + } + if json.Unmarshal(b, &a) != nil { + return Usage{} + } + u := a.Usage + read, write := max(u.Details.Cached, 0), max(u.Details.Write, 0) + return Usage{Input: max(u.Input-read-write, 0), CacheRead: read, CacheWrite: write} +} + +// canDecide is whether p can serve OpenAI's Decisions API: OpenAI's own +// API with a key (a ChatGPT sign-in's backend has no such route), Azure +// OpenAI, which serves it on its v1 API, or another magpie, which routes +// it on. A relay or a plugin, whatever models it lists, is none. +func canDecide(p provider.Provider) bool { + if p.IsPlugin() { + return false + } + if p.IsRemoteMagpie() || p.IsAzure() { + return true + } + return p.Account == nil && p.Key != "" && provider.HostOf(p.Base(provider.Chat)) == "api.openai.com" +} + +// servesDecision is servesKind's for the Decisions API: a provider that +// can serve it with the model on its list, or an OpenAI key asked for a +// model the API takes. Azure's ids are its deployments' and another +// magpie's are its own, so each has the model when its list says so. +func servesDecision(p provider.Provider, model string) bool { + if !canDecide(p) { + return false + } + if !offChatList(p, model) { + return true + } + return slices.Contains(decisionModels, model) && !p.IsAzure() && !p.IsRemoteMagpie() +} diff --git a/internal/gateway/decisions_test.go b/internal/gateway/decisions_test.go new file mode 100644 index 000000000..4d9de57f5 --- /dev/null +++ b/internal/gateway/decisions_test.go @@ -0,0 +1,293 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// decisionAsked is the Decisions guide's request +// (developers.openai.com/api/docs/guides/decisions), as openai-python's +// client.decisions.create sends it: a model, the input every question +// shares (a user message of text and an image) and the questions. +func decisionAsked(model string) string { + return `{"model":"` + model + `","input":[{"role":"user","content":[{"type":"input_text","text":"Inspect the product in this photo."},{"type":"input_image","image_url":"data:image/png;base64,iVBORw0KGgo="}]}],"questions":[{"type":"predicate","name":"visible_damage","instructions":"Is there visible damage?"},{"type":"choice","name":"condition","instructions":"Its condition","choices":[{"value":"new"},{"value":"used"}]}]}` +} + +// decisionAnswer is a Decisions answer, the shape openai-python's +// Decision reads: typed answers and a usage whose input_tokens has its +// cached and cache-written tokens in it. +const decisionAnswer = `{"answers":[{"type":"predicate","name":"visible_damage","probability":0.92},{"type":"choice","name":"condition","choice":"used","confidence":0.8,"probabilities":[{"value":"new","probability":0.2},{"value":"used","probability":0.8}]}],"model":"gpt-6-luna","usage":{"input_tokens":1200,"input_tokens_details":{"cached_tokens":1000,"cache_write_tokens":50},"output_tokens":3,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":1203}}` + +type decisionHit struct { + host, path, auth, apiKey string + body map[string]any +} + +// decider is a vendor that serves the Decisions API at /v1/decisions and +// Azure's /openai/v1/decisions, and keeps each request. +type decider struct { + mu sync.Mutex + hits []decisionHit +} + +func (d *decider) ServeHTTP(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body map[string]any + json.Unmarshal(raw, &body) + d.mu.Lock() + d.hits = append(d.hits, decisionHit{host: r.Host, path: r.URL.Path, auth: r.Header.Get("Authorization"), apiKey: r.Header.Get("api-key"), body: body}) + d.mu.Unlock() + if r.URL.Path != "/v1/decisions" && r.URL.Path != "/openai/v1/decisions" { + w.WriteHeader(404) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, decisionAnswer) +} + +func (d *decider) all() []decisionHit { + d.mu.Lock() + defer d.mu.Unlock() + return append([]decisionHit(nil), d.hits...) +} + +// decidingProviders saves an OpenAI API key (reached through the +// provider's proxy, so its host is OpenAI's own), an Azure OpenAI +// resource and a relay that lists gpt-6-luna among its chat models. +func decidingProviders(t *testing.T) (*decider, *decider) { + t.Helper() + fresh(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + openai := &decider{} + ou := httptest.NewServer(openai) + t.Cleanup(ou.Close) + if err := provider.Save(provider.Provider{ID: "openai", Name: "OpenAI", Key: "sk-openai", Chat: "http://api.openai.com/v1", Proxy: ou.URL, Models: []string{"gpt-6-sol"}}); err != nil { + t.Fatal(err) + } + other := &decider{} + au := httptest.NewServer(other) + t.Cleanup(au.Close) + az, err := provider.FromPreset(provider.AzurePreset) + if err != nil { + t.Fatal(err) + } + az.Key, az.Chat, az.Models = "azure-key", au.URL+"/openai/v1", []string{"luna-deploy"} + az.Responses = az.Chat + if err := provider.Save(az); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "relay-key", Chat: au.URL + "/v1", Models: []string{"gpt-6-luna"}}); err != nil { + t.Fatal(err) + } + return openai, other +} + +func decisionRecords(t *testing.T, n int) []usage.Record { + t.Helper() + var recs []usage.Record + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { + recs = nil + for _, r := range usage.Load(time.Time{}) { + if r.Operation == "decisions" { + recs = append(recs, r) + } + } + if len(recs) >= n { + return recs + } + } + t.Fatalf("%d decisions recorded, want %d: %+v", len(recs), n, recs) + return nil +} + +// POST /v1/decisions (a Discord user had a 404) goes as the agent sent it +// to OpenAI with its key, to Azure OpenAI at its v1 API's +// /openai/v1/decisions with the key in api-key, and on the bare +// /decisions an SDK given magpie's root posts to. The answer comes back +// as OpenAI said it, and the call is recorded as decisions: its input +// apart from the cached and cache-written tokens, each priced at its +// rate, and no output. +func TestDecisionsReachOpenAIAndAzure(t *testing.T) { + openai, other := decidingProviders(t) + s := New() + for _, tc := range []struct { + name, path, model, sentModel, host, upPath string + up *decider + }{ + {"openai by its ref", "/v1/decisions", "openai/gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai}, + // a relay lists the same id, but only OpenAI can serve the API + {"the bare id", "/v1/decisions", "gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai}, + {"the bare path", "/decisions", "openai/gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai}, + {"azure", "/v1/decisions", "azure/luna-deploy", "luna-deploy", "", "/openai/v1/decisions", other}, + } { + t.Run(tc.name, func(t *testing.T) { + before := len(tc.up.all()) + code, raw := postJSON(t, s, tc.path, decisionAsked(tc.model)) + if code != 200 || raw != decisionAnswer { + t.Fatalf("%d %s", code, raw) + } + hits := tc.up.all() + if len(hits) != before+1 { + t.Fatalf("vendor asked %d times", len(hits)-before) + } + h := hits[len(hits)-1] + if h.path != tc.upPath || tc.host != "" && h.host != tc.host || h.body["model"] != tc.sentModel { + t.Fatalf("sent to %s%s as %v", h.host, h.path, h.body["model"]) + } + if qs, _ := h.body["questions"].([]any); len(qs) != 2 { + t.Fatalf("questions sent: %v", h.body["questions"]) + } + in, _ := h.body["input"].([]any) + if b, _ := json.Marshal(in); !strings.Contains(string(b), `"image_url":"data:image/png;base64,iVBORw0KGgo="`) { + t.Fatalf("input sent: %s", b) + } + if tc.up == other { + if h.apiKey != "azure-key" || h.auth != "" { + t.Fatalf("azure signed with %q %q", h.apiKey, h.auth) + } + } else if h.auth != "Bearer sk-openai" { + t.Fatalf("openai signed with %q", h.auth) + } + }) + } + for _, h := range other.all() { + if h.path == "/v1/decisions" { + t.Fatal("the relay was sent a decision") + } + } + recs := decisionRecords(t, 4) + for _, r := range recs { + if r.Status != 200 || r.Input != 150 || r.CacheRead != 1000 || r.CacheWrite != 50 || r.Output != 0 { + t.Fatalf("recorded %+v", r) + } + } + if r := recs[0]; r.Provider != "openai" || r.Model != "gpt-6-luna" || r.Requested != "openai/gpt-6-luna" { + t.Fatalf("recorded %+v", r) + } +} + +// A provider that can't serve the Decisions API is never sent the +// request: a relay, whatever its list says, gets a 400 that says who +// can, not the vendor's 404. +func TestDecisionsRefusedWhereNotServed(t *testing.T) { + _, other := decidingProviders(t) + code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("relay/gpt-6-luna")) + if code != 400 || !strings.Contains(raw, "Relay can't serve OpenAI's Decisions API") || !strings.Contains(raw, "Azure OpenAI") { + t.Fatalf("%d %s", code, raw) + } + if hits := other.all(); len(hits) != 0 { + t.Fatalf("the relay was asked: %+v", hits) + } + // no model, no JSON + if code, raw := postJSON(t, New(), "/v1/decisions", `{"input":"hi","questions":[]}`); code != 400 || !strings.Contains(raw, "name the model") { + t.Fatalf("no model: %d %s", code, raw) + } +} + +// canDecide: OpenAI's API with a key, Azure OpenAI and another magpie; +// never a ChatGPT sign-in on OpenAI's host, a plugin, or a relay. +func TestCanDecide(t *testing.T) { + for _, tc := range []struct { + name string + p provider.Provider + want bool + }{ + {"openai key", provider.Provider{ID: "openai", Key: "sk", Chat: "https://api.openai.com/v1"}, true}, + {"azure", provider.Provider{ID: "az", Preset: provider.AzurePreset, Key: "k", Chat: "https://res.openai.azure.com/openai/v1"}, true}, + {"azure by its host", provider.Provider{ID: "az2", Key: "k", Chat: "https://res.openai.azure.com/openai/v1"}, true}, + {"another magpie", provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Key: "k", Chat: "http://192.168.1.20:3425/v1"}, true}, + {"a chatgpt sign-in", provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}, Chat: "https://api.openai.com/v1"}, false}, + {"a plugin", provider.PluginForTest("grok", "grok"), false}, + {"a relay", provider.Provider{ID: "relay", Key: "k", Chat: "https://relay.example/v1"}, false}, + {"openai with no key", provider.Provider{ID: "openai", Chat: "https://api.openai.com/v1"}, false}, + } { + if got := canDecide(tc.p); got != tc.want { + t.Errorf("%s: %v", tc.name, got) + } + } +} + +// Another magpie serves the Decisions API by routing it on: the request +// reaches its /v1/decisions and, through it, OpenAI. +func TestDecisionsThroughAnotherMagpie(t *testing.T) { + openai, _ := decidingProviders(t) + remote := httptest.NewServer(New().Handler()) + t.Cleanup(remote.Close) + if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key", Models: []string{"openai/gpt-6-luna"}}); err != nil { + t.Fatal(err) + } + p, _ := provider.Find("office") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("office/openai/gpt-6-luna")) + if code != 200 || raw != decisionAnswer { + t.Fatalf("%d %s", code, raw) + } + if hits := openai.all(); len(hits) != 1 || hits[0].body["model"] != "gpt-6-luna" { + t.Fatalf("openai asked %+v", hits) + } + recs := decisionRecords(t, 2) + seen := map[string]bool{} + for _, r := range recs { + seen[r.Provider] = true + } + if !seen["office"] || !seen["openai"] { + t.Fatalf("recorded %+v", recs) + } +} + +// A gateway key's rules hold on /v1/decisions as on every route: a key +// held to other models is refused before any vendor is asked, a disabled +// model is refused, and a key's spent limit of the model refuses it. +func TestDecisionsHeldByKeysAndRules(t *testing.T) { + openai, _ := decidingProviders(t) + budget.Forget() + pinLimitClock(t) + keys, secrets := newCaller(t, "Held", "Capped") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay/*"}}); err != nil { + t.Fatal(err) + } + setLimit(t, keys[1].ID, &access.Limit{Period: "day", Tokens: 100, Models: []string{"openai/*"}}) + h := New().Handler() + if w := keyCall(h, secrets[0], "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != http.StatusForbidden { + t.Fatalf("a key held to other models: %d %s", w.Code, w.Body.String()) + } + if w := keyCall(h, "sk-magpie-not-a-key", "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden { + t.Fatalf("a wrong key: %d %s", w.Code, w.Body.String()) + } + if n := len(openai.all()); n != 0 { + t.Fatalf("openai asked %d times", n) + } + if w := keyCall(h, secrets[1], "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != 200 { + t.Fatalf("the capped key's first call: %d %s", w.Code, w.Body.String()) + } + decisionRecords(t, 1) + spentSaid(t, keyCall(h, secrets[1], "/v1/decisions", decisionAsked("openai/gpt-6-luna")), "openai/*") + if n := len(openai.all()); n != 1 { + t.Fatalf("openai asked %d times", n) + } + if err := provider.DisableModels("openai/gpt-6-luna"); err != nil { + t.Fatal(err) + } + if code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("openai/gpt-6-luna")); code != http.StatusForbidden { + t.Fatalf("a disabled model: %d %s", code, raw) + } + if n := len(openai.all()); n != 1 { + t.Fatalf("openai asked %d times", n) + } +} diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 7c9631b79..cd5faaf52 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -63,6 +63,18 @@ type retrieval interface { answerType(got string) string } +// refusingRetrieval is a retrieval request only some providers can be +// sent: refuses is why p can't, "" when it can (decisionRequest). +type refusingRetrieval interface { + refuses(p provider.Provider) string +} + +// countedRetrieval is a retrieval request whose answer's usage is read +// its own way, cached tokens apart (decisionRequest). +type countedRetrieval interface { + counted(b []byte) Usage +} + // jsonRetrieval is an embeddings or rerank body: a JSON object. type jsonRetrieval struct{ req map[string]json.RawMessage } @@ -228,6 +240,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op switch req.(type) { case *audioForm, *speechRequest: what = "audio" + case *decisionRequest: + what = "decisions" } // the record names the try that had it last, not the first // planned (noteMaskedUntil) @@ -240,8 +254,13 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op call.Provider, went = c.p.ID, c.model base := strings.TrimRight(c.p.OpenAIBase(), "/") tried := side.try(c) + msg := "" if base == "" { - msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) + msg = fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path) + } else if rr, ok := req.(refusingRetrieval); ok { + msg = rr.refuses(c.p) // never sent, so never a 404 of the vendor's + } + if msg != "" { tried(400, errors.New(msg)) if !last { skipped = append(skipped, c.label()+": "+msg) @@ -289,6 +308,11 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op } call.Status = code in, outTokens := retrievedTokens(b), answeredTokens(b) + var cached Usage // the cache's share, when the answer tells it + if cr, ok := req.(countedRetrieval); ok && res == nil && err == nil { + cached = cr.counted(b) + in, outTokens = cached.Input, cached.Output + } if res != nil { // passed on as it comes: audio, or SSE, is never held whole heard.into(w.Header()) @@ -303,14 +327,15 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op } } call.Usage.Input, call.Usage.Output = in, outTokens + call.Usage.CacheRead, call.Usage.CacheWrite = cached.CacheRead, cached.CacheWrite call.Fallback = strings.Join(skipped, "; ") providerKeyID, providerKeyName := "", "" if c.p.Account == nil && c.p.Key != "" { providerKeyID, providerKeyName = provider.KeyID(c.p.Key), c.p.KeyName } - side.end(c.p, c.model, code, err, Usage{Input: in, Output: outTokens}) + side.end(c.p, c.model, code, err, Usage{Input: in, Output: outTokens, CacheRead: cached.CacheRead, CacheWrite: cached.CacheWrite}) appendUsage(r, usage.Record{RouteID: side.id(), Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p), - Input: in, Output: outTokens, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)}) + Input: in, Output: outTokens, CacheRead: cached.CacheRead, CacheWrite: cached.CacheWrite, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)}) if err != nil { call.Error = err.Error() s.record(call) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 122233bad..db8dcc00f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1034,6 +1034,9 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("POST /embeddings", s.retrieve("/embeddings", "embeddings")) mux.HandleFunc("POST /v1/rerank", s.retrieve("/rerank", "rerank")) mux.HandleFunc("POST /rerank", s.retrieve("/rerank", "rerank")) + // OpenAI's Decisions API, typed answers to questions on one input + mux.HandleFunc("POST /v1/decisions", s.decide) + mux.HandleFunc("POST /decisions", s.decide) // speech to text, for a client's voice input (#2053) mux.HandleFunc("POST /v1/audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions")) @@ -1070,7 +1073,7 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("GET /v1beta/models", s.geminiModels) mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*") + writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*") }) return mux } @@ -1099,7 +1102,7 @@ var catalogSize stamped[struct{}, int] func (s *Server) info(w http.ResponseWriter, r *http.Request) { out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}} // which process serves, for another magpie on this computer to name it // on its Routing page (#2606); not told to another machine if local(r) { diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index b3d14cad7..5ac65c9cf 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -372,7 +372,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { {"POST", "/v1/messages"}, {"POST", "/messages"}, {"POST", "/v1/messages/count_tokens"}, {"POST", "/v1/systemone"}, {"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"}, - {"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, + {"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, {"POST", "/v1/decisions"}, {"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"}, {"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"}, {"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"}, diff --git a/internal/gateway/media_group.go b/internal/gateway/media_group.go index 8807c2867..53f412d3d 100644 --- a/internal/gateway/media_group.go +++ b/internal/gateway/media_group.go @@ -10,7 +10,7 @@ import ( // mediaMembers is the routing group ref with its members ready now for // an API that is no chat, kind's (catalog.Serves*, provider.KindVideo): -// embeddings, rerank, speech, transcriptions and videos. +// embeddings, rerank, speech, transcriptions, videos and decisions. // // A group the user made: a provider's picks are of its chat models, and // these models are in no chat list (a fetched list keeps them apart, @@ -61,6 +61,9 @@ func bareRef(ref string) bool { // preset names it (PlanRetrieval). func servesKind(kind string) func(p provider.Provider, model string) bool { is := func(m catalog.Model, model string) bool { return m.ID == model } + if kind == kindDecision { + return servesDecision + } if kind == provider.KindVideo { return func(p provider.Provider, model string) bool { return slices.ContainsFunc(Videomakers(p), func(m catalog.Model) bool { return is(m, model) }) @@ -87,6 +90,8 @@ func retrievalKind(operation string) string { return catalog.ServesSpeech case "transcriptions", "translations": return catalog.ServesTranscription + case "decisions": + return kindDecision } return catalog.ServesEmbedding } diff --git a/internal/gateway/oneport.go b/internal/gateway/oneport.go index bc5b481fc..ab87c3353 100644 --- a/internal/gateway/oneport.go +++ b/internal/gateway/oneport.go @@ -26,7 +26,7 @@ func (s *Server) Front() http.Handler { var clientPrefixes = []string{ "/v1", "/v1beta", "/models", "/chat/completions", "/responses", "/messages", - "/images", "/embeddings", "/rerank", "/audio", "/videos", + "/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos", "/muse-code/models", CodexPath, AlphaSearchPath, "/mcp", // the key page (KeyPagePath): a key's holder opens it at the address // they give their agents diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index d6c14809d..08a68859c 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -39,6 +39,7 @@ var readOnlyRefused = []string{ "POST /v1" + AlphaSearchPath, "POST " + AlphaSearchPath, "POST /v1/messages/count_tokens", "POST /v1/images/generations", "POST /images/generations", "POST /v1/images/edits", "POST /images/edits", "POST /v1/embeddings", "POST /embeddings", "POST /v1/rerank", "POST /rerank", + "POST /v1/decisions", "POST /decisions", "POST /v1/audio/transcriptions", "POST /audio/transcriptions", "POST /v1/audio/translations", "POST /audio/translations", "POST /v1/audio/speech", "POST /audio/speech", diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index 19aeaedbe..19c0304e7 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -94,7 +94,7 @@ func (p *Provider) remoteMagpieEndpoints() { for _, suf := range []string{ "/v1/messages/count_tokens", "/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/systemone", - "/v1/embeddings", "/v1/rerank", + "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1", diff --git a/internal/provider/remote_magpie_test.go b/internal/provider/remote_magpie_test.go index 33adf13f7..1609b5850 100644 --- a/internal/provider/remote_magpie_test.go +++ b/internal/provider/remote_magpie_test.go @@ -20,6 +20,7 @@ func TestRemoteMagpie(t *testing.T) { "http://192.168.1.20:3425/v1/systemone", "http://192.168.1.20:3425/v1/embeddings", "http://192.168.1.20:3425/v1/rerank", + "http://192.168.1.20:3425/v1/decisions", "http://192.168.1.20:3425/v1/images/generations", "http://192.168.1.20:3425/v1/images/edits", "http://192.168.1.20:3425/v1/videos",