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.

Objectives: LO-2.1, LO-2.2, LO-2.3, LO-2.4
Prerequisites: the Module 2 reading and Lab 1
Time: about 2.5 hours

In this lab you build Messages API requests as Python dictionaries, read responses, price them, and plan a workload’s cost and its fit in the context window. Then you write a chat function that keeps a conversation’s history, trim that history to a budget, and handle every way a response can stop.

No cell sends anything over the network. Where a cell needs a model, a ScriptedModel from promptlab answers instead, from a script written in the cell. Its responses have the shape of real ones, but a person wrote their text, so they are illustrative, not model output.

Each exercise ends with a check cell that prints passed or fails with a message. Run the cells in order, from the top. Some cells fail on purpose until you finish the exercise above them.

Setup

1. A request is data

A request to the Messages API is a JSON object. In Python, it is a dictionary. This one asks for a one-sentence answer:

model names the model, max_tokens caps the length of the answer, system holds the instructions that apply to the whole conversation, and messages holds the conversation’s turns, oldest first, each with a role of "user" or "assistant". The last turn is the user’s, because the model writes the next one.

Exercise L2.1 (LO-2.1, ★★, about 20 minutes)

Write make_request(model, system, turns, max_tokens). turns is a list of strings, the conversation so far, starting with the user and alternating. Return the request dictionary, with the turns as messages whose roles alternate "user", "assistant", "user", and so on.

Raise ValueError with a message that says what is wrong when turns is empty, or when it ends with an assistant turn. A request that ends with an assistant turn asks the model to continue that text, which is called prefilling, and current Claude models reject it.

2. Reading a response

A response is a JSON object too. The model’s reply is in content, a list of blocks, each with a type. A plain answer has one block of type "text"; Modules 6 and 8 meet other types. stop_reason says why the model stopped, and usage counts the tokens the request used. Here is an illustrative response built by make_response, in the documented shape:

Exercise L2.2 (LO-2.1, ★, about 10 minutes)

Write response_text(response), which returns the text of every "text" block, joined in order with nothing between them. Skip blocks of any other type.

3. What a request costs

Prices are per million tokens, and differ for input, output, cache writes, and cache reads. The price table in data/prices.json was taken from Anthropic’s pricing page on the date it names. Output tokens cost five times as much as input tokens on all three models:

A request’s cost CC adds up each kind of token 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}

where each nn is a count from usage and each pp a price from the table. Haiku 5.5 has one more rule: if a request’s prompt, which counts its input, cache-write, and cache-read tokens together, is over 100,000 tokens, the whole request pays the long_prompt prices.

Exercise L2.3 (LO-2.2, ★★, about 25 minutes)

Write request_cost(usage, model, prices), which returns a request’s cost in dollars from its usage dictionary. Price cache writes at the 5-minute price. Apply Haiku’s long-prompt prices when the model’s entry has a long_prompt and the prompt is over its above_tokens.

The last line shows the long-prompt rule’s cliff: at 100,001 prompt tokens, every token of the request costs five times as much. The next cell plots the cost of one request with 1,000 output tokens against its prompt length, for Haiku 5.5 and Sonnet 5.5, on a logarithmic scale so both fit. Before you run it, predict whether the Haiku line ever crosses the Sonnet line.

The Haiku line, solid and orange, jumps fivefold at 100,000 tokens but stays well below the dashed blue Sonnet line, which costs 20 times as much per input token at short prompts and 4 times as much at long ones.

Exercise L2.4 (LO-2.2, ★★, about 15 minutes)

Plan a workload before you run it. Write workload_cost(requests, input_each, output_each, model, prices, batch=False): the cost of requests requests with the same usage, with no caching, taking the batch discount off both input and output when batch is true. Then use it to answer the question in the check cell.

The cheapest model isn’t automatically the right one: it has to do the task well enough, which only an evaluation can tell you. Module 7 builds one, and Module 6 weighs cost against accuracy.

4. Will it fit?

The context window must hold the prompt and the answer together. Each current model’s window and its largest answer are in the price file, from Anthropic’s models overview. Before you have a real token count, promptlab.rough_token_count estimates one from the overview’s rule of thumb of 2.5 characters per token.

