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(otel): allowlist team_metadata sub-keys promoted to baggage (#29442)
Yassin Kortam8190ff4d866a
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.pyindex 814da344f03..cb619ae0204 100644--- a/litellm/integrations/opentelemetry.py+++ b/litellm/integrations/opentelemetry.py@@ -83,6 +83,19 @@ _VALID_CAPTURE_MODES = {}+def _normalize_team_metadata_keys(value: Any) -> List[str]:+ """Coerce a team-metadata allowlist from a list or comma-separated string.++ config.yaml passes a YAML list; an env var passes a comma-separated string.+ Both collapse to a list of stripped, non-empty keys.+ """+ if value is None:+ return []+ if isinstance(value, str):+ return [item.strip() for item in value.split(",") if item.strip()]+ return [str(item).strip() for item in value if str(item).strip()]++@dataclassclass OpenTelemetryConfig:exporter: Union[str, SpanExporter] = "console"@@ -100,6 +113,10 @@ class OpenTelemetryConfig:# One of NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT (or "true" as legacy alias).capture_message_content: Optional[str] = Nonesemconv_stability_opt_in: Set[OTELSemconvCategory] = field(default_factory=set)+ # Sub-keys of the team's free-form metadata stamped onto the inference span+ # under ``litellm.team.metadata``. Empty by default so none of a team's+ # metadata leaves the process until explicitly allowlisted.+ baggage_team_metadata_keys: List[str] = field(default_factory=list)def __post_init__(self) -> None:# If endpoint is specified but exporter is still the default "console",@@ -130,6 +147,11 @@ class OpenTelemetryConfig:self.semconv_stability_opt_in |= parse_semconv_opt_in(os.getenv(OTEL_SEMCONV_STABILITY_OPT_IN_ENV))+ self.baggage_team_metadata_keys = _normalize_team_metadata_keys(+ self.baggage_team_metadata_keys+ ) or _normalize_team_metadata_keys(+ os.getenv("LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS")+ )@classmethoddef from_env(cls):@@ -188,8 +210,13 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):meter_provider: Optional[Any] = None,**kwargs,):+ team_metadata_keys_override = kwargs.pop("baggage_team_metadata_keys", None)if config is None:config = OpenTelemetryConfig.from_env()+ if team_metadata_keys_override is not None:+ config.baggage_team_metadata_keys = _normalize_team_metadata_keys(+ team_metadata_keys_override+ )self.config = configself.callback_name = callback_name@@ -1245,7 +1272,8 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):or {})team_metadata = self._team_metadata_json(- raw_metadata.get("user_api_key_team_metadata")+ raw_metadata.get("user_api_key_team_metadata"),+ self.config.baggage_team_metadata_keys,)if team_metadata:self.safe_set_attribute(@@ -1268,15 +1296,20 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):)@staticmethod- def _team_metadata_json(value: Any) -> Optional[str]:- """JSON-serialize a team's metadata dict for a single span attribute.+ def _team_metadata_json(value: Any, allowed_keys: List[str]) -> Optional[str]:+ """JSON-serialize only the allowlisted sub-keys of a team's metadata.- Returns ``None`` for a missing, non-dict, or empty mapping so the- empty case is dropped rather than stamping a useless ``"{}"``.+ Returns ``None`` when nothing is allowlisted or no allowlisted key is+ present, so the empty case is dropped rather than stamping a useless+ ``"{}"`` (and so a team's metadata never leaves the process until an+ operator opts each sub-key in via ``baggage_team_metadata_keys``)."""- if not isinstance(value, dict) or not value:+ if not isinstance(value, dict) or not value or not allowed_keys:+ return None+ filtered = {key: value[key] for key in allowed_keys if key in value}+ if not filtered:return None- return safe_dumps(value)+ return safe_dumps(filtered)def _record_metrics(self, kwargs, response_obj, start_time, end_time):duration_s = (end_time - start_time).total_seconds()diff --git a/litellm/integrations/otel/README.md b/litellm/integrations/otel/README.mdindex 99b3ecea162..3edb96ed8d9 100644--- a/litellm/integrations/otel/README.md+++ b/litellm/integrations/otel/README.md@@ -172,10 +172,13 @@ nothing here imports outside it:`capture_span_content` gates whether prompt/response bodies may be written asspan attributes; it defaults **off** (`no_content`). The Baggage allowlists areconfigurable, not hard-coded: set `LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS` /- `LITELLM_OTEL_BAGGAGE_METADATA_KEYS` (comma-separated) as env vars, or- `baggage_promoted_keys` / `baggage_metadata_keys` (YAML lists) under- `callback_settings.otel` in `config.yaml` — the latter reach the config through- the logger's constructor kwargs.+ `LITELLM_OTEL_BAGGAGE_METADATA_KEYS` /+ `LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS` (comma-separated) as env vars, or+ `baggage_promoted_keys` / `baggage_metadata_keys` /+ `baggage_team_metadata_keys` (YAML lists) under `callback_settings.otel` in+ `config.yaml` — the latter reach the config through the logger's constructor+ kwargs. `baggage_team_metadata_keys` is empty by default, so none of a team's+ free-form metadata is promoted until each sub-key is explicitly allowlisted.- [`baggage.py`](./model/baggage.py) — the single definition of which request-identityvalues are promoted into Baggage (so child spans inherit them) and under whichattribute keys.diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.pyindex 007b41df0a3..d7058b34d50 100644--- a/litellm/integrations/otel/logger.py+++ b/litellm/integrations/otel/logger.py@@ -254,6 +254,7 @@ class OpenTelemetryV2(CustomLogger):data.request_model,promoted_keys=tuple(self.config.baggage_promoted_keys),metadata_keys=tuple(self.config.baggage_metadata_keys),+ team_metadata_keys=tuple(self.config.baggage_team_metadata_keys),)if bag:parent_ctx = set_request_baggage(bag, context=parent_ctx)@@ -380,6 +381,7 @@ class OpenTelemetryV2(CustomLogger):model,promoted_keys=tuple(self.config.baggage_promoted_keys),metadata_keys=tuple(self.config.baggage_metadata_keys),+ team_metadata_keys=tuple(self.config.baggage_team_metadata_keys),)if bag:# Attach (no detach): the contextvar is scoped to this request'sdiff --git a/litellm/integrations/otel/model/baggage.py b/litellm/integrations/otel/model/baggage.pyindex 67dd64e3914..ecab643a26b 100644--- a/litellm/integrations/otel/model/baggage.py+++ b/litellm/integrations/otel/model/baggage.py@@ -6,26 +6,36 @@ LLM-call span so that child spans (guardrail, service) inherit them.the allowlisted keys onto every span.This module is the single place baggage is defined: ``_PROMOTABLE`` maps each-promotable attribute key to how its value is read, and the two ``*_KEYS``-defaults select what is promoted unless the config overrides them.+promotable attribute key to how its value is read, and the ``*_KEYS`` defaults+select what is promoted unless the config overrides them. ``TEAM_METADATA``'s+extractor filters the team's free-form metadata to the sub-keys an operator+allowlists via ``baggage_team_metadata_keys`` (default none), so the blob is+never promoted whole."""-from collections.abc import Callable+import json+from collections.abc import Callable, Mappingfrom typing import Finalfrom litellm.integrations.otel.model.metadata import RequestIdentityfrom litellm.integrations.otel.model.semconv import GenAI, LiteLLM-# Attribute key -> value extractor over (identity, request_model). The single-# definition of what may be promoted and under which key.-_PROMOTABLE: Final[dict[str, Callable[[RequestIdentity, str | None], str | None]]] = {- LiteLLM.TEAM_ID: lambda identity, model: identity.team_id,- LiteLLM.TEAM_ALIAS: lambda identity, model: identity.team_alias,- LiteLLM.TEAM_METADATA: lambda identity, model: identity.team_metadata,- LiteLLM.KEY_HASH: lambda identity, model: identity.key_hash,- LiteLLM.END_USER: lambda identity, model: identity.end_user,- GenAI.REQUEST_MODEL: lambda identity, model: model,- LiteLLM.PROVIDER_MODEL: lambda identity, model: identity.provider_model,+# Attribute key -> value extractor over (identity, request_model,+# team_metadata_keys). The single definition of what may be promoted and under+# which key. Only the ``TEAM_METADATA`` extractor consults team_metadata_keys+# (to filter the team's metadata to an allowlist); the rest ignore it.+_PROMOTABLE: Final[+ dict[str, Callable[[RequestIdentity, str | None, tuple[str, ...]], str | None]]+] = {+ LiteLLM.TEAM_ID: lambda identity, model, team_metadata_keys: identity.team_id,+ LiteLLM.TEAM_ALIAS: lambda identity, model, team_metadata_keys: identity.team_alias,+ LiteLLM.TEAM_METADATA: lambda identity, model, team_metadata_keys: _filtered_team_metadata_json(+ identity.team_metadata, team_metadata_keys+ ),+ LiteLLM.KEY_HASH: lambda identity, model, team_metadata_keys: identity.key_hash,+ LiteLLM.END_USER: lambda identity, model, team_metadata_keys: identity.end_user,+ GenAI.REQUEST_MODEL: lambda identity, model, team_metadata_keys: model,+ LiteLLM.PROVIDER_MODEL: lambda identity, model, team_metadata_keys: identity.provider_model,}# Keys promoted by default (a subset of ``_PROMOTABLE``). ``END_USER`` is@@ -50,23 +60,31 @@ DEFAULT_BAGGAGE_METADATA_KEYS: Final[tuple[str, ...]] = ("requester_ip_address",)+# Sub-keys of the team's free-form metadata eligible for promotion under+# ``litellm.team.metadata``. Empty by default: a team's metadata can hold+# arbitrary operator data, so none of it is promoted until each key is+# explicitly allowlisted via ``config.baggage_team_metadata_keys``.+DEFAULT_BAGGAGE_TEAM_METADATA_KEYS: Final[tuple[str, ...]] = ()+def promoted_baggage(identity: RequestIdentity,request_model: str | None,promoted_keys: tuple[str, ...],metadata_keys: tuple[str, ...] = DEFAULT_BAGGAGE_METADATA_KEYS,+ team_metadata_keys: tuple[str, ...] = DEFAULT_BAGGAGE_TEAM_METADATA_KEYS,) -> dict[str, str]:"""Identity values to write into Baggage, filtered to ``promoted_keys``.``promoted_keys`` selects from ``_PROMOTABLE``; ``metadata_keys`` selects- sub-keys of ``identity.metadata`` to promote under ``litellm.metadata.*``.- Empty values are dropped.+ sub-keys of ``identity.metadata`` to promote under ``litellm.metadata.*``;+ ``team_metadata_keys`` selects sub-keys of the team's metadata to promote+ under ``litellm.team.metadata``. Empty values are dropped."""out: dict[str, str] = {}for key, extract in _PROMOTABLE.items():if key in promoted_keys:- value = extract(identity, request_model)+ value = extract(identity, request_model, team_metadata_keys)if value:out[key] = valuefor meta_key in metadata_keys:@@ -74,3 +92,21 @@ def promoted_baggage(if value:out[f"{LiteLLM.METADATA_PREFIX}{meta_key}"] = valuereturn out+++def _filtered_team_metadata_json(+ metadata: Mapping[str, object] | None,+ allowed_keys: tuple[str, ...],+) -> str | None:+ """JSON-serialize only the allowlisted sub-keys of a team's metadata.++ Returns ``None`` when nothing is allowlisted or no allowlisted key is+ present, so the empty case is dropped rather than promoting ``"{}"``. Keys+ are sorted for a stable, diff-friendly value.+ """+ if not isinstance(metadata, Mapping) or not allowed_keys:+ return None+ filtered = {key: metadata[key] for key in allowed_keys if key in metadata}+ if not filtered:+ return None+ return json.dumps(filtered, default=str, sort_keys=True)diff --git a/litellm/integrations/otel/model/config.py b/litellm/integrations/otel/model/config.pyindex f78e1515ea1..ca46182bc66 100644--- a/litellm/integrations/otel/model/config.py+++ b/litellm/integrations/otel/model/config.py@@ -9,6 +9,7 @@ from typing_extensions import Annotatedfrom litellm.integrations.otel.model.baggage import (BAGGAGE_PROMOTED_KEYS,DEFAULT_BAGGAGE_METADATA_KEYS,+ DEFAULT_BAGGAGE_TEAM_METADATA_KEYS,)#: Master feature-flag env var. The logger is inert until this is truthy.@@ -168,10 +169,25 @@ class OpenTelemetryV2Config(BaseSettings):"``callback_settings.otel.baggage_metadata_keys`` in config.yaml."),)+ baggage_team_metadata_keys: Annotated[List[str], NoDecode] = Field(+ default_factory=lambda: list(DEFAULT_BAGGAGE_TEAM_METADATA_KEYS),+ validation_alias=AliasChoices(+ "baggage_team_metadata_keys", "LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS"+ ),+ description=(+ "Sub-keys of the team's free-form metadata promoted under "+ "``litellm.team.metadata``. Empty by default so none of a team's "+ "metadata leaves the process until explicitly allowlisted. Configure "+ "via the ``LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS`` env var "+ "(comma-separated) or "+ "``callback_settings.otel.baggage_team_metadata_keys`` in config.yaml."+ ),+ )@field_validator("baggage_promoted_keys","baggage_metadata_keys",+ "baggage_team_metadata_keys","mapper_names",mode="before",)diff --git a/litellm/integrations/otel/model/metadata.py b/litellm/integrations/otel/model/metadata.pyindex f0ea0a608c6..4663ed59761 100644--- a/litellm/integrations/otel/model/metadata.py+++ b/litellm/integrations/otel/model/metadata.py@@ -36,7 +36,6 @@ model. They coincide on the SDK path, which is correct.from __future__ import annotations-import jsonfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, Mapping, cast@@ -53,8 +52,10 @@ class RequestIdentity:call_id: str | None = Noneteam_id: str | None = Noneteam_alias: str | None = None- # The team's free-form metadata dict, JSON-serialized (empty/missing -> None).- team_metadata: str | None = None+ # The team's free-form metadata, carried raw (empty/missing -> None) and+ # filtered to an operator allowlist only at Baggage-promotion time, so an+ # unconfigured deployment never promotes any of it.+ team_metadata: Mapping[str, Any] | None = Nonekey_hash: str | None = Noneend_user: str | None = None# The model litellm dispatched to the provider. Only known once the call@@ -86,7 +87,7 @@ class RequestIdentity:or as_str(raw_meta.get("team_id")),team_alias=as_str(raw_meta.get("user_api_key_team_alias"))or as_str(raw_meta.get("team_alias")),- team_metadata=_team_metadata_json(+ team_metadata=_team_metadata_dict(raw_meta.get("user_api_key_team_metadata")),key_hash=as_str(raw_meta.get("user_api_key_hash")),@@ -121,7 +122,7 @@ class RequestIdentity:return cls(team_id=as_str(get("team_id")),team_alias=as_str(get("team_alias")),- team_metadata=_team_metadata_json(get("team_metadata")),+ team_metadata=_team_metadata_dict(get("team_metadata")),key_hash=as_str(get("api_key")),end_user=as_str(get("end_user_id")),# ``provider_model`` is unknown at the auth boundary — routing hasn't@@ -300,16 +301,14 @@ def _model_info_id(model_info: object) -> str | None:return None-def _team_metadata_json(value: object) -> str | None:- """JSON-serialize a team's metadata dict for a single Baggage value.+def _team_metadata_dict(value: object) -> Mapping[str, Any] | None:+ """The team's free-form metadata as a raw mapping, or ``None`` when missing+ or empty.- Returns ``None`` for a missing, non-dict, or empty mapping so the empty case- is dropped rather than promoting a useless ``"{}"``. Keys are sorted for a- stable, diff-friendly serialization.+ Carried raw on the identity and filtered to an operator allowlist only at+ Baggage-promotion time (see ``baggage.promoted_baggage``), so an empty case+ is dropped rather than carrying a useless ``{}``."""- if not isinstance(value, Mapping) or not value:- return None- try:- return json.dumps(value, default=str, sort_keys=True)- except Exception:- return None+ if isinstance(value, Mapping) and value:+ return dict(value)+ return Nonediff --git a/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py b/tests/test_litellm/integrations/otel/test_otel_v2_baggage.pyindex fd4a7e141e5..b379b8bebc9 100644--- a/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py+++ b/tests/test_litellm/integrations/otel/test_otel_v2_baggage.py@@ -77,28 +77,67 @@ def test_identity_promoted_onto_every_span():assert span.attributes.get(GenAI.REQUEST_MODEL) == "gpt-4o"-def test_team_metadata_and_provider_model_promoted():- """The team's metadata dict (JSON) and the provider/underlying model name are- promoted onto every span, alongside the user-facing ``gen_ai.request.model``."""+def test_team_metadata_promoted_only_for_allowlisted_subkeys():+ """Allowlisted team-metadata sub-keys are promoted (JSON) onto every span;+ non-allowlisted sub-keys are excluded, alongside the provider/underlying+ model name and the user-facing ``gen_ai.request.model``."""import jsonengine, exporter = _engine_and_exporter()data = LLMCallSpanData.from_standard_logging_payload(_payload())- bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)+ bag = promoted_baggage(+ data.identity,+ data.request_model,+ BAGGAGE_PROMOTED_KEYS,+ team_metadata_keys=("tier",),+ )ctx = ctx_mod.set_request_baggage(bag)engine.emit(SpanRole.SERVICE, ServiceSpanData("redis", call_type="set"), ctx)(span,) = exporter.get_finished_spans()- # team metadata: the whole dict, JSON-serialized into one value- assert json.loads(span.attributes[LiteLLM.TEAM_METADATA]) == {- "tier": "gold",- "cost_center": "42",- }+ # only the allowlisted sub-key is promoted; ``cost_center`` is excluded+ assert json.loads(span.attributes[LiteLLM.TEAM_METADATA]) == {"tier": "gold"}# provider model is distinct from the user-facing request modelassert span.attributes.get(LiteLLM.PROVIDER_MODEL) == "azure/my-deployment"assert span.attributes.get(GenAI.REQUEST_MODEL) == "gpt-4o"+def test_team_metadata_not_promoted_by_default():+ """The default allowlist is empty, so a team's metadata is never promoted+ even though its dict is present on the request."""+ data = LLMCallSpanData.from_standard_logging_payload(_payload())+ # raw dict is carried on the identity for promotion-time filtering+ assert data.identity.team_metadata == {"tier": "gold", "cost_center": "42"}+ bag = promoted_baggage(data.identity, data.request_model, BAGGAGE_PROMOTED_KEYS)+ assert LiteLLM.TEAM_METADATA not in bag+++def test_team_metadata_dropped_when_no_allowlisted_key_present():+ """An allowlist that matches no present sub-key drops team_metadata rather+ than promoting a useless ``{}``."""+ data = LLMCallSpanData.from_standard_logging_payload(_payload())+ bag = promoted_baggage(+ data.identity,+ data.request_model,+ BAGGAGE_PROMOTED_KEYS,+ team_metadata_keys=("absent_key",),+ )+ assert LiteLLM.TEAM_METADATA not in bag+++def test_team_metadata_not_promoted_when_key_excluded_from_promoted_keys():+ """Even with sub-keys allowlisted, team_metadata stays off the wire when+ ``litellm.team.metadata`` itself isn't in ``promoted_keys``."""+ data = LLMCallSpanData.from_standard_logging_payload(_payload())+ bag = promoted_baggage(+ data.identity,+ data.request_model,+ (LiteLLM.TEAM_ID,),+ team_metadata_keys=("tier",),+ )+ assert LiteLLM.TEAM_METADATA not in bag++def test_empty_team_metadata_is_dropped():"""An absent/empty team_metadata dict must not promote a useless ``"{}"``."""payload = _payload()diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.pyindex c1cde55c58e..7fb0e10a247 100644--- a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py+++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py@@ -96,8 +96,12 @@ def _kwargs(payload=None):}-def _logger(legacy_compat=True):- cfg = OpenTelemetryV2Config(exporter="in_memory", legacy_compat=legacy_compat)+def _logger(legacy_compat=True, team_metadata_keys=None):+ cfg = OpenTelemetryV2Config(+ exporter="in_memory",+ legacy_compat=legacy_compat,+ baggage_team_metadata_keys=team_metadata_keys or [],+ )exporter = InMemorySpanExporter()tracer_provider = providers.build_tracer_provider(cfg, exporter=exporter)return OpenTelemetryV2(config=cfg, tracer_provider=tracer_provider), exporter@@ -541,8 +545,9 @@ class _Auth:def test_provider_model_and_team_metadata_on_real_boundary_flow():"""End-to-end on the proxy boundary path (the gap a pure-emitter test misses):- - ``litellm.team.metadata`` is known at auth, so it rides identity Baggage- seeded there onto EVERY span (server + LLM call).+ - ``litellm.team.metadata`` (filtered to the allowlisted sub-keys) is known+ at auth, so it rides identity Baggage seeded there onto EVERY span+ (server + LLM call).- ``litellm.provider.model`` is only known once routing picks a deployment(in the payload at close), AFTER the auth seed and AFTER the boundary spanstarts — so it can't ride Baggage. It's stamped directly on the LLM-call@@ -550,7 +555,7 @@ def test_provider_model_and_team_metadata_on_real_boundary_flow():"""import json- logger, exporter = _logger()+ logger, exporter = _logger(team_metadata_keys=["tier", "cost_center"])server = logger._emitter.start_span(SpanRole.PROXY_REQUEST, LITELLM_PROXY_REQUEST_SPAN_NAME)diff --git a/tests/test_litellm/integrations/test_opentelemetry.py b/tests/test_litellm/integrations/test_opentelemetry.pyindex 461ab39c288..c4500bd6135 100644--- a/tests/test_litellm/integrations/test_opentelemetry.py+++ b/tests/test_litellm/integrations/test_opentelemetry.py@@ -23,6 +23,7 @@ from litellm.integrations.opentelemetry import (OpenTelemetry,OpenTelemetryConfig,OTELSemconvCategory,+ _normalize_team_metadata_keys,)from litellm.litellm_core_utils.safe_json_dumps import safe_dumps@@ -5187,8 +5188,13 @@ class TestOpenTelemetryInferenceIdentityAttributes(unittest.TestCase):},}+ def _otel_with_team_metadata_keys(self, keys):+ return OpenTelemetry(+ config=OpenTelemetryConfig(baggage_team_metadata_keys=keys)+ )+def test_all_identity_attributes_stamped(self):- otel = OpenTelemetry()+ otel = self._otel_with_team_metadata_keys(["tier", "cost_center"])span, exp = self._span()otel.set_attributes(span, self._kwargs(), {"model": "azure/gpt-4o"})attrs = self._attr(span, exp)@@ -5201,6 +5207,33 @@ class TestOpenTelemetryInferenceIdentityAttributes(unittest.TestCase):assert attrs["litellm.model_group"] == "gpt-4o"assert attrs["litellm.provider.model"] == "azure/my-deployment"+ def test_team_metadata_defaults_to_none_stamped(self):+ """With no allowlist configured (the default), a team's metadata must+ never be stamped, even when present on the request."""+ otel = OpenTelemetry()+ span, exp = self._span()+ otel.set_attributes(span, self._kwargs(), {"model": "azure/gpt-4o"})+ assert "litellm.team.metadata" not in self._attr(span, exp)++ def test_only_allowlisted_team_metadata_keys_stamped(self):+ """Sub-keys outside the allowlist are excluded from the stamped value."""+ otel = self._otel_with_team_metadata_keys(["tier"])+ span, exp = self._span()+ otel.set_attributes(span, self._kwargs(), {"model": "azure/gpt-4o"})+ assert json.loads(self._attr(span, exp)["litellm.team.metadata"]) == {+ "tier": "gold"+ }++ def test_team_metadata_allowlist_from_config_yaml_kwarg(self):+ """callback_settings.otel.baggage_team_metadata_keys arrives as a kwarg+ and must drive the allowlist."""+ otel = OpenTelemetry(baggage_team_metadata_keys=["cost_center"])+ span, exp = self._span()+ otel.set_attributes(span, self._kwargs(), {"model": "azure/gpt-4o"})+ assert json.loads(self._attr(span, exp)["litellm.team.metadata"]) == {+ "cost_center": "42"+ }+def test_provider_model_falls_back_to_payload_model(self):"""Without hidden_params.litellm_model_name the dispatched model isthe payload model (the SDK path, where no router renaming happened)."""@@ -5229,8 +5262,52 @@ class TestOpenTelemetryInferenceIdentityAttributes(unittest.TestCase):otel.set_attributes(span, kwargs, {"model": "azure/gpt-4o"})assert "http.route" not in self._attr(span, exp)- def test_team_metadata_json_helper_non_dict(self):- assert OpenTelemetry._team_metadata_json(None) is None- assert OpenTelemetry._team_metadata_json("not-a-dict") is None- assert OpenTelemetry._team_metadata_json({}) is None- assert json.loads(OpenTelemetry._team_metadata_json({"a": 1})) == {"a": 1}+ def test_team_metadata_json_helper(self):+ keys = ["a", "b"]+ assert OpenTelemetry._team_metadata_json(None, keys) is None+ assert OpenTelemetry._team_metadata_json("not-a-dict", keys) is None+ assert OpenTelemetry._team_metadata_json({}, keys) is None+ # empty allowlist -> nothing stamped, even with data present+ assert OpenTelemetry._team_metadata_json({"a": 1}, []) is None+ # no allowlisted key present -> dropped, not a useless "{}"+ assert OpenTelemetry._team_metadata_json({"c": 1}, keys) is None+ # only allowlisted sub-keys survive+ assert json.loads(+ OpenTelemetry._team_metadata_json({"a": 1, "c": 2}, keys)+ ) == {"a": 1}+++class TestOpenTelemetryTeamMetadataKeysConfig(unittest.TestCase):+ def test_normalize_from_csv_string(self):+ # comma-separated env var: strip whitespace and drop empties+ assert _normalize_team_metadata_keys("tier, cost_center , ,") == [+ "tier",+ "cost_center",+ ]++ def test_normalize_from_list(self):+ assert _normalize_team_metadata_keys(["tier", " cost_center ", ""]) == [+ "tier",+ "cost_center",+ ]++ def test_normalize_none(self):+ assert _normalize_team_metadata_keys(None) == []++ def test_config_reads_csv_env_var(self):+ with patch.dict(+ "os.environ",+ {"LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS": "tier, cost_center"},+ ):+ assert OpenTelemetryConfig().baggage_team_metadata_keys == [+ "tier",+ "cost_center",+ ]++ def test_explicit_keys_win_over_env_var(self):+ with patch.dict(+ "os.environ",+ {"LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS": "from_env"},+ ):+ cfg = OpenTelemetryConfig(baggage_team_metadata_keys=["from_arg"])+ assert cfg.baggage_team_metadata_keys == ["from_arg"]