Plain Reckoner
English

← Blog

Plain Reckoner Team · Release date:

Source checked:

Fix “Could not parse response content as the length limit was reached”

What does “Could not parse response content as the length limit was reached” mean? The model ran out of output tokens before it finished writing your JSON, so the OpenAI SDK refused to parse the half-written text. Raise the output limit or ask for less output, and read the partial text and token count from the exception before you retry.

That is the short answer. The longer one is that this helpful error only exists in some code paths. We pointed six structured-output libraries at a local mock server that returns the same cut-off JSON, and recorded what each one did. Of 45 truncated cases, 11 produced an error that names the output limit, 28 produced a generic parsing or validation error, and 6 produced no error at all: the call returned None or null. The table, the code and the recorded results are below.

What the error means

The message is a fixed string in the OpenAI Python SDK. It belongs to LengthFinishReasonError, which the SDK raises from its parse() helpers when a Chat Completions choice comes back with finish_reason set to length. When the response includes token usage, the SDK appends it to the message, which is why the error usually ends with something like CompletionUsage(completion_tokens=32, prompt_tokens=42, total_tokens=74).

finish_reason: "length" means generation stopped because it hit a token limit: the max_tokens or max_completion_tokens you sent, or the model’s own maximum. It is not a network failure and it is not malformed output in the usual sense. The JSON was valid as far as it went. It simply stops in the middle, for example:

