Skip to content

finish_reason: "length"

Cause: The model stopped because it reached the maximum number of output tokens set in the request, so the reply is incomplete.

Copy-paste fix

Treat a length stop as an error. Either retry with a higher limit, or keep the partial text and ask the model to continue.

def complete(client, model, messages, max_completion_tokens=800, max_continues=2):
    parts = []
    for _ in range(max_continues + 1):
        resp = client.chat.completions.create(
            model=model, messages=messages,
            max_completion_tokens=max_completion_tokens)
        choice = resp.choices[0]
        parts.append(choice.message.content or "")
        if choice.finish_reason != "length":
            return "".join(parts)
        messages = messages + [
            {"role": "assistant", "content": choice.message.content or ""},
            {"role": "user", "content": "Continue exactly where you stopped. "
                                        "Do not repeat anything."},
        ]
    raise RuntimeError("Reply still cut off after continuing; raise the limit "
                       "or ask for a shorter answer")

Check what a higher output limit costs on TokenCenter

What the error means

In OpenAI's API spec, finish_reason is length “if the maximum number of tokens specified in the request was reached.” The Claude API reports the same case as stop_reason: "max_tokens", and its docs say to raise max_tokens or continue the response.

Anthropic's docs also note that Claude 4.6 and later models don't accept a prefilled last assistant message, so continue with a new user turn instead.

Checklist

  1. Check finish_reason (or stop_reason) on every call, not just in tests.
  2. Log how often replies stop on length per feature.
  3. Don't continue structured output (JSON, code) by stitching; retry with a higher limit instead.
  4. Ask for shorter answers when you don't need long ones.
  5. Remember a higher output limit also needs room in the context window.

Related

Sources

All guides · All errors