Testing request parameters: max_tokens, stop sequences, system and removed parameters

Study time
≈ 2.5 h (estimate)
Needs
L1-M03-L01
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M03 · Duration: ~150 min (estimate, including the independent exercise) · Previous: L01 · Next: L03 - Errors, rate limits, timeouts and retries

1. Introduction

Every behaviour of an LLM feature starts from the request: which model, which system prompt, how large the output limit is, where to stop. A defect here, such as forgetting to send the system prompt, setting max_tokens too low or sending a parameter that the API has dropped, breaks everything downstream, and often does not show up as a clear error.

This lesson teaches you to write contract tests for the request: assert exactly what the product's code sends, and how it handles each kind of response that those parameters produce.

2. Learning objectives

  1. Write a contract test that asserts the entire body of the request that the product's code sends.
  2. Explain what max_tokens, stop_sequences and system do, and the corresponding response.
  3. Verify that a truncated reply (max_tokens) and a refused reply (refusal) are handled correctly before they reach the user.
  4. Detect the sending of parameters that the API has removed, and explain why a test for this is necessary when upgrading the SDK.
  5. Distinguish tests for the request (deterministic, using a fake) from tests for the quality of the answer.

3. Prerequisites and tools

  • L01: the fake API, the api and client fixtures.
  • L1-M01-L04 (stop reason) and L1-M01-L03 (the note about temperature being removed).

4. Concepts

4.1 The main request parameters

Parameter Required? What it does Risk to test
model Yes The model that handles the request Wrong model name (404); a model outside the cost plan
max_tokens Yes Limits the number of output tokens Too low: the answer is cut off (stop_reason: "max_tokens")
messages Yes The conversation A missing turn, a wrong role
system No The system prompt Not sent, or the wrong version sent
stop_sequences No Strings that make the model stop Stopping early unintentionally; stop_reason: "stop_sequence"

The three required parameters are model, max_tokens, messages (L1-M01-L04).

Everyday example. A request is like an order slip at a noodle shop. model is the shop you order from, messages is the dish you order, system is the owner's standing note taped up in the kitchen ("no MSG"), max_tokens is "one bowl at most": when the bowl is full they stop ladling, even if the toppings are not all in, and stop_sequences is the "stop here" phrase the kitchen stops at as soon as it sees it. One wrong line on the slip and the dish comes out wrong, however good the cook is.

4.2 Removed parameters

According to Anthropic's Versions page, from API version 2026-10-21 the parameters temperature, top_p and top_k are removed: a request that sends any of them gets a 400 error on every model [R1]. The lab observed with anthropic 2.3.0 (2026-10-31) that messages.create() no longer accepts temperature, and passing that parameter raises TypeError.

Why a tester cares: old code, for example code written for an earlier SDK version, may still pass temperature. When the SDK or the API version is upgraded, that code breaks. A test that asserts "the client never sends temperature, top_p, top_k" protects you across upgrades.

Good vs bad. Old code that sends a removed parameter:

# "for stable answers" - breaks after the SDK upgrade
msg = client.messages.create(model=model, max_tokens=300, temperature=0, messages=messages)

The good way: drop the parameter (if you want steadier answers, say so in the prompt, L1-M02), and keep a test that stops it from coming back (this test is already in tests/test_l02_params.py):

def test_removed_sampling_parameters_are_never_sent(client, api):
    ask(client, "hi")
    assert not {"temperature", "top_p", "top_k"} & set(api.requests[0]["body"])

This test is deterministic and runs on every commit; it fails as soon as someone adds one of the three parameters back.

4.3 Test the request, not the model

Question Checked by Deterministic?
Does the client send the right system prompt? Contract test on the request (fake API) Yes
Does the client mark a truncated reply? The fake returns stop_reason: "max_tokens" Yes
Does the model answer briefly when max_tokens is low? Live test No: it depends on the model

Common misconception: "Set max_tokens low and the model will answer concisely." max_tokens is a hard limit on the number of tokens, not an instruction: when the limit is reached, the output is cut off (stop_reason: "max_tokens"), even mid-sentence. If you want a short answer, write that in the prompt (L1-M02), and keep max_tokens large enough.

Everyday example. Checking the slip that the waiter sends to the kitchen (right dish, right note) gives the same result every time; judging the taste depends on who is cooking that day. A contract test checks the slip; answer quality is a job for live tests and Level 2.

Good vs bad. Same goal, "a truncated reply is not shown as a full reply":

Weak test Good test
A live test sends max_tokens=20 and asserts the answer is "short": the result changes with the model, and it never checks how the code handles it The fake returns stop_reason: "max_tokens", the test asserts reason == "truncated" and that the text carries the […] mark

