Claude Certified Developer · Foundations

Module 1: What the words mean

Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.

Practice this module

On this page

Claude Developer (Foundations) · "Ship your first Claude feature to production" · study notes

Facts in these notes were checked against Anthropic's public docs on 2026-11-25. Model IDs, prices and limits change, so check them again before you rely on them. Anything we could not confirm is marked check before relying on it.


What you'll be able to do

By the end of this module you can:

  • Make a Messages API call from TypeScript (or Python) with the official SDK, and read every part of the response.

  • Explain tokens, context window, max_tokens, system prompt, adaptive thinking and effort in one plain sentence each.

  • Count tokens before you send a request and turn a usage block into a cost.

  • Pick a model and an effort level for a task, and say why.

  • Check stop_reason before you trust content, and handle each value.

  • Describe what happens between your code and the model: SDK, HTTP, retries, rate limits and errors.

The running example

Every module in this course adds a layer to one feature, so the notes match the videos.

Ticket triage for a multi-tenant SaaS help desk. A support ticket comes in. Claude reads it (and any screenshot or PDF attached), sets a category and priority as strict JSON, looks up the customer's account through a tool that only sees that tenant's data, and streams a draft reply that a human approves.

All data is fake. The tenants are acme, globex and himal-traders, and the users are Alice and Bob. The stack is TypeScript on Node 22 with the official @anthropic-ai/sdk. A few snippets also show the Python SDK (anthropic) for readers who prefer it.

In Module 1 we only make the first call: classify one ticket and understand everything that comes back.


Key idea 1: one endpoint, one request, one response

Almost everything you do with Claude goes through one endpoint: POST /v1/messages, the Messages API. Tools, JSON output, images, PDFs and thinking are all fields on that one request, not separate APIs. A few supporting endpoints sit beside it: token counting, message batches, files and models.

A request has a small required core:

FieldWhat it means
modelWhich Claude model runs the request, for example claude-opus-5-5.
max_tokensThe most tokens the model may generate in this response. It is a hard stop, not a target.
messagesThe conversation so far: a list of user and assistant turns. The first must be user.

And some optional fields you will use all course long: system (the system prompt), tools, output_config (effort and JSON format), thinking, stop_sequences and metadata.

The response is a Message object:

FieldWhat it means
idA unique ID for this message.
modelThe model that produced it.
contentA list of content blocks, not a string. Common block types: text, thinking, tool_use.
stop_reasonWhy the model stopped. Read this before you use content.
usageToken counts: input_tokens, output_tokens, and the cache fields cache_creation_input_tokens and cache_read_input_tokens.

Each HTTP response also carries a request-id header. The Python and TypeScript SDKs expose it as _request_id on the response object. Log it: support asks for it when something goes wrong.

Your first call (TypeScript)

Bash
npm install @anthropic-ai/sdk
TypeScript
// src/classify.ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment

const ticket =
  "Hi, I'm Alice from Acme. Since this morning the invoice page shows error 502 " +
  "and our finance team can't download last month's invoices.";

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  system:
    "You triage support tickets for a SaaS help desk. " +
    "Reply with one line: <category> | <priority>. " +
    "Categories: billing, bug, access, how-to, other. Priorities: P1, P2, P3.",
  messages: [{ role: "user", content: ticket }],
});

if (response.stop_reason !== "end_turn") {
  throw new Error(`Unexpected stop_reason: ${response.stop_reason}`);
}

for (const block of response.content) {
  if (block.type === "text") console.log(block.text);
}
console.log(response.usage, response._request_id);

Three habits are already visible here:

  1. The key never appears in code. new Anthropic() reads ANTHROPIC_API_KEY from the environment. Keep it in .env locally and in a secret store in production.

  2. We loop over content and narrow by block.type. The first block may be thinking or tool_use, not text, and TypeScript won't compile content[0].text without narrowing.

  3. We check stop_reason first. More on that below.

The same call in Python:

Python
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    system="You triage support tickets... Reply with one line: <category> | <priority>.",
    messages=[{"role": "user", "content": ticket}],
)
for block in response.content:
    if block.type == "text":
        print(block.text)
