Skip to content

Module 09 · Lesson 9.4

Monitoring Quality, Failures, Latency and Cost

40 minUpdated 18 Nov 2026Part of Deployment, Observability and Optimization · AI Agent Development
On this page
  1. What you will learn
  2. Why a live agent needs monitoring
  3. The signals to watch: quality, failures, latency and cost
  4. Latency: why the median and the slowest runs both matter
  5. Cost: count model calls before you count money
  6. Alerts, dashboards and logs: which tool for which job
  7. Summarise trace events and raise alerts with Python
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

A restaurant owner does not wait for a bad review to learn the kitchen is slow. They glance at the ticket rail, see orders piling up and step in. A live AI agent needs the same kind of glance, because it can get worse quietly: slower, dearer or less accurate, with no error message at all.

Monitoring means watching a small set of numbers about a running system and being told when they cross a line. This lesson shows which numbers matter for an agent, how to get them from the traces you built in the last lesson, and how to set alerts. Most of it needs no coding. One short Python script at the end turns trace events into the numbers.

What you will learn

  • Name the signals that show an agent's quality, reliability, speed and cost.
  • Explain why the median and the slowest runs tell different stories.
  • Choose alert thresholds and decide who should act on each alert.
  • Run a Python script that summarises trace events and raises alerts.

Before you start

  • Tracing Tool Calls and Agent Decisions, because monitoring reads the trace events defined there.
  • No coding experience is needed for most of this lesson.
  • Optional: Python 3.10 or later, if you want to run the example yourself.

Why a live agent needs monitoring

Ordinary software usually fails loudly. A crash, an error page, a red line in a log. An agent often fails softly. It still answers, but the answer is wrong, or it takes three times as long, or it makes ten model calls where it used to make two.

Soft failures are the reason to watch trends. A trace tells you what happened in one run. Monitoring tells you what is happening across all runs, so you can see a change early.

Metric
A number you can calculate for every run or every hour. Example: how many runs ended in an error.
Threshold
The line a metric must not cross. Example: more than 10% of runs failing.
Alert
A message sent to a person when a metric crosses its threshold.
Dashboard
One screen that shows the key metrics as numbers and simple charts, so you can judge health at a glance.

The signals to watch: quality, failures, latency and cost

You do not need fifty metrics. Start with one or two in each of four groups. The table uses the Quillfeather support agent as the example.

GroupSignalWhat it tells you
FailuresError rate: share of runs where a tool or the model call failedSomething is broken: a tool, a key, a network link.
QualityHandover rate: share of runs that ended with the customer sent to a personA sudden rise means the agent can no longer answer what it used to. A drop to zero can also be bad: it may be refusing to hand over.
QualityGrounding-check failure rate: share of runs where the reply cited no source or an unknown sourceThe agent is making things up or the knowledge base search is returning poor passages.
LatencyMedian and slowest run timeHow long customers wait, in a typical case and in the worst case.
CostModel calls per run, and a rough cost per runA loop, a bigger prompt or a changed model is making each run dearer.
Four groups, five signals. Each one can be calculated from the trace events alone.

Latency: why the median and the slowest runs both matter

Latency is the time a customer waits for an answer. People often quote the average, but one very slow run can hide inside it, or a few slow runs can drag it up.

The median is the middle value when you sort all run times. Half the runs were faster and half were slower. It shows the typical customer experience and ignores a few extreme runs.

The slow tail is the slowest few runs, for example the slowest 1 in 20. Think of a coach with 20 passengers. The median passenger arrives on time, but the person on the longest route arrives an hour late. Both facts matter, and one number cannot show both.

  • Watch the median to see whether the whole service is getting slower.
  • Watch the slowest runs to find stuck tools, long loops and huge prompts.
  • Use the trace of a slow run to see which step took the time. Monitoring finds the problem and tracing explains it.

Cost: count model calls before you count money

Providers change their prices, and the real bill arrives late. A faster early warning is the number of model calls per run. If a run that used to need two calls now needs six, cost has tripled, whatever the price list says.

  • Count model calls per run from the trace. This is exact and instant.
  • Estimate a rough cost per run: calls multiplied by an average cost per call that you look up on your provider's price page and keep in a config file.
  • Compare the estimate with the real bill once a month. If they drift apart, fix the estimate.

A sudden rise in calls per run usually means a loop or a retry storm. The budgets from Budget Limits, Rate Limits and Runaway Execution Controls stop the worst cases. Monitoring shows you the milder ones that stay under the limit.

Alerts, dashboards and logs: which tool for which job

Dashboards, alerts and logs answer different questions. Mixing them up is why many teams drown in noise.

ToolBest question to answerExample
AlertDo I need to act now?Error rate above 10% for 15 minutes.
DashboardHow is the service doing over the last day or week?A chart of median run time and calls per run.
Log or traceWhat exactly happened in this run?Run R-0003: the search tool failed, then the grounding check failed.

