16 min read
How to call an AI model API from your backend
In one sentence: Your backend asks a model with an HTTP request: its instructions, the whole conversation and a token limit, with a key that never leaves the server. The answer brings the text, why it stopped and the tokens you’ll be charged for.
What you will learn
- Explain why the API key lives on the server, and what happens if it reaches the browser.
- Read a Messages API request and its response (blocks, stop_reason and usage), and work out what it cost.
- Keep up a conversation with a stateless API, sending the whole of it with every question.
- Turn the API’s errors (429, 529, 400) and the model’s refusals into the response your customer should see.
Before you start, read: 00-introduction.md phase-6/08-rate-limiting.md phase-10/01-writing-tests.md
The problem
Section titled “The problem”Imagine Luis wants the assistant this very afternoon. He copies the call to the LLMLLM stands for Large Language Model.A program trained on a huge amount of text that, given some text, writes how it continues. Claude, GPT and Gemini are LLMs. Your backend uses one like any other API: it sends text and gets text back, and pays for what the model reads and what it writes.Go to definition from an example, pastes it into the JavaScript of the shop’s website, with the key inside, and it works: Carmen asks and the model answers.
The next day, the Console says the shop has spent all its credit. Someone opened DevTools, saw the key in the Network tab and used it for their own program. Everything that reaches the browser can be read by whoever uses it.
The fix is the usual one: the browser asks your backend, and your backend, with its key, asks the model. In this lesson you write that route, POST /v2/assistant, and see what travels, what comes back and what you pay for.
The analogy
Section titled “The analogy”The analogy
The shop hires a phone translation service and pays for it with its card. When a foreign customer asks something at the counter, Ana calls, gives the card number and reads out the whole conversation from the start: the service doesn’t remember earlier calls. It charges for every word it hears and every word it says.
Ana never writes the card number on a sign on the counter: whoever reads it can charge their own calls to the shop.
Where the analogy breaks down
- A call is charged by the minute. The API charges for the pieces of text it reads and writes, and writing costs five times more than reading.
- A translator who doesn’t know something says so. A model can write something false with the same confidence.
- A person ends up getting tired of a pushy customer. The API answers whoever has the key, at any hour and as many times as they ask: you set the limit.
How it really works
Section titled “How it really works”The key lives on the server
Section titled “The key lives on the server”This is how one of Carmen’s questions travels:
- ShopIs she a customer?
Does she have questions left? - Claude API → Shopthe text and the tokens it charges
- Shop → Carmen’s browserthe text, without the key
The key only leaves the server toward the API. Why not in the frontend:
- Everything that reaches the browser can be read: the code, the headers of every request in DevTools’ Network tab, what the page stores.
- Whoever has the key spends on your account, without your session, without your limits and without going through your backend.
- The SDK itself refuses: in a browser, it throws an error unless you pass it the
dangerouslyAllowBrowseroption.
In the shop, the key is ANTHROPIC_API_KEY, in .env, like the other secrets (Phase 6). It’s optional: without it, POST /v2/assistant answers 503 with assistant-not-configured, and the rest of the shop works the same.
Who can ask, and how many times
Section titled “Who can ask, and how many times”The shop pays for every question. That’s why, before it reaches the model:
- Only a customer with their session can ask. The new permission,
assistant:use, belongs only to thecustomerrole (Phase 6): without a session,401; with Fast Delivery’s key,403. - At most 20 questions per customer every 10 minutes, and 60 per IP, with the limiter from Phase 6 in Redis. The next one gets
429withRetry-After, without reaching the model. If Redis doesn’t answer, the limit closes:503.
A request: the model, the instructions, the conversation and a limit
Section titled “A request: the model, the instructions, the conversation and a limit”This is the request the shop sends to Claude’s Messages API, in src/assistant/conversation.ts:
// The longest an answer can be, in tokens (a token is a piece of a word). A short answer is a few// hundred; the rest leaves room for what the model thinks before answering, which counts too. If it// reaches the limit, the answer is cut (stop_reason: max_tokens).export const MAX_TOKENS = 2048;
// The request: the model, the token limit, the instructions (system), the effort and the whole// conversation, because the API doesn't remember anything from one request to the next. The API's// roles are called user and assistant, like ours. It carries no temperature, top_p or top_k: current// models reject them with a 400.export function modelRequest( messages: Message[], instructions: string, settings: Settings,): Anthropic.MessageCreateParamsNonStreaming { return { model: settings.model, max_tokens: MAX_TOKENS, system: instructions, output_config: { effort: settings.effort }, messages: messages.map((message) => ({ role: message.role, content: message.text })), };}model: which model answers. It comes fromMODEL, inconfig.ts: by default,claude-haiku-5-5.max_tokens: the longest the answer can be, 2048 Token (of a model)The piece of text a language model counts in: often a short word or part of a long one. Model APIs charge per token, and the limit on what a model can read at once is measured in tokens too.Go to definition, the pieces of words the API counts and charges in. If it reaches the limit, it’s cut.system: the System promptThe part of the prompt written by whoever builds the application, not by whoever uses it: who the assistant is, what it may and may not do. In the shop it lives in a file, versioned like the code.Go to definition, what the model reads before the conversation: who it is, what it can do and how to answer.output_config.effort: how much it thinks before answering. What it thinks is paid for too, and the shop asks forlow, which takes less time and costs less.messages: the conversation, with the API’s roles,userandassistant.
It carries no temperature or anything like it: current models reject it with a 400.
The instructions live in their own file, versioned like the code:
You are the assistant of Ana and Luis's online shop, which sells clothes and things for the home and for gifts. You talk with customers who have signed in to the shop.
How you answer:
- In the language the customer writes to you in: if they write in Spanish, in Spanish; if in English, in English.- In a warm, friendly tone, and in a few sentences: it's a chat, not an email.- In plain text, without Markdown (no headings, no bold, no tables): the shop shows the text as it is.
What you don't do:
- You don't make up products, prices, stock, orders, delivery times or shop policies (shipping, returns, payments). You can't look at the catalogue or the orders yet: if they ask about them, say so plainly and suggest checking on the shop's website.- You don't talk about things that have nothing to do with the shop: you say so kindly and come back to it.Look at the last part: the model can’t see the catalog or the orders yet, and it’s told not to make them up.
The answer: blocks, why it stopped and what it costs
Section titled “The answer: blocks, why it stopped and what it costs”This is what the shop’s fake model (below) answered to the curl in “Try it”: the fields the shop uses, with made-up text and tokens. Claude’s may bring a few more:
{ "id": "msg_fake_2", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": [ { "type": "thinking", "thinking": "", "signature": "fake-signature-2" }, { "type": "text", "text": "I'm the fake model: I understand nothing, I just repeat your last question. It was: \"Hi, what do you sell?\"." } ], "stop_reason": "end_turn", "stop_sequence": null, "stop_details": null, "usage": { "input_tokens": 120, "output_tokens": 30, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0 }}contentis a list of blocks. Thetextone is the answer. Before it there may be athinkingone, with empty text and a signature (signature): what the model thought, which it doesn’t show but does charge for.stop_reasonsays why it stopped:end_turn, it has finished;max_tokens, it ran out of room;refusal, it refused; and, in lesson 3,tool_use.usagebrings the tokens that are charged:input_tokens, what it read, andoutput_tokens, what it wrote, thinking included.
The shop keeps what’s useful to Carmen: the text of the text blocks, the two numbers in usage and, if the model refused, a fixed sentence.
// What the shop answers the customer (assistantAnswerSchema, in schemas.ts).export interface Answer { text: string; refused: boolean; usage: { input: number; output: number };}
// If the model refuses to answer (stop_reason: refusal), the shop doesn't show what it might have// written up to there: it answers this sentence, always the same one.export const REFUSAL_TEXT = "Sorry, I can't help with that. Can I help with something else from the shop?";
// The answer arrives as a list of blocks: text, what the model thinks (thinking), tools (lesson 3)…// The customer gets only the text. And in usage, the tokens that are charged.export function modelAnswer(message: Anthropic.Message): Answer { const usage = { input: message.usage.input_tokens, output: message.usage.output_tokens }; if (message.stop_reason === 'refusal') return { text: REFUSAL_TEXT, refused: true, usage }; const text = message.content.map((block) => (block.type === 'text' ? block.text : '')).join(''); return { text, refused: false, usage };}Tokens: what’s counted and what’s paid for
Section titled “Tokens: what’s counted and what’s paid for”Imagine a Prompt (for a model)The text sent to a language model for it to answer: the instructions, the conversation and whatever it needs to reply.Go to definition of 500 tokens, between instructions and conversation, and an answer of 150, thinking included. With Claude Haiku 5.5’s prices on November 21, 2026:
| Tokens | Price per million | Cost | |
|---|---|---|---|
| Input | 500 | $0.10 | $0.00005 |
| Output | 150 | $0.50 | $0.000075 |
| Total | $0.000125 |
About eight thousand questions like that per dollar. Besides the model, two things move the bill:
- Output costs five times more, and what the model thinks counts as output.
- Input grows with the conversation, because it travels whole with every question (below).
There’s also a maximum: the Context windowHow many tokens a model can read at once: the instructions, the conversation and what the tools return, all together. What doesn't fit, it doesn't see.Go to definition, the most a model can read in one request. Claude Haiku 5.5’s is one million tokens, and the shop stays very far from it on purpose (below).
The API remembers nothing
Section titled “The API remembers nothing”Between one request and the next, the API forgets everything: it’s StatelessSaid of a server that remembers nothing from one request to the next. Each request carries everything needed to understand it, such as who you are or which page you want, and that’s why any copy of the server can handle it. What it does keep is the data, such as the orders.Go to definition, like the REST API from Phase 4. For the model to know what you were talking about, every request carries the whole conversation.
The shop doesn’t store conversations either: the frontend sends the latest messages each time, and the Zod schema limits them to 20, of 2,000 characters each. Storing them would add a table and decisions that aren’t about code: they’re Carmen’s data.
What does change is the price: in a ten-question conversation, the first question is paid for ten times. Lesson 7 makes it cheaper with the cache.
The SDK: the same request, with types and retries
Section titled “The SDK: the same request, with types and retries”The shop doesn’t write the request by hand: it uses Anthropic’s official SDKSDK stands for Software Development Kit.A package a company provides to use its API from a programming language: named functions and types instead of hand-written HTTP requests, with retries and errors already handled.Go to definition for TypeScript, @anthropic-ai/sdk 1.8.0, in src/assistant/client.ts:
// Without ANTHROPIC_API_KEY there's no client, and the route answers 503 (route.ts).// - maxRetries: the SDK repeats only what's passing (a 429, a 529 or any 5xx, a network cut),// waiting what the retry-after header says or, if there isn't one, a bit longer each time. With 2,// at most three attempts.// - timeout: what each attempt waits, in milliseconds. Without it, 10 minutes: too long for someone// waiting for the answer in front of the screen.// - The API's address isn't set: the SDK reads ANTHROPIC_BASE_URL, and without it uses// https://api.anthropic.com. The tests point it at their fake model (test/fake-model.ts).// How long a whole answer lasts, with its attempts and its waits, is cut by something else: each// call's signal (below), with ASSISTANT_TIMEOUT_MS (config.ts).export const client = config.ANTHROPIC_API_KEY === undefined ? undefined : new Anthropic({ apiKey: config.ANTHROPIC_API_KEY, maxRetries: config.MODEL_RETRIES, timeout: config.MODEL_TIMEOUT_MS, });- No key, no client, and the route answers
503. maxRetries: the SDK only repeats what’s temporary (429,529, another5xx, a network cut), waiting as long asretry-aftersays or, if it doesn’t say, with an Exponential backoffA way of retrying something that failed by waiting longer each time: one second, then two, then four. It gives the problem time to clear and avoids piling retries onto a service that is already struggling.Go to definition like the one in Phase 9. With 2, at most three attempts.timeout: how long each attempt waits, 15 seconds. Without it, it would be 10 minutes.- The API’s address isn’t there: the SDK reads
ANTHROPIC_BASE_URL, and without it uses Anthropic’s. The tests change it (below).
client.messages.create(…) is the POST /v1/messages from above, with types and a class for each error.
When the API fails: what’s temporary and what’s the shop’s fault
Section titled “When the API fails: what’s temporary and what’s the shop’s fault”In Phase 6 we promised you model APIs that answer 429. Here it is, with a twist: that 429 isn’t Carmen’s, but the shop’s account’s, which has asked too much. Passed on as it is, Carmen would think it was her fault.
| The API answers | What it means | The shop answers |
|---|---|---|
429 |
The shop’s account has asked too much | 503 with Retry-After |
529 or another 5xx |
The API is overloaded, or has failed | 503 with Retry-After |
| Nothing in time, or the network cuts out | The model isn’t answering | 503 with Retry-After |
400, 401, 404 |
The shop’s request is wrong: a parameter, the key, the model | 500, and the reason to the log |
The decision is in src/assistant/errors.ts:
// undefined: it isn't an API error (a programming mistake in the shop); let it go on its way to// app.onError, like any other.export function modelFailure(error: unknown): Failure | undefined { // A network cut, or an answer that doesn't arrive in time (APIConnectionTimeoutError is a kind of // APIConnectionError). It goes first: in the SDK, APIConnectionError is also an APIError. if (error instanceof Anthropic.APIConnectionError) { return { status: 503, retryAfter: DEFAULT_WAIT, detail: 'The model is not answering' }; } // The call was cancelled (APIUserAbortError, which is also an APIError). In the shop only the // assistant's time limit cancels it (ASSISTANT_TIMEOUT_MS, in config.ts): the model didn't finish // in time. if (error instanceof Anthropic.APIUserAbortError) { return { status: 503, retryAfter: DEFAULT_WAIT, detail: 'The model is not answering' }; } // 429: the shop's account has made too many requests (or, according to the docs, reached its tier's // spend cap; the spend limit you set in the Console gives a 400, which ends up as a 500 here). The // limit is the shop's, not the customer's: that's why the customer gets a 503, not a 429. if (error instanceof Anthropic.RateLimitError) { return { status: 503, retryAfter: waitFrom(error.headers), detail: 'The model is getting too many requests from the shop', }; } // 529 (overloaded, OverloadedError) and any other 5xx: a problem of the API's, which usually goes // away on its own. if (error instanceof Anthropic.InternalServerError) { return { status: 503, retryAfter: waitFrom(error.headers), detail: 'The model is overloaded' }; } // Any other error response from the API: 400 (a badly made request), 401 (the key isn't valid), // 403, 404 (a model that doesn't exist)… if (error instanceof Anthropic.APIError) return { status: 500 }; return undefined;}- It decides by the error’s class (
instanceof), never by the message’s text, which can change. - The order matters:
APIConnectionErrorandRateLimitErrorare alsoAPIError, so they go before the last check. - A
500doesn’t tell Carmen what the API said: that goes to the log, as in Phase 4.
According to the documentation, the spend limit isn’t a 429: yours gives a 400, and the shop, a 500; your tier’s cap, a 429 without retry-after. We haven’t checked it.
The time limit, and the customer who leaves
Section titled “The time limit, and the customer who leaves”Three 15-second attempts and the waits between them add up to 46.5 seconds. But if the API asks for two minutes in retry-after, the SDK would wait all of them. That’s why the whole answer has its own limit, 50 seconds (ASSISTANT_TIMEOUT_MS), below the 60 that nginx waits for the API (Phase 8): that way the answer is the shop’s 503, not an nginx 504.
// The time limit for the whole answer (config.ts): when it's up, this signal cancels the call to// the model, also while the SDK waits to repeat it.const deadline = AbortSignal.timeout(config.ASSISTANT_TIMEOUT_MS);// And the signal of the customer's request, c.req.raw.signal: @hono/node-server aborts it if the// connection closes before the response has gone out (the customer closes the tab, Ctrl + C in// curl). The call to the model gets both together (AbortSignal.any), and the first one to fire// cancels it: that way the shop doesn't keep waiting, and paying, for an answer nobody will read.const signal = AbortSignal.any([deadline, c.req.raw.signal]);AbortSignal.timeoutcreates a signal that fires at 50 seconds and cancels the call to the model, also while the SDK waits to repeat it.c.req.raw.signalis the signal of Carmen’s request: it fires if she closes the tab before the answer.AbortSignal.anyjoins the two and cancels with the first one to fire: the shop doesn’t keep waiting for an answer nobody is going to read.
A refusal isn’t an error
Section titled “A refusal isn’t an error”Sometimes the model refuses to answer: the API responds 200, with stop_reason: "refusal" and the category of the reason in stop_details. Carmen gets the shop’s fixed sentence, with refused: true, and the log gets the message’s id and the category, never the conversation.
The tests don’t call the model
Section titled “The tests don’t call the model”A test that called the real model would cost money, need the key in CI and answer differently every time. The tests use a fake model, test/fake-model.ts: a small HTTP server that speaks the part of the Messages API the shop uses and answers whatever each test asks for, a text, a 429 or a silence. The SDK reaches it because ANTHROPIC_BASE_URL points at its address: it’s a Test doubleA fake piece that takes the place of a real one during a test, like a “mail sender” that only writes down what it was asked to send instead of sending it. It avoids depending on slow, paid or unpredictable services.Go to definition from Phase 10.
You can run it too, for free: docker compose --profile practice up -d fake-model (with SCENARIO=429, 529 or slow in front); put ANTHROPIC_BASE_URL=http://fake-model:4100 and any key in your .env, and restart the shop. To go back to the real one, delete that line.
Another option: a model on your computer
Section titled “Another option: a model on your computer”Ollama serves open models on your computer, with its own API: you don’t pay per token, but in memory and speed. The course uses a paid API because that’s what you’ll find in almost any company.
Try it
Section titled “Try it”The goal: ask a model a question, by hand and through the shop; work out what it cost; check that the API remembers nothing, and see what Carmen gets when the API says 429.
The shop’s answers are from its fake model; Claude’s we don’t copy, because they change every time.
Before the first question, your spend limit. If you don’t have a key, follow the steps in the introduction, in that order: the limit before the key. If you already have one, check in the Console that the limit is still there.
A question by hand
Section titled “A question by hand”First, without the SDK or the shop: the request the shop will make, with curl and some short instructions. The answer is saved in a variable, so you can read it twice and pay for it once:
1. A question, with curl
cd ~/backend-course/phase-3/shop-apiexport $(grep '^ANTHROPIC_API_KEY=' .env)ANSWER=$(curl -s https://api.anthropic.com/v1/messages \-H "x-api-key: $ANTHROPIC_API_KEY" -H 'anthropic-version: 2026-10-21' \--json '{"model":"claude-haiku-5-5","max_tokens":2048,"output_config":{"effort":"low"}, "system":"You are the assistant of the online shop of Ana and Luis. Answer in a few sentences.", "messages":[{"role":"user","content":"Hi, what do you sell?"}]}')echo "$ANSWER" | jq .It has the shape of the one above: look at the text, in content; at "stop_reason": "end_turn", and at usage, with real tokens.
If you get "type": "error", read its error.type: authentication_error is the key (repeat the export); invalid_request_error, something in the request, with the field in the message; not_found_error, the model’s name.
2. What it cost
echo "$ANSWER" | jq '.usage | (.input_tokens * 0.10 + .output_tokens * 0.50) / 1000000'The input tokens times their price, plus the output ones times theirs, divided by a million: dollars. jq reads the saved answer, without calling again. With the fake model’s (120 and 30) it writes 2.7e-05: $0.000027.
The same question, through the shop
Section titled “The same question, through the shop”Put your project on step 47, as in the introduction:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/47-model.tar.gztar -xzf 47-model.tar.gzcp -R 47-model/. shop-api/cd shop-apinpm installdocker compose up -d --build --waitnpm install brings @anthropic-ai/sdk. Save the API’s port in API, as in Phase 10, and sign Carmen in:
API=$(docker compose port api 3000)curl -s -o /dev/null -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' $API/v2/session3. Carmen asks
curl -s -b carmen.txt --json '{"messages":[{"role":"user","text":"Hi, what do you sell?"}]}' $API/v2/assistant | jq .What you will see:
{"text": "I'm the fake model: I understand nothing, I just repeat your last question. It was: \"Hi, what do you sell?\".","refused": false,"usage": { "input": 120, "output": 30}}It’s the shop’s answer: text, refused and usage, without blocks or signatures. This one is the fake model’s, which always says 120 and 30; in your usage.input, many more than in your curl: the whole instructions go along.
With 503 and assistant-not-configured, the API is missing your key: check your .env and repeat docker compose up -d --wait. With 401, sign in again.
The API remembers nothing: check it
Section titled “The API remembers nothing: check it”Carmen asks something that depends on an earlier message. First, sending only the last question:
4. Only the last question
curl -s -b carmen.txt --json '{"messages":[{"role":"user","text":"Who was the gift for?"}]}' $API/v2/assistant | jq .Look in text for the model not knowing which gift you mean: nobody has told it in this request.
Now, the whole conversation. The second message is what the assistant answered: on the website, the frontend sends what it showed.
5. With the whole conversation
curl -s -b carmen.txt --json '{"messages":[{"role":"user","text":"Hi, I am Carmen. I am looking for a gift for my brother."},{"role":"assistant","text":"Hi, Carmen! What does your brother like?"},{"role":"user","text":"Who was the gift for?"}]}' $API/v2/assistant | jq .Now text should talk about your brother: it has read it in this request. Compare usage.input with test 4’s: what was said before is paid for again.
A 429, with the fake model
Section titled “A 429, with the fake model”A real 429 would mean using up your limits. The fake model answers one when asked to: run the tests with “429” in their name.
6. The two 429s
node --env-file=test/.env --test --test-name-pattern=429 test/assistant.test.tsWhat you will see:
✔ a 429 from the API: a 503 for the customer, with the Retry-After the API gave (72.921789ms)✔ a customer's 21st question in 10 minutes: 429 with Retry-After, and the model never gets it (73.056286ms)ℹ tests 2ℹ suites 0ℹ pass 2ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 1720.073294--test-name-pattern runs only the tests whose name contains it. There are two:
- “a 429 from the API”: the fake model answers
429withretry-after: 17, and Carmen gets503withRetry-After: 17. - “a customer’s 21st question in 10 minutes”: Carmen goes past her limit and gets
429, which this time is hers, without the question reaching the model.
They spend nothing, and they need PostgreSQL with shop_test, as in the introduction. If you get ECONNREFUSED, PostgreSQL isn’t running.
This is the first one:
test('a 429 from the API: a 503 for the customer, with the Retry-After the API gave', async () => { const warning = mock.method(log, 'warn', () => {}); try { model.script(rateLimited(17)); const res = await ask(hello); assert.equal(res.status, 503); assert.equal(res.headers.get('retry-after'), '17'); assert.match(res.headers.get('content-type')!, /^application\/problem\+json/); const problem = await res.clone().json(); assert.equal(problem.type, 'https://shop.example/problems/assistant-not-available'); assert.match(problem.detail, /too many requests.*17 seconds/); await matchesContract(res, 'post', '/assistant'); assert.equal(warning.mock.callCount(), 1); } finally { warning.mock.restore(); }});model.script(…) tells the fake model what it will answer to the next request. mock.method(log, 'warn', …) silences the log’s warning and counts how many times it’s written, as in Phase 10.
Challenge: in errors.ts, move the last check, the APIError one, to the start of modelFailure, and run test 6’s tests again. Which one turns red, and why?Show answer
The first one, “a 429 from the API”: it expects 503 and gets 500, because RateLimitError is also an APIError and the check at the top takes it as a failure of the shop’s. The second one stays green: Carmen’s limit comes before the model. Put the file back as it was with cp ../47-model/src/assistant/errors.ts src/assistant/.
On your server
Section titled “On your server”Step 47 deploys as always: with no key on the server, the assistant answers 503 and nothing else changes. To have it there, create a key in the Console just for the server, with its own spend limit: if it leaks, you delete it without touching your computer’s. Paste it into your server’s .env, in /opt/shop:
# The shop's assistant (Phase 11): empty, the shop works the same and POST /v2/assistant answers# 503. To have it on your server, paste your Claude API key here (better one just for the server,# with its own spend limit in the Console).ANTHROPIC_API_KEY=Do it before deploying, so the API’s copies start with it.
You have already seen it
Section titled “You have already seen it”- The help chats on many websites, with their “How can I help you?”: behind them there’s a route like this one, with the company’s key.
- The “too many requests, try again later” of some AI apps: a
429or a529, translated by the app.
Common mistakes
Section titled “Common mistakes”- Putting the key in the frontend, or in the code and in Git. Whoever reads it spends on your account.
- Using the API without a spend limit, or a route without a question limit. A forgotten loop spends without stopping.
- Passing the API’s
429on to your customer. The limit is your account’s, not theirs: for them,503. - Looking at the error’s text instead of its class. The text changes; the class doesn’t.
- Forgetting that the conversation travels whole. A long conversation pays for each message many times.
- Trusting what the model says about your shop. It only knows what you give it.
Summary
Section titled “Summary”- The key lives on the server: the browser asks your backend, and your backend asks the model.
- A request carries the model, the instructions (
system), the conversation (messages) and a limit (max_tokens); the answer, blocks (content), why it stopped (stop_reason) and the tokens (usage). - You pay for the tokens it reads and the ones it writes, which cost five times more, and the whole conversation travels with every question.
- What’s temporary (
429,529, a cut) is a503withRetry-Afterfor your customer; a badly made request, a500and the reason to the log; a refusal, a200with a fixed sentence. - The tests talk to a fake model, which
ANTHROPIC_BASE_URLpoints at.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Messages API, in Claude’s documentation: every field of the request and the response.
- Errors: each code and which ones are retried.
- Rate limits: the per-minute limits, the spend limits and their headers.
- Pricing: what each model costs.
- The TypeScript SDK, Anthropic’s: retries, timeouts and errors.