AI Engineering NotesRohit’s interview study guide
Chapter 02

Calling Models from Code

The Messages API end to end with the real TypeScript SDK: requests and responses, conversations, streaming, errors and retries, tokens and cost, thinking and effort, images and PDFs, stop reasons and refusals, the OpenAI shapes, provider-neutral code with the AI SDK, and batches at half price.

How these examples run. Every example runs on Node 26 with the real @anthropic-ai/sdk 1.17.0 (and, where named, openai 7.71.0 and the AI SDK ai 7.1.1). There is no API key in the examples, so each one starts with a block marked // Scripted replies (see "How these examples run"): it swaps only the SDK's fetch for a function that returns replies in the exact shape the API returns (the same fields, the same server-sent events, the same error bodies and headers). The model's words inside those replies were written for the example; they are not something a real model said. Everything below that block is ordinary production code: to run an example for real, delete the block, write const client = new Anthropic(); and set ANTHROPIC_API_KEY (or sign in once with ant auth login). The printed Results are the real output of these scripts. API facts (model IDs, prices, parameters, limits) were checked against Anthropic's documentation and the installed SDK's source in December 2026.

11 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#The Messages API: request and response

Added

Everything you do with Claude from code goes through one endpoint: POST /v1/messages. You send a model ID, a ceiling on how many tokens the reply may use, and a list of messages; you get back one assistant message. Tools, structured output, images, PDFs and thinking are all extra fields on that same request, not separate APIs. Once you can read one request and one response fluently, the rest of this course is variations.

The mental model: a function call to a very expensive, stateless pure function. You pass in the whole situation every time (model, system, messages, tools), and you get back a value (content) plus a receipt (usage) and a reason it stopped (stop_reason). Nothing is remembered on the server between calls unless you use a feature that says it does. That is why the request looks the way it does, and why most production bugs are about what you did or didn't put in it.

The request has three required fields:

FieldWhat it isNotes
modelThe exact model ID, e.g. claude-opus-5-5Use the IDs exactly as published; current models have no date suffix
max_tokensThe most output tokens this reply may useA hard cap the model doesn't see; hitting it cuts the reply off
messagesThe conversation so far: { role, content } objectsMust start with a user message; content is a string or a list of content blocks

The response is a message object: id (msg_…), role: "assistant", model, a content array of content blocks (each with a type: text, thinking, tool_use and others), stop_reason, stop_details (filled only for refusals), and usage, the token counts you are billed for. The current models as of December 2026, from Anthropic's model and pricing pages:

ModelIDInput / output per million tokensContext / max output
Claude Opus 5.5claude-opus-5-5$4 / $201M / 128K
Claude Sonnet 5.5claude-sonnet-5-5$2 / $101M / 128K
Claude Haiku 5.5claude-haiku-5-5$0.10 / $0.50 (prompts up to 100K tokens)1M / 128K
Claude Fable 5.2claude-fable-5-2$8 / $401M / 128K

Parameters that no longer exist on current models. If you learnt the API from older tutorials, these surprise people, and they all return 400 invalid_request_error on the current models:

  • temperature, top_p and top_k: rejected on every model from API version 2026-10-21 (the version SDK 1.17.0 sends). You steer variety with the prompt and depth with effort instead (Sampling explains what they did).
  • thinking: { type: "enabled", budget_tokens: N }: rejected on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2; adaptive thinking plus output_config.effort replaced it (Thinking and effort in requests).
  • Assistant prefill (ending messages with a partial assistant turn to force how the reply starts): rejected. Use structured outputs (output_config.format) or instructions.
first-call.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  const headers = new Headers(init.headers);
  console.log(`> ${init.method} ${new URL(url).pathname}`);
  console.log(`> anthropic-version: ${headers.get("anthropic-version")}, authorization: ${headers.get("authorization")}`);
  console.log(`> body: ${init.body}`);
  return Response.json(
    {
      id: "msg_01HcLx4s9VnR2qEe7TfJdWp3",
      type: "message",
      role: "assistant",
      model: "claude-opus-5-5",
      content: [{ type: "text", text: "A token is a chunk of text, often a word or part of a word, that the model reads and writes one at a time.", citations: null }],
      stop_reason: "end_turn",
      stop_sequence: null,
      stop_details: null,
      container: null,
      diagnostics: null,
      usage: {
        input_tokens: 19, output_tokens: 31,
        cache_creation_input_tokens: 0, cache_read_input_tokens: 0,
        cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 },
        output_tokens_details: { thinking_tokens: 0 },
        server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard",
      },
    },
    { headers: { "request-id": "req_011CYf3k8vQe2LpR9sTdWx4N" } },
  );
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "In one sentence, what is a token?" }],
});

for (const block of response.content) {
  if (block.type === "text") console.log("text:", block.text);
}
console.log("stop_reason:", response.stop_reason);
console.log("usage:", response.usage.input_tokens, "input tokens,", response.usage.output_tokens, "output tokens");
console.log("message id:", response.id, "| request id:", response._request_id);
Result
> POST /v1/messages
> anthropic-version: 2026-10-21, authorization: Bearer sk-ant-test
> body: {"model":"claude-opus-5-5","max_tokens":1024,"messages":[{"role":"user","content":"In one sentence, what is a token?"}]}
text: A token is a chunk of text, often a word or part of a word, that the model reads and writes one at a time.
stop_reason: end_turn
usage: 19 input tokens, 31 output tokens
message id: msg_01HcLx4s9VnR2qEe7TfJdWp3 | request id: req_011CYf3k8vQe2LpR9sTdWx4N
What’s happening
  1. new Anthropic({ apiKey, fetch }) builds the client. In production you'd write new Anthropic() and the SDK would find ANTHROPIC_API_KEY (or an ant auth login profile); here the scripted fetch stands in for the network so you can see exactly what goes over the wire.
  2. client.messages.create({...}) serialises the three required fields into JSON and sends POST /v1/messages. The > lines show it: the SDK adds the anthropic-version: 2026-10-21 header itself (it's hard-coded in SDK 1.17.0) and sends the key as Authorization: Bearer … (older SDKs and many tutorials use an x-api-key header; the API accepts either, and Anthropic's current curl examples use the bearer form). The version header pins the API's behaviour, which is why upgrading the SDK can change what the API accepts.
  3. The reply's content is an array, not a string. Even a plain answer is one text block, and on current models the same array can also hold thinking or tool_use blocks, so the loop checks block.type before reading .text. In TypeScript, response.content[0].text doesn't even compile, because content[0] could be a block without text.
  4. stop_reason: "end_turn" means the model finished on its own. Always look at it: max_tokens means the answer was cut off, refusal means there is no answer (Stop reasons and refusals).
  5. usage is the bill: 19 input tokens (your prompt plus the API's own formatting) and 31 output tokens. Output is what you pay most for, at five times the input price on Opus 5.5.
  6. response._request_id comes from the request-id response header. Log it with every call: it's the first thing Anthropic support asks for, and it's how you join your logs to theirs.
Advancedmax_tokens is a ceiling, not a target

max_tokens is a ceiling, not a target. The model doesn't see it and doesn't aim for it; it just gets cut off if it reaches it. Set it to the most you'd ever accept for that feature (a classifier: a few hundred; a chat answer: a few thousand; long generation: stream it and allow tens of thousands). Two practical limits apply. The model's own maximum is 128K output tokens on the current models. And the TypeScript SDK refuses a non-streaming request whose max_tokens implies it could run longer than ten minutes (the check in SDK 1.17.0 is 60 min × max_tokens / 128000 > 10 min, so anything above 21,333), throwing Streaming is required for operations that may take longer than 10 minutes before sending anything. For big outputs you stream (Streaming responses).

Advancedcontent[0].text is a bug waiting to happen
What does this cost?

A request to claude-opus-5-5 reports usage: { input_tokens: 1200, output_tokens: 800 } with no caching. Using the price table above, what did it cost, and which part dominates?

Show answer

$0.0208, and output is 77% of it even though it's fewer tokens.

What’s happening
  1. Input: 1,200 tokens × $4 per million = 1,200 × 0.000004 = $0.0048.
  2. Output: 800 tokens × $20 per million = 800 × 0.00002 = $0.016.
  3. Total: 0.0048 + 0.016 = $0.0208. At a million such requests a month that's $20,800.
  4. Output is 0.016 / 0.0208 ≈ 77% of the cost. Output tokens are generated one at a time, which is why every provider prices them several times higher than input (Next-token prediction explains the generation loop).
  5. So the cheapest lever is usually shorter answers (ask for them, cap max_tokens, use structured output), not a shorter prompt.

#System prompts and multi-turn conversations

Added

The API is stateless. It has no idea that your second request is a follow-up to your first. A "conversation" is just your application sending the growing list of messages every time: the user's turns, the model's previous replies, the user's next turn. If you forget to include an earlier reply, the model has never seen it. This surprises people coming from ChatGPT's interface, which hides the resending from you.

The system prompt is a separate top-level system field, not a message. It holds the instructions that frame the whole conversation: who the assistant is, what it may and may not do, the format to answer in. The messages list alternates user and assistant turns and must start with user (consecutive turns with the same role are allowed and get merged into one turn). Think of it as a screenplay you hand to an actor who has amnesia: the stage directions (system) and every line spoken so far (messages), every single time, and the actor writes only the next line.

multi-turn.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const scripted = [
  ["Nice to meet you, Priya! How can I help with your Angular app?", 41, 17],
  ["You told me your name is Priya.", 72, 10],
  ["I don't know your name: you haven't told me in this conversation.", 25, 16],
];
async function fetch(url, init) {
  const body = JSON.parse(init.body);
  console.log(`  > sent system + ${body.messages.length} message(s): ${body.messages.map((m) => m.role).join(", ")}`);
  const [text, input_tokens, output_tokens] = scripted.shift();
  return Response.json({
    id: `msg_01Tq${scripted.length}Wm8sKfR2xLp`, type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [{ type: "text", text, citations: null }], stop_reason: "end_turn", stop_sequence: null, stop_details: null,
    container: null, diagnostics: null,
    usage: { input_tokens, output_tokens, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" },
  });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const system = "You are a concise assistant for a web development team. Answer in one sentence.";

function createChat() {
  const history = []; // the whole conversation lives here, in your app
  return async function send(userText) {
    history.push({ role: "user", content: userText });
    const reply = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 1024, system, messages: history });
    history.push({ role: "assistant", content: reply.content }); // keep the blocks, not just the text
    const text = reply.content.filter((b) => b.type === "text").map((b) => b.text).join("");
    console.log(`  < ${text} (input_tokens: ${reply.usage.input_tokens})`);
    return text;
  };
}

const chat = createChat();
console.log("Turn 1");
await chat("Hi, I'm Priya and I work on an Angular app.");
console.log("Turn 2");
await chat("What's my name?");

console.log("A new chat (empty history)");
await createChat()("What's my name?");
Result
Turn 1
  > sent system + 1 message(s): user
  < Nice to meet you, Priya! How can I help with your Angular app? (input_tokens: 41)
Turn 2
  > sent system + 3 message(s): user, assistant, user
  < You told me your name is Priya. (input_tokens: 72)
A new chat (empty history)
  > sent system + 1 message(s): user
  < I don't know your name: you haven't told me in this conversation. (input_tokens: 25)
What’s happening
  1. createChat() returns a send function that closes over its own history array. That array is the conversation; the API never stores it. Each call to createChat() starts a fresh, empty one.
  2. Turn 1 pushes the user's message and sends system plus 1 message. The reply comes back and is appended as an assistant turn. Note it appends reply.content, the whole block list: with thinking or tools on, that list holds blocks the API needs to see again on the next turn, so extracting only the text silently drops them.
  3. Turn 2 sends user, assistant, user: three messages. The model "remembers" Priya only because its own previous reply and her first message are in the request. input_tokens grew from 41 to 72 because you paid again for the whole history.
  4. The new chat sends one message with no history, so the model has nothing to go on and says it doesn't know. Same model, same question, different input, different answer.
  5. The system prompt was sent with every request as a separate field. It shapes every turn (here, one-sentence answers) and is the right place for rules that must hold for the whole conversation.
  6. This demonstrates the cost curve of chat: every turn re-bills every previous turn. A 40-turn conversation pays for turn 1 forty times, which is why long chats need prompt caching (Prompt caching) and, eventually, trimming or summarising (Storing conversations).
AdvancedWhere the conversation lives in a real app

Where the conversation lives in a real app. In a web app the browser shows the conversation, but your server owns it: store the messages (as content blocks) in your database keyed by conversation id, load them on each request, append the new user turn, call the model, append the reply, save. Never let the browser send you the "history" to forward as-is: a user could edit it to put words in the assistant's mouth or inject fake system-sounding text (Security).

AdvancedSystem messages in the middle of a conversation

Sometimes an instruction arrives mid-conversation: the user switches on "terse mode", or your app learns something it wants the model to act on. Editing the top-level system field works, but it changes the start of the prompt, which throws away the prompt cache for everything after it. On Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2 (not on Claude Sonnet 5), you can instead append a message with role: "system" to messages. It carries operator authority like the top-level system prompt, keeps the cached prefix intact, and is the channel to use for instructions from your application rather than the user. The rules, from Anthropic's documentation: it must follow a user message, it must be the last message or be followed by an assistant turn, and it can't be messages[0]. Older models reject it with a 400 (role 'system' is not supported on this model).

JavaScript
const reply = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  system, // unchanged, so the cached prefix survives
  messages: [
    ...history,
    { role: "user", content: "Explain signals vs RxJS." },
    { role: "system", content: "Terse mode is on: keep answers under 40 words." },
  ],
});
What’s happening
  1. history and the top-level system are byte-for-byte what earlier requests sent, so everything up to the new turn can be read from the prompt cache.
  2. The new user turn is appended as usual.
  3. The role: "system" message comes after it and is the last entry, which satisfies the placement rule. The model treats it as an instruction from you, the operator, not from the user.
  4. On the next turn you keep this message in the history where it is (removing it later would change the prefix again). This fragment wasn't run: it's the same request shape as multi-turn.mjs with one more message.
