Production AI Observability

On this page 15 sections
  1. What observability means for an LLM feature
  2. Step 1: Write one record per model call
  3. Step 2: Work out the cost when you write the record
  4. Step 3: Tie retrieval and the model call together with a trace
  5. Step 4: Turn the records into a cost report and one alert
  6. Step 5: Pick the calls a person should read
  7. Step 6: Keep personal data out of the logs
  8. Before you ship: evals in CI
  9. Try it yourself
  10. Common beginner mistakes
  11. Questions you will face in production
  12. Check your understanding
  13. What to remember
  14. What to study next
  15. Further reading

The Kitebase support bot from article 04 has been live for a few days. One morning, two messages arrive:

  • Finance asks why yesterday’s Anthropic bill for the bot was about 65% higher than the days before.
  • A customer says the bot’s answer “just stopped mid-sentence and took forever”.

Your service dashboard is green. Every request returned 200 OK, and the error rate is zero.

That’s how an LLM feature fails: quietly, inside a successful response. The HTTP logs say a request came in and a response went out. They don’t say any of the things you now need to know:

  • which prompt ran
  • how many tokens it used
  • which help articles it read
  • whether the model finished

What you’ll build: a thin wrapper around the Kitebase bot’s model call. It writes one structured record per call, as part of a trace. Each record holds the prompt version, model, tokens, cost, stop_reason and the chunks the model read. You’ll also build a report that finds the cost jump in four days of logs and picks out the calls worth reading. It all runs offline with a fake Claude client.

What observability means for an LLM feature

Observability means you can answer a new question about production from data you already record. A question like “why did this cost more?” shouldn’t need you to ship new code first.

For a normal service, that data is the request, the status code and the latency. For an LLM call it isn’t enough, because a 200 OK can hide three problems:

  • A wrong answer. The model invented a step, or retrieval handed it the wrong help article.
  • A cut-off answer. The model hit max_tokens, the output limit you set, and stopped mid-sentence.
  • An expensive answer. Normally $0.005, today $0.03, because the prompt or the answer grew.

So for every call, you record what went in and what came back, in a shape you can query.

Step 1: Write one record per model call

A structured log is a log line that’s data, not a sentence. Each line is one JSON object with the same field names every time. That means you can filter it, group it and add it up.

“Called Claude, took 1.8s” is a sentence. This is a record:

prompt            "support@v3"
prompt_fp         "13674be7"
model             "claude-opus-5"
chunk_ids         ["account-recovery#1", "recovery-email#1", "reset-password#1"]
input_tokens      412
output_tokens     118
stop_reason       "end_turn"
cost_usd          0.00501
duration_ms       1844

That’s the worked question from article 04, “How do I reset my password if I never set a recovery email?” It’s shown the way it appears in the sample log that ships with the example, one field per line.

Each field answers a question you’ll be asked:

  • prompt, prompt_fp: which prompt produced this answer. prompt is a version name. prompt_fp is a fingerprint (8 characters of a hash of the prompt text) from article 03. When answers change, these tell you whether the prompt did.
  • model: which model answered. Read it from the response, not your config, so a switch or a fallback shows up.
  • input_tokens, output_tokens: what you pay for. Tokens are the units models read and bill in. Each one is about 4 characters of English (article 01).
  • cost_usd: the same thing in dollars, from step 2.
  • stop_reason: why the model stopped. "end_turn" means it finished. "max_tokens" means it was cut off. "refusal" means it declined.
  • chunk_ids: which help-center passages went into the prompt. When an answer is wrong, this tells you whether to blame retrieval or the model.
  • duration_ms: how long the call took.

The wrapper does three things:

  1. It opens a span. Step 3 explains what a span is.
  2. It makes the call, the same way article 04 did.
  3. It copies the fields off the response.
