LLM Metrics and Observability: Complete Reference

From metric taxonomy and trace schemas through quality, retrieval, latency, cost, safety, drift, SLOs, Prometheus/Grafana, alerting, and production Python pipelines for LLM systems.

1. Metrics Hierarchy

LLM observability spans four layers. Each layer answers a different question and uses different storage, cardinality, and retention policies. Treating all signals as one flat dashboard leads to alert fatigue and blind spots.

Four-layer model

LayerQuestionExamplesTypical store
BusinessIs the product working for users and revenue?Task completion rate, CSAT, conversion lift, support deflectionProduct analytics, warehouse
QualityAre answers correct, grounded, and on-brand?Faithfulness, hallucination rate, rubric scores, eval pass rateEval DB, labeling platform
SystemIs infrastructure healthy?p95 latency, error rate, GPU utilization, queue depthPrometheus, Datadog
CostAre we spending efficiently?Tokens per task, $/successful answer, cache hit rateFinOps warehouse, billing API

Golden signals adapted for LLMs

Google SRE golden signals (latency, traffic, errors, saturation) still apply, but LLM services add quality and cost as first-class dimensions:

Metric types

TypeUse whenCardinality risk
CounterMonotonically increasing totals (requests, tokens, errors)Low if labels bounded
GaugePoint-in-time values (queue depth, active users)Medium
HistogramLatency and size distributions (p50, p95, p99)Low to medium
SummaryClient-side quantiles (less common in Prometheus)Medium
Intuition: Business metrics lag. System metrics are fast but say nothing about hallucinations. Quality metrics are slow but decisive. A healthy stack instruments all three and correlates them on trace_id.

Cardinality discipline

Never attach unbounded labels (raw user_id, full prompt text, chunk content) to Prometheus metrics. Use bounded enums: model, feature, tenant_tier, prompt_version. Store high-cardinality detail in trace backends (Langfuse, Phoenix, ClickHouse).

2. Quality Metrics

Quality metrics measure whether model outputs satisfy task requirements. Unlike latency, quality is rarely observable from infrastructure alone. You need eval harnesses, judges, human labels, or proxy signals.

Offline vs online quality

Core quality dimensions

DimensionDefinitionHow to measure
CorrectnessAnswer matches ground truth or expert labelExact match, F1, unit tests
FaithfulnessAnswer supported by provided contextRAGAS faithfulness, citation check
RelevanceAnswer addresses the user questionLLM-as-judge, answer relevancy
CoherenceLogical, readable, well structuredRubric score, perplexity (weak)
Instruction followingFormat, tone, constraints respectedSchema validation, regex, judge
HelpfulnessUser would find it usefulThumbs, MT-Bench style rubric

LLM-as-judge metrics

A strong model scores candidate outputs on a 1-5 rubric. Track:

Judge bias: Judges favor verbosity, their own model family, and confident tone. Re-calibrate monthly against human labels. Never use a single judge score as the only launch gate.

Regression detection

Store eval results keyed by config_hash (model + prompt + tools + retrieval settings). Alert when:

$$|\text{score}_{\text{new}} - \text{score}_{\text{baseline}}| > \delta$$

for any stratified slice (language, task type, tenant). Aggregate averages hide regressions on minority slices that carry legal or revenue risk.

Quality SLO examples

3. Retrieval Metrics

RAG systems fail in retrieval before generation. Split metrics across the retrieval pipeline: embedding, index lookup, reranking, and context assembly.

Classic IR metrics

MetricFormula / meaningWhen to use
Recall@kFraction of relevant docs in top-kRecall-oriented QA, support bots
Precision@kFraction of top-k that are relevantShort context windows
MRRMean reciprocal rank of first relevant hitSingle correct document expected
nDCG@kDiscounted cumulative gain normalizedGraded relevance labels
Hit rate% queries with ≥1 relevant doc in top-kOperational dashboard

Production retrieval proxies

When labeled q-d pairs are scarce, monitor proxies:

Embedding and index health

Context assembly metrics