print(response.usage, response._request_id)

The API keeps no memory

The Messages API is stateless. It does not remember your last request. If you want a conversation, your code stores the history and sends all of it every time:

TypeScript
const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "My name is Alice and I work at Acme." },
  { role: "assistant", content: "Thanks Alice. How can I help Acme today?" },
  { role: "user", content: "What's my name and company?" },
];
const reply = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 256, messages });

Leave out the first two turns and Claude cannot know the answer. This has two consequences you must design for:

  • Every turn costs more than the last, because you resend the whole history as input tokens.

  • Your code owns the conversation. Where you store it, how long you keep it, and which tenant it belongs to are your decisions, and your responsibility.

(Beta features can hold conversation state briefly or compact long chats; treat them as optimisations, not a replacement for your own copy. Check before relying on it.)


Key idea 2: tokens

A token is the unit the model reads and writes: a chunk of text, often part of a word. You pay per token, rate limits are counted in tokens, and the context window is measured in tokens.

Plain rules that hold up:

  • Token counts are model-specific. Different model generations use different tokenizers. The current one arrived with Claude Opus 4.7, and the docs say 1M tokens on it is roughly 555k English words.

  • Other languages often cost more tokens for the same meaning. A Nepali or Hindi ticket can use noticeably more tokens than the same ticket in English. Don't guess the ratio: measure it.

  • Don't use another vendor's tokenizer to estimate. Libraries such as tiktoken belong to other model families and give wrong counts for Claude.

  • Images and PDFs cost tokens too. An image is billed by its size in 28 × 28 pixel patches (current models cap large images at 4,784 visual tokens; older models at 1,568). A PDF page costs its extracted text tokens plus an image of the page.

Count before you send

Use the token counting endpoint with the same model you will call:

TypeScript
// src/count.ts
import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "node:fs";

const client = new Anthropic();

for (const file of ["tickets/en.txt", "tickets/ne.txt"]) {
  const { input_tokens } = await client.messages.countTokens({
    model: "claude-opus-5-5",
    messages: [{ role: "user", content: readFileSync(file, "utf8") }],
  });
  console.log(file, input_tokens);
}

Token counting accepts the same system, tools and messages you would send for real, so you can count the full request, including tool definitions.

From usage to dollars

Prices are per million tokens ("MTok") and differ for input and output. Output is always the expensive side.

Worked example. A triage call on Claude Opus 5.5 reports input_tokens: 600 and output_tokens: 150. At $4 / MTok input and $20 / MTok output (Claude API list price, checked 2026-11-25):

  • Input: 600 × $4 / 1,000,000 = $0.0024

  • Output: 150 × $20 / 1,000,000 = $0.0030

  • Total: $0.0054, about half a US cent. For 10,000 tickets a day, about $54 a day.

Two traps: thinking tokens are billed as output tokens, even when the thinking text is not shown to you; and cached input is billed at a different rate (Module 4). Keep prices in one dated file (prices.ts), never scattered through code.


Key idea 3: the context window

The context window is the most tokens the model can consider in one request: everything you send plus everything it generates in that response. On the current lineup (Claude Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5) it is 1M tokens, with up to 128K output tokens per synchronous response. Older models such as Claude Haiku 4.5 have 200K.

What counts against it in each request:

  • the system prompt

  • tool definitions (the API turns them into extra system prompt text)

  • every message you resend, including earlier tool calls and tool results

  • images and documents

  • the response being generated, including thinking

A window this big tempts people to send everything. Don't: more context costs more, is slower, and adds noise. Module 2 practises sending only what a step needs.

max_tokens is not the context window

These two are often mixed up:

Context windowmax_tokens
Who sets itThe modelYou, per request
What it limitsInput + output togetherOutput only (thinking + text)
What happens at the limitThe request fails, or stops with model_context_window_exceededThe response stops with stop_reason: "max_tokens"

Set max_tokens on purpose. Too low and answers are cut off mid-sentence. Too high on a non-streaming call and you risk an HTTP timeout: the SDK refuses non-streaming requests it expects to take over about 10 minutes, so very large outputs should be streamed (Module 2).


Key idea 4: models and reasoning

The current lineup (checked 2026-11-25)

ModelAPI IDBest forPrice in / out per MTokDefault effort
Claude Fable 5.2claude-fable-5-2The hardest reasoning and long agentic work$8 / $40high
Claude Opus 5.5claude-opus-5-5The recommended default for most work$4 / $20medium
Claude Sonnet 5.5claude-sonnet-5-5Speed plus intelligence; judges, cheaper routes$2 / $10high
Claude Haiku 5.5claude-haiku-5-5High-volume classification, extraction, routingfrom $0.10 / $0.50medium

Haiku 5.5's price rises for prompts over 100K tokens. All four have a 1M context window and 128K max output. On the Claude API, every model ID is a pinned snapshot, including these dateless IDs, so the model behind an ID does not change under you. On Amazon Bedrock the same models carry an anthropic. prefix (Module 5).

How to choose: start with the recommended default (Opus 5.5). Move a route to a cheaper model only when your evals (Module 4) show it holds quality there. Use the cheapest model that passes your evals, per task, not one model for everything.

In our help desk: Opus 5.5 drafts replies, Sonnet 5.5 is the eval judge, and Haiku 5.5 bulk-classifies the backlog.

Thinking and effort

Current Claude models can think before they answer: they produce reasoning in thinking blocks before the final text block. On the current lineup this is adaptive thinking: the model decides when and how much to think.

You steer it with effort, set in output_config:

TypeScript
const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  output_config: { effort: "high" }, // low | medium | high | xhigh | max
  messages: [{ role: "user", content: billingDisputeTicket }],
});

What you need to know about effort:

  • It affects all output tokens: thinking, text and tool calls. Lower effort means less thinking, fewer and terser tool calls, less preamble.

  • It is a behavioural signal, not a strict budget. At low, the model still thinks on a hard problem, just less.

  • The default differs by model: medium on Opus 5.5 and Haiku 5.5, high on Fable 5.2 and Sonnet 5.5. Setting the default explicitly behaves exactly like leaving it out. Set it explicitly anyway, so nobody has to remember the default.

  • Raise it only where your evals show it helps. A simple classification often does fine at low.

Things that changed recently and trip people up:

  • The old fixed thinking budget is gone on current models. thinking: { type: "enabled", budget_tokens: N } returns a 400 error on Claude 4.7 and later. Use effort instead.

  • On Opus 5.5 and Fable 5.2, thinking is always on. Sending thinking: { type: "disabled" } returns a 400. Lower the effort instead. (Sonnet 5.5 has its own "no up-front thinking" mode, { type: "between_tools" }; check before relying on it if you need thinking off.)

  • Thinking text is hidden by default. On current models, thinking blocks come back with empty text unless you ask for a summary with thinking: { type: "adaptive", display: "summarized" }. Either way, you are billed for the thinking, and the raw chain of thought is never returned.

  • Thinking counts toward max_tokens. If you raise effort, raise max_tokens too, or the answer gets cut off.


Key idea 5: prompting modes

You can put instructions in three places. Each has a job.

PlaceUse it forExample in our help desk
systemRole, rules, output format, anything that holds for the whole conversation"You triage tickets for a SaaS help desk. Never promise refunds."
user turnThe task and the data for this requestThe ticket text, the customer's plan
Examples in the promptShowing the pattern you want ("few-shot")Three tickets with the correct category and priority

