LESSON 70 ยท PRODUCTION GENAI

Monitoring

Learn how to observe a production GenAI application so you can understand what users experience, detect failures, measure quality, control cost, and improve the system safely.

20 min readโ€ขIntermediateโ€ขPythonโ€ขProduction

How GenAI Monitoring Works

User RequestPrompt + context
AI PipelineRAG + model + tools
TelemetryLogs + traces
MetricsLatency + cost + errors
QualityFeedback + evaluation
Alert & ImproveDetect + act
iImportant: Monitoring is more than checking whether the API returned HTTP 200. A GenAI request can succeed technically while still producing a poor, unsafe, expensive, or irrelevant answer.
1

What Is Monitoring?

Monitoring is the continuous collection and analysis of signals from your AI application so the team can understand system health and user experience.

Key idea:Production monitoring should answer four questions: Is the system working? Is it fast enough? Is it affordable? Is it producing useful results?
2

Why GenAI Monitoring Is Different

Traditional web applications often have deterministic outputs. GenAI systems introduce probabilistic behavior, model changes, retrieval quality, tool decisions, and variable token usage.

  • Variable latency: Response time changes with model, context, and output length.
  • Variable cost: Token usage can change from request to request.
  • Quality drift: A technically successful response can become less useful.
  • Retrieval failures: The model may receive incomplete or irrelevant context.
  • Tool failures: External APIs can fail independently of the model.
  • Model changes: Provider updates can change behavior without application code changes.
3

What Should You Monitor?

A practical monitoring strategy combines infrastructure, application, model, retrieval, security, and quality signals.

ReliabilityErrors, timeouts, retries, availability, and failed tool calls.
LatencyTime to first token, total response time, and slow dependencies.
CostInput tokens, output tokens, model usage, and spend per request.
QualityUser feedback, evaluation scores, groundedness, and task success.
RetrievalTop-K results, scores, empty retrievals, and source coverage.
SafetyGuardrail decisions, blocked requests, policy violations, and escalations.
4

Logs, Metrics, and Traces

These three telemetry types answer different questions and work best together.

Logs

Detailed events such as request validation, model calls, tool errors, and policy decisions.

Metrics

Aggregated numbers such as p95 latency, error rate, token usage, and cost.

Traces

The full path of one request across retrieval, models, tools, and downstream services.

5

Design a Useful Request ID

Give each user request a correlation ID so a support engineer can follow the request across services.

</> Python
from uuid import uuid4


def start_request(user_id: str) -> dict:
    return {
        "request_id": str(uuid4()),
        "user_id": user_id,
    }


context = start_request("user-123")
print(context["request_id"])

Use the request ID in application logs, model-call records, tool traces, and user-facing support workflows.

6

Monitor Latency

Track latency as a distribution rather than only an average. p50 shows the typical request, while p95 and p99 expose slow experiences.

TTFTTime until the first generated token appears.
Generation timeTime spent producing the remaining output.
Total latencyEnd-to-end time from request to completed response.
TargetFast UX
p50Typical
p95Slow tail
p99Worst tail
AlertThreshold
7

Monitor Errors and Retries

Separate error types so an increasing error rate leads to the correct action.

Model errors

Provider errors, invalid requests, unavailable models, or quota failures.

Retrieval errors

Vector database failures, empty results, or metadata-filter problems.

Tool errors

Timeouts, authentication failures, validation failures, and external API errors.

Application errors

Bad configuration, code exceptions, serialization issues, or downstream failures.

Also track retry counts. A request that eventually succeeds after several retries may hide a reliability problem and increase cost and latency.

8

Monitor Token Usage and Cost

Token usage is one of the most important operational signals for GenAI applications.

  • Input tokens per request
  • Output tokens per request
  • Total tokens by model
  • Average cost per request
  • Cost by feature or tenant
  • Daily and monthly spend
Watch for anomalies:A sudden increase in input tokens can indicate oversized retrieval context, prompt growth, an agent loop, or unexpected user input.
9

