If your LLM call returns finish_reason='length' with content: null, the model used its entire max_tokens budget before writing a single visible token. On reasoning-enabled models such as Claude Sonnet 5 via OpenRouter, reasoning tokens count against that budget. In our 65 production runs, 95 of 97 failed JSON calls disappeared after one change to the request.

The system is a daily LinkedIn auto-poster we run in production. Every morning it sends all of the day's candidate drafts to anthropic/claude-sonnet-5 through OpenRouter and asks for a JSON object scoring each one. A second call then rewrites the winning post's hook. The model is asked for JSON in the prompt and the reply is parsed defensively. Below is every failure from 2026-08-28 to 2026-11-23, counted from the daemon log.

What does finish_reason='length' with null content actually mean?

It means generation stopped because the token budget ran out, and none of that budget reached the visible output. With reasoning enabled, the model's hidden reasoning counts against max_tokens. If it reasons for 1,500 tokens on a 1,500-token budget, you get a valid HTTP 200, an empty content, and finish_reason='length'. Nothing was refused and nothing crashed.

This is the line our daemon logged 39 times:

[WARNING] zeroday_select: OpenRouter call (model=anthropic/claude-sonnet-5) attempt 1/3 failed:
Model returned empty/null content (finish_reason='length', refusal=None)

OpenRouter's parameter reference states that for reasoning models, max_tokens covers reasoning and visible output together on most providers. A small limit can therefore be used up entirely by reasoning. Anthropic's own API has the same structure: the extended thinking budget must be smaller than max_tokens, because both come from the same pool.

The usage objects from calls that succeeded show how much of the budget reasoning was taking. Before the fix, our selector used 271, 800 and 963 reasoning tokens on three successful runs. On seven others it used 0. Reasoning length varied from run to run, which is why the failure was intermittent rather than constant, and why it took so long to recognise as a budget problem.

What did every failure look like across 65 production runs in 2026?

Over 65 selection runs we logged 97 failed calls in five error shapes. 93 were what running out of tokens looks like: null content (39) or JSON cut off partway (54). Two "Expecting value" errors also vanished with the fix. Only two, both after it, were real formatting mistakes, and one retry fixed each.

Error string (as logged)Attempt 1Attempt 2Attempt 3TotalAfter fix
Expecting ',' delimiter161313420
Model returned empty/null content (finish_reason='length')171111390
Unterminated string starting at156120
Expecting value02020
Expecting property name enclosed in double quotes20022
Total363130972

Each run counts as one failure if all three attempts fail. Before the fix there were 40 runs, and 30 of them failed every attempt, a 75% run failure rate. After the fix there have been 25 runs and none have failed every attempt. Every failed attempt came from the selector call. The hook-rewrite call never failed in the daemon.

The two remaining failures look different. After the fix, Expecting property name enclosed in double quotes: line 35 column 5 appeared twice. That is what a trailing comma after the last field of an object produces. We reproduced the exact line and column locally. A comma in the wrong place is random, so a second attempt fixed it both times.

Why does truncated JSON report "Expecting ',' delimiter: line 24 column 6"?

Because our fallback parser was hiding the real error. When json.loads failed, it took the outermost {...} with a greedy regex and parsed that instead. On a truncated reply, that regex stops at the last complete candidate object. The reported error then points to the end of that object, not to where the output was actually cut off.

The shipped parser:

def _strip_code_fences(text: str) -> str:
    """Robustly strip markdown code fences (```json ... ``` or ``` ... ```)
    that models sometimes wrap JSON output in despite instructions not to."""
    text = text.strip()
    if text.startswith("```"):
        text = re.sub(r"^```[a-zA-Z]*\n?", "", text)
        text = re.sub(r"\n?```$", "", text)
    return text.strip()


def _parse_json_response(content: str) -> dict:
    cleaned = _strip_code_fences(content)
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError:
        # Last-resort recovery: extract the outermost {...} block.
        match = re.search(r"\{.*\}", cleaned, re.DOTALL)
        if match:
            return json.loads(match.group(0))
        raise

Each scored candidate in our schema takes exactly 11 lines. The logged positions were always line 13, line 24 or line 35, all at column 6, which is 11 lines apart. To confirm, we truncated a 6-entry reply at every possible character and parsed each version with the shipped parser. Cutting after entry 0, 1 and 2 gave Expecting ',' delimiter: line 13 column 6, then line 24, then line 35. These are the same positions as in the production log.