A few rules that hold up:

  • Rules belong in system, data belongs in user. If you paste rules and ticket text together in one user turn, the model has a harder time telling instruction from content, and a hostile ticket can more easily pose as an instruction (Module 4 covers prompt injection).

  • Wrap untrusted data so its edges are clear, for example <ticket>…</ticket>, and say in the system prompt that text inside is data to analyse, not instructions to follow.

  • Examples are powerful and literal. If all your examples are billing tickets, expect more "billing" answers. Vary them.

  • Assistant prefill is gone. Older guides end the messages list with a partial assistant turn (for example {) to force JSON. On Claude 4.6 and later this returns a 400 error. Use structured outputs (Module 2) or a system prompt instruction instead.

Worked example: moving rules into system. Version A sends one user message: "Classify this ticket as billing/bug/access/how-to/other with P1–P3. Ticket: …". Answers come back in different shapes: sometimes a sentence, sometimes a list. Version B moves the categories, priorities and the one-line output format into system and sends only <ticket>…</ticket> as the user turn. Answers now come back in one shape. Nothing about the model changed; the prompt became clearer about what is a rule and what is data.


Key idea 6: stop_reason, the field you check first

Every response says why the model stopped. Handle each case on purpose:

stop_reasonMeaningWhat your code does
end_turnFinished naturallyUse the response
max_tokensHit your max_tokensTreat as truncated: raise the limit, continue, or flag it. Never save it as complete.
stop_sequenceEmitted one of your stop_sequencesRead stop_sequence to see which one
tool_useWants to call a toolRun it and send back a tool_result (Module 2)
pause_turnA server-side tool loop pausedSend the response back unchanged to continue
refusalA safety classifier declinedRead stop_details; retry on a fallback model (Module 4)
model_context_window_exceededThe response filled the context windowTreat as truncated

Two details people miss:

  • A refusal is an HTTP 200, not an error. Your try/catch will not see it. Only stop_reason tells you. stop_details is filled in only for refusals and is null otherwise.

  • When streaming, stop_reason is null at the start and arrives near the end (in the message_delta event). Check it on the final message.

The guard pattern

TypeScript
// src/stop-reasons.ts
function textOrThrow(msg: Anthropic.Message): string {
  switch (msg.stop_reason) {
    case "end_turn":
    case "stop_sequence":
      return msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
    case "max_tokens":
    case "model_context_window_exceeded":
      throw new Error("Truncated reply: raise max_tokens or shorten the input");
    case "refusal":
      throw new Error(`Refused: ${msg.stop_details?.category ?? "unknown category"}`);
    default:
      throw new Error(`Not a final text reply: ${msg.stop_reason}`);
  }
}

Worked example: the half-saved reply. Set max_tokens: 40 and ask for a draft reply. The response stops mid-sentence with stop_reason: "max_tokens". Without the guard, the app saves "Hi Alice, thanks for reaching out. We've looked into the 502 error on your invoice page and" as the reply. With the guard, it raises an error you can log, alert on, and retry with a bigger limit.


Key idea 7: the technical substrate

What sits between your code and the model:

  1. The SDK builds the HTTP request, adds your credentials and the anthropic-version header for you, and parses the response into typed objects. Use the official SDK rather than hand-written HTTP in an SDK-supported language.

  2. Credentials. The SDK reads ANTHROPIC_API_KEY (it can also use other credential sources, such as a signed-in profile or workload identity federation). Never hard-code a key, and never call the API directly from a browser with your key in it.

  3. Retries. The SDK automatically retries connection errors, 408, 409, 429 and 5xx responses, twice by default, with exponential backoff, honouring retry-after. Configure with maxRetries (TypeScript) or max_retries (Python).

  4. Timeouts. The default is 10 minutes. TypeScript takes milliseconds (timeout: 60_000), Python takes seconds (timeout=60). Timeouts are retried too, so the worst-case wait is roughly timeout × (retries + 1).

  5. Rate limits are set per organisation and per model class, in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). Going over returns 429 rate_limit_error. Tokens read from the prompt cache do not count toward ITPM.

  6. Errors come back as JSON with an error.type. The ones you will meet most:

StatusTypeMeaningRetry?
400invalid_request_errorYour request is wrong (bad field, unsupported option, prefill on a new model)No, fix the request
401authentication_errorBad or missing keyNo
403permission_errorKey lacks accessNo
404not_found_errorWrong path or IDNo
413request_too_largeRequest body too big (128 MB on the Messages API)No, shrink it or use the Files API
429rate_limit_errorOver a rate limit, ramp limit or spend capYes, after retry-after (but a monthly spend-cap 429 has no retry-after and keeps failing)
500api_errorUnexpected error inside AnthropicYes, with backoff
529overloaded_errorThe API is temporarily overloaded across all usersYes, with backoff

In code, catch the SDK's typed classes, most specific first, never by matching message strings:

TypeScript
const client = new Anthropic({ maxRetries: 3, timeout: 60_000 });

try {
  await client.messages.create({ /* ... */ });
} catch (err) {
  if (err instanceof Anthropic.RateLimitError) {
    // still rate limited after the SDK's own retries: queue it for later
  } else if (err instanceof Anthropic.BadRequestError) {
    // a bug in our request: log it and alert, don't retry
  } else if (err instanceof Anthropic.APIError) {
    console.error(err.status, err.message);
  } else {
    throw err;
  }
}
  1. Where it runs. The same models are available through the Claude API and through cloud platforms (Amazon Bedrock, Google Cloud, Microsoft Foundry, Claude Platform on AWS). Request shapes are nearly the same; auth, billing and feature availability differ. Module 5 covers choosing.


Worked example: the whole first call, end to end

Ticket from Bob at globex: "Can't log in since the SSO change, whole team locked out."

  1. Count: countTokens with the same model, system prompt and ticket → 412 input tokens.

  2. Call: Opus 5.5, effort: "low" (a short classification), max_tokens: 1024.

  3. Check: stop_reason is end_turn.

  4. Read: one text block: access | P1. (There may also be a thinking block before it. Our loop skips it.)

  5. Log: _request_id, tenant globex, model, effort, usage, computed cost, latency.

  6. Cost: say input_tokens: 412, output_tokens: 60 → 412 × 4 / 1e6 + 60 × 20 / 1e6 = $0.0016 + $0.0012 = $0.0028.

Then try the same ticket on Sonnet 5.5 and Haiku 5.5, and at low and high effort. Put latency, cost and answer in a table. That table, not a hunch, is how you pick a model for a route.


Common mistakes and how to spot them

MistakeHow to spot itFix
Reading response.content[0].text blindlyCrashes or wrong output when the first block is thinking or tool_use; TypeScript compile errorsLoop over blocks and narrow on type
Ignoring stop_reasonHalf-finished replies saved in the database; "the model stopped mid-sentence" bug reportsUse a guard like textOrThrow
Treating a refusal as an exceptionYour error dashboard shows nothing, but users get empty repliesCheck for stop_reason: "refusal"; it arrives as HTTP 200
max_tokens set too low after raising effortTruncation appears only on hard ticketsThinking counts toward max_tokens; give it room
Expecting the API to rememberClaude "forgets" what the user said one message agoStore and resend history yourself
Estimating tokens with another vendor's tokenizerCosts and context use are higher than your estimateUse countTokens with the real model ID
API key in source code or a browser bundleKey in Git history; key visible in browser dev toolsEnvironment variable or secret store, calls from your back end only
Using budget_tokens or thinking: disabled from an old tutorial400 errors on current modelsUse adaptive thinking and set output_config.effort
Assistant prefill to force JSON400: "This model does not support assistant message prefill"Structured outputs (Module 2)
Retrying every error400s retried forever, wasting money; real outages hidden in noiseRetry 429/5xx/529 only; fix 4xx in code
Prices hard-coded all over the codeCost reports wrong after a price changeOne dated prices.ts

Remember

  1. Everything goes through POST /v1/messages; tools, JSON and images are fields on it.

  2. content is a list of typed blocks: loop and narrow on type.

  3. Check stop_reason before you trust the output; a refusal is a 200, not an error.

  4. The API is stateless: you store and resend the conversation, and every turn costs more.

  5. Count tokens with countTokens and the real model ID; other languages often cost more.

  6. max_tokens caps output (thinking included); the context window caps input plus output.

  7. Current models think adaptively; steer with output_config.effort, not budget_tokens.

  8. Opus 5.5 is the default; move a route to a cheaper model only when evals say it holds.

  9. Rules in system, data in user, untrusted data wrapped in clear tags; no prefill.

  10. The SDK retries 429/5xx twice by default; fix 4xx errors, don't retry them.


Practice: mcq/module-01.md · More on raw HTTP, API versions and the request lifecycle: exam-domains.md, Part A · Next: Module 2: Prompts, tools and agents that hold up · Course home: README.md

↑ ↓ navigate · ↵ select · esc close