Skip to content

Fix /analyze 502 on complex products: raise Gemini token caps so thinking can't truncate JSON#23

Merged
Bhagat-Atul merged 1 commit into
benevolentbandwidth:mainfrom
eman-cickusic:fix-analyze-chat-token-cap
Jul 12, 2026
Merged

Fix /analyze 502 on complex products: raise Gemini token caps so thinking can't truncate JSON#23
Bhagat-Atul merged 1 commit into
benevolentbandwidth:mainfrom
eman-cickusic:fix-analyze-chat-token-cap

Conversation

@eman-cickusic

Copy link
Copy Markdown
Contributor

Problem

POST /analyze returns 502 model_response_unparseable for complex / ultra-processed products, while simple inputs succeed. Reproduced live on Cloud Run (ultraprocessed-ai-proxy, us-east1).

Root cause

gemini-2.5-flash counts internal thinking tokens against max_output_tokens. With the current caps (GEMINI_MAX_OUTPUT_TOKENS=700, GEMINI_CHAT_MAX_OUTPUT_TOKENS=512) a complex label makes the model spend the whole budget thinking, leaving almost nothing for the JSON answer, so it is truncated mid-string and json.loads raises:

INFO:httpx: ... gemini-2.5-flash:generateContent "HTTP/1.1 200 OK"
WARNING: Model returned unparseable output: Unterminated string starting at: line 3 column 5 (char 18)

/chat (512 cap) has the same latent risk.

Fix

Raise defaults to 4096 (analysis) and 2048 (chat) so thinking + answer both fit. Env-var overrides still work; README table updated. If a pathological label ever still truncates, bound thinking with types.ThinkingConfig(thinking_budget=N) (noted in a code comment).

Verification (live on Cloud Run, us-east1)

  • 15-ingredient ultra-processed biscuit: was 502 → now 200, NOVA 4, 7 ultra-processing markers, allergens Milk/Wheat/Soy (deterministic across 3 runs).
  • Complex multi-part /chat question with history: 200, correct scan-scoped answer.
  • Simple inputs unaffected.

🤖 Generated with Claude Code

gemini-2.5-flash counts internal thinking tokens against max_output_tokens. The 700/512 caps let thinking consume the whole budget on complex labels, truncating the structured JSON mid-string and returning HTTP 502 (model_response_unparseable) from /analyze; /chat had the same latent risk.

Raise defaults to 4096 (analysis) and 2048 (chat) so thinking + answer both fit. Env-var overrides still work; README updated. Verified live on Cloud Run: a 15-ingredient product that previously 502'd now returns NOVA 4 with correct markers/allergens, and a complex /chat question returns a scoped answer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@Bhagat-Atul Bhagat-Atul merged commit d3540d4 into benevolentbandwidth:main Jul 12, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants