Why Setting max_tokens to 8000 Truncated My Translation Model at 318 Output Tokens
The Alert Said “No JSON Object”
The translation worker in my learning library runs the same contract on every note: one call, one JSON object, fields for title, description, body. Failures do not reach me as a stack trace — the scheduler pushes them to Telegram, so what arrived was one line:
translate failed: model returned no JSON object: ```json {}
That is an empty JSON shell inside a code fence. No stack trace, no hint of why the model stopped. Only after I replayed the same prompt inside the container did I see the payload cut mid-bullet at - **Facade of Strength, Deception Mechanism.
The call site in pipeline/translate.py:516 passes these parameters:
result = call_llm(
"translate",
[{"role": "system", "content": system_prompt(glossary)},
{"role": "user", "content": note_user_prompt(data, masked_body, glossary)}],
model=model, temperature=0.15, timeout=300, max_tokens=8000,
transport=transport, db=db,
)
On paper, max_tokens=8000 looked generous enough for a single translated note: the complete output of the same prompt, later, needed only 1,739 body tokens.
What the Ledger Showed
Every call writes a row to an llm_calls ledger, and the two failing runs were recorded at 10,283 and 10,112 tokens. Both totals sit above the 8,000 ceiling, which is the first sign that the ledger total and the length of the answer are not the same measurement:
| Measurement | Value |
|---|---|
| Ceiling passed to the API | 8,000 |
| Tokens recorded for the first failing run | 10,283 |
| Tokens recorded for the second failing run | 10,112 |
| Parse result | model returned no JSON object |
The row holds one total, not a breakdown. Read against the provider’s bill, that total has to cover prompt, thinking, and output together — an inference from the numbers, not a per-field figure the ledger actually gives me. So “10,283 tokens were spent” and “the answer was cut short” are both true, and the total on its own suggests the opposite: a call that produced plenty.
This is where an aggregate number becomes a liability. A pipeline that logs one tokens figure per call can show a healthy average while a class of calls is quietly dying, because the expensive part of a truncated reasoning call is the thinking nobody can see.
Replaying the Same Prompt Twice
To separate hypothesis from cause I went with the dumbest control available: run the failing note again inside the container, same prompt, same model, two different ceilings. Same input, one variable.
max_tokens | Reasoning tokens | Output tokens | finish_reason | Result |
|---|---|---|---|---|
| 8,000 (the live value) | 7,678 | 318 | length | 1,417 chars, cut inside a bullet |
| 30,000 | 6,689 | 1,739 | stop | 8,210 chars, parsed; body 6,952 chars |
At 8,000, 96% of the budget went to reasoning. The visible output got 318 tokens — 1,417 characters of a response that needed 8,210 characters. The parse failure came downstream: the truncation happened first.
That table is the whole post. On this model and API path, thinking tokens share the same max_tokens ceiling as the visible answer, so a ceiling chosen by asking “how long is my output?” answers the wrong question. The right question is “how long is my output plus however long this model thinks about this input?” — and the only reliable way to learn the second number is to measure it on the prompt in hand.
One Parse Error Hid Truncation and Aggregate Blindness
The same symptom — a JSON parser complaining — has three distinct causes, and they need different fixes:
- Output starvation under a shared budget. Reasoning tokens and visible tokens draw on one ceiling. In this run, reasoning consumed 7,678 of the 8,000-token ceiling, leaving 318 tokens for the JSON body.
- Silent truncation the call never raises for. Nothing throws. The response comes back well formed with
finish_reason=length, and everything downstream that reads “no exception” as success treats a half-object as a complete one. - Attribution blindness in aggregate metrics. A single
tokenstotal per call cannot distinguish “the model wrote a lot” from “the model thought a lot and wrote almost nothing”. Two calls with the same total are not the same call.
The second one is the dangerous one, because the failure is only visible if something explicitly reads the field that says the answer is incomplete.
What the Guard Needs, and What My Router Still Drops
Raising the ceiling is a mitigation, not a fix: any static number can be outgrown by a longer input.
The escalation itself already exists. The call site loops over two budgets and retries once:
for budget in (NOTE_MAX_TOKENS, NOTE_RETRY_MAX_TOKENS): # 8000, then 16000
result = call_llm("translate", messages, model=model, temperature=0.15,
timeout=300, max_tokens=budget, transport=transport, db=db)
try:
parsed = parse_model_json(result.get("text", ""))
break
except TranslateError as exc:
first_error = str(exc)
What it retries on is the whole point: the trigger is parse_model_json() raising, not a truncation flag. Truncation and malformed output take the same branch, so the second call is a bet that a bigger ceiling fixes both.
⚠ The field that would tell them apart never arrives. extract_text() in pipeline/llm_router.py returns choices[0].message.content and drops the rest of the response, so finish_reason does not reach that loop at all. The target is the same two calls with the gate moved up:
result = call_llm(..., max_tokens=NOTE_MAX_TOKENS)
if result.get("finish_reason") == "length": # needs the router to pass it through
result = call_llm(..., max_tokens=NOTE_RETRY_MAX_TOKENS)
A guard that reads a value nobody stored is not a guard — it is a comment.
The rule worth keeping: assert on finish_reason, not on whether the call came back. A pipeline that only checks whether JSON parsed can fail late with a misleading parse error whenever a note triggers heavy reasoning — and without finish_reason, it cannot tell truncation from malformed output.
Splitting the ledger row matters as much, and that part is still a plan. Recording prompt_tokens, reasoning_tokens, and output_tokens as separate columns would turn “why did this call cost 10,283 tokens and produce nothing usable” into a glance instead of an afternoon of replays.
🔍 View the replay harness used to compare the two ceilings (container exec, 2 calls, 4 printed fields)
docker exec -e NOTE=/notes/the-failing-note.zh.md -it "$CONTAINER" python - <<'PY'
import json
import os
from pathlib import Path
from pipeline.llm_router import resolve_chain, default_transport, _auth_headers
from pipeline.translate import (split_note, glossary_for, load_glossary,
mask_mermaid, system_prompt, note_user_prompt)
raw, data, body = split_note(Path(os.environ["NOTE"]).read_text(encoding="utf-8"))
glossary = glossary_for(body + " " + str(data.get("title", "")), load_glossary())
masked_body, _blocks = mask_mermaid(body)
messages = [{"role": "system", "content": system_prompt(glossary)},
{"role": "user", "content": note_user_prompt(data, masked_body, glossary)}]
candidate = resolve_chain("translate")[0][0]
transport = default_transport()
for ceiling in (8000, 30000):
payload = {"model": candidate["model"], "messages": messages,
"temperature": 0.15, "max_tokens": ceiling}
resp = transport.post(candidate["url"], headers=_auth_headers(candidate),
json=payload, timeout=300)
raw_body = resp.json() # raw response: extract_text() never runs
choice = raw_body["choices"][0]
print(ceiling,
choice["finish_reason"],
len(choice["message"]["content"]),
json.dumps(raw_body.get("usage")))
PY
At 30,000 the Body Came Back and the Ledger Made Sense
Same prompt, same model, one variable changed:
- 7,678 reasoning tokens / 318 output tokens at the live ceiling,
finish_reason=length, 1,417 characters cut inside a bullet. - 1,739 output tokens and 8,210 characters at 30,000,
finish_reason=stop, parsed with a 6,952-characterbody. - The two ledger totals, 10,283 / 10,112, stop looking contradictory: they were never the size of the answer, they were the size of the call.
What changed from this replay is not picking a magic ceiling, but measuring thinking overhead before sizing max_tokens — and then gating the retry on finish_reason, which is the half still owed.
Want a 24/7 bot or automation pipeline that never drops a lead?
Don't let customer inquiries slip away at midnight or on weekends. I build custom Telegram/WhatsApp AI assistants and deterministic workflows that connect directly to your catalogue, CRM, and order fulfillment.