The good test behaves identically on every run, and checks exactly what the product's code is responsible for.

5. Technical deep dive

5.1 The fake API records the request

Every request the SDK sends to FakeClaudeAPI is stored in api.requests: path, headers (with the header names converted to lower case) and body (the parsed JSON). A test can assert the entire body with a single == comparison. That is the strictest way to write a contract test: add a new parameter without updating the test and the test fails.

Worked example (real run). The code below calls ask() once with stop_sequences, prints each key of the recorded body, then makes the fake return six stop reasons in turn (the second part is used in section 5.2). Run it from the lab folder:

python - <<'EOF'
import json, os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"
from lab.fake_api import FakeClaudeAPI, Reply, message
from lab.tutor_client import ask, make_client

with FakeClaudeAPI() as api:
    client = make_client(base_url=api.base_url)
    ask(client, "I has a cat", model="claude-sonnet-5-5", max_tokens=200, stop_sequences=["###"])
    body = api.requests[0]["body"]
    for key in sorted(body):
        print(f"{key:<14} = {json.dumps(body[key], ensure_ascii=False)[:60]}")
    for stop in ["end_turn", "stop_sequence", "max_tokens", "refusal", "pause_turn", "tool_use"]:
        api.queue(Reply(body=message("I have a cat.", stop_reason=stop)))
        r = ask(client, "I has a cat")
        print(f"{stop:<14} -> ok={r.ok!s:<5} reason={r.reason:<15} text={r.text!r}")
EOF

The first part of the output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):

max_tokens     = 200
messages       = [{"role": "user", "content": "I has a cat"}]
model          = "claude-sonnet-5-5"
stop_sequences = ["###"]
system         = "You are LinguaBot, an English grammar tutor. Correct the le

Line by line: max_tokens, model and stop_sequences are the values you passed; messages is built by ask() from the learner text; system is added by ask() itself (printed cut at 60 characters). There is no temperature. The contract test in section 8.2 asserts exactly this dict with one ==.

5.2 How ask() handles stop reasons

if msg.stop_reason == "refusal":
    return TutorResult(False, "Mình không thể hỗ trợ yêu cầu này.", "refused", msg._request_id, *usage)
if msg.stop_reason in ("max_tokens", "model_context_window_exceeded"):
    return TutorResult(True, text + " […]", "truncated", msg._request_id, *usage)
if msg.stop_reason in ("end_turn", "stop_sequence"):
    return TutorResult(True, text, "complete", msg._request_id, *usage)
# Fail closed: a stop reason this client does not handle (pause_turn, tool_use, a new value) is not shown.
return TutorResult(False, "Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.", "unexpected_stop", msg._request_id, *usage)

In English, the two Vietnamese messages read: "I can't help with this request." and "Something went wrong. The technical team has been notified."

  • A refused reply: the UI shows a friendly, approved sentence, not empty content.
  • A truncated reply: still shown, but with a […] mark so the learner knows. This is LinguaBot's product decision, and the tester verifies that it is implemented correctly.
  • Any other stop reason (pause_turn, tool_use, or a new value in the future) is not shown as a complete answer: the client reports unexpected_stop. This is the fail-closed principle learned in L1-M01-L04.
  • *usage passes the two token counts into TutorResult. The * "spreads" a tuple into separate arguments.

Worked example (real run). The second part of the output from section 5.1, the same text 'I have a cat.' with six stop reasons:

end_turn       -> ok=True  reason=complete        text='I have a cat.'
stop_sequence  -> ok=True  reason=complete        text='I have a cat.'
max_tokens     -> ok=True  reason=truncated       text='I have a cat. […]'
refusal        -> ok=False reason=refused         text='Mình không thể hỗ trợ yêu cầu này.'
pause_turn     -> ok=False reason=unexpected_stop text='Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.'
tool_use       -> ok=False reason=unexpected_stop text='Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.'

The same text, six outcomes: two reasons for a complete reply, one reply shown with the […] mark, and three reasons that do not show the model's text. This is the table you give the product owner to approve.

Everyday example. It is like the counter that hands out lab test results: the clerk reads the "notes" box before handing over the sheet. "Complete": hand it over; "sample insufficient": hand it over but stamped "incomplete"; a note they have never seen before: keep the sheet and ask the doctor, do not just give it to the patient.

