Monitoring Quality, Cost and Latency

Updated · 10 min read
hardPython 3.13aimonitoringllmopsloggingalertscost

Monitoring an AI system means recording what it does in production and watching a few key numbers, so that problems are found by you, not by angry users. For AI the numbers are quality (are answers right?), cost (how much does each answer cost?), latency (how long do users wait?) and safety. Unlike a normal bug, a drop in AI quality rarely causes an error message, so it has to be measured on purpose.

This lesson completes the chapter's checkpoint: deploy Campus Helper with logging, a cost dashboard and an alert when quality drops.

What to Monitor

SignalDescription
Request logIt is used to store each question, answer, version, time taken, tokens and cost, without personal data
Offline qualityIt is used to rerun the fixed evaluation set every night and after every change
Online quality signalsDeclines, low similarity scores, user ratings, retries and complaints
Cost per interactionTokens in and out times the price; total per day and per 1,000 requests
LatencyMedian and 95th percentile response time; the slowest users matter
AlertsIt is used to notify a person automatically when a number crosses a limit

Example: The Checkpoint

The programs in this chapter need pip install fastapi httpx sentence-transformers scikit-learn torch transformers. Several use faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.

This program runs Campus Helper as a FastAPI service that logs every request to SQLite, sends it three days of traffic, runs the evaluation set every night, and prints a dashboard. On day 2, a new version 1.1 raises the decline threshold from 0.35 to 0.55, perhaps to cut wrong answers. On day 3, it is rolled back.

To show the method, the program estimates cost as if each answer were written by a hosted model at example prices of $0.25 per million input tokens and $1.25 per million output tokens, with 400 extra input tokens for instructions and documents, and counts tokens with the embedding model's tokenizer. Replace these with your provider's real prices and token counts.

Log everything, evaluate nightly, alert on drops, roll back fast
Python
import json
import os
import sqlite3
import time
 
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
 
DECLINE = "Sorry, I can only answer questions about this school. Please contact the school office."
PRICE_IN, PRICE_OUT = 0.25 / 1e6, 1.25 / 1e6        # EXAMPLE prices per token for a hosted model; use your provider's
BASELINE, ALERT_DROP = 44, 3                         # the evaluation score at launch, and the drop that raises an alert
 
texts = [item["text"] for item in json.load(open("faq.json"))]
cases = json.load(open("eval_set.json"))
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
 
if os.path.exists("campus.db"):
    os.remove("campus.db")                           # start each run with an empty log
with sqlite3.connect("campus.db") as db:
    db.execute("""CREATE TABLE log (day INTEGER, version TEXT, question TEXT, answer TEXT, declined INTEGER,
                  latency_ms REAL, tokens_in INTEGER, tokens_out INTEGER, cost REAL)""")
 
config = {"version": "1.0", "threshold": 0.35, "day": 1}
app = FastAPI()
 
class Question(BaseModel):
    question: str
 
def answer(question, threshold):
    scores = vectors @ model.encode(question, normalize_embeddings=True)
    best = int(scores.argmax())
    return texts[best] if scores[best] >= threshold else DECLINE
 
def tokens(text):
    return len(model.tokenizer.tokenize(text))
 
@app.post("/ask")
def ask(q: Question):
    start = time.perf_counter()
    reply = answer(q.question, config["threshold"])
    latency = (time.perf_counter() - start) * 1000
    t_in, t_out = tokens(q.question) + 400, tokens(reply)      # + 400 for instructions and documents
    with sqlite3.connect("campus.db") as db:        # one short connection per request
        db.execute("INSERT INTO log VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                   (config["day"], config["version"], q.question, reply, reply == DECLINE, latency,
                    t_in, t_out, t_in * PRICE_IN + t_out * PRICE_OUT))
    return {"answer": reply}
 
def nightly_evaluation():
    answered = declined = 0
    for case in cases:
        reply = answer(case["question"], config["threshold"])
        if case["must_contain"] is None:
            declined += reply == DECLINE
        else:
            answered += case["must_contain"] in reply
    passed = answered + declined
    alert = passed <= BASELINE - ALERT_DROP
    print(f"  nightly evaluation: {passed}/50 (answered {answered}/40, declined {declined}/10)"
          + ("  ALERT: quality dropped, page the on-call person" if alert else "  ok"))
 
client = TestClient(app)
releases = [(1, "1.0", 0.35), (2, "1.1", 0.55), (3, "1.0", 0.35)]   # day 2: someone raises the threshold
for day, version, threshold in releases:
    config.update(day=day, version=version, threshold=threshold)
    print(f"Day {day}: version {version} (threshold {threshold})")
    for case in cases:                                               # the day's traffic: parents' questions
        client.post("/ask", json={"question": case["question"]})
    nightly_evaluation()
 
print("\nDashboard (from the log table)")
print("day  version  requests  declined  tokens  est. cost  cost per 1,000")
rows = sqlite3.connect("campus.db").execute("""SELECT day, version, COUNT(*), AVG(declined),
    SUM(tokens_in + tokens_out), SUM(cost) FROM log GROUP BY day ORDER BY day""")
for day, version, n, declined, toks, cost in rows:
    print(f"{day:3}  {version:7}  {n:8}  {declined:8.0%}  {toks:6,}  ${cost:8.4f}  ${cost / n * 1000:8.2f}")
Output
Day 1: version 1.0 (threshold 0.35)
  nightly evaluation: 44/50 (answered 35/40, declined 9/10)  ok
