[bug] image tokens are underestimated (0 in the routing estimate, flat 1,600 in the window estimate) — long screenshot sessions hit the context limit without compaction
Environment
- magpie 0.1.1778, macOS arm64; gateway on
127.0.0.1:3425 - Provider: Claude subscription accounts (OAuth), model
claude-opus-5-5 - Client: Claude Code (desktop, 3p mode)
- Source checked at
bb35653
Two separate image undercounts
1. Routing counts images as 0.
ruleFor takes size := estimate(req) (internal/gateway/rules.go:184), and estimate (internal/gateway/gateway.go:1724) sums only len(p.Text) + len(p.Args) + len(p.Name). An image part has none of those, so it adds nothing.
One user message with 20 base64 PNGs of 1024×2048 plus the text "How many images?":
| value | |
|---|---|
vendor usage (prompt tokens) |
56,345 |
rule.tokens in GET /v1/magpie/trace |
4 |
(The 4 is the text block.)
2. The prompt/parts estimate uses a flat imageTokens = 1600.
internal/gateway/prompt.go:95 — "about what Anthropic counts for a 1092×1092 one" — used at :800, :817, :938, :982, :1065, :1075, :1173. A screenshot is much bigger than 1092×1092:
| one image + short text | vendor usage |
|---|---|
| 1024×2048 PNG | 5,228 |
| 512×1024 PNG | 2,469 |
| 256×512 PNG | 2,788 |
So a full-size screenshot costs ~3.3× what magpie assumes. (512×1024 coming back below 256×512 suggests a floor or a resize on the vendor side — worth a look on its own.)
What it breaks
A real Claude Code session (screenshots + text):
rule.tokensreached ~698,000 while the vendor's actual prompt was ~1,000,000 — the ~290k gap is ≈55 full-size screenshots at ~5.2k each.- From that point every request to
claude-opus-5-5returned400 invalid_request_error: "Prompt is too long"; magpie classifies itfail: "overflow"(UI: too long for its model). - Nothing compacted before it, because magpie's own count said there were ~300k tokens of headroom (
Compact atwas set to 1,000,000). rules.go:199(q.Tokens = tr.input) can't rescue it:tr.inputis only set when a request succeeds, so a conversation that is already past the window never calibrates — it just keeps failing.
Control, same minute / same account / same model:
| request | result |
|---|---|
| 713,664 prompt tokens, text only | 200 |
| 721,664 prompt tokens, text only | 200 |
713,664 + max_tokens: 393216 (sum 1.1M) |
200 |
the session's 712,679 (rule.tokens) |
400 |
So the account, the model, max_tokens, the context-1m beta, thinking, tools/system and group routing were all ruled out by direct probes — the image payload that never enters the count is what tips it over.
Suggestion
- Size images from their dimensions instead of a flat 1,600 — magpie already reads image dimensions elsewhere (
internal/gateway/codex_images.go). - Include images in
estimate()sotokens=rules and the trace reflect them. - Or, when a request carries images, hold back a margin in the window that
Compact at/ a group'scontextwork from.
中文摘要
magpie 对图片 token 有两处低估,叠加起来会让带截图的长会话在没有触发压缩的情况下直接撞上上下文上限:
- 路由用的
estimate()(internal/gateway/gateway.go:1724,被rules.go:184调用)只累加文本长度,图片部分为 0。实测 20 张 1024×2048 的图:供应商计 56,345 token,rule.tokens只有 4。 - 窗口/构成分析用的是固定常量
imageTokens = 1600(internal/gateway/prompt.go:95)。实测单张 1024×2048 供应商计 5,228,约 3.3 倍;512×1024 是 2,469,256×512 反而是 2,788(可能有下限或缩放)。
后果:一个真实会话 rule.tokens 到约 698,000 时,供应商那边其实已到 100 万(差额 ≈ 55 张全尺寸截图),之后每轮都是 400 "Prompt is too long",fail: "overflow",界面上显示 too long for its model,且因为 Compact at 设的是 1,000,000,永远不会提前压缩。rules.go:199 用「上次供应商计数」兜底也救不了——只有请求成功时才会更新,一旦越线就再也校准不了。
对照实验(同一分钟、同一账号、同一模型):纯文本 713,664 / 721,664 都是 200,713,664 + max_tokens 393,216 也是 200,而该会话 712,679 是 400。
建议:按图片尺寸算 token(internal/gateway/codex_images.go 已有读取尺寸的代码),把图片计入 estimate(),或者在有图时给窗口留余量。
Pull requests are disabled on this repository (the newest one is #1355, 2026-10-08), so here is the fix as a patch instead. It is also a branch: mikehasa/magpie:estimate-counts-images.
What it does: estimate() counts each Image part as imageTokens — the number prompt.go already takes an image for — and never as its base64, so a screenshot-heavy conversation stops being taken for text alone.
TestEstimateCountsImagesis new; on the old code it fails withan image added 0 tokens to estimate(), want imageTokens (1600)TestPayloadTooLargeIsNotContextOverflowkeeps its "image bytes don't pass the token margin" guarantee by using a window above the image's own cost (2,000): the image there is 287 KB of base64, ~71,000 tokens if bytes were countedgofmt -lclean,go build ./...ok,go vet ./internal/gateway/ok,go test ./internal/gateway/green exceptTestServeWSLListensBesideLoopbackandFuzzMarshalRaw/seed#7, which fail identically on the unmodified tree on this machine (macOS 27, Go 1.27.3)
It deliberately leaves the flat imageTokens = 1600 in prompt.go alone: that one is still ~3× low for a 1024×2048 screenshot and needs the vendor's per-size numbers, which is the second half of this issue.
patch
From 045f59f1e8c85470049d62af9bb5338fc3385c41 Mon Sep 17 00:00:00 2001
From: mikehasa <[email protected]>
Date: Thu, 29 Oct 2026 02:19:09 -0700
Subject: [PATCH] gateway: an image counts in the token estimate, as the
prompt's parts count one
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
estimate() read each part's text and byte length, and an image part has
neither: a request carrying screenshots counted as its text alone. Routing
rules (ruleFor) and the count_tokens endpoints read exactly this number, so
a session with ~55 full-size screenshots was taken for 698,000 tokens while
the vendor counted 1,000,000 — nothing compacted, and every request came
back "Prompt is too long" until the conversation was thrown away (#4239).
Count each image as imageTokens, the number the prompt's parts already take
one for, never as its base64.
TestEstimateCountsImages fails without this ("an image added 0 tokens to
estimate(), want imageTokens (1600)"). TestPayloadTooLargeIsNotContextOverflow
keeps its guarantee with a window over the image's own cost: an image's
bytes still don't pass the token margin.
Ran: gofmt -l (clean), go build ./..., go vet ./internal/gateway/,
go test ./internal/gateway/ — all pass except two that also fail on the
unmodified tree on this machine (macOS 27, Go 1.27.3):
TestServeWSLListensBesideLoopback (IPv6 loopback answers here) and
FuzzMarshalRaw/seed#7 (U+2028 escaping).
Co-Authored-By: Claude Code <[email protected]>
---
internal/gateway/estimate_test.go | 30 ++++++++++++++++++++++
internal/gateway/gateway.go | 9 ++++++-
internal/gateway/payload_too_large_test.go | 7 +++--
3 files changed, 43 insertions(+), 3 deletions(-)
create mode 100644 internal/gateway/estimate_test.go
diff --git a/internal/gateway/estimate_test.go b/internal/gateway/estimate_test.go
new file mode 100644
index 0000000..bea9969
--- /dev/null
+++ b/internal/gateway/estimate_test.go
@@ -0,0 +1,30 @@
+package gateway
+
+import (
+ "strings"
+ "testing"
+)
+
+// An image is part of what a request costs: the count rules and counting
+// clients read takes each one for imageTokens. Its base64 is not its cost,
+// or a single screenshot would be hundreds of thousands of tokens (#4239).
+func TestEstimateCountsImages(t *testing.T) {
+ text := &Request{Messages: []Message{{Role: "user", Parts: []Part{
+ {Kind: Text, Text: "abcd"},
+ }}}}
+ one := &Request{Messages: []Message{{Role: "user", Parts: []Part{
+ {Kind: Text, Text: "abcd"},
+ {Kind: Image, MediaType: "image/png", Data: "aGVsbG8="},
+ }}}}
+ big := &Request{Messages: []Message{{Role: "user", Parts: []Part{
+ {Kind: Text, Text: "abcd"},
+ {Kind: Image, MediaType: "image/png", Data: strings.Repeat("aGVsbG8=", 50000)},
+ }}}}
+
+ if got, want := estimate(one)-estimate(text), imageTokens; got != want {
+ t.Errorf("an image added %d tokens to estimate(), want imageTokens (%d)", got, want)
+ }
+ if got, want := estimate(big), estimate(one); got != want {
+ t.Errorf("a larger image's base64 changed the count: %d, want %d", got, want)
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 31702d6..c687660 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1724,15 +1724,22 @@ func (s *Server) geminiModels(w http.ResponseWriter, r *http.Request) {
// estimate is a token count from sizes, for clients that ask before sending.
func estimate(req *Request) int {
n := len(req.System)
+ images := 0
for _, m := range req.Messages {
for _, p := range m.Parts {
n += len(p.Text) + len(p.Args) + len(p.Name)
+ if p.Kind == Image {
+ images++
+ }
}
}
for _, t := range req.Tools {
n += len(t.Name) + len(t.Description) + len(t.Schema)
}
- return n / 4
+ // an image is counted as the prompt's parts count one, imageTokens,
+ // not as its base64: a screenshot's bytes are hundreds of thousands of
+ // n/4 tokens, while its picture is one of these (#4239)
+ return n/4 + images*imageTokens
}
// serve routes one parsed-enough request to its provider.
diff --git a/internal/gateway/payload_too_large_test.go b/internal/gateway/payload_too_large_test.go
index 41a2896..0549f64 100644
--- a/internal/gateway/payload_too_large_test.go
+++ b/internal/gateway/payload_too_large_test.go
@@ -25,12 +25,15 @@ func TestPayloadTooLargeIsNotContextOverflow(t *testing.T) {
t.Errorf("byte limit classified as token limit: %s", msg)
}
p := provider.Provider{ID: "fake", Name: "Fake", Contexts: map[string]int{"m": 100}}
- // Image bytes don't make a text estimate pass the token margin.
+ // Image bytes don't make a text estimate pass the token margin: a
+ // picture is imageTokens, not the hundreds of thousands of tokens
+ // its base64 would come to, so a window over it sees the text fit.
+ roomy := provider.Provider{ID: "fake", Name: "Fake", Contexts: map[string]int{"m": 2000}}
tokens := estimate(&Request{Messages: []Message{{Role: "user", Parts: []Part{
{Kind: Text, Text: strings.Repeat("word", 100)},
{Kind: Image, Data: strings.Repeat(pngA, 4096)},
}}}})
- if inferred, ok := tooLongUnsaid(p, "m", tokens, 413, []byte(msg)); ok {
+ if inferred, ok := tooLongUnsaid(roomy, "m", tokens, 413, []byte(msg)); ok {
t.Errorf("byte limit inferred as token limit: %s", inferred)
}
if inferred, ok := tooLongUnsaid(p, "m", 1000, 413, []byte(msg)); !ok || !strings.Contains(inferred, "prompt is too long") {
--
2.54.0 (Apple Git-157)
Took this one (OPEN; git log --grep=4239 shows no fix on main as of 4534561f). Two things up front:
- mikehasa's patch on this issue is taken, credited. Your
estimate()half is in, with your test name (TestEstimateCountsImages) and your reasoning about the image's base64 never counting as its tokens. - Since the repo doesn't take pull requests, the fix is a branch of my fork for cherry-picking — it shares nothing with the other commits in that branch beyond two files at different hunks:
git fetch https://github.com/Niko-Wu/magpie fix/oss-batch && git cherry-pick 33db9b8d
(based on 4534561f, one commit, internal/gateway/ only)
The second half — a flat 1,600 becomes the image's own size
An image now costs what its pixels cost, read from its header alone (image.DecodeConfig over the base64, the way codex's images are already read in codex_images.go) and never below 1 megapixel's worth. Your three measurements fit a floor plus a slope, which is what explains the odd 256×512 reading you flagged:
| image | your vendor usage |
this change |
|---|---|---|
| 1024×2048 | 5,228 | 5,242 |
| 512×1024 | 2,469 | 2,500 |
| 256×512 | 2,788 | 2,500 |
i.e. one token per 400 pixels with a 1,000,000-pixel floor — the vendor appears to count an image smaller than that as if it were that size, which is why 256×512 did not come back cheaper than 512×1024. This is a fit to three points, not a documented rule, and it errs high: Anthropic's own rule for a plain API call is 750 pixels per token, so a 1092×1092 image is 2,981 here where a documented-rule reading would say ~1,590. For the failure you hit, erring high is the safe direction — a turn compacts early instead of a session running past the window. A source whose header can't be read (a URL a vendor fetches, a document, a truncated base64) keeps the flat 1,600, so nothing that used to count counts zero.
The base64 is read where it is, as a subslice of the source JSON, so a source holding megabytes of it costs the scan and a header decode, not a copy.
Tests, red before and green after (internal/gateway/estimate_test.go)
TestEstimateCountsImages— your test: an image adds its size's cost toestimate(), not 0; an unreadable one still costsimageTokens.TestPromptPartsCountImageSize— one 1024×2048 PNG throughpromptOfas an Anthropic source object, a Chatimage_urland a Responsesinput_image; each part must cost 5,242.TestPromptImageWithoutAHeaderKeepsTheFlatCost— a URL source and a base64 that isn't an image.TestImageBase64IsASubslice— the base64 is a subslice of the source, and an escaped source is not read.TestPayloadTooLargeIsNotContextOverflowkeeps its guarantee with the window taken from the estimate (your change too).TestIntentNotAskedWhenItCantMatterneeded one edit: its tokens rule (1,000) sat below an image's new cost, so the image case matched it. The rule is now 2,000 and the long requestlong(2400), which keeps the test about "an image has no words to classify".
Verification
go test ./internal/gateway/ -timeout 45m→ 428s; green except four that are red on unmodifiedupstream/main4534561fon this machine (macOS 27, Go 1.27.3):TestCodexFittedImagesPastTheBudget,TestMarshalRawIsEncodingJSON,TestServeWSLListensBesideLoopback,FuzzMarshalRaw/seed#7.gofmt -l,go vet, andGOOS=linux/GOOS=windows(CGO_ENABLED=0)go vet→ clean.- Not tried: a real long screenshot session against
claude-opus-5-5, so the numbers that matter are still yours. If you can, the check isrule.tokensin/v1/magpie/traceagainst the vendor'susagefor the same request — they should now be within a few per cent for a screenshot-heavy turn.
I did not take your third suggestion (hold a margin back in the window for a request carrying images). Sizing the images seemed the smaller change that removes the whole class, and a margin on top of a fitted estimate would double-count.
No .github/, no site/, no dependency changes.
take
Credit @mikehasa for the report. Standing down — Niko-Wu's patch (33db9b8d, October 29) already covers both halves of this report and my verification lane will follow it rather than a second fix.
AI use: this note was written with AI assistance (ZCode).