Learning Goals
3 min- Install the Anthropic SDK; store your API key safely.
- Send a message with
client.messages.create. - Read the response object (
.content[0].text, usage). - Pick a model +
max_tokenssensibly for cost.
Warm-Up · It's Just an API Call
5 minpip install anthropic # get a key from console.anthropic.com, then (don't hard-code it!): export ANTHROPIC_API_KEY="sk-ant-..." # macOS/Linux setx ANTHROPIC_API_KEY "sk-ant-..." # Windows
An LLM API is the REST + auth pattern from Level 4 (L4-11) wrapped in a friendly SDK. You send a list of messages, you get a reply object. The model is doing the magic; your job is the plumbing — and keeping the key out of your code.
New Concept · messages.create
14 minThe first call
import anthropic client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment msg = client.messages.create( model="claude-haiku-4-5", # fast + cheap; great for learning max_tokens=300, messages=[ {"role": "user", "content": "Explain photosynthesis to a 10-year-old."} ], ) print(msg.content[0].text)
The response object
print(msg.content[0].text) # the reply text print(msg.stop_reason) # why it stopped (end_turn, max_tokens, ...) print(msg.usage) # input_tokens / output_tokens — your bill
You pay per token (input + output). max_tokens caps the reply length (and your cost). Check usage to learn how much each call costs.
Choosing a model (cost vs capability)
claude-haiku-4-5 fastest, cheapest — quizzes, simple tasks, learning claude-sonnet-4-6 balanced — most apps claude-opus-4-7 most capable — hard reasoning, complex tasks (OpenAI's GPT models work the same way via the openai SDK.)
Keep your key out of code
# ✓ from environment (the SDK does this automatically) client = anthropic.Anthropic() # ✓ or via python-dotenv for local dev from dotenv import load_dotenv load_dotenv() # reads .env (which is git-ignored!) # ✗ NEVER: client = anthropic.Anthropic(api_key="sk-ant-hardcoded") # leaks in git!
Handle errors
try: msg = client.messages.create(model="claude-haiku-4-5", max_tokens=300, messages=[{"role": "user", "content": q}]) except anthropic.APIError as e: print(f"API error: {e}")
Worked Example · A Homework Explainer
12 min# explainer.py — ask Claude to explain anything simply import anthropic client = anthropic.Anthropic() def explain(topic, age=12): msg = client.messages.create( model="claude-haiku-4-5", max_tokens=400, messages=[{ "role": "user", "content": f"Explain '{topic}' to a {age}-year-old in 3 short " f"sentences, with one everyday analogy." }], ) return msg.content[0].text, msg.usage text, usage = explain("how vaccines work") print(text) print(f"\n[tokens: in={usage.input_tokens}, out={usage.output_tokens}]")
Sample output
A vaccine is like showing your body a "wanted poster" of a germ. Your immune system studies the poster and practises fighting that germ without you getting sick. Then if the real germ ever shows up, your body already knows how to beat it. [tokens: in=28, out=71]
Read the diff
The whole call is three lines; everything interesting is in the prompt (the next lessons are all about writing good prompts). Notice we logged token usage — get in the habit early, because it's your bill. For a learning app, Haiku keeps calls to fractions of a cent.
Try It Yourself
13 minSend any question to Claude and print the reply. Then print the token usage.
Ask for a story with max_tokens=50 then max_tokens=500. How does stop_reason differ? (Hint: short caps hit max_tokens.)
Ask the same hard reasoning question to claude-haiku-4-5 and claude-sonnet-4-6. Compare the answers and the token cost. When is the bigger model worth it?
Mini-Challenge · A CLI Q&A Tool
8 minBuild ask.py: read a question from sys.argv, send it to Claude, print the answer and the cost in tokens. Handle the "no API key" and network-error cases gracefully.
Show one possible solution
# ask.py import sys, os, anthropic if not os.environ.get("ANTHROPIC_API_KEY"): sys.exit("Set ANTHROPIC_API_KEY first.") question = " ".join(sys.argv[1:]) or "Tell me a fun science fact." client = anthropic.Anthropic() try: msg = client.messages.create( model="claude-haiku-4-5", max_tokens=400, messages=[{"role": "user", "content": question}], ) except anthropic.APIError as e: sys.exit(f"API error: {e}") print(msg.content[0].text) print(f"\n[in {msg.usage.input_tokens} / out {msg.usage.output_tokens} tokens]")
Non-negotiables: key from env, friendly errors, token report. This is the skeleton every later LLM lesson builds on.
Recap
3 minAn LLM call is a REST request with auth, wrapped in an SDK: client.messages.create(model, max_tokens, messages) → .content[0].text. Keep the key in the environment, never in code. Pick the cheapest model that does the job (Haiku for learning). Watch usage — that's your bill. Next: shaping behaviour with system prompts.
Vocabulary Card
- LLM
- Large Language Model — predicts text; accessed via an API.
- messages
- The conversation list of role/content dicts sent to the model.
- token
- A chunk of text (~¾ of a word); you're billed per input + output token.
- max_tokens
- Caps the reply length (and cost).
Homework
4 minBuild a small CLI tool that does one useful LLM task (explain a word, summarise a paragraph, rewrite text politely). Key from env, friendly errors, print token usage. Commit it with a README and a .env.example (no real key).
Adapt ask.py to your chosen task. Make sure .env is in .gitignore and a .env.example documents the key name.