Day 2: version 1.1 (threshold 0.55)
  nightly evaluation: 40/50 (answered 30/40, declined 10/10)  ALERT: quality dropped, page the on-call person
Day 3: version 1.0 (threshold 0.35)
  nightly evaluation: 44/50 (answered 35/40, declined 9/10)  ok
 
Dashboard (from the log table)
day  version  requests  declined  tokens  est. cost  cost per 1,000
  1  1.0            50       22%  21,135  $  0.0060  $    0.12
  2  1.1            50       40%  21,164  $  0.0061  $    0.12
  3  1.0            50       22%  21,135  $  0.0060  $    0.12

Explanation:

  • Every request is logged with the day, version, question, answer, whether it declined, latency, tokens and estimated cost. A real log would store a user ID only if needed, and never sensitive personal data.
  • Each SQLite connection is opened inside the request, because FastAPI runs requests on worker threads and a SQLite connection can't be shared between threads.
  • The nightly evaluation reruns the 50 cases from "Building an Evaluation Set". Version 1.0 scores 44/50, as in that lesson.
  • Version 1.1 drops to 40/50, 4 below the launch baseline, more than the allowed drop of 3, so the program raises an ALERT. In production, that line would send a message to the person on call. The breakdown shows the trade: it now declines all 10 off-topic questions (one more than before), but answers only 30 of 40 real questions, down from 35.
  • The dashboard shows the same problem from live traffic: declines jump from 22% to 40%. The new threshold turns away questions it used to answer correctly. Cost per 1,000 requests stays about $0.12, so this change hurt quality without saving money.
  • Rolling back to 1.0 on day 3 restores 44/50 and 22% declines. Keeping the previous version ready is what makes a fast fix possible.

Example: Latency from the Log

The same log answers latency questions. This program reads campus.db from the checkpoint and reports the median and the 95th percentile: the time within which 95% of requests finished.

Python
import sqlite3
import statistics
 
db = sqlite3.connect("campus.db")                     # the log written by the checkpoint
for day, in db.execute("SELECT DISTINCT day FROM log ORDER BY day"):
    times = sorted(t for t, in db.execute("SELECT latency_ms FROM log WHERE day = ?", (day,)))
    p50 = statistics.median(times)
    p95 = times[int(0.95 * len(times)) - 1]
    print(f"day {day}: median {p50:.1f} ms, 95th percentile {p95:.1f} ms, slowest {times[-1]:.1f} ms")
Output
day 1: median 3.1 ms, 95th percentile 4.2 ms, slowest 9.6 ms
day 2: median 3.0 ms, 95th percentile 3.3 ms, slowest 3.5 ms
day 3: median 3.0 ms, 95th percentile 3.5 ms, slowest 3.8 ms

Explanation: The median answer took about 3 ms and the 95th percentile 3.3 to 4.2 ms, because the semantic search is tiny. The slowest request on day 1 (9.6 ms) is typical of the first requests after a start. These timings are one run on this laptop and change between runs. An app that calls an LLM would show hundreds of milliseconds to several seconds, which is why the 95th percentile, not the average, is the number to set limits on.

Setting Alerts

SignalExample alert
Evaluation scoreMore than 3 points below the launch baseline
Decline or error rateAbove 30% for an hour
CostDaily cost more than twice the 7-day average
Latency95th percentile above 2 seconds for 10 minutes
SafetyAny flagged harmful output reaches a user
User feedbackThumbs-down rate doubles in a day

Alerts should be rare and actionable: too many and people start ignoring them.

Common Mistakes

Monitoring only uptime and errors. The service can be up, fast and wrong.

Averages only. A good average latency can hide a slow 5% of users.

No baseline. An alert needs a number to compare with, recorded at launch.

Logging everything forever. Logs cost money and hold personal data; keep what you need, for as long as you need it.

Interview Corner

How would you monitor an LLM application in production?

Log every request with version, latency, tokens and cost; rerun an evaluation set on a schedule and after changes; watch live signals like decline rate, ratings and flagged outputs; and alert when quality, cost or latency cross agreed limits. Keep the previous version ready for rollback.

Why look at the 95th percentile latency rather than the average?

Because averages hide the slow requests that frustrate users. The 95th percentile shows the wait for the slowest one in twenty requests, which is closer to what users complain about.

Practice

Exercise: a cost alert. Add a check after the dashboard that prints an ALERT when a day's cost per 1,000 requests is more than 20% above day 1's. Then make version 1.1 add 800 extra input tokens instead of 400. Does the alert fire?

Check your understanding:

  1. Why did version 1.1 score lower even though it declined every off-topic question?
  2. Which two signals showed the problem on day 2?
  3. Why are SQLite connections opened inside the request?

Quick check: monitoring

4 questions
1What did the nightly evaluation score on day 2?
2How did the decline rate change on day 2?
3What fixed the problem on day 3?
4Why prefer the 95th percentile latency over the average?

Key Takeaways

Quick reference

NeedCode or practice
Log a requestINSERT INTO log VALUES (...) with version, latency, tokens, cost
Daily dashboardSELECT day, COUNT(*), AVG(declined), SUM(cost) FROM log GROUP BY day
Nightly qualityRerun the evaluation set; alert below baseline minus a limit
Latency percentilesorted(times)[int(0.95 * len(times)) - 1]
Time a requesttime.perf_counter() before and after

Was this tutorial helpful?

Lesson 160 of 186