Python: Record Request Metrics

A simple application can start by recording duration, token counts, and status for every request.

</> Python
import time


def observe_request(run_model):
    started = time.perf_counter()
    status = "success"

    try:
        result = run_model()
        return result
    except Exception:
        status = "error"
        raise
    finally:
        duration_ms = (time.perf_counter() - started) * 1000
        print({
            "status": status,
            "duration_ms": round(duration_ms, 2),
        })

In production, send these measurements to your telemetry system instead of printing them to stdout.

10

Monitor Retrieval Quality

For RAG systems, monitoring the model alone is not enough. You also need to understand what context was retrieved.

Empty retrievals

Count requests where no useful documents were returned.

Low scores

Track similarity-score distributions and unusual drops.

Source coverage

Record which sources and document types contribute to answers.

Retrieval latency

Measure vector search, filtering, reranking, and document loading separately.

Keep enough trace metadata to investigate retrieval failures, but avoid storing sensitive document contents unnecessarily.

11

Monitor Tool Calls

Agents can create operational risk because one user request may trigger several external actions.

Tool name

Which tool was selected?

Arguments

Were arguments valid and within policy?

Duration

How long did the tool take?

Result

Did it succeed, fail, or require retry?

RequestStart trace
DecisionSelect tool
ValidationCheck policy
ExecutionCall API
ResultRecord outcome
12

Monitor AI Quality

Technical health does not prove that the answer is useful. Add quality signals appropriate to the application.

User feedback

Track thumbs-up/down, ratings, corrections, and repeated questions.

Task success

Measure whether the user's intended task was completed.

Groundedness

Evaluate whether RAG answers are supported by retrieved evidence.

Human review

Sample important or uncertain responses for expert evaluation.

13

Online vs Offline Evaluation

Use both real production signals and controlled evaluation datasets.

Online monitoring

Observes live traffic, latency, cost, errors, feedback, and guardrail decisions.

Offline evaluation

Runs a fixed test set to compare prompts, models, retrieval changes, or code versions.

Best practice

Use offline tests before release and online monitoring after release to detect real-world drift.

14

Monitoring Guardrails and Safety

Record guardrail outcomes so you can identify attacks, false positives, and policy changes.

  • Blocked input count
  • Blocked output count
  • Prompt injection detections
  • PII redaction events
  • Tool approval requests
  • Human escalations
Privacy rule:Monitoring data can itself become sensitive. Minimize content collection, redact secrets, restrict access, and define retention periods.
15

What Belongs in a Trace?

A useful trace captures enough metadata to reconstruct a request without turning observability into a copy of your entire data store.

Request metadataRequest ID, timestamp, feature, model, and application version.
Model metadataModel name, token counts, finish reason, and latency.
Retrieval metadataQuery ID, top-K, scores, filters, and source identifiers.
Tool metadataTool name, validation result, duration, and status.
Quality metadataFeedback, evaluation result, or task outcome.
Security metadataGuardrail decision, policy version, and escalation status.
16

Alerting: When Should You Be Notified?

Alerts should point to actionable problems rather than every small fluctuation.

Symptomp95 latency suddenly increases.
ThresholdDefine a sustained or significant change.
ActionInvestigate the model, dependency, or deployment.

Useful alerts include high error rates, provider failures, abnormal spend, latency regressions, retrieval failures, and spikes in safety events.

17

Dashboards That Matter

A production dashboard should make the health of the application understandable in seconds.

Traffic

Requests, active users, requests by feature, and success rate.

Performance

p50/p95/p99 latency, TTFT, and dependency latency.

AI usage

Model mix, tokens, tool calls, retrieval volume, and cache hit rate.

Business quality

Task success, user feedback, escalations, and important failure categories.

18

Monitoring a Multi-Agent System

For multi-agent applications, one request can become a tree of agent calls. Track parent and child spans so you can see which agent caused latency, cost, or failure.

