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] DD LLM Observability - Ensure `apm_id` is set on traces (#14272)
Ishaan Jaff13525456172f
diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.pyindex 4f9c6409770..200f2f283de 100644--- a/litellm/integrations/datadog/datadog_llm_obs.py+++ b/litellm/integrations/datadog/datadog_llm_obs.py@@ -19,6 +19,7 @@ import litellmfrom litellm._logging import verbose_loggerfrom litellm.integrations.custom_batch_logger import CustomBatchLoggerfrom litellm.integrations.datadog.datadog import DataDogLogger+from litellm.litellm_core_utils.dd_tracing import tracerfrom litellm.litellm_core_utils.prompt_templates.common_utils import (handle_any_messages_to_chat_completion_str_messages_conversion,)@@ -216,7 +217,7 @@ class DataDogLLMObsLogger(DataDogLogger, CustomBatchLogger):time_to_first_token=self._get_time_to_first_token_seconds(standard_logging_payload),)- return LLMObsPayload(+ payload: LLMObsPayload = LLMObsPayload(parent_id=metadata.get("parent_id", "undefined"),trace_id=standard_logging_payload.get("trace_id", str(uuid.uuid4())),span_id=metadata.get("span_id", str(uuid.uuid4())),@@ -230,6 +231,26 @@ class DataDogLLMObsLogger(DataDogLogger, CustomBatchLogger):self._get_datadog_tags(standard_logging_object=standard_logging_payload)],)++ apm_trace_id = self._get_apm_trace_id()+ if apm_trace_id is not None:+ payload["apm_id"] = apm_trace_id++ return payload++ def _get_apm_trace_id(self) -> Optional[str]:+ """Retrieve the current APM trace ID if available."""+ try:+ current_span_fn = getattr(tracer, "current_span", None)+ if callable(current_span_fn):+ current_span = current_span_fn()+ if current_span is not None:+ trace_id = getattr(current_span, "trace_id", None)+ if trace_id is not None:+ return str(trace_id)+ except Exception:+ pass+ return Nonedef _assemble_error_info(self, standard_logging_payload: StandardLoggingPayload) -> Optional[DDLLMObsError]:"""diff --git a/litellm/types/integrations/datadog_llm_obs.py b/litellm/types/integrations/datadog_llm_obs.pyindex 82fb4fe3887..75c55bcc93c 100644--- a/litellm/types/integrations/datadog_llm_obs.py+++ b/litellm/types/integrations/datadog_llm_obs.py@@ -46,6 +46,7 @@ class LLMMetrics(TypedDict, total=False):class LLMObsPayload(TypedDict, total=False):parent_id: strtrace_id: str+ apm_id: strspan_id: strname: strmeta: Metadiff --git a/tests/test_litellm/integrations/datadog/test_datadog_llm_observability.py b/tests/test_litellm/integrations/datadog/test_datadog_llm_observability.pyindex b4575a7ebdc..b1ce08de9e7 100644--- a/tests/test_litellm/integrations/datadog/test_datadog_llm_observability.py+++ b/tests/test_litellm/integrations/datadog/test_datadog_llm_observability.py@@ -195,6 +195,32 @@ class TestDataDogLLMObsLogger:assert metadata["cache_hit"] == Trueassert metadata["cache_key"] == "test-cache-key-789"+ def test_apm_id_included(self, mock_env_vars, mock_response_obj):+ """Test that the current APM trace ID is attached to the payload"""+ with patch('litellm.integrations.datadog.datadog_llm_obs.get_async_httpx_client'), \+ patch('asyncio.create_task'):+ fake_tracer = MagicMock()+ fake_span = MagicMock()+ fake_span.trace_id = 987654321+ fake_tracer.current_span.return_value = fake_span++ with patch('litellm.integrations.datadog.datadog_llm_obs.tracer', fake_tracer):+ logger = DataDogLLMObsLogger()++ standard_payload = create_standard_logging_payload_with_cache()++ kwargs = {+ "standard_logging_object": standard_payload,+ "litellm_params": {"metadata": {}}+ }++ start_time = datetime.now()+ end_time = datetime.now()++ payload = logger.create_llm_obs_payload(kwargs, start_time, end_time)++ assert payload["apm_id"] == str(fake_span.trace_id)+def test_cache_metadata_fields(self, mock_env_vars, mock_response_obj):"""Test that cache-related metadata fields are correctly tracked"""with patch('litellm.integrations.datadog.datadog_llm_obs.get_async_httpx_client'), \