Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(otel): make OTLP export work against Grafana Cloud (#35060)

Yassin Kortam440b1bcf654d
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py
index 12465377b51..11e7ab062b6 100644
--- a/litellm/integrations/opentelemetry.py
+++ b/litellm/integrations/opentelemetry.py
@@ -27,6 +27,7 @@ from litellm.integrations.opentelemetry_utils.gen_ai_semconv import (
OTELSemconvCategory,
parse_semconv_opt_in,
)
+from litellm.integrations.otel.model.semconv import Metric
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.litellm_core_utils.secret_redaction import redact_string
from litellm.secret_managers.main import get_secret_bool, str_to_bool
@@ -597,32 +598,32 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
meter = meter_provider.get_meter(__name__)
self._operation_duration_histogram = meter.create_histogram(
- name="gen_ai.client.operation.duration", # Replace with semconv constant in otel 1.38
+ name=Metric.OPERATION_DURATION,
description="GenAI operation duration",
unit="s",
)
self._token_usage_histogram = meter.create_histogram(
- name="gen_ai.client.token.usage", # Replace with semconv constant in otel 1.38
+ name=Metric.TOKEN_USAGE,
description="GenAI token usage",
unit="{token}",
)
self._cost_histogram = meter.create_histogram(
- name="gen_ai.client.token.cost",
+ name=Metric.TOKEN_COST,
description="GenAI request cost",
unit="USD",
)
self._time_to_first_token_histogram = meter.create_histogram(
- name="gen_ai.client.response.time_to_first_token",
+ name=Metric.TIME_TO_FIRST_TOKEN,
description="Time to first token for streaming requests",
unit="s",
)
self._time_per_output_token_histogram = meter.create_histogram(
- name="gen_ai.client.response.time_per_output_token",
+ name=Metric.TIME_PER_OUTPUT_TOKEN,
description="Average time per output token (generation time / completion tokens)",
unit="s",
)
self._response_duration_histogram = meter.create_histogram(
- name="gen_ai.client.response.duration",
+ name=Metric.RESPONSE_DURATION,
description="Total LLM API generation time (excludes LiteLLM overhead)",
unit="s",
)
@@ -2980,10 +2981,12 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
def _get_metric_reader(self):
"""
Get the appropriate metric reader based on the configuration.
+
+ Histograms keep the SDK's default cumulative temporality: Prometheus-backed
+ OTLP receivers reject delta histograms and drop the whole batch, while
+ backends that prefer delta still accept cumulative.
"""
- from opentelemetry.sdk.metrics import Histogram
from opentelemetry.sdk.metrics.export import (
- AggregationTemporality,
ConsoleMetricExporter,
PeriodicExportingMetricReader,
)
@@ -3014,7 +3017,6 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
exporter = OTLPMetricExporter(
endpoint=normalized_endpoint,
headers=_split_otel_headers,
- preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
@@ -3032,7 +3034,6 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
exporter = OTLPMetricExporter(
endpoint=normalized_endpoint,
headers=_split_otel_headers,
- preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
diff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.py
index 44b2f7e0488..1abe8ca33fa 100644
--- a/litellm/integrations/otel/model/semconv.py
+++ b/litellm/integrations/otel/model/semconv.py
@@ -257,13 +257,27 @@ class LiteLLM:
class Metric:
- """GenAI metric instrument names."""
+ """GenAI metric instrument names.
+
+ Every name here that a convention or a backend defines uses that name, so a
+ consumer charting GenAI telemetry finds litellm's series where it looks for
+ them. ``TOKEN_USAGE``, ``OPERATION_DURATION``, ``TIME_TO_FIRST_TOKEN`` and
+ ``TIME_PER_OUTPUT_TOKEN`` are semconv instruments, defined in the GenAI
+ conventions; the ``gen_ai.client.response.*`` spellings litellm used for the
+ latter two are not conventions at all, so nothing downstream could chart
+ them. Cost has no semconv instrument, so it takes ``gen_ai.usage.cost``, the
+ name backends already query for spend.
+
+ ``RESPONSE_DURATION`` keeps its vendor spelling deliberately: the closest
+ convention, ``gen_ai.server.request.duration``, would collide in meaning with
+ ``OPERATION_DURATION``, which litellm already emits for the whole operation.
+ """
TOKEN_USAGE: Final = "gen_ai.client.token.usage"
OPERATION_DURATION: Final = "gen_ai.client.operation.duration"
- TOKEN_COST: Final = "gen_ai.client.token.cost"
- TIME_TO_FIRST_TOKEN: Final = "gen_ai.client.response.time_to_first_token"
- TIME_PER_OUTPUT_TOKEN: Final = "gen_ai.client.response.time_per_output_token"
+ TOKEN_COST: Final = "gen_ai.usage.cost"
+ TIME_TO_FIRST_TOKEN: Final = "gen_ai.server.time_to_first_token"
+ TIME_PER_OUTPUT_TOKEN: Final = "gen_ai.server.time_per_output_token"
RESPONSE_DURATION: Final = "gen_ai.client.response.duration"
diff --git a/litellm/integrations/otel/model/utils.py b/litellm/integrations/otel/model/utils.py
index f37afc97879..ab54a558a9a 100644
--- a/litellm/integrations/otel/model/utils.py
+++ b/litellm/integrations/otel/model/utils.py
@@ -1,9 +1,11 @@
"""Shared, OpenTelemetry-free helpers for the otel integration.
-Generic value coercion (for reading heterogeneous logging-payload dicts), time
-conversion, and header parsing — pulled out of the individual modules so they
-live in one place. Deliberately free of any ``opentelemetry`` import so the
-OTel-free sources of truth (payloads, semconv, spans, config) can use it too.
+Generic value coercion (for reading heterogeneous logging-payload dicts) and
+time conversion — pulled out of the individual modules so they live in one
+place. Deliberately free of any ``opentelemetry`` import so the OTel-free
+sources of truth (payloads, semconv, spans, config) can use it too. OTLP header
+parsing lives in :mod:`litellm.integrations.otel.plumbing.providers` instead,
+because it delegates to the OTel SDK's own W3C Baggage parser.
"""
from datetime import datetime
@@ -89,15 +91,3 @@ def to_seconds(value: datetime | float | int | str | None) -> float | None:
except ValueError:
continue
return None
-
-
-def parse_headers(raw: str | None) -> dict[str, str]:
- """Parse an OTLP ``"k=v,k=v"`` header string into a dict."""
- headers: dict[str, str] = {}
- if not raw:
- return headers
- for pair in raw.split(","):
- if "=" in pair:
- key, _, value = pair.partition("=")
- headers[key.strip()] = value.strip()
- return headers
diff --git a/litellm/integrations/otel/plumbing/providers.py b/litellm/integrations/otel/plumbing/providers.py
index ced65aa1ec3..ede9acc6d8f 100644
--- a/litellm/integrations/otel/plumbing/providers.py
+++ b/litellm/integrations/otel/plumbing/providers.py
@@ -29,15 +29,13 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
from opentelemetry.trace import Span, SpanKind, Tracer
+from opentelemetry.util.re import parse_env_headers
from litellm._version import version as litellm_version
from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
from litellm.integrations.otel.model.semconv import LiteLLM
from litellm.integrations.otel.model.spans import LiteLLMSpanKind
-# Re-exported so ``providers.parse_headers`` remains a stable entry point.
-from litellm.integrations.otel.model.utils import parse_headers as parse_headers
-
if TYPE_CHECKING:
from opentelemetry.metrics import Meter
from opentelemetry.sdk.metrics.export import MetricReader
@@ -119,6 +117,23 @@ def _otlp_traces_endpoint(endpoint: str | None) -> str | None:
return endpoint + "/v1/traces"
+def parse_headers(raw: str | None) -> dict[str, str]:
+ """Parse an OTLP ``"k=v,k=v"`` header string into a dict.
+
+ ``OTEL_EXPORTER_OTLP_HEADERS`` is W3C Baggage encoded per the OTLP spec, so
+ values are percent-decoded: a vendor that documents
+ ``Authorization=Basic%20<token>`` (Grafana Cloud does, because a bare space
+ is not representable there) has to reach the exporter as ``Basic <token>``,
+ not with a literal ``%20`` that the backend rejects as malformed. The SDK's
+ own parser is used so litellm decodes exactly what the OTLP exporters do
+ when they read the env var themselves; ``liberal`` keeps values that are not
+ percent-encoded (``Authorization=Bearer <token>``) working unchanged.
+ """
+ if not raw:
+ return {}
+ return dict(parse_env_headers(raw, liberal=True))
+
+
def _exporter_from_spec(spec: ExporterSpec) -> SpanExporter:
kind = (spec.kind or "console").lower()
factory = _EXPORTER_FACTORIES.get(kind)
@@ -191,6 +206,13 @@ def build_metric_reader(config: OpenTelemetryV2Config) -> "MetricReader":
``console`` (and any unrecognized kind) exports to the console; ``otlp_http``
and ``otlp_grpc`` export over OTLP with the configured endpoint/headers. The
reader exports on a 5s period, matching v1.
+
+ Histograms keep the SDK's default cumulative temporality. Prometheus-backed
+ OTLP receivers (Grafana Cloud / Mimir, and the Prometheus OTLP endpoint)
+ reject delta histograms outright with ``invalid temporality and type
+ combination``, which drops the whole metric batch, while backends that
+ prefer delta still accept cumulative. The enterprise billing exporter
+ already relies on the same default.
"""
from opentelemetry.sdk.metrics.export import (
ConsoleMetricExporter,
@@ -202,18 +224,12 @@ def build_metric_reader(config: OpenTelemetryV2Config) -> "MetricReader":
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
OTLPMetricExporter as HTTPMetricExporter,
)
- from opentelemetry.sdk.metrics import Histogram
- from opentelemetry.sdk.metrics.export import AggregationTemporality
exporter: Any = HTTPMetricExporter(
endpoint=_otlp_metrics_endpoint(config.endpoint),
headers=parse_headers(config.headers),
- preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
elif kind in ("otlp_grpc", "grpc"):
- from opentelemetry.sdk.metrics import Histogram
- from opentelemetry.sdk.metrics.export import AggregationTemporality
-
try:
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
OTLPMetricExporter as GRPCMetricExporter,
@@ -227,7 +243,6 @@ def build_metric_reader(config: OpenTelemetryV2Config) -> "MetricReader":
exporter = GRPCMetricExporter(
endpoint=config.endpoint,
headers=parse_headers(config.headers),
- preferred_temporality={Histogram: AggregationTemporality.DELTA},
)
else:
exporter = ConsoleMetricExporter()
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_components.py b/tests/test_litellm/integrations/otel/test_otel_v2_components.py
index 5191414edeb..d856d6871a3 100644
--- a/tests/test_litellm/integrations/otel/test_otel_v2_components.py
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_components.py
@@ -451,6 +451,30 @@ def test_parse_headers():
assert providers.parse_headers("no-equals") == {}
+def test_parse_headers_percent_decodes_values():
+ """A percent-encoded OTLP header value reaches the exporter decoded.
+
+ ``OTEL_EXPORTER_OTLP_HEADERS`` is W3C Baggage encoded, and Grafana Cloud
+ documents ``Authorization=Basic%20<token>``. Forwarding the literal ``%20``
+ makes the backend reject the export as a malformed credential.
+ """
+ token = "MTMzNzc4MzpnbGNfZXlKdklqb2lNVEl6TkNJPQ=="
+ assert providers.parse_headers(f"Authorization=Basic%20{token}") == {"authorization": f"Basic {token}"}
+ assert providers.parse_headers("x-scope-orgid=team%20a") == {"x-scope-orgid": "team a"}
+
+
+def test_parse_headers_keeps_unencoded_values_working():
+ """Values that are not percent-encoded keep parsing unchanged.
+
+ Vendors that document a bare space, and litellm's own presets, must survive
+ the switch to the spec-compliant parser. Base64 padding also means a value
+ can contain ``=``, so only the first one may split the pair.
+ """
+ assert providers.parse_headers("Authorization=Bearer sk-123") == {"authorization": "Bearer sk-123"}
+ assert providers.parse_headers("api_key=abc,space_id=xyz") == {"api_key": "abc", "space_id": "xyz"}
+ assert providers.parse_headers("api_key=YWJjZA==") == {"api_key": "YWJjZA=="}
+
+
def test_otlp_traces_endpoint_normalization():
norm = providers._otlp_traces_endpoint
# A base endpoint gets the signal path appended (the common OTLP env shape).
@@ -487,6 +511,24 @@ def test_build_span_exporter_variants():
assert "OTLPSpanExporter" in type(http_exporter).__name__
+def test_otlp_metric_exporter_uses_cumulative_histogram_temporality():
+ """Histograms must export as cumulative, not delta.
+
+ Prometheus-backed OTLP receivers (Grafana Cloud / Mimir) reject delta
+ histograms with ``invalid temporality and type combination`` and drop the
+ entire metric batch, so a delta default silently loses every GenAI metric.
+ """
+ from opentelemetry.sdk.metrics import Histogram
+ from opentelemetry.sdk.metrics.export import AggregationTemporality
+
+ reader = providers.build_metric_reader(
+ OpenTelemetryV2Config(exporter="otlp_http", endpoint="http://h:4318")
+ )
+ temporality = reader._exporter._preferred_temporality # noqa: SLF001 # exporter exposes no public accessor
+
+ assert temporality[Histogram] is AggregationTemporality.CUMULATIVE
+
+
def test_otlp_logs_endpoint_normalization():
norm = providers._otlp_logs_endpoint
# A base endpoint gets the signal path appended (the common OTLP env shape).
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py
index 02954578644..41c02501acc 100644
--- a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py
@@ -2120,9 +2120,9 @@ def test_valid_metric_filter_records_six_metrics(monkeypatch):
assert _emitted_metric_names(reader) == {
"gen_ai.client.operation.duration",
"gen_ai.client.token.usage",
- "gen_ai.client.token.cost",
- "gen_ai.client.response.time_to_first_token",
- "gen_ai.client.response.time_per_output_token",
+ "gen_ai.usage.cost",
+ "gen_ai.server.time_to_first_token",
+ "gen_ai.server.time_per_output_token",
"gen_ai.client.response.duration",
}
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py b/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py
index 29067f91b5a..b2d89053ba3 100644
--- a/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py
@@ -39,9 +39,9 @@ from litellm.integrations.otel.plumbing.providers import ( # noqa: E402
OPERATION_DURATION = "gen_ai.client.operation.duration"
TOKEN_USAGE = "gen_ai.client.token.usage"
-TOKEN_COST = "gen_ai.client.token.cost"
-TIME_TO_FIRST_TOKEN = "gen_ai.client.response.time_to_first_token"
-TIME_PER_OUTPUT_TOKEN = "gen_ai.client.response.time_per_output_token"
+TOKEN_COST = "gen_ai.usage.cost"
+TIME_TO_FIRST_TOKEN = "gen_ai.server.time_to_first_token"
+TIME_PER_OUTPUT_TOKEN = "gen_ai.server.time_per_output_token"
RESPONSE_DURATION = "gen_ai.client.response.duration"
ALL_METRICS = frozenset(
diff --git a/tests/test_litellm/integrations/test_opentelemetry.py b/tests/test_litellm/integrations/test_opentelemetry.py
index 7ffd09b931f..05205cb76f2 100644
--- a/tests/test_litellm/integrations/test_opentelemetry.py
+++ b/tests/test_litellm/integrations/test_opentelemetry.py
@@ -412,6 +412,40 @@ class TestOpenTelemetryProviderInitialization(unittest.TestCase):
current_provider is existing_provider
), "Existing TracerProvider should be respected and not overridden"
+ @patch.dict(
+ os.environ, {"LITELLM_OTEL_INTEGRATION_ENABLE_METRICS": "true"}, clear=True
+ )
+ def test_init_metrics_creates_instruments_under_their_published_names(self):
+ """
+ The v1 engine's instrument names are a public contract.
+
+ Every name here is what a backend queries: four are GenAI semantic
+ conventions and gen_ai.usage.cost is the name backends query for spend.
+ A rename is breaking for anyone charting them, so it has to be a
+ deliberate edit to the shared Metric constants and to this list, never
+ a silent drift between the v1 and v2 engines.
+ """
+ from opentelemetry import metrics
+
+ metrics.set_meter_provider(MeterProvider(metric_readers=[InMemoryMetricReader()]))
+ otel_integration = OpenTelemetry(config=OpenTelemetryConfig.from_env())
+
+ assert {
+ otel_integration._operation_duration_histogram.name,
+ otel_integration._token_usage_histogram.name,
+ otel_integration._cost_histogram.name,
+ otel_integration._time_to_first_token_histogram.name,
+ otel_integration._time_per_output_token_histogram.name,
+ otel_integration._response_duration_histogram.name,
+ } == {
+ "gen_ai.client.operation.duration",
+ "gen_ai.client.token.usage",
+ "gen_ai.usage.cost",
+ "gen_ai.server.time_to_first_token",
+ "gen_ai.server.time_per_output_token",
+ "gen_ai.client.response.duration",
+ }
+
@patch.dict(
os.environ, {"LITELLM_OTEL_INTEGRATION_ENABLE_METRICS": "true"}, clear=True
)