retrieval_trace = {
  "query_hash": "a9f2",
  "embed_ms": 38,
  "search_ms": 112,
  "rerank_ms": 67,
  "chunks_retrieved": 20,
  "chunks_after_rerank": 5,
  "chunks_after_dedup": 4,
  "total_context_tokens": 1840,
  "top_score": 0.87,
  "hit": true
}
Intuition: High generation quality with poor retrieval metrics means the model is hallucinating from parametric memory. Fix retrieval before fine-tuning the LLM.

4. Generation Metrics

Generation metrics cover the LLM inference step: decoding behavior, output shape, streaming performance, and post-processing success.

Output structure metrics

MetricDescription
Output token countDistribution of completion length; spikes may indicate runaway generation
Finish reason ratestop vs length vs content_filter
Schema pass rateJSON/XML/tool-call parse success
Refusal rateModel declines to answer (may be correct or over-refusal)
Repetition scoren-gram repetition, loop detection in agents
Citation coverage% factual claims with valid source pointers

Decoding parameters to log

Streaming metrics

Logprob and confidence (when available)

Mean token logprob, entropy per step, and calibrated uncertainty help flag low-confidence answers for human review or retrieval fallback. Not all APIs expose logprobs; treat absence as a known gap.

Post-generation pipeline

Track success rates for moderation filters, PII redaction, format repair loops, and tool-call validation. A generation can be "good" yet fail downstream parsing.

5. Latency Metrics

Latency drives user experience and infrastructure sizing. LLM latency is multi-modal: prefill (prompt processing) and decode (token generation) have different scaling behavior.

Key latency definitions

MetricDefinitionTypical target (interactive)
TTFTRequest accepted → first token streamed< 500 ms (small model) to 2 s (large)
TPOTTime per output token after first20-80 ms/token depending on hardware
E2E latencyFull response ready (non-streaming)Task-dependent
Prefill latencyProcess prompt tokens (often ∝ input length)Monitor separately from decode
Queue waitTime in scheduler before GPU work startsShould be < 5% of E2E at normal load

Span breakdown (standard)

latency_ms: {
  "auth": 3,
  "rate_limit_check": 1,
  "embed": 45,
  "retrieve": 120,
  "rerank": 68,
  "prompt_build": 5,
  "prefill": 210,
  "decode": 890,
  "postprocess": 12,
  "total": 1354
}

Percentiles, not averages

Report p50, p90, p95, p99 for each span. Means are misleading because LLM latency distributions are heavy-tailed (long outputs, cache misses, cold starts). SLOs should reference percentiles.

Factors that inflate latency

Intuition: Users perceive TTFT most acutely. Optimize perceived speed with streaming even if total E2E is unchanged. Show partial output early.

6. Cost and Token Metrics

Token usage is the billing unit for most LLM APIs and the primary driver of self-hosted GPU cost (via throughput and model size). Cost metrics must tie to outcomes, not raw request counts.

Token accounting

MetricNotes
Input tokensSystem + user + retrieved context + tool results
Output tokensCompletion including hidden chain-of-thought if logged
Cached input tokensProvider prompt cache hits (discounted billing)
Embedding tokensSeparate from generation; often forgotten in budgets
Reranker callsPer-document or per-query pricing

Cost estimation

$$C_{\text{request}} = \frac{N_{\text{in}} \cdot p_{\text{in}} + N_{\text{out}} \cdot p_{\text{out}}}{10^6} + C_{\text{embed}} + C_{\text{tools}}$$

Store price tables per model version. Providers change rates; version your pricing config.

Efficiency ratios

Budget guardrails

Enforce per-tenant daily caps, per-request max_tokens, retrieval top-k limits, and agent max_steps at the gateway. Emit metrics when requests are truncated or rejected by budget policy.

7. Throughput Metrics

Throughput measures how much work the system completes per unit time. For GPUs, the key units are tokens/sec (prefill and decode reported separately) and concurrent sequences.

Service-level throughput

Hardware utilization

