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(datadog): add agent support for LLM Observability (#19574)

Harshit Jain1d04414f3054
diff --git a/docs/my-website/docs/observability/datadog.md b/docs/my-website/docs/observability/datadog.md
index 7cf91ced34c..0f50cbd5c91 100644
--- a/docs/my-website/docs/observability/datadog.md
+++ b/docs/my-website/docs/observability/datadog.md
@@ -73,7 +73,7 @@ Send logs through a local DataDog agent (useful for containerized environments):
```shell
LITELLM_DD_AGENT_HOST="localhost" # hostname or IP of DataDog agent
LITELLM_DD_AGENT_PORT="10518" # [OPTIONAL] port of DataDog agent (default: 10518)
-DD_API_KEY="5f2d0f310***********" # [OPTIONAL] your datadog API Key (agent handles auth)
+DD_API_KEY="5f2d0f310***********" # [OPTIONAL] your datadog API Key (Agent handles auth for Logs. REQUIRED for LLM Observability)
DD_SOURCE="litellm_dev" # [OPTIONAL] your datadog source
```
@@ -84,6 +84,9 @@ When `LITELLM_DD_AGENT_HOST` is set, logs are sent to the agent instead of direc
**Note:** We use `LITELLM_DD_AGENT_HOST` instead of `DD_AGENT_HOST` to avoid conflicts with `ddtrace` which automatically sets `DD_AGENT_HOST` for APM tracing.
+> [!IMPORTANT]
+> **Datadog LLM Observability**: `DD_API_KEY` is **REQUIRED** even when using the Datadog Agent (`LITELLM_DD_AGENT_HOST`). The agent acts as a proxy but the API key header is mandatory for the LLM Observability endpoint.
+
**Step 3**: Start the proxy, make a test request
Start proxy
@@ -203,5 +206,5 @@ LiteLLM supports customizing the following Datadog environment variables
| `POD_NAME` | Pod name tag (useful for Kubernetes deployments) | "unknown" | ❌ No |
\* **Required when using Direct API** (default): `DD_API_KEY` and `DD_SITE` are required
-\* **Optional when using DataDog Agent**: Set `LITELLM_DD_AGENT_HOST` to use agent mode; `DD_API_KEY` and `DD_SITE` are not required
+\* **Optional when using DataDog Agent**: Set `LITELLM_DD_AGENT_HOST` to use agent mode; `DD_API_KEY` and `DD_SITE` are not required for **Datadog Logs**. (**Note: `DD_API_KEY` IS REQUIRED for Datadog LLM Observability**)
diff --git a/litellm/integrations/datadog/datadog.py b/litellm/integrations/datadog/datadog.py
index 503e8d8c87a..735d1005d2c 100644
--- a/litellm/integrations/datadog/datadog.py
+++ b/litellm/integrations/datadog/datadog.py
@@ -32,6 +32,7 @@ from litellm.integrations.datadog.datadog_handler import (
get_datadog_service,
get_datadog_source,
get_datadog_tags,
+ get_datadog_base_url_from_env,
)
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.llms.custom_httpx.http_handler import (
@@ -100,7 +101,9 @@ class DataDogLogger(
self._configure_dd_direct_api()
# Optional override for testing
- self._apply_dd_base_url_override()
+ dd_base_url = get_datadog_base_url_from_env()
+ if dd_base_url:
+ self.intake_url = f"{dd_base_url}/api/v2/logs"
self.sync_client = _get_httpx_client()
asyncio.create_task(self.periodic_flush())
self.flush_lock = asyncio.Lock()
@@ -159,18 +162,6 @@ class DataDogLogger(
self.DD_API_KEY = os.getenv("DD_API_KEY")
self.intake_url = f"https://http-intake.logs.{os.getenv('DD_SITE')}/api/v2/logs"
- def _apply_dd_base_url_override(self) -> None:
- """
- Apply base URL override for testing purposes
- """
- dd_base_url: Optional[str] = (
- os.getenv("_DATADOG_BASE_URL")
- or os.getenv("DATADOG_BASE_URL")
- or os.getenv("DD_BASE_URL")
- )
- if dd_base_url is not None:
- self.intake_url = f"{dd_base_url}/api/v2/logs"
-
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
"""
Async Log success events to Datadog
diff --git a/litellm/integrations/datadog/datadog_handler.py b/litellm/integrations/datadog/datadog_handler.py
index 26fab77759e..e2f30f2f614 100644
--- a/litellm/integrations/datadog/datadog_handler.py
+++ b/litellm/integrations/datadog/datadog_handler.py
@@ -20,6 +20,14 @@ def get_datadog_hostname() -> str:
return os.getenv("HOSTNAME", "")
+def get_datadog_base_url_from_env() -> Optional[str]:
+ """
+ Get base URL override from common DD_BASE_URL env var.
+ This is useful for testing or custom endpoints.
+ """
+ return os.getenv("DD_BASE_URL")
+
+
def get_datadog_env() -> str:
return os.getenv("DD_ENV", "unknown")
diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.py
index 6ffdbc0a005..4f6a5b339a7 100644
--- a/litellm/integrations/datadog/datadog_llm_obs.py
+++ b/litellm/integrations/datadog/datadog_llm_obs.py
@@ -21,6 +21,7 @@ from litellm.integrations.custom_batch_logger import CustomBatchLogger
from litellm.integrations.datadog.datadog_handler import (
get_datadog_service,
get_datadog_tags,
+ get_datadog_base_url_from_env,
)
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.litellm_core_utils.prompt_templates.common_utils import (
@@ -43,24 +44,22 @@ class DataDogLLMObsLogger(CustomBatchLogger):
def __init__(self, **kwargs):
try:
verbose_logger.debug("DataDogLLMObs: Initializing logger")
- if os.getenv("DD_API_KEY", None) is None:
- raise Exception("DD_API_KEY is not set, set 'DD_API_KEY=<>'")
- if os.getenv("DD_SITE", None) is None:
- raise Exception(
- "DD_SITE is not set, set 'DD_SITE=<>', example sit = `us5.datadoghq.com`"
- )
+ # Configure DataDog endpoint (Agent or Direct API)
+ # Use LITELLM_DD_AGENT_HOST to avoid conflicts with ddtrace's DD_AGENT_HOST
+ dd_agent_host = os.getenv("LITELLM_DD_AGENT_HOST")
self.async_client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.LoggingCallback
)
self.DD_API_KEY = os.getenv("DD_API_KEY")
- self.DD_SITE = os.getenv("DD_SITE")
- self.intake_url = (
- f"https://api.{self.DD_SITE}/api/intake/llm-obs/v1/trace/spans"
- )
- # testing base url
- dd_base_url = os.getenv("DD_BASE_URL")
+ if dd_agent_host:
+ self._configure_dd_agent(dd_agent_host=dd_agent_host)
+ else:
+ self._configure_dd_direct_api()
+
+ # Optional override for testing
+ dd_base_url = get_datadog_base_url_from_env()
if dd_base_url:
self.intake_url = f"{dd_base_url}/api/intake/llm-obs/v1/trace/spans"
@@ -78,6 +77,38 @@ class DataDogLLMObsLogger(CustomBatchLogger):
verbose_logger.exception(f"DataDogLLMObs: Error initializing - {str(e)}")
raise e
+ def _configure_dd_agent(self, dd_agent_host: str):
+ """
+ Configure the Datadog logger to send traces to the Agent.
+ """
+ # When using the Agent, LLM Observability Intake does NOT require the API Key
+ # Reference: https://docs.datadoghq.com/llm_observability/setup/sdk/#agent-setup
+
+ # Use specific port for LLM Obs (Trace Agent) to avoid conflict with Logs Agent (10518)
+ agent_port = os.getenv("LITELLM_DD_LLM_OBS_PORT", "8126")
+ self.DD_SITE = "localhost" # Not used for URL construction in agent mode
+ self.intake_url = (
+ f"http://{dd_agent_host}:{agent_port}/api/intake/llm-obs/v1/trace/spans"
+ )
+ verbose_logger.debug(f"DataDogLLMObs: Using DD Agent at {self.intake_url}")
+
+ def _configure_dd_direct_api(self):
+ """
+ Configure the Datadog logger to send traces directly to the Datadog API.
+ """
+ if not self.DD_API_KEY:
+ raise Exception("DD_API_KEY is not set, set 'DD_API_KEY=<>'")
+
+ self.DD_SITE = os.getenv("DD_SITE")
+ if not self.DD_SITE:
+ raise Exception(
+ "DD_SITE is not set, set 'DD_SITE=<>', example site = `us5.datadoghq.com`"
+ )
+
+ self.intake_url = (
+ f"https://api.{self.DD_SITE}/api/intake/llm-obs/v1/trace/spans"
+ )
+
def _get_datadog_llm_obs_params(self) -> Dict:
"""
Get the datadog_llm_observability_params from litellm.datadog_llm_observability_params
@@ -164,13 +195,14 @@ class DataDogLLMObsLogger(CustomBatchLogger):
json_payload = safe_dumps(payload)
+ headers = {"Content-Type": "application/json"}
+ if self.DD_API_KEY:
+ headers["DD-API-KEY"] = self.DD_API_KEY
+
response = await self.async_client.post(
url=self.intake_url,
content=json_payload,
- headers={
- "DD-API-KEY": self.DD_API_KEY,
- "Content-Type": "application/json",
- },
+ headers=headers,
)
if response.status_code != 202:
diff --git a/tests/test_litellm/integrations/datadog/test_datadog_llm_obs_agent.py b/tests/test_litellm/integrations/datadog/test_datadog_llm_obs_agent.py
new file mode 100644
index 00000000000..2bb51e1e1b7
--- /dev/null
+++ b/tests/test_litellm/integrations/datadog/test_datadog_llm_obs_agent.py
@@ -0,0 +1,62 @@
+import os
+from unittest.mock import patch
+from litellm.integrations.datadog.datadog_llm_obs import DataDogLLMObsLogger
+
+
+def test_datadog_llm_obs_agent_configuration():
+ """
+ Test that DataDog LLM Obs logger correctly configures agent endpoint.
+ """
+ test_env = {
+ "LITELLM_DD_AGENT_HOST": "localhost",
+ "LITELLM_DD_LLM_OBS_PORT": "10518",
+ "DD_API_KEY": "test-api-key", # Optional, but checking if it's preserved
+ }
+
+ # Ensure DD_SITE is NOT set to verify we don't need it in agent mode
+
+ with patch.dict(os.environ, test_env, clear=True):
+ with patch("asyncio.create_task"): # Prevent periodic flush task from running
+ dd_logger = DataDogLLMObsLogger()
+
+ expected_url = "http://localhost:10518/api/intake/llm-obs/v1/trace/spans"
+ assert dd_logger.intake_url == expected_url
+ assert dd_logger.DD_API_KEY == "test-api-key"
+
+
+def test_datadog_llm_obs_agent_no_api_key_ok():
+ """
+ Test that agent mode works WITHOUT DD_API_KEY (agent handles auth).
+ """
+ test_env = {
+ "LITELLM_DD_AGENT_HOST": "localhost",
+ # No DD_API_KEY
+ }
+
+ with patch.dict(os.environ, test_env, clear=True):
+ with patch("asyncio.create_task"):
+ # Should NOT raise exception anymore
+ dd_logger = DataDogLLMObsLogger()
+
+ assert dd_logger.DD_API_KEY is None
+ # Default port is 8126 if not set
+ expected_url = "http://localhost:8126/api/intake/llm-obs/v1/trace/spans"
+ assert dd_logger.intake_url == expected_url
+
+
+def test_datadog_llm_obs_direct_api_configuration():
+ """
+ Test that direct API configuration still works as expected.
+ """
+ test_env = {
+ "DD_API_KEY": "direct-api-key",
+ "DD_SITE": "us5.datadoghq.com",
+ }
+
+ with patch.dict(os.environ, test_env, clear=True):
+ with patch("asyncio.create_task"):
+ dd_logger = DataDogLLMObsLogger()
+
+ expected_url = "https://api.us5.datadoghq.com/api/intake/llm-obs/v1/trace/spans"
+ assert dd_logger.intake_url == expected_url
+ assert dd_logger.DD_API_KEY == "direct-api-key"