Franklin icon indicating copy to clipboard operation
Franklin copied to clipboard

Gateway tokenizes vision image blocks as text — ~80× cost inflation per image

Open KillerQueen-Z opened this issue 6 months ago • 1 comments

Summary

The BlockRun gateway appears to count vision image content blocks as text tokens (tokenizing the base64 data field via BPE) instead of routing them through the upstream provider's vision pipeline (which would charge ~(width × height) / 750 image tokens per Anthropic's spec).

Effect: a single 1024×1024 image is billed at ~110,000 input tokens instead of the ~1,400 that direct Anthropic API would charge. ~78× cost inflation per image.

This is separate from #51 (size-truncation issue). Both bugs likely share the same root cause (gateway not recursively recognizing image blocks inside tool_result.content).

Concrete numbers (real session, 2026-05-09)

Single-turn vision conversation:

  • Image: 162 KB JPEG, 1024×1024 (after our client-side normalize)
  • Base64 length: 216,772 chars
  • Model: anthropic/claude-opus-4.7
  • Reported input_tokens: 228,845 (114% of context window) on turn 2

Anthropic's documented formula for image tokens:

image_tokens ≈ (width × height) / 750
            = (1024 × 1024) / 750
            ≈ 1,400 tokens

Two images in turn 2 should = ~2,800 image tokens + a few thousand for system prompt + text = under 10,000 total. We saw 228,845 → text-tokenization is the only explanation.

Reproduction

  1. Send any vision request through the gateway (Read tool returns image, agent loop wraps as tool_result.content with [text, image] array)
  2. Inspect Anthropic's response usage.input_tokens
  3. Compare against (width × height) / 750
  4. Observe ~80× discrepancy

Likely root cause

Gateway likely doesn't recursively walk into tool_result.content arrays to find nested image blocks. Three common variants:

(a) Top-level only check

// Wrong — only catches messages[N].content[i] = {type:'image'}
for (const block of message.content) {
  if (block.type === 'image') routeAsImage(block);
}
// Misses nested:
// messages[N].content[i] = {
//   type: 'tool_result',
//   content: [{type:'text'}, {type:'image', source:{...}}]  ← skipped
// }

(b) JSON.stringify on tool_result.content

// Wrong — converts entire array (including image block) to text
const text = typeof block.content === 'string'
  ? block.content
  : JSON.stringify(block.content);  // base64 ends up in text payload

(c) Provider translation drops nested

When routing to non-Anthropic upstream (Gemini / OpenAI), translation lookup may only match top-level image blocks; nested ones get inlined as text.

Why the cost difference is ~80×

Base64 is high-entropy (random A-Z a-z 0-9 + / chars). BPE tokenizers built for natural language can't compress it — typical density is ~2–4 chars per token. A 217 KB base64 string → ~80–110K tokens.

True vision pipeline:

  1. base64 → bytes → image decoder → pixel matrix
  2. Pixel matrix → vision encoder (CLIP/ViT)
  3. Few hundred dense vectors representing semantic content
  4. Counted at (w×h) / 750
Tokens Cost (Sonnet 4.6, $3/M input)
Vision pipeline ~1,400 $0.0042
Text pipeline (current) ~110,000 $0.33
Ratio — ~78×

Verification test

curl -X POST $GATEWAY_URL/v1/messages \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.6",
    "max_tokens": 100,
    "messages": [
      {"role": "user", "content": [
        {"type": "text", "text": "What is in this image?"},
        {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "<base64 of any 1024x1024 image>"}}
      ]}
    ]
  }'

Expected usage.input_tokens ≈ 1,500–3,000 (system + text + image_tokens). Observed (current bug): 100,000+

Also test with the image nested inside a tool_result:

{"role": "user", "content": [
  {"type": "tool_result", "tool_use_id": "abc", "content": [
    {"type": "text", "text": "Image file:..."},
    {"type": "image", "source": {...}}
  ]}
]}

The nested case is the one Franklin's Read tool produces — it's where the bug bites hardest.

Impact

Affects everyone using vision features through the gateway:

  • Franklin CLI users reading local screenshots / images
  • Franklin VS Code extension image paste/drop (just shipped)
  • Any agent reading ImageGen / VideoGen output for follow-up analysis
  • Multi-turn vision conversations (each turn re-pays the inflated cost on prior images)

Estimated user-side over-charge: ~$0.30/image vs $0.004/image on Sonnet 4.6. On Opus 4.7 ($15/M input) it's ~$1.65/image vs $0.02/image — even worse.

Recommended fix

