devHọc Dev

Week 2 - Day 5: Claude API: Messages, streaming, tool use, structured output, caching, cost and errors

Week 2 – Day 5

This lesson combines 4 topics: Messages API basics, Streaming, structured output and tool use, Prompt caching, token counting and cost, Error handling and rate limits.

Learning Objectives

  • Call the Messages API with the TypeScript and Python SDKs, and understand every field of the request and response
  • Understand that the API is stateless: you manage the conversation history yourself
  • Read stop_reason and handle each value correctly (end_turn, max_tokens, tool_use, refusal...)
  • Tune thinking depth with output_config.effort
  • Use streaming for long output and get the complete message with the SDK helper
  • Force output to match a JSON schema with structured outputs instead of prefill or regex
  • Define a tool, run a complete tool use loop, and return tool errors correctly
  • Design prompts that cache well and verify cache hits through usage
  • Count tokens before sending and estimate monthly cost
  • Classify API errors: which ones to retry, which ones need a fixed request; handle 429 and 529
  • Know the important API differences of current models compared with older models

Part 1: Messages API basics

1. Installation and authentication

# TypeScript / JavaScript
npm install @anthropic-ai/sdk

# Python
pip install anthropic

Create an API key in the Claude Console and put it in an environment variable:

export ANTHROPIC_API_KEY=sk-ant-...   # placeholder, never commit a real key

The SDK reads ANTHROPIC_API_KEY automatically; do not hard-code the key in your code. In production, fetch the key from a secret manager (AWS Secrets Manager, Vault...) and inject it through an environment variable.

2. Your first request

TypeScript:

import Anthropic from "@anthropic-ai/sdk";

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

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  system: "You are an assistant for the acme-shop backend team. Answer concisely, with TypeScript code examples.",
  messages: [
    { role: "user", content: "When should I use optimistic locking instead of pessimistic locking?" },
  ],
});

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

Python:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    system="You are an assistant for the acme-shop backend team. Answer concisely, with Python code examples.",
    messages=[
        {"role": "user", "content": "When should I use optimistic locking instead of pessimistic locking?"}
    ],
)

for block in response.content:
    if block.type == "text":
        print(block.text)
print(response.stop_reason, response.usage)

3. Request and response structure

Request fieldMeaning
modelModel ID, e.g. claude-opus-5-5. Use the exact string from the docs; do not append a date suffix yourself
max_tokensOutput ceiling for this response. Set it too low and the output gets cut off midway
systemYour instructions (role, rules, stable context)
messagesConversation history, alternating user / assistant, starting with user
toolsTool definitions (Part 2)
output_configeffort, format for structured output
Response fieldMeaning
contentArray of content blocks: text, thinking, tool_use... Always check type before reading
stop_reasonWhy the model stopped (table below)
usageinput_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens
idMessage ID

Common trap: reading response.content[0].text directly. With current models the first block may be thinking, so the code throws or reads an empty string. Always filter by type.

4. Multi-turn conversations: the API remembers nothing

The API is stateless. To continue a conversation, you send the whole history again:

const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "The orders table in my schema has a total column of type FLOAT." },
];

const first = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, messages });
messages.push({ role: "assistant", content: first.content }); // push the whole content, not just the text

messages.push({ role: "user", content: "Write a Prisma migration that changes it to an integer (VND)." });
const second = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, messages });

Push the assistant's entire content (including thinking blocks and tool_use blocks) into the history; do not extract only the text. With current models, thinking blocks must be sent back unmodified; treat the history as append-only and do not edit earlier turns.

5. stop_reason

ValueMeaningHandling
end_turnThe model finished its answerUse the result
max_tokensHit the max_tokens ceilingOutput is truncated: raise max_tokens, use streaming, or ask for shorter output
stop_sequenceHit a stop sequence you setHandle as designed
tool_useThe model wants to call a toolRun the tool, send tool_result (Part 2)
pause_turnThe turn was paused (usually with long-running server tools)Send it back to continue
refusalThe model refused for safety reasonsRead stop_details; do not treat content as a valid answer

