Maya asked a model to describe Leo’s next show, and it wrote two sentences Leo liked at once. Then she pasted the list of seats still for sale and asked how many there were. The model said 140.
“It writes better than I do,” Leo said. “And it can’t count?”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
Module 1 used a model as a black box that takes a prompt and returns an answer. This module opens the box, so you can predict where a model will be right, where it will be wrong, what each call costs and what it remembers. You’ll also make your first call to a model from TypeScript, which every later module builds on.
After this module, you can:
- call a Claude model from TypeScript and read what comes back: the text, why it stopped, and how many tokens it used
- explain what a token is, how many fit in the context window, and why numbers, spelling and other languages behave differently
- explain how the model picks each piece of its answer, and why the same prompt gives different answers
- say where a model’s skills come from, and predict which tasks it will do well and which it will get wrong
- keep a conversation going by sending the history yourself, and say what that costs
Two sentences right, one number wrong
Suppose you send a model two requests, in two separate calls. The first asks for writing:
Write a two-sentence description for a jazz night at Leo's club, Friday at 8 pm.
The second asks for a count. Your code builds the list of seats (lab step 4), and the prompt starts and ends like this:
These seats are still for sale: A1, A2, A3, A4, A5, A6, A7, A8, A9, A10,
A11, A12, A13, A14, B1, B2, ... K10, K11, K12, K14.
How many seats are in this list? Answer with a number only.
The full prompt lists every seat. There are 137, in ten rows of 14 seats minus three seats that are held.
Pause and predict. Which of the two requests is the model more likely to get wrong, and why?
Answer
The count. A show description has thousands of acceptable answers, and the model was trained on a huge amount of text that includes descriptions like it. The count has one right answer, and getting it means keeping track of 137 items that the model sees as hundreds of small pieces of text. Each section below explains one part of that answer.
When you run both prompts in the lab, compare the description with the count. A model may get the count right on one run and wrong on the next, so run it more than once.
Karpathy gave two failures of this kind in his June 2025 talk Software Is Changing (Again). One model insists 9.11 is greater than 9.9, and another says “strawberry” has two r’s. A model that writes a good paragraph and then gets a small fact wrong is common, and the sections below explain why.
So this module answers one question. What is the thing on the other end of the call, so that you can predict its answers, its mistakes and its cost?
What one call sends and gets back
Every program in this course talks to the model the same way. It sends an HTTPS request to the Claude API’s /v1/messages endpoint, and a JSON response comes back. Anthropic’s official TypeScript library, @anthropic-ai/sdk, builds the request for you. Version 1.12.0 was current on 2026-11-22.
Here is the core of the lab’s first program:
// Excerpt from first-call.ts (the full file is in lab step 2)
const message = await client.messages.create({
model: "claude-haiku-5-5",
max_tokens: 1000,
output_config: { effort: "low" },
messages: [{ role: "user", content: "Write a two-sentence description ..." }],
});
Figure 1 shows what travels over the network when this line runs.
(Developer) [first-call.ts + SDK] [Claude API]
| | |
| node first-call.ts | |
|------------------->| |
| | POST /v1/messages |
| | anthropic-version: 2026-10-21 |
| | your API key |
| | { model, max_tokens, |
| | output_config, messages } |
| |------------------------------->|
| | | runs [Model]
| | { content, stop_reason, usage }|
| |<-------------------------------|
| printed response | |
|<-------------------| |
Figure 1: one call is one HTTP request with the whole conversation in it, and one JSON response.
The request names four things:
modelis the model’s ID.claude-haiku-5-5is Claude Haiku 5.5, which this course uses for small tasks.max_tokensis the most tokens the model may write in this answer. The API requires it.output_config.effortsets how much the model may think before it answers (explained below).messagesis the conversation so far, as a list of turns, each with arole(userorassistant) and itscontent.
The Claude docs show this example response for a request that says hello:
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"content": [{ "type": "text", "text": "Hello!" }],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": { "input_tokens": 12, "output_tokens": 6 }
}
Three fields matter on every call:
contentis a list of blocks. The answer is in the blocks whosetypeis"text".stop_reasonsays why the model stopped.end_turnmeans it finished.max_tokensmeans it hit your limit, so the answer is cut off. Module 4 usestool_use; the other values (stop_sequence,pause_turn,refusal,model_context_window_exceeded) are rarer.usagecounts the tokens the model read (input_tokens) and wrote (output_tokens). You pay for both.
The content list can also start with a different block. Thinking is text the model writes to work a problem out before it writes the answer. The response may leave the thinking text out, but you pay for its tokens as output, and they count toward max_tokens. The effort setting controls how much of it the model may write. The SDK’s levels are low, medium, high, xhigh and max. Haiku 5.5’s default is medium (models overview, checked 2026-11-22), and the lab uses low to keep its calls short.
An API key costs money. Each call is billed by the tokens in usage, at the prices on the Claude pricing page. If your account has no credit, the API answers with a 402 and the error type billing_error. The free path, Ollama on your own laptop, runs the same code against a smaller model (see the lab).
You could also send the request with fetch or curl and no SDK. The SDK adds types, reads your key from the environment and retries temporary failures twice by default (SDK repository, version 1.12.0). Raw HTTP wins only where you can’t install a package, such as a shell script.
What changed recently is the version header. SDK 1.0.0 (October 21, 2026) was the first to send anthropic-version: 2026-10-21; the 0.x versions sent 2023-06-01. That API version removed the sampling settings, as Module 1 showed, so code copied from older examples can fail with a 400 error (migration guide).
Text goes in as tokens
Module 1 said a token is a small piece of text, often part of a word. Here is how text becomes tokens, and why it matters for the seat count.
A tokenizer is the program that splits text into tokens before the model sees it. Each token then becomes a number, its token ID, from a fixed list of tokens called the vocabulary. So the model never receives letters or digits. It receives a list of IDs.
Claude’s tokenizer isn’t public. Anthropic’s old tokenizer package on npm says in its README that it stopped being accurate with the Claude 3 models. So Figure 2 uses OpenAI’s o200k_base tokenizer, through the tiktoken 0.14.0 library, run on 2026-11-22. You can paste the same text into Tiktokenizer, choose o200k_base, and see the same pieces.
| Text | Characters | Tokens | Pieces |
|---|---|---|---|
strawberry |
10 | 3 | st raw berry |
strawberry (leading space) |
11 | 1 | strawberry |
STRAWBERRY |
10 | 4 | ST RAW B ERRY |
9.11 > 9.9 |
10 | 8 | 9 . 11 > 9 . 9 |
1234567890 |
10 | 4 | 123 456 789 0 |
TinyTickets |
11 | 2 | Tiny Tickets |
Xin chào, tôi muốn mua hai vé. (Vietnamese) |
30 | 10 | Xin ch ào … |
Figure 2: OpenAI’s o200k_base tokenizer splits words, numbers and languages into pieces of different sizes. Claude’s tokenizer splits differently.
Three things in the table explain failures you’ll meet:
- Letters are hidden inside IDs. In this tokenizer,
strawberrywith a leading space is one token, ID 101830. To count its r’s, the model must know which letters ID 101830 stands for, and it only knows that from text it read in training. - Digits come in chunks.
1234567890is four tokens, and in9.11the11is one token. So comparing 9.11 with 9.9 means comparing chunks, not reading digit by digit. - Other languages cost more per character in some tokenizers. The Vietnamese sentence is 10 tokens here and 17 in OpenAI’s older
cl100k_basetokenizer. The price and the context window are counted in tokens, so the same message costs a different amount in each language and each tokenizer.
Token counts belong to one model’s tokenizer. For Claude, you get them in two ways. After a call, usage reports them. Before a call, client.messages.countTokens() sends the same input to POST /v1/messages/count_tokens and returns { input_tokens } without running the model. It’s free, limited in requests per minute, and the docs call its result an estimate (token counting, checked 2026-11-22).
So when does each way fit? For a rough budget, estimate from the length of the text. Before you send a very large prompt, count it. For the bill, read usage.
What changed recently is the tokenizer itself. Claude Opus 4.7, released April 16, 2026, brought a new tokenizer, and the models since then produce about 30 percent more tokens for the same text (glossary). On these models, one million tokens is roughly 555,000 English words (models overview). So the same prompt has a different token count on an older model, and an old estimate can be too low.
Rule: The model reads token IDs, not letters or digits, so spelling, letter counts and digit-by-digit math are hard for it.
How much fits in the context window
Module 1 defined the context window as all the text the model reads on one call. Anthropic’s definition adds one part. The window also holds the response the model is writing. Figure 3 shows what fills it.
Context window of claude-haiku-5-5: 1,000,000 tokens
+------------------------------------------------------+
| system prompt (Module 3) |
| tool definitions (Module 4) |
| message 1 user |
| message 2 assistant |
| message 3 user, the newest |
|------------------------------------------------------|
| output: thinking + text, at most max_tokens |
| (room left over) |
+------------------------------------------------------+
Figure 3: everything you send and everything the model writes share one window, counted in tokens.
On 2026-11-22, Claude Haiku 5.5, Sonnet 5.5 and Opus 5.5 each had a window of 1,000,000 tokens, and could write at most 128,000 tokens per answer (models overview). Your code can read both limits for any model from GET /v1/models/{id}, which has returned max_input_tokens and max_tokens since March 18, 2026. That beats copying a number from a page that changes.
What happens past the limit depends on what overflows:
- The input alone is too long. The API refuses the request with a
400invalid_request_error, and its message says the prompt is too long. - The input fits, but input plus
max_tokensdoesn’t. On Claude 4.5 and newer models, the API accepts the request. If the answer fills the window, it stops withstop_reason: "model_context_window_exceeded".
A chat app may hide the limit from you by dropping the oldest messages first, but the API never drops anything on its own (context windows). The free path behaves differently. On a laptop with less than 24 GiB of graphics memory (VRAM), Ollama’s default window is 4k tokens (Ollama docs). When a chat grows past it, Ollama’s chat code drops older messages and logs it only at debug level (source).
A big window isn’t free to fill. You pay for every input token on every call. And Anthropic’s own docs say that “as token count grows, accuracy and recall degrade.” Module 3 decides what earns a place in the window.
What changed recently is the size. Earlier Claude models had 200,000 tokens. A 1-million-token window arrived as a beta for Sonnet 4 on August 12, 2025, and became generally available at standard prices on March 13, 2026, with Opus 4.6 and Sonnet 4.6 (release notes).
One token at a time, chosen by chance
The model writes its answer one token at a time. Next-token prediction is the model’s whole job. It reads every token in the context window and gives each token in its vocabulary a share, a number between 0 and 1, and the shares add up to 1. Module 1’s classifier did the same for four tags. Here the list holds every token the model knows, which is about 200,000 in OpenAI’s o200k_base (Anthropic doesn’t publish Claude’s number).
Then a program picks one token. Sampling is that pick, a random choice in which each token’s chance is its share. The chosen token goes at the end of the window, and the model runs again for the next one. Figure 4 shows the loop.
Context window (every token so far)
+--------------------------------------------------+
| ... The show starts at 8 pm. Doors open at |
+--------------------------------------------------+
|
v
[Model] --> a share for every token in the vocabulary
|
v
sampling picks one token: " 7"
|
v
" 7" goes at the end of the window; run again
until an end token --> stop_reason "end_turn"
or max_tokens --> stop_reason "max_tokens"
Figure 4: the model runs once for every token it writes, and sampling chooses each token.
So a 200-token answer is 200 runs and 200 random picks. That’s why a long answer takes longer than a short one.
Figure 5 shows what one pick looks like. The shares are invented for this example, not taken from any model.
After "The show starts at 8 pm. Doors open at" (invented shares)
token temperature 1.0 temperature 0.2
" 7" ######################## 0.609 0.982
" 7:30" ########### 0.274 0.018
" 6:30" ### 0.082 0.000
" 8" # 0.030 0.000
" noon" . 0.004 0.000
Figure 5: at temperature 1.0 an unlikely token keeps a small chance; a low temperature squeezes almost all the chance onto the top token.
Module 1 named temperature, the setting that made a model’s choices less random. Figure 5 shows what it did. It reshaped the shares before the pick. Claude now always samples with its defaults, “including a temperature of 1.0” (working with messages, checked 2026-11-22). Models from Opus 4.7 (April 16, 2026) reject other values, and API version 2026-10-21 rejects the setting on every model. The migration guide says: “No other setting replaces it.”
At temperature 1.0, the ” noon” token with a share of 0.004 comes out about 4 times in every 1,000 answers, on average. An answer of 200 tokens has 200 such picks. That’s why the same prompt gives different text on different runs, and why a wrong digit can turn up inside an answer that is otherwise good.
Reader’s question. If every token is a random pick, why is the text sensible at all? Because the shares are very uneven. For most positions, a few tokens hold almost all of the share, and the rest are close to zero, as in Figure 5.
Even the old setting of 0 didn’t make Claude repeatable. The glossary says that, even at temperature 0, “identical inputs might produce different outputs across API calls.” So with Claude, you test properties of an answer (it contains the right number, it is one of four tags), and you run it more than once. Module 8 builds that into evals.
The alternative is a local model. Ollama’s own API still accepts temperature and a seed, so with both fixed, the same prompt should give the same answer on the same machine (Ollama API). That’s useful while you debug a prompt, at the cost of a smaller model than the one you’ll run in production.
Where the model’s skills come from
Why does the model write so well? Its skills come from training in stages, and each stage explains part of what you see.
Pretraining is the first stage, in which the network learns to predict the next token on a huge amount of text. Anthropic’s glossary says Claude’s underlying model was “pretrained to predict the next word, given the previous context of text in the document.” For Claude Haiku 5.5, the text was “a proprietary mix of publicly available information from the internet” plus other data (Anthropic transparency hub).
A model after pretraining continues documents. The glossary says such models “are not inherently good at answering questions or following instructions.” Given “How many seats are left?”, it might continue with more questions, the way a forum page would.
Post-training is everything after pretraining that turns a document continuer into an assistant. The recipe OpenAI published in InstructGPT (March 2022) has two steps. First, the model is fine-tuned, which means trained further on example conversations that people wrote, so it learns the shape of a good answer. Then comes reinforcement learning.
Reinforcement learning is training in which the model writes an answer, something gives the answer a score, and the weights are nudged toward answers that score higher. It is like Module 1’s training loop, except that a score replaces the label. RLHF (reinforcement learning from human feedback) is reinforcement learning where the score comes from people. They rank two or more answers to the same prompt, and training makes the model prefer answers like the higher-ranked ones. Anthropic published its RLHF paper in April 2022.
Stage Learns from Result
------------- ----------------------------------- -------------------------
Pretraining [[Huge amounts of text]] continues any document
Post-training:
fine-tuning [[Conversations people wrote]] answers like an assistant
RLHF [[People's rankings of answers]] answers people prefer
RLVR [[Problems a program can check]] strong at math and code
Figure 6: each training stage adds a skill, and the data it learns from decides which one.
Figure 6 has one more stage, RLVR, which the next section explains.
The limit of this picture is that it is the published recipe, not Claude’s exact one. Anthropic’s transparency hub says Claude Haiku 5.5 had “substantial post-training, with the goal of making it an effective assistant”, and doesn’t name the methods. Training and fine-tuning models, and the math inside the network, are outside this course. The Claude API doesn’t offer fine-tuning.
Strong where answers can be checked, weak at counting
RLHF needs people to judge answers, which is slow. For some tasks, a program can judge instead, by checking that a math answer matches the answer key or that the code passes its tests. RLVR (reinforcement learning with verifiable rewards) is reinforcement learning where a program checks each answer and gives the score. The name comes from AI2’s Tulu 3 paper (November 22, 2024).
In his 2025 LLM Year in Review (December 19, 2025), Karpathy wrote that RLVR “emerged as the de facto new major stage” of training in 2025. He also wrote that it added a new setting, which is how long the model thinks before it answers. That’s what effort controls in your requests.
Karpathy’s Verifiability post (November 17, 2025), which Module 1 quoted, says what makes a task fit for this training. A task trains well when its environment can be reset, tried many times quickly, and scored automatically. Math and code fit all three. A good show description doesn’t, because no program can score it. So models improve fastest where a program can check the answer, and more slowly everywhere else.
Jagged intelligence is Karpathy’s name for the result, in which the same model solves very hard problems and fails very simple ones. He used it in an X post on July 25, 2024. The idea is shared. A 2023 study by Dell’Acqua, Mollick and others called it the “jagged technological frontier”. In the Year in Review, Karpathy adds that capability spikes where rewards are verifiable.
Now put the pieces together for the seat count:
- In OpenAI’s
o200k_base, a list like this one is about 410 tokens. Each seat code and its comma take about three, so no single token stands for “one seat”. - The model writes the number as its first output tokens. If it hasn’t thought first, nothing in the window holds a running count.
- The number comes out of next-token prediction and sampling, like every other token, so it can be close and still wrong.
So the model writes a description well because many good answers exist and it has read a huge amount of text like them. It miscounts because a count has one right answer, the items are hidden in tokens, and no running total is written down.
More thinking gives the model room to write a running count, so a higher effort may fix the count. It costs more output tokens, and it is still sampled text. Code is exact and costs nothing, and seats.length is 137 every time. Module 4 gives the model a tool, so it can ask your code to do the counting.
What changed recently is that the famous examples may pass. Your model may count the r’s in “strawberry” correctly. The question and its answer now appear in many places online, and current models can think before they answer, so a famous example is a weak test. That’s why the lab uses a list nobody has seen.
Rule: Give counting, arithmetic and exact lookups to code, and give the model the reading and the writing.
The model remembers nothing between calls
Suppose you call the model with “My name is Maya and I run TinyTickets.” Then, in a second call, you ask “What is my name?”
Pause and predict. What will the second answer say?
Answer
It can’t know. The second request holds only “What is my name?”, so the name isn’t in the context window. The model may say it doesn’t know, or ask.
An API is stateless when it keeps nothing from one request to the next. The Claude docs say: “The Messages API is stateless, which means that you always send the full conversational history to the API.” The weights don’t change between your calls. The only thing that carries over is what you send again.
A chat app feels as if it remembers, because the app resends the history on every turn. Your code must do the same. Figure 7 shows the failure and the fix.
Call 1 messages: [ user: "My name is Maya and I run TinyTickets." ]
--> [Model] --> <reply 1>
Call 2 messages: [ user: "What is my name?" ]
--> [Model] --> the name isn't there X
Call 3 messages: [ user: "My name is Maya and I run TinyTickets.",
assistant: <reply 1>,
user: "What is my name?" ]
--> [Model] --> the name is in the window
usage.input_tokens: larger than in call 1 or call 2
Figure 7: the model sees only the messages in this request, so the fix is to send the history again.
Karpathy described the same limit in his June 2025 talk. He compared an LLM to a coworker with amnesia, who doesn’t build up knowledge from one day to the next, and called the context window its working memory. The literal fact behind the comparison is the docs sentence above.
The cost is that every turn pays again for every earlier turn. In a chat of 20 turns, your first message is sent, and billed as input, 20 times. Module 3 shows prompt caching, which lowers the price of a repeated beginning.
What changed recently is where the history can live. Message threads, a beta launched on November 2, 2026, keep a conversation on Anthropic’s servers for a few minutes, so a request can send only the new message (message threads). The docs say that “the API rebuilds the conversation before it calls the model.” They also say: “Your application stays the source of truth for the conversation.” So the model still receives the whole history on every call.
One seat count, step by step
This trace follows the seat-count request from the problem section, from your code to the number on your screen. Figure 8 shows the path.
seats.ts Claude API
1 build 137 seat codes in a list
2 messages: [ user: list + question ] -----> 3 tokenize: about 410
tokens in o200k_base
4 [Model] predicts and
samples the answer,
one token at a time
5 content, stop_reason, usage <----------
6 compare the answer with seats.length (137)
Figure 8: the count crosses the network as hundreds of tokens, and the answer comes back as sampled text that your code must check.
Step 1: your code builds the list. Ten rows (A to K, with no row I), 14 seats each, minus the held seats C7, F2 and K13. seats.length is 137, and that number never leaves your program.
Step 2: the request. The list and the question go into one user message. The request also carries the model ID, max_tokens: 1000 and effort: "low".
Step 3: tokens. The API turns the text into token IDs. In OpenAI’s tokenizer the list is about 410 tokens; Claude’s count is in usage.input_tokens, which you read in your own run. No token says “137”.
Step 4: the answer. At low effort the model may think briefly or not at all. It predicts a share for every possible first token, sampling picks one, and the loop repeats until the end token.
Pause and predict. Will the answer be the same on five runs?
Answer
Not necessarily. Each run samples at temperature 1.0, so a different first token can be picked. If the model’s shares are spread over 136, 137 and 140, the runs can disagree with each other and with the truth.
Step 5: the response. content holds a text block with a number, stop_reason is end_turn, and usage gives the token counts. Run seats.ts in the lab to see the number your model gives.
Step 6: the check. Your code prints the model’s answer next to seats.length. Code is the only part of this trace that is sure to be right.
Lab: meet the model through the API
Time: about 25 minutes. You’ll make your first API call, count tokens, watch the model fail at counting and at remembering, and fix both in code.
You need:
- Node.js 26 LTS, as in Module 1. It runs
.tsfiles directly. - An API key from the Claude Console. It costs money per token (pricing). The lab makes about 15 short calls. Or use Ollama for free (see the note at the end of the lab).
Model used: claude-haiku-5-5 at effort: "low", checked on 2026-11-22. Each file reads the model from a MODEL environment variable, so a later model is a one-word change. With a new model, expect different token counts, limits and effort levels, and check the models overview.
The outputs described below are the shapes the docs give, not a recorded run. Your own run shows the real text and numbers.
Step 1: set up the folder and the key
Why: the lab needs one package, and ES modules, so files can use await at the top level.
mkdir model-lab
cd model-lab
npm init -y
npm pkg set type=module
npm install @anthropic-ai/sdk
export ANTHROPIC_API_KEY="your key here"
You should see @anthropic-ai/sdk under dependencies in package.json, version 1.12.0 or a later 1.x. The SDK reads ANTHROPIC_API_KEY from the environment, so the key never appears in your code.
Step 2: make the first call
Why: you see the whole response once, with every field, before you write code that keeps only the text. Create first-call.ts:
// first-call.ts
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY
const model = process.env.MODEL ?? "claude-haiku-5-5";
const started = Date.now();
const message = await client.messages.create({
model,
max_tokens: 1000,
output_config: { effort: "low" },
messages: [
{
role: "user",
content: "Write a two-sentence description for a jazz night at Leo's club, Friday at 8 pm.",
},
],
});
console.log(JSON.stringify(message, null, 2));
console.log(`took ${Date.now() - started} ms`);
Run it:
node first-call.ts
You should see a JSON object shaped like the docs example, with a content list holding a text block of two sentences, "stop_reason": "end_turn" and a usage object. The last line gives the time for this one call; yours will differ from run to run. Check whether your content list also holds a thinking block.
Pause and predict. Run it a second time. Will the two descriptions be the same?
Answer
Almost certainly not. Every token is sampled at temperature 1.0, so the wording changes, while the facts you gave (jazz, Leo’s club, Friday, 8 pm) usually stay. The output_tokens count changes with the wording.
Step 3: count tokens before you send
Why: you see that token counts follow neither characters nor words. Create count.ts:
// count.ts
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-haiku-5-5";
const texts = [
"strawberry",
"STRAWBERRY",
"TinyTickets",
"9.11 > 9.9",
"Xin chào, tôi muốn mua hai vé.",
];
for (const text of texts) {
const result = await client.messages.countTokens({
model,
messages: [{ role: "user", content: text }],
});
console.log(result.input_tokens, JSON.stringify(text));
}
Run node count.ts. You should see one count per text. Each count includes a few tokens the API adds around every message, so compare the counts with each other, not with Figure 2.
Step 4: make the model count, and watch it fail
Why: this is the failure from the opening, on your own machine. First, create ask.ts, a small helper that the next steps share. It keeps only the text blocks, and prints the token counts of each call:
// ask.ts: one call to the model, shared by seats.ts and memory.ts
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-haiku-5-5";
export async function ask(messages: Anthropic.MessageParam[]): Promise<string> {
const message = await client.messages.create({
model,
max_tokens: 1000,
output_config: { effort: "low" },
messages,
});
console.log(`[input_tokens=${message.usage.input_tokens} output_tokens=${message.usage.output_tokens}]`);
let text = "";
for (const block of message.content) {
if (block.type === "text") {
text += block.text;
}
}
return text;
}
The loop checks each block’s type, because the first block can be a thinking block. Now create seats.ts:
// seats.ts
import { ask } from "./ask.ts";
const rows = "ABCDEFGHJK".split(""); // there is no row I
const held = ["C7", "F2", "K13"];
const seats: string[] = [];
for (const row of rows) {
for (let n = 1; n <= 14; n++) {
const code = `${row}${n}`;
if (!held.includes(code)) {
seats.push(code);
}
}
}
const prompt = `These seats are still for sale: ${seats.join(", ")}.
How many seats are in this list? Answer with a number only.`;
const answer = await ask([{ role: "user", content: prompt }]);
console.log("model:", answer);
console.log("code: ", seats.length);
Pause and predict. Will the model’s number match seats.length on five runs?
Run node seats.ts five times. You should see code: 137 every time, and the model’s number next to it. If the model is right on every run, its answer still can’t show you whether it counted, so the next step applies either way.
If you want to see the cost of more thinking, change "low" to "high" in ask.ts and run once more. Compare output_tokens with the low-effort runs, then change it back.
Step 5: fix it by letting code count
Why: the count belongs to code, and the writing belongs to the model. In seats.ts, replace everything after the loop with these lines:
// Excerpt from seats.ts: code counts, the model writes
const count = seats.length;
const prompt = `Write one short sentence for a show page saying that ${count} seats are still for sale.`;
const sentence = await ask([{ role: "user", content: prompt }]);
console.log(sentence);
console.log(sentence.includes(String(count)) ? "number kept" : "number changed: check it");
Run node seats.ts. You should see one sentence with 137 in it, followed by number kept. The last line is a check in code. If the model ever writes the number in words or changes it, you see number changed: check it in place of a wrong page.
Step 6: ask a follow-up, and watch the model forget
Why: this shows that each call starts from nothing. Create memory.ts:
// memory.ts
import { ask } from "./ask.ts";
const intro = "My name is Maya and I run TinyTickets.";
const first = await ask([{ role: "user", content: intro }]);
console.log(first, "\n");
// A new call, without the history
const second = await ask([{ role: "user", content: "What is my name?" }]);
console.log(second, "\n");
Run node memory.ts. You should see a reply to the first message, then a second answer that most likely doesn’t contain “Maya”. Check yours.
Step 7: send the history yourself
Why: this is the fix, and it shows what the fix costs. Add this third call at the end of memory.ts:
// Excerpt from memory.ts: the same question, with the history sent again
const third = await ask([
{ role: "user", content: intro },
{ role: "assistant", content: first },
{ role: "user", content: "What is my name?" },
]);
console.log(third);
Run node memory.ts again. The third answer is likely to contain “Maya”, so check it. Now read the input_tokens lines. The third call’s count is larger than the first call’s or the second’s, because it carries the first exchange again.
Ollama note. For the free path, install Ollama (v0.40.17 was current on 2026-11-22; you need 0.14.0 or later) and run
ollama pull qwen3.5:4b, a download of about 3 to 4 GB. Then point the same files at it with three variables:export ANTHROPIC_BASE_URL=http://localhost:11434,export ANTHROPIC_API_KEY=ollama(the SDK needs a value, and Ollama ignores it) andexport MODEL=qwen3.5:4b. Ollama accepts the same requests through its Anthropic-compatible API. Step 3 doesn’t work there, because Ollama has no token counting endpoint; readusageinstead, which Ollama only approximates. A small local model may miscount more and follow instructions less well. Its default window on most laptops is 4k tokens, and older messages are dropped without an error when a chat grows past it. Start it withOLLAMA_CONTEXT_LENGTH=64000 ollama serveto raise that. Check whether the Anthropic-compatible API drops old messages the same way, for example withmemory.ts.
Going deeper
How a tokenizer learns its pieces
Most LLM tokenizers descend from byte-pair encoding, a method that starts from single characters (or bytes) and repeatedly merges the pair that appears most often in a large sample of text. Frequent words end up as one token and rare words as several. Sennrich, Haddow and Birch applied it to neural networks in 2015. Karpathy builds one from scratch in Let’s build the GPT Tokenizer (February 20, 2024). His Deep Dive into LLMs like ChatGPT (February 5, 2025) has chapters titled “models need tokens to think” (01:46:56) and “tokenization revisited: models struggle with spelling” (02:01:11).
Seeing the shares yourself
The Claude API returns no shares, because a Message has no per-token data. Ollama’s own API (not the Anthropic-compatible one) returns them since v0.12.11 (November 12, 2025), as log probabilities, the natural logarithm of each share. Math.exp(logprob) turns one back into a share.
curl http://localhost:11434/api/generate -d '{
"model": "qwen3.5:4b",
"prompt": "The show starts at 8 pm. Doors open at",
"raw": true,
"stream": false,
"logprobs": true,
"top_logprobs": 5,
"options": { "temperature": 0, "num_predict": 5, "seed": 42 }
}'
The response lists each token it wrote, with its log probability and the five most likely alternatives (Ollama API). If your model thinks before it answers, check whether you also need "think": false.
Ghosts, not animals
In Animals vs Ghosts (October 1, 2025), Karpathy wrote that LLM research “is about summoning ghosts”, not building animals that learn from experience. He said he holds the view with “double digit percent uncertainty”. The literal fact behind the analogy is the one this module has shown. The model is a fixed set of weights, trained to imitate text and then tuned with reinforcement learning. It learns nothing from your calls and keeps nothing outside its context window.
Common mistakes when you call a model
- Copying code written for older models. Symptom: a
400error for a request that setstemperature, or one whosemessagesend with anassistantturn (“This model does not support assistant message prefill. The conversation must end with a user message.”). Fix: remove both; say what you want in the prompt, and Module 3 makes the output format strict. - Reading
message.content[0].text. Symptom: TypeScript refuses it, or the text is missing because the first block is a thinking block. Fix: loop overcontentand keep the blocks whosetypeis"text", asask.tsdoes. - Expecting the model to remember. Symptom: the second call asks who you are. Fix: send the history in
messages, and log what you send. - Asking the model for a number you already have. Symptom: good prose with a wrong count, total or date in it. Fix: compute it in code, put it in the prompt, and check that the answer still contains it.
- Testing output with
===. Symptom: a test passes once and fails on the next run. Fix: test properties (contains 137, is one of four tags), and run each case more than once. - A missing key. Symptom: the SDK throws “Could not resolve authentication method…” before any request. A wrong key gets
401, and an account without credit gets402. Fix:export ANTHROPIC_API_KEYin the same terminal where you runnode. - A small window on Ollama. Symptom: a long chat forgets its beginning, with no error. Fix: start Ollama with
OLLAMA_CONTEXT_LENGTH=64000.
Check yourself
Scenario. Nina writes a script that emails each organizer a weekly summary. It pastes the week’s 2,000 orders into one request and asks the model for “the number of tickets sold and a friendly summary”. She tests it twice on the same week’s orders before it goes live. The totals differ, and one of them is 12 tickets too high. What went wrong, and how would you change the script?
Answer
Two things went wrong. Counting across 2,000 orders is the model’s weak spot. The orders are thousands of tokens, no token holds a running total, and the total comes out of next-token prediction like any other text. And each run samples at temperature 1.0, so the same input can give a different total.
Change the script so code computes the numbers, with SQL or orders.length, and puts them in the prompt. The model writes the friendly summary around them, and code checks that each number still appears in the email. The 2,000 orders fit in a window of 1,000,000 tokens. Still, sending them costs thousands of input tokens every week for a number that code computes for free.
- In a response, which field holds the answer, which says why the model stopped, and which says what you’re billed for?
- Why can a model spell “strawberry” correctly and still miscount its r’s?
- Why does the same prompt give different text on two runs, even with no setting changed?
- Why have models improved fastest at math and code?
- Your second call asks “What is my name?” and the model doesn’t know. What do you change, and what happens to
input_tokens?
Answers
- The text blocks in
contenthold the answer,stop_reasonsays why it stopped, andusagecounts the input and output tokens you pay for. - The model receives token IDs, and a word can be one token, so its letters are hidden inside an ID the model only knows from training text.
- The model picks every token by sampling at temperature 1.0, so an answer of many tokens has many chances to take a different turn.
- Their answers can be checked by a program, so reinforcement learning with verifiable rewards (RLVR) can score a huge number of attempts automatically.
- Send the earlier messages again in
messages, because the API is stateless;input_tokensgrows, because you pay for the history on every call.
Cheat sheet
What the model is, for the code that calls it
- A call:
POST /v1/messageswithmodel,max_tokensandmessages; back comecontent,stop_reasonandusage. - Tokens: text becomes token IDs, so letters and digits are hidden. Count Claude’s tokens with
countTokensorusage. - Context window: everything you send plus the answer, 1,000,000 tokens on Haiku 5.5 (2026-11-22).
- Writing: one token at a time, sampled at temperature 1.0, so runs differ.
- Training: pretraining continues text, post-training makes an assistant, RLVR makes it strong where answers can be checked.
- Jagged: good prose and a wrong count from the same model. Counting, math and lookups go to code.
- Stateless: send the whole history on every call, and pay for it on every call.
Figure 9 is the whole module in one picture: what you send, what the model does with it, and what comes back.
(Developer) --> messages (the whole history) ---------> [Model]
tokens, up to the context window trained: pretraining,
post-training, RLVR
<-- content + stop_reason + usage <--------- one sampled token
at a time
your code: counts, checks numbers, keeps the history
Figure 9: the model reads tokens and writes sampled tokens, and your code does the counting, the checking and the remembering.
Next, Module 3 decides what goes into the context window: a system prompt, examples, a strict output format, and what each token costs.
Sources
- Andrej Karpathy, Software Is Changing (Again), keynote at Y Combinator’s AI Startup School, June 17, 2025.
- Andrej Karpathy, post on X introducing “jagged intelligence”, July 25, 2024.
- Andrej Karpathy, Animals vs Ghosts, October 1, 2025; Verifiability, November 17, 2025; 2025 LLM Year in Review, December 19, 2025.
- Andrej Karpathy, Deep Dive into LLMs like ChatGPT, February 5, 2025, and Let’s build the GPT Tokenizer, February 20, 2024.
- Claude documentation, checked 2026-11-22: working with messages, context windows, token counting, models overview, glossary, migrating to API version 2026-10-21, message threads, release notes, pricing.
- Anthropic, transparency hub (Claude Haiku 5.5).
@anthropic-ai/sdkon GitHub, version 1.12.0.- Ollama docs: Anthropic compatibility, context length, generate API.
- Papers: Sennrich, Haddow and Birch, Neural Machine Translation of Rare Words with Subword Units, 2015; Ouyang et al., Training language models to follow instructions with human feedback, 2022; Bai et al., Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback, 2022; Lambert et al., Tulu 3, 2024; Dell’Acqua et al., Navigating the Jagged Technological Frontier, 2023.