← Blog

Claude API Output Token Limit Handling Guide

2026-11-14 · 5 min read · SubToAPI Team

Every Claude API response can be cut short in two different ways, and confusing them is the single biggest source of "why did my output stop halfway through" bugs. The first is max_tokens, a parameter you set yourself that caps how many tokens Claude is allowed to generate. The second is the model's actual context window, which limits the combined size of your input and output together. Handling output token limits correctly means detecting which one happened, reacting to it programmatically, and designing your requests so truncation doesn't silently corrupt your data.

This guide walks through the practical mechanics: how to read the stop_reason field, how to raise or right-size max_tokens, how to continue a truncated generation, and how to structure long-output tasks (code generation, document rewriting, structured JSON) so they don't get cut off mid-object.

Why Claude output gets truncated

There are three distinct causes, and each needs a different fix:

The fix for each is different: raise max_tokens for the first, reduce input or paginate the task for the second, and do nothing for the third.

Reading stop_reason correctly

Every Claude response includes a stop_reason field. This is the single most important signal for output token limit handling:

{
  "id": "msg_01...",
  "content": [{ "type": "text", "text": "..." }],
  "stop_reason": "max_tokens",
  "usage": { "input_tokens": 512, "output_tokens": 1024 }
}

Any code consuming Claude output should check stop_reason before trusting the content, especially for structured data:

const response = await client.messages.create({
  model: "claude-sonnet-4-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: prompt }],
});

if (response.stop_reason === "max_tokens") {
  // content is incomplete — do not parse as final JSON/code
  console.warn("Response truncated, output_tokens:", response.usage.output_tokens);
}

Fix 1: raise max_tokens to the task's real ceiling

The simplest fix is often the right one. If you're generating long-form content, code files, or JSON with many fields, set max_tokens close to the model's actual output ceiling rather than a conservative default like 512 or 1024. Check the current model's documented max output tokens and budget accordingly — most truncation issues disappear once max_tokens matches the task size instead of an arbitrary guess.

Don't over-correct either: setting max_tokens unnecessarily high doesn't cost more (billing is based on actual tokens generated, not the cap) but it can increase latency on providers that pre-allocate generation buffers, so size it to the task.

Fix 2: continue a truncated generation

For cases where even the maximum allowed max_tokens isn't enough — a very long document rewrite, for example — you need a continuation strategy. The pattern is: send the partial output back as context and ask Claude to continue from where it stopped.

let fullText = response.content[0].text;
let stopReason = response.stop_reason;

while (stopReason === "max_tokens") {
  const continuation = await client.messages.create({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    messages: [
      { role: "user", content: prompt },
      { role: "assistant", content: fullText },
      { role: "user", content: "Continue exactly where you left off." },
    ],
  });
  fullText += continuation.content[0].text;
  stopReason = continuation.stop_reason;
}

This works well for prose and code but is risky for structured formats like JSON — concatenating two incomplete JSON fragments rarely produces valid JSON. For structured output, prefer Fix 3.

Fix 3: chunk structured output instead of concatenating it

If you need Claude to produce a large structured result (a long list, a multi-file code generation, a big table), don't ask for it in one giant blob and hope max_tokens is enough. Split the task at the prompt level:

This avoids truncation entirely for most workloads, keeps each response parseable on its own, and makes retries cheap — you only re-run the chunk that failed, not the whole task.

Streaming helps you react earlier

If you stream responses, you can detect an approaching max_tokens cutoff before the connection closes, since you're receiving tokens incrementally rather than waiting for the full payload. This is especially useful for long code generation where you want to start writing to disk or rendering to a UI as tokens arrive, and stop/retry logic can kick in immediately on stop_reason.

If you're routing Claude access through SubToAPI (https://subtoapi.app), the same stop_reason and usage.output_tokens fields are returned unchanged, so existing truncation-handling code works without modification. SubToAPI adds application API keys, per-key usage tracking, and streaming support on top of standard Claude Messages — see the streaming docs and messages docs for request shapes, or check pricing if you're evaluating plans. No new truncation behavior to learn, just a cleaner key-management layer.

A simple checklist

  1. Always check stop_reason, never assume "end_turn".
  2. Size max_tokens to the task, not a safe-sounding default.
  3. For prose/code, implement a continuation loop on "max_tokens".
  4. For structured data, chunk the request instead of relying on continuation.
  5. Log usage.output_tokens per request so you can tune max_tokens over time based on real distributions.

questions

Does raising max_tokens cost more if Claude doesn't use it all? No. Billing is based on actual output tokens generated, not the max_tokens cap you set. Setting it higher than needed is safe for cost, though very high values can slightly affect latency expectations.

How do I know if truncation happened versus a natural stop? Check the stop_reason field on the response. "max_tokens" means truncated by your cap; "end_turn" means Claude finished naturally; "stop_sequence" means it hit a custom stop string you defined.

Is continuation safe for JSON output? Not reliably. Concatenating two incomplete JSON fragments usually produces invalid JSON. For structured formats, split the task into smaller chunks up front rather than continuing a truncated response.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →