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]

feat(otel): typed semconv-aligned OpenTelemetry instrumentation (#28909)

Yassin Kortamd82eb33a60b7
diff --git a/litellm/_service_logger.py b/litellm/_service_logger.py
index 1a3be203fec..5531c418799 100644
--- a/litellm/_service_logger.py
+++ b/litellm/_service_logger.py
@@ -24,6 +24,22 @@ else:
UserAPIKeyAuth = Any
+def _get_otel_v2_class() -> Optional[type]:
+ """Return the ``OpenTelemetryV2`` class, or ``None`` if the OTel SDK is absent.
+
+ Imported lazily: ``litellm.integrations.otel.logger`` imports the OpenTelemetry
+ SDK at module scope, so importing it eagerly would break installs without the
+ SDK. The V2 logger only exists when ``LITELLM_OTEL_V2`` is enabled (which
+ requires the SDK), so a failed import simply means "no V2 logger in play".
+ """
+ try:
+ from litellm.integrations.otel.logger import OpenTelemetryV2
+
+ return OpenTelemetryV2
+ except Exception:
+ return None
+
+
class ServiceLogging(CustomLogger):
"""
Separate class used for monitoring health of litellm-adjacent services (redis/postgres).
@@ -38,6 +54,37 @@ class ServiceLogging(CustomLogger):
if "prometheus_system" in litellm.service_callback:
self.prometheusServicesLogger = PrometheusServicesLogger()
+ def _resolve_otel_service_logger(self, callback: Any) -> Optional[Any]:
+ """Resolve the OTel logger (legacy or V2) to emit a service span on.
+
+ Returns the logger instance whose ``async_service_*_hook`` should fire for
+ this ``callback``, or ``None`` when ``callback`` is not an OTel callback.
+
+ The V2 ``OpenTelemetryV2`` logger is a plain ``CustomLogger`` and is NOT a
+ subclass of the legacy ``OpenTelemetry``, so the legacy ``isinstance``
+ check alone misses it — which is why redis/postgres service spans never
+ showed up under ``LITELLM_OTEL_V2``. Match both the legacy and V2 types,
+ whether the callback is the logger instance itself or the ``"otel"`` string
+ (which routes to the proxy's registered ``open_telemetry_logger``).
+ """
+ otel_v2_cls = _get_otel_v2_class()
+
+ def _is_otel_logger(obj: Any) -> bool:
+ if isinstance(obj, OpenTelemetry):
+ return True
+ return otel_v2_cls is not None and isinstance(obj, otel_v2_cls)
+
+ if _is_otel_logger(callback):
+ return callback
+ if callback == "otel":
+ from litellm.proxy.proxy_server import open_telemetry_logger
+
+ if open_telemetry_logger is not None and _is_otel_logger(
+ open_telemetry_logger
+ ):
+ return open_telemetry_logger
+ return None
+
def service_success_hook(
self,
service: ServiceTypes,
@@ -129,6 +176,13 @@ class ServiceLogging(CustomLogger):
event_metadata=event_metadata,
)
+ # OTel loggers already fired this event. ``service_callback`` can hold more
+ # than one reference that resolves to the *same* logger — the ``"otel"``
+ # string AND the registered instance both map to ``open_telemetry_logger``
+ # (the V2 logger self-registers its instance even when the string is
+ # present, unlike V1). Without this guard each such reference emits its own
+ # span, so a single DB call shows up as duplicate ``postgres ...`` spans.
+ emitted_otel_logger_ids: set = set()
for callback in litellm.service_callback:
if callback == "prometheus_system":
await self.init_prometheus_services_logger_if_none()
@@ -144,19 +198,18 @@ class ServiceLogging(CustomLogger):
end_time=end_time,
event_metadata=event_metadata,
)
- elif callback == "otel" or isinstance(callback, OpenTelemetry):
- _otel_logger_to_use: Optional[OpenTelemetry] = None
- if isinstance(callback, OpenTelemetry):
- _otel_logger_to_use = callback
- else:
- from litellm.proxy.proxy_server import open_telemetry_logger
-
- if open_telemetry_logger is not None and isinstance(
- open_telemetry_logger, OpenTelemetry
- ):
- _otel_logger_to_use = open_telemetry_logger
-
- if _otel_logger_to_use is not None and parent_otel_span is not None:
+ else:
+ _otel_logger_to_use = self._resolve_otel_service_logger(callback)
+ # No ``parent_otel_span is not None`` gate: a background service
+ # call (no request on the stack) has no parent, and dropping it
+ # here is what hid those calls from traces entirely. The OTel
+ # logger decides what to do with a missing parent — legacy V1
+ # no-ops, V2 emits a root span (and skips metrics-only pings).
+ if (
+ _otel_logger_to_use is not None
+ and id(_otel_logger_to_use) not in emitted_otel_logger_ids
+ ):
+ emitted_otel_logger_ids.add(id(_otel_logger_to_use))
await _otel_logger_to_use.async_service_success_hook(
payload=payload,
parent_otel_span=parent_otel_span,
@@ -238,6 +291,9 @@ class ServiceLogging(CustomLogger):
event_metadata=event_metadata,
)
+ # Dedupe OTel loggers per event — see ``async_service_success_hook`` for why
+ # the same logger can be referenced twice in ``service_callback``.
+ emitted_otel_logger_ids: set = set()
for callback in litellm.service_callback:
if callback == "prometheus_system":
await self.init_prometheus_services_logger_if_none()
@@ -255,22 +311,19 @@ class ServiceLogging(CustomLogger):
end_time=end_time,
event_metadata=event_metadata,
)
- elif callback == "otel" or isinstance(callback, OpenTelemetry):
- _otel_logger_to_use: Optional[OpenTelemetry] = None
- if isinstance(callback, OpenTelemetry):
- _otel_logger_to_use = callback
- else:
- from litellm.proxy.proxy_server import open_telemetry_logger
-
- if open_telemetry_logger is not None and isinstance(
- open_telemetry_logger, OpenTelemetry
- ):
- _otel_logger_to_use = open_telemetry_logger
+ else:
+ _otel_logger_to_use = self._resolve_otel_service_logger(callback)
if not isinstance(error, str):
error = str(error)
- if _otel_logger_to_use is not None and parent_otel_span is not None:
+ # See the success hook: no parent gate, so background failures
+ # are traced too. V1 no-ops without a parent; V2 emits a root.
+ if (
+ _otel_logger_to_use is not None
+ and id(_otel_logger_to_use) not in emitted_otel_logger_ids
+ ):
+ emitted_otel_logger_ids.add(id(_otel_logger_to_use))
await _otel_logger_to_use.async_service_failure_hook(
payload=payload,
error=error,
diff --git a/litellm/constants.py b/litellm/constants.py
index f72528eb170..ae98b37d6e6 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1409,6 +1409,13 @@ LITELLM_INTERNAL_JOBS_SERVICE_ACCOUNT_NAME = "litellm_internal_jobs"
# Prometheus metrics, audit trails, or any other downstream consumer.
LITELLM_PROXY_MASTER_KEY_ALIAS = "litellm_proxy_master_key"
+# Marker placed in ``model_call_details`` on a synthetic ``Logging`` object that
+# records a proxy-gate error (auth/rate-limit rejection) for a request that never
+# reached an upstream provider. Tracing callbacks key off it to avoid fabricating
+# an LLM-call span for a call that did not happen. See
+# ``ProxyLogging._handle_logging_proxy_only_error``.
+LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL = "litellm_no_upstream_llm_call"
+
# Key Rotation Constants
LITELLM_KEY_ROTATION_ENABLED = os.getenv("LITELLM_KEY_ROTATION_ENABLED", "false")
LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS = int(
diff --git a/litellm/integrations/otel/README.md b/litellm/integrations/otel/README.md
new file mode 100644
index 00000000000..99b3ecea162
--- /dev/null
+++ b/litellm/integrations/otel/README.md
@@ -0,0 +1,258 @@
+# OpenTelemetry instrumentation
+
+This package produces OpenTelemetry traces for LiteLLM. It is enabled by the
+`LITELLM_OTEL_V2` environment variable (`is_otel_v2_enabled()` in
+[`config.py`](./model/config.py)); when unset, nothing in this package runs.
+
+## What gets traced
+
+A traced proxy request produces one trace with two kinds of spans:
+
+```
+SERVER span "POST /v1/chat/completions" ← FastAPI instrumentation
+├── INTERNAL span "auth /v1/chat/completions" ← auth phase ┐
+│ ├── CLIENT span "postgres get_key_object" ← datastore call │
+│ └── CLIENT span "postgres get_team_membership" │
+├── INTERNAL span "execute_guardrail …" ← guardrail │ this package
+├── CLIENT span "chat gpt-4o" ← LLM call │
+└── CLIENT span "batch_write_to_db …" ← spend write ┘
+```
+
+The gen-ai spans are siblings under the server span. In particular the guardrail
+span is a sibling of the LLM call, not a child of it: pre/during/post-call
+guardrail hooks are part of the request lifecycle (a pre-call guardrail runs
+before the LLM call even starts), so they belong directly under the server span,
+alongside the LLM call.
+
+Request-level spans (LLM call, guardrail) parent to the server span via an
+**explicit anchor** — `context.set_request_root_span` captures the server span
+once at request entry, and `resolve_request_span_context` reads it — rather than
+to whatever span is momentarily active. Ambient-only parenting was wrong at two
+boundaries: inside the live `auth` phase span the active span is `auth` (so the
+span would nest under auth), and a pass-through request closes its span from a
+detached `asyncio.create_task` where the server span is no longer active (so the
+span orphaned into its own trace). The anchor — a contextvar inherited by those
+child tasks — gives a stable parent in both cases. DB/service spans keep ambient
+parenting so an auth DB lookup still nests under `auth`.
+
+**Which service calls become spans (`spans.span_role_for_service`).** LiteLLM's
+service-logging layer instruments many internal functions, but only some are
+traceable units of work:
+
+- **`DB_CALL` (CLIENT)** — outbound datastore calls (redis, postgres,
+ `batch_write_to_db`), carrying `db.system.name` / `db.operation.name` semconv.
+- **`SERVICE` (INTERNAL)** — genuine internal work worth a span (background
+ budget/reset jobs, pod-lock manager).
+- **metrics-only (no span)** — `self` (the `track_llm_api_timing` wrapper, which
+ duplicates the LLM-call span), `router` (duplicates the request), and
+ `proxy_pre_call` (a guardrail's real span is `execute_guardrail …`). These
+ still feed Prometheus/Datadog through their own hooks; they just never enter
+ the trace. `auth` is also excluded here because it gets a **live phase span**
+ instead (see below).
+
+Spans are named `"{service} {call_type}"` (e.g. `"redis set"`) so repeated calls
+to one service stay distinguishable. Like every other span they parent to the
+**ambient** context, falling back to the threaded `litellm_parent_otel_span` only
+when ambient has no live span; a background job with neither starts its own root
+trace. Caller-supplied `event_metadata` is **sanitized** before it reaches a span
+(primitives only, no live objects, no secrets/headers, bounded) — see
+`payloads.sanitize_event_metadata`.
+
+**Live phase spans.** `auth` is wrapped in a real, active span
+(`logger.phase_span`) for the duration of authentication, so the DB lookups it
+triggers nest **under** it instead of flattening onto the server span. Identity
+Baggage (team/key/user) is seeded once the key resolves, so every post-auth span
+inherits it; auth-internal DB lookups that run before the key is known stay
+unlabeled, which is correct.
+
+**Status.** On success a span's status is left `UNSET` (the semconv default,
+matching the FastAPI server span); only a genuine error sets `ERROR`.
+
+- **Server spans** (one per HTTP route) are created by the
+ `opentelemetry-instrumentation-fastapi` package. It stamps `http.*` attributes
+ and extracts inbound `traceparent` headers. This package does **not** create
+ or modify server spans — request routes never touch spans.
+- **Gen-AI spans** (LLM calls, guardrails, internal service calls) are created
+ by this package from LiteLLM's logging callbacks. Request-level spans parent to
+ the server span via the captured anchor; DB/service spans parent to the active
+ span (ambient) so they nest under the request phase that triggered them.
+
+Both kinds share a single `TracerProvider`, so they belong to the same trace
+and export through the same configured exporters. FastAPI middleware can only be
+added before the app starts serving, so the app is instrumented at
+import time **without** a provider — it binds to the OTel global
+`ProxyTracerProvider`. Once config (and the callbacks) is loaded, the proxy
+publishes the chosen logger's `TracerProvider` as the global via
+`trace.set_tracer_provider(...)`, and the server spans delegate to it. When a
+preset callback (`arize`, `langfuse_otel`, …) is configured, its provider
+becomes the global, so server spans export to that backend too.
+
+## How a request flows
+
+1. **App creation** (`proxy_server` import): when the gate is on,
+ `mount.instrument_fastapi_app(app)` calls `FastAPIInstrumentor.instrument_app`
+ with no provider (the middleware stack is frozen once the app serves, so this
+ can't wait for startup). It binds to the OTel global `ProxyTracerProvider`. Noisy
+ non-LLM routes are excluded by default (`mount._DEFAULT_EXCLUDED_ROUTES`): health
+ checks (`/health*`), the Prometheus scrape (`/metrics`), and static UI/docs assets
+ (`/litellm-asset-prefix`, `/_next`, `/ui`, `/swagger`, `/docs`, `/redoc`,
+ `/openapi.json`, favicons, `/.well-known`) — so load-balancer polling, metric
+ scrapes, and asset fetches don't flood traces. Entries are substring-matched, so
+ `/metrics` also drops the `/model/metrics` admin-analytics spans. Set
+ `OTEL_PYTHON_FASTAPI_EXCLUDED_URLS` to override the whole set (e.g. `""` to trace
+ everything, or your own comma-separated path list).
+2. **Startup** (`proxy_server.proxy_startup_event`): after the config (and
+ callbacks) is loaded, the already-registered preset `OpenTelemetryV2` logger
+ is reused — or a generic one reading `OTEL_*` envs is built when no preset is
+ configured — and its `TracerProvider` is published as the OTel global with
+ `trace.set_tracer_provider(...)`. The proxy tracer then delegates to it, so
+ server spans and gen-ai spans share one provider and the same trace.
+3. **Request**: the FastAPI instrumentation starts the server span and makes it
+ the active context for the request task. The proxy's first call into the V2
+ logger (`create_litellm_proxy_request_started_span`, at the auth boundary)
+ **captures it as the request anchor** (`set_request_root_span`), so every later
+ request-level span has a stable explicit parent regardless of what is active
+ when it emits.
+4. **LLM call span (born at the boundary)**: `OpenTelemetryV2.log_pre_api_call`
+ runs synchronously in the request task, just before the upstream call, and
+ **opens** the LLM-call span there, parented to the anchored server span
+ (`resolve_request_span_context`). The open span is held in a bounded cache keyed
+ by `litellm_call_id` (a primitive the callback kwargs carry at both `pre_call`
+ and close), so no live `Span` ever travels through a `litellm_params` metadata
+ dict. For the boundary hook to fire at all, the logger is registered into
+ `litellm.input_callback` — the list `Logging.pre_call` iterates. The async
+ success/failure callback later
+ **closes** it: it builds an `LLMCallSpanData` from the typed
+ `standard_logging_object` (token usage and cost are computed only by then),
+ stamps the attributes, sets status, and ends the span. The sync callback is a
+ no-op (closing is async-only). When `pre_call` runs off the request task — a
+ sync-only provider driven through a thread pool, where contextvars (and so the
+ anchor) don't follow — no parent is visible there, so creation is **deferred**
+ to the async callback, whose worker context was copied from the request task at
+ enqueue and so still carries the anchor. **Pass-through** endpoints call
+ `logging_obj.pre_call` in the request task too, then close from a detached
+ `asyncio.create_task`; the anchor (not the by-then-inactive server span) keeps
+ their LLM-call span in the request's trace. `pre_call` is litellm's generic
+ "log the attempt" hook, so it also fires for synthetic proxy-gate error logs
+ (auth/rate-limit rejections); those carry `LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL`
+ and are skipped, so a request rejected before reaching a provider never produces
+ a phantom CLIENT span.
+5. **Guardrails / services**: the post-call and service hooks emit guardrail and
+ service spans the same way — typed data → engine → span. Service spans
+ (Redis/Postgres) are dispatched by `litellm/_service_logger.py`, which
+ recognizes the V2 `OpenTelemetryV2` logger (a plain `CustomLogger`, not a
+ subclass of the legacy `OpenTelemetry`). It hands every service call to the
+ logger — including calls with no parent span — and the V2 adapter decides the
+ role (`DB_CALL` vs `SERVICE`), the parent (ambient → threaded → root), and
+ whether the call is a traceable operation or a metrics-only ping. Guardrail
+ span data is built from the typed, provider-agnostic
+ `StandardLoggingGuardrailInformation` — no single provider's field shape is
+ assumed.
+6. **Export**: each span ends and is handed to the provider's span processors,
+ which export to the configured backends (OTLP, console, in-memory, …).
+
+## Components
+
+### Sources of truth (`model/`, no OpenTelemetry import)
+
+These define the shape of a span without depending on the OTel SDK, so they can
+be imported anywhere. They live in [`model/`](./model) and form a closed set —
+nothing here imports outside it:
+
+- [`semconv.py`](./model/semconv.py) — attribute-key constants (`gen_ai.*`, `http.*`,
+ `litellm.*`), the GenAI operation/provider enums, and the functions that map
+ LiteLLM provider/call-type strings onto convention values.
+- [`spans.py`](./model/spans.py) — the span registry: every span role, its OTel span
+ kind, its place in the hierarchy, and its name builder.
+- [`payloads.py`](./model/payloads.py) — frozen dataclasses (`LLMCallSpanData`,
+ `GuardrailSpanData`, `ServiceSpanData`, …) built from heterogeneous logging
+ payloads via `from_*` classmethods.
+- [`config.py`](./model/config.py) — `OpenTelemetryV2Config`, a pydantic-settings
+ model that reads `OTEL_*` / `LITELLM_OTEL_*` env vars, plus the feature gate.
+ `capture_span_content` gates whether prompt/response bodies may be written as
+ span attributes; it defaults **off** (`no_content`). The Baggage allowlists are
+ configurable, not hard-coded: set `LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS` /
+ `LITELLM_OTEL_BAGGAGE_METADATA_KEYS` (comma-separated) as env vars, or
+ `baggage_promoted_keys` / `baggage_metadata_keys` (YAML lists) under
+ `callback_settings.otel` in `config.yaml` — the latter reach the config through
+ the logger's constructor kwargs.
+- [`baggage.py`](./model/baggage.py) — the single definition of which request-identity
+ values are promoted into Baggage (so child spans inherit them) and under which
+ attribute keys.
+- [`utils.py`](./model/utils.py) — value coercion, JSON serialization, and
+ extractor-table application, shared across the package.
+
+### Engine
+
+- [`emitter.py`](./emitter.py) — `SpanEmitter.emit(role, data)`: dedupe → start
+ the span → run the mapper chain to stamp attributes → set status → end. It
+ owns no attribute keys. The dedupe set (which coalesces the sync+async firing
+ of one request) is a bounded LRU so it can't grow without limit.
+- [`mappers/`](./mappers) — each mapper turns typed span data into a flat
+ `{attribute key: value}` dict. They compose: listing several mapper names in
+ the config layers multiple attribute vocabularies onto the same span.
+ - `genai` — the canonical OpenTelemetry GenAI vocabulary, always present.
+ - `legacy` — an additional vocabulary using the older semconv-ai / Traceloop
+ attribute key names, for backends that read those.
+ - `openinference`, `langfuse`, `weave`, `langtrace` — vendor vocabularies.
+ - `resolve_mappers(names)` turns config names into mapper instances.
+
+### Plumbing (`plumbing/`)
+
+The OTel-SDK wiring. Everything here imports only `model/` and each other; it
+lives in [`plumbing/`](./plumbing):
+
+- [`providers.py`](./plumbing/providers.py) — builds the `TracerProvider`, its exporters
+ (from `ExporterSpec`s), and the span processor that copies allowlisted Baggage
+ entries onto every span. `register_exporter_factory(kind, factory)` lets a
+ preset contribute a custom exporter `kind` (e.g. one that fetches an auth
+ token lazily) without coupling this module to any vendor.
+- [`context.py`](./plumbing/context.py) — trace-context and Baggage read/write helpers.
+- [`routing.py`](./plumbing/routing.py) — `TenantTracerCache`: when a request carries
+ team/key-scoped vendor credentials, route its spans through a credential-keyed
+ `TracerProvider` so one logger serves many tenants. The cache is a bounded LRU
+ that flushes + shuts down evicted providers, since the key derives from
+ request-supplied credentials and must not grow (or leak threads) without limit.
+- [`metrics.py`](./plumbing/metrics.py) — GenAI client metric instruments.
+
+### Adapter
+
+- [`logger.py`](./logger.py) — `OpenTelemetryV2`, a `CustomLogger` that
+ translates LiteLLM's logging callbacks into typed span data and hands them to
+ the engine. The LLM-call span is opened at the `log_pre_api_call` boundary
+ (parented to the live server span via ambient context) and closed at the async
+ success/failure callback; the open span is held in a bounded cache keyed by
+ `litellm_call_id`, never threaded through a metadata dict. The logger registers
+ itself into `litellm.input_callback` so `Logging.pre_call` fires the boundary
+ hook.
+- [`mount.py`](./mount.py) — `instrument_fastapi_app(app)`, the single call site
+ that attaches `opentelemetry-instrumentation-fastapi` for SERVER spans. It owns
+ the health-check exclusion default (`OTEL_PYTHON_FASTAPI_EXCLUDED_URLS`) and the
+ passthrough span-naming hook (`PASSTHROUGH_PREFIXES`) so `proxy_server` carries
+ no OTel detail. A safe no-op when the gate is off or the instrumentation package
+ is absent; must be called at app-creation time (the middleware stack freezes
+ once the app serves).
+
+### Presets
+
+- [`presets/`](./presets) — each preset reads one integration's env vars and
+ returns an `OpenTelemetryV2Config` (exporter destination + mapper vocabularies
+ + resource attributes). `PRESET_BY_CALLBACK` maps a callback name (`"arize"`,
+ `"langfuse_otel"`, …) to its preset. Integrations that support team/key-scoped
+ credentials also provide a per-request OTLP header builder
+ (`DYNAMIC_HEADERS_BY_CALLBACK`). Presets do **no** network I/O at build time:
+ AgentOps, for example, mints its JWT lazily inside a custom exporter on the
+ first export (in the `BatchSpanProcessor` worker thread), never on the event
+ loop.
+
+## Extending
+
+- **A new attribute vocabulary for a backend**: add a mapper in `mappers/`
+ (a class with a `map(data) -> AttributeMap` method, typically built from
+ `key -> extractor` tables) and register it in `mappers/__init__._MAPPER_BY_NAME`.
+- **A new integration**: add a preset in `presets/` that returns an
+ `OpenTelemetryV2Config`, and register it in `presets/__init__.PRESET_BY_CALLBACK`.
+ If it supports dynamic credentials, add a header builder to
+ `DYNAMIC_HEADERS_BY_CALLBACK`.
+- **A new span kind**: add a role to `spans.py` (registry entry + name builder),
+ a payload dataclass in `payloads.py`, and a branch in the relevant mapper(s).
diff --git a/litellm/integrations/otel/__init__.py b/litellm/integrations/otel/__init__.py
new file mode 100644
index 00000000000..42a84a85fbd
--- /dev/null
+++ b/litellm/integrations/otel/__init__.py
@@ -0,0 +1,102 @@
+"""Typed, semconv-aligned OpenTelemetry instrumentation for LiteLLM.
+
+The three sources of truth — attribute keys (:mod:`semconv`), the span and
+hierarchy registry (:mod:`spans`), and the typed span-data inputs
+(:mod:`payloads`) — plus :mod:`config` are exported here and are free of any
+``opentelemetry`` import. The engine layer (``emitter``, ``providers``,
+``context``, ``metrics``) and the ``CustomLogger`` adapter (``logger``) are
+reached via their submodule paths so that importing this package never
+requires the OTel SDK.
+
+The ``LITELLM_OTEL_V2`` env var gates whether the factory in
+``litellm_core_utils.litellm_logging`` constructs the ``OpenTelemetryV2``
+class (from :mod:`logger`).
+"""
+
+from litellm.integrations.otel.model.config import (
+ OTEL_V2_ENV,
+ OpenTelemetryV2Config,
+ is_otel_v2_enabled,
+)
+from litellm.integrations.otel.model.baggage import (
+ BAGGAGE_PROMOTED_KEYS,
+ DEFAULT_BAGGAGE_METADATA_KEYS,
+ promoted_baggage,
+)
+from litellm.integrations.otel.model.metadata import (
+ RequestContext,
+ RequestIdentity,
+)
+from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ LLMRequestParams,
+ LLMUsage,
+ ProxyRequestSpanData,
+ ServerInfo,
+ ServiceSpanData,
+ SpanError,
+)
+from litellm.integrations.otel.model.semconv import (
+ DB,
+ Error,
+ GenAI,
+ GenAIOperation,
+ GenAIProvider,
+ HTTP,
+ LiteLLM,
+ Metric,
+ Server,
+ resolve_operation,
+ resolve_provider,
+)
+from litellm.integrations.otel.model.spans import (
+ SPAN_REGISTRY,
+ LiteLLMSpanKind,
+ SpanRole,
+ SpanSpec,
+ db_system,
+ span_role_for_service,
+ validate_registry,
+)
+
+__all__ = [
+ # config
+ "OTEL_V2_ENV",
+ "OpenTelemetryV2Config",
+ "is_otel_v2_enabled",
+ # semconv
+ "BAGGAGE_PROMOTED_KEYS",
+ "DB",
+ "DEFAULT_BAGGAGE_METADATA_KEYS",
+ "Error",
+ "GenAI",
+ "GenAIOperation",
+ "GenAIProvider",
+ "HTTP",
+ "LiteLLM",
+ "Metric",
+ "Server",
+ "resolve_operation",
+ "resolve_provider",
+ # spans
+ "SPAN_REGISTRY",
+ "LiteLLMSpanKind",
+ "SpanRole",
+ "SpanSpec",
+ "db_system",
+ "span_role_for_service",
+ "validate_registry",
+ # payloads
+ "GuardrailSpanData",
+ "LLMCallSpanData",
+ "LLMRequestParams",
+ "LLMUsage",
+ "ProxyRequestSpanData",
+ "RequestContext",
+ "RequestIdentity",
+ "ServerInfo",
+ "ServiceSpanData",
+ "SpanError",
+ "promoted_baggage",
+]
diff --git a/litellm/integrations/otel/emitter.py b/litellm/integrations/otel/emitter.py
new file mode 100644
index 00000000000..cae6514efdf
--- /dev/null
+++ b/litellm/integrations/otel/emitter.py
@@ -0,0 +1,175 @@
+"""The span engine: dedup, start, run the mapper chain, set status, end."""
+
+from collections import OrderedDict
+from typing import Callable, Sequence
+
+from opentelemetry.context import Context
+from opentelemetry.trace import Span, Tracer
+from opentelemetry.trace.status import Status, StatusCode
+
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config
+from litellm.integrations.otel.mappers import resolve_mappers
+from litellm.integrations.otel.mappers.base import AttributeMapper, SpanData
+from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+)
+from litellm.integrations.otel.plumbing.providers import to_otel_span_kind
+from litellm.integrations.otel.model.semconv import Error
+from litellm.integrations.otel.model.spans import (
+ SPAN_REGISTRY,
+ SpanRole,
+ guardrail_span_name,
+ llm_call_span_name,
+ service_span_name,
+)
+
+# Roles emit() knows how to name and emit. PROXY_REQUEST and the management
+# routes are SERVER spans owned by the mounted FastAPI instrumentor, so they
+# have no builder here.
+_NAME_BUILDERS: dict[SpanRole, Callable[..., str]] = {
+ SpanRole.LLM_CALL: llm_call_span_name,
+ SpanRole.GUARDRAIL: guardrail_span_name,
+ # DB_CALL and SERVICE are both built from ServiceSpanData; they differ only in
+ # span kind (CLIENT vs INTERNAL) and attribute vocabulary, not in naming.
+ SpanRole.DB_CALL: service_span_name,
+ SpanRole.SERVICE: service_span_name,
+}
+
+# Cap on the dedup cache. It only needs to coalesce the sync+async firing window
+# of a single in-flight request, so a bounded LRU keeps memory flat on a
+# long-running proxy while still covering every concurrently-open call.
+_DEDUP_CACHE_MAX = 10_000
+
+
+class SpanEmitter:
+ def __init__(
+ self,
+ tracer: Tracer,
+ config: OpenTelemetryV2Config,
+ mappers: Sequence[AttributeMapper] | None = None,
+ ) -> None:
+ self._tracer = tracer
+ self._config = config
+ # The mapper chain is the sole source of span attributes. When not
+ # passed in, resolve it from the config so there's one source of truth.
+ self._mappers: list[AttributeMapper] = (
+ list(mappers)
+ if mappers is not None
+ else resolve_mappers(config.mapper_names)
+ )
+ # Bounded LRU (ordered by insertion / most-recent touch). Storing keys
+ # only — the value is unused — so it behaves like a capped set.
+ self._emitted: "OrderedDict[tuple[str, SpanRole], None]" = OrderedDict()
+
+ # -- low-level helpers --------------------------------------------------- #
+
+ def start_span(
+ self,
+ role: SpanRole,
+ name: str,
+ parent_context: Context | None = None,
+ start_time_ns: int | None = None,
+ *,
+ tracer: Tracer | None = None,
+ ) -> Span:
+ """Start a span for ``role`` without dedup or attribute mapping.
+
+ For callers that own and manage their own span lifecycle. ``tracer``
+ overrides the bound tracer for this span only, used for per-request
+ multi-tenant credential routing.
+ """
+ return (tracer or self._tracer).start_span(
+ name,
+ context=parent_context,
+ kind=to_otel_span_kind(SPAN_REGISTRY[role].kind),
+ start_time=start_time_ns,
+ )
+
+ def _seen(self, dedup_key: str | None, role: SpanRole) -> bool:
+ """Return True once a ``(dedup_key, role)`` pair has been emitted.
+
+ Guards against emitting the same span twice when a streaming call
+ fires both a sync and an async logging callback.
+ """
+ if not dedup_key:
+ return False
+ marker = (dedup_key, role)
+ if marker in self._emitted:
+ self._emitted.move_to_end(marker)
+ return True
+ self._emitted[marker] = None
+ if len(self._emitted) > _DEDUP_CACHE_MAX:
+ self._emitted.popitem(last=False) # evict least-recently-used
+ return False
+
+ # -- the engine ---------------------------------------------------------- #
+
+ def emit(
+ self,
+ role: SpanRole,
+ data: SpanData,
+ parent_context: Context | None = None,
+ *,
+ start_time_ns: int | None = None,
+ end_time_ns: int | None = None,
+ tracer: Tracer | None = None,
+ ) -> Span | None:
+ """Emit one complete span: dedup, start, map attributes, status, end.
+
+ Return the span, or ``None`` if it was deduplicated away. ``tracer``
+ overrides the bound tracer for this span, used for per-request routing.
+ """
+ # Only LLM-call spans carry a dedup key; LLM-call and service spans
+ # carry an ``error`` field. ``isinstance`` narrows the type for mypy and
+ # keeps the engine free of duck-typed attribute reads.
+ dedup_key = data.identity.call_id if isinstance(data, LLMCallSpanData) else None
+ if self._seen(dedup_key, role):
+ return None
+ span = self.start_span(
+ role,
+ _NAME_BUILDERS[role](data),
+ parent_context=parent_context,
+ start_time_ns=start_time_ns,
+ tracer=tracer,
+ )
+ self.finish_span(role, span, data, end_time_ns=end_time_ns)
+ return span
+
+ def finish_span(
+ self,
+ role: SpanRole,
+ span: Span,
+ data: SpanData,
+ *,
+ end_time_ns: int | None = None,
+ ) -> None:
+ """Stamp attributes + status on an already-started ``span`` and end it.
+
+ The counterpart to :meth:`start_span` for callers that own a span's
+ lifecycle — the LLM-call span is opened at the request's ``pre_call``
+ boundary (so it parents to the live server span via real ambient context,
+ never a span threaded through a metadata dict) and closed here once the
+ typed payload is available. The span name is (re)built from the now-known
+ data, since the boundary opener only has a provisional name.
+ """
+ span.update_name(_NAME_BUILDERS[role](data))
+ for mapper in self._mappers:
+ for key, value in mapper.map(data).items():
+ span.set_attribute(key, value)
+ error = (
+ data.error
+ if isinstance(data, (LLMCallSpanData, ServiceSpanData, GuardrailSpanData))
+ else None
+ )
+ if error and (error.error_type or error.message):
+ span.set_attribute(Error.TYPE, error.error_type or "error")
+ span.set_status(
+ Status(StatusCode.ERROR, error.message or error.error_type or "error")
+ )
+ # On success leave the status UNSET (the semconv default) rather than
+ # forcing OK — that matches the FastAPI server span and avoids implying a
+ # span-level health signal litellm doesn't actually evaluate. Only a
+ # genuine error sets a status.
+ span.end(end_time=end_time_ns)
diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py
new file mode 100644
index 00000000000..007b41df0a3
--- /dev/null
+++ b/litellm/integrations/otel/logger.py
@@ -0,0 +1,495 @@
+"""``CustomLogger`` adapter on the OpenTelemetry span engine."""
+
+from collections import OrderedDict
+from contextlib import contextmanager
+from datetime import datetime
+from typing import TYPE_CHECKING, Any, Iterator, Mapping, cast
+
+from opentelemetry.context import attach, get_current
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.trace import Span, Tracer, get_current_span, use_span
+
+import litellm
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.integrations.otel.model.baggage import promoted_baggage
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config
+from litellm.integrations.otel.plumbing.context import (
+ is_recordable_span,
+ resolve_parent_context,
+ resolve_request_span_context,
+ set_request_baggage,
+ set_request_root_span,
+)
+from litellm.integrations.otel.emitter import SpanEmitter
+from litellm.integrations.otel.mappers import resolve_mappers
+from litellm.integrations.otel.model.metadata import (
+ LLMCallEvent,
+ RequestIdentity,
+ guardrail_entries_from_request_data,
+ model_from_request_data,
+)
+from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+ SpanError,
+)
+from litellm.integrations.otel.plumbing.providers import (
+ build_tracer_provider,
+ get_tracer,
+)
+from litellm.integrations.otel.plumbing.routing import TenantTracerCache
+from litellm.integrations.otel.model.spans import SpanRole, span_role_for_service
+from litellm.integrations.otel.model.utils import to_ns
+
+if TYPE_CHECKING:
+ from litellm.types.utils import StandardLoggingGuardrailInformation
+
+LITELLM_TRACER_NAME = "litellm"
+
+# Any callback whose class belongs to one of these modules is "the OTel
+# callback" for proxy-global-registration purposes.
+_OTEL_MODULES = (
+ "litellm.integrations.otel",
+ "litellm.integrations.opentelemetry",
+)
+
+
+# Cap on the open-call carrier map. A span opened at ``pre_call`` that never
+# reaches a success/failure callback (e.g. a stream that only fires stream
+# events) would otherwise linger; bounding the map evicts the oldest so memory
+# stays flat on a long-running proxy while covering every concurrent in-flight
+# call.
+_OPEN_CALLS_MAX = 10_000
+
+
+class _LLMCallSpan:
+ """The state carried from the ``pre_call`` boundary to span close.
+
+ ``span`` is the live span when it could be opened at the boundary (the server
+ span was ambient), or ``None`` when creation was deferred because no ambient
+ parent was visible — in which case the async callback creates it against its
+ own (worker-copied) ambient context using ``start_time_ns``. The presence of
+ a carrier for a call at all is the proof that ``pre_call`` ran, i.e. that an
+ upstream call was actually attempted.
+ """
+
+ __slots__ = ("span", "start_time_ns")
+
+ def __init__(self, span: "Span | None", start_time_ns: int | None) -> None:
+ self.span = span
+ self.start_time_ns = start_time_ns
+
+
+class OpenTelemetryV2(CustomLogger):
+ """The ``CustomLogger`` for OpenTelemetry."""
+
+ def __init__(
+ self,
+ config: OpenTelemetryV2Config | None = None,
+ 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
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.config: OpenTelemetryV2Config = config or OpenTelemetryV2Config(**kwargs)
+ self.callback_name = callback_name
+ self._tracer_provider: TracerProvider = (
+ tracer_provider
+ if tracer_provider is not None
+ else build_tracer_provider(self.config)
+ )
+ self.tracer: Tracer = get_tracer(self._tracer_provider, LITELLM_TRACER_NAME)
+ self._emitter = SpanEmitter(
+ self.tracer, self.config, mappers=resolve_mappers(self.config.mapper_names)
+ )
+ self._tenant_tracers = TenantTracerCache(
+ self.config, callback_name, LITELLM_TRACER_NAME
+ )
+ self._open_llm_calls: "OrderedDict[str, _LLMCallSpan]" = OrderedDict()
+ self._init_otel_logger_on_litellm_proxy()
+
+ # ====================================================================== #
+ # Proxy global registration
+ # ====================================================================== #
+
+ def _register_in_callback_list(self, callbacks: list) -> None:
+ already_otel = any(
+ cb.__class__.__module__.startswith(_OTEL_MODULES)
+ for cb in callbacks
+ if hasattr(cb, "__class__")
+ )
+ if not already_otel:
+ callbacks.append(self)
+
+ def _init_otel_logger_on_litellm_proxy(self) -> None:
+ try:
+ from litellm.proxy import proxy_server
+ except Exception:
+ return
+ try:
+ self._register_in_callback_list(litellm.service_callback)
+ self._register_in_callback_list(litellm.input_callback)
+ self._register_in_callback_list(litellm._async_success_callback)
+ self._register_in_callback_list(litellm._async_failure_callback)
+ except Exception:
+ pass
+ if getattr(proxy_server, "open_telemetry_logger", None) is None:
+ setattr(proxy_server, "open_telemetry_logger", self)
+
+ # ====================================================================== #
+ # LLM-call callbacks — the span is opened at the ``pre_call`` boundary and
+ # closed here. See ``log_pre_api_call``.
+ # ====================================================================== #
+
+ def log_pre_api_call(self, model, messages, kwargs):
+ """Open the LLM-call span at the call boundary.
+
+ Runs synchronously inside the request task, before the upstream call —
+ the one place where the live server span is genuinely the ambient OTel
+ context — so the span parents to it natively, with no span threaded
+ through a metadata dict. The open span is stashed on the per-request
+ ``LiteLLMLoggingObj`` (a typed object) and closed in the async callback.
+
+ When no recordable parent is visible (``pre_call`` was driven from a thread
+ pool for a sync-only provider, where contextvars — and so the anchor —
+ don't follow), creation is deferred: only the start time is recorded, and
+ the async callback — whose worker context was copied from the request task
+ and so still carries the anchor — creates the span then.
+
+ Synthetic proxy-gate error logs (auth/rate-limit rejections) also fire this
+ hook but never made an upstream call; they are tagged and skipped so no
+ phantom LLM-call span is produced.
+ """
+ call = LLMCallEvent.from_dict(kwargs)
+ if call.is_no_upstream_call:
+ return
+ call_id = call.call_id
+ if call_id is None:
+ return
+ # Idempotent: a retried call may re-enter ``pre_call`` with the same
+ # call id; keep the first span so its start time is the true one.
+ if call_id in self._open_llm_calls:
+ return
+ start_time_ns = to_ns(datetime.now())
+ span: Span | None = None
+ # Parent to the request's anchored root span (stable across the request),
+ # falling back to ambient on the SDK path. Open the span live only when
+ # that resolves to a recordable parent; otherwise defer to the close
+ # callback (the thread-pool case, where the anchor isn't visible here).
+ parent_context = resolve_request_span_context()
+ if is_recordable_span(get_current_span(parent_context)):
+ span = self._emitter.start_span(
+ SpanRole.LLM_CALL,
+ call.provisional_span_name,
+ parent_context=parent_context,
+ start_time_ns=start_time_ns,
+ tracer=self._tenant_tracers.tracer_for(
+ self.tracer, call.dynamic_params
+ ),
+ )
+ self._open_llm_calls[call_id] = _LLMCallSpan(
+ span=span, start_time_ns=start_time_ns
+ )
+ # Evict the oldest open call if the map is over budget. A call that opens
+ # but never closes (a stream that only fires stream events) would linger
+ # otherwise; the evicted span is simply dropped (never exported).
+ if len(self._open_llm_calls) > _OPEN_CALLS_MAX:
+ self._open_llm_calls.popitem(last=False)
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ self._close_llm_call(kwargs, start_time, end_time)
+
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
+ self._close_llm_call(kwargs, start_time, end_time)
+
+ def _close_llm_call(
+ self,
+ kwargs: Mapping[str, Any],
+ start_time: datetime | float | None,
+ end_time: datetime | float | None,
+ ) -> Span | None:
+ """Finish the LLM-call span opened at ``pre_call`` (or create it deferred).
+
+ No carrier for this call id means ``pre_call`` never ran — the request was
+ rejected at the gate or blocked by a pre-call guardrail before any upstream
+ call — so there is nothing to record and no phantom span.
+ """
+ call = LLMCallEvent.from_dict(kwargs)
+ call_id = call.call_id
+ # ``pop`` is the dedup: this method runs from both the success and failure
+ # paths, and whichever fires first removes the carrier and closes the span.
+ carrier = self._open_llm_calls.pop(call_id, None) if call_id else None
+ if carrier is None:
+ return None
+ payload = call.payload
+ if payload is None:
+ if carrier.span is not None:
+ # Opened at the boundary but the payload never materialized — end
+ # it (named provisionally) so it isn't leaked as an open span.
+ carrier.span.end(end_time=to_ns(end_time))
+ return None
+ data = LLMCallSpanData.from_standard_logging_payload(
+ payload, capture_content=self.config.capture_span_content
+ )
+ end_time_ns = to_ns(end_time)
+ if carrier.span is not None:
+ # Born at the boundary: stamp attributes from the typed payload, set
+ # status, and end it. Its parent (the server span) was captured at
+ # creation from real ambient context.
+ self._emitter.finish_span(
+ SpanRole.LLM_CALL, carrier.span, data, end_time_ns=end_time_ns
+ )
+ return carrier.span
+ # Deferred: ``pre_call`` saw no recordable parent, so create the span now.
+ # The worker copied the request task's context, which carries the anchored
+ # root span — parent to it (ambient fallback on the SDK path). Seed identity
+ # Baggage so the span — and the SDK path, which has none — is labeled
+ # consistently.
+ parent_ctx = resolve_request_span_context()
+ bag = promoted_baggage(
+ data.identity,
+ data.request_model,
+ promoted_keys=tuple(self.config.baggage_promoted_keys),
+ metadata_keys=tuple(self.config.baggage_metadata_keys),
+ )
+ if bag:
+ parent_ctx = set_request_baggage(bag, context=parent_ctx)
+ return self._emitter.emit(
+ SpanRole.LLM_CALL,
+ data,
+ parent_context=parent_ctx,
+ start_time_ns=carrier.start_time_ns,
+ end_time_ns=end_time_ns,
+ tracer=self._tenant_tracers.tracer_for(self.tracer, call.dynamic_params),
+ )
+
+ # ====================================================================== #
+ # Service hooks
+ # ====================================================================== #
+
+ async def async_service_success_hook(
+ self,
+ payload: Any,
+ parent_otel_span: Span | None = None,
+ start_time: datetime | float | None = None,
+ end_time: datetime | float | None = None,
+ event_metadata: dict | None = None,
+ ) -> None:
+ self._emit_service(
+ payload,
+ parent_otel_span=parent_otel_span,
+ start_time=start_time,
+ end_time=end_time,
+ event_metadata=event_metadata,
+ error_override=None,
+ )
+
+ async def async_service_failure_hook(
+ self,
+ payload: Any,
+ error: str | None = "",
+ parent_otel_span: Span | None = None,
+ start_time: datetime | float | None = None,
+ end_time: datetime | float | None = None,
+ event_metadata: dict | None = None,
+ ) -> None:
+ self._emit_service(
+ payload,
+ parent_otel_span=parent_otel_span,
+ start_time=start_time,
+ end_time=end_time,
+ event_metadata=event_metadata,
+ error_override=error or "error",
+ )
+
+ def _emit_service(
+ self,
+ payload: Any,
+ *,
+ parent_otel_span: Span | None,
+ start_time: datetime | float | None,
+ end_time: datetime | float | None,
+ event_metadata: dict | None,
+ error_override: str | None,
+ ) -> Span | None:
+ data = ServiceSpanData.from_payload(payload, event_metadata=event_metadata)
+ # Decide whether this service call is a span at all, and of what kind.
+ # ``None`` means metrics-only (framework instrumentation that duplicates a
+ # gen-AI span — ``self``/``router``/``proxy_pre_call`` — or ``auth``, which
+ # gets a live phase span instead). Those still feed Prometheus/Datadog via
+ # their own hooks; they just never enter the trace.
+ role = span_role_for_service(data.service_name)
+ if role is None:
+ return None
+ # A metrics-only ping with neither timing nor a parent (in-memory queue
+ # gauges) is not a traceable operation; a span for it would be a
+ # zero-duration root with no context, so skip it. Real background work
+ # (budget/reset jobs, spend flush) passes start/end times and still emits
+ # as a root; anything with a parent emits regardless.
+ if (
+ error_override is None
+ and start_time is None
+ and end_time is None
+ and parent_otel_span is None
+ ):
+ return None
+ if error_override is not None and data.error is None:
+ data = ServiceSpanData(
+ service_name=data.service_name,
+ call_type=data.call_type,
+ error=SpanError(message=error_override),
+ event_metadata=data.event_metadata,
+ )
+ # Parent like every other span: ambient context first (so identity Baggage
+ # rides along and the call nests under whatever request phase is active —
+ # e.g. a DB lookup under the live ``auth`` span), falling back to the
+ # server span the proxy threaded as ``parent_otel_span``. A background
+ # service call has neither, so it starts its own root trace.
+ parent_context = resolve_parent_context(threaded=parent_otel_span)
+ return self._emitter.emit(
+ role,
+ data,
+ parent_context=parent_context,
+ start_time_ns=to_ns(start_time),
+ end_time_ns=to_ns(end_time),
+ )
+
+ # ====================================================================== #
+ # async_post_call_* hooks — emit guardrail spans. The server span's status
+ # / errors are the FastAPI instrumentor's job, so we don't touch it here.
+ # ====================================================================== #
+
+ def seed_request_identity(self, user_api_key_dict: Any, model: Any = None) -> None:
+ """Attach request-identity Baggage to the current context + server span.
+
+ Seeding identity into Baggage makes **every** span emitted afterwards for
+ this request — LLM call, guardrail, DB call — inherit it via
+ ``LiteLLMBaggageSpanProcessor``. Called once at the auth boundary (as soon
+ as the key resolves) so post-auth spans are labeled consistently; the
+ Baggage rides the request task's contextvar from there on. Auth-internal
+ DB lookups that run before the key is known stay unlabeled — identity
+ isn't determined yet, which is correct.
+ """
+ try:
+ identity = RequestIdentity.from_user_api_key_auth(user_api_key_dict)
+ bag = promoted_baggage(
+ identity,
+ model,
+ promoted_keys=tuple(self.config.baggage_promoted_keys),
+ metadata_keys=tuple(self.config.baggage_metadata_keys),
+ )
+ if bag:
+ # Attach (no detach): the contextvar is scoped to this request's
+ # asyncio task and is reclaimed when the task ends.
+ attach(set_request_baggage(bag, context=get_current()))
+ # The server span was started by the instrumentor before this ran,
+ # so the Baggage processor (which only fires at span start) won't
+ # backfill it — stamp identity on it directly.
+ server_span = get_current_span()
+ if is_recordable_span(server_span):
+ # Re-capture the anchor here too: this runs post-auth with the
+ # server span active and covers entrypoints that bypass
+ # ``create_litellm_proxy_request_started_span`` (e.g. the SDK
+ # path's ``async_pre_call_hook``). Idempotent.
+ set_request_root_span(server_span)
+ for key, value in bag.items():
+ server_span.set_attribute(key, value)
+ except Exception:
+ pass
+
+ @contextmanager
+ def start_phase_span(self, name: str) -> "Iterator[Span]":
+ span = self._emitter.start_span(SpanRole.SERVICE, name)
+ with use_span(span, end_on_exit=True):
+ yield span
+
+ async def async_pre_call_hook(
+ self,
+ user_api_key_dict: Any,
+ cache: Any,
+ data: dict,
+ call_type: Any,
+ ) -> dict:
+ self.seed_request_identity(
+ user_api_key_dict,
+ model=model_from_request_data(data),
+ )
+ return data
+
+ async def async_post_call_success_hook(
+ self,
+ data: Mapping[str, Any],
+ user_api_key_dict: Any,
+ response: Any,
+ ) -> Any:
+ self._emit_guardrail_spans(data)
+ return response
+
+ async def async_post_call_failure_hook(
+ self,
+ request_data: Mapping[str, Any],
+ original_exception: BaseException | None,
+ user_api_key_dict: Any,
+ traceback_str: str | None = None,
+ ) -> None:
+ self._emit_guardrail_spans(request_data)
+
+ def _emit_guardrail_spans(self, request_data: Mapping[str, Any]) -> None:
+ # A guardrail is a sibling of the LLM call under the request's root span,
+ # so parent it to the explicit anchor — not the active span, which on the
+ # failure path can be the live ``auth`` phase span (post-call failure hooks
+ # run from inside it on an auth rejection). Emit with the guardrail's actual
+ # execution window so a pre_call guardrail is placed before the LLM call
+ # rather than at post-call emission time.
+ guardrails = guardrail_entries_from_request_data(request_data)
+ if not guardrails:
+ return
+ parent_ctx = resolve_request_span_context()
+ for entry in guardrails:
+ data = GuardrailSpanData.from_logging_entry(
+ cast("StandardLoggingGuardrailInformation", entry)
+ )
+ self._emitter.emit(
+ SpanRole.GUARDRAIL,
+ data,
+ parent_context=parent_ctx,
+ start_time_ns=to_ns(data.start_time),
+ end_time_ns=to_ns(data.end_time),
+ )
+
+ def create_litellm_proxy_request_started_span(
+ self, start_time: datetime, headers: Mapping[str, str] | None
+ ) -> Span | None:
+ span = get_current_span()
+ if not is_recordable_span(span):
+ return None
+ set_request_root_span(span)
+ return span
+
+
+def _registered_v2_logger() -> "OpenTelemetryV2 | None":
+ try:
+ from litellm.proxy import proxy_server
+ except Exception:
+ return None
+ logger = getattr(proxy_server, "open_telemetry_logger", None)
+ return logger if isinstance(logger, OpenTelemetryV2) else None
+
+
+def seed_request_identity(user_api_key_dict: Any, model: Any = None) -> None:
+ logger = _registered_v2_logger()
+ if logger is not None:
+ logger.seed_request_identity(user_api_key_dict, model=model)
+
+
+@contextmanager
+def phase_span(name: str) -> "Iterator[Span | None]":
+ logger = _registered_v2_logger()
+ if logger is None:
+ yield None
+ return
+ with logger.start_phase_span(name) as span:
+ yield span
diff --git a/litellm/integrations/otel/mappers/__init__.py b/litellm/integrations/otel/mappers/__init__.py
new file mode 100644
index 00000000000..012e63f1bee
--- /dev/null
+++ b/litellm/integrations/otel/mappers/__init__.py
@@ -0,0 +1,58 @@
+"""Attribute mappers: pure ``LLMCallSpanData -> {attribute key: value}`` functions.
+
+Composition over inheritance: vocabularies layer onto the same span. Listing
+``["genai", "openinference"]`` in ``config.mapper_names`` makes every span
+carry both the canonical ``gen_ai.*`` keys and the OpenInference (Arize +
+Phoenix) keys. Add ``"langfuse"`` and it works for all three backends at once.
+"""
+
+from typing import Callable, Iterable
+
+from litellm.integrations.otel.mappers.base import (
+ AttributeMap,
+ AttributeMapper,
+ AttrValue,
+)
+from litellm.integrations.otel.mappers.genai import GenAIMapper
+from litellm.integrations.otel.mappers.langfuse import LangfuseMapper
+from litellm.integrations.otel.mappers.langtrace import LangtraceMapper
+from litellm.integrations.otel.mappers.legacy import LegacyMapper
+from litellm.integrations.otel.mappers.openinference import OpenInferenceMapper
+from litellm.integrations.otel.mappers.weave import WeaveMapper
+
+# Registry keyed by ``config.mapper_names`` entries.
+_MAPPER_BY_NAME: dict[str, Callable[[], AttributeMapper]] = {
+ "genai": GenAIMapper,
+ "legacy": LegacyMapper,
+ "openinference": OpenInferenceMapper,
+ "langfuse": LangfuseMapper,
+ "weave": WeaveMapper,
+ "langtrace": LangtraceMapper,
+}
+
+
+def resolve_mappers(names: Iterable[str]) -> list[AttributeMapper]:
+ """Resolve mapper names to instances. Unknown names raise ``ValueError``."""
+ out: list[AttributeMapper] = []
+ for name in names:
+ factory = _MAPPER_BY_NAME.get(name)
+ if factory is None:
+ raise ValueError(
+ f"unknown mapper name {name!r}; known: " f"{sorted(_MAPPER_BY_NAME)}"
+ )
+ out.append(factory())
+ return out
+
+
+__all__ = [
+ "AttributeMap",
+ "AttributeMapper",
+ "AttrValue",
+ "GenAIMapper",
+ "LangfuseMapper",
+ "LangtraceMapper",
+ "LegacyMapper",
+ "OpenInferenceMapper",
+ "WeaveMapper",
+ "resolve_mappers",
+]
diff --git a/litellm/integrations/otel/mappers/base.py b/litellm/integrations/otel/mappers/base.py
new file mode 100644
index 00000000000..e8fb5af9797
--- /dev/null
+++ b/litellm/integrations/otel/mappers/base.py
@@ -0,0 +1,36 @@
+"""Mapper protocol and attribute value types."""
+
+from typing import Sequence
+
+from typing_extensions import Protocol, runtime_checkable
+
+from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+)
+
+AttrScalar = str | bool | int | float
+# Mirrors ``opentelemetry.util.types.AttributeValue`` (homogeneous sequences)
+# without importing the SDK, so mappers stay OTel-free.
+AttrValue = (
+ AttrScalar | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]
+)
+AttributeMap = dict[str, AttrValue]
+
+# The closed set of span-data types the engine routes through the mapper chain.
+# Server spans (PROXY_REQUEST + management routes) belong to the mounted FastAPI
+# instrumentor, not the mapper chain.
+SpanData = LLMCallSpanData | GuardrailSpanData | ServiceSpanData
+
+
+@runtime_checkable
+class AttributeMapper(Protocol):
+ """Maps a typed span input to a flat dict of OTel span attributes.
+
+ One method per mapper, dispatched internally on the ``data`` type. The
+ engine calls this uniformly for every span kind — mappers that don't speak
+ a given type return ``{}``. This is why the engine contains no attribute keys.
+ """
+
+ def map(self, data: SpanData) -> AttributeMap: ...
diff --git a/litellm/integrations/otel/mappers/genai.py b/litellm/integrations/otel/mappers/genai.py
new file mode 100644
index 00000000000..57fa51ea1fb
--- /dev/null
+++ b/litellm/integrations/otel/mappers/genai.py
@@ -0,0 +1,137 @@
+"""Canonical OpenTelemetry GenAI semantic-convention mapper (always active).
+
+Owns the attribute schema for every span kind the engine emits — LLM call,
+guardrail, and service — so the engine itself never references attribute keys.
+
+Each span kind declares its schema as a flat ``attribute key -> extractor``
+table: one lambda per mapping operation, applied against the typed span data.
+"""
+
+from typing import Callable
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import collect, drop_none
+from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+ ToolDefinition,
+)
+from litellm.integrations.otel.model.semconv import DB, Error, GenAI, LiteLLM, Server
+from litellm.integrations.otel.model.spans import db_system
+
+
+class GenAIMapper:
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ GenAI.OPERATION_NAME: lambda d: d.operation.value,
+ GenAI.PROVIDER_NAME: lambda d: d.provider or None,
+ GenAI.REQUEST_MODEL: lambda d: d.request_model or None,
+ GenAI.REQUEST_TEMPERATURE: lambda d: d.request_params.temperature,
+ GenAI.REQUEST_TOP_P: lambda d: d.request_params.top_p,
+ GenAI.REQUEST_TOP_K: lambda d: d.request_params.top_k,
+ GenAI.REQUEST_MAX_TOKENS: lambda d: d.request_params.max_tokens,
+ GenAI.REQUEST_FREQUENCY_PENALTY: lambda d: d.request_params.frequency_penalty,
+ GenAI.REQUEST_PRESENCE_PENALTY: lambda d: d.request_params.presence_penalty,
+ GenAI.REQUEST_STOP_SEQUENCES: lambda d: (
+ list(d.request_params.stop_sequences)
+ if d.request_params.stop_sequences
+ else None
+ ),
+ GenAI.REQUEST_SEED: lambda d: d.request_params.seed,
+ GenAI.RESPONSE_MODEL: lambda d: d.response_model,
+ GenAI.RESPONSE_ID: lambda d: d.response_id,
+ GenAI.RESPONSE_FINISH_REASONS: lambda d: (
+ list(d.finish_reasons) if d.finish_reasons else None
+ ),
+ GenAI.USAGE_INPUT_TOKENS: lambda d: d.usage.input_tokens,
+ GenAI.USAGE_OUTPUT_TOKENS: lambda d: d.usage.output_tokens,
+ Error.TYPE: lambda d: d.error.error_type if d.error else None,
+ Server.ADDRESS: lambda d: d.server.address if d.server else None,
+ Server.PORT: lambda d: d.server.port if d.server else None,
+ LiteLLM.CALL_ID: lambda d: d.identity.call_id or None,
+ # The provider/underlying model is only known once routing has picked a
+ # deployment, so it can't ride identity Baggage (seeded at auth, before
+ # routing) onto the boundary-born LLM span — stamp it directly here.
+ LiteLLM.PROVIDER_MODEL: lambda d: d.identity.provider_model or None,
+ f"{LiteLLM.COST_PREFIX}total": lambda d: d.response_cost,
+ LiteLLM.REQUEST_STREAMING: lambda d: d.is_streaming,
+ }
+
+ _TOOL_ATTRS: dict[str, Callable[[ToolDefinition], AttrValue | None]] = {
+ "name": lambda t: t.name,
+ "description": lambda t: t.description or None,
+ "parameters": lambda t: t.parameters_json or None,
+ }
+
+ _GUARDRAIL_ATTRS: dict[str, Callable[[GuardrailSpanData], AttrValue | None]] = {
+ LiteLLM.GUARDRAIL_NAME: lambda d: d.guardrail_name,
+ LiteLLM.GUARDRAIL_MODE: lambda d: d.mode,
+ LiteLLM.GUARDRAIL_STATUS: lambda d: d.status,
+ LiteLLM.GUARDRAIL_PROVIDER: lambda d: d.provider,
+ LiteLLM.GUARDRAIL_ACTION: lambda d: d.action,
+ LiteLLM.GUARDRAIL_RESPONSE: lambda d: d.response_json,
+ LiteLLM.GUARDRAIL_VIOLATION_CATEGORIES: lambda d: (
+ list(d.violation_categories) if d.violation_categories else None
+ ),
+ LiteLLM.GUARDRAIL_CONFIDENCE_SCORE: lambda d: d.confidence_score,
+ LiteLLM.GUARDRAIL_RISK_SCORE: lambda d: d.risk_score,
+ LiteLLM.GUARDRAIL_MASKED_ENTITY_COUNT: lambda d: d.masked_entity_count,
+ LiteLLM.GUARDRAIL_DURATION: lambda d: d.duration,
+ LiteLLM.GUARDRAIL_ID: lambda d: d.guardrail_id,
+ LiteLLM.GUARDRAIL_POLICY_TEMPLATE: lambda d: d.policy_template,
+ LiteLLM.GUARDRAIL_DETECTION_METHOD: lambda d: d.detection_method,
+ }
+
+ _SERVICE_ATTRS: dict[str, Callable[[ServiceSpanData], AttrValue | None]] = {
+ LiteLLM.SERVICE_NAME: lambda d: d.service_name,
+ LiteLLM.SERVICE_CALL_TYPE: lambda d: d.call_type,
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case GuardrailSpanData():
+ return self._guardrail(data)
+ case ServiceSpanData():
+ return self._service(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ attrs = collect(cls._LLM_CALL_ATTRS, data)
+ attrs.update(
+ drop_none(
+ {
+ f"gen_ai.tool.{idx}.{suffix}": extract(tool)
+ for idx, tool in enumerate(data.tools)
+ for suffix, extract in cls._TOOL_ATTRS.items()
+ }
+ )
+ )
+ return attrs
+
+ @classmethod
+ def _guardrail(cls, data: GuardrailSpanData) -> AttributeMap:
+ return collect(cls._GUARDRAIL_ATTRS, data)
+
+ @classmethod
+ def _service(cls, data: ServiceSpanData) -> AttributeMap:
+ attrs = collect(cls._SERVICE_ATTRS, data)
+ # An outbound datastore call (DB_CALL / CLIENT span) also carries db.*
+ # semconv. Internal services (router, budget jobs, …) have no db.system,
+ # so they get only the litellm.service.* keys above.
+ system = db_system(data.service_name)
+ if system is not None:
+ attrs[DB.SYSTEM_NAME] = system
+ if data.call_type:
+ attrs[DB.OPERATION_NAME] = data.call_type
+ attrs.update(
+ {
+ f"{LiteLLM.METADATA_PREFIX}{key}": value
+ for key, value in data.event_metadata.items()
+ }
+ )
+ return attrs
diff --git a/litellm/integrations/otel/mappers/langfuse.py b/litellm/integrations/otel/mappers/langfuse.py
new file mode 100644
index 00000000000..14c9fd01d05
--- /dev/null
+++ b/litellm/integrations/otel/mappers/langfuse.py
@@ -0,0 +1,84 @@
+"""Langfuse OTLP attribute mapper.
+
+Langfuse ingests OTLP spans and reads from its own vendor namespace
+(``langfuse.observation.*``, ``langfuse.trace.*``). Compose this mapper after
+``GenAIMapper`` to send canonical + Langfuse-flavored spans simultaneously.
+
+Every attribute is declared as a ``key -> extractor`` table entry (one callable
+per mapping operation): ``_LLM_CALL_ATTRS`` for scalars and ``_BLOB_ATTRS`` for
+the JSON-serialized payloads. ``_llm_call`` just applies both tables.
+"""
+
+import json
+from typing import Callable
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import (
+ collect,
+ json_if,
+ output_messages,
+ serialize_messages,
+)
+from litellm.integrations.otel.model.payloads import (
+ LLMCallSpanData,
+ LLMRequestParams,
+ LLMUsage,
+)
+
+
+class LangfuseMapper:
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "langfuse.observation.type": lambda d: "generation",
+ "langfuse.observation.model.name": lambda d: d.request_model or None,
+ "langfuse.observation.metadata.provider": lambda d: d.provider or None,
+ "langfuse.observation.id": lambda d: d.identity.call_id or None,
+ "langfuse.trace.metadata.team_id": lambda d: d.identity.team_id or None,
+ "langfuse.trace.metadata.team_alias": lambda d: d.identity.team_alias or None,
+ }
+
+ # Sub-tables folded into their respective JSON blobs.
+ _MODEL_PARAMS: dict[str, Callable[[LLMRequestParams], AttrValue | None]] = {
+ "temperature": lambda rp: rp.temperature,
+ "top_p": lambda rp: rp.top_p,
+ "max_tokens": lambda rp: rp.max_tokens,
+ "frequency_penalty": lambda rp: rp.frequency_penalty,
+ "presence_penalty": lambda rp: rp.presence_penalty,
+ "seed": lambda rp: rp.seed,
+ }
+ _USAGE_FIELDS: dict[str, Callable[[LLMUsage], AttrValue | None]] = {
+ "input": lambda u: u.input_tokens,
+ "output": lambda u: u.output_tokens,
+ "total": lambda u: u.total_tokens,
+ }
+
+ # JSON-payload attributes: each builder returns the serialized blob or None.
+ _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "langfuse.observation.model.parameters": lambda d: json_if(
+ collect(LangfuseMapper._MODEL_PARAMS, d.request_params)
+ ),
+ "langfuse.observation.input": lambda d: serialize_messages(d.messages_in),
+ "langfuse.observation.output": lambda d: serialize_messages(output_messages(d)),
+ "langfuse.observation.usage_details": lambda d: json_if(
+ collect(LangfuseMapper._USAGE_FIELDS, d.usage)
+ ),
+ "langfuse.observation.cost_details": lambda d: (
+ json.dumps({"total": d.response_cost})
+ if d.response_cost is not None
+ else None
+ ),
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ return {
+ **collect(cls._LLM_CALL_ATTRS, data),
+ **collect(cls._BLOB_ATTRS, data),
+ }
diff --git a/litellm/integrations/otel/mappers/langtrace.py b/litellm/integrations/otel/mappers/langtrace.py
new file mode 100644
index 00000000000..7c0f30e57dd
--- /dev/null
+++ b/litellm/integrations/otel/mappers/langtrace.py
@@ -0,0 +1,64 @@
+"""Langtrace attribute mapper.
+
+Produces Langtrace's attribute vocabulary so a span can be ingested by a
+Langtrace backend. Compose it alongside other mappers like any other
+vocabulary.
+
+Scalar attributes are declared as a flat ``key -> extractor`` table (one lambda
+per mapping operation); the prompt/completion blobs are serialized as a tail.
+"""
+
+from typing import Callable
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import (
+ collect,
+ json_or_none,
+ output_messages,
+)
+from litellm.integrations.otel.model.payloads import LLMCallSpanData
+
+
+class LangtraceMapper:
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "gen_ai.operation.name": lambda d: "chat",
+ "langtrace.service.name": lambda d: d.provider or None,
+ "llm.model": lambda d: d.request_model or None,
+ "gen_ai.response.model": lambda d: d.response_model or None,
+ "gen_ai.response_id": lambda d: d.response_id or None,
+ "gen_ai.system_fingerprint": lambda d: d.system_fingerprint or None,
+ "llm.temperature": lambda d: d.request_params.temperature,
+ "llm.top_p": lambda d: d.request_params.top_p,
+ "llm.top_k": lambda d: d.request_params.top_k,
+ "llm.max_tokens": lambda d: d.request_params.max_tokens,
+ "llm.frequency_penalty": lambda d: d.request_params.frequency_penalty,
+ "llm.presence_penalty": lambda d: d.request_params.presence_penalty,
+ "llm.stream": lambda d: d.is_streaming,
+ "llm.token.counts.prompt": lambda d: d.usage.input_tokens,
+ "llm.token.counts.completion": lambda d: d.usage.output_tokens,
+ "llm.token.counts.total": lambda d: d.usage.total_tokens,
+ }
+
+ _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "llm.prompts": lambda d: (
+ json_or_none(list(d.messages_in)) if d.messages_in else None
+ ),
+ "llm.completions": lambda d: (
+ json_or_none(output_messages(d)) if d.choices_out else None
+ ),
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ return {
+ **collect(cls._LLM_CALL_ATTRS, data),
+ **collect(cls._BLOB_ATTRS, data),
+ }
diff --git a/litellm/integrations/otel/mappers/legacy.py b/litellm/integrations/otel/mappers/legacy.py
new file mode 100644
index 00000000000..20ffe8b0dd8
--- /dev/null
+++ b/litellm/integrations/otel/mappers/legacy.py
@@ -0,0 +1,97 @@
+"""Mapper for the older semantic-convention attribute vocabulary.
+
+Emits attributes under the semconv-ai / Traceloop key names (e.g.
+``gen_ai.system``, ``gen_ai.usage.prompt_tokens``, ``llm.is_streaming``) plus a
+few bare, unprefixed service keys (``service``, ``call_type``, ``error``), for
+backends that consume those names.
+
+Like ``GenAIMapper``, each span kind declares its schema as a flat
+``attribute key -> extractor`` table: one lambda per mapping operation.
+"""
+
+from typing import Callable, Final
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import collect, drop_none
+from litellm.integrations.otel.model.payloads import (
+ LLMCallSpanData,
+ ServiceSpanData,
+ ToolDefinition,
+)
+
+# Attribute keys in the semconv-ai / Traceloop vocabulary.
+_LEGACY_SYSTEM: Final = "gen_ai.system"
+_LEGACY_PROMPT_TOKENS: Final = "gen_ai.usage.prompt_tokens"
+_LEGACY_COMPLETION_TOKENS: Final = "gen_ai.usage.completion_tokens"
+_LEGACY_TOTAL_TOKENS: Final = "gen_ai.usage.total_tokens"
+_LEGACY_IS_STREAMING: Final = "llm.is_streaming"
+_LEGACY_TOP_K: Final = "llm.top_k"
+_LEGACY_FREQUENCY_PENALTY: Final = "llm.frequency_penalty"
+_LEGACY_PRESENCE_PENALTY: Final = "llm.presence_penalty"
+_LEGACY_STOP_SEQUENCES: Final = "llm.chat.stop_sequences"
+_LEGACY_SERVICE: Final = "service"
+_LEGACY_CALL_TYPE: Final = "call_type"
+_LEGACY_ERROR: Final = "error"
+
+
+class LegacyMapper:
+ """Emits LLM-call and service attributes under the older key names."""
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ _LEGACY_SYSTEM: lambda d: d.provider or None,
+ _LEGACY_PROMPT_TOKENS: lambda d: d.usage.input_tokens,
+ _LEGACY_COMPLETION_TOKENS: lambda d: d.usage.output_tokens,
+ _LEGACY_TOTAL_TOKENS: lambda d: d.usage.total_tokens,
+ _LEGACY_IS_STREAMING: lambda d: d.is_streaming,
+ _LEGACY_TOP_K: lambda d: d.request_params.top_k,
+ _LEGACY_FREQUENCY_PENALTY: lambda d: d.request_params.frequency_penalty,
+ _LEGACY_PRESENCE_PENALTY: lambda d: d.request_params.presence_penalty,
+ _LEGACY_STOP_SEQUENCES: lambda d: (
+ list(d.request_params.stop_sequences)
+ if d.request_params.stop_sequences
+ else None
+ ),
+ }
+
+ _TOOL_ATTRS: dict[str, Callable[[ToolDefinition], AttrValue | None]] = {
+ "name": lambda t: t.name,
+ "description": lambda t: t.description or None,
+ "parameters": lambda t: t.parameters_json or None,
+ }
+
+ _SERVICE_ATTRS: dict[str, Callable[[ServiceSpanData], AttrValue | None]] = {
+ _LEGACY_SERVICE: lambda d: d.service_name,
+ _LEGACY_CALL_TYPE: lambda d: d.call_type,
+ _LEGACY_ERROR: lambda d: (
+ d.error.message if d.error is not None and d.error.message else None
+ ),
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case ServiceSpanData():
+ return self._service(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ attrs = collect(cls._LLM_CALL_ATTRS, data)
+ attrs.update(
+ drop_none(
+ {
+ f"llm.request.functions.{idx}.{suffix}": extract(tool)
+ for idx, tool in enumerate(data.tools)
+ for suffix, extract in cls._TOOL_ATTRS.items()
+ }
+ )
+ )
+ return attrs
+
+ @classmethod
+ def _service(cls, data: ServiceSpanData) -> AttributeMap:
+ attrs = collect(cls._SERVICE_ATTRS, data)
+ attrs.update(dict(data.event_metadata))
+ return attrs
diff --git a/litellm/integrations/otel/mappers/openinference.py b/litellm/integrations/otel/mappers/openinference.py
new file mode 100644
index 00000000000..d8195cbe03d
--- /dev/null
+++ b/litellm/integrations/otel/mappers/openinference.py
@@ -0,0 +1,128 @@
+"""OpenInference attribute mapper (Arize + Arize-Phoenix shared vocabulary).
+
+Spec: https://github.com/Arize-ai/openinference/tree/main/spec — the standard
+both Arize and Phoenix consume. Composing this mapper after ``GenAIMapper``
+gives the same span both vocabularies, so a single trace lights up Arize +
+Phoenix + any other OpenInference-aware backend simultaneously.
+"""
+
+import json
+from typing import Callable, Sequence
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import (
+ collect,
+ drop_none,
+ json_if,
+ message_content,
+ output_messages,
+)
+from litellm.integrations.otel.model.payloads import (
+ LLMCallSpanData,
+ LLMRequestParams,
+ ToolDefinition,
+)
+
+
+class OpenInferenceMapper:
+ """Emits OpenInference attributes for LLM_CALL spans.
+
+ Key families (per the OpenInference spec):
+ - ``openinference.span.kind`` — discriminator (``"LLM"`` here)
+ - ``llm.model_name`` / ``llm.provider`` / ``llm.invocation_parameters``
+ - ``llm.input_messages.{i}.message.role`` / ``...content``
+ - ``llm.output_messages.{i}.message.role`` / ``...content``
+ - ``llm.token_count.prompt`` / ``...completion`` / ``...total``
+ - ``input.value`` / ``output.value`` — JSON-serialized request / response
+ """
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "openinference.span.kind": lambda d: "LLM",
+ "llm.model_name": lambda d: d.request_model or None,
+ "llm.provider": lambda d: d.provider or None,
+ "llm.token_count.prompt": lambda d: d.usage.input_tokens,
+ "llm.token_count.completion": lambda d: d.usage.output_tokens,
+ "llm.token_count.total": lambda d: d.usage.total_tokens,
+ }
+
+ # Folded into the ``llm.invocation_parameters`` JSON blob.
+ _INVOCATION_PARAMS: dict[str, Callable[[LLMRequestParams], AttrValue | None]] = {
+ "temperature": lambda rp: rp.temperature,
+ "top_p": lambda rp: rp.top_p,
+ "top_k": lambda rp: rp.top_k,
+ "max_tokens": lambda rp: rp.max_tokens,
+ "frequency_penalty": lambda rp: rp.frequency_penalty,
+ "presence_penalty": lambda rp: rp.presence_penalty,
+ "seed": lambda rp: rp.seed,
+ }
+
+ # Per-tool extractors, keyed by the ``llm.tools.{idx}.*`` suffix.
+ _TOOL_ATTRS: dict[str, Callable[[ToolDefinition], AttrValue | None]] = {
+ "tool.name": lambda t: t.name,
+ "tool.description": lambda t: t.description or None,
+ "tool.json_schema": lambda t: t.parameters_json or None,
+ }
+
+ # JSON-payload attributes: each builder returns the serialized blob or None.
+ _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ "llm.invocation_parameters": lambda d: json_if(
+ collect(OpenInferenceMapper._INVOCATION_PARAMS, d.request_params)
+ ),
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ return {
+ **collect(cls._LLM_CALL_ATTRS, data),
+ **collect(cls._BLOB_ATTRS, data),
+ **cls._messages("llm.input_messages", "input.value", data.messages_in),
+ **cls._messages(
+ "llm.output_messages", "output.value", output_messages(data)
+ ),
+ **cls._tools(data),
+ }
+
+ @staticmethod
+ def _messages(
+ prefix: str, value_key: str, messages: Sequence[object]
+ ) -> AttributeMap:
+ """Per-message ``{prefix}.{idx}.message.*`` keys + the ``value_key`` blob."""
+ parsed = [
+ (m.get("role") if isinstance(m, dict) else None, message_content(m))
+ for m in messages
+ ]
+ attrs = drop_none(
+ {
+ key: value
+ for idx, (role, content) in enumerate(parsed)
+ for key, value in (
+ (
+ f"{prefix}.{idx}.message.role",
+ role if isinstance(role, str) else None,
+ ),
+ (f"{prefix}.{idx}.message.content", content),
+ )
+ }
+ )
+ if parsed:
+ attrs[value_key] = json.dumps(
+ [{"role": role, "content": content} for role, content in parsed]
+ )
+ return attrs
+
+ @classmethod
+ def _tools(cls, data: LLMCallSpanData) -> AttributeMap:
+ return drop_none(
+ {
+ f"llm.tools.{idx}.{suffix}": extract(tool)
+ for idx, tool in enumerate(data.tools)
+ for suffix, extract in cls._TOOL_ATTRS.items()
+ }
+ )
diff --git a/litellm/integrations/otel/mappers/utils.py b/litellm/integrations/otel/mappers/utils.py
new file mode 100644
index 00000000000..6228fc8bbe7
--- /dev/null
+++ b/litellm/integrations/otel/mappers/utils.py
@@ -0,0 +1,76 @@
+"""Shared helpers for the attribute mappers.
+
+Small, mapper-agnostic utilities — JSON serialization, message extraction, and
+extractor-table application — pulled out of the individual mapper modules so
+they live in one place.
+"""
+
+import json
+from typing import Callable, Mapping, Sequence
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue
+from litellm.integrations.otel.model.payloads import LLMCallSpanData
+
+
+def drop_none(values: Mapping[str, AttrValue | None]) -> AttributeMap:
+ """Return ``values`` with ``None``-valued entries removed."""
+ return {k: v for k, v in values.items() if v is not None}
+
+
+def collect(table: Mapping[str, Callable], source: object) -> AttributeMap:
+ """Apply an extractor table to ``source``, dropping ``None`` results."""
+ return drop_none({key: extract(source) for key, extract in table.items()})
+
+
+def json_if(payload: Mapping[str, object]) -> str | None:
+ """JSON-serialize ``payload`` only when it's non-empty; else ``None``."""
+ return json.dumps(payload) if payload else None
+
+
+def json_or_none(value: object) -> str | None:
+ """JSON-serialize ``value`` (falling back to ``str``); ``None`` on failure."""
+ try:
+ return json.dumps(value, default=str)
+ except Exception:
+ return None
+
+
+def stringify_message(message: object) -> str | None:
+ """JSON-serialize a chat message dict; ``None`` if not a dict or on failure."""
+ if not isinstance(message, dict):
+ return None
+ try:
+ return json.dumps(message, default=str)
+ except Exception:
+ return None
+
+
+def serialize_messages(messages: Sequence[object]) -> str | None:
+ """Round-trip a sequence of message dicts through ``stringify_message``."""
+ serialized = [
+ json.loads(s) for s in (stringify_message(m) for m in messages) if s is not None
+ ]
+ return json.dumps(serialized) if serialized else None
+
+
+def message_content(message: object) -> str | None:
+ """Extract the textual ``content`` from a chat message dict."""
+ if not isinstance(message, dict):
+ return None
+ content = message.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ # multimodal: concatenate text parts only
+ parts = [
+ part.get("text", "")
+ for part in content
+ if isinstance(part, dict) and part.get("type") == "text"
+ ]
+ return "".join(p for p in parts if isinstance(p, str)) or None
+ return None
+
+
+def output_messages(data: LLMCallSpanData) -> list:
+ """The ``message`` payload of each response choice."""
+ return [c.get("message") for c in data.choices_out if isinstance(c, dict)]
diff --git a/litellm/integrations/otel/mappers/weave.py b/litellm/integrations/otel/mappers/weave.py
new file mode 100644
index 00000000000..54b07299271
--- /dev/null
+++ b/litellm/integrations/otel/mappers/weave.py
@@ -0,0 +1,48 @@
+"""Weave (W&B) attribute mapper.
+
+Weave consumes OpenInference + a small set of Weave-specific keys (display
+name, thread id, output value). This mapper layers the latter on top of
+OpenInference's vocabulary — compose ``["genai", "openinference", "weave"]``
+to feed a Weave backend.
+"""
+
+from typing import Callable
+
+from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
+from litellm.integrations.otel.mappers.utils import collect, json_or_none
+from litellm.integrations.otel.model.payloads import LLMCallSpanData
+
+
+class WeaveMapper:
+ """Maps ``LLMCallSpanData`` to Weave's vendor attributes."""
+
+ _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ # ``display_name`` has the form ``"{operation} {model}"``. The span
+ # name already covers that, but Weave reads this attribute too.
+ "weave.display_name": lambda d: (
+ f"{d.operation.value} {d.request_model}" if d.request_model else None
+ ),
+ "weave.call_id": lambda d: d.identity.call_id or None,
+ }
+
+ # JSON-payload attributes: each builder returns the serialized blob or None.
+ _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
+ # Weave treats the response choices as the "output" payload.
+ "weave.output": lambda d: (
+ json_or_none(list(d.choices_out)) if d.choices_out else None
+ ),
+ }
+
+ def map(self, data: SpanData) -> AttributeMap:
+ match data:
+ case LLMCallSpanData():
+ return self._llm_call(data)
+ case _:
+ return {}
+
+ @classmethod
+ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ return {
+ **collect(cls._LLM_CALL_ATTRS, data),
+ **collect(cls._BLOB_ATTRS, data),
+ }
diff --git a/litellm/integrations/otel/model/__init__.py b/litellm/integrations/otel/model/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/integrations/otel/model/baggage.py b/litellm/integrations/otel/model/baggage.py
new file mode 100644
index 00000000000..67dd64e3914
--- /dev/null
+++ b/litellm/integrations/otel/model/baggage.py
@@ -0,0 +1,76 @@
+"""Baggage promotion: request-identity values carried across child spans.
+
+A bounded set of identity values is written into OpenTelemetry Baggage on the
+LLM-call span so that child spans (guardrail, service) inherit them.
+``providers.LiteLLMBaggageSpanProcessor`` reads Baggage at span start and stamps
+the allowlisted keys onto every span.
+
+This module is the single place baggage is defined: ``_PROMOTABLE`` maps each
+promotable attribute key to how its value is read, and the two ``*_KEYS``
+defaults select what is promoted unless the config overrides them.
+"""
+
+from collections.abc import Callable
+from typing import Final
+
+from litellm.integrations.otel.model.metadata import RequestIdentity
+from litellm.integrations.otel.model.semconv import GenAI, LiteLLM
+
+# Attribute key -> value extractor over (identity, request_model). The single
+# definition of what may be promoted and under which key.
+_PROMOTABLE: Final[dict[str, Callable[[RequestIdentity, str | None], str | None]]] = {
+ LiteLLM.TEAM_ID: lambda identity, model: identity.team_id,
+ LiteLLM.TEAM_ALIAS: lambda identity, model: identity.team_alias,
+ LiteLLM.TEAM_METADATA: lambda identity, model: identity.team_metadata,
+ LiteLLM.KEY_HASH: lambda identity, model: identity.key_hash,
+ LiteLLM.END_USER: lambda identity, model: identity.end_user,
+ GenAI.REQUEST_MODEL: lambda identity, model: model,
+ LiteLLM.PROVIDER_MODEL: lambda identity, model: identity.provider_model,
+}
+
+# Keys promoted by default (a subset of ``_PROMOTABLE``). ``END_USER`` is
+# promotable but off by default — it identifies an individual user, so stamping
+# it onto every span is opt-in via ``config.baggage_promoted_keys``.
+BAGGAGE_PROMOTED_KEYS: Final[tuple[str, ...]] = (
+ LiteLLM.TEAM_ID,
+ LiteLLM.TEAM_ALIAS,
+ LiteLLM.TEAM_METADATA,
+ LiteLLM.KEY_HASH,
+ GenAI.REQUEST_MODEL,
+ LiteLLM.PROVIDER_MODEL,
+)
+
+# Metadata sub-keys eligible for promotion under the ``litellm.metadata.*``
+# namespace. The full metadata blob is never promoted; only this allowlist is.
+DEFAULT_BAGGAGE_METADATA_KEYS: Final[tuple[str, ...]] = (
+ "user_api_key_org_id",
+ "user_api_key_user_id",
+ "user_api_key_alias",
+ "user_api_key_end_user_id",
+ "requester_ip_address",
+)
+
+
+def promoted_baggage(
+ identity: RequestIdentity,
+ request_model: str | None,
+ promoted_keys: tuple[str, ...],
+ metadata_keys: tuple[str, ...] = DEFAULT_BAGGAGE_METADATA_KEYS,
+) -> dict[str, str]:
+ """Identity values to write into Baggage, filtered to ``promoted_keys``.
+
+ ``promoted_keys`` selects from ``_PROMOTABLE``; ``metadata_keys`` selects
+ sub-keys of ``identity.metadata`` to promote under ``litellm.metadata.*``.
+ Empty values are dropped.
+ """
+ out: dict[str, str] = {}
+ for key, extract in _PROMOTABLE.items():
+ if key in promoted_keys:
+ value = extract(identity, request_model)
+ if value:
+ out[key] = value
+ for meta_key in metadata_keys:
+ value = identity.metadata.get(meta_key)
+ if value:
+ out[f"{LiteLLM.METADATA_PREFIX}{meta_key}"] = value
+ return out
diff --git a/litellm/integrations/otel/model/config.py b/litellm/integrations/otel/model/config.py
new file mode 100644
index 00000000000..f78e1515ea1
--- /dev/null
+++ b/litellm/integrations/otel/model/config.py
@@ -0,0 +1,236 @@
+"""Typed configuration for the OpenTelemetry instrumentation."""
+
+from typing import Any, List
+
+from pydantic import AliasChoices, BaseModel, Field, field_validator, model_validator
+from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
+from typing_extensions import Annotated
+
+from litellm.integrations.otel.model.baggage import (
+ BAGGAGE_PROMOTED_KEYS,
+ DEFAULT_BAGGAGE_METADATA_KEYS,
+)
+
+#: Master feature-flag env var. The logger is inert until this is truthy.
+OTEL_V2_ENV = "LITELLM_OTEL_V2"
+
+
+class CaptureMessageContent(str):
+ NO_CONTENT = "no_content"
+ SPAN_ONLY = "span_only"
+ EVENT_ONLY = "event_only"
+ SPAN_AND_EVENT = "span_and_event"
+
+
+class _OTelV2Flag(BaseSettings):
+ model_config = SettingsConfigDict(extra="ignore")
+
+ enabled: bool = Field(default=False, validation_alias=AliasChoices(OTEL_V2_ENV))
+
+
+def is_otel_v2_enabled() -> bool:
+ return _OTelV2Flag().enabled
+
+
+class ExporterSpec(BaseModel):
+ """One span-export destination.
+
+ The shared ``TracerProvider`` attaches one ``SpanProcessor`` per spec, so
+ listing several specs sends every span to all of them at once (e.g. Arize +
+ Phoenix + your own Honeycomb).
+ """
+
+ model_config = {"extra": "forbid"}
+
+ kind: str = Field(
+ default="console",
+ description="console | in_memory | otlp_http | otlp_grpc | <factory kind>",
+ )
+ endpoint: str | None = None
+ headers: str | None = None
+ options: dict[str, str] | None = Field(
+ default=None,
+ description=(
+ "Factory-specific configuration for a custom exporter ``kind`` "
+ "registered via ``providers.register_exporter_factory`` (e.g. an "
+ "API key a lazy-auth exporter fetches a token with). Ignored by the "
+ "built-in console/in_memory/otlp exporters."
+ ),
+ )
+ use_simple_processor: bool | None = Field(
+ default=None,
+ description=(
+ "Force SimpleSpanProcessor regardless of exporter kind. Default: "
+ "auto (Simple for console/in_memory, Batch otherwise)."
+ ),
+ )
+
+
+class OpenTelemetryV2Config(BaseSettings):
+ model_config = SettingsConfigDict(populate_by_name=True, extra="ignore")
+
+ # ----- single-destination shorthand, read from standard OTEL_* envs ----- #
+ exporter: str = Field(
+ default="console",
+ validation_alias=AliasChoices("OTEL_EXPORTER", "OTEL_EXPORTER_OTLP_PROTOCOL"),
+ description=(
+ "Exporter kind for the single-destination shorthand. The model "
+ "validator folds this (with ``endpoint`` / ``headers``) into a "
+ "one-entry ``exporters`` list when ``exporters`` is empty; set "
+ "``exporters`` directly for multiple destinations."
+ ),
+ )
+ endpoint: str | None = Field(
+ default=None,
+ validation_alias=AliasChoices("OTEL_ENDPOINT", "OTEL_EXPORTER_OTLP_ENDPOINT"),
+ )
+ headers: str | None = Field(
+ default=None,
+ validation_alias=AliasChoices("OTEL_HEADERS", "OTEL_EXPORTER_OTLP_HEADERS"),
+ )
+ service_name: str = Field(
+ default="litellm", validation_alias=AliasChoices("OTEL_SERVICE_NAME")
+ )
+ deployment_environment: str | None = Field(
+ default=None, validation_alias=AliasChoices("OTEL_ENVIRONMENT_NAME")
+ )
+
+ enable_metrics: bool = Field(
+ default=False,
+ validation_alias=AliasChoices("LITELLM_OTEL_INTEGRATION_ENABLE_METRICS"),
+ )
+ enable_events: bool = Field(
+ default=False,
+ validation_alias=AliasChoices("LITELLM_OTEL_INTEGRATION_ENABLE_EVENTS"),
+ )
+ capture_message_content: str = Field(
+ default=CaptureMessageContent.NO_CONTENT,
+ validation_alias=AliasChoices(
+ "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
+ ),
+ )
+ legacy_compat: bool = Field(
+ default=True, validation_alias=AliasChoices("LITELLM_OTEL_LEGACY_COMPAT")
+ )
+
+ # ----- explicit multi-destination / vocabulary configuration ------------ #
+
+ exporters: list[ExporterSpec] = Field(
+ default_factory=list,
+ description=(
+ "One destination per spec. The shared TracerProvider attaches a "
+ "SpanProcessor per entry. When empty, the model validator folds "
+ "the ``exporter`` / ``endpoint`` / ``headers`` shorthand into a "
+ "single spec so there is always at least one destination."
+ ),
+ )
+
+ mapper_names: Annotated[List[str], NoDecode] = Field(
+ default_factory=lambda: ["genai"],
+ description=(
+ "Ordered attribute vocabularies to emit. ``genai`` is the "
+ "canonical OTel GenAI vocabulary and is always placed first. "
+ "Vendor names: ``openinference`` (Arize + Phoenix), ``langfuse``, "
+ "``weave``, ``langtrace``."
+ ),
+ )
+
+ resource_attributes: dict[str, str] = Field(
+ default_factory=dict,
+ description=(
+ "Extra Resource attributes beyond ``service.name`` and "
+ "``deployment.environment`` (e.g. integration-specific markers)."
+ ),
+ )
+
+ baggage_promoted_keys: Annotated[List[str], NoDecode] = Field(
+ default_factory=lambda: list(BAGGAGE_PROMOTED_KEYS),
+ validation_alias=AliasChoices(
+ "baggage_promoted_keys", "LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS"
+ ),
+ description=(
+ "Identity attribute keys written into Baggage and stamped on every "
+ "child span (e.g. ``litellm.team.id``). Configure via the "
+ "``LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS`` env var (comma-separated) or "
+ "``callback_settings.otel.baggage_promoted_keys`` in config.yaml (a "
+ "YAML list)."
+ ),
+ )
+ baggage_metadata_keys: Annotated[List[str], NoDecode] = Field(
+ default_factory=lambda: list(DEFAULT_BAGGAGE_METADATA_KEYS),
+ validation_alias=AliasChoices(
+ "baggage_metadata_keys", "LITELLM_OTEL_BAGGAGE_METADATA_KEYS"
+ ),
+ description=(
+ "Metadata sub-keys promoted under the ``litellm.metadata.*`` "
+ "namespace. Configure via the ``LITELLM_OTEL_BAGGAGE_METADATA_KEYS`` "
+ "env var (comma-separated) or "
+ "``callback_settings.otel.baggage_metadata_keys`` in config.yaml."
+ ),
+ )
+
+ @field_validator(
+ "baggage_promoted_keys",
+ "baggage_metadata_keys",
+ "mapper_names",
+ mode="before",
+ )
+ @classmethod
+ def _split_csv(cls, value: Any) -> Any:
+ """Accept a comma-separated string for list fields.
+
+ Env vars are strings, but these fields are lists. Pydantic-settings would
+ otherwise require JSON for a list env var; splitting on commas here lets
+ an operator write ``LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS=litellm.team.id,litellm.api_key.hash``.
+ YAML lists (from ``callback_settings.otel.*``) and real lists pass through
+ unchanged.
+ """
+ if isinstance(value, str):
+ return [item.strip() for item in value.split(",") if item.strip()]
+ return value
+
+ @model_validator(mode="after")
+ def _normalize(self) -> "OpenTelemetryV2Config":
+ # An endpoint with the default exporter kind implies OTLP/HTTP.
+ if self.endpoint and self.exporter == "console":
+ self.exporter = "otlp_http"
+ # When no explicit destinations are given, fold the single-destination
+ # shorthand into one spec so the provider always has a destination.
+ if not self.exporters:
+ self.exporters = [
+ ExporterSpec(
+ kind=self.exporter,
+ endpoint=self.endpoint,
+ headers=self.headers,
+ )
+ ]
+ # Ensure ``genai`` is always present and first.
+ names = list(self.mapper_names)
+ if "genai" in names:
+ names = ["genai"] + [n for n in names if n != "genai"]
+ else:
+ names = ["genai"] + names
+ # When enabled, also emit attribute keys under their semconv-ai /
+ # Traceloop names via the ``legacy`` mapper. Append it at the tail so
+ # the canonical ``genai`` keys win on any conflict.
+ if self.legacy_compat and "legacy" not in names:
+ names.append("legacy")
+ self.mapper_names = names
+ return self
+
+ @property
+ def capture_span_content(self) -> bool:
+ """Whether prompt/response content may be stamped as span attributes.
+
+ Defaults off (``no_content``): an operator must opt in before message
+ bodies leave the process, so a user request can never force its prompt
+ or completion into the configured backend while capture is disabled.
+ """
+ return self.capture_message_content in (
+ CaptureMessageContent.SPAN_ONLY,
+ CaptureMessageContent.SPAN_AND_EVENT,
+ )
+
+ @classmethod
+ def from_env(cls) -> "OpenTelemetryV2Config":
+ return cls()
diff --git a/litellm/integrations/otel/model/metadata.py b/litellm/integrations/otel/model/metadata.py
new file mode 100644
index 00000000000..f0ea0a608c6
--- /dev/null
+++ b/litellm/integrations/otel/model/metadata.py
@@ -0,0 +1,315 @@
+"""The single translation layer between a request's metadata and the spans.
+
+Every relevant field litellm exposes about a request — the user-facing model,
+the model actually dispatched to the provider, the deployment, and the caller's
+identity (team, key, end-user) — is parsed **once**, here, out of the
+``StandardLoggingPayload`` (or a ``UserAPIKeyAuth`` at the auth boundary). Span
+data, baggage promotion, and the mappers then read these typed fields instead of
+each digging into the raw ``metadata`` / ``hidden_params`` dicts.
+
+Two models live here because a request's identity is known *before* its model
+resolution is:
+
+* :class:`RequestIdentity` — team / key / end-user, seeded into Baggage at the
+ auth boundary (``from_user_api_key_auth``), before routing has picked a
+ deployment. ``provider_model`` is therefore absent from that early seed and is
+ only filled in from the payload once the call closes.
+* :class:`RequestContext` — the full picture available at close: the resolved
+ request vs. provider model split, plus the response model, model group, model
+ id, and api base, wrapping the :class:`RequestIdentity`.
+
+The request-vs-provider model split is the subtle part. On the proxy a caller
+asks for a *model group* (e.g. ``gpt-4o``) that routes to a concrete deployment
+(e.g. ``azure/my-deployment``); the two are distinct and both worth recording.
+``StandardLoggingPayload`` exposes them as:
+
+* ``model_group`` — the user-facing name the caller requested.
+* ``model`` — already reconstructed (see ``reconstruct_model_name``) to the name
+ litellm dispatched to the provider (the deployment, provider-prefixed).
+* ``hidden_params.litellm_model_name`` — a secondary source for the dispatched
+ model (populated only on some call paths, e.g. files).
+
+So ``gen_ai.request.model`` is the *group* (falling back to the call model on the
+SDK path, which has no group), and ``litellm.provider.model`` is the *dispatched*
+model. They coincide on the SDK path, which is correct.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Mapping, cast
+
+from litellm.constants import LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL
+from litellm.integrations.otel.model.semconv import resolve_operation
+from litellm.integrations.otel.model.utils import as_str
+
+if TYPE_CHECKING:
+ from litellm.types.utils import StandardLoggingPayload
+
+
+@dataclass(frozen=True)
+class RequestIdentity:
+ call_id: str | None = None
+ team_id: str | None = None
+ team_alias: str | None = None
+ # The team's free-form metadata dict, JSON-serialized (empty/missing -> None).
+ team_metadata: str | None = None
+ key_hash: str | None = None
+ end_user: str | None = None
+ # The model litellm dispatched to the provider. Only known once the call
+ # completes (routing has picked a deployment), so it's absent from the
+ # auth-time seed and filled only from the payload.
+ provider_model: str | None = None
+ metadata: Mapping[str, str] = field(default_factory=dict)
+
+ @classmethod
+ def from_payload(cls, payload: "StandardLoggingPayload") -> "RequestIdentity":
+ """Parse caller identity out of a closed request's payload metadata.
+
+ ``provider_model`` is resolved here too (see :func:`resolve_provider_model`)
+ so the identity carried into Baggage labels every span with the dispatched
+ model, not just the user-facing one.
+ """
+ raw_meta = cast(Mapping[str, object], payload.get("metadata") or {})
+ metadata = {
+ key: str(value)
+ for key, value in raw_meta.items()
+ if isinstance(value, (str, bool, int, float))
+ }
+ return cls(
+ call_id=as_str(payload.get("litellm_call_id")) or as_str(payload.get("id")),
+ # StandardLoggingMetadata's canonical key is ``user_api_key_team_id``;
+ # the bare ``team_id`` is a legacy alias and is often empty, so prefer
+ # the canonical key and fall back to the alias.
+ team_id=as_str(raw_meta.get("user_api_key_team_id"))
+ or as_str(raw_meta.get("team_id")),
+ team_alias=as_str(raw_meta.get("user_api_key_team_alias"))
+ or as_str(raw_meta.get("team_alias")),
+ team_metadata=_team_metadata_json(
+ raw_meta.get("user_api_key_team_metadata")
+ ),
+ key_hash=as_str(raw_meta.get("user_api_key_hash")),
+ end_user=as_str(payload.get("end_user"))
+ or as_str(raw_meta.get("user_api_key_end_user_id")),
+ provider_model=resolve_provider_model(payload),
+ metadata=metadata,
+ )
+
+ @classmethod
+ def from_user_api_key_auth(cls, auth: object) -> "RequestIdentity":
+ """Identity from a ``UserAPIKeyAuth`` (duck-typed to keep this module
+ free of a proxy import).
+
+ Used in the pre-call hook to seed Baggage early — before any LLM,
+ guardrail, or service span is created — so the whole request's spans
+ inherit identity, not just the LLM-call span. Metadata sub-keys use the
+ ``user_api_key_*`` names that ``baggage.DEFAULT_BAGGAGE_METADATA_KEYS``
+ promotes.
+ """
+ get = lambda name: getattr(auth, name, None) # noqa: E731
+ metadata = {
+ meta_key: str(value)
+ for meta_key, attr in (
+ ("user_api_key_user_id", "user_id"),
+ ("user_api_key_org_id", "org_id"),
+ ("user_api_key_alias", "key_alias"),
+ ("user_api_key_end_user_id", "end_user_id"),
+ )
+ if (value := get(attr))
+ }
+ return cls(
+ team_id=as_str(get("team_id")),
+ team_alias=as_str(get("team_alias")),
+ team_metadata=_team_metadata_json(get("team_metadata")),
+ key_hash=as_str(get("api_key")),
+ end_user=as_str(get("end_user_id")),
+ # ``provider_model`` is unknown at the auth boundary — routing hasn't
+ # picked a deployment yet — so it's only populated from the payload.
+ metadata=metadata,
+ )
+
+
+@dataclass(frozen=True)
+class RequestContext:
+ """The fully-resolved view of a closed request, parsed once from the payload.
+
+ ``request_model`` is the user-facing requested model and ``provider_model``
+ (on :attr:`identity`) is the model litellm dispatched to the provider; the two
+ differ on the proxy (group vs. deployment) and coincide on the SDK path.
+ """
+
+ request_model: str
+ response_model: str | None
+ model_group: str | None
+ model_id: str | None
+ api_base: str | None
+ identity: RequestIdentity
+
+ @property
+ def provider_model(self) -> str | None:
+ """The dispatched-model name, carried on the identity for Baggage."""
+ return self.identity.provider_model
+
+ @classmethod
+ def from_standard_logging_payload(
+ cls, payload: "StandardLoggingPayload"
+ ) -> "RequestContext":
+ raw_meta = cast(Mapping[str, object], payload.get("metadata") or {})
+ hidden = cast(Mapping[str, object], payload.get("hidden_params") or {})
+ raw_response = payload.get("response")
+ response = cast(
+ Mapping[str, object], raw_response if isinstance(raw_response, dict) else {}
+ )
+ model_group = as_str(payload.get("model_group")) or as_str(
+ raw_meta.get("model_group")
+ )
+ return cls(
+ # The user asked for the group; fall back to the call model on the SDK
+ # path, which has no group. Empty string (never None) so the span name
+ # builder and the mapper see a plain string.
+ request_model=model_group or as_str(payload.get("model")) or "",
+ response_model=as_str(response.get("model")),
+ model_group=model_group,
+ model_id=as_str(payload.get("model_id"))
+ or _model_info_id(raw_meta.get("model_info")),
+ api_base=as_str(payload.get("api_base")) or as_str(hidden.get("api_base")),
+ identity=RequestIdentity.from_payload(payload),
+ )
+
+
+# --- live-callback kwargs parsing ------------------------------------------- #
+#
+# The model and helpers below parse the *live* callback ``kwargs`` god object (and
+# the raw pre/post-call ``data`` dicts) — the untyped request state that reaches a
+# ``CustomLogger`` before, or instead of, a ``StandardLoggingPayload``. They live
+# here, with the payload/auth parsers, so every read out of a request's raw dicts
+# is in one place rather than scattered across the ``CustomLogger``.
+
+
+@dataclass(frozen=True)
+class LLMCallEvent:
+ """The typed view of the live callback ``kwargs`` (``model_call_details``).
+
+ litellm hands every callback an untyped ``kwargs`` god object. The fields the
+ OTel logger needs out of it are parsed **once**, here, so the ``CustomLogger``
+ reads typed attributes instead of digging into the dict at each boundary.
+ """
+
+ # The ``litellm_call_id`` correlating ``pre_call`` with the close callback.
+ # Present in ``model_call_details`` at ``pre_call`` and in both the kwargs and
+ # the ``standard_logging_object`` at success/failure, so it's a stable key for
+ # the open-call carrier — no back-reference to the logging object required (the
+ # object isn't reachable from the callback kwargs at ``pre_call`` time).
+ call_id: str | None
+ # The ``StandardLoggingPayload`` carried on a success/failure callback; ``None``
+ # at ``pre_call``, or when the call closed before any payload materialized (so
+ # there is nothing to stamp on the span).
+ payload: "StandardLoggingPayload | None"
+ # The ``standard_callback_dynamic_params`` routing the call to a per-tenant
+ # tracer (its own exporter/endpoint), or ``None`` when the call isn't scoped.
+ dynamic_params: Any
+ # True for synthetic proxy-gate logs (auth / rate-limit rejections): they fire
+ # the ``pre_call`` hook but never made an upstream call, so they get no span.
+ is_no_upstream_call: bool
+ # A best-effort ``"{operation} {model}"`` name known at ``pre_call`` time. The
+ # span is renamed from the typed payload at close (``finish_span``); this only
+ # needs to be reasonable for a span that never gets closed (a leak).
+ provisional_span_name: str
+
+ @classmethod
+ def from_dict(cls, kwargs: Mapping[str, Any]) -> "LLMCallEvent":
+ raw_payload = kwargs.get("standard_logging_object")
+ payload = cast("StandardLoggingPayload", raw_payload) if raw_payload else None
+ operation = resolve_operation(as_str(kwargs.get("call_type")))
+ model = as_str(kwargs.get("model")) or ""
+ return cls(
+ call_id=_call_id(payload, kwargs),
+ payload=payload,
+ dynamic_params=kwargs.get("standard_callback_dynamic_params"),
+ is_no_upstream_call=bool(kwargs.get(LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL)),
+ provisional_span_name=f"{operation.value} {model}".strip(),
+ )
+
+
+def _call_id(
+ payload: "StandardLoggingPayload | None", kwargs: Mapping[str, Any]
+) -> str | None:
+ """The call id from the payload (when closed) or the bare kwargs (at pre_call)."""
+ if payload is not None:
+ call_id = as_str(payload.get("litellm_call_id")) or as_str(payload.get("id"))
+ if call_id:
+ return call_id
+ return as_str(kwargs.get("litellm_call_id"))
+
+
+def model_from_request_data(data: object) -> str | None:
+ """The user-facing ``model`` from a pre-call ``data`` dict (``None`` if absent).
+
+ Read at the auth boundary to label early Baggage before routing has resolved
+ a deployment; ``data`` is duck-typed since it arrives untyped from the proxy.
+ """
+ if isinstance(data, Mapping):
+ return as_str(data.get("model"))
+ return None
+
+
+def guardrail_entries_from_request_data(
+ request_data: Mapping[str, Any],
+) -> list[dict]:
+ """The guardrail-information dicts buried in ``metadata`` of a post-call dict.
+
+ ``standard_logging_guardrail_information`` is stored as either a single dict
+ or a list of them; normalize to a list of dicts (dropping non-dict noise) so
+ the caller just iterates. Empty list when none are present.
+ """
+ metadata = request_data.get("metadata")
+ if not isinstance(metadata, Mapping):
+ return []
+ info = metadata.get("standard_logging_guardrail_information")
+ if isinstance(info, Mapping):
+ return [cast(dict, info)]
+ if isinstance(info, list):
+ return [entry for entry in info if isinstance(entry, dict)]
+ return []
+
+
+def resolve_provider_model(payload: "StandardLoggingPayload") -> str | None:
+ """The model litellm dispatched to the provider, from the payload.
+
+ Prefers the explicit ``hidden_params.litellm_model_name`` (set on call paths
+ that know it, e.g. files), then the top-level ``model`` — which
+ ``reconstruct_model_name`` has already resolved to the deployment's
+ provider-prefixed name. Returns ``None`` only when neither is present.
+ """
+ raw_meta = cast(Mapping[str, object], payload.get("metadata") or {})
+ hidden = cast(Mapping[str, object], payload.get("hidden_params") or {})
+ return (
+ # ``deployment`` survives only on paths that don't strip it from metadata;
+ # harmless (and most precise) to prefer it when present.
+ as_str(raw_meta.get("deployment"))
+ or as_str(hidden.get("litellm_model_name"))
+ or as_str(payload.get("model"))
+ )
+
+
+def _model_info_id(model_info: object) -> str | None:
+ """The deployment id from a ``metadata.model_info`` sub-dict, if present."""
+ if isinstance(model_info, Mapping):
+ return as_str(model_info.get("id"))
+ return None
+
+
+def _team_metadata_json(value: object) -> str | None:
+ """JSON-serialize a team's metadata dict for a single Baggage value.
+
+ Returns ``None`` for a missing, non-dict, or empty mapping so the empty case
+ is dropped rather than promoting a useless ``"{}"``. Keys are sorted for a
+ stable, diff-friendly serialization.
+ """
+ if not isinstance(value, Mapping) or not value:
+ return None
+ try:
+ return json.dumps(value, default=str, sort_keys=True)
+ except Exception:
+ return None
diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.py
new file mode 100644
index 00000000000..65b50d0fc12
--- /dev/null
+++ b/litellm/integrations/otel/model/payloads.py
@@ -0,0 +1,468 @@
+"""Typed span-data inputs: frozen dataclasses the engine and mappers consume."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import TYPE_CHECKING, ClassVar, Mapping, cast
+from urllib.parse import urlsplit
+
+from litellm.integrations.otel.model.metadata import (
+ RequestContext,
+ RequestIdentity,
+)
+from litellm.integrations.otel.model.semconv import (
+ GenAIOperation,
+ resolve_operation,
+ resolve_provider,
+)
+from litellm.integrations.otel.model.utils import (
+ as_bool,
+ as_float,
+ as_int,
+ as_str,
+ as_str_tuple,
+)
+
+# ``RequestIdentity`` and the request-metadata translation now live in
+# :mod:`metadata`; re-exported here so existing ``model.payloads`` imports keep
+# resolving it.
+__all__ = [
+ "RequestContext",
+ "RequestIdentity",
+ "GuardrailSpanData",
+ "LLMCallSpanData",
+ "LLMRequestParams",
+ "LLMUsage",
+ "ProxyRequestSpanData",
+ "ServerInfo",
+ "ServiceSpanData",
+ "SpanError",
+ "ToolDefinition",
+]
+
+if TYPE_CHECKING:
+ from litellm.types.services import ServiceLoggerPayload
+ from litellm.types.utils import (
+ StandardLoggingGuardrailInformation,
+ StandardLoggingPayload,
+ )
+
+
+# --- typed sub-structures ---------------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class LLMRequestParams:
+ temperature: float | None = None
+ top_p: float | None = None
+ top_k: int | None = None
+ max_tokens: int | None = None
+ frequency_penalty: float | None = None
+ presence_penalty: float | None = None
+ stop_sequences: tuple[str, ...] | None = None
+ seed: int | None = None
+
+ @classmethod
+ def from_model_parameters(cls, params: Mapping[str, object]) -> "LLMRequestParams":
+ max_tokens = as_int(params.get("max_tokens"))
+ if max_tokens is None:
+ max_tokens = as_int(params.get("max_completion_tokens"))
+ return cls(
+ temperature=as_float(params.get("temperature")),
+ top_p=as_float(params.get("top_p")),
+ top_k=as_int(params.get("top_k")),
+ max_tokens=max_tokens,
+ frequency_penalty=as_float(params.get("frequency_penalty")),
+ presence_penalty=as_float(params.get("presence_penalty")),
+ stop_sequences=as_str_tuple(params.get("stop")),
+ seed=as_int(params.get("seed")),
+ )
+
+
+@dataclass(frozen=True)
+class LLMUsage:
+ input_tokens: int | None = None
+ output_tokens: int | None = None
+ total_tokens: int | None = None
+
+
+@dataclass(frozen=True)
+class SpanError:
+ error_type: str | None = None
+ message: str | None = None
+
+
+@dataclass(frozen=True)
+class ServerInfo:
+ address: str | None = None
+ port: int | None = None
+
+ @classmethod
+ def from_api_base(cls, api_base: str | None) -> ServerInfo | None:
+ if not api_base:
+ return None
+ parsed = urlsplit(api_base if "://" in api_base else f"//{api_base}")
+ if not parsed.hostname:
+ return None
+ return cls(address=parsed.hostname, port=parsed.port)
+
+
+@dataclass(frozen=True)
+class GuardrailSpanData:
+ guardrail_name: str
+ mode: str | None = None
+ status: str | None = None
+ masked_entity_count: int | None = None
+ provider: str | None = None
+ action: str | None = None
+ # The guardrail verdict / provider response (e.g. the moderation result),
+ # JSON-serialized. This is the detail that belongs on the guardrail span.
+ response_json: str | None = None
+ violation_categories: tuple[str, ...] = ()
+ confidence_score: float | None = None
+ risk_score: float | None = None
+ duration: float | None = None
+ # Actual execution window (epoch seconds) from the logging entry, so the span
+ # is placed when the guardrail really ran — a pre_call guardrail before the
+ # LLM call — rather than at post-call emission time.
+ start_time: float | None = None
+ end_time: float | None = None
+ # Provider-agnostic configuration/detection metadata (see
+ # ``StandardLoggingGuardrailInformation``). Present for any guardrail that
+ # populates them, not just one provider's shape.
+ guardrail_id: str | None = None
+ policy_template: str | None = None
+ detection_method: str | None = None
+ # Set when the guardrail intervened/blocked or failed, so the emitter marks
+ # the span ERROR — a blocking guardrail is an error outcome for that span.
+ error: SpanError | None = None
+
+ # Guardrail statuses that mean the guardrail did not pass the request through.
+ _ERROR_STATUSES: ClassVar[frozenset[str]] = frozenset(
+ {"guardrail_intervened", "guardrail_failed_to_respond"}
+ )
+
+ @classmethod
+ def from_logging_entry(
+ cls, entry: "StandardLoggingGuardrailInformation"
+ ) -> "GuardrailSpanData":
+ """Build from one ``standard_logging_guardrail_information`` entry.
+
+ Reads the canonical, provider-agnostic ``StandardLoggingGuardrailInformation``
+ keys only — no guessing at a single provider's field names. Values that are
+ typed as enums or lists (e.g. ``guardrail_mode``) are normalized to a
+ stable string rather than assumed to already be plain strings.
+ """
+ get = cast(Mapping[str, object], entry).get
+ status = as_str(get("guardrail_status"))
+ response = get("guardrail_response")
+ error = (
+ SpanError(error_type=status, message=as_str(get("guardrail_action")))
+ if status in cls._ERROR_STATUSES
+ else None
+ )
+ return cls(
+ guardrail_name=as_str(get("guardrail_name")) or "guardrail",
+ mode=_guardrail_mode_str(get("guardrail_mode")),
+ status=status,
+ masked_entity_count=_total_masked_entities(get("masked_entity_count")),
+ provider=as_str(get("guardrail_provider")),
+ action=as_str(get("guardrail_action")),
+ response_json=_json_or_none(response) if response is not None else None,
+ violation_categories=as_str_tuple(get("violation_categories")) or (),
+ confidence_score=as_float(get("confidence_score")),
+ risk_score=as_float(get("risk_score")),
+ duration=as_float(get("duration")),
+ start_time=as_float(get("start_time")),
+ end_time=as_float(get("end_time")),
+ guardrail_id=as_str(get("guardrail_id")),
+ policy_template=as_str(get("policy_template")),
+ detection_method=as_str(get("detection_method")),
+ error=error,
+ )
+
+
+@dataclass(frozen=True)
+class ServiceSpanData:
+ service_name: str
+ call_type: str | None = None
+ error: SpanError | None = None
+ # Caller-supplied attributes to stamp on the service span, passed through
+ # from ``async_service_*_hook(event_metadata=...)``. The mapper owns how
+ # these are namespaced: the canonical vocabulary uses ``litellm.metadata.*``
+ # keys, the semconv-ai / Traceloop vocabulary uses the bare key names.
+ event_metadata: Mapping[str, str] = field(default_factory=dict)
+
+ @classmethod
+ def from_payload(
+ cls,
+ payload: "ServiceLoggerPayload",
+ event_metadata: Mapping[str, object] | None = None,
+ ) -> "ServiceSpanData":
+ # ``payload.service`` is a ``ServiceTypes(str, Enum)`` and ``error`` is
+ # ``Optional[str]`` on the Pydantic model — no defensive reads needed.
+ # ``event_metadata`` is sanitized: the legacy service decorators pass raw
+ # call-site data (live objects, full request metadata, response headers),
+ # none of which belongs on a span.
+ return cls(
+ service_name=payload.service.value,
+ call_type=payload.call_type,
+ error=SpanError(message=payload.error) if payload.error else None,
+ event_metadata=sanitize_event_metadata(event_metadata),
+ )
+
+
+@dataclass(frozen=True)
+class ProxyRequestSpanData:
+ http_method: str
+ route: str
+ url_path: str | None = None
+ status_code: int | None = None
+ identity: RequestIdentity | None = None
+
+
+# --- the primary LLM-call model ---------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class ToolDefinition:
+ """A single function/tool declared on a chat-completion request."""
+
+ name: str
+ description: str | None = None
+ parameters_json: str | None = (
+ None # JSON-serialized schema (str so it's an AttrValue)
+ )
+
+
+@dataclass(frozen=True)
+class LLMCallSpanData:
+ operation: GenAIOperation
+ provider: str
+ request_model: str
+ response_model: str | None
+ response_id: str | None
+ request_params: LLMRequestParams
+ usage: LLMUsage
+ finish_reasons: tuple[str, ...]
+ error: SpanError | None
+ response_cost: float | None
+ server: ServerInfo | None
+ identity: RequestIdentity
+ is_streaming: bool | None = None
+ tools: tuple[ToolDefinition, ...] = ()
+ # Raw messages and response, needed by vendor mappers (OpenInference,
+ # Langfuse, Weave) that stamp message-level attributes. ``messages_in`` is
+ # the request payload; ``choices_out`` mirrors ``response.choices`` from
+ # the StandardLoggingPayload. Both are tuples of immutable mappings so the
+ # dataclass stays hashable and frozen.
+ messages_in: tuple[Mapping[str, object], ...] = ()
+ choices_out: tuple[Mapping[str, object], ...] = ()
+ system_fingerprint: str | None = None
+
+ @classmethod
+ def from_standard_logging_payload(
+ cls, payload: "StandardLoggingPayload", capture_content: bool = False
+ ) -> "LLMCallSpanData":
+ params = cast(Mapping[str, object], payload.get("model_parameters") or {})
+ # The single parse of the request's metadata — the request-vs-provider
+ # model split, the response model, api base, and identity all come from
+ # here rather than being re-derived from the raw payload dicts.
+ context = RequestContext.from_standard_logging_payload(payload)
+ # Normalize ``response`` to a dict once so the content/id reads below are a
+ # plain ``.get`` — no repeated ``isinstance`` guards.
+ raw_response = payload.get("response")
+ response = cast(
+ Mapping[str, object], raw_response if isinstance(raw_response, dict) else {}
+ )
+ choices_out = _dicts(response.get("choices"))
+ # ``finish_reasons`` is metadata, not content, so derive it from
+ # ``choices_out`` before gating. The raw message/choice bodies are only
+ # retained when content capture is enabled (see ``capture_span_content``);
+ # otherwise the content-bearing mappers receive empty sequences and emit
+ # no prompt/response text.
+ finish_reasons = _finish_reasons(choices_out)
+ return cls(
+ operation=resolve_operation(as_str(payload.get("call_type"))),
+ provider=resolve_provider(as_str(payload.get("custom_llm_provider"))),
+ request_model=context.request_model,
+ response_model=context.response_model,
+ response_id=as_str(response.get("id")),
+ request_params=LLMRequestParams.from_model_parameters(params),
+ usage=LLMUsage(
+ input_tokens=as_int(payload.get("prompt_tokens")),
+ output_tokens=as_int(payload.get("completion_tokens")),
+ total_tokens=as_int(payload.get("total_tokens")),
+ ),
+ finish_reasons=finish_reasons,
+ error=_parse_error(payload),
+ response_cost=as_float(payload.get("response_cost")),
+ server=ServerInfo.from_api_base(context.api_base),
+ identity=context.identity,
+ is_streaming=as_bool(payload.get("stream")),
+ tools=_extract_tools(params),
+ messages_in=_dicts(payload.get("messages")) if capture_content else (),
+ choices_out=choices_out if capture_content else (),
+ system_fingerprint=as_str(response.get("system_fingerprint")),
+ )
+
+
+# --- service event_metadata sanitization ------------------------------------ #
+
+# Substrings (case-insensitive) of keys that must never reach a span: secrets,
+# tokens, and raw request/response dumps the legacy service decorators pass.
+_SENSITIVE_METADATA_SUBSTRINGS: tuple[str, ...] = (
+ "api_key",
+ "token",
+ "secret",
+ "password",
+ "cookie",
+ "authorization",
+ "header",
+ "hidden_params",
+)
+# Keys that carry raw call-site internals — live objects, full kwargs/args. The
+# operation name is already the span's ``call_type``, so ``function_name`` is
+# redundant.
+_DROP_METADATA_KEYS: frozenset = frozenset(
+ {"function_kwargs", "function_args", "function_name"}
+)
+_MAX_METADATA_VALUE_LEN = 1024
+_MAX_METADATA_ITEMS = 32
+
+
+def sanitize_event_metadata(
+ event_metadata: Mapping[str, object] | None,
+) -> dict[str, str]:
+ """Reduce caller-supplied ``event_metadata`` to span-safe string attributes.
+
+ Keeps only primitive values (str/int/float/bool) under non-sensitive keys —
+ never ``repr()``-ing objects, dicts, or lists, never stamping secrets/headers,
+ and bounding the count and per-value length. This is the single chokepoint:
+ both the GenAI and legacy mappers read the cleaned result.
+ """
+ if not event_metadata:
+ return {}
+ clean: dict[str, str] = {}
+ for key, value in event_metadata.items():
+ if len(clean) >= _MAX_METADATA_ITEMS:
+ break
+ if not isinstance(key, str) or key in _DROP_METADATA_KEYS:
+ continue
+ lowered = key.lower()
+ if any(token in lowered for token in _SENSITIVE_METADATA_SUBSTRINGS):
+ continue
+ # ``bool`` is a subclass of ``int``, so it's covered. Non-primitive values
+ # (objects, dicts, lists) are dropped rather than stringified.
+ if isinstance(value, (str, int, float)):
+ clean[key] = str(value)[:_MAX_METADATA_VALUE_LEN]
+ return clean
+
+
+def _json_or_none(value: object) -> str | None:
+ """JSON-serialize ``value`` (already-string values pass through). ``None`` on failure."""
+ if isinstance(value, str):
+ return value
+ try:
+ return json.dumps(value, default=str)
+ except Exception:
+ return None
+
+
+def _guardrail_mode_str(value: object) -> str | None:
+ """Normalize ``guardrail_mode`` to a stable string.
+
+ ``guardrail_mode`` is typed as a ``GuardrailEventHooks`` enum, a list of them,
+ or a ``GuardrailMode`` — not a plain string. Emit the enum *value* (e.g.
+ ``"pre_call"``) rather than ``str(enum)`` (``"GuardrailEventHooks.pre_call"``),
+ and join a list of modes so a guardrail that runs at multiple hooks is
+ represented faithfully.
+ """
+ if value is None:
+ return None
+ if isinstance(value, (list, tuple)):
+ parts: list[str] = []
+ for item in value:
+ if item is None:
+ continue
+ part = as_str(item.value) if isinstance(item, Enum) else as_str(item)
+ if part:
+ parts.append(part)
+ return ",".join(parts) or None
+ if isinstance(value, Enum):
+ return as_str(value.value)
+ return as_str(value)
+
+
+def _total_masked_entities(value: object) -> int | None:
+ """``masked_entity_count`` is a ``{entity_type: count}`` map — sum to a total."""
+ if isinstance(value, Mapping):
+ total = sum(v for v in value.values() if isinstance(v, int))
+ return total or None
+ return as_int(value)
+
+
+def _dicts(value: object) -> tuple[Mapping[str, object], ...]:
+ """The dict items of ``value`` (when it's a list), as a tuple. Else empty."""
+ if not isinstance(value, list):
+ return ()
+ return tuple(item for item in value if isinstance(item, dict))
+
+
+def _finish_reasons(choices: tuple[Mapping[str, object], ...]) -> tuple[str, ...]:
+ """Non-empty ``finish_reason`` of each response choice."""
+ return tuple(r for c in choices if (r := as_str(c.get("finish_reason"))))
+
+
+def _parse_error(payload: "StandardLoggingPayload") -> SpanError | None:
+ """A ``SpanError`` for a failed request, or ``None`` on success."""
+ if payload.get("status") != "failure":
+ return None
+ info = cast(Mapping[str, object], payload.get("error_information") or {})
+ return SpanError(
+ error_type=as_str(info.get("error_class")) or as_str(info.get("error_code")),
+ message=as_str(info.get("error_message")) or as_str(payload.get("error_str")),
+ )
+
+
+def _tool_from_entry(entry: object) -> ToolDefinition | None:
+ """One ``tools``/``functions`` entry → ``ToolDefinition``, or ``None`` if unusable."""
+ if not isinstance(entry, dict):
+ return None
+ fn = entry.get("function") if "function" in entry else entry
+ if not isinstance(fn, dict):
+ return None
+ name = as_str(fn.get("name"))
+ if not name:
+ return None
+ params = fn.get("parameters")
+ parameters_json: str | None = None
+ if params is not None:
+ try:
+ parameters_json = json.dumps(params, default=str)
+ except Exception:
+ parameters_json = None
+ return ToolDefinition(
+ name=name,
+ description=as_str(fn.get("description")),
+ parameters_json=parameters_json,
+ )
+
+
+def _extract_tools(
+ model_parameters: Mapping[str, object],
+) -> tuple[ToolDefinition, ...]:
+ """Pull declared tools from request params (OpenAI / Anthropic shape).
+
+ Accepts the chat-completion ``tools=[{"type":"function", "function":
+ {...}}, ...]`` shape, and falls back to the ``functions=[...]`` shape.
+ Returns an empty tuple when neither is present.
+ """
+ raw_tools = model_parameters.get("tools")
+ if not isinstance(raw_tools, list):
+ raw_tools = model_parameters.get("functions") # ``functions`` shape
+ if not isinstance(raw_tools, list):
+ return ()
+ return tuple(t for entry in raw_tools if (t := _tool_from_entry(entry)) is not None)
diff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.py
new file mode 100644
index 00000000000..1c6c30eda0d
--- /dev/null
+++ b/litellm/integrations/otel/model/semconv.py
@@ -0,0 +1,201 @@
+"""
+Keys follow the OpenTelemetry GenAI semantic conventions (experimental). Anything
+without a semconv equivalent lives under the ``litellm.*`` vendor namespace.
+"""
+
+from enum import Enum
+from typing import Final
+
+
+class GenAIOperation(str, Enum):
+ """Values for ``gen_ai.operation.name``."""
+
+ CHAT = "chat"
+ TEXT_COMPLETION = "text_completion"
+ EMBEDDINGS = "embeddings"
+ GENERATE_CONTENT = "generate_content"
+ CREATE_AGENT = "create_agent" # reserved for future agent spans
+ INVOKE_AGENT = "invoke_agent" # reserved for future agent spans
+ EXECUTE_TOOL = "execute_tool" # reserved for future tool spans
+
+
+class GenAIProvider(str, Enum):
+ """Common values for the ``gen_ai.provider.name`` attribute."""
+
+ OPENAI = "openai"
+ ANTHROPIC = "anthropic"
+ AWS_BEDROCK = "aws.bedrock"
+ AZURE_AI_OPENAI = "azure.ai.openai"
+ AZURE_AI_INFERENCE = "azure.ai.inference"
+ GCP_GEMINI = "gcp.gemini"
+ GCP_VERTEX_AI = "gcp.vertex_ai"
+ COHERE = "cohere"
+ MISTRAL_AI = "mistral_ai"
+ DEEPSEEK = "deepseek"
+ GROQ = "groq"
+ PERPLEXITY = "perplexity"
+ X_AI = "x_ai"
+ IBM_WATSONX_AI = "ibm.watsonx.ai"
+
+
+class GenAI:
+ """Canonical OTel GenAI span-attribute keys."""
+
+ # request
+ OPERATION_NAME: Final = "gen_ai.operation.name"
+ PROVIDER_NAME: Final = "gen_ai.provider.name"
+ REQUEST_MODEL: Final = "gen_ai.request.model"
+ REQUEST_TEMPERATURE: Final = "gen_ai.request.temperature"
+ REQUEST_TOP_P: Final = "gen_ai.request.top_p"
+ REQUEST_TOP_K: Final = "gen_ai.request.top_k"
+ REQUEST_MAX_TOKENS: Final = "gen_ai.request.max_tokens"
+ REQUEST_FREQUENCY_PENALTY: Final = "gen_ai.request.frequency_penalty"
+ REQUEST_PRESENCE_PENALTY: Final = "gen_ai.request.presence_penalty"
+ REQUEST_STOP_SEQUENCES: Final = "gen_ai.request.stop_sequences"
+ REQUEST_SEED: Final = "gen_ai.request.seed"
+ REQUEST_CHOICE_COUNT: Final = "gen_ai.request.choice.count"
+ REQUEST_ENCODING_FORMATS: Final = "gen_ai.request.encoding_formats"
+ # response
+ RESPONSE_ID: Final = "gen_ai.response.id"
+ RESPONSE_MODEL: Final = "gen_ai.response.model"
+ RESPONSE_FINISH_REASONS: Final = "gen_ai.response.finish_reasons"
+ # usage
+ USAGE_INPUT_TOKENS: Final = "gen_ai.usage.input_tokens"
+ USAGE_OUTPUT_TOKENS: Final = "gen_ai.usage.output_tokens"
+ # content (opt-in, gated by capture mode)
+ INPUT_MESSAGES: Final = "gen_ai.input.messages"
+ OUTPUT_MESSAGES: Final = "gen_ai.output.messages"
+ SYSTEM_INSTRUCTIONS: Final = "gen_ai.system_instructions"
+ OUTPUT_TYPE: Final = "gen_ai.output.type"
+ CONVERSATION_ID: Final = "gen_ai.conversation.id"
+ # agent / tool (reserved)
+ AGENT_ID: Final = "gen_ai.agent.id"
+ AGENT_NAME: Final = "gen_ai.agent.name"
+ TOOL_NAME: Final = "gen_ai.tool.name"
+ TOOL_CALL_ID: Final = "gen_ai.tool.call.id"
+
+
+class Error:
+ TYPE: Final = "error.type"
+
+
+class Server:
+ ADDRESS: Final = "server.address"
+ PORT: Final = "server.port"
+
+
+class DB:
+ """Database / cache client-span keys (OTel ``db.*`` semconv).
+
+ Stamped on ``DB_CALL`` spans (redis / postgres), which are CLIENT spans for
+ outbound datastore calls — not on the INTERNAL ``SERVICE`` spans.
+ """
+
+ SYSTEM_NAME: Final = "db.system.name"
+ OPERATION_NAME: Final = "db.operation.name"
+
+
+class HTTP:
+ """HTTP server-span keys. Belong on the SERVER span only (never promoted)."""
+
+ REQUEST_METHOD: Final = "http.request.method"
+ ROUTE: Final = "http.route"
+ RESPONSE_STATUS_CODE: Final = "http.response.status_code"
+ URL_PATH: Final = "url.path"
+
+
+class LiteLLM:
+ """Vendor-extension keys (no semconv equivalent). Always ``litellm.*``."""
+
+ CALL_ID: Final = "litellm.call_id"
+ COST_PREFIX: Final = "litellm.cost."
+ METADATA_PREFIX: Final = "litellm.metadata."
+ TEAM_ID: Final = "litellm.team.id"
+ TEAM_ALIAS: Final = "litellm.team.alias"
+ # The team's free-form metadata dict, JSON-serialized into a single value.
+ TEAM_METADATA: Final = "litellm.team.metadata"
+ KEY_HASH: Final = "litellm.api_key.hash"
+ END_USER: Final = "litellm.end_user.id"
+ # The model string litellm actually sent to the provider (the deployment's
+ # ``litellm_params.model``), distinct from the user-facing ``gen_ai.request.model``.
+ PROVIDER_MODEL: Final = "litellm.provider.model"
+ REQUEST_STREAMING: Final = "litellm.request.streaming"
+ GUARDRAIL_NAME: Final = "litellm.guardrail.name"
+ GUARDRAIL_MODE: Final = "litellm.guardrail.mode"
+ GUARDRAIL_STATUS: Final = "litellm.guardrail.status"
+ GUARDRAIL_PROVIDER: Final = "litellm.guardrail.provider"
+ GUARDRAIL_ACTION: Final = "litellm.guardrail.action"
+ GUARDRAIL_RESPONSE: Final = "litellm.guardrail.response"
+ GUARDRAIL_VIOLATION_CATEGORIES: Final = "litellm.guardrail.violation_categories"
+ GUARDRAIL_CONFIDENCE_SCORE: Final = "litellm.guardrail.confidence_score"
+ GUARDRAIL_RISK_SCORE: Final = "litellm.guardrail.risk_score"
+ GUARDRAIL_MASKED_ENTITY_COUNT: Final = "litellm.guardrail.masked_entity_count"
+ GUARDRAIL_DURATION: Final = "litellm.guardrail.duration"
+ GUARDRAIL_ID: Final = "litellm.guardrail.id"
+ GUARDRAIL_POLICY_TEMPLATE: Final = "litellm.guardrail.policy_template"
+ GUARDRAIL_DETECTION_METHOD: Final = "litellm.guardrail.detection_method"
+ SERVICE_NAME: Final = "litellm.service.name"
+ SERVICE_CALL_TYPE: Final = "litellm.service.call_type"
+ PREPROCESSING_MS: Final = "litellm.preprocessing.duration_ms"
+
+
+class Metric:
+ """GenAI metric instrument names."""
+
+ TOKEN_USAGE: Final = "gen_ai.client.token.usage"
+ OPERATION_DURATION: Final = "gen_ai.client.operation.duration"
+
+
+# litellm ``custom_llm_provider`` -> ``gen_ai.provider.name`` value.
+_PROVIDER_BY_LITELLM: dict[str, GenAIProvider] = {
+ "openai": GenAIProvider.OPENAI,
+ "text-completion-openai": GenAIProvider.OPENAI,
+ "azure": GenAIProvider.AZURE_AI_OPENAI,
+ "azure_ai": GenAIProvider.AZURE_AI_INFERENCE,
+ "anthropic": GenAIProvider.ANTHROPIC,
+ "bedrock": GenAIProvider.AWS_BEDROCK,
+ "bedrock_converse": GenAIProvider.AWS_BEDROCK,
+ "vertex_ai": GenAIProvider.GCP_VERTEX_AI,
+ "vertex_ai_beta": GenAIProvider.GCP_VERTEX_AI,
+ "gemini": GenAIProvider.GCP_GEMINI,
+ "cohere": GenAIProvider.COHERE,
+ "cohere_chat": GenAIProvider.COHERE,
+ "mistral": GenAIProvider.MISTRAL_AI,
+ "deepseek": GenAIProvider.DEEPSEEK,
+ "groq": GenAIProvider.GROQ,
+ "perplexity": GenAIProvider.PERPLEXITY,
+ "xai": GenAIProvider.X_AI,
+ "watsonx": GenAIProvider.IBM_WATSONX_AI,
+}
+
+# litellm ``call_type`` -> ``gen_ai.operation.name``.
+_OPERATION_BY_CALL_TYPE: dict[str, GenAIOperation] = {
+ "completion": GenAIOperation.CHAT,
+ "acompletion": GenAIOperation.CHAT,
+ "completion_with_retries": GenAIOperation.CHAT,
+ "text_completion": GenAIOperation.TEXT_COMPLETION,
+ "atext_completion": GenAIOperation.TEXT_COMPLETION,
+ "embedding": GenAIOperation.EMBEDDINGS,
+ "aembedding": GenAIOperation.EMBEDDINGS,
+ "responses": GenAIOperation.CHAT,
+ "aresponses": GenAIOperation.CHAT,
+}
+
+
+def resolve_provider(custom_llm_provider: str | None) -> str:
+ """Map a litellm provider string to a ``gen_ai.provider.name`` value.
+
+ Unknown providers pass through verbatim — the convention explicitly allows
+ provider-specific values, so an unmapped name is still valid.
+ """
+ if not custom_llm_provider:
+ return ""
+ mapped = _PROVIDER_BY_LITELLM.get(custom_llm_provider.lower())
+ return mapped.value if mapped is not None else custom_llm_provider
+
+
+def resolve_operation(call_type: str | None) -> GenAIOperation:
+ """Map a litellm ``call_type`` to a ``gen_ai.operation.name`` value."""
+ if not call_type:
+ return GenAIOperation.CHAT
+ return _OPERATION_BY_CALL_TYPE.get(call_type.lower(), GenAIOperation.CHAT)
diff --git a/litellm/integrations/otel/model/spans.py b/litellm/integrations/otel/model/spans.py
new file mode 100644
index 00000000000..e4876f4ee58
--- /dev/null
+++ b/litellm/integrations/otel/model/spans.py
@@ -0,0 +1,203 @@
+"""
+This module declares every span the instrumentation can emit and the hierarchy.
+
+Span-name patterns live here as typed builder functions.
+
+Canonical hierarchy::
+
+ PROXY_REQUEST (SERVER, root) # owned by the FastAPI instrumentor
+ ├── SERVICE (INTERNAL) # auth phase span (live; see logger.phase_span)
+ │ └── DB_CALL (CLIENT) # its key/user/team lookups nest here
+ ├── GUARDRAIL (INTERNAL) # request-lifecycle hook, sibling of LLM_CALL
+ ├── LLM_CALL (CLIENT)
+ └── DB_CALL (CLIENT) # e.g. the spend-log write
+
+Guardrails parent to PROXY_REQUEST, not LLM_CALL: pre/during/post-call guardrail
+hooks are orchestrated by the request lifecycle (a pre-call guardrail runs
+before the LLM call even starts), so a guardrail is a sibling of the LLM call,
+not a child of it. The emitter parents every span to the ambient OTel context
+(the active server span), which matches this.
+
+Not every service call becomes a span — :func:`span_role_for_service` decides:
+
+- ``DB_CALL`` (CLIENT) — outbound datastores (redis, postgres,
+ ``batch_write_to_db``), carrying ``db.*`` semconv.
+- ``SERVICE`` (INTERNAL) — genuine internal work worth a span (background
+ budget/reset jobs, pod-lock manager).
+- ``None`` (metrics-only) — framework instrumentation that duplicates a gen-AI
+ span (``self`` = the ``track_llm_api_timing`` wrapper, ``router``,
+ ``proxy_pre_call``) or ``auth`` (which gets a live phase span instead). These
+ still feed Prometheus/Datadog; they just never enter the trace.
+
+``DB_CALL`` and ``SERVICE`` are built from the same ``ServiceSpanData``; only the
+role (hence span kind and attribute vocabulary) differs. A service call can fire
+outside any request (a background job), in which case it parents to no server
+span and starts its own root trace rather than being dropped.
+
+Management/admin endpoints are ordinary FastAPI routes — their SERVER spans are
+owned by the instrumentor too, so they don't appear as a role here.
+"""
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from litellm.integrations.otel.model.payloads import (
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ProxyRequestSpanData,
+ ServiceSpanData,
+ )
+
+
+class SpanRole(str, Enum):
+ PROXY_REQUEST = "proxy_request"
+ LLM_CALL = "llm_call"
+ GUARDRAIL = "guardrail"
+ DB_CALL = "db_call"
+ SERVICE = "service"
+
+
+class LiteLLMSpanKind(str, Enum):
+ SERVER = "server"
+ CLIENT = "client"
+ INTERNAL = "internal"
+ PRODUCER = "producer"
+ CONSUMER = "consumer"
+
+
+@dataclass(frozen=True)
+class SpanSpec:
+ role: SpanRole
+ kind: LiteLLMSpanKind
+ parent: SpanRole | None
+
+
+SPAN_REGISTRY: dict[SpanRole, SpanSpec] = {
+ SpanRole.PROXY_REQUEST: SpanSpec(
+ SpanRole.PROXY_REQUEST, LiteLLMSpanKind.SERVER, parent=None
+ ),
+ SpanRole.LLM_CALL: SpanSpec(
+ SpanRole.LLM_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST
+ ),
+ SpanRole.GUARDRAIL: SpanSpec(
+ SpanRole.GUARDRAIL, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST
+ ),
+ SpanRole.DB_CALL: SpanSpec(
+ SpanRole.DB_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST
+ ),
+ SpanRole.SERVICE: SpanSpec(
+ SpanRole.SERVICE, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST
+ ),
+}
+
+
+# ``ServiceTypes`` value -> ``db.system.name``. These are outbound datastore
+# calls and become CLIENT ``DB_CALL`` spans; ``redis_``-prefixed names cover the
+# redis-backed spend queues. Any service not mapped here is litellm-internal work
+# and stays an INTERNAL ``SERVICE`` span. This table is the single source of
+# datastore knowledge — both the role classifier and the mapper read it.
+_DB_SYSTEM_BY_SERVICE: dict[str, str] = {
+ "redis": "redis",
+ "postgres": "postgresql",
+ "batch_write_to_db": "postgresql",
+}
+
+
+def db_system(service_name: str) -> str | None:
+ """The ``db.system.name`` for a datastore service, else ``None``.
+
+ ``None`` means the service is not an outbound datastore call. Redis-backed
+ spend queues (``redis_*``) map to ``redis``.
+ """
+ if service_name in _DB_SYSTEM_BY_SERVICE:
+ return _DB_SYSTEM_BY_SERVICE[service_name]
+ if service_name.startswith("redis_"):
+ return "redis"
+ return None
+
+
+# ``ServiceTypes`` values that are NOT emitted as spans — they are framework
+# instrumentation that either duplicates a gen-AI span or has a better home as a
+# Prometheus/Datadog metric. They still flow to those metric backends via their
+# own hooks; the v2 logger just does not put them in the trace:
+#
+# - ``self`` — ``track_llm_api_timing`` wraps the LLM call; the
+# ``chat {model}`` CLIENT span already represents it.
+# - ``router`` — wraps the whole request; duplicates the server span.
+# - ``proxy_pre_call`` — per-callback pre-call timing; a guardrail's real span
+# is ``execute_guardrail {name}``.
+# - ``auth`` — emitted instead as a live phase span (see
+# ``logger.phase_span``) so its DB lookups nest under it,
+# not as a flat post-hoc service span.
+_METRICS_ONLY_SERVICES: frozenset[str] = frozenset(
+ {"self", "router", "proxy_pre_call", "auth"}
+)
+
+
+def span_role_for_service(service_name: str) -> SpanRole | None:
+ """The span role for a service call, or ``None`` when it must not be a span.
+
+ ``DB_CALL`` for outbound datastores, ``SERVICE`` for genuine internal work
+ worth a span (background jobs), and ``None`` for framework instrumentation
+ that duplicates a gen-AI span or belongs in metrics only
+ (see ``_METRICS_ONLY_SERVICES``).
+ """
+ if service_name in _METRICS_ONLY_SERVICES:
+ return None
+ return SpanRole.DB_CALL if db_system(service_name) is not None else SpanRole.SERVICE
+
+
+# --- span name builders (the naming convention, per role) ------------------- #
+
+
+# The name the FastAPI instrumentor gives the root server span. V2 never creates
+# this span (the instrumentor owns it), but it anchors request-level spans to it
+# and tests assert against it by name, so the literal lives here with the rest of
+# the span vocabulary rather than being duplicated at each call site.
+LITELLM_PROXY_REQUEST_SPAN_NAME = "Received Proxy Server Request"
+
+
+def llm_call_span_name(data: "LLMCallSpanData") -> str:
+ """``"{operation} {model}"`` e.g. ``"chat gpt-4o"`` (GenAI semconv)."""
+ model = data.request_model or ""
+ return f"{data.operation.value} {model}".strip()
+
+
+def proxy_request_span_name(data: "ProxyRequestSpanData") -> str:
+ """``"{method} {route}"`` (HTTP semconv)."""
+ return f"{data.http_method} {data.route}".strip()
+
+
+def guardrail_span_name(data: "GuardrailSpanData") -> str:
+ return f"execute_guardrail {data.guardrail_name}".strip()
+
+
+def service_span_name(data: "ServiceSpanData") -> str:
+ """``"{service} {call_type}"`` e.g. ``"redis set"`` — service name alone when
+ no call type is known, so identically-named calls stay distinguishable."""
+ return f"{data.service_name} {data.call_type or ''}".strip()
+
+
+def root_roles() -> list[SpanRole]:
+ """Roles that start a new trace (no in-process parent)."""
+ return [role for role, spec in SPAN_REGISTRY.items() if spec.parent is None]
+
+
+def child_roles(parent: SpanRole) -> list[SpanRole]:
+ return [role for role, spec in SPAN_REGISTRY.items() if spec.parent == parent]
+
+
+def validate_registry(
+ registry: dict[SpanRole, SpanSpec] | None = None,
+) -> None:
+ reg = registry if registry is not None else SPAN_REGISTRY
+ for role, spec in reg.items():
+ if spec.role is not role:
+ raise ValueError(f"SPAN_REGISTRY[{role}] has mismatched role {spec.role}")
+ if spec.parent is not None and spec.parent not in reg:
+ raise ValueError(f"span role {role} declares unknown parent {spec.parent}")
+ missing = [role for role in SpanRole if role not in reg]
+ if missing:
+ raise ValueError(f"SPAN_REGISTRY is missing roles: {missing}")
diff --git a/litellm/integrations/otel/model/utils.py b/litellm/integrations/otel/model/utils.py
new file mode 100644
index 00000000000..f37afc97879
--- /dev/null
+++ b/litellm/integrations/otel/model/utils.py
@@ -0,0 +1,103 @@
+"""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.
+"""
+
+from datetime import datetime
+
+
+def as_str(value: object) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ return str(value)
+
+
+def as_int(value: object) -> int | None:
+ if isinstance(value, bool):
+ return int(value)
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ return None
+ return None
+
+
+def as_float(value: object) -> float | None:
+ if isinstance(value, bool):
+ return float(value)
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value)
+ except ValueError:
+ return None
+ return None
+
+
+def as_bool(value: object) -> bool | None:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return value
+ return bool(value)
+
+
+def as_str_tuple(value: object) -> tuple[str, ...] | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return (value,)
+ if isinstance(value, (list, tuple)):
+ return tuple(str(v) for v in value)
+ return None
+
+
+def to_ns(value: datetime | float | int | None) -> int | None:
+ """Coerce a datetime / epoch value to integer nanoseconds."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return int(value.timestamp() * 1e9)
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return int(float(value) * 1e9)
+ return None
+
+
+def to_seconds(value: datetime | float | int | str | None) -> float | None:
+ """Coerce a datetime / epoch / formatted-string value to epoch seconds."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.timestamp()
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, str):
+ for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
+ try:
+ return datetime.strptime(value, fmt).timestamp()
+ 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/mount.py b/litellm/integrations/otel/mount.py
new file mode 100644
index 00000000000..ebcf4aa35af
--- /dev/null
+++ b/litellm/integrations/otel/mount.py
@@ -0,0 +1,130 @@
+"""FastAPI server-span instrumentation — the proxy mounts this at app creation.
+
+``opentelemetry-instrumentation-fastapi`` creates the SERVER span for each HTTP
+route and extracts inbound ``traceparent`` headers. This module owns the one call
+site that attaches it to the proxy app, plus the passthrough span-naming hook, so
+``proxy_server`` stays free of OTel details.
+
+The ``FastAPIInstrumentor`` import is kept lazy (inside :func:`instrument_fastapi_app`,
+after the gate check) so importing this module never requires the optional
+``opentelemetry-instrumentation-fastapi`` package and pulls in nothing OTel-related
+when the feature gate is off.
+"""
+
+import os
+from typing import Any
+
+from litellm._logging import verbose_logger
+from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+# Routes excluded from server-span tracing by default: high-frequency pollers and
+# static UI/docs assets, none of which are LLM traffic. Entries are substring-matched
+# against the request path (unanchored, so they survive a ``server_root_path`` prefix
+# and each entry also covers everything beneath it — e.g. ``/health`` covers
+# ``/health/readiness``). Operators override the whole set via the standard
+# ``OTEL_PYTHON_FASTAPI_EXCLUDED_URLS`` env var (set "" to trace everything).
+_DEFAULT_EXCLUDED_ROUTES = (
+ "/health", # load-balancer liveness/readiness polling
+ "/metrics", # Prometheus scrape (also drops the /model/metrics admin analytics)
+ "/litellm-asset-prefix", # hashed UI asset bundles
+ "/_next", # Next.js static JS/CSS chunks (root-level mount)
+ "/ui", # admin UI single-page app
+ "/swagger", # static Swagger UI assets
+ "/docs", # FastAPI Swagger docs page
+ "/redoc", # FastAPI ReDoc docs page
+ "/openapi.json", # OpenAPI schema
+ "favicon", # /favicon.ico + /get_favicon
+ "/.well-known", # UI config discovery
+)
+_DEFAULT_EXCLUDED_URLS = ",".join(_DEFAULT_EXCLUDED_ROUTES)
+
+# Passthrough routes are catch-alls (e.g. "/openai/{endpoint:path}"), so the
+# default OTel server-span name "{method} {route}" collapses every upstream
+# endpoint into "POST /openai/{endpoint:path}". The hook below renames those spans
+# to the real request path so each endpoint is distinguishable. Non-catch-all
+# routes keep their low-cardinality template name.
+PASSTHROUGH_PREFIXES = frozenset(
+ {
+ "openai",
+ "openai_passthrough",
+ "anthropic",
+ "azure",
+ "azure_ai",
+ "bedrock",
+ "cohere",
+ "cursor",
+ "gemini",
+ "mistral",
+ "vllm",
+ "vertex_ai",
+ "vertex-ai",
+ "assemblyai",
+ "eu.assemblyai",
+ "milvus",
+ }
+)
+
+
+def _passthrough_span_name_hook(span: Any, scope: dict) -> None:
+ """FastAPI ``server_request_hook``: give passthrough server spans a useful name.
+
+ The instrumentation matches the route at span creation, so both the span name
+ and ``http.route`` are set to the catch-all template (``/openai/{endpoint:path}``)
+ before this hook runs. Rewrite both to the real request path so each upstream
+ endpoint is distinguishable. (The ASGI ``http receive``/``http send`` sub-spans
+ can't be renamed from here — their name is captured at creation — so they are
+ dropped via ``exclude_spans`` at instrumentation time.)
+ """
+ try:
+ if span is None or not span.is_recording():
+ return
+ path = scope.get("path") or ""
+ method = scope.get("method") or ""
+ first_segment = path.lstrip("/").split("/", 1)[0]
+ if first_segment in PASSTHROUGH_PREFIXES:
+ span.update_name(f"{method} {path}".strip())
+ span.set_attribute("http.route", path)
+ except Exception:
+ pass
+
+
+def instrument_fastapi_app(app: Any) -> None:
+ """Attach OTel server-span instrumentation to the proxy FastAPI app.
+
+ Safe no-op when the V2 gate is off or ``opentelemetry-instrumentation-fastapi``
+ is unavailable. This MUST be called at app-creation time — once the lifespan
+ runs, the middleware stack is frozen and ``instrument_app`` raises "Cannot add
+ middleware after an application has started".
+
+ No ``TracerProvider`` is passed, so the instrumentation binds to the OTel global
+ ``ProxyTracerProvider``; the proxy publishes the real provider as the global
+ after config load (see ``proxy_startup_event``), and the proxy delegates to it.
+ That way server spans and gen-ai spans share one provider and the same trace.
+ """
+ try:
+ if not is_otel_v2_enabled():
+ return
+
+ # Lazy: only the V2-enabled path needs the optional
+ # ``opentelemetry-instrumentation-fastapi`` package, which is not part of the
+ # base ``litellm[proxy]`` install. Importing it at module top would make
+ # ``proxy_server``'s unconditional ``import`` of this module crash when the
+ # package is absent, even with the gate off.
+ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
+
+ excluded_urls = (
+ os.environ.get("OTEL_PYTHON_FASTAPI_EXCLUDED_URLS")
+ if "OTEL_PYTHON_FASTAPI_EXCLUDED_URLS" in os.environ
+ else _DEFAULT_EXCLUDED_URLS
+ )
+ FastAPIInstrumentor.instrument_app(
+ app,
+ excluded_urls=excluded_urls,
+ server_request_hook=_passthrough_span_name_hook,
+ # Drop the ASGI "http receive"/"http send" lifecycle sub-spans: they
+ # are low-value noise and (for passthrough) carry the catch-all route
+ # template in their name, which can't be rewritten from a hook.
+ exclude_spans=["receive", "send"],
+ )
+ except Exception as e:
+ verbose_logger.debug("Skipping OTel V2 FastAPI instrumentation: %s", e)
diff --git a/litellm/integrations/otel/plumbing/__init__.py b/litellm/integrations/otel/plumbing/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/integrations/otel/plumbing/context.py b/litellm/integrations/otel/plumbing/context.py
new file mode 100644
index 00000000000..64790da814b
--- /dev/null
+++ b/litellm/integrations/otel/plumbing/context.py
@@ -0,0 +1,127 @@
+"""Trace-context + Baggage helpers."""
+
+from contextvars import ContextVar
+from typing import Mapping
+
+from opentelemetry import baggage
+from opentelemetry.context import Context, get_current
+from opentelemetry.trace import Span, get_current_span, set_span_in_context
+from opentelemetry.trace.propagation.tracecontext import (
+ TraceContextTextMapPropagator,
+)
+
+_PROPAGATOR = TraceContextTextMapPropagator()
+
+# The request's root span — the FastAPI-owned SERVER span — captured ONCE when the
+# proxy first resolves it, so request-level spans (the LLM call, guardrails) can
+# parent to it EXPLICITLY instead of to whatever span happens to be active at the
+# instant they are emitted. Ambient-only parenting (``get_current_span()``) is
+# wrong at two boundaries:
+# * inside the ``auth`` phase span the active span is the auth span, so an LLM /
+# guardrail span emitted there would nest under auth instead of being its
+# sibling; and
+# * in a detached success task (pass-through logs success from a fire-and-forget
+# ``asyncio.create_task``) the server span may not be active at all, orphaning
+# the span into a brand-new trace.
+# A ``ContextVar`` (not a request attribute) so it rides the request task's context
+# and is inherited by ``asyncio.create_task`` children — i.e. the async logging
+# callbacks that close the span. It is never reset: the contextvar dies with the
+# request task, so there is nothing to leak.
+_request_root_span: "ContextVar[Span | None]" = ContextVar(
+ "litellm_otel_request_root_span", default=None
+)
+
+
+def set_request_root_span(span: Span) -> None:
+ """Anchor the request's root (server) span for explicit child parenting.
+
+ No-ops for a non-recordable span so a bad capture can never replace a good one
+ with a phantom parent. Idempotent — the proxy captures the same server span at
+ more than one entry point.
+ """
+ if is_recordable_span(span):
+ _request_root_span.set(span)
+
+
+def request_root_span() -> "Span | None":
+ """The anchored request root span, or ``None`` outside a proxy request."""
+ span = _request_root_span.get()
+ return span if is_recordable_span(span) else None
+
+
+def set_request_baggage(
+ values: Mapping[str, str], context: Context | None = None
+) -> Context:
+ """Return a context with ``values`` written into Baggage."""
+ ctx = context
+ for key, value in values.items():
+ ctx = baggage.set_baggage(key, value, context=ctx)
+ return ctx if ctx is not None else (context or get_current())
+
+
+def get_baggage_attributes(context: Context | None = None) -> dict[str, str]:
+ """All Baggage entries on ``context`` as strings."""
+ return {key: str(value) for key, value in baggage.get_all(context).items()}
+
+
+def context_from_span(span: Span, context: Context | None = None) -> Context:
+ """A context with ``span`` as the active span (for explicit parenting)."""
+ return set_span_in_context(span, context=context)
+
+
+def resolve_parent_context(threaded: Span | None = None) -> Context:
+ """The context a child span should parent under.
+
+ Ambient-first: parent to the active OTel context (the server span, restored
+ by the logging worker or active in the request task), falling back to a span
+ passed explicitly (``threaded``) only when the ambient context has no
+ recordable span — e.g. a background service call with no request on the
+ stack. When neither is recordable the ambient context is returned unchanged,
+ so the span starts a new root trace.
+
+ Only service/DB spans pass ``threaded`` (the ``parent_otel_span`` handed to
+ the service hook). Request-level spans — the LLM call and guardrails — are
+ created where the server span is genuinely ambient, so they never need it.
+ """
+ ctx = get_current()
+ if is_recordable_span(threaded) and not is_recordable_span(get_current_span(ctx)):
+ ctx = context_from_span(threaded, context=ctx) # type: ignore[arg-type]
+ return ctx
+
+
+def resolve_request_span_context() -> Context:
+ """The parent context for a request-level span (the LLM call, a guardrail).
+
+ These are direct children of the request's root server span — siblings of the
+ ``auth`` phase span and of each other, never nested under whatever span is
+ momentarily active. So prefer the explicitly anchored root span; fall back to
+ ambient context only when there is no anchor (the SDK / no-proxy path), where
+ the span legitimately starts its own root trace.
+
+ Unlike :func:`resolve_parent_context` (used by DB/service spans, which DO want
+ to nest under the active phase span, e.g. an auth DB lookup under ``auth``),
+ this never returns the active span when an anchor exists.
+ """
+ root = request_root_span()
+ if root is not None:
+ return context_from_span(root)
+ return get_current()
+
+
+def is_recordable_span(obj: object) -> bool:
+ """True if ``obj`` is a live span with a valid context (safe to parent under)."""
+ if not isinstance(obj, Span):
+ return False
+ try:
+ ctx = obj.get_span_context()
+ except Exception:
+ return False
+ return ctx is not None and ctx.is_valid
+
+
+def extract_traceparent(headers: Mapping[str, str]) -> Context | None:
+ """Extract a remote parent context from incoming HTTP headers, if present."""
+ if not any(key.lower() == "traceparent" for key in headers):
+ return None
+ carrier = {str(key).lower(): value for key, value in headers.items()}
+ return _PROPAGATOR.extract(carrier)
diff --git a/litellm/integrations/otel/plumbing/metrics.py b/litellm/integrations/otel/plumbing/metrics.py
new file mode 100644
index 00000000000..edd120f91e6
--- /dev/null
+++ b/litellm/integrations/otel/plumbing/metrics.py
@@ -0,0 +1,28 @@
+"""GenAI client metrics (token usage + operation duration histograms)."""
+
+from dataclasses import dataclass
+
+from opentelemetry.metrics import Histogram, Meter
+
+from litellm.integrations.otel.model.semconv import Metric
+
+
+@dataclass(frozen=True)
+class GenAIMetrics:
+ token_usage: Histogram
+ operation_duration: Histogram
+
+
+def create_genai_metrics(meter: Meter) -> GenAIMetrics:
+ return GenAIMetrics(
+ token_usage=meter.create_histogram(
+ name=Metric.TOKEN_USAGE,
+ unit="{token}",
+ description="Number of tokens used per GenAI request.",
+ ),
+ operation_duration=meter.create_histogram(
+ name=Metric.OPERATION_DURATION,
+ unit="s",
+ description="GenAI operation duration.",
+ ),
+ )
diff --git a/litellm/integrations/otel/plumbing/providers.py b/litellm/integrations/otel/plumbing/providers.py
new file mode 100644
index 00000000000..40a0e41b905
--- /dev/null
+++ b/litellm/integrations/otel/plumbing/providers.py
@@ -0,0 +1,220 @@
+"""Provider / exporter factory + the Baggage span processor."""
+
+from typing import Callable, Iterable
+
+from opentelemetry import baggage
+from opentelemetry.context import Context
+from opentelemetry.sdk.resources import Resource
+from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
+from opentelemetry.sdk.trace.export import (
+ BatchSpanProcessor,
+ ConsoleSpanExporter,
+ SimpleSpanProcessor,
+ SpanExporter,
+)
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
+ InMemorySpanExporter,
+)
+from opentelemetry.trace import Span, SpanKind, Tracer
+
+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
+
+_SPAN_KIND_BY_ROLE_KIND: dict[LiteLLMSpanKind, SpanKind] = {
+ LiteLLMSpanKind.SERVER: SpanKind.SERVER,
+ LiteLLMSpanKind.CLIENT: SpanKind.CLIENT,
+ LiteLLMSpanKind.INTERNAL: SpanKind.INTERNAL,
+ LiteLLMSpanKind.PRODUCER: SpanKind.PRODUCER,
+ LiteLLMSpanKind.CONSUMER: SpanKind.CONSUMER,
+}
+
+
+def to_otel_span_kind(kind: LiteLLMSpanKind) -> SpanKind:
+ return _SPAN_KIND_BY_ROLE_KIND[kind]
+
+
+# Custom exporter factories keyed by ``ExporterSpec.kind``. A preset registers
+# one here when its destination needs construction logic the built-in kinds
+# can't express — e.g. an exporter that fetches an auth token lazily on its
+# first export (off the event loop) instead of blocking at config-build time.
+# Keeping the registry here lets this module stay vendor-agnostic: the factory
+# lives with the integration that needs it.
+_EXPORTER_FACTORIES: dict[str, Callable[[ExporterSpec], SpanExporter]] = {}
+
+
+def register_exporter_factory(
+ kind: str, factory: Callable[[ExporterSpec], SpanExporter]
+) -> None:
+ """Register a custom exporter ``factory`` for the exporter ``kind``."""
+ _EXPORTER_FACTORIES[kind.lower()] = factory
+
+
+class LiteLLMBaggageSpanProcessor(SpanProcessor):
+ """Stamps an allowlisted set of Baggage entries onto every span at start."""
+
+ def __init__(
+ self,
+ allowed_keys: Iterable[str],
+ allowed_prefixes: tuple[str, ...] = (LiteLLM.METADATA_PREFIX,),
+ ) -> None:
+ self._allowed_keys = frozenset(allowed_keys)
+ self._allowed_prefixes = tuple(allowed_prefixes)
+
+ def _is_allowed(self, key: str) -> bool:
+ return key in self._allowed_keys or any(
+ key.startswith(prefix) for prefix in self._allowed_prefixes
+ )
+
+ def on_start(self, span: Span, parent_context: Context | None = None) -> None:
+ for key, value in baggage.get_all(parent_context).items():
+ if self._is_allowed(key) and isinstance(value, (str, bool, int, float)):
+ span.set_attribute(key, value)
+
+ def on_end(self, span: ReadableSpan) -> None: # noqa: D401 - no-op
+ return None
+
+ def shutdown(self) -> None:
+ return None
+
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
+ return True
+
+
+def _otlp_traces_endpoint(endpoint: str | None) -> str | None:
+ """Point an OTLP/HTTP base endpoint at the ``/v1/traces`` signal path.
+
+ ``OTEL_EXPORTER_OTLP_ENDPOINT`` is a base URL (e.g. ``http://host:4318``).
+ The OTLP/HTTP exporter only appends the ``/v1/traces`` path when it reads
+ that env var itself; when an endpoint is passed explicitly it is used
+ verbatim, so a base URL would POST to the root and the collector returns
+ 404. Append the signal path here (leaving an already-correct path intact).
+ """
+ if not endpoint:
+ return endpoint
+ endpoint = endpoint.rstrip("/")
+ # Splunk Observability uses ``/v2/trace/otlp``; never rewrite it.
+ if endpoint.endswith("/v1/traces") or "/v2/trace/otlp" in endpoint:
+ return endpoint
+ for other_signal in ("/v1/logs", "/v1/metrics"):
+ if endpoint.endswith(other_signal):
+ return endpoint[: -len(other_signal)] + "/v1/traces"
+ return endpoint + "/v1/traces"
+
+
+def _exporter_from_spec(spec: ExporterSpec) -> SpanExporter:
+ kind = (spec.kind or "console").lower()
+ factory = _EXPORTER_FACTORIES.get(kind)
+ if factory is not None:
+ return factory(spec)
+ if kind in ("in_memory", "inmemory", "memory"):
+ return InMemorySpanExporter()
+ if kind in ("otlp_http", "http", "http/protobuf", "http/json"):
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
+ OTLPSpanExporter as HTTPExporter,
+ )
+
+ return HTTPExporter(
+ endpoint=_otlp_traces_endpoint(spec.endpoint),
+ headers=parse_headers(spec.headers),
+ )
+ if kind in ("otlp_grpc", "grpc"):
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
+ OTLPSpanExporter as GRPCExporter,
+ )
+
+ return GRPCExporter(endpoint=spec.endpoint, headers=parse_headers(spec.headers))
+ return ConsoleSpanExporter()
+
+
+def _processor_for(exporter: SpanExporter, use_simple: bool | None) -> SpanProcessor:
+ """Pick a Simple or Batch span processor for ``exporter``.
+
+ When ``use_simple`` is unset, default to Simple for console and in-memory
+ exporters (spans export synchronously, which tests rely on) and Batch for
+ everything else (the right export semantics for production).
+ """
+ if use_simple is None:
+ use_simple = isinstance(exporter, (ConsoleSpanExporter, InMemorySpanExporter))
+ return SimpleSpanProcessor(exporter) if use_simple else BatchSpanProcessor(exporter)
+
+
+def build_span_exporter(config: OpenTelemetryV2Config) -> SpanExporter:
+ """Build a single exporter from the top-level config fields.
+
+ Convenience for the common single-exporter case (and for tests): reads the
+ ``exporter`` / ``endpoint`` / ``headers`` fields. To configure multiple
+ exporters, populate ``config.exporters`` directly.
+ """
+ return _exporter_from_spec(
+ ExporterSpec(
+ kind=config.exporter, endpoint=config.endpoint, headers=config.headers
+ )
+ )
+
+
+def build_resource(config: OpenTelemetryV2Config) -> Resource:
+ attributes: dict[str, str] = {"service.name": config.service_name}
+ if config.deployment_environment:
+ attributes["deployment.environment"] = config.deployment_environment
+ attributes.update(config.resource_attributes)
+ return Resource.create(attributes)
+
+
+def build_tracer_provider(
+ config: OpenTelemetryV2Config,
+ exporter: SpanExporter | None = None,
+ baggage_processor: SpanProcessor | None = None,
+ use_simple_processor: bool | None = None,
+) -> TracerProvider:
+ """Build the shared :class:`TracerProvider`.
+
+ Attach the Baggage processor first (so identity attributes land on each
+ span before any export decision), then add one ``SpanProcessor`` per
+ ``config.exporters`` entry — this is what fans spans out to multiple
+ backends. ``exporter`` and ``use_simple_processor`` are explicit overrides:
+ pass a single exporter to attach exactly that one (used by tests).
+ """
+ provider = TracerProvider(resource=build_resource(config))
+ if baggage_processor is None:
+ baggage_processor = LiteLLMBaggageSpanProcessor(
+ allowed_keys=config.baggage_promoted_keys
+ )
+ provider.add_span_processor(baggage_processor)
+
+ if exporter is not None:
+ provider.add_span_processor(_processor_for(exporter, use_simple_processor))
+ return provider
+
+ # ``config._normalize`` guarantees at least one spec (it folds the top-level
+ # ``exporter``/``endpoint``/``headers`` fields in when ``exporters`` is empty).
+ for spec in config.exporters:
+ exp = _exporter_from_spec(spec)
+ provider.add_span_processor(
+ _processor_for(
+ exp,
+ (
+ spec.use_simple_processor
+ if spec.use_simple_processor is not None
+ else use_simple_processor
+ ),
+ )
+ )
+ return provider
+
+
+def get_tracer(provider: TracerProvider, name: str = "litellm") -> Tracer:
+ return provider.get_tracer(name)
+
+
+def in_memory_provider(
+ config: OpenTelemetryV2Config | None = None,
+) -> tuple[TracerProvider, InMemorySpanExporter]:
+ """Convenience for tests: a provider exporting to an in-memory buffer."""
+ cfg = config or OpenTelemetryV2Config(exporter="in_memory")
+ exporter = InMemorySpanExporter()
+ provider = build_tracer_provider(cfg, exporter=exporter)
+ return provider, exporter
diff --git a/litellm/integrations/otel/plumbing/routing.py b/litellm/integrations/otel/plumbing/routing.py
new file mode 100644
index 00000000000..4d0943a263a
--- /dev/null
+++ b/litellm/integrations/otel/plumbing/routing.py
@@ -0,0 +1,101 @@
+"""Per-request multi-tenant tracer routing.
+
+When a request carries team/key vendor credentials in
+``standard_callback_dynamic_params``, its spans must export through a
+``TracerProvider`` whose OTLP headers carry those credentials.
+``TenantTracerCache`` builds and caches one provider per distinct credential
+set, and otherwise hands back the logger's default tracer. This lets a single
+logger fan requests out to many tenants without needing a logger per tenant.
+"""
+
+from collections import OrderedDict
+from typing import Any, Mapping
+
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.trace import Tracer
+
+from litellm._logging import verbose_logger
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config
+from litellm.integrations.otel.presets import dynamic_otlp_headers
+from litellm.integrations.otel.plumbing.providers import (
+ build_tracer_provider,
+ get_tracer,
+)
+
+# Exporter kinds that ignore headers — never rewritten with dynamic credentials.
+_NON_OTLP_KINDS = ("console", "in_memory", "inmemory", "memory")
+
+# Cap on distinct credential-scoped providers held at once. ``dynamic_params``
+# can be populated from request metadata, so an unbounded cache lets a caller
+# spawn one ``TracerProvider`` (plus its ``BatchSpanProcessor`` background
+# thread) per unique credential set and exhaust the proxy. The LRU bound keeps
+# the working set of active tenants resident while flushing and shutting down
+# evicted providers so their threads are reclaimed.
+_MAX_CACHED_PROVIDERS = 256
+
+
+def _shutdown_provider(provider: TracerProvider) -> None:
+ """Flush + stop an evicted provider's processors (reclaims their threads).
+
+ ``TracerProvider.shutdown`` force-flushes each ``SpanProcessor`` before
+ stopping it, so any spans already handed to a ``BatchSpanProcessor`` are
+ exported rather than dropped. Best-effort: a shutdown failure must not break
+ the request that triggered the eviction.
+ """
+ try:
+ provider.shutdown()
+ except Exception as e: # pragma: no cover - defensive
+ verbose_logger.debug("OTel V2: error shutting down evicted provider: %s", e)
+
+
+class TenantTracerCache:
+ """Credential-scoped ``TracerProvider`` cache keyed by the dynamic headers."""
+
+ def __init__(
+ self,
+ config: OpenTelemetryV2Config,
+ callback_name: str | None,
+ tracer_name: str,
+ ) -> None:
+ self._config = config
+ self._callback_name = callback_name
+ self._tracer_name = tracer_name
+ self._providers: "OrderedDict[tuple[tuple[str, str], ...], TracerProvider]" = (
+ OrderedDict()
+ )
+
+ def tracer_for(self, default: Tracer, dynamic_params: Any) -> Tracer:
+ """Return the tracer for this request.
+
+ Use ``default`` unless the request's dynamic credentials require a
+ credential-scoped tracer, in which case build (or reuse) one. The cache
+ is a bounded LRU: the least-recently-used provider is flushed and shut
+ down on overflow so its exporter threads don't accumulate.
+ """
+ headers = dynamic_otlp_headers(self._callback_name, dynamic_params)
+ if not headers:
+ return default
+ cache_key = tuple(sorted(headers.items()))
+ provider = self._providers.get(cache_key)
+ if provider is not None:
+ self._providers.move_to_end(cache_key)
+ else:
+ provider = build_tracer_provider(self._config_with_headers(headers))
+ self._providers[cache_key] = provider
+ if len(self._providers) > _MAX_CACHED_PROVIDERS:
+ _, evicted = self._providers.popitem(last=False)
+ _shutdown_provider(evicted)
+ return get_tracer(provider, self._tracer_name)
+
+ def _config_with_headers(self, headers: Mapping[str, str]) -> OpenTelemetryV2Config:
+ """Clone the config, replacing OTLP exporter headers with ``headers``."""
+ header_str = ",".join(f"{key}={value}" for key, value in headers.items())
+ exporters = [
+ (
+ spec
+ if spec.kind.lower() in _NON_OTLP_KINDS
+ else spec.model_copy(update={"headers": header_str})
+ )
+ for spec in self._config.exporters
+ ]
+ return self._config.model_copy(update={"exporters": exporters})
diff --git a/litellm/integrations/otel/presets/__init__.py b/litellm/integrations/otel/presets/__init__.py
new file mode 100644
index 00000000000..c69d257ab52
--- /dev/null
+++ b/litellm/integrations/otel/presets/__init__.py
@@ -0,0 +1,78 @@
+"""Integration presets — each one returns an :class:`OpenTelemetryV2Config`.
+
+A preset is a callable that reads an integration's env vars and returns an
+``OpenTelemetryV2Config`` describing the exporter destination, the mapper
+vocabularies to apply, and any resource attributes. ``PRESET_BY_CALLBACK``
+maps a callback name (``"arize"``, ``"langfuse_otel"``, ...) to its preset so
+the factory in ``litellm_logging`` can resolve a name and build a single
+``OpenTelemetryV2`` instance from the result.
+"""
+
+from typing import Callable
+
+from litellm.integrations.otel.presets.agentops import agentops_preset
+from litellm.integrations.otel.presets.arize import arize_dynamic_headers, arize_preset
+from litellm.integrations.otel.presets.base import Preset
+from litellm.integrations.otel.presets.langfuse import (
+ langfuse_dynamic_headers,
+ langfuse_preset,
+)
+from litellm.integrations.otel.presets.langtrace import langtrace_preset
+from litellm.integrations.otel.presets.levo import levo_preset
+from litellm.integrations.otel.presets.phoenix import phoenix_preset
+from litellm.integrations.otel.presets.weave import weave_dynamic_headers, weave_preset
+from litellm.types.utils import StandardCallbackDynamicParams
+
+#: Callback name → preset. The ``Preset`` annotation makes mypy verify every
+#: registered value matches the preset interface.
+PRESET_BY_CALLBACK: dict[str, Preset] = {
+ "agentops": agentops_preset,
+ "arize": arize_preset,
+ "arize_phoenix": phoenix_preset,
+ "langfuse_otel": langfuse_preset,
+ "langtrace": langtrace_preset,
+ "levo": levo_preset,
+ "weave_otel": weave_preset,
+}
+
+#: Callback name → per-request OTLP header builder (team/key multi-tenant
+#: routing). Only integrations that support dynamic credentials appear here —
+#: Arize-Phoenix/Langtrace/Levo/AgentOps don't, so they use the logger's
+#: default tracer.
+DYNAMIC_HEADERS_BY_CALLBACK: dict[
+ str, Callable[[StandardCallbackDynamicParams], dict[str, str]]
+] = {
+ "arize": arize_dynamic_headers,
+ "langfuse_otel": langfuse_dynamic_headers,
+ "weave_otel": weave_dynamic_headers,
+}
+
+
+def dynamic_otlp_headers(
+ callback_name: str | None,
+ dynamic_params: StandardCallbackDynamicParams | None,
+) -> dict[str, str] | None:
+ """Per-request OTLP headers for ``callback_name``, or ``None`` if N/A.
+
+ ``None`` means "no per-request routing" — the caller uses its default tracer.
+ """
+ builder = DYNAMIC_HEADERS_BY_CALLBACK.get(callback_name or "")
+ if builder is None or not dynamic_params:
+ return None
+ headers = builder(dynamic_params)
+ return headers or None
+
+
+__all__ = [
+ "PRESET_BY_CALLBACK",
+ "DYNAMIC_HEADERS_BY_CALLBACK",
+ "Preset",
+ "dynamic_otlp_headers",
+ "agentops_preset",
+ "arize_preset",
+ "langfuse_preset",
+ "langtrace_preset",
+ "levo_preset",
+ "phoenix_preset",
+ "weave_preset",
+]
diff --git a/litellm/integrations/otel/presets/agentops.py b/litellm/integrations/otel/presets/agentops.py
new file mode 100644
index 00000000000..5a12818fd99
--- /dev/null
+++ b/litellm/integrations/otel/presets/agentops.py
@@ -0,0 +1,139 @@
+"""AgentOps preset — OTLP/HTTP to AgentOps' endpoint with a lazily-fetched JWT.
+
+AgentOps authenticates with a short-lived JWT minted from the API key. Fetching
+it is blocking network I/O, so it must never run on the event loop: callback
+construction (where presets are built) can run inside the proxy's async startup
+or, in the SDK, on the first request. Instead of fetching at config-build time,
+this preset registers a custom exporter (``kind="agentops"``) that mints the JWT
+**on its first export** — which the ``BatchSpanProcessor`` runs in its own
+worker thread, off any event loop — and caches it for the process lifetime.
+"""
+
+from typing import Any
+
+import httpx
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+from litellm._logging import verbose_logger
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.plumbing.providers import register_exporter_factory
+
+_AGENTOPS_ENDPOINT = "https://otlp.agentops.cloud/v1/traces"
+_AGENTOPS_AUTH_ENDPOINT = "https://api.agentops.ai/v3/auth/token"
+_AGENTOPS_EXPORTER_KIND = "agentops"
+
+
+class _AgentOpsSettings(BaseSettings):
+ model_config = SettingsConfigDict(case_sensitive=False, extra="ignore")
+
+ api_key: str | None = Field(default=None, validation_alias="AGENTOPS_API_KEY")
+ service_name: str = Field(
+ default="agentops", validation_alias="AGENTOPS_SERVICE_NAME"
+ )
+ environment: str | None = Field(
+ default=None, validation_alias="AGENTOPS_ENVIRONMENT"
+ )
+
+
+def agentops_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ """Build the AgentOps config without any network I/O.
+
+ The ``agentops`` exporter mints (and caches) the JWT lazily on its first
+ export, so this stays non-blocking. ``project.id`` is therefore not a
+ resource attribute — it is encoded in the JWT, which AgentOps uses to route
+ the trace to the right project.
+ """
+ settings = _AgentOpsSettings()
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind=_AGENTOPS_EXPORTER_KIND,
+ endpoint=_AGENTOPS_ENDPOINT,
+ options=(
+ {"api_key": settings.api_key} if settings.api_key else None
+ ),
+ ),
+ ],
+ "resource_attributes": {
+ **base.resource_attributes,
+ "service.name": settings.service_name,
+ "telemetry.sdk.name": "agentops",
+ **(
+ {"deployment.environment": settings.environment}
+ if settings.environment
+ else {}
+ ),
+ },
+ }
+ )
+
+
+def _build_agentops_exporter(spec: ExporterSpec) -> Any:
+ """Factory for the ``agentops`` exporter kind: a lazy-auth OTLP/HTTP exporter."""
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
+ OTLPSpanExporter,
+ )
+
+ class _LazyAuthAgentOpsExporter(OTLPSpanExporter):
+ """OTLP/HTTP exporter that mints the AgentOps JWT on its first export.
+
+ ``export`` runs in the ``BatchSpanProcessor`` worker thread, so the
+ blocking token fetch never touches an event loop. The result is cached
+ after the first attempt (success or failure) so it runs at most once.
+ """
+
+ def __init__(self, *, endpoint: str | None, api_key: str | None) -> None:
+ super().__init__(endpoint=endpoint)
+ self._agentops_api_key = api_key
+ self._auth_resolved = False
+
+ def _ensure_authenticated(self) -> None:
+ if self._auth_resolved:
+ return
+ self._auth_resolved = True
+ if not self._agentops_api_key:
+ return
+ try:
+ token = _fetch_agentops_jwt(self._agentops_api_key).get("token")
+ if token:
+ # ``_session`` is the requests.Session the base exporter
+ # POSTs through; updating its Authorization header is how the
+ # minted JWT reaches every subsequent export.
+ self._session.headers["Authorization"] = f"Bearer {token}"
+ except Exception as e:
+ verbose_logger.debug("AgentOps JWT fetch failed: %s", e)
+
+ def export(self, spans: Any) -> Any:
+ self._ensure_authenticated()
+ return super().export(spans)
+
+ options = spec.options or {}
+ return _LazyAuthAgentOpsExporter(
+ endpoint=spec.endpoint, api_key=options.get("api_key")
+ )
+
+
+def _fetch_agentops_jwt(api_key: str) -> dict[str, Any]:
+ # Own a short-lived client rather than ``_get_httpx_client()``: that returns
+ # a process-wide cached ``HTTPHandler`` whose connection pool is shared by
+ # every caller, so closing it here would break concurrent/subsequent
+ # requests. This one-shot auth call gets its own client to close.
+ with httpx.Client(timeout=10) as client:
+ response = client.post(
+ url=_AGENTOPS_AUTH_ENDPOINT,
+ headers={"Content-Type": "application/json", "Connection": "keep-alive"},
+ json={"api_key": api_key},
+ )
+ if response.status_code != 200:
+ raise RuntimeError(f"Failed to fetch AgentOps token: {response.text}")
+ return response.json()
+
+
+register_exporter_factory(_AGENTOPS_EXPORTER_KIND, _build_agentops_exporter)
diff --git a/litellm/integrations/otel/presets/arize.py b/litellm/integrations/otel/presets/arize.py
new file mode 100644
index 00000000000..4df15125f5a
--- /dev/null
+++ b/litellm/integrations/otel/presets/arize.py
@@ -0,0 +1,75 @@
+"""Arize preset — OTLP exporter to Arize + OpenInference vocabulary."""
+
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+from litellm.integrations.arize.arize import ArizeLogger as _V1ArizeLogger
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.presets.utils import ensure_mappers
+from litellm.types.utils import StandardCallbackDynamicParams
+
+
+class _ArizeSettings(BaseSettings):
+ model_config = SettingsConfigDict(case_sensitive=False, extra="ignore")
+
+ # Standard OTLP headers env var, used as the fallback when no Arize
+ # credentials are configured.
+ otlp_traces_headers: str | None = Field(
+ default=None, validation_alias="OTEL_EXPORTER_OTLP_TRACES_HEADERS"
+ )
+
+
+def arize_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ arize_cfg = _V1ArizeLogger.get_arize_config()
+ headers = _arize_headers(arize_cfg)
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind=arize_cfg.protocol or "otlp_grpc",
+ endpoint=arize_cfg.endpoint or "https://otlp.arize.com/v1",
+ headers=headers,
+ ),
+ ],
+ "mapper_names": ensure_mappers(base.mapper_names, "openinference"),
+ "resource_attributes": {
+ **base.resource_attributes,
+ **(
+ {"model_id": arize_cfg.project_name}
+ if arize_cfg.project_name
+ else {}
+ ),
+ },
+ }
+ )
+
+
+def _arize_headers(arize_cfg) -> str | None:
+ pieces = []
+ if arize_cfg.space_id or arize_cfg.space_key:
+ pieces.append(f"space_id={arize_cfg.space_id or arize_cfg.space_key}")
+ if arize_cfg.api_key:
+ pieces.append(f"api_key={arize_cfg.api_key}")
+ if not pieces:
+ # Fall back to the standard OTLP headers env var when no Arize
+ # credentials are configured.
+ return _ArizeSettings().otlp_traces_headers
+ return ",".join(pieces)
+
+
+def arize_dynamic_headers(params: StandardCallbackDynamicParams) -> dict[str, str]:
+ """Per-request Arize OTLP headers from team/key dynamic params."""
+ headers: dict[str, str] = {}
+ # ``arize_space_key`` is the suggested param and wins over ``arize_space_id``.
+ space = params.get("arize_space_key") or params.get("arize_space_id")
+ if space:
+ headers["arize-space-id"] = space
+ api_key = params.get("arize_api_key")
+ if api_key:
+ headers["api_key"] = api_key
+ return headers
diff --git a/litellm/integrations/otel/presets/base.py b/litellm/integrations/otel/presets/base.py
new file mode 100644
index 00000000000..b50908e7652
--- /dev/null
+++ b/litellm/integrations/otel/presets/base.py
@@ -0,0 +1,25 @@
+"""Preset interface.
+
+A preset is a callable that reads its integration's env vars and produces an
+:class:`OpenTelemetryV2Config` (exporter list + mapper-name list + resource
+attributes). This ``Protocol`` pins that contract so ``PRESET_BY_CALLBACK`` and
+the factory in ``litellm_logging`` are type-checked structurally against it,
+matching the ``AttributeMapper`` protocol the mappers use.
+"""
+
+from typing import Protocol, runtime_checkable
+
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config
+
+
+@runtime_checkable
+class Preset(Protocol):
+ """Reads an integration's env config and returns an ``OpenTelemetryV2Config``.
+
+ ``config_overrides`` lets one preset layer onto another's config (or onto
+ test-supplied defaults); the factory calls presets with no arguments.
+ """
+
+ def __call__(
+ self, *, config_overrides: OpenTelemetryV2Config | None = None
+ ) -> OpenTelemetryV2Config: ...
diff --git a/litellm/integrations/otel/presets/langfuse.py b/litellm/integrations/otel/presets/langfuse.py
new file mode 100644
index 00000000000..011545384b9
--- /dev/null
+++ b/litellm/integrations/otel/presets/langfuse.py
@@ -0,0 +1,43 @@
+"""Langfuse-OTEL preset."""
+
+from litellm.integrations.langfuse.langfuse_otel import (
+ LangfuseOtelLogger as _V1Langfuse,
+)
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.presets.utils import ensure_mappers
+from litellm.types.utils import StandardCallbackDynamicParams
+
+
+def langfuse_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ cfg = _V1Langfuse.get_langfuse_otel_config()
+ kind = cfg.exporter if isinstance(cfg.exporter, str) else "otlp_http"
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind=kind,
+ endpoint=cfg.endpoint,
+ headers=cfg.headers,
+ ),
+ ],
+ "mapper_names": ensure_mappers(base.mapper_names, "langfuse"),
+ }
+ )
+
+
+def langfuse_dynamic_headers(params: StandardCallbackDynamicParams) -> dict[str, str]:
+ """Per-request Langfuse OTLP headers from team/key dynamic params."""
+ public_key = params.get("langfuse_public_key")
+ secret_key = params.get("langfuse_secret_key")
+ if public_key and secret_key:
+ return {
+ "Authorization": _V1Langfuse._get_langfuse_authorization_header(
+ public_key=public_key, secret_key=secret_key
+ )
+ }
+ return {}
diff --git a/litellm/integrations/otel/presets/langtrace.py b/litellm/integrations/otel/presets/langtrace.py
new file mode 100644
index 00000000000..acdbaf870d3
--- /dev/null
+++ b/litellm/integrations/otel/presets/langtrace.py
@@ -0,0 +1,22 @@
+"""Langtrace preset — Langtrace consumes generic OTLP + a vendor mapper."""
+
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config
+from litellm.integrations.otel.presets.utils import ensure_mappers
+
+
+def langtrace_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ """Compose the Langtrace mapper on top of the customer's OTLP destination.
+
+ Unlike Arize / Phoenix / Langfuse, Langtrace doesn't ship its own endpoint
+ — users point their existing OTLP collector at Langtrace and just
+ need the vendor attribute schema applied to outgoing spans.
+ """
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "mapper_names": ensure_mappers(base.mapper_names, "langtrace"),
+ }
+ )
diff --git a/litellm/integrations/otel/presets/levo.py b/litellm/integrations/otel/presets/levo.py
new file mode 100644
index 00000000000..4c4cba982a4
--- /dev/null
+++ b/litellm/integrations/otel/presets/levo.py
@@ -0,0 +1,24 @@
+"""Levo preset — OTLP/HTTP to a Levo collector with org+workspace headers."""
+
+from litellm.integrations.levo.levo import LevoLogger as _V1Levo
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+
+
+def levo_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ cfg = _V1Levo.get_levo_config()
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind="otlp_http",
+ endpoint=cfg.endpoint,
+ headers=cfg.otlp_auth_headers,
+ ),
+ ],
+ }
+ )
diff --git a/litellm/integrations/otel/presets/phoenix.py b/litellm/integrations/otel/presets/phoenix.py
new file mode 100644
index 00000000000..4c2b165ffca
--- /dev/null
+++ b/litellm/integrations/otel/presets/phoenix.py
@@ -0,0 +1,48 @@
+"""Arize-Phoenix preset."""
+
+from pydantic import AliasChoices, Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+from litellm.integrations.arize.arize_phoenix import (
+ ArizePhoenixLogger as _V1Phoenix,
+)
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.presets.utils import ensure_mappers
+
+
+class _PhoenixSettings(BaseSettings):
+ model_config = SettingsConfigDict(case_sensitive=False, extra="ignore")
+
+ project_name: str = Field(
+ default="default",
+ validation_alias=AliasChoices(
+ "PHOENIX_PROJECT_NAME", "PHOENIX_COLLECTOR_PROJECT_NAME"
+ ),
+ )
+
+
+def phoenix_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ cfg = _V1Phoenix.get_arize_phoenix_config()
+ headers = cfg.otlp_auth_headers if hasattr(cfg, "otlp_auth_headers") else None
+ project_name = _PhoenixSettings().project_name
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind=cfg.protocol if hasattr(cfg, "protocol") else "otlp_http",
+ endpoint=cfg.endpoint,
+ headers=headers,
+ ),
+ ],
+ "mapper_names": ensure_mappers(base.mapper_names, "openinference"),
+ "resource_attributes": {
+ **base.resource_attributes,
+ "openinference.project.name": project_name,
+ },
+ }
+ )
diff --git a/litellm/integrations/otel/presets/utils.py b/litellm/integrations/otel/presets/utils.py
new file mode 100644
index 00000000000..fdf8184441d
--- /dev/null
+++ b/litellm/integrations/otel/presets/utils.py
@@ -0,0 +1,16 @@
+"""Shared helpers for the integration presets."""
+
+from typing import Iterable
+
+
+def ensure_mappers(mapper_names: Iterable[str], *names: str) -> list[str]:
+ """Return ``mapper_names`` with each of ``names`` appended if not already present.
+
+ Order is preserved and duplicates are skipped, so composing several presets
+ (or re-applying one) never double-adds a vocabulary.
+ """
+ result = list(mapper_names)
+ for name in names:
+ if name not in result:
+ result.append(name)
+ return result
diff --git a/litellm/integrations/otel/presets/weave.py b/litellm/integrations/otel/presets/weave.py
new file mode 100644
index 00000000000..9fc03c84a6d
--- /dev/null
+++ b/litellm/integrations/otel/presets/weave.py
@@ -0,0 +1,43 @@
+"""Weave (W&B) preset."""
+
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.presets.utils import ensure_mappers
+from litellm.integrations.weave.weave_otel import (
+ _get_weave_authorization_header,
+ get_weave_otel_config,
+)
+from litellm.types.utils import StandardCallbackDynamicParams
+
+
+def weave_preset(
+ *,
+ config_overrides: OpenTelemetryV2Config | None = None,
+) -> OpenTelemetryV2Config:
+ weave_cfg = get_weave_otel_config()
+ base = config_overrides or OpenTelemetryV2Config()
+ return base.model_copy(
+ update={
+ "exporters": [
+ *base.exporters,
+ ExporterSpec(
+ kind=weave_cfg.protocol or "otlp_http",
+ endpoint=weave_cfg.endpoint,
+ headers=weave_cfg.otlp_auth_headers,
+ ),
+ ],
+ # Weave consumes OpenInference + a small Weave-specific overlay.
+ "mapper_names": ensure_mappers(base.mapper_names, "openinference", "weave"),
+ }
+ )
+
+
+def weave_dynamic_headers(params: StandardCallbackDynamicParams) -> dict[str, str]:
+ """Per-request Weave OTLP headers from team/key dynamic params."""
+ headers: dict[str, str] = {}
+ api_key = params.get("wandb_api_key")
+ if api_key:
+ headers["Authorization"] = _get_weave_authorization_header(api_key=api_key)
+ project_id = params.get("weave_project_id")
+ if project_id:
+ headers["project_id"] = project_id
+ return headers
diff --git a/litellm/integrations/otel/runtime.py b/litellm/integrations/otel/runtime.py
new file mode 100644
index 00000000000..ac3b991c971
--- /dev/null
+++ b/litellm/integrations/otel/runtime.py
@@ -0,0 +1,38 @@
+"""SDK-free entrypoints for proxy-core call sites (auth, …).
+
+Proxy code may run without the OpenTelemetry SDK installed, so it must not import
+``litellm.integrations.otel.logger`` (which imports the SDK at module scope) at
+module load. These wrappers import it lazily and no-op when the SDK is absent or
+V2 is not the active logger — so a call site can wrap a request phase or seed
+identity unconditionally.
+"""
+
+from contextlib import contextmanager
+from typing import Any, Iterator
+
+
+@contextmanager
+def phase_span(name: str) -> "Iterator[Any]":
+ """Run a request phase inside a live active span so its DB/service calls nest.
+
+ Yields ``None`` (a plain no-op) when the OTel SDK is unavailable or V2 is not
+ the active logger.
+ """
+ try:
+ from litellm.integrations.otel.logger import phase_span as _phase_span
+ except Exception:
+ yield None
+ return
+ with _phase_span(name) as span:
+ yield span
+
+
+def seed_request_identity(user_api_key_dict: Any, model: Any = None) -> None:
+ """Seed request-identity Baggage at the auth boundary (no-op without V2)."""
+ try:
+ from litellm.integrations.otel.logger import (
+ seed_request_identity as _seed_request_identity,
+ )
+ except Exception:
+ return
+ _seed_request_identity(user_api_key_dict, model=model)
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 606d28585bc..c127b3873a7 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -3792,6 +3792,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
try:
custom_logger_init_args = custom_logger_init_args or {}
if logging_integration == "agentops": # Add AgentOps initialization
+ _v2 = _maybe_construct_otel_v2("agentops", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
for callback in _in_memory_loggers:
if isinstance(callback, AgentOps):
return callback # type: ignore
@@ -3944,6 +3947,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(_opik_logger)
return _opik_logger # type: ignore
elif logging_integration == "arize":
+ _v2 = _maybe_construct_otel_v2("arize", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.opentelemetry import (
OpenTelemetry,
OpenTelemetryConfig,
@@ -3973,6 +3979,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(_arize_otel_logger)
return _arize_otel_logger # type: ignore
elif logging_integration == "arize_phoenix":
+ _v2 = _maybe_construct_otel_v2("arize_phoenix", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.opentelemetry import (
OpenTelemetry,
OpenTelemetryConfig,
@@ -4003,6 +4012,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(_arize_phoenix_otel_logger)
return _arize_phoenix_otel_logger # type: ignore
elif logging_integration == "levo":
+ _v2 = _maybe_construct_otel_v2("levo", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.levo.levo import LevoLogger
from litellm.integrations.opentelemetry import (
OpenTelemetry,
@@ -4028,6 +4040,28 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(_levo_otel_logger)
return _levo_otel_logger # type: ignore
elif logging_integration == "otel":
+ # Gate the new typed V2 adapter behind LITELLM_OTEL_V2. When off,
+ # the legacy 3,227-line god-class is used unchanged. The two are
+ # never registered simultaneously — the dedup loop below treats
+ # any module under ``litellm.integrations.otel`` or
+ # ``litellm.integrations.opentelemetry`` as "the OTel callback".
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ if is_otel_v2_enabled():
+ from litellm.integrations.otel.logger import OpenTelemetryV2
+
+ for callback in _in_memory_loggers:
+ if type(callback) is OpenTelemetryV2:
+ return callback # type: ignore
+ otel_logger_v2 = OpenTelemetryV2(
+ **_get_custom_logger_settings_from_proxy_server(
+ callback_name=logging_integration
+ )
+ )
+ _in_memory_loggers.append(otel_logger_v2)
+ _maybe_auto_initialize_arize_phoenix(_in_memory_loggers)
+ return otel_logger_v2 # type: ignore
+
from litellm.integrations.opentelemetry import OpenTelemetry
for callback in _in_memory_loggers:
@@ -4166,6 +4200,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
elif logging_integration == "langtrace":
if "LANGTRACE_API_KEY" not in os.environ:
raise ValueError("LANGTRACE_API_KEY not found in environment variables")
+ _v2 = _maybe_construct_otel_v2("langtrace", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.opentelemetry import (
OpenTelemetry,
@@ -4206,6 +4243,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(langfuse_logger)
return langfuse_logger # type: ignore
elif logging_integration == "langfuse_otel":
+ _v2 = _maybe_construct_otel_v2("langfuse_otel", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger
for callback in _in_memory_loggers:
@@ -4222,6 +4262,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_in_memory_loggers.append(_otel_logger)
return _otel_logger # type: ignore
elif logging_integration == "weave_otel":
+ _v2 = _maybe_construct_otel_v2("weave_otel", _in_memory_loggers)
+ if _v2 is not None:
+ return _v2 # type: ignore
from litellm.integrations.opentelemetry import OpenTelemetryConfig
from litellm.integrations.weave.weave_otel import (
WeaveOtelLogger,
@@ -4370,6 +4413,42 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
return None
+def _maybe_construct_otel_v2(
+ callback_name: str, _in_memory_loggers: list
+) -> Optional[Any]:
+ """If ``LITELLM_OTEL_V2`` is on, build (or reuse) a single ``OpenTelemetryV2``
+ instance configured via the preset for ``callback_name``.
+
+ Returns ``None`` when V2 is off OR when there's no preset registered for
+ ``callback_name`` — callers should then fall through to the legacy path.
+ """
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ if not is_otel_v2_enabled():
+ return None
+ from litellm.integrations.otel.logger import OpenTelemetryV2
+ from litellm.integrations.otel.presets import PRESET_BY_CALLBACK
+
+ preset_fn = PRESET_BY_CALLBACK.get(callback_name)
+ if preset_fn is None:
+ return None
+ for callback in _in_memory_loggers:
+ if (
+ isinstance(callback, OpenTelemetryV2)
+ and getattr(callback, "callback_name", None) == callback_name
+ ):
+ return callback
+ try:
+ config = preset_fn()
+ except Exception:
+ # If env vars are missing or the preset raises, defer to the legacy path
+ # so customers get the same error story they had before V2 landed.
+ return None
+ v2_logger = OpenTelemetryV2(config=config, callback_name=callback_name)
+ _in_memory_loggers.append(v2_logger)
+ return v2_logger
+
+
def _maybe_auto_initialize_arize_phoenix(_in_memory_loggers: list) -> None:
"""
Auto-initialize ArizePhoenixLogger when Phoenix env vars are detected.
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index 813b9826b37..828b719e299 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -21,6 +21,8 @@ from fastapi.security.api_key import APIKeyHeader
import litellm
from litellm._logging import verbose_logger, verbose_proxy_logger
from litellm._service_logger import ServiceLogging
+from litellm.integrations.otel.model.config import is_otel_v2_enabled
+from litellm.integrations.otel.runtime import phase_span, seed_request_identity
from litellm.constants import LITELLM_PROXY_MASTER_KEY_ALIAS
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.litellm_core_utils.dot_notation_indexing import get_nested_value
@@ -694,11 +696,17 @@ def _ensure_parent_otel_span_on_request_state(request: Request) -> None:
start_time=start_time,
headers=_safe_get_request_headers(request),
)
- open_telemetry_logger.set_proxy_request_route_attributes(
- parent_otel_span,
- url_path=get_request_route(request=request),
- http_route=get_request_route_template(request),
+ # Under V2 the FastAPI instrumentor stamps http.route / url.path on the server
+ # span; only the legacy logger needs these set explicitly.
+ set_route_attrs = getattr(
+ open_telemetry_logger, "set_proxy_request_route_attributes", None
)
+ if not is_otel_v2_enabled() and set_route_attrs is not None:
+ set_route_attrs(
+ parent_otel_span,
+ url_path=get_request_route(request=request),
+ http_route=get_request_route_template(request),
+ )
request.state.parent_otel_span = parent_otel_span
@@ -2187,73 +2195,85 @@ async def user_api_key_auth(
route: str = get_request_route(request=request)
## CHECK IF ROUTE IS ALLOWED
- user_api_key_auth_obj = await _user_api_key_auth_builder(
- request=request,
- api_key=api_key,
- azure_api_key_header=azure_api_key_header,
- anthropic_api_key_header=anthropic_api_key_header,
- google_ai_studio_api_key_header=google_ai_studio_api_key_header,
- azure_apim_header=azure_apim_header,
- request_data=request_data,
- custom_litellm_key_header=custom_litellm_key_header,
- )
- user_api_key_auth_obj.budget_reservation = None
-
- ## ENSURE DISABLE ROUTE WORKS ACROSS ALL USER AUTH FLOWS ##
- RouteChecks.should_call_route(
- route=route, valid_token=user_api_key_auth_obj, request=request
- )
-
- # Single authorization point. Builder paths MUST NOT call common_checks.
- # Route through the same exception handler the builder uses so
- # authorization failures (ProxyException, or plain Exception from
- # admin-only-route / model-access / budget checks) surface as
- # ProxyException consistently with pre-refactor behavior.
- try:
- await _run_centralized_common_checks(
- user_api_key_auth_obj=user_api_key_auth_obj,
+ # Run the whole auth phase inside a live ``auth`` span so the DB lookups it
+ # triggers (key/user/team object reads) nest under it instead of flattening
+ # onto the server span. No-op when OTel V2 isn't active.
+ with phase_span(f"auth {route}"):
+ user_api_key_auth_obj = await _user_api_key_auth_builder(
request=request,
- request_data=request_data,
- route=route,
- )
- except Exception as e:
- return await UserAPIKeyAuthExceptionHandler._handle_authentication_error(
- e=e,
- request=request,
- request_data=request_data,
- route=route,
- parent_otel_span=user_api_key_auth_obj.parent_otel_span,
api_key=api_key,
+ azure_api_key_header=azure_api_key_header,
+ anthropic_api_key_header=anthropic_api_key_header,
+ google_ai_studio_api_key_header=google_ai_studio_api_key_header,
+ azure_apim_header=azure_apim_header,
+ request_data=request_data,
+ custom_litellm_key_header=custom_litellm_key_header,
)
+ user_api_key_auth_obj.budget_reservation = None
- # Defense-in-depth: ``_user_api_key_auth_builder`` has multiple early-return
- # paths (no master key, /user/auth route, JWT short-circuits) that bypass
- # the end-user resolution block. If those paths produced an auth obj
- # without an ``end_user_id`` set, fall back to extracting from the request
- # body so spend logs are still attributed correctly. Validation honours
- # ``litellm.validate_end_user_id_in_db``.
- if user_api_key_auth_obj.end_user_id is None:
- from litellm.proxy.proxy_server import (
- prisma_client,
- proxy_logging_obj,
- user_api_key_cache,
+ ## ENSURE DISABLE ROUTE WORKS ACROSS ALL USER AUTH FLOWS ##
+ RouteChecks.should_call_route(
+ route=route, valid_token=user_api_key_auth_obj, request=request
)
- raw_end_user_id = get_end_user_id_from_request_body(
- request_data, _safe_get_request_headers(request)
- )
- if raw_end_user_id is not None:
- resolved_end_user_id = await resolve_and_validate_end_user_id(
- raw_end_user_id=raw_end_user_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- parent_otel_span=user_api_key_auth_obj.parent_otel_span,
- proxy_logging_obj=proxy_logging_obj,
+ # Single authorization point. Builder paths MUST NOT call common_checks.
+ # Route through the same exception handler the builder uses so
+ # authorization failures (ProxyException, or plain Exception from
+ # admin-only-route / model-access / budget checks) surface as
+ # ProxyException consistently with pre-refactor behavior.
+ try:
+ await _run_centralized_common_checks(
+ user_api_key_auth_obj=user_api_key_auth_obj,
+ request=request,
+ request_data=request_data,
+ route=route,
+ )
+ except Exception as e:
+ return await UserAPIKeyAuthExceptionHandler._handle_authentication_error(
+ e=e,
+ request=request,
+ request_data=request_data,
route=route,
+ parent_otel_span=user_api_key_auth_obj.parent_otel_span,
+ api_key=api_key,
)
- if resolved_end_user_id is not None:
- user_api_key_auth_obj.end_user_id = resolved_end_user_id
+ # Defense-in-depth: ``_user_api_key_auth_builder`` has multiple early-return
+ # paths (no master key, /user/auth route, JWT short-circuits) that bypass
+ # the end-user resolution block. If those paths produced an auth obj
+ # without an ``end_user_id`` set, fall back to extracting from the request
+ # body so spend logs are still attributed correctly. Validation honours
+ # ``litellm.validate_end_user_id_in_db``.
+ if user_api_key_auth_obj.end_user_id is None:
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ raw_end_user_id = get_end_user_id_from_request_body(
+ request_data, _safe_get_request_headers(request)
+ )
+ if raw_end_user_id is not None:
+ resolved_end_user_id = await resolve_and_validate_end_user_id(
+ raw_end_user_id=raw_end_user_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=user_api_key_auth_obj.parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ route=route,
+ )
+ if resolved_end_user_id is not None:
+ user_api_key_auth_obj.end_user_id = resolved_end_user_id
+
+ # Identity is now resolved. Seed it AFTER the auth span closes so the Baggage
+ # persists on the request task (detaching the span's context token inside the
+ # ``with`` would unwind a Baggage attach made within it) and every post-auth
+ # span — pre-call, LLM call, guardrail, spend write — inherits team/key/user.
+ seed_request_identity(
+ user_api_key_auth_obj,
+ model=request_data.get("model") if isinstance(request_data, dict) else None,
+ )
user_api_key_auth_obj.request_route = normalize_request_route(route)
return user_api_key_auth_obj
diff --git a/litellm/proxy/db/log_db_metrics.py b/litellm/proxy/db/log_db_metrics.py
index 5c795155324..eb4961062df 100644
--- a/litellm/proxy/db/log_db_metrics.py
+++ b/litellm/proxy/db/log_db_metrics.py
@@ -7,13 +7,21 @@ ServiceLogger() then sends DB logs to Prometheus, OTEL, Datadog etc
import asyncio
from datetime import datetime
from functools import wraps
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Tuple
from litellm._service_logger import ServiceTypes
-from litellm.litellm_core_utils.core_helpers import (
- _get_parent_otel_span_from_kwargs,
- get_litellm_metadata_from_kwargs,
-)
+from litellm.litellm_core_utils.core_helpers import _get_parent_otel_span_from_kwargs
+
+
+def _safe_db_event_metadata(kwargs: Dict) -> Optional[Dict[str, str]]:
+ """Minimal, non-sensitive ``event_metadata`` for a DB service log.
+
+ The raw ``kwargs``/``args`` carry live objects (Prisma client, OTel spans)
+ and secrets (tokens), none of which belongs on a span — so we surface only
+ the table name when present. Everything else is dropped.
+ """
+ table_name = kwargs.get("table_name")
+ return {"table_name": table_name} if isinstance(table_name, str) else None
def log_db_metrics(func):
@@ -52,11 +60,7 @@ def log_db_metrics(func):
duration=(end_time - start_time).total_seconds(),
start_time=start_time,
end_time=end_time,
- event_metadata={
- "function_name": func.__name__,
- "function_kwargs": kwargs,
- "function_args": args,
- },
+ event_metadata=_safe_db_event_metadata(kwargs),
)
)
elif (
@@ -71,8 +75,9 @@ def log_db_metrics(func):
kwargs=passed_kwargs
)
if parent_otel_span is not None:
- metadata = get_litellm_metadata_from_kwargs(kwargs=passed_kwargs)
-
+ # No metadata dump: identity rides on Baggage, and the full
+ # request metadata (auth blob, response headers, tokens) must
+ # not land on a span.
asyncio.create_task(
proxy_logging_obj.service_logging_obj.async_service_success_hook(
service=ServiceTypes.BATCH_WRITE_TO_DB,
@@ -81,7 +86,7 @@ def log_db_metrics(func):
duration=0.0,
start_time=start_time,
end_time=end_time,
- event_metadata=metadata,
+ event_metadata=None,
)
)
# end of logging to otel
@@ -134,9 +139,5 @@ async def _handle_logging_db_exception(
duration=(end_time - start_time).total_seconds(),
start_time=start_time,
end_time=end_time,
- event_metadata={
- "function_name": func.__name__,
- "function_kwargs": kwargs,
- "function_args": args,
- },
+ event_metadata=_safe_db_event_metadata(kwargs),
)
diff --git a/litellm/proxy/management_helpers/utils.py b/litellm/proxy/management_helpers/utils.py
index 888ccc78188..287dc38a1fb 100644
--- a/litellm/proxy/management_helpers/utils.py
+++ b/litellm/proxy/management_helpers/utils.py
@@ -8,6 +8,7 @@ from fastapi import HTTPException, Request
import litellm
from litellm._logging import verbose_logger
+from litellm.integrations.otel.model.config import is_otel_v2_enabled
from litellm._uuid import uuid
from litellm.proxy.common_utils.timezone_utils import get_budget_reset_time
from litellm.proxy._types import ( # key request types; user request types; team request types; customer request types
@@ -458,6 +459,12 @@ async def _emit_management_endpoint_otel_span(
if open_telemetry_logger is None:
return
+ # Under V2 OTel, management endpoints are ordinary FastAPI routes already
+ # spanned by the mounted instrumentor — there is no management hook to fire, so
+ # skip the payload build entirely. The legacy logger still needs the hook.
+ if is_otel_v2_enabled():
+ return
+
http_request: Optional[Request] = kwargs.get("http_request")
if http_request is not None:
# Inline import — auth_utils participates in a proxy import cycle.
diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index 67af176c1eb..5aa0f6cb184 100644
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@ -801,9 +801,14 @@ async def pass_through_request( # noqa: PLR0915
)
## LOGGING OBJECT ## - initialize before pre_call_hook so guardrails can access it
+ # Surface the requested model (when the body carries one) so logging/spans
+ # read e.g. ``chat gpt-4o`` instead of ``chat unknown``.
+ passthrough_model = (
+ _parsed_body.get("model") if isinstance(_parsed_body, dict) else None
+ ) or "unknown"
start_time = datetime.now()
logging_obj = Logging(
- model="unknown",
+ model=passthrough_model,
messages=[{"role": "user", "content": safe_dumps(_parsed_body)}],
stream=False,
call_type="pass_through_endpoint",
@@ -855,7 +860,7 @@ async def pass_through_request( # noqa: PLR0915
# done for supporting 'parallel_request_limiter.py' with pass-through endpoints
logging_obj.update_environment_variables(
- model="unknown",
+ model=passthrough_model,
user="unknown",
optional_params={},
litellm_params=kwargs["litellm_params"],
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 8fbe6d97dbc..2a085077434 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -825,6 +825,37 @@ async def proxy_startup_event(app: FastAPI): # noqa: PLR0915
if isinstance(worker_config, dict):
await initialize(**worker_config)
+ ## V2 OTEL: now that config (and therefore the callbacks) is loaded, publish
+ ## the chosen V2 logger's TracerProvider as the OTel global. The FastAPI
+ ## instrumentation mounted at app-creation binds to the global provider, so
+ ## this is what makes server spans and gen-ai spans share one provider and
+ ## land in the same trace. Prefer an already-registered preset logger
+ ## (arize, langfuse, …) so server spans export to that backend too; otherwise
+ ## build a generic one from OTEL_* envs. ``set_tracer_provider`` only takes
+ ## effect once, so the first configured logger wins.
+ try:
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ if is_otel_v2_enabled():
+ from opentelemetry import trace as _otel_trace
+
+ from litellm.integrations.otel.logger import OpenTelemetryV2
+
+ _otel_v2_logger = (
+ next(
+ (
+ cb
+ for cb in litellm.service_callback
+ if isinstance(cb, OpenTelemetryV2)
+ ),
+ None,
+ )
+ or OpenTelemetryV2()
+ )
+ _otel_trace.set_tracer_provider(_otel_v2_logger._tracer_provider)
+ except Exception as e:
+ verbose_proxy_logger.debug("Skipping OTel V2 provider setup: %s", e)
+
# check if DATABASE_URL in environment - load from there
if prisma_client is None:
_db_url: Optional[str] = get_secret("DATABASE_URL", None) # type: ignore
@@ -1074,6 +1105,16 @@ app = FastAPI(
strict_content_type=False,
)
+## V2 OTEL: instrument the FastAPI app for server spans (gated by
+## LITELLM_OTEL_V2). This MUST run at app-creation time — once the lifespan runs,
+## the middleware stack is frozen and ``instrument_app`` raises "Cannot add
+## middleware after an application has started". See
+## ``litellm.integrations.otel.mount`` for the full rationale; the call is a safe
+## no-op when the gate is off or the instrumentation package is unavailable.
+from litellm.integrations.otel.mount import instrument_fastapi_app
+
+instrument_fastapi_app(app)
+
vertex_live_passthrough_vertex_base = VertexBase()
@@ -1238,6 +1279,17 @@ def _close_dangling_otel_server_span(request: Request, status_code: int) -> None
return
if open_telemetry_logger is None:
return
+ # Under OTel V2 the FastAPI instrumentor owns the server span (parent_otel_span
+ # is that same span), and it records the error + ends it itself. Ending it here
+ # would end it early — losing the http.* attributes the instrumentor stamps on
+ # completion — and double-end it. Leave it to the instrumentor.
+ try:
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ if is_otel_v2_enabled():
+ return
+ except Exception:
+ pass
try:
from opentelemetry.trace import Status, StatusCode
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 14f7f411e41..0e72f47e224 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -30,7 +30,11 @@ from typing import (
)
from litellm import _custom_logger_compatible_callbacks_literal
-from litellm.constants import DEFAULT_MODEL_CREATED_AT_TIME, MAX_TEAM_LIST_LIMIT
+from litellm.constants import (
+ DEFAULT_MODEL_CREATED_AT_TIME,
+ LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL,
+ MAX_TEAM_LIST_LIMIT,
+)
from litellm.proxy._types import (
DB_CONNECTION_ERROR_TYPES,
CommonProxyErrors,
@@ -557,6 +561,26 @@ class ProxyLogging:
for idx, initialized_callback in string_callbacks_to_replace.items():
litellm.callbacks[idx] = initialized_callback
+ # Fan ``litellm.callbacks`` (the "all events" registry) out into the
+ # success/failure event lists eagerly, at startup. ``completion()`` does
+ # this lazily in ``function_setup`` on the first call, but request paths
+ # that build their own logging object and never run ``function_setup`` —
+ # notably pass-through endpoints — read ``litellm._async_success_callback``
+ # directly. Without this, a config-registered logger (e.g. ``otel``) is
+ # invisible to pass-through traffic until some other request warms the
+ # global lists. The manager dedupes, so this is idempotent with
+ # ``function_setup``.
+ for callback in litellm.callbacks:
+ if isinstance(callback, CustomLogger):
+ litellm.logging_callback_manager.add_litellm_success_callback(callback)
+ litellm.logging_callback_manager.add_litellm_failure_callback(callback)
+ litellm.logging_callback_manager.add_litellm_async_success_callback(
+ callback
+ )
+ litellm.logging_callback_manager.add_litellm_async_failure_callback(
+ callback
+ )
+
async def update_request_status(
self, litellm_call_id: str, status: Literal["success", "fail"]
):
@@ -2171,6 +2195,15 @@ class ProxyLogging:
# async_post_call_failure_hook — skip pre_call and failure handlers.
if litellm_logging_obj.call_type == CallTypes.pass_through.value:
return
+ # This is a proxy-gate error (auth/rate-limit) for a request that never
+ # reached a provider. ``pre_call`` below still fires every callback's
+ # input hook so the failure is logged — but tracing callbacks must not
+ # fabricate an LLM-call span for a call that did not happen (and, since
+ # this runs inside the live ``auth`` phase span, would otherwise nest it
+ # under auth). The marker tells them to skip span creation.
+ litellm_logging_obj.model_call_details[
+ LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL
+ ] = True
litellm_logging_obj.pre_call(
input=input,
api_key="",
diff --git a/pyproject.toml b/pyproject.toml
index 6e84afad17e..2e371630fd4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -119,6 +119,7 @@ proxy-runtime = [
"opentelemetry-api==1.28.0",
"opentelemetry-sdk==1.28.0",
"opentelemetry-exporter-otlp==1.28.0",
+ "opentelemetry-instrumentation-fastapi==0.49b0",
"ddtrace>=2.19.0,<3.0",
"sentry-sdk>=2.21.0,<3.0",
"mangum>=0.17.0,<1.0",
@@ -160,6 +161,7 @@ dev = [
"opentelemetry-api==1.28.0",
"opentelemetry-sdk==1.28.0",
"opentelemetry-exporter-otlp==1.28.0",
+ "opentelemetry-instrumentation-fastapi==0.49b0",
"langfuse==2.59.7",
"fastapi-offline==1.7.6",
"fakeredis==2.34.1",
@@ -178,6 +180,7 @@ proxy-dev = [
"opentelemetry-api==1.28.0",
"opentelemetry-sdk==1.28.0",
"opentelemetry-exporter-otlp==1.28.0",
+ "opentelemetry-instrumentation-fastapi==0.49b0",
"azure-identity==1.25.2",
"a2a-sdk==0.3.24",
]
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py b/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py
new file mode 100644
index 00000000000..fd4a7e141e5
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py
@@ -0,0 +1,172 @@
+"""Tests for Baggage-based promotion of request-scoped attributes onto every span,
+and the two antipattern boundaries: http.* is never promoted, and the full
+metadata blob is never promoted (only the bounded allowlist)."""
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from litellm.integrations.otel import ( # noqa: E402
+ GenAI,
+ HTTP,
+ LiteLLM,
+ OpenTelemetryV2Config,
+ promoted_baggage,
+)
+from litellm.integrations.otel.plumbing import context as ctx_mod # noqa: E402
+from litellm.integrations.otel.plumbing import providers # noqa: E402
+from litellm.integrations.otel.emitter import SpanEmitter # noqa: E402
+from litellm.integrations.otel.model.payloads import ( # noqa: E402
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+)
+from litellm.integrations.otel.model.baggage import BAGGAGE_PROMOTED_KEYS # noqa: E402
+from litellm.integrations.otel.model.spans import SpanRole # noqa: E402
+
+
+def _payload():
+ return {
+ "call_type": "acompletion",
+ "custom_llm_provider": "openai",
+ "model": "gpt-4o",
+ "prompt_tokens": 1,
+ "completion_tokens": 1,
+ "total_tokens": 2,
+ "metadata": {
+ "team_id": "t1",
+ "team_alias": "team one",
+ "user_api_key_hash": "hsh",
+ "user_api_key_org_id": "org1",
+ "user_api_key_team_metadata": {"tier": "gold", "cost_center": "42"},
+ "private_note": "do-not-promote",
+ },
+ "status": "success",
+ "litellm_call_id": "call_1",
+ "hidden_params": {"litellm_model_name": "azure/my-deployment"},
+ }
+
+
+def _engine_and_exporter(config=None):
+ cfg = config or OpenTelemetryV2Config(exporter="in_memory")
+ provider, exporter = providers.in_memory_provider(cfg)
+ tracer = providers.get_tracer(provider, "litellm-baggage-test")
+ return SpanEmitter(tracer, cfg), exporter
+
+
+def test_identity_promoted_onto_every_span():
+ engine, exporter = _engine_and_exporter()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)
+ ctx = ctx_mod.set_request_baggage(bag)
+
+ root = engine.start_span(SpanRole.PROXY_REQUEST, "POST /chat/completions", ctx)
+ root_ctx = ctx_mod.context_from_span(root, ctx)
+ engine.emit(SpanRole.LLM_CALL, data, parent_context=root_ctx)
+ engine.emit(
+ SpanRole.GUARDRAIL, GuardrailSpanData("presidio", status="success"), root_ctx
+ )
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), root_ctx)
+ root.end()
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 4
+ for span in spans:
+ assert span.attributes.get(LiteLLM.TEAM_ID) == "t1"
+ assert span.attributes.get(LiteLLM.TEAM_ALIAS) == "team one"
+ assert span.attributes.get(GenAI.REQUEST_MODEL) == "gpt-4o"
+
+
+def test_team_metadata_and_provider_model_promoted():
+ """The team's metadata dict (JSON) and the provider/underlying model name are
+ promoted onto every span, alongside the user-facing ``gen_ai.request.model``."""
+ import json
+
+ engine, exporter = _engine_and_exporter()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)
+ ctx = ctx_mod.set_request_baggage(bag)
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), ctx)
+ (span,) = exporter.get_finished_spans()
+
+ # team metadata: the whole dict, JSON-serialized into one value
+ assert json.loads(span.attributes[LiteLLM.TEAM_METADATA]) == {
+ "tier": "gold",
+ "cost_center": "42",
+ }
+ # provider model is distinct from the user-facing request model
+ assert span.attributes.get(LiteLLM.PROVIDER_MODEL) == "azure/my-deployment"
+ assert span.attributes.get(GenAI.REQUEST_MODEL) == "gpt-4o"
+
+
+def test_empty_team_metadata_is_dropped():
+ """An absent/empty team_metadata dict must not promote a useless ``"{}"``."""
+ payload = _payload()
+ payload["metadata"]["user_api_key_team_metadata"] = {}
+ payload["hidden_params"] = {}
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.identity.team_metadata is None
+ # With no explicit dispatched-model source (hidden_params emptied), the
+ # provider model falls back to the call model — so it's present, not dropped.
+ assert data.identity.provider_model == "gpt-4o"
+ bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)
+ assert LiteLLM.TEAM_METADATA not in bag
+ assert bag[LiteLLM.PROVIDER_MODEL] == "gpt-4o"
+
+
+def test_allowlisted_metadata_subkey_promoted_blob_excluded():
+ engine, exporter = _engine_and_exporter()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)
+ ctx = ctx_mod.set_request_baggage(bag)
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), ctx)
+ (span,) = exporter.get_finished_spans()
+ # allowlisted metadata sub-key is promoted
+ assert (
+ span.attributes.get(f"{LiteLLM.METADATA_PREFIX}user_api_key_org_id") == "org1"
+ )
+ # non-allowlisted metadata is NOT promoted (no full-blob dumping)
+ assert all("private_note" not in k for k in span.attributes)
+
+
+def test_http_attributes_never_promoted():
+ """Even if http.* is present in baggage, the processor must not stamp it on
+ child spans (it belongs on the SERVER span only)."""
+ engine, exporter = _engine_and_exporter()
+ ctx = ctx_mod.set_request_baggage(
+ {
+ LiteLLM.TEAM_ID: "t1",
+ HTTP.ROUTE: "/chat/completions",
+ HTTP.REQUEST_METHOD: "POST",
+ }
+ )
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), ctx)
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes.get(LiteLLM.TEAM_ID) == "t1"
+ assert HTTP.ROUTE not in span.attributes
+ assert HTTP.REQUEST_METHOD not in span.attributes
+
+
+def test_arbitrary_upstream_baggage_not_promoted():
+ engine, exporter = _engine_and_exporter()
+ ctx = ctx_mod.set_request_baggage(
+ {LiteLLM.TEAM_ID: "t1", "some.upstream.key": "leak"}
+ )
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), ctx)
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes.get(LiteLLM.TEAM_ID) == "t1"
+ assert "some.upstream.key" not in span.attributes
+
+
+def test_baggage_processor_allowlist_can_be_widened():
+ cfg = OpenTelemetryV2Config(
+ exporter="in_memory",
+ baggage_promoted_keys=[LiteLLM.TEAM_ID, "custom.key"],
+ )
+ engine, exporter = _engine_and_exporter(cfg)
+ ctx = ctx_mod.set_request_baggage({"custom.key": "v", LiteLLM.TEAM_ALIAS: "ta"})
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis"), ctx)
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes.get("custom.key") == "v"
+ # team_alias not in this config's allowlist -> not promoted
+ assert LiteLLM.TEAM_ALIAS not in span.attributes
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_components.py b/tests/test_litellm/integrations/otel/test_otel_v2_components.py
new file mode 100644
index 00000000000..86d84bd8100
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_components.py
@@ -0,0 +1,463 @@
+"""Coverage for the engine-layer components: providers/exporters, context +
+baggage helpers, metrics, the typed coercion helpers, mapper branches, span-name
+builders, and the registry validator's failure paths. Needs the OTel SDK."""
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from opentelemetry.sdk.metrics import MeterProvider # noqa: E402
+from opentelemetry.sdk.metrics.export import InMemoryMetricReader # noqa: E402
+from opentelemetry.sdk.trace.export import ( # noqa: E402
+ BatchSpanProcessor,
+ ConsoleSpanExporter,
+ SimpleSpanProcessor,
+)
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( # noqa: E402
+ InMemorySpanExporter,
+)
+from opentelemetry.trace import SpanKind # noqa: E402
+
+from litellm.integrations.otel.plumbing import context as ctx_mod # noqa: E402
+from litellm.integrations.otel.plumbing import providers # noqa: E402
+from litellm.integrations.otel.model.config import OpenTelemetryV2Config # noqa: E402
+from litellm.integrations.otel.mappers.genai import GenAIMapper # noqa: E402
+from litellm.integrations.otel.mappers.legacy import LegacyMapper # noqa: E402
+from litellm.integrations.otel.plumbing.metrics import (
+ create_genai_metrics,
+) # noqa: E402
+from litellm.integrations.otel.model.payloads import ( # noqa: E402
+ GuardrailSpanData,
+ LLMCallSpanData,
+ LLMRequestParams,
+ LLMUsage,
+ ProxyRequestSpanData,
+ RequestIdentity,
+ ServerInfo,
+ ServiceSpanData,
+ SpanError,
+)
+from litellm.integrations.otel.model.semconv import GenAI, GenAIOperation
+from litellm.integrations.otel.model.spans import ( # noqa: E402
+ SPAN_REGISTRY,
+ LiteLLMSpanKind,
+ SpanRole,
+ SpanSpec,
+ db_system,
+ guardrail_span_name,
+ proxy_request_span_name,
+ service_span_name,
+ span_role_for_service,
+ validate_registry,
+)
+from litellm.integrations.otel.model.utils import ( # noqa: E402
+ as_bool,
+ as_float,
+ as_int,
+ as_str,
+ as_str_tuple,
+)
+
+# --- typed coercion helpers ------------------------------------------------- #
+
+
+def test_as_str():
+ assert as_str(None) is None
+ assert as_str("x") == "x"
+ assert as_str(5) == "5"
+
+
+def test_as_int():
+ assert as_int(True) == 1
+ assert as_int(3) == 3
+ assert as_int(3.9) == 3
+ assert as_int("7") == 7
+ assert as_int("nope") is None
+ assert as_int(None) is None
+
+
+def test_as_float():
+ assert as_float(True) == 1.0
+ assert as_float(2) == 2.0
+ assert as_float("1.5") == 1.5
+ assert as_float("nope") is None
+ assert as_float(None) is None
+
+
+def test_as_bool():
+ assert as_bool(None) is None
+ assert as_bool(True) is True
+ assert as_bool(1) is True
+ assert as_bool(0) is False
+
+
+def test_as_str_tuple():
+ assert as_str_tuple(None) is None
+ assert as_str_tuple("a") == ("a",)
+ assert as_str_tuple(["a", 2]) == ("a", "2")
+ assert as_str_tuple(123) is None
+
+
+def test_request_params_max_completion_tokens_fallback():
+ params = LLMRequestParams.from_model_parameters({"max_completion_tokens": 99})
+ assert params.max_tokens == 99
+
+
+def test_server_info_from_api_base():
+ assert ServerInfo.from_api_base(None) is None
+ assert ServerInfo.from_api_base("api.host.com:8080") == ServerInfo(
+ "api.host.com", 8080
+ )
+ assert ServerInfo.from_api_base("https://h.com/v1") == ServerInfo("h.com", None)
+ # scheme present but empty netloc -> no hostname
+ assert ServerInfo.from_api_base("http:///v1") is None
+
+
+def test_service_span_data_from_payload():
+ class _Service:
+ value = "redis"
+
+ class _Payload:
+ service = _Service()
+ call_type = "async_set_cache"
+ error = None
+
+ data = ServiceSpanData.from_payload(_Payload())
+ assert data.service_name == "redis"
+ assert data.call_type == "async_set_cache"
+ assert data.error is None
+
+ class _FailPayload:
+ service = _Service()
+ call_type = "async_set_cache"
+ error = "boom"
+
+ failed = ServiceSpanData.from_payload(_FailPayload())
+ assert failed.error is not None
+ assert failed.error.message == "boom"
+
+
+# --- span name builders ----------------------------------------------------- #
+
+
+def test_name_builders():
+ assert (
+ proxy_request_span_name(ProxyRequestSpanData("POST", "/chat/completions"))
+ == "POST /chat/completions"
+ )
+ # "{service} {call_type}" so same-service calls stay distinguishable; the
+ # service name alone when there's no call type.
+ assert service_span_name(ServiceSpanData("redis", call_type="set")) == "redis set"
+ assert service_span_name(ServiceSpanData("redis")) == "redis"
+ assert (
+ guardrail_span_name(GuardrailSpanData("presidio"))
+ == "execute_guardrail presidio"
+ )
+
+
+# --- registry validator failure paths --------------------------------------- #
+
+
+def test_validate_registry_detects_role_mismatch():
+ bad = {SpanRole.LLM_CALL: SpanSpec(SpanRole.SERVICE, LiteLLMSpanKind.CLIENT, None)}
+ with pytest.raises(ValueError, match="mismatched role"):
+ validate_registry(bad)
+
+
+def test_validate_registry_detects_unknown_parent():
+ bad = {
+ SpanRole.LLM_CALL: SpanSpec(
+ SpanRole.LLM_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST
+ )
+ }
+ with pytest.raises(ValueError, match="unknown parent"):
+ validate_registry(bad)
+
+
+def test_validate_registry_detects_missing_roles():
+ partial = {
+ SpanRole.PROXY_REQUEST: SPAN_REGISTRY[SpanRole.PROXY_REQUEST],
+ }
+ with pytest.raises(ValueError, match="missing roles"):
+ validate_registry(partial)
+
+
+# --- mappers (full branch coverage) ----------------------------------------- #
+
+
+def _full_llm_call():
+ return LLMCallSpanData(
+ operation=GenAIOperation.CHAT,
+ provider="openai",
+ request_model="gpt-4o",
+ response_model="gpt-4o-2024",
+ response_id="resp_1",
+ request_params=LLMRequestParams(
+ temperature=0.7,
+ top_p=0.9,
+ top_k=40,
+ max_tokens=256,
+ frequency_penalty=0.1,
+ presence_penalty=0.2,
+ stop_sequences=("STOP",),
+ seed=42,
+ ),
+ usage=LLMUsage(input_tokens=10, output_tokens=5, total_tokens=15),
+ finish_reasons=("stop",),
+ error=None,
+ response_cost=0.002,
+ server=ServerInfo("api.openai.com", 443),
+ identity=RequestIdentity(call_id="c1"),
+ is_streaming=True,
+ )
+
+
+def test_genai_mapper_all_request_params():
+ attrs = GenAIMapper().map(_full_llm_call())
+ assert attrs[GenAI.REQUEST_TOP_P] == 0.9
+ assert attrs[GenAI.REQUEST_TOP_K] == 40
+ assert attrs[GenAI.REQUEST_MAX_TOKENS] == 256
+ assert attrs[GenAI.REQUEST_FREQUENCY_PENALTY] == 0.1
+ assert attrs[GenAI.REQUEST_PRESENCE_PENALTY] == 0.2
+ assert attrs[GenAI.REQUEST_STOP_SEQUENCES] == ["STOP"]
+ assert attrs[GenAI.REQUEST_SEED] == 42
+ assert attrs["server.port"] == 443
+
+
+def test_genai_mapper_guardrail_and_service():
+ from litellm.integrations.otel.model.semconv import LiteLLM
+
+ g = GenAIMapper().map(GuardrailSpanData("presidio", mode="pre"))
+ assert g[LiteLLM.GUARDRAIL_NAME] == "presidio"
+ assert g[LiteLLM.GUARDRAIL_MODE] == "pre"
+
+ # A datastore service (redis) also gets db.* semconv.
+ s = GenAIMapper().map(ServiceSpanData("redis", call_type="set"))
+ assert s[LiteLLM.SERVICE_NAME] == "redis"
+ assert s[LiteLLM.SERVICE_CALL_TYPE] == "set"
+ assert s["db.system.name"] == "redis"
+ assert s["db.operation.name"] == "set"
+
+ # An internal service (router) gets no db.* keys.
+ internal = GenAIMapper().map(ServiceSpanData("router", call_type="acompletion"))
+ assert internal[LiteLLM.SERVICE_NAME] == "router"
+ assert "db.system.name" not in internal
+
+
+def test_legacy_mapper_all_request_params():
+ attrs = LegacyMapper().map(_full_llm_call())
+ assert attrs["llm.top_k"] == 40
+ assert attrs["llm.frequency_penalty"] == 0.1
+ assert attrs["llm.presence_penalty"] == 0.2
+ assert attrs["llm.chat.stop_sequences"] == ["STOP"]
+ assert attrs["gen_ai.usage.total_tokens"] == 15
+
+
+def test_legacy_mapper_covers_service_with_v1_bare_keys():
+ """Service spans dual-emit V1's bare ``service``/``call_type``/``error`` keys."""
+ attrs = LegacyMapper().map(
+ ServiceSpanData("redis", call_type="set", event_metadata={"k": "v"}),
+ )
+ assert attrs["service"] == "redis"
+ assert attrs["call_type"] == "set"
+ assert attrs["k"] == "v" # event_metadata is stamped bare (V1 behavior)
+
+
+def test_legacy_mapper_skips_guardrail_role():
+ """Guardrail spans never had a V1 vocabulary; legacy mapper returns ``{}``."""
+ assert LegacyMapper().map(GuardrailSpanData("presidio")) == {}
+
+
+# --- metrics ---------------------------------------------------------------- #
+
+
+def test_create_genai_metrics_records():
+ reader = InMemoryMetricReader()
+ meter = MeterProvider(metric_readers=[reader]).get_meter("test")
+ metrics = create_genai_metrics(meter)
+ metrics.token_usage.record(10, {"x": "y"})
+ metrics.operation_duration.record(0.5, {"x": "y"})
+ data = reader.get_metrics_data()
+ assert data is not None
+
+
+# --- context + baggage helpers ---------------------------------------------- #
+
+
+def test_extract_traceparent():
+ valid = {"traceparent": "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"}
+ assert ctx_mod.extract_traceparent(valid) is not None
+ assert ctx_mod.extract_traceparent({"x": "y"}) is None
+
+
+def test_set_request_baggage_empty_returns_context():
+ assert ctx_mod.set_request_baggage({}) is not None
+
+
+def test_get_baggage_attributes_roundtrip():
+ ctx = ctx_mod.set_request_baggage({"litellm.team.id": "t1"})
+ assert ctx_mod.get_baggage_attributes(ctx)["litellm.team.id"] == "t1"
+
+
+# --- providers -------------------------------------------------------------- #
+
+
+def test_to_otel_span_kind_covers_all():
+ assert providers.to_otel_span_kind(LiteLLMSpanKind.SERVER) is SpanKind.SERVER
+ assert providers.to_otel_span_kind(LiteLLMSpanKind.CLIENT) is SpanKind.CLIENT
+ assert providers.to_otel_span_kind(LiteLLMSpanKind.INTERNAL) is SpanKind.INTERNAL
+ assert providers.to_otel_span_kind(LiteLLMSpanKind.PRODUCER) is SpanKind.PRODUCER
+ assert providers.to_otel_span_kind(LiteLLMSpanKind.CONSUMER) is SpanKind.CONSUMER
+
+
+def test_parse_headers():
+ assert providers.parse_headers(None) == {}
+ assert providers.parse_headers("a=1,b=2") == {"a": "1", "b": "2"}
+ assert providers.parse_headers("no-equals") == {}
+
+
+def test_otlp_traces_endpoint_normalization():
+ norm = providers._otlp_traces_endpoint
+ # A base endpoint gets the signal path appended (the common OTLP env shape).
+ assert norm("http://collector:4318") == "http://collector:4318/v1/traces"
+ assert norm("http://collector:4318/") == "http://collector:4318/v1/traces"
+ # An already-correct path is left intact.
+ assert norm("http://collector:4318/v1/traces") == "http://collector:4318/v1/traces"
+ # Another signal's path is rewritten to traces.
+ assert norm("http://collector:4318/v1/logs") == "http://collector:4318/v1/traces"
+ # Splunk's path is preserved; None passes through.
+ assert (
+ norm("https://x.splunk.com/v2/trace/otlp")
+ == "https://x.splunk.com/v2/trace/otlp"
+ )
+ assert norm(None) is None
+
+
+def test_build_span_exporter_variants():
+ assert isinstance(
+ providers.build_span_exporter(OpenTelemetryV2Config(exporter="console")),
+ ConsoleSpanExporter,
+ )
+ assert isinstance(
+ providers.build_span_exporter(OpenTelemetryV2Config(exporter="in_memory")),
+ InMemorySpanExporter,
+ )
+ assert isinstance(
+ providers.build_span_exporter(OpenTelemetryV2Config(exporter="unknown")),
+ ConsoleSpanExporter,
+ )
+ http_exporter = providers.build_span_exporter(
+ OpenTelemetryV2Config(exporter="otlp_http", endpoint="http://h:4318")
+ )
+ assert "OTLPSpanExporter" in type(http_exporter).__name__
+ grpc_exporter = providers.build_span_exporter(
+ OpenTelemetryV2Config(exporter="otlp_grpc", endpoint="http://h:4317")
+ )
+ assert "OTLPSpanExporter" in type(grpc_exporter).__name__
+
+
+def test_build_resource_includes_deployment_environment():
+ resource = providers.build_resource(
+ OpenTelemetryV2Config(service_name="svc", deployment_environment="prod")
+ )
+ assert resource.attributes["service.name"] == "svc"
+ assert resource.attributes["deployment.environment"] == "prod"
+
+
+def test_build_tracer_provider_processor_selection():
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ simple = providers.build_tracer_provider(cfg, exporter=InMemorySpanExporter())
+ batch = providers.build_tracer_provider(
+ cfg, exporter=ConsoleSpanExporter(), use_simple_processor=False
+ )
+ # both build without error; assert the requested processor type was used
+ simple_procs = simple._active_span_processor._span_processors
+ batch_procs = batch._active_span_processor._span_processors
+ assert any(isinstance(p, SimpleSpanProcessor) for p in simple_procs)
+ assert any(isinstance(p, BatchSpanProcessor) for p in batch_procs)
+
+
+def test_baggage_processor_lifecycle_noops():
+ proc = providers.LiteLLMBaggageSpanProcessor(allowed_keys=["litellm.team.id"])
+ # no-op lifecycle hooks must not raise
+ assert proc.on_end(None) is None # type: ignore[arg-type]
+ assert proc.shutdown() is None
+ assert proc.force_flush() is True
+
+
+def test_emitter_without_call_id_is_not_deduped():
+ from litellm.integrations.otel.emitter import SpanEmitter
+
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ provider, exporter = providers.in_memory_provider(cfg)
+ engine = SpanEmitter(providers.get_tracer(provider, "t"), cfg)
+ data = LLMCallSpanData(
+ operation=GenAIOperation.CHAT,
+ provider="openai",
+ request_model="gpt-4o",
+ response_model=None,
+ response_id=None,
+ request_params=LLMRequestParams(),
+ usage=LLMUsage(),
+ finish_reasons=(),
+ error=SpanError(error_type="X", message=None),
+ response_cost=None,
+ server=None,
+ identity=RequestIdentity(call_id=None),
+ )
+ engine.emit(SpanRole.LLM_CALL, data)
+ engine.emit(SpanRole.LLM_CALL, data) # no call_id -> not deduped
+ assert len(exporter.get_finished_spans()) == 2
+
+
+# --- service taxonomy: which calls become spans, and of what kind ----------- #
+
+
+def test_span_role_for_service_classifies_datastores_internal_and_metrics_only():
+ # Outbound datastores -> DB_CALL (CLIENT), with a db.system.
+ for name in (
+ "redis",
+ "postgres",
+ "batch_write_to_db",
+ "redis_daily_spend_update_queue",
+ ):
+ assert span_role_for_service(name) is SpanRole.DB_CALL
+ assert db_system(name) is not None
+ # Genuine internal work worth a span -> SERVICE (INTERNAL).
+ assert span_role_for_service("reset_budget_job") is SpanRole.SERVICE
+ assert db_system("reset_budget_job") is None
+ # Framework instrumentation that duplicates a gen-AI span (or gets a live
+ # phase span) -> None: never emitted as a service span.
+ for name in ("self", "router", "proxy_pre_call", "auth"):
+ assert span_role_for_service(name) is None
+
+
+# --- event_metadata sanitization -------------------------------------------- #
+
+
+def test_sanitize_event_metadata_drops_objects_dumps_and_secrets():
+ from litellm.integrations.otel.model.payloads import sanitize_event_metadata
+
+ clean = sanitize_event_metadata(
+ {
+ "table_name": "combined_view", # safe primitive -> kept
+ "count": 3, # primitive -> kept (stringified)
+ "function_kwargs": {"prisma_client": object()}, # denylisted key
+ "function_args": (1, 2), # denylisted key
+ "user_api_key_auth": "blob", # 'auth' substring -> dropped
+ "api_key": "sk-secret", # 'api_key' substring -> dropped
+ "set-cookie": "x", # 'cookie' substring -> dropped
+ "hidden_params": "headers...", # denylisted substring
+ "obj": object(), # non-primitive value -> dropped
+ "nested": {"x": 1}, # non-primitive value -> dropped
+ }
+ )
+ assert clean == {"table_name": "combined_view", "count": "3"}
+
+
+def test_sanitize_event_metadata_caps_value_length_and_handles_none():
+ from litellm.integrations.otel.model.payloads import sanitize_event_metadata
+
+ assert sanitize_event_metadata(None) == {}
+ big = sanitize_event_metadata({"k": "v" * 5000})
+ assert len(big["k"]) == 1024
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_config_baggage_parenting_guardrails.py b/tests/test_litellm/integrations/otel/test_otel_v2_config_baggage_parenting_guardrails.py
new file mode 100644
index 00000000000..dcaff3c911a
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_config_baggage_parenting_guardrails.py
@@ -0,0 +1,237 @@
+"""Behavior of three V2 OTel instrumentation areas:
+
+1. Baggage allowlists are configurable via env vars and config.yaml
+ (``callback_settings.otel.*``), not just hard-coded.
+2. Pass-through LLM-call spans nest under the proxy server span because they are
+ opened at the ``pre_call`` boundary in the request task (where the server span
+ is ambient) — no span threaded through metadata.
+3. Guardrail span data is built from the typed
+ ``StandardLoggingGuardrailInformation`` shape (provider-agnostic), not from
+ one provider's assumed field names.
+"""
+
+import asyncio
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from opentelemetry import trace # noqa: E402
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( # noqa: E402
+ InMemorySpanExporter,
+)
+
+from litellm.integrations.otel import LiteLLM, OpenTelemetryV2Config # noqa: E402
+from litellm.integrations.otel.plumbing import providers # noqa: E402
+from litellm.integrations.otel.model.baggage import ( # noqa: E402
+ BAGGAGE_PROMOTED_KEYS,
+ DEFAULT_BAGGAGE_METADATA_KEYS,
+)
+from litellm.integrations.otel.logger import OpenTelemetryV2 # noqa: E402
+from litellm.integrations.otel.model.payloads import GuardrailSpanData # noqa: E402
+from litellm.integrations.otel.model.spans import ( # noqa: E402
+ LITELLM_PROXY_REQUEST_SPAN_NAME,
+ SpanRole,
+)
+
+# --------------------------------------------------------------------------- #
+# Area 1 — baggage allowlists configurable
+# --------------------------------------------------------------------------- #
+
+
+def test_baggage_keys_default_when_unset():
+ cfg = OpenTelemetryV2Config()
+ assert cfg.baggage_promoted_keys == list(BAGGAGE_PROMOTED_KEYS)
+ assert cfg.baggage_metadata_keys == list(DEFAULT_BAGGAGE_METADATA_KEYS)
+
+
+def test_baggage_promoted_keys_from_env_csv(monkeypatch):
+ monkeypatch.setenv(
+ "LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS",
+ f"{LiteLLM.TEAM_ID}, {LiteLLM.KEY_HASH}",
+ )
+ monkeypatch.setenv(
+ "LITELLM_OTEL_BAGGAGE_METADATA_KEYS",
+ "user_api_key_user_id,requester_ip_address",
+ )
+ cfg = OpenTelemetryV2Config()
+ # Whitespace around comma-separated entries is trimmed.
+ assert cfg.baggage_promoted_keys == [LiteLLM.TEAM_ID, LiteLLM.KEY_HASH]
+ assert cfg.baggage_metadata_keys == [
+ "user_api_key_user_id",
+ "requester_ip_address",
+ ]
+
+
+def test_baggage_keys_from_config_yaml_kwargs():
+ """``callback_settings.otel.*`` reaches the config through the logger kwargs."""
+ logger = OpenTelemetryV2(
+ baggage_promoted_keys=[LiteLLM.TEAM_ALIAS],
+ baggage_metadata_keys=["user_api_key_alias"],
+ )
+ assert logger.config.baggage_promoted_keys == [LiteLLM.TEAM_ALIAS]
+ assert logger.config.baggage_metadata_keys == ["user_api_key_alias"]
+
+
+def test_baggage_processor_allowlist_uses_config_keys():
+ cfg = OpenTelemetryV2Config(
+ exporter="in_memory", baggage_promoted_keys=[LiteLLM.TEAM_ID]
+ )
+ provider, exporter = providers.in_memory_provider(cfg)
+ from litellm.integrations.otel.plumbing import context as ctx_mod
+ from litellm.integrations.otel.emitter import SpanEmitter
+ from litellm.integrations.otel.model.payloads import ServiceSpanData
+
+ engine = SpanEmitter(providers.get_tracer(provider, "t"), cfg)
+ ctx = ctx_mod.set_request_baggage({LiteLLM.TEAM_ID: "t1", LiteLLM.TEAM_ALIAS: "ta"})
+ engine.emit(SpanRole.SERVICE, ServiceSpanData("redis"), ctx)
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes.get(LiteLLM.TEAM_ID) == "t1"
+ assert LiteLLM.TEAM_ALIAS not in span.attributes # not in this allowlist
+
+
+# --------------------------------------------------------------------------- #
+# Area 2 — pass-through LLM span parents to the ambient server span
+# --------------------------------------------------------------------------- #
+
+
+def _logger():
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ exporter = InMemorySpanExporter()
+ tracer_provider = providers.build_tracer_provider(cfg, exporter=exporter)
+ return OpenTelemetryV2(config=cfg, tracer_provider=tracer_provider), exporter
+
+
+def _payload():
+ return {
+ "call_type": "pass_through_endpoint",
+ "custom_llm_provider": "openai",
+ "model": "gpt-4o",
+ "prompt_tokens": 1,
+ "completion_tokens": 1,
+ "total_tokens": 2,
+ "status": "success",
+ "litellm_call_id": "call_pt",
+ "metadata": {},
+ "hidden_params": {},
+ }
+
+
+def test_passthrough_llm_span_parents_to_ambient_server_span():
+ """Pass-through calls ``logging_obj.pre_call`` in the request task, where the
+ server span is the ambient context — so the LLM-call span is opened there and
+ parents to it natively, with no ``litellm_parent_otel_span`` threading. The
+ later (possibly detached) success callback only closes the already-parented
+ span, so it never becomes a separate root trace."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ kwargs = {
+ "standard_logging_object": _payload(),
+ "litellm_params": {"metadata": {}},
+ }
+ # pre_call runs in the request task (server span ambient); success closes it.
+ with trace.use_span(server, end_on_exit=False):
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent is not None
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+
+
+def test_llm_span_unaffected_by_phase_span_active_at_close():
+ """The LLM-call span's parent is captured at the ``pre_call`` boundary (under
+ the server span), so a phase span (e.g. ``auth``) that happens to be ambient
+ when the *close* callback fires can't re-parent it. This is the structural
+ successor to the old auth-failure-401 case where the LLM log nested under
+ ``auth``: the span is now born after auth, parented to the request root."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ kwargs = {
+ "standard_logging_object": _payload(),
+ "litellm_params": {"metadata": {}},
+ }
+ with trace.use_span(server, end_on_exit=False):
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ # A phase span is ambient when the close callback fires — must not re-parent.
+ phase = logger._emitter.start_span(SpanRole.SERVICE, "auth /v1/chat/completions")
+ with trace.use_span(phase, end_on_exit=False):
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ phase.end()
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+
+
+# --------------------------------------------------------------------------- #
+# Area 3 — typed, provider-agnostic guardrail span data
+# --------------------------------------------------------------------------- #
+
+
+def test_guardrail_mode_enum_normalized_to_value():
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ d = GuardrailSpanData.from_logging_entry(
+ {
+ "guardrail_name": "bedrock-guardrail",
+ "guardrail_mode": GuardrailEventHooks.pre_call,
+ "guardrail_status": "success",
+ }
+ )
+ # The enum *value* ("pre_call"), not "GuardrailEventHooks.pre_call".
+ assert d.mode == "pre_call"
+
+
+def test_guardrail_mode_list_of_enums_joined():
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ d = GuardrailSpanData.from_logging_entry(
+ {
+ "guardrail_name": "g",
+ "guardrail_mode": [
+ GuardrailEventHooks.pre_call,
+ GuardrailEventHooks.post_call,
+ ],
+ "guardrail_status": "success",
+ }
+ )
+ assert d.mode == "pre_call,post_call"
+
+
+def test_guardrail_typed_metadata_fields_mapped_to_span():
+ from litellm.integrations.otel.mappers.genai import GenAIMapper
+
+ d = GuardrailSpanData.from_logging_entry(
+ {
+ "guardrail_name": "eu-pii",
+ "guardrail_status": "success",
+ "guardrail_id": "gd-eu-pii-001",
+ "policy_template": "EU AI Act Article 5",
+ "detection_method": "presidio",
+ }
+ )
+ assert d.guardrail_id == "gd-eu-pii-001"
+ assert d.policy_template == "EU AI Act Article 5"
+ assert d.detection_method == "presidio"
+ attrs = GenAIMapper().map(d)
+ assert attrs[LiteLLM.GUARDRAIL_ID] == "gd-eu-pii-001"
+ assert attrs[LiteLLM.GUARDRAIL_POLICY_TEMPLATE] == "EU AI Act Article 5"
+ assert attrs[LiteLLM.GUARDRAIL_DETECTION_METHOD] == "presidio"
+
+
+def test_guardrail_ignores_non_canonical_provider_keys():
+ """Only canonical ``StandardLoggingGuardrailInformation`` keys are read; a
+ provider's ad-hoc bare ``name``/``status``/``mode`` keys are not assumed."""
+ d = GuardrailSpanData.from_logging_entry(
+ {"name": "bare", "status": "blocked", "mode": "pre"} # type: ignore[typeddict-unknown-key]
+ )
+ assert d.guardrail_name == "guardrail" # fell back to the default
+ assert d.status is None
+ assert d.mode is None
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py b/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py
new file mode 100644
index 00000000000..1150c2c51c3
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_dynamic.py
@@ -0,0 +1,131 @@
+"""Per-request multi-tenant credential routing (V1 parity)."""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+from opentelemetry.trace import NoOpTracer
+
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.presets import dynamic_otlp_headers
+from litellm.integrations.otel.plumbing.routing import TenantTracerCache
+
+
+def _cache(callback_name, exporters=None):
+ cfg = OpenTelemetryV2Config(exporters=exporters or [ExporterSpec(kind="in_memory")])
+ return TenantTracerCache(cfg, callback_name, "litellm")
+
+
+# --- header builders mirror the V1 construct_dynamic_otel_headers overrides --- #
+
+
+def test_arize_dynamic_headers():
+ headers = dynamic_otlp_headers(
+ "arize", {"arize_space_id": "S", "arize_api_key": "K"}
+ )
+ assert headers == {"arize-space-id": "S", "api_key": "K"}
+
+
+def test_arize_space_key_overrides_space_id():
+ headers = dynamic_otlp_headers(
+ "arize", {"arize_space_id": "S", "arize_space_key": "SK"}
+ )
+ assert headers == {"arize-space-id": "SK"}
+
+
+def test_langfuse_dynamic_headers_need_both_keys():
+ assert dynamic_otlp_headers("langfuse_otel", {"langfuse_public_key": "pk"}) is None
+ headers = dynamic_otlp_headers(
+ "langfuse_otel", {"langfuse_public_key": "pk", "langfuse_secret_key": "sk"}
+ )
+ assert headers is not None and "Authorization" in headers
+
+
+def test_weave_dynamic_headers():
+ headers = dynamic_otlp_headers(
+ "weave_otel", {"wandb_api_key": "w", "weave_project_id": "p"}
+ )
+ assert headers is not None
+ assert "Authorization" in headers and headers["project_id"] == "p"
+
+
+def test_non_participating_callbacks_have_no_routing():
+ # Phoenix subclasses the base in V1 (no override) → no dynamic routing.
+ assert dynamic_otlp_headers("arize_phoenix", {"arize_api_key": "K"}) is None
+ assert dynamic_otlp_headers("langtrace", {"arize_api_key": "K"}) is None
+ assert dynamic_otlp_headers(None, {"arize_api_key": "K"}) is None
+
+
+def test_no_dynamic_params_is_no_routing():
+ assert dynamic_otlp_headers("arize", None) is None
+ assert dynamic_otlp_headers("arize", {}) is None
+
+
+# --- TenantTracerCache routes + caches a TracerProvider per credential set --- #
+
+
+def test_provider_cached_per_credential_set():
+ cache = _cache("arize")
+ default = NoOpTracer()
+ creds_a = {"arize_space_id": "S", "arize_api_key": "K"}
+ creds_b = {"arize_space_id": "S2", "arize_api_key": "K2"}
+
+ cache.tracer_for(default, creds_a)
+ cache.tracer_for(default, creds_a) # same set → reuse, no new provider
+ assert len(cache._providers) == 1
+ cache.tracer_for(default, creds_b) # new set → new provider
+ assert len(cache._providers) == 2
+
+
+def test_provider_cache_is_bounded_and_evicts_lru(monkeypatch):
+ # The cache key derives from request-supplied dynamic credentials, so it
+ # must be bounded — an unbounded cache lets a caller spawn one provider (and
+ # its background exporter thread) per unique credential set. On overflow the
+ # least-recently-used provider is evicted and shut down.
+ from litellm.integrations.otel.plumbing import routing as routing_mod
+
+ monkeypatch.setattr(routing_mod, "_MAX_CACHED_PROVIDERS", 2)
+ shut_down = []
+ monkeypatch.setattr(
+ routing_mod, "_shutdown_provider", lambda p: shut_down.append(p)
+ )
+
+ cache = _cache("arize")
+ default = NoOpTracer()
+
+ def creds(space):
+ return {"arize_space_id": space, "arize_api_key": "K"}
+
+ cache.tracer_for(default, creds("1"))
+ cache.tracer_for(default, creds("2"))
+ cache.tracer_for(default, creds("1")) # touch "1" → "2" is now LRU
+ cache.tracer_for(default, creds("3")) # overflow → evict "2"
+
+ assert len(cache._providers) == 2
+ assert len(shut_down) == 1 # exactly the evicted provider was shut down
+
+
+def test_no_dynamic_params_uses_default_tracer():
+ cache = _cache("arize")
+ default = NoOpTracer()
+ assert cache.tracer_for(default, {}) is default
+ assert cache._providers == {}
+
+
+def test_non_participating_callback_uses_default_tracer():
+ cache = _cache("arize_phoenix")
+ default = NoOpTracer()
+ assert cache.tracer_for(default, {"arize_api_key": "K"}) is default
+ assert cache._providers == {}
+
+
+def test_dynamic_headers_applied_to_otlp_exporter_only():
+ cache = _cache(
+ "arize",
+ exporters=[ExporterSpec(kind="otlp_http"), ExporterSpec(kind="in_memory")],
+ )
+ new_cfg = cache._config_with_headers({"arize-space-id": "S", "api_key": "K"})
+ otlp, in_mem = new_cfg.exporters
+ assert otlp.headers == "arize-space-id=S,api_key=K"
+ assert in_mem.headers is None # console/in_memory left untouched
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py b/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py
new file mode 100644
index 00000000000..2dbedda1ab6
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py
@@ -0,0 +1,229 @@
+"""Golden tests for the OTel v2 engine: span shape, kinds, semconv attributes,
+legacy dual-emit, hierarchy, error status, and idempotency. Needs the OTel SDK."""
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from opentelemetry.trace import SpanKind # noqa: E402
+from opentelemetry.trace.status import StatusCode # noqa: E402
+
+from litellm.integrations.otel import ( # noqa: E402
+ GenAI,
+ LiteLLM,
+ OpenTelemetryV2Config,
+)
+from litellm.integrations.otel.plumbing import context as ctx_mod # noqa: E402
+from litellm.integrations.otel.plumbing import providers # noqa: E402
+from litellm.integrations.otel.emitter import SpanEmitter # noqa: E402
+from litellm.integrations.otel.model.payloads import ( # noqa: E402
+ GuardrailSpanData,
+ LLMCallSpanData,
+ ServiceSpanData,
+)
+from litellm.integrations.otel.model.spans import SPAN_REGISTRY, SpanRole # noqa: E402
+
+
+def _payload(**overrides):
+ payload = {
+ "call_type": "acompletion",
+ "custom_llm_provider": "openai",
+ "model": "gpt-4o",
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ "stream": False,
+ "model_parameters": {"temperature": 0.7, "max_tokens": 256, "top_k": 40},
+ "response": {
+ "id": "resp_1",
+ "model": "gpt-4o-2024",
+ "choices": [{"finish_reason": "stop"}],
+ },
+ "metadata": {"team_id": "t1", "team_alias": "team one"},
+ "api_base": "https://api.openai.com:443/v1",
+ "status": "success",
+ "litellm_call_id": "call_1",
+ "response_cost": 0.002,
+ "hidden_params": {},
+ }
+ payload.update(overrides)
+ return payload
+
+
+def _engine(legacy_compat=True):
+ cfg = OpenTelemetryV2Config(exporter="in_memory", legacy_compat=legacy_compat)
+ provider, exporter = providers.in_memory_provider(cfg)
+ tracer = providers.get_tracer(provider, "litellm-test")
+ return SpanEmitter(tracer, cfg), exporter
+
+
+def test_llm_call_span_golden():
+ engine, exporter = _engine()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ engine.emit(SpanRole.LLM_CALL, data)
+ (span,) = exporter.get_finished_spans()
+ assert span.name == "chat gpt-4o"
+ assert span.kind is SpanKind.CLIENT
+ a = span.attributes
+ assert a[GenAI.OPERATION_NAME] == "chat"
+ assert a[GenAI.PROVIDER_NAME] == "openai"
+ assert a[GenAI.REQUEST_MODEL] == "gpt-4o"
+ assert a[GenAI.RESPONSE_MODEL] == "gpt-4o-2024"
+ assert a[GenAI.RESPONSE_ID] == "resp_1"
+ assert a[GenAI.USAGE_INPUT_TOKENS] == 10
+ assert a[GenAI.USAGE_OUTPUT_TOKENS] == 5
+ assert a[GenAI.RESPONSE_FINISH_REASONS] == ("stop",)
+ assert a[GenAI.REQUEST_TEMPERATURE] == 0.7
+ assert a["server.address"] == "api.openai.com"
+ assert a[LiteLLM.CALL_ID] == "call_1"
+ assert a["litellm.cost.total"] == 0.002
+ # Success leaves status UNSET (semconv default), not forced OK.
+ assert span.status.status_code is StatusCode.UNSET
+
+
+def test_legacy_dual_emit_on():
+ engine, exporter = _engine(legacy_compat=True)
+ engine.emit(
+ SpanRole.LLM_CALL, LLMCallSpanData.from_standard_logging_payload(_payload())
+ )
+ (span,) = exporter.get_finished_spans()
+ # canonical AND legacy keys are both present
+ assert span.attributes[GenAI.USAGE_OUTPUT_TOKENS] == 5
+ assert span.attributes["gen_ai.usage.completion_tokens"] == 5
+ assert span.attributes["gen_ai.system"] == "openai"
+
+
+def test_legacy_dual_emit_off():
+ engine, exporter = _engine(legacy_compat=False)
+ engine.emit(
+ SpanRole.LLM_CALL, LLMCallSpanData.from_standard_logging_payload(_payload())
+ )
+ (span,) = exporter.get_finished_spans()
+ # canonical present, legacy absent
+ assert span.attributes[GenAI.USAGE_OUTPUT_TOKENS] == 5
+ assert "gen_ai.usage.completion_tokens" not in span.attributes
+ assert "gen_ai.system" not in span.attributes
+
+
+def test_error_span_sets_status_and_error_type():
+ engine, exporter = _engine()
+ payload = _payload(
+ status="failure",
+ error_information={"error_class": "RateLimitError", "error_message": "429"},
+ )
+ engine.emit(
+ SpanRole.LLM_CALL, LLMCallSpanData.from_standard_logging_payload(payload)
+ )
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code is StatusCode.ERROR
+ assert span.attributes["error.type"] == "RateLimitError"
+
+
+def test_hierarchy_and_kinds_match_registry():
+ engine, exporter = _engine()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ root = engine.start_span(SpanRole.PROXY_REQUEST, "POST /chat/completions")
+ root_ctx = ctx_mod.context_from_span(root)
+ engine.emit(SpanRole.LLM_CALL, data, parent_context=root_ctx)
+ engine.emit(
+ SpanRole.GUARDRAIL, GuardrailSpanData("presidio", status="success"), root_ctx
+ )
+ # An outbound datastore call (DB_CALL) and an internal service call differ in
+ # span kind; both are named "{service} {call_type}".
+ engine.emit(SpanRole.DB_CALL, ServiceSpanData("redis", call_type="set"), root_ctx)
+ engine.emit(
+ SpanRole.SERVICE, ServiceSpanData("router", call_type="acompletion"), root_ctx
+ )
+ root.end()
+
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ root_id = root.get_span_context().span_id
+ assert by_name["chat gpt-4o"].parent.span_id == root_id
+ assert by_name["execute_guardrail presidio"].parent.span_id == root_id
+ assert by_name["redis set"].parent.span_id == root_id
+ assert by_name["router acompletion"].parent.span_id == root_id
+ # kinds come straight from the registry
+ assert by_name["chat gpt-4o"].kind is SpanKind.CLIENT
+ assert by_name["execute_guardrail presidio"].kind is SpanKind.INTERNAL
+ assert by_name["redis set"].kind is SpanKind.CLIENT
+ assert by_name["router acompletion"].kind is SpanKind.INTERNAL
+ assert by_name["POST /chat/completions"].kind is SpanKind.SERVER
+
+
+def test_idempotent_dual_fire():
+ engine, exporter = _engine()
+ data = LLMCallSpanData.from_standard_logging_payload(_payload())
+ first = engine.emit(SpanRole.LLM_CALL, data)
+ second = engine.emit(SpanRole.LLM_CALL, data) # same call_id -> deduped
+ assert first is not None
+ assert second is None
+ assert len(exporter.get_finished_spans()) == 1
+
+
+def test_dedup_cache_is_bounded(monkeypatch):
+ """The dedup cache only needs to coalesce one request's sync+async fire, so
+ it is a bounded LRU — every unique call_id must not accumulate forever on a
+ long-running proxy."""
+ from litellm.integrations.otel import emitter as emitter_mod
+
+ monkeypatch.setattr(emitter_mod, "_DEDUP_CACHE_MAX", 3)
+ engine, _ = _engine()
+ for i in range(10):
+ engine.emit(
+ SpanRole.LLM_CALL,
+ LLMCallSpanData.from_standard_logging_payload(
+ _payload(litellm_call_id=f"call_{i}")
+ ),
+ )
+ assert len(engine._emitted) <= 3
+
+
+def test_service_error_span():
+ from litellm.integrations.otel.model.payloads import SpanError
+
+ engine, exporter = _engine()
+ engine.emit(
+ SpanRole.SERVICE,
+ ServiceSpanData(
+ "postgres", call_type="query", error=SpanError("DBError", "boom")
+ ),
+ )
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code is StatusCode.ERROR
+ assert span.attributes["error.type"] == "DBError"
+ assert span.attributes[LiteLLM.SERVICE_NAME] == "postgres"
+
+
+def test_guardrail_block_span_is_error_and_carries_verdict():
+ engine, exporter = _engine()
+ data = GuardrailSpanData.from_logging_entry(
+ {
+ "guardrail_name": "openai-moderation",
+ "guardrail_mode": "pre_call",
+ "guardrail_status": "guardrail_intervened",
+ "guardrail_provider": "openai",
+ "guardrail_response": {"violated_categories": ["violence"]},
+ "masked_entity_count": {"EMAIL": 2},
+ }
+ )
+ engine.emit(SpanRole.GUARDRAIL, data)
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code is StatusCode.ERROR # intervention → ERROR
+ a = span.attributes
+ assert a[LiteLLM.GUARDRAIL_STATUS] == "guardrail_intervened"
+ assert a[LiteLLM.GUARDRAIL_PROVIDER] == "openai"
+ assert "violence" in a[LiteLLM.GUARDRAIL_RESPONSE] # the verdict rides the span
+ assert a[LiteLLM.GUARDRAIL_MASKED_ENTITY_COUNT] == 2
+
+
+def test_guardrail_success_span_is_unset():
+ """On success the status is left UNSET (semconv default) — not forced OK."""
+ engine, exporter = _engine()
+ engine.emit(
+ SpanRole.GUARDRAIL,
+ GuardrailSpanData.from_logging_entry(
+ {"guardrail_name": "g", "guardrail_status": "success"}
+ ),
+ )
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code is StatusCode.UNSET
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py
new file mode 100644
index 00000000000..c1cde55c58e
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py
@@ -0,0 +1,1122 @@
+"""Tests for the V2 ``OpenTelemetryV2`` CustomLogger adapter.
+
+Exercises the callback surface the existing call sites use: the LLM-call span
+opened at the ``pre_call`` boundary and closed at async success/failure, service
+hooks, proxy SERVER span lifecycle (start + setters), parent-context resolution
+(ambient context), and Baggage promotion onto child spans.
+"""
+
+import asyncio
+import contextlib
+from datetime import datetime, timezone
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from opentelemetry import trace # noqa: E402
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( # noqa: E402
+ InMemorySpanExporter,
+)
+from opentelemetry.trace import SpanKind # noqa: E402
+from opentelemetry.trace.status import StatusCode # noqa: E402
+
+from litellm.integrations.otel import ( # noqa: E402
+ GenAI,
+ LiteLLM,
+ OpenTelemetryV2Config,
+)
+from litellm.integrations.otel.plumbing import providers # noqa: E402
+from litellm.integrations.otel.plumbing.context import (
+ set_request_root_span,
+) # noqa: E402
+from litellm.integrations.otel.logger import OpenTelemetryV2 # noqa: E402
+from litellm.integrations.otel.model.spans import ( # noqa: E402
+ LITELLM_PROXY_REQUEST_SPAN_NAME,
+ SpanRole,
+)
+from litellm.integrations.otel.model.utils import to_ns, to_seconds # noqa: E402
+
+# --------------------------------------------------------------------------- #
+# Fixtures
+# --------------------------------------------------------------------------- #
+
+
[email protected](autouse=True)
+def _reset_request_root_span():
+ """Clear the request-root-span anchor around every test.
+
+ In production each request runs in its own asyncio task whose context is a
+ fresh copy, so the anchor never leaks between requests. The test process
+ shares one context, so reset it explicitly to keep tests order-independent.
+ """
+ from litellm.integrations.otel.plumbing import context as _otel_context
+
+ _otel_context._request_root_span.set(None)
+ yield
+ _otel_context._request_root_span.set(None)
+
+
+def _payload(**overrides):
+ payload = {
+ "call_type": "acompletion",
+ "custom_llm_provider": "openai",
+ "model": "gpt-4o",
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ "stream": False,
+ "model_parameters": {"temperature": 0.7, "max_tokens": 256},
+ "response": {
+ "id": "resp_1",
+ "model": "gpt-4o-2024",
+ "choices": [{"finish_reason": "stop"}],
+ },
+ "metadata": {
+ "team_id": "t1",
+ "team_alias": "team one",
+ "user_api_key_hash": "hsh",
+ },
+ "api_base": "https://api.openai.com:443/v1",
+ "status": "success",
+ "litellm_call_id": "call_1",
+ "response_cost": 0.002,
+ "hidden_params": {},
+ }
+ payload.update(overrides)
+ return payload
+
+
+def _kwargs(payload=None):
+ return {
+ # ``litellm_call_id`` (here carried inside the payload) correlates the
+ # pre_call boundary with the close callback — the carrier is keyed by it.
+ "standard_logging_object": payload if payload is not None else _payload(),
+ "litellm_params": {"metadata": {}},
+ }
+
+
+def _logger(legacy_compat=True):
+ cfg = OpenTelemetryV2Config(exporter="in_memory", legacy_compat=legacy_compat)
+ exporter = InMemorySpanExporter()
+ tracer_provider = providers.build_tracer_provider(cfg, exporter=exporter)
+ return OpenTelemetryV2(config=cfg, tracer_provider=tracer_provider), exporter
+
+
+def _emit_llm(logger, kwargs=None, *, ambient=None, fail=False):
+ """Drive the real boundary flow: open at ``pre_call`` then close at the async
+ callback. ``ambient``, if given, is the span that is the active OTel context
+ while ``pre_call`` runs (the server span) so the LLM span parents to it."""
+ if kwargs is None:
+ kwargs = _kwargs()
+ payload = kwargs.get("standard_logging_object") or {}
+ with (
+ trace.use_span(ambient, end_on_exit=False)
+ if ambient is not None
+ else contextlib.nullcontext()
+ ):
+ logger.log_pre_api_call(model=payload.get("model"), messages=[], kwargs=kwargs)
+ hook = logger.async_log_failure_event if fail else logger.async_log_success_event
+ asyncio.run(hook(kwargs, None, None, None))
+ return kwargs
+
+
+# --------------------------------------------------------------------------- #
+# Time helpers
+# --------------------------------------------------------------------------- #
+
+
+def test_to_ns_handles_datetime_and_float():
+ dt = datetime(2026, 5, 26, 12, 0, 0, tzinfo=timezone.utc)
+ assert to_ns(dt) == int(dt.timestamp() * 1e9)
+ assert to_ns(1.5) == 1_500_000_000
+ assert to_ns(None) is None
+ assert to_ns(True) is None # bool is rejected — not a real epoch value
+
+
+def test_to_seconds_parses_string_formats():
+ assert to_seconds("2026-05-26 12:00:00.123") is not None
+ assert to_seconds("2026-05-26 12:00:00") is not None
+ assert to_seconds("nonsense") is None
+ assert to_seconds(None) is None
+ assert to_seconds(1.5) == 1.5
+
+
+# --------------------------------------------------------------------------- #
+# LLM-call callbacks
+# --------------------------------------------------------------------------- #
+
+
+def test_async_log_success_event_emits_llm_call_span():
+ logger, exporter = _logger()
+ _emit_llm(logger)
+ (span,) = exporter.get_finished_spans()
+ assert span.name == "chat gpt-4o"
+ assert span.kind is SpanKind.CLIENT
+ assert span.attributes[GenAI.OPERATION_NAME] == "chat"
+ assert span.attributes[GenAI.REQUEST_MODEL] == "gpt-4o"
+ assert span.attributes[LiteLLM.CALL_ID] == "call_1"
+ # Success leaves status UNSET (semconv default), not forced OK.
+ assert span.status.status_code is StatusCode.UNSET
+
+
+def test_async_log_failure_event_marks_error_status():
+ logger, exporter = _logger()
+ payload = _payload(
+ status="failure",
+ error_information={"error_class": "RateLimitError", "error_message": "429"},
+ )
+ _emit_llm(logger, _kwargs(payload=payload), fail=True)
+ (span,) = exporter.get_finished_spans()
+ assert span.status.status_code is StatusCode.ERROR
+ assert span.attributes["error.type"] == "RateLimitError"
+
+
+def test_sync_log_event_is_noop():
+ """V2 closes the span async-only; the sync callback runs out-of-context, so
+ it no-ops (the span stays open on the carrier until the async callback)."""
+ logger, exporter = _logger()
+ kwargs = _kwargs()
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ logger.log_success_event(kwargs, None, None, None)
+ logger.log_failure_event(kwargs, None, None, None)
+ assert exporter.get_finished_spans() == ()
+
+
+def test_missing_standard_logging_object_is_noop():
+ """No carrier (``pre_call`` never ran) → the callback emits nothing."""
+ logger, exporter = _logger()
+ asyncio.run(
+ logger.async_log_success_event({"litellm_params": {}}, None, None, None)
+ )
+ assert exporter.get_finished_spans() == ()
+
+
+def test_no_span_when_pre_call_never_ran():
+ """A request rejected before the upstream call — at the auth/budget gate, or
+ blocked by a pre-call guardrail — never reaches ``pre_call``, so there is no
+ carrier and the failure log produces no phantom CLIENT span. This replaces the
+ old post-hoc heuristics: "did pre_call run?" is the only signal needed."""
+ logger, exporter = _logger()
+ payload = _payload(
+ status="failure",
+ error_information={"error_class": "ProxyException", "error_code": "401"},
+ )
+ # No log_pre_api_call: the call never started.
+ asyncio.run(
+ logger.async_log_failure_event(_kwargs(payload=payload), None, None, None)
+ )
+ assert exporter.get_finished_spans() == () # no phantom LLM span
+
+
+def test_real_llm_failure_still_emitted():
+ """A genuine LLM failure: ``pre_call`` ran (the call was attempted), so the
+ CLIENT span is opened at the boundary and closed ERROR."""
+ logger, exporter = _logger()
+ payload = _payload(
+ status="failure",
+ error_information={"error_class": "RateLimitError", "error_code": "429"},
+ )
+ _emit_llm(logger, _kwargs(payload=payload), fail=True)
+ (span,) = exporter.get_finished_spans()
+ assert span.name == "chat gpt-4o"
+ assert span.status.status_code is StatusCode.ERROR
+
+
+def test_idempotent_on_repeat_callback():
+ """The carrier is the dedup: once the async callback closes the span and
+ clears the carrier, a second callback firing emits nothing."""
+ logger, exporter = _logger()
+ kwargs = _kwargs()
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ assert len(exporter.get_finished_spans()) == 1
+
+
+def test_pre_call_idempotent_keeps_first_span():
+ """A retried call may re-enter ``pre_call`` with the same call id; the first
+ span (with the true start time) is kept, not replaced."""
+ logger, _ = _logger()
+ kwargs = _kwargs()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ with trace.use_span(server, end_on_exit=False):
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ first = logger._open_llm_calls["call_1"]
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ second = logger._open_llm_calls["call_1"]
+ server.end()
+ assert first is second # not overwritten
+
+
+# --------------------------------------------------------------------------- #
+# Parent resolution — ambient context at the boundary (no metadata threading)
+# --------------------------------------------------------------------------- #
+
+
+def test_llm_span_parents_to_ambient_server_span():
+ """The span is opened at ``pre_call`` while the server span is the active
+ context, so it nests under it natively (no ``litellm_parent_otel_span``)."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ _emit_llm(logger, ambient=server)
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent is not None
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+
+
+def test_llm_span_is_root_without_ambient_server_span():
+ """No server span at ``pre_call`` → creation is deferred and the span is a
+ root of its own trace (the SDK / no-proxy path)."""
+ logger, exporter = _logger()
+ _emit_llm(logger)
+ (span,) = exporter.get_finished_spans()
+ assert span.parent is None # standalone (no proxy server span) → root
+
+
+# --------------------------------------------------------------------------- #
+# Explicit request-root-span anchor — request-level spans (LLM call, guardrail)
+# parent to the captured server span, NOT to whatever span is momentarily
+# active. Regression cover for the two ambient-only failure modes:
+# * auth: the LLM/guardrail span must not nest under the live ``auth`` span;
+# * pass-through: the span must not orphan when closed off the request task.
+# --------------------------------------------------------------------------- #
+
+
+def test_llm_span_anchors_to_root_even_inside_active_phase_span():
+ """Bug 1: a synthetic error log can fire ``pre_call`` while the ``auth`` phase
+ span is the *active* context. The LLM span must still parent to the request
+ root (the server span), never to the auth span it happens to be nested in."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ set_request_root_span(server)
+ kwargs = _kwargs()
+ # ``auth`` phase span is the active span when pre_call + close run.
+ with trace.use_span(server, end_on_exit=False):
+ with logger.start_phase_span("auth /chat/completions"):
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ auth_span = by_name["auth /chat/completions"]
+ # Parented to the server root, NOT the auth span it was emitted inside.
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+ assert llm_span.parent.span_id != auth_span.get_span_context().span_id
+
+
+def test_live_llm_span_anchors_to_root_with_no_active_span():
+ """Bug 2 (pass-through), live path: even with no span active at ``pre_call``,
+ the anchor is a recordable parent, so the span opens live under the server root
+ instead of orphaning — and the detached close just ends it, in the right
+ trace."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ set_request_root_span(server)
+ kwargs = _kwargs()
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ assert logger._open_llm_calls["call_1"].span is not None # live, via anchor
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+ assert llm_span.context.trace_id == server.get_span_context().trace_id
+
+
+def test_deferred_llm_span_reads_anchor_at_close():
+ """Bug 2, deferred path: when the anchor isn't visible at ``pre_call`` (a
+ sync-only provider's thread-pool call) the span defers; the close — back on the
+ request task, anchor visible — must parent it to the root, not orphan it."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ kwargs = _kwargs()
+ # pre_call with NO anchor and no active span → deferred.
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ assert logger._open_llm_calls["call_1"].span is None # deferred
+ # Anchor becomes visible at close (worker copied the request task's context).
+ set_request_root_span(server)
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+ assert llm_span.context.trace_id == server.get_span_context().trace_id
+
+
+def test_synthetic_error_log_produces_no_llm_span():
+ """Bug 1 root cause: a proxy-gate error log (auth/rate-limit) fires ``pre_call``
+ for a request that never reached a provider. Tagged with
+ ``LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL``, it must open no carrier and emit no
+ LLM-call span — even though the failure callback also fires."""
+ from litellm.constants import LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL
+
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ set_request_root_span(server)
+ payload = _payload(
+ status="failure",
+ error_information={"error_class": "ProxyException", "error_code": "401"},
+ )
+ kwargs = _kwargs(payload=payload)
+ kwargs[LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL] = True
+ with trace.use_span(server, end_on_exit=False):
+ with logger.start_phase_span("auth /chat/completions"):
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ assert "call_1" not in logger._open_llm_calls # no carrier opened
+ asyncio.run(logger.async_log_failure_event(kwargs, None, None, None))
+ server.end()
+ names = {s.name for s in exporter.get_finished_spans()}
+ assert "chat gpt-4o" not in names # no phantom LLM span
+ assert "auth /chat/completions" in names # auth span itself still recorded
+
+
+def test_create_request_started_span_captures_anchor():
+ """``create_litellm_proxy_request_started_span`` doubles as the anchor capture
+ point: the active server span becomes the request root for later spans."""
+ from litellm.integrations.otel.plumbing.context import request_root_span
+
+ logger, _ = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ with trace.use_span(server, end_on_exit=False):
+ returned = logger.create_litellm_proxy_request_started_span(
+ start_time=datetime.now(), headers=None
+ )
+ server.end()
+ assert returned.get_span_context().span_id == server.get_span_context().span_id
+ assert (
+ request_root_span().get_span_context().span_id
+ == server.get_span_context().span_id
+ )
+
+
+def test_guardrail_span_anchors_to_root_inside_active_phase_span():
+ """A guardrail emitted from a failure hook that runs inside the live ``auth``
+ span must still be a sibling of the LLM call under the request root, not a
+ child of auth."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ set_request_root_span(server)
+ request_data = {
+ "metadata": {
+ "standard_logging_guardrail_information": {
+ "guardrail_name": "my_guard",
+ "guardrail_status": "success",
+ }
+ }
+ }
+ with trace.use_span(server, end_on_exit=False):
+ with logger.start_phase_span("auth /chat/completions"):
+ logger._emit_guardrail_spans(request_data)
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ guard = by_name["execute_guardrail my_guard"]
+ auth_span = by_name["auth /chat/completions"]
+ assert guard.parent.span_id == server.get_span_context().span_id
+ assert guard.parent.span_id != auth_span.get_span_context().span_id
+
+
+def test_real_logging_pre_call_opens_span_end_to_end():
+ """Regression guard: a real ``LiteLLMLoggingObj.pre_call`` must fire
+ ``log_pre_api_call`` on the V2 logger (via ``litellm.input_callback``), so the
+ boundary span is opened and then closed by the success callback. If the logger
+ is not wired into ``input_callback``, no span is produced at all."""
+ import litellm
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+ logger, exporter = _logger()
+ # Register exactly this logger as the (only) input callback pre_call iterates.
+ monkeypatch = pytest.MonkeyPatch()
+ monkeypatch.setattr(litellm, "input_callback", [logger], raising=False)
+ try:
+ logging_obj = Logging(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="acompletion",
+ start_time=datetime.now(),
+ litellm_call_id="call_e2e",
+ function_id="fn",
+ )
+ # The wrapper always runs this before pre_call — it's what seeds
+ # ``litellm_params`` and ``litellm_call_id`` into ``model_call_details``
+ # (the call id is how the close callback correlates back to this span).
+ logging_obj.update_environment_variables(
+ litellm_params={"metadata": {}},
+ optional_params={},
+ model="gpt-4o",
+ )
+ # pre_call fires log_pre_api_call → opens the boundary span on the obj.
+ logging_obj.pre_call(input="hi", api_key="sk-test")
+ # The success callback closes it, reading the typed payload.
+ logging_obj.model_call_details["standard_logging_object"] = _payload(
+ litellm_call_id="call_e2e"
+ )
+ asyncio.run(
+ logger.async_log_success_event(
+ logging_obj.model_call_details, None, None, None
+ )
+ )
+ finally:
+ monkeypatch.undo()
+ (span,) = exporter.get_finished_spans()
+ assert span.name == "chat gpt-4o"
+
+
+def test_deferred_span_parents_to_ambient_at_close():
+ """When ``pre_call`` runs off the request task (a sync-only provider driven
+ through a thread pool, where contextvars don't follow), no ambient parent is
+ visible there, so span creation is deferred. The async callback — whose worker
+ context was copied from the request task and so still carries the server span —
+ then creates it parented to that server span, not as an orphan root."""
+ logger, exporter = _logger()
+ kwargs = _kwargs()
+ # pre_call with NO ambient span (the thread-pool case) → deferred.
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ # The close callback runs with the (worker-copied) server span ambient.
+ with trace.use_span(server, end_on_exit=False):
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ llm_span = by_name["chat gpt-4o"]
+ assert llm_span.parent.span_id == server.get_span_context().span_id
+
+
+# Inbound ``traceparent`` propagation is now the FastAPI instrumentor's job
+# (see proxy_server's startup mount + ``test_otel_v2_mount``), not the logger's.
+
+
+# --------------------------------------------------------------------------- #
+# Baggage promotion (LLM call writes identity into baggage so child spans
+# inherit team/key/model attrs).
+# --------------------------------------------------------------------------- #
+
+
+def test_baggage_identity_promoted_onto_llm_call():
+ """On the deferred (SDK / no-proxy) path the callback seeds identity Baggage
+ from the payload so the span is still labeled with team/key. (On the proxy
+ boundary path identity rides in from auth-seeded ambient Baggage instead.)"""
+ logger, exporter = _logger()
+ _emit_llm(logger)
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes[LiteLLM.TEAM_ID] == "t1"
+ assert span.attributes[LiteLLM.TEAM_ALIAS] == "team one"
+ assert span.attributes[GenAI.REQUEST_MODEL] == "gpt-4o"
+
+
+class _Auth:
+ """Stub matching the ``UserAPIKeyAuth`` fields the logger reads."""
+
+ team_id = "t1"
+ team_alias = "team one"
+ team_metadata = {"tier": "gold", "cost_center": "42"}
+ api_key = "hash1"
+ user_id = "u1"
+ org_id = None
+ key_alias = "k1"
+ end_user_id = None
+
+
+def test_provider_model_and_team_metadata_on_real_boundary_flow():
+ """End-to-end on the proxy boundary path (the gap a pure-emitter test misses):
+
+ - ``litellm.team.metadata`` is known at auth, so it rides identity Baggage
+ seeded there onto EVERY span (server + LLM call).
+ - ``litellm.provider.model`` is only known once routing picks a deployment
+ (in the payload at close), AFTER the auth seed and AFTER the boundary span
+ starts — so it can't ride Baggage. It's stamped directly on the LLM-call
+ span by the mapper, and is absent from the server span (which starts first).
+ """
+ import json
+
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ payload = _payload(
+ hidden_params={"litellm_model_name": "azure/my-deployment"},
+ metadata={
+ "user_api_key_team_id": "t1",
+ "user_api_key_team_alias": "team one",
+ "user_api_key_hash": "hash1",
+ "user_api_key_team_metadata": {"tier": "gold", "cost_center": "42"},
+ },
+ )
+ kwargs = _kwargs(payload=payload)
+ with trace.use_span(server, end_on_exit=False):
+ # auth boundary: seed identity (provider model unknown here)
+ logger.seed_request_identity(_Auth(), model="gpt-4o")
+ # pre_call boundary opens the LLM span; success closes it from the payload
+ logger.log_pre_api_call(model="gpt-4o", messages=[], kwargs=kwargs)
+ asyncio.run(logger.async_log_success_event(kwargs, None, None, None))
+ server.end()
+
+ spans = {s.name: s for s in exporter.get_finished_spans()}
+ llm = spans["chat gpt-4o"]
+ srv = spans[LITELLM_PROXY_REQUEST_SPAN_NAME]
+ # provider model: on the LLM call span, NOT the server span
+ assert llm.attributes[LiteLLM.PROVIDER_MODEL] == "azure/my-deployment"
+ assert LiteLLM.PROVIDER_MODEL not in srv.attributes
+ # team metadata: on every span, JSON-serialized
+ expected = {"tier": "gold", "cost_center": "42"}
+ assert json.loads(llm.attributes[LiteLLM.TEAM_METADATA]) == expected
+ assert json.loads(srv.attributes[LiteLLM.TEAM_METADATA]) == expected
+
+
+def test_pre_call_hook_seeds_baggage_onto_server_and_child_spans():
+ """The pre-call hook seeds identity Baggage in the request context so the
+ server span (stamped directly) AND later child spans (service here, via the
+ Baggage processor) carry identity — not just the LLM-call span."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+
+ async def _flow():
+ # pre-call seeds baggage + stamps the active server span
+ await logger.async_pre_call_hook(
+ _Auth(), None, {"model": "gpt-4o"}, "completion"
+ )
+ # a later service call (same task) must inherit the identity
+ await logger.async_service_success_hook(
+ payload=_ServicePayload("redis", "set"), parent_otel_span=server
+ )
+
+ with trace.use_span(server, end_on_exit=False):
+ asyncio.run(_flow())
+ server.end()
+
+ spans = {s.name: s for s in exporter.get_finished_spans()}
+ redis = spans["redis set"]
+ assert redis.attributes[LiteLLM.TEAM_ID] == "t1"
+ assert redis.attributes[LiteLLM.KEY_HASH] == "hash1"
+ assert redis.attributes[f"{LiteLLM.METADATA_PREFIX}user_api_key_user_id"] == "u1"
+ srv = spans[LITELLM_PROXY_REQUEST_SPAN_NAME]
+ assert (
+ srv.attributes[LiteLLM.TEAM_ID] == "t1"
+ ) # stamped directly on the server span
+ assert srv.attributes[f"{LiteLLM.METADATA_PREFIX}user_api_key_user_id"] == "u1"
+
+
+# --------------------------------------------------------------------------- #
+# Service hooks (Phase 3)
+# --------------------------------------------------------------------------- #
+
+
+class _Service:
+ """Stub matching ``ServiceTypes(str, Enum)``."""
+
+ def __init__(self, value):
+ self.value = value
+
+
+class _ServicePayload:
+ def __init__(self, service="redis", call_type="set", error=None):
+ self.service = _Service(service)
+ self.call_type = call_type
+ self.error = error
+
+
+def _service_parent(logger):
+ """Helper: a live PROXY_REQUEST span to parent service spans under."""
+ return logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+
+
+def test_async_service_success_hook_emits_service_span():
+ logger, exporter = _logger()
+ parent = _service_parent(logger)
+ try:
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload("redis", "set"),
+ parent_otel_span=parent,
+ event_metadata={"key1": "val1"},
+ )
+ )
+ finally:
+ parent.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ # Name disambiguates calls to the same service; redis is an outbound
+ # datastore call, so it's a CLIENT span with db.* semconv.
+ span = by_name["redis set"]
+ assert span.kind is SpanKind.CLIENT
+ assert span.attributes["db.system.name"] == "redis"
+ assert span.attributes["db.operation.name"] == "set"
+ assert span.attributes[LiteLLM.SERVICE_NAME] == "redis"
+ assert span.attributes[LiteLLM.SERVICE_CALL_TYPE] == "set"
+ # Canonical (V2) namespaced metadata key
+ assert span.attributes[f"{LiteLLM.METADATA_PREFIX}key1"] == "val1"
+ # V1 bare key (legacy dual-emit)
+ assert span.attributes["key1"] == "val1"
+ assert span.attributes["service"] == "redis" # V1 bare key
+ assert span.attributes["call_type"] == "set" # V1 bare key
+ # Success leaves status UNSET (semconv default), not forced OK.
+ assert span.status.status_code is StatusCode.UNSET
+
+
+def test_async_service_failure_hook_marks_error_status():
+ logger, exporter = _logger()
+ parent = _service_parent(logger)
+ try:
+ asyncio.run(
+ logger.async_service_failure_hook(
+ payload=_ServicePayload("postgres", "query"),
+ error="boom",
+ parent_otel_span=parent,
+ )
+ )
+ finally:
+ parent.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ span = by_name["postgres query"]
+ assert span.kind is SpanKind.CLIENT
+ assert span.attributes["db.system.name"] == "postgresql"
+ assert span.status.status_code is StatusCode.ERROR
+ # Without an explicit error_type from the payload, V2 stamps the fallback.
+ assert span.attributes["error.type"] == "error"
+ assert span.attributes[LiteLLM.SERVICE_NAME] == "postgres"
+
+
+def test_async_service_failure_hook_preserves_payload_error_over_override():
+ """When the payload itself carries an error, that takes precedence over the override."""
+ logger, exporter = _logger()
+ parent = _service_parent(logger)
+ try:
+ asyncio.run(
+ logger.async_service_failure_hook(
+ payload=_ServicePayload("postgres", "query", error="db-down"),
+ error="override-only-used-when-payload-clean",
+ parent_otel_span=parent,
+ )
+ )
+ finally:
+ parent.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ span = by_name["postgres query"]
+ assert span.status.status_code is StatusCode.ERROR
+ assert "db-down" in (span.status.description or "")
+
+
+def test_metrics_only_ping_without_timing_or_parent_is_noop():
+ """A success with no timing and no parent is a prometheus-only ping (the
+ per-request ``self`` latency hook, in-memory queue gauges) — not a traceable
+ operation, so no span is emitted."""
+ logger, exporter = _logger()
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload(), parent_otel_span=None
+ )
+ )
+ assert exporter.get_finished_spans() == ()
+
+
+def test_background_service_call_with_timing_emits_root_span():
+ """A background datastore call (no request → no parent) but with real timing
+ still emits — as its own root trace — instead of being dropped."""
+ logger, exporter = _logger()
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload("postgres", "query"),
+ parent_otel_span=None,
+ start_time=1.0,
+ end_time=2.0,
+ )
+ )
+ spans = exporter.get_finished_spans()
+ assert [s.name for s in spans] == ["postgres query"]
+ # No parent → it's a root span of its own trace.
+ assert spans[0].parent is None
+ assert spans[0].kind is SpanKind.CLIENT
+
+
+def test_internal_service_call_is_internal_kind_without_db_attrs():
+ """A genuine internal service (background job) is an INTERNAL span, no db.*."""
+ logger, exporter = _logger()
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload("reset_budget_job", "reset_budget"),
+ parent_otel_span=None,
+ start_time=1.0,
+ end_time=2.0,
+ )
+ )
+ span = exporter.get_finished_spans()[0]
+ assert span.name == "reset_budget_job reset_budget"
+ assert span.kind is SpanKind.INTERNAL
+ assert "db.system.name" not in span.attributes
+ assert span.attributes[LiteLLM.SERVICE_NAME] == "reset_budget_job"
+
+
+def test_metrics_only_services_emit_no_span():
+ """self / router / proxy_pre_call / auth duplicate gen-AI spans or get a live
+ phase span — they are metrics-only and must not produce a service span."""
+ for service in ("self", "router", "proxy_pre_call", "auth"):
+ logger, exporter = _logger()
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload(service, "x"),
+ parent_otel_span=None,
+ start_time=1.0,
+ end_time=2.0,
+ )
+ )
+ assert exporter.get_finished_spans() == (), f"{service} should emit no span"
+
+
+def test_service_span_inherits_parent_when_provided():
+ logger, exporter = _logger()
+ parent = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ try:
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload(), parent_otel_span=parent
+ )
+ )
+ finally:
+ parent.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ assert (
+ by_name["redis set"].parent.span_id
+ == by_name[LITELLM_PROXY_REQUEST_SPAN_NAME].get_span_context().span_id
+ )
+
+
+def test_service_span_prefers_ambient_context_over_threaded_parent():
+ """Service/DB spans parent to the active (ambient) span when there is one, so
+ they nest under whatever phase is active (e.g. a DB lookup under the live
+ ``auth`` span). The threaded ``parent_otel_span`` is only a fallback for when
+ ambient has no live span (a background service call)."""
+ logger, exporter = _logger()
+ ambient = logger._emitter.start_span(SpanRole.LLM_CALL, "chat gpt-4o")
+ threaded = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ try:
+ with trace.use_span(ambient, end_on_exit=False):
+ asyncio.run(
+ logger.async_service_success_hook(
+ payload=_ServicePayload("redis", "get"),
+ parent_otel_span=threaded,
+ )
+ )
+ finally:
+ ambient.end()
+ threaded.end()
+ by_name = {s.name: s for s in exporter.get_finished_spans()}
+ assert by_name["redis get"].parent.span_id == ambient.get_span_context().span_id
+
+
+# --------------------------------------------------------------------------- #
+# Proxy SERVER span lifecycle
+# --------------------------------------------------------------------------- #
+
+
+def test_create_proxy_request_started_span_returns_ambient_span():
+ """V2 doesn't create a server span (the instrumentor does), but it returns
+ the active server span so the proxy can thread it as the service-span parent
+ — service logging only fires the OTel hook when that parent is non-None."""
+ logger, exporter = _logger()
+ # No ambient recordable span → None (and creates nothing).
+ assert (
+ logger.create_litellm_proxy_request_started_span(
+ start_time=datetime.now(timezone.utc), headers={"traceparent": "x"}
+ )
+ is None
+ )
+ assert exporter.get_finished_spans() == ()
+ # With an active server span, return it (do NOT create a new one).
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ with trace.use_span(server, end_on_exit=False):
+ got = logger.create_litellm_proxy_request_started_span(
+ start_time=datetime.now(timezone.utc), headers=None
+ )
+ server.end()
+ assert got is server
+
+
+# --------------------------------------------------------------------------- #
+# Constructor / proxy global guard
+# --------------------------------------------------------------------------- #
+
+
+def test_constructor_accepts_v1_compatible_kwargs():
+ """Mirrors V1's positional shape — config / callback_name / providers / **kwargs."""
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ tp = providers.build_tracer_provider(cfg)
+ logger = OpenTelemetryV2(
+ config=cfg,
+ callback_name="otel",
+ tracer_provider=tp,
+ logger_provider=None,
+ meter_provider=None,
+ turn_off_message_logging=True,
+ )
+ assert logger.callback_name == "otel"
+ assert logger.turn_off_message_logging is True
+ assert logger.tracer is not None
+
+
+def test_default_config_reads_env(monkeypatch):
+ """No explicit config → reads env (exporter=console by default)."""
+ monkeypatch.delenv("OTEL_EXPORTER", raising=False)
+ monkeypatch.delenv("OTEL_EXPORTER_OTLP_PROTOCOL", raising=False)
+ logger = OpenTelemetryV2(
+ tracer_provider=providers.build_tracer_provider(
+ OpenTelemetryV2Config(exporter="in_memory")
+ )
+ )
+ assert logger.config.exporter == "console"
+
+
+def test_proxy_global_first_registered_wins(monkeypatch):
+ """``_init_otel_logger_on_litellm_proxy`` claims the global only when empty."""
+ proxy_server = pytest.importorskip("litellm.proxy.proxy_server")
+ monkeypatch.setattr(proxy_server, "open_telemetry_logger", None, raising=False)
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ tp = providers.build_tracer_provider(cfg)
+
+ first = OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ assert proxy_server.open_telemetry_logger is first
+
+ second = OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ # Global still points at the first registration.
+ assert proxy_server.open_telemetry_logger is first
+ assert second is not first
+
+
+def test_registers_into_litellm_service_callback(monkeypatch):
+ """The logger must mutate ``litellm.service_callback`` in place. An empty
+ list is falsy, so a ``getattr(..) or []`` would append to a throwaway local
+ and service spans (Redis, …) would silently never fire on this logger.
+ """
+ import litellm
+
+ pytest.importorskip("litellm.proxy.proxy_server")
+ monkeypatch.setattr(litellm, "service_callback", [], raising=False)
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ tp = providers.build_tracer_provider(cfg)
+
+ first = OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ assert first in litellm.service_callback
+
+ # A second OTel logger sees one is already registered and does not duplicate.
+ OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ otel_registrations = [
+ cb
+ for cb in litellm.service_callback
+ if cb.__class__.__module__.startswith("litellm.integrations.otel")
+ ]
+ assert len(otel_registrations) == 1
+
+
+def test_registers_into_litellm_input_callback(monkeypatch):
+ """The logger must land in ``litellm.input_callback`` — the list
+ ``Logging.pre_call`` iterates to fire ``log_pre_api_call``. Without this the
+ boundary hook never runs and the gen-AI span is never opened (the span goes
+ completely missing). Deduped like ``service_callback``.
+ """
+ import litellm
+
+ pytest.importorskip("litellm.proxy.proxy_server")
+ monkeypatch.setattr(litellm, "input_callback", [], raising=False)
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ tp = providers.build_tracer_provider(cfg)
+
+ first = OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ assert first in litellm.input_callback
+
+ OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ otel_registrations = [
+ cb
+ for cb in litellm.input_callback
+ if cb.__class__.__module__.startswith("litellm.integrations.otel")
+ ]
+ assert len(otel_registrations) == 1
+
+
+def test_registers_into_async_success_and_failure_callbacks(monkeypatch):
+ """The logger must self-register into ``litellm._async_success_callback`` and
+ ``litellm._async_failure_callback`` — the lists ``Logging.async_success_handler``
+ / ``async_failure_handler`` iterate to fire ``async_log_success_event`` /
+ ``async_log_failure_event``, where the boundary span is *closed*.
+
+ ``input_callback`` opens the span; these lists close it. Relying only on the
+ proxy's ``litellm.callbacks`` fan-out to populate them is not enough: a logger
+ that reached litellm via ``service_callback`` / ``success_callback`` (or was
+ created after the fan-out ran) is absent from ``litellm.callbacks``, so on a
+ pass-through request (which never runs ``function_setup``) the span opens and is
+ never ended — the gen-AI span leaks and never exports, while DB/service spans
+ still show up. Self-registration here guarantees every open has a close.
+ """
+ import litellm
+
+ pytest.importorskip("litellm.proxy.proxy_server")
+ monkeypatch.setattr(litellm, "_async_success_callback", [], raising=False)
+ monkeypatch.setattr(litellm, "_async_failure_callback", [], raising=False)
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ tp = providers.build_tracer_provider(cfg)
+
+ first = OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ assert first in litellm._async_success_callback
+ assert first in litellm._async_failure_callback
+
+ # Deduped — a second otel logger doesn't double up the close hook.
+ OpenTelemetryV2(config=cfg, tracer_provider=tp)
+ for callback_list in (
+ litellm._async_success_callback,
+ litellm._async_failure_callback,
+ ):
+ otel_registrations = [
+ cb
+ for cb in callback_list
+ if cb.__class__.__module__.startswith("litellm.integrations.otel")
+ ]
+ assert len(otel_registrations) == 1
+
+
+def test_boundary_span_closes_without_proxy_fanout(monkeypatch):
+ """A span opened at ``pre_call`` is still closed and exported when the logger is
+ registered ONLY via its own ``__init__`` (no ``litellm.callbacks`` fan-out, as
+ happens for a logger configured through ``service_callback``) and the close runs
+ through the real ``async_success_handler``.
+
+ Self-registration must wire both ends: the open hook (``input_callback``) and the
+ close hook (``_async_success_callback``). If only the open end were wired the span
+ would leak — opened but never closed, never exported.
+ """
+ import litellm
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+ pytest.importorskip("litellm.proxy.proxy_server")
+ monkeypatch.setattr(litellm, "input_callback", [], raising=False)
+ monkeypatch.setattr(litellm, "_async_success_callback", [], raising=False)
+ monkeypatch.setattr(litellm, "_async_failure_callback", [], raising=False)
+ # Crucially: the logger is NOT in litellm.callbacks, so the proxy fan-out would
+ # never reach it. Only __init__ self-registration wires the open + close hooks.
+ monkeypatch.setattr(litellm, "callbacks", [], raising=False)
+
+ logger, exporter = _logger()
+ logging_obj = Logging(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="pass_through_endpoint",
+ start_time=datetime.now(),
+ litellm_call_id="pt_leak",
+ function_id="fn",
+ )
+ logging_obj.update_environment_variables(
+ litellm_params={"metadata": {}},
+ optional_params={},
+ model="gpt-4o",
+ )
+ logging_obj.model_call_details["litellm_call_id"] = "pt_leak"
+ # pre_call opens the boundary span (logger is in input_callback).
+ logging_obj.pre_call(input="hi", api_key="")
+ assert "pt_leak" in logger._open_llm_calls
+ # The close runs through the real async_success_handler, which iterates
+ # _async_success_callback — where the logger self-registered.
+ logging_obj.model_call_details["standard_logging_object"] = _payload(
+ litellm_call_id="pt_leak"
+ )
+ asyncio.run(
+ logging_obj.async_success_handler(
+ result=None, start_time=datetime.now(), end_time=datetime.now()
+ )
+ )
+ assert "pt_leak" not in logger._open_llm_calls # carrier closed, not leaked
+ (span,) = exporter.get_finished_spans()
+ assert span.name == "chat gpt-4o"
+
+
+# --------------------------------------------------------------------------- #
+# Guardrail span placement: request-level parent + real execution timestamps
+# --------------------------------------------------------------------------- #
+
+
+def _guardrail_request_data(*, start, end):
+ return {
+ "metadata": {
+ "standard_logging_guardrail_information": [
+ {
+ "guardrail_name": "openai-moderation",
+ "guardrail_mode": "pre_call",
+ "guardrail_status": "success",
+ "start_time": start,
+ "end_time": end,
+ "duration": end - start,
+ }
+ ],
+ }
+ }
+
+
+def test_guardrail_span_parents_to_ambient_server_span():
+ """The post-call hook runs in the request task with the server span ambient,
+ so the guardrail span parents to it natively — no span threaded through
+ metadata. (Auth already finished, so no phase span is active.)"""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ data = _guardrail_request_data(start=1000.0, end=1000.5)
+ try:
+ with trace.use_span(server, end_on_exit=False):
+ asyncio.run(
+ logger.async_post_call_success_hook(data, _Auth(), {"ok": True})
+ )
+ finally:
+ server.end()
+ g = {s.name: s for s in exporter.get_finished_spans()}[
+ "execute_guardrail openai-moderation"
+ ]
+ assert g.parent.span_id == server.get_span_context().span_id
+
+
+def test_guardrail_span_uses_actual_execution_timestamps():
+ """A pre_call guardrail's span carries its real start/end (from the logging
+ entry), so it sorts before the LLM call instead of at post-call emit time."""
+ logger, exporter = _logger()
+ server = logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME
+ )
+ data = _guardrail_request_data(start=1700.0, end=1700.25)
+ try:
+ with trace.use_span(server, end_on_exit=False):
+ asyncio.run(
+ logger.async_post_call_success_hook(data, _Auth(), {"ok": True})
+ )
+ finally:
+ server.end()
+ g = {s.name: s for s in exporter.get_finished_spans()}[
+ "execute_guardrail openai-moderation"
+ ]
+ assert g.start_time == to_ns(1700.0)
+ assert g.end_time == to_ns(1700.25)
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_mount.py b/tests/test_litellm/integrations/otel/test_otel_v2_mount.py
new file mode 100644
index 00000000000..956d8c53cee
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_mount.py
@@ -0,0 +1,151 @@
+"""V2 entrypoint: the FastAPI instrumentation proxy_server mounts at app creation
+(gated by LITELLM_OTEL_V2). The mount logic lives in
+``litellm.integrations.otel.mount``; this exercises both that module's public
+surface and the server-span + shared-provider behavior it produces.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+pytest.importorskip("opentelemetry")
+pytest.importorskip("opentelemetry.instrumentation.fastapi")
+fastapi = pytest.importorskip("fastapi")
+
+from fastapi.testclient import TestClient # noqa: E402
+from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor # noqa: E402
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor # noqa: E402
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( # noqa: E402
+ InMemorySpanExporter,
+)
+from opentelemetry.trace import SpanKind # noqa: E402
+
+from litellm.integrations.otel.model.config import ( # noqa: E402
+ OpenTelemetryV2Config,
+ is_otel_v2_enabled,
+)
+from litellm.integrations.otel.logger import OpenTelemetryV2 # noqa: E402
+from litellm.integrations.otel.mount import ( # noqa: E402
+ PASSTHROUGH_PREFIXES,
+ _passthrough_span_name_hook,
+ instrument_fastapi_app,
+)
+
+
+class _FakeSpan:
+ """Minimal recording span capturing what the hook writes."""
+
+ def __init__(self, recording=True):
+ self._recording = recording
+ self.name = None
+ self.attributes = {}
+
+ def is_recording(self):
+ return self._recording
+
+ def update_name(self, name):
+ self.name = name
+
+ def set_attribute(self, key, value):
+ self.attributes[key] = value
+
+
+def _instrumented_app():
+ """Mirror proxy_server's startup mount: a logger builds the shared provider,
+ and the FastAPI instrumentor is attached to it."""
+ app = fastapi.FastAPI()
+
+ @app.get("/ping")
+ def ping():
+ return {"ok": True}
+
+ logger = OpenTelemetryV2(config=OpenTelemetryV2Config(exporter="in_memory"))
+ FastAPIInstrumentor.instrument_app(app, tracer_provider=logger._tracer_provider)
+ return app, logger
+
+
+def test_gate_toggles_with_env(monkeypatch):
+ """The startup mount is guarded by this flag."""
+ monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)
+ assert is_otel_v2_enabled() is False
+ monkeypatch.setenv("LITELLM_OTEL_V2", "1")
+ assert is_otel_v2_enabled() is True
+
+
+def test_instrumented_app_emits_server_span():
+ app, logger = _instrumented_app()
+ exporter = InMemorySpanExporter()
+ logger._tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ TestClient(app).get("/ping")
+
+ server_spans = [
+ s for s in exporter.get_finished_spans() if s.kind is SpanKind.SERVER
+ ]
+ assert server_spans, "FastAPI instrumentor should emit a SERVER span per request"
+ attrs = server_spans[0].attributes or {}
+ assert any("route" in k or "method" in k for k in attrs)
+
+
+def test_logger_and_instrumentor_share_provider():
+ """Gen-ai spans (logger) and server spans (instrumentor) write to one provider."""
+ _, logger = _instrumented_app()
+ assert logger._emitter._tracer is logger.tracer
+
+
+def test_passthrough_hook_renames_catch_all_span():
+ """A passthrough route gets its span renamed to the real request path."""
+ span = _FakeSpan()
+ _passthrough_span_name_hook(
+ span, {"path": "/openai/v1/chat/completions", "method": "POST"}
+ )
+ assert span.name == "POST /openai/v1/chat/completions"
+ assert span.attributes["http.route"] == "/openai/v1/chat/completions"
+
+
+def test_passthrough_hook_leaves_non_passthrough_route_unchanged():
+ """A normal route keeps its low-cardinality template name (hook no-ops)."""
+ span = _FakeSpan()
+ _passthrough_span_name_hook(span, {"path": "/v1/models", "method": "GET"})
+ assert span.name is None
+ assert "http.route" not in span.attributes
+
+
+def test_passthrough_hook_ignores_non_recording_span():
+ span = _FakeSpan(recording=False)
+ _passthrough_span_name_hook(
+ span, {"path": "/openai/v1/chat/completions", "method": "POST"}
+ )
+ assert span.name is None
+
+
+def test_known_passthrough_prefixes_present():
+ """Guard the prefix set against accidental edits."""
+ assert {"openai", "anthropic", "vertex_ai", "bedrock"} <= PASSTHROUGH_PREFIXES
+
+
+def test_instrument_fastapi_app_noop_when_gate_off(monkeypatch):
+ """With the gate off the mount is a no-op — no instrumentation attached."""
+ monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)
+ app = fastapi.FastAPI()
+ instrument_fastapi_app(app)
+ assert getattr(app, "_is_instrumented_by_opentelemetry", False) is False
+
+
+def test_instrument_fastapi_app_attaches_when_gate_on(monkeypatch):
+ """With the gate on the FastAPI app is instrumented for server spans."""
+ monkeypatch.setenv("LITELLM_OTEL_V2", "1")
+ app = fastapi.FastAPI()
+
+ @app.get("/ping")
+ def ping():
+ return {"ok": True}
+
+ instrument_fastapi_app(app)
+ try:
+ assert getattr(app, "_is_instrumented_by_opentelemetry", False) is True
+ finally:
+ FastAPIInstrumentor.uninstrument_app(app)
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_multibackend.py b/tests/test_litellm/integrations/otel/test_otel_v2_multibackend.py
new file mode 100644
index 00000000000..e879766c5c7
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_multibackend.py
@@ -0,0 +1,89 @@
+"""Multi-backend fan-out: one TracerProvider, *N* SpanProcessors.
+
+V1 needed a separate ``TracerProvider`` per integration to avoid stepping on
+the global. V2 attaches a ``SpanProcessor`` per exporter to the *same*
+provider, so the same trace ID lights up every backend — no duplicate spans,
+no per-integration provider caches.
+"""
+
+import pytest
+
+pytest.importorskip("opentelemetry")
+
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
+ InMemorySpanExporter,
+)
+
+from litellm.integrations.otel.model.config import ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.plumbing.providers import build_tracer_provider
+
+
+def test_two_exporters_receive_the_same_span():
+ """A single ``span.end()`` lands in BOTH exporters with the same span ID."""
+ exporter_a = InMemorySpanExporter()
+ exporter_b = InMemorySpanExporter()
+ cfg = OpenTelemetryV2Config(
+ exporters=[
+ ExporterSpec(kind="in_memory"),
+ ExporterSpec(kind="in_memory"),
+ ]
+ )
+ # Override the auto-built exporters with our test ones by swapping
+ # processors after construction (the test's purpose is to exercise the
+ # multi-processor wiring, not to negotiate the in-memory pipe).
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+ provider = build_tracer_provider(cfg)
+ # Clear out any auto-built export processors and attach our pair.
+ while provider._active_span_processor._span_processors:
+ provider._active_span_processor._span_processors = (
+ provider._active_span_processor._span_processors[:-1]
+ )
+ provider.add_span_processor(SimpleSpanProcessor(exporter_a))
+ provider.add_span_processor(SimpleSpanProcessor(exporter_b))
+
+ tracer = provider.get_tracer("test")
+ span = tracer.start_span("multi-backend")
+ span.set_attribute("test.marker", "yes")
+ span.end()
+
+ spans_a = exporter_a.get_finished_spans()
+ spans_b = exporter_b.get_finished_spans()
+ assert len(spans_a) == 1
+ assert len(spans_b) == 1
+ assert spans_a[0].context.span_id == spans_b[0].context.span_id
+
+
+def test_resource_attributes_apply_to_all_exporters():
+ """``resource_attributes`` flow through the shared TracerProvider."""
+ cfg = OpenTelemetryV2Config(
+ exporters=[ExporterSpec(kind="in_memory")],
+ resource_attributes={"openinference.project.name": "phoenix-test"},
+ )
+ provider = build_tracer_provider(cfg)
+ assert provider.resource.attributes["openinference.project.name"] == "phoenix-test"
+
+
+def test_config_normalizer_inserts_genai_first():
+ """The validator pins ``genai`` at the head + appends ``legacy`` on legacy_compat."""
+ cfg = OpenTelemetryV2Config(mapper_names=["openinference", "langfuse"])
+ assert cfg.mapper_names[0] == "genai"
+ assert "openinference" in cfg.mapper_names
+ assert "langfuse" in cfg.mapper_names
+ assert cfg.mapper_names[-1] == "legacy" # legacy_compat=True by default
+
+
+def test_config_normalizer_no_legacy_when_compat_off():
+ cfg = OpenTelemetryV2Config(legacy_compat=False, mapper_names=["openinference"])
+ assert "legacy" not in cfg.mapper_names
+ assert cfg.mapper_names[0] == "genai"
+
+
+def test_config_folds_legacy_exporter_triple_into_exporters_list():
+ """When ``exporters`` is empty, the validator folds the legacy single triple."""
+ cfg = OpenTelemetryV2Config(
+ exporter="otlp_http", endpoint="https://api.example.com", headers="k=v"
+ )
+ assert len(cfg.exporters) == 1
+ assert cfg.exporters[0].kind == "otlp_http"
+ assert cfg.exporters[0].endpoint == "https://api.example.com"
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_presets.py b/tests/test_litellm/integrations/otel/test_otel_v2_presets.py
new file mode 100644
index 00000000000..6b9fa820cdf
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_presets.py
@@ -0,0 +1,122 @@
+"""Preset tests. Focused on the AgentOps JWT fetch, which must never block the
+event loop: the preset does no network I/O, and a custom exporter mints the JWT
+lazily on its first export (in the BatchSpanProcessor worker thread)."""
+
+import httpx
+import pytest
+
+from litellm.integrations.otel.plumbing import providers
+from litellm.integrations.otel.model.config import ExporterSpec
+from litellm.integrations.otel.presets import agentops as agentops_mod
+from litellm.integrations.otel.presets.agentops import (
+ _AGENTOPS_ENDPOINT,
+ _AGENTOPS_EXPORTER_KIND,
+ _build_agentops_exporter,
+ _fetch_agentops_jwt,
+ agentops_preset,
+)
+
+
+def test_agentops_preset_does_no_network_io(monkeypatch):
+ # The preset must not fetch the JWT at build time — that would block the
+ # event loop during callback construction. It only describes the exporter.
+ def _boom(*_a, **_k):
+ raise AssertionError("agentops_preset must not fetch the JWT eagerly")
+
+ monkeypatch.setattr(agentops_mod, "_fetch_agentops_jwt", _boom)
+ monkeypatch.setenv("AGENTOPS_API_KEY", "ak-123")
+ cfg = agentops_preset()
+ agentops_exporters = [e for e in cfg.exporters if e.kind == _AGENTOPS_EXPORTER_KIND]
+ assert len(agentops_exporters) == 1
+ spec = agentops_exporters[0]
+ assert spec.endpoint == _AGENTOPS_ENDPOINT
+ assert spec.options == {"api_key": "ak-123"} # carried to the lazy exporter
+
+
+def test_agentops_preset_without_key_omits_options(monkeypatch):
+ monkeypatch.delenv("AGENTOPS_API_KEY", raising=False)
+ cfg = agentops_preset()
+ spec = next(e for e in cfg.exporters if e.kind == _AGENTOPS_EXPORTER_KIND)
+ assert spec.options is None
+
+
+def test_agentops_exporter_factory_is_registered():
+ assert _AGENTOPS_EXPORTER_KIND in providers._EXPORTER_FACTORIES
+
+
+def test_agentops_exporter_mints_jwt_lazily(monkeypatch):
+ pytest.importorskip("opentelemetry.exporter.otlp.proto.http.trace_exporter")
+ monkeypatch.setattr(
+ agentops_mod, "_fetch_agentops_jwt", lambda _k: {"token": "jwt-xyz"}
+ )
+ spec = ExporterSpec(
+ kind=_AGENTOPS_EXPORTER_KIND,
+ endpoint=_AGENTOPS_ENDPOINT,
+ options={"api_key": "ak"},
+ )
+ exporter = _build_agentops_exporter(spec)
+
+ # No auth header until the first export triggers the (off-loop) fetch.
+ assert "Authorization" not in exporter._session.headers
+ exporter._ensure_authenticated()
+ assert exporter._session.headers["Authorization"] == "Bearer jwt-xyz"
+
+ # Cached: a second resolution does not re-fetch.
+ calls = []
+ monkeypatch.setattr(
+ agentops_mod,
+ "_fetch_agentops_jwt",
+ lambda k: calls.append(k) or {"token": "again"},
+ )
+ exporter._ensure_authenticated()
+ assert calls == []
+
+
+def test_agentops_exporter_tolerates_fetch_failure(monkeypatch):
+ pytest.importorskip("opentelemetry.exporter.otlp.proto.http.trace_exporter")
+
+ def _raise(_k):
+ raise RuntimeError("auth down")
+
+ monkeypatch.setattr(agentops_mod, "_fetch_agentops_jwt", _raise)
+ exporter = _build_agentops_exporter(
+ ExporterSpec(
+ kind=_AGENTOPS_EXPORTER_KIND,
+ endpoint=_AGENTOPS_ENDPOINT,
+ options={"api_key": "ak"},
+ )
+ )
+ exporter._ensure_authenticated() # must not raise
+ assert "Authorization" not in exporter._session.headers
+
+
+def test_fetch_jwt_uses_owned_client_not_shared_pool(monkeypatch):
+ """The fetch owns a short-lived client and closes it, rather than closing
+ the process-wide cached ``_get_httpx_client`` pool shared by other callers."""
+ closed = {"n": 0}
+
+ class _FakeResponse:
+ status_code = 200
+
+ def json(self):
+ return {"token": "jwt-123"}
+
+ class _FakeClient:
+ def __init__(self, *_a, **_k):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_a):
+ closed["n"] += 1
+
+ def post(self, *_a, **_k):
+ return _FakeResponse()
+
+ monkeypatch.setattr(httpx, "Client", _FakeClient)
+ assert not hasattr(agentops_mod, "_get_httpx_client")
+
+ result = _fetch_agentops_jwt("api-key")
+ assert result == {"token": "jwt-123"}
+ assert closed["n"] == 1 # the owned client was closed
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py
new file mode 100644
index 00000000000..c4e80145c70
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py
@@ -0,0 +1,454 @@
+"""Tests for the OTel v2 sources of truth: span registry, semconv keys, config,
+and the typed StandardLoggingPayload adapter. These need no OTel SDK."""
+
+import pytest
+
+from litellm.integrations.otel import (
+ BAGGAGE_PROMOTED_KEYS,
+ DB,
+ Error,
+ GenAI,
+ GenAIOperation,
+ HTTP,
+ LiteLLM,
+ OpenTelemetryV2Config,
+ Server,
+ is_otel_v2_enabled,
+ promoted_baggage,
+ resolve_operation,
+ resolve_provider,
+)
+from litellm.integrations.otel.model import spans as spans_mod
+from litellm.integrations.otel.model.payloads import LLMCallSpanData, RequestIdentity
+from litellm.integrations.otel.model.spans import (
+ SPAN_REGISTRY,
+ LiteLLMSpanKind,
+ SpanRole,
+ child_roles,
+ root_roles,
+ validate_registry,
+)
+
+
+def _sample_payload(**overrides):
+ payload = {
+ "call_type": "acompletion",
+ "custom_llm_provider": "openai",
+ "model": "gpt-4o",
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ "stream": False,
+ "model_parameters": {
+ "temperature": 0.7,
+ "max_tokens": 256,
+ "top_p": 0.9,
+ "top_k": 40,
+ "frequency_penalty": 0.1,
+ "presence_penalty": 0.2,
+ "stop": ["STOP"],
+ "seed": 42,
+ },
+ "response": {
+ "id": "resp_1",
+ "model": "gpt-4o-2024",
+ "choices": [{"finish_reason": "stop"}],
+ },
+ "metadata": {
+ "team_id": "t1",
+ "team_alias": "team one",
+ "user_api_key_hash": "hsh",
+ "user_api_key_org_id": "org1",
+ },
+ "api_base": "https://api.openai.com:443/v1",
+ "status": "success",
+ "litellm_call_id": "call_1",
+ "end_user": "u1",
+ "response_cost": 0.002,
+ "hidden_params": {},
+ }
+ payload.update(overrides)
+ return payload
+
+
+# --- span registry (source of truth #2) ------------------------------------- #
+
+
+def test_registry_validates_and_is_complete():
+ validate_registry() # raises on inconsistency
+ assert set(SPAN_REGISTRY) == set(SpanRole)
+
+
+def test_registry_parent_integrity_no_orphans():
+ for role, spec in SPAN_REGISTRY.items():
+ assert spec.role is role
+ if spec.parent is not None:
+ assert spec.parent in SPAN_REGISTRY
+
+
+def test_registry_hierarchy_shape():
+ assert set(root_roles()) == {SpanRole.PROXY_REQUEST}
+ # Guardrails parent to the request span, not the LLM call: a pre-call
+ # guardrail runs before the LLM call exists, so it's a sibling of it.
+ assert set(child_roles(SpanRole.PROXY_REQUEST)) == {
+ SpanRole.LLM_CALL,
+ SpanRole.GUARDRAIL,
+ SpanRole.DB_CALL,
+ SpanRole.SERVICE,
+ }
+ assert SPAN_REGISTRY[SpanRole.LLM_CALL].kind is LiteLLMSpanKind.CLIENT
+ assert SPAN_REGISTRY[SpanRole.PROXY_REQUEST].kind is LiteLLMSpanKind.SERVER
+ assert SPAN_REGISTRY[SpanRole.GUARDRAIL].parent is SpanRole.PROXY_REQUEST
+ # An outbound datastore call is a CLIENT span; an internal service is INTERNAL.
+ assert SPAN_REGISTRY[SpanRole.DB_CALL].kind is LiteLLMSpanKind.CLIENT
+ assert SPAN_REGISTRY[SpanRole.SERVICE].kind is LiteLLMSpanKind.INTERNAL
+
+
+def test_llm_call_span_name():
+ data = LLMCallSpanData.from_standard_logging_payload(_sample_payload())
+ assert spans_mod.llm_call_span_name(data) == "chat gpt-4o"
+
+
+# --- semconv (source of truth #1) ------------------------------------------- #
+
+
+def _all_constants(cls):
+ return {
+ getattr(cls, name)
+ for name in vars(cls)
+ if not name.startswith("__") and isinstance(getattr(cls, name), str)
+ }
+
+
+def test_attribute_keys_are_unique_across_namespaces():
+ # prefixes are allowed to be substrings; exact keys must not collide.
+ exact = set()
+ for cls in (GenAI, Error, Server, HTTP, DB):
+ for key in _all_constants(cls):
+ assert key not in exact, f"duplicate attribute key {key}"
+ exact.add(key)
+
+
+def test_provider_resolution():
+ assert resolve_provider("openai") == "openai"
+ assert resolve_provider("bedrock") == "aws.bedrock"
+ assert resolve_provider("vertex_ai") == "gcp.vertex_ai"
+ # unknown providers pass through verbatim (semconv allows provider-specific)
+ assert resolve_provider("my_custom_llm") == "my_custom_llm"
+ assert resolve_provider(None) == ""
+
+
+def test_operation_resolution():
+ assert resolve_operation("acompletion") is GenAIOperation.CHAT
+ assert resolve_operation("aembedding") is GenAIOperation.EMBEDDINGS
+ assert resolve_operation("atext_completion") is GenAIOperation.TEXT_COMPLETION
+ assert resolve_operation(None) is GenAIOperation.CHAT
+
+
+# --- typed adapter (source of truth #3) ------------------------------------- #
+
+
+def test_llm_call_adapter_extracts_all_fields():
+ data = LLMCallSpanData.from_standard_logging_payload(_sample_payload())
+ assert data.operation is GenAIOperation.CHAT
+ assert data.provider == "openai"
+ assert data.request_model == "gpt-4o"
+ assert data.response_model == "gpt-4o-2024"
+ assert data.response_id == "resp_1"
+ assert data.finish_reasons == ("stop",)
+ assert (data.usage.input_tokens, data.usage.output_tokens) == (10, 5)
+ assert data.request_params.temperature == 0.7
+ assert data.request_params.top_k == 40
+ assert data.request_params.stop_sequences == ("STOP",)
+ assert data.request_params.seed == 42
+ assert data.server is not None
+ assert data.server.address == "api.openai.com"
+ assert data.server.port == 443
+ assert data.response_cost == 0.002
+ assert data.error is None
+ assert data.identity.team_id == "t1"
+ assert data.identity.key_hash == "hsh"
+
+
+def test_llm_call_adapter_failure_path():
+ payload = _sample_payload(
+ status="failure",
+ error_information={
+ "error_class": "RateLimitError",
+ "error_message": "429 slow down",
+ },
+ )
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.error is not None
+ assert data.error.error_type == "RateLimitError"
+ assert data.error.message == "429 slow down"
+
+
+def test_adapter_is_resilient_to_minimal_payload():
+ data = LLMCallSpanData.from_standard_logging_payload({})
+ assert data.request_model == ""
+ assert data.operation is GenAIOperation.CHAT
+ assert data.server is None
+ assert data.usage.input_tokens is None
+
+
+def test_content_capture_gated_off_by_default():
+ # ``capture_content`` defaults off: prompt/response bodies must not reach the
+ # span data (and so no vendor mapper can export them) unless explicitly
+ # opted in. Non-content metadata (finish reasons) is still derived.
+ payload = _sample_payload(
+ messages=[{"role": "user", "content": "secret prompt"}],
+ )
+ payload["response"]["choices"] = [
+ {"finish_reason": "stop", "message": {"role": "assistant", "content": "secret"}}
+ ]
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.messages_in == ()
+ assert data.choices_out == ()
+ assert data.finish_reasons == ("stop",)
+
+
+def test_request_identity_prefers_canonical_team_keys():
+ from litellm.integrations.otel.model.payloads import RequestIdentity
+
+ payload = _sample_payload(
+ metadata={
+ "user_api_key_team_id": "team-canonical",
+ "user_api_key_team_alias": "alias-canonical",
+ "user_api_key_hash": "hsh",
+ "team_id": "legacy-ignored", # legacy alias loses to the canonical key
+ }
+ )
+ ident = RequestIdentity.from_payload(payload)
+ assert ident.team_id == "team-canonical"
+ assert ident.team_alias == "alias-canonical"
+ assert ident.key_hash == "hsh"
+
+
+def test_request_identity_falls_back_to_legacy_team_keys():
+ from litellm.integrations.otel.model.payloads import RequestIdentity
+
+ payload = _sample_payload(
+ metadata={"team_id": "legacy-team", "team_alias": "legacy"}
+ )
+ ident = RequestIdentity.from_payload(payload)
+ assert ident.team_id == "legacy-team"
+ assert ident.team_alias == "legacy"
+
+
+def test_guardrail_span_data_block_carries_verdict_and_error():
+ from litellm.integrations.otel.model.payloads import GuardrailSpanData
+
+ entry = {
+ "guardrail_name": "openai-moderation",
+ "guardrail_mode": "pre_call",
+ "guardrail_status": "guardrail_intervened",
+ "guardrail_provider": "openai",
+ "guardrail_action": "BLOCKED",
+ "guardrail_response": {"violated_categories": ["violence"]},
+ "violation_categories": ["violence"],
+ "masked_entity_count": {"EMAIL": 2, "PHONE": 1},
+ "duration": 0.05,
+ }
+ d = GuardrailSpanData.from_logging_entry(entry)
+ assert d.guardrail_name == "openai-moderation"
+ assert d.status == "guardrail_intervened"
+ assert d.provider == "openai"
+ assert d.action == "BLOCKED"
+ assert '"violence"' in (d.response_json or "")
+ assert d.violation_categories == ("violence",)
+ assert d.masked_entity_count == 3 # summed across entity types
+ assert d.duration == 0.05
+ assert d.error is not None # intervention → span marked ERROR
+
+
+def test_guardrail_span_data_success_has_no_error():
+ from litellm.integrations.otel.model.payloads import GuardrailSpanData
+
+ d = GuardrailSpanData.from_logging_entry(
+ {
+ "guardrail_name": "g",
+ "guardrail_mode": "pre_call",
+ "guardrail_status": "success",
+ }
+ )
+ assert d.error is None
+ assert d.status == "success"
+
+
+def test_request_identity_from_user_api_key_auth():
+ from litellm.integrations.otel.model.payloads import RequestIdentity
+
+ class _Auth:
+ team_id = "t9"
+ team_alias = "team nine"
+ api_key = "hashed-key"
+ user_id = "u9"
+ org_id = "o9"
+ key_alias = "my-key"
+ end_user_id = "eu9"
+
+ ident = RequestIdentity.from_user_api_key_auth(_Auth())
+ assert (ident.team_id, ident.team_alias, ident.key_hash) == (
+ "t9",
+ "team nine",
+ "hashed-key",
+ )
+ assert ident.end_user == "eu9"
+ assert ident.metadata["user_api_key_user_id"] == "u9"
+ assert ident.metadata["user_api_key_org_id"] == "o9"
+ assert ident.metadata["user_api_key_alias"] == "my-key"
+ assert ident.metadata["user_api_key_end_user_id"] == "eu9"
+
+
+# --- request-metadata translation layer (RequestContext) -------------------- #
+
+
+def test_request_context_splits_group_from_dispatched_model():
+ """On the proxy the caller asks for a model *group* that routes to a concrete
+ deployment: ``gen_ai.request.model`` is the group, ``litellm.provider.model``
+ is the dispatched (provider-prefixed) deployment model."""
+ from litellm.integrations.otel.model.metadata import RequestContext
+
+ payload = _sample_payload(
+ model="openai/gpt-5.4-mini", # reconstructed dispatched name
+ model_group="gpt-5.4-mini", # user-facing requested name
+ model_id="dep-123",
+ )
+ ctx = RequestContext.from_standard_logging_payload(payload)
+ assert ctx.request_model == "gpt-5.4-mini"
+ assert ctx.provider_model == "openai/gpt-5.4-mini"
+ assert ctx.identity.provider_model == "openai/gpt-5.4-mini"
+ assert ctx.model_group == "gpt-5.4-mini"
+ assert ctx.model_id == "dep-123"
+
+
+def test_request_context_sdk_path_has_no_group():
+ """Without a model group (the SDK path) the request and provider models
+ coincide on the single call model."""
+ from litellm.integrations.otel.model.metadata import RequestContext
+
+ payload = _sample_payload() # model="gpt-4o", no model_group
+ ctx = RequestContext.from_standard_logging_payload(payload)
+ assert ctx.request_model == "gpt-4o"
+ assert ctx.provider_model == "gpt-4o"
+ assert ctx.model_group is None
+
+
+def test_request_context_prefers_explicit_dispatched_model():
+ """``hidden_params.litellm_model_name`` is the authoritative dispatched model
+ when present, winning over the reconstructed top-level ``model``."""
+ from litellm.integrations.otel.model.metadata import RequestContext
+
+ payload = _sample_payload(
+ model="gpt-4o",
+ model_group="gpt-4o",
+ hidden_params={"litellm_model_name": "azure/my-deployment"},
+ )
+ ctx = RequestContext.from_standard_logging_payload(payload)
+ assert ctx.request_model == "gpt-4o"
+ assert ctx.provider_model == "azure/my-deployment"
+
+
+def test_content_capture_opt_in_retains_bodies():
+ payload = _sample_payload(
+ messages=[{"role": "user", "content": "secret prompt"}],
+ )
+ payload["response"]["choices"] = [
+ {"finish_reason": "stop", "message": {"role": "assistant", "content": "hi"}}
+ ]
+ data = LLMCallSpanData.from_standard_logging_payload(payload, capture_content=True)
+ assert data.messages_in and data.messages_in[0]["content"] == "secret prompt"
+ assert data.choices_out and data.choices_out[0]["message"]["content"] == "hi"
+
+
+# --- config ----------------------------------------------------------------- #
+
+
+def test_capture_span_content_resolves_modes():
+ from litellm.integrations.otel.model.config import (
+ CaptureMessageContent,
+ OpenTelemetryV2Config,
+ )
+
+ # default (no_content) → off
+ assert OpenTelemetryV2Config().capture_span_content is False
+ assert (
+ OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.SPAN_ONLY
+ ).capture_span_content
+ is True
+ )
+ assert (
+ OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.SPAN_AND_EVENT
+ ).capture_span_content
+ is True
+ )
+ # event-only does not authorize span-attribute content
+ assert (
+ OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.EVENT_ONLY
+ ).capture_span_content
+ is False
+ )
+
+
+def test_v2_flag_is_off_by_default(monkeypatch):
+ monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)
+ assert is_otel_v2_enabled() is False
+ monkeypatch.setenv("LITELLM_OTEL_V2", "true")
+ assert is_otel_v2_enabled() is True
+
+
+def test_config_from_env(monkeypatch):
+ for var in (
+ "OTEL_EXPORTER",
+ "OTEL_EXPORTER_OTLP_PROTOCOL",
+ "OTEL_ENDPOINT",
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "OTEL_HEADERS",
+ "OTEL_EXPORTER_OTLP_HEADERS",
+ "OTEL_SERVICE_NAME",
+ "LITELLM_OTEL_LEGACY_COMPAT",
+ ):
+ monkeypatch.delenv(var, raising=False)
+
+ monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "https://collector:4318")
+ monkeypatch.setenv("OTEL_SERVICE_NAME", "my-svc")
+ cfg = OpenTelemetryV2Config.from_env()
+ # endpoint with no explicit exporter implies OTLP/HTTP
+ assert cfg.exporter == "otlp_http"
+ assert cfg.endpoint == "https://collector:4318"
+ assert cfg.service_name == "my-svc"
+ assert cfg.legacy_compat is True # dual-emit default during deprecation window
+
+
+def test_config_legacy_compat_env_toggle(monkeypatch):
+ monkeypatch.setenv("LITELLM_OTEL_LEGACY_COMPAT", "false")
+ assert OpenTelemetryV2Config.from_env().legacy_compat is False
+
+
+# --- baggage allowlist (the antipattern boundary) --------------------------- #
+
+
+def test_promoted_baggage_is_bounded_allowlist():
+ identity = RequestIdentity(
+ call_id="c1",
+ team_id="t1",
+ team_alias="team one",
+ key_hash="hsh",
+ end_user="u1",
+ metadata={"user_api_key_org_id": "org1", "secret_blob": "should-not-promote"},
+ )
+ promoted = promoted_baggage(identity, "gpt-4o", BAGGAGE_PROMOTED_KEYS)
+ assert promoted[LiteLLM.TEAM_ID] == "t1"
+ assert promoted[LiteLLM.TEAM_ALIAS] == "team one"
+ assert promoted[GenAI.REQUEST_MODEL] == "gpt-4o"
+ # allowlisted metadata sub-key is promoted under the litellm.metadata.* prefix
+ assert promoted[f"{LiteLLM.METADATA_PREFIX}user_api_key_org_id"] == "org1"
+ # full metadata blob is NOT promoted
+ assert all("secret_blob" not in key for key in promoted)
+ # http.* is never a promoted key
+ assert HTTP.ROUTE not in promoted
+ assert HTTP.REQUEST_METHOD not in promoted
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_vendor_mappers.py b/tests/test_litellm/integrations/otel/test_otel_v2_vendor_mappers.py
new file mode 100644
index 00000000000..94cb79f53b8
--- /dev/null
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_vendor_mappers.py
@@ -0,0 +1,196 @@
+"""Tests for the vendor mappers (OpenInference, Langfuse, Weave, Langtrace).
+
+Composition over inheritance: each vendor's vocabulary is a mapper. Layering
+mappers on the same span carries multiple naming schemes for different
+backends, so one trace lights up every configured destination.
+"""
+
+import json
+
+import pytest
+
+from litellm.integrations.otel import GenAIOperation
+from litellm.integrations.otel.mappers import (
+ GenAIMapper,
+ LangfuseMapper,
+ LangtraceMapper,
+ OpenInferenceMapper,
+ WeaveMapper,
+ resolve_mappers,
+)
+from litellm.integrations.otel.model.payloads import (
+ LLMCallSpanData,
+ LLMRequestParams,
+ LLMUsage,
+ RequestIdentity,
+ ServerInfo,
+ ToolDefinition,
+)
+
+
+def _llm_call(**overrides):
+ base = dict(
+ operation=GenAIOperation.CHAT,
+ provider="openai",
+ request_model="gpt-4o",
+ response_model="gpt-4o-2024",
+ response_id="resp_1",
+ request_params=LLMRequestParams(temperature=0.5, top_p=0.9, max_tokens=128),
+ usage=LLMUsage(input_tokens=12, output_tokens=8, total_tokens=20),
+ finish_reasons=("stop",),
+ error=None,
+ response_cost=0.001,
+ server=ServerInfo("api.openai.com", 443),
+ identity=RequestIdentity(call_id="c1", team_id="t1", team_alias="team one"),
+ is_streaming=False,
+ tools=(
+ ToolDefinition(
+ name="lookup_weather",
+ description="Get weather",
+ parameters_json='{"type":"object"}',
+ ),
+ ),
+ messages_in=(
+ {"role": "system", "content": "Be concise."},
+ {"role": "user", "content": "What's the weather?"},
+ ),
+ choices_out=(
+ {
+ "finish_reason": "stop",
+ "message": {"role": "assistant", "content": "Sunny."},
+ },
+ ),
+ system_fingerprint="fp_abc",
+ )
+ base.update(overrides)
+ return LLMCallSpanData(**base)
+
+
+# --------------------------------------------------------------------------- #
+# OpenInference (Arize + Phoenix shared vocabulary)
+# --------------------------------------------------------------------------- #
+
+
+def test_openinference_mapper_input_output_messages():
+ attrs = OpenInferenceMapper().map(_llm_call())
+ assert attrs["openinference.span.kind"] == "LLM"
+ assert attrs["llm.model_name"] == "gpt-4o"
+ assert attrs["llm.provider"] == "openai"
+ assert attrs["llm.input_messages.0.message.role"] == "system"
+ assert attrs["llm.input_messages.0.message.content"] == "Be concise."
+ assert attrs["llm.input_messages.1.message.role"] == "user"
+ assert attrs["llm.output_messages.0.message.role"] == "assistant"
+ assert attrs["llm.output_messages.0.message.content"] == "Sunny."
+ assert attrs["llm.token_count.prompt"] == 12
+ assert attrs["llm.token_count.completion"] == 8
+ assert attrs["llm.token_count.total"] == 20
+ # tool definitions ride the OpenInference schema
+ assert attrs["llm.tools.0.tool.name"] == "lookup_weather"
+ # invocation_parameters is JSON-serialized
+ params = json.loads(attrs["llm.invocation_parameters"])
+ assert params["temperature"] == 0.5
+ assert params["max_tokens"] == 128
+
+
+def test_openinference_mapper_skips_non_llm_roles():
+ from litellm.integrations.otel.model.payloads import GuardrailSpanData
+
+ assert OpenInferenceMapper().map(GuardrailSpanData("presidio")) == {}
+
+
+def test_openinference_multimodal_content_text_only():
+ data = _llm_call(
+ messages_in=(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hi "},
+ {"type": "image_url", "image_url": {"url": "x"}},
+ {"type": "text", "text": "there"},
+ ],
+ },
+ )
+ )
+ attrs = OpenInferenceMapper().map(data)
+ assert attrs["llm.input_messages.0.message.content"] == "hi there"
+
+
+# --------------------------------------------------------------------------- #
+# Langfuse
+# --------------------------------------------------------------------------- #
+
+
+def test_langfuse_mapper_observation_attrs():
+ attrs = LangfuseMapper().map(_llm_call())
+ assert attrs["langfuse.observation.type"] == "generation"
+ assert attrs["langfuse.observation.model.name"] == "gpt-4o"
+ assert attrs["langfuse.observation.metadata.provider"] == "openai"
+ usage = json.loads(attrs["langfuse.observation.usage_details"])
+ assert usage["input"] == 12 and usage["output"] == 8
+ params = json.loads(attrs["langfuse.observation.model.parameters"])
+ assert params["temperature"] == 0.5
+ cost = json.loads(attrs["langfuse.observation.cost_details"])
+ assert cost["total"] == 0.001
+ assert attrs["langfuse.trace.metadata.team_id"] == "t1"
+
+
+def test_langfuse_mapper_skips_when_no_messages():
+ data = _llm_call(messages_in=(), choices_out=())
+ attrs = LangfuseMapper().map(data)
+ assert "langfuse.observation.input" not in attrs
+ assert "langfuse.observation.output" not in attrs
+
+
+# --------------------------------------------------------------------------- #
+# Weave
+# --------------------------------------------------------------------------- #
+
+
+def test_weave_mapper_display_and_output():
+ attrs = WeaveMapper().map(_llm_call())
+ assert attrs["weave.display_name"] == "chat gpt-4o"
+ assert attrs["weave.call_id"] == "c1"
+ decoded = json.loads(attrs["weave.output"])
+ assert decoded[0]["message"]["content"] == "Sunny."
+
+
+# --------------------------------------------------------------------------- #
+# Langtrace
+# --------------------------------------------------------------------------- #
+
+
+def test_langtrace_mapper_attrs():
+ attrs = LangtraceMapper().map(_llm_call())
+ assert attrs["gen_ai.operation.name"] == "chat"
+ assert attrs["langtrace.service.name"] == "openai"
+ assert attrs["llm.model"] == "gpt-4o"
+ assert attrs["gen_ai.response.model"] == "gpt-4o-2024"
+ assert attrs["gen_ai.system_fingerprint"] == "fp_abc"
+ assert attrs["llm.temperature"] == 0.5
+ assert attrs["llm.token.counts.total"] == 20
+
+
+# --------------------------------------------------------------------------- #
+# Composition (the V2 punchline)
+# --------------------------------------------------------------------------- #
+
+
+def test_resolve_mappers_composition_layers_vocabularies():
+ """One span, three vocabularies — Arize + Langfuse + canonical together."""
+ chain = resolve_mappers(["genai", "openinference", "langfuse"])
+ data = _llm_call()
+ union: dict = {}
+ for mapper in chain:
+ union.update(mapper.map(data))
+ # Canonical
+ assert union["gen_ai.operation.name"] == "chat"
+ # OpenInference
+ assert union["llm.model_name"] == "gpt-4o"
+ assert union["openinference.span.kind"] == "LLM"
+ # Langfuse
+ assert union["langfuse.observation.type"] == "generation"
+
+
+def test_resolve_mappers_rejects_unknown_name():
+ with pytest.raises(ValueError, match="unknown mapper name 'nope'"):
+ resolve_mappers(["genai", "nope"])
diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.py
index 7a2b20bd8fb..f0015d9df0d 100644
--- a/tests/test_litellm/proxy/test_proxy_utils.py
+++ b/tests/test_litellm/proxy/test_proxy_utils.py
@@ -71,6 +71,53 @@ def test_proxy_only_error_false_for_other_error_type():
)
+async def test_proxy_only_error_log_marks_no_upstream_llm_call():
+ """A proxy-gate error (auth/rate-limit) synthesizes a ``Logging`` object and
+ fires ``pre_call`` so the failure is logged — but it must tag the object with
+ ``LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL`` so tracing callbacks don't fabricate
+ an LLM-call span for a request that never reached a provider (root cause of the
+ misplaced gen-AI span on auth failure)."""
+ from litellm.constants import LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL
+ from litellm.proxy._types import UserAPIKeyAuth
+
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())
+ captured = {}
+
+ def fake_pre_call(self, *args, **kwargs):
+ captured["flag"] = self.model_call_details.get(
+ LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL
+ )
+
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+ orig_pre_call = Logging.pre_call
+ orig_async_failure = Logging.async_failure_handler
+ Logging.pre_call = fake_pre_call
+
+ async def _noop_async_failure(self, *args, **kwargs):
+ return None
+
+ Logging.async_failure_handler = _noop_async_failure
+ try:
+ await proxy_logging_obj._handle_logging_proxy_only_error(
+ request_data={
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "hi"}],
+ },
+ user_api_key_dict=UserAPIKeyAuth(
+ api_key="sk-bad", request_route="/v1/chat/completions"
+ ),
+ route="/v1/chat/completions",
+ original_exception=Exception("bad key"),
+ )
+ finally:
+ Logging.pre_call = orig_pre_call
+ Logging.async_failure_handler = orig_async_failure
+
+ assert captured.get("flag") is True
+
+
def test_get_model_group_info_order():
from litellm import Router
from litellm.proxy.proxy_server import _get_model_group_info
diff --git a/tests/test_litellm/test_service_logger.py b/tests/test_litellm/test_service_logger.py
index ed44fe9b9f2..34fe73382b3 100644
--- a/tests/test_litellm/test_service_logger.py
+++ b/tests/test_litellm/test_service_logger.py
@@ -6,10 +6,12 @@ is called without call_type in kwargs (e.g. from batch polling callbacks).
"""
import pytest
-from datetime import datetime, timedelta
+from datetime import datetime
from unittest.mock import AsyncMock, patch
+import litellm
from litellm._service_logger import ServiceLogging
+from litellm.types.services import ServiceTypes
@pytest.mark.asyncio
@@ -95,3 +97,156 @@ async def test_async_log_success_event_should_handle_float_duration():
mock_hook.assert_called_once()
call_kwargs = mock_hook.call_args
assert call_kwargs.kwargs["duration"] == 1.5
+
+
+# --------------------------------------------------------------------------- #
+# V2 OpenTelemetry service-span dispatch (regression: service spans were always
+# dropped because the dispatch only recognized the legacy OpenTelemetry class).
+# --------------------------------------------------------------------------- #
+
+
+def _make_otel_v2_logger():
+ pytest.importorskip("opentelemetry")
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
+ InMemorySpanExporter,
+ )
+
+ from litellm.integrations.otel import OpenTelemetryV2Config
+ from litellm.integrations.otel.plumbing import providers
+ from litellm.integrations.otel.logger import OpenTelemetryV2
+
+ cfg = OpenTelemetryV2Config(exporter="in_memory")
+ exporter = InMemorySpanExporter()
+ tracer_provider = providers.build_tracer_provider(cfg, exporter=exporter)
+ return OpenTelemetryV2(config=cfg, tracer_provider=tracer_provider), exporter
+
+
+def test_resolve_otel_service_logger_recognizes_v2_instance():
+ """The V2 logger is a plain CustomLogger, not a subclass of the legacy
+ OpenTelemetry. The resolver must still recognize it (else service spans are
+ silently dropped)."""
+ service_logger = ServiceLogging()
+ v2_logger, _ = _make_otel_v2_logger()
+ assert service_logger._resolve_otel_service_logger(v2_logger) is v2_logger
+
+
+def test_resolve_otel_service_logger_recognizes_otel_string(monkeypatch):
+ # The "otel" string path resolves through the proxy's registered logger, so
+ # it needs the proxy server module importable.
+ try:
+ import litellm.proxy.proxy_server as proxy_server
+ except ImportError:
+ pytest.skip("proxy server dependencies not installed")
+ service_logger = ServiceLogging()
+ v2_logger, _ = _make_otel_v2_logger()
+
+ monkeypatch.setattr(proxy_server, "open_telemetry_logger", v2_logger, raising=False)
+ assert service_logger._resolve_otel_service_logger("otel") is v2_logger
+
+
+def test_resolve_otel_service_logger_ignores_unrelated_callback():
+ service_logger = ServiceLogging()
+ assert service_logger._resolve_otel_service_logger("prometheus_system") is None
+ assert service_logger._resolve_otel_service_logger(object()) is None
+
+
+async def test_service_span_emitted_for_v2_logger_in_service_callback(monkeypatch):
+ """End-to-end: a V2 logger registered in ``litellm.service_callback`` produces
+ a service span when ``async_service_success_hook`` fires with a parent span."""
+ from litellm.integrations.otel.model.spans import SpanRole
+
+ v2_logger, exporter = _make_otel_v2_logger()
+ parent = v2_logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, "POST /chat/completions"
+ )
+
+ monkeypatch.setattr(litellm, "service_callback", [v2_logger])
+ service_logger = ServiceLogging()
+
+ await service_logger.async_service_success_hook(
+ service=ServiceTypes.REDIS,
+ call_type="async_set_cache",
+ duration=0.01,
+ parent_otel_span=parent,
+ )
+ parent.end()
+
+ names = [s.name for s in exporter.get_finished_spans()]
+ # Span name is "{service} {call_type}" so repeated calls stay distinguishable.
+ assert "redis async_set_cache" in names
+
+
+async def test_service_span_not_duplicated_for_string_and_instance(monkeypatch):
+ """``service_callback`` can hold the ``"otel"`` string AND the registered
+ logger instance — the V2 logger self-registers its instance even when the
+ string is present. Both references resolve to the same logger, so the dispatch
+ loop must emit only ONE span per service event, not one per reference. Before
+ the dedup guard this produced duplicate ``postgres ...`` / ``redis ...`` spans.
+ """
+ try:
+ import litellm.proxy.proxy_server as proxy_server
+ except ImportError:
+ pytest.skip("proxy server dependencies not installed")
+ from litellm.integrations.otel.model.spans import SpanRole
+
+ v2_logger, exporter = _make_otel_v2_logger()
+ parent = v2_logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, "POST /chat/completions"
+ )
+
+ # The "otel" string resolves to the proxy's registered logger (the same
+ # instance), so the list holds two references to one logger.
+ monkeypatch.setattr(proxy_server, "open_telemetry_logger", v2_logger, raising=False)
+ monkeypatch.setattr(litellm, "service_callback", ["otel", v2_logger])
+ service_logger = ServiceLogging()
+
+ await service_logger.async_service_success_hook(
+ service=ServiceTypes.DB,
+ call_type="get_user_object",
+ duration=0.01,
+ parent_otel_span=parent,
+ )
+ parent.end()
+
+ db_spans = [
+ s for s in exporter.get_finished_spans() if s.name == "postgres get_user_object"
+ ]
+ assert len(db_spans) == 1
+
+
+async def test_service_failure_span_not_duplicated_for_string_and_instance(
+ monkeypatch,
+):
+ """Failure path mirror of the dedup guard — one span per failed service event,
+ even with both the ``"otel"`` string and the instance in ``service_callback``."""
+ try:
+ import litellm.proxy.proxy_server as proxy_server
+ except ImportError:
+ pytest.skip("proxy server dependencies not installed")
+ from litellm.integrations.otel.model.spans import SpanRole
+
+ v2_logger, exporter = _make_otel_v2_logger()
+ parent = v2_logger._emitter.start_span(
+ SpanRole.PROXY_REQUEST, "POST /chat/completions"
+ )
+
+ monkeypatch.setattr(proxy_server, "open_telemetry_logger", v2_logger, raising=False)
+ monkeypatch.setattr(litellm, "service_callback", ["otel", v2_logger])
+ service_logger = ServiceLogging()
+
+ await service_logger.async_service_failure_hook(
+ service=ServiceTypes.DB,
+ call_type="get_user_object",
+ duration=0.01,
+ error="boom",
+ parent_otel_span=parent,
+ )
+ parent.end()
+
+ db_spans = [
+ s for s in exporter.get_finished_spans() if s.name == "postgres get_user_object"
+ ]
+ assert len(db_spans) == 1
diff --git a/uv.lock b/uv.lock
index 080cd89df6b..a632f72936d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -294,6 +294,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ee/82/82745642d3c46e7cea25e1885b014b033f4693346ce46b7f47483cf5d448/argon2_cffi_bindings-25.1.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:da0c79c23a63723aa5d782250fbf51b768abca630285262fb5144ba5ae01e520", size = 29187, upload-time = "2025-07-30T10:02:03.674Z" },
]
+[[package]]
+name = "asgiref"
+version = "3.11.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/63/40/f03da1264ae8f7cfdbf9146542e5e7e8100a4c66ab48e791df9a03d3f6c0/asgiref-3.11.1.tar.gz", hash = "sha256:5f184dc43b7e763efe848065441eac62229c9f7b0475f41f80e207a114eda4ce", size = 38550, upload-time = "2026-02-03T13:30:14.33Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/0a/a72d10ed65068e115044937873362e6e32fab1b7dce0046aeb224682c989/asgiref-3.11.1-py3-none-any.whl", hash = "sha256:e8667a091e69529631969fd45dc268fa79b99c92c5fcdda727757e52146ec133", size = 24345, upload-time = "2026-02-03T13:30:13.039Z" },
+]
+
[[package]]
name = "assemblyai"
version = "0.52.4"
@@ -3349,6 +3361,7 @@ proxy-runtime = [
{ name = "mangum" },
{ name = "opentelemetry-api" },
{ name = "opentelemetry-exporter-otlp" },
+ { name = "opentelemetry-instrumentation-fastapi" },
{ name = "opentelemetry-sdk" },
{ name = "prometheus-client" },
{ name = "pypdf" },
@@ -3411,6 +3424,7 @@ dev = [
{ name = "openapi-core" },
{ name = "opentelemetry-api" },
{ name = "opentelemetry-exporter-otlp" },
+ { name = "opentelemetry-instrumentation-fastapi" },
{ name = "opentelemetry-sdk" },
{ name = "parameterized" },
{ name = "psycopg" },
@@ -3444,6 +3458,7 @@ proxy-dev = [
{ name = "hypercorn" },
{ name = "opentelemetry-api" },
{ name = "opentelemetry-exporter-otlp" },
+ { name = "opentelemetry-instrumentation-fastapi" },
{ name = "opentelemetry-sdk" },
{ name = "prisma" },
{ name = "prometheus-client" },
@@ -3499,6 +3514,7 @@ requires-dist = [
{ name = "openai", specifier = ">=2.20.0,<3.0.0" },
{ name = "opentelemetry-api", marker = "extra == 'proxy-runtime'", specifier = "==1.28.0" },
{ name = "opentelemetry-exporter-otlp", marker = "extra == 'proxy-runtime'", specifier = "==1.28.0" },
+ { name = "opentelemetry-instrumentation-fastapi", marker = "extra == 'proxy-runtime'", specifier = "==0.49b0" },
{ name = "opentelemetry-sdk", marker = "extra == 'proxy-runtime'", specifier = "==1.28.0" },
{ name = "orjson", marker = "extra == 'proxy'", specifier = ">=3.11.6,<4.0" },
{ name = "polars", marker = "extra == 'proxy'", specifier = ">=1.38.1,<2.0" },
@@ -3573,6 +3589,7 @@ dev = [
{ name = "openapi-core", marker = "python_full_version < '3.14'", specifier = "==0.22.0" },
{ name = "opentelemetry-api", specifier = "==1.28.0" },
{ name = "opentelemetry-exporter-otlp", specifier = "==1.28.0" },
+ { name = "opentelemetry-instrumentation-fastapi", specifier = "==0.49b0" },
{ name = "opentelemetry-sdk", specifier = "==1.28.0" },
{ name = "parameterized", specifier = "==0.9.0" },
{ name = "psycopg", specifier = "==3.3.3" },
@@ -3606,6 +3623,7 @@ proxy-dev = [
{ name = "hypercorn", specifier = "==0.17.3" },
{ name = "opentelemetry-api", specifier = "==1.28.0" },
{ name = "opentelemetry-exporter-otlp", specifier = "==1.28.0" },
+ { name = "opentelemetry-instrumentation-fastapi", specifier = "==0.49b0" },
{ name = "opentelemetry-sdk", specifier = "==1.28.0" },
{ name = "prisma", specifier = "==0.11.0" },
{ name = "prometheus-client", specifier = "==0.20.0" },
@@ -4561,6 +4579,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ba/46/ba2dc8d18b04acae3d34facd8fe1e5e0cdc9fe64292d45eca9d1d4a8a298/opentelemetry_instrumentation_anthropic-0.33.12-py3-none-any.whl", hash = "sha256:b31618d12a429045db14ed982a142a25df0f0f1dbf03d756e8d597f25b9a053d", size = 11024, upload-time = "2024-11-13T20:27:14.622Z" },
]
+[[package]]
+name = "opentelemetry-instrumentation-asgi"
+version = "0.49b0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "asgiref" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "opentelemetry-util-http" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e8/55/693c3d0938ba5fead5c3aa4ac7022a992b4ff99a8e9979800d0feb843ff4/opentelemetry_instrumentation_asgi-0.49b0.tar.gz", hash = "sha256:959fd9b1345c92f20c6ef1d42f92ef6a76b3c3083fbc4104d59da6859b15b083", size = 24117, upload-time = "2024-11-05T19:21:46.769Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2c/0b/7900c782a1dfaa584588d724bc3bbdf8405a32497537dd96b3fcbf8461b9/opentelemetry_instrumentation_asgi-0.49b0-py3-none-any.whl", hash = "sha256:722a90856457c81956c88f35a6db606cc7db3231046b708aae2ddde065723dbe", size = 16326, upload-time = "2024-11-05T19:20:46.176Z" },
+]
+
[[package]]
name = "opentelemetry-instrumentation-bedrock"
version = "0.33.12"
@@ -4607,6 +4641,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bf/08/dce2b7926ace0204ce7946563348e1ff755873e387833484791e4ed391c8/opentelemetry_instrumentation_cohere-0.33.12-py3-none-any.whl", hash = "sha256:3bee3f7f7105259c85145be8c3b68612421860c95ad170f4d03144a3b8c07418", size = 5589, upload-time = "2024-11-13T20:27:21.317Z" },
]
+[[package]]
+name = "opentelemetry-instrumentation-fastapi"
+version = "0.49b0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-instrumentation-asgi" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "opentelemetry-util-http" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fe/bf/8e6d2a4807360f2203192017eb4845f5628dbeaf0597adf3d141cc5c24e1/opentelemetry_instrumentation_fastapi-0.49b0.tar.gz", hash = "sha256:6d14935c41fd3e49328188b6a59dd4c37bd17a66b01c15b0c64afa9714a1f905", size = 19230, upload-time = "2024-11-05T19:21:59.361Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b1/f4/0895b9410c10abf987c90dee1b7688a8f2214a284fe15e575648f6a1473a/opentelemetry_instrumentation_fastapi-0.49b0-py3-none-any.whl", hash = "sha256:646e1b18523cbe6860ae9711eb2c7b9c85466c3c7697cd6b8fb5180d85d3fe6e", size = 12101, upload-time = "2024-11-05T19:21:01.805Z" },
+]
+
[[package]]
name = "opentelemetry-instrumentation-google-generativeai"
version = "0.33.12"