Rules for good alerts

  • Alert on symptoms customers feel, such as failures and slow replies, not on every internal detail.
  • Every alert needs a person and a first step. If nobody knows what to do, delete the alert or write the step down.
  • Set thresholds from real data. Run for a week, see what normal looks like, then set the line a little above it.
  • Fewer, better alerts. If an alert fires every day and is ignored, it is teaching people to ignore alerts.

The Google SRE book chapter listed in the references explains these ideas for large systems. Its advice on alerting on symptoms and keeping alerts rare applies well to agents.

Summarise trace events and raise alerts with Python

The script below uses fixed sample data in the trace format from the last lesson: run id, kind, name, milliseconds and ok. It adds one convention for this lesson: a check event named handover appears when a run hands the customer to a person. It builds a summary for each run, calculates overall numbers and prints an alert for each threshold that is crossed.

Pythonmonitor_demo.py
from statistics import median

# (run_id, kind, name, ms, ok) - fixed sample data, all version v2
RAW = [
    ("R-0001", "model", "gemini", 400, True), ("R-0001", "tool", "lookup_order", 90, True),
    ("R-0001", "model", "gemini", 380, True),
    ("R-0002", "model", "gemini", 420, True), ("R-0002", "tool", "search_help", 60, True),
    ("R-0002", "model", "gemini", 410, True), ("R-0002", "check", "grounding", 1, True),
    ("R-0003", "model", "gemini", 450, True), ("R-0003", "tool", "search_help", 70, False),
    ("R-0003", "model", "gemini", 430, True), ("R-0003", "check", "grounding", 1, False),
    ("R-0003", "check", "handover", 1, True),
    ("R-0004", "model", "gemini", 1900, True), ("R-0004", "tool", "lookup_order", 800, True),
    ("R-0004", "model", "gemini", 1700, True),
]
LIMITS = {"error_rate": 0.10, "handover_rate": 0.20, "grounding_fail_rate": 0.10,
          "median_ms": 1000, "slowest_ms": 3000}
COST_PER_MODEL_CALL = 2  # made-up cost units, not real prices

runs = {}
for run_id, kind, name, ms, ok in RAW:
    s = runs.setdefault(run_id, {"steps": 0, "ms": 0, "calls": 0, "errors": 0,
                                 "handover": 0, "grounding_fail": 0})
    s["steps"] += 1
    s["ms"] += ms
    s["calls"] += kind == "model"
    s["errors"] += kind == "tool" and not ok
    s["handover"] += name == "handover"
    s["grounding_fail"] += name == "grounding" and not ok

for run_id, s in runs.items():
    print(run_id, "steps", s["steps"], "ms", s["ms"], "model_calls", s["calls"],
          "errors", s["errors"], "cost", s["calls"] * COST_PER_MODEL_CALL)

def rate(key):
    return sum(s[key] > 0 for s in runs.values()) / len(runs)

times = [s["ms"] for s in runs.values()]
overall = {"error_rate": rate("errors"), "handover_rate": rate("handover"),
           "grounding_fail_rate": rate("grounding_fail"),
           "median_ms": median(times), "slowest_ms": max(times)}
print("overall", overall)
for name, limit in LIMITS.items():
    if overall[name] > limit:
        print("ALERT", name, overall[name], "is above", limit)

Offline and deterministic. The cost figure uses made-up units, not real prices. Run it with python monitor_demo.py.

What each part does

  • RAW holds the trace events as short tuples. Run R-0004 has two slow model calls and a slow tool, so its total is far above the others.
  • LIMITS is the threshold table. Every metric has one line it must not cross.
  • COST_PER_MODEL_CALL = 2 is a made-up unit. In real use you would load an estimate from a config file.
  • runs.setdefault(run_id, {...}) creates a summary the first time a run id appears. Later events for the same run add to it.
  • s["calls"] += kind == "model" adds 1 when the event is a model call, because True counts as 1 in Python.
  • rate(key) returns the share of runs where that counter is above zero. For example, one of four runs had an error, so the rate is 0.25.
  • median(times) comes from the statistics module. max(times) is the slowest run.
  • The last loop compares each overall number with its limit and prints an ALERT line when it is higher.
OutputCaptured from a real run
R-0001 steps 3 ms 870 model_calls 2 errors 0 cost 4
R-0002 steps 4 ms 891 model_calls 2 errors 0 cost 4
R-0003 steps 5 ms 952 model_calls 2 errors 1 cost 4
R-0004 steps 3 ms 4400 model_calls 2 errors 0 cost 4
overall {'error_rate': 0.25, 'handover_rate': 0.25, 'grounding_fail_rate': 0.25, 'median_ms': 921.5, 'slowest_ms': 4400}
ALERT error_rate 0.25 is above 0.1
ALERT handover_rate 0.25 is above 0.2
ALERT grounding_fail_rate 0.25 is above 0.1
ALERT slowest_ms 4400 is above 3000

