Working with LLM APIs
Statelessness, roles, streaming, structured outputs, tool calls and prompt caching.
Part 2 was about what happens inside a model. Part 3 is about building with one, and that starts at the API. A model API looks like any other web service: send JSON, get JSON back. It differs in ways that decide whether a product works. It is stateless, it is billed by the token, it streams, it is rate-limited, and its payload is generated text that may or may not have the shape you asked for.
Provider details change quickly, so this chapter teaches the mechanisms and marks the facts that are specific to one provider. Where a number comes from documentation, it was checked in November 2026; check it again before you depend on it.
11.1Stateless
The conversation is a transcript you resend, and pay for, on every call.
A chat feels like a session. On the wire it is a series of unrelated requests, each carrying the complete conversation so far:
POST /v1/messages
{
"model": "a-mid-tier-model",
"system": "You are a support agent for Acme.",
"messages": [
{"role": "user", "content": "Hi, I'm Priya"},
{"role": "assistant", "content": "Hello Priya!"},
{"role": "user", "content": "What's my name?"}
],
"max_tokens": 1024
}The second message, the model’s own earlier reply, is sent back by you. The provider keeps nothing between calls. Its server flattens the list into one token sequence with the chat template from section 6.8 and runs the next-token loop of section 2.1. A conversation is one long prompt that grows.
Two consequences follow. When a bot “forgets” something the user said, the cause is your history handling, not the model. And you pay again for the whole history on every turn:
- full price for the whole history each turn
- with prompt caching (section 11.6)
The total grows with the square of the number of turns. That curve is why prompt caching exists, and why long conversations get summarized or trimmed (Chapter 20).
Common take“The API remembers the conversation.”
Sharper take“The API is stateless. Memory is something my code provides by re-sending history, it has a token bill, and I budget for it.”
11.2Roles
A trust hierarchy that the model mostly respects.
| Role | Who writes it | The model treats it as | What you use it for |
|---|---|---|---|
| System | You, the developer | Standing instructions, highest authority | Persona, rules, output format |
| User | Your users, and anything they paste | The request | The question and its attached content |
| Assistant | The model, sent back by you | Its own earlier words | History; worked examples |
| Tool result | Your code | Data returned by a tool it asked for | Results of function calls (section 11.5) |
Three things about this hierarchy matter in practice.
- It is trained, not enforced. The model prefers system instructions over user instructions because post-training taught it to (Chapter 9). Nothing in the architecture guarantees it. A user message saying “ignore your instructions” should lose and occasionally wins. That gap is prompt injection, the subject of Chapter 26.
- Earlier assistant turns steer later ones. You can write example exchanges yourself, as user and assistant messages, and the model will imitate what it appears to have said before (section 13.3).
- Prefilling is going away. Older guides recommend ending the list with a partial assistant message, such as an opening brace, to force the reply to continue from it. Recent Claude models reject such requests with an error, and schema-enforced output (section 11.4) does the job properly.
Common take“The system prompt is a rule the model cannot break.”
Sharper take“The system prompt is my channel and the user message is the untrusted channel. The model usually sides with mine, and ‘usually’ is why I never put a secret or a permission check in a prompt.”
11.3Streaming
A response can fail after it has started to succeed.
Generation takes seconds, so APIs can send tokens as they are produced, using server-sent events. The stream is a sequence of small JSON events: text arrives a few tokens at a time, and the final events carry the reason generation stopped and the token counts.
data: {"type": "content_block_delta", "delta": {"text": "Par"}}
data: {"type": "content_block_delta", "delta": {"text": "is"}}
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 214}}
data: {"type": "message_stop"}Streaming changes how fast a product feels, since the user starts reading after the time to first token and not after the whole response. It also adds three failure modes that ordinary request handling does not have.
- Status 200 is not success. The status line is sent before generation finishes. A provider can fail mid-stream, after the 200. The symptom is responses cut off mid-sentence with clean logs. Handle error events inside the stream, and decide whether to retry or show the partial text.
- Proxies can undo it. A load balancer or reverse proxy that buffers responses turns a stream back into one delayed lump. Users see nothing, then everything.
- Usage arrives last. If the user closes the tab and your code abandons the stream, the token counts never arrive and your cost records quietly undercount.
Common take“The request returned 200, so the response is fine.”
Sharper take“A stream is a transaction that can fail after it starts succeeding. I handle errors inside it, and I record the stop reason and usage for every call, including the abandoned ones.”
11.4Structured outputs
A ladder, and only the top rung is a guarantee.
Programs need output they can parse. There are three levels of assurance, and it matters which one you are standing on.
| Rung | Technique | What is guaranteed | How it fails |
|---|---|---|---|
| 1 | Ask for JSON in the prompt | Nothing | Code fences, a chatty preamble, a missing quote |
| 2 | JSON mode | Syntactically valid JSON | Valid JSON in the wrong shape: missing keys, a string where you wanted a number |
| 3 | Schema-enforced output | JSON that matches your schema | Wrong values in the right shape |
The top rung works by constrained decoding. At every step, the provider works out which tokens could legally come next under your schema and removes all the others before sampling. The model cannot emit an invalid token, because invalid tokens are given zero probability. In practice you define the shape once, as a JSON Schema or a typed class in your language, pass it with the request, and parse the reply into the same type.
The mechanism is simple enough to run on the small model from Chapter 9. The task is to capitalize a five-letter word. The constraint allows only five capital letters followed by a line break.
| Model | Unconstrained | Constrained to the format | Unconstrained answer for “rings” | Constrained answer |
|---|---|---|---|---|
| Base model (never saw the task) | 0% valid, 0% correct | 100% valid, 0% correct | what t | ISABE |
| Half-trained on the task | 100% valid, 46% correct | 100% valid, 46% correct | RINGS | RINGS |
| Fully trained on the task | 100% valid, 99.5% correct | 100% valid, 99.5% correct | RINGS | RINGS |
Look at the first row. The base model has never seen the task. Unconstrained, it writes ordinary text. Constrained, it produces perfectly formatted output every time, and every answer is wrong: it writes “ISABE” for every word, the most likely capital letters it knows. The constraint fixed the shape and added no knowledge.
That is the limit of every structured-output feature. Schema conformance is not correctness: {"amount": 4999.00} can be valid and false. Three practical cautions go with it.
- Not every schema rule is enforced. Providers support a subset of JSON Schema, and rules such as numeric ranges or string lengths may be accepted without being enforced. Validate in your own code as well.
- Truncation still breaks it. If generation stops at the output limit, the JSON is cut off mid-object. Check the stop reason.
- Leave room to reason. A schema that allows only the answer removes the model’s scratch space. Put a reasoning field before the answer field when the task needs steps (section 13.5).
Common take“We turned on JSON mode, so the output always parses into our object.”
Sharper take“JSON mode guarantees syntax. A schema guarantees shape. Nothing guarantees the values, so I validate them against real data and I evaluate them like any other model output.”
11.5Function calling
The model states an intent, and your code decides what runs.
A model cannot call anything. Function calling, or tool use, is a structured output with a convention around it: you describe the functions you are willing to run, and the model may reply with the name of one and its arguments. Your code runs it and sends the result back.
{
"name": "get_order",
"description": "Fetch the status of an order by its ID. Use when the user asks about an order.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]
}
}The model decides whether and when to call a tool by reading its description, so the quality of the description is the quality of the routing. The security model is in the figure: the model supplies untrusted intent, and your code is the trusted executor. The model can ask for delete_user; whether that runs is your decision, made in code (Chapter 26).
Three things catch teams out.
- Tool definitions are prompt tokens. The whole list is sent with every request. Forty tools at 300 tokens each is 12,000 input tokens before the user has said anything.
- Calls can come in batches. A model may ask for several tools in one reply. Handle a list.
- Arguments can be valid and wrong. An order ID can match the schema and not exist. Check arguments against your data, not only against the schema.
Run this request, execute and return cycle in a loop, with a limit, and you have an agent. Part 5 is this section grown up.
Common take“The model called our refund API.”
Sharper take“The model asked for a refund call. My code checked the arguments and the user’s permissions and then decided to make it.”
11.6Prompt caching
Reuse a processed prefix at a tenth of the price.
Most requests to a product begin the same way: the same system prompt, the same tool definitions, the same examples. Section 2.7 showed that processing a prompt produces a KV cache. With prompt caching, the provider keeps that cache for a prompt prefix, and a later request that begins with exactly the same tokens skips the work and is billed far less for it.
On the Claude API, as documented in November 2026, writing a prefix to the cache costs 1.25 times the normal input price for a five-minute lifetime, or 2 times for one hour, and reading it back costs 0.1 times on most models. Other providers cache automatically and apply their own discounts. The arithmetic is similar everywhere:
- no caching
- 5-minute cache
- 1-hour cache
One rule follows from “exactly the same tokens from the start”: order a prompt by how often each part changes, with the most stable parts first.
At 100,000 requests a day and $3 per million input tokens, this prompt costs about $4,260 a day uncached and about $480 a day when the prefix is read from the cache. Responses also start sooner, because the cached part is not reprocessed.
Common take“We enabled caching, so costs will drop.”
Sharper take“Caching matches an exact prefix. I put stable content first and per-request content last, and I watch the cache-read token count to confirm it is hitting.”
11.7Token economics
Three asymmetries and one hard cap.
| Fact | Typical size | What follows |
|---|---|---|
| Output costs more than input | 3 to 5 times as much per token | Verbose answers are the expensive kind. A length limit is a cost control |
| Model tiers differ widely | 10 times or more between a small and a flagship model | Sending easy requests to a small model saves more than any prompt tuning |
| Latency follows output length | 500 output tokens at 50 per second is 10 seconds | To finish sooner, shorten the output. To start sooner, shorten the input |
| The output limit is a cut-off, not a target | Generation stops mid-word at the limit | Truncated replies: check the stop reason before blaming the model |
A worked example makes the levers concrete. A support assistant handles 100,000 requests a day, each with a 2,000-token system prompt and tool list, 500 tokens of history, a 200-token question and a 300-token answer.
| Setup | Input per day | Output per day | Total per day |
|---|---|---|---|
| Mid-tier model at $3 and $15 per million tokens | $810 | $450 | $1,260 |
| The same, with the 2,000-token prefix read from cache | $270 | $450 | $720 |
| Small model at $1 and $5 | $270 | $150 | $420 |
| Small model, prefix cached | $90 | $150 | $240 |
The prices are examples; the proportions are the point. Caching and model choice multiply together, and for work that does not need an immediate answer, batch APIs typically halve the price again in exchange for results within a day.
The quiet consumers are all input, billed on every request: re-sent history, tool definitions, retrieved documents and examples. Log input tokens, output tokens, cached tokens and the stop reason for every call from the first day (Chapter 24). You cannot diagnose what you did not record. Chapter 28 takes cost engineering further.
Common take“Our prompts are short, so the bill should be small.”
Sharper take“I look at what is sent, not what I wrote: history, tools and retrieved text on every call, and output at several times the input price. Then I pick the model tier per task.”
11.8Logprobs
A confidence signal for the price of one token.
Section 2.8 showed that a model produces a probability for every possible next token before one is chosen. Some APIs will return those numbers for the tokens they generated, as log-probabilities, or logprobs, often with the top few alternatives. Not every provider or model offers them, so check before designing around them.
Where they exist, they turn a model into a classifier with a confidence score. Ask a question whose answer is a single token, such as yes or no, or one of a few labels, and read the probability of each option. One output token, and you get a decision plus a number to threshold on.
Is the number worth anything? I tested it on the half-trained model from section 10.4, which is right 46% of the time, by sorting its answers by the probability the model assigned to them.
| Answers, sorted by the model’s own probability | Average probability | Correct |
|---|---|---|
| Most confident quarter | 0.60 | 84% |
| Second quarter | 0.35 | 52% |
| Third quarter | 0.21 | 36% |
| Least confident quarter | 0.10 | 12% |
The model’s own probability separates its good answers from its bad ones. The answers it gave with a probability of at least one half, a fifth of the total, were right 85% of the time. That is enough to act on: accept the confident answers, and send the rest to a stronger model or a person.
Two cautions. The probability is of the tokens, not of the truth, and how well the two line up varies by model and task, so measure it on your data before choosing a threshold. And for answers longer than a token or two, the numbers get harder to interpret.
Common take“I ask the model how confident it is, from 1 to 10.”
Sharper take“A stated confidence is more generated text. Where the API exposes logprobs, I read the probability of the answer token itself, and I check on labeled data that it tracks accuracy.”
11.9Server-side state and hosted tools
Convenience that changes who holds the data.
Everything so far assumed that your code holds the conversation and runs the tools. Providers also offer to do both for you.
- Server-side conversation state. OpenAI’s Responses API, which it now recommends for new projects, can store a conversation and continue it from an identifier, so you send only the new message. Its older Chat Completions API remains supported, and its Assistants API was shut down in August 2026. Stored state changes the plumbing, not the bill: earlier turns are still charged as input tokens on each call.
- Hosted tools. Web search, code execution and file search can run on the provider’s side, inside a single request. You write no executor. These tools are usually billed per call on top of tokens.
| You hold state and run tools | The provider does | |
|---|---|---|
| Code to write | History store, tool loop, executors | Much less |
| Where conversation data lives | Your systems | The provider’s, under its retention settings |
| Switching providers | A change of adapter | A migration |
| Visibility into each step | Everything is in your logs | What the provider chooses to return |
| Control over context | You decide what is trimmed or summarized | The provider’s defaults, unless you override them |
Neither column is wrong. Hosted features are a good way to start and a reasonable place to stay for simple products. Systems with strict data rules, more than one provider, or a need to control exactly what is in context tend to keep state themselves.
Common take“With a stateful API I stop paying for history.”
Sharper take“I stop sending it. I still pay for it, since the model reads the whole conversation either way. What changes is where the data lives and how much of the loop I can see.”
11.10The production call
Everything a naive call leaves out.
A model API is a remote, metered, rate-limited dependency whose payload is generated. The difference between a demo and a product is mostly the handling around each call.
| Concern | Naive call | Production call |
|---|---|---|
| Failure | Catch the exception and hope | Timeouts; retries on rate-limit and server errors with exponential backoff and jitter; honor the retry-after header |
| Rate limits | Discovered in production | Limits apply to requests and to tokens separately; cap concurrency on your side |
| Provider outage | The feature is down | A fallback chain: second provider, smaller model, then an honest degraded message |
| Output | Parse the text as JSON | Schema-enforced output, validation, one retry that includes the error |
| Streams | Assume 200 means success | Handle mid-stream errors; record usage even when abandoned |
| Cost | Read the invoice | Prefix-ordered prompts, cache metrics, per-request token logs |
| Retried writes | May run twice | Idempotency keys on anything with a side effect |
The first two rows interact, and a simulation shows how. Two hundred clients need one request each from a server that accepts ten per second. All of them arrive at once, as they would after an outage.
| Retry strategy | Requests sent | Rejected | Seconds until all 200 are served |
|---|---|---|---|
| Retry immediately (50 ms) | 38,200 | 38,000 | 19 |
| Retry after a fixed 1 second | 2,100 | 1,900 | 19 |
| Exponential backoff, no jitter | 2,100 | 1,900 | 451 |
| Exponential backoff with jitter | 834 | 634 | 39 |
| Client-side rate limit (10 per second) | 200 | 0 | 20 |
Retrying immediately finishes quickly in this simulation only because the simulated server shrugs off 38,000 rejected requests; a real one slows down or blocks you. Exponential backoff without jitter is the worst of both: every client waits the same time and they all return together, wave after wave. Jitter spreads them out. Best of all is not to exceed the limit in the first place, by rate-limiting on your own side.
One more component appears as systems grow: a gateway, a service that sits between your code and several providers and gives them one interface. It is a natural home for retries, fallbacks, budgets and logging. The costs are an extra network hop, another dependency, and a tendency to support only the features every provider shares.
Common take“The API is flaky.”
Sharper take“The API is a dependency with a known failure model: timeouts, rate limits, mid-stream errors and wrong-but-valid output. Each has a standard answer, and I build all of them before launch.”
Key takeaways
- The API is stateless. Memory is your code re-sending history, and the bill grows with the square of the number of turns until caching flattens it.
- Roles are a trained trust hierarchy, not an enforced one. The gap between those is prompt injection.
- A stream can fail after returning 200. Read the stop reason and record usage for every call.
- JSON mode guarantees syntax, a schema guarantees shape, and nothing guarantees values: a constrained model that had never seen the task produced valid output that was wrong every time.
- The model never calls a function. It emits a request, and your code decides whether to run it.
- Prompt caching matches an exact prefix. Order prompts from most stable to most variable; a cached read costs about a tenth of the input price.
- Output costs several times what input costs, and model tiers differ by ten times or more. Model choice and caching are the big levers.
- Where logprobs are available they are a real confidence signal: the most confident quarter of answers was right 84% of the time, the least confident 12%.
- Server-side state saves code, not tokens, and moves your data to the provider.
- Retry with backoff and jitter, and rate-limit on your own side: without jitter, 200 clients took 451 seconds to clear a queue that needs 20.
Check your understanding
-
Your assistant’s cost per conversation has doubled in a month, though traffic and prices are unchanged. Caching is enabled. List what you would look at, in order, and what each would tell you.
Answer outline
First the per-request token logs: input, cached input and output tokens over the month. If cached tokens fell toward zero, the prefix has changed: look for something variable added near the top of the system prompt, or a reordering of tools. If input grew, look for longer histories, more tools, or larger retrieved passages. If output grew, look for a prompt change that made answers longer, or reasoning turned on. Then conversation length: more turns means quadratically more re-sent history. Each finding points to a specific fix: restore the prefix, trim or summarize history, cap output, or prune the tool list.
-
An extraction pipeline uses schema-enforced output and never throws a parse error, yet finance reports wrong invoice totals. Explain how both can be true, using the experiment in section 11.4, and describe two checks you would add.
Answer outline
The schema guarantees shape, not values. In the experiment a model that had never seen the task produced perfectly valid output that was wrong every time, because the constraint removes invalid tokens and adds no knowledge. Checks to add: validate values against the source, for example confirm that the extracted total appears in the document text and that line items sum to it; apply range and format rules in code; and where logprobs are available, send low-confidence fields to review. Evaluate on a labeled set, since no parse error will ever reveal this.
-
After a provider outage ends, your service is rejected with rate-limit errors for ten minutes even though normal traffic is well under the limit. What is happening, and what would you change?
Answer outline
Queued and failed requests are all retrying together, so the burst far exceeds the limit, and if retries are synchronized they keep colliding, the pattern that took 451 seconds in the simulation. Changes: exponential backoff with jitter so retries spread out; honor the retry-after header; cap concurrency or rate on your own side so the backlog drains at the allowed rate; give retries a budget so old requests are dropped and not retried forever; and shed or queue low-priority work during recovery.
Further reading
- Your provider’s API documentation: the primary source for this chapter. Read the pages on messages, streaming, structured outputs, tool use, prompt caching, rate limits and errors for the provider you use.
- Chip Huyen, AI Engineering, chapter 2: the sections on sampling and structured outputs.
- The AWS Architecture Blog, “Exponential Backoff and Jitter”: the classic short analysis behind the retry advice in section 11.10.