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
fix(langfuse_otel)!: send the completion start time (#45597)
Max Azatian5145250d83db
diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.pyindex e5bd38bb7ed..f44e3f6a81b 100644--- a/litellm/a2a_protocol/main.py+++ b/litellm/a2a_protocol/main.py@@ -602,9 +602,9 @@ def _build_streaming_logging_obj(litellm_params: dict[str, object] | None,metadata: dict[str, object] | None,proxy_server_request: dict[str, object] | None,+ start_time: datetime.datetime,) -> Logging:"""Build logging object for streaming A2A requests."""- start_time: Final = datetime.datetime.now()model: Final = f"a2a_agent/{agent_name}"logging_obj: Final = Logging(@@ -718,6 +718,7 @@ async def asend_message_streaming(if request is None:raise ValueError("request is required")+ called_at: Final = datetime.datetime.now()_raw_logging_obj: Final = kwargs.get("litellm_logging_obj")logging_obj: Logging | None = _raw_logging_obj if isinstance(_raw_logging_obj, Logging) else None@@ -751,6 +752,7 @@ async def asend_message_streaming(litellm_params=litellm_params,metadata=metadata,proxy_server_request=proxy_server_request,+ start_time=called_at,)verbose_logger.info("A2A send_message_streaming request_id=%s, agent=%s", request.id, agent_name)diff --git a/litellm/a2a_protocol/streaming_iterator.py b/litellm/a2a_protocol/streaming_iterator.pyindex 0b649f62a66..328681b8dbe 100644--- a/litellm/a2a_protocol/streaming_iterator.py+++ b/litellm/a2a_protocol/streaming_iterator.py@@ -41,7 +41,7 @@ class A2AStreamingIterator:self.request = requestself.logging_obj = logging_objself.agent_name = agent_name- self.start_time = datetime.now()+ self.start_time = logging_obj.start_time# Collect chunks for token countingself.chunks: list[SendStreamingMessageResponse] = []@@ -54,6 +54,8 @@ class A2AStreamingIterator:async def __anext__(self) -> "SendStreamingMessageResponse":try:chunk: Final = await self.stream.__anext__()+ if self.logging_obj.completion_start_time is None:+ self.logging_obj.update_completion_start_time(completion_start_time=datetime.now())# Store chunkself.chunks.append(chunk)diff --git a/litellm/google_genai/streaming_iterator.py b/litellm/google_genai/streaming_iterator.pyindex 37d08dfb59a..a22c47cb1e7 100644--- a/litellm/google_genai/streaming_iterator.py+++ b/litellm/google_genai/streaming_iterator.py@@ -71,7 +71,7 @@ class BaseGoogleGenAIGenerateContentStreamingIterator:):self.litellm_logging_obj = litellm_logging_objself.request_body = request_body- self.start_time = datetime.now()+ self.start_time = litellm_logging_obj.start_timeself.collected_chunks: list[bytes] = []self.model = modelself.custom_llm_provider = custom_llm_provider@@ -192,6 +192,8 @@ class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateCoasync def __anext__(self):try:chunk: Final = await _anext_google_genai_sse_chunk(self.stream_iterator)+ if self.litellm_logging_obj.completion_start_time is None:+ self.litellm_logging_obj.update_completion_start_time(completion_start_time=datetime.now())self.collected_chunks.append(chunk)return chunkexcept StopAsyncIteration:diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.pyindex ae63ab99929..f195cd97e3c 100644--- a/litellm/integrations/langfuse/langfuse_otel.py+++ b/litellm/integrations/langfuse/langfuse_otel.py@@ -1,7 +1,7 @@import base64import jsonimport os-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Final, Optional@@ -9,6 +9,7 @@ from litellm._logging import verbose_loggerfrom litellm.integrations.arize import _utilsfrom litellm.integrations.langfuse.langfuse_otel_attributes import (LangfuseLLMObsOTELAttributes,+ serialize_langfuse_datetime,)from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfigfrom litellm.litellm_core_utils.safe_json_loads import safe_json_loads@@ -55,7 +56,7 @@ class LangfuseOtelLogger(OpenTelemetry):LangfuseOtelLogger._set_langfuse_specific_attributes(span=span, kwargs=kwargs, response_obj=response_obj)@staticmethod- def _extract_langfuse_metadata(kwargs: dict) -> dict:+ def _extract_langfuse_metadata(kwargs: Mapping[str, Any]) -> dict:"""Extracts Langfuse metadata from the standard LiteLLM kwargs structure.@@ -221,7 +222,7 @@ class LangfuseOtelLogger(OpenTelemetry):)@staticmethod- def _set_langfuse_specific_attributes(span: Span, kwargs, response_obj):+ def _set_langfuse_specific_attributes(span: Span, kwargs: Mapping[str, Any], response_obj):"""Sets Langfuse specific metadata attributes onto the OTEL span.@@ -255,6 +256,14 @@ class LangfuseOtelLogger(OpenTelemetry):safe_dumps(messages),)+ completion_start_time: Final = kwargs.get("completion_start_time")+ if isinstance(completion_start_time, datetime):+ safe_set_attribute(+ span,+ LangfuseSpanAttributes.OBSERVATION_COMPLETION_START_TIME.value,+ serialize_langfuse_datetime(completion_start_time),+ )+LangfuseOtelLogger._set_observation_output(span=span, response_obj=response_obj)@staticmethoddiff --git a/litellm/integrations/langfuse/langfuse_otel_attributes.py b/litellm/integrations/langfuse/langfuse_otel_attributes.pyindex 1eb3ce1a9c2..2873dba93ed 100644--- a/litellm/integrations/langfuse/langfuse_otel_attributes.py+++ b/litellm/integrations/langfuse/langfuse_otel_attributes.py@@ -6,6 +6,7 @@ Relevant Issue: https://github.com/BerriAI/litellm/issues/13764import jsonfrom collections.abc import Mapping+from datetime import datetimefrom typing import TYPE_CHECKING, Any, Finalfrom pydantic import BaseModel@@ -29,6 +30,10 @@ if TYPE_CHECKING:from opentelemetry.trace import Span+def serialize_langfuse_datetime(value: datetime) -> str:+ return json.dumps(value.astimezone().isoformat())++def get_output_content_by_type(response_obj: None| dictdiff --git a/litellm/integrations/langfuse/langfuse_sdk.py b/litellm/integrations/langfuse/langfuse_sdk.pyindex 864c0697eb3..51b08cb72df 100644--- a/litellm/integrations/langfuse/langfuse_sdk.py+++ b/litellm/integrations/langfuse/langfuse_sdk.py@@ -39,6 +39,7 @@ from pydantic import ConfigDictimport litellmfrom litellm._logging import verbose_loggerfrom litellm.integrations.langfuse.langfuse import PROMPT_CACHE_TTL_ENV, parse_langfuse_debug, whole_number+from litellm.integrations.langfuse.langfuse_otel_attributes import serialize_langfuse_datetimefrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.llms.custom_httpx.http_handler import HTTPHandler, get_httpx_clientfrom litellm.types.llms.base import LiteLLMBaseModel@@ -168,7 +169,7 @@ def _string_or_none(value: object) -> str | None:def _serialize_datetime(value: object) -> str | None:"""A datetime the way the SDK's ``EventSerializer`` sends one: a JSON string, naive values read as local time."""if isinstance(value, datetime):- return safe_dumps(value.astimezone().isoformat())+ return serialize_langfuse_datetime(value)return _serialize(value)diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.pyindex 73448221acb..5092b248eac 100644--- a/litellm/integrations/otel/logger.py+++ b/litellm/integrations/otel/logger.py@@ -594,6 +594,7 @@ class OpenTelemetryV2(CustomLogger):payload,capture_content=self._capture_span_content(),time_to_first_chunk_seconds=call.time_to_first_chunk_seconds,+ completion_start_seconds=call.completion_start_seconds,request_route=request_root_http_route(),request_purpose=call.purpose,trace=call.trace,diff --git a/litellm/integrations/otel/mappers/langfuse.py b/litellm/integrations/otel/mappers/langfuse.pyindex 68860931b76..e60ea539188 100644--- a/litellm/integrations/otel/mappers/langfuse.py+++ b/litellm/integrations/otel/mappers/langfuse.py@@ -12,8 +12,10 @@ the JSON-serialized payloads. ``trace_attributes`` maps the caller's trace contrimport jsonfrom collections.abc import Callable+from datetime import datetime, timezonefrom typing import Final+from litellm.integrations.langfuse.langfuse_otel_attributes import serialize_langfuse_datetimefrom litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanDatafrom litellm.integrations.otel.mappers.utils import (collect,@@ -45,6 +47,11 @@ class LangfuseMapper:"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,+ "langfuse.observation.completion_start_time": lambda d: (+ serialize_langfuse_datetime(datetime.fromtimestamp(d.completion_start_seconds, tz=timezone.utc))+ if d.completion_start_seconds is not None+ else None+ ),}# Sub-tables folded into their respective JSON blobs.diff --git a/litellm/integrations/otel/model/metadata.py b/litellm/integrations/otel/model/metadata.pyindex a3151c24519..5d37894bb8f 100644--- a/litellm/integrations/otel/model/metadata.py+++ b/litellm/integrations/otel/model/metadata.py@@ -258,6 +258,7 @@ class LLMCallEvent:# needs to be reasonable for a span that never gets closed (a leak).provisional_span_name: strtime_to_first_chunk_seconds: float | None+ completion_start_seconds: float | Nonetrace: TraceControlssession_id: str | None@@ -280,6 +281,7 @@ class LLMCallEvent:cache_hit=bool(payload.get("cache_hit")) if payload else False, # pyright: ignore[reportUnknownMemberType] # TypedDict .get on a str key is partially unknownprovisional_span_name=f"{operation.value} {model}".strip(),time_to_first_chunk_seconds=time_to_first_chunk_seconds(kwargs),+ completion_start_seconds=_epoch_seconds(kwargs.get("completion_start_time")),trace=trace,session_id=caller_session_id(kwargs, trace),)diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.pyindex e15072c009b..d11505ce026 100644--- a/litellm/integrations/otel/model/payloads.py+++ b/litellm/integrations/otel/model/payloads.py@@ -429,6 +429,7 @@ class LLMCallSpanData:choices_out: tuple[Mapping[str, object], ...] = ()system_fingerprint: str | None = Nonetime_to_first_chunk_seconds: float | None = None+ completion_start_seconds: float | None = None# The requested output modality, set only on the routes that pin one (image# generation, speech, transcription, OCR), and the litellm route itself, which# keeps routes the convention folds into one operation distinguishable.@@ -450,6 +451,7 @@ class LLMCallSpanData:payload: StandardLoggingPayload,capture_content: bool = False,time_to_first_chunk_seconds: float | None = None,+ completion_start_seconds: float | None = None,request_route: str | None = None,request_purpose: str | None = None,trace: TraceControls | None = None,@@ -503,6 +505,7 @@ class LLMCallSpanData:choices_out=choices_out if capture_content else (),system_fingerprint=as_str(response.get("system_fingerprint")),time_to_first_chunk_seconds=time_to_first_chunk_seconds,+ completion_start_seconds=completion_start_seconds,output_type=resolve_output_type(call_type),call_type=call_type or None,request_route=request_route or context.identity.request_route,diff --git a/litellm/interactions/streaming_iterator.py b/litellm/interactions/streaming_iterator.pyindex 64b599edfe2..a2468cd894f 100644--- a/litellm/interactions/streaming_iterator.py+++ b/litellm/interactions/streaming_iterator.py@@ -48,7 +48,7 @@ class BaseInteractionsAPIStreamingIterator:self.finished = Falseself.interactions_api_config = interactions_api_configself.completed_response: InteractionsAPIStreamingResponse | None = None- self.start_time = datetime.now()+ self.start_time = logging_obj.start_time# set request kwargsself.litellm_metadata = litellm_metadata@@ -87,6 +87,8 @@ class BaseInteractionsAPIStreamingIterator:# Format as InteractionsAPIStreamingResponseif isinstance(parsed_chunk, dict):+ if self.logging_obj.completion_start_time is None:+ self.logging_obj.update_completion_start_time(completion_start_time=datetime.now())streaming_response: Final = self.interactions_api_config.transform_streaming_response(model=self.model,parsed_chunk=parsed_chunk,diff --git a/litellm/llms/anthropic/pass_through/messages/response_cache.py b/litellm/llms/anthropic/pass_through/messages/response_cache.pyindex 4c5f47bc650..81d01f1437e 100644--- a/litellm/llms/anthropic/pass_through/messages/response_cache.py+++ b/litellm/llms/anthropic/pass_through/messages/response_cache.py@@ -1,5 +1,6 @@import refrom collections.abc import AsyncIterator, Mapping, Sequence+from datetime import datetimefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, cast@@ -153,6 +154,8 @@ class CachedAnthropicMessagesStreamIterator(BaseAnthropicMessagesStreamingIteratawait self._handle_streaming_logging(chunks)raise StopAsyncIterationchunk: Final = self.chunks[self.current_index]+ if self.completion_start_time is None:+ self.completion_start_time = datetime.now()self.current_index += 1return chunkdiff --git a/litellm/llms/anthropic/pass_through/messages/streaming_iterator.py b/litellm/llms/anthropic/pass_through/messages/streaming_iterator.pyindex 44db193ea83..bfa309fad83 100644--- a/litellm/llms/anthropic/pass_through/messages/streaming_iterator.py+++ b/litellm/llms/anthropic/pass_through/messages/streaming_iterator.py@@ -506,7 +506,7 @@ class BaseAnthropicMessagesStreamingIterator:):self.litellm_logging_obj = litellm_logging_objself.request_body = request_body- self.start_time = datetime.now()+ self.start_time = litellm_logging_obj.start_timeself.completion_start_time: datetime | None = Noneasync def _handle_streaming_logging(self, collected_chunks: list[bytes], *, stream_teardown: bool = False):diff --git a/litellm/types/integrations/langfuse_otel.py b/litellm/types/integrations/langfuse_otel.pyindex 4bcd0448c3a..5647f28c757 100644--- a/litellm/types/integrations/langfuse_otel.py+++ b/litellm/types/integrations/langfuse_otel.py@@ -29,6 +29,7 @@ class LangfuseSpanAttributes(str, Enum):# ---- Observation input/output ----OBSERVATION_INPUT = "langfuse.observation.input"OBSERVATION_OUTPUT = "langfuse.observation.output"+ OBSERVATION_COMPLETION_START_TIME = "langfuse.observation.completion_start_time"# ---- Trace-level metadata ----TRACE_USER_ID = "user.id"diff --git a/tests/integration/observability/test_arize_otel_v2_openinference_family.py b/tests/integration/observability/test_arize_otel_v2_openinference_family.pyindex 242b7bfe8c1..0b0c077cbee 100644--- a/tests/integration/observability/test_arize_otel_v2_openinference_family.py+++ b/tests/integration/observability/test_arize_otel_v2_openinference_family.py@@ -43,6 +43,7 @@ _GENAI_B3_KEYS_WITHOUT_BAGGAGE: Final = frozenset("gen_ai.usage.prompt_tokens","gen_ai.usage.total_tokens","litellm.api_key.hash",+ "litellm.cache_hit","litellm.call_id","litellm.call_type","litellm.cost.discount_amount",@@ -85,6 +86,7 @@ _LANGFUSE_B3_KEYS: Final = frozenset("gen_ai.usage.output_tokens","gen_ai.usage.prompt_tokens","gen_ai.usage.total_tokens",+ "langfuse.observation.completion_start_time","langfuse.observation.cost_details","langfuse.observation.id","langfuse.observation.input",@@ -94,6 +96,7 @@ _LANGFUSE_B3_KEYS: Final = frozenset("langfuse.observation.type","langfuse.observation.usage_details","litellm.api_key.hash",+ "litellm.cache_hit","litellm.call_id","litellm.call_type","litellm.cost.discount_amount",diff --git a/tests/unit/a2a_protocol/test_a2a_streaming_iterator.py b/tests/unit/a2a_protocol/test_a2a_streaming_iterator.pyindex 2e883e91fda..6d685674984 100644--- a/tests/unit/a2a_protocol/test_a2a_streaming_iterator.py+++ b/tests/unit/a2a_protocol/test_a2a_streaming_iterator.py@@ -6,6 +6,8 @@ async_success_handler (cross-thread pydantic mutation segfaults pydantic-core).import asyncioimport time+from datetime import datetime+from typing import Finalfrom types import SimpleNamespaceimport pytest@@ -135,3 +137,55 @@ async def test_stream_completion_counts_tokens_off_the_event_loop(monkeypatch):assert usage.prompt_tokens > 100_000assert usage.completion_tokens > 100_000assert_loop_stayed_free(took, lags)+++class _SuccessRecorder(CustomLogger):+ def __init__(self):+ super().__init__()+ self.logged: list[tuple[datetime, object]] = []++ async def async_log_success_event(+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged.append((start_time, kwargs.get("completion_start_time")))++ async def async_log_stream_event(+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged.append((start_time, kwargs.get("completion_start_time")))+++async def test_stream_logs_its_first_chunk_time_measured_from_the_call_start():+ call_start: Final = datetime(2026, 10, 9, 12, 0, 0)+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = LitellmLogging(+ model="a2a/test-agent",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ call_type="a2a_send_message_streaming",+ start_time=call_start,+ litellm_call_id="a2a-first-chunk",+ function_id="a2a-first-chunk",+ dynamic_async_success_callbacks=[recorder],+ )++ async def _stream():+ yield _AgentChunk("Hel")+ yield _AgentChunk("Hello")++ iterator: Final = A2AStreamingIterator(+ stream=_stream(),+ request=SimpleNamespace(params=SimpleNamespace(message={"role": "user", "parts": [{"kind": "text", "text": "hi"}]})),+ logging_obj=logging_obj,+ agent_name="test-agent",+ )+ tasks_before: Final = asyncio.all_tasks()++ _ = await iterator.__anext__()+ first_chunk_at: Final = logging_obj.completion_start_time+ _ = [chunk async for chunk in iterator]+ await asyncio.gather(*(asyncio.all_tasks() - tasks_before))++ assert first_chunk_at is not None+ assert recorder.logged == [(call_start, first_chunk_at)]diff --git a/tests/unit/a2a_protocol/test_main.py b/tests/unit/a2a_protocol/test_main.pyindex bab14dd26d6..75fd9eda75b 100644--- a/tests/unit/a2a_protocol/test_main.py+++ b/tests/unit/a2a_protocol/test_main.py@@ -1,7 +1,9 @@"""Tests for litellm/a2a_protocol/main.py non-streaming send behavior."""import asyncio+import datetimeimport json+from typing import Finalimport httpximport pytest@@ -155,6 +157,7 @@ def test_streaming_logging_obj_carries_call_type_into_model_call_details():litellm_params=None,metadata=None,proxy_server_request=None,+ start_time=datetime.datetime(2026, 10, 20, 12, 0, 0),)assert logging_obj.model_call_details["call_type"] == "asend_message_streaming"@@ -352,6 +355,7 @@ async def _seed_shared_a2a_client(rpc_reply=_RPC_REPLY,rpc_stream_events=None,provider: str = httpxSpecialProvider.A2AProvider,+ recorder: _RequestRecorder | None = None,) -> _RequestRecorder:"""Put the one A2A client the cache will hand out behind a mock transport.@@ -359,10 +363,12 @@ async def _seed_shared_a2a_client(it. The injected client is a real httpx.AsyncClient, so the merge of per-requestheaders over client defaults, which is what these tests are about, stays real."""- recorder = _RequestRecorder(card=card, rpc_reply=rpc_reply, rpc_stream_events=rpc_stream_events)+ active_recorder: Final = recorder or _RequestRecorder(+ card=card, rpc_reply=rpc_reply, rpc_stream_events=rpc_stream_events+ )handler = AsyncHTTPHandler(timeout=DEFAULT_A2A_AGENT_TIMEOUT)owned_client = handler.client- handler.client = httpx.AsyncClient(transport=httpx.MockTransport(recorder))+ handler.client = httpx.AsyncClient(transport=httpx.MockTransport(active_recorder))await owned_client.aclose()litellm.in_memory_llm_clients_cache.set_cache(@@ -374,8 +380,8 @@ async def _seed_shared_a2a_client()assert seeded is handler, "cache key drifted from get_async_httpx_client; these tests would test nothing"- recorder.client = handler.client- return recorder+ active_recorder.client = handler.client+ return active_recorder@pytest.fixture@@ -679,6 +685,43 @@ class _UsageRecorder(CustomLogger):self.logged.set()+class _CardServedAtRecorder(_RequestRecorder):+ def __init__(self) -> None:+ super().__init__(rpc_stream_events=_LANGGRAPH_STREAM_EVENTS)+ self.card_served_at: datetime.datetime | None = None++ def __call__(self, request: httpx.Request) -> httpx.Response:+ if request.method == "GET" and self.card_served_at is None:+ self.card_served_at = datetime.datetime.now()+ return super().__call__(request)+++async def test_streamed_send_is_timed_from_before_the_agent_card_fetch(+ isolated_client_cache: LLMClientCache, monkeypatch: pytest.MonkeyPatch+):+ from litellm.a2a_protocol import main as a2a_main++ card_recorder: Final = _CardServedAtRecorder()+ await _seed_shared_a2a_client(recorder=card_recorder)+ logger: Final = _UsageRecorder()+ monkeypatch.setattr(litellm, "callbacks", [logger])+ monkeypatch.setattr(litellm, "success_callback", [logger])+ monkeypatch.setattr(litellm, "_async_success_callback", [logger])+ request: Final = SendStreamingMessageRequest(+ id="reply",+ params=MessageSendParams(+ message={"messageId": "m-user", "role": "user", "parts": [{"kind": "text", "text": "hi"}]}+ ),+ )++ _ = [chunk async for chunk in a2a_main.asend_message_streaming(request=request, api_base="http://127.0.0.1:9")]+ await asyncio.wait_for(logger.logged.wait(), timeout=10)++ assert card_recorder.card_served_at is not None+ assert logger.payload["startTime"] <= card_recorder.card_served_at.timestamp()++@pytest.mark.asyncioasync def test_asend_message_counts_usage_off_the_event_loop(monkeypatch):from tests.large_text import text@@ -742,6 +785,7 @@ def test_streaming_logging_obj_keeps_agent_credentials_out_of_logging_params():},metadata={"user_api_key": "hashed"},proxy_server_request={"url": "http://localhost:4000"},+ start_time=datetime.datetime(2026, 10, 20, 12, 0, 0),)expected = {diff --git a/tests/unit/google_genai/test_google_genai_streaming_iterator.py b/tests/unit/google_genai/test_google_genai_streaming_iterator.pyindex e8ec2848233..120c99b6e42 100644--- a/tests/unit/google_genai/test_google_genai_streaming_iterator.py+++ b/tests/unit/google_genai/test_google_genai_streaming_iterator.py@@ -1,16 +1,55 @@+import asyncioimport json+from datetime import datetime+from typing import Finalfrom unittest.mock import MagicMock+import httpximport pytestfrom litellm.google_genai.streaming_iterator import (AsyncGoogleGenAIGenerateContentStreamingIterator,GoogleGenAIGenerateContentStreamingIterator,)+from litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType+class _SuccessRecorder(CustomLogger):+ def __init__(self):+ super().__init__()+ self.logged: list[tuple[datetime, object]] = []++ async def async_log_success_event(+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged.append((start_time, kwargs.get("completion_start_time")))+++def _logging_obj(+ start_time: datetime = datetime(2026, 10, 9, 12, 0, 0), recorder: _SuccessRecorder | None = None+) -> LiteLLMLoggingObj:+ logging_obj: Final = LiteLLMLoggingObj(+ model="gemini-3.1-flash",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ call_type="agenerate_content_stream",+ start_time=start_time,+ litellm_call_id="google-genai-stream",+ function_id="google-genai-stream",+ dynamic_async_success_callbacks=[recorder] if recorder else None,+ )+ logging_obj.update_environment_variables(+ model="gemini-3.1-flash",+ user="",+ optional_params={},+ litellm_params={"custom_llm_provider": "gemini"},+ custom_llm_provider="gemini",+ )+ return logging_obj++@pytest.mark.parametrize("custom_llm_provider, expected_endpoint_type",[("gemini", EndpointType.GEMINI), ("vertex_ai", EndpointType.VERTEX_AI)],@@ -31,7 +70,7 @@ def test_streaming_logging_targets_the_provider_that_served_the_request(iterator = iterator_cls(response=MagicMock(),model="gemini-3.1-flash-image",- logging_obj=MagicMock(spec=LiteLLMLoggingObj),+ logging_obj=_logging_obj(),generate_content_provider_config=MagicMock(),litellm_metadata={},custom_llm_provider=custom_llm_provider,@@ -73,7 +112,7 @@ async def test_async_streaming_iterator_yields_complete_sse_events():iterator = AsyncGoogleGenAIGenerateContentStreamingIterator(response=mock_response,model="gemini-3.1-flash-image-preview",- logging_obj=MagicMock(spec=LiteLLMLoggingObj),+ logging_obj=_logging_obj(),generate_content_provider_config=MagicMock(),litellm_metadata={},custom_llm_provider="gemini",@@ -95,7 +134,7 @@ def test_sync_streaming_iterator_yields_complete_sse_events():iterator = GoogleGenAIGenerateContentStreamingIterator(response=mock_response,model="gemini-3.1-flash-image-preview",- logging_obj=MagicMock(spec=LiteLLMLoggingObj),+ logging_obj=_logging_obj(),generate_content_provider_config=MagicMock(),litellm_metadata={},custom_llm_provider="gemini",@@ -123,7 +162,7 @@ async def test_async_streaming_iterator_preserves_multi_field_sse_event():iterator = AsyncGoogleGenAIGenerateContentStreamingIterator(response=mock_response,model="gemini-test",- logging_obj=MagicMock(spec=LiteLLMLoggingObj),+ logging_obj=_logging_obj(),generate_content_provider_config=MagicMock(),litellm_metadata={},custom_llm_provider="gemini",@@ -146,7 +185,7 @@ async def test_async_streaming_iterator_forwards_sse_comment_events():iterator = AsyncGoogleGenAIGenerateContentStreamingIterator(response=mock_response,model="gemini-test",- logging_obj=MagicMock(spec=LiteLLMLoggingObj),+ logging_obj=_logging_obj(),generate_content_provider_config=MagicMock(),litellm_metadata={},custom_llm_provider="gemini",@@ -154,3 +193,38 @@ async def test_async_streaming_iterator_forwards_sse_comment_events():chunk = await iterator.__anext__()assert chunk == b": keepalive\n\n"+++def _gemini_event(text: str, finish_reason: str | None = None) -> str:+ candidate: Final = {"content": {"role": "model", "parts": [{"text": text}]}, "index": 0}+ payload: Final = {+ "candidates": [{**candidate, "finishReason": finish_reason} if finish_reason else candidate],+ "usageMetadata": {"promptTokenCount": 3, "candidatesTokenCount": 2, "totalTokenCount": 5},+ "modelVersion": "gemini-3.1-flash",+ }+ return f"data: {json.dumps(payload)}\n\n"+++async def test_async_stream_logs_its_first_chunk_time_measured_from_the_call_start():+ call_start: Final = datetime(2026, 10, 9, 12, 0, 0)+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = _logging_obj(call_start, recorder)+ response: Final = httpx.Response(200, content=(_gemini_event("Hel") + _gemini_event("lo", "STOP")).encode())+ iterator: Final = AsyncGoogleGenAIGenerateContentStreamingIterator(+ response=response,+ model="gemini-3.1-flash",+ logging_obj=logging_obj,+ generate_content_provider_config=MagicMock(),+ litellm_metadata={},+ custom_llm_provider="gemini",+ )+ tasks_before: Final = asyncio.all_tasks()++ _ = await iterator.__anext__()+ first_chunk_at: Final = logging_obj.completion_start_time+ _ = [chunk async for chunk in iterator]+ await asyncio.gather(*(asyncio.all_tasks() - tasks_before))++ assert first_chunk_at is not None+ assert recorder.logged == [(call_start, first_chunk_at)]diff --git a/tests/unit/integrations/otel/test_langfuse_logger.py b/tests/unit/integrations/otel/test_langfuse_logger.pyindex ff2060d91c2..d55f0577e03 100644--- a/tests/unit/integrations/otel/test_langfuse_logger.py+++ b/tests/unit/integrations/otel/test_langfuse_logger.py@@ -4,6 +4,7 @@ stamped from the request task while the root span is still recording, so Langfusimport asyncioimport jsonfrom collections.abc import AsyncIterator, Mapping, Sequence+from datetime import datetime, timezonefrom typing import Finalimport pytest@@ -11,6 +12,7 @@ import pytestpytest.importorskip("opentelemetry")from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter # noqa: E402+from opentelemetry.trace import SpanKind # noqa: E402import litellm # noqa: E402from litellm.caching.dual_cache import DualCache # noqa: E402@@ -43,6 +45,7 @@ from litellm.types.utils import ( # noqa: E402INPUT_ATTR: Final = "langfuse.observation.input"OUTPUT_ATTR: Final = "langfuse.observation.output"TRACE_NAME_ATTR: Final = "langfuse.trace.name"+COMPLETION_START_ATTR: Final = "langfuse.observation.completion_start_time"TRACE_CONTROL_ATTRS: Final = (TRACE_NAME_ATTR, "user.id", "session.id", "langfuse.trace.tags")CHAT_DATA: Final = {"model": "gpt-5.4-mini", "messages": [{"role": "user", "content": "ping"}]}@@ -541,3 +544,53 @@ def test_langfuse_otel_preset_builds_a_logger_that_stamps_the_root(monkeypatch):assert INPUT_ATTR in attrs and OUTPUT_ATTR in attrsfinally:is_otel_v2_enabled.cache_clear()+++def _llm_call_kwargs(optional_params: Mapping[str, object], completion_start: datetime | None) -> dict[str, object]:+ return {+ "standard_logging_object": {+ "litellm_call_id": "call_1",+ "call_type": "acompletion",+ "custom_llm_provider": "openai",+ "model": "gpt-5.4-mini",+ "stream": bool(optional_params.get("stream")),+ "status": "success",+ "completionStartTime": datetime(2026, 10, 9, 12, 0, 9, tzinfo=timezone.utc).timestamp(),+ },+ "litellm_params": {"metadata": {}},+ "optional_params": optional_params,+ "api_call_start_time": datetime(2026, 10, 9, 12, 0, 0, tzinfo=timezone.utc),+ "completion_start_time": completion_start,+ }+++def _generation_attrs(kwargs: dict[str, object], *, fail: bool = False) -> Mapping[str, object]:+ logger, exporter = _logger()+ logger.log_pre_api_call(model="gpt-5.4-mini", messages=[], kwargs=kwargs)+ hook: Final = logger.async_log_failure_event if fail else logger.async_log_success_event+ asyncio.run(hook(kwargs, None, None, None))+ (generation,) = [span for span in exporter.get_finished_spans() if span.kind is SpanKind.CLIENT]+ return dict(generation.attributes or {})+++ "optional_params",+ [+ pytest.param({"stream": True}, id="streamed"),+ pytest.param({}, id="not_streamed_or_pass_through_stream"),+ ],+)+def test_generation_carries_litellms_completion_start_time_like_the_default_emitter(+ optional_params: Mapping[str, object],+) -> None:+ completion_start: Final = datetime(2026, 10, 9, 12, 0, 0, 250000, tzinfo=timezone.utc)++ attrs: Final = _generation_attrs(_llm_call_kwargs(optional_params, completion_start))++ assert datetime.fromisoformat(json.loads(attrs[COMPLETION_START_ATTR])) == completion_start+++def test_failed_generation_without_a_first_chunk_has_no_completion_start_time() -> None:+ attrs: Final = _generation_attrs(_llm_call_kwargs({"stream": True}, None), fail=True)++ assert COMPLETION_START_ATTR not in attrsdiff --git a/tests/unit/integrations/otel/test_otel_v2_vendor_mappers.py b/tests/unit/integrations/otel/test_otel_v2_vendor_mappers.pyindex ca7a9b424ad..7e112fcf6a4 100644--- a/tests/unit/integrations/otel/test_otel_v2_vendor_mappers.py+++ b/tests/unit/integrations/otel/test_otel_v2_vendor_mappers.py@@ -7,6 +7,7 @@ backends, so one trace lights up every configured destination.import jsonfrom collections.abc import Mapping+from datetime import datetime, timezonefrom itertools import chainfrom typing import Final@@ -580,6 +581,32 @@ def test_langfuse_usage_details_omit_zero_cache_and_reasoning_counts():assert usage == {"input": 12, "output": 8, "total": 20}+def _langfuse_payload() -> dict[str, object]:+ return {+ "call_type": "acompletion",+ "custom_llm_provider": "openai",+ "model": "gpt-4o",+ "completionStartTime": 1791547299.0,+ }+++def test_langfuse_mapper_sends_the_completion_start_time_as_the_sdks_json_string():+ data: Final = LLMCallSpanData.from_standard_logging_payload(+ _langfuse_payload(), completion_start_seconds=1791547200.25+ )++ attrs: Final = LangfuseMapper().map(data)++ sent: Final = datetime.fromisoformat(json.loads(attrs["langfuse.observation.completion_start_time"]))+ assert sent == datetime(2026, 10, 9, 12, 0, 0, 250000, tzinfo=timezone.utc)+++def test_langfuse_mapper_ignores_the_payloads_end_time_fallback_when_litellm_recorded_no_completion_start():+ attrs: Final = LangfuseMapper().map(LLMCallSpanData.from_standard_logging_payload(_langfuse_payload()))++ assert "langfuse.observation.completion_start_time" not in attrs++def test_langfuse_mapper_names_the_trace_from_the_caller():named = LangfuseMapper().map(_llm_call(trace=TraceControls(name="nightly-eval")))assert named["langfuse.trace.name"] == "nightly-eval"diff --git a/tests/unit/integrations/test_langfuse_otel.py b/tests/unit/integrations/test_langfuse_otel.pyindex 13a49f40d7e..9f536ab0dac 100644--- a/tests/unit/integrations/test_langfuse_otel.py+++ b/tests/unit/integrations/test_langfuse_otel.py@@ -168,6 +168,31 @@ class TestLangfuseOtelIntegration:assert span.attributes["langfuse.environment"] == "team-a-env"+ @pytest.mark.parametrize(+ "completion_start_time",+ [+ datetime(2026, 10, 9, 12, 0, 0, 250000, tzinfo=timezone.utc),+ datetime(2026, 10, 9, 12, 0, 0, 250000),+ ],+ ids=["aware", "naive_local_time"],+ )+ def test_set_langfuse_specific_attributes_completion_start_time(self, completion_start_time: datetime):+ """The first-token time goes out the way the Langfuse SDK sends it: a JSON string, with an explicit offset."""+ span: Final = TracerProvider().get_tracer(__name__).start_span("litellm_request")++ LangfuseOtelLogger._set_langfuse_specific_attributes(span, {"completion_start_time": completion_start_time}, {})++ sent: Final = datetime.fromisoformat(json.loads(span.attributes["langfuse.observation.completion_start_time"]))+ assert sent.tzinfo is not None+ assert sent.timestamp() == completion_start_time.timestamp()++ def test_set_langfuse_specific_attributes_without_completion_start_time(self):+ span: Final = TracerProvider().get_tracer(__name__).start_span("litellm_request")++ LangfuseOtelLogger._set_langfuse_specific_attributes(span, {}, {})++ assert "langfuse.observation.completion_start_time" not in span.attributes+def test_extract_langfuse_metadata_basic(self):"""Ensure metadata is correctly pulled from litellm_params."""metadata_in = {"generation_name": "my-gen", "custom": "data"}diff --git a/tests/unit/interactions/test_interactions_streaming_iterator.py b/tests/unit/interactions/test_interactions_streaming_iterator.pyindex c52ab36deaa..afcd0d559d7 100644--- a/tests/unit/interactions/test_interactions_streaming_iterator.py+++ b/tests/unit/interactions/test_interactions_streaming_iterator.py@@ -5,7 +5,10 @@ async_success_handler (cross-thread pydantic mutation segfaults pydantic-core)."""import asyncio+import jsonimport time+from datetime import datetime+from typing import Finalimport httpximport pytest@@ -16,6 +19,7 @@ from litellm.interactions import streaming_iterator as interactions_streaming_itfrom litellm.interactions.streaming_iterator import InteractionsAPIStreamingIteratorfrom litellm.litellm_core_utils import thread_pool_executor as thread_pool_executor_modulefrom litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging+from litellm.llms.gemini.interactions.transformation import GoogleAIStudioInteractionsConfigfrom litellm.types.interactions import InteractionsAPIStreamingResponse@@ -97,3 +101,50 @@ async def test_custom_logger_only_never_submits_sync_success_handler(monkeypatchassert recorder.async_hook_fired is Trueassert recording_executor.submitted_for(logging_obj) == []+++class _SuccessRecorder(CustomLogger):+ def __init__(self):+ super().__init__()+ self.logged: list[tuple[datetime, object]] = []++ async def async_log_success_event(+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged.append((start_time, kwargs.get("completion_start_time")))+++async def test_stream_logs_its_first_event_time_measured_from_the_call_start():+ call_start: Final = datetime(2026, 10, 9, 12, 0, 0)+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = LitellmLogging(+ model="gemini/gemini-3-pro-preview",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ call_type="ainteraction",+ start_time=call_start,+ litellm_call_id="interactions-stream",+ function_id="interactions-stream",+ dynamic_async_success_callbacks=[recorder],+ )+ events: Final = (+ {"event_type": "step.delta", "id": "interaction-1"},+ {"event_type": "interaction.completed", "id": "interaction-1", "status": "completed"},+ )+ response: Final = httpx.Response(200, content="".join(f"data: {json.dumps(e)}\n\n" for e in events).encode())+ iterator: Final = InteractionsAPIStreamingIterator(+ response=response,+ model="gemini/gemini-3-pro-preview",+ interactions_api_config=GoogleAIStudioInteractionsConfig(),+ logging_obj=logging_obj,+ )+ tasks_before: Final = asyncio.all_tasks()++ _ = await iterator.__anext__()+ first_event_at: Final = logging_obj.completion_start_time+ _ = [event async for event in iterator]+ await asyncio.gather(*(asyncio.all_tasks() - tasks_before))++ assert first_event_at is not None+ assert recorder.logged == [(call_start, first_event_at)]diff --git a/tests/unit/llms/anthropic/pass_through/messages/test_response_cache.py b/tests/unit/llms/anthropic/pass_through/messages/test_response_cache.pyindex b88a57f440d..1df4ccec02c 100644--- a/tests/unit/llms/anthropic/pass_through/messages/test_response_cache.py+++ b/tests/unit/llms/anthropic/pass_through/messages/test_response_cache.py@@ -1,5 +1,5 @@import asyncio-from typing import Any, AsyncIterator, Dict, List+from typing import Any, AsyncIterator, Dict, Final, Listimport pytest@@ -10,10 +10,13 @@ import litellmfrom litellm._internal_context import in_post_response_phasefrom litellm.caching.caching import Cache, LiteLLMCacheTypefrom litellm.caching.caching_handler import LLMCachingHandler+from litellm.integrations.custom_logger import CustomLogger+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKERfrom litellm.llms.anthropic.pass_through.messages import handlerfrom litellm.llms.anthropic.pass_through.messages.response_cache import (AnthropicMessagesStreamCacheWriter,+ CachedAnthropicMessagesStreamIterator,)STREAM_EVENTS: List[bytes] = [@@ -299,6 +302,58 @@ async def test_cached_stream_replay_logs_once_when_polled_after_exhaustion():await asyncio.sleep(0)mock_route.assert_called_once()+++class _ReplayRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logged: list[object] = []++ async def async_log_success_event(+ self,+ kwargs: dict[str, object],+ response_obj: object,+ start_time: datetime.datetime,+ end_time: datetime.datetime,+ ) -> None:+ self.logged.append(kwargs.get("completion_start_time"))+++async def test_cached_stream_replay_logs_when_its_first_event_was_replayed():+ recorder: Final = _ReplayRecorder()+ logging_obj: Final = LiteLLMLoggingObj(+ model="claude-sonnet-4-5",+ messages=[{"role": "user", "content": "which greek letter?"}],+ stream=True,+ call_type="anthropic_messages",+ start_time=datetime.datetime(2026, 10, 20, 12, 0, 0),+ litellm_call_id="cached-replay",+ function_id="cached-replay",+ dynamic_async_success_callbacks=[recorder],+ )+ logging_obj.update_environment_variables(+ model="claude-sonnet-4-5",+ user="",+ optional_params={},+ litellm_params={"custom_llm_provider": "anthropic"},+ custom_llm_provider="anthropic",+ )+ iterator: Final = CachedAnthropicMessagesStreamIterator(+ events=[event.decode("utf-8") for event in STREAM_EVENTS],+ litellm_logging_obj=logging_obj,+ request_body={"model": "claude-sonnet-4-5", "stream": True},+ )++ _ = await iterator.__anext__()+ first_event_at: Final = iterator.completion_start_time+ _ = await _collect(iterator)+ await GLOBAL_LOGGING_WORKER.flush()++ assert first_event_at is not None+ assert recorder.logged == [first_event_at]++class _HeldBackStream:has_buffered_provider_output = Truediff --git a/tests/unit/llms/anthropic/pass_through/messages/test_streaming_iterator.py b/tests/unit/llms/anthropic/pass_through/messages/test_streaming_iterator.pyindex b995c6dba9b..fd9aa75be74 100644--- a/tests/unit/llms/anthropic/pass_through/messages/test_streaming_iterator.py+++ b/tests/unit/llms/anthropic/pass_through/messages/test_streaming_iterator.py@@ -5,6 +5,7 @@ from datetime import datetimefrom typing import Final, Literalfrom unittest.mock import patch+import httpximport pytest@@ -859,13 +860,15 @@ class _SuccessRecorder(CustomLogger):self.success_kwargs.append(kwargs)-def _make_priced_logging_obj(call_id: str, recorder: _SuccessRecorder, model: str) -> LiteLLMLoggingObj:+def _make_priced_logging_obj(+ call_id: str, recorder: _SuccessRecorder, model: str, start_time: datetime | None = None+) -> LiteLLMLoggingObj:logging_obj = LiteLLMLoggingObj(model=model,messages=[{"role": "user", "content": "hi"}],stream=True,call_type="anthropic_messages",- start_time=datetime.now(),+ start_time=start_time or datetime.now(),litellm_call_id=call_id,function_id=call_id,dynamic_async_success_callbacks=[recorder],@@ -880,6 +883,53 @@ def _make_priced_logging_obj(call_id: str, recorder: _SuccessRecorder, model: streturn logging_obj+async def test_streamed_messages_log_the_call_start_instead_of_when_the_upstream_answered():+ model: Final = "claude-sonnet-5"+ call_start: Final = datetime(2026, 10, 9, 12, 0, 0)+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = _make_priced_logging_obj("logs_call_start", recorder, model, start_time=call_start)+ logging_obj._on_deferred_stream_complete = lambda logging_coroutine: logging_coroutine+ iterator: Final = BaseAnthropicMessagesStreamingIterator(+ litellm_logging_obj=logging_obj, request_body={"model": model, "stream": True}+ )++ async def _full_stream():+ for event in (*_STREAM_PREFIX, *_STREAM_TAIL):+ yield event++ _ = [chunk async for chunk in iterator.async_sse_wrapper(_full_stream())]+ (logging_coroutine,) = logging_obj._deferred_stream_complete_args+ await logging_coroutine++ assert len(recorder.success_kwargs) == 1+ assert recorder.success_kwargs[0]["standard_logging_object"]["startTime"] == call_start.timestamp()+++async def test_streamed_messages_from_anthropic_log_the_call_start_instead_of_when_the_upstream_answered():+ model: Final = "claude-sonnet-5"+ call_start: Final = datetime(2026, 10, 9, 12, 0, 0)+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = _make_priced_logging_obj("anthropic_logs_call_start", recorder, model, start_time=call_start)+ logging_obj._on_deferred_stream_complete = lambda logging_coroutine: logging_coroutine+ request_body: Final = {"model": model, "stream": True}+ iterator: Final = BaseAnthropicMessagesStreamingIterator(litellm_logging_obj=logging_obj, request_body=request_body)+ sse: Final = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in (*_STREAM_PREFIX, *_STREAM_TAIL))++ _ = [+ chunk+ async for chunk in iterator.get_async_streaming_response_iterator(+ httpx.Response(200, content=sse.encode()), request_body, logging_obj+ )+ ]+ (logging_coroutine,) = logging_obj._deferred_stream_complete_args+ await logging_coroutine++ assert len(recorder.success_kwargs) == 1+ assert recorder.success_kwargs[0]["standard_logging_object"]["startTime"] == call_start.timestamp()++class _UpstreamClosedOnDetach:"""Upstream that yields its events and then, like a socket read, waits until it is closed."""