6. The QA perspective

  • What to test: the body of the request (model, max_tokens, system, messages, stop_sequences); no removed parameters; handling of max_tokens, model_context_window_exceeded, refusal, stop_sequence.
  • Why: this is the only deterministic part of an LLM feature, so it can be tested fully with a fake.
  • What can go wrong: the system prompt is lost after a refactor; max_tokens is set too low to "save money"; an old parameter breaks the request after an SDK upgrade; a truncated reply is shown as a complete reply.
  • Expected behaviour: decided by the product owner for each stop reason (what to show, whether to retry).
  • How to detect it: contract tests on the request; a fake that returns each kind of stop reason.
  • How to report it: attach the request body (with sensitive data removed) and the stop reason; record the SDK version.

7. Real-world scenarios

Scenario 1 - An SDK upgrade (fictional). The team upgrades anthropic to a new version. Code that calls messages.create(..., temperature=0) "for stability" starts raising TypeError in production. A "does not send removed parameters" test could have caught this in CI, before deployment.

Scenario 2 - A copilot that summarises business reports (fictional). max_tokens is set to 200 to reduce cost. Long reports are cut off mid-sentence and shown as if complete. Test: the fake returns stop_reason: "max_tokens", and you check whether the UI marks the summary as incomplete.

8. Hands-on tutorial

8.1 Running the demo

python -m lab.demo l02

Actual output (2026-10-31):

request body keys: ['max_tokens', 'messages', 'model', 'system']
max_tokens reply -> reason=truncated text='The present simple is used for […]'
refusal reply    -> reason=refused text='Mình không thể hỗ trợ yêu cầu này.'
temperature=0.2  -> TypeError: Messages.create() got an unexpected keyword argument 'temperature'

In English, the refusal text reads: "I can't help with this request."

Reading the result:

  • The body has only four keys: max_tokens, messages, model, system. There are no removed parameters.
  • The max_tokens reply is marked […]; the refusal reply is replaced by the friendly sentence.
  • The last line is the SDK rejecting temperature before the request is sent.

8.2 A contract test for the whole request

def test_request_matches_the_contract(client, api):
    ask(client, "She go to school", model="claude-opus-5-5", max_tokens=120)
    body = api.requests[0]["body"]
    assert api.requests[0]["path"] == "/v1/messages"
    assert body == {"model": "claude-opus-5-5", "max_tokens": 120, "system": SYSTEM,
                    "messages": [{"role": "user", "content": "She go to school"}]}

8.3 Running the tests

python -m pytest tests/test_l02_params.py -v

Expected result: 10 passed. test_truncated_reply_is_marked runs with two stop reasons, and test_unhandled_stop_reasons_fail_closed with three stop reasons, thanks to parametrize.

8.4 Troubleshooting

Symptom Cause Fix
AssertionError in the contract test after you add a parameter The test compares the whole body Update the test deliberately: a new parameter is a contract change
TypeError: ... unexpected keyword argument 'temperature' The code passes a removed parameter Drop that parameter; control the behaviour through the prompt

9. Independent exercise

Problem: The product team wants to use stop_sequences=["###"] to cut off long explanations.

Tasks:

  1. Copy exercises/test_l02_stop_sequence.py into tests/.
  2. Assert that the request sends stop_sequences with the right value.
  3. Assert that a reply with stop_reason: "stop_sequence" is reported by ask() as complete.
  4. Write 3-5 sentences: should stop_sequence be treated as "complete"? What question do you ask the product owner?

Test data: the fake returns message("She goes to school.", stop_reason="stop_sequence").

Deliverable: the test file and the comment.

Acceptance criteria: the test passes; the comment names at least one risk of treating stop_sequence as complete.

Hint: api.requests[0]["body"]["stop_sequences"].

9.1 Extra exercise: write the contract first, run second

Problem (about 20 minutes): a good contract test starts with you predicting the request and how the response is handled, and only then running. Every failing test is a place where your understanding differs from the code.

Tasks:

  1. Copy exercises/test_l02_extra_contract.py into tests/.
  2. TODO 1: write EXPECTED_BODY, the exact body that ask(client, "I has a cat", **CALL) sends, using only sections 4.1, 5.1 and the code of ask() (do not print it first).
  3. TODO 2: write EXPECTED_REASON, the reason that ask() reports for the six stop reasons in the file.
  4. Run python -m pytest tests/test_l02_extra_contract.py. For each failing test, write one line: what did you predict wrongly?

Acceptance criteria: untouched, 9 failed with a TODO message; when done, 9 passed.

Hint: CALL has stop_sequences, the contract in section 8.2 does not. There is one parameter that ask() always adds even though you do not pass it.

9.2 Real-world scenario: "lower max_tokens to save money"

