
Auto-Route Claude Refusals by Category on Opus 5
Summary
Auto-recover from Claude safety refusals on Opus 5 with one line of code: fallbacks='default'.
Auto-Route Claude Refusals by Category on Opus 5
Anthropic shipped Claude Opus 5 on July 24, 2026, and buried in the release notes is a small change that quietly fixes a real production headache: the fallbacks parameter now takes a "default" mode. Instead of hand-maintaining a chain of backup models, you tell the API to route a refused request to whatever fallback Anthropic recommends for that specific refusal category. It is one line of code, and it turns a class of silent, hard-to-monitor failures into automatic recovery.
Here is the part that trips people up. When a safety classifier declines a request on Claude Fable 5, you do not get an HTTP error. You get a perfectly normal 200 OK with an empty content array and stop_reason: "refusal". If your code assumes a 200 means "we have an answer," the user sees a blank reply and your dashboards see nothing wrong. Teams have shipped this bug to production more than once.
This guide shows you exactly what a refusal looks like on the wire, how the old explicit-list fallback worked, and how the new default mode replaces it. Every code sample is checked against the official Refusals and fallback and What's new in Claude Opus 5 docs. By the end you will have a drop-in wrapper that never dead-ends on a refusal, plus the instrumentation to actually see when a fallback saved you.
Prerequisites
- Python 3.9+ and the official SDK:
pip install -U anthropic(0.116.0 or newer for the Opus 5 headers). - An Anthropic API key in the
ANTHROPIC_API_KEYenvironment variable. - Access to
claude-fable-5(the model with safety classifiers) and at least one fallback target such asclaude-opus-4-8orclaude-opus-5. - Basic familiarity with the Messages API. If you have called
client.messages.createbefore, you are ready.
Step 1: See a refusal for what it is
A refusal is a successful response, not an exception. The tell is stop_reason == "refusal" and a populated stop_details object. Run a normal request first so you know the shape of a healthy response:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
resp = client.messages.create(
model="claude-fable-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Explain the trade-offs of monoliths vs microservices.",
}],
)
print(resp.stop_reason) # "end_turn"
print(resp.stop_details) # None on a normal answer
print(resp.content[0].text[:80])
When a classifier declines, the same call returns HTTP 200 but the body changes. This is the raw JSON of a decline that fired before any output was generated:
{
"id": "msg_01XFUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"model": "claude-fable-5",
"content": [],
"stop_reason": "refusal",
"stop_details": {
"type": "refusal",
"category": "cyber",
"explanation": "This request was declined because it could enable cyber harm."
},
"usage": { "input_tokens": 412, "output_tokens": 0 }
}
Two things worth internalizing. First, content is empty, so anything that reaches for resp.content[0].text will throw an IndexError and mask the real cause. Second, you are not billed for a refusal that lands before any output, and it does not count against rate limits. A mid-stream refusal is different: you pay for the input plus whatever streamed.
The category field is the hook the new default mode routes on. These are the published categories:
| category | What triggered it |
|---|---|
| cyber | Could enable cyber harm (malware, exploits). Benign security work can trip it too. |
| bio | Could enable biological harm. Legitimate life-sciences work can trip it too. |
| frontier_llm | Could help build a competing frontier model, restricted under Anthropic's commercial terms. |
| reasoning_extraction | Asks the model to dump its internal reasoning as text. Use adaptive thinking to get reasoning properly. |
Both category and explanation are null when the refusal does not map to a named policy area. That null is a real, permanent value, not a placeholder you should wait on. And the explanation wording is not stable, so display it to a human but never branch on its text.
Step 2: The old way (explicit fallback list)
Before Opus 5, server-side fallback meant naming the backup models yourself. You pass a fallbacks list of up to three entries and the server-side-fallback-2026-06-01 beta header. When Fable 5 declines, the API runs the next model on the same request and returns a single response, so the user gets an answer in one round trip:
resp = client.beta.messages.create(
model="claude-fable-5",
max_tokens=1024,
messages=[{"role": "user", "content": user_prompt}],
fallbacks=[{"model": "claude-opus-4-8"}],
betas=["server-side-fallback-2026-06-01"],
)
print(resp.model) # names the model that actually answered
This works, but it puts a policy decision in your codebase. Which model should catch a cyber decline versus a bio one? Is claude-opus-4-8 still the right catcher after the next release? Every service, retry handler, and background worker needs the same list, and the list drifts. That maintenance burden is exactly what the default mode removes.
Step 3: The new way (fallbacks="default")
On Claude Opus 5, the fallbacks parameter accepts the string "default". Pair it with the newer server-side-fallback-2026-07-01 beta header and the API applies Anthropic's recommended fallback model for whatever category triggered the decline. You stop maintaining the routing table entirely:
resp = client.beta.messages.create(
model="claude-fable-5",
max_tokens=1024,
messages=[{"role": "user", "content": user_prompt}],
fallbacks="default",
betas=["server-side-fallback-2026-07-01"],
)
print(resp.stop_reason) # "end_turn" once a fallback answered
print(resp.model) # the resolved model that served the turn
The 2026-07-01 header is a superset: it accepts both "default" and an explicit list, so you can migrate one call at a time. The important caveat: for a category that has no recommended fallback, the refusal stands. Default mode is automatic recovery where recovery is sensible, not a guarantee that every request gets answered.
One hard rule about the header date. It must be exact. Send "default" under the older server-side-fallback-2026-06-01 header, or under any other server-side-fallback-* value, and the fallbacks parameter is rejected with a 400. If you built against an earlier preview, bump the header and the request shape together.
Step 4: Know when a fallback actually served
"It returned 200" is not the same as "the primary model answered." The response carries a full audit trail in usage.iterations: every attempt is listed, a model that declined shows up as an ordinary message entry, and the model that served the turn shows up as a fallback_message entry. There is also a fallback content block marking the handoff point inside content. Use both signals:
def served_by_fallback(resp) -> bool:
"""True only if a fallback model produced the final answer."""
iterations = resp.usage.iterations or []
a_fallback_ran = any(it.type == "fallback_message" for it in iterations)
return a_fallback_ran and resp.stop_reason != "refusal"
served = served_by_fallback(resp)
print(json.dumps({
"stop_reason": resp.stop_reason,
"answered_by": resp.model,
"served_by_fallback": served,
}))
Example output when Fable 5 declined and Opus 4.8 caught it:
{"stop_reason": "end_turn", "answered_by": "claude-opus-4-8", "served_by_fallback": true}
Do not try to infer the handoff by comparing resp.model to your requested string. Read the fallback_message marker. It is unambiguous even when the fallback resolves to a model ID that differs from the alias you sent.
Worked example: a support assistant that never dead-ends
Say you run an internal assistant for a security team. Their questions legitimately brush the cyber classifier ('how would this CVE be exploited so we can patch it'), and a blank reply is worse than useless. You want automatic recovery plus a metric you can alert on. Here is a self-contained wrapper:
import json
import anthropic
client = anthropic.Anthropic()
FALLBACK_BETA = "server-side-fallback-2026-07-01"
def ask(prompt: str, model: str = "claude-fable-5") -> dict:
resp = client.beta.messages.create(
model=model,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
fallbacks="default", # auto-route by refusal category
betas=[FALLBACK_BETA],
)
iterations = resp.usage.iterations or []
fallback_ran = any(it.type == "fallback_message" for it in iterations)
if resp.stop_reason == "refusal":
# Every model in the chain declined (or the category has no fallback).
emit_metric("llm.refusal.final", category=_category(resp))
return {"ok": False, "reason": "refused", "category": _category(resp)}
if fallback_ran:
emit_metric("llm.refusal.recovered", answered_by=resp.model)
text = "".join(b.text for b in resp.content if b.type == "text")
return {"ok": True, "text": text, "answered_by": resp.model,
"served_by_fallback": fallback_ran}
def _category(resp):
d = resp.stop_details
return getattr(d, "category", None) if d else None
def emit_metric(name, **tags):
# Wire this to StatsD / OpenTelemetry. A refusal is an HTTP 200,
# so error-rate dashboards never see it -- emit it explicitly.
print(f"METRIC {name} {json.dumps(tags)}")
result = ask("Walk me through how CVE-2026-1234 is exploited so we can prioritize the patch.")
print(json.dumps(result, indent=2))
The wrapper does three jobs at once: it recovers automatically via default mode, it distinguishes 'recovered by fallback' from 'refused by everyone,' and it emits a metric per outcome so you can alert on the gap. That last point matters more than it looks, which brings us to the pitfalls.
Common pitfalls
- A refusal is a 200, not a 5xx. Monitoring built on error rates or exception counts will never see it. Emit one event per refusal and one per fallback-served response, then alert on the divergence between the two.
- Branch on
stop_reason, not onstop_detailsorcontent.stop_detailscan benulleven on a real refusal (unnamed category), and in the Message Batches API it isnullon batch results. Checkstop_reason == "refusal"directly. - The beta header date is load-bearing.
"default"mode needs exactlyserver-side-fallback-2026-07-01. The older2026-06-01header accepts explicit lists only and 400s on"default". - Fallback does not propagate into tool calls. If your agent spawns sub-agent model calls inside tool execution, each of those calls needs its own
fallbackssetting. A single turn can produce several refusals (an agent plus its sub-agents), so budget retries per request, not per session. - The request must be valid for every fallback target. If a fallback model does not support a feature your request uses, the API rejects the whole call up front with a 400 rather than at fallback time. Test your request against each candidate model.
- Server-tool declines do not advance. When a decline fires after a server tool (web search, code execution) already ran in the request, the API returns the refusal instead of moving to a fallback. Set the
fallback-credit-2026-06-01header so that refusal carries a credit token and the completed tool work is not billed twice. - Only safety declines trigger fallback. A rate limit, overload, or server error on the primary model is returned to you as-is. Keep your ordinary retry/backoff logic for those; fallback is strictly for classifier refusals.
- Echo the
fallbackblock back verbatim on the next turn. Keep it exactly where it appeared and drop anythinkingor client-sidetool_useblocks that came before it. The API uses the block's position to validate surrounding thinking blocks, so moving or omitting it gets the follow-up rejected.
Quick reference
| Item | Value / meaning |
|---|---|
| Refusal signal | HTTP 200, stop_reason == "refusal", content == [] |
| Default mode | fallbacks="default" (string) |
| Required header | server-side-fallback-2026-07-01 |
| Explicit list header | server-side-fallback-2026-06-01 (lists only, no "default") |
| Categories | cyber, bio, frontier_llm, reasoning_extraction (or null) |
| Fallback-served marker | a fallback_message entry in usage.iterations |
| Handoff marker in content | a fallback block: {"type":"fallback","from":...,"to":...} |
| Max explicit fallbacks | 3 entries, tried in order, each distinct |
| Billing for pre-output refusal | not billed, no rate-limit charge |
| Server-tool decline | refusal returned, not advanced; use fallback-credit-2026-06-01 |
Next steps
- Swap
fallbacks="default"into your highest-traffic Fable 5 endpoint behind a feature flag and watch the recovered-vs-refused metric for a week. - Add the
fallback-credit-2026-06-01header on any request that uses server tools so partial tool work is not paid for twice on a decline. - For Ruby/PHP or custom retry logic, implement the detect-and-retry pattern by hand against
stop_reason; for TypeScript, Python, Go, Java, or C#, use the SDK refusal-fallback middleware to configure this once on the client. - Read the official Effort and What's-new-in-Opus-5 pages next, since thinking is now on by default on Opus 5 and effort is the control for cost.
That is the whole feature: one string, one header, and a metric so you can trust it. Refusals stop being silent blanks and start being a signal you route around automatically.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.