Exercise L2.5 (LO-2.2, ★, about 10 minutes)

Write fits(prompt_tokens, max_tokens, model, prices), which is true when the prompt plus the whole answer fit in the model’s context window, and max_tokens is within the model’s output limit.

5. Conversations

The model keeps nothing between requests. To hold a conversation, a program keeps the history itself and sends all of it with each new message. The next exercise builds that loop, and a ScriptedModel plays the model: it answers from its script and records each request, so you can see what your code sent.

Exercise L2.6 (LO-2.3, ★★, about 20 minutes)

Write chat(model, history, user_text, system, max_tokens=300). model is a function that takes a request and returns a response, and history is a list of message dictionaries, which chat changes in place. Append the user’s message, send a request for the model "claude-haiku-5-5" with the whole history, then append the reply as an assistant message and return its text. Use response_text.

The third reply could mention the flat tire only because the third request contained the first message. The scripted model didn’t read it, of course, but a real one could only answer from what that request held.

Resending the history has a price: every request pays again for every earlier turn. The next cell estimates the input tokens of a 30-turn conversation, with a 200-token system prompt, 60-token user messages, and 150-token replies, and plots them.

The bars grow by 210 tokens a turn, so the total grows with the square of the number of turns: 30 turns send about 99,000 input tokens to carry 6,300 tokens of conversation. Prompt caching, in Module 10, makes the repeated part cheaper; trimming the history makes it shorter.

Exercise L2.7 (LO-2.3, ★★★, about 30 minutes)

Write trim_history(messages, budget, count_tokens), which returns a new list: the most recent messages whose tokens, counted with count_tokens(text), add up to no more than budget. Drop whole exchanges, a user message and the reply after it, from the oldest end, so the list still starts with a user message. Always keep the last message, the user’s newest. Raise ValueError if that message alone is over the budget. Don’t change the list passed in.

Dropping the oldest exchange is the simplest policy, and it loses facts like the bike’s color. Two other policies are to summarize older turns or store a needed fact, such as an order number, separately and include it as data in the next request.

6. Why the model stopped

Every response says why it stopped. Code that reads content without checking stop_reason will one day show a user half an answer, or an empty one. The API documentation lists seven stop reasons:

  • "end_turn": the model finished its answer.

  • "stop_sequence": the model wrote one of the request’s stop_sequences.

  • "max_tokens": the answer reached the request’s max_tokens and was cut off.

  • "model_context_window_exceeded": the answer filled the context window and was cut off.

  • "refusal": the model declined to respond.

  • "tool_use": the model is asking to call a tool, which Module 8 handles.

  • "pause_turn": a loop of server-side tools reached its limit, which this course doesn’t use.

Exercise L2.8 (LO-2.4, ★★, about 25 minutes)

  1. Write final_text(response). Return the text for "end_turn" and "stop_sequence". Raise Truncated for the two cut-off reasons and Refused for a refusal. For any other reason, raise ValueError naming it.

  2. Write ask(model, request, ceiling), which sends the request and returns final_text of the response. If the answer was cut off by max_tokens, send a copy of the request with max_tokens doubled, up to ceiling, and try again. If it is still cut off at the ceiling, let Truncated propagate. Never change the request passed in.

Doubling max_tokens is right only when the answer was legitimately long. If a prompt makes answers longer than they should be, more room just costs more: fix the prompt instead, as Module 3 does. A refusal is a different case: it isn’t a length problem, so more room won’t change it.

Summary

  • The request dictionary supplies a model, max_tokens, and messages. The lab adds a system prompt. A response holds content blocks, a stop reason, and token usage.

  • Cost is each kind of token times its price. Output costs five times as much as input on the current models, the Batch API halves both, and Haiku 5.5 charges more for prompts over 100,000 tokens.

  • The context window holds the prompt and the answer together, and max_tokens has its own limit.

  • A conversation lives in the program, which resends the whole history every time. Its cost grows with the square of its length, and trimming it loses what it drops.

  • Check stop_reason before you use the text: a cut-off answer and a refusal are normal responses, not errors the API reports.

Next, do the Module 2 practice, then PA1.