The Unterminated string starting at errors are the opposite case. The output was cut off inside the first candidate object, before any closing brace existed, so the regex found nothing to match and the original json.loads error came through. In both cases the true cause was finish_reason='length'. We never logged it for those calls, because the code only checked finish_reason when content was empty.

This is the general weakness of the prompt-for-JSON approach. JSON output fails in confusing ways when nothing is checking the output, which is one reason we argued an LLM should write code against a toolkit rather than fill in a JSON spec for anything with structure.

Why did three retries with exponential backoff not fix it?

Because running out of tokens is not a temporary error. Retrying the same request with the same max_tokens and the same prompt usually runs out at the same place again. Before the fix, our 3-attempt, 2s/4s backoff rescued only 4 of 34 runs whose first attempt failed. After the fix, it rescued both runs that needed it.

Splitting the pre-fix runs by the number of candidates in the prompt shows the cause directly:

Candidates in promptRuns (pre-fix)Fell back after 3 attempts
1–340
476
586
61513
7–965

None of the small prompts failed, and 83% of the large ones did. After the fix, with reasoning off, the selector writes between 119 and 168 visible tokens per candidate, about 155 on average. That is roughly 950 tokens for six candidates and 1,400 for nine. The original budget was 1,500. Six candidates plus a few hundred reasoning tokens exceeds it.

Retries are the right tool for the two post-fix trailing-comma failures, which are random. They are the wrong tool for a budget that is too small. If your retry loop treats both kinds of error the same way, you pay for three calls that were never going to succeed.

What was the actual fix, and what did it cost?

We changed two lines. Reasoning is now explicitly disabled in the request, and both max_tokens values were doubled: selector from 1,500 to 3,000, hook rewrite from 1,200 to 2,400. Since 2026-10-24 there have been 25 runs with no fallbacks. Average cost per run went down from $0.0252 to $0.0238.

payload = {
    "model": model,
    "messages": [...],
    "temperature": temperature,
    "max_tokens": max_tokens,
    # Sonnet 5 reasons by default and reasoning tokens count against max_tokens;
    # at 1500 the whole budget went to reasoning -> empty content, finish_reason=length
    # (observed 2026-10-23). Structured JSON output doesn't need it.
    "reasoning": {"enabled": False},
    "usage": {"include": True},
}

OpenRouter's reasoning-tokens guide documents the reasoning object. Setting enabled: false is how you turn off reasoning for a model that has it on by default. We considered keeping reasoning on with a separate reasoning budget and decided against it. Scoring each draft against seven fixed criteria is a structured task with no multi-step problem to work through. Reasoning also made output length unpredictable, and predictable length is exactly what a fixed budget needs.

The cost figures come from OpenRouter's usage object on successful runs:

Per run (successful)SelectorHook rewriteTotal
Before fix (10 runs, reasoning on)$0.0139$0.0113$0.0252
After fix (25 runs, reasoning off)$0.0159$0.0079$0.0238

The selector cost per run went up because post-fix runs scored more candidates, and the pre-fix runs that succeeded were mostly the small ones. The hook rewrite got 30% cheaper, because it was spending an average of 327 reasoning tokens per call that it didn't need. Our first smoke test, with three candidates, cost $0.0163 for both calls together.

What should a hardened LLM JSON call look like?

Check finish_reason before parsing. Handle 'length' as its own error: raise the budget instead of sleeping and sending the same request. Remove any greedy regex fallback that turns truncation into a misleading parse error. Log the last part of the raw output. Set the budget from the size of the input, not a fixed number.

Here is the version we moved to. We tested it against mocked OpenRouter responses for a null-content truncation, a partial-JSON truncation and a fenced success:

class TruncatedOutput(RuntimeError):
    """finish_reason='length': the budget ran out. Retrying the identical request is pointless."""


