AI Foundations0% complete
0%

Chapter 20 of 2525 chapters remaining

Saved on this device. Mark a chapter complete after reading.

MODULE 4 · LESSON 20 · 12 MIN

Observability and Monitoring for AI Applications

By Siten Sanghvi · Published · Updated

An AI application can return a normal HTTP 200 on every request and still give wrong answers, so uptime and HTTP error rate alone cannot tell you whether it works. Observability means recording enough about each request, as a few numbers, a trace of its steps and carefully chosen content, that you can see from the outside what happened and why. Record what you need to debug and measure, treat prompts and outputs as sensitive data, and alert on what users feel rather than on every internal cause.

Google's site reliability engineering (SRE) book counts a 200 response carrying the wrong content as an error. In a hypothetical service with 1,000,000 requests a month where 5% of answers are bad, that is 50,000 bad answers, and none shows up as an HTTP error.

Logs, metrics and traces

The OpenTelemetry primer separates three kinds of record.

Record What it is Best for Privacy cost
Metric A number aggregated over time, such as error rate or tokens per minute Noticing that something changed; alerting Low: no content
Log A timestamped message from a component Detail about one event Grows with the message content
Trace The path of one request through its steps Finding which step went wrong Grows with step attributes

A span is one unit of work in a trace (a retrieval, model call, tool call or validation check) with timing and attributes. A trace is the spans of one request, under a root span covering all of it.

What to record about an AI request

  • Identity. Your own request ID, the provider's, and the feature. OpenAI recommends logging request IDs in production; Anthropic returns a request-id header and asks for it in support tickets.
  • The model call. The exact model identifier called, token counts (input, output, cached), why generation stopped, retries, errors (type), and for streaming the time to first token (BT-L17).
  • The steps. Documents retrieved (IDs and versions), tool calls and their outcomes, validation results, guardrail triggers (BT-L18).
  • Quality. Scores for a sample of outputs (BT-L19), and user feedback or what the user did next. They are pointers to check against traces: only some users react, and a retry may mean a changed need.
  • Content (prompts and outputs). Not by default; see below.

Check how your provider counts tokens: Anthropic's input_tokens excludes tokens read from or written to the prompt cache; add its cache fields for the total. OpenTelemetry's conventions say input-token totals should include cached tokens. Summing the wrong field undercounts.

Cost per request is derived from token counts and your provider's prices (BT-L16). Provider reports reconcile the bill but lag: Anthropic's Usage and Cost Analytics API (beta, admin access) groups usage by model, workspace and API key, and its data typically refreshes within 4 hours and can take up to 24. To attribute spend to a feature, tag each request with it, or use separate keys or workspaces per feature. Alert on your own counts, not the report.

One request, one trace (illustrative)

A support assistant tells a customer refunds are allowed within 30 days; the current policy says 14. The synthetic trace:

Span Time (ms) What the trace recorded
request (root) 2,410 feature refund-help, model identifier, request IDs
retrieval 180 3 documents returned; top hit refund-policy v1
model call 1,900 1,850 input tokens, 120 output tokens, stopped normally
output check 40 format check passed

The child spans total 180 + 1,900 + 40 = 2,120 ms, so 290 of the 2,410 ms is outside any span (queueing, network, your own code). At made-up prices of $3 per million input tokens and $15 per million output tokens, the call cost 1,850 × $3 / 1,000,000 + 120 × $15 / 1,000,000 = $0.00555 + $0.0018 = $0.00735.

Reading it: retrieval returned an outdated document, the likeliest cause since the answer matches it, and the output check only tests format. The fix is in the index (BT-L13 covers retrieval), and the failure becomes an eval case (BT-L19). IDs and versions were enough to see this; reproducing the exact question needs content.

EXHIBIT 20 / OBSERVABILITY

Explore the mechanism

Healthy API. Wrong answer.

Compare what a trace explains with what it exposes.

Healthy API. Wrong answer.Retrieval180Model call1900Check40Outside spans290Handpicked example values · inspect exact values below
Total time2410 ms
Recorded token cost$0.00735
Logging exposureMinimal: IDs may identify users.

Why was the answer wrong?

Timing alone cannot explain the wrong answer.

Inspect the example data and reasoning
Healthy API. Wrong answer. — current illustrative state
ElementWhat to notice
Retrieval180 ms
Model call1900 ms
Check40 ms
Outside spans290 ms
Tokens1850 input / 120 output

Illustrative monitoring layers. Thresholds depend on your service objectives; minimize or redact sensitive logging.

Read the mechanism without interacting
Infrastructure
Track availability, errors, queueing and latency.
Request
Track token usage, version, time to first token and cost estimates.
Outcome
Use review and task-specific evaluations to spot unsupported or unhelpful answers.

An API can return HTTP 200 while quoting the wrong policy. Request traces help locate it; quality review detects the wrong claim.

Try explaining it: Which signal would reveal a fluent but unsupported answer when uptime stays green?

OpenTelemetry's GenAI semantic conventions are a shared naming scheme: spans for model calls, retrieval and tool execution, plus token metrics. On 2026-11-09 the pages were marked Development and had moved to a separate repository. OpenTelemetry's maturity definition, written for software components, says a Development component should not be used in production and may be removed without prior notice. Treat the conventions as a pilot or design reference, and keep names behind one mapping layer.

OpenTelemetry's sampling guide says head sampling decides early and cannot guarantee that traces with errors are kept; tail sampling can keep every error or slow trace but is harder to run. A tail rule can also keep traces flagged by a check, such as a guardrail, if the flag is recorded on the trace.