Example:A research request might call a planner, three research agents, a summarizer, and a reviewer. Monitoring should show the complete trace and the contribution of each agent.
19

Detecting Drift

Monitor changes in traffic, prompts, retrieved sources, model behavior, and user outcomes over time.

Input drift

User questions or languages change.

Data drift

Your knowledge base changes.

Model drift

Provider or model versions change behavior.

Quality drift

Task success or user satisfaction declines.

20

Common Monitoring Mistakes

  • Monitoring only server uptime
  • Tracking average latency but not p95/p99
  • Ignoring token and cost anomalies
  • Logging sensitive prompts and documents by default
  • Collecting logs without request correlation IDs
  • Measuring model calls but not retrieval or tools
  • Alerting on everything without clear actions
  • Never connecting technical metrics to user outcomes
21

Mini Project: Build a GenAI Monitoring Layer

Create a small Python wrapper around your AI pipeline that records a request ID, latency, status, token usage, retrieval count, tool-call count, and quality feedback.

</> Python
from dataclasses import dataclass
from time import perf_counter
from uuid import uuid4


@dataclass
class GenAIMetrics:
    request_id: str
    duration_ms: float
    status: str
    retrieved_docs: int
    tool_calls: int


def monitor(run_pipeline, retrieved_docs=0, tool_calls=0):
    request_id = str(uuid4())
    started = perf_counter()
    status = "success"

    try:
        result = run_pipeline()
        return result
    except Exception:
        status = "error"
        raise
    finally:
        metrics = GenAIMetrics(
            request_id=request_id,
            duration_ms=(perf_counter() - started) * 1000,
            status=status,
            retrieved_docs=retrieved_docs,
            tool_calls=tool_calls,
        )
        print(metrics)

Extend this pattern with your telemetry backend, token counts, model metadata, trace spans, and privacy-safe quality signals.

22

Monitoring Checklist

ReliabilityErrors, timeouts, retries, provider health.
PerformanceTTFT, total latency, p95, p99.
CostTokens, model usage, spend, anomalies.
RAGRetrieval count, scores, latency, source coverage.
AgentsSteps, tools, child traces, failures.
QualityFeedback, task success, evaluations, escalations.
23

Production Monitoring Architecture

A mature system connects application telemetry to dashboards, alerts, evaluation, and an improvement loop.

AI AppGenerate
TelemetryCollect
StorageRetain
DashboardUnderstand
AlertAct

Monitoring should feed engineering decisions: tune prompts, change retrieval, optimize models, fix tools, improve guardrails, and update evaluation sets.

30-Second Recap

01Monitor more than uptime: include latency, cost, errors, retrieval, tools, safety, and quality.
02Use logs, metrics, and traces together to investigate production behavior.
03Track p50/p95/p99 latency and token usage instead of relying on averages alone.
04Correlate every request with an ID so failures can be reconstructed.
05Protect monitoring data with redaction, access control, and retention policies.
06Connect live monitoring with offline evaluation and user outcomes.

Key Takeaways

  • GenAI monitoring must cover both technical health and AI quality.
  • Measure latency, errors, tokens, cost, retrieval, tools, safety, and user outcomes.
  • Use request IDs and traces to understand the complete execution path.
  • Monitor distributions such as p95 and p99 rather than only averages.
  • Do not log sensitive prompts, documents, secrets, or outputs unnecessarily.
  • Use alerts for actionable problems and evaluation to detect quality regressions.
  • Turn monitoring signals into an engineering feedback loop for continuous improvement.
?

Quick Quiz

1. Is HTTP 200 enough to prove a GenAI request was successful?

No. The response can still be irrelevant, unsafe, ungrounded, or incorrect.

2. Why use p95 and p99 latency?

They reveal slow-tail experiences that an average can hide.

3. Why is a request ID useful?

It connects logs and traces across retrieval, models, tools, and services.

4. What should you monitor in RAG?

Retrieval success, scores, source coverage, latency, filters, and downstream answer quality.