Claude Sampling and Non-Determinism: Temperature on Current Models
👋 In plain words: Ask Claude the same question twice and you may get two different answers. Older APIs let you turn a “temperature” knob to reduce that. On current Claude models that knob is gone, so you need other ways to get consistent, testable output. This lesson explains why, one step at a time, and shows what to do instead.
Testers hate non-deterministic systems, and a language model is one. In this lesson you will learn how sampling works, why the current Claude API rejects temperature, top_p and top_k, what happens if old code still sends them, and the practical techniques that make Claude’s output consistent enough to test: tight instructions, examples, structured outputs, stop sequences and repeated-run checks.
🔑 Key terms
- Sampling: how the model picks each next token from a list of likely options.
- Temperature, top_p, top_k: older sampling parameters that changed how random that pick was.
- Non-deterministic: the same input can give different outputs on different runs.
- API version: the
anthropic-versionheader that fixes the API’s behaviour. The current Python SDK sends2026-10-21. - Stop sequence: a string that makes Claude stop writing as soon as it produces it.
🪜 Step 1: See why output varies
For each token, the model scores many possible next tokens and samples one. Because it samples, two runs can choose different tokens early, and the answers then drift apart. Other things add variation too: thinking depth, model updates, and tiny differences in the input.
For a tester this means: never assert on exact free-text output. Assert on properties instead, such as format, required fields, allowed values and facts that must appear.
🪜 Step 2: Know what changed with the sampling parameters
Older Claude tutorials set temperature=0 “for determinism”. That advice is out of date:
- On Claude Opus 4.7 and later, Fable models and Claude Sonnet 5, sending
temperature,top_portop_kreturns a 400 error. - Claude Sonnet 5.5 and Claude Haiku 5.5 reject non-default values with a 400 error.
- With API version
2026-10-21, a Messages request that sends any of the three returns a 400 on every model, even at the default value. This also applies to each request in a Message Batch. - The current Python SDK (2.x) sends
2026-10-21by default and no longer has atemperatureargument at all.
You can see point 4 without calling the API:
📄 old_temperature.py
import anthropic
from anthropic._constants import ANTHROPIC_API_VERSION
print("SDK", anthropic.__version__, "sends anthropic-version", ANTHROPIC_API_VERSION)
client = anthropic.Anthropic()
try:
client.messages.create(
model="claude-opus-5-5",
max_tokens=100,
temperature=0, # old advice
messages=[{"role": "user", "content": "Hi"}],
)
except TypeError as e:
print("TypeError:", e)⌨️ Terminal
python old_temperature.py🖥️ Output
SDK 2.13.0 sends anthropic-version 2026-10-21
TypeError: Messages.create() got an unexpected keyword argument 'temperature'
- The error happens inside your Python process, before any request is sent. The SDK’s method signature no longer accepts the argument.
- On older models that still accept other values (Claude Opus 4.6, Sonnet 4.6, Haiku 4.5), code that lowered temperature for consistency loses that control under
2026-10-21. There is no replacement setting.
temperature setting from configuration, or through extra_body. Under 2026-10-21 that still produces a 400. Search your config and remove it.🪜 Step 3: Make output consistent with clear criteria
The biggest lever is a precise prompt. Compare a vague and a precise instruction for the same classification task:
📄 prompts.txt
VAGUE: Is this bug important?
PRECISE: Classify the bug as exactly one of: critical, major, minor.
critical = money, data loss or security; major = a main user flow is blocked; minor = anything else.
Reply with the single word only.
The precise version removes choices the model would otherwise make differently each time: the label set, the definitions and the output length.
🪜 Step 4: Lock the format with structured outputs and stop sequences
When code reads the answer, constrain the shape:
- Structured outputs (
output_config.formatorclient.messages.parse()) make Claude return JSON that matches your schema. Lesson 22 covers them. - Stop sequences end the reply as soon as a marker appears, which keeps free text short and predictable.
📄 stop_sequence.py
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=200,
stop_sequences=["END"],
messages=[{
"role": "user",
"content": "Give one Playwright locator for a 'Sign in' button, then write END.",
}],
)
print(repr(response.content[0].text))
print("stop_reason:", response.stop_reason, "| stop_sequence:", response.stop_sequence)⌨️ Terminal
python stop_sequence.py🖥️ Output (sample run)
'page.get_by_role("button", name="Sign in")\n'
stop_reason: stop_sequence | stop_sequence: END
- When a stop sequence ends the reply,
stop_reasonisstop_sequenceandstop_sequencetells you which one. The marker itself is not included in the text. - Stop sequences are still supported under
2026-10-21. Only the three sampling parameters were removed.
🪜 Step 5: Measure consistency like a tester
You cannot make a model fully deterministic, but you can measure how consistent a prompt is, and fail a build when it drops. Run the same input several times and count distinct answers:
📄 consistency.py
from collections import Counter
import anthropic
client = anthropic.Anthropic()
PROMPT = """Classify the bug as exactly one of: critical, major, minor.
critical = money, data loss or security; major = a main user flow is blocked; minor = anything else.
Reply with the single word only.
Bug: The 'Forgot password' link on the login page has the wrong font colour."""
def classify() -> str:
r = client.messages.create(model="claude-opus-5-5", max_tokens=10, messages=[{"role": "user", "content": PROMPT}])
return r.content[0].text.strip().lower()
runs = [classify() for _ in range(5)]
counts = Counter(runs)
label, hits = counts.most_common(1)[0]
print("answers:", dict(counts))
print(f"agreement: {hits}/{len(runs)} on '{label}'")
assert hits / len(runs) >= 0.8, "prompt is not consistent enough"
print("consistency check passed")⌨️ Terminal
python consistency.py🖥️ Output (sample run)
answers: {'minor': 5}
agreement: 5/5 on 'minor'
consistency check passed
Countertallies the answers;most_common(1)gives the winning label and how often it won.- The
assertturns consistency into a pass/fail gate, just like any other test. Choose the threshold from your requirements. - This sample run used a local stand-in API that always returns the same answer. Against the real API, run it on a set of borderline bugs, where disagreement shows up first. Lesson 45 builds this into a full evaluation with a golden set.
🌍 Real-world example: Ravi’s flaky AI test
Ravi’s pipeline asserted response == "minor". It failed one night because Claude answered Minor. with a capital and a full stop. He changed the test to normalise the text, added “Reply with the single word only” to the prompt, and later moved to structured output with an enum. The “flaky” test was really an over-specific assertion.
🧪 Practice Questions
Question 1. After upgrading the Python SDK to 2.x, a call that passes temperature=0.2 fails before any HTTP request is made. Why?
- A. The API key is missing
- B. The SDK no longer accepts the temperature argument, so Python raises a TypeError
- C. The model is rate limited
- D. temperature must be an integer
Show answer
Answer: B. The 2.x Python SDK sends API version 2026-10-21, which removed sampling parameters, and its method signature no longer includes them.
Question 2. A team wants more consistent severity labels from Claude Opus 5.5. Which change helps most?
- A. Set temperature to 0
- B. Set top_k to 1
- C. Define each label precisely, restrict the reply to one word, and validate with structured output
- D. Raise max_tokens
Show answer
Answer: C. Sampling parameters are rejected on current models. Precise criteria and constrained output formats reduce the model’s freedom to vary.
Question 3. A reply ends early and the response shows stop_reason “stop_sequence”. What happened?
- A. Claude produced one of the stop strings you passed, so generation stopped there
- B. The output hit max_tokens
- C. A safety classifier declined the request
- D. The request was retried
Show answer
Answer: A. stop_sequence means a configured stop string was generated. The response’s stop_sequence field names which one.
Question 4. Which two statements about API version 2026-10-21 are true? (Choose 2.)
- A. Sending temperature, top_p or top_k returns a 400 error on every model
- B. It removes stop_sequences
- C. It applies to each request inside a Message Batch created with that version
- D. It only affects Claude Haiku models
Show answer
Answer: A and C. The 2026-10-21 version rejects all three sampling parameters on every model, including batch requests. Stop sequences remain supported.
📝 Assignment
- Task 1: Search one of your projects (or a public repo) for
temperature,top_pandtop_kin Claude calls and list what would break under2026-10-21.
✅ Done when: you have a list of every hit and what to do with it. - Task 2: Rewrite a vague prompt of your own into a precise one with a fixed label set and definitions.
✅ Done when: the new prompt names every allowed output. - Stretch: Extend
consistency.pyto run 10 different bug reports 5 times each and print the agreement per report.
✅ Done when: you can name the report with the lowest agreement and explain why it is ambiguous.
❓ Frequently Asked Questions
🤔 Can I set temperature to 0 on Claude Opus 5.5?
No. Sampling parameters are rejected on current models, and API version 2026-10-21 rejects them on every model. Use precise prompts and structured outputs for consistency.
🤔 Is Claude deterministic if I send the same prompt twice?
No. Output is sampled, so it can differ between runs. Design tests to check properties and formats, not exact text.
🤔 Are stop sequences still supported?
Yes. stop_sequences still works, and the response reports stop_reason: "stop_sequence" with the matching string.
🤔 What should I do with old code that sets temperature?
Remove the parameter. On models that only accept the default, behaviour does not change. On older models that accepted other values, decide whether default sampling is acceptable for that call.
🏁 Summary
- Claude samples each token, so the same input can give different outputs.
- Current models reject
temperature,top_pandtop_k; API version2026-10-21rejects them on every model, and the Python SDK 2.x drops them. - Consistency comes from precise criteria, fixed label sets, structured outputs and stop sequences.
- Test properties, not exact strings, and measure agreement across repeated runs.
Next, continue with Claude Model Selection: Opus vs Sonnet vs Haiku, Thinking and Effort.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.