Skip to content
Migrate to Claude Sonnet 5: Effort and the Tokenizer Trap — ContentBuffer guide

Migrate to Claude Sonnet 5: Effort and the Tokenizer Trap

K
Kodetra Technologies··10 min read Intermediate

Summary

Hands-on Python guide to Sonnet 5's adaptive thinking, effort levels, and the 30% tokenizer trap.

Anthropic shipped Claude Sonnet 5 on June 30, 2026, and pitched it as a cheaper way to run agents: near-Opus coding and tool use in a Sonnet-priced model. The headline that spread across dev communities in hours was the introductory rate of $2 / $10 per million input/output tokens through August 31, 2026. But the same launch quietly ships a new tokenizer that turns the same text into roughly 30% more tokens. That one detail flips the naive cost math, and a lot of teams are about to migrate on a bad estimate.

This guide walks the real migration, not the press release. You will swap the model ID, fix the three requests that now return a 400 error, control cost with the effort parameter, turn adaptive thinking on and off, and re-measure your token bill under the new tokenizer before you trust any spreadsheet. Every code block is written against the Anthropic Python SDK and the current Messages API.

By the end you will have a small, runnable migration harness that takes any existing Sonnet 4.6 request, points it at Sonnet 5, strips the parameters that would break, counts tokens under both tokenizers, and prints the true cost delta for your prompts.

Prerequisites

  • Python 3.9+ and the official SDK: pip install anthropic (use 0.40+; the effort and adaptive-thinking fields are current-API).
  • An Anthropic API key exported as ANTHROPIC_API_KEY.
  • An existing request you already run on claude-sonnet-4-6 (or any earlier Sonnet). Migration is easiest to reason about when you have a real prompt to compare.
  • Basic familiarity with the Messages API: client.messages.create(model=..., max_tokens=..., messages=[...]).

Sonnet 5 is available on the Claude API to all customers at launch, plus AWS (Bedrock and Claude Platform on AWS, not the legacy InvokeModel/Converse path), Google Cloud Vertex AI, and Microsoft Foundry preview. The examples below use the first-party API; the same parameters apply on Bedrock and Vertex.

Step 1: The one-line swap (and why it is not actually one line)

Anthropic calls Sonnet 5 a drop-in replacement for Sonnet 4.6. The model ID changes and nothing else in the request shape does: tools, response format, and streaming events are identical. So the migration starts here:

model = "claude-sonnet-4-6"   # before
model = "claude-sonnet-5"     # after

If your request was already minimal (a model, max_tokens, and messages) you are done. The catch is that three things which were tolerated on Sonnet 4.6 now hard-fail on Sonnet 5, and one behavior silently changes. Skipping the rest of this guide is how you ship a migration that 400s in production or quietly doubles your latency.

Step 2: Fix the three requests that now return 400

Sonnet 5 tightens the API surface. Each of these was accepted (or deprecated-but-working) on Sonnet 4.6 and is now rejected.

2a. Remove sampling parameters

Setting temperature, top_p, or top_k to any non-default value returns a 400. Omitting them (or leaving the default) is fine. To steer behavior, move that intent into the system prompt instead of turning the temperature knob.

# BREAKS on Sonnet 5 -> 400
resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    temperature=0.2,          # <-- non-default sampling param
    messages=[{"role": "user", "content": "Summarize this ticket."}],
)

# WORKS: drop the sampling param, guide via system prompt
resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system="Be terse and deterministic. Prefer the most literal reading.",
    messages=[{"role": "user", "content": "Summarize this ticket."}],
)

2b. Drop manual thinking budgets

Manual extended thinking, thinking={"type": "enabled", "budget_tokens": N}, was deprecated on Sonnet 4.6 and is removed on Sonnet 5. It returns a 400, the same as on Opus 4.8 and Opus 4.7. Replace it with adaptive thinking plus the effort parameter (Step 3).

# BREAKS on Sonnet 5 -> 400
thinking = {"type": "enabled", "budget_tokens": 32000}

# USE THIS INSTEAD
thinking = {"type": "adaptive"}

2c. Know that adaptive thinking is now ON by default

This is the silent one. On Sonnet 4.6, a request with no thinking field ran without thinking. On Sonnet 5, the same request runs with adaptive thinking: the model decides when and how much to reason. That is great for quality, but it spends output tokens and adds latency on workloads that never asked for it. Because max_tokens is a hard cap on total output (thinking + visible text), a limit you tuned for non-thinking Sonnet 4.6 can now truncate the answer. If a workload genuinely does not need reasoning, disable it explicitly:

# Turn thinking off on Sonnet 5 (lowest latency, cheapest)
resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    thinking={"type": "disabled"},
    messages=[{"role": "user", "content": "Extract the order ID as JSON."}],
)

Assistant message prefilling is still unsupported (it 400s, unchanged from Sonnet 4.6). If you relied on prefill, use structured outputs or system-prompt instructions instead.

Step 3: Control cost with the effort parameter

