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]

fix(datadog_llm_obs): send tool calls, tool results and cache tokens in DD's own fields (#39222)

tin-berri81277252e1e3
diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.py
index e5789965c6e..5e116b7301a 100644
--- a/litellm/integrations/datadog/datadog_llm_obs.py
+++ b/litellm/integrations/datadog/datadog_llm_obs.py
@@ -11,6 +11,7 @@ import json
import os
from collections.abc import Mapping, Sequence
from datetime import datetime
+from types import MappingProxyType
from typing import Any, Final, Literal
import httpx
@@ -30,12 +31,16 @@ from litellm.integrations.datadog.datadog_mock_client import (
)
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_content_list_to_str,
handle_any_messages_to_chat_completion_str_messages_conversion,
)
+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.litellm_core_utils.safe_json_loads import safe_json_loads
from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
httpxSpecialProvider,
)
+from litellm.proxy.spend_tracking.savings import extract_cache_creation_tokens, extract_cache_read_tokens
from litellm.types.integrations.datadog_llm_obs import *
from litellm.types.utils import (
CallTypes,
@@ -44,6 +49,189 @@ from litellm.types.utils import (
StandardLoggingPayloadErrorInformation,
)
+_EMPTY_MAPPING: Final[Mapping[str, Any]] = MappingProxyType({})
+_EMPTY_MESSAGE: Final[Message] = {"role": "", "content": ""}
+_MAX_PARSED_TOOL_ARGUMENT_CHARS: Final = 256 * 1024
+
+
+def _mapping_field(source: Mapping[str, Any], key: str) -> Mapping[str, Any]:
+ """The value at `key` when it is a mapping, else an empty one."""
+ value: Final = source.get(key)
+ return value if isinstance(value, dict) else _EMPTY_MAPPING
+
+
+def _content_blocks(message: Mapping[str, Any]) -> tuple[Mapping[str, Any], ...]:
+ content: Final = message.get("content")
+ if not isinstance(content, list):
+ return ()
+ return tuple(block for block in content if isinstance(block, dict))
+
+
+def _to_dd_arguments(raw_arguments: object) -> dict[str, Any] | str:
+ """
+ Arguments as the object LLM Obs types them as, or the raw string when they are not one.
+
+ Strings past the size bound ship unparsed: decoding multiplies memory on hostile compact
+ JSON, and the raw string is what the intake receives either way.
+ """
+ if not isinstance(raw_arguments, str):
+ return raw_arguments if isinstance(raw_arguments, dict) else str(raw_arguments)
+ if len(raw_arguments) > _MAX_PARSED_TOOL_ARGUMENT_CHARS:
+ return raw_arguments
+ parsed: Final = safe_json_loads(raw_arguments)
+ return parsed if isinstance(parsed, dict) else raw_arguments
+
+
+def _to_dd_tool_calls(message: Mapping[str, Any]) -> tuple[ToolCall, ...]:
+ """
+ The tool calls a message carries, in LLM Obs' ToolCall schema, from either dialect.
+
+ OpenAI puts them in `tool_calls` with the callee nested under `function` and `arguments`
+ serialized; Anthropic puts them in `content` as `tool_use` blocks with `input` already an
+ object. LLM Obs reads `name` / `arguments` / `tool_id` either way.
+ """
+ raw_tool_calls: Final = message.get("tool_calls")
+ openai_calls: Final = tuple(
+ ToolCall(
+ name=function.get("name", ""),
+ arguments=_to_dd_arguments(function.get("arguments", "")),
+ tool_id=tool_call.get("id", ""),
+ type=tool_call.get("type", "function"),
+ )
+ for tool_call in (raw_tool_calls if isinstance(raw_tool_calls, list) else ())
+ if isinstance(tool_call, dict)
+ for function in [_mapping_field(tool_call, "function")]
+ )
+ anthropic_calls: Final = tuple(
+ ToolCall(
+ name=block.get("name", ""),
+ arguments=_to_dd_arguments(block.get("input") or {}),
+ tool_id=block.get("id", ""),
+ type="tool_use",
+ )
+ for block in _content_blocks(message)
+ if block.get("type") == "tool_use"
+ )
+ return openai_calls + anthropic_calls
+
+
+def _to_dd_tool_results(message: Mapping[str, Any], tool_call_names: Mapping[str, str]) -> tuple[ToolResult, ...]:
+ """
+ The tool results a message carries, linked back to the call each answers.
+
+ OpenAI models a result as a whole `role: "tool"` message keyed by `tool_call_id`;
+ Anthropic nests `tool_result` blocks inside a user message, keyed by `tool_use_id`.
+ """
+
+ def to_result(tool_id: str, result: object) -> ToolResult:
+ return ToolResult(
+ name=tool_call_names.get(tool_id, ""),
+ result=result if isinstance(result, str) else safe_dumps(result),
+ tool_id=tool_id,
+ type="function",
+ )
+
+ if message.get("role") == "tool":
+ return (to_result(str(message.get("tool_call_id", "")), message.get("content") or ""),)
+ return tuple(
+ to_result(str(block.get("tool_use_id", "")), block.get("content") or "")
+ for block in _content_blocks(message)
+ if block.get("type") == "tool_result"
+ )
+
+
+def _tool_call_names_by_id(messages: Sequence[object]) -> Mapping[str, str]:
+ """Ids to tool names for result linking; reads names structurally and parses nothing."""
+ openai_pairs: Final = tuple(
+ (tool_call.get("id"), function.get("name", ""))
+ for message in messages
+ if isinstance(message, dict) and isinstance(message.get("tool_calls"), list)
+ for tool_call in message["tool_calls"]
+ if isinstance(tool_call, dict)
+ for function in [_mapping_field(tool_call, "function")]
+ )
+ anthropic_pairs: Final = tuple(
+ (block.get("id"), block.get("name", ""))
+ for message in messages
+ if isinstance(message, dict)
+ for block in _content_blocks(message)
+ if block.get("type") == "tool_use"
+ )
+ return MappingProxyType({str(tool_id): str(name) for tool_id, name in openai_pairs + anthropic_pairs if tool_id})
+
+
+def _to_dd_message(message: object, tool_call_names: Mapping[str, str]) -> Message:
+ """
+ Map one chat message onto LLM Obs' Message schema, adding fields and never destroying content.
+
+ Content collapses to its text only when it has text; a content list with none (tool blocks,
+ images) rides along unchanged so nothing the caller logged is lost. Tool calls and results
+ move into the fields the LLM Obs Tools panel reads, from both the OpenAI and Anthropic shapes.
+ """
+ if not isinstance(message, dict):
+ converted: Final = handle_any_messages_to_chat_completion_str_messages_conversion(message)
+ return converted[0] if converted else _EMPTY_MESSAGE
+
+ text: Final = convert_content_list_to_str(message) # pyright: ignore[reportArgumentType] # caller-supplied dict
+ original_content: Final = message.get("content")
+ content: Final = (
+ text if text or not isinstance(original_content, list) or not original_content else original_content
+ )
+ reasoning: Final = message.get("reasoning_content")
+ tool_calls: Final = _to_dd_tool_calls(message)
+ tool_results: Final = _to_dd_tool_results(message, tool_call_names)
+ dd_message: Final[Message] = {
+ "role": message.get("role", ""),
+ "content": content,
+ **({"reasoning_content": reasoning} if reasoning is not None else {}),
+ **({"tool_calls": tool_calls} if tool_calls else {}),
+ **({"tool_results": tool_results} if tool_results else {}),
+ }
+ return dd_message
+
+
+def _to_dd_messages(messages: object) -> tuple[Message, ...]:
+ """Map a whole conversation, resolving each tool result against the calls that precede it."""
+ if messages is None:
+ return ()
+ if not isinstance(messages, list):
+ return tuple(handle_any_messages_to_chat_completion_str_messages_conversion(messages))
+ tool_call_names: Final = _tool_call_names_by_id(messages)
+ return tuple(_to_dd_message(message, tool_call_names) for message in messages)
+
+
+def _to_dd_tool_definition(entry: Mapping[str, Any]) -> ToolDefinition | None:
+ function: Final = entry.get("function")
+ declared: Final[Mapping[str, Any]] = function if isinstance(function, dict) else entry
+ name: Final = declared.get("name")
+ if not name:
+ return None
+ schema: Final = declared.get("parameters") or declared.get("input_schema")
+ description: Final = declared.get("description", "")
+ if not isinstance(schema, dict):
+ return ToolDefinition(name=name, description=description)
+ return ToolDefinition(name=name, description=description, schema=schema)
+
+
+def _to_dd_tool_definitions(model_parameters: object) -> tuple[ToolDefinition, ...]:
+ """
+ Map the request's declared tools onto LLM Obs' ToolDefinition schema.
+
+ Handles the wrapped chat-completions shape and the bare shape the Anthropic and
+ Responses surfaces use, since both reach this logger through `model_parameters`.
+ """
+ if not isinstance(model_parameters, dict):
+ return ()
+ raw_tools: Final = model_parameters.get("tools") or model_parameters.get("functions")
+ if not isinstance(raw_tools, list):
+ return ()
+ return tuple(
+ definition
+ for entry in raw_tools
+ if isinstance(entry, dict)
+ if (definition := _to_dd_tool_definition(entry)) is not None
+ )
+
class DataDogLLMObsLogger(CustomBatchLogger):
def __init__(self, **kwargs):
@@ -222,12 +410,9 @@ class DataDogLLMObsLogger(CustomBatchLogger):
if standard_logging_payload is None:
raise Exception("DataDogLLMObs: standard_logging_object is not set")
- messages = standard_logging_payload["messages"]
- messages = self._ensure_string_content(messages=messages)
-
metadata: Final = kwargs.get("litellm_params", {}).get("metadata", {})
- input_meta: Final = InputMeta(messages=handle_any_messages_to_chat_completion_str_messages_conversion(messages))
+ input_meta: Final = InputMeta(messages=_to_dd_messages(standard_logging_payload["messages"]))
output_meta: Final = OutputMeta(
messages=self._get_response_messages(
standard_logging_payload=standard_logging_payload,
@@ -241,22 +426,20 @@ class DataDogLLMObsLogger(CustomBatchLogger):
if isinstance(metadata, dict):
metadata_parent_id = metadata.get("parent_id")
- meta: Final = Meta(
- kind=self._get_datadog_span_kind(standard_logging_payload.get("call_type"), metadata_parent_id),
- input=input_meta,
- output=output_meta,
- metadata=self._get_dd_llm_obs_payload_metadata(standard_logging_payload),
- error=error_info,
- )
+ tool_definitions: Final = _to_dd_tool_definitions(standard_logging_payload.get("model_parameters"))
+ span_kind: Final = self._get_datadog_span_kind(standard_logging_payload.get("call_type"), metadata_parent_id)
+ payload_metadata: Final = self._get_dd_llm_obs_payload_metadata(standard_logging_payload)
+
+ meta: Final[Meta] = {
+ "kind": span_kind,
+ "input": input_meta,
+ "output": output_meta,
+ "metadata": payload_metadata,
+ "error": error_info,
+ **({"tool_definitions": tool_definitions} if tool_definitions else {}),
+ }
- # Calculate metrics (you may need to adjust these based on available data)
- metrics: Final = LLMMetrics(
- input_tokens=float(standard_logging_payload.get("prompt_tokens", 0)),
- output_tokens=float(standard_logging_payload.get("completion_tokens", 0)),
- total_tokens=float(standard_logging_payload.get("total_tokens", 0)),
- total_cost=float(standard_logging_payload.get("response_cost", 0)),
- time_to_first_token=self._get_time_to_first_token_seconds(standard_logging_payload),
- )
+ metrics: Final = self._assemble_metrics(standard_logging_payload)
payload: Final[LLMObsPayload] = LLMObsPayload(
parent_id=metadata_parent_id if metadata_parent_id else "undefined",
@@ -314,6 +497,45 @@ class DataDogLLMObsLogger(CustomBatchLogger):
)
return error_info
+ def _assemble_metrics(self, standard_logging_payload: StandardLoggingPayload) -> LLMMetrics:
+ """
+ Build the span metrics, including the prompt-cache counts LLM Obs charts cache savings from.
+
+ Cache counts resolve through the same owners the savings dashboard uses, so every provider
+ spelling is covered, and `non_cached_input_tokens` subtracts BOTH cache categories because
+ litellm's normalized prompt count includes both (the invariant the cost calculator's custom
+ pricing helper documents). A zero residual on a fully cached request is real data and is
+ emitted; a zero read or write count is absence and is not.
+ """
+ prompt_tokens: Final = float(standard_logging_payload.get("prompt_tokens", 0))
+ completion_tokens: Final = float(standard_logging_payload.get("completion_tokens", 0))
+ total_tokens: Final = float(standard_logging_payload.get("total_tokens", 0))
+ total_cost: Final = float(standard_logging_payload.get("response_cost", 0))
+ time_to_first_token: Final = self._get_time_to_first_token_seconds(standard_logging_payload)
+
+ raw_usage: Final = (standard_logging_payload.get("metadata") or {}).get("usage_object")
+ usage_object: Final = raw_usage if isinstance(raw_usage, dict) else None
+ cache_read: Final = float(extract_cache_read_tokens(usage_object))
+ cache_write: Final = float(extract_cache_creation_tokens(usage_object))
+
+ metrics: Final[LLMMetrics] = {
+ "input_tokens": prompt_tokens,
+ "output_tokens": completion_tokens,
+ "total_tokens": total_tokens,
+ "total_cost": total_cost,
+ "time_to_first_token": time_to_first_token,
+ **(
+ {
+ **({"cache_read_input_tokens": cache_read} if cache_read else {}),
+ **({"cache_write_input_tokens": cache_write} if cache_write else {}),
+ "non_cached_input_tokens": max(prompt_tokens - cache_read - cache_write, 0.0),
+ }
+ if cache_read or cache_write
+ else {}
+ ),
+ }
+ return metrics
+
def _get_time_to_first_token_seconds(self, standard_logging_payload: StandardLoggingPayload) -> float:
"""
Get the time to first token in seconds
@@ -335,7 +557,7 @@ class DataDogLLMObsLogger(CustomBatchLogger):
def _get_response_messages(
self, standard_logging_payload: StandardLoggingPayload, call_type: str | None
- ) -> list[object]:
+ ) -> tuple[Message, ...]:
"""
Get the messages from the response object
@@ -344,7 +566,7 @@ class DataDogLLMObsLogger(CustomBatchLogger):
response_obj = standard_logging_payload.get("response")
if response_obj is None:
- return []
+ return ()
# edge case: handle response_obj is a string representation of a dict
if isinstance(response_obj, str):
@@ -357,7 +579,7 @@ class DataDogLLMObsLogger(CustomBatchLogger):
# fallback to json parsing
response_obj = json.loads(str(response_obj))
except json.JSONDecodeError:
- return []
+ return ()
if call_type in [
CallTypes.completion.value,
@@ -375,12 +597,12 @@ class DataDogLLMObsLogger(CustomBatchLogger):
if isinstance(response_obj, dict) and "choices" in response_obj:
choices: Final = response_obj["choices"]
if choices and len(choices) > 0 and "message" in choices[0]:
- return [choices[0]["message"]]
- return []
+ return _to_dd_messages([choices[0]["message"]])
+ return ()
except (KeyError, IndexError, TypeError):
# In case of any error accessing the response structure, return empty list
- return []
- return []
+ return ()
+ return ()
def _get_datadog_span_kind(
self, call_type: str | None, parent_id: str | None = None
@@ -485,17 +707,6 @@ class DataDogLLMObsLogger(CustomBatchLogger):
# Default fallback for unknown or passthrough operations
return "llm"
- def _ensure_string_content(self, messages: str | Sequence[object] | Mapping[object, object] | None) -> list[object]:
- if messages is None:
- return []
- if isinstance(messages, str):
- return [messages]
- elif isinstance(messages, list):
- return [message for message in messages]
- elif isinstance(messages, dict):
- return [str(messages.get("content", ""))]
- return []
-
def _get_dd_llm_obs_payload_metadata(self, standard_logging_payload: StandardLoggingPayload) -> dict[str, object]:
"""
Fields to track in DD LLM Observability metadata from litellm standard logging payload
@@ -524,10 +735,6 @@ class DataDogLLMObsLogger(CustomBatchLogger):
spend_metrics: Final = self._get_spend_metrics(standard_logging_payload)
_metadata.update({"spend_metrics": dict(spend_metrics)})
- ## extract tool calls and add to metadata
- tool_call_metadata: Final = self._extract_tool_call_metadata(standard_logging_payload)
- _metadata.update(tool_call_metadata)
-
_standard_logging_metadata: Final[dict] = dict(standard_logging_payload.get("metadata", {})) or {}
_metadata.update(_standard_logging_metadata)
return _metadata
@@ -647,107 +854,3 @@ class DataDogLLMObsLogger(CustomBatchLogger):
verbose_logger.debug("Original value: %s", user_api_key_budget_reset_at)
return spend_metrics
-
- def _process_input_messages_preserving_tool_calls(self, messages: Sequence[object]) -> list[dict[str, object]]:
- """
- Process input messages while preserving tool_calls and tool message types.
-
- This bypasses the lossy string conversion when tool calls are present,
- allowing complex nested tool_calls objects to be preserved for Datadog.
- """
- processed: Final = []
- for msg in messages:
- if isinstance(msg, dict):
- # Preserve messages with tool_calls or tool role as-is
- if "tool_calls" in msg or msg.get("role") == "tool":
- processed.append(msg)
- else:
- # For regular messages, still apply string conversion
- converted = handle_any_messages_to_chat_completion_str_messages_conversion([msg])
- processed.extend(converted)
- else:
- # For non-dict messages, apply string conversion
- converted = handle_any_messages_to_chat_completion_str_messages_conversion([msg])
- processed.extend(converted)
- return processed
-
- @staticmethod
- def _tool_calls_kv_pair(tool_calls: list[dict[str, Any]]) -> dict[str, object]:
- """
- Extract tool call information into key-value pairs for Datadog metadata.
-
- Similar to OpenTelemetry's implementation but adapted for Datadog's format.
- """
- kv_pairs: Final[dict[str, object]] = {}
- for idx, tool_call in enumerate(tool_calls):
- try:
- # Extract tool call ID
- tool_id = tool_call.get("id")
- if tool_id:
- kv_pairs[f"tool_calls.{idx}.id"] = tool_id
-
- # Extract tool call type
- tool_type = tool_call.get("type")
- if tool_type:
- kv_pairs[f"tool_calls.{idx}.type"] = tool_type
-
- # Extract function information
- function = tool_call.get("function")
- if function:
- function_name = function.get("name")
- if function_name:
- kv_pairs[f"tool_calls.{idx}.function.name"] = function_name
-
- function_arguments = function.get("arguments")
- if function_arguments:
- # Store arguments as JSON string for Datadog
- if isinstance(function_arguments, str):
- kv_pairs[f"tool_calls.{idx}.function.arguments"] = function_arguments
- else:
- import json
-
- kv_pairs[f"tool_calls.{idx}.function.arguments"] = json.dumps(function_arguments)
- except (KeyError, TypeError, ValueError) as e:
- verbose_logger.debug("DataDogLLMObs: Error processing tool call %s: %s", idx, e)
- continue
-
- return kv_pairs
-
- def _extract_tool_call_metadata(self, standard_logging_payload: StandardLoggingPayload) -> dict[str, object]:
- """
- Extract tool call information from both input messages and response for Datadog metadata.
- """
- tool_call_metadata: Final[dict[str, object]] = {}
-
- try:
- # Extract tool calls from input messages
- messages: Final = standard_logging_payload.get("messages", [])
- if messages and isinstance(messages, list):
- for message in messages:
- if isinstance(message, dict) and "tool_calls" in message:
- tool_calls = message.get("tool_calls")
- if tool_calls:
- input_tool_calls_kv = self._tool_calls_kv_pair(tool_calls)
- # Prefix with "input_" to distinguish from response tool calls
- for key, value in input_tool_calls_kv.items():
- tool_call_metadata[f"input_{key}"] = value
-
- # Extract tool calls from response
- response_obj: Final = standard_logging_payload.get("response")
- if response_obj and isinstance(response_obj, dict):
- choices: Final = response_obj.get("choices", [])
- for choice in choices:
- if isinstance(choice, dict):
- message = choice.get("message")
- if message and isinstance(message, dict):
- tool_calls = message.get("tool_calls")
- if tool_calls:
- response_tool_calls_kv = self._tool_calls_kv_pair(tool_calls)
- # Prefix with "output_" to distinguish from input tool calls
- for key, value in response_tool_calls_kv.items():
- tool_call_metadata[f"output_{key}"] = value
-
- except Exception as e:
- verbose_logger.debug("DataDogLLMObs: Error extracting tool call metadata: %s", e)
-
- return tool_call_metadata
diff --git a/litellm/types/integrations/datadog_llm_obs.py b/litellm/types/integrations/datadog_llm_obs.py
index 7853dda1213..bae876dfdd9 100644
--- a/litellm/types/integrations/datadog_llm_obs.py
+++ b/litellm/types/integrations/datadog_llm_obs.py
@@ -4,21 +4,58 @@ Payloads for Datadog LLM Observability Service (LLMObs)
API Reference: https://docs.datadoghq.com/llm_observability/setup/api/?tab=example#api-standards
"""
+from collections.abc import Sequence
from typing import Any, Literal
-from typing_extensions import TypedDict
+from typing_extensions import ReadOnly, TypedDict
from litellm.types.integrations.custom_logger import StandardCustomLoggerInitParams
+class ToolCall(TypedDict, total=False):
+ """A tool call on a message, as LLM Obs names its fields."""
+
+ name: ReadOnly[str]
+ arguments: ReadOnly[dict[str, Any] | str] # parsed object, or the raw string when it will not parse to one
+ tool_id: ReadOnly[str]
+ type: ReadOnly[str]
+
+
+class ToolResult(TypedDict, total=False):
+ """The result of a tool call, as LLM Obs names its fields."""
+
+ name: ReadOnly[str]
+ result: ReadOnly[str]
+ tool_id: ReadOnly[str]
+ type: ReadOnly[str]
+
+
+class ToolDefinition(TypedDict, total=False):
+ """A tool the model was offered on the request."""
+
+ name: ReadOnly[str]
+ description: ReadOnly[str]
+ schema: ReadOnly[dict[str, Any]]
+
+
+class Message(TypedDict, total=False):
+ """A message on a span, as LLM Obs names its fields."""
+
+ content: ReadOnly[str]
+ role: ReadOnly[str]
+ reasoning_content: ReadOnly[str]
+ tool_calls: ReadOnly[Sequence[ToolCall]]
+ tool_results: ReadOnly[Sequence[ToolResult]]
+
+
class InputMeta(TypedDict):
- messages: list[
- dict[str, Any] # changed to fit with tool calls
+ messages: Sequence[
+ Message | dict[str, Any] # changed to fit with tool calls
] # Relevant Issue: https://github.com/BerriAI/litellm/issues/9494
class OutputMeta(TypedDict):
- messages: list[Any]
+ messages: Sequence[Any]
class DDLLMObsError(TypedDict, total=False):
@@ -36,6 +73,7 @@ class Meta(TypedDict, total=False):
output: OutputMeta # The span's output information.
metadata: dict[str, Any]
error: DDLLMObsError | None # Error information on the span
+ tool_definitions: ReadOnly[Sequence[ToolDefinition]] # The tools offered to the model on this request
class LLMMetrics(TypedDict, total=False):
@@ -45,6 +83,9 @@ class LLMMetrics(TypedDict, total=False):
time_to_first_token: float
time_per_output_token: float
total_cost: float
+ cache_read_input_tokens: ReadOnly[float]
+ cache_write_input_tokens: ReadOnly[float]
+ non_cached_input_tokens: ReadOnly[float]
class LLMObsPayload(TypedDict, total=False):
diff --git a/tests/test_litellm/integrations/datadog/test_datadog_llm_obs.py b/tests/test_litellm/integrations/datadog/test_datadog_llm_obs.py
new file mode 100644
index 00000000000..2d0605e3b7f
--- /dev/null
+++ b/tests/test_litellm/integrations/datadog/test_datadog_llm_obs.py
@@ -0,0 +1,469 @@
+"""
+Regression tests for the Datadog LLM Observability payload schema (issue #35786).
+
+Datadog renders tool calls, tool results and prompt-cache savings only from the fields its
+own schema names. These assert on the payload `create_llm_obs_payload` actually hands the
+intake, so a regression that moves data back into `meta.metadata` fails here.
+
+Fixtures mirror what a live proxy run recorded on the callback, including the provider
+spelling of prompt-cache counts (`prompt_tokens_details.cached_tokens`).
+"""
+
+import json
+import os
+from datetime import datetime, timedelta
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from litellm.integrations.datadog.datadog_llm_obs import DataDogLLMObsLogger
+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+
+TOOL_DEFINITION: dict[str, Any] = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get current weather for a city",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+}
+
+ASSISTANT_TOOL_CALL: dict[str, Any] = {
+ "id": "call_abc123",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city":"Paris","unit":"c"}'},
+}
+
+
+def logger() -> DataDogLLMObsLogger:
+ with patch.dict(os.environ, {"DD_API_KEY": "k", "DD_SITE": "us5.datadoghq.com"}, clear=True):
+ with patch("asyncio.create_task"):
+ return DataDogLLMObsLogger()
+
+
+NOT_GIVEN: Any = object()
+
+
+def build_payload(
+ messages: Any = NOT_GIVEN,
+ response_message: dict[str, Any] | None = None,
+ usage_object: dict[str, Any] | None = None,
+ model_parameters: dict[str, Any] | None = None,
+ prompt_tokens: int = 4447,
+) -> dict[str, Any]:
+ return {
+ "standard_logging_object": {
+ "call_type": "acompletion",
+ "messages": [{"role": "user", "content": "hi"}] if messages is NOT_GIVEN else messages,
+ "response": {"choices": [{"message": response_message or {"role": "assistant", "content": "hello"}}]},
+ "model_parameters": model_parameters or {},
+ "metadata": {"usage_object": usage_object} if usage_object is not None else {},
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": 507,
+ "total_tokens": prompt_tokens + 507,
+ "response_cost": 0.02,
+ "status": "success",
+ },
+ "litellm_params": {"metadata": {}},
+ }
+
+
+def build(logger: DataDogLLMObsLogger, **kwargs: Any) -> dict[str, Any]:
+ """Build a span and read it back as the JSON the intake receives, not as Python objects."""
+ start = datetime(2026, 9, 1, 12, 0, 0)
+ payload = logger.create_llm_obs_payload(build_payload(**kwargs), start, start + timedelta(seconds=2))
+ return json.loads(safe_dumps(payload))
+
+
+def test_output_tool_calls_use_the_datadog_tool_call_schema(logger: DataDogLLMObsLogger) -> None:
+ """Datadog reads name/arguments/tool_id off the tool call; OpenAI nests them under `function`."""
+ payload = build(
+ logger,
+ response_message={"role": "assistant", "content": None, "tool_calls": [ASSISTANT_TOOL_CALL]},
+ )
+
+ message = payload["meta"]["output"]["messages"][0]
+ assert message["tool_calls"] == [
+ {
+ "name": "get_weather",
+ "arguments": {"city": "Paris", "unit": "c"},
+ "tool_id": "call_abc123",
+ "type": "function",
+ }
+ ]
+ assert "function" not in message["tool_calls"][0]
+
+
+def test_tool_calls_are_not_duplicated_into_metadata(logger: DataDogLLMObsLogger) -> None:
+ """The flat `output_tool_calls.*` keys were a second copy of a fact that now has its own field."""
+ payload = build(
+ logger,
+ response_message={"role": "assistant", "content": None, "tool_calls": [ASSISTANT_TOOL_CALL]},
+ )
+
+ assert [key for key in payload["meta"]["metadata"] if "tool_calls." in key] == []
+
+
+def test_tool_result_message_links_back_to_its_tool_call(logger: DataDogLLMObsLogger) -> None:
+ """Datadog pairs a result with its call through tool_id, and names the tool from the call."""
+ payload = build(
+ logger,
+ messages=[
+ {"role": "user", "content": "Weather in Paris?"},
+ {"role": "assistant", "content": None, "tool_calls": [ASSISTANT_TOOL_CALL]},
+ {"role": "tool", "tool_call_id": "call_abc123", "content": '{"temp_c": 18}'},
+ ],
+ )
+
+ tool_message = payload["meta"]["input"]["messages"][2]
+ assert tool_message["tool_results"] == [
+ {"name": "get_weather", "result": '{"temp_c": 18}', "tool_id": "call_abc123", "type": "function"}
+ ]
+
+
+def test_tool_result_without_a_matching_call_still_reports_its_id(logger: DataDogLLMObsLogger) -> None:
+ """A truncated conversation loses the call, so the name is unknown but the link must survive."""
+ payload = build(
+ logger,
+ messages=[{"role": "tool", "tool_call_id": "call_orphan", "content": "42"}],
+ )
+
+ assert payload["meta"]["input"]["messages"][0]["tool_results"] == [
+ {"name": "", "result": "42", "tool_id": "call_orphan", "type": "function"}
+ ]
+
+
+def test_cache_tokens_are_reported_as_span_metrics(logger: DataDogLLMObsLogger) -> None:
+ """
+ Datadog charts cache savings from span metrics; nested usage_object is not read for it.
+
+ litellm's normalized prompt count includes both cache categories, so the three cache
+ metrics must partition input_tokens: read + write + non_cached == input.
+ """
+ payload = build(
+ logger,
+ usage_object={"prompt_tokens_details": {"cached_tokens": 4300, "cache_write_tokens": 95}},
+ )
+
+ metrics = payload["metrics"]
+ assert metrics["cache_read_input_tokens"] == 4300.0
+ assert metrics["cache_write_input_tokens"] == 95.0
+ assert metrics["non_cached_input_tokens"] == 4447.0 - 4300.0 - 95.0
+ assert (
+ metrics["cache_read_input_tokens"] + metrics["cache_write_input_tokens"] + metrics["non_cached_input_tokens"]
+ == metrics["input_tokens"]
+ )
+
+
+def test_cache_write_tokens_are_not_counted_as_non_cached(logger: DataDogLLMObsLogger) -> None:
+ """A cache-priming request must not report its primed prefix as full-price uncached input."""
+ payload = build(logger, usage_object={"prompt_tokens_details": {"cache_write_tokens": 4000}})
+
+ assert payload["metrics"]["cache_write_input_tokens"] == 4000.0
+ assert payload["metrics"]["non_cached_input_tokens"] == 4447.0 - 4000.0
+ assert "cache_read_input_tokens" not in payload["metrics"]
+
+
+def test_a_fully_cached_request_reports_a_zero_non_cached_count(logger: DataDogLLMObsLogger) -> None:
+ """Zero residual is real data: everything was served from cache. Inconsistent counts clamp to it."""
+ payload = build(
+ logger,
+ usage_object={"prompt_tokens_details": {"cached_tokens": 4352, "cache_write_tokens": 95}},
+ )
+
+ assert payload["metrics"]["non_cached_input_tokens"] == 0.0
+
+
+def test_anthropic_top_level_cache_keys_are_read(logger: DataDogLLMObsLogger) -> None:
+ """A raw Anthropic usage dict records the counts top level, not under prompt_tokens_details."""
+ payload = build(
+ logger,
+ usage_object={"cache_read_input_tokens": 4300, "cache_creation_input_tokens": 95},
+ )
+
+ metrics = payload["metrics"]
+ assert metrics["cache_read_input_tokens"] == 4300.0
+ assert metrics["cache_write_input_tokens"] == 95.0
+ assert metrics["non_cached_input_tokens"] == 4447.0 - 4300.0 - 95.0
+
+
+def test_cache_metrics_come_from_the_normalized_field_not_the_anthropic_one(logger: DataDogLLMObsLogger) -> None:
+ """
+ litellm normalizes every provider's cache counters into prompt_tokens_details.
+
+ A real cached request from a non-Anthropic provider carries only `cached_tokens`, so
+ reading the Anthropic-specific `cache_read_input_tokens` key reports nothing for it.
+ """
+ payload = build(
+ logger,
+ usage_object={"prompt_tokens_details": {"audio_tokens": None, "cached_tokens": 4096}},
+ prompt_tokens=4335,
+ )
+
+ assert payload["metrics"]["cache_read_input_tokens"] == 4096.0
+ assert payload["metrics"]["non_cached_input_tokens"] == 4335.0 - 4096.0
+
+
+ "usage_object",
+ [
+ {"prompt_tokens_details": {"cache_write_tokens": 95}},
+ {"prompt_tokens_details": {"cache_creation_tokens": 95}},
+ {"cache_creation_input_tokens": 95},
+ ],
+)
+def test_every_spelling_of_cache_write_tokens_is_read(
+ logger: DataDogLLMObsLogger, usage_object: dict[str, Any]
+) -> None:
+ """A raw usage dict that bypassed litellm's normalizer can carry any provider's spelling."""
+ payload = build(logger, usage_object=usage_object)
+
+ assert payload["metrics"]["cache_write_input_tokens"] == 95.0
+
+
+def test_a_cache_read_does_not_emit_a_zero_cache_write(logger: DataDogLLMObsLogger) -> None:
+ """A zero write on every cache-read span would drag Datadog's cache-write average to nothing."""
+ payload = build(logger, usage_object={"prompt_tokens_details": {"cached_tokens": 4096}})
+
+ assert payload["metrics"]["cache_read_input_tokens"] == 4096.0
+ assert "cache_write_input_tokens" not in payload["metrics"]
+
+
+def test_no_cache_keys_when_the_provider_reports_no_caching(logger: DataDogLLMObsLogger) -> None:
+ """An uncached request must not gain zero-valued cache metrics that dilute cache dashboards."""
+ payload = build(logger, usage_object={"prompt_tokens_details": None})
+
+ assert "cache_read_input_tokens" not in payload["metrics"]
+ assert "cache_write_input_tokens" not in payload["metrics"]
+ assert "non_cached_input_tokens" not in payload["metrics"]
+
+
+def test_tool_definitions_are_sent_on_meta(logger: DataDogLLMObsLogger) -> None:
+ payload = build(logger, model_parameters={"tools": [TOOL_DEFINITION]})
+
+ assert payload["meta"]["tool_definitions"] == [
+ {
+ "name": "get_weather",
+ "description": "Get current weather for a city",
+ "schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+ }
+ ]
+
+
+def test_tool_definitions_accept_the_bare_anthropic_shape(logger: DataDogLLMObsLogger) -> None:
+ """The Anthropic surface declares tools unwrapped, with input_schema instead of parameters."""
+ payload = build(
+ logger,
+ model_parameters={"tools": [{"name": "get_weather", "description": "d", "input_schema": {"type": "object"}}]},
+ )
+
+ assert payload["meta"]["tool_definitions"] == [
+ {"name": "get_weather", "description": "d", "schema": {"type": "object"}}
+ ]
+
+
+def test_meta_omits_tool_definitions_when_no_tools_were_offered(logger: DataDogLLMObsLogger) -> None:
+ assert "tool_definitions" not in build(logger)["meta"]
+
+
+def test_unparseable_tool_arguments_are_preserved_rather_than_dropped(logger: DataDogLLMObsLogger) -> None:
+ """A truncated argument string is still the only record of what the model tried to call."""
+ payload = build(
+ logger,
+ response_message={
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": '{"city":'}}],
+ },
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["tool_calls"][0]["arguments"] == '{"city":'
+
+
+def test_oversized_tool_arguments_ship_unparsed(logger: DataDogLLMObsLogger) -> None:
+ """
+ Decoding attacker-sized compact JSON multiplies memory for a span that is only logging.
+
+ This payload is perfectly valid JSON, so the only reason it arrives as a string is the
+ size bound; a smaller copy of the same shape comes back as an object below.
+ """
+ oversized = '{"a":"' + "x" * 300_000 + '"}'
+
+ payload = build(
+ logger,
+ response_message={
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": oversized}}],
+ },
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["tool_calls"][0]["arguments"] == oversized
+
+
+def test_valid_arguments_below_the_bound_still_parse(logger: DataDogLLMObsLogger) -> None:
+ """The size bound must not swallow ordinary arguments; this is the oversized test's control."""
+ payload = build(
+ logger,
+ response_message={
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "c1", "type": "function", "function": {"name": "f", "arguments": '{"a":"' + "x" * 64 + '"}'}}
+ ],
+ },
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["tool_calls"][0]["arguments"] == {"a": "x" * 64}
+
+
+def test_a_result_is_named_even_when_its_call_had_unparseable_arguments(logger: DataDogLLMObsLogger) -> None:
+ """Correlating a result to its call reads ids and names, so bad arguments cannot break linking."""
+ payload = build(
+ logger,
+ messages=[
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_abc123", "type": "function", "function": {"name": "get_weather", "arguments": "{"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_abc123", "content": "18C"},
+ ],
+ )
+
+ assert payload["meta"]["input"]["messages"][1]["tool_results"] == [
+ {"name": "get_weather", "result": "18C", "tool_id": "call_abc123", "type": "function"}
+ ]
+
+
+def test_deeply_nested_tool_arguments_do_not_drop_the_span(logger: DataDogLLMObsLogger) -> None:
+ """json.loads raises RecursionError, not JSONDecodeError, on hostile nesting."""
+ payload = build(
+ logger,
+ response_message={
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "[" * 50_000}}],
+ },
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["tool_calls"][0]["arguments"] == "[" * 50_000
+
+
+def test_tool_arguments_that_parse_to_a_non_object_stay_a_string(logger: DataDogLLMObsLogger) -> None:
+ """Datadog types arguments as an object, so a bare JSON scalar must not land there as one."""
+ payload = build(
+ logger,
+ response_message={
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "42"}}],
+ },
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["tool_calls"][0]["arguments"] == "42"
+
+
+def test_a_tool_without_a_name_is_not_offered_as_a_definition(logger: DataDogLLMObsLogger) -> None:
+ """A nameless tool cannot be matched to a call, so it is dropped rather than sent blank."""
+ payload = build(logger, model_parameters={"tools": [{"function": {"description": "no name"}}, TOOL_DEFINITION]})
+
+ assert [tool["name"] for tool in payload["meta"]["tool_definitions"]] == ["get_weather"]
+
+
+def test_a_tool_definition_without_a_schema_omits_the_field(logger: DataDogLLMObsLogger) -> None:
+ """An empty schema object would read as a tool that takes no arguments, which is a different claim."""
+ payload = build(logger, model_parameters={"tools": [{"name": "ping", "description": "d"}]})
+
+ assert payload["meta"]["tool_definitions"] == [{"name": "ping", "description": "d"}]
+
+
+def test_a_non_dict_message_still_reaches_datadog(logger: DataDogLLMObsLogger) -> None:
+ """Callers can log arbitrary message payloads, and dropping the span over one loses the request."""
+ payload = build(logger, messages=["just a bare string"])
+
+ assert payload["meta"]["input"]["messages"] == [{"input": "just a bare string"}]
+
+
+def test_messages_logged_as_a_bare_string_still_reach_datadog(logger: DataDogLLMObsLogger) -> None:
+ payload = build(logger, messages="the whole prompt as one string")
+
+ assert payload["meta"]["input"]["messages"] == [{"input": "the whole prompt as one string"}]
+
+
+def test_non_chat_call_types_log_an_empty_input(logger: DataDogLLMObsLogger) -> None:
+ """Embedding and image calls carry no messages; fabricating an "None" turn misreads in Datadog."""
+ payload = build(logger, messages=None)
+
+ assert payload["meta"]["input"]["messages"] == []
+
+
+def test_anthropic_tool_blocks_map_to_tool_calls_and_results(logger: DataDogLLMObsLogger) -> None:
+ """/v1/messages carries tool traffic as content blocks, not OpenAI fields."""
+ payload = build(
+ logger,
+ messages=[
+ {"role": "user", "content": [{"type": "text", "text": "Weather in Tokyo?"}]},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Tokyo"}}],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "18C"}]},
+ ],
+ )
+
+ assistant, result_turn = payload["meta"]["input"]["messages"][1:3]
+ assert assistant["tool_calls"] == [
+ {"name": "get_weather", "arguments": {"city": "Tokyo"}, "tool_id": "toolu_1", "type": "tool_use"}
+ ]
+ assert result_turn["tool_results"] == [
+ {"name": "get_weather", "result": "18C", "tool_id": "toolu_1", "type": "function"}
+ ]
+
+
+def test_content_with_no_text_parts_is_preserved_not_blanked(logger: DataDogLLMObsLogger) -> None:
+ """A content list the mapper does not understand must ride along, not be erased."""
+ blocks = [{"type": "image_url", "image_url": {"url": "https://example.com/x.png"}}]
+ payload = build(logger, messages=[{"role": "user", "content": blocks}])
+
+ assert payload["meta"]["input"]["messages"][0]["content"] == blocks
+
+
+def test_multimodal_content_parts_are_flattened_to_text(logger: DataDogLLMObsLogger) -> None:
+ """Datadog types Message.content as a string, so content lists collapse to their text."""
+ payload = build(
+ logger,
+ messages=[
+ {"role": "user", "content": [{"type": "text", "text": "describe "}, {"type": "text", "text": "this"}]}
+ ],
+ )
+
+ assert payload["meta"]["input"]["messages"][0]["content"] == "describe this"
+
+
+def test_mapping_input_messages_does_not_mutate_the_shared_payload(logger: DataDogLLMObsLogger) -> None:
+ """Sibling callbacks read the same messages list, so flattening must not write through it."""
+ messages: list[dict[str, Any]] = [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]
+ kwargs = build_payload(messages=messages)
+ start = datetime(2026, 9, 1, 12, 0, 0)
+
+ logger.create_llm_obs_payload(kwargs, start, start + timedelta(seconds=1))
+
+ assert messages[0]["content"] == [{"type": "text", "text": "hi"}]
+
+
+def test_reasoning_content_survives_the_mapping(logger: DataDogLLMObsLogger) -> None:
+ payload = build(
+ logger,
+ response_message={"role": "assistant", "content": "answer", "reasoning_content": "thinking"},
+ )
+
+ assert payload["meta"]["output"]["messages"][0]["reasoning_content"] == "thinking"