Learnings

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

One model call

The model keeps nothing between requests. Everything it should know must be in the request you send.

Two calls share nothing unless the client sends it twice.

Not run for this page (needs an API key).

Tokens and the context window

One model call

A token is a piece of a word. Limits, speed and price are all counted in tokens, never in characters or requests.

Input and output share one window. What does not fit is rejected, not trimmed.
FactRule of thumb (approximate, check the docs)
Size of a tokenAbout 4 characters or 0.75 words of English. Code, JSON and other languages use more.
Context windowHundreds of thousands to 1M tokens on current large models
Input over the windowA 400 error, before any generation
TokenizerDiffers per model: count with the provider's counter, see token counting
Long inputCosts more, answers slower, and details in the middle get less attention

Anatomy of a request

One model call

FieldWhat it isNote
modelWhich model answersPin the exact id in config
systemStanding instructions: role, rules, formatYours, not the user's. Top-level field here; a first message with role system in OpenAI-style chat APIs
messagesThe conversation, a list of {role, content}Roles user and assistant; the first is user
max_tokensHard cap on output tokensRequired. The model is cut off at it, it does not plan for it
stop_sequencesStrings that end the replyOptional
output_configeffort and a JSON formatSee effort and structured output

The response is JSON too. content is a list of typed blocks, so read the ones with type == "text".

Response fieldUse
contentThe reply blocks
stop_reasonWhy it stopped: check it before using the text
usageinput_tokens, output_tokens: what you are billed for
id, request idLog 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

One model call

The model produces a probability for every next token and samples one. Temperature controls how adventurous that pick is.

SettingEffectUse for
Temperature 0Nearly always the most likely token. Still not guaranteed identical between runsExtraction, classification
Temperature near 1More varied wordingDrafts, brainstorming
effort low to maxHow much the model reasons before answering. Reasoning tokens are billed as outputLow 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

One model call

A 200 response is not a finished answer. The stop reason says which of the two you got.

Only 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

One model call

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.

The client owns the conversation. The server sees it fresh each time.

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

Prompts and structured output

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.

Stable parts first, the changing question last. That order also helps caching.
  • 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

Prompts and structured output

BadBetterWhy
"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 exampleNames 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 afterDocuments first, question at the endThe 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

Prompts and 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).

LevelYou getStill check
"Return JSON" in the promptUsually JSON, sometimes with prose around itEverything
Schema in the requestJSON that matches the schemaStop 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

Prompts and structured output

Without schema enforcement, or for rules a schema cannot express, validate in code and send the error back. Cap the attempts.

The error message is the repair prompt, so make it exact.

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

Streaming and cost

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.

Text arrives in deltas. Stop reason and output token count arrive at the end.

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.

MetricMeaningMatters for
Time to first tokenRequest sent to first textHow fast a chat feels
Tokens per secondSpeed after thatLong answers
Total timeGrows with output lengthBatch 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

Streaming and cost

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

Streaming and cost

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.

Only an identical prefix hits. One changed byte early in the prompt misses everything after it.

Not run for this page (needs an API key).

PointDetail (approximate, check the docs)
PriceRead about 0.1× input price, write about 1.25×
LifetimeAbout 5 minutes by default, refreshed on each hit
Minimum sizeShort prefixes are not cached; the floor depends on the model
OrderStable text first (rules, articles), changing text last (the question)
Silent missA timestamp or request id in the system prompt
Proofusage.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

Failures

Retry what may pass next time. Never retry a request the server called wrong.
StatusMeaningDo
400Bad request, or prompt too longFix the request
401, 403Bad key, not allowedFix config, alert
404Unknown model idFix config
429Rate limit (requests or tokens per minute)Wait retry-after, then retry
500, 529Server error, overloadedBack off and retry
Timeout, connection resetNo answerRetry, 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

Failures

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

Failures

Generating text changes nothing, so retrying a model call is safe. What you do with the reply may not be.

RiskGuard
The call timed out on your side but finished on theirs: you pay twiceA timeout long enough for the output you asked for; a retry cap
The retry gives a different answerStore 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 retriedAn 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

Failures

When the output reaches max_tokens the reply simply ends, mid-sentence or mid-JSON, with HTTP 200.

Half a JSON object is garbage. Half an essay may still be worth showing.

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

Failures

The model writes the most plausible continuation. When it lacks the fact, plausible and true come apart, and the tone stays just as confident.

Ask for evidence, then check the evidence in code.

Run against the stub. The second scripted reply quotes a sentence the article does not contain.

CauseReduce it by
The fact is not in the promptPut 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 declineAllow "I do not know" and reward it in examples
Free-form answersClosed lists and schemas, validated in code
Nobody measures itA 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)CapabilityLatencyPrice per 1M tokens, in / outBank assistant use
Large (claude-opus-5-5)HighestSlowestAbout $4 / $20Drafting a reply to a complex complaint
Medium (claude-sonnet-5-5)HighMiddleAbout $2 / $10Answering from help articles
Small (claude-haiku-5-5)Enough for narrow tasksFastestAbout $0.10 / $0.50Intent 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

Shipping it

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.

One door to the model. Tests swap the model behind it.

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

Shipping it

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

Shipping it

I need toDo this
Keep a conversationResend the history; trim or summarise old turns
Set standing rulesSystem prompt; user text stays in messages
Get a usable answerTask, context, example, format; question last
Parse the reply in codeSchema in the request, then validate
Make a chat feel fastStream; watch time to first token
Estimate the billTokens × price, input and output apart
Cut cost of a long fixed promptCache the prefix; stable text first
Handle 429 and 5xxBackoff with jitter, honour retry-after, cap attempts
Handle 400, 401, 404Do not retry; fix and alert
Avoid half answersCheck stop reason on every reply
Avoid made-up factsSources in, quote out, check in code
Pick a modelLargest first, then down while tests pass

Interview questions

Shipping it

QuestionAnswer
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.