Introduction
As Large Language Model (LLM) applications move from experimental prototypes to production-critical systems, developers encounter a recurring problem: the "black box" nature of model inference. Unlike traditional microservices, where a request's path is deterministic and its failure modes are well-understood, LLM requests are stochastic, high-latency, and computationally expensive. When a user reports that a response was "wrong," "slow," or "weird," traditional logging is often insufficient to diagnose the root cause. Was the prompt poorly constructed? Did the model experience a transient spike in latency? Or did a retrieval-augmented generation (RAG) step inject irrelevant context?
Production observability for LLMs requires a shift from simple logging to comprehensive telemetry. The goal is to achieve full visibility into the entire request lifecycle—from the initial user input and the construction of the final prompt, through the model's inference process, and finally to the post-processing and delivery of the output. This guide explores how to implement this visibility using OpenTelemetry (OTel) and the emerging GenAI semantic conventions, providing a standardized, provider-agnostic framework for monitoring AI systems at scale.
The Power of Semantic Conventions
One of the primary challenges in LLM observability is the fragmentation of provider APIs. OpenAI, Anthropic, and Google each have different ways of reporting token usage, latency, and error codes. If an organization uses multiple models—a common strategy for cost and reliability—they often end up with a fragmented monitoring stack where metrics from one provider cannot be easily compared with another.
This is where OpenTelemetry's GenAI semantic conventions become critical. Semantic conventions are a set of standardized names for attributes and metrics. Instead of using provider-specific keys like usage.completion_tokens or prompt_tokens, the GenAI specification defines universal attributes such as gen_ai.request.model and gen_ai.response.tokens_generated.
By adhering to these standards, organizations can build a single observability dashboard that works regardless of the underlying model. This standardization allows for:
- Provider Agnostic Monitoring: Compare the performance and cost of Claude 3.5 Sonnet versus GPT-4o using the same set of metrics.
- Consistent Tooling: Use any OpenTelemetry-compliant backend (such as Honeycomb, Jaeger, or Prometheus) without writing custom adapters for every new model release.
- Simplified Governance: Implement global alerts based on standardized attributes, such as alerting when any model's p99 latency exceeds 5 seconds, regardless of the provider.
Distributed Tracing for LLMs
In a production LLM application, a single user request rarely results in a single API call. A typical request might involve a series of steps: authenticating the user, querying a vector database for context, rewriting the prompt, calling the LLM, and then sanitizing the output. If the final response is slow, knowing that the "LLM call took 3 seconds" is only part of the story. The real bottleneck might be a slow vector search that took 2 seconds before the model was even invoked.
Distributed tracing solves this by treating the entire request as a "trace" composed of multiple "spans." Each span represents a discrete unit of work.
Mapping the LLM Request Lifecycle
A well-instrumented LLM trace should include the following spans:
- Root Span: The overall request from the user's perspective.
- Context Retrieval Span: The time spent searching knowledge bases or databases. This should include attributes for the query used and the number of documents retrieved.
- Prompt Construction Span: The time spent assembling the system prompt, few-shot examples, and retrieved context. This is where you capture the final prompt sent to the model.
- Model Inference Span: The actual call to the LLM provider. This is the most critical span, capturing the model ID, the prompt tokens, the completion tokens, and the raw response.
- Post-Processing Span: The time spent on output validation, sanitization, or formatting.
Example Instrumentation Pattern
Using an OpenTelemetry-compatible library like OpenLLMetry, this tracing happens automatically. Here is a conceptual example of how these spans are captured in a Python application:
from opentelemetry import trace
from openllmetry import OpenLLMetry
# Initialize OpenLLMetry to automatically instrument LLM calls
OpenLLMetry.init(api_key="your-api-key")
tracer = trace.get_tracer(__name__)
async def handle_user_query(user_input):
with tracer.start_as_current_span("handle_user_query") as root_span:
# Step 1: Context Retrieval
with tracer.start_as_current_span("retrieve_context") as retrieval_span:
context = await vector_db.search(user_input)
retrieval_span.set_attribute("retrieval.docs_count", len(context))
# Step 2: Model Inference (Auto-instrumented by OpenLLMetry)
# This will create a span with gen_ai.request.model and usage attributes
response = await llm_client.complete(prompt=f"Context: {context}\\nQuery: {user_input}")
# Step 3: Post-processing
with tracer.start_as_current_span("sanitize_output") as sanitize_span:
final_output = sanitize(response.text)
return final_output
By visualizing this trace in a UI, developers can immediately see where the latency is occurring and how the prompt evolved at each stage of the pipeline.
Critical Observability Metrics
While traces provide depth for individual requests, metrics provide the breadth needed to understand system health over time. For LLM applications, three categories of metrics are essential.
1. Performance and Latency
Standard latency (p50, p95, p99) is necessary but insufficient. LLMs generate tokens sequentially, meaning the total time to finish a response is proportional to the output length. To get a true sense of performance, you must track:
- Time to First Token (TTFT): The time from the request being sent to the first token being generated. This is the primary driver of perceived user experience in streaming interfaces.
- Tokens Per Second (TPS): The throughput of the model. This helps distinguish between a slow model and a model that is simply generating a very long response.
- Request-to-Token Ratio: Analyzing how much input context is required to generate a useful output, which helps in optimizing prompt length.
2. Cost and Token Usage
In production, token usage is a direct financial cost. Monitoring this at the aggregate level is not enough; you need granular visibility:
- Token Consumption by User/Feature: Identify which users or application features are driving the most cost.
- Cache Hit Rate: If using a prompt cache, track the percentage of tokens served from the cache versus the model to measure cost savings.
- Token Wastage: Monitor the ratio of prompt tokens to output tokens to identify inefficient prompt templates that are wasting money.
3. Quality and Reliability Signals
Quality is the hardest metric to track, but observability can provide the necessary signals:
- Refusal Rate: Track how often the model returns a "I cannot answer this" response. A spike in refusal rates often indicates a change in the provider's safety filters or a shift in user input patterns.
- Format Violation Rate: For applications requiring structured output (JSON/YAML), track the percentage of responses that fail schema validation. This is a leading indicator of prompt degradation.
- Sentiment and Feedback Correlation: Link user "thumbs up/down" feedback directly to the specific trace ID of the request, allowing you to analyze exactly what prompt and model version led to a poor experience.
Integration with the OpenTelemetry Ecosystem
Implementing instrumentation is only the first step. The real value comes from how the data is transported and analyzed. The standard architecture for LLM observability follows the OpenTelemetry pipeline:
- Instrumentation: Libraries (like OpenLLMetry) capture spans and metrics using the GenAI semantic conventions.
- OTel Collector: A vendor-neutral proxy that receives the telemetry data. The collector can be configured to scrub PII from prompts before sending data to a backend, ensuring security and compliance.
- Backend/Storage: The data is sent to a tracing backend (e.g., Jaeger) and a metrics backend (e.g., Prometheus).
This decoupled architecture prevents vendor lock-in. If an organization decides to switch from one observability provider to another, they only need to change the exporter configuration in the OTel Collector, rather than re-instrumenting their entire codebase.
Advanced Patterns: Correlating Traces with Evaluation
The ultimate goal of observability is to move from "observing" to "improving." One of the most powerful patterns in production AI is correlating distributed traces with evaluation metrics.
By attaching a trace_id to every request, you can export a sample of production traces to an evaluation pipeline. For example, you can take the 100 slowest requests from the last 24 hours (identified via Prometheus metrics), retrieve their full traces (from Jaeger), and run those specific prompts through an "LLM-as-a-Judge" framework to see if the latency trade-off resulted in higher quality. This creates a tight feedback loop between production performance and model optimization.
For a more comprehensive look at the infrastructure side of this process, refer to our guide on Production LLM Deployment Best Practices, which covers the underlying scaling and infrastructure patterns that support these observability layers.
Conclusion
Moving from "vibes-based" development to data-driven production requires a commitment to standardized observability. By implementing OpenTelemetry and adhering to the GenAI semantic conventions, developers can transform the LLM "black box" into a transparent system. Distributed tracing reveals the hidden bottlenecks in RAG pipelines, and standardized metrics provide the financial and operational clarity needed to scale AI applications sustainably. As the ecosystem evolves, these standards will ensure that our observability stacks remain resilient to the rapid pace of model innovation, allowing us to focus on building better AI experiences rather than fighting with provider-specific logs.