Read the output carefully. The median, 921.5 ms, is under the 1000 ms limit, so no median alert fires. Yet one run took 4400 ms, and the slowest-run alert caught it. With one number you would have missed the problem or panicked about a healthy service.

Conclusion and your next step

Monitoring turns traces into a few numbers: error rate, handover rate, grounding failures, median and slowest time, and model calls per run. Thresholds and alerts tell a person when to look. Dashboards show trends, and traces explain single runs.

Your next step: take the five signals from the table, write a threshold for each one for your own agent and name who would act on it. Then continue to Caching, Model Selection and Token Optimization, where you use these numbers to lower cost and latency and to check that a change really helped.

Want more background? Read Tracing Tool Calls and Agent Decisions again for the event format, or the Agent Launch Safety Checklist for what to confirm before go-live.

Common errors and how to fix them

The dashboard looks healthy but customers complain about slow answers.

Why it happens: Only the average or median time is shown, so a slow tail stays hidden.

Fix: Add the slowest runs, and look at the trace of each slow run to find the slow step.

Alerts fire every day and everyone ignores them.

Why it happens: Thresholds were guessed instead of set from a week of normal data, or the alert has no action attached.

Fix: Raise the line to just above normal, alert on customer-facing symptoms and write the first step next to each alert.

The error rate is zero but replies are wrong.

Why it happens: Errors only count crashed tool calls. A wrong answer is not an error to the program.

Fix: Add quality signals: grounding-check failures, handover rate and a regular sample of replies read by a person.

Cost jumps and nobody can say why.

Why it happens: Model calls per run were never recorded, so a loop or a longer prompt went unnoticed.

Fix: Count model calls in every trace and alert when calls per run rise above the normal range.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Set thresholds for a returns agent

A returns agent has run for a week. Use the numbers below to set a threshold for each signal and decide which ones should wake someone at night and which can wait for the morning.

You will need

  • Error rate: usually 1% to 3% of runs.
  • Handover rate: usually 12% to 18% of runs.
  • Median run time: usually 800 to 1000 ms. Slowest run in a day: usually under 3000 ms.
  • Model calls per run: almost always 2, sometimes 3.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If normal is 1% to 3%, a limit of 2% would fire all the time.
  • Ask: if this goes wrong, does a customer notice right now?
  • A first step can be as simple as "open the trace of the slowest run".
Show a model answer

One reasonable answer: error rate above 8% for 15 minutes is urgent, because customers are getting failures now. First step: open the newest failed runs and check the tool that failed. Handover rate above 25% over an hour is a morning check, unless a person cannot keep up. First step: read five handover traces to see what the agent could not answer. Median above 1500 ms is a morning check, and any run above 6000 ms is worth a look the same day because it points to a stuck tool. Model calls per run above 4 on average is urgent if spend is limited, because it usually means a loop. The exact numbers can differ. What matters is that every line sits above normal, matches what customers feel and comes with a first step.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why look at the slowest runs as well as the median?
    Show the answer and explanation

    Answer: B. The median describes the typical run, so it ignores a handful of extreme ones. Those extremes are real customers waiting. It is not that the median is wrong, which makes the first option tempting. It simply answers a different question.

  2. 2.Which alert is best?
    Show the answer and explanation

    Answer: B. It watches a customer-facing symptom over a window and tells the person what to do. Alerting on every single failure sounds careful, but one failed call is normal noise and people soon stop reading the alerts.

  3. 3.Model calls per run doubled overnight. What is the most likely cause?
    Show the answer and explanation

    Answer: B. Calls per run rise when the agent takes more steps or retries more. The trace of a recent run shows which. Customer behaviour can change the number of runs, but not the calls inside each run, which is why the first option fails.

Frequently asked questions

What should I monitor for an AI agent?

Start with failures (error rate), quality (handover rate and grounding-check failures), latency (median and slowest runs) and cost (model calls per run). These five can all be calculated from your trace events.

What is the difference between monitoring and logging?

Logs and traces record what happened in each run. Monitoring adds up many runs into numbers, compares them with thresholds and alerts you. You need both: monitoring tells you something changed, and the trace tells you why.

How do I know if my agent's answers are getting worse?

Watch quality signals such as grounding-check failures and the handover rate, and re-run your evaluation set after every change. Also have a person read a small sample of real replies every week, because some problems no automatic number shows.

What is a good threshold for an alert?

There is no universal value. Run the service for a while, see the normal range and set the line a little above it. Then adjust: if the alert fires too often, raise the line or lengthen the time window. If you miss real problems, lower it.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.