def call_claude(client, trace: Trace, user_message: str, chunk_ids: list[str]):
    with trace.span("llm.call", prompt=PROMPT_ID, prompt_fp=PROMPT_FP,
                    model=MODEL, chunk_ids=chunk_ids) as rec:
        response = client.messages.create(
            model=MODEL,
            max_tokens=1024,
            system=SYSTEM_PROMPT,
            messages=[{"role": "user", "content": user_message}],
        )
        u = response.usage
        rec.update(
            model=response.model,  # what actually answered, not what you asked for
            message_id=response.id,
            input_tokens=u.input_tokens,
            output_tokens=u.output_tokens,
            cache_read_tokens=u.cache_read_input_tokens or 0,
            stop_reason=response.stop_reason,
        )
        rec["cost_usd"] = cost_usd(rec["model"], u.input_tokens, u.output_tokens,
                                   rec["cache_read_tokens"], u.cache_creation_input_tokens or 0)
        return response

message_id is the id Anthropic gives the response (msg_...). Include it when you ask their support about a specific call.

The question and answer text are missing on purpose. Step 6 stores them somewhere else.

The real risk is logging too little. If a field isn’t in the record on the day something breaks, you can’t add it after the fact. So log stop_reason and the prompt version from day one, before you even have a dashboard.

Step 2: Work out the cost when you write the record

The API response has token counts, not dollars. The price table on this site lists claude-opus-5 at $5 per million input tokens and $25 per million output tokens. So the worked call costs:

412 input tokens  × $5  / 1,000,000 = $0.00206
118 output tokens × $25 / 1,000,000 = $0.00295
                                      $0.00501

Output tokens cost five times as much as input tokens. So long answers cost more than long questions. In code:

def cost_usd(model: str, input_tokens: int, output_tokens: int,
             cache_read_tokens: int = 0, cache_write_tokens: int = 0) -> float | None:
    price = PRICES.get(model)
    if price is None or cache_write_tokens:
        return None  # an unknown price, not $0
    total = (input_tokens * price["input"] + output_tokens * price["output"]
             + cache_read_tokens * price["cache_read"])
    return round(total / 1_000_000, 6)

Why work out the cost now, and not later in the report? Because prices change. A record that stores the cost at call time, plus the tokens behind it, stays right after the next price change.

The line to watch is the return None. Say you add a model and forget to add it to the price table. A function that defaults to $0 would show the cheapest day you’ve ever had. Returning None lets the report count the unpriced calls and say so.

Some cached calls come back unknown too. With prompt caching (article 10), cache reads cost a tenth of normal input, which is $0.50 per million here. Cache writes are different. They have their own price, and it isn’t in the table, so those calls return None as well.

Step 3: Tie retrieval and the model call together with a trace

The record from step 1 only covers the model call. It doesn’t say how long retrieval took, or which user asked. Those belong to other steps of the same request. When the customer from the opening complains, you want all of those steps, in order.

A trace is the record of one request as it moves through your code. It’s made of spans, one per step. Each span has a name, a duration and its own fields.

Two ids tie the spans together:

  • Every span in a trace carries the same trace_id.
  • Each span points to the span it ran inside through parent_id.

The result is a call stack written down with timings. For Kitebase, the root span support.answer covers the whole request, and retrieve and llm.call run inside it:

Trace 990f3ccb: one question, three spans "How do I reset my password if I never set a recovery email?" support.answer 1,990 ms retrieve 144 ms llm.call 1,844 ms 0 500 1,000 1,500 2,000 ms SUPPORT.ANSWER (ROOT) parent_id null user "u_07d1cbf11020" An HMAC of the login, not the email. RETRIEVE parent_id → support.answer k 3, top_score 0.61 account-recovery#1 recovery-email#1 reset-password#1 LLM.CALL: THE RECORD YOU DEBUG WITH prompt support@v3 13674be7 the exact prompt text model claude-opus-5 what actually answered input 412, output 118 tokens, what you pay for cost_usd 0.00501 412 × $5 + 118 × $25, /1M stop_reason end_turn finished, not cut off chunk_ids [3 ids] what it was given to read duration_ms 1844 93% of the wait trace_id, parent_id ties it to the other two
The worked question as it appears in the sample log. The model call is 93% of the wait.

