Claude and the Anthropic SDK · Chapter 1 of 21
Meet Parchi, and your first Claude call
By the end of this chapter you can send a request to Claude with the official Python SDK, read everything that comes back (the content blocks, the stop reason, the token usage), turn that usage into dollars, and explain why Claude was wrong about a hospital bill while sounding completely sure. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The Messages API
- 4 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Parchi, in Jaipur, helps families claim their health insurance. A family sends a photo of the hospital bill, the pharmacy slip, the discharge summary; Parchi reads them against the policy wording and tells the family, before the insurer decides, what will be paid, what will not, and why. Four hundred bills a week come in on WhatsApp, and three people read them by hand.
Meher, Parchi's founder, spent eight years at a hospital billing desk, and she wants an assistant that does the first reading for the team. Arjun, the senior engineer, will build it with you on Claude, with Anthropic's official Python SDK, the anthropic package. Kamla runs the claims desk and brings the real, messy bills. Farhan, in finance, asks what every answer costs. The assistant will be called Sahay, "help".
If you have called a model before, you used an OpenAI-style API: a messages list, choices[0].message.content, finish_reason. Claude's Messages API looks close enough to guess at, and the guesses break. The reply is not a string but a list of content blocks, and on Claude Opus 5.5 the first block is often not text, so content[0].text stops your program with an AttributeError. max_tokens is required. The system prompt is not a message. The usage fields have other names, and the cache adds two more. This chapter reads a Claude reply properly, field by field, before any of Sahay is built.
The lesson
The lab's Claude
This lab has no internet, so it brings its own Claude: a stand-in that speaks the same HTTP API as Anthropic's, POST /v1/messages, with the same request and reply shapes, the same errors, the same streaming events and the same rules for each model. Two environment variables point the official SDK at it, and your code never mentions them:
ANTHROPIC_BASE_URL=http://127.0.0.1:11500
ANTHROPIC_API_KEY=sk-ant-lab-not-a-real-key
The stand-in is a predictable program, not a neural network. It reads only what your request sends (the system prompt, the messages, documents, images, tool results), never Parchi's files directly, and it answers the same way every time, so a Check can measure what your code changed. Its answers are about Parchi's claims and policy; ask it about anything else and it says so. Its token counts come from its own tokenizer, in Claude's range: real Claude counts differently, and the only true count is what the API reports. The prices are Anthropic's real ones.
To try a real Claude model with the same code, on a machine with internet and your own API key from the Claude Console, pip install anthropic, unset ANTHROPIC_BASE_URL and set ANTHROPIC_API_KEY to your key. Never paste a real key into the lab.
Your first request
import anthropic
client = anthropic.Anthropic()
reply = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello! Can you help me with an insurance claim?"}],
)
print(reply.to_json())
anthropic.Anthropic() reads the key and the address from the environment. Without a key it stops before anything is sent:
TypeError: "Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for the `Authorization` header to be explicitly omitted"
With the lab's key, it prints the whole reply (python3 hello.py):
{
"id": "msg_01FO1xmb8eUAX5mPrkzWdSsj",
"content": [
{
"text": "Namaste! I'm Claude, an AI assistant made by Anthropic. How can I help you today?",
"type": "text"
}
],
"model": "claude-opus-5-5",
"role": "assistant",
"stop_details": null,
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
...
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
...
"input_tokens": 16,
"output_tokens": 24,
...
"service_tier": "standard"
}
}
(The usage object is trimmed: the ... lines are fields for caching and server tools that later chapters use.) The reply is not a dictionary but an object, with an attribute for every field: reply.stop_reason, reply.usage.input_tokens. reply.to_json() and reply.to_dict() turn it into JSON or a dictionary when you want one.
Three fields every request needs
model: which Claude answers. The current models areclaude-opus-5-5(the most capable of the three, and the lab's default),claude-sonnet-5-5(fast and capable for everyday work) andclaude-haiku-5-5(the fastest and cheapest). Ids are written exactly so, with no date on the end. A wrong id is a404 not_found_error.max_tokens: the most tokens the reply may use. It is required, and a reply that reaches it stops in the middle (chapter 3). Thinking, which Opus 5.5 always does, counts towards it too.messages: the conversation, a list of{"role": ..., "content": ...}dictionaries whereroleis"user"or"assistant". The first message is the user's.contentcan be a string, as here, or a list of blocks (images and documents come in blocks, in chapters 10 and 11).
There is one endpoint, POST /v1/messages, and client.messages.create sends one request to it and waits for the reply. Tools, images, PDFs, thinking, caching and structured output are all arguments of this same request, not other APIs.
What comes back: a Message
The reply is a Message (the SDK's class anthropic.types.Message):
| Attribute | What it is |
|---|---|
id | the message's id, msg_... (log it: support asks for it) |
role | always "assistant" |
model | the model that answered |
content | the reply, as a list of content blocks |
stop_reason | why it stopped: end_turn here, the model finished |
usage | the tokens that went in and came out, which is what you pay for |
stop_reason is end_turn when Claude finished on its own. Chapter 3 meets the others: max_tokens (cut off by your limit), stop_sequence, tool_use (it wants to call a tool, chapter 6), refusal, pause_turn. A program should look at stop_reason before it trusts content.
Content is a list of blocks
Gopal Meena's bill is a harder message: eight lines and a question, "How much will the policy pay?". Send it the same way and look at the types of the blocks, then at the first block's text:
print([block.type for block in reply.content])
print(reply.content[0].text)
['thinking', 'text']
Traceback (most recent call last):
...
AttributeError: 'ThinkingBlock' object has no attribute 'text'
Two blocks, and the first is not text. Claude Opus 5.5 always thinks before it answers a question that needs working out (chapter 15 is about thinking), and the thinking comes back as its own block, before the text. By default the thinking's words are left out: the block is there with an empty thinking attribute and a signature, and the tokens are still counted. So content[0] is a ThinkingBlock, it has no text, and the program stops in front of a family.
Every block has a type. Look at it first, and then you know which attributes the block has:
for block in reply.content:
if block.type == "text":
print(block.text)
A text block (TextBlock) keeps its words in text; a thinking block (ThinkingBlock) keeps them in thinking. There are a dozen block types in all (tool calls, and the results of Anthropic's server tools, among them), so a program that reads only the types it knows, by type, keeps working when a new one arrives.
Here is that request and its reply, step by step:
Use the SDK's own classes (anthropic.types.Message, anthropic.types.MessageParam, anthropic.types.ContentBlock) in your type hints instead of writing your own: they change with the API, and yours would not.
Usage, and what it cost
Claude is billed by the token. usage.input_tokens is what you sent (the messages and everything else in the request), and usage.output_tokens is what came back, thinking included. Gopal's question on Opus 5.5:
print(reply.usage.input_tokens, reply.usage.output_tokens, reply.usage.output_tokens_details)
107 164 OutputTokensDetails(thinking_tokens=132)
107 tokens in, 164 out, and 132 of those 164 were thinking you never saw. Prices are in US dollars per million tokens, and output costs five times as much as input (PRICES in the shared prices module has them: from prices import PRICES):
| Model | Input | Output |
|---|---|---|
claude-opus-5-5 | $4.00 | $20.00 |
claude-sonnet-5-5 | $2.00 | $10.00 |
claude-haiku-5-5 | $0.10 | $0.50 |
So Gopal's answer cost 107 x $4 / 1,000,000 + 164 x $20 / 1,000,000 = $0.003708. A third of a US cent sounds like nothing; Farhan multiplies it by four hundred bills a week, several questions a bill, and a model choice that changes it twentyfold. Chapter 5 is about choosing; caching (chapter 13) and batches (chapter 17) are how the bill comes down.
Coming from the OpenAI-style API
| OpenAI-style chat completions | Claude's Messages API |
|---|---|
client.chat.completions.create(...) | client.messages.create(...) |
max_tokens optional | max_tokens required |
the system prompt is a message ("role": "system") | system is a top-level argument |
choices[0].message.content, a string | content, a list of blocks |
finish_reason: "stop" | stop_reason: "end_turn" |
prompt_tokens, completion_tokens | input_tokens, output_tokens |
temperature to tune | not sent on the current API version (chapter 3) |
n for several answers | one answer per request |
Wrong, and sure of it
Ask the lab's Claude a question about Parchi's policy, "Are gloves and masks paid by the policy?", with nothing else in the request:
without: Consumables like gloves, masks and the admission kit are part of the hospital bill, so they are usually paid with the rest of it.
Fluent, confident, and wrong: Parchi's policy pays for neither. The request did not carry the policy, so the model answered with what such policies "usually" say. Now send the same question with the policy wording as the request's system prompt (system=policy_wording(), an argument beside messages; policy_wording comes from the shared parchi module):
with: The policy says: Masks of any kind, N95 or surgical, are non-payable. Annexure I, the list of non-payable items, includes gloves.
Claude knows nothing about Parchi, the families or their policies except what a request carries. A real model's general knowledge is wider than the lab's, and it guesses better, but it cannot know a document it was never sent: Parchi's policy is Parchi's own. The rest of this lab is about sending Claude the right things (instructions, documents, photos, tools), cheaply, and reading what comes back.
Your turn
Send your first request in task 1. Print every block of a reply to Kamla's message in task 2, and price it on all three models for Farhan in task 3. In the interview question, show why Claude was wrong about Pooja's bill.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
first_call.py: your first Claude call
Make a client with anthropic.Anthropic() and send one request with client.messages.create: model "claude-opus-5-5", max_tokens 1024, and one user message, exactly: Namaste! Who are you, and what can you do?
Then print, in this order: the text of the reply's text block, then stop_reason: STOP (reply.stop_reason), then tokens: I in, O out (reply.usage.input_tokens and reply.usage.output_tokens).
- Task 2
read_the_reply.py: every block of the reply
Send KAMLA (given) to "claude-opus-5-5" with max_tokens 1024, as the one user message. Print one line per block of the reply's content, in order: block I: TYPE (N characters), where I counts from 0, TYPE is block.type, and N is the length of block.text for a text block or block.thinking for a thinking block.
Then print the text of the text blocks, then stop_reason: STOP, then usage: I in, O out.
- Task 3
what_it_cost.py: what did it cost?
Send KAMLA to claude-opus-5-5, then claude-sonnet-5-5, then claude-haiku-5-5 (max_tokens 1024, one user message each). Price each reply with PRICES (imported, dollars per million tokens): input_tokens x input price + output_tokens x output price, divided by 1,000,000.
Print one line per model, in that order: MODEL: I in, O out, $COST with COST to 6 decimals (f"{cost:.6f}"). Then print cheapest: MODEL.
- Task 4 · interview question
Interview: wrong_and_sure.py
"Claude told Kamla the policy pays Pooja's whole bill. It does not. Why?" Send KAMLA to "claude-opus-5-5" twice (max_tokens 1024, one user message each): first with nothing else, then with system=policy_wording(), the top-level system argument.
Print without the policy: LINE, then with the policy: LINE, where LINE is the first line of that reply's text.
What you will learn
- The Messages API: the one endpoint, and the three fields every request needs.
- The reply: a Message with content blocks, a stop reason and usage.
- Content blocks: why you check type before you read text.
- What a reply costs, from its usage and the price per million tokens.
- Why a model is confidently wrong about a document it was never sent.
More in The Messages API
Build "Meet Parchi, and your first Claude call" yourself
Parchi, a Jaipur startup, helps families claim health insurance. You build Sahay, a claims assistant that reads bills and policies with Claude, and measure what caching, models and effort cost. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.