MetricHealthy rangeInterpretation
GPU utilization70-90% sustainedToo low: over-provisioned; too high: queue buildup
GPU memory usedBelow OOM threshold with headroomKV cache dominates at high concurrency
Batch size (continuous batching)Varies dynamicallySmall batches → low throughput; huge → latency spikes
MFU / HFUModel FLOPs utilizationTraining metric; inference uses tokens/GPU/s

Backpressure signals

Throughput and latency trade off via batching. Document the operating point: max RPS at p95 latency target.

8. Agent Metrics

Agents loop: plan, call tools, observe results, repeat. Metrics must capture loop structure, tool reliability, and termination behavior. A single "request" can span dozens of LLM calls.

Agent session metrics

MetricWhy it matters
Steps per sessionDetect runaway loops; correlate with cost
LLM calls per sessionEach call bills tokens
Tool calls per sessionExternal API load and failure surface
Termination reasonsuccess, max_steps, timeout, user_cancel, error
Time to resolutionWall clock for end-to-end task
Replan rateHow often agent revises strategy mid-session

Tool-specific metrics

Planning quality proxies

Agent cost explosions: A loop with 30 GPT-4 calls and 15 web searches can cost dollars per user message. Hard caps on steps, tokens, and tool spend are mandatory production controls, not optional optimizations.

Multi-agent systems

Track handoff count, message fan-out, supervisor override rate, and per-role token share. Without role-level attribution, you cannot tell whether the planner or executor wastes budget.

9. Safety Metrics

Safety metrics quantify policy compliance, harm prevention, and attack resistance. They complement quality metrics: an answer can be fluent yet unsafe or leak confidential data.

Input-side metrics

Output-side metrics

MetricDescription
Toxicity score distributionClassifier on output text
PII leakage rateSecrets, emails, SSN patterns in output
Over-refusal rateSafe queries incorrectly refused
Under-refusal rateUnsafe queries answered (red team)
Policy violation rateCustom rules (medical advice, legal claims)
Hallucinated authorityCites nonexistent sources or laws

Red team and eval cadence

Run scheduled adversarial suites (harmful instructions, injection payloads, multilingual attacks). Track pass rate over time and alert on regressions after model or prompt changes.

Human review queue

Intuition: Safety metrics are sparse-event statistics. Use Wilson score intervals or Bayesian smoothing for rates below 1%. A drop from 0.1% to 0.05% may be noise; a jump from 0.1% to 2% is an incident.

10. User Feedback Metrics

User feedback is the ultimate ground truth for product quality, but it is biased, sparse, and delayed. Treat it as a first-class metric stream linked to traces.

Explicit feedback

SignalMetricCaveats
Thumbs up/downPositive rate, net scoreAngry users over-report; satisfied users stay silent
Star ratingsMean, distributionSurvey fatigue lowers volume
Free-text commentsTheme clusteringRequires NLP pipeline; high signal
Report / flagReport rate per 1k sessionsSerious issues; low volume

Implicit feedback

Feedback loop engineering

Every thumbs-down should enqueue: trace replay link, prompt version, model, retrieval chunks, and optional label for eval set. Measure time from feedback to fix deployed as an organizational metric.

Segmentation

Break feedback rates by locale, subscription tier, feature flag, and new vs returning users. A global thumbs-up rate hiding a broken locale is a common failure mode.

11. Drift Metrics

Drift is change in behavior or data distribution that degrades performance without a code deploy. LLM systems drift from model updates, corpus aging, user behavior shifts, and embedding index decay.

Types of drift

TypeWhat shiftsDetection approach
Data driftInput query distribution, language, lengthEmbedding distance, PSI on features
Concept driftMapping from input to correct answerGolden eval regression, feedback drop
Upstream model driftProvider silently updates weightsEval suite on fixed prompts, output hash shifts
Corpus driftRetrieved docs stale or wrongIndex age, source freshness metrics
Prompt driftUnversioned prompt edits in prodConfig registry, hash mismatch alerts

Population Stability Index (PSI)

Compare binned distributions of a feature (e.g., query length, retrieval score) between reference and current windows:

$$\text{PSI} = \sum_i (A_i - E_i) \ln\frac{A_i}{E_i}$$

