ChatGPT API Token Limit: Fix Truncated Long JSON Responses
The ChatGPT API token limit includes a separate output cap, so long JSON replies get cut off with finish_reason 'length' and fail to parse. Check it, budget tokens, chunk the input, and keep the JSON small.
- Always check choices[0].finish_reason before json.loads; 'length' means the output was cut off and the JSON is incomplete.
- The context window is shared by input and output, and the output cap is a separate, usually smaller limit.
- Chunk long text into 1,500 to 3,000 token pieces, rewrite each in its own call, and merge in code.
- Keep JSON for small metadata and return long bodies as plain text or per chunk, which cuts escaping and truncation risk.
- Structured Outputs guarantees valid syntax only when the model finishes; a length cutoff still breaks it.
Why does the ChatGPT API token limit cut off long JSON?
Three separate limits sit behind the ChatGPT API token limit, and people usually blame the wrong one. The context window holds input plus output together. The output cap (max_tokens, or max_completion_tokens on newer models) limits only what the model writes. A third, softer limit is the model's own habit of stopping or compressing early.
When generation reaches the output cap, the API stops mid-token stream and returns finish_reason 'length'. The text is simply cut off, so a JSON string is left with no closing quote, bracket or brace. json.loads then fails with an error like 'Unterminated string' or 'Expecting , delimiter'.
A long input makes this worse. If the context window is 128k tokens and you send 120k tokens, only about 8k remain for output, whatever the output cap says.
| Limit | What it covers | Typical symptom when exceeded |
|---|---|---|
| Context window | Input + output tokens in one request | 400 error, or output squeezed to almost nothing |
| Output cap (max_completion_tokens) | Tokens the model may generate | finish_reason 'length', cut-off JSON |
| Your own max setting | Whatever value you pass | Truncation earlier than the model needs |
| Model's natural length | How much it chooses to write | Short, summarised output with finish_reason 'stop' |
| Rate limits (TPM/RPM) | Tokens and requests per minute | 429 errors, not truncation |
How do I detect truncation before parsing the JSON?
Read finish_reason on every response. 'stop' means the model finished naturally, 'length' means it hit a token limit, and 'content_filter' means the output was withheld. Only parse on 'stop'.
Newer models may also return a refusal field with Structured Outputs, so check that as well rather than assuming content is present.
import json
from openai import OpenAI
client = OpenAI()
class TruncatedError(Exception):
pass
def call_json(messages, max_out=4000, model="gpt-4o"):
r = client.chat.completions.create(
model=model,
messages=messages,
max_completion_tokens=max_out,
response_format={"type": "json_object"},
)
choice = r.choices[0]
if choice.finish_reason == "length":
raise TruncatedError(f"cut off at {r.usage.completion_tokens} tokens")
if choice.message.refusal:
raise ValueError(choice.message.refusal)
return json.loads(choice.message.content)How do I budget tokens with tiktoken before sending?
Count input tokens first so you stay inside the ChatGPT API token limit, then compute what is left. The context window minus input minus a safety margin gives the room for output, and you take the smaller of that and the model's output cap.
Rewriting usually produces about as many tokens as it reads, so a 6,000 token input needs at least 6,000 output tokens plus JSON overhead. If that exceeds the output cap, one call cannot work and you must chunk.
Non-English text costs more tokens per word, sometimes two to three times as many as English, so measure instead of estimating from word counts.
import tiktoken
CONTEXT = 128_000
OUTPUT_CAP = 16_384
def budget(text, system, model="gpt-4o", margin=500):
try:
enc = tiktoken.encoding_for_model(model)
except KeyError:
enc = tiktoken.get_encoding("o200k_base")
n_in = len(enc.encode(text)) + len(enc.encode(system)) + margin
room = min(CONTEXT - n_in, OUTPUT_CAP)
need = int(len(enc.encode(text)) * 1.2) # rewrite ~ same length + overhead
return {"input": n_in, "room": room, "needed": need, "fits": need <= room}Why does the model return very short content for long input?
When finish_reason is 'stop' but the text is far shorter than the source, the model chose to condense. Models are trained to give answers of moderate length, and in practice they rarely write more than a few thousand tokens in a single reply, even when the cap is much higher.
Raising max_tokens does not fix this, because the cap is a ceiling and not a target. Ask for length explicitly: 'Rewrite every paragraph. Keep all details. Output must be roughly the same length as the input. Do not summarise or skip sections.'
Smaller inputs help most. A model rewriting 2,000 tokens is far more faithful than one rewriting 20,000, which is why chunking is the main fix.
How do I process a long article with chunking?
Split on paragraph boundaries until each chunk reaches a token target, usually 1,500 to 3,000 tokens. Rewrite each chunk in its own call with the same system prompt, then join the results in code.
Keep the JSON small. Ask for metadata such as title, summary and tags in one cheap call, and get the body as plain text per chunk. This avoids escaping newlines and quotes inside a giant JSON string, and a failure affects one chunk instead of the whole article.
- Count tokens with tiktoken and split on blank lines, packing paragraphs up to about 2,500 tokens.
- Optionally carry a short tail (one or two sentences) of the previous chunk, or a running summary of 100 to 200 tokens, for continuity. Mark it as context only, not to be rewritten.
- Send each chunk with an identical system prompt and a max_completion_tokens of about twice the chunk size.
- Check finish_reason on each result. On 'length', split that chunk in half at a paragraph break (or the midpoint if there is none) and retry. After three levels of splitting, raise an error instead of returning cut-off text.
- Run chunks in parallel with a small thread pool, retry 429 and 5xx errors with exponential backoff, and merge in original order.
import time, random
import tiktoken
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError, APIError
client = OpenAI()
enc = tiktoken.get_encoding("o200k_base")
SYSTEM = "Rewrite the text in clear, plain English. Keep every fact and paragraph. Do not summarise. Return only the rewritten text."
class TruncatedError(Exception):
pass
def chunk(text, target=2500):
out, cur, n = [], [], 0
for p in text.split("\n\n"):
t = len(enc.encode(p))
if cur and n + t > target:
out.append("\n\n".join(cur)); cur, n = [], 0
cur.append(p); n += t
if cur: out.append("\n\n".join(cur))
return out
def rewrite(part, depth=0):
for attempt in range(5):
try:
r = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": part}],
max_completion_tokens=6000)
break
except (RateLimitError, APIError):
time.sleep(2 ** attempt + random.random())
else:
raise RuntimeError("retries exhausted")
c = r.choices[0]
if c.finish_reason == "length":
if depth >= 3:
# never return cut-off text as if it were complete
raise TruncatedError("chunk still truncated after 3 splits")
mid = len(part) // 2
cut = part.rfind("\n\n", 0, mid) # -1 when there is no blank line
if cut <= 0:
cut = mid
left = part[:cut]
right = part[cut:].lstrip("\n") # drop the leading separator
return rewrite(left, depth + 1) + "\n\n" + rewrite(right, depth + 1)
return c.message.content
def rewrite_article(text):
with ThreadPoolExecutor(max_workers=4) as ex:
return "\n\n".join(ex.map(rewrite, chunk(text)))How do I get valid JSON metadata with Structured Outputs?
Use a strict schema for the small part only. Pydantic validates the result, and the SDK's parse helper raises clearly when output is incomplete.
The full pipeline then returns a dict with the metadata from the schema call and the body from the chunk merge, so no long text is ever inside a JSON field.
from pydantic import BaseModel
class Meta(BaseModel):
title: str
summary: str
tags: list[str]
def get_meta(article_head):
r = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[{"role": "system", "content": "Extract metadata."},
{"role": "user", "content": article_head}],
response_format=Meta,
max_completion_tokens=500)
c = r.choices[0]
if c.finish_reason == "length":
raise RuntimeError("metadata truncated")
return c.message.parsed
def pipeline(text):
meta = get_meta(text[:12000])
return {**meta.model_dump(), "body": rewrite_article(text)} What if I still need a continuation or JSON repair?
Continuation works best for plain text. Append the partial reply as an assistant message, add a user message such as 'Continue exactly where you stopped. Do not repeat anything', and concatenate. Expect occasional duplicated sentences or style drift, so trim overlap in code.
Do not feed the broken response into a fresh request and ask the model to fix it. The history plus the partial output consumes the context again, and the model hits the same cap while regenerating it. For JSON, continuation is fragile because the model may restart the object or alter the structure.
As a last resort, the json-repair library can close open strings and brackets, and streaming lets you parse partial output incrementally. Treat repaired data as incomplete: the missing tail is gone, and repair hides data loss.
Using a newer model with a 128k context and 16k or more output tokens widens the headroom. gpt-3.5-turbo is legacy and has much tighter limits.
def continue_text(messages, model="gpt-4o", max_rounds=4):
parts = []
for _ in range(max_rounds):
r = client.chat.completions.create(
model=model, messages=messages, max_completion_tokens=4000)
c = r.choices[0]
parts.append(c.message.content)
if c.finish_reason != "length":
break
messages = messages + [
{"role": "assistant", "content": c.message.content},
{"role": "user", "content": "Continue exactly where you stopped. Do not repeat anything."}]
else:
raise TruncatedError("still cut off after max_rounds")
return "".join(parts)Common questions
Does a higher max_tokens give me longer output?
Not by itself. It raises the ceiling, but the model decides how much to write, and it often stops or condenses well before the cap. State the required length and coverage in the prompt, and split the input.
Why does json.loads fail even with response_format set?
Most likely the response ended with finish_reason 'length', so the JSON is cut off. JSON mode and strict schemas guarantee syntax only when the model completes. Check finish_reason first and handle a refusal field.
How big should each chunk be?
Between 1,500 and 3,000 input tokens works well for rewriting, since the output is about the same size and fits comfortably under the output cap. Split on paragraph or heading boundaries, and add a small overlap or running summary if the text needs continuity.
Why do non-English texts hit the limit sooner?
Tokenizers split many languages into more tokens per word than English, so the same content uses more of both the input and output budget. Measure with tiktoken on the real text and use smaller chunks.