Log in←Next →
Field reading10 min

Claude in the FDE Toolkit: Your First API Call

By the end of this lesson you will be able to make a Messages API call, read the response blocks safely, check stop_reason, count tokens and work out the cost of a call.

Try itReading a response safelystop_reason: end_turn
  1. [0] thinking"" (empty by default)
  2. [1] text{"customer": "Lumen", "pain_points": ["18% rework"]}
answer = response.content[0].text

Crash: AttributeError: 'ThinkingBlock' object has no attribute 'text'

A response is a list of typed blocks plus a stop_reason. Opus 5.5 thinks adaptively, so the first block is often a thinking block with empty text. Try each response against each reader, with and without json.loads: only the reader that checks stop_reason first and filters by block type copes with all of them.

Dana Ruiz wants a summary of every Brightline steering meeting to forward to her CEO. You'll have Claude draft it, so you need the API basics: how to send a request, how to read what comes back without crashing, and what each call costs. Try the diagram first: pick a response and a way of reading it, and see which readers break.

The Messages API

One endpoint, messages.create: you send a list of messages, Claude returns one assistant message.

import anthropic

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

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,                 # covers thinking and the answer
    system="You are a concise assistant for a forward deployed engineer.",
    messages=[
        {"role": "user", "content": "Give me three questions to ask in a discovery call."}
    ],
)

print("blocks:", [b.type for b in response.content], "| stop_reason:", response.stop_reason)
for block in response.content:
    if block.type == "text":
        print(block.text)
  • Stateless: Claude doesn't remember earlier calls. Send the full history each time.
  • system holds role, context and rules.
  • messages alternate "user" and "assistant"; the first must be "user".
  • max_tokens caps the output, thinking included. Hit it and the response is cut off. About 16,000 is a sensible default.

For Dana's summaries, the system prompt is where you put what stays the same every week: who reads the summary (a CEO with two minutes), the format (decisions, metric, risks, asks) and the rules (no patient details, say "not discussed" rather than guess). The user message carries this week's notes. Keeping the two apart makes the prompt easy to review and change.

Statelessness surprises people most. If Dana's steering summary needs last week's decisions, your code must put them in the request: there is no session on the server that remembers them. That's also why long conversations get more expensive every turn: each request resends everything before it.

The response is a list of blocks

Block types
Block type What it is
"text" The answer, in block.text
"thinking" Claude's reasoning. Claude Opus 5.5 thinks adaptively, so responses often start with one (text empty by default)
"tool_use" A request to call your tool (Module 7)

So response.content[0].text is fragile: content[0] may be a thinking block. Use:

answer = "".join(b.text for b in response.content if b.type == "text")
Your teammate's script uses response.content[0].text and worked fine on an older model. You switch it to Opus 5.5. What happens?

It usually crashes with an AttributeError, because the first block is now a thinking block, which has no .text. Nothing about the prompt changed; the response shape did. Filtering blocks by type == "text" works on every model, with or without thinking, and when tools are involved.

Check stop_reason

Stop reasons and what to do about each
stop_reason Meaning Do
"end_turn" Finished normally Use the answer
"max_tokens" Output truncated at your cap Raise max_tokens or ask for less
"tool_use" Wants a tool Run it, send the result (Module 7)
"refusal" Declined by safety systems Don't treat it as an answer

A truncated summary is the dangerous case: it reads like an answer and nothing raises. Wrap the reading in one function and use it everywhere. The snippet below scripts the offline simulator to return one normal response and one truncated one:

import anthropic
from anthropic import _sim  # the course's offline simulator; skip this line against the real API

client = anthropic.Anthropic()

def answer_text(response):
    if response.stop_reason == "max_tokens":
        raise RuntimeError("truncated: raise max_tokens or ask for less")
    if response.stop_reason == "refusal":
        raise RuntimeError("refused: don't treat this as an answer")
    return "".join(b.text for b in response.content if b.type == "text")

_sim.queue(_sim.message(_sim.thinking(), _sim.text("Steering summary: intake pilot on track.")))
_sim.queue(_sim.message(_sim.text("Steering summary: intake pil"), stop_reason="max_tokens"))
for attempt in (1, 2):
    r = client.messages.create(model="claude-opus-5-5", max_tokens=16000,
                               messages=[{"role": "user", "content": "Summarize the steering meeting."}])
    try:
        print([b.type for b in r.content], "->", answer_text(r))
    except RuntimeError as e:
        print([b.type for b in r.content], "->", e)

