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
feat(arize/phoenix): OpenInference rendering parity — tool_calls, cost, passthrough I/O, session/user, multimodal, cache tokens (#28800)
milan-berri5119b9462f96
diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.pyindex a1bf65141c9..75710e10498 100644--- a/litellm/integrations/arize/_utils.py+++ b/litellm/integrations/arize/_utils.py@@ -8,18 +8,23 @@ from litellm.integrations.opentelemetry_utils.base_otel_llm_obs_attributes imporBaseLLMObsOTELAttributes,safe_set_attribute,)+from litellm.litellm_core_utils.redact_messages import (+ should_redact_message_logging,+)from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.types.utils import StandardLoggingPayloadif TYPE_CHECKING:from opentelemetry.trace import Spanfrom litellm.integrations._types.open_inference import (- MessageAttributes,- ImageAttributes,- SpanAttributes,AudioAttributes,EmbeddingAttributes,+ ImageAttributes,+ MessageAttributes,+ MessageContentAttributes,OpenInferenceSpanKindValues,+ SpanAttributes,+ ToolCallAttributes,)@@ -53,40 +58,24 @@ class ArizeOTELAttributes(BaseLLMObsOTELAttributes):msg.get("content", ""),)- @staticmethod- @override- def set_response_output_messages(span: "Span", response_obj):- """- Sets output message attributes on the span from the LLM response.- Args:- span: The OpenTelemetry span to set attributes on- response_obj: The response object containing choices with messages- """- from litellm.integrations._types.open_inference import (- MessageAttributes,- SpanAttributes,- )-- for idx, choice in enumerate(response_obj.get("choices", [])):- response_message = choice.get("message", {})- safe_set_attribute(- span,- SpanAttributes.OUTPUT_VALUE,- response_message.get("content", ""),- )+ # Additive: emit structured tool_calls / multimodal content+ # so Arize/Phoenix can render tool-using and image-bearing+ # turns. These set NEW attribute keys (MESSAGE_TOOL_CALLS /+ # MESSAGE_NAME / MESSAGE_TOOL_CALL_ID / MESSAGE_CONTENTS.*) —+ # never replace the MESSAGE_CONTENT write above.+ _safe_emit(+ f"input message extras (idx={idx})",+ _emit_input_message_extras,+ span,+ prefix,+ msg,+ )- # This shows up under `output_messages` tab on the span page.- prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{idx}"- safe_set_attribute(- span,- f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",- response_message.get("role"),- )- safe_set_attribute(- span,- f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",- response_message.get("content", ""),- )+ # Note: `BaseLLMObsOTELAttributes.set_response_output_messages` is not+ # overridden here. The live code path uses `_set_choice_outputs` (called+ # via `_set_response_attributes` from `set_attributes`) which handles+ # tool_calls, multimodal output, embeddings, audio, images, and structured+ # outputs in a single place.def _set_response_attributes(span: "Span", response_obj):@@ -106,11 +95,17 @@ def _set_response_attributes(span: "Span", response_obj):def _set_choice_outputs(span: "Span", response_obj, msg_attrs, span_attrs):for idx, choice in enumerate(response_obj.get("choices", [])):response_message = choice.get("message", {})- safe_set_attribute(- span,- span_attrs.OUTPUT_VALUE,- response_message.get("content", ""),- )+ content = response_message.get("content", "")++ # Tool-only assistant responses have empty content; serialize the+ # tool_calls into OUTPUT_VALUE so Arize's "Output" pane isn't blank.+ output_value = content+ if not output_value:+ tool_calls = _get_tool_calls(response_message)+ if tool_calls:+ output_value = _summarize_tool_calls_for_output(tool_calls)++ safe_set_attribute(span, span_attrs.OUTPUT_VALUE, output_value)prefix = f"{span_attrs.LLM_OUTPUT_MESSAGES}.{idx}"safe_set_attribute(span,@@ -120,7 +115,18 @@ def _set_choice_outputs(span: "Span", response_obj, msg_attrs, span_attrs):safe_set_attribute(span,f"{prefix}.{msg_attrs.MESSAGE_CONTENT}",- response_message.get("content", ""),+ content,+ )++ # Additive: emit assistant tool_calls so tool-using turns render in+ # Arize/Phoenix. Sets new MESSAGE_TOOL_CALLS keys only — does not+ # change MESSAGE_CONTENT/MESSAGE_ROLE writes above.+ _safe_emit(+ f"output tool_calls (idx={idx})",+ _emit_message_tool_calls,+ span,+ prefix,+ response_message,)@@ -278,6 +284,43 @@ def _set_usage_outputs(span: "Span", response_obj, span_attrs):reasoning_tokens,)+ # Additive: cache token breakdown so prompt-caching savings render in+ # Arize. Sources covered:+ # - OpenAI Chat Completions: `prompt_tokens_details.cached_tokens`+ # - Anthropic / Bedrock-Anthropic: `cache_read_input_tokens`,+ # `cache_creation_input_tokens`+ # All emits are conditional, so when none of these fields exist (the+ # situation in the existing test fixtures) no extra attributes are set.+ prompt_token_details = _safe_get(usage, "prompt_tokens_details") or _safe_get(+ usage, "input_tokens_details"+ )+ cache_read = _safe_get(prompt_token_details, "cached_tokens") or _safe_get(+ usage, "cache_read_input_tokens"+ )+ if cache_read:+ safe_set_attribute(+ span,+ span_attrs.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ,+ cache_read,+ )+ # Anthropic / Bedrock-Anthropic only — OpenAI's `prompt_tokens_details`+ # does not expose a cache-write count, so we read straight off `usage`.+ cache_write = _safe_get(usage, "cache_creation_input_tokens")+ if cache_write:+ safe_set_attribute(+ span,+ span_attrs.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE,+ cache_write,+ )++ audio_prompt_tokens = _safe_get(prompt_token_details, "audio_tokens")+ if audio_prompt_tokens:+ safe_set_attribute(+ span,+ span_attrs.LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO,+ audio_prompt_tokens,+ )+def _infer_open_inference_span_kind(call_type: Optional[str]) -> str:"""@@ -321,6 +364,10 @@ def _infer_open_inference_span_kind(call_type: Optional[str]) -> str:"videos","realtime","pass_through",+ # `passthrough` (no underscore) is what real call_types use:+ # `allm_passthrough_route`, `llm_passthrough_route`. Without+ # this they fell through to UNKNOWN, blanking span.kind.+ "passthrough","anthropic_messages","ocr",)@@ -396,6 +443,18 @@ def set_attributes("""Populates span with OpenInference-compliant LLM attributes for Arize and Phoenix tracing."""+ # Coerce non-dict response objects (e.g. httpx.Response from passthrough+ # routes) into a dict so downstream `.get()` calls don't crash. Existing+ # dict / `.get()`-bearing objects (incl. Pydantic OpenAI Responses API+ # models) are returned unchanged, preserving the existing test behavior.+ response_obj_for_attrs = _coerce_response_obj_for_attrs(response_obj)++ # Set span.kind defensively before anything else. If a downstream step+ # throws, the span still has a kind so Arize can render it correctly+ # (an LLM call instead of UNKNOWN). This is the single source of truth+ # for span.kind — no late re-write happens below.+ _safe_emit("early span kind", _set_early_span_kind, span, kwargs)+try:optional_params = _sanitize_optional_params(kwargs.get("optional_params"))litellm_params = kwargs.get("litellm_params", {}) or {}@@ -415,25 +474,22 @@ def set_attributes(metadata_tools = _extract_metadata_tools(metadata)optional_tools = _extract_optional_tools(optional_params)- call_type = standard_logging_payload.get("call_type")_set_request_attributes(span=span,kwargs=kwargs,standard_logging_payload=standard_logging_payload,optional_params=optional_params,litellm_params=litellm_params,- response_obj=response_obj,+ response_obj=response_obj_for_attrs,span_attrs=SpanAttributes,)- span_kind = _infer_open_inference_span_kind(call_type=call_type)+ # span.kind was already set above by `_set_early_span_kind`. We do+ # NOT re-write it here based on tool presence: a chat completion+ # that passes `tools=[...]` (or returns `tool_calls`) is still an+ # LLM call per the OpenInference spec — TOOL is reserved for actual+ # tool execution spans, not LLM calls that request tools._set_tool_attributes(span, optional_tools, metadata_tools)- if (- optional_tools or metadata_tools- ) and span_kind != OpenInferenceSpanKindValues.TOOL.value:- span_kind = OpenInferenceSpanKindValues.TOOL.value-- safe_set_attribute(span, SpanAttributes.OPENINFERENCE_SPAN_KIND, span_kind)attributes.set_messages(span, kwargs)model_params = (@@ -443,7 +499,7 @@ def set_attributes()_set_model_params(span, model_params, SpanAttributes)- _set_response_attributes(span=span, response_obj=response_obj)+ _set_response_attributes(span=span, response_obj=response_obj_for_attrs)except Exception as e:verbose_logger.error(@@ -452,6 +508,22 @@ def set_attributes(if hasattr(span, "record_exception"):span.record_exception(e)+ # Additive emitters. Each is independently guarded so a failure can never+ # blank the attributes set by the main try-block above. New attributes are+ # written under new keys; existing attributes are not overwritten.+ slp = kwargs.get("standard_logging_object")+ _safe_emit("session/user attrs", _set_session_and_user_attrs, span, kwargs, slp)+ _safe_emit("response cost", _set_response_cost_attr, span, slp)+ _safe_emit(+ "passthrough normalization",+ _maybe_normalize_passthrough,+ span,+ kwargs,+ response_obj,+ response_obj_for_attrs,+ slp,+ )+def _sanitize_optional_params(optional_params: Optional[dict]) -> dict:if not isinstance(optional_params, dict):@@ -534,3 +606,529 @@ def _set_model_params(span: "Span", model_params: Optional[dict], span_attrs) ->user_id = model_params.get("user")if user_id is not None:safe_set_attribute(span, span_attrs.USER_ID, user_id)+++# ---------------------------------------------------------------------------+# Additive rendering helpers (introduced to enhance Arize/Phoenix rendering+# without changing any previously-emitted attribute keys or values).+# ---------------------------------------------------------------------------+++def _safe_emit(label: str, fn, *args, **kwargs) -> None:+ """Run an additive attribute emitter, swallowing any error so it cannot+ blank attributes set elsewhere on the span. Failures are logged at debug.+ """+ try:+ fn(*args, **kwargs)+ except Exception as e:+ verbose_logger.debug("[Arize] %s skipped: %s", label, e)+++def _set_early_span_kind(span: "Span", kwargs: dict) -> None:+ """Defensively set OPENINFERENCE_SPAN_KIND before any other logic runs."""+ slp = kwargs.get("standard_logging_object")+ call_type = slp.get("call_type") if isinstance(slp, dict) else None+ safe_set_attribute(+ span,+ SpanAttributes.OPENINFERENCE_SPAN_KIND,+ _infer_open_inference_span_kind(call_type=call_type),+ )+++def _coerce_response_obj_for_attrs(response_obj):+ """Return a `.get`-compatible view of `response_obj` when possible.++ - dicts and Pydantic models that already expose `.get` are returned+ unchanged (preserves all current behavior, including the Responses API+ flow which relies on Pydantic attribute access).+ - `httpx.Response` and other text-only responses (passthrough routes)+ are JSON-decoded so the standard extraction paths can read fields like+ `id`, `model`, and `usage`. On failure the original object is returned+ so behavior is no worse than today.+ """+ if response_obj is None or hasattr(response_obj, "get"):+ return response_obj+ text = getattr(response_obj, "text", None)+ if isinstance(text, str) and text:+ try:+ parsed = json.loads(text)+ if isinstance(parsed, dict):+ return parsed+ except Exception:+ pass+ return response_obj+++def _coerce_text(value) -> Optional[str]:+ """Best-effort text extraction from a message-content value.++ Returns None when no textual portion can be derived. Handles:+ - plain strings+ - lists of OpenAI-style content parts (`{"type": "text", "text": ...}`)+ - lists of Anthropic-style content parts (`{"type": "text", "text": ...}`+ or `{"type": "input_text", "text": ...}`)+ """+ if value is None:+ return None+ if isinstance(value, str):+ return value+ if isinstance(value, list):+ parts = []+ for part in value:+ if isinstance(part, str):+ parts.append(part)+ elif isinstance(part, dict):+ text = part.get("text") or part.get("input_text")+ if isinstance(text, str):+ parts.append(text)+ if parts:+ return "\n".join(parts)+ return None+++def _to_plain_dict(value):+ """Best-effort: coerce a value (Pydantic model / dict / None) to a dict.++ Returns the original value when no safe conversion exists. Used to bridge+ OpenAI Pydantic message/tool_call objects into the dict-based helpers.+ """+ if value is None or isinstance(value, dict):+ return value+ model_dump = getattr(value, "model_dump", None)+ if callable(model_dump):+ try:+ return model_dump()+ except Exception:+ pass+ return value+++def _get_tool_calls(message) -> Optional[list]:+ """Return ``message.tool_calls`` only when it's a non-empty list.++ Works for dicts and Pydantic message objects via ``_safe_get``.+ """+ tool_calls = _safe_get(message, "tool_calls")+ return tool_calls if isinstance(tool_calls, list) and tool_calls else None+++def _normalize_tool_call(raw_tc) -> Optional[Dict[str, Any]]:+ """Normalize a single tool_call (dict or Pydantic) into a stable shape:++ {"id": str|None, "type": str, "function": {"name": str|None, "arguments": str|None}}++ Arguments are coerced to a JSON string per OpenInference convention.+ Returns ``None`` when ``raw_tc`` cannot be coerced to a dict.+ """+ tc = _to_plain_dict(raw_tc)+ if not isinstance(tc, dict):+ return None+ function = _to_plain_dict(tc.get("function"))+ name = function.get("name") if isinstance(function, dict) else None+ args = function.get("arguments") if isinstance(function, dict) else None+ if args is not None and not isinstance(args, str):+ try:+ args = json.dumps(args)+ except Exception:+ args = str(args)+ return {+ "id": tc.get("id"),+ "type": tc.get("type", "function"),+ "function": {"name": name, "arguments": args},+ }+++def _summarize_tool_calls_for_output(tool_calls) -> str:+ """Render a tool_calls list as a compact JSON string for OUTPUT_VALUE.++ Best-effort: returns ``str(tool_calls)`` if anything unexpected happens+ so OUTPUT_VALUE is never blanked on a malformed payload.+ """+ try:+ normalized = [n for n in (_normalize_tool_call(tc) for tc in tool_calls) if n]+ return json.dumps({"tool_calls": normalized})+ except Exception:+ return str(tool_calls)+++def _emit_message_tool_calls(span: "Span", prefix: str, message) -> None:+ """Emit ``MESSAGE_TOOL_CALLS.*`` for an assistant message that requested+ tool calls. Pure addition: only writes when ``tool_calls`` is non-empty.++ Accepts dicts or Pydantic message objects (e.g. ``litellm.Message``); the+ same applies to each tool_call entry.+ """+ tool_calls = _get_tool_calls(message)+ if not tool_calls:+ return+ for tc_idx, raw_tc in enumerate(tool_calls):+ tc = _normalize_tool_call(raw_tc)+ if tc is None:+ continue+ tc_prefix = f"{prefix}.{MessageAttributes.MESSAGE_TOOL_CALLS}.{tc_idx}"+ if tc["id"]:+ safe_set_attribute(+ span, f"{tc_prefix}.{ToolCallAttributes.TOOL_CALL_ID}", tc["id"]+ )+ fn = tc["function"]+ if fn["name"]:+ safe_set_attribute(+ span,+ f"{tc_prefix}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}",+ fn["name"],+ )+ if fn["arguments"] is not None:+ safe_set_attribute(+ span,+ f"{tc_prefix}.{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}",+ fn["arguments"],+ )+++def _emit_input_message_extras(span: "Span", prefix: str, message: dict) -> None:+ """Emit additive attributes for an input message:++ - `MESSAGE_NAME` and `MESSAGE_TOOL_CALL_ID` (commonly set on tool-result+ messages so traces show which tool produced which result).+ - `MESSAGE_TOOL_CALLS.*` when an assistant message requested tools.+ - `MESSAGE_CONTENTS.*` structured content for list-shaped content+ (multimodal text + image parts). The plain `MESSAGE_CONTENT` write is+ still performed by the caller, so renderers that only read the legacy+ key continue to work.+ """+ if not isinstance(message, dict):+ return++ name = message.get("name")+ if name:+ safe_set_attribute(span, f"{prefix}.{MessageAttributes.MESSAGE_NAME}", name)++ tool_call_id = message.get("tool_call_id")+ if tool_call_id:+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_TOOL_CALL_ID}",+ tool_call_id,+ )++ _emit_message_tool_calls(span, prefix, message)++ content = message.get("content")+ if isinstance(content, list):+ contents_prefix = f"{prefix}.{MessageAttributes.MESSAGE_CONTENTS}"+ for part_idx, part in enumerate(content):+ if not isinstance(part, dict):+ continue+ part_prefix = f"{contents_prefix}.{part_idx}"+ part_type = part.get("type")+ if part_type in ("text", "input_text"):+ text = part.get("text")+ if isinstance(text, str):+ safe_set_attribute(+ span,+ f"{part_prefix}.{MessageContentAttributes.MESSAGE_CONTENT_TYPE}",+ "text",+ )+ safe_set_attribute(+ span,+ f"{part_prefix}.{MessageContentAttributes.MESSAGE_CONTENT_TEXT}",+ text,+ )+ elif part_type in ("image_url", "image", "input_image"):+ url = None+ image = part.get("image_url")+ if isinstance(image, dict):+ url = image.get("url")+ elif isinstance(image, str):+ url = image+ if not url:+ # Anthropic-style source.{type=base64,media_type,data}+ source = part.get("source")+ if isinstance(source, dict) and source.get("data"):+ media_type = source.get("media_type", "image/jpeg")+ url = f"data:{media_type};base64,{source['data']}"+ elif isinstance(part.get("url"), str):+ url = part["url"]+ if url:+ safe_set_attribute(+ span,+ f"{part_prefix}.{MessageContentAttributes.MESSAGE_CONTENT_TYPE}",+ "image",+ )+ safe_set_attribute(+ span,+ f"{part_prefix}.message_content.image.image.url",+ url,+ )+++def _set_session_and_user_attrs(+ span: "Span", kwargs: dict, standard_logging_payload+) -> None:+ """Emit `SESSION_ID` / `USER_ID` / team metadata when source data exists.++ `SESSION_ID` is emitted only when an explicit end-user identifier exists+ (`metadata.user_api_key_end_user_id`). We deliberately do NOT fall back+ to `trace_id`, because that would create a distinct "session" for every+ single request and distort Arize's Session-grouping analytics. The+ `trace_id` is still emitted under its own `litellm.trace_id` key so+ spans remain filterable by trace.++ USER_ID is *only* emitted when no upstream path (model_params.user or+ optional_params.user) has already set it, to avoid overwriting an+ existing value with a possibly-different one from API-key metadata.+ """+ if not isinstance(standard_logging_payload, dict):+ return+ metadata = standard_logging_payload.get("metadata") or {}+ if not isinstance(metadata, dict):+ return++ session_id = metadata.get("user_api_key_end_user_id")+ if session_id:+ safe_set_attribute(span, SpanAttributes.SESSION_ID, str(session_id))++ trace_id = standard_logging_payload.get("trace_id")+ if trace_id:+ safe_set_attribute(span, "litellm.trace_id", str(trace_id))++ optional_params = kwargs.get("optional_params") or {}+ model_params = standard_logging_payload.get("model_parameters") or {}+ has_user_already = bool(+ (isinstance(optional_params, dict) and optional_params.get("user"))+ or (isinstance(model_params, dict) and model_params.get("user"))+ )+ if not has_user_already:+ user_id = metadata.get("user_api_key_user_id")+ if user_id:+ safe_set_attribute(span, SpanAttributes.USER_ID, str(user_id))++ team_id = metadata.get("user_api_key_team_id")+ if team_id:+ safe_set_attribute(span, "litellm.team_id", str(team_id))+ team_alias = metadata.get("user_api_key_team_alias")+ if team_alias:+ safe_set_attribute(span, "litellm.team_alias", str(team_alias))+ key_alias = metadata.get("user_api_key_alias")+ if key_alias:+ safe_set_attribute(span, "litellm.key_alias", str(key_alias))+++def _set_response_cost_attr(span: "Span", standard_logging_payload) -> None:+ """Emit cost attributes from the StandardLoggingPayload when present.++ Uses the OpenInference `llm.cost.total` key so Arize / Phoenix can+ surface the cost in their "Total Cost" column. LiteLLM only tracks a+ single total in `StandardLoggingPayload.response_cost`, so we cannot+ split it into prompt/completion. We also keep the legacy+ `llm.response.cost` key for back-compat with any consumer querying it.+ """+ if not isinstance(standard_logging_payload, dict):+ return+ cost = standard_logging_payload.get("response_cost")+ if cost is None:+ return+ try:+ cost_value = float(cost)+ except (TypeError, ValueError):+ return+ safe_set_attribute(span, "llm.cost.total", cost_value)+ safe_set_attribute(span, "llm.response.cost", cost_value)+++def _is_passthrough_call_type(call_type: Optional[str]) -> bool:+ if not call_type:+ return False+ lowered = str(call_type).lower()+ return "passthrough" in lowered or "pass_through" in lowered+++def _maybe_normalize_passthrough(+ span: "Span",+ kwargs: dict,+ raw_response_obj,+ coerced_response_obj,+ standard_logging_payload,+) -> None:+ """Surface input/output text for passthrough routes (e.g. Bedrock+ InvokeModel) so the parent span renders as more than `usage` numbers.++ Only runs when `call_type` is a passthrough variant. Reads from:+ - `kwargs["additional_args"]["complete_input_dict"]` for input+ - the coerced response (or `kwargs["original_response"]`) for output++ All emits are best-effort: if the provider shape isn't recognized the+ helper exits silently. Existing chat/completion paths never enter this+ helper because their call_type doesn't contain "passthrough".++ TEMPORARY BRIDGE: passthrough handlers don't populate the+ StandardLoggingPayload `messages` field today (they call+ `transform_response(messages=[])`), so the input is only available via+ `additional_args.complete_input_dict`. The proper fix is upstream in+ `base_passthrough_logging_handler._create_response_logging_payload()`:+ once that populates SLP `messages`/`response`, every callback gets+ passthrough I/O (with central redaction) for free and this helper's+ `complete_input_dict` fallback can be deleted. See follow-up issue.+ """+ call_type = (+ standard_logging_payload.get("call_type")+ if isinstance(standard_logging_payload, dict)+ else None+ )+ if not _is_passthrough_call_type(call_type):+ return++ # Respect LiteLLM's central message-redaction contract. The normal+ # chat/completion path is redacted by `perform_redaction` before+ # callbacks run, but `complete_input_dict` (read below) is NOT covered by+ # that layer — so without this gate, an operator who enabled redaction+ # would still see raw passthrough prompts in Arize. Skip entirely when+ # redaction is on so neither input nor output leaks through this bridge.+ if should_redact_message_logging(kwargs):+ return++ # --- INPUT --------------------------------------------------------------+ additional_args = kwargs.get("additional_args") or {}+ complete_input_dict = (+ additional_args.get("complete_input_dict")+ if isinstance(additional_args, dict)+ else None+ )+ if isinstance(complete_input_dict, dict):+ _set_passthrough_input_attributes(span, complete_input_dict.get("messages"))++ # --- OUTPUT -------------------------------------------------------------+ parsed_response = _parse_passthrough_response(+ raw_response_obj, coerced_response_obj, kwargs+ )+ if not isinstance(parsed_response, dict):+ return++ _set_passthrough_output_attributes(span, parsed_response)+++def _set_passthrough_input_attributes(span: "Span", messages) -> None:+ """Render passthrough request messages into INPUT_VALUE + LLM_INPUT_MESSAGES."""+ if not (isinstance(messages, list) and messages):+ return+ # Set INPUT_VALUE from the last user message text if discoverable.+ last_text = None+ for msg in reversed(messages):+ if isinstance(msg, dict):+ last_text = _coerce_text(msg.get("content"))+ if last_text:+ break+ if last_text:+ safe_set_attribute(span, SpanAttributes.INPUT_VALUE, last_text)+ # Mirror messages into LLM_INPUT_MESSAGES so the input pane renders.+ for idx, msg in enumerate(messages):+ if not isinstance(msg, dict):+ continue+ prefix = f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}"+ role = msg.get("role")+ if role:+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",+ role,+ )+ text = _coerce_text(msg.get("content"))+ if text is not None:+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",+ text,+ )+++def _set_passthrough_output_attributes(span: "Span", parsed_response: dict) -> None:+ """Render passthrough response into OUTPUT_VALUE + LLM_OUTPUT_MESSAGES."""+ # Anthropic / Bedrock-Anthropic: `content` is a list of typed parts.+ content_list = parsed_response.get("content")+ if isinstance(content_list, list) and content_list:+ texts = []+ for part in content_list:+ if isinstance(part, dict) and isinstance(part.get("text"), str):+ texts.append(part["text"])+ joined = "\n\n".join(t for t in texts if t)+ if joined:+ safe_set_attribute(span, SpanAttributes.OUTPUT_VALUE, joined)+ prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0"+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",+ parsed_response.get("role", "assistant"),+ )+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",+ joined,+ )++ # OpenAI-style passthrough: `choices[0].message.content`+ choices = parsed_response.get("choices")+ if isinstance(choices, list) and choices:+ first = choices[0]+ if isinstance(first, dict):+ msg = first.get("message")+ if isinstance(msg, dict):+ text = _coerce_text(msg.get("content"))+ if text:+ safe_set_attribute(span, SpanAttributes.OUTPUT_VALUE, text)+ prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0"+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",+ msg.get("role", "assistant"),+ )+ safe_set_attribute(+ span,+ f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",+ text,+ )+++def _parse_passthrough_response(raw_response_obj, coerced_response_obj, kwargs):+ """Return a dict view of the provider response for passthrough routes."""+ # Prefer the coerced view (already JSON-parsed for httpx.Response).+ candidates = []+ if isinstance(coerced_response_obj, dict):+ candidates.append(coerced_response_obj)+ if (+ isinstance(raw_response_obj, dict)+ and raw_response_obj is not coerced_response_obj+ ):+ candidates.append(raw_response_obj)++ for candidate in candidates:+ # StandardPassThroughResponseObject wrapper: {"response": "..."}.+ if (+ "response" in candidate+ and "content" not in candidate+ and "choices" not in candidate+ ):+ inner = candidate.get("response")+ if isinstance(inner, str):+ try:+ parsed = json.loads(inner)+ if isinstance(parsed, dict):+ return parsed+ except Exception:+ continue+ if isinstance(inner, dict):+ return inner+ else:+ return candidate++ # Fallback: kwargs["original_response"] from the OTel base path.+ original = kwargs.get("original_response") if isinstance(kwargs, dict) else None+ if isinstance(original, dict):+ return original+ if isinstance(original, str):+ try:+ parsed = json.loads(original)+ if isinstance(parsed, dict):+ return parsed+ except Exception:+ return None+ return Nonediff --git a/tests/test_litellm/integrations/arize/test_arize_utils.py b/tests/test_litellm/integrations/arize/test_arize_utils.pyindex 86c5448d468..83c3351319a 100644--- a/tests/test_litellm/integrations/arize/test_arize_utils.py+++ b/tests/test_litellm/integrations/arize/test_arize_utils.py@@ -83,7 +83,12 @@ def test_arize_set_attributes():# Apply attribute setting via ArizeLoggerArizeLogger.set_arize_attributes(span, kwargs, response_obj)- # Validate that the expected number of attributes were set+ # Validate that the expected number of attributes were set.+ # OPENINFERENCE_SPAN_KIND is written exactly once (defensively, before+ # the main attribute pipeline) so a partial failure cannot blank it.+ # Per the OpenInference spec, a chat completion that passes `tools=[...]`+ # is still an LLM span — not TOOL (TOOL is reserved for actual tool+ # execution by application code).assert span.set_attribute.call_count == 26# Metadata attached to the span@@ -108,8 +113,15 @@ def test_arize_set_attributes():# Response metadataspan.set_attribute.assert_any_call("llm.response.id", "chatcmpl-ID")span.set_attribute.assert_any_call("llm.response.model", "gpt-4o")- # Span kind is set to TOOL when tools are present- span.set_attribute.assert_any_call(SpanAttributes.OPENINFERENCE_SPAN_KIND, "TOOL")+ # Span kind stays LLM even when tools are passed (OpenInference spec).+ span.set_attribute.assert_any_call(SpanAttributes.OPENINFERENCE_SPAN_KIND, "LLM")+ # And TOOL must never be written for an LLM chat completion call.+ span_kind_writes = [+ c.args[1]+ for c in span.set_attribute.call_args_list+ if c.args[0] == SpanAttributes.OPENINFERENCE_SPAN_KIND+ ]+ assert "TOOL" not in span_kind_writes# Request message content and metadataspan.set_attribute.assert_any_call(@@ -451,3 +463,733 @@ def test_construct_dynamic_arize_headers():dynamic_params_space_key_and_api_key)expected_headers = {"arize-space-id": "test_space_key", "api_key": "test_api_key"}+++# ---------------------------------------------------------------------------+# Additive rendering-enhancement tests. None of these assert that previously+# emitted attributes were removed or changed — they only assert that the new+# attributes appear in their respective scenarios.+# ---------------------------------------------------------------------------+++def _collect_calls(span):+ """Helper: return dict[attr_name] = value of all set_attribute calls."""+ out = {}+ for call in span.set_attribute.call_args_list:+ args = call.args+ if len(args) >= 2:+ out[args[0]] = args[1]+ return out+++def test_arize_emits_cache_tokens_openai_style():+ """OpenAI prompt_tokens_details.cached_tokens → cache_read attr."""+ from unittest.mock import MagicMock++ from litellm.integrations.arize._utils import _set_usage_outputs++ span = MagicMock()+ response_obj = {+ "usage": {+ "total_tokens": 100,+ "completion_tokens": 60,+ "prompt_tokens": 40,+ "prompt_tokens_details": {"cached_tokens": 32, "audio_tokens": 8},+ }+ }+ _set_usage_outputs(span, response_obj, SpanAttributes)+ attrs = _collect_calls(span)+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ] == 32+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO] == 8+++def test_arize_emits_cache_tokens_anthropic_style():+ """Anthropic/Bedrock cache_read_input_tokens / cache_creation_input_tokens."""+ from unittest.mock import MagicMock++ from litellm.integrations.arize._utils import _set_usage_outputs++ span = MagicMock()+ response_obj = {+ "usage": {+ "input_tokens": 100,+ "output_tokens": 50,+ "cache_read_input_tokens": 80,+ "cache_creation_input_tokens": 20,+ }+ }+ _set_usage_outputs(span, response_obj, SpanAttributes)+ attrs = _collect_calls(span)+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ] == 80+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE] == 20+++def test_arize_emits_no_cache_tokens_when_absent():+ """Regression guard: when no cache fields exist, no cache attrs emitted."""+ from unittest.mock import MagicMock++ from litellm.integrations.arize._utils import _set_usage_outputs++ span = MagicMock()+ response_obj = {+ "usage": {"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6}+ }+ _set_usage_outputs(span, response_obj, SpanAttributes)+ attrs = _collect_calls(span)+ assert SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ not in attrs+ assert SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE not in attrs+++def test_passthrough_call_type_resolves_to_llm_span_kind():+ """`allm_passthrough_route` should map to LLM (was UNKNOWN before fix)."""+ from litellm.integrations._types.open_inference import OpenInferenceSpanKindValues+ from litellm.integrations.arize._utils import _infer_open_inference_span_kind++ assert (+ _infer_open_inference_span_kind("allm_passthrough_route")+ == OpenInferenceSpanKindValues.LLM.value+ )+ assert (+ _infer_open_inference_span_kind("llm_passthrough_route")+ == OpenInferenceSpanKindValues.LLM.value+ )+++def test_arize_chat_completion_with_tools_stays_llm_span_kind():+ """Regression guard against the old `TOOL` override: a chat completion+ that passes `tools=[...]` AND returns `tool_calls` must remain LLM."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "weather?"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "weather",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]+ },+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6},+ choices=[+ Choices(+ message={+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_x",+ "type": "function",+ "function": {"name": "get_weather", "arguments": "{}"},+ }+ ],+ }+ )+ ],+ model="gpt-4o",+ id="r-toolkind",+ )++ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ span_kind_writes = [+ c.args[1]+ for c in span.set_attribute.call_args_list+ if c.args[0] == SpanAttributes.OPENINFERENCE_SPAN_KIND+ ]+ assert span_kind_writes, "span.kind must be written"+ assert all(v == "LLM" for v in span_kind_writes)+ assert "TOOL" not in span_kind_writes+++def test_arize_emits_assistant_tool_calls_on_output_message():+ """Assistant tool_calls should surface as MESSAGE_TOOL_CALLS.* attrs."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "weather?"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6},+ choices=[+ Choices(+ message={+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_abc",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "SF"}',+ },+ }+ ],+ }+ )+ ],+ model="gpt-4o",+ id="chatcmpl-1",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ base = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_TOOL_CALLS}.0"+ assert attrs[f"{base}.{ToolCallAttributes.TOOL_CALL_ID}"] == "call_abc"+ assert (+ attrs[f"{base}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}"] == "get_weather"+ )+ assert (+ attrs[f"{base}.{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}"]+ == '{"location": "SF"}'+ )+++def test_arize_output_value_falls_back_to_tool_calls_summary():+ """When the assistant returns no text content but did request tool+ calls, OUTPUT_VALUE should contain a JSON summary so Arize's Output+ pane shows something."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "weather?"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6},+ choices=[+ Choices(+ message={+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_abc",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "SF"}',+ },+ }+ ],+ }+ )+ ],+ model="gpt-4o",+ id="r-tc-out",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)++ # OUTPUT_VALUE should contain the tool_call name + arguments JSON+ out = attrs[SpanAttributes.OUTPUT_VALUE]+ assert "tool_calls" in out+ assert "get_weather" in out+ assert "SF" in out+++def test_arize_output_value_unchanged_when_content_present():+ """Regression guard: when content is non-empty, OUTPUT_VALUE must be+ exactly that content (no summary written)."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 4, "completion_tokens": 2, "prompt_tokens": 2},+ choices=[+ Choices(+ message={+ "role": "assistant",+ "content": "hello world",+ "tool_calls": [+ {+ "id": "call_x",+ "type": "function",+ "function": {"name": "n", "arguments": "{}"},+ }+ ],+ }+ )+ ],+ model="gpt-4o",+ id="r-content",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ assert attrs[SpanAttributes.OUTPUT_VALUE] == "hello world"+++def test_arize_emits_tool_call_id_and_name_on_input_tool_message():+ """A tool-result input message should expose tool_call_id + name."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "weather?"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_abc",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "SF"}',+ },+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_abc",+ "name": "get_weather",+ "content": "sunny, 72F",+ },+ ],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6},+ choices=[Choices(message={"role": "assistant", "content": "It's sunny."})],+ model="gpt-4o",+ id="chatcmpl-2",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ # Assistant tool_call surfaces on input msg index 1+ assistant_base = f"{SpanAttributes.LLM_INPUT_MESSAGES}.1.{MessageAttributes.MESSAGE_TOOL_CALLS}.0"+ assert attrs[f"{assistant_base}.{ToolCallAttributes.TOOL_CALL_ID}"] == "call_abc"+ # Tool message at index 2+ tool_prefix = f"{SpanAttributes.LLM_INPUT_MESSAGES}.2"+ assert (+ attrs[f"{tool_prefix}.{MessageAttributes.MESSAGE_TOOL_CALL_ID}"] == "call_abc"+ )+ assert attrs[f"{tool_prefix}.{MessageAttributes.MESSAGE_NAME}"] == "get_weather"+++def test_arize_emits_multimodal_input_contents():+ """List-shaped content should populate MESSAGE_CONTENTS.* alongside the+ legacy MESSAGE_CONTENT (which stays for back-compat)."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What is in this image?"},+ {+ "type": "image_url",+ "image_url": {"url": "https://example.com/cat.png"},+ },+ ],+ }+ ],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 10, "completion_tokens": 4, "prompt_tokens": 6},+ choices=[Choices(message={"role": "assistant", "content": "A cat."})],+ model="gpt-4o",+ id="chatcmpl-img",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ base = f"{SpanAttributes.LLM_INPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENTS}"+ assert attrs[f"{base}.0.message_content.type"] == "text"+ assert attrs[f"{base}.0.message_content.text"] == "What is in this image?"+ assert attrs[f"{base}.1.message_content.type"] == "image"+ assert (+ attrs[f"{base}.1.message_content.image.image.url"]+ == "https://example.com/cat.png"+ )+++def test_arize_emits_session_and_user_attrs_from_metadata():+ """end_user_id → SESSION_ID; user_api_key_user_id → USER_ID (only when+ optional_params.user/model_params.user absent)."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {+ "user_api_key_user_id": "user_42",+ "user_api_key_end_user_id": "session_99",+ "user_api_key_team_id": "team_7",+ "user_api_key_team_alias": "alpha",+ "user_api_key_alias": "key_alpha",+ },+ "call_type": "completion",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 4, "completion_tokens": 2, "prompt_tokens": 2},+ choices=[Choices(message={"role": "assistant", "content": "hello"})],+ model="gpt-4o",+ id="r1",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ assert attrs[SpanAttributes.SESSION_ID] == "session_99"+ assert attrs[SpanAttributes.USER_ID] == "user_42"+ assert attrs["litellm.team_id"] == "team_7"+ assert attrs["litellm.team_alias"] == "alpha"+ assert attrs["litellm.key_alias"] == "key_alpha"+++def test_arize_does_not_use_trace_id_as_session_id_fallback():+ """SESSION_ID must NOT fall back to trace_id (one session-per-request+ would distort Arize Session analytics). trace_id is emitted under its+ own `litellm.trace_id` key instead.+ """+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ "trace_id": "trace-xyz-123",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 4, "completion_tokens": 2, "prompt_tokens": 2},+ choices=[Choices(message={"role": "assistant", "content": "hi"})],+ model="gpt-4o",+ id="r-trace",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)++ # SESSION_ID must NOT be derived from trace_id.+ assert SpanAttributes.SESSION_ID not in attrs+ # trace_id surfaces under its own key.+ assert attrs["litellm.trace_id"] == "trace-xyz-123"+++def test_arize_does_not_overwrite_user_id_from_optional_params():+ """If optional_params.user is set, metadata USER_ID must NOT overwrite."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ "standard_logging_object": {+ "model_parameters": {"user": "from_model_params"},+ "metadata": {"user_api_key_user_id": "from_metadata"},+ "call_type": "completion",+ },+ "optional_params": {"user": "from_optional_params"},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 4, "completion_tokens": 2, "prompt_tokens": 2},+ choices=[Choices(message={"role": "assistant", "content": "hello"})],+ model="gpt-4o",+ id="r2",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ user_id_writes = [+ c.args[1]+ for c in span.set_attribute.call_args_list+ if c.args[0] == SpanAttributes.USER_ID+ ]+ assert "from_metadata" not in user_id_writes+++def test_arize_emits_response_cost():+ """StandardLoggingPayload.response_cost → llm.cost.total (+ legacy llm.response.cost)."""+ from unittest.mock import MagicMock++ from litellm.types.utils import Choices, ModelResponse++ span = MagicMock()+ kwargs = {+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "completion",+ "response_cost": 0.0012345,+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "openai"},+ }+ response_obj = ModelResponse(+ usage={"total_tokens": 4, "completion_tokens": 2, "prompt_tokens": 2},+ choices=[Choices(message={"role": "assistant", "content": "hello"})],+ model="gpt-4o",+ id="r3",+ )+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)+ assert attrs["llm.cost.total"] == 0.0012345+ assert attrs["llm.response.cost"] == 0.0012345 # legacy key still emitted+++def test_arize_passthrough_bedrock_anthropic_normalization():+ """Bedrock-Anthropic passthrough: input/output text must be set so the+ span renders something other than raw provider attrs."""+ from unittest.mock import MagicMock++ span = MagicMock()+ bedrock_response_body = {+ "id": "msg_01",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "The capital of France is Paris."}],+ "model": "anthropic.claude-sonnet-4-v1:0",+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 18, "output_tokens": 12},+ }++ class FakeHttpxResponse:+ """Minimal httpx.Response stand-in: has `.text` and no `.get`."""++ def __init__(self, body):+ self.text = json.dumps(body)++ response_obj = FakeHttpxResponse(bedrock_response_body)+ kwargs = {+ "model": "anthropic.claude-sonnet-4-v1:0",+ "messages": [+ {+ "role": "user",+ "content": json.dumps({"messages": [{"role": "user", "content": "?"}]}),+ }+ ],+ "additional_args": {+ "complete_input_dict": {+ "anthropic_version": "bedrock-2023-05-31",+ "max_tokens": 64,+ "messages": [+ {"role": "user", "content": "What is the capital of France?"}+ ],+ }+ },+ "standard_logging_object": {+ "model_parameters": {},+ "metadata": {},+ "call_type": "allm_passthrough_route",+ },+ "optional_params": {},+ "litellm_params": {"custom_llm_provider": "bedrock"},+ }+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)+ attrs = _collect_calls(span)++ # Input rendering+ assert attrs[SpanAttributes.INPUT_VALUE] == "What is the capital of France?"+ msg0 = f"{SpanAttributes.LLM_INPUT_MESSAGES}.0"+ assert attrs[f"{msg0}.{MessageAttributes.MESSAGE_ROLE}"] == "user"+ assert (+ attrs[f"{msg0}.{MessageAttributes.MESSAGE_CONTENT}"]+ == "What is the capital of France?"+ )++ # Output rendering (Anthropic content[].text)+ assert attrs[SpanAttributes.OUTPUT_VALUE] == "The capital of France is Paris."+ out0 = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0"+ assert attrs[f"{out0}.{MessageAttributes.MESSAGE_ROLE}"] == "assistant"+ assert (+ attrs[f"{out0}.{MessageAttributes.MESSAGE_CONTENT}"]+ == "The capital of France is Paris."+ )++ # Token counts (Bedrock input_tokens/output_tokens) — extracted via+ # coercion of the non-dict response.+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_PROMPT] == 18+ assert attrs[SpanAttributes.LLM_TOKEN_COUNT_COMPLETION] == 12++ # Span kind defended even though the call_type is a passthrough variant.+ span_kind_writes = [+ c.args[1]+ for c in span.set_attribute.call_args_list+ if c.args[0] == SpanAttributes.OPENINFERENCE_SPAN_KIND+ ]+ assert span_kind_writes # at least one+ assert all(v == "LLM" for v in span_kind_writes)+++def test_arize_passthrough_call_type_does_not_run_on_chat_completion():+ """Guard: passthrough normalizer must not fire for normal chat calls.++ If it did, it could double-write input/output for ordinary completions.+ """+ from unittest.mock import MagicMock++ from litellm.integrations.arize._utils import _maybe_normalize_passthrough++ span = MagicMock()+ _maybe_normalize_passthrough(+ span,+ {+ "additional_args": {+ "complete_input_dict": {"messages": [{"role": "user", "content": "x"}]}+ }+ },+ {"choices": [{"message": {"role": "assistant", "content": "y"}}]},+ {"choices": [{"message": {"role": "assistant", "content": "y"}}]},+ {"call_type": "completion"},+ )+ assert span.set_attribute.call_count == 0+++def test_arize_passthrough_skipped_when_message_redaction_enabled():+ """Security guard: when message-logging redaction is enabled, the+ passthrough normalizer must NOT export the raw prompt (read from+ `complete_input_dict`, which bypasses central redaction) to the span.+ """+ from unittest.mock import MagicMock++ from litellm.integrations.arize._utils import _maybe_normalize_passthrough++ span = MagicMock()+ kwargs = {+ "additional_args": {+ "complete_input_dict": {+ "messages": [+ {"role": "user", "content": "Patient John Doe, SSN 123-45-6789"}+ ]+ }+ },+ # Enables redaction via the dynamic-param path inside+ # should_redact_message_logging(), without touching globals.+ "standard_callback_dynamic_params": {"turn_off_message_logging": True},+ }+ _maybe_normalize_passthrough(+ span,+ kwargs,+ {"content": [{"type": "text", "text": "secret response"}]},+ {"content": [{"type": "text", "text": "secret response"}]},+ {"call_type": "allm_passthrough_route"},+ )+ # Nothing — neither input nor output — should be written to the span.+ assert span.set_attribute.call_count == 0+++def test_arize_coerce_response_obj_passes_dicts_through_untouched():+ """Regression guard for the BaseModel/dict path."""+ from litellm.integrations.arize._utils import _coerce_response_obj_for_attrs++ d = {"id": "x", "model": "m"}+ assert _coerce_response_obj_for_attrs(d) is d++ class HasGet:+ def get(self, *a, **k): # noqa: D401+ return None++ obj = HasGet()+ assert _coerce_response_obj_for_attrs(obj) is obj++ assert _coerce_response_obj_for_attrs(None) is None+++def test_arize_coerce_response_obj_parses_httpx_like():+ """httpx.Response-like objects without `.get` should JSON-decode."""+ from litellm.integrations.arize._utils import _coerce_response_obj_for_attrs++ class FakeHttpxResponse:+ text = '{"id": "msg_1", "model": "claude"}'++ parsed = _coerce_response_obj_for_attrs(FakeHttpxResponse())+ assert parsed == {"id": "msg_1", "model": "claude"}+++def test_arize_coerce_response_obj_returns_original_on_bad_json():+ from litellm.integrations.arize._utils import _coerce_response_obj_for_attrs++ class BadJson:+ text = "not-json"++ obj = BadJson()+ assert _coerce_response_obj_for_attrs(obj) is obj