// Recursive walk that handles both top-level AND nested image blocks
function findAllImageBlocks(messages, callback) {
  for (const m of messages) {
    if (!Array.isArray(m.content)) continue;
    for (const block of m.content) {
      if (block.type === 'image') {
        callback(block);
      } else if (block.type === 'tool_result' && Array.isArray(block.content)) {
        for (const inner of block.content) {
          if (inner.type === 'image') {
            callback(inner);
          }
        }
      }
    }
  }
}

// On routing:
// - Anthropic upstream → pass through (it recognizes the format natively)
// - Gemini → translate to inlineData.data
// - OpenAI → translate to image_url.url with data: URI
// CRITICAL: never JSON.stringify image blocks into text fields

Related

  • #51 — gateway truncates large vision payloads (likely same root cause)
  • Both will likely be fixed by the same recursive-walk patch

Workaround in Franklin (already shipped client-side)

We've added keepRecentImagesOnly() in src/agent/optimize.ts so multi-turn conversations only re-send the most recent image. This caps the per-turn cost but doesn't fix the per-image inflation.

Once the gateway is patched, we'd like to remove this workaround and bump the VS Code extension's client-side image normalization from 1280 px back to Anthropic's recommended 1568 px (currently constrained by the per-payload size cap from #51).

KillerQueen-Z avatar May 09 '26 22:05 KillerQueen-Z

Direct evidence captured 2026-05-09 — confirms gateway-side transformation

Captured the literal HTTP body Franklin POSTs to the gateway (instrumented JSON.stringify(requestPayload) to disk just before fetch()). The structure proves the client is sending Anthropic-spec-compliant image content blocks intact.

Outgoing payload structure (real capture)

messages: 5 entries
[0] user:      STRING(3 chars) = '你是谁'
[1] assistant: text(23 chars) — prior response
[2] user:      text(503 chars) — '[USER ATTACHED 1 IMAGE — YOU MUST READ THEM]\nPaths:\n  1. /var/folders/.../scene1_opening-XXX.jpg ...'
[3] assistant: tool_use name=Read
[4] user:      LIST(1 block)
    └─ tool_result.content = LIST(2 blocks)         ← array, NOT a string
        ├─ text  = 'Image file: /var/folders/.../scene1_opening-XXX.jpg ...'
        └─ image source.type=base64 media_type=image/jpeg data=<full base64, ~217k chars>

The tool_result.content is an array of blocks (text + image), exactly per Anthropic docs. The image block has source.type=base64, valid media_type, and the base64 data field intact.

Anthropic's billed usage.input_tokens for the same request

usage.input_tokens = 114,543   (single image, fresh chat)
usage.input_tokens = 228,845   (image carried into turn 2 — confirmed via in-flight history)

Anthropic's documented vision token formula

image_tokens ≈ (width × height) / 750
            = (1024 × 1024) / 750
            ≈ 1,400 tokens

Even with a generous system-prompt + scaffold overhead, a single 1024×1024 image request should be in the 2,000–3,000 token range, not 114,000.

Conclusion

  • Client-side payload: ✅ correct format (verified bytes-on-disk)
  • Anthropic billing: 114k tokens (verified from usage.input_tokens in stream response)
  • Discrepancy ratio: ~80×

Since the gateway is the only transformation layer between Franklin and Anthropic, and the client payload is provably correct, the gateway must be either:

  1. Stringifying tool_result.content arrays before forwarding (so Anthropic receives base64 in a text field and tokenizes char-by-char)
  2. Hoisting the image bytes into a sibling text block (same effective result)
  3. Failing recursive recognition of nested image blocks inside tool_result.content and falling through to a generic JSON.stringify fallback

All three would produce the observed 80× cost inflation without producing any visible client-side error (Franklin's payload looks correct to us; Anthropic's response looks correct to Franklin — but input_tokens reveals what really happened upstream).

Recommended verification on the gateway side

Add a one-line dump of the literal body sent to the upstream Anthropic API (after gateway translation, before fetch). Compare to the body received from the client. If they differ in any image-bearing message, that diff is the bug.

Bonus: client-side workarounds we've shipped (none of these fix the root cause)

  1. Resize to 1280px long edge + JPEG q85 → smaller base64 → less token over-charge
  2. keepRecentImagesOnly() in optimizeHistory → prevents multi-turn re-payment for the same image
  3. Fixed our own budgetToolResults JSON.stringify bug (was destroying image blocks before they reached the wire — different root cause, also real)

Once the gateway is fixed, we can roll back these workarounds and bump client-side normalization back to Anthropic's recommended 1568 px (currently constrained by the size cap from #51 too).

KillerQueen-Z avatar May 09 '26 23:05 KillerQueen-Z