The replacement for hand-tuned thinking budgets is effort, passed inside output_config. It is a behavioral signal, not a hard token budget, and it affects every token in the response, text, tool calls, and thinking, so lowering it also means fewer and terser tool calls. Sonnet 5 defaults to high.

resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=4096,
    output_config={"effort": "medium"},   # step down from the default
    messages=[{"role": "user",
               "content": "Draft a reply to this refund request."}],
)
print(resp.content[0].text)

Anthropic's own calibration guidance for Sonnet 5 is worth internalizing, because medium is roughly the old default in disguise:

EffortUse it forNote for Sonnet 5
maxFrontier problems, deepest analysisNo token constraints; highest cost
xhighHardest coding / long-horizon agentsBudgets in the millions; 30+ min tasks
high (default)Complex reasoning, agentic tasksSame as omitting effort
mediumCost-saving defaultComparable to Sonnet 4.6 at high effort
lowChat, high-volume, latency-sensitiveFewest tokens, some capability loss

Practical rule: if you were happy with Sonnet 4.6 at its high default, start Sonnet 5 at medium. You keep comparable quality and claw back the extra tokens the new tokenizer adds. Reserve xhigh/max for coding and multi-step agent loops where your evals actually show headroom.

Step 4: Read what thinking actually costs you

Adaptive thinking is billed as output tokens even when you never display it. To see how much of a response was reasoning versus answer, read usage.output_tokens_details.thinking_tokens. This is the number that quietly moves your bill after migration.

resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=8000,
    thinking={"type": "adaptive"},          # on by default on Sonnet 5; explicit here for clarity
    output_config={"effort": "high"},
    messages=[{"role": "user",
               "content": "Are there infinitely many primes p with p mod 4 == 3? Prove it."}],
)

u = resp.usage
thinking = getattr(u.output_tokens_details, "thinking_tokens", 0)
print(f"input:    {u.input_tokens}")
print(f"output:   {u.output_tokens}  (thinking: {thinking})")
print(f"answer-only output ~= {u.output_tokens - thinking}")

Example output for a request like this:

input:    28
output:   963  (thinking: 611)
answer-only output ~= 352

On the newest thinking-on models the thinking field can come back empty unless you ask for a summary. If you want to inspect the reasoning during development, set display:

thinking = {"type": "adaptive", "display": "summarized"}

You are billed for the full reasoning regardless of display; the setting only controls visibility and streaming latency, not cost.

Step 5: The tokenizer trap, recount before you trust any estimate

Here is the part every migration blog is underselling. Sonnet 5 uses the tokenizer introduced with Opus 4.7 (the same one Fable 5 and Mythos 5 use). For the same text it produces about 30% more tokens. Per-token pricing is unchanged, so the same request costs more, and the 1M-token context window now holds less text than it did on Sonnet 4.6.

This is not an API change; no code changes are required. But any number you measured in tokens is now wrong: usage counts, max_tokens budgets sized near your expected output, context-fit calculations, and your cost model. The fix is to recount your actual prompts with the token-counting endpoint, once under the old model and once under the new one, and compare. Counting is free and does not touch your generation rate limit.

import anthropic
client = anthropic.Anthropic()

sample = [{"role": "user", "content": open("prompt.txt").read()}]

old = client.messages.count_tokens(model="claude-sonnet-4-6", messages=sample)
new = client.messages.count_tokens(model="claude-sonnet-5",   messages=sample)

inflation = (new.input_tokens - old.input_tokens) / old.input_tokens
print(f"sonnet-4-6: {old.input_tokens} tokens")
print(f"sonnet-5:   {new.input_tokens} tokens  (+{inflation:.1%})")
sonnet-4-6: 5100 tokens
sonnet-5:   6630 tokens  (+30.0%)

Do this for a representative prompt, not a toy string; the exact inflation varies with content (code, non-English text, and structured data drift differently). Whatever ratio you get is the multiplier to apply to your input cost. Output inflates too, so also revisit any max_tokens value you set close to your expected answer length, or Sonnet 5 will truncate output that Sonnet 4.6 fit.


Worked example: migrate a support-triage script and measure the true delta

Put it together. Below is a realistic before/after for a customer-support triage call that classifies a ticket and drafts a reply. The Sonnet 4.6 version used a manual thinking budget and a low temperature, both of which now 400. The Sonnet 5 version drops them, sets medium effort, and prints the real cost using the new tokenizer's counts.

import os, anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

PRICES = {  # USD per token, Sonnet 5 introductory rate (through 2026-08-31)
    "in":  2 / 1_000_000,
    "out": 10 / 1_000_000,
}

SYSTEM = (
    "You are a support triage assistant. Classify the ticket "
    "(billing | bug | feature | other) and draft a 2-sentence reply. "
    "Be deterministic and literal."   # replaces the old temperature=0.1
)

ticket = "I was charged twice for my June invoice. Please refund the duplicate."
msgs = [{"role": "user", "content": ticket}]

resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=SYSTEM,
    output_config={"effort": "medium"},   # ~Sonnet 4.6 high, cheaper
    # no temperature, no budget_tokens -> both would 400 now
    messages=msgs,
)

u = resp.usage
cost = u.input_tokens * PRICES["in"] + u.output_tokens * PRICES["out"]
print(resp.content[0].text)
print(f"\ntokens  in={u.input_tokens} out={u.output_tokens}")
print(f"cost    ${cost:.6f}")

Example output:

Classification: billing
Reply: Thanks for flagging this, I can see the duplicate charge on your
June invoice and I have queued the refund for the extra amount. You should
see it back on your original payment method within 5-7 business days.

tokens  in=41 out=88
cost    $0.000962

Now the honest comparison. If you had estimated this workload from Sonnet 4.6 token counts and the $2/$10 intro price, you would be low by the tokenizer inflation. Counting the same batch under both models tells you the truth before you commit a budget:

batch = [{"role": "user", "content": t} for t in load_recent_tickets(1000)]

def total(model):
    return sum(client.messages.count_tokens(model=model, system=SYSTEM,
              messages=[m]).input_tokens for m in batch)

old_in = total("claude-sonnet-4-6")
new_in = total("claude-sonnet-5")
print(f"input tokens 4.6: {old_in:,}")
print(f"input tokens 5:   {new_in:,}  (+{(new_in-old_in)/old_in:.1%})")
print(f"est input cost/1k tickets @ $2/M: ${new_in * 2/1_000_000:.2f}")

The intro price still makes Sonnet 5 cheaper per token than the $3/$15 standard rate, but your per-request cost is set by tokens x price, and the tokenizer moved the first term. Budget on measured counts, not on the sticker price.

Common pitfalls and gotchas

  • Estimating cost from old token counts. The single most expensive mistake. A prompt that was 5,100 tokens on Sonnet 4.6 is ~6,630 on Sonnet 5. Recount with count_tokens using model="claude-sonnet-5".
  • Leaving a stray temperature in. Even temperature=1.0-adjacent values 400 if they are non-default. Grep your codebase for temperature, top_p, top_k and delete them; steer via the system prompt.
  • Keeping budget_tokens. Manual thinking is removed, not deprecated. It 400s. Switch to thinking={"type": "adaptive"} plus effort.
  • Reusing a tight max_tokens. Thinking is on by default and shares the max_tokens budget with the visible answer. A limit tuned for non-thinking 4.6 can truncate 5. Watch for stop_reason: "max_tokens" and raise the cap or lower effort.
  • Assuming thinking is free. It bills as output tokens even when display hides it. Track usage.output_tokens_details.thinking_tokens.
  • Treating a refusal as an exception. Sonnet 5 is the first Sonnet with real-time cyber safeguards. Refusals come back as a successful HTTP 200 with stop_reason: "refusal", not an error, so a naive try/except never sees them. Check resp.stop_reason.
  • Expecting Priority Tier. It is not available on Sonnet 5. If you depended on it, plan around standard/other service tiers.

A minimal, safe refusal check:

resp = client.messages.create(model="claude-sonnet-5", max_tokens=1024,
                              messages=msgs)
if resp.stop_reason == "refusal":
    # 200 OK, but the model declined; route to fallback or a human
    handle_refusal(resp)
else:
    use(resp.content[0].text)

Quick reference

ItemSonnet 4.6Sonnet 5
Model IDclaude-sonnet-4-6claude-sonnet-5
Default thinkingoffadaptive (on)
Disable thinkingomit thinkingthinking={"type":"disabled"}
Manual budget_tokensdeprecated, works400 error
temperature/top_p/top_kaccepted400 if non-default
Thinking depth controleffort / budget_tokensoutput_config effort
Context window(per model)1M (default & max)
Max output tokens(per model)128k
Tokenizerpre-4.7new (~+30% tokens)
Intro price (in/out /M)n/a$2 / $10 to 2026-08-31
Standard price (in/out /M)$3 / $15$3 / $15
Refusal signaln/a (Sonnet)stop_reason "refusal", HTTP 200
Priority Tieravailablenot available

Next steps

  • Run the token recount on your top 3 prompt templates and update your cost model with the measured inflation, not 30% flat.
  • Add a stop_reason == "refusal" branch anywhere you call Sonnet 5 in production.
  • Sweep the code for temperature, top_p, top_k, and budget_tokens and remove them.
  • A/B medium vs high effort on your eval set; keep the cheapest level that holds quality.
  • For agent loops, test xhigh with a generous max_tokens and confirm you are not hitting stop_reason: "max_tokens".

Sonnet 5 really is a cheaper way to run agents, but only if you migrate on measured numbers. Swap the ID, delete the parameters that now 400, pick an effort level deliberately, and recount your tokens. Do that and the intro-price math actually works in your favor instead of surprising you at the end of the month.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,617 newsletter subscribers.

Also get