Why did the bill double?

A support chat sends a 2,000-token system prompt and averages 150 tokens per user turn and 250 per reply. Roughly how many input tokens does turn 10 cost, compared with turn 1?

Show answer

Turn 1 is about 2,150 input tokens; turn 10 is about 5,750, nearly three times as much, even though the user typed the same amount.

What’s happening
  1. Turn 1 sends the system prompt plus one user turn: 2,000 + 150 = 2,150 input tokens.
  2. Turn 10 sends the system prompt, nine earlier user turns and nine earlier replies, plus the new user turn: 2,000 + 9 × (150 + 250) + 150 = 2,000 + 3,600 + 150 = 5,750.
  3. Summed over the ten turns the input is 10 × 2,150 + 400 × (0 + 1 + … + 9) = 21,500 + 400 × 45 = 39,500 tokens, for a conversation whose new text was only 10 × 150 + 9 × 250 = 3,750 tokens.
  4. The growth is linear per turn and quadratic over the conversation, because the API is stateless and you resend everything.
  5. Prompt caching turns the repeated prefix into cheap cache reads (0.05× the input price on Opus 5.5), which is why it's the first thing to switch on for chat.

#Streaming responses

Added

A non-streaming call makes the user wait for the whole answer before seeing anything. A model writing 500 tokens might take many seconds; the first token may be ready in under one. Streaming sends the reply as it's generated, so the user starts reading almost immediately. The total time doesn't change; the time to first token (TTFT) is what the user feels.

The API streams with server-sent events (SSE): one long HTTP response with Content-Type: text/event-stream, made of small events separated by blank lines, each with an event: name and a data: line of JSON. Anthropic's documentation describes a fixed sequence: message_start (a message with empty content), then for each content block a content_block_start, any number of content_block_deltas and a content_block_stop, then one or more message_deltas (carrying stop_reason and the cumulative usage), and finally message_stop. Streams may also contain any number of ping events, and occasionally an error event such as overloaded_error. The mental model is a typewriter with a protocol: open the message, open a block, type characters into it, close it, say why you stopped, done.

time The wire: one HTTP response, events in this order message_ start block_start index 0 block_delta × N "Hel" "lo" "!" block_stop index 0 message_ delta message_ stop ping events can appear anywhere stop_reason, usage The SDK's MessageStream yields each event to for await, emits "text" with each fragment, and accumulates the deltas into one Message await stream.finalMessage()
A streamed reply is the same message as a normal call, delivered as a sequence of small events that the SDK reassembles.
stream-events.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const events = [
  { type: "message_start", message: { id: "msg_01JvN8sTq2YbKc4XeWm7RdLp", type: "message", role: "assistant", content: [], model: "claude-opus-5-5", stop_reason: null, stop_sequence: null, usage: { input_tokens: 22, output_tokens: 1 } } },
  { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  { type: "ping" },
  { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Streaming shows" } },
  { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: " the answer while" } },
  { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: " it is written." } },
  { type: "content_block_stop", index: 0 },
  { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 11 } },
  { type: "message_stop" },
];
const sseBody = events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join("");
async function fetch(url, init) {
  console.log("request body has stream:", JSON.parse(init.body).stream);
  return new Response(sseBody, { headers: { "content-type": "text/event-stream" } });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const stream = client.messages.stream({
  model: "claude-opus-5-5",
  max_tokens: 64000,
  messages: [{ role: "user", content: "Why stream a model's reply? One sentence." }],
});

let shown = "";
stream.on("text", (fragment) => (shown += fragment)); // what a UI would append to the screen

for await (const event of stream) {
  const detail =
    event.type === "content_block_delta" ? JSON.stringify(event.delta.text)
    : event.type === "message_delta" ? `stop_reason=${event.delta.stop_reason} output_tokens=${event.usage.output_tokens}`
    : "";
  console.log(event.type.padEnd(20), detail);
}

const message = await stream.finalMessage();
console.log("on screen:", shown);
console.log("final:", message.content[0].text, "|", message.stop_reason, "|", message.usage.output_tokens, "output tokens");
Result
request body has stream: true
message_start        
content_block_start  
content_block_delta  "Streaming shows"
content_block_delta  " the answer while"
content_block_delta  " it is written."
content_block_stop   
message_delta        stop_reason=end_turn output_tokens=11
message_stop         
on screen: Streaming shows the answer while it is written.
final: Streaming shows the answer while it is written. | end_turn | 11 output tokens
What’s happening
  1. client.messages.stream({...}) sends the same request as create with stream: true added (the first line of output shows the SDK set it). It returns a MessageStream straight away, before any data has arrived.
  2. The body that comes back is the SSE text built from events: event: message_start, data: {...}, a blank line, and so on. The SDK parses it incrementally, as bytes arrive, not after the whole response.
  3. for await (const event of stream) yields one parsed event at a time, in wire order. Notice what's missing from the printed list: the ping event. The SDK swallows pings (they exist to keep proxies from closing an idle connection), so your code never sees them.
  4. Each content_block_delta carries a text_delta fragment. Fragments don't line up with words or sentences, so a UI just appends them. The stream.on("text", …) listener receives exactly those fragments, which is the simplest way to drive a UI; shown ends up as the full sentence.
  5. message_delta carries the stop_reason and usage.output_tokens: 11. That count is cumulative (Anthropic's docs put this in a warning box), so you keep the last value, never add them up.
  6. await stream.finalMessage() gives you the same Message object a non-streaming create would have returned, assembled from the deltas. Use it for logging usage and saving the reply to history; don't rebuild the message yourself from events.
AdvancedWhy streaming matters beyond UX

Why streaming matters beyond UX. Long non-streaming requests hit timeouts: proxies, load balancers and the SDK itself (10 minutes by default) give up on a response that sends nothing for a long time, and the SDK refuses large non-streaming max_tokens up front. Streaming keeps bytes flowing, so the default advice in Anthropic's SDK guidance is to stream anything that might be long, and call finalMessage() if you don't need the individual events.

Time to first token is what you optimise for interactive features. It's driven by queueing at the provider, the length of your prompt (the model must read all of it before writing anything: the "prefill"), whether the prompt prefix is cached, and, with thinking on, how long the model thinks before its first visible word. The rest of the wait is output length divided by output speed. Latency works through the maths.

AdvancedWhat the SDK does: parsing SSE by hand

You'll rarely parse SSE yourself in Node (use the SDK), but you will in a browser that reads your own server's stream, and interviewers like asking how it works. The format is simple: events are separated by a blank line; inside an event, event: lines name it and data: lines carry the payload. The catch is that network chunks don't respect event boundaries: one read can end in the middle of a JSON object. This parser feeds the body in deliberately awkward 7-byte chunks to prove it copes.

parse-sse.mjsPlayground ↗
// A minimal SSE parser: buffer bytes, split on blank lines, keep the incomplete tail for the next chunk.
const wire =
  'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_01","content":[]}}\n\n' +
  'event: ping\ndata: {"type": "ping"}\n\n' +
  'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}\n\n' +
  'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo!"}}\n\n' +
  'event: message_stop\ndata: {"type":"message_stop"}\n\n';

// Simulate the network: a ReadableStream that delivers the body 7 bytes at a time.
const bytes = new TextEncoder().encode(wire);
const body = new ReadableStream({
  start(controller) {
    for (let i = 0; i < bytes.length; i += 7) controller.enqueue(bytes.slice(i, i + 7));
    controller.close();
  },
});

async function* parseSSE(stream) {
  const decoder = new TextDecoder();
  let buffer = "";
  for await (const chunk of stream) {
    buffer += decoder.decode(chunk, { stream: true }); // stream:true keeps multi-byte characters intact
    let end;
    while ((end = buffer.indexOf("\n\n")) !== -1) {
      const raw = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      const event = raw.match(/^event: (.*)$/m)?.[1];
      const data = raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => l.slice(6)).join("\n");
      yield { event, data: JSON.parse(data) };
    }
  }
}

let text = "";
let chunks = 0;
for await (const { event, data } of parseSSE(body.pipeThrough(new TransformStream({ transform(c, ctl) { chunks++; ctl.enqueue(c); } })))) {
  if (event === "ping") continue;
  if (data.type === "content_block_delta") text += data.delta.text;
  console.log(event);
}
console.log(`assembled "${text}" from ${chunks} network chunks`);
Result
message_start
content_block_delta
content_block_delta
message_stop
assembled "Hello!" from 60 network chunks
What’s happening
  1. wire is five events in the exact text format the API sends. The ReadableStream hands it over 7 bytes at a time, so almost every chunk cuts an event (and its JSON) in half.
  2. parseSSE appends each decoded chunk to buffer. decoder.decode(chunk, { stream: true }) matters for non-ASCII text: a character like é is two bytes in UTF-8 and can be split across chunks; without stream: true you'd get replacement characters.
  3. The inner while loop cuts off every complete event (everything up to a blank line, \n\n) and leaves the incomplete tail in buffer for the next chunk. That one line is the whole trick of SSE parsing.
  4. Each complete event's event: line gives its name and its data: lines are joined and parsed as JSON. The loop skips ping and appends text deltas.
  5. The result shows every event arrived intact, even though the body came in dozens of tiny chunks. If you parsed each chunk on its own (a common bug), JSON.parse would throw on the first half-event.
AdvancedWhen a stream fails halfway

A stream can fail after it has started: the connection drops, or the API sends an error event (Anthropic's docs show overloaded_error, the streaming twin of HTTP 529). The SDK can't retry automatically at that point, because part of the answer has already been delivered; it ends the stream and your for await (or finalMessage()) throws. What you already showed the user is still valid, so the documented recovery for Claude 4.6 and later models is: keep the partial text, then send a new request with a user message that contains it and asks the model to continue (on older models you'd put the partial text in an assistant turn, but that's prefill, which current models reject).

stream-error.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const sse = (events) => events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join("");
const replies = [
  sse([
    { type: "message_start", message: { id: "msg_01Fh2KqP9wLx3NcV7bTyRe4D", type: "message", role: "assistant", content: [], model: "claude-opus-5-5", stop_reason: null, stop_sequence: null, usage: { input_tokens: 30, output_tokens: 1 } } },
    { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
    { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "1. Open the settings page." } },
    { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "\n2. Choose Security." } },
    { type: "error", error: { type: "overloaded_error", message: "Overloaded" } },
  ]),
  sse([
    { type: "message_start", message: { id: "msg_01Rk7VbN3sQe8MxT2wLcYp5H", type: "message", role: "assistant", content: [], model: "claude-opus-5-5", stop_reason: null, stop_sequence: null, usage: { input_tokens: 71, output_tokens: 1 } } },
    { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
    { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "\n3. Click Reset password and follow the email link." } },
    { type: "content_block_stop", index: 0 },
    { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 14 } },
    { type: "message_stop" },
  ]),
];
const fetch = async () => new Response(replies.shift(), { headers: { "content-type": "text/event-stream" } });
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const question = { role: "user", content: "List the steps to reset my password." };
let partial = "";
try {
  const stream = client.messages.stream({ model: "claude-opus-5-5", max_tokens: 4096, messages: [question] });
  stream.on("text", (t) => (partial += t));
  await stream.finalMessage();
} catch (err) {
  console.log(`stream failed: ${err.constructor.name} (${err.type}); kept ${partial.length} characters`);
  const resume = client.messages.stream({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [question, {
      role: "user",
      content: `Your previous response was interrupted and ended with:\n${partial}\nContinue from where you left off.`,
    }],
  });
  resume.on("text", (t) => (partial += t));
  await resume.finalMessage();
}
console.log(partial);
Result
stream failed: APIError (overloaded_error); kept 46 characters
1. Open the settings page.
2. Choose Security.
3. Click Reset password and follow the email link.
What’s happening
  1. The first scripted stream delivers two text deltas and then an error event with overloaded_error, exactly the example in Anthropic's streaming docs. No message_stop ever arrives.
  2. The text listener has already appended both fragments to partial, so the user saw the first two steps.
  3. When the SDK reads the error event it ends the stream and finalMessage() rejects with an APIError whose type is overloaded_error. The SDK doesn't retry a stream that has already produced output, because retrying would duplicate text you've shown.
  4. The catch block builds a continuation request: the original question, then a user message containing the partial answer and the instruction to continue (the wording follows Anthropic's documented sample). It doesn't use an assistant prefill, which current models reject.
  5. The second stream adds step 3, and the combined text reads as one answer. In a UI you'd keep the partial text on screen and append the continuation; for tool calls and thinking blocks there's no partial recovery (Anthropic's docs say they can't be resumed), so you'd re-run that turn instead.
Spot the bug

A UI renders a streamed reply with if (event.type === "content_block_delta") output += event.delta.text;. It worked for months. After the team turns on thinking: { type: "adaptive", display: "summarized" }, the screen starts showing the word undefined before the answer. Why?

Show answer

Thinking arrives as content_block_delta events too, but with a thinking_delta, whose text is in delta.thinking, not delta.text (and signature_delta events carry no text at all).

What’s happening
  1. A stream contains one content_block_start / content_block_delta / content_block_stop sequence per content block, and with thinking on, the thinking block comes first.
  2. Its deltas have delta.type === "thinking_delta" with the text in delta.thinking, followed by one signature_delta. Neither has a text property.
  3. output += undefined appends the string "undefined", once per thinking delta, before the real answer's text_delta events begin.
  4. The fix is to branch on event.delta.type: append text_delta text to the answer, route thinking_delta text to a "Thinking" panel (or ignore it), and skip signature_delta. Or use stream.on("text", …), which only fires for answer text.
  5. The general lesson: stream handlers must switch on event and delta types and ignore types they don't know, because new block types (tool use, server tools, fallbacks) arrive the same way.

#Errors, retries and rate limits

Added

Model APIs fail more often than the APIs you're used to, and mostly for reasons that go away if you wait: you sent too much too fast (429 rate limited), the provider is out of capacity right now (529 overloaded), or something broke on their side (500, or a 504 timeout). A smaller set of errors are your fault and never fix themselves: a malformed request or a rejected parameter (400), a bad key (401), a model your org can't use (403/404), a request that's too big (413). The skill is telling the two apart: retry the transient ones with backoff, fix the permanent ones, and never retry a 400 in a loop.

The good news is that the SDK already retries. The TypeScript SDK 1.17.0 retries connection errors, timeouts, 408, 409, 429 and every 5xx (which includes 529), up to maxRetries (default 2, so three attempts in total). Reading its source (client.js), the wait before each retry is: the retry-after-ms header if the server sent one, otherwise retry-after (seconds, or an HTTP date), otherwise exponential backoff of 0.5 s × 2^n capped at 8 s, multiplied by a random factor between 0.75 and 1 (jitter, so a thousand clients that failed together don't all retry at the same instant). A server header x-should-retry: true or false overrides all of that. The mental model is a polite doorman: if the club says "come back in 2 seconds" he waits exactly 2 seconds; if it says nothing he waits a bit longer each time, and he gives up after a couple of tries so your user isn't left hanging.

What reaches your code. An error that comes out of the SDK is one it wouldn't retry or gave up on. Catch the typed classes from most specific to least: Anthropic.BadRequestError (400), AuthenticationError (401), PermissionDeniedError (403), NotFoundError (404), RateLimitError (429), InternalServerError (any 5xx, including 529, which also has its own OverloadedError class in other SDKs), APIConnectionError and APIConnectionTimeoutError (no HTTP response at all). Every APIError has status, type (the API's error type string such as rate_limit_error), headers and requestID. Branch on the class, the status or type; never on the message text, which Anthropic's docs say can change.

Statuserror.typeRetry?What to do
400invalid_request_errorNoFix the request (rejected parameter, bad shape, too many images)
401 / 403authentication_error / permission_errorNoFix the key, workspace or access
404not_found_errorNoWrong model ID, or a model your org can't use
413request_too_largeNoShrink the request (128 MB limit on the Claude API)
429rate_limit_errorYes, after retry-afterSlow down; a 429 with error.details.error_code: "enforced_spend_limit_reached" is the monthly spend cap and won't clear by waiting
500 / 504api_error / timeout_errorYesTransient; check status.anthropic.com if it persists
529overloaded_errorYesCapacity; back off, spread load, or fall back to another model
retry-429.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const replies = [
  { status: 429, headers: { "retry-after": "0.05" }, body: { type: "error", error: { type: "rate_limit_error", message: "Number of request tokens has exceeded your per-minute rate limit." }, request_id: "req_011CYgA1" } },
  { status: 529, headers: { "retry-after-ms": "20" }, body: { type: "error", error: { type: "overloaded_error", message: "Overloaded" }, request_id: "req_011CYgA2" } },
  { status: 200, headers: {}, body: {
    id: "msg_01Wc5RtY8nKp2LqX9vBsMe3J", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [{ type: "text", text: "Retries worked.", citations: null }], stop_reason: "end_turn", stop_sequence: null, stop_details: null,
    container: null, diagnostics: null,
    usage: { input_tokens: 12, output_tokens: 5, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" },
  } },
];
async function fetch(url, init) {
  const attempt = new Headers(init.headers).get("x-stainless-retry-count");
  const { status, headers, body } = replies.shift();
  console.log(`attempt with x-stainless-retry-count=${attempt} -> HTTP ${status}`, JSON.stringify(headers));
  return Response.json(body, { status, headers: { "request-id": body.request_id ?? "req_011CYgA3", ...headers } });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch }); // maxRetries defaults to 2
// End of scripted replies

const started = performance.now();
const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 256,
  messages: [{ role: "user", content: "Say that retries worked." }],
});
const waited = performance.now() - started;
console.log(response.content[0].text, `(waited at least 70 ms: ${waited >= 70})`);
Result
attempt with x-stainless-retry-count=0 -> HTTP 429 {"retry-after":"0.05"}
attempt with x-stainless-retry-count=1 -> HTTP 529 {"retry-after-ms":"20"}
attempt with x-stainless-retry-count=2 -> HTTP 200 {}
Retries worked. (waited at least 70 ms: true)
What’s happening
  1. The code under the scripted block is a plain create call with no retry logic. All the retrying you see is the SDK's own.
  2. Attempt 1 gets 429 rate_limit_error with retry-after: 0.05. The SDK's shouldRetry says yes to 429, and retryRequest parses the header as 0.05 seconds and sleeps 50 ms (real responses usually say whole seconds; it's tiny here so the example runs fast).
  3. Attempt 2 is sent with x-stainless-retry-count: 1, a header the SDK adds so the server can see retries. It gets 529 overloaded_error with retry-after-ms: 20. The SDK prefers retry-after-ms over retry-after and sleeps 20 ms.
  4. Attempt 3 (x-stainless-retry-count: 2) succeeds and create resolves as if nothing had happened. The default maxRetries: 2 allowed exactly these two retries; one more failure and you'd have got an exception.
  5. The elapsed time is at least the 50 + 20 ms the server asked for. The example prints a true/false rather than the time, because real timings change from run to run.
  6. If the server hadn't sent either header, the waits would have been about 0.5 s then 1 s (each times a random 0.75 to 1), and the cap is 8 s. That is exponential backoff with jitter, built in.
