Day 7, 30 minutes · beginner
Why it matters
A script that calls Claude costs money every time it runs, and it can fail for reasons that have nothing to do with your code: too many requests in a minute, a monthly cap, a busy API. If you do not plan for that, the first surprise is a bill or a script that stops on a Saturday.
Today you learn how the costs are counted, how to put a ceiling on them, and what the common errors mean. Then you put lessons 2 to 6 together in one small script for Linde: it reads a review, counts the tokens, streams a reply in the voice of Harbour Lane Tea Co, checks that the reply is complete, saves it and tells you what it cost. That script is what you take away from this course.
How you pay: tokens in, tokens out
You pay per token, with separate prices for input (what you send) and output (what Claude writes). Output costs more: for Claude Sonnet 5.5 on 4 December 2026, $2 per million input tokens and $10 per million output tokens. The pricing page has the current numbers. A few things that push the count up:
- The system prompt and the history count as input on every request. That is why lesson 5's chat got more expensive each turn.
- Thinking counts as output. The docs say thinking tokens are part of
max_tokensand are billed as output tokens. - Language and model change the count. The same text gives a different number of tokens on another model.
Every response has a usage field with the real numbers. Multiply them by the prices and you know what one request cost, as you did in lesson 4. Today's script prints it each time.
Counting before you send
The token counting endpoint tells you how many input tokens a request would use, without sending it to Claude. The docs say it is free to use, has its own rate limits, and gives an estimate: the real number can differ by a small amount. It is handy for checking a long input before you pay for it. Today's script prints the estimate first and the real count at the end, so you can compare.
Limits: spend and rate
The Claude API has two kinds of limits, both per organization:
- Spend limits: a maximum cost per calendar month. The usage tiers Start, Build and Scale each come with a monthly cap; the Custom tier has none and is arranged with Anthropic. New organizations may begin in an Evaluation tier with lower limits. Organizations move up automatically as they build history. You can also set your own lower limit, and you should: it is your safety net if a script runs in a loop.
- Rate limits: how much you may send per minute, measured in requests per minute, input tokens per minute and output tokens per minute, per model class. The docs note that a limit of 60 requests per minute can be enforced as one per second, so a quick burst can hit it.
Both are on the Console pages in today's steps.
The errors you will meet
When a request fails you get an HTTP status code (a number that says what went wrong) and an error type. The ones that matter most at the start:
| Code | Type | What it usually means |
|---|---|---|
| 400 | invalid_request_error |
something is wrong in your request, or you reached a spend limit you set yourself |
| 401 | authentication_error |
the key is wrong, revoked or expired |
| 402 | billing_error |
a problem with your billing or payment details |
| 403 | permission_error |
your key or role may not do this |
| 429 | rate_limit_error |
too many requests or tokens per minute, or your tier's monthly cap |
| 500 | api_error |
an unexpected problem on Anthropic's side |
| 529 | overloaded_error |
the API is very busy for everyone |
What to do about them:
- Let the SDK retry. By default it tries a failed request up to two more times for connection errors, timeouts, 408, 409, 429 and server errors (5xx). It waits as long as the
retry-afterheader says, or a short, growing pause. - Do not retry blindly after a 429. A rate limit response can carry a
retry-afterheader that says how long to wait. The monthly cap does not: that 429 has noretry-afterand keeps failing until the next month or a higher limit. - Read the message for a 400. It names the problem, and a spend limit you set yourself shows up here, not as a 429.
- Keep the request ID. Every error carries one. Support needs it to look at a request.
- Errors in a stream are not retried by the SDK, as you saw in lesson 6.
The script, piece by piece
The final script uses everything from this course:
- Lesson 2: the key comes from
.env, never from the code. - Lesson 3: one request to the Messages API with a model,
max_tokensand messages. - Lesson 4: the model you picked, in one place at the top, with its prices.
- Lesson 5: the system prompt, now in its own file
system.txtso Linde can change the tone without touching code. - Lesson 6: the reply streams in, and the script refuses to save it unless the stop reason is
end_turn. - Today: a token estimate first, readable errors, and the cost at the end.
The steps
- Set a spend limit in the Console.
- Look up your tier and rate limits.
- Create the two text files: the system prompt and a made-up review.
- Create and run the script, and read the reply it saved.
- Check your usage in the Console.
Follow the steps below.
Where to go next
You can now call Claude from your own code. Natural next steps are tools (letting Claude call functions you write) and agents. The lab page linked below explains how agents work. If you would like Claude to help you write code in your editor, see Claude Code 101.
Deeper dive
Today's actions
Ticks are not saved without an accountDo it in Claude API
Claude API
- Open the Spend limits page at
platform.claude.com/spending/spend-limits. Next to Monthly spend limit, click Adjust limit or Set limit, enter an amount such as 10 and save. - Open the Rate limits page at
platform.claude.com/spending/rate-limitsand note your usage tier and the limits per minute for the model you picked. - In your harbour-lane-replies folder, create
system.txtwith your system prompt from lesson 5 as plain text, or use this one.You write replies to customer reviews for Harbour Lane Tea Co, a small online tea shop run by Linde. Be warm and short: at most three sentences. Thank the customer for what they actually said. If they mention a problem, apologise once and say what happens next. Never promise discounts or refunds. End with: Linde, Harbour Lane Tea Co - Create
review.txtwith one made-up review, for example this one.Four stars. The jasmine green tea is fresh and fragrant, but one of the two tins arrived with a dent in the lid. - Create
reply_to_review.pywith this code. The prices are for Claude Sonnet 5.5 in US dollars per million tokens on 4 December 2026: check the pricing page and change them if you use another model.from pathlib import Path from dotenv import load_dotenv import anthropic load_dotenv() client = anthropic.Anthropic() MODEL = "claude-sonnet-5-5" PRICE_IN, PRICE_OUT = 2.00, 10.00 # per MTok SYSTEM = Path("system.txt").read_text(encoding="utf-8") review = Path("review.txt").read_text(encoding="utf-8") messages = [{"role": "user", "content": "Reply to this review:\n\n" + review}] count = client.messages.count_tokens(model=MODEL, system=SYSTEM, messages=messages) print("Input tokens:", count.input_tokens) try: with client.messages.stream( model=MODEL, max_tokens=1000, system=SYSTEM, messages=messages ) as stream: for text in stream.text_stream: print(text, end="", flush=True) message = stream.get_final_message() except anthropic.RateLimitError as e: raise SystemExit(f"\nLimit reached. Request ID: {e.request_id}") except anthropic.APIStatusError as e: raise SystemExit(f"\nError {e.status_code}: {e.type} {e.api_message}") except anthropic.APIConnectionError: raise SystemExit("\nNo connection.") print("\n---") if message.stop_reason != "end_turn": raise SystemExit(f"Not complete. stop_reason: {message.stop_reason}") reply = "".join(b.text for b in message.content if b.type == "text") Path("reply.txt").write_text(reply, encoding="utf-8") u = message.usage cost = u.input_tokens / 1e6 * PRICE_IN + u.output_tokens / 1e6 * PRICE_OUT print(f"Saved. Tokens in/out: {u.input_tokens}/{u.output_tokens}, about ${cost:.4f}") - With the virtual environment on, run
python reply_to_review.py. You see the token estimate, the reply as it streams, and the real token counts with the cost. Openreply.txtto see the saved reply. - For Node instead of Python: save this as
reply_to_review.mjsand runnode --env-file=.env reply_to_review.mjs.import { readFileSync, writeFileSync } from "node:fs"; import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); const MODEL = "claude-sonnet-5-5"; const PRICE_IN = 2.0, PRICE_OUT = 10.0; // dollars per million tokens: check the pricing page const system = readFileSync("system.txt", "utf8"); const review = readFileSync("review.txt", "utf8"); const messages = [{ role: "user", content: "Reply to this review:\n\n" + review }]; const count = await client.messages.countTokens({ model: MODEL, system, messages }); console.log("Input tokens (estimate):", count.input_tokens); let message; try { message = await client.messages .stream({ model: MODEL, max_tokens: 1000, system, messages }) .on("text", (text) => process.stdout.write(text)) .finalMessage(); } catch (err) { if (err instanceof Anthropic.APIError) { console.log("\nError:", err.status, err.type, err.apiMessage); process.exit(1); } throw err; } console.log("\n---"); if (message.stop_reason !== "end_turn") { console.log("Not complete. stop_reason:", message.stop_reason); process.exit(1); } const reply = message.content.filter((b) => b.type === "text").map((b) => b.text).join(""); writeFileSync("reply.txt", reply); const u = message.usage; const cost = (u.input_tokens / 1e6) * PRICE_IN + (u.output_tokens / 1e6) * PRICE_OUT; console.log(`Saved. Tokens in/out: ${u.input_tokens}/${u.output_tokens}, about $${cost.toFixed(4)}`); - Open the Usage page at
platform.claude.com/spending/api-usageand find today's requests. Put a new review in review.txt whenever Linde gets one and run the script again.
Note: A spend limit you set yourself stops requests with a 400 error once it is reached. The usage cap of your tier gives a 429 error that keeps failing until the next month or a higher limit.
Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.
Create a free account to save your progress
Free, and no payment details. Your ticks and finished lessons are kept, on every device.
Create a free account I already have an accountCreate a free account to save your progress. Sign in or sign up