Tokens and cost

response.usage reports a call's input and output tokens. To know the input size before you send, count it with the model you'll use. Don't estimate with a characters-per-token constant. Token counts depend on the model's tokenizer: the newer tokenizers (Sonnet 5 and 5.5, Haiku 5.5) count roughly 30% more tokens than Sonnet 4.6 for the same text, and other vendors' tokenizers (such as tiktoken) undercount Claude tokens. A rule of thumb that was fine last year can be off by a third today.

Claude Opus 5.5 costs $4 per million input tokens and $20 per million output tokens. Output includes thinking: Opus 5.5 always thinks (at medium effort by default), those tokens are billed as output, and max_tokens has to leave room for them. For a 2,000-token prompt and 500 output tokens (say 350 thinking plus 150 of answer):

2,000 / 1,000,000 × $4  = $0.008   input (from count_tokens)
  500 / 1,000,000 × $20 = $0.010   output, thinking included
                  total = $0.018
import anthropic

client = anthropic.Anthropic()
meeting_notes = "Steering meeting, Mar 12. Pilot median intake 71h -> 22h. Sam: BAA signed Friday. " * 20

count = client.messages.count_tokens(
    model="claude-opus-5-5",  # count with the model you'll actually call
    system="You are a concise assistant for a forward deployed engineer.",
    messages=[{"role": "user", "content": meeting_notes}],
)
output_tokens = 500  # assumed: thinking + a short summary; measure response.usage on real calls
cost = count.input_tokens * 4 / 1_000_000 + output_tokens * 20 / 1_000_000
print(f"input {count.input_tokens} tokens -> ${cost:.4f} per summary on Opus 5.5")
print(f"at 50,000 calls a day: ${cost * 50_000 * 30:,.0f} a month")

Lower effort (output_config={"effort": "low"}) cuts the thinking part. Measure real usage on a sample before you quote a number.

At 50,000 calls a day that's real money. Know your unit economics. The calculator below compares models on the same request: try Dana's summary at 2,000 tokens in and 500 out.

Try itWhat one request costsSonnet 5.5: $2.00 in · $10.00 out per 1M
Input cost
$0.006
Output cost
$0.005
Per request
$0.011
Per month (30 d)
$33,000
Cost = input tokens × input price + output tokens × output price, per million. Output (thinking included) costs 5× input on these models, so a few hundred output tokens can outweigh thousands of input tokens. Start values are the ticket-summarizer example below.
Which costs more on Opus 5.5: 10,000 input tokens with 1,000 output tokens, or 2,000 input with 2,000 output?

The first. It's 10,000 × $4/M + 1,000 × $20/M = $0.04 + $0.02 = $0.06. The second is 2,000 × $4/M + 2,000 × $20/M = $0.008 + $0.04 = $0.048. Many people guess the second because output is 5x the input price, but 8,000 extra input tokens still outweigh 1,000 extra output tokens. Do the arithmetic rather than trust intuition.

Where Claude fits in an FDE's week

Most of your Claude calls in the first weeks aren't the product. They're tools: drafting a recap, extracting requirements from notes, categorizing a sample of tickets, proposing a schema mapping. Each one follows the same pattern from this lesson: a clear system prompt, a request you can afford, a reader that checks stop_reason, and a human reviewing anything that reaches the customer. Later modules build on this with structured outputs (Module 2), batching (Module 3), tools and retrieval (Module 7) and evals (Module 8).

Try it: the simulator behaves like the real SDK, errors included. Run the scratchpad, print response.content, then change the first message's role to "assistant" and read the error.

Cheat card

  1. response.content is a list of typed blocks; Opus 5.5 often starts with a thinking block, so filter for "text" instead of reading content[0].
  2. Check stop_reason before trusting output: max_tokens means truncated, refusal means no answer, tool_use means run a tool.
  3. Cost = tokens × price per million, input and output separately; output includes thinking. Opus 5.5 is $4 in / $20 out. Count input with count_tokens for the model you'll use.
if response.stop_reason != "end_turn": handle(response.stop_reason)
answer = "".join(b.text for b in response.content if b.type == "text")
cost = input_tokens * 4 / 1e6 + output_tokens * 20 / 1e6   # Opus 5.5

Interview line "I never read content[0].text. I check stop_reason, join the text blocks, and I know what a call costs because I counted its tokens with the model I'm shipping on."

main.py
Run your code to see output here. Ctrl/Cmd + Enter runs it.