AdvancedWhat reaches your code after the retries

This model shows the three outcomes you handle: a 400 that is never retried, a 429 that the SDK gives up on, and a timeout. maxRetries and timeout (in milliseconds in TypeScript) can be set on the client or per request.

error-handling.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
let attempts = 0;
const errorReply = (status, type, message, headers = {}) => Response.json(
  { type: "error", error: { type, message }, request_id: "req_011CYhB7mQ2" },
  { status, headers: { "request-id": "req_011CYhB7mQ2", ...headers } },
);
async function fetch(url, init) {
  attempts++;
  const body = JSON.parse(init.body);
  if (body.thinking?.type === "disabled") return errorReply(400, "invalid_request_error", '"thinking.type.disabled" is not supported for this model');
  if (body.messages[0].content === "slow") return new Promise((_, reject) => init.signal.addEventListener("abort", () => reject(init.signal.reason)));
  return errorReply(429, "rate_limit_error", "Number of request tokens has exceeded your per-minute rate limit.", { "retry-after": "0.01", "anthropic-ratelimit-input-tokens-remaining": "0" });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

async function ask(params, options) {
  attempts = 0;
  try {
    await client.messages.create({ model: "claude-opus-5-5", max_tokens: 256, ...params }, options);
  } catch (err) {
    if (err instanceof Anthropic.BadRequestError) {
      console.log(`400 after ${attempts} attempt(s): fix the request. type=${err.type}`);
    } else if (err instanceof Anthropic.RateLimitError) {
      console.log(`429 after ${attempts} attempt(s): ${err.type}, input tokens left=${err.headers.get("anthropic-ratelimit-input-tokens-remaining")}, retry-after=${err.headers.get("retry-after")}s, request ${err.requestID}`);
    } else if (err instanceof Anthropic.APIConnectionTimeoutError) {
      console.log(`timeout after ${attempts} attempt(s): ${err.message}`);
    } else if (err instanceof Anthropic.APIError) {
      console.log(`other API error ${err.status}: ${err.type}`);
    } else throw err;
  }
}

await ask({ messages: [{ role: "user", content: "hi" }], thinking: { type: "disabled" } });
await ask({ messages: [{ role: "user", content: "hi" }] }, { maxRetries: 1 });
await ask({ messages: [{ role: "user", content: "slow" }] }, { timeout: 30, maxRetries: 1 });
Result
400 after 1 attempt(s): fix the request. type=invalid_request_error
429 after 2 attempt(s): rate_limit_error, input tokens left=0, retry-after=0.01s, request req_011CYhB7mQ2
timeout after 2 attempt(s): Request to api.anthropic.com timed out after 0.03s
What’s happening
  1. The first call sends thinking: { type: "disabled" } to Opus 5.5, which the API rejects (the scripted 400 uses the error message quoted in Anthropic's error reference). It took 1 attempt: 4xx errors other than 408, 409 and 429 are never retried, because the same request would fail the same way.
  2. The second call gets a 429 every time. With maxRetries: 1 the SDK tries twice, then throws RateLimitError. The error still carries the response headers, so you can read retry-after and the anthropic-ratelimit-* headers (requests, tokens, input tokens and output tokens each have -limit, -remaining and -reset) to decide what your app does next: queue the work, tell the user, or shed load.
  3. The third call's scripted fetch never answers. The SDK's 30 ms timeout aborts it, retries once (timeouts are retried) and then throws APIConnectionTimeoutError after 2 attempts. A real timeout is much longer: the TypeScript default is 10 minutes per attempt, so the wall-clock worst case is timeout × (maxRetries + 1).
  4. The instanceof chain goes from most specific to least. APIError last catches anything else from the API; truly unexpected errors are rethrown.
  5. Note what's not here: no retry loop of our own. Wrapping the SDK in another retry loop multiplies attempts (3 × 3 = 9 requests per call), which turns a rate limit into a worse rate limit.
AdvancedBackoff with jitter for everything else

Your own code still needs retries for things the SDK doesn't wrap: a queue worker that re-runs a whole job, a call to a vector database, a webhook. The standard recipe is exponential backoff with full jitter: pick a random delay between 0 and min(cap, base × 2^attempt). AWS's architecture blog popularised it because it spreads retries out better than adding a small random amount. This model uses a seeded random number generator (mulberry32), so the delays are the same every run.

backoff.mjsPlayground ↗
// Exponential backoff with full jitter, seeded so the output is reproducible.
function mulberry32(seed) {
  return () => {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const random = mulberry32(42);

function backoffDelay(attempt, { baseMs = 500, capMs = 8000, retryAfterMs } = {}) {
  if (retryAfterMs !== undefined) return retryAfterMs; // the server knows best
  const ceiling = Math.min(capMs, baseMs * 2 ** attempt);
  return Math.round(random() * ceiling); // full jitter: anywhere in [0, ceiling)
}

for (let attempt = 0; attempt < 6; attempt++) {
  const ceiling = Math.min(8000, 500 * 2 ** attempt);
  console.log(`retry ${attempt + 1}: ceiling ${String(ceiling).padStart(4)} ms, wait ${String(backoffDelay(attempt)).padStart(4)} ms`);
}
console.log("with retry-after: 2 s ->", backoffDelay(0, { retryAfterMs: 2000 }), "ms");
Result
retry 1: ceiling  500 ms, wait  301 ms
retry 2: ceiling 1000 ms, wait  448 ms
retry 3: ceiling 2000 ms, wait 1705 ms
retry 4: ceiling 4000 ms, wait 2679 ms
retry 5: ceiling 8000 ms, wait 1399 ms
retry 6: ceiling 8000 ms, wait 4213 ms
with retry-after: 2 s -> 2000 ms
What’s happening
  1. mulberry32(42) is a tiny seeded PRNG: the same seed gives the same sequence, so the printed delays never change (production code would use Math.random()).
  2. The ceiling doubles each attempt (500, 1000, 2000, 4000 ms) until it hits the 8 s cap, which is the same base and cap the Anthropic SDK uses.
  3. Each actual wait is a random point below the ceiling. Some waits are short even late in the sequence; that's the point: many clients that failed at the same moment spread out instead of retrying in synchronised waves (the "thundering herd").
  4. A server retry-after always wins over the formula: the server knows when your rate limit window resets.
  5. The SDK's own jitter is gentler (it waits 75 to 100% of the ceiling). Both are reasonable; what matters is having some randomness and a cap.

Rate limits on the Claude API are per organisation and per model class, measured in requests per minute and input and output tokens per minute, and they rise with your usage tier (Anthropic's rate-limit docs list the current numbers per tier; they change, so read them for your account rather than hard-coding them). Token-per-minute limits are why one huge prompt can trip a 429 even at low request counts. Cached input tokens and the Batches API have their own accounting; Rate limits, queues and backpressure shows how to keep a busy service under the limit with a token bucket and a queue.

AdvancedTimeouts are in milliseconds, and retried
How many requests?

Your code wraps client.messages.create in its own for (let i = 0; i < 3; i++) retry loop, and the SDK keeps its default maxRetries. The API returns 529 to every request for a minute. How many HTTP requests does one call make before giving up?

Show answer

9.

What’s happening
  1. Each SDK call makes up to maxRetries + 1 = 3 attempts, because 529 is a 5xx and the SDK retries those.
  2. After the third failure the SDK throws InternalServerError, and your loop catches it and calls the SDK again.
  3. Your loop runs 3 times, so the total is 3 × 3 = 9 requests, all against an API that is already overloaded.
  4. Multiply by every user hitting the same path and your service is now one of the reasons the API is overloaded. Remove the outer loop and, if you need more patience, raise maxRetries on that one call or fall back to another model.

#Counting tokens and estimating cost

Added

You pay per token, separately for input and output, and the price differs by model. To budget a feature you need two things: how many tokens a request will use, and what each kind of token costs. After the call, usage tells you exactly. Before the call, you ask the API: Claude's tokenizer isn't public, so the only accurate count comes from the free count_tokens endpoint (client.messages.countTokens), which takes the same model, system, messages and tools as a real request and returns { input_tokens }. Don't estimate Claude tokens with OpenAI's tokenizer: Anthropic's own guidance says it undercounts, by more on code and non-English text (Tokens and tokenizers shows how much tokenizers differ).

The usage object has four input-side fields and you need all of them, because input_tokens is only the uncached remainder. Total prompt size is input_tokens + cache_creation_input_tokens + cache_read_input_tokens. Thinking tokens are part of output_tokens and billed at the output price (output_tokens_details.thinking_tokens tells you how many). The prices, from Anthropic's pricing page in December 2026:

ModelInput5-min cache write1-hour cache writeCache readOutput
Opus 5.5$4$5$8$0.20$20
Sonnet 5.5$2$2.50$4$0.10$10
Haiku 5.5 (prompt ≤ 100K tokens)$0.10$0.125$0.20$0.01$0.50
Haiku 5.5 (prompt > 100K tokens)$0.50$0.625$1$0.05$2.50
Fable 5.2$8$10$16$0.20$40

All per million tokens. Cache writes cost 1.25× the input price for a 5-minute cache and 2× for a 1-hour cache. Cache reads are 0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.2 and 0.1× on other models. The Batches API halves everything, and the discounts stack. Using US-only inference (inference_geo: "us") multiplies everything by 1.1.

cost-calculator.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  console.log(`> POST ${new URL(url).pathname}`);
  return Response.json({ input_tokens: 2817 });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

// USD per million tokens, from Anthropic's pricing page (December 2026).
const PRICES = {
  "claude-opus-5-5": { input: 4, write5m: 5, write1h: 8, read: 0.2, output: 20 },
  "claude-sonnet-5-5": { input: 2, write5m: 2.5, write1h: 4, read: 0.1, output: 10 },
  "claude-haiku-5-5": { input: 0.1, write5m: 0.125, write1h: 0.2, read: 0.01, output: 0.5 },
  "claude-haiku-5-5>100k": { input: 0.5, write5m: 0.625, write1h: 1, read: 0.05, output: 2.5 },
  "claude-fable-5-2": { input: 8, write5m: 10, write1h: 16, read: 0.2, output: 40 },
};

function cost(model, usage, { batch = false } = {}) {
  const promptTokens = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
  const key = model === "claude-haiku-5-5" && promptTokens > 100_000 ? "claude-haiku-5-5>100k" : model;
  const p = PRICES[key];
  const write1h = usage.cache_creation?.ephemeral_1h_input_tokens ?? 0;
  const write5m = (usage.cache_creation_input_tokens ?? 0) - write1h;
  const dollars =
    (usage.input_tokens * p.input + write5m * p.write5m + write1h * p.write1h +
      (usage.cache_read_input_tokens ?? 0) * p.read + usage.output_tokens * p.output) / 1e6;
  return batch ? dollars / 2 : dollars;
}

const request = {
  model: "claude-opus-5-5",
  system: "You summarise customer support tickets for the on-call engineer.",
  messages: [{ role: "user", content: "<ticket>…a long ticket thread…</ticket>\nSummarise it in five bullet points." }],
};
const { input_tokens } = await client.messages.countTokens(request);
console.log("count_tokens says:", input_tokens, "input tokens");

const estimate = { input_tokens, output_tokens: 400 }; // assume a 400-token summary
for (const model of ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"]) {
  const each = cost(model, estimate);
  console.log(`${model.padEnd(18)} $${each.toFixed(6)} per call, $${(each * 50_000).toFixed(2)} for 50,000 calls, batch $${(cost(model, estimate, { batch: true }) * 50_000).toFixed(2)}`);
}

// A real usage object from a cached request: most of the prompt was read from the cache.
const cachedUsage = { input_tokens: 217, cache_creation_input_tokens: 0, cache_read_input_tokens: 2600, output_tokens: 400 };
console.log("same call on Opus 5.5 with a warm cache: $" + cost("claude-opus-5-5", cachedUsage).toFixed(6));
Result
> POST /v1/messages/count_tokens
count_tokens says: 2817 input tokens
claude-opus-5-5    $0.019268 per call, $963.40 for 50,000 calls, batch $481.70
claude-sonnet-5-5  $0.009634 per call, $481.70 for 50,000 calls, batch $240.85
claude-haiku-5-5   $0.000482 per call, $24.09 for 50,000 calls, batch $12.04
same call on Opus 5.5 with a warm cache: $0.009388
What’s happening
  1. client.messages.countTokens(request) sends the request to POST /v1/messages/count_tokens and returns { input_tokens }: 2,817 here. It accepts the same system, messages and tools as create, so you count exactly what you'll send; it's free but rate limited. Tokenizers differ between model generations, so pass the model you'll actually use.
  2. PRICES copies Anthropic's pricing table. In real code this lives in config with a date next to it, because prices change (Opus 5.5 is cheaper than Opus 5 was) and you want old cost reports to stay explainable.
  3. cost() handles every usage field: uncached input at the input price, cache writes split by TTL using usage.cache_creation, cache reads at the read price, and output at the output price. It also applies Haiku 5.5's long-prompt tier, which depends on the whole prompt including cached tokens.
  4. The loop prices one summary on three models. Opus 5.5 is 40 times Haiku 5.5 per call here. Whether that's worth it depends on quality for your task, which you only learn from an eval (Evals), never from the price table.
  5. The batch column halves the cost: for 50,000 summaries that don't need to come back in seconds, the Batches API is the single easiest saving (Batch processing).
  6. The last line uses a usage object where 2,600 of the 2,817 prompt tokens were cache reads: the call drops from $0.019268 to $0.009388, about half. It doesn't fall further because the 400 output tokens ($0.008, now 85% of the bill) are unaffected by caching.
AdvancedEstimate before you build

Estimate before you build. A per-feature cost model needs four numbers: requests per day, prompt tokens per request (count a few real ones), output tokens per request (measure from usage, don't guess), and the cache hit rate. Controlling cost builds that model in code for a whole product. Images and PDFs count too: an image costs ⌈width/28⌉ × ⌈height/28⌉ tokens (Images, PDFs and files).

AdvancedThinking tokens are output tokens
What did this call cost?

A Sonnet 5.5 call reports usage: { input_tokens: 300, cache_creation_input_tokens: 0, cache_read_input_tokens: 20000, output_tokens: 500 }. Using the price table above ($2 input, $0.10 cache read, $10 output per million), what did it cost, and what would it have cost without the cache?

Show answer

$0.0076 with the cache; $0.0456 without it, six times as much.

What’s happening
  1. The prompt was 300 + 0 + 20,000 = 20,300 tokens; input_tokens is only the uncached part after the breakpoint.
  2. With the cache: 300 × $2/M = $0.0006, plus 20,000 × $0.10/M = $0.002, plus 500 × $10/M = $0.005. Total $0.0076.
  3. Without the cache, all 20,300 input tokens are billed at $2/M ($0.0406), plus the same $0.005 of output: $0.0456.
  4. Caching cut the input cost by about 95% here; the output tokens are now about two thirds of the bill, so the next saving would come from shorter answers.
  5. A dashboard that only charts input_tokens would report this as a 300-token prompt, which is why cost code must use all four fields.

#Thinking and effort in requests

Added

Current Claude models can think before they answer: generate reasoning tokens in thinking blocks, then the visible answer in text blocks. On the current generation this is adaptive: the model decides per request whether and how much to think, so an easy question gets little or none and a hard one gets a lot. On Claude Opus 5.5 thinking can't be switched off at all ({ type: "disabled" } is a 400), and on every current model the old fixed budget (thinking: { type: "enabled", budget_tokens: N }) is rejected with a 400. Your control is output_config.effort: low, medium, high, xhigh or max. It sets how thorough the model is overall (thinking depth, how many tool calls, how much it double-checks), and with it the cost and latency. Defaults differ by model: medium on Opus 5.5 and Haiku 5.5, high on Sonnet 5.5 and the others, so Anthropic's guidance is to set it explicitly.

The mental model: effort is a dial for how hard the model tries, not a word count. low is "answer from the hip" (fast and cheap: chat, classification, simple extraction); high is "work it out properly" (the minimum Anthropic recommends for intelligence-sensitive work); xhigh and max are for the hardest coding and agentic problems where correctness matters more than cost. How much the model writes in its visible answer is set by your prompt, not by effort.

What you get back depends on thinking.display. The default on current models is "omitted": thinking blocks come back with an empty thinking string and a signature; you're billed for the reasoning but see none of it. "summarized" returns a readable summary. Either way the raw chain of thought is never exposed, and you must pass thinking blocks back unchanged in the next request (that's what the signature verifies).

thinking-and-effort.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const usage = (input_tokens, output_tokens, thinking_tokens) => ({
  input_tokens, output_tokens, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
  output_tokens_details: { thinking_tokens }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard",
});
const replies = [
  {
    id: "msg_01ZsT4qW8xLm2RbN6vKcPe9H", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [
      { type: "thinking", thinking: "Compared the two schedules: the nightly job overlaps the 02:00 backup window, so moving it to 03:30 avoids the lock contention.", signature: "EqQBCgIYAhIMbX9fK2pQr7tWv1sZGgx3nLmQ8cR4dT6yH0wiMNb5sVq2kP7xE1rJ" },
      { type: "text", text: "Move the nightly job to 03:30: it currently overlaps the 02:00 backup and fights it for table locks.", citations: null },
    ],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null, usage: usage(184, 512, 461),
  },
  {
    id: "msg_01Lp8VcX3nQk6TsW2mRyBf7D", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [{ type: "text", text: "Add an index on orders(created_at) so the job's range scan stops reading the whole table.", citations: null }],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null, usage: usage(296, 38, 0),
  },
];
async function fetch(url, init) {
  const body = JSON.parse(init.body);
  console.log(`> thinking=${JSON.stringify(body.thinking)} effort=${body.output_config.effort} messages=[${body.messages.map((m) => Array.isArray(m.content) ? `${m.role}:${m.content.map((b) => b.type).join("+")}` : m.role).join(", ")}]`);
  return Response.json(replies.shift());
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const messages = [{ role: "user", content: "Our nightly report job and the 02:00 backup keep timing out. One fix?" }];
const first = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  thinking: { type: "adaptive", display: "summarized" },
  output_config: { effort: "high" },
  messages,
});

for (const block of first.content) {
  if (block.type === "thinking") console.log("thinking summary:", block.thinking);
  if (block.type === "text") console.log("answer:", block.text);
}
const { output_tokens, output_tokens_details } = first.usage;
console.log(`output_tokens=${output_tokens}, of which thinking=${output_tokens_details.thinking_tokens}`);

messages.push({ role: "assistant", content: first.content }); // thinking blocks go back unchanged
messages.push({ role: "user", content: "And one more fix?" });
const second = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  thinking: { type: "adaptive", display: "summarized" },
  output_config: { effort: "high" },
  messages,
});
console.log("answer:", second.content.find((b) => b.type === "text").text);
console.log(`output_tokens=${second.usage.output_tokens}, of which thinking=${second.usage.output_tokens_details.thinking_tokens}`);
Result
> thinking={"type":"adaptive","display":"summarized"} effort=high messages=[user]
thinking summary: Compared the two schedules: the nightly job overlaps the 02:00 backup window, so moving it to 03:30 avoids the lock contention.
answer: Move the nightly job to 03:30: it currently overlaps the 02:00 backup and fights it for table locks.
output_tokens=512, of which thinking=461
> thinking={"type":"adaptive","display":"summarized"} effort=high messages=[user, assistant:thinking+text, user]
answer: Add an index on orders(created_at) so the job's range scan stops reading the whole table.
output_tokens=38, of which thinking=0
What’s happening
  1. The request sets thinking: { type: "adaptive", display: "summarized" } and output_config: { effort: "high" }. Note where effort lives: inside output_config, not at the top level. On Opus 5.5 you could omit thinking entirely and still get adaptive thinking; display: "summarized" is there so there's something readable to show.
  2. The response has two blocks: a thinking block (a summary of the reasoning, plus an opaque signature) and a text block with the answer. The loop handles them by type; a UI might show the summary in a collapsible "Thinking" panel.
  3. usage.output_tokens is 512, of which 461 were thinking. Those 461 are billed at the output price ($20 per million on Opus 5.5) even though the visible answer is one sentence. With display: "omitted" you'd pay the same and see an empty string.
  4. The follow-up appends first.content (both blocks, untouched) as the assistant turn. The > line for the second request shows assistant:thinking+text. The signature lets the API verify the block came from this model in this conversation; editing or dropping it breaks that check.
  5. On the second, easier question the model chose not to think at all: thinking_tokens is 0 and there's only a text block. That's what adaptive means: you set the effort level, the model decides per request how much reasoning the problem needs.
AdvancedWhat changed from budget_tokens

What changed from budget_tokens. Older models (Claude 4.5 and earlier, and Haiku 4.5 today) used thinking: { type: "enabled", budget_tokens: N }: a fixed number of thinking tokens, which had to be at least 1,024 and less than max_tokens. On Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2 that shape returns a 400. Migration is mechanical: replace it with { type: "adaptive" } (or omit thinking where adaptive is the default) and pick an effort level; a big budget maps roughly to high or above, a small one to low or medium, and you confirm with an eval. Two related changes: max_tokens still caps the total output including thinking, so don't set it tight on hard tasks, and changing thinking or effort between requests invalidates the messages part of the prompt cache, so pin them per route.

EffortUse it forTrade-off
lowChat, classification, extraction, sub-agents, high-volume or latency-sensitive routesFastest and cheapest; fewer tool calls, terser
mediumThe default on Opus 5.5 and Haiku 5.5; routine work where quality holdsA cost-saving step down from high
highIntelligence-sensitive work; Anthropic's suggested minimum for itOften the sweet spot of quality and tokens
xhighHard coding and long agentic tasksMore thorough, more tokens and time
maxWhen correctness matters more than costRaise to it only when measurement shows headroom
AdvancedStreaming thinking, and why the default looks like a pause

When you stream with thinking on, the thinking block arrives first as thinking_delta events, then a single signature_delta just before its content_block_stop, then the text block. With the default display: "omitted", Anthropic's streaming docs say the thinking block opens, receives one thinking_delta with an empty string and a signature_delta, and closes. The model may have spent many seconds thinking before that, so a UI that only renders text shows nothing for a while. If your users watch the stream, either set display: "summarized" and show a "Thinking…" panel, or at least show a spinner from content_block_start of type thinking.

thinking-stream.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const events = [
  { type: "message_start", message: { id: "msg_01Qy6NbR2vTk9WsL4xMcHe8P", type: "message", role: "assistant", content: [], model: "claude-opus-5-5", stop_reason: null, stop_sequence: null, usage: { input_tokens: 40, output_tokens: 1 } } },
  { type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "", signature: "" } },
  { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "" } },
  { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "EqQBCgIYAhIMa1b2C3d4E5f6G7h8GgxIiJjKkLlMmNnOoPpQ" } },
  { type: "content_block_stop", index: 0 },
  { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
  { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "GCD(1071, 462) = 21." } },
  { type: "content_block_stop", index: 1 },
  { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 236 } },
  { type: "message_stop" },
];
const fetch = async () => new Response(events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } });
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const stream = client.messages.stream({
  model: "claude-opus-5-5",
  max_tokens: 64000,
  output_config: { effort: "medium" }, // thinking omitted: adaptive is the default on Opus 5.5
  messages: [{ role: "user", content: "What is the GCD of 1071 and 462?" }],
});
for await (const event of stream) {
  if (event.type === "content_block_start") console.log(`[${event.content_block.type} block opens]${event.content_block.type === "thinking" ? " show a spinner" : ""}`);
  if (event.type === "content_block_delta") {
    if (event.delta.type === "thinking_delta") console.log(`  thinking_delta: ${JSON.stringify(event.delta.thinking)}`);
    if (event.delta.type === "signature_delta") console.log(`  signature_delta (${event.delta.signature.length} chars)`);
    if (event.delta.type === "text_delta") console.log(`  text_delta: ${event.delta.text}`);
  }
}
const final = await stream.finalMessage();
console.log("blocks:", final.content.map((b) => b.type).join(", "), "| thinking text:", JSON.stringify(final.content[0].thinking));
Result
[thinking block opens] show a spinner
  thinking_delta: ""
  signature_delta (48 chars)
