Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 130 additions & 12 deletions litellm/integrations/otel/mappers/genai.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
table: one lambda per mapping operation, applied against the typed span data.
"""

from typing import Callable
import json
from typing import Callable, Mapping

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 collect, drop_none, json_or_none
from litellm.integrations.otel.model.payloads import (
GuardrailSpanData,
LLMCallSpanData,
Expand Down Expand Up @@ -80,6 +81,14 @@ class GenAIMapper:
LiteLLM.REQUEST_STREAMING: lambda d: d.is_streaming,
}

# Prompt/response content, serialized into the OTel GenAI message schema.
# Populated only when content capture is enabled — otherwise ``messages_in``
# and ``choices_out`` arrive empty and these resolve to ``None``.
_BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = {
GenAI.INPUT_MESSAGES: lambda d: _input_messages(d.messages_in),
GenAI.OUTPUT_MESSAGES: lambda d: _output_messages(d.choices_out),
}

_TOOL_ATTRS: dict[str, Callable[[ToolDefinition], AttrValue | None]] = {
"name": lambda t: t.name,
"description": lambda t: t.description or None,
Expand Down Expand Up @@ -137,17 +146,21 @@ def map(self, data: SpanData) -> AttributeMap:

@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()
}
)
return {
**collect(cls._LLM_CALL_ATTRS, data),
**collect(cls._BLOB_ATTRS, data),
**cls._tools(data),
}

@classmethod
def _tools(cls, data: LLMCallSpanData) -> AttributeMap:
return 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()
}
)
return attrs

@classmethod
def _guardrail(cls, data: GuardrailSpanData) -> AttributeMap:
Expand All @@ -171,3 +184,108 @@ def _service(cls, data: ServiceSpanData) -> AttributeMap:
}
)
return attrs


# --- OTel GenAI message serialization ---------------------------------------- #
#
# ``gen_ai.input.messages`` / ``gen_ai.output.messages`` carry a list of
# ``{"role", "parts": [...]}`` objects, where each part is a typed fragment
# (``text``, ``tool_call``, ``tool_call_response``). Spans can't hold nested
# structures, so the list is serialized to a JSON string (the convention's
# documented fallback). Output messages add the choice's ``finish_reason``.


def _input_messages(messages: tuple[Mapping[str, object], ...]) -> str | None:
return json_or_none([_input_message(m) for m in messages]) if messages else None


def _output_messages(choices: tuple[Mapping[str, object], ...]) -> str | None:
return json_or_none([_output_message(c) for c in choices]) if choices else None


def _input_message(message: Mapping[str, object]) -> Mapping[str, object]:
return _prune({"role": _as_str(message.get("role")), "parts": _parts(message)})


def _output_message(choice: Mapping[str, object]) -> Mapping[str, object]:
message = _as_mapping(choice.get("message"))
return _prune(
{
"role": _as_str(message.get("role")) or "assistant",
"parts": _parts(message),
"finish_reason": _as_str(choice.get("finish_reason")),
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
)


def _parts(message: Mapping[str, object]) -> list[Mapping[str, object]]:
if message.get("role") == "tool":
return [_tool_response_part(message)]
return [
*_text_parts(message.get("content")),
*_tool_call_parts(message.get("tool_calls")),
]


def _text_parts(content: object) -> list[Mapping[str, object]]:
if isinstance(content, str):
return [{"type": "text", "content": content}] if content else []
if not isinstance(content, list):
return []
texts = (
part.get("text")
for part in content
if isinstance(part, dict) and part.get("type") == "text"
)
return [{"type": "text", "content": t} for t in texts if isinstance(t, str) and t]


def _tool_call_parts(tool_calls: object) -> list[Mapping[str, object]]:
if not isinstance(tool_calls, list):
return []
return [_tool_call_part(c) for c in tool_calls if isinstance(c, dict)]


def _tool_call_part(call: Mapping[str, object]) -> Mapping[str, object]:
function = _as_mapping(call.get("function"))
return _prune(
{
"type": "tool_call",
"id": _as_str(call.get("id")),
"name": _as_str(function.get("name")),
"arguments": _maybe_json(function.get("arguments")),
}
)


def _tool_response_part(message: Mapping[str, object]) -> Mapping[str, object]:
return _prune(
{
"type": "tool_call_response",
"id": _as_str(message.get("tool_call_id")),
"result": message.get("content"),
}
)


def _maybe_json(value: object) -> object:
"""Parse a JSON-string ``arguments`` blob into structured form; pass through
anything that isn't valid JSON so the raw value survives."""
if not isinstance(value, str):
return value
try:
return json.loads(value)
except ValueError:
return value


def _as_str(value: object) -> str | None:
return value if isinstance(value, str) else None


def _as_mapping(value: object) -> Mapping[str, object]:
return value if isinstance(value, Mapping) else {}


def _prune(values: Mapping[str, object]) -> Mapping[str, object]:
return {key: value for key, value in values.items() if value is not None}
165 changes: 165 additions & 0 deletions tests/test_litellm/integrations/otel/test_otel_v2_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
baggage helpers, metrics, the typed coercion helpers, mapper branches, span-name
builders, and the registry validator's failure paths. Needs the OTel SDK."""

import json
from datetime import datetime

import pytest

