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
fix(langfuse): warn and drop invalid LANGFUSE_TRACING_ENVIRONMENT instead of failing requests (#38582)
yucheng-berribb72815e7062
diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.pyindex d1a9125ac71..296c2b5714e 100644--- a/litellm/integrations/langfuse/langfuse.py+++ b/litellm/integrations/langfuse/langfuse.py@@ -5,6 +5,7 @@ import osimport tracebackfrom collections.abc import Callable, Iterable, Mappingfrom datetime import datetime+from functools import lru_cachefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Literal, Protocol, cast@@ -137,6 +138,16 @@ def resolve_langfuse_credentials(return public_key, secret_key, resolved_host+@lru_cache(maxsize=8)+def _warn_invalid_deployment_environment(raw_value: str, error: str) -> None:+ verbose_logger.warning(+ "Ignoring invalid LANGFUSE_TRACING_ENVIRONMENT=%r for the langfuse callback: %s. "+ "Traces will be sent to Langfuse's default environment.",+ raw_value,+ error,+ )++class LangFuseLogger:# Class variables or attributesdef __init__(@@ -165,9 +176,11 @@ class LangFuseLogger:# add http:// if unset, assume communicating over private network - e.g. renderself.langfuse_host = "http://" + self.langfuse_host_env_override: Final = str(langfuse_environment).strip() if langfuse_environment is not None else None- self.langfuse_environment = _env_override or os.getenv("LANGFUSE_TRACING_ENVIRONMENT")- if self.langfuse_environment:- validate_langfuse_environment_value(self.langfuse_environment)+ if _env_override:+ validate_langfuse_environment_value(_env_override)+ self.langfuse_environment: str | None = _env_override+ else:+ self.langfuse_environment = self.resolve_deployment_environment()self.langfuse_release = os.getenv("LANGFUSE_RELEASE")self.langfuse_debug = os.getenv("LANGFUSE_DEBUG")self.langfuse_flush_interval = LangFuseLogger._get_langfuse_flush_interval(flush_interval)@@ -953,6 +966,20 @@ class LangFuseLogger:verbose_logger.warning("Failed to apply masking function: %s. Returning original data.", e)return data+ @staticmethod+ def resolve_deployment_environment() -> str | None:+ """Resolve LANGFUSE_TRACING_ENVIRONMENT: stripped value, "default" plus a warning when invalid, None when unset."""+ raw: Final = os.getenv("LANGFUSE_TRACING_ENVIRONMENT")+ if not raw:+ return None+ value: Final = raw.strip()+ try:+ validate_langfuse_environment_value(value)+ except ValueError as e:+ _warn_invalid_deployment_environment(raw, str(e))+ return "default"+ return value+@staticmethoddef _get_langfuse_flush_interval(flush_interval: int) -> int:"""diff --git a/litellm/integrations/langfuse/langfuse_handler.py b/litellm/integrations/langfuse/langfuse_handler.pyindex 8a407f71b3b..c74866c7a9e 100644--- a/litellm/integrations/langfuse/langfuse_handler.py+++ b/litellm/integrations/langfuse/langfuse_handler.py@@ -1,5 +1,3 @@-import os-"""This file contains the LangFuseHandler class@@ -8,6 +6,7 @@ Used to get the LangFuseLogger for a given requestHandles Key/Team Based Langfuse Logging"""+import osfrom typing import TYPE_CHECKING, Any, Finalfrom litellm.litellm_core_utils.litellm_logging import StandardCallbackDynamicParams@@ -157,7 +156,11 @@ class LangFuseHandler:if raw is None:return Nonevalue = str(raw).strip()- if not value or value == os.getenv("LANGFUSE_TRACING_ENVIRONMENT"):+ if (+ not value+ or value == os.getenv("LANGFUSE_TRACING_ENVIRONMENT")+ or value == LangFuseLogger.resolve_deployment_environment()+ ):return Nonereturn valuediff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.pyindex d8d03b73d14..90db0626e23 100644--- a/litellm/integrations/langfuse/langfuse_prompt_management.py+++ b/litellm/integrations/langfuse/langfuse_prompt_management.py@@ -2,6 +2,7 @@Call Hook for LiteLLM Proxy which allows Langfuse prompt management."""+import inspectimport osfrom functools import lru_cachefrom typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, cast@@ -109,6 +110,9 @@ def langfuse_client_init(cert=os.getenv("SSL_CERTIFICATE", litellm.ssl_certificate),)+ if "environment" in inspect.signature(Langfuse.__init__).parameters:+ parameters["environment"] = LangFuseLogger.resolve_deployment_environment()+client: Final = Langfuse(**parameters)return clientdiff --git a/tests/test_litellm/integrations/langfuse/test_langfuse_prompt_management.py b/tests/test_litellm/integrations/langfuse/test_langfuse_prompt_management.pyindex a2d938cad29..7dea4e67cdd 100644--- a/tests/test_litellm/integrations/langfuse/test_langfuse_prompt_management.py+++ b/tests/test_litellm/integrations/langfuse/test_langfuse_prompt_management.py@@ -1,5 +1,9 @@+from types import MappingProxyType+from typing import Finalfrom unittest.mock import MagicMock, patch+import pytest+from litellm.integrations.langfuse.langfuse_prompt_management import (LangfusePromptManagement,langfuse_client_init,@@ -106,3 +110,30 @@ class TestLangfusePromptManagement:mock_get_ssl.assert_called_once()langfuse_client_init.cache_clear()+++class _RecordingLangfuseForEnv:+ last_environment: str | None = None++ def __init__(self, *, environment: str | None = None, **parameters: object) -> None: # kwargs-ok: records only environment out of whatever langfuse_client_init forwards+ type(self).last_environment = environment+++ ("env_value", "expected"),+ (("Production", "default"), ("production ", "production"), ("prod", "prod")),+)+def test_langfuse_client_init_resolves_deployment_environment(monkeypatch, env_value, expected):+ mock_langfuse_module: Final = MagicMock()+ mock_langfuse_module.version.__version__ = "2.60.0"+ mock_langfuse_module.Langfuse = _RecordingLangfuseForEnv+ monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "pk-test")+ monkeypatch.setenv("LANGFUSE_SECRET_KEY", "sk-test")+ monkeypatch.setenv("LANGFUSE_HOST", "https://test.langfuse.com")+ monkeypatch.setenv("LANGFUSE_TRACING_ENVIRONMENT", env_value)+ monkeypatch.setattr(_RecordingLangfuseForEnv, "last_environment", None)+ with patch.dict("sys.modules", MappingProxyType({"langfuse": mock_langfuse_module})):+ langfuse_client_init.cache_clear()+ langfuse_client_init()+ langfuse_client_init.cache_clear()+ assert _RecordingLangfuseForEnv.last_environment == expecteddiff --git a/tests/test_litellm/integrations/test_langfuse.py b/tests/test_litellm/integrations/test_langfuse.pyindex f153ec1193c..d36878e455f 100644--- a/tests/test_litellm/integrations/test_langfuse.py+++ b/tests/test_litellm/integrations/test_langfuse.py@@ -3,7 +3,7 @@ import jsonimport sysimport typesimport unittest-from typing import Optional+from typing import Final, Optionalfrom unittest.mock import MagicMock, patchimport pytest@@ -1521,3 +1521,36 @@ def test_langfuse_empty_environment_falls_back_and_is_not_dynamic(monkeypatch):params = StandardCallbackDynamicParams(langfuse_environment="team-a-prod")assert LangFuseHandler._dynamic_langfuse_credentials_are_passed(params) is True++ # a dynamic value equal to the logger's effective (stripped) environment is redundant+ monkeypatch.setenv("LANGFUSE_TRACING_ENVIRONMENT", "production ")+ stripped_redundant_params: Final = StandardCallbackDynamicParams(langfuse_environment="production")+ assert LangFuseHandler._dynamic_langfuse_credentials_are_passed(stripped_redundant_params) is False++ # a dynamic value repeating the raw (even invalid) deployment value is redundant, not an override+ monkeypatch.setenv("LANGFUSE_TRACING_ENVIRONMENT", "Production")+ raw_redundant_params: Final = StandardCallbackDynamicParams(langfuse_environment="Production")+ assert LangFuseHandler._dynamic_langfuse_credentials_are_passed(raw_redundant_params) is False+++ ("env_value", "expected"),+ (+ ("Production", "default"),+ ("EU-Prod", "default"),+ ("langfuse-prod", "default"),+ (" ", "default"),+ ("production ", "production"),+ ("prod", "prod"),+ ),+)+def test_langfuse_deployment_environment_fallback_never_raises(monkeypatch, env_value, expected):+ monkeypatch.setenv("LANGFUSE_MOCK", "true")+ monkeypatch.setenv("LANGFUSE_TRACING_ENVIRONMENT", env_value)+ monkeypatch.setattr(litellm, "initialized_langfuse_clients", 0)+ logger: Final = LangFuseLogger(+ langfuse_public_key="pk-env",+ langfuse_secret="sk-env",+ langfuse_host="https://test.langfuse.com",+ )+ assert logger.langfuse_environment == expected