[text block opens]
  text_delta: GCD(1071, 462) = 21.
blocks: thinking, text | thinking text: ""
What’s happening
  1. The request leaves out thinking (adaptive is the default on Opus 5.5) and sets effort: "medium" explicitly, which is also that model's default; being explicit protects you when a new model changes the default.
  2. The thinking block opens first. This is the moment to show a spinner: the model may already have been reasoning for seconds.
  3. With display omitted, the only thinking_delta carries an empty string, then a signature_delta carries the signature. Your code must keep that block (the SDK does, in finalMessage()) to send it back next turn.
  4. The text block follows with the visible answer, and usage.output_tokens (236) includes the hidden reasoning.
  5. finalMessage() has both blocks, the thinking one with an empty thinking string. If a user complains the app "freezes" before answering, this is usually why.
Why is the answer empty?

A classification route on Opus 5.5 sets max_tokens: 300 and output_config: { effort: "high" }. Most replies are fine, but a few come back with stop_reason: "max_tokens" and no text block at all. What's happening, and what do you change?

Show answer

Thinking tokens count towards max_tokens. On the harder inputs the model spent the whole 300-token cap thinking and was cut off before writing the answer.

What’s happening
  1. On Opus 5.5 thinking is always on, and max_tokens caps the total output: thinking plus visible text.
  2. At high effort the model may think for hundreds of tokens on borderline cases. When the cap is reached mid-thought, the response stops with stop_reason: "max_tokens" and the content holds only a thinking block.
  3. Code that reads the first text block finds none; code that doesn't check stop_reason may treat it as an empty answer.
  4. Fixes: lower the effort (classification usually does well at low, which also saves money), and raise max_tokens enough to leave room for thinking plus the label. Anthropic's guidance on a max_tokens stop is exactly that: raise max_tokens or lower the effort.
  5. Always check stop_reason before parsing, and treat max_tokens as "no result", never as an answer.