PSI < 0.1 stable; 0.1-0.25 moderate shift; > 0.25 investigate.

Operational drift dashboard

Correlate drift timestamps with deploy events: prompt version, model ID change, index rebuild, data pipeline failure.

12. SLOs for LLM Services

Service Level Objectives define measurable targets over a window. Error budgets connect reliability work to product velocity. LLM SLOs must include latency, availability, quality, and cost.

SLI vs SLO vs SLA

Example SLO set

SLISLO targetWindow
Availability (non-5xx)99.9%30 days
p95 E2E latency (chat)< 4 s30 days
p95 TTFT (streaming)< 1.2 s30 days
Golden eval pass rate≥ 94%7 days
Safety red-team pass≥ 99%7 days
Cost per task (p50)< $0.0230 days

Error budget policy

When latency error budget is exhausted: freeze non-critical deploys, enable aggressive caching, route to faster model tier. When quality budget is exhausted: block prompt experiments, roll back last config change, increase human review sampling.

Multi-window alerting

Google SRE recommends burn-rate alerts on multiple windows (e.g., 1h and 6h) to catch fast and slow burns. Apply the same pattern to quality SLOs, not only availability.

User-facing vs internal SLOs: External chat may target 4 s p95 while internal batch summarization targets throughput. Do not use one SLO for all surfaces.

13. Trace Schema

A consistent trace schema is the contract between application code, observability backends, and analysts. Use OpenTelemetry conventions where possible; extend with LLM-specific attributes.

Top-level trace fields

{
  "trace_id": "7f3a9c2e1b8d4f6a",
  "span_id": "a1b2c3d4",
  "parent_span_id": null,
  "service_name": "rag-gateway",
  "operation": "chat.completion",
  "start_time": "2026-07-12T10:15:30.123Z",
  "duration_ms": 1456,
  "status": "ok",
  "user_id_hash": "u_8f3e2a",
  "session_id": "sess_9912",
  "tenant_id": "acme_corp",
  "feature": "support_copilot",
  "environment": "production"
}

LLM span attributes

FieldTypeDescription
llm.modelstringProvider model identifier
llm.prompt_versionstringTemplate registry version
llm.prompt_hashstringSHA-256 of rendered prompt (no raw PII)
llm.input_tokensintBillable input tokens
llm.output_tokensintCompletion tokens
llm.finish_reasonenumstop, length, content_filter, tool_calls
llm.temperaturefloatDecoding temperature
llm.ttft_msfloatTime to first token
llm.estimated_cost_usdfloatFrom price table

RAG span attributes

Agent span attributes

Privacy and retention

Store hashes and IDs by default. Raw prompts and completions go to restricted stores with TTL and access audit. GDPR/CCPA deletion must cascade to trace stores by user_id_hash.

14. Dashboards

Dashboards translate metrics into decisions. Organize by persona and incident type, not by raw metric names.

Dashboard hierarchy

DashboardAudienceTop panels
Executive healthLeadershipDAU, task success, cost/day, CSAT trend
On-call operationsSREError rate, p95 latency, queue depth, burn rate
Quality reviewML / PMEval scores, feedback rate, drift PSI, slice breakdown
Cost FinOpsFinance / Eng$ by tenant, tokens/task, cache savings
SafetyTrust & SafetyFlag volume, red-team pass, injection rate
RAG deep diveRetrieval ownersRecall@k, empty hits, index lag, rerank lift

Design principles

USE and RED methods

Sample on-call row

Single screen answering: "Is the system up?", "Is it slow?", "Is it wrong?", "Is it expensive?"

  1. Availability and 5xx rate (last 1h vs SLO).
  2. p95 latency by stage (embed, retrieve, generate).
  3. Thumbs-down rate spike detector.
  4. Cost per hour vs budget.

15. Prometheus and Grafana

Prometheus pulls or receives time-series metrics. Grafana visualizes them. This stack is the default for self-hosted LLM inference and gateway services.

Instrumenting Python services

from prometheus_client import Counter, Histogram, start_http_server