pytest.importorskip("opentelemetry")
Expand Down Expand Up @@ -282,6 +285,168 @@ def test_genai_mapper_cost_breakdown_absent():
)


def _llm_call_with_content(**overrides):
base = dict(
operation=GenAIOperation.CHAT,
provider="openai",
request_model="gpt-4o",
response_model="gpt-4o-2024",
response_id="resp_1",
request_params=LLMRequestParams(),
usage=LLMUsage(input_tokens=10, output_tokens=5, total_tokens=15),
finish_reasons=("stop",),
error=None,
response_cost=None,
server=None,
identity=RequestIdentity(call_id="c1"),
messages_in=(
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Weather in Paris?"},
),
choices_out=(
{
"finish_reason": "stop",
"message": {"role": "assistant", "content": "Sunny."},
},
),
)
base.update(overrides)
return LLMCallSpanData(**base)


def test_genai_mapper_input_messages_use_parts_schema():
attrs = GenAIMapper().map(_llm_call_with_content())
assert json.loads(attrs[GenAI.INPUT_MESSAGES]) == [
{"role": "system", "parts": [{"type": "text", "content": "Be concise."}]},
{"role": "user", "parts": [{"type": "text", "content": "Weather in Paris?"}]},
]


def test_genai_mapper_output_messages_carry_finish_reason():
attrs = GenAIMapper().map(_llm_call_with_content())
assert json.loads(attrs[GenAI.OUTPUT_MESSAGES]) == [
{
"role": "assistant",
"parts": [{"type": "text", "content": "Sunny."}],
"finish_reason": "stop",
}
]


def test_genai_mapper_omits_messages_when_content_not_captured():
# Capture off → payload builds empty tuples → no message attributes stamped.
attrs = GenAIMapper().map(_llm_call_with_content(messages_in=(), choices_out=()))
assert GenAI.INPUT_MESSAGES not in attrs
assert GenAI.OUTPUT_MESSAGES not in attrs


def test_genai_mapper_multimodal_keeps_text_parts_only():
data = _llm_call_with_content(
messages_in=(
{
"role": "user",
"content": [
{"type": "text", "text": "describe "},
{"type": "image_url", "image_url": {"url": "data:..."}},
{"type": "text", "text": "this"},
],
},
)
)
(message,) = json.loads(GenAIMapper().map(data)[GenAI.INPUT_MESSAGES])
assert message["parts"] == [
{"type": "text", "content": "describe "},
{"type": "text", "content": "this"},
]


def test_genai_mapper_assistant_tool_call_becomes_tool_call_part():
data = _llm_call_with_content(
choices_out=(
{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_42",
"function": {
"name": "get_weather",
"arguments": '{"city": "Paris"}',
},
}
],
},
},
)
)
(message,) = json.loads(GenAIMapper().map(data)[GenAI.OUTPUT_MESSAGES])
assert message["finish_reason"] == "tool_calls"
# ``arguments`` is parsed from the JSON-string blob into structured form.
assert message["parts"] == [
{
"type": "tool_call",
"id": "call_42",
"name": "get_weather",
"arguments": {"city": "Paris"},
}
]


def test_genai_mapper_tool_result_message_becomes_response_part():
data = _llm_call_with_content(
messages_in=(
{"role": "tool", "tool_call_id": "call_42", "content": "21C and sunny"},
)
)
(message,) = json.loads(GenAIMapper().map(data)[GenAI.INPUT_MESSAGES])
assert message["role"] == "tool"
assert message["parts"] == [
{"type": "tool_call_response", "id": "call_42", "result": "21C and sunny"}
]


def test_genai_mapper_tool_call_arguments_pass_through_when_not_json():
# A non-string blob is kept as-is; an unparseable string survives verbatim
# rather than letting the JSON parse error bubble up.
data = _llm_call_with_content(
choices_out=(
{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"tool_calls": [
{"id": "a", "function": {"name": "f", "arguments": "not json"}},
{"id": "b", "function": {"name": "g", "arguments": {"x": 1}}},
],
},
},
)
)
(message,) = json.loads(GenAIMapper().map(data)[GenAI.OUTPUT_MESSAGES])
assert [p["arguments"] for p in message["parts"]] == ["not json", {"x": 1}]


def test_genai_mapper_output_choice_without_message_defaults_role():
data = _llm_call_with_content(choices_out=({"finish_reason": "stop"},))
(message,) = json.loads(GenAIMapper().map(data)[GenAI.OUTPUT_MESSAGES])
assert message == {"role": "assistant", "parts": [], "finish_reason": "stop"}


def test_genai_mapper_non_serializable_content_does_not_crash_span():
# json_or_none guards the dump: a stray non-JSON value is stringified instead
# of raising through ``collect`` and dropping the whole span.
data = _llm_call_with_content(
messages_in=(
{"role": "tool", "tool_call_id": "c", "content": datetime(2026, 1, 1)},
)
)
(message,) = json.loads(GenAIMapper().map(data)[GenAI.INPUT_MESSAGES])
assert message["parts"][0]["type"] == "tool_call_response"
assert "2026" in message["parts"][0]["result"]


def test_llm_cost_from_breakdown_maps_costbreakdown_keys():
cost = LLMCost.from_breakdown(
{
Expand Down
Loading