Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 14 / Stage 4

Using LLM APIs

Goal: Call Claude correctly from Python: the Messages API, multi-turn, streaming, structured output, errors, and cost. Time: ~3 hours · Needs: Part 13

About the outputs here: every example in this part ran against the installed anthropic SDK pointed at a local placeholder server (tools/mock_claude.py), so the request/response code is genuinely exercised without an API key — but printed replies like [mock reply] are placeholder text, not Claude. Set ANTHROPIC_API_KEY and run the same files for real answers.

What you will learn

  • The Messages API: model, max_tokens, system, content blocks
  • Multi-turn conversations
  • Streaming
  • Structured output with Pydantic
  • Images and PDFs as input
  • Errors and retries
  • Tokens, cost and prompt caching

Topics in this part

Practice

API exercises run without a key against the local placeholder server: start python tools/mock_claude.py 8765 in another terminal, then export ANTHROPIC_BASE_URL=http://127.0.0.1:8765 ANTHROPIC_API_KEY=mock-key. (With a real ANTHROPIC_API_KEY and no base-url override, the same code returns real answers.)

Exercise 1: Read the blocks properly

Send one message and print, for each content block: its type, and its text if it has one. Then print stop_reason and both token counts from usage.

Show the solution to Exercise 1
# Exercise 1: Read the blocks properly
import anthropic

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Name one use of embeddings."}],
)
for block in response.content:
    text = getattr(block, "text", "")
    print(f"block type={block.type}" + (f" text={text!r}" if text else ""))
print("stop_reason:", response.stop_reason)
print("tokens in/out:", response.usage.input_tokens, response.usage.output_tokens)

Exercise 2: A minimal chat loop

Write chat(text) that appends to a shared history, calls the API, appends the assistant's full content blocks, and returns the reply text. After two calls, print the number of messages that the third call would send.

Show the solution to Exercise 2
# Exercise 2: A minimal chat loop
import anthropic

client = anthropic.Anthropic()
history = []


def chat(user_text):
    history.append({"role": "user", "content": user_text})
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=16000, messages=history)
    history.append({"role": "assistant", "content": response.content})
    return "".join(b.text for b in response.content if b.type == "text")


chat("My order number is A1001.")
chat("What was my order number?")
print("messages the third call would send:", len(history) + 1)  # history + new user turn
print("roles so far:", [m["role"] for m in history])

Exercise 3: Your own schema

Define an Order Pydantic model (item: str, quantity: int, express: bool) and use messages.parse to extract it from "Two blue mugs please, as fast as possible." Print the type and the model_dump of the result. (Against the mock, values are placeholders — the exercise is the schema round trip.)

Show the solution to Exercise 3
# Exercise 3: Your own schema
from pydantic import BaseModel
import anthropic


class Order(BaseModel):
    item: str
    quantity: int
    express: bool


client = anthropic.Anthropic()
response = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content":
               "Extract the order: 'Two blue mugs please, as fast as possible.'"}],
    output_format=Order,
)
order = response.parsed_output
print(type(order).__name__, order.model_dump())
print("quantity is an int:", isinstance(order.quantity, int))

Exercise 4: Retry policy

Write should_retry(exc) -> bool covering NotFoundError, RateLimitError, APIConnectionError and APIStatusError (by status code). Prove it with the fake model name (expect False) — and print the decision table for the other cases.


Show the solution to Exercise 4
# Exercise 4: Retry policy
import anthropic

client = anthropic.Anthropic()


def should_retry(exc) -> bool:
    if isinstance(exc, anthropic.APIConnectionError):
        return True                                   # network: transient
    if isinstance(exc, anthropic.RateLimitError):
        return True                                   # 429: back off and retry
    if isinstance(exc, anthropic.APIStatusError):
        return exc.status_code >= 500                 # 5xx yes; other 4xx no
    return False


try:
    client.messages.create(model="claude-does-not-exist", max_tokens=1024,
                           messages=[{"role": "user", "content": "Hello"}])
except anthropic.APIStatusError as e:
    print(f"got {type(e).__name__} status={e.status_code}; retry -> {should_retry(e)}")

print("\ndecision table:")
print("NotFoundError (404)   -> retry False (fix the request)")
print("RateLimitError (429)  -> retry True  (backoff)")
print("APIStatusError 5xx    -> retry True  (server-side)")
print("APIConnectionError    -> retry True  (network)")

Mini-project: Ticket triage

Classify 12 support messages into the lesson's Ticket schema via messages.parse and write the results to a CSV with columns category/urgent/summary/text. Against the mock the categories are placeholders; the deliverable is the loop, validation and CSV.

A complete version is in solutions/mini_ticket_triage.py.

Stretch: process the tickets with the Message Batches API instead and compare the cost math at list prices.

Common mistakes

Mistake Why it is wrong Fix
Instructions in the first user message Weaker than the system prompt, drifts in long chats system=
response.content[0].text unconditionally Content is typed blocks; first may not be text Filter by block.type
Expecting the API to remember It is stateless Resend history each turn
Retrying 400/404 The request is wrong; retries burn quota Retry only 429/5xx/network
Ignoring stop_reason Truncated replies ship to users Check for max_tokens
Never reading usage Costs surprise you at invoice time Log tokens per request from day one

Quick recap

  • There is one endpoint; the system prompt carries the rules, and content travels as typed blocks.
  • The API is stateless: a chat means resending the history, with the assistant's blocks intact.
  • Stream for perceived speed, and read get_final_message() for usage.
  • messages.parse with a Pydantic model gives validated structured output.
  • The exception type decides the retry; back off for 429 and 5xx only.
  • At $4/$20 per MTok (verified 2026-11-29), log your usage, cache stable prefixes, and batch bulk work.

Checklist

  • I sent a request with a system prompt and read the typed blocks.
  • I can explain why turn 2 sends three messages.
  • I streamed a reply and got the final usage.
  • I got a validated Pydantic object back from parse().
  • I can sort every exception into retry / don't-retry.
  • I computed a monthly cost from per-request usage.

Read more: Messages API · Streaming · Structured outputs · Errors · Prompt caching

Search the guide