Production code must check stop_reason before using content. JSON truncated at max_tokens is a common source of bugs.

6. Effort and thinking

Current models use adaptive thinking. You control the depth with effort:

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  output_config: { effort: "low" }, // low | medium | high | xhigh | max
  messages: [{ role: "user", content: "Classify the following as a bug report or a feature request: ..." }],
});

Remember (as of 11/2026, see Effort):

  • Default effort: medium for Opus 5.5 and Haiku 5.5, high for Sonnet 5.5 and Fable 5.2. Set it explicitly so switching models does not surprise you.
  • Opus 5.5: thinking is always on; thinking: {type: "disabled"} and budget_tokens both return 400.
  • By default the thinking content is not shown (the text field is empty) but it is still billed. To see a summary: thinking: { type: "adaptive", display: "summarized" }.

7. API changes that trip people up when moving from older models

Old habitWith current modelsReplace with
Prefill: last message is assistant with { to force JSON400Structured outputs (output_config.format)
tool_choice: {type: "any"} or {type: "tool", name} to force a tool call400 on Opus 5.5, Sonnet 5.5, Fable 5.2auto + instructions in the prompt + strict: true
temperature, top_p, top_kCannot be tuned as before (400)Drop them; design around non-determinism
thinking: {type: "enabled", budget_tokens: N}400Adaptive thinking + effort
Reading content[0].textMay be a thinking blockFilter blocks by type

See the full list in the Migration guide.


Part 2: Streaming, structured output and tool use

1. Streaming

For long output or a large max_tokens, use streaming to avoid HTTP timeouts and to show the output to the user progressively.

TypeScript, printing text as it arrives:

const stream = client.messages.stream({
  model: "claude-opus-5-5",
  max_tokens: 64000,
  messages: [{ role: "user", content: "Write technical documentation for the payment module based on this description: ..." }],
});

for await (const event of stream) {
  if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
    process.stdout.write(event.delta.text);
  }
}

If you do not need progressive display but still want to avoid timeouts, use the helper that returns the complete message instead of assembling events yourself:

const message = await client.messages
  .stream({ model: "claude-opus-5-5", max_tokens: 64000, messages })
  .finalMessage();

The Python equivalent: with client.messages.stream(...) as stream: message = stream.get_final_message().

2. Structured outputs: JSON that matches the schema

When output feeds into code (saved to a DB, passed to another API), do not parse free text with regex. Use structured outputs to constrain the output to a JSON Schema.

Python:

import json

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{
        "role": "user",
        "content": "Classify the ticket: 'I was charged twice for order #A1023 and have not received it.'",
    }],
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "category": {"type": "string", "enum": ["billing", "shipping", "account", "product", "other"]},
                    "urgency": {"type": "string", "enum": ["low", "medium", "high"]},
                    "order_ids": {"type": "array", "items": {"type": "string"}},
                },
                "required": ["category", "urgency", "order_ids"],
                "additionalProperties": False,
            },
        }
    },
)

if response.stop_reason == "end_turn":
    text = next(b.text for b in response.content if b.type == "text")
    ticket = json.loads(text)

TypeScript with Zod and the SDK helper:

import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";

const Ticket = z.object({
  category: z.enum(["billing", "shipping", "account", "product", "other"]),
  urgency: z.enum(["low", "medium", "high"]),
  order_ids: z.array(z.string()),
});

const response = await client.messages.parse({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  messages: [{ role: "user", content: "Classify the ticket: 'I was charged twice for order #A1023.'" }],
  output_config: { format: zodOutputFormat(Ticket) },
});

const ticket = response.parsed_output; // null if parsing failed: you must check

Structured outputs guarantee syntax and schema, not correct content. category: "billing" is valid against the schema but can still be the wrong classification. Content quality is measured with evals (Day 6).

3. Tool use: letting the model call your functions

Tool use lets the model ask to run a function you define. The model runs nothing itself: it returns a tool_use block with the tool name and arguments; your code runs the function and sends the result back.

