The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(telemetry): add AggregatingSink, fixed-bucket histograms, Report and HttpExporter (#45487)
devin-ai-integration[bot]596c51a5faaf
diff --git a/litellm/telemetry/aggregate.py b/litellm/telemetry/aggregate.pynew file mode 100644index 00000000000..f875026c74d--- /dev/null+++ b/litellm/telemetry/aggregate.py@@ -0,0 +1,133 @@+import logging+import time+from collections.abc import Callable+from typing import Final, TypeVar++from litellm.telemetry.records import AttemptRecord, InstanceInfo, RequestRecord, UIEvent+from litellm.telemetry.report import AttemptKey, AttemptMetrics, Report, RequestKey, RequestMetrics+from litellm.telemetry.sink import Exporter, ExportOutcome++DEFAULT_MAX_ROWS: Final = 2000+QUIET_RETRIES: Final = 3++_LOGGER: Final = logging.getLogger(__name__)++_Key: Final = TypeVar("_Key")+_Row: Final = TypeVar("_Row")+++class AggregatingSink:+ """Folds records into per-window rows and hands each window to an exporter as one ``Report``"""++ def __init__(+ self,+ exporter: Exporter,+ *,+ clock: Callable[[], float] = time.time,+ max_rows: int = DEFAULT_MAX_ROWS,+ logger: logging.Logger = _LOGGER,+ ) -> None:+ self._exporter: Final = exporter+ self._clock: Final = clock+ self._max_rows: Final = max_rows+ self._logger: Final = logger+ self._instance: InstanceInfo | None = None+ self._window_start: float = clock()+ self._requests: dict[RequestKey, RequestMetrics] = {} # mutable-ok: bounded fold, drained per flush+ self._attempts: dict[AttemptKey, AttemptMetrics] = {} # mutable-ok: bounded fold, drained per flush+ self._ui_events: dict[UIEvent, int] = {} # mutable-ok: bounded fold, drained per flush+ self._dropped: int = 0+ self._flushing: bool = False+ self._consecutive_retries: int = 0++ def _row_count(self) -> int:+ return len(self._requests) + len(self._attempts) + len(self._ui_events)++ def _row(+ self,+ rows: dict[_Key, _Row], # mutable-ok: one of this sink's bounded row folds, shared cap check+ key: _Key,+ empty: Callable[[], _Row],+ weight: int,+ ) -> _Row | None:+ existing: Final = rows.get(key)+ if existing is not None:+ return existing+ if self._row_count() >= self._max_rows:+ self._dropped += weight+ return None+ row: Final = empty()+ rows[key] = row # rebind-ok: inserts the new row into this sink's own bounded fold+ return row++ def _add_ui_events(self, event: UIEvent, count: int) -> None:+ existing: Final = self._ui_events.get(event)+ if existing is None and self._row_count() >= self._max_rows:+ self._dropped += count+ return+ self._ui_events[event] = (existing or 0) + count++ def set_instance(self, info: InstanceInfo) -> None:+ self._instance = info++ def record_request(self, record: RequestRecord) -> None:+ row: Final = self._row(self._requests, RequestKey.of(record), RequestMetrics.empty, 1)+ if row is not None:+ row.add(record)++ def record_attempt(self, record: AttemptRecord) -> None:+ row: Final = self._row(self._attempts, AttemptKey.of(record), AttemptMetrics.empty, 1)+ if row is not None:+ row.add(record)++ def record_ui_event(self, event: UIEvent) -> None:+ self._add_ui_events(event, 1)++ def _restore(self, report: Report) -> None:+ self._window_start = report.window_start+ self._dropped += report.dropped_records+ for request_key, request_metrics in report.requests:+ request_row = self._row(self._requests, request_key, RequestMetrics.empty, request_metrics.request_count)+ if request_row is not None:+ request_row.add_metrics(request_metrics)+ for attempt_key, attempt_metrics in report.attempts:+ attempt_row = self._row(self._attempts, attempt_key, AttemptMetrics.empty, attempt_metrics.attempt_count)+ if attempt_row is not None:+ attempt_row.add_metrics(attempt_metrics)+ for event, count in report.ui_events:+ self._add_ui_events(event, count)++ async def flush(self) -> None:+ instance: Final = self._instance+ if instance is None or self._flushing:+ return+ self._flushing = True+ try:+ await self._export_window(instance)+ finally:+ self._flushing = False++ async def _export_window(self, instance: InstanceInfo) -> None:+ window_end: Final = self._clock()+ report: Final = Report(+ instance=instance,+ window_start=self._window_start,+ window_end=window_end,+ requests=tuple(self._requests.items()),+ attempts=tuple(self._attempts.items()),+ ui_events=tuple(self._ui_events.items()),+ dropped_records=self._dropped,+ )+ self._requests, self._attempts, self._ui_events, self._dropped = {}, {}, {}, 0+ self._window_start = window_end+ outcome: Final = await self._exporter.export(report)+ if outcome is not ExportOutcome.RETRY:+ self._consecutive_retries = 0+ return+ self._consecutive_retries += 1+ if self._consecutive_retries >= QUIET_RETRIES:+ self._logger.error(+ "telemetry: report export failed %d times in a row, keeping the window for the next flush",+ self._consecutive_retries,+ )+ self._restore(report)diff --git a/litellm/telemetry/histogram.py b/litellm/telemetry/histogram.pynew file mode 100644index 00000000000..54fa9b493ce--- /dev/null+++ b/litellm/telemetry/histogram.py@@ -0,0 +1,35 @@+import bisect+import math+from dataclasses import dataclass+from typing import Final++LATENCY_BOUNDS_MS: Final = (50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0)+BLOCK_COUNT_BOUNDS: Final = (1.0, 5.0, 20.0, 100.0)+ATTEMPT_BOUNDS: Final = (0.0, 1.0, 2.0, 3.0)+++@dataclass(slots=True)+class Histogram:+ """Fixed-bucket counts: ``counts[i]`` holds values ``<= bounds[i]``, the last slot everything above.+ Negative, NaN and infinite values are counted in ``invalid`` instead of a bucket"""++ bounds: tuple[float, ...]+ counts: list[int] # mutable-ok: incremented in place once per record on the request path+ invalid: int = 0++ @classmethod+ def empty(cls, bounds: tuple[float, ...]) -> "Histogram":+ return cls(bounds=bounds, counts=[0] * (len(bounds) + 1))++ def add(self, value: float | None) -> None:+ if value is None:+ return+ if not math.isfinite(value) or value < 0:+ self.invalid += 1+ return+ self.counts[bisect.bisect_left(self.bounds, value)] += 1++ def add_histogram(self, other: "Histogram") -> None:+ for index, count in enumerate(other.counts):+ self.counts[index] += count+ self.invalid += other.invaliddiff --git a/litellm/telemetry/http_exporter.py b/litellm/telemetry/http_exporter.pynew file mode 100644index 00000000000..799ae3dec9d--- /dev/null+++ b/litellm/telemetry/http_exporter.py@@ -0,0 +1,37 @@+import json+from typing import Final++import httpx++from litellm.telemetry.report import Report, report_to_json+from litellm.telemetry.sink import ExportOutcome++_RETRYABLE_STATUS: Final = frozenset({408, 409, 429})+++def _outcome_for(status_code: int) -> ExportOutcome:+ if 200 <= status_code < 300:+ return ExportOutcome.SENT+ if status_code in _RETRYABLE_STATUS or status_code >= 500:+ return ExportOutcome.RETRY+ return ExportOutcome.REJECTED+++class HttpExporter:+ """POSTs each report as JSON; failures come back as an ``ExportOutcome``, never as an exception"""++ def __init__(self, client: httpx.AsyncClient, endpoint: str) -> None:+ self._client: Final = client+ self._endpoint: Final = endpoint++ async def export(self, report: Report) -> ExportOutcome:+ body: Final = json.dumps(report_to_json(report), separators=(",", ":")).encode()+ try:+ response: Final = await self._client.post(+ self._endpoint, content=body, headers={"content-type": "application/json"}+ )+ except (httpx.InvalidURL, httpx.UnsupportedProtocol):+ return ExportOutcome.REJECTED+ except httpx.HTTPError:+ return ExportOutcome.RETRY+ return _outcome_for(response.status_code)diff --git a/litellm/telemetry/report.py b/litellm/telemetry/report.pynew file mode 100644index 00000000000..6993db1e974--- /dev/null+++ b/litellm/telemetry/report.py@@ -0,0 +1,246 @@+"""The wire shape of one telemetry report: what an exporter sends or stores for one window"""++from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from typing import Final, TypeAlias++from litellm.telemetry.histogram import ATTEMPT_BOUNDS, BLOCK_COUNT_BOUNDS, LATENCY_BOUNDS_MS, Histogram+from litellm.telemetry.records import (+ AttemptRecord,+ BlockType,+ InstanceInfo,+ RequestRecord,+ StatusClass,+ TelemetryGroup,+ UIAction,+ UIEvent,+)++REPORT_SCHEMA_VERSION: Final = 1++JsonValue: TypeAlias = "str | int | float | bool | None | Sequence[JsonValue] | Mapping[str, JsonValue]"+++@dataclass(frozen=True, slots=True)+class RequestKey:+ endpoint: str+ provider: str | None+ deployment_hash: str | None+ litellm_status: StatusClass+ provider_status: StatusClass+ litellm_cache_hit: bool+ handled_by_rust: bool+ provider_cache_hit: bool+ stream: bool++ @classmethod+ def of(cls, record: RequestRecord) -> "RequestKey":+ return cls(+ endpoint=record.endpoint,+ provider=record.provider,+ deployment_hash=record.deployment_hash,+ litellm_status=record.litellm_status,+ provider_status=record.provider_status,+ litellm_cache_hit=record.litellm_cache_hit,+ handled_by_rust=record.handled_by_rust,+ provider_cache_hit=record.provider_cache_hit,+ stream=record.stream,+ )+++@dataclass(slots=True)+class RequestMetrics:+ """One request row's running totals, added to in place so each record costs no allocation"""++ request_count: int+ input_tokens: int+ output_tokens: int+ cache_read_tokens: int+ block_count: Histogram+ block_types: dict[BlockType, int] # mutable-ok: incremented in place once per record on the request path+ header_keys: dict[str, int] # mutable-ok: incremented in place once per record on the request path+ provider_attempts: Histogram+ latency_to_headers: Histogram+ latency_to_first_byte: Histogram++ @classmethod+ def empty(cls) -> "RequestMetrics":+ return cls(+ request_count=0,+ input_tokens=0,+ output_tokens=0,+ cache_read_tokens=0,+ block_count=Histogram.empty(BLOCK_COUNT_BOUNDS),+ block_types={},+ header_keys={},+ provider_attempts=Histogram.empty(ATTEMPT_BOUNDS),+ latency_to_headers=Histogram.empty(LATENCY_BOUNDS_MS),+ latency_to_first_byte=Histogram.empty(LATENCY_BOUNDS_MS),+ )++ def add(self, record: RequestRecord) -> None:+ self.request_count += 1+ self.input_tokens += record.tokens.input+ self.output_tokens += record.tokens.output+ self.cache_read_tokens += record.tokens.cache_read+ self.provider_attempts.add(record.provider_attempts)+ self.latency_to_headers.add(record.latency_to_headers_ms)+ self.latency_to_first_byte.add(record.latency_to_first_byte_ms)+ for key in record.header_keys:+ self.header_keys[key] = self.header_keys.get(key, 0) + 1+ if record.blocks is None:+ return+ self.block_count.add(record.blocks.total)+ for block_type, count in record.blocks.by_type:+ self.block_types[block_type] = self.block_types.get(block_type, 0) + count++ def add_metrics(self, other: "RequestMetrics") -> None:+ self.request_count += other.request_count+ self.input_tokens += other.input_tokens+ self.output_tokens += other.output_tokens+ self.cache_read_tokens += other.cache_read_tokens+ self.block_count.add_histogram(other.block_count)+ self.provider_attempts.add_histogram(other.provider_attempts)+ self.latency_to_headers.add_histogram(other.latency_to_headers)+ self.latency_to_first_byte.add_histogram(other.latency_to_first_byte)+ for block_type, count in other.block_types.items():+ self.block_types[block_type] = self.block_types.get(block_type, 0) + count+ for key, count in other.header_keys.items():+ self.header_keys[key] = self.header_keys.get(key, 0) + count+++@dataclass(frozen=True, slots=True)+class AttemptKey:+ provider: str+ deployment_hash: str | None+ provider_status: StatusClass+ stream: bool++ @classmethod+ def of(cls, record: AttemptRecord) -> "AttemptKey":+ return cls(+ provider=record.provider,+ deployment_hash=record.deployment_hash,+ provider_status=record.provider_status,+ stream=record.stream,+ )+++@dataclass(slots=True)+class AttemptMetrics:+ attempt_count: int+ latency_to_first_token: Histogram++ @classmethod+ def empty(cls) -> "AttemptMetrics":+ return cls(attempt_count=0, latency_to_first_token=Histogram.empty(LATENCY_BOUNDS_MS))++ def add(self, record: AttemptRecord) -> None:+ self.attempt_count += 1+ self.latency_to_first_token.add(record.latency_to_first_token_ms)++ def add_metrics(self, other: "AttemptMetrics") -> None:+ self.attempt_count += other.attempt_count+ self.latency_to_first_token.add_histogram(other.latency_to_first_token)+++@dataclass(frozen=True, slots=True)+class Report:+ instance: InstanceInfo+ window_start: float+ window_end: float+ requests: tuple[tuple[RequestKey, RequestMetrics], ...] = ()+ attempts: tuple[tuple[AttemptKey, AttemptMetrics], ...] = ()+ ui_events: tuple[tuple[UIEvent, int], ...] = ()+ dropped_records: int = 0+ schema_version: int = REPORT_SCHEMA_VERSION+++def _enum_value(value: StatusClass | BlockType | UIAction | TelemetryGroup) -> str:+ return value.value+++def _histogram_json(histogram: Histogram) -> JsonValue:+ return {"counts": list(histogram.counts), "invalid": histogram.invalid}+++def _request_json(key: RequestKey, metrics: RequestMetrics, groups: frozenset[TelemetryGroup]) -> JsonValue:+ success: Final[Mapping[str, JsonValue]] = {+ "endpoint": key.endpoint,+ "litellm_status": _enum_value(key.litellm_status),+ "provider_status": _enum_value(key.provider_status),+ "litellm_cache_hit": key.litellm_cache_hit,+ "handled_by_rust": key.handled_by_rust,+ "stream": key.stream,+ "request_count": metrics.request_count,+ "provider_attempts": _histogram_json(metrics.provider_attempts),+ "latency_to_headers_ms": _histogram_json(metrics.latency_to_headers),+ "latency_to_first_byte_ms": _histogram_json(metrics.latency_to_first_byte),+ }+ tokens: Final[Mapping[str, JsonValue]] = {+ "provider_cache_hit": key.provider_cache_hit,+ "input_tokens": metrics.input_tokens,+ "output_tokens": metrics.output_tokens,+ "cache_read_tokens": metrics.cache_read_tokens,+ }+ taxonomy: Final[Mapping[str, JsonValue]] = {"provider": key.provider, "deployment_hash": key.deployment_hash}+ details: Final[Mapping[str, JsonValue]] = {+ "block_count": _histogram_json(metrics.block_count),+ "block_types": {_enum_value(block_type): n for block_type, n in sorted(metrics.block_types.items())},+ "header_keys": dict(sorted(metrics.header_keys.items())),+ }+ return {+ **success,+ **(tokens if TelemetryGroup.TOKEN_INFO in groups else {}),+ **(taxonomy if TelemetryGroup.REQUEST_TAXONOMY in groups else {}),+ **(details if TelemetryGroup.EVENT_DETAILS in groups else {}),+ }+++def _attempt_json(key: AttemptKey, metrics: AttemptMetrics) -> JsonValue:+ return {+ "provider": key.provider,+ "deployment_hash": key.deployment_hash,+ "provider_status": _enum_value(key.provider_status),+ "stream": key.stream,+ "attempt_count": metrics.attempt_count,+ "latency_to_first_token_ms": _histogram_json(metrics.latency_to_first_token),+ }+++def _ui_event_json(event: UIEvent, count: int) -> JsonValue:+ return {"page": event.page, "action": _enum_value(event.action), "target": event.target, "count": count}+++def _instance_json(instance: InstanceInfo) -> JsonValue:+ configuration: Final[Mapping[str, JsonValue]] = {"config_keys": sorted(instance.config_keys)}+ return {+ "instance_id": instance.instance_id,+ "litellm_version": instance.litellm_version,+ "groups": sorted(_enum_value(group) for group in instance.groups),+ **(configuration if TelemetryGroup.INSTANCE_CONFIGURATION in instance.groups else {}),+ }+++def report_to_json(report: Report) -> Mapping[str, JsonValue]:+ """Only the fields of the report's enabled groups, so a stored or sent report shows exactly what was collected"""+ groups: Final = report.instance.groups+ requests: Final[Mapping[str, JsonValue]] = {+ "requests": [_request_json(key, metrics, groups) for key, metrics in report.requests]+ }+ attempts: Final[Mapping[str, JsonValue]] = {+ "attempts": [_attempt_json(key, metrics) for key, metrics in report.attempts]+ }+ ui_events: Final[Mapping[str, JsonValue]] = {+ "ui_events": [_ui_event_json(event, count) for event, count in report.ui_events]+ }+ return {+ "schema_version": report.schema_version,+ "instance": _instance_json(report.instance),+ "window_start": report.window_start,+ "window_end": report.window_end,+ "dropped_records": report.dropped_records,+ **(requests if TelemetryGroup.REQUEST_SUCCESS in groups else {}),+ **(attempts if TelemetryGroup.REQUEST_TAXONOMY in groups else {}),+ **(ui_events if TelemetryGroup.PAGE_NAVIGATION in groups else {}),+ }diff --git a/litellm/telemetry/sample.py b/litellm/telemetry/sample.pynew file mode 100644index 00000000000..42cbb8dfe69--- /dev/null+++ b/litellm/telemetry/sample.py@@ -0,0 +1,106 @@+"""A made-up report, built through the real gate and aggregator, that shows what each group adds"""++from typing import Final++from litellm.telemetry.aggregate import AggregatingSink+from litellm.telemetry.consent import ConsentGatedSink, TelemetryConsent+from litellm.telemetry.records import (+ AttemptRecord,+ BlockCounts,+ BlockType,+ InstanceInfo,+ RequestRecord,+ StatusClass,+ TokenCounts,+ UIAction,+ UIEvent,+)+from litellm.telemetry.report import Report+from litellm.telemetry.sink import ExportOutcome++SAMPLE_WINDOW_S: Final = 300.0++_REQUESTS: Final = (+ RequestRecord(+ endpoint="/chat/completions",+ stream=True,+ litellm_status=StatusClass.SUCCESS,+ provider="openai",+ deployment_hash="3f9a1c0d2b7e4a61",+ provider_status=StatusClass.SUCCESS,+ provider_cache_hit=True,+ provider_attempts=1,+ tokens=TokenCounts(input=1200, output=340, cache_read=1024),+ latency_to_headers_ms=210.0,+ latency_to_first_byte_ms=420.0,+ blocks=BlockCounts(total=3, by_type=((BlockType.TEXT, 2), (BlockType.IMAGE, 1))),+ header_keys=frozenset({"x-stainless-lang", "x-request-id"}),+ ),+ RequestRecord(+ endpoint="/messages",+ stream=False,+ litellm_status=StatusClass.SERVER_ERROR,+ provider="anthropic",+ deployment_hash="8c2e5b9f01d34a77",+ provider_status=StatusClass.SERVER_ERROR,+ handled_by_rust=True,+ provider_attempts=3,+ latency_to_headers_ms=9150.0,+ latency_to_first_byte_ms=9180.0,+ blocks=BlockCounts(total=2, by_type=((BlockType.TEXT, 1), (BlockType.TOOL_RESULT, 1))),+ header_keys=frozenset({"anthropic-version", "anthropic-beta"}),+ ),+)+_ATTEMPTS: Final = (+ AttemptRecord(+ provider="openai",+ provider_status=StatusClass.SUCCESS,+ stream=True,+ deployment_hash="3f9a1c0d2b7e4a61",+ latency_to_first_token_ms=380.0,+ ),+ *(+ AttemptRecord(+ provider="anthropic",+ provider_status=StatusClass.SERVER_ERROR,+ stream=False,+ deployment_hash="8c2e5b9f01d34a77",+ )+ for _ in range(3)+ ),+)+_UI_EVENTS: Final = (+ UIEvent(page="models", action=UIAction.VIEW),+ UIEvent(page="playground", action=UIAction.CLICK, target="tab=compare"),+)+++class _Capture:+ def __init__(self) -> None:+ self.report: Report | None = None++ async def export(self, report: Report) -> ExportOutcome:+ self.report = report+ return ExportOutcome.SENT+++async def sample_report(consent: TelemetryConsent, *, litellm_version: str) -> Report | None:+ """``None`` when the consent sends nothing at all"""+ capture: Final = _Capture()+ times: Final = iter((0.0, SAMPLE_WINDOW_S))+ sink: Final = ConsentGatedSink(AggregatingSink(capture, clock=lambda: next(times)), consent)+ sink.set_instance(+ InstanceInfo(+ instance_id="00000000000000000000000000000000",+ litellm_version=litellm_version,+ config_keys=frozenset({"litellm_settings.cache", "router_settings.routing_strategy"}),+ )+ )+ for request in _REQUESTS:+ sink.record_request(request)+ for attempt in _ATTEMPTS:+ sink.record_attempt(attempt)+ for event in _UI_EVENTS:+ sink.record_ui_event(event)+ await sink.flush()+ return capture.reportdiff --git a/litellm/telemetry/sink.py b/litellm/telemetry/sink.pyindex 13fa6ed7c34..fe4b0e5e871 100644--- a/litellm/telemetry/sink.py+++ b/litellm/telemetry/sink.py@@ -1,6 +1,8 @@+from enum import Enumfrom typing import Protocolfrom litellm.telemetry.records import AttemptRecord, InstanceInfo, RequestRecord, UIEvent+from litellm.telemetry.report import Reportclass TelemetrySink(Protocol):@@ -30,3 +32,13 @@ class NoopSink:async def flush(self) -> None:return None+++class ExportOutcome(str, Enum):+ SENT = "sent"+ REJECTED = "rejected"+ RETRY = "retry"+++class Exporter(Protocol):+ async def export(self, report: Report) -> ExportOutcome: ...diff --git a/tests/unit/telemetry/test_aggregate.py b/tests/unit/telemetry/test_aggregate.pynew file mode 100644index 00000000000..50c706dcc72--- /dev/null+++ b/tests/unit/telemetry/test_aggregate.py@@ -0,0 +1,265 @@+import asyncio+import logging+from dataclasses import dataclass+from typing import Final++import pytest++from litellm.telemetry.aggregate import AggregatingSink+from litellm.telemetry.histogram import ATTEMPT_BOUNDS, BLOCK_COUNT_BOUNDS, LATENCY_BOUNDS_MS, Histogram+from litellm.telemetry.records import (+ AttemptRecord,+ BlockCounts,+ BlockType,+ InstanceInfo,+ RequestRecord,+ StatusClass,+ TelemetryGroup,+ TokenCounts,+ UIAction,+ UIEvent,+)+from litellm.telemetry.report import Report, RequestKey+from litellm.telemetry.sink import Exporter, ExportOutcome+++@dataclass+class _FakeExporter:+ outcome: ExportOutcome = ExportOutcome.SENT+ reports: tuple[Report, ...] = ()++ async def export(self, report: Report) -> ExportOutcome:+ self.reports = (*self.reports, report)+ return self.outcome+++@dataclass+class _Clock:+ now: float = 1000.0++ def __call__(self) -> float:+ return self.now+++_INSTANCE: Final = InstanceInfo(instance_id="i", litellm_version="1.0.0", groups=frozenset(TelemetryGroup))+++def _request(+ *, provider: str = "openai", latency_ms: float = 80.0, tokens: TokenCounts = TokenCounts(), attempts: int = 1+) -> RequestRecord:+ return RequestRecord(+ endpoint="/chat/completions",+ stream=False,+ litellm_status=StatusClass.SUCCESS,+ latency_to_first_byte_ms=latency_ms,+ provider=provider,+ provider_status=StatusClass.SUCCESS,+ provider_attempts=attempts,+ tokens=tokens,+ blocks=BlockCounts(total=2, by_type=((BlockType.TEXT, 2),)),+ header_keys=frozenset({"anthropic-beta"}),+ )+++def _histogram(bounds: tuple[float, ...], *values: float) -> Histogram:+ histogram: Final = Histogram.empty(bounds)+ for value in values:+ histogram.add(value)+ return histogram+++def _sink(exporter: Exporter, clock: _Clock, max_rows: int = 100) -> AggregatingSink:+ sink: Final = AggregatingSink(exporter, clock=clock, max_rows=max_rows)+ sink.set_instance(_INSTANCE)+ return sink+++async def test_requests_with_the_same_dimensions_fold_into_one_row() -> None:+ exporter: Final = _FakeExporter()+ clock: Final = _Clock()+ sink: Final = _sink(exporter, clock)+ sink.record_request(_request(latency_ms=80.0, tokens=TokenCounts(input=10, output=3, cache_read=4), attempts=1))+ sink.record_request(_request(latency_ms=600.0, tokens=TokenCounts(input=5, output=2, cache_read=7), attempts=2))+ clock.now = 1060.0+ await sink.flush()++ (report,) = exporter.reports+ assert (report.window_start, report.window_end) == (1000.0, 1060.0)+ ((key, metrics),) = report.requests+ assert key == RequestKey.of(_request())+ assert (metrics.request_count, metrics.input_tokens, metrics.output_tokens, metrics.cache_read_tokens) == (+ 2,+ 15,+ 5,+ 11,+ )+ assert metrics.latency_to_first_byte == _histogram(LATENCY_BOUNDS_MS, 80.0, 600.0)+ assert metrics.provider_attempts == _histogram(ATTEMPT_BOUNDS, 1, 2)+ assert metrics.block_count == _histogram(BLOCK_COUNT_BOUNDS, 2, 2)+ assert metrics.block_types == {BlockType.TEXT: 4}+ assert metrics.header_keys == {"anthropic-beta": 2}+ assert metrics.latency_to_headers == Histogram.empty(LATENCY_BOUNDS_MS)+++async def test_each_window_starts_empty_after_a_successful_export() -> None:+ exporter: Final = _FakeExporter()+ clock: Final = _Clock()+ sink: Final = _sink(exporter, clock)+ sink.record_request(_request(provider="openai"))+ sink.record_request(_request(provider="anthropic"))+ await sink.flush()+ clock.now = 1100.0+ await sink.flush()++ first, second = exporter.reports+ assert {key.provider for key, _ in first.requests} == {"openai", "anthropic"}+ assert second.requests == ()+ assert second.window_start == first.window_end+++async def test_a_retryable_export_failure_carries_the_window_into_the_next_report() -> None:+ exporter: Final = _FakeExporter(outcome=ExportOutcome.RETRY)+ clock: Final = _Clock()+ sink: Final = _sink(exporter, clock)+ sink.record_request(_request())+ sink.record_attempt(AttemptRecord(provider="openai", provider_status=StatusClass.SUCCESS, stream=False))+ sink.record_ui_event(UIEvent(page="models", action=UIAction.VIEW))+ await sink.flush()+ sink.record_request(_request())+ sink.record_ui_event(UIEvent(page="models", action=UIAction.VIEW))+ exporter.outcome = ExportOutcome.SENT+ clock.now = 2000.0+ await sink.flush()++ retried: Final = exporter.reports[-1]+ assert retried.window_start == 1000.0+ assert retried.requests[0][1].request_count == 2+ assert retried.attempts[0][1].attempt_count == 1+ assert retried.ui_events == ((UIEvent(page="models", action=UIAction.VIEW), 2),)+++async def test_a_rejected_report_is_not_resent() -> None:+ exporter: Final = _FakeExporter(outcome=ExportOutcome.REJECTED)+ sink: Final = _sink(exporter, _Clock())+ sink.record_request(_request())+ await sink.flush()+ await sink.flush()+ assert exporter.reports[-1].requests == ()+++async def test_new_rows_past_the_cap_are_dropped_and_counted_but_existing_rows_keep_folding() -> None:+ exporter: Final = _FakeExporter()+ sink: Final = _sink(exporter, _Clock(), max_rows=1)+ sink.record_request(_request(provider="openai"))+ sink.record_request(_request(provider="anthropic"))+ sink.record_attempt(AttemptRecord(provider="openai", provider_status=StatusClass.SUCCESS, stream=False))+ sink.record_request(_request(provider="openai"))+ await sink.flush()++ (report,) = exporter.reports+ assert [(key.provider, metrics.request_count) for key, metrics in report.requests] == [("openai", 2)]+ assert report.attempts == ()+ assert report.dropped_records == 2+++async def test_nothing_is_exported_before_the_instance_is_known() -> None:+ exporter: Final = _FakeExporter()+ sink: Final = AggregatingSink(exporter, clock=_Clock())+ sink.record_request(_request())+ await sink.flush()+ assert exporter.reports == ()+ sink.set_instance(_INSTANCE)+ await sink.flush()+ assert exporter.reports[0].requests[0][1].request_count == 1+++@dataclass+class _RecordsDuringExport:+ records: tuple[RequestRecord, ...]+ sink: AggregatingSink | None = None+ outcome: ExportOutcome = ExportOutcome.RETRY+ reports: tuple[Report, ...] = ()++ async def export(self, report: Report) -> ExportOutcome:+ self.reports = (*self.reports, report)+ sink: Final = self.sink+ if sink is not None:+ for record in self.records:+ sink.record_request(record)+ return self.outcome+++async def test_a_retried_window_restores_only_up_to_the_row_cap_and_counts_the_rest_as_dropped() -> None:+ exporter: Final = _RecordsDuringExport(records=(_request(provider="bedrock"), _request(provider="vertex_ai")))+ sink: Final = _sink(exporter, _Clock(), max_rows=2)+ exporter.sink = sink+ sink.record_request(_request(provider="openai"))+ sink.record_request(_request(provider="openai"))+ sink.record_request(_request(provider="anthropic"))+ await sink.flush()+ exporter.outcome, exporter.records = ExportOutcome.SENT, ()+ await sink.flush()++ retried: Final = exporter.reports[-1]+ assert [(key.provider, metrics.request_count) for key, metrics in retried.requests] == [+ ("bedrock", 1),+ ("vertex_ai", 1),+ ]+ assert retried.dropped_records == 3+++@dataclass+class _BlockingExporter:+ release: asyncio.Event+ reports: tuple[Report, ...] = ()++ async def export(self, report: Report) -> ExportOutcome:+ self.reports = (*self.reports, report)+ await self.release.wait()+ return ExportOutcome.SENT+++async def test_a_flush_while_another_flush_is_exporting_does_nothing() -> None:+ exporter: Final = _BlockingExporter(release=asyncio.Event())+ sink: Final = AggregatingSink(exporter, clock=_Clock())+ sink.set_instance(_INSTANCE)+ sink.record_request(_request())+ first: Final = asyncio.create_task(sink.flush())+ await asyncio.sleep(0)+ sink.record_request(_request())+ await sink.flush()+ exporter.release.set()+ await first++ assert len(exporter.reports) == 1+ await sink.flush()+ assert exporter.reports[-1].requests[0][1].request_count == 1+++async def test_each_retry_past_the_quiet_limit_logs_an_error_until_an_export_succeeds(+ caplog: pytest.LogCaptureFixture,+) -> None:+ exporter: Final = _FakeExporter(outcome=ExportOutcome.RETRY)+ sink: Final = AggregatingSink(exporter, clock=_Clock(), logger=logging.getLogger("telemetry-test"))+ sink.set_instance(_INSTANCE)+ with caplog.at_level(logging.ERROR, logger="telemetry-test"):+ for _ in range(4):+ await sink.flush()+ exporter.outcome = ExportOutcome.SENT+ await sink.flush()+ exporter.outcome = ExportOutcome.RETRY+ await sink.flush()++ assert [record.getMessage() for record in caplog.records] == [+ "telemetry: report export failed 3 times in a row, keeping the window for the next flush",+ "telemetry: report export failed 4 times in a row, keeping the window for the next flush",+ ]diff --git a/tests/unit/telemetry/test_histogram.py b/tests/unit/telemetry/test_histogram.pynew file mode 100644index 00000000000..ccc29e35f04--- /dev/null+++ b/tests/unit/telemetry/test_histogram.py@@ -0,0 +1,43 @@+import math+from typing import Final++import pytest++from litellm.telemetry.histogram import Histogram++_BOUNDS: Final = (10.0, 100.0)+++def _histogram_of(*values: float | None) -> Histogram:+ histogram: Final = Histogram.empty(_BOUNDS)+ for value in values:+ histogram.add(value)+ return histogram+++ ("value", "expected_counts"),+ [+ (None, [0, 0, 0]),+ (0.0, [1, 0, 0]),+ (10.0, [1, 0, 0]),+ (10.5, [0, 1, 0]),+ (100.0, [0, 1, 0]),+ (100.5, [0, 0, 1]),+ ],+)+def test_a_value_lands_in_the_first_bucket_whose_bound_it_does_not_exceed(+ value: float | None, expected_counts: list[int]+) -> None:+ assert _histogram_of(value) == Histogram(bounds=_BOUNDS, counts=expected_counts, invalid=0)++[email protected]("value", [-1.0, math.nan, math.inf, -math.inf])+def test_a_negative_or_non_finite_value_is_counted_as_invalid_instead_of_bucketed(value: float) -> None:+ assert _histogram_of(value, 5.0) == Histogram(bounds=_BOUNDS, counts=[1, 0, 0], invalid=1)+++def test_add_histogram_adds_bucket_and_invalid_counts() -> None:+ total: Final = _histogram_of(5.0, -1.0)+ total.add_histogram(_histogram_of(5.0, 500.0, math.nan))+ assert total == Histogram(bounds=_BOUNDS, counts=[2, 0, 1], invalid=2)diff --git a/tests/unit/telemetry/test_http_exporter.py b/tests/unit/telemetry/test_http_exporter.pynew file mode 100644index 00000000000..b8efb2e17c9--- /dev/null+++ b/tests/unit/telemetry/test_http_exporter.py@@ -0,0 +1,128 @@+import json+from collections.abc import Mapping, Sequence+from typing import Final++import httpx+import pytest++from litellm.telemetry.histogram import ATTEMPT_BOUNDS, BLOCK_COUNT_BOUNDS, LATENCY_BOUNDS_MS+from litellm.telemetry.records import InstanceInfo, RequestRecord, StatusClass, TelemetryGroup+from litellm.telemetry.report import Report, RequestKey, RequestMetrics+from litellm.telemetry.http_exporter import HttpExporter+from litellm.telemetry.sink import ExportOutcome++_RECORD: Final = RequestRecord(+ endpoint="/v1/messages",+ stream=True,+ litellm_status=StatusClass.SUCCESS,+ provider="anthropic",+ provider_status=StatusClass.SUCCESS,+ latency_to_first_byte_ms=120.0,+)+++def _metrics_of(record: RequestRecord) -> RequestMetrics:+ metrics: Final = RequestMetrics.empty()+ metrics.add(record)+ return metrics+++_REPORT: Final = Report(+ instance=InstanceInfo(instance_id="i", litellm_version="1.2.3", groups=frozenset(TelemetryGroup)),+ window_start=10.0,+ window_end=70.0,+ requests=((RequestKey.of(_RECORD), _metrics_of(_RECORD)),),+)+++def _histogram_json(bounds: tuple[float, ...], hit_index: int | None) -> Mapping[str, Sequence[int] | int]:+ return {"counts": [int(index == hit_index) for index in range(len(bounds) + 1)], "invalid": 0}+++async def test_posts_the_report_as_json() -> None:+ seen: Final[list[httpx.Request]] = [] # mutable-ok: captures what the transport received++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(202)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ outcome: Final = await HttpExporter(client, "https://telemetry.example/v1/reports").export(_REPORT)++ assert outcome is ExportOutcome.SENT+ (request,) = seen+ assert request.url == "https://telemetry.example/v1/reports"+ assert request.headers["content-type"] == "application/json"+ assert json.loads(request.content) == {+ "schema_version": 1,+ "instance": {+ "instance_id": "i",+ "litellm_version": "1.2.3",+ "groups": sorted(group.value for group in TelemetryGroup),+ "config_keys": [],+ },+ "window_start": 10.0,+ "window_end": 70.0,+ "dropped_records": 0,+ "requests": [+ {+ "endpoint": "/v1/messages",+ "provider": "anthropic",+ "deployment_hash": None,+ "litellm_status": "2xx",+ "provider_status": "2xx",+ "litellm_cache_hit": False,+ "handled_by_rust": False,+ "provider_cache_hit": False,+ "stream": True,+ "request_count": 1,+ "input_tokens": 0,+ "output_tokens": 0,+ "cache_read_tokens": 0,+ "block_count": _histogram_json(BLOCK_COUNT_BOUNDS, None),+ "block_types": {},+ "header_keys": {},+ "provider_attempts": _histogram_json(ATTEMPT_BOUNDS, 0),+ "latency_to_headers_ms": _histogram_json(LATENCY_BOUNDS_MS, None),+ "latency_to_first_byte_ms": _histogram_json(LATENCY_BOUNDS_MS, 2),+ }+ ],+ "attempts": [],+ "ui_events": [],+ }+++ ("status_code", "expected"),+ [+ (200, ExportOutcome.SENT),+ (400, ExportOutcome.REJECTED),+ (413, ExportOutcome.REJECTED),+ (425, ExportOutcome.REJECTED),+ (408, ExportOutcome.RETRY),+ (409, ExportOutcome.RETRY),+ (429, ExportOutcome.RETRY),+ (503, ExportOutcome.RETRY),+ ],+)+async def test_status_codes_map_to_outcomes(status_code: int, expected: ExportOutcome) -> None:+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(status_code))) as client:+ assert await HttpExporter(client, "https://telemetry.example").export(_REPORT) is expected+++async def test_a_transport_error_is_retryable_instead_of_raising() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("unreachable", request=request)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ assert await HttpExporter(client, "https://telemetry.example").export(_REPORT) is ExportOutcome.RETRY++[email protected]("endpoint", ["https://[::1/v1/reports", "telemetry.example/v1/reports"])+async def test_an_invalid_endpoint_url_is_rejected_instead_of_retried_forever(endpoint: str) -> None:+ async with httpx.AsyncClient() as client:+ assert await HttpExporter(client, endpoint).export(_REPORT) is ExportOutcome.REJECTEDdiff --git a/tests/unit/telemetry/test_report.py b/tests/unit/telemetry/test_report.pynew file mode 100644index 00000000000..4ad42ab6314--- /dev/null+++ b/tests/unit/telemetry/test_report.py@@ -0,0 +1,95 @@+from typing import Final++from litellm.telemetry.histogram import LATENCY_BOUNDS_MS+from litellm.telemetry.records import (+ AttemptRecord,+ BlockCounts,+ BlockType,+ InstanceInfo,+ RequestRecord,+ StatusClass,+ TelemetryGroup,+ UIAction,+ UIEvent,+)+from litellm.telemetry.report import AttemptKey, AttemptMetrics, Report, RequestKey, RequestMetrics, report_to_json+++def _metrics_of(*records: AttemptRecord) -> AttemptMetrics:+ metrics: Final = AttemptMetrics.empty()+ for record in records:+ metrics.add(record)+ return metrics+++def test_attempt_and_ui_event_rows_serialize_with_merged_counts() -> None:+ first: Final = AttemptRecord(+ provider="bedrock",+ provider_status=StatusClass.SERVER_ERROR,+ stream=True,+ deployment_hash="abc",+ latency_to_first_token_ms=-1.0,+ )+ second: Final = AttemptRecord(+ provider="bedrock",+ provider_status=StatusClass.SERVER_ERROR,+ stream=True,+ deployment_hash="abc",+ latency_to_first_token_ms=200.0,+ )+ report: Final = Report(+ instance=InstanceInfo(instance_id="i", litellm_version="1.0.0", groups=frozenset(TelemetryGroup)),+ window_start=0.0,+ window_end=60.0,+ attempts=((AttemptKey.of(first), _metrics_of(first, second)),),+ ui_events=((UIEvent(page="models", action=UIAction.CLICK, target="add_model"), 3),),+ )++ json_report: Final = report_to_json(report)+ assert isinstance(json_report, dict)+ assert json_report["attempts"] == [+ {+ "provider": "bedrock",+ "deployment_hash": "abc",+ "provider_status": "5xx",+ "stream": True,+ "attempt_count": 2,+ "latency_to_first_token_ms": {"counts": [0, 0, 1, *[0] * (len(LATENCY_BOUNDS_MS) - 2)], "invalid": 1},+ }+ ]+ assert json_report["ui_events"] == [{"page": "models", "action": "click", "target": "add_model", "count": 3}]+++def test_block_types_and_header_keys_serialize_with_merged_counts() -> None:+ first: Final = RequestRecord(+ endpoint="/v1/messages",+ stream=False,+ litellm_status=StatusClass.SUCCESS,+ blocks=BlockCounts(total=3, by_type=((BlockType.TEXT, 2), (BlockType.IMAGE, 1))),+ header_keys=frozenset({"anthropic-beta", "x-custom"}),+ )+ second: Final = RequestRecord(+ endpoint="/v1/messages",+ stream=False,+ litellm_status=StatusClass.SUCCESS,+ blocks=BlockCounts(total=1, by_type=((BlockType.TEXT, 1),)),+ header_keys=frozenset({"anthropic-beta"}),+ )+ metrics: Final = RequestMetrics.empty()+ metrics.add(first)+ metrics.add(second)+ report: Final = Report(+ instance=InstanceInfo(instance_id="i", litellm_version="1.0.0", groups=frozenset(TelemetryGroup)),+ window_start=0.0,+ window_end=60.0,+ requests=((RequestKey.of(first), metrics),),+ )++ json_report: Final = report_to_json(report)+ assert isinstance(json_report, dict)+ (row,) = json_report["requests"]+ assert {key: row[key] for key in ("block_count", "block_types", "header_keys")} == {+ "block_count": {"counts": [1, 1, 0, 0, 0], "invalid": 0},+ "block_types": {"image": 1, "text": 3},+ "header_keys": {"anthropic-beta": 2, "x-custom": 1},+ }diff --git a/tests/unit/telemetry/test_sample.py b/tests/unit/telemetry/test_sample.pynew file mode 100644index 00000000000..7a4e418fc65--- /dev/null+++ b/tests/unit/telemetry/test_sample.py@@ -0,0 +1,83 @@+from typing import Final++import pytest++from litellm.telemetry.consent import OFF, REQUIRES, TelemetryConsent+from litellm.telemetry.records import TelemetryGroup+from litellm.telemetry.report import report_to_json+from litellm.telemetry.sample import sample_report++_REQUEST_FIELDS: Final = {+ TelemetryGroup.REQUEST_SUCCESS: {+ "endpoint",+ "litellm_status",+ "handled_by_rust",+ "latency_to_first_byte_ms",+ "request_count",+ },+ TelemetryGroup.TOKEN_INFO: {"provider_cache_hit", "input_tokens", "cache_read_tokens"},+ TelemetryGroup.REQUEST_TAXONOMY: {"provider", "deployment_hash"},+ TelemetryGroup.EVENT_DETAILS: {"block_count", "block_types", "header_keys"},+}+++def _with_requirements(group: TelemetryGroup) -> frozenset[TelemetryGroup]:+ required: Final = REQUIRES[group]+ parents: Final[frozenset[TelemetryGroup]] = _with_requirements(required) if required is not None else frozenset()+ return frozenset({group}) | parents+++async def test_off_builds_no_report() -> None:+ assert await sample_report(OFF, litellm_version="1.0.0") is None++[email protected]("group", list(_REQUEST_FIELDS))+async def test_each_request_group_adds_exactly_its_own_fields(group: TelemetryGroup) -> None:+ groups: Final = _with_requirements(group)+ with_group: Final = await sample_report(TelemetryConsent(groups), litellm_version="1.0.0")+ without_group: Final = await sample_report(TelemetryConsent(groups - {group}), litellm_version="1.0.0")+ assert with_group is not None and without_group is not None+ rows_with: Final = report_to_json(with_group)["requests"]+ assert isinstance(rows_with, list) and isinstance(rows_with[0], dict)+ rows_without: Final = report_to_json(without_group).get("requests", [{}])+ assert isinstance(rows_without, list) and isinstance(rows_without[0], dict)+ assert _REQUEST_FIELDS[group] <= set(rows_with[0]) - set(rows_without[0])+++async def test_heartbeat_only_sample_is_just_the_instance_header() -> None:+ report: Final = await sample_report(TelemetryConsent(frozenset({TelemetryGroup.HEARTBEAT})), litellm_version="2.0")+ assert report is not None+ assert report_to_json(report) == {+ "schema_version": 1,+ "instance": {"instance_id": "0" * 32, "litellm_version": "2.0", "groups": ["heartbeat"]},+ "window_start": 0.0,+ "window_end": 300.0,+ "dropped_records": 0,+ }+++async def test_without_taxonomy_rows_from_different_providers_with_the_same_status_merge() -> None:+ consent: Final = TelemetryConsent(_with_requirements(TelemetryGroup.TOKEN_INFO))+ report: Final = await sample_report(consent, litellm_version="1.0.0")+ assert report is not None+ assert len(report.requests) == 2+ assert all(key.provider is None for key, _ in report.requests)+ assert report.attempts == ()+++async def test_instance_configuration_adds_config_keys_and_page_navigation_adds_ui_events() -> None:+ consent: Final = TelemetryConsent(+ frozenset({TelemetryGroup.HEARTBEAT, TelemetryGroup.INSTANCE_CONFIGURATION, TelemetryGroup.PAGE_NAVIGATION})+ )+ report: Final = await sample_report(consent, litellm_version="1.0.0")+ assert report is not None+ json_report: Final = report_to_json(report)+ instance: Final = json_report["instance"]+ assert isinstance(instance, dict) and instance["config_keys"]+ assert json_report["ui_events"]+ assert "requests" not in json_report