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(otel): cap tool-definition attributes so they cannot evict gen_ai.* from the LLM span (#34828)

Yassin Kortambf8e4af0e245
diff --git a/litellm/integrations/otel/README.md b/litellm/integrations/otel/README.md
index 3038bdb90b2..f318bb42b82 100644
--- a/litellm/integrations/otel/README.md
+++ b/litellm/integrations/otel/README.md
@@ -267,7 +267,10 @@ lives in [`plumbing/`](./plumbing):
- **A new attribute vocabulary for a backend**: add a mapper in `mappers/`
(a class with a `map(data) -> AttributeMap` method, typically built from
- `key -> extractor` tables) and register it in `mappers/__init__._MAPPER_BY_NAME`.
+ `key -> extractor` tables) and register it in `mappers/__init__._PLAIN_MAPPERS`.
+ If it spells declared tool definitions out per index, register it in
+ `_TOOL_DEFINITION_MAPPERS` instead and take the shared attribute budget in its
+ constructor, so the family stays bounded span-wide rather than per vocabulary.
- **A new integration**: add a preset in `presets/` that returns an
`OpenTelemetryV2Config`, and register it in `presets/__init__.PRESET_BY_CALLBACK`.
If it supports dynamic credentials, add a header builder to
diff --git a/litellm/integrations/otel/mappers/__init__.py b/litellm/integrations/otel/mappers/__init__.py
index b0c1d7019db..55504c5e8bf 100644
--- a/litellm/integrations/otel/mappers/__init__.py
+++ b/litellm/integrations/otel/mappers/__init__.py
@@ -18,13 +18,19 @@ from litellm.integrations.otel.mappers.langfuse import LangfuseMapper
from litellm.integrations.otel.mappers.langtrace import LangtraceMapper
from litellm.integrations.otel.mappers.legacy import LegacyMapper
from litellm.integrations.otel.mappers.openinference import OpenInferenceMapper
+from litellm.integrations.otel.mappers.utils import tool_attr_budget
from litellm.integrations.otel.mappers.weave import WeaveMapper
-# Registry keyed by ``config.mapper_names`` entries.
-_MAPPER_BY_NAME: dict[str, Callable[[], AttributeMapper]] = {
+# Registries keyed by ``config.mapper_names`` entries, split by whether the
+# vocabulary spells declared tool definitions out per index. Those share one
+# span-wide attribute ceiling, so resolution has to know how many of them are
+# active before it can build them.
+_TOOL_DEFINITION_MAPPERS: dict[str, Callable[[int], AttributeMapper]] = {
"genai": GenAIMapper,
"legacy": LegacyMapper,
"openinference": OpenInferenceMapper,
+}
+_PLAIN_MAPPERS: dict[str, Callable[[], AttributeMapper]] = {
"langfuse": LangfuseMapper,
"weave": WeaveMapper,
"langtrace": LangtraceMapper,
@@ -33,13 +39,19 @@ _MAPPER_BY_NAME: dict[str, Callable[[], AttributeMapper]] = {
def resolve_mappers(names: Iterable[str]) -> list[AttributeMapper]:
"""Resolve mapper names to instances. Unknown names raise ``ValueError``."""
- out: list[AttributeMapper] = []
- for name in names:
- factory = _MAPPER_BY_NAME.get(name)
- if factory is None:
- raise ValueError(f"unknown mapper name {name!r}; known: {sorted(_MAPPER_BY_NAME)}")
- out.append(factory())
- return out
+ ordered = tuple(names)
+ for name in ordered:
+ if name not in _TOOL_DEFINITION_MAPPERS and name not in _PLAIN_MAPPERS:
+ known = sorted((*_TOOL_DEFINITION_MAPPERS, *_PLAIN_MAPPERS))
+ raise ValueError(f"unknown mapper name {name!r}; known: {known}")
+ # Distinct vocabularies each write the tool family under their own keys, so
+ # the ceiling is split by how many of them are configured. Repeating a name
+ # rewrites the same keys, so only distinct ones count.
+ budget = tool_attr_budget(len({*ordered} & _TOOL_DEFINITION_MAPPERS.keys()))
+ return [
+ _TOOL_DEFINITION_MAPPERS[name](budget) if name in _TOOL_DEFINITION_MAPPERS else _PLAIN_MAPPERS[name]()
+ for name in ordered
+ ]
__all__ = [
diff --git a/litellm/integrations/otel/mappers/genai.py b/litellm/integrations/otel/mappers/genai.py
index f568afa9e3e..70414734b72 100644
--- a/litellm/integrations/otel/mappers/genai.py
+++ b/litellm/integrations/otel/mappers/genai.py
@@ -11,10 +11,11 @@ from typing import Callable
from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
from litellm.integrations.otel.mappers.utils import (
+ MAX_TOOL_DEFINITION_ATTRS_PER_SPAN,
collect,
- drop_none,
output_messages,
serialize_messages,
+ tool_definition_attrs,
)
from litellm.integrations.otel.model.payloads import (
GuardrailSpanData,
@@ -135,6 +136,9 @@ class GenAIMapper:
LiteLLM.SERVICE_CALL_TYPE: lambda d: d.call_type,
}
+ def __init__(self, tool_attr_budget: int = MAX_TOOL_DEFINITION_ATTRS_PER_SPAN) -> None:
+ self._tool_attr_budget = tool_attr_budget
+
def map(self, data: SpanData) -> AttributeMap:
match data:
case LLMCallSpanData():
@@ -150,18 +154,18 @@ class GenAIMapper:
case _:
return {}
- @classmethod
- def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
- attrs = collect(cls._LLM_CALL_ATTRS, data)
- attrs.update(
- drop_none(
- {
- f"gen_ai.tool.{idx}.{suffix}": extract(tool)
- for idx, tool in enumerate(data.tools)
- for suffix, extract in cls._TOOL_ATTRS.items()
- }
+ def _llm_call(self, data: LLMCallSpanData) -> AttributeMap:
+ attrs = collect(self._LLM_CALL_ATTRS, data)
+ if data.tools:
+ attrs[LiteLLM.TOOLS_DECLARED] = len(data.tools)
+ attrs.update(
+ tool_definition_attrs(
+ lambda idx, suffix: f"gen_ai.tool.{idx}.{suffix}",
+ data.tools,
+ self._TOOL_ATTRS,
+ self._tool_attr_budget,
+ )
)
- )
return attrs
@classmethod
diff --git a/litellm/integrations/otel/mappers/legacy.py b/litellm/integrations/otel/mappers/legacy.py
index 57dc7ed3632..f17a62828e7 100644
--- a/litellm/integrations/otel/mappers/legacy.py
+++ b/litellm/integrations/otel/mappers/legacy.py
@@ -12,7 +12,11 @@ Like ``GenAIMapper``, each span kind declares its schema as a flat
from typing import Callable, Final
from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, SpanData
-from litellm.integrations.otel.mappers.utils import collect, drop_none
+from litellm.integrations.otel.mappers.utils import (
+ MAX_TOOL_DEFINITION_ATTRS_PER_SPAN,
+ collect,
+ tool_definition_attrs,
+)
from litellm.integrations.otel.model.payloads import (
LLMCallSpanData,
ServiceSpanData,
@@ -63,6 +67,9 @@ class LegacyMapper:
_LEGACY_ERROR: lambda d: d.error.message if d.error is not None and d.error.message else None,
}
+ def __init__(self, tool_attr_budget: int = MAX_TOOL_DEFINITION_ATTRS_PER_SPAN) -> None:
+ self._tool_attr_budget = tool_attr_budget
+
def map(self, data: SpanData) -> AttributeMap:
match data:
case LLMCallSpanData():
@@ -72,16 +79,14 @@ class LegacyMapper:
case _:
return {}
- @classmethod
- def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
- attrs = collect(cls._LLM_CALL_ATTRS, data)
+ def _llm_call(self, data: LLMCallSpanData) -> AttributeMap:
+ attrs = collect(self._LLM_CALL_ATTRS, data)
attrs.update(
- drop_none(
- {
- f"llm.request.functions.{idx}.{suffix}": extract(tool)
- for idx, tool in enumerate(data.tools)
- for suffix, extract in cls._TOOL_ATTRS.items()
- }
+ tool_definition_attrs(
+ lambda idx, suffix: f"llm.request.functions.{idx}.{suffix}",
+ data.tools,
+ self._TOOL_ATTRS,
+ self._tool_attr_budget,
)
)
return attrs
diff --git a/litellm/integrations/otel/mappers/openinference.py b/litellm/integrations/otel/mappers/openinference.py
index dab9a616979..87c4d0d6484 100644
--- a/litellm/integrations/otel/mappers/openinference.py
+++ b/litellm/integrations/otel/mappers/openinference.py
@@ -13,9 +13,11 @@ from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue, Span
from litellm.integrations.otel.mappers.utils import (
collect,
drop_none,
+ MAX_TOOL_DEFINITION_ATTRS_PER_SPAN,
json_if,
message_content,
output_messages,
+ tool_definition_attrs,
)
from litellm.integrations.otel.model.payloads import (
LLMCallSpanData,
@@ -70,6 +72,9 @@ class OpenInferenceMapper:
),
}
+ def __init__(self, tool_attr_budget: int = MAX_TOOL_DEFINITION_ATTRS_PER_SPAN) -> None:
+ self._tool_attr_budget = tool_attr_budget
+
def map(self, data: SpanData) -> AttributeMap:
match data:
case LLMCallSpanData():
@@ -77,14 +82,13 @@ class OpenInferenceMapper:
case _:
return {}
- @classmethod
- def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap:
+ def _llm_call(self, data: LLMCallSpanData) -> AttributeMap:
return {
- **collect(cls._LLM_CALL_ATTRS, data),
- **collect(cls._BLOB_ATTRS, data),
- **cls._messages("llm.input_messages", "input.value", data.messages_in),
- **cls._messages("llm.output_messages", "output.value", output_messages(data)),
- **cls._tools(data),
+ **collect(self._LLM_CALL_ATTRS, data),
+ **collect(self._BLOB_ATTRS, data),
+ **self._messages("llm.input_messages", "input.value", data.messages_in),
+ **self._messages("llm.output_messages", "output.value", output_messages(data)),
+ **self._tools(data),
}
@staticmethod
@@ -108,12 +112,10 @@ class OpenInferenceMapper:
attrs[value_key] = json.dumps([{"role": role, "content": content} for role, content in parsed])
return attrs
- @classmethod
- def _tools(cls, data: LLMCallSpanData) -> AttributeMap:
- return drop_none(
- {
- f"llm.tools.{idx}.{suffix}": extract(tool)
- for idx, tool in enumerate(data.tools)
- for suffix, extract in cls._TOOL_ATTRS.items()
- }
+ def _tools(self, data: LLMCallSpanData) -> AttributeMap:
+ return tool_definition_attrs(
+ lambda idx, suffix: f"llm.tools.{idx}.{suffix}",
+ data.tools,
+ self._TOOL_ATTRS,
+ self._tool_attr_budget,
)
diff --git a/litellm/integrations/otel/mappers/utils.py b/litellm/integrations/otel/mappers/utils.py
index a91e59e4ab8..cbdb60f42c9 100644
--- a/litellm/integrations/otel/mappers/utils.py
+++ b/litellm/integrations/otel/mappers/utils.py
@@ -6,10 +6,34 @@ they live in one place.
"""
import json
-from typing import Callable, Mapping, Sequence
+from typing import Callable, Final, Mapping, Sequence
from litellm.integrations.otel.mappers.base import AttributeMap, AttrValue
-from litellm.integrations.otel.model.payloads import LLMCallSpanData
+from litellm.integrations.otel.model.payloads import LLMCallSpanData, ToolDefinition
+
+DEFAULT_SPAN_ATTRIBUTE_LIMIT: Final = 128
+"""The OTel SDK's default per-span attribute count limit."""
+
+MAX_TOOL_DEFINITION_ATTRS_PER_SPAN: Final = DEFAULT_SPAN_ATTRIBUTE_LIMIT // 4
+"""Span-wide ceiling on attributes spent spelling out declared tool definitions.
+
+Tool definitions are an unbounded attribute family: one entry per declared
+tool, per field, per active vocabulary. Agentic clients declare hundreds, which
+overruns the span attribute limit. That limit evicts oldest-first, so an
+uncapped family silently destroys the core ``gen_ai.*`` attributes written
+before it.
+
+The ceiling is span-wide rather than per-mapper because several vocabularies
+can be active at once and each spells the same tools out under its own keys, so
+a per-mapper allowance multiplies by the number of vocabularies and reaches the
+limit again. Reserving a quarter of the span for tool detail leaves the rest to
+core telemetry no matter how many vocabularies are configured.
+"""
+
+
+def tool_attr_budget(vocabularies: int) -> int:
+ """Split the span-wide tool-definition ceiling across active vocabularies."""
+ return MAX_TOOL_DEFINITION_ATTRS_PER_SPAN // max(vocabularies, 1)
def drop_none(values: Mapping[str, AttrValue | None]) -> AttributeMap:
@@ -17,6 +41,29 @@ def drop_none(values: Mapping[str, AttrValue | None]) -> AttributeMap:
return {k: v for k, v in values.items() if v is not None}
+def tool_definition_attrs(
+ key_for: Callable[[int, str], str],
+ tools: Sequence[ToolDefinition],
+ extractors: Mapping[str, Callable[[ToolDefinition], AttrValue | None]],
+ attr_budget: int,
+) -> AttributeMap:
+ """Per-index attributes for as many tools as ``attr_budget`` affords.
+
+ ``key_for`` builds a vocabulary's key from the tool's index and the field
+ name, so each mapper keeps its own naming while sharing the budget. One tool
+ always keeps its detail, so the family stays legible even when many
+ vocabularies split the ceiling.
+ """
+ max_tools = max(attr_budget // max(len(extractors), 1), 1)
+ return drop_none(
+ {
+ key_for(idx, suffix): extract(tool)
+ for idx, tool in enumerate(tools[:max_tools])
+ for suffix, extract in extractors.items()
+ }
+ )
+
+
def collect(table: Mapping[str, Callable], source: object) -> AttributeMap:
"""Apply an extractor table to ``source``, dropping ``None`` results."""
return drop_none({key: extract(source) for key, extract in table.items()})
diff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.py
index 1abe8ca33fa..a0994d1948a 100644
--- a/litellm/integrations/otel/model/semconv.py
+++ b/litellm/integrations/otel/model/semconv.py
@@ -233,6 +233,7 @@ class LiteLLM:
# ``litellm_params.model``), distinct from the user-facing ``gen_ai.request.model``.
PROVIDER_MODEL: Final = "litellm.provider.model"
REQUEST_STREAMING: Final = "litellm.request.streaming"
+ TOOLS_DECLARED: Final = "litellm.request.tools.declared"
GUARDRAIL_NAME: Final = "litellm.guardrail.name"
GUARDRAIL_MODE: Final = "litellm.guardrail.mode"
GUARDRAIL_STATUS: Final = "litellm.guardrail.status"
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py b/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py
index 6b1da4c2952..b1b1b62c820 100644
--- a/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_emitter.py
@@ -17,6 +17,9 @@ from litellm.integrations.otel.plumbing import context as ctx_mod # noqa: E402
from litellm.integrations.otel.plumbing import providers # noqa: E402
from litellm.integrations.otel.emitter import SpanEmitter # noqa: E402
from litellm.integrations.otel.emitter import stamp_error # noqa: E402
+from litellm.integrations.otel.mappers.utils import ( # noqa: E402
+ MAX_TOOL_DEFINITION_ATTRS_PER_SPAN,
+)
from litellm.integrations.otel.model.payloads import ( # noqa: E402
GuardrailSpanData,
LLMCallSpanData,
@@ -305,3 +308,135 @@ def test_guardrail_success_span_is_unset():
)
(span,) = exporter.get_finished_spans()
assert span.status.status_code is StatusCode.UNSET
+
+
+def _tools_payload(count):
+ """A request declaring ``count`` tools, in the chat-completion shape."""
+ return _payload(
+ model_parameters={
+ "temperature": 0.7,
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": f"tool_{i}",
+ "description": f"description for tool {i}",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ for i in range(count)
+ ],
+ }
+ )
+
+
+def test_many_tools_do_not_evict_core_attributes():
+ """Tool definitions must never crowd core telemetry off the span.
+
+ An agentic client declares hundreds of tools. Spelling each one out as
+ per-index attributes overruns the OTel SDK's 128-attribute span limit,
+ which evicts oldest-first and so destroys the ``gen_ai.*`` attributes
+ written before it. Capping the tool family keeps the core intact.
+ """
+ engine, exporter = _engine()
+ data = LLMCallSpanData.from_standard_logging_payload(_tools_payload(127))
+ engine.emit(SpanRole.LLM_CALL, data)
+ (span,) = exporter.get_finished_spans()
+ a = span.attributes
+
+ assert a[GenAI.REQUEST_MODEL] == "gpt-4o"
+ assert a[GenAI.PROVIDER_NAME] == "openai"
+ assert a[GenAI.USAGE_INPUT_TOKENS] == 10
+ assert a[GenAI.USAGE_OUTPUT_TOKENS] == 5
+ assert a[GenAI.RESPONSE_FINISH_REASONS] == ("stop",)
+ assert a[f"{LiteLLM.COST_PREFIX}total"] == 0.002
+ assert a["gen_ai.usage.prompt_tokens"] == 10
+
+ assert span.dropped_attributes == 0
+ assert a[LiteLLM.TOOLS_DECLARED] == 127
+ assert a["gen_ai.tool.0.name"] == "tool_0"
+ assert "gen_ai.tool.126.name" not in a
+ assert "llm.request.functions.126.name" not in a
+
+
+def test_tool_definitions_kept_in_full_below_the_cap():
+ """A handful of tools keeps full per-index detail in both vocabularies."""
+ engine, exporter = _engine()
+ data = LLMCallSpanData.from_standard_logging_payload(_tools_payload(3))
+ engine.emit(SpanRole.LLM_CALL, data)
+ (span,) = exporter.get_finished_spans()
+ a = span.attributes
+
+ assert a[LiteLLM.TOOLS_DECLARED] == 3
+ for idx in range(3):
+ assert a[f"gen_ai.tool.{idx}.name"] == f"tool_{idx}"
+ assert a[f"gen_ai.tool.{idx}.description"] == f"description for tool {idx}"
+ assert a[f"gen_ai.tool.{idx}.parameters"]
+ assert a[f"llm.request.functions.{idx}.name"] == f"tool_{idx}"
+
+
+def _tool_span(mapper_names, tool_count):
+ """The exported LLM-call span for ``mapper_names`` and ``tool_count`` tools."""
+ cfg = OpenTelemetryV2Config(
+ exporter="in_memory",
+ legacy_compat=True,
+ mapper_names=list(mapper_names),
+ )
+ provider, exporter = providers.in_memory_provider(cfg)
+ engine = SpanEmitter(providers.get_tracer(provider, "litellm-test"), cfg)
+ engine.emit(
+ SpanRole.LLM_CALL,
+ LLMCallSpanData.from_standard_logging_payload(_tools_payload(tool_count)),
+ )
+ (span,) = exporter.get_finished_spans()
+ return span
+
+
+def _tool_definition_keys(attributes):
+ return [
+ key
+ for key in attributes
+ if key.startswith(("gen_ai.tool.", "llm.request.functions.", "llm.tools."))
+ ]
+
+
+ "mapper_names",
+ [
+ ["genai"],
+ ["genai", "openinference"],
+ ["genai", "openinference", "langfuse", "weave", "langtrace"],
+ ],
+)
+def test_tool_definitions_stay_within_one_span_wide_budget(mapper_names):
+ """Every supported composition has to leave core telemetry on the span.
+
+ Each vocabulary spells the same tools out under its own keys, so an
+ allowance handed to each mapper separately multiplies by the number of
+ configured vocabularies and reaches the attribute limit again. Arize and
+ Phoenix already layer OpenInference on top of the default two, and every
+ vendor vocabulary can be listed at once. One budget shared across them all
+ is what keeps the total bounded.
+ """
+ span = _tool_span(mapper_names, 127)
+ a = span.attributes
+
+ assert span.dropped_attributes == 0
+ assert a[GenAI.REQUEST_MODEL] == "gpt-4o"
+ assert a[GenAI.PROVIDER_NAME] == "openai"
+ assert a[GenAI.USAGE_INPUT_TOKENS] == 10
+ assert a[GenAI.USAGE_OUTPUT_TOKENS] == 5
+ assert a[f"{LiteLLM.COST_PREFIX}total"] == 0.002
+ assert a[LiteLLM.TOOLS_DECLARED] == 127
+
+ emitted = _tool_definition_keys(a)
+ assert emitted, "some tool detail should survive in every composition"
+ assert len(emitted) <= MAX_TOOL_DEFINITION_ATTRS_PER_SPAN
+
+
+def test_vendor_tool_definitions_are_truncated_not_dropped():
+ """The OpenInference vocabulary keeps its leading tools and loses the tail."""
+ a = _tool_span(["genai", "openinference"], 127).attributes
+ assert a["llm.tools.0.tool.name"] == "tool_0"
+ assert a["llm.tools.0.tool.json_schema"]
+ assert "llm.tools.126.tool.name" not in a