Lesson 23 of 40AI in production
AI Features in Production
Ship an AI feature that survives real users, with structured output, retries, caching, fallbacks, logging, cost tracking and human review.
Until now the course has been about AI that helps you write code. This unit is about shipping AI inside your own product, with the same production habits you used in the Docker and AWS courses. A demo needs one good answer. A production feature needs ten thousand answers a day, on bad inputs, during an outage, inside a budget, with someone able to explain afterwards why answer 4,812 was wrong. The model call is the easy part. Everything around it (the shape of the output, what happens when the API is slow, what you log, who checks the risky cases) decides whether the feature is trusted or switched off. This lesson walks through that wrapper, piece by piece, for a running example: a support tool that reads an incoming customer email and turns it into a ticket.
Start with the simplest tier
Before you write any code, decide how much autonomy the feature really needs. Anthropic's own guidance is to start with the simplest tier that works:
| Tier | Who decides the steps | Example |
|---|---|---|
| Single call | Nobody: one prompt, one answer | Classify an email as bug, billing or question |
| Workflow | Your code: fixed steps, each a model call | Classify, then extract fields, then draft a reply |
| Agent | The model: it picks tools in a loop | Investigate a bug report across logs and code |
Each step up adds cost, latency and new ways to fail. A single call is easy to test, cheap, and fails in one place. An agent can take a different path every time. Only move up when the task is complex, valuable, within the model's ability, and when its errors can be caught by tests, review or rollback. (The lesson on what an agent is covers this decision in depth.)
Our ticket feature is a single call. Most production AI features are.
Structured outputs: answers your code can use
Your code cannot do much with a paragraph. It needs fields: a title, a priority, a list of tags. Structured output means the model returns data in a shape you define, and the SDK validates it before your code sees it. With the Python SDK you describe the shape as a Pydantic model (a Python class that declares field names and types):
from pydantic import BaseModel
class Ticket(BaseModel):
title: str
priority: str
tags: list[str]
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Turn this bug report into a ticket: ..."}],
output_format=Ticket,
)
ticket = response.parsed_outputticket.priority is now a real string field, not something you hoped to find with a regular expression. Validation catches the wrong shape. It does not catch the wrong content, so you still check values your business depends on (is priority one of the three you support?) before acting on them.
Streaming: show progress on long answers
A long answer can take many seconds to finish. Streaming sends the output in pieces as the model generates it, so the user sees text appear instead of a spinner. Use it for anything a person reads as it arrives: drafted replies, explanations, chat. Skip it for structured data your code parses only once the whole thing is complete. The SDKs have streaming helpers; check the official docs for the current method names.
When the API fails: retries, rate limits, timeouts
Network calls fail. Three cases matter:
- Rate limits (HTTP status 429): you sent too many requests or tokens too fast. The fix is to wait and try again.
- Server errors (5xx): something broke on the provider's side, usually briefly. Also worth a retry.
- Timeouts: the request is taking too long for your user to wait. Set a time limit and decide what happens when it passes.
The Anthropic SDK clients already retry 429 and 5xx errors twice by default. When retries run out, they raise typed errors you can catch:
import anthropic
try:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": email_text}],
)
except anthropic.RateLimitError:
queue_for_later(email_text) # your code: try again in a few minutesGood retries use exponential backoff (wait 1 second, then 2, then 4) plus a little jitter (random extra wait) so a thousand clients do not all retry at the same instant. They also respect a total time budget, because a user will not wait forever. Here is the idea with a fake API that fails twice:
Press Run (⌘ Enter) to see what happens.Try setting budget=2.0 and run it again: the function gives up and the fallback message appears. That is the behaviour you want, a clear failure instead of a hung page.
What does this print?
print([1 * 2 ** n for n in range(4)])
Prompt caching: pay less for the part that never changes
Most requests in a feature share a big, stable beginning: the same system prompt, the same tool definitions, the same style guide. Prompt caching lets the API reuse the work it already did on that beginning. Cached reads cost about a tenth of normal input, and writing to the cache costs a bit more than normal input, so it pays off whenever the same prefix is sent again within the cache lifetime (5 minutes by default, with a 1 hour option).
Caching is a prefix match. The cache only helps up to the first byte that differs, so order matters:
Everything stable goes first. On the second request this whole block can be read from the cache at a fraction of the price.
The simplest way to turn it on is cache_control={"type": "ephemeral"} on messages.create. Then check that it works: on a repeated request, response.usage.cache_read_input_tokens should be above zero. If it stays at zero, look for something in the prefix that changes between calls.
Current time: 14:02:31. What is going on?Refusals, cut-offs and fallbacks
Not every successful response is a usable one. Before you read the content, check stop_reason:
end_turn: the model finished normally.max_tokens: the answer was cut off. Raise the limit, or ask for something shorter.refusal: the model declined. Do not parse the content as if it were a ticket.
if response.stop_reason == "refusal":
return route_to_human(email_text) # your code
if response.stop_reason == "max_tokens":
log_truncation(response) # your codeEvery failure path needs a fallback: a sensible thing to do instead. For our support tool, that could be creating a plain ticket with the raw email and a "needs triage" tag. The user's work is never lost because a model call went wrong.
Match each problem to a sensible response.
Logging, observability and cost
When a user says "the AI gave me nonsense yesterday", you need to find that exact request. Observability means you can see what your system did and why. For every call, log at least:
- a request id, the user or tenant, and the feature name
- the model and the prompt version
- input and output token counts (from
response.usage) - latency,
stop_reason, retries and whether a fallback fired
Be careful with full prompt and response text: it may contain personal data. Log it only where your privacy rules allow, and redact what you can (the lesson AI Security covers this).
Token counts turn into money. Price each call and add it up per feature, so you notice when one feature quietly costs a hundred times more than another:
Press Run (⌘ Enter) to see what happens.Fractions of a cent per call look harmless until you multiply by real traffic. Set a budget alert per feature.
Version prompts like code
A prompt is part of your program. Changing one word can change behaviour as much as changing a line of code, so treat it the same way:
- Keep prompts in files in the repository, not pasted into a dashboard.
- Give each one a version (
triage@v3) and log that version with every call. - Change prompts through pull requests, with a review.
- Before shipping a change, run it against a fixed set of test cases and compare. That practice has its own lesson: Evals.
The same goes for model upgrades. A new model is a new dependency: test it before you switch.
Keep a human in the loop for high stakes
Some outputs are cheap to get wrong: a slightly off ticket title. Others are not: a refund, a medical note, a message sent to a customer in your company's name. For high-stakes output, the model drafts and a person approves. Design the interface so approving is quick, but never automatic. Route by risk: low-confidence, refused, or high-value items go to the review queue; routine items flow straight through.
The app sends a prompt with the stable part first, so the cache can help. Retries with backoff wrap this call.
Put the handling of one request in a sensible order.
- Tap the steps below in the right order.
- structured output
- Model output in a shape you define, such as JSON matching a schema, validated before your code uses it.
- streaming
- Receiving a model's output in pieces as it is generated instead of waiting for the whole answer.
- rate limit
- A cap on how many requests or tokens you can send in a period. Exceeding it returns HTTP 429.
- exponential backoff
- Retrying after waits that double each time, usually with random jitter added.
- prompt caching
- Reusing the processed beginning of a prompt across requests, so repeated prefixes cost less.
- fallback
- What your feature does instead when a model call fails, is refused, or returns unusable output.
- observability
- Logging and metrics that let you see what your system did, why, and at what cost.