LLM_REQUESTS = Counter(
    "llm_requests_total",
    "Total LLM requests",
    ["model", "feature", "status"],
)
LLM_LATENCY = Histogram(
    "llm_request_duration_seconds",
    "End-to-end request latency",
    ["model", "feature"],
    buckets=[0.1, 0.25, 0.5, 1, 2, 5, 10, 30],
)
LLM_TOKENS = Counter(
    "llm_tokens_total",
    "Token usage",
    ["model", "direction"],  # direction: input | output
)

def handle_request(model, feature, fn):
    with LLM_LATENCY.labels(model=model, feature=feature).time():
        try:
            result = fn()
            LLM_REQUESTS.labels(model=model, feature=feature, status="ok").inc()
            return result
        except Exception:
            LLM_REQUESTS.labels(model=model, feature=feature, status="error").inc()
            raise

start_http_server(8000)  # /metrics endpoint

PromQL examples

# p95 latency over 5m
histogram_quantile(0.95,
  sum(rate(llm_request_duration_seconds_bucket[5m])) by (le, feature)
)

# Error rate
sum(rate(llm_requests_total{status="error"}[5m]))
  / sum(rate(llm_requests_total[5m]))

# Output tokens per second
sum(rate(llm_tokens_total{direction="output"}[5m])) by (model)

Grafana setup tips

Histogram bucket selection

Choose buckets that match SLO thresholds. If p95 SLO is 3 s, include buckets around 1, 2, 3, 5, 10 seconds. Misaligned buckets make quantile estimation noisy.

Exporters for GPU nodes

DCGM exporter for NVIDIA metrics: GPU util, memory, temperature, power. Correlate GPU saturation with queue wait spans.

16. Platform Tools

Specialized LLM observability platforms add trace UI, eval integration, and prompt versioning beyond raw Prometheus. Teams often run Prometheus for SRE plus a LLM platform for debugging.

Tool comparison

ToolStrengthsBest for
LangfuseOpen source, traces, scores, prompt mgmtSelf-hosted LLM apps
LangSmithLangChain integration, datasets, evalLangChain/LangGraph stacks
Phoenix (Arize)Embeddings viz, drift, evalRAG debugging
HeliconeGateway proxy, cost, cachingAPI cost tracking
Weights & BiasesExperiment tracking, eval tablesResearch to prod bridge
Datadog / New RelicUnified APM + LLM modulesEnterprise existing APM
OpenTelemetry + JaegerVendor-neutral tracingMulti-service mesh

Selection criteria

Avoid tool sprawl

Pick one system of record for traces and one for time-series metrics. Duplicate instrumentation across five vendors creates conflicting numbers and double billing.

Intuition: Platform tools win at debugging single bad traces. Prometheus wins at paging on-call at 3 AM. You need both workflows, not a single tool miracle.

17. Alerting

Alerts must be actionable, routed to owners, and tied to runbooks. Alert on symptoms users feel, not every metric fluctuation.

Alert tiers

TierResponseExamples
P1 pageImmediate human wake-upAvailability < 99% over 15m, safety leak spike
P2 ticketBusiness hours escalationp95 latency 2x baseline 1h, eval drop 5%
P3 infoDashboard reviewCost 20% above forecast, PSI moderate

Recommended alert rules

Alert hygiene

Example Alertmanager route

route:
  receiver: default
  routes:
    - match: { severity: critical }
      receiver: pagerduty
    - match: { team: safety }
      receiver: safety-slack
    - match: { alertname: CostRunaway }
      receiver: finops-email

18. Cost Attribution

Cost attribution assigns spend to teams, features, tenants, and outcomes. Without it, LLM bills appear as a single opaque line item and nobody optimizes.

Attribution dimensions

DimensionUse
Tenant / customerUsage-based billing, quota enforcement
Feature / product surfaceROI per feature, kill low-value experiments
Team / cost centerInternal chargeback
Model tierCompare cheap vs premium routing policies
EnvironmentSeparate prod vs staging waste
Prompt versionCost impact of prompt changes

Unit economics

Shared cost allocation