def call_llm_json(api_key: str, model: str, system_prompt: str, user_content: str,
                  temperature: float, max_tokens: int) -> tuple[dict, dict]:
    payload = {
        "model": model,
        "messages": [{"role": "system", "content": system_prompt},
                     {"role": "user", "content": user_content}],
        "temperature": temperature,
        "max_tokens": max_tokens,
        "reasoning": {"enabled": False},   # reasoning tokens are billed against max_tokens
        "usage": {"include": True},
    }
    last_error = None
    for attempt in range(1, MAX_ATTEMPTS + 1):
        content = ""
        try:
            resp = requests.post(OPENROUTER_URL, json=payload, timeout=90,
                                 headers={"Authorization": f"Bearer {api_key}"})
            resp.raise_for_status()
            result = resp.json()
            choice = result["choices"][0]
            finish_reason = choice.get("finish_reason")
            content = (choice.get("message") or {}).get("content") or ""
            usage = result.get("usage", {})

            # Check WHY generation stopped before touching the content.
            if finish_reason == "length":
                details = usage.get("completion_tokens_details") or {}
                raise TruncatedOutput(
                    f"finish_reason='length' at max_tokens={payload['max_tokens']} "
                    f"(completion={usage.get('completion_tokens')}, "
                    f"reasoning={details.get('reasoning_tokens')}, visible_chars={len(content)})"
                )
            if not content:
                raise RuntimeError(f"empty content, finish_reason={finish_reason!r}")

            # No greedy {.*} rescue: it turns a truncation into a misleading
            # "Expecting ',' delimiter" at the last complete object.
            return json.loads(strip_code_fences(content)), usage

        except TruncatedOutput as e:
            last_error = e
            logger.warning(f"attempt {attempt}/{MAX_ATTEMPTS}: {e}")
            if payload["max_tokens"] >= MAX_TOKENS_CEILING:
                break
            payload["max_tokens"] = min(payload["max_tokens"] * 2, MAX_TOKENS_CEILING)
        except (requests.RequestException, json.JSONDecodeError, RuntimeError) as e:
            last_error = e
            logger.warning(f"attempt {attempt}/{MAX_ATTEMPTS}: {e} | tail={content[-120:]!r}")
            if attempt < MAX_ATTEMPTS:
                time.sleep(BACKOFF_BASE_SECONDS ** attempt)
    raise RuntimeError(f"LLM JSON call failed after {attempt} attempts: {last_error}")

The budget is calculated from the number of candidates, using the per-candidate figure measured above with 2x headroom:

def selector_budget(n_candidates: int) -> int:
    # ~155 visible tokens per scored candidate in our logs (range 119-168), 2x headroom.
    return 400 + 320 * n_candidates

Strict JSON-schema modes don't solve this either. Constrained decoding makes sure every token produced fits the schema, but it cannot add tokens after the budget is used up. A response cut off at max_tokens is still cut off. The finish_reason check is what makes either approach safe.

Why compute weighted scores in Python instead of trusting the model?

Because ranking decisions should not depend on the model doing arithmetic correctly. The model returns raw 0–10 scores per criterion and a short rationale. Python applies the weights, sums them and picks the highest total. The weights live in one constant that the prompt only describes, so they can be checked and changed without editing the prompt.

WEIGHTS = {"criterion_a": 0.25, "criterion_b": 0.20, ...}   # sums to 1.0
assert abs(sum(WEIGHTS.values()) - 1.0) < 1e-9

for entry in parsed["scores"]:
    entry["weighted_total"] = round(
        sum(float(entry.get(k, 0)) * w for k, w in WEIGHTS.items()), 4
    )
winner = max(parsed["scores"], key=lambda e: e["weighted_total"])

This also shortens the output. Asking the model to show its arithmetic adds tokens to every candidate entry. In a pipeline whose main failure was running out of tokens, that length counts.

What happened when all three attempts failed?

A deterministic fallback posted the newest candidate's original draft, with no scoring and no hook rewrite. That happened 30 times, and the daily post went out every day. That reliability is also why the problem lasted as long as it did. A fallback that always succeeds stops anyone from noticing that 75% of runs are failing.

[WARNING] zeroday_select: zeroday_select pipeline failed, falling back to newest candidate uid=7480:
OpenRouter call (model=anthropic/claude-sonnet-5) failed after 3 attempts:
Model returned empty/null content (finish_reason='length', refusal=None)

We would build the fallback the same way again, since a missed daily post is worse than an unranked one. What was missing was an alert on the fallback rate. One warning per day in a log of 89,000 lines is easy to miss. This kind of slow decline is what we described in why AI agents work in staging but degrade in production: it never fails loudly, so nobody gets paged.

What's the short version?

finish_reason='length' with null content is a token budget problem. On reasoning models the budget includes hidden reasoning, so null replies and truncated JSON are one problem showing up two ways. In our 65 runs, retries rescued 4 of 34 failing runs, while disabling reasoning and doubling the budget fixed 95 of 97 failures. Check finish_reason first and alert on fallback rate.