The waterfall shows where the time went. The model call is almost all of it. That’s typical, so latency work usually starts there.

The example’s Trace class is about 20 lines. Here’s the part that matters:

@contextmanager
def span(self, name: str, **fields):
    record = {"trace_id": self.trace_id, "span_id": secrets.token_hex(8),
              "parent_id": self._open[-1] if self._open else None,
              "name": name, "status": "ok", **fields}
    self._open.append(record["span_id"])
    start = time.perf_counter()
    try:
        yield record  # the caller adds fields as it learns them
    except Exception as e:
        record.update(status="error", error=type(e).__name__)
        raise
    finally:  # write the span even when the call failed
        record["duration_ms"] = round((time.perf_counter() - start) * 1000)
        self._open.pop()
        self.sink(record)

Two names in there need explaining:

  • self._open is a stack of running spans. A span opened inside another one gets that span as its parent.
  • sink is wherever finished records go. In the example it’s a JSON-lines file. In the tests it’s a list.

The line that matters most is the finally. A span written only on success vanishes exactly when you need it. A timeout or a rate-limit error would leave nothing behind. Because the span is written in finally, the failed call still shows up, with status: "error" and the exception’s name.

One side effect is the order. Children finish before their parent, so they’re written first. Read traces by parent_id, not by line order.

Should I use OpenTelemetry instead of writing my own?

In production, yes. OpenTelemetry is the open standard for traces. Datadog, Honeycomb and Grafana accept it, and so do LLM tools like Langfuse and Phoenix.

The shape is the same as the example’s:

  • tracer.start_as_current_span("llm.call") opens a span.
  • A span opened inside it becomes its child.
  • An exception marks it as an error.

OpenTelemetry also names LLM fields, like gen_ai.usage.input_tokens, so tools can chart them without setup. The Python package still marks those names experimental. The example’s otel_span.py writes the same spans with opentelemetry-sdk.

Step 4: Turn the records into a cost report and one alert

Now back to finance’s question. The example ships data/sample_spans.jsonl, four made-up days of Kitebase traffic in the format above. That’s 160 questions in all. python report.py groups the llm.call spans by day:

day          calls     cost   $/call  p95 ms not ok
2026-09-20      40   $0.202  $0.0050   3,647      0
2026-09-21      40   $0.198  $0.0050   3,107      1
2026-09-22      40   $0.216  $0.0055   2,900      2
2026-09-23      40   $0.338  $0.0084   4,133      2

Three of those columns need a word:

  • $/call is cost divided by priced calls.
  • p95 ms is the 95th percentile latency. 95% of calls finished within it, and only the slowest 1 in 20 took longer. An average would hide those slow ones.
  • not ok counts calls that errored or didn’t end with "end_turn".

Cost per call jumped on the 23rd. Grouping the same records by prompt version shows why:

prompt       calls  avg in chunks   $/call
support@v3     128     417      3  $0.0052
support@v4      32   1,014     13  $0.0093

ALERT 2026-09-23: $0.0084 per call is 63% above the 3 days before ($0.0052).

Prompt v4 shipped at 09:00 on the 23rd. Every call since then has sent all 13 chunks instead of the top 3. Someone set TOP_K = 13 while testing, which is exactly what article 04 suggests, and it shipped along with the prompt change:

Cost per call, by day 160 questions from the sample log $0.0050 $0.0050 $0.0055 alert line for 09-23: $0.0052 + 30% = $0.0068 $0.0084 09-20 09-21 09-22 09-23 1 cut-off answer v4 ships at 09:00 ALERT 09-23: 63% above the 3 days before WHY: GROUP THE SAME LOG BY PROMPT support@v3: 128 calls 3 chunks, 417 tokens in, $0.0052 support@v4: 32 calls 13 chunks, 1,014 tokens in, $0.0093 v4 sends every chunk, not the top 3. 417 × $5 / 1M = $0.0021 1,014 × $5 / 1M = $0.0051 +$0.0030 a call from input alone; two cut-off answers add the rest. At 5,000 questions a day: $26 a day becomes $47.
The alert says something changed. The prompt and chunk fields say what.