What not to log, and how long to keep the rest

Prompts and outputs can hold personal or confidential data. The OpenTelemetry conventions call them sensitive and large, and say instrumentation should not capture them by default. The same opt-in covers tool arguments, results and retrieval queries. For large or sensitive data they recommend storing content externally and recording references, allowing separate access controls.

  • Collect less. GDPR, the EU data-protection law, requires personal data to be limited to what is necessary for the purpose (Article 5(1)(c)) and kept identifiable no longer than necessary (5(1)(e)). Whether it applies to your logs is a legal question; see BT-L22.
  • Keep secrets out. OWASP's logging guidance lists data usually removed, masked, hashed or encrypted: passwords, access tokens, payment card data, session IDs and sensitive personal data.
  • Pseudonymised is not anonymous. GDPR (Recital 26) says data attributable to a person with additional information is still information on an identifiable person. An unkeyed hash of a guessable value, such as an email address, can be matched by hashing guesses.
  • Limit retention and access. Set deletion periods, restrict who can read content, and cover backups. Providers keep data too: OpenAI's abuse-monitoring logs up to 30 days by default (checked 2026-11-09). Anthropic's pages differ (checked 2026-11-13): its privacy page says API inputs and outputs are deleted within 30 days; its API retention page says content is not retained by default except for Covered Models, which require 30 days. None limits your own copy.

Default: metadata, IDs and versions always, with user or session identifiers kept out or pseudonymised and under the same limits; content only for flagged, sampled or consented requests, redacted, in a separate short-retention, access-limited store.

Alert on symptoms, diagnose with causes

Google's SRE guidance says to ask what is broken (the symptom) and why (a cause), and to page on symptoms. It names four golden signals: latency, traffic, errors and saturation. Every page should be actionable; too many cause fatigue.

  • Page on: users getting errors or timeouts, slow first tokens, a sustained fall in sampled quality scores.
  • Ticket, or page by your own policy: spend ahead of budget, a jump in refusals or guardrail blocks.
  • Dashboard, not page: retrieval hit counts, retry rates, queue depth, tokens per request.

This lesson found no standard AI thresholds; take them from your own baseline and targets (BT-L17 covers latency measures and SLOs). Sampled quality scores move by chance, so alert on sustained change.

Drift and regressions

Drift here means production behavior or inputs have moved away from the reference you measured at launch. One 2025 taxonomy paper names three kinds: version drift (the provider changes the model), data drift (inputs change) and behavior drift (same prompt, different output). It is conceptual, not a measurement study.

A 2023 study compared March and June versions of GPT-4 and GPT-3.5: GPT-4's accuracy on a prime-number test fell from 84% to 51%, but its numbers were all primes, which critics read as changed default answers, not lost skill. It shows behavior can change, not how often. OpenAI's docs say prompting behavior between snapshots is subject to change and advise pinned model versions and evals. A model name can also be an alias the provider repoints: Anthropic documents this for earlier models. A logged name alone may not reveal a change.

This lesson's suggested practice, not a standard:

  1. Record the model name you requested and, where the response reports one, the model that ran.
  2. Rerun the BT-L19 eval set on a schedule and after any change, and compare with a stored baseline.
  3. Compare a recent window of inputs with a reference window (topics, lengths, retrieved documents). Statistical shift tests exist but were studied on image data (Rabanser and colleagues, 2018); treat a drift number as a prompt to look.
  4. Turn confirmed production failures into new eval cases.

Limits: an input shift is not a quality drop, and the eval set only catches what it contains.

Try it

A paper exercise for a support assistant. Write the fields recorded on every request, two redactions, one symptom alert (signal, baseline, responder), and the first trace step to open for a wrong-fact complaint. Self-check: request IDs, model identifier, token counts and document IDs, content only by exception; redactions from the OWASP list, such as passwords or card numbers; retrieved sources first.

The takeaway

For an application built on a hosted model, a 200 response does not show the answer was right. Record request IDs, model name, token counts, step facts such as document versions, and outcomes; keep content a small, protected, short-lived exception. Alert on symptoms users feel, diagnose with traces, and catch drift by rerunning your eval set against a baseline.

Up next

Build vs. Buy: Foundation Models, Fine-Tuning, or RAG?: using a model as is, adding retrieval, or fine-tuning.

VISUAL FIELDNOTES / 20

Keep the big picture.

A one-page visual companion. Save it, print it, or explain it to someone else.

Compare what a trace explains with what it exposes. Illustrative monitoring layers. Thresholds depend on your service objectives; minimize or redact sensitive logging.View the full-size sheet ↗

Healthy API. Wrong answer.

Compare what a trace explains with what it exposes.

One US Letter page · Vector artwork · Fits A4 when printed to fit

Read the key points as text
Infrastructure
Track availability, errors, queueing and latency.
Request
Track token usage, version, time to first token and cost estimates.
Outcome
Use review and task-specific evaluations to spot unsupported or unhelpful answers.

Remember: Track availability, errors, queueing and latency.

Try it: An API can return HTTP 200 while quoting the wrong policy. Request traces help locate it; quality review detects the wrong claim.

Recall: Which signal would reveal a fluent but unsupported answer when uptime stays green?

OPTIONAL CHECK

Check your understanding.

The optional check requires JavaScript. You can continue reading the lesson.

YOUR LEARNING

Keep your place.

Your progress is saved on this device.