Implementing LLM Pipeline Observability Infrastructure with OpenTelemetry and GenAI Semantic Conventions

A technical note on implementing distributed tracing, token aggregation, and data redaction for LLM/RAG pipelines using OpenTelemetry architecture and GenAI Semantic Conventions.

As the operations of distributed systems, AI agents, and Retrieval-Augmented Generation (RAG) pipelines grow increasingly complex, the demand to accurately trace the latency, inference costs, and external tool integration success/failure of black-boxed LLM calls has surged. In environments that rely solely on conventional metrics monitoring or isolated log outputs, identifying processing bottlenecks across asynchronous tasks and multi-turn conversations becomes exceedingly difficult. This note examines the technical design and implementation approach for establishing vendor-agnostic telemetry collection and context propagation by adopting OpenTelemetry (OTel) and GenAI Semantic Conventions.

Architecture Overview and Telemetry Integration

OpenTelemetry is a framework that collects, processes, and exports traces, metrics, and logs by binding each signal to a unified context (Trace ID, Span ID, Resource Attributes). It does not provide storage or visualization layers itself; instead, it transmits data via OTLP (OpenTelemetry Protocol) to diverse backends such as Prometheus, Grafana Tempo, Jaeger, and Datadog.

+--------------------------------------------------------------------------------------------------+
|                                    OpenTelemetry (OTel) Scope                                    |
|                                                                                                  |
|  [Applications & AI Pipelines]                                                                   |
|          │                                                                                       |
|          ▼                                                                                       |
|   Instrumentation ──────► Collection ──────► Processing / Transformation ──────► Export Pipeline |
|  (Tracing, Metrics, Logs)  (gRPC / HTTP OTLP)  (Batching, Filtering, Sampling)   (Vendor-Neutral) |
|                                                                                         │        |
|                                                                                         ▼        |
|                                                       [Storage & Visualization Backends]         |
|                                                       Prometheus, Jaeger, Grafana Tempo,         |
|                                                       Datadog, Arize Phoenix, Langfuse           |
+--------------------------------------------------------------------------------------------------+

Context propagation utilizes the W3C TraceContext specification (traceparent header). This generates a directed acyclic graph (DAG) structured span tree spanning across distributed microservices and LLM orchestrators.

$$\text{traceparent: } \text{version(00)}-\text{trace_id(32 hex)}-\text{parent_span_id(16 hex)}-\text{trace_flags(02 hex)}$$

GenAI Semantic Conventions Specification

To ensure observability for generative AI workflows, OpenTelemetry defines standard semantic conventions within the gen_ai.* namespace. Core attribute structures across model inference, vector search, and tool execution are categorized as follows:

Span CategoryStandard Span NameRequired / Key Attributes
Model Inferencechat {model}gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons
Vector SearchRetrievalgen_ai.data_source.id, db.system.name, db.collection.name, gen_ai.retrieval.documents
Tool / Agent Executionexecute_tool {name}gen_ai.tool.name, gen_ai.tool.call.id, gen_ai.tool.call.arguments, gen_ai.tool.call.result, gen_ai.conversation.id

Regarding token usage, gen_ai.usage.input_tokens represents the total number of input tokens including cache hits and writes; therefore, cost calculation when utilizing prompt caching requires distinguishing discrete counters via gen_ai.client.inference.usage.*.

Python Implementation Using OpenLLMetry

The following is a Python implementation example demonstrating both automatic and manual integration of tracing across an entire RAG pipeline using OpenLLMetry (traceloop-sdk).

import os
from traceloop.sdk import Traceloop
from traceloop.sdk.decorators import workflow, task, tool
from openai import OpenAI

# SDK initialization to send traces to the OTLP endpoint
Traceloop.init(
    app_name="rag-agent-service",
    disable_batch=False
)

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

@tool(name="vector_search")
def search_vector_db(query: str) -> list[str]:
    # Document retrieval process compliant with gen_ai.retrieval specifications
    return [
        "OpenTelemetry standardizes metrics, traces, and logs across cloud environments.",
        "OpenLLMetry automates trace generation for modern LLM and AI agent pipelines."
    ]

@task(name="synthesize_prompt")
def construct_prompt(query: str, contexts: list[str]) -> str:
    context_str = "
".join(contexts)
    return f"Context:
{context_str}

Question: {query}
Answer:"

@workflow(name="rag_pipeline")
def run_pipeline(user_query: str) -> str:
    # 1. Context retrieval from knowledge base
    contexts = search_vector_db(query=user_query)
    
    # 2. Prompt generation task
    prompt = construct_prompt(query=user_query, contexts=contexts)
    
    # 3. LLM inference (auto-instrumented child span: chat gpt-4o-mini is generated)
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.2
    )
    answer = response.choices[0].message.content
    return answer