GPU cluster costs split by measured GPU-seconds per feature (from labels on jobs) or by token share. Embedding index storage split by corpus owner. Avoid equal split across teams; it hides heavy users.

Tagging discipline

Require tenant_id and feature on every internal API call. Reject untagged calls in production. Backfill tags from trace_id in batch jobs for legacy paths.

FinOps review cadence

Weekly: top 10 expensive tenants and features. Monthly: model routing opportunities (swap 20% of traffic to smaller model with < 2% quality loss). Quarterly: reserved capacity vs on-demand for self-hosted.

19. Metrics Pipeline (Python)

A production metrics pipeline collects spans from the app, aggregates low-cardinality series to Prometheus, and ships rich events to a warehouse for quality and cost analysis.

Architecture overview

  1. App emits OpenTelemetry spans + Prometheus counters/histograms.
  2. OTel Collector receives, batches, redacts PII fields.
  3. Exporter fan-out: Prometheus scrape endpoint, ClickHouse for traces, S3 parquet for batch eval.
  4. Nightly job joins traces with feedback and eval labels.

End-to-end Python example

"""
Minimal LLM metrics pipeline: trace + Prometheus + structured log.
"""
from __future__ import annotations

import hashlib
import json
import time
import uuid
from dataclasses import dataclass, field
from typing import Any

from prometheus_client import Counter, Histogram

# --- Prometheus metrics (low cardinality labels only) ---
REQUESTS = Counter("llm_requests_total", "Requests", ["feature", "model", "status"])
LATENCY = Histogram("llm_latency_seconds", "E2E latency", ["feature"], buckets=[0.5, 1, 2, 5, 10, 30])
TOKENS = Counter("llm_tokens_total", "Tokens", ["model", "direction"])
COST = Counter("llm_cost_usd_micros", "Cost in micro-dollars", ["feature", "model"])

PRICE_PER_1M = {"gpt-4o-mini": {"input": 0.15, "output": 0.60}}


@dataclass
class LLMTrace:
    trace_id: str
    feature: str
    model: str
    prompt_version: str
    input_tokens: int = 0
    output_tokens: int = 0
    spans: list[dict[str, Any]] = field(default_factory=list)
    status: str = "ok"

    def add_span(self, name: str, duration_ms: float, attrs: dict | None = None):
        self.spans.append({
            "name": name,
            "duration_ms": duration_ms,
            "attributes": attrs or {},
        })

    def prompt_hash(self, text: str) -> str:
        return hashlib.sha256(text.encode()).hexdigest()[:16]

    def estimated_cost_usd(self) -> float:
        p = PRICE_PER_1M[self.model]
        return (self.input_tokens * p["input"] + self.output_tokens * p["output"]) / 1_000_000

    def flush_log(self):
        """Ship to structured log / OTel / warehouse."""
        record = {
            "trace_id": self.trace_id,
            "feature": self.feature,
            "model": self.model,
            "prompt_version": self.prompt_version,
            "input_tokens": self.input_tokens,
            "output_tokens": self.output_tokens,
            "cost_usd": self.estimated_cost_usd(),
            "spans": self.spans,
            "status": self.status,
        }
        print(json.dumps(record))  # replace with OTel exporter


def run_rag_request(feature: str, model: str, prompt: str) -> str:
    trace = LLMTrace(
        trace_id=str(uuid.uuid4()),
        feature=feature,
        model=model,
        prompt_version="v3.2",
    )
    t0 = time.perf_counter()
    try:
        # Embed
        t_embed = time.perf_counter()
        time.sleep(0.04)
        trace.add_span("embed", (time.perf_counter() - t_embed) * 1000)

        # Retrieve
        t_ret = time.perf_counter()
        time.sleep(0.11)
        trace.add_span("retrieve", (time.perf_counter() - t_ret) * 1000, {"hit": True, "top_k": 5})

        # Generate
        t_gen = time.perf_counter()
        time.sleep(0.35)
        trace.input_tokens = 1800
        trace.output_tokens = 240
        trace.add_span("generate", (time.perf_counter() - t_gen) * 1000, {
            "prompt_hash": trace.prompt_hash(prompt),
            "finish_reason": "stop",
        })

        answer = "Synthetic answer for metrics demo."
        status = "ok"
    except Exception:
        trace.status = "error"
        status = "error"
        raise
    finally:
        elapsed = time.perf_counter() - t0
        LATENCY.labels(feature=feature).observe(elapsed)
        REQUESTS.labels(feature=feature, model=model, status=trace.status).inc()
        TOKENS.labels(model=model, direction="input").inc(trace.input_tokens)
        TOKENS.labels(model=model, direction="output").inc(trace.output_tokens)
        micros = int(trace.estimated_cost_usd() * 1_000_000)
        COST.labels(feature=feature, model=model).inc(micros)
        trace.flush_log()
    return answer