#Images, PDFs and files

Added

Claude reads images and PDFs as ordinary content blocks in a user message, next to your text. An image block is { type: "image", source: … } and a PDF is { type: "document", source: … }, where source is base64 data, a URL, or a file_id from the Files API. Anthropic's vision guide notes the model works best when images come before the text that asks about them, the same advice as for long documents.

The mental model for cost: an image is a grid of 28 × 28-pixel tiles, and each tile is one token. Anthropic's vision docs give the formula ⌈width / 28⌉ × ⌈height / 28⌉ visual tokens. Every image is first scaled down (keeping its aspect ratio) to fit the model's limits: on "high-resolution" models (Claude 4.7 and later, so all current models) the long edge is capped at 2,576 px and the cost at 4,784 tokens per image; older models cap at 1,568 px and 1,568 tokens. A PDF is read as both: each page becomes an image (capped at 1,568 visual tokens per page on every model) plus the text extracted from it, and Anthropic's PDF guide says text typically costs 1,500 to 3,000 tokens per page. Limits on the Claude API: JPEG, PNG, GIF (first frame) and WebP; 10 MB per base64 image; up to 600 images or PDF pages per request on 1M-context models (100 on 200K-context models); 128 MB per request.

Turn on citations on a document block (citations: { enabled: true }) and the answer comes back split into text blocks, the factual ones carrying a citations array that points at the exact page and quoted text. For a PDF the location type is page_location with 1-based page numbers. Citations are what let your UI show "source: page 2" and let you verify the model didn't make it up.

vision-and-pdf.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";
import { deflateSync } from "node:zlib";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  const body = JSON.parse(init.body);
  for (const block of body.messages[0].content) {
    const data = block.source?.data ? `data: ${block.source.data.length} base64 chars` : "";
    console.log(`> ${block.type}${block.source ? ` (${block.source.type}, ${block.source.media_type})` : ""} ${data}${block.citations ? " citations on" : ""}${block.text ? JSON.stringify(block.text) : ""}`);
  }
  return Response.json({
    id: "msg_01Gx7TmK4qWv2NcR8sLbYp3E", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [
      { type: "text", text: "The chart shows a single bar. According to the invoice, ", citations: null },
      { type: "text", text: "the total due is 1,240 EUR", citations: [{ type: "page_location", cited_text: "Total due: 1,240 EUR", document_index: 1, document_title: "invoice-2026-11.pdf", start_page_number: 1, end_page_number: 2, file_id: null }] },
      { type: "text", text: ".", citations: null },
    ],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null,
    usage: { input_tokens: 1702, output_tokens: 29, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" },
  });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

// A real 56x28 PNG built in code (one bar on a white background), so the example needs no files.
function makePng(w, h, pixel) {
  const crcTable = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
  const crc = (buf) => { let c = 0xffffffff; for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
  const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  const raw = Buffer.alloc((w * 3 + 1) * h);
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set(pixel(x, y), y * (w * 3 + 1) + 1 + x * 3);
  const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr.set([8, 2, 0, 0, 0], 8);
  return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
}
const png = makePng(56, 28, (x, y) => (x > 20 && x < 36 && y > 6 ? [79, 70, 229] : [255, 255, 255]));
const pdf = Buffer.from("%PDF-1.4\n% a stand-in for a real invoice PDF read from disk\n%%EOF\n");

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{
    role: "user",
    content: [
      { type: "image", source: { type: "base64", media_type: "image/png", data: png.toString("base64") } },
      { type: "document", source: { type: "base64", media_type: "application/pdf", data: pdf.toString("base64") }, title: "invoice-2026-11.pdf", citations: { enabled: true } },
      { type: "text", text: "What does the chart show, and what is the invoice total?" },
    ],
  }],
});

console.log("answer:", response.content.filter((b) => b.type === "text").map((b) => b.text).join(""));
for (const block of response.content) {
  for (const c of (block.type === "text" && block.citations) || []) {
    const last = c.end_page_number - 1; // end_page_number is exclusive
    console.log(`cited "${c.cited_text}" from ${c.document_title}, page ${c.start_page_number}${last > c.start_page_number ? `-${last}` : ""}`);
  }
}
Result
> image (base64, image/png) data: 160 base64 chars
> document (base64, application/pdf) data: 88 base64 chars citations on
> text "What does the chart show, and what is the invoice total?"
answer: The chart shows a single bar. According to the invoice, the total due is 1,240 EUR.
cited "Total due: 1,240 EUR" from invoice-2026-11.pdf, page 1
What’s happening
  1. makePng writes a genuine 56 × 28 PNG (signature, header, compressed pixel rows, checksums) so the example is self-contained; in real code you'd readFile an upload. At 56 × 28 it costs ⌈56/28⌉ × ⌈28/28⌉ = 2 visual tokens. The PDF here is a placeholder buffer; with a real API key you'd read a real file.
  2. The user message's content is a list of blocks: the image first, then the document, then the question last, the order Anthropic recommends. Both binary blocks use source.type: "base64" with a media_type; the > lines show the shapes the SDK sent (the data lengths, not the data).
  3. The document block has a title and citations: { enabled: true }. Citations must be on for all documents in a request or none, and they can't be combined with structured outputs (output_config.format), which returns a 400.
  4. The reply comes back as three text blocks: plain text, a cited span, and the closing full stop. Joining their text gives the readable answer; the middle block's citations entry is a page_location with cited_text, the document_index (1, because the image is block 0 and the PDF block 1 in the request) and page numbers.
  5. Page numbers are 1-based and end_page_number is exclusive, so start_page_number: 1, end_page_number: 2 means "page 1"; the code subtracts one before printing. A UI can link the cited span to that page of the original file, which is how you make a document answer checkable.
AdvancedBase64, URL or file id

Base64, URL or file id. Base64 is simplest and works everywhere, but it's 33% bigger than the file and is resent with every request in a conversation. A { type: "url", url } source makes Anthropic fetch a public URL. The Files API uploads once (client.files.upload({ file }) returns a file_… id; uploads are up to 500 MB, storage is 100 GB per organisation, files persist until you delete them, and the file operations themselves are free) and you then reference { type: "file", file_id } in as many requests as you like. Use it for anything sent more than once, such as a contract a user asks ten questions about. The Files API isn't available on Amazon Bedrock or Google Vertex AI; there you send base64.

AdvancedImage tokens in code

Before you send screenshots at scale, estimate the cost. This model implements the formula and the downscaling rule as Anthropic's vision docs describe them (scale to the largest size that fits both the long-edge cap and the token cap, keeping the aspect ratio) and checks itself against the table of examples in those docs.

image-tokens.mjsPlayground ↗
// Visual tokens per image: ceil(w/28) * ceil(h/28), after fitting the model's limits (Anthropic vision docs).
const TIERS = {
  high: { maxEdge: 2576, maxTokens: 4784 }, // Claude 4.7 and later: every current model
  standard: { maxEdge: 1568, maxTokens: 1568 }, // older models, and every PDF page
};
const tokensAt = (w, h) => Math.ceil(w / 28) * Math.ceil(h / 28);

