Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 2: The anatomy of a request

Objectives: LO-2.1, LO-2.2, LO-2.3, LO-2.4
Prerequisites: Module 1
Time: about 6 hours: 2 for this reading, 2.5 for Lab 2, and 1.5 for the practice; PA1 follows, and takes about 3 more

Every prompt reaches a model inside a request, and every answer comes back inside a response. This module takes both apart, using the Claude Messages API as the example. You will build requests as data, read the parts of a response that code must check, and work out what a request costs before you send it. You will also see how a program holds a conversation with a model that remembers nothing, what that costs, and what to do when the conversation outgrows its budget. The course never sends a request, but everything here is what a real program sends and reads.

A request is a JSON object

A program talks to the Messages API by sending an HTTP POST request to https://api.anthropic.com/v1/messages, with three headers: x-api-key, which carries the account’s secret key; anthropic-version, which names the version of the API the program was written for; and content-type: application/json. The body is a JSON object. Here is one, as the Python dictionary that Lab 2 builds:

request = {
    "model": "claude-opus-5-5",
    "max_tokens": 300,
    "system": "You answer questions for the customers of a bicycle repair shop, in one sentence.",
    "messages": [
        {"role": "user", "content": "How often should I clean my chain?"},
    ],
}

The course builds alternating user and assistant turns and ends with the user’s message. The API combines consecutive messages that have the same role.

Prefill is gone

