JSONDecodeError: Unterminated string starting at
Cause: The JSON ends in the middle of a string, which with LLM output almost always means the reply hit its output-token limit before the object was finished.
Copy-paste fix
Check why the model stopped before you parse. A cut-off reply is a failed call, not bad JSON to repair.
import json
class TruncatedOutput(Exception):
pass
def parse_complete_json(text, finish_reason=None, stop_reason=None,
response_status=None, incomplete_reason=None):
if finish_reason == "length": # OpenAI Chat Completions
raise TruncatedOutput("hit max_tokens")
if response_status == "incomplete" and incomplete_reason == "max_output_tokens":
raise TruncatedOutput("hit max_output_tokens") # OpenAI Responses API
if stop_reason == "max_tokens": # Claude Messages API
raise TruncatedOutput("hit max_tokens")
return json.loads(text)
# On TruncatedOutput: retry once with a higher output limit,
# or ask for fewer items / shorter fields.
See what a bigger output limit costs on TokenCenter
What the error means
Python's json decoder raises Unterminated string starting at when a string opens with a quote and the text ends before it closes.
OpenAI's docs warn that JSON-mode content may be partially cut off when finish_reason="length", and the Responses API reports it as status: "incomplete" with reason max_output_tokens. On the Claude API the same case is stop_reason: "max_tokens".
Checklist
- Check finish_reason, stop_reason or response status on every structured reply.
- Size the output limit for your largest expected object, not the average one.
- Ask for fewer or shorter fields when objects run long, or page through results.
- Use Structured Outputs where supported, and still handle the incomplete case.
- Don't try to repair cut-off JSON by guessing the missing end.
Related
- JSONDecodeError: Expecting value
- finish_reason: "length" (reply cut off)
- Failure mode: Truncation and lost instructions
- Context planner: will your prompt fit the model?
- ModelRaters list: Best for coding