function fit(w, h, tier) {
  const { maxEdge, maxTokens } = TIERS[tier];
  if (Math.max(w, h) <= maxEdge && tokensAt(w, h) <= maxTokens) return { w, h, resized: false };
  // Largest width (aspect ratio kept) that satisfies both limits.
  for (let nw = Math.min(w, Math.floor((maxEdge * w) / Math.max(w, h))); nw > 0; nw--) {
    const nh = Math.round((nw * h) / w);
    if (nh <= maxEdge && tokensAt(nw, nh) <= maxTokens) return { w: nw, h: nh, resized: true };
  }
}

const docsTable = [ // [width, height, standard tokens, high-res tokens] from the vision docs
  [200, 200, 64, 64], [1000, 1000, 1296, 1296], [1920, 1080, 1560, 2691], [2000, 1500, 1564, 3888], [3840, 2160, 1560, 4784],
];
for (const [w, h, wantStd, wantHigh] of docsTable) {
  const s = fit(w, h, "standard"), hi = fit(w, h, "high");
  const std = tokensAt(s.w, s.h), high = tokensAt(hi.w, hi.h);
  console.log(`${`${w}x${h}`.padEnd(9)} standard ${String(std).padStart(4)}${s.resized ? ` (as ${s.w}x${s.h})` : ""}  high ${String(high).padStart(4)}${hi.resized ? ` (as ${hi.w}x${hi.h})` : ""}  matches docs: ${std === wantStd && high === wantHigh}`);
}
const perThousand = (tokens, pricePerM) => ((tokens * 1000 * pricePerM) / 1e6).toFixed(2);
console.log(`1000 full-HD screenshots on Opus 5.5 ($4/M): $${perThousand(2691, 4)}; downscaled to 1280x720 first: $${perThousand(tokensAt(1280, 720), 4)}`);
Result
200x200   standard   64  high   64  matches docs: true
1000x1000 standard 1296  high 1296  matches docs: true
1920x1080 standard 1560 (as 1456x819)  high 2691  matches docs: true
2000x1500 standard 1564 (as 1269x952)  high 3888  matches docs: true
3840x2160 standard 1560 (as 1456x819)  high 4784 (as 2576x1449)  matches docs: true
1000 full-HD screenshots on Opus 5.5 ($4/M): $10.76; downscaled to 1280x720 first: $4.78
What’s happening
  1. tokensAt is the documented formula: one token per started 28 × 28 tile. A 1000 × 1000 image is 36 × 36 = 1,296 tiles.
  2. fit returns the image unchanged if it's within both limits. Otherwise it searches for the largest width (height following the aspect ratio) whose height fits the edge cap and whose tile count fits the token cap.
  3. On the high-resolution tier, 1920 × 1080 isn't resized: 69 × 39 = 2,691 tokens. On the standard tier it's shrunk to 1456 × 819, which is 52 × 30 = 1,560 tokens, just under the 1,568 cap. Every row prints matches docs: true, so the rule reproduces Anthropic's published table.
  4. A 4K screenshot hits the high-resolution caps: shrunk to 2576 × 1449, exactly 4,784 tokens.
  5. The last line is the practical lesson: a thousand full-HD screenshots cost about $10.76 in input on Opus 5.5, and downscaling them to 1280 × 720 first (46 × 26 = 1,196 tokens each) cuts that to about $4.78. If the task doesn't need the detail (reading a big chart title, not tiny text), resize before sending.
AdvancedUploading once with the Files API
files-api.mjsPlayground ↗
import Anthropic, { toFile } from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  const path = new URL(url).pathname;
  if (path === "/v1/files") {
    console.log(`> POST ${path} (multipart upload: body is ${init.body.constructor.name})`);
    return Response.json({ id: "file_011CYjQ4p8sVmT2xW6nRbL9e", type: "file", filename: "contract.pdf", mime_type: "application/pdf", size_bytes: 58, created_at: "2026-12-06T10:15:00Z", downloadable: false });
  }
  const doc = JSON.parse(init.body).messages[0].content[0];
  console.log(`> POST ${path} document source ${JSON.stringify(doc.source)}`);
  return Response.json({
    id: "msg_01Sx3PqL8vNm4RtK2wYcBh6G", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [{ type: "text", text: "The notice period is 30 days.", citations: null }],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null,
    usage: { input_tokens: 2210, output_tokens: 9, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" },
  });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const bytes = Buffer.from("%PDF-1.4\n% stand-in for contract.pdf read from disk\n%%EOF\n");
const uploaded = await client.files.upload({ file: await toFile(bytes, "contract.pdf", { type: "application/pdf" }) });
console.log(`uploaded ${uploaded.filename}: ${uploaded.id} (${uploaded.size_bytes} bytes)`);

const answer = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{ role: "user", content: [
    { type: "document", source: { type: "file", file_id: uploaded.id } },
    { type: "text", text: "What is the notice period?" },
  ] }],
});
console.log(answer.content[0].text);
Result
> POST /v1/files (multipart upload: body is FormData)
uploaded contract.pdf: file_011CYjQ4p8sVmT2xW6nRbL9e (58 bytes)
> POST /v1/messages document source {"type":"file","file_id":"file_011CYjQ4p8sVmT2xW6nRbL9e"}
The notice period is 30 days.
What’s happening
  1. toFile(bytes, "contract.pdf", { type: "application/pdf" }) wraps a buffer as an uploadable file with a name and MIME type; with a real file you could pass fs.createReadStream(path) instead.
  2. client.files.upload sends a multipart POST /v1/files (no beta header: the Files API is out of beta in SDK 1.17.0, under client.files). The reply is the file's metadata, including its id.
  3. The message references the file with source: { type: "file", file_id }; the request carries a short id instead of the whole PDF. The block type must match the file: document for PDFs and text, image for images.
  4. Every later question about the same contract reuses the id. You're still billed for the document's tokens on each request (combine it with prompt caching to make repeat reads cheap); what you save is upload bandwidth and request size.
How much do the screenshots cost?

A QA tool sends 10,000 screenshots a day, each 1500 × 1000 pixels, to Opus 5.5 ($4 per million input tokens). Using the formula from this topic, what's the daily image cost, and what happens if you downscale to 750 × 500 first?

Show answer

About $77.76 a day at full size (1,944 tokens per image); about $19.44 at 750 × 500 (486 tokens each).

What’s happening
  1. Opus 5.5 is in the high-resolution tier (long edge up to 2,576 px, up to 4,784 tokens), so a 1500 × 1000 image isn't resized.
  2. Tokens = ⌈1500/28⌉ × ⌈1000/28⌉ = 54 × 36 = 1,944 per image. 10,000 images is 19.44 million tokens; at $4 per million that's $77.76 a day.
  3. At 750 × 500: ⌈750/28⌉ × ⌈500/28⌉ = 27 × 18 = 486 tokens, a quarter, so $19.44 a day.
  4. Halving both dimensions roughly quarters the cost. Whether you can afford to depends on the task: reading small UI text needs detail, checking layout or colour often doesn't. Run the eval set at both sizes before deciding.

#Stop reasons and refusals

Added

Every response says why it stopped, and production code branches on it before reading anything else. The values (from the SDK's StopReason type in 1.17.0):

stop_reasonWhat happenedWhat your code does
end_turnThe model finished naturallyUse the answer
max_tokensIt hit your max_tokens cap mid-answerTreat the output as incomplete: raise the cap, stream, or ask for something shorter. Never parse truncated JSON
stop_sequenceIt produced one of your stop_sequencesstop_sequence names which one
tool_useIt wants you to run one or more toolsRun them, send tool_results back (Tool calling)
pause_turnA long server-side tool turn (web search, code execution) pausedSend the response back as-is to let it continue
refusalA safety classifier or the model declinedDon't read content as an answer; check stop_details; fall back or explain
model_context_window_exceededThe conversation outgrew the context windowTrim, summarise or compact the history

Refusals are a normal, successful response. On the current models, safety classifiers can decline a request: you get HTTP 200 with stop_reason: "refusal" and a stop_details object { type: "refusal", category, explanation }. The categories in SDK 1.17.0 are cyber, bio, frontier_llm, reasoning_extraction, general_harms, or null. The decline can happen before any output (content is empty) or mid-stream after some text (Anthropic's guidance: discard the partial output). Benign work in nearby areas (security tooling, life sciences) can occasionally trigger it, so a refusal isn't always the user's fault. Anthropic's docs are explicit: branch on stop_reason, never on stop_details, which can be null even on a refusal, and the explanation text isn't stable.

stop-reasons.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const base = { type: "message", role: "assistant", model: "claude-opus-5-5", stop_sequence: null, container: null, diagnostics: null };
const usage = (i, o) => ({ input_tokens: i, output_tokens: o, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null, output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" });
const replies = [
  { ...base, id: "msg_01A", content: [{ type: "text", text: "Here are the release notes.", citations: null }], stop_reason: "end_turn", stop_details: null, usage: usage(30, 7) },
  { ...base, id: "msg_01B", content: [{ type: "text", text: '{"items": [{"sku": "A-1", "qty": 2}, {"sku": "B-', citations: null }], stop_reason: "max_tokens", stop_details: null, usage: usage(52, 24) },
  { ...base, id: "msg_01C", content: [], stop_reason: "refusal", stop_details: { type: "refusal", category: "cyber", explanation: "This request may enable cyber harm." }, usage: usage(41, 0) },
  { ...base, id: "msg_01D", content: [], stop_reason: "refusal", stop_details: null, usage: usage(38, 0) },
  { ...base, id: "msg_01E", content: [{ type: "text", text: "Let me keep searching.", citations: null }], stop_reason: "pause_turn", stop_details: null, usage: usage(900, 40) },
];
const fetch = async () => Response.json(replies.shift());
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

function readReply(response) {
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
  switch (response.stop_reason) {
    case "end_turn":
    case "stop_sequence":
      return { ok: true, text };
    case "max_tokens":
      return { ok: false, retry: "raise max_tokens or ask for less", partial: text.length + " chars, incomplete" };
    case "refusal": {
      const category = response.stop_details?.category ?? "unspecified"; // stop_details may be null
      return { ok: false, refused: category, retry: category === "reasoning_extraction" ? "don't retry" : "try a fallback model" };
    }
    case "pause_turn":
      return { ok: false, retry: "send the response back as-is to continue" };
    default:
      return { ok: false, retry: `unhandled stop_reason ${response.stop_reason}` };
  }
}

for (let i = 0; i < 5; i++) {
  const response = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 24, messages: [{ role: "user", content: `request ${i + 1}` }] });
  console.log(response.stop_reason.padEnd(10), JSON.stringify(readReply(response)));
}
Result
end_turn   {"ok":true,"text":"Here are the release notes."}
max_tokens {"ok":false,"retry":"raise max_tokens or ask for less","partial":"48 chars, incomplete"}
refusal    {"ok":false,"refused":"cyber","retry":"try a fallback model"}
refusal    {"ok":false,"refused":"unspecified","retry":"try a fallback model"}
pause_turn {"ok":false,"retry":"send the response back as-is to continue"}
What’s happening
  1. readReply reads the text blocks once, then switches on stop_reason before trusting them. That order is the whole point: the text means different things depending on why the model stopped.
  2. end_turn returns the answer. max_tokens returns a failure with the partial length, because the JSON in that reply is cut off mid-object ("sku": "B-) and parsing it would throw, or worse, a lenient parser would quietly drop an item.
  3. The first refusal has content: [] and stop_details.category: "cyber". Code that did response.content[0].text would crash right here with Cannot read properties of undefined.
  4. The second refusal has stop_details: null. The ?. and the ?? "unspecified" keep the code alive: Anthropic documents null as a valid state, so a refusal is identified by stop_reason alone.
  5. The reasoning_extraction category (asking the model to print its internal reasoning in the answer) is singled out because Anthropic's migration guide says it isn't retried on a fallback model; the fix there is to stop asking for it and use thinking blocks instead.
  6. pause_turn is not an error: a long server-tool turn paused, and sending the assistant content back in a new request lets it carry on. The default branch makes new stop reasons visible instead of silently treating them as success.
AdvancedRefusal fallbacks on the server

A false-positive refusal on a legitimate request is an outage for that user. Anthropic's recommendation for Opus 5.5, Sonnet 5.5 and Fable 5.2 code is to opt into server-side fallbacks from day one: with the beta header server-side-fallback-2026-07-01 and a fallbacks parameter, the API re-runs a refused request on a fallback model inside the same call and returns that model's answer. fallbacks: "default" lets Anthropic pick the model per refusal category; the array form names your own (for Opus 5.5 the migration guide says to expect claude-opus-5 or claude-opus-4-8 among the allowed targets, published as allowed_fallback_models on the model's /v1/models entry). It triggers on policy declines only, never on rate limits or overloads. It isn't available on the Batches API, Amazon Bedrock, Vertex AI or Microsoft Foundry (the SDK has a client-side middleware for those).

refusal-fallback.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  const body = JSON.parse(init.body);
  console.log(`> ${new URL(url).pathname}${new URL(url).search} anthropic-beta: ${new Headers(init.headers).get("anthropic-beta")} fallbacks: ${JSON.stringify(body.fallbacks)}`);
  return Response.json({
    id: "msg_01Nb6WqT3xKv8RmL2sYcPf4J", type: "message", role: "assistant", model: "claude-opus-4-8",
    content: [
      { type: "fallback", from: { model: "claude-opus-5-5" }, to: { model: "claude-opus-4-8" }, trigger: { type: "refusal", category: "cyber" } },
      { type: "text", text: "Here is how to configure rate limiting on your own nginx server: …", citations: null },
    ],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, context_management: null, diagnostics: null,
    usage: {
      input_tokens: 58, output_tokens: 212, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      iterations: [
        { type: "message", model: "claude-opus-5-5", input_tokens: 58, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null },
        { type: "fallback_message", model: "claude-opus-4-8", input_tokens: 58, output_tokens: 212, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null },
      ],
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard",
    },
  });
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const response = await client.beta.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 4096,
  betas: ["server-side-fallback-2026-07-01"],
  fallbacks: [{ model: "claude-opus-4-8" }],
  messages: [{ role: "user", content: "How do I rate-limit abusive clients on my nginx server?" }],
});

for (const block of response.content) {
  if (block.type === "fallback") console.log(`${block.from.model} declined (${block.trigger.category}); ${block.to.model} continued`);
}
const fallbackRan = (response.usage.iterations ?? []).some((it) => it.type === "fallback_message");
if (response.stop_reason === "refusal") console.log("every model in the chain refused");
else console.log(`served by ${response.model} (fallback ran: ${fallbackRan}):`, response.content.find((b) => b.type === "text").text);
Result
> /v1/messages anthropic-beta: server-side-fallback-2026-07-01 fallbacks: [{"model":"claude-opus-4-8"}]
claude-opus-5-5 declined (cyber); claude-opus-4-8 continued
served by claude-opus-4-8 (fallback ran: true): Here is how to configure rate limiting on your own nginx server: …
What’s happening
  1. The call goes through client.beta.messages.create because fallbacks is a beta parameter; betas: [...] becomes the anthropic-beta header, visible in the > line, and fallbacks goes in the body.
  2. The scripted reply is what the API returns when the first model declines before output: a fallback content block marking the switch (from, to, and the trigger's category), then the fallback model's answer. The top-level model is the model that produced the message.
  3. usage.iterations is the per-attempt record: a message entry for Opus 5.5 with 0 output tokens, and a fallback_message entry for the model that served the answer. Anthropic's docs say to use the fallback_message entry, not the block, as the "a fallback served this" signal, because later turns in the same conversation can be routed straight to the fallback model (sticky routing, about an hour) with no block at all.
  4. The code still checks stop_reason: the fallback model can refuse too, and then the whole chain refused.
  5. One consequence to plan for: a fallback model runs without Opus 5.5's thinking blocks (only Fable and Mythos 5.x read them), so a conversation that falls back loses that reasoning context.
Predict what the code does

A ticket classifier calls Opus 5.5 with max_tokens: 5 and the categories billing, bug, account. The code does const label = reply.content.find((b) => b.type === "text")?.text.trim() and stores it without checking stop_reason. A month later the database contains labels like "bill" and "acco". What happened?

Show answer

Some replies were cut off by max_tokens: the stored text is the start of a label, and stop_reason was max_tokens, which the code never checked.

What’s happening
  1. max_tokens: 5 is a hard cap on all output, including thinking (always on for Opus 5.5) and any words before the label such as "Category:".
  2. When the model used some of those tokens on thinking or a preamble, the label itself was truncated, and the response ended with stop_reason: "max_tokens".
  3. The code read the text block anyway, so the fragment went into the database as if it were a label.
  4. Fixes: give the reply room (a few hundred tokens and low effort), constrain the output with structured outputs (an enum of the three categories), and reject any reply whose stop_reason isn't end_turn, or whose label isn't in the allowed set.
  5. Validating against the allowed set alone would have caught this on day one.

#OpenAI and the OpenAI-compatible shape

Added

You'll meet three request shapes in the wild, and recognising them is half the battle when you read other people's code or switch providers:

  • OpenAI Chat Completions (POST /v1/chat/completions): messages with roles system/developer, user, assistant and tool; the reply is choices[0].message.content with finish_reason; usage is prompt_tokens and completion_tokens. It's the de facto lingua franca: most local servers and many other vendors speak it.
  • OpenAI Responses (POST /v1/responses): OpenAI's newer API, which its reference recommends for new projects. You send input (a string or a list of items) and instructions; the reply is a list of output items (messages, tool calls, reasoning), with the SDK's convenience output_text; usage is input_tokens and output_tokens. It can store conversation state server-side (previous_response_id).
  • Anthropic Messages (POST /v1/messages): system as a separate field, messages of content blocks, max_tokens required, reply content blocks with stop_reason.

They model the same idea, so the mapping is mostly mechanical: system prompt → system / instructions / a system message; max_tokens → max_tokens / max_output_tokens / max_completion_tokens; tool calls → tool_use blocks / function_call items / tool_calls; stop reasons → stop_reason / status + incomplete_details / finish_reason. The differences that bite are in the details: where the system prompt goes, whether tool results are a role or a block, how streaming events are named, and which parameters each model rejects. OpenAI's current production family, per its changelog (17 November 2026), is GPT-6.2 (gpt-6.2-sol, gpt-6.2-astra).

openai-shapes.mjsPlayground ↗
import OpenAI from "openai";

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  const path = new URL(url).pathname;
  console.log(`> POST ${path} ${init.body}`);
  if (path === "/v1/chat/completions") {
    return Response.json({
      id: "chatcmpl-Cq81mZ4rT", object: "chat.completion", created: 1796544000, model: "gpt-6.2-sol",
      choices: [{ index: 0, message: { role: "assistant", content: "Tokens are pieces of text a model reads.", refusal: null, annotations: [] }, logprobs: null, finish_reason: "stop" }],
      usage: { prompt_tokens: 24, completion_tokens: 9, total_tokens: 33, prompt_tokens_details: { cached_tokens: 0, audio_tokens: 0 }, completion_tokens_details: { reasoning_tokens: 0, audio_tokens: 0, accepted_prediction_tokens: 0, rejected_prediction_tokens: 0 } },
      service_tier: "default",
    });
  }
  return Response.json({
    id: "resp_0a1b2c3d4e", object: "response", created_at: 1796544001, status: "completed", model: "gpt-6.2-sol",
    output: [{ id: "msg_0f9e8d", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "Tokens are pieces of text a model reads.", annotations: [], logprobs: [] }] }],
    usage: { input_tokens: 24, input_tokens_details: { cached_tokens: 0 }, output_tokens: 9, output_tokens_details: { reasoning_tokens: 0 }, total_tokens: 33 },
    error: null, incomplete_details: null, instructions: "Answer in one sentence.", metadata: {}, parallel_tool_calls: true, temperature: null, top_p: null, tool_choice: "auto", tools: [],
  });
}
const openai = new OpenAI({ apiKey: "sk-test", fetch });
// End of scripted replies

