ac4af582301a4e8a29245dbba767eba31334ddf9
12
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7a6211d047 |
providers: a model's own headers, in Model settings
axelburks on Discord: a vendor routes one model by a header of its own. A key's provider (built-in or custom) can give each model headers (settings.ModelHeaders["pid/model"]). They go on that provider's requests for that model alone, after the provider's headers and after auth: a name both have is sent once, as the model's, so a user's value is never overridden by the provider's or magpie's key header. The gateway names the model (provider.WithModel) on every route that asks one: chat on each API, translated and streamed, count_tokens, System One's decision, embeddings, images, videos and the model test. A fallback provider serving the same model id gets its own headers only. Accounts and plugins carry their sign-in's headers and take none. The editor's "Name, price and reasoning level" panel is now "Model settings" (every language), with + Add header per model, staged and made with the Save; Restore default takes them away. The rows being typed are kept out of the draft's compare, so an untouched editor still closes without asking. Broken by hand: dropping WithModel from gateway.go turns TestModelHeadersReachTheirModelOnEveryRoute red; dropping the provider id check in modelOf turns TestModelHeadersStayWithTheirProvider red. Run, on this stack over origin/main |
||
|
|
d10f377657 |
providers: Names & levels is Names, prices & levels, where a model's own price at one provider is set (ferock4669)
ferock4669 asked on Discord whether magpie has a screen to price each model, since one model can cost differently on each provider. It has: each row in a provider's per-model list has a price box (input, output, cache read, cache write, 1h cache write, long-context tier, $ / 1M tokens), saved in settings' ModelPrices under pid/model. It wins over the list price in Usage (usage.Pricer through provider.BasePriceIn) and in a key's spend cap (usage.KeySpent through NewCoster). Nothing has to be built; the button opening it said only "Names & levels", so nobody finds a price there. What changed: - The button, its panel's heading and fold, and every note that sends the user there say "Names, prices & levels" (zh 名称、价格与推理档位, zh-TW 名稱、價格與推理檔位, ja 名前・価格・推論レベル, de "Namen, Preise & Stufen"); the gateway's vision and compaction notes, the provider package's text, the subsystem pages and the site's start docs (en, zh, ja) follow. - The button's tooltip says it sets what each model costs at this provider; Usage's "estimated" tooltip says where a provider's own price is set and that it counts over the list price. Both in en, zh, zh-TW, ja and de. - Not changed: the Codex model description text in internal/codexcat (it goes to Codex, so a vendor sees it) and core_budget_test's history comment. - app.js: a comment above the price box is shortened so the core script stays under its budget, not raised (app.js 116 bytes under origin/main). Run at the pushed head (rebased on origin/main |
||
|
|
fcbf618ebb |
gateway: a request's turns are looked through for images in place, before any copy (#3725)
walkImages decoded the whole request's top level (a copy of the body) before it knew whether any turn held an image, and anyImageBlock read every block whole, so a long agent conversation of text tool_results was decoded block by block on every request. Now anyImageTurn walks the turns array in place with eachMember/eachElement and decodes only when an image is there. A tool_result's content (Anthropic) and a functionResponse's parts (Gemini) are looked inside, so an image a tool returned is still found. Measured: - hasImage on a 60-turn, 76KB body of text tool_results: 6863 allocations before, at most 4 now (TestImageWalkReadsToolResultsInPlace, red on the old code with "took 6863 allocations"). - BenchmarkZZIO (12x20 catalog, ~31KB body, a local benchmark not committed): 620KB/1944 allocs per request before, 520KB/1544 after. The test's table covers content before type, content given twice, a tool_result inside a tool_result, an escaped "type" key, a text block with content, string content, Gemini parts after name, nested fileData and text-only parts. The existing image tests pass unchanged. Run at this tree (base |
||
|
|
43001be863 |
gateway: a relayed Chat body's unpaired tool calls are paired before Kimi sees them
Paidaixinbao on X: Qoder through magpie on Kimi Code, a conversation forked at an earlier turn fails on every prompt while a new one works. A Chat client's body to a Chat upstream was relayed as-is, and only translated requests had their tool exchanges mended (pairToolMessages). A forked or stopped history can hold a call with no tool answer, calls split over two assistant messages, a user turn between a call and its answer, or an answer to no call. Kimi turns the whole request away with 400 "an assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'..." or "tool_call_id is not found". toolPairsOut now pairs such a body on the Chat relay (joining split calls, answering the unanswered, turning an orphan answer into user text); a paired body goes out byte for byte. Run: - Real Kimi Code API (kimi.com/coding/v1, 2026-10-26; the account's plan has lapsed, so a body past validation answers 403 and a refused one 400): unanswered call, split calls, user between call and answer, one of two answered and an orphan answer are each 400; every one of them after toolPairsOut is 403, past validation. A tool turn without reasoning_content, null content, repeated ids, out-of-order and double answers, prefill and a reasoning field all pass as-is, so they are not the cause and are left alone. - gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and GOOS=windows. - go test -timeout 45m ./internal/gateway: ok, at this commit. - Two fixtures held an unpaired body only by accident and are paired now: image_input's chat-tool case (a lone tool message) and the large-chat upstream golden (its last call left unanswered); the new large-chat hash is the same on the old code. Broken by hand: without the toolPairsOut call all six subtests of TestChatRelayPairsToolsForKimi go red against a fake Kimi with Kimi's own wording; without joinSplitChatCalls the split case goes red; reading only string content in toolAsUser turns the parts case red. Not tried: the real Qoder app and the reporter's own forked history, so which shape their fork holds is not proven; Qoder's "unsupported request" text is not magpie's wording. A real Kimi model answer (the plan has lapsed, only validation was seen). A non-Kimi Chat upstream, though the rule is OpenAI's too and runs for every Chat relay. |
||
|
|
68133754a3 |
gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.
Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.
Fix:
- readRequestBody holds the body (holdBody) until the request's context
ends. A RawMessage decodeJSON fills from inside a held body shares the
body's bytes, capped so an append can't write into it. The body must
be at most 16x the value (heldShareMost), so a small value kept past
its request (a cache entry, a signature) never pins a whole body.
Anything not held is still copied: a stream's buffer, a scanner line,
a body built and changed in place. The list is bounded at 64 bodies
(heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
the two readers that run on every request take them in place:
- conversationID takes the turns with elementsOf, slices of the
body.
- walkImages, which runs several times a request, first scans the
turns without decoding (anyImageBlock/anyImageIn) and returns at
once when there is no image. Keys and kinds are compared with
jsonStringIs, so an escaped "type", a duplicate key, a tool
result, a Responses function_call_output and Gemini's inlineData,
fileData and functionResponse still count.
Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:
peak RSS HeapSys GCs allocated bytes.Clone
before 273 MB 222 MB 117 6416 MB 3635 MB
held bodies 233 MB 186 MB 74 3379 MB 1480 MB
+ id/image scan 223 MB 174 MB 64 2853 MB 927 MB
That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.
Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
conversation allocates under len/8 per walk plus id, and eight image
shapes are still found.
Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)
No subsystem page covers decodeJSON.
Run record, the three commits on origin/main
|
||
|
|
81a24cf8fe |
groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.
What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
public one). Every old form is still accepted as input forever:
provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
gateway (validateModel), keys, stats, affinity and usage, so both ids
route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
(allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
exists, found groups are listed by their old id (AutoRefsOn) and
auto/<x> means that provider's model. Documented in
docs/subsystems/gateway-routing.md.
Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).
Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.
Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
gateway, whose failures were the tests' expected ids (updated here)
and two regressions now fixed (bare ids; desktop models hiding groups
by prefix). Every failing test passes on rerun. Load average was
~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
10.19s), and it fails the same in a git-archive export of
|
||
|
|
6f950653fc |
gateway, codex: a model turned away for an image says why magpie takes it for text-only and where Accepts images is (KimYx0207 on X)
mark_li21 pasted an image in Codex through magpie and was told the model
doesn't take images, with no hint of why or where that is changed;
KimYx0207 asked that the refusal say the model's list has no image input
and point to Providers → Names & levels, so nobody switches models or
reinstalls Codex first.
Codex turns the image away itself ("… does not support image inputs.
Remove images or switch models."), and magpie can't word that. What it
can:
- Codex's /model: a model magpie hands Codex without "image" now reads
"<name> (text only: Accepts images is in its provider's Names & levels
in magpie) via magpie". It still ends " via magpie", which is how
catalog.MagpieAdded tells magpie's entries from Codex's own. A model
that sees and a routing group read as before.
- The gateway's own 400 (every other agent): after "does not support
image input" it says why — Accepts images turned off by the user for
it, or the provider's model list marking it as not taking images, or no
model in the group marked as taking images — and names
Providers → <provider> → Names & levels, before the note on image
recognition it already gave.
Tests: TestCodexCatalogSaysTextOnly; TestTextOnlyRefusalSaysWhyAndWhere
(the user's own answer, a group); TestKnownTextOnlyModelRejectsImagesBeforeUpstream
now checks the why and the where on all four APIs. With codexcat.go and
gateway.go put back, all three are red.
Real use: a catalog from codexcat.Catalog handed to Codex 0.162.1 under a
sandbox CODEX_HOME (model_catalog_json, a dead provider URL); /model
lists "Text Model (text only: Accepts images is in its provider's Names
& levels in magpie) via magpie" and "Sees Model via magpie". Pasting an
image there wasn't tried.
Run at origin/main
|
||
|
|
b415c0a570 | group: a routing group takes images when one of its members sees them, and an image goes to the members that do (#756, HuHong-Tao on v0.1.813: group/auto-deepseek-v4-1-flash turned 1198 image requests away with 400 "model does not support image input" in a day, where commandcode's deepseek-v4.1-flash of the group took them) — groupEntries said a group took images only when every member did (Images ANDed, ImageInput through sharedImageInput, where one explicit text-only answer wins), and the gateway's membersImageInput said the same of a request, so one text-only member turned away every image before any member was tried, and /v1/models gave the group input ["text"]. Since a rule for images can send one past a text-only member, the gateway already dropped text-only members for a request with a new image; it now does so for every group without a model to describe images: a new image goes to the members that see it (an explicit answer, or models.dev's estimate as blindTo reads it for a model of its own), to members magpie knows nothing of when none is known to see, and is turned away (400) only when every member is text-only. With a describer the members keep their order, a text-only one given the image described, as before. groupEntries ORs Images and takes ImageInput through anyImageInput (true when a member's is, false when all are, else unknown); membersImageInput drops the rule's members (the rule's member first changes nothing: one that can't see is passed over). With the owner's real accounts (a copy of the config, Vision off): an image to group/auto-deepseek-v4-1-flash was 400 on origin/main and is answered by the Devin account's deepseek-v4-1-flash ("White"); group/auto-kimi-k3, whose only member that sees is an OpenCode Go key without a subscription, went from 400 to that member's 403. TestGroupImages (a group with one member that sees takes images, all text-only doesn't), TestGroupImagesFromAMemberThatSees, TestKnownTextOnlyModelRejectsImagesBeforeUpstream (an ordered group with its text-only member first sends the image to the one that sees), TestRuleImages and TestRuleImagesUnlistedMember now expect the image answered by the member that sees; they fail on the old code. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. | ||
|
|
2e1fcb8a77 |
gateway: a Chat upstream gets a mended tool exchange — strict ones (Kimi) answered a broken one 400 "tool_call_id is not found" (#554)
Relaying Claude Code (or Codex via Responses) to a Chat Completions upstream that checks the tool exchange strictly — Kimi answers 400 "tool_call_id is not found" — got stuck once a history tripped it, since every retry resent it. buildChat now puts a turn's tool results ahead of its own text and images, and pairToolMessages mends the built messages for every Chat upstream (Zed's xAI path included; Chat→Chat passthrough never reaches it): an assistant's tool messages go in its calls' order; a second answer to a call is dropped, the first standing; a result answering no pending call (already answered and closed, compacted away, never sent, or an empty id) becomes user text — joined to the user message just before it — as orphanedToolOutputs does on the Responses path, so no call is made up and no id is used twice; an unanswered call gets a synthetic "unavailable: the turn was interrupted" result; an assistant message with nothing in it is dropped only inside a pending exchange, and passes through outside one. A well-formed exchange is built byte-identical to before. chat_tool_pairing_test.go (order, gathering across user messages, orphan, late result, duplicate, empty id, unanswered call, thinking-only inside and outside an exchange, a session-shaped fixture, a clean exchange; checked for Kimi's adjacency and for ids used once) is new — 9 of its 11 tests fail without the change; TestTextOnlyModelOmitsToolImages' responses-to-chat case now expects the orphaned output as user text without its id. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME and go test -race ./internal/gateway pass. (#554) |
||
|
|
d00d9ffe6f | gateway: a model that can't see images is given what a model that can says of them (让Magpie支持配置图像识别模型) — until now an image sent to a model the catalog knows takes text only was turned away in the latest turn and left out of older turns and tool results, so an agent on DeepSeek, GLM or any text-only model couldn't be shown a screenshot at all. Now each image in such a request is described once by the vision model and the description goes in its place, in every protocol (Chat, Responses, Anthropic, Gemini), current turn, older turns and tool results alike: "[Image, as <model> describes it for this model, which can't see images:] … [End of the image's description]". The describer is asked through the gateway itself (User-Agent magpie-vision/1, recorded as agent magpie), with a system prompt to transcribe text, code, errors and UI state exactly and not to answer or guess; images are described four at a time, and a description is kept (256, by model+image) since an agent sends a conversation's images again every turn, a failure not kept. An image of the latest turn that can't be described is a 502 saying why; one in an older turn is left out as before. Settings → Images → Image recognition picks the model: Automatic (a small model that sees — a Claude account's, a Codex account's, the cheapest of an API key's, another account's), Off (images turned away as before), or any model or group that sees; an id that doesn't resolve is refused. In a routing group the description is made only when a text-only member is actually tried, so a rule that routes images to a member that sees costs nothing; a member whose image can't be described is skipped for the next, the last one answers 502. The describer's own request is never described again, so a Vision set to a text-only model is turned away, not looped. Checked in a sandbox HOME against a local vendor: an image sent over Chat and over Anthropic to a text-only model reached it as the description, the describer was asked once per image, and the Settings row and its picker in light and dark. | ||
|
|
e136cf9a27 |
gateway: Gemini PDF and audio files kept on text-only routes (#95)
* gateway: keep Gemini document and audio file data on text-only routes * fix(gateway): avoid translating Gemini files as images * fix(gateway): preserve Gemini files for Code Assist while translating safely * fix(gateway): retain Gemini file placeholder for Claude subscriptions --------- Co-authored-by: Instinct Agent <agent@instinct.com> Co-authored-by: Charan Rathore <charan-rathore@users.noreply.github.com> |
||
|
|
b5d47ca5e7 |
gateway: an image sent to a model that can't see is dealt with before it goes out, and one a tool returned no longer ends the chat (#56)
A model's image input is taken from models.dev and the provider's own list, and a group's from its members: only a model known to be text-only is refused an image — one whose support is unknown still gets it, and Codex, OpenCode and Pi are told which models take images. An image the user attaches for a text-only model answers 400 in the client's own format before the upstream is asked; an image earlier in the chat, or one a tool returned (Claude Code's Read, Codex's view_image, a Chat tool message), becomes a short text note, so a chat that met a picture carries on after a switch to a text-only model. Thanks @herrkaefer. |