Skip to content

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.

18 min read0/5 questions

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:

TierWho decides the stepsExample
Single callNobody: one prompt, one answerClassify an email as bug, billing or question
WorkflowYour code: fixed steps, each a model callClassify, then extract fields, then draft a reply
AgentThe model: it picks tools in a loopInvestigate 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.

Quick check
A team wants to tag 20,000 product reviews as positive, negative or mixed. Which tier should they start with?
Need a nudge? A hint rules out a wrong answer.

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):

ticket.py
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_output

ticket.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 minutes

Good 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:

Python
import random random.seed(7) class RateLimitError(Exception): pass calls = {"n": 0} def flaky_api(prompt): # A fake model API: the first two calls hit a rate limit. calls["n"] += 1 if calls["n"] <= 2: raise RateLimitError("429: slow down") return f"summary of: {prompt[:20]}" def call_with_retries(prompt, max_attempts=4, base_delay=1.0, budget=10.0): waited = 0.0 for attempt in range(1, max_attempts + 1): try: result = flaky_api(prompt) print(f"attempt {attempt}: ok after {waited:.1f}s of waiting") return result except RateLimitError as err: delay = base_delay * 2 ** (attempt - 1) # 1, 2, 4, 8 ... delay += random.uniform(0, delay * 0.25) # jitter if attempt == max_attempts or waited + delay > budget: print(f"attempt {attempt}: {err}, giving up") return None print(f"attempt {attempt}: {err}, waiting {delay:.1f}s") waited += delay # a real app would time.sleep(delay) here return None answer = call_with_retries("The customer says the export button does nothing.")print("answer:", answer or "fallback: show a friendly error")
Output
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.

Predict the outputPython

What does this print?

print([1 * 2 ** n for n in range(4)])
Need a nudge? Hints walk you through it.

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:

Ordering a prompt for caching
  1. Tool definitionsidentical on every request
  2. System promptrules, style guide, examples
  3. Reference docsproduct FAQ, policies
  4. This customer's emaildifferent every time

Everything stable goes first. On the second request this whole block can be read from the cache at a fraction of the price.

1/3

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.

Quick check
Your cache hit rate is zero. The system prompt starts with Current time: 14:02:31. What is going on?
Need a nudge? A hint rules out a wrong answer.

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 code

Every 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 the pairs0/4 matched

Match each problem to a sensible response.

Choose an item, then its match on the other side.

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:

Python
# Prices per million tokens (input, output). A dated snapshot: check the docs.PRICES = { "claude-sonnet-5-5": (2.00, 10.00), "claude-haiku-5-5": (0.10, 0.50),} log = [ {"feature": "ticket-triage", "model": "claude-haiku-5-5", "prompt": "triage@v3", "in": 1200, "out": 150}, {"feature": "ticket-triage", "model": "claude-haiku-5-5", "prompt": "triage@v3", "in": 1350, "out": 170}, {"feature": "reply-draft", "model": "claude-sonnet-5-5", "prompt": "reply@v7", "in": 4800, "out": 900}, {"feature": "reply-draft", "model": "claude-sonnet-5-5", "prompt": "reply@v7", "in": 5100, "out": 1100},] def cost(row): price_in, price_out = PRICES[row["model"]] return row["in"] / 1_000_000 * price_in + row["out"] / 1_000_000 * price_out totals = {}for row in log: totals[row["feature"]] = totals.get(row["feature"], 0) + cost(row) for feature, dollars in totals.items(): per_call = dollars / sum(1 for r in log if r["feature"] == feature) print(f"{feature:14} ${dollars:.5f} total, ${per_call:.5f} per call") print(f"{'':14} at 50,000 calls a day: ${per_call * 50_000:,.2f}")
Output
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.

One production request
Your app: builds the promptYour appbuilds the promptModel API: cached prefixModel APIcached prefixChecks: stop_reason, schemaChecksstop_reason, schemaReview queue: high stakesReview queuehigh stakesTicket: savedTicketsavedLogs: tokens, cost, versionLogstokens, cost, versionrequestresponseokrisky

The app sends a prompt with the stable part first, so the cache can help. Retries with backoff wrap this call.

1/5
Put it in order6 steps

Put the handling of one request in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.