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]

feat(langfuse): Add support for custom masking function (#17826)

Cesar Garciad693596e8721
diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.py
index cd11a116fc6..7d7f5ded614 100644
--- a/litellm/integrations/langfuse/langfuse.py
+++ b/litellm/integrations/langfuse/langfuse.py
@@ -549,6 +549,14 @@ class LangFuseLogger:
debug = clean_metadata.pop("debug_langfuse", None)
mask_input = clean_metadata.pop("mask_input", False)
mask_output = clean_metadata.pop("mask_output", False)
+ # Look for masking function in the dedicated location first (set by scrub_sensitive_keys_in_metadata)
+ # Fall back to metadata for backwards compatibility
+ masking_function = litellm_params.get("_langfuse_masking_function") or clean_metadata.pop("langfuse_masking_function", None)
+
+ # Apply custom masking function if provided
+ if masking_function is not None and callable(masking_function):
+ input = self._apply_masking_function(input, masking_function)
+ output = self._apply_masking_function(output, masking_function)
clean_metadata = redact_user_api_key_info(metadata=clean_metadata)
@@ -885,6 +893,45 @@ class LangFuseLogger:
"""Check if current langfuse version supports completion start time"""
return Version(self.langfuse_sdk_version) >= Version("2.7.3")
+ @staticmethod
+ def _apply_masking_function(data: Any, masking_function: callable) -> Any:
+ """
+ Apply a masking function to data, handling different data types.
+
+ Args:
+ data: The data to mask (can be str, dict, list, or None)
+ masking_function: A callable that takes data and returns masked data
+
+ Returns:
+ The masked data
+ """
+ if data is None:
+ return None
+
+ try:
+ if isinstance(data, str):
+ return masking_function(data)
+ elif isinstance(data, dict):
+ masked_dict = {}
+ for key, value in data.items():
+ masked_dict[key] = LangFuseLogger._apply_masking_function(
+ value, masking_function
+ )
+ return masked_dict
+ elif isinstance(data, list):
+ return [
+ LangFuseLogger._apply_masking_function(item, masking_function)
+ for item in data
+ ]
+ else:
+ # For other types, try to apply the function directly
+ return masking_function(data)
+ except Exception as e:
+ verbose_logger.warning(
+ f"Failed to apply masking function: {e}. Returning original data."
+ )
+ return data
+
@staticmethod
def _get_langfuse_flush_interval(flush_interval: int) -> int:
"""
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index fbfe3786b80..e1277138456 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -5150,6 +5150,15 @@ def scrub_sensitive_keys_in_metadata(litellm_params: Optional[dict]):
metadata = litellm_params.get("metadata", {}) or {}
+ ## Extract provider-specific callable values (like langfuse_masking_function)
+ ## Store them separately so only the intended logger can access them
+ ## This prevents callables from leaking to other logging integrations
+ if "langfuse_masking_function" in metadata:
+ masking_fn = metadata.pop("langfuse_masking_function", None)
+ if callable(masking_fn):
+ litellm_params["_langfuse_masking_function"] = masking_fn
+ litellm_params["metadata"] = metadata
+
## check user_api_key_metadata for sensitive logging keys
cleaned_user_api_key_metadata = {}
if "user_api_key_metadata" in metadata and isinstance(
diff --git a/tests/logging_callback_tests/test_langfuse_unit_tests.py b/tests/logging_callback_tests/test_langfuse_unit_tests.py
index c89b41b8b07..21d18fefade 100644
--- a/tests/logging_callback_tests/test_langfuse_unit_tests.py
+++ b/tests/logging_callback_tests/test_langfuse_unit_tests.py
@@ -387,3 +387,128 @@ def test_get_text_completion_content_for_langfuse():
mock_response = TextCompletionResponse()
result = LangFuseLogger._get_text_completion_content_for_langfuse(mock_response)
assert result is None
+
+
+def test_apply_masking_function_with_string():
+ """
+ Test that _apply_masking_function correctly applies masking to strings
+ """
+ import re
+
+ def mask_credit_cards(data):
+ if isinstance(data, str):
+ return re.sub(r'\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b', '[CARD]', data)
+ return data
+
+ # Test with string containing credit card
+ input_str = "My card is 4532-1234-5678-9012"
+ result = LangFuseLogger._apply_masking_function(input_str, mask_credit_cards)
+ assert result == "My card is [CARD]"
+ assert "4532" not in result
+
+ # Test with string without sensitive data
+ input_str = "Hello world"
+ result = LangFuseLogger._apply_masking_function(input_str, mask_credit_cards)
+ assert result == "Hello world"
+
+
+def test_apply_masking_function_with_dict():
+ """
+ Test that _apply_masking_function correctly applies masking to nested dicts
+ """
+ import re
+
+ def mask_emails(data):
+ if isinstance(data, str):
+ return re.sub(r'[\w\.-]+@[\w\.-]+', '[EMAIL]', data)
+ return data
+
+ # Test with dict containing messages
+ input_dict = {
+ "messages": [
+ {"role": "user", "content": "My email is [email protected]"}
+ ]
+ }
+ result = LangFuseLogger._apply_masking_function(input_dict, mask_emails)
+ assert result["messages"][0]["content"] == "My email is [EMAIL]"
+ assert "[email protected]" not in str(result)
+
+
+def test_apply_masking_function_with_none():
+ """
+ Test that _apply_masking_function handles None correctly
+ """
+ def dummy_mask(data):
+ return data
+
+ result = LangFuseLogger._apply_masking_function(None, dummy_mask)
+ assert result is None
+
+
+def test_apply_masking_function_with_list():
+ """
+ Test that _apply_masking_function correctly applies masking to lists
+ """
+ import re
+
+ def mask_ssn(data):
+ if isinstance(data, str):
+ return re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]', data)
+ return data
+
+ input_list = ["SSN: 123-45-6789", "No sensitive data here"]
+ result = LangFuseLogger._apply_masking_function(input_list, mask_ssn)
+ assert result[0] == "SSN: [SSN]"
+ assert result[1] == "No sensitive data here"
+
+
+def test_masking_function_isolated_from_other_loggers():
+ """
+ Test that langfuse_masking_function is extracted from metadata and stored separately.
+ This ensures the callable doesn't leak to other logging integrations.
+ """
+ from litellm.litellm_core_utils.litellm_logging import scrub_sensitive_keys_in_metadata
+
+ def my_masking_fn(data):
+ return data
+
+ # Simulate litellm_params with masking function in metadata
+ litellm_params = {
+ "metadata": {
+ "langfuse_masking_function": my_masking_fn,
+ "other_key": "other_value",
+ }
+ }
+
+ # Scrub should extract the function
+ result = scrub_sensitive_keys_in_metadata(litellm_params)
+
+ # Function should be removed from metadata (won't leak to other loggers)
+ assert "langfuse_masking_function" not in result["metadata"]
+
+ # Function should be stored in dedicated key for Langfuse to access
+ assert result.get("_langfuse_masking_function") == my_masking_fn
+
+ # Other metadata should remain intact
+ assert result["metadata"]["other_key"] == "other_value"
+
+
+def test_masking_function_not_in_metadata_when_not_provided():
+ """
+ Test that scrub_sensitive_keys_in_metadata works normally when no masking function is provided.
+ """
+ from litellm.litellm_core_utils.litellm_logging import scrub_sensitive_keys_in_metadata
+
+ litellm_params = {
+ "metadata": {
+ "some_key": "some_value",
+ }
+ }
+
+ result = scrub_sensitive_keys_in_metadata(litellm_params)
+
+ # No _langfuse_masking_function should be added
+ assert "_langfuse_masking_function" not in result
+
+ # Original metadata should be unchanged
+ assert result["metadata"]["some_key"] == "some_value"