if __name__ == "__main__":
    run_rag_request("support_copilot", "gpt-4o-mini", "How do I reset my password?")

Pipeline hardening

20. Master Metrics Catalog

Complete reference of LLM production metrics. Use as an instrumentation checklist when designing or auditing observability.

CategoryMetricTypeLabels (bounded)Notes
Trafficllm_requests_totalCounterfeature, model, statusCore RED rate numerator
Trafficllm_tokens_totalCountermodel, directioninput | output | cached_input
Latencyllm_latency_secondsHistogramfeature, stagestage: e2e, ttft, prefill, decode
Latencyllm_span_duration_secondsHistogramspan_nameembed, retrieve, rerank, generate
Errorsllm_errors_totalCountererror_type, modeltimeout, rate_limit, parse, provider
Costllm_cost_usd_microsCounterfeature, model, tenant_tierInteger micro-dollars avoids float drift
Costllm_cache_hits_totalCountercache_typeprompt_cache, semantic_cache
Qualityllm_eval_scoreGaugeeval_suite, sliceFrom nightly jobs, not per-request
Qualityllm_schema_pass_totalCounterfeature, schema_versionStructured output validation
Qualityllm_judge_score_histogramHistogramrubricSampled online eval
Retrievalrag_retrieval_hit_totalCountercorpus, featureAt least one chunk above threshold
Retrievalrag_top_scoreHistogramcorpusDistribution shift detector
Retrievalrag_recall_at_kGaugeeval_suiteOffline labeled eval only
Retrievalrag_index_lag_secondsGaugecorpusSource update to index fresh
Generationllm_finish_reason_totalCounterreason, modelstop, length, content_filter
Generationllm_output_tokensHistogramfeatureDetect runaway length
Generationllm_refusal_totalCounterfeature, categoryTrack over/under refusal
Throughputllm_inflight_requestsGaugefeatureConcurrency saturation
Throughputgpu_tokens_per_secondGaugegpu_id, modelSelf-hosted inference
Agentagent_steps_totalHistogramfeatureSteps per session
Agentagent_tool_calls_totalCountertool_name, statusPer-tool reliability
Agentagent_termination_totalCounterreasonsuccess, max_steps, timeout
Safetysafety_flag_totalCounterflag_type, actionblock, redact, escalate
Safetyjailbreak_attempt_totalCounterdetector_versionInput classifier hits
Safetypii_detected_totalCounterfield, directioninput | output
Feedbackuser_feedback_totalCountersignal, valuethumbs_up, thumbs_down, report
Feedbackuser_regenerate_totalCounterfeatureImplicit negative signal
Driftfeature_psiGaugefeature_namePopulation stability index
Driftquery_embedding_driftGaugecorpusCentroid distance vs reference
SLOslo_burn_rateGaugeslo_name, windowMulti-window alert input
SLOslo_error_budget_remainingGaugeslo_name0-1 fraction left in period
Systemqueue_depthGaugequeue_nameBackpressure indicator
Systemprovider_rate_limit_totalCounterprovider429 responses
Master observability by layers: (1) Instrument traces with a stable schema, (2) export bounded Prometheus metrics for paging, (3) join warehouse data for quality and cost attribution, (4) define SLOs per surface, (5) close the loop from alerts and feedback back to eval and prompts.