1ccacad63281094de8a3372d5a507d38f9969e5c
9
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d614f21721 |
gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.
What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.
Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.
Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).
Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.
Run at this tree (
|
||
|
|
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 |
||
|
|
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
|
||
|
|
5feadabef6 |
gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.
decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.
Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:
CPU in the request's handler time per request
(pprof, per request) (ns/op)
anthropic 154ms -> 45ms 208-212ms -> 52ms
anthropic, group 178ms -> 51ms 249-262ms -> 65-67ms
chat 122ms -> 35ms 167-254ms -> 50-54ms
responses 215ms -> 56ms 294-452ms -> 70ms
TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).
Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
Responses; direct, through a group, translated to each other protocol,
with images, thinking, escapes, odd spacing, a repeated key, and four
2 MB conversations) and compares what the vendor gets with
testdata/upstream_bodies, recorded on the code before this change
(all 18 identical; three runs agreed). Breaking decodeJSON's \n
unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
the gateway's, and jsonValid with json.Valid, over seeds, every cut
and a changed byte at every place of each seed, and 2.5 minutes of
fuzzing (~1.75M inputs). Breaking the validator's control-byte check
by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
origin/main
|
||
|
|
da1fd6cb0c |
gateway: a Gemini functionResponse's own parts reach the upstream — the image agy's view_file read (#1038, handong66: agy via magpie can't see images, the model makes up what they show)
agy sends the image a tool read inside the function response, as Gemini 3's
multimodal function responses carry it: functionResponse.parts[].inlineData
(under role "model", as agy sends tool results). parseGemini read only id,
name and response, so the parts were dropped before any translation: the
reporter's prompt was 96 tokens instead of 1115 and the model invented the
watermark and subtitle, with a 200 / STOP the client couldn't tell apart.
parseGemini now reads functionResponse.parts (camelCase, and snake_case
through geminiCamel): an image (inlineData or fileData) becomes the tool
result's Images, which every builder already carries — Antigravity/Code
Assist and Factory's Gemini as inlineData right after the functionResponse
in the same turn (the shape top-level images already work in), Anthropic as
tool_result image blocks, Responses as function_call_output input_image,
Chat as the image message after the tool's. A non-image file (a PDF) can't
sit in a tool result, so it follows the result in the same turn instead of
being lost. walkImages now looks inside a Gemini functionResponse's parts
too, so a model that can't see is sent the request with the tool's image
replaced by the omitted note, as for every other surface's tool images.
Tests from the reporter's literal request shape (view_file, call_462432,
response.output + parts[].inlineData; role model and user; camelCase and
snake_case): TestGeminiFunctionResponseImage (parse + Code Assist, Anthropic,
Chat, Responses bodies), TestGeminiFunctionResponseImageReachesUpstream
(/v1beta to a Chat upstream through the gateway), TestGeminiFunctionResponseFile
and TestGeminiFunctionResponseImageIsATools. All four fail without the change
("Images:[]", "the tool's image was not seen"). Not run against a real agy
or Antigravity account.
|
||
|
|
3b6ea8b589 |
gateway: clear 400 for Responses images named by file_id on translated routes (#166)
* gateway: 400 on translated Responses images named by file_id Add error handling for unportable current image in translate function. * gateway: keep native file_id passthrough, reject on translation Added hasUnportableCurrentImage function to check for images without a portable source. * gateway: test Responses file_id image handling |
||
|
|
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. |