const chat = await openai.chat.completions.create({
  model: "gpt-6.2-sol",
  max_completion_tokens: 200,
  messages: [
    { role: "developer", content: "Answer in one sentence." },
    { role: "user", content: "What is a token?" },
  ],
});
console.log("chat:", chat.choices[0].message.content, `| finish_reason=${chat.choices[0].finish_reason} | ${chat.usage.prompt_tokens} in, ${chat.usage.completion_tokens} out`);

const resp = await openai.responses.create({
  model: "gpt-6.2-sol",
  max_output_tokens: 200,
  instructions: "Answer in one sentence.",
  input: "What is a token?",
});
console.log("responses:", resp.output_text, `| status=${resp.status} | ${resp.usage.input_tokens} in, ${resp.usage.output_tokens} out`);
Result
> POST /v1/chat/completions {"model":"gpt-6.2-sol","max_completion_tokens":200,"messages":[{"role":"developer","content":"Answer in one sentence."},{"role":"user","content":"What is a token?"}]}
chat: Tokens are pieces of text a model reads. | finish_reason=stop | 24 in, 9 out
> POST /v1/responses {"model":"gpt-6.2-sol","max_output_tokens":200,"instructions":"Answer in one sentence.","input":"What is a token?"}
responses: Tokens are pieces of text a model reads. | status=completed | 24 in, 9 out
What’s happening
  1. The OpenAI SDK takes a custom fetch just like Anthropic's, so the same scripting trick works; the > lines show the two request bodies it sent.
  2. Chat Completions puts the system instructions in the message list, as a developer (newer) or system message, and limits output with max_completion_tokens. The answer is choices[0].message.content and the stop reason is finish_reason: "stop" (Anthropic's end_turn); a cut-off answer would say length (Anthropic's max_tokens).
  3. Responses takes instructions and input separately and limits output with max_output_tokens. The reply's output is a list of items; resp.output_text is an SDK convenience property that joins the text of the message items, the equivalent of joining Anthropic's text blocks.
  4. Usage field names differ: prompt_tokens/completion_tokens in Chat Completions, input_tokens/output_tokens in Responses (matching Anthropic's names). Cost dashboards that mix providers need a mapping layer.
  5. Compare with first-call.mjs: Anthropic has system as its own top-level field, makes max_tokens required, and returns typed content blocks. Same concept, three shapes, which is exactly what provider-neutral libraries smooth over (next topic).
AdvancedLocal models speak these shapes too

Local models speak these shapes too. Ollama serves an OpenAI-compatible API at http://localhost:11434/v1/ (chat completions, a stateless Responses endpoint, embeddings, models; any API key string works) and, per its docs, a subset of the Anthropic Messages API at http://localhost:11434 (messages, streaming, tools, vision with base64 images, thinking; no count_tokens, prompt caching, batches, citations or PDFs). LM Studio's local server does the same: OpenAI-compatible at http://localhost:1234/v1, and Anthropic-compatible POST /v1/messages since version 0.4.1, with base URL http://localhost:1234. So you can point the OpenAI SDK (or the Anthropic SDK, with baseURL) at a local model for development or offline use, with the caveat that unsupported features fail or are silently ignored. Open-weight models covers running them.

Advanced"OpenAI-compatible" means "the common subset"
Translate the request

You're porting this Chat Completions call to the Anthropic Messages API: messages: [{ role: "system", content: "Be brief." }, { role: "user", content: "Hi" }], max_completion_tokens: 200, and the code checks finish_reason === "length". What changes?

Show answer

The system prompt moves to the top-level system field, max_completion_tokens becomes the required max_tokens, and finish_reason === "length" becomes stop_reason === "max_tokens".

What’s happening
  1. In Chat Completions the system (or developer) prompt is a message in the list. In the Messages API it's a separate top-level system field, and messages contains only user and assistant turns, starting with user.
  2. max_completion_tokens (optional in OpenAI's API) maps to max_tokens, which the Messages API requires on every request.
  3. The reply is read from content blocks (join the text blocks) instead of choices[0].message.content.
  4. Stop reasons map: stop ↔ end_turn, length ↔ max_tokens, tool_calls ↔ tool_use. Anthropic also has stop reasons with no Chat Completions equivalent, such as refusal and pause_turn, which the ported code must handle.
  5. Usage fields rename too: prompt_tokens ↔ input_tokens (plus the cache fields), completion_tokens ↔ output_tokens.

#Provider-neutral code with the AI SDK

Added

The Vercel AI SDK (package ai, version 7.1.1 here) is a TypeScript library that gives you one set of functions for every provider: generateText for a full reply, streamText for a stream, plus structured output, tool calling and UI hooks for React and other frameworks (A chat UI in React uses it). Providers are separate packages (@ai-sdk/anthropic, @ai-sdk/openai, …) that turn its normalised call into each vendor's request. Swapping providers is changing one line: model: anthropic("claude-opus-5-5") to another provider's model.

The mental model is a database driver for language models: one query API, a driver per vendor. Like an ORM, it's great for the common 80% and leaky at the edges: provider-specific features go through providerOptions, and its defaults are its own, not the vendor's. For tests it ships mock models in ai/test, so you can test code that calls a model without a network or a key.

ai-sdk-mock.mjsPlayground ↗
import { generateText, streamText } from "ai";
import { MockLanguageModelV4, simulateReadableStream } from "ai/test";

// A mock model from ai/test: the AI SDK's official test double (no network, no key).
const usage = { inputTokens: { total: 21, noCache: 21, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 9, text: 9, reasoning: 0 } };
const model = new MockLanguageModelV4({
  provider: "mock", modelId: "mock-model",
  doGenerate: async () => ({
    content: [{ type: "text", text: "Use generateText for a whole reply." }],
    finishReason: { unified: "stop", raw: "end_turn" },
    usage, warnings: [],
  }),
  doStream: async () => ({
    stream: simulateReadableStream({
      chunks: [
        { type: "text-start", id: "t1" },
        { type: "text-delta", id: "t1", delta: "Use streamText" },
        { type: "text-delta", id: "t1", delta: " for a stream." },
        { type: "text-end", id: "t1" },
        { type: "finish", finishReason: { unified: "stop", raw: "end_turn" }, usage },
      ],
    }),
  }),
});

const result = await generateText({
  model,
  system: "Answer in one sentence.",
  prompt: "Which AI SDK function returns a whole reply?",
  maxOutputTokens: 200,
});
console.log("generateText:", result.text, `| finishReason=${result.finishReason} | ${result.usage.inputTokens} in, ${result.usage.outputTokens} out`);
console.log("what the provider received:", JSON.stringify(model.doGenerateCalls[0].prompt));

const stream = streamText({ model, prompt: "And for a stream?" });
for await (const delta of stream.textStream) console.log("streamText delta:", JSON.stringify(delta));
console.log("finishReason:", await stream.finishReason);
Result
generateText: Use generateText for a whole reply. | finishReason=stop | 21 in, 9 out
what the provider received: [{"role":"system","content":"Answer in one sentence."},{"role":"user","content":[{"type":"text","text":"Which AI SDK function returns a whole reply?"}]}]
streamText delta: "Use streamText"
streamText delta: " for a stream."
finishReason: stop
What’s happening
  1. MockLanguageModelV4 implements the same LanguageModelV4 interface a real provider does; you give it doGenerate and doStream functions that return results in the AI SDK's normalised shape. These outputs are mocks, written for the example.
  2. generateText({ model, system, prompt, maxOutputTokens }) uses the AI SDK's own option names (maxOutputTokens, not max_tokens) and returns text, a unified finishReason (stop, length, content-filter, tool-calls, error, interrupted or other; the provider's raw value is kept separately) and usage with inputTokens and outputTokens.
  3. model.doGenerateCalls[0].prompt shows what a provider receives: the AI SDK has converted system and prompt into a normalised list of messages with content parts. Each provider package translates that list into its vendor's request body.
  4. streamText returns immediately; textStream is an async iterable of text deltas, the same idea as the Anthropic SDK's text events. simulateReadableStream replays the chunks the mock was given.
  5. This is how you unit-test code that calls a model: inject a mock model, assert on what your code did with its output and on what it sent (doGenerateCalls). Testing AI code in CI builds on it.
AdvancedWhat a translation layer costs you

What you lose. The AI SDK maps the common features well, but it is a translation layer with its own opinions, and the next example shows three real ones from @ai-sdk/anthropic 4.0.115: it sends its own anthropic-version header (2023-06-01, where the official SDK sends 2026-10-21); when you don't set maxOutputTokens it defaults max_tokens to the model's maximum (128,000 for Opus 5.5) on a non-streaming call, a request the official SDK would refuse; and it drops temperature for Opus 5.5 with a warning instead of letting the API reject it. Provider features such as effort and thinking go in providerOptions.anthropic. None of this is wrong, but you should know what's on the wire, and new vendor features reach the provider package some time after they reach the vendor's own SDK.

AdvancedWhat @ai-sdk/anthropic actually sends
ai-sdk-anthropic-wire.mjsPlayground ↗
import { generateText } from "ai";
import { createAnthropic } from "@ai-sdk/anthropic";

globalThis.AI_SDK_LOG_WARNINGS = false; // keep warnings off stderr; we print result.warnings ourselves

// Scripted replies (see "How these examples run")
async function fetch(url, init) {
  console.log(`> POST ${new URL(url).pathname} anthropic-version: ${new Headers(init.headers).get("anthropic-version")}`);
  console.log(`> body: ${init.body}`);
  return Response.json({
    id: "msg_01Hm4QwX9sTv2LkR7nBcYe5P", type: "message", role: "assistant", model: "claude-opus-5-5",
    content: [{ type: "text", text: "Lazy loading defers work until it's needed.", citations: null }],
    stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null,
    usage: { input_tokens: 16, output_tokens: 11, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null,
      output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "standard", speed: "standard" },
  });
}
const anthropic = createAnthropic({ apiKey: "sk-ant-test", fetch });
// End of scripted replies

const result = await generateText({
  model: anthropic("claude-opus-5-5"),
  prompt: "Define lazy loading in one sentence.",
  temperature: 0.2,
  providerOptions: { anthropic: { effort: "low" } },
});
console.log("text:", result.text, "| finishReason:", result.finishReason, "| raw:", result.rawFinishReason);
for (const w of result.warnings) console.log("warning:", w.feature, "-", w.details);
Result
> POST /v1/messages anthropic-version: 2023-06-01
> body: {"model":"claude-opus-5-5","max_tokens":128000,"output_config":{"effort":"low"},"messages":[{"role":"user","content":[{"type":"text","text":"Define lazy loading in one sentence."}]}]}
text: Lazy loading defers work until it's needed. | finishReason: stop | raw: end_turn
warning: temperature - temperature is not supported by claude-opus-5-5 and will be ignored
What’s happening
  1. createAnthropic({ apiKey, fetch }) builds the provider with the scripted transport; anthropic("claude-opus-5-5") is the model object you pass to any AI SDK function. Swapping to another provider would change only this line.
  2. The > lines show the real request: anthropic-version: 2023-06-01 (the AI SDK's own header, not the official SDK's 2026-10-21), and a body with max_tokens: 128000 because no maxOutputTokens was given and the provider package defaults to the model's maximum.
  3. providerOptions: { anthropic: { effort: "low" } } became output_config: { effort: "low" } in the body: provider-specific features are passed through this escape hatch.
  4. temperature: 0.2 is not in the body. The provider knows Opus 5.5 rejects it, drops it, and reports it in result.warnings as unsupported. Your code keeps working, but a setting you thought you'd applied silently isn't; read the warnings in tests.
  5. The reply's stop_reason: "end_turn" is normalised to finishReason: "stop", with the original kept as rawFinishReason. That normalisation is what lets one UI handle many providers, and also why provider-specific stop reasons (like refusal) need checking in the raw value or provider metadata.
Why do outputs still vary?

A team switches its AI SDK code to anthropic("claude-opus-5-5") and sets temperature: 0 to make answers repeatable in tests. Answers still vary between runs, and nothing errors. Why?

Show answer

The temperature never reached the API: @ai-sdk/anthropic drops temperature for Opus 5.5 and reports it only as a warning in result.warnings (shown in ai-sdk-anthropic-wire.mjs above).

What’s happening
  1. Current Claude models reject temperature, top_p and top_k; from API version 2026-10-21 they return a 400 on every model.
  2. The AI SDK's Anthropic provider knows this and removes temperature from the request instead of letting it fail. The real run above shows the request body without it and a warning saying it "will be ignored".
  3. So the model ran with its normal sampling, and answers vary as they always would.
  4. For repeatable tests, don't rely on sampling settings: use the AI SDK's mock models (MockLanguageModelV4) for unit tests, and for evals with a real model, grade with checks that tolerate wording differences.
  5. And read result.warnings in tests (or fail on them), so a setting that silently stops applying is noticed.

#Batch processing

Added

Much AI work doesn't need an answer in seconds: summarising yesterday's tickets, tagging a product catalogue, generating embeddings-ready descriptions, running an eval set. The Message Batches API takes up to 100,000 requests (or 256 MB) in one submission, processes them asynchronously, and charges 50% of the normal price for every token. Anthropic's docs say most batches finish within an hour, the maximum is 24 hours, and results stay available for 29 days. Batch requests support most Messages features (vision, tools, caching); they can't set stream, speed, fallbacks or max_tokens: 0.

The mental model is dropping off laundry instead of using the launderette: you hand over a labelled bag, come back later, and pay less. Each request carries your own custom_id label, and the results come back in any order, so you match them by custom_id, never by position. Each result is succeeded (with the message), errored (an invalid request, or a server error worth retrying), canceled or expired.

batch.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run")
const batchId = "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d";
const batch = (status, counts, ended) => ({
  id: batchId, type: "message_batch", processing_status: status,
  request_counts: { processing: 0, succeeded: 0, errored: 0, canceled: 0, expired: 0, ...counts },
  created_at: "2026-12-06T09:00:00Z", ended_at: ended ? "2026-12-06T09:21:07Z" : null, expires_at: "2026-12-07T09:00:00Z",
  archived_at: null, cancel_initiated_at: null,
  results_url: ended ? `https://api.anthropic.com/v1/messages/batches/${batchId}/results` : null,
});
const msg = (text, i, o) => ({ id: `msg_01B${i}`, type: "message", role: "assistant", model: "claude-haiku-5-5", content: [{ type: "text", text, citations: null }],
  stop_reason: "end_turn", stop_sequence: null, stop_details: null, container: null, diagnostics: null,
  usage: { input_tokens: i, output_tokens: o, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: null, output_tokens_details: { thinking_tokens: 0 }, server_tool_use: null, inference_geo: "global", service_tier: "batch", speed: "standard" } });
const results = [ // deliberately not in submission order
  { custom_id: "ticket-3", result: { type: "succeeded", message: msg("billing", 61, 3) } },
  { custom_id: "ticket-1", result: { type: "succeeded", message: msg("bug", 58, 2) } },
  { custom_id: "ticket-2", result: { type: "errored", error: { type: "error", error: { type: "invalid_request_error", message: "max_tokens: Field required" }, request_id: null } } },
];
const polls = [batch("in_progress", { processing: 3 }), batch("ended", { succeeded: 2, errored: 1 }, true), batch("ended", { succeeded: 2, errored: 1 }, true)];
async function fetch(url, init) {
  const { pathname } = new URL(url);
  console.log(`> ${init.method} ${pathname}`);
  if (init.method === "POST") return Response.json(batch("in_progress", { processing: JSON.parse(init.body).requests.length }));
  if (pathname.endsWith("/results")) return new Response(results.map((r) => JSON.stringify(r)).join("\n") + "\n", { headers: { "content-type": "application/binary" } });
  return Response.json(polls.shift());
}
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
const sleep = () => Promise.resolve(); // a real poller waits ~60 s between checks
// End of scripted replies

const tickets = { "ticket-1": "The export button crashes the page.", "ticket-2": "I was charged twice.", "ticket-3": "Can I get an invoice for November?" };
const created = await client.messages.batches.create({
  requests: Object.entries(tickets).map(([custom_id, text]) => ({
    custom_id,
    params: {
      model: "claude-haiku-5-5",
      max_tokens: 10,
      system: "Classify the support ticket as one word: bug, billing or other.",
      messages: [{ role: "user", content: text }],
    },
  })),
});
console.log(`created ${created.id}: ${created.processing_status}, ${created.request_counts.processing} processing`);

let status;
do {
  await sleep();
  status = await client.messages.batches.retrieve(created.id);
  console.log(`poll: ${status.processing_status}`, JSON.stringify(status.request_counts));
} while (status.processing_status !== "ended");

const labels = {};
for await (const item of await client.messages.batches.results(created.id)) {
  if (item.result.type === "succeeded") labels[item.custom_id] = item.result.message.content[0].text;
  else labels[item.custom_id] = `${item.result.type}: ${item.result.error?.error?.type ?? ""}`;
}
for (const id of Object.keys(tickets)) console.log(id, "->", labels[id]);
Result
> POST /v1/messages/batches
created msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d: in_progress, 3 processing
> GET /v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d
poll: in_progress {"processing":3,"succeeded":0,"errored":0,"canceled":0,"expired":0}
> GET /v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d
poll: ended {"processing":0,"succeeded":2,"errored":1,"canceled":0,"expired":0}
> GET /v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d
> GET /v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d/results
ticket-1 -> bug
ticket-2 -> errored: invalid_request_error
ticket-3 -> billing
What’s happening
  1. batches.create sends all three requests in one POST /v1/messages/batches. Each has a custom_id and ordinary Messages params; the reply is a batch object with processing_status: "in_progress".
  2. The loop polls batches.retrieve until processing_status is "ended". A real poller sleeps a minute or so between checks (the docs' examples use 60 s); here sleep resolves immediately so the model is fast. request_counts shows how many succeeded or errored.
  3. batches.results(id) first re-reads the batch to get its results_url, then streams the results file: one JSON object per line (JSONL), which the SDK decodes as it reads, so a 100,000-line result file never has to sit in memory as one string.
  4. The results arrive as ticket-3, ticket-1, ticket-2: not in submission order. Storing them in labels by custom_id and then printing in your own order is the correct pattern; using the array index would have assigned "billing" to ticket 1.
  5. ticket-2 errored with invalid_request_error (the scripted error says max_tokens was missing). An invalid_request error needs the request fixed before resubmitting; a server error can be resubmitted as is. Only the failed items need a new batch.
  6. The usage.service_tier on each result is "batch", and every token was billed at half price. Prompt caching discounts stack on top, so a shared system prompt across thousands of requests gets cheaper still.
AdvancedWhen to use batches

When to use batches. Anything a user isn't waiting for: nightly enrichment, backfills, offline evaluation runs, bulk classification, generating test data. Not for anything interactive, and not when you need the result of one request to build the next (that's a workflow, Agents). Batches also have their own rate limits, separate from the Messages API's, so moving bulk work to them protects your interactive traffic's limits as well as halving its price.

Batch or not?

Which of these should use the Batches API? (a) Re-summarising 300,000 archived support tickets with a new prompt. (b) The "summarise this thread" button in your support tool. (c) Running your 2,000-case eval set against a candidate model before a release.

Show answer

(a) and (c) are batch work; (b) must stay synchronous.

What’s happening
  1. (a) Nobody is waiting on each summary, there are many of them, and they're independent: perfect for batches at half price, with results matched back by ticket id as custom_id.
  2. (b) A user clicked a button and is watching the screen. Batches can take up to 24 hours (most finish within an hour, but you can't promise seconds), so this needs a normal, streamed request.
  3. (c) An eval run is offline and independent per case. Batching it halves the cost of every model comparison, which makes it cheaper to evaluate often; the only cost is waiting a bit longer for the scores.
  4. The rule: if a human is waiting for this specific answer, don't batch it; if it's bulk, independent work, batch it.

Written fresh for AI engineering interviews (there was no Google Doc for this one). Examples were run on Node 26 with @anthropic-ai/sdk 1.17.0, the AI SDK 7.1 and transformers.js 4.3; API facts were checked against Anthropic’s documentation in December 2026.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.