YourcodeClaudeAPI│messages+tools││──────────────────────────────────▶││stop_reason:tool_use││tool_use{id,name,input}││◀──────────────────────────────────││││runthefunctionyourself││││user:tool_result{tool_use_id}││──────────────────────────────────▶││stop_reason:end_turn││finaltextanswer││◀──────────────────────────────────│

TypeScript example with a tool that looks up order status:

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const tools: Anthropic.Tool[] = [
  {
    name: "get_order_status",
    description:
      "Look up the status of an acme-shop order by order ID. Returns the status, " +
      "order date and tracking number if any. Use when a customer asks where their order is.",
    strict: true,
    input_schema: {
      type: "object",
      properties: {
        order_id: { type: "string", description: "Order ID in the form A1234" },
      },
      required: ["order_id"],
      additionalProperties: false,
    },
  },
];

async function getOrderStatus(orderId: string): Promise<string> {
  // Call the real service here; this example returns fake data
  return JSON.stringify({ order_id: orderId, status: "shipping", tracking: "VN123456" });
}

const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "Where is my order A1023? Please look it up with the tool." },
];

const MAX_TURNS = 10; // cap the number of turns: avoid running forever and burning money
let finished = false;

for (let turn = 0; turn < MAX_TURNS; turn++) {
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    tools,
    messages,
  });

  messages.push({ role: "assistant", content: response.content });
  if (response.stop_reason !== "tool_use") {
    finished = true;
    break;
  }

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== "tool_use") continue;
    try {
      const input = block.input as { order_id: string };
      results.push({ type: "tool_result", tool_use_id: block.id, content: await getOrderStatus(input.order_id) });
    } catch (err) {
      results.push({ type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true });
    }
  }
  messages.push({ role: "user", content: results }); // all tool_results in ONE message
}

if (!finished) throw new Error(`Tool loop exceeded ${MAX_TURNS} turns, stopping`);

Key points:

  • Send every tool_result of a turn in the same user message. The model may call several tools in parallel in one turn; splitting the results across multiple messages breaks parallel calling.
  • When a tool fails, return a tool_result with is_error: true; do not drop it. The model can read the error and try another approach.
  • strict: true guarantees input matches the schema (the schema needs additionalProperties: false and required). Still validate on your side before doing anything with side effects.
  • Do not force tool calls on Opus 5.5, Sonnet 5.5, Fable 5.2 (tool_choice any/tool returns 400). Use the default auto and state clearly in the prompt when to use the tool; check whether the response contains tool_use and handle the case where it does not.
  • Parse input as a JSON object; do not do string matching on its serialized form.
  • Cap the number of loop iterations (MAX_TURNS above, e.g. at most 10 turns) to avoid infinite loops and runaway cost; if the cap is hit before the work is done, fail loudly instead of silently.

The SDK also has a tool runner (beta) that runs this loop for you: client.beta.messages.toolRunner(...) in TypeScript, client.beta.messages.tool_runner(...) in Python. Day 6 compares ways to build an agent loop.


Part 3: Prompt caching, token counting and cost

1. How prompt caching works

Many applications repeatedly send a large identical portion: a long system prompt, reference documents, tool definitions. Prompt caching stores that prefix so later requests can read it back at a much lower price.

The core principle: caching is prefix matching. The render order is tools → system → messages. Changing a single byte anywhere in the prefix invalidates the cache for everything after it.

Requestlayout(renderorder)┌────────────┬──────────────────────┬────────────────────┬──────────────┐│tools│system(stabledocs)│oldmessages│newquestion│└────────────┴──────────────────────┴────────────────────┴──────────────┘◀────────────cachedprefix(mustbebyte-identical)──▶◀─uncached─▶

The simplest approach: set cache_control at the top level so the SDK automatically marks the last cacheable block:

const response = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  cache_control: { type: "ephemeral" },
  system: LONG_PRODUCT_CATALOG_GUIDE, // long, stable content
  messages: [{ role: "user", content: question }],
});

Or set it explicitly on a specific block (at most 4 breakpoints per request):

