Stop Claude from 'giving up' mid-generation. Learn how to decode stop_reason and implement continuation loops for reliable long-form code and documents.
Published: 2026-02-11
URL: https://pithycyborg.substack.com/p/the-token-budget-bug-that-makes-claude
Your function is 90% complete. Claude stops. No error. No explanation. Just truncation at the worst possible moment. This is one of the most frustrating failure modes in Claude-based production systems, and it has a specific cause that is almost never explained in the documentation where developers first encounter it. Claude does not run out of tokens the way a string runs out of characters.
It manages token budgets dynamically, and when certain conditions are met, it stops generating before the task is complete in ways that look like bugs but are actually intended behavior that your implementation did not account for.
What Token Budget Management Actually Is Claude has a maximum output token limit per API call. For Claude Sonnet and Opus models on standard API access, this limit is configurable up to a defined maximum through the max_tokens parameter.
What many developers do not realize is that Claude does not simply generate up to the limit and stop. It tracks its output length during generation and makes decisions about whether to continue based on how much of the budget it has consumed.
When Claude is generating a long structured output, such as a complete function, a detailed analysis, or a multi-part response, and it calculates that it is approaching its token budget, it will sometimes truncate the output, add a closing marker, and stop.
This is not a failure. It is Claude trying to produce a complete response within its perceived budget rather than getting cut off mid-sentence at the hard limit. The problem is that “trying to produce a complete response within budget” and “producing the complete output you requested” are not the same thing. Claude may decide that completing a function cleanly within the remaining budget requires truncating the function body, so it closes the function stub and stops rather than getting cut off mid-implementation.
The Three Common Manifestations Truncated code generation. You ask Claude to implement a class with multiple methods. Claude implements the first two methods in detail, then produces stubs or abbreviated implementations for the remaining methods, and closes the class.
The output is syntactically valid. It is also incomplete in a way that is not immediately obvious from the structure. Missing sections in structured documents. You ask Claude to produce a multi-section document.
The first sections are complete. Later sections are abbreviated or reduced to bullet points. The document ends cleanly. You may not notice the quality degradation until you review the later sections against your requirements. Mid-pipeline truncation in agentic workflows. Claude is operating as an agent, generating a sequence of tool calls or reasoning steps.
The sequence is cut short before the task is complete. Claude returns a partial result that looks like a complete result because it was structured to look complete even though the underlying task was not finished.
Why Setting maxtokens Higher Does Not Always Fix It The instinctive fix is to increase maxtokens. This sometimes works. It does not always work, for two reasons. First, Claude’s internal token budget estimation does not always accurately predict the remaining output length. If Claude overestimates how many tokens the remaining output will require, it may still truncate even with a generous max_tokens setting, because its internal calculation suggests it cannot complete the task within the available budget.
Second, some Claude API configurations have hard limits on maxtokens that cannot be overridden by the parameter value. If you are using Claude through a platform or wrapper that has configured a maximum output length, passing a higher maxtokens value may have no effect if the platform limit is lower.
Third, Instruction-Induced Early Stopping. If your prompt includes phrases like 'be concise' or 'summarize if necessary,' Claude’s internal cost-weighting will trigger a truncation much earlier than it would for a 'raw' generation task, effectively shrinking your usable token budget by 30%.
The Fix That Actually Works Explicit continuation prompting. For long structured outputs, break the generation into explicit continuation steps. Instead of asking Claude to generate an entire implementation in one call, ask it to generate a specific portion, check whether it is complete, and continue in a subsequent call if needed. def generatewithcontinuation(prompt: str, client, maxcontinuations: int = 3): """ Handles Claude's tendency to truncate output when it hits the maxtokens limit by automatically continuing the generation.
Important Prompt Caching Optimization:
- Do NOT resend the entire original system prompt (or long user prompt) on continuation calls.
- Only append the assistant's partial response + the short "Continue" message.
- This allows Anthropic's prompt caching to keep the expensive prefix in cache,
typically saving ~85-95% on input token costs for each continuation. Behavior:
- If stopreason == "endturn" → generation finished naturally.
- If stopreason == "maxtokens" → append partial output and request continuation.
""" messages = [{"role": "user", "content": prompt}] fulloutput = "" for i in range(maxcontinuations): response = client.messages.create( model="claude-3-5-sonnet-20241022", # Update for current version maxtokens=4096, messages=messages ) content = response.content[0].text fulloutput += content stopreason = response.stopreason if stopreason == "endturn": break elif stopreason == "maxtokens":
Append only the partial assistant output + minimal continuation request
This is what enables prompt caching to work efficiently
messages.append({"role": "assistant", "content": content}) messages.append({"role": "user", "content": "Continue exactly from where you left off."}) else:
Handle other stop reasons (e.g. stopsequence, tooluse, etc.)
break return fulloutput Check stopreason in every response. The stopreason field in Claude’s API response tells you why generation stopped. endturn means Claude decided the response was complete. maxtokens means generation hit the token limit. If you are seeing maxtokens on responses that should not be that long, the truncation is happening at the hard limit rather than due to internal budget management. If you are seeing end_turn on responses that are clearly incomplete, the budget management behavior is the cause.
Set maxtokens explicitly and generously. Do not rely on the default. For any task that might produce long output, set maxtokens to the maximum value your account tier supports, and check the stop_reason to understand why generation stopped on every call. Structure tasks to fit within known limits.
For generation tasks where you know the expected output length, structure the prompt to produce output in segments that fit comfortably within the token limit. Ask Claude to generate a function signature and the first method, then continue in a subsequent call for each additional method.
This is more API calls but more reliable output. The Diagnostic Checklist If Claude is stopping mid-function or mid-document: Check stopreason. Is it endturn or maxtokens? If endturn: the problem is budget management behavior. Claude thinks it is done. Use continuation prompting. If maxtokens: the problem is the hard token limit. Increase maxtokens or break the task into smaller calls. Log the token usage from every response. response.usage.output_tokens tells you how many tokens were generated.
If it is consistently at or near your max_tokens value on tasks that should not be that long, you have a limit configuration problem. If You Read This Far, My Weekly AI Newsletter Is Probably For You. Every Wednesday I send Pithy Cyborg | AI News Made Simple → 3 elite AI stories plus one prompt, no advertisers, no sponsors, no outside funding.
One person. 10 to 20 hours of research. Straight to your inbox. Always free. No paywalls. If it matters to you, a paid subscription ($5/month or $40/year) is what keeps it independent. Subscribe free → Join Pithy Cyborg | AI News Made Simple for free. Upgrade to paid → Become a paid subscriber. Support independent AI journalism. If you’re not ready to subscribe, following on social helps more than you might think. ✖️ X/Twitter | 🦋 Bluesky | 💼 LinkedIn | ❓ Quora | 👽 Reddit Thanks for reading. Cordially yours, Mike D (aka MrComputerScience) Pithy Cyborg | AI News Made Simple PithyCyborg.Substack.com