The sample’s dollars are small because it’s only 40 questions a day. At 5,000 a day, $26 becomes $47. That happens every day, until someone notices.

Here’s the alert rule:

for i, day in enumerate(names[1:], start=1):
    before = [days[d]["per_call"] for d in names[max(0, i - 7):i]]
    baseline = sum(before) / len(before)
    now = days[day]["per_call"]
    if baseline and now > baseline * (1 + jump):  # jump = 0.30
        alerts.append(f"ALERT {day}: ...")

Alert on cost per call, not total cost. Total cost also rises when more customers use the bot, and that’s good news. Per-call cost only moves when the calls themselves changed.

Start the threshold at 30%. That’s tight enough to catch a prompt that doubled. It’s also loose enough that one long answer doesn’t page anyone. On the 22nd, a single cut-off reply pushed cost per call up 11%, which stays under the line.

Getting this balance right matters. An alert that fires every other day gets muted, and then it catches nothing.

For the dashboard, start with five numbers per day:

  • calls
  • cost per call
  • p95 latency
  • the share of calls that were not ok
  • the review fail rate from step 5

If the bot streams (article 02), add time to first token (TTFT). That’s the wait before the first word appears, and it’s the delay users actually feel.

Step 5: Pick the calls a person should read

Numbers catch expensive answers and cut-off answers. They don’t catch wrong ones.

Say an answer claims the reset link lasts 24 hours, when the help article says 30 minutes. That answer has normal tokens, normal cost and "end_turn". Nothing in the numbers stands out.

You find wrong answers by reading them. You can’t read them all, so you sample: you pick a subset to read.

def pick_for_review(calls: list[dict], rate: float = REVIEW_RATE) -> list[dict]:
    return [c for c in calls if not_ok(c) or int(c["trace_id"][:8], 16) / 0xFFFFFFFF < rate]

That picks two groups of calls:

  • Every call that went wrong. Each one is rare and worth a look.
  • About 5% of the normal ones.

The 5% comes from the trace id, not random.random(). That way re-runs pick the same calls, and a trace is either wholly in or wholly out:

For review: 17 calls (5 didn't end normally, the rest are a 5% sample)
  2026-09-21T12:52  52e3f4b5  support@v3  refusal
  2026-09-22T12:18  8f40f198  support@v3  RateLimitError
  2026-09-23T10:34  e0d95f41  support@v4  max_tokens
  ...

e0d95f41 looks like the customer from the opening. Pull every span of that trace:

$ python report.py --trace e0d95f41
Trace e0d95f41, 2026-09-23T10:34:00+00:00
  support.answer     12,456 ms  u_4cb749ec5114
    retrieve            242 ms  k=13  top 0.35  account-recovery#1, account-recovery#2, ...
    llm.call         12,211 ms  support@v4  1,028 in / 1,024 out  max_tokens  $0.0307

The answer ran into the 1,024-token limit after 12 seconds, with 13 excerpts in its prompt. Both cut-off answers on the 23rd came from v4. So it’s most likely the same change as the cost spike, found from a different direction.

The fix is to roll back to v3. Then add this question to the eval set, so the next prompt change is tested against it.

The normal 5% is the part people skip. Read them yourself, or hand them to the judge from article 09 and track its fail rate daily.

That fail rate is how you notice drift. Drift is quality slowly getting worse with no deploy to blame. It happens because customers start asking about something new, or because the help center changed.

Each failure you find becomes a question in the golden set from article 08. The golden set is the labelled questions your evals run on. Once a failure is in there, it can’t ship twice.

How big should the sample be?

Big enough to read. In the sample, 5% is 12 of 155 normal calls. At 5,000 questions a day it’s 250. That’s too many for a person, and about right for a judge.

A workable default is to review three groups:

  • every not-ok call
  • every answer a user marked unhelpful
  • a fixed number of random ones per day, say 20 for a person or a few hundred for a judge

The fixed number keeps the effort steady as traffic grows.

Step 6: Keep personal data out of the logs

Customers type personal data into support bots: “My login is sam@northwind.example and I’m locked out, call me on +31 6 1234 5678.”

If you log that raw, it gets copied into your log search, your vendor’s servers and every downloaded log file. It stays there for as long as the logs live. Under GDPR, personal data in a log is still personal data, and that includes deletion requests.

The example follows three rules:

ANSWER_QUESTION writes two records user id, via hash_user() sam@northwind.example → u_daf0139f40bc text, via redact() sam@northwind.example → [email] SPANS.JSONL ids, tokens, cost, ms no question or answer keep 90 days TRANSCRIPTS.JSONL question + answer, redacted, by trace_id keep 7 days REPORT.PY $/call per day and per prompt p95 ms, not ok PICK FOR REVIEW every not-ok call + 5% by trace id 17 of 160 ALERT $/call more than 30% above the days before READ IT a person, or the judge from article 09 Delete text sooner than numbers: the numbers make the dashboard, the text is for debugging this week. Every failure you find becomes a golden-set question (article 08).
Delete text sooner than numbers: the numbers make the dashboard, the text is for debugging this week.

Hash user ids with a secret key. The spans need to know which calls came from the same user. They don’t need to know who that user is:

def hash_user(user_id: str) -> str:
    key = os.environ.get("LOG_HASH_KEY", "dev-only-not-secret").encode()
    return "u_" + hmac.new(key, user_id.encode(), hashlib.sha256).hexdigest()[:12]

An HMAC is a hash that needs a secret key. The key is the point. A plain SHA-256 of an email looks anonymous, but anyone can hash a list of known emails and match them.

Without the key, u_daf0139f40bc can’t be traced back to Sam. With the key, you can still find Sam’s calls when Sam complains.

Redact the text you keep. Before the question and answer are stored, redact() swaps out two kinds of pattern. Emails become [email]. Long runs of digits, like phone and card numbers, become [number].

Store text separately, and delete it sooner. Spans never hold question or answer text. The redacted text goes to transcripts.jsonl instead, keyed by trace_id so review can join the two.

Keep spans for 90 days and text for 7. The two get used differently. Complaints about an answer arrive within days, but cost trends need months. Real log stores let you set retention per index or bucket.

Regex redaction has a limit. It misses anything that isn’t an obvious pattern, so a name, an address or “my account number is four four one two” gets through. Treat redaction as a way to reduce risk. The controls that actually hold are short retention and limited access to transcripts.

Before you ship: evals in CI

Everything above happens after a change is live. The other half happens before it ships.

That half is the eval harness from article 08, run in CI. CI is the set of checks your repo runs on every pull request. Run the evals whenever a change touches a prompt, the retrieval settings or the model. They would have shown v4’s longer prompts and answers before a customer did.

The two halves feed each other. Observability catches what the eval set didn’t think to ask, and those failures go back into the eval set.

Try it yourself

The example contains the wrapper, the trace, the report and the four-day sample log. It runs offline. If you set ANTHROPIC_API_KEY, main.py also sends one real call.

Download the runnable example (zip)

cd 11-production-ai-observability
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python main.py        # one traced question, written to logs/
python report.py      # the four-day sample

Then try these:

  1. Run python main.py "My login is sam@northwind.example and I'm locked out", then open the last line of logs/transcripts.jsonl. The email is [email], and no span mentions it.
  2. Set ALERT_JUMP = 0.05 in report.py and run the report. The 22nd alerts too, because of one long answer. Put it back to 0.30 afterwards.
  3. Change MODEL in main.py to a name that isn’t in PRICES. Run python main.py, then python report.py logs/spans.jsonl. cost_usd is null, and the report says the call has no price instead of showing a cheap day.

pip install pytest && pytest -q runs the offline tests. They check:

  • the record fields
  • the cost maths
  • that failed calls are still logged
  • that no email appears in either log
  • that the alert fires on the 23rd only

Common beginner mistakes

  • Treating 200 OK as success. A cut-off, wrong or expensive answer is still a 200. Log stop_reason and cost, and read a sample.
  • Logging only “request in, response out”. Without chunk ids and a span per step, you can’t tell a retrieval problem from a model problem.
  • No prompt version in the log. When answers change, you can’t tell whether the prompt did.
  • Raw questions in long-lived logs. Hash user ids and redact text. Keep text for days, not months.

Questions you will face in production

“Hosted tool or our own logs?” Start from what you already run. If that’s Datadog, Honeycomb or Grafana, send OpenTelemetry spans there with the LLM fields. If not, a hosted LLM tool (LangSmith, Langfuse, Phoenix, Helicone) gives you a trace viewer on day one.

Either way, the fields matter more than the tool. Get the record right and you can switch later.

“Answers suddenly got worse. Where do I start?” Start by looking for a change. Group the last few days by prompt version and model, and look for one on the day it started.

Then check top_score and the chunk ids on the bad calls. Wrong articles mean the problem is retrieval. Right articles with a wrong answer mean it’s the prompt or the model.

If nothing changed on your side, read 30 recent answers from the review sample.

“What should page someone at night?” Very little. Two things are worth waking someone for:

  • The error rate is above normal for 10 minutes. That means the API is down or rate-limiting you.
  • Cost per call is far above normal. That means a runaway prompt.

Drift and p95 creep go in a daily summary. Nobody fixes those at 3am.

Check your understanding

Cost per call is flat, but the total bill doubled this month. Is something broken?

Probably not. The same cost per call with twice the bill means twice the calls. More customers are using the bot, and that isn’t a bug. It’s why the alert watches cost per call.

A customer says the bot told them the reset link lasts 24 hours. Which fields do you look at, and in what order?

Start with their trace, found by hashed user id and time. Then check chunk_ids on retrieve.

If reset-password#1 (which says 30 minutes) wasn’t retrieved, it’s a retrieval problem. If it was retrieved, the model misread it. Note prompt and model, and add the question to the eval set.

The transcript shows what they saw, as long as it’s under 7 days old.

A teammate samples spans with random.random() < 0.05. What goes wrong?

Each span gets sampled on its own. So you keep an llm.call without its retrieve, or the reverse. Sampling by trace id keeps traces whole and repeatable.

Random-only sampling also drops most rare failures. That’s why every not-ok call is kept on top of the sample.

You switch the bot to a new model and forget to add it to PRICES. What does the report show?

cost_usd is None for those calls, and the report says how many have no price. With a $0 default, the day would look cheaper, and nobody would notice until the invoice.

What to remember

  • A 200 OK proves nothing about an LLM answer. For every call, log the prompt version and fingerprint, the model from the response, tokens, cost, stop_reason, chunk ids and latency.
  • A trace ties one request’s steps together. Every span shares a trace_id and has its own parent_id. Write spans in finally, so failures are logged too.
  • Compute cost when you write the record. An unknown price means None, never $0. Alert on cost per call, not total spend.
  • Read every call that went wrong, plus a small sample of normal ones picked by trace id. Feed the failures into the eval set.
  • Hash user ids with a key and redact text. Keep text for days, while the numbers stay for months.

What to study next

You can now see what each call costs and why. The next step is bringing that number down. Article 12: Cost Optimization in Production AI covers model routing, prompt caching and shorter outputs. Each one is measured with the kind of per-call cost records you just built.

Further reading

Where this article comes from. This is a synthesis of common practice in AI engineering as of 2026, not a citation of any single paper. The sources above are where the broad mechanics and specific numbers come from. If you find an error or have a better source for a claim, send me a note. The article gets fixed within a day.


Auto-marks when you reach the end. Click to toggle.