Practical technical guides / AI engineering

An Output Token Limit Cuts JSON Mid-Object: Detect the Stop Reason Before You Parse

A model that hits its output limit returns a successful response with JSON cut mid-object. Check finish_reason or stop_reason first, then retry, continue or split.

By Sandeep Belgavi · Published 2026-11-30

A model that hits its output limit returns a successful response with JSON cut mid-object. Check finish_reason or stop_reason first, then retry, continue or split.

A complete-looking response that is not complete

Every chat-style model API has an output limit per request: max_tokens, max_output_tokens, num_predict or similar. When generation reaches it, the model simply stops, often in the middle of a word, and the API returns a successful response. Nothing is raised. The only signal is a field that says why generation stopped, and code that goes straight from the response to json.loads never looks at it.

For structured output this produces two kinds of failure. The loud one is a parse error on a cut-off object, which at least fails visibly. The quiet one comes from "lenient" JSON repair, which closes the open brackets and returns a valid object that is missing data. A list of six order lines becomes a list of three, the schema validates, and the downstream system processes half an order.

This guide shows where each major API reports the reason, what a measured truncation looks like, how to choose a recovery, and how to budget output tokens so it happens less often. The companion example output_limit_stop_reason contains the checks and a recorded run against a local model.

Where each API says it stopped on the limit

These field names were checked against the provider SDK types on 30 November 2026: openai 3.60.0, anthropic 2.14.0 and google-genai 3.6.1, plus Ollama 0.40.18.

APIFieldValue that means "hit the output limit"
OpenAI Chat Completionschoices[i].finish_reasonlength
OpenAI Responsesstatus and incomplete_details.reasonincomplete and max_output_tokens
Anthropic Messagesstop_reasonmax_tokens (also model_context_window_exceeded for a full context window)
Geminicandidates[i].finishReasonMAX_TOKENS
Ollama native APIdone_reasonlength

Anthropic's stop-reason documentation separates the two limits. max_tokens means your requested limit was reached, and the recommendation is to raise it or continue the response. model_context_window_exceeded means the response filled the model's context window, and it says to treat the response as truncated. The distinction matters for recovery: more output budget cannot help when the context window is the limit.

Measured: JSON mode does not prevent truncation

The companion probe asked a local qwen2.5:0.5b-instruct model, through Ollama 0.40.18, for a JSON object listing six order lines, with JSON mode on, temperature 0 and a fixed seed. It made the same request through the native /api/chat endpoint and through the OpenAI-compatible /v1/chat/completions endpoint, with two output budgets.

EndpointOutput budgetStop reasonOutput tokensParses as JSON
Native /api/chat40length40No
OpenAI-compatible40length40No
Native /api/chat600stop255Yes
OpenAI-compatible600stop255Yes

With a 40-token budget, both endpoints returned text ending in "title": "The Great Gatsby", followed by a bare "qty. JSON mode constrains which tokens the model may produce. It does not make the model finish before the budget runs out. The complete answer needed 255 tokens, so the 40-token budget was never going to fit, and the stop reason said so on both endpoints. This is a small local model and one prompt. The point is the shape of the failure, not a rate.

Check the stop reason before parsing

def stop_info(provider, resp):
    if provider == "openai_chat":
        c = resp["choices"][0]
        return ("output" if c["finish_reason"] == "length" else None), c["message"].get("content") or ""
    if provider == "anthropic":
        text = "".join(b.get("text", "") for b in resp["content"] if b["type"] == "text")
        limit = {"max_tokens": "output", "model_context_window_exceeded": "context"}.get(resp["stop_reason"])
        return limit, text
    raise ValueError("unknown provider " + provider)

def decide(provider, resp, budget, cap, expected_items=None):
    limited, text = stop_info(provider, resp)
    if not limited:
        data = json.loads(text)
        if expected_items is not None and len(data.get("lines", [])) != expected_items:
            return {"action": "fail", "why": "complete JSON, wrong number of lines"}
        return {"action": "parse"}
    if limited == "context":
        return {"action": "split", "why": "the context window is full"}
    if budget * 2 <= cap:
        return {"action": "retry", "budget": budget * 2}
    return {"action": "split", "why": "a doubled budget exceeds the cap"}

The example applies the same rule to all five response shapes. A synthetic truncated response in the OpenAI Chat, OpenAI Responses and Gemini shapes, with a 400-token budget and a 4,000-token cap, gives "retry with 800", and the recorded Ollama response at 40 tokens gives "retry with 80". An Anthropic max_tokens stop at a 3,000-token budget gives "split", because doubling would exceed the cap. A model_context_window_exceeded stop gives "split" regardless of budget. A complete response with all six lines gives "parse". A complete response that stopped normally but contains only four of the six requested lines gives "fail": the stop reason was fine, and only the schema check catches it.

Why not repair the JSON?

The example includes a naive repair: drop the unfinished tail and close the open brackets. Applied to a response cut off in the fourth of six order lines, it returns valid JSON with 3 lines. Nothing about that object says it is incomplete. Repair is reasonable for display, such as rendering a partial streamed answer while it arrives. It is not acceptable for anything that will be executed or stored as the model's decision. If you must keep partial results, keep them labelled as partial and never pass them to a write path.

Choosing a recovery

  • Retry with a larger budget when the output limit was hit and a larger request still fits your cost and latency limits. It is simple and keeps the output in one piece. Cap the number of retries.
  • Continue the response when the output is long prose or a large document and regeneration is expensive. Anthropic's documentation shows continuation by sending the partial text back as the assistant message and adding a user message asking the model to continue from where it left off. It also notes that a truncated response containing an incomplete tool-use block must be retried with a higher limit rather than continued. Stitching continued JSON is fragile, because the continuation may restart the object or change formatting. Validate the joined result as strictly as a single response.
  • Split the task when the output is inherently large: ask for the order lines in pages of ten, or for one object per request. Splitting also keeps each request well away from the limit, which makes the other two recoveries rare.
  • Fail loudly when the response is complete but wrong for the schema, and treat that as an evaluation finding rather than a retry case.

Budgeting output tokens

Set the limit from the expected output, not from a habit. Measure the token count of real outputs for each task, for example from the usage fields every API returns, and set the limit at a high percentile plus a margin. The probe's complete answer used 255 tokens; a budget of 40 had no chance, and a budget of 4,000 would have allowed a runaway answer to cost sixteen times as much. Reasoning models add a further complication: on some APIs hidden reasoning tokens count against the same output limit, so a budget that fits the visible answer can still stop before the answer starts. Check the provider's usage breakdown for reasoning tokens and size the limit from the total.

Failure modes

  • Checking the stop reason only in the streaming path. The final event of a stream carries the reason too, and it is easy to drop. Assert on it in both paths.
  • Treating length as an error and retrying forever. If the task does not fit, retries only multiply cost. Escalate to splitting after one retry.
  • Tool calls cut off mid-arguments. A truncated tool call can look like a valid call with missing fields if a library fills defaults. Validate tool arguments against the schema with no defaults applied.
  • Logs that omit the stop reason. Without it, a spike in half-processed orders looks like a model regression. Record the stop reason and output token count with every call.

Verification

Run the companion tests. They check every provider shape, assert that each truncated text fails to parse, that a context-window stop is never retried with more output, that a short but complete response is rejected by the schema check, that naive repair keeps 3 of 6 lines, and that the recorded Ollama run shows length at 40 tokens and stop at 600. In production, alert on the share of calls that end on a limit, per task; it should be close to zero once budgets fit the task.

Primary references and authorship

Sources checked 2026-11-30. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/output_limit_stop_reason. Views are my own and do not represent any employer, past or present.