Older guides teach prefilling: ending messages with an assistant turn that holds the start of the answer, such as {, so the model continues from there. Anthropic’s documentation says that only Claude 4.5 and earlier models accept a prefill, and that all other models return an error for it. Current models get the same effect from clear format instructions (Module 3) and structured outputs (Module 8).

A response is a JSON object too

Here is an illustrative response to that request, in the documented shape. A person wrote its text for this course; no model produced it.

{
    "id": "msg_standin_0001",
    "type": "message",
    "role": "assistant",
    "model": "claude-opus-5-5",
    "content": [{"type": "text", "text": "Clean it once a month, or after any ride in the rain."}],
    "stop_reason": "end_turn",
    "stop_sequence": None,
    "usage": {
        "input_tokens": 41,
        "output_tokens": 18,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
    },
}

The usage counts are the truth about what a request cost. An estimate made before the request, from characters or words, is only a plan.

What a request costs

Anthropic prices each model per million tokens, separately for input, output, cache writes, and cache reads. The course’s data/prices.json records the November 26, 2026 rates for the three models used in the exercises.

ModelInputOutputCache write (5 minutes)Cache read
Claude Opus 5.5$4.00$20.00$5.00$0.20
Claude Sonnet 5.5$2.00$10.00$2.50$0.10
Claude Haiku 5.5$0.10$0.50$0.125$0.01

The prices are in US dollars per million tokens. Prices change, so check the pricing page before you rely on these. Four rules from the same page matter for planning:

A request’s cost CC is each count from usage times its price, divided by a million:

C=nin pin+nout pout+nwrite pwrite+nread pread1,000,000C = \frac{n_\text{in} \, p_\text{in} + n_\text{out} \, p_\text{out} + n_\text{write} \, p_\text{write} + n_\text{read} \, p_\text{read}}{1{,}000{,}000}

Worked example: one request, then ten thousand

The response above used 41 input and 18 output tokens on Opus 5.5:

C=41×4+18×201,000,000=164+3601,000,000=0.000524 dollarsC = \frac{41 \times 4 + 18 \times 20}{1{,}000{,}000} = \frac{164 + 360}{1{,}000{,}000} = 0.000524 \text{ dollars}

That is about a twentieth of a cent. Now plan a workload: 10,000 requests, each with a 1,500-token prompt and a 300-token answer, on Opus 5.5. One request costs (1,500 × 4 + 300 × 20) / 1,000,000 = 0.012 dollars, so the workload costs 120 dollars, or 60 in the Batch API. On Haiku 5.5, the same workload costs 3 dollars, or 1.50 in the Batch API. Whether Haiku does the task well enough is a separate question, which only an evaluation (Module 7) can answer.

Will it fit?

The context window holds the prompt and the answer together. The current Claude models each have a 1M-token window and can write at most 128K tokens in one response, according to Anthropic’s models overview. To leave room for the entire requested answer, add the input count to max_tokens and compare the sum with the window. The API can accept a prompt that fits on its own even if the full requested answer would exceed the window. If generation reaches that boundary, the stop reason is model_context_window_exceeded. The output limit still applies.

To check before you have a real count, estimate. Module 1’s rule of thumb, 2.5 characters per token, gives a 2-million-character manual about 800,000 tokens, which fits with room for a 4,000-token answer. Anthropic’s free token-counting endpoint gives a model-specific input estimate for supported request content. For a completed request, use the token counts in usage.

Conversations

The Messages API is stateless. The chat program in this example stores the conversation as a list and sends it with each new message. The model can use an earlier detail when the program includes it in the current request.

Worked example: what a conversation costs

A support chat has a 200-token system prompt. Each user message is about 60 tokens and each reply about 150. Request 1 sends 200 + 60 = 260 input tokens. Request 2 sends those, the first reply, and the new message: 200 + 210 + 60 = 470. Each request sends 210 more than the one before, so request 30 sends 200 + 29 × 210 + 60 = 6,350. Over 30 turns, the requests send 99,150 input tokens to carry 6,300 tokens of conversation. The total grows with the square of the number of turns, because every turn is paid for again by every request after it.

When the history outgrows its budget

Long conversations hit two limits: the context window, and the budget you set for cost. Three policies keep a history within a budget, and each loses something:

Prompt caching, in Module 10, makes the repeated part of each request cheaper without dropping anything, but it doesn’t make a history fit a window it has outgrown.

Why the model stopped

Every response gives a stop_reason. Anthropic’s documentation lists seven:

stop_reasonWhat happenedWhat code should do
"end_turn"The model finished its answerUse the text
"stop_sequence"The model wrote one of the request’s stop_sequencesUse the text; stop_sequence says which one
"max_tokens"The answer reached max_tokens and was cut offDon’t show it as complete; retry with more room, or shorten what you ask for
"model_context_window_exceeded"The answer filled the context window and was cut offShorten the prompt; more max_tokens won’t help
"refusal"The model declined to respondShow a fallback, and never present the content as an answer
"tool_use"The model is asking to call a toolRun the tool and send its result back (Module 8)
"pause_turn"A loop of server-side tools reached its limitSend the response back to let it continue; this course doesn’t use server-side tools

A refusal or a cut-off answer can arrive with HTTP 200. Read stop_reason before displaying the text. If the request fails, check the HTTP status instead. For example, HTTP 429 means the client reached a rate limit, and HTTP 529 means the service is overloaded. Anthropic’s API errors reference lists the other statuses.

Common misconceptions

Summary

Self-check

  1. A request’s messages ends with an assistant turn holding "{". What happens on Claude Opus 5.5, and what should the program do instead?

    Answer

    The API returns an error, because current models reject prefills. To get JSON, say so in the prompt and check the output in code (Module 3), or use structured outputs (Module 8).

  2. A response from Sonnet 5.5 reports 2,000 input tokens and 500 output tokens, with no caching. What did it cost?

    Answer

    (2,000 × 2 + 500 × 10) / 1,000,000 = 9,000 / 1,000,000 = 0.009 dollars, almost a cent.

  3. A prompt is 990,000 tokens, and the request sets max_tokens to 16,000. Will the answer have room in a 1M-token window?

    Answer

    No. 990,000 + 16,000 = 1,006,000, more than 1,000,000. If the answer runs long, it fills the window and stops with model_context_window_exceeded. Shorten the prompt or lower max_tokens.

  4. Why does a 40-turn conversation cost far more than four 10-turn conversations of the same messages?

    Answer

    Each request resends the whole history, so turn k pays again for all k − 1 turns before it, and the total grows with the square of the number of turns. Four short conversations each start over with an empty history.

  5. A response has stop_reason "max_tokens". Name two things the program could do, and say when each is right.

    Answer

    Retry with a larger max_tokens, when the answer is legitimately long. Or change the prompt to ask for less, when the answers are longer than they should be. In both cases, don’t show the cut-off text as complete.

Further reading