diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 9f71eedb8..dd4720220 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -65,7 +65,7 @@ another for the conversation instead of listing every id | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one silent for 10s (no HEADERS or DATA from the vendor since the last request) is pinged, and dropped when no answer comes within 10s, so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A silence answered is pinged again only 5 minutes on (`netproxy.CalmHTTP2`, `PingAgain`): Go's own health check pings it every 10s, its ping's answer restarting its clock, and Google's front end, holding clients to gRPC's ping policy (a ping within 5 minutes of the last with nothing sent between is a strike, and the third ends the connection), ended a turn of gemini thinking through Antigravity at ~235s with GOAWAY ENHANCE_YOUR_CALM "too_many_pings" (zdevoz on Discord; `TestLongSilenceIsNotPingedIntoGoaway`, `TestCalmFindsAPathDeadLaterInTheSilence`). The try after a GOAWAY goes on a new connection (`TestTryAfterGoawayDialsAnew`). `http.DefaultTransport`, whose requests are short, keeps Go's (`netproxy.HTTP2Health`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | | 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, and 200 MB for the days that are over: today's plain file, however big, takes none of it, `TestHistoryTodayTakesNoRoomFromPastDays`). 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, each inline picture's base64 swapped for a ref into `keptImages` (in memory, 128 MiB at most, least recently used first; `image_keep.go`), so a conversation of pictures, which DeepSeek's file ids let grow past 64 MiB (#5407), keeps its text and pictures (matrix0487 on Discord; the archive's copy is read the same way, `TestFileIDConversationStillShows`); 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) | +| 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; an inline image is counted from the size its header gives by the rule of the vendor whose protocol the request speaks (Anthropic's 28 px patches in the model's tier, OpenAI's 32 px patches or 512 px tiles at the part's detail; [`prompt_image.go`](../../internal/gateway/prompt_image.go), @paiven_x on X), one whose size can't be read, and a Gemini request's, at 1600; `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, each inline picture's base64 swapped for a ref into `keptImages` (in memory, 128 MiB at most, least recently used first; `image_keep.go`), so a conversation of pictures, which DeepSeek's file ids let grow past 64 MiB (#5407), keeps its text and pictures (matrix0487 on Discord; the archive's copy is read the same way, `TestFileIDConversationStillShows`); 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.` (or AI Studio's `Corrupted thought signature.`, `signatureRefused`) is asked again with every call sent so (`withoutSignatures`), for that request only, at any upstream Gemini's signatures reach (`signaturesReach`), relayed too; it rests no account and lets a group go on (`restAfterMarked`, `shapeRefused`). 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; that retry is 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) | | Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) | diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index 56b66b1e9..a16d7c958 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -131,6 +131,17 @@ type promptBuilder struct { // so its bytes count once sent sentSizes again bool + // from and model: the protocol the request speaks and the model it + // names, whose vendor's rule an inline image is counted by + // (imageTokensOf) + from provider.Protocol + model string +} + +// image is what an inline image of src takes, at detail when the request +// named one. +func (b *promptBuilder) image(detail string, src []byte) int { + return imageTokensOf(b.from, b.model, detail, src) } // PromptPiece is a stretch of an item's text as the request sent it: a @@ -790,10 +801,12 @@ func (b *promptBuilder) anthropic(body []byte) bool { Content json.RawMessage `json:"content"` } `json:"messages"` Tools []json.RawMessage `json:"tools"` + Model string `json:"model"` } if decodeJSONView(body, &req) != nil { return false } + b.from, b.model = provider.Anthropic, req.Model for _, s := range blocksOf(req.System) { if strings.HasPrefix(s.Text, "x-anthropic-billing-header") { b.add(PartSystem, "billing", "", tokensOf(s.Text), txt("system", s.Text)) @@ -929,7 +942,7 @@ func (b *promptBuilder) anthropicBlock(role string, x rawBlock) { for _, c := range blocksOf(x.Content) { switch c.Type { case "image", "document": - b.add(PartFiles, c.Type, "image", imageTokens, imgPiece(c.Source)) + b.add(PartFiles, c.Type, "image", b.sourceTokens(c.Type, c.Source), imgPiece(c.Source)) default: n += tokensOf(c.Text) texts = append(texts, c.Text) @@ -946,7 +959,7 @@ func (b *promptBuilder) anthropicBlock(role string, x rawBlock) { b.add(PartFiles, "document", "image", rawTokens(x.Source), rawPiece("", "", x.Source)) return } - b.add(PartFiles, x.Type, "image", imageTokens, imgPiece(x.Source)) + b.add(PartFiles, x.Type, "image", b.sourceTokens(x.Type, x.Source), imgPiece(x.Source)) default: b.chat(tokensOf(x.Text), txt(role, x.Text)) } @@ -960,10 +973,12 @@ func (b *promptBuilder) responses(body []byte) bool { Input json.RawMessage `json:"input"` Tools []json.RawMessage `json:"tools"` Previous string `json:"previous_response_id"` + Model string `json:"model"` } if decodeJSONView(body, &req) != nil { return false } + b.from, b.model = provider.Responses, req.Model b.held = req.Previous != "" var ins string if decodeJSONView(req.Instructions, &ins) == nil && ins != "" { @@ -1067,7 +1082,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) { } for _, p := range parts { if p.image { - b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src)) + b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src)) continue } b.userText(p.text) @@ -1111,7 +1126,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) { var texts []string for _, p := range responsesContent(it.Output) { if p.image { - b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src)) + b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src)) continue } n += tokensOf(p.text) @@ -1133,9 +1148,29 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) { } type rPart struct { - text string - image bool - src json.RawMessage // an image's image_url + text string + image bool + src json.RawMessage // an image's image_url + detail string // a Responses image's detail, beside its image_url + file bool // an input_file: a document, not a picture +} + +// partImage is what a Responses or Chat image part takes; a file at the +// estimate for a picture. +func (b *promptBuilder) partImage(p rPart) int { + if p.file { + return imageTokens + } + return b.image(p.detail, p.src) +} + +// sourceTokens is what an Anthropic image or document block takes: a +// document at the estimate for a picture. +func (b *promptBuilder) sourceTokens(typ string, src []byte) int { + if typ != "image" { + return imageTokens + } + return b.image("", src) } func responsesContent(c json.RawMessage) []rPart { @@ -1147,11 +1182,13 @@ func responsesContent(c json.RawMessage) []rPart { Type string `json:"type"` Text string `json:"text"` ImageURL json.RawMessage `json:"image_url"` + Detail string `json:"detail"` } _ = decodeJSONView(c, &ps) out := make([]rPart, 0, len(ps)) for _, p := range ps { - out = append(out, rPart{text: p.Text, image: p.Type == "input_image" || p.Type == "input_file" || p.Type == "image_url", src: p.ImageURL}) + out = append(out, rPart{text: p.Text, image: p.Type == "input_image" || p.Type == "input_file" || p.Type == "image_url", src: p.ImageURL, + detail: p.Detail, file: p.Type == "input_file"}) } return out } @@ -1174,10 +1211,12 @@ func (b *promptBuilder) chatCompletions(body []byte) bool { } `json:"tool_calls"` } `json:"messages"` Tools []json.RawMessage `json:"tools"` + Model string `json:"model"` } if decodeJSONView(body, &req) != nil { return false } + b.from, b.model = provider.Chat, req.Model for _, t := range req.Tools { b.responsesTool(t) } @@ -1194,7 +1233,7 @@ func (b *promptBuilder) chatCompletions(body []byte) bool { } for _, p := range parts { if p.image { - b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src)) + b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src)) continue } b.userText(p.text) @@ -1204,7 +1243,7 @@ func (b *promptBuilder) chatCompletions(body []byte) bool { var texts []string for _, p := range parts { if p.image { - b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.src)) + b.add(PartFiles, "image", "image", b.partImage(p), imgPiece(p.src)) continue } n += tokensOf(p.text) @@ -1302,7 +1341,7 @@ func (b *promptBuilder) gemini(body []byte) bool { } b.result(id, rawTokens(p.FunctionResponse.Response), rawPiece("result", "", p.FunctionResponse.Response)) case len(p.InlineData) > 0 || len(p.FileData) > 0: - b.add(PartFiles, "image", "image", imageTokens, imgPiece(p.InlineData)) + b.add(PartFiles, "image", "image", b.image("", p.InlineData), imgPiece(p.InlineData)) case c.Role == "model": role := "assistant" if p.Thought { diff --git a/internal/gateway/prompt_image.go b/internal/gateway/prompt_image.go new file mode 100644 index 000000000..c1384bfff --- /dev/null +++ b/internal/gateway/prompt_image.go @@ -0,0 +1,328 @@ +package gateway + +// What an image a request sends inline takes of the model's context, by +// the rule of the vendor whose protocol the request speaks, from the +// image's own size. The size is read from the image's header alone, the +// base64 decoded as a stream as far as the format needs (a few KB of a +// PNG, a JPEG up to its frame header), never the picture, so a request +// carrying hundreds of screenshots costs a few KB read for each. +// +// Every image used to be taken at 1600 tokens (imageTokens). A Codex +// session of a few hundred small screenshots then showed 413K of images in +// a 764K prompt that OpenAI counted at about 371K (@paiven_x on X): small +// pictures cost OpenAI a few hundred tokens each. An image whose size +// can't be read (a link, a file id, a document) is still taken at +// imageTokens, and the vendor's count, once it answers, scales them all +// (calibrate). + +import ( + "bytes" + "encoding/base64" + "image" + _ "image/gif" // DecodeConfig of a GIF + _ "image/jpeg" // of a JPEG + _ "image/png" // of a PNG + "io" + "math" + "strconv" + "strings" + + _ "golang.org/x/image/webp" // of a WebP + + "github.com/yetone/magpie/internal/provider" +) + +// imageTokensOf is what an inline image takes of the context: src as the +// request sent it (an Anthropic source, a Responses image_url, a Chat +// image_url object, Gemini's inlineData), at detail when the request +// named one, to model, by the rule of the vendor of protocol from. +// imageTokens when its size can't be read. +func imageTokensOf(from provider.Protocol, model, detail string, src []byte) int { + w, h, ok := inlineImageSize(src) + if !ok { + return imageTokens + } + if detail == "" { + detail = jsonField(src, "detail") + } + switch from { + case provider.Anthropic: + return claudeImageTokens(w, h, model) + case provider.Responses, provider.Chat: + return openAIImageTokens(w, h, detail, model) + } + return imageTokens +} + +// inlineImageSize is an inline image's width and height, read from its header. +func inlineImageSize(src []byte) (w, h int, ok bool) { + b64 := imageBase64(src) + if len(b64) == 0 { + return 0, 0, false + } + var r io.Reader = bytes.NewReader(b64) + if bytes.IndexByte(b64, '\\') >= 0 { + r = unescaped{r} // a JSON encoder's \/ + } + if ref, isRef := bytes.CutPrefix(b64, []byte(imageRef)); isRef { + // a picture a lean body kept apart (leanImages) + data, found := keptImageOf(string(ref)) + if !found { + return 0, 0, false + } + r = strings.NewReader(data) + } + cfg, _, err := image.DecodeConfig(base64.NewDecoder(base64.StdEncoding, r)) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 { + return 0, 0, false + } + return cfg.Width, cfg.Height, true +} + +// imageBase64 is the base64 of an inline image's source, where it sits in +// the source's JSON, not copied: after a data: URL's comma, else Anthropic's +// and Gemini's "data" string. nil for a link or a file. +func imageBase64(src []byte) []byte { + var s []byte + if i := bytes.Index(src, []byte(";base64,")); i >= 0 { + s = src[i+len(";base64,"):] + } else if i := bytes.Index(src, []byte(`"data"`)); i >= 0 { + s = bytes.TrimLeft(src[i+len(`"data"`):], " \t\r\n:") + if len(s) == 0 || s[0] != '"' { + return nil + } + s = s[1:] + } else { + return nil + } + if end := bytes.IndexByte(s, '"'); end >= 0 { + s = s[:end] + } + return s +} + +// unescaped reads a JSON string's bytes without its backslashes, which +// base64 has none of. +type unescaped struct{ r io.Reader } + +func (u unescaped) Read(p []byte) (int, error) { + n, err := u.r.Read(p) + k := 0 + for _, c := range p[:n] { + if c != '\\' { + p[k] = c + k++ + } + } + return k, err +} + +// jsonField is a short string field of a small JSON object, "" when it +// has none: a Chat image_url's detail, read past its url. +func jsonField(obj []byte, key string) string { + if len(obj) == 0 || obj[0] != '{' { + return "" + } + q := []byte(`"` + key + `"`) + i := bytes.LastIndex(obj, q) + if i < 0 { + return "" + } + s := bytes.TrimLeft(obj[i+len(q):], " \t\r\n:") + if len(s) < 2 || s[0] != '"' { + return "" + } + end := bytes.IndexByte(s[1:], '"') + if end < 0 || end > 16 { + return "" + } + return string(s[1 : 1+end]) +} + +// modelSlug is a model id as its vendor names it: lower case, without +// magpie's provider prefix. +func modelSlug(model string) string { + m := strings.ToLower(model) + if i := strings.LastIndexByte(m, '/'); i >= 0 { + m = m[i+1:] + } + return m +} + +// --- Anthropic --- + +// claudeImageTokens is Anthropic's count of a w×h image: a token for each +// 28 px patch, ⌈w/28⌉×⌈h/28⌉, once the image is scaled to the largest +// size that fits the model's tier (platform.claude.com, Vision and +// "How Claude resizes and pads images"): Claude 4.7 and later 2576 px +// a side and 4784 tokens, the models before 1568 and 1568. +func claudeImageTokens(w, h int, model string) int { + edge, most := 2576, 4784 + if claudeStandardTier(model) { + edge, most = 1568, 1568 + } + w, h = claudeResized(w, h, edge, most) + return claudePatches(w, h) +} + +func claudePatches(w, h int) int { return ((w + 27) / 28) * ((h + 27) / 28) } + +// claudeResized is Anthropic's reference resizedSize: the largest +// aspect-kept size whose padded sides fit edge and whose patches fit most. +func claudeResized(w, h, edge, most int) (int, int) { + fits := func(w, h int) bool { + return (w+27)/28*28 <= edge && (h+27)/28*28 <= edge && claudePatches(w, h) <= most + } + if fits(w, h) { + return w, h + } + if h > w { + rh, rw := claudeResized(h, w, edge, most) + return rw, rh + } + ratio := float64(w) / float64(h) + short := func(long int) int { return max(int(math.RoundToEven(float64(long)/ratio)), 1) } + lo, hi := 1, w + for lo+1 < hi { + mid := (lo + hi) / 2 + if fits(mid, short(mid)) { + lo = mid + } else { + hi = mid + } + } + return lo, short(lo) +} + +// claudeStandardTier: a Claude model before 4.7 (Opus 4.6, Sonnet 4.5, +// Haiku 4.5, the 3s). Any other, a model magpie doesn't know among them, +// is taken at the high-resolution tier of the models Claude Code runs now. +func claudeStandardTier(model string) bool { + m := modelSlug(model) + if !strings.HasPrefix(m, "claude-") { + return false + } + // claude-opus-4-6, claude-sonnet-4-5-20250929, claude-3-5-sonnet-… + var nums []int + for _, f := range strings.FieldsFunc(m, func(r rune) bool { return r == '-' || r == '.' || r == '[' }) { + if n, err := strconv.Atoi(f); err == nil && len(f) <= 2 { + nums = append(nums, n) + } + } + if len(nums) == 0 { + return false + } + major, minor := nums[0], 0 + if len(nums) > 1 { + minor = nums[1] + } + return major < 4 || major == 4 && minor < 7 +} + +// --- OpenAI --- + +// openAIImageTokens is OpenAI's count of a w×h image at detail on model +// (developers.openai.com, Images and vision: "Calculating costs"). The +// models before GPT-5.2 count 512 px tiles; the rest 32 px patches, times +// the model's multiplier, in limits each detail sets. +func openAIImageTokens(w, h int, detail, model string) int { + m := modelSlug(model) + if base, tile, ok := openAITiles(m); ok { + if detail == "low" { + return base + } + // fit 2048×2048, then the shortest side to 768, as tiles of 512 + fw, fh := fitSide(w, h, 2048) + if s := min(fw, fh); s > 768 { + r := 768 / float64(s) + fw, fh = int(float64(fw)*r), int(float64(fh)*r) + if fw < fh { + fw = 768 + } else { + fh = 768 + } + } + return base + tile*((fw+511)/512)*((fh+511)/512) + } + side, budget := openAIPatchLimits(m, detail) + pw, ph := fitSide(w, h, side) + if budget > 0 && openAIPatches(pw, ph) > budget { + fw, fh := float64(pw), float64(ph) + s := math.Sqrt(32 * 32 * float64(budget) / (fw * fh)) + s *= min(math.Floor(fw*s/32)/(fw*s/32), math.Floor(fh*s/32)/(fh*s/32)) + pw, ph = max(int(fw*s), 1), max(int(fh*s), 1) + } + return int(math.Ceil(float64(openAIPatches(pw, ph)) * openAIMultiplier(m))) +} + +func openAIPatches(w, h int) int { return ((w + 31) / 32) * ((h + 31) / 32) } + +// fitSide scales w×h to fit side×side, never up. +func fitSide(w, h, side int) (int, int) { + if side <= 0 || w <= side && h <= side { + return w, h + } + r := float64(side) / float64(max(w, h)) + return max(int(math.Round(float64(w)*r)), 1), max(int(math.Round(float64(h)*r)), 1) +} + +// openAITiles: the base and per-tile tokens of a model that counts tiles. +func openAITiles(m string) (base, tile int, ok bool) { + switch { + case strings.HasPrefix(m, "gpt-4o-mini"): + return 2833, 5667, true + case strings.HasPrefix(m, "gpt-4o"), m == "gpt-4.1" || strings.HasPrefix(m, "gpt-4.1-20"): + return 85, 170, true + case m == "o1" || strings.HasPrefix(m, "o1-"), m == "o3" || strings.HasPrefix(m, "o3-pro") || strings.HasPrefix(m, "o3-20"): + return 75, 150, true + case strings.HasPrefix(m, "gpt-5.1"), + strings.HasPrefix(m, "gpt-5") && !strings.HasPrefix(m, "gpt-5.") && !strings.HasPrefix(m, "gpt-5-mini") && !strings.HasPrefix(m, "gpt-5-nano"): + return 70, 140, true + } + return 0, 0, false +} + +// openAIMultiplier is a patch model's multiplier: 1.2 for GPT-5.2 and +// after, and for a model OpenAI doesn't list. +func openAIMultiplier(m string) float64 { + switch { + case strings.HasPrefix(m, "gpt-5-nano"): + return 1.5 + case strings.HasPrefix(m, "gpt-4.1-mini"): + return 1.62 + case strings.HasPrefix(m, "gpt-4.1-nano"): + return 2.46 + case strings.HasPrefix(m, "o4-mini"): + return 1.72 + } + return 1.2 +} + +// openAIPatchLimits is the longest side and the patch budget (0: none) a +// patch model holds an image to at detail; auto is the model's default. +func openAIPatchLimits(m, detail string) (side, budget int) { + switch { + case strings.HasPrefix(m, "gpt-5.2"), strings.HasPrefix(m, "gpt-4.1-"), strings.HasPrefix(m, "gpt-5-mini"), + strings.HasPrefix(m, "gpt-5-nano"), strings.HasPrefix(m, "o4-mini"): + return 2048, 6144 // every detail alike + case strings.HasPrefix(m, "gpt-5.4"), strings.HasPrefix(m, "gpt-5.3"): + switch detail { + case "low": + return 2048, 6144 + case "original": + return 6000, 10000 + } + return 2048, 2500 // high, auto + } + // GPT-5.5 and after, and models OpenAI doesn't list: auto is original + switch detail { + case "low": + return 512, 0 + case "high": + return 2048, 2500 + } + if strings.HasPrefix(m, "gpt-5.5") { + return 6000, 10000 + } + return 65535, 0 +} diff --git a/internal/gateway/prompt_image_test.go b/internal/gateway/prompt_image_test.go new file mode 100644 index 000000000..cd76479cb --- /dev/null +++ b/internal/gateway/prompt_image_test.go @@ -0,0 +1,119 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "image" + "image/color" + "image/jpeg" + "image/png" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// pngB64 is a real PNG of w×h, as base64. +func pngB64(t *testing.T, w, h int) string { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for x := 0; x < w; x += 7 { + img.Set(x, x%h, color.RGBA{R: byte(x), G: 90, B: 200, A: 255}) + } + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +// jpegB64 is a real JPEG of w×h with a 40 KB APP1 segment (EXIF's place) +// before its frame header, as a camera's or a phone's has. +func jpegB64(t *testing.T, w, h int) string { + t.Helper() + var buf bytes.Buffer + if err := jpeg.Encode(&buf, image.NewGray(image.Rect(0, 0, w, h)), nil); err != nil { + t.Fatal(err) + } + raw := buf.Bytes() + app := make([]byte, 40000) + seg := append([]byte{0xFF, 0xE1, byte((len(app) + 2) >> 8), byte(len(app) + 2)}, app...) + out := append(append(append([]byte{}, raw[:2]...), seg...), raw[2:]...) + return base64.StdEncoding.EncodeToString(out) +} + +// An inline image is counted by the vendor's rule from its own size, not +// at 1600 whatever it is: a Codex session of a few hundred small +// screenshots showed 413K of images in a prompt OpenAI counted at about +// 371K in all (@paiven_x on X). The numbers are the vendors' own docs'. +func TestPromptImageTokensByVendor(t *testing.T) { + small, shot, hd := pngB64(t, 800, 500), pngB64(t, 2880, 1800), pngB64(t, 1920, 1080) + resp := func(model, detail, b64 string) string { + d := "" + if detail != "" { + d = `,"detail":"` + detail + `"` + } + return `{"model":"` + model + `","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"look"},{"type":"input_image","image_url":"data:image/png;base64,` + b64 + `"` + d + `}]}]}` + } + chat := func(model, detail, b64 string) string { + return `{"model":"` + model + `","messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,` + b64 + `","detail":"` + detail + `"}}]}]}` + } + anth := func(model, b64 string) string { + return `{"model":"` + model + `","messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + b64 + `"}}]}]}` + } + cases := []struct { + name string + from provider.Protocol + body string + want int + }{ + // 32 px patches, 25×16, times 1.2; auto is original on GPT-6 + {"codex small screenshot", provider.Responses, resp("codex/gpt-6.1-terra", "", small), 480}, + // high: 2048 a side, then the 2500-patch budget: 1996×1248, 63×39 patches + {"retina at high", provider.Responses, resp("gpt-6.1-terra", "high", shot), 2949}, + // low on GPT-5.5 and after: fits 512×512, 16×10 patches + {"low", provider.Responses, resp("gpt-5.5", "low", small), 192}, + // tiles: 1024² is 768² at high, 4 tiles of 170 and 85 (OpenAI's example) + {"gpt-4o tiles", provider.Chat, chat("gpt-4o", "high", pngB64(t, 1024, 1024)), 765}, + {"gpt-4o low", provider.Chat, chat("gpt-4o", "low", shot), 85}, + // Anthropic's table: 1920×1080 is 2691 on the high-resolution tier, + // 1456×819 and 1560 on the standard + {"claude high tier", provider.Anthropic, anth("claude-opus-5-5", hd), 2691}, + {"claude standard tier", provider.Anthropic, anth("anthropic/claude-sonnet-4-5-20250929", hd), 1560}, + // 3840×2160: 2576×1449, 4784 + {"claude 4k", provider.Anthropic, anth("claude-opus-4-7", pngB64(t, 3840, 2160)), 4784}, + // a JPEG's frame header behind 40 KB of EXIF is still read: 600×400 + // on the standard tier is 22×15 + {"jpeg behind exif", provider.Anthropic, strings.Replace(anth("claude-haiku-4-5", jpegB64(t, 600, 400)), "image/png", "image/jpeg", 1), 330}, + // a JSON encoder's \/ in the base64 + {"escaped slashes", provider.Responses, strings.ReplaceAll(resp("gpt-6.1-terra", "", small), "/", `\/`), 480}, + } + for _, c := range cases { + p := promptOf(c.from, []byte(c.body)) + if p == nil { + t.Fatalf("%s: no prompt", c.name) + } + it, ok := itemOf(p, PartFiles, "image") + if !ok || it.Tokens != c.want { + t.Errorf("%s: image %+v, want %d tokens", c.name, it, c.want) + } + } +} + +// Only the image's header is read: its size comes out of the base64 of a +// PNG's first few KB, the rest of it never decoded, so hundreds of +// screenshots in one Codex request cost a few KB read each. +func TestPromptImageSizeReadsHeaderOnly(t *testing.T) { + b64 := pngB64(t, 2880, 1800) + src := []byte(`"data:image/png;base64,` + b64[:4096] + `"`) + w, h, ok := inlineImageSize(src) + if !ok || w != 2880 || h != 1800 { + t.Fatalf("size %d×%d %v", w, h, ok) + } + // a link, a file, bytes that aren't an image: the estimate for a picture + for _, s := range []string{`"https://example.com/a.png"`, `{"type":"url","url":"https://x/a.png"}`, `"data:image/png;base64,AAAA"`} { + if n := imageTokensOf(provider.Responses, "gpt-6.1-terra", "", []byte(s)); n != imageTokens { + t.Fatalf("%s: %d", s, n) + } + } +}