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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(otel-v2): emit the 6 gen_ai.client.* metrics at parity with v1 (#30326)
Yassin Kortam45d5153c125a
diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.pyindex 5e683ce7b99..a8378b6a043 100644--- a/litellm/integrations/otel/logger.py+++ b/litellm/integrations/otel/logger.py@@ -10,6 +10,7 @@ from opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.trace import Span, Tracer, get_current_span, use_spanimport litellm+from litellm._logging import verbose_loggerfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.otel.model.baggage import promoted_baggagefrom litellm.integrations.otel.model.config import OpenTelemetryV2Config@@ -36,7 +37,12 @@ from litellm.integrations.otel.model.payloads import (SpanError,is_mcp_tool_call,)+from litellm.integrations.otel.plumbing.metrics import (+ GenAIMetricRecorder,+ create_genai_metrics,+)from litellm.integrations.otel.plumbing.providers import (+ build_meter_provider,build_tracer_provider,get_tracer,)@@ -95,7 +101,7 @@ class OpenTelemetryV2(CustomLogger):callback_name: str | None = None,tracer_provider: TracerProvider | None = None,logger_provider: Any | None = None, # reserved for OTel logs- meter_provider: Any | None = None, # reserved for metrics+ meter_provider: Any | None = None,**kwargs: Any,) -> None:super().__init__(**kwargs)@@ -107,6 +113,8 @@ class OpenTelemetryV2(CustomLogger):else build_tracer_provider(self.config))self.tracer: Tracer = get_tracer(self._tracer_provider, LITELLM_TRACER_NAME)+ self._metrics_recorder = self._init_metrics(meter_provider)+ self._metric_filter_error_logged = Falseself._emitter = SpanEmitter(self.tracer, self.config, mappers=resolve_mappers(self.config.mapper_names))@@ -116,6 +124,22 @@ class OpenTelemetryV2(CustomLogger):self._open_llm_calls: "OrderedDict[str, _LLMCallSpan]" = OrderedDict()self._init_otel_logger_on_litellm_proxy()+ def _init_metrics(self, meter_provider: Any | None) -> "GenAIMetricRecorder | None":+ """Create the six GenAI histograms when metrics are enabled, else ``None``.++ ``meter_provider`` is an explicit override (tests inject one); otherwise a+ provider is built from the config's exporter selection.+ """+ if not self.config.enable_metrics:+ return None+ provider = (+ meter_provider+ if meter_provider is not None+ else build_meter_provider(self.config)+ )+ meter = provider.get_meter(LITELLM_TRACER_NAME)+ return GenAIMetricRecorder(create_genai_metrics(meter), self.callback_name)+# ====================================================================== ## Proxy global registration# ====================================================================== #@@ -208,6 +232,25 @@ class OpenTelemetryV2(CustomLogger):if self._emit_mcp_tool_call(kwargs, start_time, end_time):returnself._close_llm_call(kwargs, start_time, end_time)+ self._record_metrics(kwargs, response_obj, start_time, end_time)++ def _record_metrics(self, kwargs, response_obj, start_time, end_time) -> None:+ """Record the GenAI metrics for a successful LLM call. Best-effort: a+ recording failure (e.g. a malformed payload) must never break the span+ close or the request itself."""+ if self._metrics_recorder is None:+ return+ try:+ self._metrics_recorder.record(kwargs, response_obj, start_time, end_time)+ except ValueError as exc:+ if not self._metric_filter_error_logged:+ verbose_logger.error(+ "OpenTelemetryV2: invalid otel.attributes metric filter, metrics disabled: %s",+ exc,+ )+ self._metric_filter_error_logged = True+ except Exception as exc:+ verbose_logger.debug("OpenTelemetryV2: metric recording failed: %s", exc)async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):if self._emit_mcp_tool_call(kwargs, start_time, end_time):diff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.pyindex bb93a357516..6315a5a4a89 100644--- a/litellm/integrations/otel/model/semconv.py+++ b/litellm/integrations/otel/model/semconv.py@@ -230,6 +230,10 @@ class Metric: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"+ RESPONSE_DURATION: Final = "gen_ai.client.response.duration"# litellm ``custom_llm_provider`` -> ``gen_ai.provider.name`` value.diff --git a/litellm/integrations/otel/plumbing/metrics.py b/litellm/integrations/otel/plumbing/metrics.pyindex edd120f91e6..95ac939ff7f 100644--- a/litellm/integrations/otel/plumbing/metrics.py+++ b/litellm/integrations/otel/plumbing/metrics.py@@ -1,28 +1,265 @@-"""GenAI client metrics (token usage + operation duration histograms)."""+"""GenAI client metrics: the six ``gen_ai.client.*`` histograms plus the+recorder that builds attributes, applies the shared cardinality filter, and+records a request's metrics in the success path.++The instrument names/units/descriptions and the recording + timing math mirror+the v1 :mod:`litellm.integrations.opentelemetry` integration so both engines emit+identical metrics. The attribute cardinality filter is reused from v1 by import+(no duplication of the valid-name set or its validation).+"""from dataclasses import dataclass+from datetime import datetime+from typing import Any, FrozenSet, Mapping, Optionalfrom opentelemetry.metrics import Histogram, Meter-from litellm.integrations.otel.model.semconv import Metric+import litellm+from litellm.integrations.opentelemetry import (+ METRIC_METADATA_KEYS,+ TOKEN_TYPE_ATTRIBUTE,+ _build_metric_attribute_filter,+ _resolve_metric_attribute_filter,+)+from litellm.integrations.otel.model.semconv import Metric, resolve_operation+from litellm.integrations.otel.model.utils import to_seconds+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps@dataclass(frozen=True)class GenAIMetrics:- token_usage: Histogramoperation_duration: Histogram+ token_usage: Histogram+ token_cost: Histogram+ time_to_first_token: Histogram+ time_per_output_token: Histogram+ response_duration: Histogramdef create_genai_metrics(meter: Meter) -> GenAIMetrics:return GenAIMetrics(+ operation_duration=meter.create_histogram(+ name=Metric.OPERATION_DURATION,+ unit="s",+ description="GenAI operation duration",+ ),token_usage=meter.create_histogram(name=Metric.TOKEN_USAGE,unit="{token}",- description="Number of tokens used per GenAI request.",+ description="GenAI token usage",),- operation_duration=meter.create_histogram(- name=Metric.OPERATION_DURATION,+ token_cost=meter.create_histogram(+ name=Metric.TOKEN_COST,+ unit="USD",+ description="GenAI request cost",+ ),+ time_to_first_token=meter.create_histogram(+ name=Metric.TIME_TO_FIRST_TOKEN,+ unit="s",+ description="Time to first token for streaming requests",+ ),+ time_per_output_token=meter.create_histogram(+ name=Metric.TIME_PER_OUTPUT_TOKEN,+ unit="s",+ description="Average time per output token (generation time / completion tokens)",+ ),+ response_duration=meter.create_histogram(+ name=Metric.RESPONSE_DURATION,unit="s",- description="GenAI operation duration.",+ description="Total LLM API generation time (excludes LiteLLM overhead)",),)+++class GenAIMetricRecorder:+ """Records the six GenAI histograms for one successful LLM call.++ The cardinality filter is resolved lazily on the first record: the proxy+ populates ``callback_settings.otel.attributes`` after the logger is built, so+ reading it at construction time would miss it. ``gen_ai.token.type`` is added+ to the token-usage attributes after filtering so the input/output split always+ survives.+ """++ def __init__(+ self, metrics: GenAIMetrics, callback_name: Optional[str] = None+ ) -> None:+ self._metrics = metrics+ self._callback_name = callback_name+ self._include: Optional[FrozenSet[str]] = None+ self._exclude: Optional[FrozenSet[str]] = None+ self._filter_resolved = False++ def record(+ self,+ kwargs: Mapping[str, Any],+ response_obj: Any,+ start_time: datetime,+ end_time: datetime,+ ) -> None:+ common_attrs = self._filter_attributes(self._common_attributes(kwargs))+ duration_s = (end_time - start_time).total_seconds()++ self._metrics.operation_duration.record(duration_s, attributes=common_attrs)+ self._record_token_usage(response_obj, common_attrs)++ cost = kwargs.get("response_cost")+ if cost:+ self._metrics.token_cost.record(cost, attributes=common_attrs)++ self._record_time_to_first_token(kwargs, common_attrs)+ self._record_time_per_output_token(+ kwargs, response_obj, end_time, duration_s, common_attrs+ )+ self._record_response_duration(kwargs, end_time, common_attrs)++ # ------------------------------------------------------------------ #+ # Attribute building + cardinality filter+ # ------------------------------------------------------------------ #++ def _common_attributes(self, kwargs: Mapping[str, Any]) -> dict:+ params = kwargs.get("litellm_params") or {}+ provider = params.get("custom_llm_provider", "Unknown")+ common_attrs: dict = {+ "gen_ai.operation.name": resolve_operation(kwargs.get("call_type")).value,+ "gen_ai.system": provider,+ "gen_ai.request.model": kwargs.get("model"),+ "gen_ai.framework": "litellm",+ }++ std_log = kwargs.get("standard_logging_object")+ md = getattr(std_log, "metadata", None) or (std_log or {}).get("metadata", {})+ for key in METRIC_METADATA_KEYS:+ value = md.get(key)+ if value is None:+ continue+ if isinstance(value, (dict, list)):+ common_attrs[f"metadata.{key}"] = safe_dumps(value)+ else:+ common_attrs[f"metadata.{key}"] = str(value)++ hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get(+ "hidden_params", {}+ )+ if hidden_params:+ common_attrs["hidden_params"] = safe_dumps(hidden_params)++ return common_attrs++ def _ensure_filter(self) -> None:+ if self._filter_resolved:+ return+ attributes = None+ if self._callback_name in (None, "otel"):+ otel_settings = (litellm.callback_settings or {}).get("otel") or {}+ raw = (+ otel_settings.get("attributes")+ if isinstance(otel_settings, dict)+ else None+ )+ if raw is not None:+ attributes = _build_metric_attribute_filter(raw)+ # A bad filter (include_list + exclude_list both set, an unfilterable name)+ # raises here; the caller (logger._record_metrics) surfaces it once at ERROR+ # so the operator-fixable config error is visible. Not cached on the raise+ # path -- _filter_resolved stays False -- so a corrected config takes effect+ # without reconstructing the recorder.+ self._include, self._exclude = _resolve_metric_attribute_filter(attributes)+ self._filter_resolved = True++ def _filter_attributes(self, attrs: dict) -> dict:+ self._ensure_filter()+ if self._include is not None:+ return {k: v for k, v in attrs.items() if k in self._include}+ if self._exclude is not None:+ return {k: v for k, v in attrs.items() if k not in self._exclude}+ return attrs++ # ------------------------------------------------------------------ #+ # Per-metric recording+ # ------------------------------------------------------------------ #++ def _record_token_usage(self, response_obj: Any, common_attrs: dict) -> None:+ if not response_obj:+ return+ usage = response_obj.get("usage")+ if not usage:+ return+ in_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "input"}+ out_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "output"}+ self._metrics.token_usage.record(+ usage.get("prompt_tokens", 0), attributes=in_attrs+ )+ self._metrics.token_usage.record(+ usage.get("completion_tokens", 0), attributes=out_attrs+ )++ def _record_time_to_first_token(+ self, kwargs: Mapping[str, Any], common_attrs: dict+ ) -> None:+ if not kwargs.get("optional_params", {}).get("stream", False):+ return+ api_call_start = to_seconds(kwargs.get("api_call_start_time"))+ completion_start = to_seconds(kwargs.get("completion_start_time"))+ if api_call_start is None or completion_start is None:+ return+ self._metrics.time_to_first_token.record(+ completion_start - api_call_start, attributes=common_attrs+ )++ def _record_time_per_output_token(+ self,+ kwargs: Mapping[str, Any],+ response_obj: Any,+ end_time: datetime,+ duration_s: float,+ common_attrs: dict,+ ) -> None:+ completion_tokens = None+ if response_obj and (usage := response_obj.get("usage")):+ completion_tokens = usage.get("completion_tokens")+ if completion_tokens is None or completion_tokens <= 0:+ return++ end_ts = to_seconds(end_time)+ if end_ts is None:+ generation_time = duration_s+ else:+ completion_start_time = kwargs.get("completion_start_time")+ api_call_start_time = kwargs.get("api_call_start_time")+ if completion_start_time is not None:+ completion_start = to_seconds(completion_start_time)+ generation_time = (+ duration_s+ if completion_start is None+ else end_ts - completion_start+ )+ elif api_call_start_time is not None:+ api_call_start = to_seconds(api_call_start_time)+ generation_time = (+ duration_s if api_call_start is None else end_ts - api_call_start+ )+ else:+ generation_time = duration_s++ if generation_time > 0:+ self._metrics.time_per_output_token.record(+ generation_time / completion_tokens, attributes=common_attrs+ )++ def _record_response_duration(+ self, kwargs: Mapping[str, Any], end_time: datetime, common_attrs: dict+ ) -> None:+ api_call_start_time = kwargs.get("api_call_start_time")+ if api_call_start_time is None:+ return+ _end_time = kwargs.get("end_time") or end_time+ if _end_time is None:+ _end_time = datetime.now()+ api_call_start = to_seconds(api_call_start_time)+ end_ts = to_seconds(_end_time)+ if api_call_start is None or end_ts is None:+ return+ duration = end_ts - api_call_start+ if duration > 0:+ self._metrics.response_duration.record(duration, attributes=common_attrs)diff --git a/litellm/integrations/otel/plumbing/providers.py b/litellm/integrations/otel/plumbing/providers.pyindex 4c98802479a..a4362f05e86 100644--- a/litellm/integrations/otel/plumbing/providers.py+++ b/litellm/integrations/otel/plumbing/providers.py@@ -1,6 +1,6 @@"""Provider / exporter factory + the Baggage span processor."""-from typing import Callable, Iterable+from typing import TYPE_CHECKING, Any, Callable, Iterablefrom opentelemetry import baggagefrom opentelemetry.context import Context@@ -25,6 +25,10 @@ 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.sdk.metrics import MeterProvider+ from opentelemetry.sdk.metrics.export import MetricReader+_SPAN_KIND_BY_ROLE_KIND: dict[LiteLLMSpanKind, SpanKind] = {LiteLLMSpanKind.SERVER: SpanKind.SERVER,LiteLLMSpanKind.CLIENT: SpanKind.CLIENT,@@ -157,6 +161,91 @@ def build_span_exporter(config: OpenTelemetryV2Config) -> SpanExporter:)+def _otlp_metrics_endpoint(endpoint: str | None) -> str | None:+ """Point an OTLP/HTTP base endpoint at the ``/v1/metrics`` signal path.++ The OTLP/HTTP exporter only appends ``/v1/metrics`` when it reads+ ``OTEL_EXPORTER_OTLP_ENDPOINT`` itself; an explicitly passed endpoint is used+ verbatim, so a base URL would POST to the root. Mirror ``_otlp_traces_endpoint``+ for the metrics signal (rewriting a sibling signal path when present).+ """+ if not endpoint:+ return endpoint+ endpoint = endpoint.rstrip("/")+ if endpoint.endswith("/v1/metrics"):+ return endpoint+ for other_signal in ("/v1/traces", "/v1/logs"):+ if endpoint.endswith(other_signal):+ return endpoint[: -len(other_signal)] + "/v1/metrics"+ return endpoint + "/v1/metrics"+++def build_metric_reader(config: OpenTelemetryV2Config) -> "MetricReader":+ """Build a metric reader mirroring v1's exporter selection.++ ``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.+ """+ from opentelemetry.sdk.metrics.export import (+ ConsoleMetricExporter,+ PeriodicExportingMetricReader,+ )++ kind = (config.exporter or "console").lower()+ if kind in ("otlp_http", "http", "http/protobuf", "http/json"):+ 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,+ )+ except ImportError as exc:+ raise ImportError(+ "OpenTelemetry OTLP gRPC metric exporter is not available. Install "+ "`opentelemetry-exporter-otlp` and `grpcio` (or `litellm[grpc]`)."+ ) from exc++ exporter = GRPCMetricExporter(+ endpoint=config.endpoint,+ headers=parse_headers(config.headers),+ preferred_temporality={Histogram: AggregationTemporality.DELTA},+ )+ else:+ exporter = ConsoleMetricExporter()++ return PeriodicExportingMetricReader(exporter, export_interval_millis=5000)+++def build_meter_provider(+ config: OpenTelemetryV2Config,+ metric_reader: "MetricReader | None" = None,+) -> "MeterProvider":+ """Build the :class:`MeterProvider` for GenAI metrics.++ ``metric_reader`` is an explicit override (tests inject an+ ``InMemoryMetricReader``); otherwise the reader is selected from the config's+ exporter kind via :func:`build_metric_reader`.+ """+ from opentelemetry.sdk.metrics import MeterProvider++ reader = metric_reader if metric_reader is not None else build_metric_reader(config)+ return MeterProvider(metric_readers=[reader], resource=build_resource(config))++def build_resource(config: OpenTelemetryV2Config) -> Resource:attributes: dict[str, str] = {"service.name": config.service_name}if config.deployment_environment:diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.pyindex 8dffb71bbf0..77ee4d0a5a9 100644--- a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py+++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py@@ -8,7 +8,7 @@ hooks, proxy SERVER span lifecycle (start + setters), parent-context resolutionimport asyncioimport contextlib-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezoneimport pytest@@ -1314,3 +1314,178 @@ def test_module_level_emit_guardrail_span_swallows_emit_errors(monkeypatch):monkeypatch.setattr(otel_logger, "_registered_v2_logger", lambda: _Boom())otel_logger.emit_guardrail_span(_guardrail_entry(start=1.0, end=2.0))+++# --------------------------------------------------------------------------- #+# Metrics: invalid attribute-filter config is visible, not a silent no-op+# --------------------------------------------------------------------------- #+++def _emitted_metric_names(reader) -> set:+ data = reader.get_metrics_data()+ if data is None:+ return set()+ return {+ m.name+ for rm in data.resource_metrics+ for sm in rm.scope_metrics+ for m in sm.metrics+ if any(m.data.data_points)+ }+++def _metric_success_kwargs() -> dict:+ return {+ "model": "gpt-4o-mini",+ "call_type": "acompletion",+ "litellm_params": {"custom_llm_provider": "openai"},+ "optional_params": {},+ "response_cost": 0.001,+ "standard_logging_object": {"metadata": {}, "hidden_params": {}},+ }+++def test_invalid_metric_filter_logged_once_records_nothing(caplog, monkeypatch):+ """An invalid ``callback_settings.otel.attributes`` (include_list + exclude_list+ both set) must make the operator-fixable config error visible once at ERROR and+ record no metrics — without raising out of the success path and without+ per-request log spam. Mirrors the v1 fix against the silent-no-op failure mode.+ """+ import logging++ from opentelemetry.sdk.metrics import MeterProvider+ from opentelemetry.sdk.metrics.export import InMemoryMetricReader++ import litellm++ monkeypatch.setattr(+ litellm,+ "callback_settings",+ {+ "otel": {+ "attributes": {+ "include_list": ["gen_ai.system"],+ "exclude_list": ["hidden_params"],+ }+ }+ },+ raising=False,+ )++ cfg = OpenTelemetryV2Config(exporter="in_memory", enable_metrics=True)+ reader = InMemoryMetricReader()+ logger = OpenTelemetryV2(+ config=cfg,+ callback_name="otel",+ tracer_provider=providers.build_tracer_provider(cfg),+ meter_provider=MeterProvider(metric_readers=[reader]),+ )++ start = datetime.now(timezone.utc)+ end = start + timedelta(seconds=1)+ response_obj = {"usage": {"prompt_tokens": 1, "completion_tokens": 1}}++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ # Neither call may raise; the bad filter is caught in the logger.+ asyncio.run(+ logger.async_log_success_event(+ _metric_success_kwargs(), response_obj, start, end+ )+ )+ asyncio.run(+ logger.async_log_success_event(+ _metric_success_kwargs(), response_obj, start, end+ )+ )++ assert _emitted_metric_names(reader) == set() # nothing recorded+ errors = [+ r+ for r in caplog.records+ if r.levelno == logging.ERROR and "metric filter" in r.getMessage()+ ]+ assert len(errors) == 1 # logged once, second bad record does not re-log+++def test_valid_metric_filter_records_six_metrics(monkeypatch):+ """The happy path: with no attribute filter, a successful LLM call records all+ six GenAI histograms, and the token metric keeps its input/output split."""+ from opentelemetry.sdk.metrics import MeterProvider+ from opentelemetry.sdk.metrics.export import InMemoryMetricReader++ import litellm++ monkeypatch.setattr(litellm, "callback_settings", {}, raising=False)++ cfg = OpenTelemetryV2Config(exporter="in_memory", enable_metrics=True)+ reader = InMemoryMetricReader()+ logger = OpenTelemetryV2(+ config=cfg,+ callback_name="otel",+ tracer_provider=providers.build_tracer_provider(cfg),+ meter_provider=MeterProvider(metric_readers=[reader]),+ )++ start = datetime.now(timezone.utc)+ end = start + timedelta(seconds=2)+ kwargs = _metric_success_kwargs()+ kwargs["api_call_start_time"] = start.timestamp()+ kwargs["completion_start_time"] = (start + timedelta(seconds=0.5)).timestamp()+ kwargs["end_time"] = end.timestamp()+ kwargs["optional_params"] = {"stream": True}+ response_obj = {"usage": {"prompt_tokens": 5, "completion_tokens": 7}}++ asyncio.run(logger.async_log_success_event(kwargs, response_obj, start, end))++ 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.client.response.duration",+ }++ data = reader.get_metrics_data()+ token_types = {+ dp.attributes.get("gen_ai.token.type")+ for rm in data.resource_metrics+ for sm in rm.scope_metrics+ for m in sm.metrics+ if m.name == "gen_ai.client.token.usage"+ for dp in m.data.data_points+ }+ assert token_types == {"input", "output"}+++def test_metrics_disabled_by_default_records_nothing(monkeypatch):+ """With ``enable_metrics`` off (the default), no meter is built and a success+ event records nothing — the default behavior must stay unchanged."""+ from opentelemetry.sdk.metrics import MeterProvider+ from opentelemetry.sdk.metrics.export import InMemoryMetricReader++ import litellm++ monkeypatch.setattr(litellm, "callback_settings", {}, raising=False)++ cfg = OpenTelemetryV2Config(exporter="in_memory") # enable_metrics defaults False+ reader = InMemoryMetricReader()+ logger = OpenTelemetryV2(+ config=cfg,+ callback_name="otel",+ tracer_provider=providers.build_tracer_provider(cfg),+ meter_provider=MeterProvider(metric_readers=[reader]),+ )+ assert logger._metrics_recorder is None++ start = datetime.now(timezone.utc)+ end = start + timedelta(seconds=1)+ asyncio.run(+ logger.async_log_success_event(+ _metric_success_kwargs(),+ {"usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ start,+ end,+ )+ )+ assert _emitted_metric_names(reader) == set()diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py b/tests/test_litellm/integrations/otel/test_otel_v2_metrics.pynew file mode 100644index 00000000000..caf2947ac2d--- /dev/null+++ b/tests/test_litellm/integrations/otel/test_otel_v2_metrics.py@@ -0,0 +1,286 @@+"""Tests for the V2 OTEL GenAI client metrics.++Drives the real success path: the six ``gen_ai.client.*`` histograms are emitted+through ``OpenTelemetryV2.async_log_success_event`` into an injected+``InMemoryMetricReader``, and attributes/values are read straight off the+recorded data points (``resource_metrics`` -> ``scope_metrics`` -> ``metrics`` ->+``data.data_points``). The cardinality filter is resolved lazily from+``litellm.callback_settings['otel']['attributes']``, which the proxy populates+after the logger is built, so those tests set it AFTER construction. A+misconfigured filter (``gen_ai.token.type`` in a list, include+exclude together)+raises out of ``GenAIMetricRecorder.record`` -- asserted directly at the recorder+layer -- and the logger turns that raise into a single ERROR ("metrics disabled")+plus a quiet no-op for the rest of the process, asserted at the logger layer so+the misconfig never breaks a request nor spams a log line per request.+"""++import asyncio+from datetime import datetime, timedelta++import pytest++pytest.importorskip("opentelemetry")++from opentelemetry.sdk.metrics import MeterProvider # noqa: E402+from opentelemetry.sdk.metrics.export import InMemoryMetricReader # noqa: E402++import litellm # noqa: E402+from litellm.integrations.otel.logger import OpenTelemetryV2 # noqa: E402+from litellm.integrations.otel.model.config import ( # noqa: E402+ OpenTelemetryV2Config,+)+from litellm.integrations.otel.plumbing.metrics import ( # noqa: E402+ GenAIMetricRecorder,+ create_genai_metrics,+)++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"+RESPONSE_DURATION = "gen_ai.client.response.duration"++ALL_METRICS = frozenset(+ {+ OPERATION_DURATION,+ TOKEN_USAGE,+ TOKEN_COST,+ TIME_TO_FIRST_TOKEN,+ TIME_PER_OUTPUT_TOKEN,+ RESPONSE_DURATION,+ }+)++TOKEN_TYPE = "gen_ai.token.type"+MODEL_KEY = "gen_ai.request.model"++# Each is a member of VALID_METRIC_ATTRIBUTE_NAMES and is stamped on the metric+# by default (proven by the no-filter test below).+HIGH_CARDINALITY_KEYS = (+ "hidden_params",+ "metadata.user_api_key_hash",+ "metadata.requester_ip_address",+ "metadata.requester_metadata",+ "metadata.applied_guardrails",+)++PROMPT_TOKENS = 137+COMPLETION_TOKENS = 89+RESPONSE_COST = 0.0023+++def _build_call(stream: bool = True):+ """A captured success-call (kwargs, response_obj, start, end) that exercises+ every one of the six metrics: usage for token.usage, response_cost for cost,+ streaming + timing for the response-time histograms."""+ start = datetime(2026, 6, 12, 12, 0, 0)+ api_call_start = start + timedelta(seconds=0.1)+ completion_start = start + timedelta(seconds=0.5)+ end = start + timedelta(seconds=1.0)+ kwargs = {+ "model": "gpt-4o-mini",+ "call_type": "completion",+ "litellm_params": {"custom_llm_provider": "openai"},+ "optional_params": {"stream": stream},+ "response_cost": RESPONSE_COST,+ "api_call_start_time": api_call_start,+ "completion_start_time": completion_start,+ "end_time": end,+ "standard_logging_object": {+ "metadata": {+ "user_api_key_hash": "hash-abc123",+ "requester_ip_address": "10.0.0.7",+ "requester_metadata": {"team": "alpha", "tier": "gold"},+ "applied_guardrails": ["pii", "toxicity"],+ },+ "hidden_params": {"litellm_call_id": "abc", "model_id": "m-1"},+ },+ }+ response_obj = {+ "usage": {+ "prompt_tokens": PROMPT_TOKENS,+ "completion_tokens": COMPLETION_TOKENS,+ }+ }+ return kwargs, response_obj, start, end+++def _logger(reader, *, enable_metrics: bool):+ return OpenTelemetryV2(+ config=OpenTelemetryV2Config(+ exporter="in_memory", enable_metrics=enable_metrics+ ),+ meter_provider=MeterProvider(metric_readers=[reader]),+ )+++def _metrics_by_name(reader):+ """{metric_name: [data_point, ...]} from everything the reader has collected."""+ data = reader.get_metrics_data()+ out: dict = {}+ if not data or not getattr(data, "resource_metrics", None):+ return out+ for rm in data.resource_metrics:+ for sm in rm.scope_metrics:+ for m in sm.metrics:+ out.setdefault(m.name, []).extend(m.data.data_points)+ return out+++def _drive_success(reader, callback_settings_attributes=None):+ """Construct a metrics-on logger, optionally populate callback_settings AFTER+ construction (mirroring the proxy ordering), run the real success hook."""+ logger = _logger(reader, enable_metrics=True)+ previous = litellm.callback_settings+ if callback_settings_attributes is not None:+ litellm.callback_settings = {+ "otel": {"attributes": callback_settings_attributes}+ }+ try:+ kwargs, response_obj, start, end = _build_call()+ asyncio.run(logger.async_log_success_event(kwargs, response_obj, start, end))+ finally:+ litellm.callback_settings = previous+ return _metrics_by_name(reader)+++def test_all_six_metrics_emitted_when_enabled():+ """A successful streaming call with metrics on emits exactly the six+ gen_ai.client.* histograms, and token.usage splits into an input and an+ output point carrying the right token counts."""+ metrics = _drive_success(InMemoryMetricReader())++ assert set(metrics.keys()) == set(ALL_METRICS)++ token_points = metrics[TOKEN_USAGE]+ by_type = {dp.attributes[TOKEN_TYPE]: dp for dp in token_points}+ assert set(by_type) == {"input", "output"}+ assert by_type["input"].sum == PROMPT_TOKENS+ assert by_type["output"].sum == COMPLETION_TOKENS++ cost_points = metrics[TOKEN_COST]+ assert len(cost_points) == 1+ assert cost_points[0].sum == pytest.approx(RESPONSE_COST)+++def test_time_to_first_token_is_streaming_only():+ """time_to_first_token is gated on streaming: a non-streaming call emits the+ other five metrics but never that one."""+ reader = InMemoryMetricReader()+ logger = _logger(reader, enable_metrics=True)+ kwargs, response_obj, start, end = _build_call(stream=False)+ asyncio.run(logger.async_log_success_event(kwargs, response_obj, start, end))++ names = set(_metrics_by_name(reader).keys())+ assert TIME_TO_FIRST_TOKEN not in names+ assert names == set(ALL_METRICS) - {TIME_TO_FIRST_TOKEN}+++def test_metrics_disabled_records_nothing():+ """enable_metrics=False: the recorder is never built, so the injected reader+ sees no gen_ai.client.* series even though the success hook runs."""+ reader = InMemoryMetricReader()+ logger = _logger(reader, enable_metrics=False)+ kwargs, response_obj, start, end = _build_call()+ asyncio.run(logger.async_log_success_event(kwargs, response_obj, start, end))++ assert set(_metrics_by_name(reader).keys()).isdisjoint(ALL_METRICS)+++def test_metrics_off_by_default_records_nothing():+ """The default config has metrics off, so a default logger records nothing."""+ reader = InMemoryMetricReader()+ logger = OpenTelemetryV2(+ config=OpenTelemetryV2Config(exporter="in_memory"),+ meter_provider=MeterProvider(metric_readers=[reader]),+ )+ kwargs, response_obj, start, end = _build_call()+ asyncio.run(logger.async_log_success_event(kwargs, response_obj, start, end))++ assert set(_metrics_by_name(reader).keys()).isdisjoint(ALL_METRICS)+++def test_exclude_list_strips_high_cardinality_across_metrics():+ """exclude_list set AFTER construction (the proxy path) removes every+ high-cardinality key from more than one metric while the low-cardinality+ model attribute survives."""+ metrics = _drive_success(+ InMemoryMetricReader(),+ callback_settings_attributes={"exclude_list": list(HIGH_CARDINALITY_KEYS)},+ )+ excluded = set(HIGH_CARDINALITY_KEYS)++ for name in (OPERATION_DURATION, TOKEN_USAGE):+ points = metrics[name]+ assert points, f"{name} was not recorded"+ for dp in points:+ keys = set(dp.attributes.keys())+ assert excluded.isdisjoint(keys), f"{name} leaked {excluded & keys}"+ assert MODEL_KEY in keys+++def test_include_list_allows_only_listed_attributes():+ """include_list caps emitted attributes to exactly the listed set;+ gen_ai.token.type is the only key permitted beyond it, and only on the+ token-usage metric."""+ include = [MODEL_KEY, "gen_ai.system"]+ metrics = _drive_success(+ InMemoryMetricReader(),+ callback_settings_attributes={"include_list": include},+ )+ allowed = set(include)++ for dp in metrics[OPERATION_DURATION]:+ assert set(dp.attributes.keys()) == allowed++ for dp in metrics[TOKEN_USAGE]:+ assert set(dp.attributes.keys()) - {TOKEN_TYPE} == allowed+++def test_no_filter_keeps_high_cardinality_keys():+ """Backward compatibility: without an attributes config every high-cardinality+ key the call carries is still stamped, so the filter tests above prove a real+ removal rather than a key that was never present."""+ metrics = _drive_success(InMemoryMetricReader())+ expected = set(HIGH_CARDINALITY_KEYS)++ for name in (OPERATION_DURATION, TOKEN_USAGE):+ for dp in metrics[name]:+ assert expected.issubset(set(dp.attributes.keys()))+++def _recorder(monkeypatch, attributes):+ """A recorder wired to a fresh in-memory meter, with callback_settings carrying+ `attributes`. record() resolves the filter lazily from there, so a misconfig+ raises out of record() at this layer (the logger turns it into log-once)."""+ monkeypatch.setattr(+ litellm,+ "callback_settings",+ {"otel": {"attributes": attributes}},+ raising=False,+ )+ meter = MeterProvider(metric_readers=[InMemoryMetricReader()]).get_meter("test")+ return GenAIMetricRecorder(create_genai_metrics(meter), callback_name=None)+++ "attributes",+ [+ {"exclude_list": [TOKEN_TYPE]},+ {"include_list": [TOKEN_TYPE]},+ ],+)+def test_token_type_rejected_from_either_list(attributes, monkeypatch):+ """gen_ai.token.type is a structural discriminator stamped onto the+ input/output series after filtering; it cannot itself be filtered without+ collapsing the two series. Listing it in either list is rejected by the+ recorder rather than silently ignored, so the misconfig is caught at all."""+ recorder = _recorder(monkeypatch, attributes)+ kwargs, response_obj, start, end = _build_call()+ with pytest.raises(ValueError) as exc_info:+ recorder.record(kwargs, response_obj, start, end)+ # The dedicated discriminator guard, not the generic unknown-name path: assert+ # the specific reason so dropping that guard (and falling through to "unknown+ # attribute name") is caught.+ assert "discriminator" in str(exc_info.value)