AI Engineering
LLM APIs and Prompting
A model call is an HTTP request: text goes in as tokens, text comes out as tokens, and you pay for both. This page covers the request, prompts that work, structured output, streaming, cost, and the failures you must handle, using a help assistant for a bank service. No model was called for this page: there is no API key on the machine that built it. The Python files that need no model were run on Python 3.9 against FakeModel, a stub with scripted replies, and their output is pasted from those runs. The real API calls (Anthropic Python SDK, Messages API) are marked "Not run for this page"; they were only checked for parameter names against anthropic 0.125 with a mock transport.
One model call
Part 1 of 5 · what goes in, what comes back
A call is stateless
The model keeps nothing between requests. Everything it should know must be in the request you send.
Not run for this page (needs an API key).
Tokens and the context window
A token is a piece of a word. Limits, speed and price are all counted in tokens, never in characters or requests.
| Fact | Rule of thumb (approximate, check the docs) |
|---|---|
| Size of a token | About 4 characters or 0.75 words of English. Code, JSON and other languages use more. |
| Context window | Hundreds of thousands to 1M tokens on current large models |
| Input over the window | A 400 error, before any generation |
| Tokenizer | Differs per model: count with the provider's counter, see token counting |
| Long input | Costs more, answers slower, and details in the middle get less attention |
Anatomy of a request
| Field | What it is | Note |
|---|---|---|
model | Which model answers | Pin the exact id in config |
system | Standing instructions: role, rules, format | Yours, not the user's. Top-level field here; a first message with role system in OpenAI-style chat APIs |
messages | The conversation, a list of {role, content} | Roles user and assistant; the first is user |
max_tokens | Hard cap on output tokens | Required. The model is cut off at it, it does not plan for it |
stop_sequences | Strings that end the reply | Optional |
output_config | effort and a JSON format | See effort and structured output |
The response is JSON too. content is a list of typed blocks, so read the ones with type == "text".
| Response field | Use |
|---|---|
content | The reply blocks |
stop_reason | Why it stopped: check it before using the text |
usage | input_tokens, output_tokens: what you are billed for |
id, request id | Log them; support asks for them |
Security: user text goes in messages, never pasted into system. Treat the reply as untrusted input to your code.
Temperature and effort
The model produces a probability for every next token and samples one. Temperature controls how adventurous that pick is.
| Setting | Effect | Use for |
|---|---|---|
| Temperature 0 | Nearly always the most likely token. Still not guaranteed identical between runs | Extraction, classification |
| Temperature near 1 | More varied wording | Drafts, brainstorming |
effort low to max | How much the model reasons before answering. Reasoning tokens are billed as output | Low for routing, high for hard analysis |
Check the docs: the current Claude models used on this page reject temperature, top_p and top_k with a 400. You steer them with the prompt and output_config={"effort": "low"}. Many other APIs still take a temperature. Either way, never build on "same input, same output".
Stop reason
A 200 response is not a finished answer. The stop reason says which of the two you got.
end_turn is a complete answer.max_tokens: see truncation.tool_use: the model asks your code to run a function. That loop is in agents-tool-use.html.refusal: the model declined. Show a neutral message; do not retry the same request in a loop.
The stub: FakeModel
One model call · a stub, not a model
FakeModel is a stub with scripted replies: each call returns the next string you gave it, or raises the next error. It lets the client logic on this page run without a model. Its token counts are a 4-characters-per-token estimate.
Multi-turn: you resend the history
A chat is the client appending to a list and sending the whole list every turn. Input tokens grow with every turn, so long chats get slower and dearer.
Run against the stub. The replies are scripted; the point is the growing input.
When history gets long: keep the system prompt and the last few turns, and replace the older turns with a short summary. Store the history yourself (database, session store), keyed by conversation id.
Prompts and structured output
Part 2 of 5 · getting the answer you can use
The four parts of a prompt
Write the prompt as you would brief a capable new colleague who knows nothing about your bank: the task and why, the material, an example, the output shape.
- Tags such as
<article>separate your instructions from pasted data. - One or two examples fix the format better than a paragraph of rules. Vary them, or the model copies them.
- Give the model a way out ("not_in_article"), or it will invent an answer.
Where the article comes from: picking the right help article for a question is retrieval, covered in rag.html.
Bad prompt, better prompt
| Bad | Better | Why |
|---|---|---|
| "Reply to this customer." | "Draft an email reply, polite, at most two sentences, for a customer whose transfer is late." | States audience, length and tone |
| "Answer the question." | "Answer only from the article in the tags. If it is not there, say so." | Limits the source, allows "I do not know" |
| "Return JSON." | "Return one JSON object with keys answer and reply. No other text." plus an example | Names the keys, shows the shape |
| "Do NOT be rude!!!" | "Write in a calm, friendly tone." | Say what to do, not what to avoid |
| "Classify it." | "Pick one of: balance, transfer_status, card_block, other." | A closed list can be validated |
| Question first, 20 pages after | Documents first, question at the end | The question is read with the material fresh |
Process: a prompt is code. Keep it in version control and change it against a test set, see llm-evaluation.html.
Structured output
When code reads the reply, ask for JSON that matches a schema. With a schema in the request the API constrains the output to it. Not run for this page (needs an API key).
| Level | You get | Still check |
|---|---|---|
| "Return JSON" in the prompt | Usually JSON, sometimes with prose around it | Everything |
| Schema in the request | JSON that matches the schema | Stop reason, and whether the values are true |
Limit: a schema guarantees shape, not truth. "account_id": "ACC-9999" is valid JSON for an account that does not exist.
Validate, repair, retry
Without schema enforcement, or for rules a schema cannot express, validate in code and send the error back. Cap the attempts.
Run against the stub, scripted to fail twice. A real model usually needs fewer repairs.
Streaming and cost
Part 3 of 5 · time and money
Streaming
The model writes token by token. Streaming sends each piece as a server-sent event, so the user reads the first words while the rest is still being written.
Not run for this page (needs an API key).
Run against the stub, whose delays are time.sleep calls, to show the two numbers that matter.
| Metric | Meaning | Matters for |
|---|---|---|
| Time to first token | Request sent to first text | How fast a chat feels |
| Tokens per second | Speed after that | Long answers |
| Total time | Grows with output length | Batch jobs, JSON you must parse whole |
- Streaming does not make the model faster. It removes the blank wait, and it avoids HTTP timeouts on long replies.
- A stream can fail halfway: show partial text as partial, and validate only the final message.
Token counting
Before a call, ask the provider's counting endpoint. After a call, read usage. A 4-characters estimate is for capacity planning only. Not run for this page (needs an API key).
Trap: a tokenizer library made for another vendor's models gives the wrong count for this one.
Cost arithmetic
Streaming and cost · invented prices
Cost = input tokens × input price + output tokens × output price. Output tokens usually cost several times more than input tokens. The prices below are invented round numbers.
- A fraction of a cent per call becomes thousands of dollars a month at volume. Do this sum before you ship.
- The 10-turn chat costs far more than ten single calls, because each turn resends the history.
- Levers, in order: shorter prompts, capped output, caching, a smaller model.
Prompt caching in brief
If the start of a request is byte-for-byte the same as a recent one, the provider can reuse its work on that prefix and bill it at a fraction of the input price.
Not run for this page (needs an API key).
| Point | Detail (approximate, check the docs) |
|---|---|
| Price | Read about 0.1× input price, write about 1.25× |
| Lifetime | About 5 minutes by default, refreshed on each hit |
| Minimum size | Short prefixes are not cached; the floor depends on the model |
| Order | Stable text first (rules, articles), changing text last (the question) |
| Silent miss | A timestamp or request id in the system prompt |
| Proof | usage.cache_read_input_tokens above zero on the second call |
Related: caching whole answers, and rate limits in production, are in serving-ai-features.html.
Failures
Part 4 of 5 · errors, cut-off replies, wrong answers
Errors: which to retry
| Status | Meaning | Do |
|---|---|---|
| 400 | Bad request, or prompt too long | Fix the request |
| 401, 403 | Bad key, not allowed | Fix config, alert |
| 404 | Unknown model id | Fix config |
| 429 | Rate limit (requests or tokens per minute) | Wait retry-after, then retry |
| 500, 529 | Server error, overloaded | Back off and retry |
| Timeout, connection reset | No answer | Retry, within a total budget |
SDK defaults (check the docs): the Anthropic SDK already retries connection errors, 408, 409, 429 and 5xx twice with backoff, and its timeout is 10 minutes. Set both on purpose: Anthropic(timeout=20.0, max_retries=3).
Backoff with jitter
Double the ceiling on each attempt, cap it, and wait a random time below it. Without the random part, every client that failed together retries together.
Retries and idempotency
Generating text changes nothing, so retrying a model call is safe. What you do with the reply may not be.
| Risk | Guard |
|---|---|
| The call timed out on your side but finished on theirs: you pay twice | A timeout long enough for the output you asked for; a retry cap |
| The retry gives a different answer | Store the first accepted reply under your request id and reuse it |
| The reply triggers an action (send the email, block the card) and the whole job is retried | An idempotency key on the action, not on the model call |
| Retries at every layer multiply (3 × 3 × 3) | Retry in one layer only, with a total time budget |
Truncation
When the output reaches max_tokens the reply simply ends, mid-sentence or mid-JSON, with HTTP 200.
Run against the stub, which cuts its scripted reply at max_tokens the way an API would.
Sizing: set max_tokens well above the longest good answer, and ask for brevity in the prompt. On models that reason first, the reasoning tokens count toward the cap too.
Hallucination
The model writes the most plausible continuation. When it lacks the fact, plausible and true come apart, and the tone stays just as confident.
Run against the stub. The second scripted reply quotes a sentence the article does not contain.
| Cause | Reduce it by |
|---|---|
| The fact is not in the prompt | Put the source in the prompt: rag.html |
| Live data (a balance, a transfer status) | Fetch it with a tool, never ask the model: agents-tool-use.html |
| No way to decline | Allow "I do not know" and reward it in examples |
| Free-form answers | Closed lists and schemas, validated in code |
| Nobody measures it | A test set with known answers: llm-evaluation.html |
Rule for a bank: the model may draft and explain. Numbers and decisions come from your systems.
Shipping it
Part 5 of 5 · model choice, a client wrapper, revision
Choosing a model
Shipping it · prices approximate, check the docs
Providers sell tiers. Start with the most capable one to learn what "good" looks like, then move down while your test set still passes.
| Tier (Claude id) | Capability | Latency | Price per 1M tokens, in / out | Bank assistant use |
|---|---|---|---|---|
Large (claude-opus-5-5) | Highest | Slowest | About $4 / $20 | Drafting a reply to a complex complaint |
Medium (claude-sonnet-5-5) | High | Middle | About $2 / $10 | Answering from help articles |
Small (claude-haiku-5-5) | Enough for narrow tasks | Fastest | About $0.10 / $0.50 | Intent classification, routing |
- Judge cost per solved task, not per call: a cheap model that needs two repairs can cost more.
- A common shape: the small model routes, a larger one answers the hard cases.
- Model ids, prices and limits change. Keep the id in config and re-run the test set on every change.
A thin client wrapper
Put every model call behind one small class, so the timeout, retry policy, logs and cost live in one place and the rest of the service stays testable.
Run against the stub: one call that succeeds on the third attempt, one that must not be retried, one that runs out of attempts. Sleeps are skipped in the demo and the price is invented.
Log per call: request id, model, attempt, stop reason, tokens in and out, latency, cost. Do not log full prompts where they hold customer data.
The same with the SDK
The SDK brings the timeout and the retries; you add logging and the stop-reason check. Not run for this page (needs an API key).
Cheat sheet
| I need to | Do this |
|---|---|
| Keep a conversation | Resend the history; trim or summarise old turns |
| Set standing rules | System prompt; user text stays in messages |
| Get a usable answer | Task, context, example, format; question last |
| Parse the reply in code | Schema in the request, then validate |
| Make a chat feel fast | Stream; watch time to first token |
| Estimate the bill | Tokens × price, input and output apart |
| Cut cost of a long fixed prompt | Cache the prefix; stable text first |
| Handle 429 and 5xx | Backoff with jitter, honour retry-after, cap attempts |
| Handle 400, 401, 404 | Do not retry; fix and alert |
| Avoid half answers | Check stop reason on every reply |
| Avoid made-up facts | Sources in, quote out, check in code |
| Pick a model | Largest first, then down while tests pass |
Interview questions
| Question | Answer |
|---|---|
| How does a chat model remember the conversation? | It does not. The client resends the history each turn, so input tokens grow with every turn. |
| What is the context window? | The token budget shared by everything sent and everything generated in one call. Input over it is rejected. |
| System prompt or user message? | System for your standing rules, messages for user text. Mixing them invites prompt injection. |
| Is temperature 0 deterministic? | No. It is the most repeatable setting, but identical output is not guaranteed, and some models do not accept the parameter. |
| The API returned 200. Can you use the reply? | Only after checking the stop reason: it may be cut off at max_tokens or a refusal. |
| How do you get reliable JSON? | A schema in the request where the API supports it, validation in code always, a bounded repair loop that sends the error back. |
| Why stream? | Lower time to first token and no timeout on long replies. Total time is the same. |
| Which errors do you retry? | 429, 5xx, timeouts and connection errors, with exponential backoff, jitter, retry-after and a cap. Not other 4xx. |
| Why jitter? | Without it, clients that failed together retry together and overload the service again. |
| How do you cut the cost of a feature? | Measure tokens per call first. Then shorter prompts, capped output, prefix caching, and a smaller model for easy cases. |
| How do you reduce hallucination? | Give sources, allow "I do not know", require quotes and verify them, take live data from systems, and measure on a test set. |
| How do you test code that calls a model? | Hide the call behind a small client and inject a stub with scripted replies and errors. Test output quality separately, with evals. |
Next: embeddings-vector-search.html. Back to AI Engineering.