llm.guideChapter 11Working with LLM APIs

Working with LLM APIs

Statelessness, roles, streaming, structured outputs, tool calls and prompt caching.

Part 3: Building with LLMs. 10 sections, about 20 minutes.

Your codeProviderModelrequest: system, messages,tools; the whole transcriptrate limit, cache lookupread (prefill)write, token by tokenstreamed text eventsusageparse, validate,log, maybe retryStateless: each call carries the whole conversation. Retries with backoff handle rate limits and overloads.
Your code sendssystem, messages, tools: everythingProviderrate limit, cached-prefix lookupModel readsthe uncached part (prefill)Model writesstreamed back as text events, then usageYour codeparses, validates, logs, retries
The life of one API call, as a sequence. Your code is at both ends, and most of what makes a call reliable happens there.

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:

0100K200K300K400K11020304050input tokens billed so farturn of the conversationno caching: 382Kwith caching: equal to 56K
0100K200K300K400K11020304050input tokens billed so farturn of the conversation382Kcached: 56K
  • full price for the whole history each turn
  • with prompt caching (section 11.6)
Figure 11.1 Computed for a 50-turn chat with 300 new tokens per turn. The conversation contains 15,000 tokens, but re-sending it bills 382,500 input tokens, about 25 times as many. With caching, the bill is equivalent to about 56,000 full-price tokens.

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.

RoleWho writes itThe model treats it asWhat you use it for
SystemYou, the developerStanding instructions, highest authorityPersona, rules, output format
UserYour users, and anything they pasteThe requestThe question and its attached content
AssistantThe model, sent back by youIts own earlier wordsHistory; worked examples
Tool resultYour codeData returned by a tool it asked forResults 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.
Systemyou, the developer: standing rulesUserthe request, and anything pasted into itTool resultsdata returned by your code; never instructionsAssistant turns sit beside these: the model’s own earlier words, which it tends to imitate.injected texttrying to climb:loses, mostly
Figure 11.2 Authority by role. The ordering comes from post-training, so it holds most of the time; Chapter 26 is about the times it does not.

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"}
0 s1 s2 s3 s4 sWhat the provider sendsWhen it fails mid-streamBehind a buffering proxy200first tokenstop reason, usageerror event, after the 200nothing, then everything
Figure 11.3 The three traps on one timeline. The status arrives before any text, so it cannot vouch for the text; usage arrives last, so an abandoned stream never reports what it cost.

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.

RungTechniqueWhat is guaranteedHow it fails
1Ask for JSON in the promptNothingCode fences, a chatty preamble, a missing quote
2JSON modeSyntactically valid JSONValid JSON in the wrong shape: missing keys, a string where you wanted a number
3Schema-enforced outputJSON that matches your schemaWrong 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.

ModelUnconstrainedConstrained to the formatUnconstrained answer for “rings”Constrained answer
Base model (never saw the task)0% valid, 0% correct100% valid, 0% correctwhat tISABE
Half-trained on the task100% valid, 46% correct100% valid, 46% correctRINGSRINGS
Fully trained on the task100% valid, 99.5% correct100% valid, 99.5% correctRINGSRINGS

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).
1 Ask in the promptguaranteed: nothingfails with fences, preambles, missing quotes2 JSON modeguaranteed: valid JSON, any shapefails with missing keys and wrong types3 Schema enforcedguaranteed: the shape you definedstill fails with wrong values in the right shape
Figure 11.4 Know which rung you stand on. Only the top one is a guarantee, and even it says nothing about whether the values are right; validate those in code.

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.

Your codeModelmessages + list of toolstool call: get_order, {"order_id": "A1B2"}tool resultthe answer, in wordsruns the tool
Figure 11.5 One round of function calling. The model’s part is two messages. Everything that touches your systems happens in your code.
{
  "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:

02×4×6×8×12345678cost of the prefixrequests that share the same prefixno caching1-hour cache: 2.7×5-minute cache: 1.95×
02×4×6×8×12345678cost of the prefixrequests that share the same prefixno caching1-hour: 2.7×5-min: 1.95×
  • no caching
  • 5-minute cache
  • 1-hour cache
Figure 11.6 Computed from those multipliers. The five-minute cache is ahead from the second request. The one-hour cache costs more to write and is ahead from the third.

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.

Cached prefix: 14,000 tokens, identical on every call, read at a tenth of the priceSystem prompt2,000 tokensTool definitions8,000 tokensWorked examples4,000 tokensUser message: 200 tokens, new each call, full price
Figure 11.7 The prompt above, drawn to scale. Only the last sliver is processed at full price on each call; everything before it is read from the cache.

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.

cost = input tokens × input price + output tokens × output price
FactTypical sizeWhat follows
Output costs more than input3 to 5 times as much per tokenVerbose answers are the expensive kind. A length limit is a cost control
Model tiers differ widely10 times or more between a small and a flagship modelSending easy requests to a small model saves more than any prompt tuning
Latency follows output length500 output tokens at 50 per second is 10 secondsTo finish sooner, shorten the output. To start sooner, shorten the input
The output limit is a cut-off, not a targetGeneration stops mid-word at the limitTruncated 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.

SetupInput per dayOutput per dayTotal 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 probabilityAverage probabilityCorrect
Most confident quarter0.6084%
Second quarter0.3552%
Third quarter0.2136%
Least confident quarter0.1012%

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 toolsThe provider does
Code to writeHistory store, tool loop, executorsMuch less
Where conversation data livesYour systemsThe provider’s, under its retention settings
Switching providersA change of adapterA migration
Visibility into each stepEverything is in your logsWhat the provider chooses to return
Control over contextYou decide what is trimmed or summarizedThe 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.

ConcernNaive callProduction call
FailureCatch the exception and hopeTimeouts; retries on rate-limit and server errors with exponential backoff and jitter; honor the retry-after header
Rate limitsDiscovered in productionLimits apply to requests and to tokens separately; cap concurrency on your side
Provider outageThe feature is downA fallback chain: second provider, smaller model, then an honest degraded message
OutputParse the text as JSONSchema-enforced output, validation, one retry that includes the error
StreamsAssume 200 means successHandle mid-stream errors; record usage even when abandoned
CostRead the invoicePrefix-ordered prompts, cache metrics, per-request token logs
Retried writesMay run twiceIdempotency keys on anything with a side effect
Logging: tokens, cost and stop reason, even for abandoned streamsA budget per request, and an idempotency key on anything with a side effectA fallback chain: a second provider, a smaller model, an honest messageA rate limit on your side; retries with exponential backoff and jitterSchema-enforced output, validated, with one retry that includes the errorA timeout, and errors handled inside the streamThe model call
Figure 11.8 The table above as layers. A naive call is only the box in the middle; each ring is a failure the product survives instead of showing to a user.

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 strategyRequests sentRejectedSeconds until all 200 are served
Retry immediately (50 ms)38,20038,00019
Retry after a fixed 1 second2,1001,90019
Exponential backoff, no jitter2,1001,900451
Exponential backoff with jitter83463439
Client-side rate limit (10 per second)200020

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

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

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

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

↑↓ to move↵ to openesc to close