Claude API 錯誤排查:5,369 個輸出 token 中有 4,474 個用於 thinking
4,474 of 5,369 Output Tokens Were Thinking: Reading Claude API Errors
作者整理 Claude API 錯誤排查流程,指出 HTTP 200 空文字回應可能源於 thinking token 用盡 max_tokens 預算,而非 JSON 提示詞出錯。
The most confusing Claude API failure is not a 400, a 429, or a 529. It is an HTTP 200 with an empty text block. Nothing was thrown and nothing was logged as an error, yet your JSON parser reports "no JSON found". In our case the cause was thinking tokens eating the whole max_tokens budget: 4,474 of 5,369 output tokens went to thinking, which left 895 for the answer.
This post is the triage order we use now. It separates "retry", "fix the request", and "wait", and it catches the failures that never produce an error at all. The longer write-up, with the full status table, is on the original post.
Errors share one shape, so classify by type
Every API error comes back as the same JSON object: a top-level error with a type and a message, plus a request_id.
{
"type": "error",
"error": {
"type": "rate_limit_error",
"message": "..."
},
"request_id": "req_..."
}
Branch on error.type, never on the message text. The docs say wording can change, and the SDK raises a different exception class per status code, so catch the class. A string comparison on the message will break silently one day.
The first-pass reading:
- 400 (
invalid_request_error): the request is wrong. Retrying the same request gives the same result. - 429 (
rate_limit_error): a limit of some kind. Which kind matters, see the next section. - 529 (
overloaded_error): temporary overload across all users. Wait and retry. It is not an account problem. - 500 (
api_error) and 504 (timeout_error): server-side. Back off, or move long requests to streaming or the batch API.
One more detail: the SDK already retries connection errors, 429s, and 5xx responses twice with exponential backoff, honoring retry-after. If an exception reached your code, two more attempts already happened.
429 is three different problems
A 429 can be a rate limit, a monthly spend cap for your usage tier, or a Claude Code workspace spend limit. Only the first one clears if you wait.
The tell is the retry-after header. A rate limit sends it. A spend cap does not, and it keeps failing until access reopens. If you treat a spend cap as a rate limit and add backoff, you get a loop that receives the same 429 all day.
import anthropic
def classify_429(err: anthropic.RateLimitError) -> str:
ra = err.response.headers.get("retry-after")
if ra is None:
return "cap-type: stop retrying, check spend caps and workspace limits"
return f"rate-type: retry after {ra}s"
Rarely, a sudden jump in organization usage can trigger a 429 from an acceleration limit. The fix there is to ramp traffic up gradually and keep usage patterns even.
A 400 on a valid-looking request
When the payload looks fine, check whether the model dropped a parameter. These are the messages that mattered to us:
| Message fragment | Cause | Fix |
|---|---|---|
| "does not support assistant message prefill" | Newer models reject a prefilled last assistant message | Use structured output or the system prompt |
"thinking.type.enabled" is not supported |
Fixed budget_tokens thinking was removed on newer models |
thinking: {type: "adaptive"} plus effort
|
| "thinking blocks ... cannot be modified" | You edited or dropped the previous assistant turn's thinking blocks | Send them back unchanged |
tool_choice: type "tool" and "any" are not supported |
Some models reject forced tool calls |
auto plus strict tool use |
One observation that is not in the official error docs: our LLM wrapper has a comment saying not to pass temperature, left behind after an old example that included it returned a 400. Treat that as our environment's experience, not a documented rule.
Empty response, HTTP 200, no error
Thinking tokens count toward max_tokens. If thinking spends the budget first, the response ends with stop_reason: "max_tokens" and the text block is truncated or missing. The status is 200 and no exception is raised.
Our case: a call asking for a content plan as JSON returned an empty string and failed with "JSON not found". We then walked a four-step misdiagnosis:
- The log said "JSON parse failed".
- We assumed the prompt was steering the model wrong and rewrote it.
- The same failure came back. It failed three times in a row.
- The real cause was the output budget. The clue was that the raw response was an empty string.
That last point is the discriminator. If the prompt had pushed the model toward prose instead of JSON, the raw response would not be empty. Only an empty raw string supports the "thinking used the budget" diagnosis.
def diagnose_empty(resp) -> str | None:
text = "".join(b.text for b in resp.content if b.type == "text")
if text.strip():
return None
thinking = getattr(getattr(resp.usage, "output_tokens_details", None),
"thinking_tokens", None)
return (f"empty response: stop_reason={resp.stop_reason}, "
f"output={resp.usage.output_tokens}, thinking={thinking}")
The field to read is usage.output_tokens_details.thinking_tokens. When streaming, it only appears on the final message_delta event.
There are two official fixes: raise max_tokens so thinking and text both fit, or lower effort so thinking spends less. We added a third. We cut what a single call has to produce: instead of "plan N posts at once", we ask for one outline, then one table of contents per post. The call that had failed three times passed on the first try.
The rule of thumb: if the output must arrive in one piece, use the official fixes. If it can be split, split it.
A six-step check order
- Is the status 200? If the result is empty, it is an output budget problem. Read
stop_reasonandthinking_tokens. - Is it a 400? Find the parameter name in the message (prefill,
thinking.type,tool_choice). Do not retry unchanged. - Is it a 429?
retry-afterpresent means rate-type; absent means cap-type, so stop the loop. - Is it a 529 or 500? The SDK already retried twice. Wait longer, and record the
request_idif it persists. Give that ID to support. - Is it a 504 or a long request? Move anything that may exceed ten minutes to streaming or the batch API. Note that an error can still arrive after a streamed 200.
- Is it a Claude Code MCP tool? Check
/mcp, and if only the first call fails, raiseMCP_TIMEOUT.
When the first MCP call fails
If a Claude Code MCP tool fails only on its first call in a session, suspect a cold start. One of our search-console servers times out on the first call and works once a lightweight tool has woken it.
| Control | What it adjusts | Example |
|---|---|---|
MCP_TIMEOUT env var |
Server startup wait | MCP_TIMEOUT=10000 claude |
Per-server timeout in .mcp.json
|
Tool execution time in ms | "timeout": 600000 |
MAX_MCP_OUTPUT_TOKENS |
Tool output token cap | Default 25,000 |
The caution that matters most: do not retry a timed-out write. A timeout means "result unknown", not "failed". Resending a write that already landed applies the change twice, so check whether it took effect first.
Two things this table does not cover. The subscription limit messages in the Claude Code UI, such as "You've hit your session limit", are plan notices, not HTTP errors. And any automation that reports "success" while producing nothing belongs to the same family as the empty response.
For the full status table, the FAQ, and the related posts on this, see the complete guide on my-blog.org.
Free tools I keep on my own site: 34 calculators and how-to guides - loans, severance pay, take-home salary, savings vs deposits. New ones go out in one email, no ads.
來源:DEV Community · dev.to

