Vision images re-attach as base64 into every LLM request - image-heavy chats hit provider 413 and die silently
Vision images re-attach as base64 into every LLM request — image-heavy chats hit provider 413 and die silently
Summary
Images loaded via vision_load remain in chat history as image_url parts forever. Every subsequent LLM call re-attaches all of them as base64 into the request body. On image-heavy long-running chats the body reaches tens of MB while the context indicator shows only 12–24% token usage. Providers behind Cloudflare (e.g. z.ai) reject the body with 413 Request Entity Too Large; LiteLLM retries 3× with the identical oversized body, all fail, and the turn dies with no visible error — the UI hangs at "Reasoning.../waiting for input" until the user restarts. Affects all presets/endpoints; text compaction does not fix it (the text shrinks, the images stay).
Reproduction
- In a long-running chat,
vision_loadseveral multi-MB images (e.g. 6 PNGs of ~3 MB each) across several turns - Keep chatting — every turn now sends the accumulated base64 payloads of all historical images in the request body
- Once accumulated payload crosses the provider's body limit (observed threshold on a Cloudflare-fronted endpoint at ~25 MB total PNGs → base64-inflated body), every turn fails:
litellm.exceptions.APIError: APIError: OpenAIException - <html>... 413 Request Entity Too Large ...
LiteLLM Retried: 3 times
No error is surfaced in the WebUI; the chat appears silently hung. Real-world correlation from our instance: vision_load at 12:25 → 413 at 12:29; 6 beat frames (~18 MB) loaded 13:58 → turn dead; same chat 413'd again at 14:00 and 15:13 — while token counts showed 12–24%.
Root cause
helpers/history.py:794treatsimage_urlparts as permanent history items; vision-loaded images (stored as files underchats/<id>/images/vision-load/, referenced by path) are never pruned.helpers/litellm_transport.py:937-945(content_part_from_chat) converts every historicalimage_urlpart into aninput_imagepart for each request. Local paths are read and base64-encoded by the transport, so N historical images ≈ N × (file size × 1.37) bytes in every single request body.- The context indicator counts tokens, not body bytes — a chat can show 12% context while its request body exceeds the provider's upload limit.
- On
413,exception_mapping_utils.py:633raises a genericAPIError; LiteLLM retries 3× with the same body; the failure surfaces only as a generic "Critical error occurred, retrying..." and then a silent dead turn.
Proposed fix
Trim historical image parts from the outgoing request (they serve no purpose after the model has seen them once). We run this as a user-space extension on call_chat_model_turn/start (verified working — a turn against the exact history that 413'd four times completed without error):
- Keep only the K most recent image parts in the outgoing message list (K=2 works well); replace older ones with a text placeholder
"[earlier image removed to keep request size down]" - Operate on a copy — never mutate stored history
- Optionally: convert old images to low-detail thumbnails instead of placeholders, if visual continuity matters
A more conservative alternative: cap the cumulative base64 payload per request (e.g. 10 MB) and drop/replace oldest images until under the cap, logging a warning.
Before/after
| Scenario | Before | After |
|---|---|---|
| Chat with many historical vision images | Every request re-sends all images; eventual deterministic 413; silent hang | Only K recent images sent; body stays bounded |
| Token indicator | Shows 12–24% while body is 25+ MB (misleading) | Unchanged (indicator is token-based; a body-size warning would help further) |
| 413 from provider | 3 identical retries, silent dead turn | Avoided in the first place |
| Compaction of image-heavy chat | Does not help (text shrinks, images stay) | Unaffected — images trimmed at request time |
| Normal image use (recent images) | Works | Unchanged (kept) |
Environment
- Agent Zero v2.10, Docker (Kali container), Chat Completions mode
- Provider: z.ai coding endpoint behind Cloudflare (body-size limit observed at roughly 20–30 MB)
- Reproduced across 4 separate incidents on 2026-08-28 in the same chat
Related: #1855 (Chat Completions mode plain-text logging gap — same "turn dies silently" UX class).
Verification status update (same day):
Two corrections to keep this report accurate:
-
Where images ride in history: images are not stored as inline
image_urlparts in the persisted chat log —vision_loadstores them as files underusr/chats/<id>/images/vision-load/(helpers/chat_media.py) and attaches them to tool-result messages via the messageattachmentsmechanism (agent.py:334,746,753). The attachment→image_url/input_imageconversion happens when the request is assembled (helpers/litellm_transport.py:937-945). Net effect is exactly as described: all historical images are re-sent in every request body. The fix approach (trim image parts from the outgoing request copy) is unchanged — it just needs to hook where attachments are expanded. -
Fix-verification status: our request-time trim extension is deployed but pending an extension-registry reload to activate; an interim test was inconclusive (turn was interrupted before the LLM call), and the 413 recurred afterwards — consistent with the extension not yet being loaded. The 413 itself has been reproduced 5+ times and is unaffected by this; the mechanism and correlation evidence stand.
We'll confirm the trim results (with request-body measurements) in a follow-up comment once the fix is loaded.
Update (2026-09-13): far lower thresholds in production + a tested fix
Two weeks of additional production data — including a second, independent failure path:
New evidence
- a0t gateway (
llm.agent-zero.ai) and z.ai coding endpoint (api.z.ai/api/coding/paas/v4) both 413 at ~1 MB body size — much lower than the ~25 MB Cloudflare case in the original report. Signature:413 - {'detail': 'Request body too large'}(FastAPI-style JSON, not Cloudflare HTML). - The trigger this time was browser-tool screenshots (saved under
usr/chats/<id>/screenshots/browser/, ~0.5–1 MB JPEG each → ~1.37 MB base64 in every subsequent request), notvision_load— the same history re-attachment mechanism, so the issue is wider than vision tools. - Retry paths resend the identical rejected body. LiteLLM's own 3× retry does (already noted); we additionally observed it at the application layer: a 413-failover that retries the turn on a second provider 413s there too, because both endpoints sit behind similar body limits. The user sees the raw error even though one provider is healthy.
Framework gap: embed trimming is count-based, not byte-based
History.trim_embeds() (helpers/history.py, ~line 486) caps the number of embedded items (max_embeds, default 10). Ten ~1 MB screenshots ≈ ~13.7 MB request body while the token indicator shows a fraction of the context used. A single screenshot can now exceed a 1 MB-endpoint's limit on its own — a count cap alone cannot prevent this class of failure.
Tested fix (running in production since today)
- Byte-aware payload diet (framework-runtime hook, before every chat-model call): serialize the assembled message list; if the body exceeds a budget (1 MB), downscale embedded
image_urldata-URLs with PIL (longest side 1568 px, JPEG quality ladder, per-image target 128 KB → progressive passes) until the body fits. Copy-on-write — original history objects are never mutated, text parts untouched, images stay valid model-readable screenshots. On 413, a forced half-budget diet runs before any retry, so retries never resend an identical rejected body. - Config mitigation:
max_embeds: 2keeps the freshest images for vision continuity while shedding the long tail.
Measured on the actual failing turns:
| Scenario | Body before | Body after |
|---|---|---|
| Two ~1 MB screenshots in history | 2553 KB | 139 KB |
| Forced retry diet (0.5 MB budget) | 689 KB | 137 KB |
PIL is already present in the official Docker image, so this is ~150 lines with no new dependencies. Happy to open a PR with the diet implementation if maintainers are interested.
Update 2 (2026-09-14): why the built-in mitigations miss this class of failure, and the proper core fix
After further production debugging (and twoweeks of 413-free operation on the layered fix), three findings that sharpen the root-cause picture:
1. Every existing mitigation is structurally blind to wire size — because of where inflation happens
Verified in source:
History.trim_embeds()(helpers/history.py) is count-based (max_embeds, default 10) — ten ~1 MB screenshots ≈ ~13.7 MB of body pass the count cap.- History stores
image_urlparts as local file paths (~100 bytes). The base64 inflation happens later, in the model layer:models.py _convert_messages→images.prepare_content()reads every path and inlines base64 — after token packing, after embed trimming, and afterchat_model_call_beforehooks run.
So every measurement point A0 currently has (token cascade, embed counting, hook-level len(json.dumps(messages))) looks at a payload that hasn't grown yet. Bytes are nobody's responsibility at any layer. A chat can sit at 20% token usage with a 2.6 MB request body — measured in production (AI Chat Interface chat, two ~1 MB browser screenshots).
2. The proper core fix (what we'd love to see upstream)
| Layer | Fix | Where |
|---|---|---|
| Store time | Normalize images at birth: save a model-view copy (longest side ~1568 px, JPEG ≈ 100–200 KB — beyond that, pixels are wasted on any vision model) next to the original for the human UI | helpers/chat_media.py, browser screenshot capture, vision_load |
| Transport | A byte budget (body_max_bytes) next to ctx_length, enforced at final assembly (the only place that knows the true size), with graceful degradation: oldest images first → lower quality → text placeholder |
litellm_transport.py |
| Retry | 413 must transform the payload before retrying — resending identical bytes is useless (also applies to LiteLLM's own 3× identical retry) | transport + exception mapping |
| Lifecycle | Images should age like text does: vision once → findings land in the agent's text → image part becomes a caption ("[prior image removed — see that turn]"). LLMs are stateless: old screenshots only ever cost bytes, never add information the agent hasn't already verbalized | helpers/history.py compression pipeline |
3. The layered production implementation (all of the above, plugin-side)
Running in usr/plugins since yesterday, zero 413s since deployment:
- One-time vision (
image_retention_messages: 2): images remain only in the newest 2 image-bearing messages; older parts become text captions. Real chat: 3332 KB → 709 KB from retirement alone. - Persistent byte diet: oversized images get a one-time downscaled sidecar (
.diet.jpg, mtime-memoized) and history is repointed — each image is processed exactly once, later turns are 0-cost no-ops. Two ~1 MB screenshots: 2623 KB → 139 KB, originals untouched. - Effective-size gauge: body measured with path-images counted at their base64-inflated size (the fix for the measurement-point blindness above).
- 413 retry transform: forced half-budget diet before any cross-provider retry.
If maintainers want, happy to split any of these into a PR — the transport byte budget (layer 2) is probably the highest-value/lowest-risk core change, and store-time normalization (layer 1) would make the rest mostly unnecessary.
Independent confirmation from a second instance running unmodified upstream code, with the byte-level root cause, a pristine-HEAD reproduction, the measured gateway threshold, and a tested core patch.
Environment: A0 v2.12 (b1cbd1f9) on the hosted gateway a0_venice (https://llm.agent-zero.ai/v1).
Confirmed against pristine HEAD (no local modifications)
| Fact | Location at HEAD |
|---|---|
| Full file base64-encoded, no size cap | helpers/images.py:41-47 to_data_url() -> base64.b64encode(path.read_bytes()) |
| Compression helper is dead code | helpers/images.py:75 compress_image(); git grep compress_image HEAD returns only the definition |
| No shrink at upload | helpers/chat_media.py::save_image_bytes() only rejects >25 MB (DEFAULT_MAX_ARTIFACT_SIZE_BYTES) |
| Both transports inflate | models.py:405, helpers/litellm_transport.py:992,2183 |
| Direct inflate path | tools/vision_load.py:180 |
Reproduction (pristine HEAD)
5 unmodified phone photos, 4032x3024, ~15.2 MB total, with HEAD:helpers/images.py loaded as a module:
1 photo -> 4.13 MB request body
2 photos -> 8.31 MB
3 photos -> 12.41 MB
5 photos -> 20.32 MB
Measured gateway limit: 4.0 MB accepted, 4.5 MB -> 413 {'detail': 'Request body too large'}.
So one normal phone photo already exceeds the limit, and because images persist in history the chat 413s on every subsequent turn and cannot self-heal. The context indicator stays low because the body is bytes, not tokens.
This also matches your Update 2 finding: History.trim_embeds() is count-based, and inflation happens in models.py _convert_messages -> images.prepare_content() after token packing and embed trimming, so no existing mitigation can see the wire size.
Tested core fix (~130 lines, 3 files)
helpers/images.py:to_data_url(url, max_bytes=...)-- above the budget, run the existingcompress_image()down a quality/pixel ladder until it fits; cache results in a temp dir (never in chat artifact folders). Newcount_local_refs()/image_budget_for()cap per-image and per-request totals (600 KB / 1.8 MB / 120 KB floor), so no number of images can exceed the limit.models.py::_convert_messages(): compute the budget once from all messages, then pass it intoprepare_content().helpers/chat_media.py::save_image_bytes(): compress at ingest (>1.5 MB -> max 1 MP, q80) so chats cannot accumulate multi-MB images at all.
Result on the affected instance: the same 5-photo chat's request body went 20.32 MB -> 0.74 MB, and the chat answered normally instead of 413ing. git apply --check is clean against main @ b1cbd1f9.
Secondary contributors observed in the same investigation (outside the patch): presets with ctx_length: 1000000 disable history compression entirely (trim threshold ~700K tokens), and the A0 CLI connector injects the workspace file tree into every request (a .pnpm-store folder alone added ~20K tokens per turn).
Happy to open a PR against main -- would you prefer the byte cap in to_data_url, or trimming at the attachment-expansion step you described?