Skip to content

LLM API Observability Setup: Tracing, Logging, and Metrics

Summary

LLM API observability includes collecting traces, logs, and metrics, enabling tracking of quality, cost, and latency.

Why Observability is Needed

Without observability, it's impossible to understand why a model responds incorrectly, where costs are rising, and which requests cause errors. Tracing connects requests to responses, logs capture details, and metrics provide an aggregated picture.

Observability Components

1. Tracing

Tracing records the request path: prompt, response, model, tokens, latency. Use Langfuse or LangSmith for automatic collection.

from langfuse import Langfuse

langfuse = Langfuse(
    public_key="YOUR_PUBLIC_KEY",
    secret_key="YOUR_SECRET_KEY",
    host="https://cloud.langfuse.com"
)

trace = langfuse.trace(name="product-classification")
span = trace.span(name="llm-call")

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": prompt}]
)

span.end(
    output=response.choices[0].message.content,
    metadata={
        "model": "deepseek-chat",
        "prompt_tokens": response.usage.prompt_tokens,
        "completion_tokens": response.usage.completion_tokens
    }
)

2. Logging

Log each request and response in a structured format. This helps reproduce errors and analyze model behavior.

import logging
import json

logger = logging.getLogger("llm_api")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("llm.log")
handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
logger.addHandler(handler)

def log_request(prompt, response, error=None):
    entry = {
        "prompt": prompt,
        "response": response,
        "error": str(error) if error else None,
        "timestamp": time.time()
    }
    logger.info(json.dumps(entry, ensure_ascii=False))

3. Metrics

Collect metrics: number of requests, average latency, error rate, cost. Use Prometheus or a simple counter in code.

from prometheus_client import Counter, Histogram, start_http_server

requests_total = Counter("llm_requests_total", "Total LLM requests")
request_duration = Histogram("llm_request_duration_seconds", "LLM request duration")
errors_total = Counter("llm_errors_total", "Total LLM errors")

start_http_server(8000)

with request_duration.time():
    try:
        response = client.chat.completions.create(...)
        requests_total.inc()
    except Exception:
        errors_total.inc()

Tools

Tool Type Features
Langfuse Tracing Open source, Python integration
LangSmith Tracing Paid, deep integration with LangChain
Helicone Proxy Transparent proxy for API
Prometheus + Grafana Metrics Standard for monitoring

Practical Recommendations

  • Log full prompt and response, but mask PII.
  • Add request ID to logs for correlation with traces.
  • Set up alerts for error and latency spikes.
  • Store logs for limited time to avoid overpaying for storage.

Conclusion

Observability is a mandatory part of production systems with LLM. Start with tracing through Langfuse, add logging and metrics. This allows for quick problem finding and cost optimization.