En este modulo
Why observability for AI
An LLM in production without observability is a blind system. You don't know if responses are good, if costs are spiraling, if latency has risen, or if an agent is stuck in an infinite tool call loop. You discover it when a user complains or when the bill arrives.
AI system observability is more complex than traditional software observability for three reasons: non-deterministic outputs, variable cost per request, and complex execution chains involving multiple LLM calls and tools.
The three pillars: metrics, logs, traces
Metrics (what is happening now)
Aggregated numbers in real time. Throughput, latency, error rate, GPU usage, tokens consumed. Stored in time series (Prometheus, InfluxDB). Visualized in dashboards (Grafana).
Logs (what happened exactly)
Individual events with detail. Each request with its input, output, timestamps, errors. Stored in log systems (Loki, Elasticsearch). Searched when something fails.
Traces (how a request flowed)
The complete path of a request through all system components. Critical for multi-service and multi-agent systems. Stored in trace backends (Jaeger, Tempo). Visualized as waterfalls.
LLM-specific metrics
Beyond standard API metrics (latency, error rate, throughput), LLM systems have their own metrics: TTFT, TPS, E2E latency, GPU utilization, KV cache usage, queue depth for performance. Tokens input/output totals, cost per request, cost per user, cache hit rate for costs. Format compliance, hallucination rate, user satisfaction for quality.
OpenTelemetry for LLMs
OpenTelemetry (OTel) is the open-source standard for instrumentation. It produces metrics, logs and traces you can send to any backend. For LLMs, there are specific semantic conventions.
# Instrumentation with OpenTelemetry for LLM calls
from opentelemetry import trace, metrics
tracer = trace.get_tracer("llm-service")
meter = metrics.get_meter("llm-service")
request_counter = meter.create_counter("llm.requests.total")
token_counter = meter.create_counter("llm.tokens.total")
latency_histogram = meter.create_histogram("llm.request.duration", unit="ms")
async def llm_inference(messages: list, model: str):
with tracer.start_as_current_span("llm.inference") as span:
span.set_attribute("gen_ai.system", "vllm")
span.set_attribute("gen_ai.request.model", model)
response = await client.chat.completions.create(model=model, messages=messages, max_tokens=1024)
request_counter.add(1, {"model": model, "status": "success"})
token_counter.add(response.usage.prompt_tokens, {"type": "input", "model": model})
token_counter.add(response.usage.completion_tokens, {"type": "output", "model": model})
return response
Langfuse: native AI observability
Langfuse is an observability platform designed specifically for LLMs. Open-source, self-hostable, with direct integration for LangChain, LlamaIndex and OpenAI-compatible APIs. It offers conversation traces, scoring, prompt management, automatic cost tracking, and datasets/evals from production.
Tool call and agent tracing
In systems with agents and tool calls, a request can generate multiple LLM calls and tool invocations. Without tracing, debugging "why the agent gave an incorrect response" is impossible.
Tracing saves hours of debugging
Without tracing, debugging an agent means reading raw logs trying to reconstruct what happened. With tracing, you open the trace, see the complete execution tree: what the LLM decided, what tool it called, what result it got, and why it generated the final response. 5 minutes vs 2 hours.
Dashboards: what to monitor
Three dashboards: Operational (SRE) with RPS, latency percentiles, error rate, GPU utilization. Costs (business) with daily/weekly/monthly cost, cost per user, tokens consumed. Quality (product) with format compliance rate, user satisfaction, hallucination rate.
Alerting: when and how
Alerts must be actionable. An alert that fires and doesn't require immediate action is noise. Critical alerts for an LLM system: P99 latency above SLA, error rate >5%, GPU VRAM almost full, abnormal daily cost, agent loop detected.
Ejercicio practico
- Add OpenTelemetry to your inference service from TE03. Export latency, token and cost metrics to Prometheus.
- Install self-hosted Langfuse (docker-compose available in their repo). Connect your service for tracing.
- Create 3 Grafana dashboards: operational, costs, quality. Use the Prometheus queries from the module.
- Configure 3 alerts: P99 latency, error rate, and daily cost. Send notifications to Slack or Telegram.
- Generate test traffic (100 requests with the benchmark script from TE03) and verify traces appear in Langfuse.
- Implement an automatic quality score: format compliance via regex. Associate it with Langfuse traces.
Expected result: you can open a dashboard and know in 10 seconds: requests per second, P99 latency, day's cost, and error rate of your LLM system.
Puntos clave
Puntos clave from TE06
- An LLM without observability is a blind system. Metrics (what's happening), logs (what happened exactly), traces (how a request flowed). All three pillars are necessary.
- LLM-specific metrics: TTFT, tokens/s, cost per request, cache hit rate, format compliance. Add these to standard API metrics.
- Langfuse is the reference tool for native LLM observability. Open-source, self-hostable, with integrated scoring and prompt management.
- Tool call and agent tracing is critical. Without it, debugging a multi-step agent is impossible in practice. 5 minutes with tracing vs 2 hours without.
- Actionable alerts, not noise. P99 latency > SLA, error rate > 5%, abnormal cost. If an alert fires and doesn't require action, remove it.
Guia de estudio — Conceptos clave de TE06
Por que observabilidad para IA
- Outputs no deterministas:el mismo input puede producir outputs diferentes. No basta con verificar "funciona/no funciona". Necesitas medir calidad.
- Coste variable:cada request tiene un coste en tokens que depende del input y la generacion. Un prompt mal disenado puede costar 10x mas que uno optimizado.
- Cadenas de ejecucion complejas:un sistema RAG con agentes puede involucrar: embedding, vector search, reranking, LLM principal, tool calls, LLM secundario, postprocesamiento. Trazar todo es critico para debuggear.
Metricas especificas de LLMs
- # Metrica Descripcion Target tipico
- # TTFT Time to first token < 500ms
- # Metrica Descripcion
- # tokens_input_total Tokens de entrada procesados
- # Ejemplo: calcular coste por request
- # Metrica Descripcion Como medir
Langfuse: observabilidad nativa para IA
- Traces de conversacion:visualiza una conversacion completa como arbol de spans, incluyendo el contenido de cada mensaje.
- Scoring:asociar puntuaciones de calidad a trazas (automaticas o humanas).
- Prompt management:versionar y A/B test prompts directamente.
- Cost tracking:calcula costes automaticamente por modelo.
- Datasets y evals:crear datasets de evaluacion desde produccion.
Tracing de tool calls y agentes
- Tracing salva horas de debugging: Sin tracing, debuggear un agente es leer logs en crudo intentando reconstruir que paso. Con tracing, abres la traza, ves el arbol de ejecucion completo: que decidio el LLM, que tool llamo, que resultado obtuvo, y por que genero la respuesta final. 5 minutos vs 2 horas.
Dashboards: que monitorear
- Requests per second (RPS)
- Latencia P50, P95, P99
- Error rate (%)
- GPU utilization y VRAM usage
- KV cache occupancy
- Queue depth
Siguiente: TE07 - Voice AI and Multimodal
Your LLM system has complete observability. Now we expand to more modalities: voice, vision, audio and multimodal pipelines.
Ir al modulo TE07