system: [
  {
    type: "text",
    text: LONG_PRODUCT_CATALOG_GUIDE,
    cache_control: { type: "ephemeral" }, // default TTL 5 minutes; optional ttl: "1h"
  },
],

Verify cache hits through usage:

console.log(response.usage.cache_creation_input_tokens); // tokens written to the cache
console.log(response.usage.cache_read_input_tokens);     // tokens read from the cache
console.log(response.usage.input_tokens);                // uncached tokens

If cache_read_input_tokens is always 0 even though the prefix is "the same", something is silently changing the prefix:

Cache breakerExampleFix
Time in the system promptToday is ${new Date().toISOString()}Move changing information to the end, after the breakpoint
Random IDsrequest ID, UUID in the system promptMove them into the last message
JSON with unstable key orderJSON.stringify on a dynamically built objectSort keys or fix the structure
Changing tool listEnabling/disabling tools per userKeep the tool list fixed, enforce permissions on your side
Prefix too short200-token system promptBelow the model's minimum threshold nothing is cached, and no error is raised

Caches are separate per model: switching models mid-conversation means the old cache cannot be used.

2. Cache pricing

According to Pricing (as of 11/2026):

  • Cache write with 5-minute TTL: 1.25x the input price; 1-hour TTL: 2x.
  • Cache read: 0.1x the input price on most models; Opus 5.5 and Sonnet 5.5 are 0.05x, Fable 5.2 is 0.025x.
  • Example for Opus 5.5: input $4/MTok, 5-minute cache write $5/MTok, cache read $0.20/MTok, output $20/MTok.

3. Counting tokens before sending