if __name__ == "__main__":
    result = run_pipeline("Explain OpenTelemetry architecture.")
    print(result)

Upon execution, a trace tree with the following hierarchical structure is emitted to the OTLP receiver:

[Trace ID: 4bf92f3577b34da6a3ce929d0e0e4736]
└── workflow rag_pipeline [Status: Ok, Duration: 820ms]
    ├── tool vector_search [Status: Ok, Duration: 45ms]
    │   └── gen_ai.data_source.id = "knowledge_embeddings_v2"
    ├── task synthesize_prompt [Status: Ok, Duration: 2ms]
    └── chat gpt-4o-mini [Status: Ok, Duration: 773ms]
        ├── gen_ai.provider.name = "openai"
        ├── gen_ai.request.model = "gpt-4o-mini"
        ├── gen_ai.response.model = "gpt-4o-mini-2024-07-18"
        ├── gen_ai.request.temperature = 0.2
        ├── gen_ai.usage.input_tokens = 245
        ├── gen_ai.usage.output_tokens = 62
        └── gen_ai.response.finish_reasons = ["stop"]

OpenTelemetry Collector Configuration

This Collector configuration receives OTLP traffic transmitted from the application, performs batch processing and redaction of personal and sensitive data, and routes the data to downstream storage backends.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  memory_limiter:
    check_interval: 1s
    limit_percentage: 75
    spike_limit_percentage: 20

  batch:
    send_batch_size: 512
    timeout: 5s

  # Attribute filtering to prevent sensitive data leakage
  attributes/redaction:
    actions:
      - key: gen_ai.tool.call.arguments
        action: hash
      - key: gen_ai.prompt
        action: delete

exporters:
  otlp/tempo:
    endpoint: tempo:4317
    tls:
      insecure: true
  prometheus:
    endpoint: 0.0.0.0:8889

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, attributes/redaction, batch]
      exporters: [otlp/tempo]
    metrics:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [prometheus]

Troubleshooting

⚠️ 1. Unintended Transmission of Sensitive Data (PII) and Compliance Violations

Symptom: Risk of storing personal information or authentication tokens in trace backends within prompt strings, model output payloads, or tool arguments.

Cause: Content capture is enabled on the SDK side, bypassing explicit opt-in controls.

Mitigation: Disable content collection via environment variables in operational environments.

export TRACELOOP_TRACE_CONTENT=false

Additionally, enforce attribute redaction using Collector processors.

⚠️ 2. TSDB Resource Exhaustion Due to Metrics Cardinality Explosion

Symptom: Rapid memory consumption growth in time-series databases such as Prometheus, leading to OOMKilled events.

Cause: Dynamic identifiers such as gen_ai.conversation.id or gen_ai.tool.call.id are assigned as metrics labels (Dimensions).

Mitigation: Restrict unbounded unique IDs to trace span attributes (Span Attributes) instead of metrics labels.

🛠️ Verification Procedure and Operational Checks

After launching the Collector and application, verify connectivity to the OTLP port and inspect Collector metrics.

$ ss -tulpn | grep -E '4317|4318|8889'
tcp   LISTEN 0      4096         0.0.0.0:4317       0.0.0.0:*    users:(("otelcol",pid=24152,fd=9))
tcp   LISTEN 0      4096         0.0.0.0:4318       0.0.0.0:*    users:(("otelcol",pid=24152,fd=10))
tcp   LISTEN 0      4096         0.0.0.0:8889       0.0.0.0:*    users:(("otelcol",pid=24152,fd=12))

Query the Collector’s internal self-monitoring endpoint (default: 8888) to verify the health of receivers and exporters.

$ curl -s http://localhost:8888/metrics | grep otelcol_receiver_accepted_spans
# HELP otelcol_receiver_accepted_spans Number of spans successfully pushed into the pipeline. [alpha]
# TYPE otelcol_receiver_accepted_spans counter
otelcol_receiver_accepted_spans{receiver="otlp",transport="grpc"} 4

💡 Configuration Notes

Based on community roadmaps, GenAI Semantic Conventions are undergoing active specification revisions in an independent repository (open-telemetry/semantic-conventions-genai). Pay close attention to backward compatibility for attribute names and type definitions, and strictly pin semantic versioning for SDK and Collector packages during production deployments.

Built with Hugo
Theme Stack designed by Jimmy
Privacy Policy Disclaimer Contact