Context (fictional): LinguaBot's product owner wants to lower max_tokens from 1,024 to 150 "to cut costs". Last month's logs (synthetic data) show: model Opus 5.5, on average 300 input tokens and 180 output tokens per answer; half of the answers are longer than 150 tokens.

Your task: write a half-page decision note for the product owner: what will happen, how much is saved (using the price table in L01 section 4.2), the tests you will run before the change, and your recommendation.

A good answer has:

  • a clear statement that max_tokens is a hard limit: answers get cut off, not more concise;
  • two numbers: the worst-case cost per request before and after, and the actual cost before and after, with the calculation;
  • the effect on learners: about half of the answers carry the […] mark;
  • at least two tests with the fake: max_tokens in the contract changed on purpose, and a max_tokens reply being marked;
  • another way to cut cost (for example asking for brevity in the prompt, or a cheaper model after an evaluation), and one question for the product owner.

10. Knowledge check

0/16 done · Results are kept in this browser only.

P02 · True or false

Setting max_tokens low is a reliable way to make the model answer concisely.

P03 · Short answer

Why is a contract test that compares the entire body better than checking each key separately? Name one drawback.

P04 · Short answer

According to the Versions page, what happens to a request with temperature on API version 2026-10-21?

P05 · Short answer

(Scenario) After a refactor, the bot starts answering in English instead of Vietnamese. Which request test do you write first, and why?

P06 · Fill in the blank

According to §8.1, the demo python -m lab.demo l02 prints request body keys: ['max_tokens', 'messages', 'model', '___'], and the last line shows that temperature=0.2 raises a ___ error.

P07 · Spot the bug

The stop-reason handling below is copied from ask() (§5.2) but has one defect. Find it.

if msg.stop_reason == "refusal":
    return TutorResult(False, "Mình không thể hỗ trợ yêu cầu này.", "refused", msg._request_id, *usage)
if msg.stop_reason in ("max_tokens", "model_context_window_exceeded"):
    return TutorResult(True, text + " […]", "truncated", msg._request_id, *usage)
if msg.stop_reason in ("end_turn", "stop_sequence"):
    return TutorResult(True, text, "complete", msg._request_id, *usage)
# Fail closed: a stop reason this client does not handle (pause_turn, tool_use, a new value) is not shown.
return TutorResult(True, "Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.", "unexpected_stop", msg._request_id, *usage)

P08 · Match

Using the code in §5.2, match each stop_reason with the reason that ask() returns.

P09 · Recall

Lesson: L1-M03-L01

Lesson L01: where does the SDK read the request ID from, and what does a tester use it for?

P11 · Multiple choice

In the output of the worked example in §5.2, which stop reason gives a reply that is shown with the […] mark?

P12 · Fill in the blank

In the worked example of §5.1, the recorded body has ___ keys; the key that ask() always adds even though you do not pass it is ___.

P13 · True or false

In the output of §5.2, both pause_turn and tool_use give ok=False and do not show the model's text.

P14 · Select all that apply

According to §4.3, which tests are deterministic and can run entirely with the fake API?

P15 · Apply now

In code-labs/l1-m03, run the code from the worked example of §5.1. Then make two changes: remove stop_sequences=["###"] from the ask(...) call, and add "model_context_window_exceeded" to the end of the list of stop reasons. Run it again.

Checklist

P16 · Apply now

In code-labs/l1-m03, do the extra exercise in §9.1: copy exercises/test_l02_extra_contract.py into tests/, fill in both TODOs before printing anything, then run python -m pytest tests/test_l02_extra_contract.py.

Checklist

11. Summary

  • Concepts: request parameters and their risks; max_tokens is a hard limit; parameters removed in API version 2026-10-21; testing the request is different from testing the model.
  • Skills: contract tests for the body; testing stop-reason handling with a fake; protecting code across SDK upgrades.
  • Traps: using max_tokens instead of an instruction; showing a truncated reply as a complete reply; keeping old parameters.
  • You can now: write contract tests for the API-calling layer of an LLM feature.

12. References

ID Title Publisher URL Accessed Relevance
R1 Versions (API version 2026-10-21) Anthropic https://platform.claude.com/docs/en/api/versioning 2026-10-31 temperature, top_p, top_k removed, return 400
R2 Messages API reference Anthropic https://platform.claude.com/docs/en/api/messages 2026-10-31 Required parameters; the stop_reason values

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Contract test Test khẳng định "hợp đồng" dữ liệu giữa hai bên
Request body Nội dung JSON của request
Stop sequence Chuỗi khiến model dừng sinh output
Removed parameter Tham số đã bị API loại bỏ
SDK upgrade Nâng cấp phiên bản thư viện SDK