{"invoice_id": "INV-2041", "customer": "Northwind Traders", "total": 1840.5, "line_items": [{"description": "Annual support plan", "amount": 1500.0}, {"description": "Onboar

Structured Outputs guarantees that a completed response matches your schema. It cannot guarantee that the response completes; OpenAI’s guide lists reaching a max tokens limit among the cases your application still has to handle. The SDK raises instead of handing you a partial object because a partial object can look plausible while missing the fields that matter.

Read the partial output and token count from the exception

A common complaint about this error is that the response seems to be gone. In the Python SDK version we tested it is not: the exception carries the whole completion on error.completion.

import openai

try:
    result = client.chat.completions.parse(
        model=MODEL, messages=messages, response_format=Invoice
    )
except openai.LengthFinishReasonError as error:
    choice = error.completion.choices[0]
    print("finish_reason:", choice.finish_reason)
    print("completion_tokens:", error.completion.usage.completion_tokens)
    print("partial text ends with:", repr(choice.message.content[-40:]))

Recorded output from our run against the mock, with openai 3.60.0:

finish_reason: length
completion_tokens: 32
partial text ends with: 'mount": 1500.0}, {"description": "Onboar'

Two numbers here tell you what to change. If completion_tokens equals the limit you set, your limit is too low for this output. If the text stops far short of what you expected while the token count is high, something other than visible JSON consumed the budget. OpenAI’s API reference defines max_completion_tokens as an upper bound that includes both visible output tokens and reasoning tokens, so a reasoning model can spend part of the limit before it writes any JSON. Compare completion_tokens with the length of the partial text before choosing a fix.

The Node SDK behaved differently. In openai 7.65.0 for Node, the same error had only message and stack; there was no completion attached. To keep the partial text there, call create() and inspect the response yourself, or use the Responses API and check status.

Fix it in this order

1. Find out what limit you actually sent. Look for max_tokens, max_completion_tokens or max_output_tokens in your call, in the framework’s model settings, and in any gateway in front of the provider. Frameworks often set a default you did not choose. Log the request once and read it.

2. Raise the limit if the output legitimately needs the room. A schema with a long list or free-text fields can need far more tokens than a test input suggests. Size the limit against your longest realistic input, not the average one.

3. Ask for less output. If you cannot raise the limit, reduce what the model has to write: drop fields nobody reads, cap list lengths in the prompt and the schema, shorten free-text fields, or split one large extraction into several calls over smaller pieces of input. Splitting also makes a later failure cheaper, because you only repeat one piece.

4. Do not retry the identical request. The same input with the same limit will usually be cut off at the same place. A retry is only useful after you change the limit, the schema or the input. This matters because some libraries retry for you, as the results below show.

5. Decide what to do with the partial text. Usually the right answer is to discard it. If you want to salvage completed list items, parse the partial text with a tolerant parser and mark the result as incomplete in your own data, so that a truncated record is never confused with a full one.

The same truncation looks different in every library

We built a mock server that imitates the OpenAI Chat Completions and Responses response formats and returns one invoice four ways:

For tool-calling libraries, the mock returns the same text as the tool call’s arguments. In the control case, all 15 calls returned the full object. The truncated cases are below. “Requests” is the number of HTTP requests the mock received for a single call.

Library and call Cut JSON, length Valid JSON, field missing, length Cut JSON labelled stop
openai 3.60.0 (Python), create() + json.loads JSONDecodeError ValidationError JSONDecodeError
openai 3.60.0 (Python), chat.completions.parse LengthFinishReasonError LengthFinishReasonError ValidationError
openai 3.60.0 (Python), responses.parse ValidationError ValidationError ValidationError
instructor 1.18.0, create(response_model=…) IncompleteOutputException IncompleteOutputException InstructorRetryException, 4 requests
langchain-openai 1.8.5, with_structured_output(method="json_schema") LengthFinishReasonError LengthFinishReasonError ValidationError
langchain-openai 1.8.5, with_structured_output(method="function_calling") no error, returns None ValidationError no error, returns None
pydantic-ai-slim 2.76.0, Agent(output_type=…) IncompleteToolCall UnexpectedModelBehavior, 2 requests UnexpectedModelBehavior, 2 requests
openai 7.65.0 (Node), chat.completions.parse LengthFinishReasonError LengthFinishReasonError SyntaxError
openai 7.65.0 (Node), responses.parse no error, output_parsed is null no error, output_parsed is null SyntaxError
ai 7.0.183 + @ai-sdk/openai 4.0.125, generateObject and generateText with Output.object NoObjectGeneratedError NoObjectGeneratedError NoObjectGeneratedError
Grid of fifteen structured-output calls against three truncated responses: eleven cells name the output limit, twenty-eight show a generic parse error and six show no error.
Generated from the recorded results. Green names the output limit, amber is a generic parse error, red is no error.

The LangChain rows with include_raw=True and the four AI SDK variants are in the downloadable results; they are summarized here to keep the table readable.

Four results worth acting on

LangChain’s function-calling method returned None. With with_structured_output(Invoice, method="function_calling"), a truncated tool call produced no exception. The chain returned None. Code that goes on to read result.customer fails later with an AttributeError that says nothing about tokens; code that checks if result: may quietly skip the record. With include_raw=True the result was {"parsed": None, "parsing_error": None}, so the parsing error field did not flag it either. The only signal was finish_reason: "length" in the raw message’s response_metadata. The json_schema method raised LengthFinishReasonError for the same response.

The Responses API helpers did not raise the length error. In Python, responses.parse raised a Pydantic ValidationError about invalid JSON for an incomplete response. In Node, responses.parse returned normally with output_parsed: null, status: "incomplete" and incomplete_details.reason: "max_output_tokens". If you moved from Chat Completions to the Responses API and kept an except LengthFinishReasonError handler, it did not fire in our test. Check response.status instead.

Some libraries repeated the request. When the cut-off JSON was labelled stop, Instructor, which has a dedicated exception for truncated output when the limit is reported, sent 4 requests before raising and Pydantic AI sent 2. Pydantic AI also sent 2 requests in the valid-but-incomplete case, even though the response said length, and the final UnexpectedModelBehavior error did not mention the limit. A validation retry makes sense for a model that wrote a wrong value. It does not help when the output is being cut at the same point each time, and each attempt is billed.

The AI SDK kept the evidence but used a generic name. NoObjectGeneratedError does not say “length” in its message, but its documented properties include the finish reason, and in our run the error object carried finishReason: "length" and the partial text. Read those two properties in your handler rather than relying on the message.

Check the stop reason before you parse

The results point to one habit that works across libraries: look at why generation stopped before you look at what it wrote. A parser can only tell you that text is broken. It cannot tell you that text is complete, as the valid-but-incomplete case shows: that JSON parses without complaint.

The download includes a small guard that works on the plain response dictionary, for both API shapes:

def require_complete(payload):
    """Return the output text, or raise TruncatedOutput when an output limit was reported."""
    if "choices" in payload:  # Chat Completions
        choice = payload["choices"][0]
        message = choice["message"]
        calls = message.get("tool_calls") or []
        text = calls[0]["function"]["arguments"] if calls else (message.get("content") or "")
        if choice.get("finish_reason") == "length":
            raise TruncatedOutput("finish_reason=length", text, payload.get("usage"))
        return text
    ...  # Responses: raise when payload["status"] == "incomplete"

Its six offline tests pass in our run, including the valid-but-incomplete case and a truncated tool call. In a framework, apply the same idea at whatever point you can see the raw response: response_metadata["finish_reason"] in LangChain with include_raw=True, error.finishReason in the AI SDK, response.status in the Responses API.

When the server says “stop” but the JSON is cut

The last column of the table is the uncomfortable one. If the response claims a normal stop, no library in our test could name the real cause. Every one fell back to a parse or validation error, and two retried.

We did not measure how often this happens, and we are not claiming that any particular provider does it. It is the case to plan for if a proxy, gateway or OpenAI-compatible server sits between you and the model, because your code then depends on that layer passing the stop reason through. The guard above cannot detect it either; one of its tests documents that limit. What you can do is treat “invalid JSON that ends mid-value” as a possible truncation in your logs, record the completion token count next to it, and compare that count with your configured limit.

What this test does not show

This is a test of client-library behavior against a mock, on one day, with pinned versions. It does not measure how often any model or provider truncates output. A real provider may send fields the mock does not, and a library may behave differently with them. Streaming was not tested; the SDK source also raises LengthFinishReasonError from its streaming helper, but we did not exercise that path. Anthropic, Gemini and other provider SDKs were not tested. Libraries change quickly: rerun the kit after upgrading and compare the new table with this one before relying on any row.

Run it yourself

The kit needs Python and Node but no API key and no network access to a provider.

python3 -m venv venv && ./venv/bin/pip install -r requirements.txt
npm install
./venv/bin/python mock_server.py 8765 &
./venv/bin/python run_python.py 8765
node run_node.mjs 8765
./venv/bin/python build_summary.py
./venv/bin/python -m unittest test_guard -v

results-python.json and results-node.json hold the 60 recorded cases behind the table, environment.txt lists the exact versions, and build_summary.py regenerates the table and chart from those files. If your versions give a different result, the difference is the useful part: it tells you which of your error handlers still match what the library does.

Source checked November 27, 2026: OpenAI Python SDK exception source · OpenAI Structured Outputs guide. Tested November 27, 2026 against a local mock server with the versions listed in the download; no provider was contacted and no model was evaluated. The test code and this article were prepared with AI assistance, and every figure comes from the recorded run.

Download the test kit and recorded results ↗ · GitHub ↗