Use the token counting endpoint, passing the exact model you will use (token counts depend on the model's tokenizer):

const count = await client.messages.countTokens({
  model: "claude-opus-5-5",
  system: LONG_PRODUCT_CATALOG_GUIDE,
  messages: [{ role: "user", content: question }],
});
console.log(count.input_tokens);
count = client.messages.count_tokens(
    model="claude-opus-5-5",
    messages=[{"role": "user", "content": open("docs/pricing.md").read()}],
)
print(count.input_tokens)

Do not estimate with another provider's tokenizer (e.g. tiktoken): the error is significant, especially for code and non-English text.

4. Cost estimation: an example

The acme-shop support chatbot uses Opus 5.5. Each request: a 20,000-token system prompt (guidelines + policies), a 500-token question, an 800-token answer. 1,000 requests/day, with the conservative assumption that the 5-minute cache is rewritten about 50 times/day (traffic comes in hourly bursts, or the system prompt gets updated). With steady traffic each cache read refreshes the TTL, so there are even fewer writes. The 800 output tokens here already include Opus 5.5's thinking tokens; in practice, measure usage.output_tokens instead of guessing.

Without caching: every input token is billed at the normal price.

ItemCalculationCost/day
Input1,000 × 20.5K = 20.5M tokens × $4/MTok$82.00
Output1,000 × 800 = 0.8M tokens × $20/MTok$16.00
Total$98.00

With caching (the 20K system prompt is cached):

ItemCalculationCost/day
Cache write50 × 20K = 1M tokens × $5/MTok$5.00
Cache read950 × 20K = 19M tokens × $0.20/MTok$3.80
Uncached input (question)1,000 × 500 = 0.5M tokens × $4/MTok$2.00
Output0.8M tokens × $20/MTok$16.00
Total$26.80

(Prices as of 11/2026, source: Pricing.)

Lessons from the tables:

  1. Caching cuts cost by ~73% in this example because the repeated part makes up most of the input.
  2. After caching, output becomes the largest item (60% of the total). The next levers: ask for more concise answers, cap length, lower effort for simple questions.
  3. For work that does not need an immediate answer (bulk classification, end-of-day summaries), use the Batch API: 50% off both input and output, and it stacks with the cache discount.

5. Cost levers in the order to try them

OrderLeverQuality impact
1Prompt caching for the repeated partNone
2Trim unnecessary input: irrelevant documents, overly long historyUsually none, sometimes better
3Limit output: ask for concise answers, structured output instead of proseUsually none
4Batch API for non-urgent workNone (just slower)
5Lower effort per request typeMust be measured with evals
6Switch to a smaller model per routeMust be measured with evals

The first four levers are nearly "free" in terms of quality; the last two are trade-offs and must be measured.


Part 4: Error handling and rate limits

1. Error code table

According to Errors:

HTTPTypeRetry?Common causes
400invalid_request_errorNoMalformed request: missing field, wrong type, prefill on a newer model, unsupported parameter
401authentication_errorNoKey is wrong, missing, or revoked
402billing_errorNoAccount billing problem
403permission_errorNoKey has no permission for the resource
404not_found_errorNoWrong endpoint or model ID
413request_too_largeNoRequest exceeds the size limit
429rate_limit_errorYesExceeded the per-minute request or token limit
500api_errorYesError on Anthropic's side
504timeout_errorYesRequest ran too long; for long output switch to streaming
529overloaded_errorYesAPI temporarily overloaded

Rule: 4xx errors (except 429) are request errors and retrying does not help; fix the request. Retry 429, 5xx and network errors with backoff.

2. Retries and timeouts in the SDK

  • The official SDKs retry automatically on 408, 409, 429, 5xx and connection errors with exponential backoff, 2 times by default (max_retries / maxRetries).
  • The default timeout is 10 minutes. The unit differs by language: Python uses seconds, TypeScript uses milliseconds.
  • Retries add up: the total wait can reach timeout × (max_retries + 1).

Catch errors by specific class, from most specific to most general:

import Anthropic from "@anthropic-ai/sdk";

try {
  const response = await client.messages.create({ /* ... */ });
} catch (error) {
  if (error instanceof Anthropic.BadRequestError) {
    // 400: request error, log it and fix the code; do not retry
  } else if (error instanceof Anthropic.AuthenticationError) {
    // 401: operational alert, something is wrong with the key
  } else if (error instanceof Anthropic.RateLimitError) {
    // 429: the SDK already retried and still failed; requeue or reduce load
  } else if (error instanceof Anthropic.APIError) {
    // other API errors, error.status is available
  } else {
    throw error;
  }
}

Python:

try:
    response = client.messages.create(...)
except anthropic.BadRequestError as e:
    log.error("bad request", extra={"message": e.message})
except anthropic.RateLimitError as e:
    retry_after = e.response.headers.get("retry-after")
    if retry_after is None:
        # 429 without retry-after: likely the spend cap was hit, retrying is pointless
        alert_ops("rate limit without retry-after", request_id=e.request_id)
        raise
    queue.requeue(job, delay=int(retry_after))
except anthropic.APIStatusError as e:
    if e.status_code >= 500:
        queue.requeue(job, delay=30)
    else:
        raise
except anthropic.APIConnectionError:
    queue.requeue(job, delay=10)

Do not catch errors by matching the message string; use the SDK's typed error classes.

3. Rate limits

According to Rate limits (as of 11/2026):

  • Limits apply per organization and usage tier, measured in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM) for each model. For the actual numbers see the Rate limits page in the Console; they vary by tier.
  • Token bucket algorithm: capacity is replenished continuously, so a short burst of requests can still get a 429 even when the per-minute average has headroom.
  • On most models, tokens read from the cache do not count toward ITPM; only input_tokens and cache_creation_input_tokens count. So caching both lowers cost and increases effective throughput.
  • Each tier has a monthly spend cap. When it is hit, the API returns 429 with error.details.error_code set to enforced_spend_limit_reached and no retry-after header; every retry (including the SDK's automatic retries) fails until it is lifted. If the organization sets its own spend limit below the cap, hitting that limit returns 400.

When you get a 429:

  • Distinguish a rate limit from a spend cap by the error_code and whether retry-after is present.
  • If there is a retry-after, wait exactly that many seconds.
  • The headers anthropic-ratelimit-requests-remaining, anthropic-ratelimit-input-tokens-remaining, anthropic-ratelimit-output-tokens-remaining... tell you what is left; use them to slow down proactively before hitting the ceiling.
  • For bulk jobs: limit concurrency, use a queue, ramp up load gradually (a sudden spike can hit the acceleration limit), or move to the Batch API.

4. Logging so you can debug

Every production request should log:

FieldWhy
Request ID (_request_id on the SDK response object)Send it to Anthropic support when an investigation is needed
Model ID, effortReproduce and compare when the configuration changes
stop_reasonDetect truncated output, refusals, tool loops
usage (including cache)Track cost, verify caching
Latency, retry countDetect overload and misconfigured timeouts
Prompt and output (with PII controls)Debug quality; comply with the organization's data policy

Review Questions

  1. Why can code like response.content[0].text break with current models?

    Show answer

    content is an array of several block types. With adaptive thinking the first block may be thinking (empty text by default), and with tool use it may be tool_use. You must filter by type === "text". Also check stop_reason to know whether the output was truncated or is a refusal.

  2. In a multi-turn conversation, why must you push the assistant's entire response.content into the history instead of just the text?

    Show answer

    The API is stateless; the history you send is everything the model knows. tool_use blocks must be in the history so that tool_result can reference them; thinking blocks must be sent back unmodified with current models; some features such as compaction also return special blocks that must be kept. Extracting only the text breaks tool use or loses state.

  3. A job receives stop_reason: "max_tokens" and JSON.parse fails. What is the cause and how do you fix it?

    Show answer

    The output was cut off when it hit max_tokens, so the JSON is not closed. Fix: check stop_reason before parsing; raise max_tokens (use streaming if it is large, to avoid timeouts); or reduce the requested output length and split the work. Do not "fix" it by closing the JSON brackets yourself.

  4. Old code uses the prefill {"role": "assistant", "content": "{"} to force JSON. What happens when you move to Opus 5.5, and what should replace it?

    Show answer

    Current models do not accept assistant prefill; the request returns 400. Replace it with structured outputs: output_config: { format: { type: "json_schema", schema } }, or messages.parse with Zod/Pydantic. Structured outputs guarantee the schema with no prefill tricks needed.

  5. What do structured outputs guarantee, and what do they not guarantee?

    Show answer

    They guarantee the output is syntactically valid JSON and matches the schema (types, enums, required fields). They do not guarantee correct content: a schema-valid value can still be a wrong classification or a wrongly extracted number. Content quality must be measured with evals.

  6. In a tool use loop, the model calls 3 tools in one turn. How do you send the results correctly? What if one tool fails?

    Show answer

    Send all 3 tool_result blocks (each with its matching tool_use_id) in the same user message. A failed tool still returns a tool_result with the error content and is_error: true, not skipped; the model reads the error and decides whether to try another approach. Splitting the results across multiple messages makes the model call tools in parallel less.

  7. You want the model to always call the get_order_status tool when a customer asks about an order. How do you do this on Opus 5.5?

    Show answer

    Do not force it with tool_choice any or tool (400 on Opus 5.5). Use auto, write a tool description that states clearly when to use it, say in the system prompt that every order question must be looked up with the tool, set strict: true so the input matches the schema, and in code check whether the response contains tool_use; if it does not, handle it (ask again or re-prompt).

  8. What does it mean that prompt caching is "prefix matching"? Why does inserting the current date and time at the start of the system prompt break the cache?

    Show answer

    The cache can only be used when the beginning of the request (in the order tools → system → messages) is byte-for-byte identical to a previous request. Changing anything in the prefix invalidates the cache for everything after it. The date and time change with every request, so the prefix is never the same; move changing information to the end, after the breakpoint.

  9. How do you know whether the cache is working?

    Show answer

    Read usage.cache_read_input_tokens on repeated requests with the same prefix. A value greater than 0 means a cache hit. If it is always 0, check: what changes in the prefix (time, IDs, JSON key order, tool list), whether the prefix is below the minimum threshold, whether the model changed, whether the requests are in the same workspace, and whether the gap between requests exceeds the TTL.

  10. After enabling caching, the chatbot's cost drops from $98 to $26.80 per day. Where should the next lever be aimed?

Show answer

Output, because after caching it accounts for about 60% of the total ($16/$26.80). Ask for more concise answers, cap length, lower effort for simple questions (reducing thinking tokens, which are billed as output), and consider a smaller model for easy question types if evals confirm the quality is sufficient.

  1. Why should you not estimate tokens with tiktoken?
Show answer

tiktoken is another provider's tokenizer; it does not match Claude's tokenizer and the error is significant, especially for code and non-English text. Token counts also depend on the model (the new tokenizer from Opus 4.7 onward produces about 30% more tokens). Use the count_tokens endpoint with the exact model ID.

  1. Which errors should be retried and which should not? Why is retrying a 400 wasteful?
Show answer

Retry: 429, 500, 529, network errors (the SDK does this automatically, 2 times by default). Do not retry: 400, 401, 403, 404, 413, because the error lies in the request or the configuration; sending the same thing again fails the same way, wastes time and can delay discovering the bug. Log it and fix the request.

  1. In the Python SDK you set timeout=30, and in TypeScript you set timeout: 30. What is wrong?
Show answer

Python uses seconds, so that is 30 seconds; TypeScript uses milliseconds, so 30 is 30ms and every request times out immediately. In TypeScript it must be 30_000. Also, with long output a short timeout cuts the request off; use streaming.

  1. Name 4 fields to log for every production request and why.
Show answer

Request ID (to work with support), model and effort (reproduce, compare configurations), stop_reason (detect truncated output, refusals), usage including cache (cost, cache verification), latency and retry count (detect overload). Prompt and output if the data policy allows it, with PII controls.

Hands-on Exercises

Exercise 1: Multi-turn Q&A CLI

Write a TypeScript or Python CLI for multi-turn Q&A with Claude: keep the history, print usage after each turn, exit with /exit. Read the key from an environment variable.

Expected output: a working program; after 5 turns, explain why input_tokens grows with every turn.

Exercise 2: Ticket classification with a schema

Write a classifyTicket(text) function that uses structured outputs with the schema from Part 2. Run it on 20 tickets you write yourself (including ambiguous tickets, tickets with multiple issues, and tickets mixing English and Vietnamese).

Expected output: 20 valid JSON results; a table of the classifications you disagree with; this becomes the data for the eval in Day 6.

Exercise 3: Tool use with two tools

Extend the tool use example with two tools, get_order_status and cancel_order. cancel_order may only be called when the user explicitly confirms; add a confirmation step in code before actually executing it.

Expected output: a log of every iteration (tool_use, tool_result); one error scenario (is_error: true) and how the model reacts; a cap of at most 8 iterations.

Exercise 4: Measuring the cache

Create a long system prompt (e.g. 5,000+ tokens of hypothetical policy documents). Send 5 consecutive requests with different questions, with cache_control. Then insert a timestamp at the start of the system prompt and repeat.

Expected output: a table of cache_creation_input_tokens, cache_read_input_tokens, input_tokens for the 10 requests; an explanation of the difference between the two rounds.

Exercise 5: Estimating cost for your own feature

Pick a real or hypothetical feature. Estimate input tokens (using count_tokens), output tokens, and requests/day. Calculate the monthly cost for 3 options: Opus 5.5 without caching, Opus 5.5 with caching, Haiku 5.5 with caching (prices as of 11/2026 from the Pricing page).

Expected output: a table of the 3 options; state your assumptions clearly; recommend an option and the conditions that need verifying (an eval of Haiku 5.5's quality).

Exercise 6: A fault-tolerant API wrapper

Write a wrapper around messages.create that: classifies errors according to the table in Part 4, honors retry-after on a 429 after the SDK has exhausted its retries, logs the fields from section 4, and checks stop_reason.

Expected output: the wrapper + tests simulating 400, 429, 529 (mocked HTTP); a sample log for each case.

References


Next lesson →