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): send v4 ingestion header for otel callback (#33907)
yucheng-berribd44c9e305b8
diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.pyindex 449457bd123..d464d55453d 100644--- a/litellm/integrations/langfuse/langfuse_otel.py+++ b/litellm/integrations/langfuse/langfuse_otel.py@@ -1,8 +1,8 @@import base64-import json # <--- NEW+import jsonimport osfrom datetime import datetime-from typing import TYPE_CHECKING, Any, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, Optional, Unionfrom litellm._logging import verbose_loggerfrom litellm.integrations.arize import _utils@@ -25,6 +25,8 @@ else:LANGFUSE_CLOUD_EU_ENDPOINT = "https://cloud.langfuse.com/api/public/otel"LANGFUSE_CLOUD_US_ENDPOINT = "https://us.cloud.langfuse.com/api/public/otel"+LANGFUSE_INGESTION_VERSION_HEADER = "x-langfuse-ingestion-version"+LANGFUSE_INGESTION_VERSION = "4"class LangfuseOtelLogger(OpenTelemetry):@@ -326,7 +328,9 @@ class LangfuseOtelLogger(OpenTelemetry):return OpenTelemetryConfig(exporter="otlp_http",endpoint=endpoint,- headers=f"Authorization={auth_header}",+ headers=LangfuseOtelLogger._format_otel_headers(+ LangfuseOtelLogger._build_langfuse_otel_headers(auth_header)+ ),)@staticmethod@@ -338,6 +342,26 @@ class LangfuseOtelLogger(OpenTelemetry):auth_header = base64.b64encode(auth_string.encode()).decode()return f"Basic {auth_header}"+ @staticmethod+ def _build_langfuse_otel_headers(auth_header: str) -> Dict[str, str]:+ """+ Build the OTLP header set Langfuse expects.++ `x-langfuse-ingestion-version: 4` selects Langfuse's v4 ingestion path;+ without it spans fall back to the older transformation path.+ """+ return {+ "Authorization": auth_header,+ LANGFUSE_INGESTION_VERSION_HEADER: LANGFUSE_INGESTION_VERSION,+ }++ @staticmethod+ def _format_otel_headers(headers: Dict[str, str]) -> str:+ """+ Serialize a header mapping into the comma-separated OTLP header string+ """+ return ",".join(f"{key}={value}" for key, value in headers.items())+def construct_dynamic_otel_headers(self, standard_callback_dynamic_params: StandardCallbackDynamicParams) -> Optional[dict]:@@ -358,7 +382,7 @@ class LangfuseOtelLogger(OpenTelemetry):public_key=dynamic_langfuse_public_key,secret_key=dynamic_langfuse_secret_key,)- dynamic_headers["Authorization"] = auth_header+ dynamic_headers.update(LangfuseOtelLogger._build_langfuse_otel_headers(auth_header))return dynamic_headersdiff --git a/tests/test_litellm/integrations/test_langfuse_otel.py b/tests/test_litellm/integrations/test_langfuse_otel.pyindex 2f2675ca790..28f138c7acd 100644--- a/tests/test_litellm/integrations/test_langfuse_otel.py+++ b/tests/test_litellm/integrations/test_langfuse_otel.py@@ -456,7 +456,7 @@ class TestLangfuseOtelKeyDynamicConfig:import base64expected_auth = base64.b64encode(b"key_public:key_secret").decode()- assert config.headers == f"Authorization=Basic {expected_auth}"+ assert config.headers == f"Authorization=Basic {expected_auth},x-langfuse-ingestion-version=4"def test_construct_dynamic_otel_config_host_without_protocol(self):with self._clean_env():@@ -521,7 +521,10 @@ class TestLangfuseOtelKeyDynamicConfig:import base64expected_auth = base64.b64encode(b"key_public:key_secret").decode()- assert exporter._headers == {"Authorization": f"Basic {expected_auth}"}+ assert exporter._headers == {+ "Authorization": f"Basic {expected_auth}",+ "x-langfuse-ingestion-version": "4",+ }def test_key_dynamic_params_reuse_cached_provider(self):with self._clean_env():@@ -574,7 +577,10 @@ class TestLangfuseOtelKeyDynamicConfig:provider = next(iter(logger._tracer_provider_cache.values()))exporter = provider._active_span_processor._span_processors[0].span_exporterassert isinstance(exporter, OTLPSpanExporter)- assert exporter._headers == {"Authorization": f"Basic {secret}"}+ assert exporter._headers == {+ "Authorization": f"Basic {secret}",+ "x-langfuse-ingestion-version": "4",+ }class TestLangfuseOtelResponsesAPI:diff --git a/tests/test_service_logger_otel.py b/tests/test_service_logger_otel.pyindex 35070d55546..044d37d6781 100644--- a/tests/test_service_logger_otel.py+++ b/tests/test_service_logger_otel.py@@ -12,6 +12,7 @@ from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLoggerfrom litellm.integrations.opentelemetry import OpenTelemetryfrom litellm.types.services import ServiceTypesfrom litellm._service_logger import ServiceLogging+from litellm.types.utils import StandardCallbackDynamicParamsclass TestServiceLoggerOTEL(unittest.IsolatedAsyncioTestCase):@@ -108,6 +109,44 @@ class TestServiceLoggerOTEL(unittest.IsolatedAsyncioTestCase):"Generic OTEL logger should have received the log exactly once.",)+ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_tracing")+ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_metrics")+ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_logs")+ async def test_langfuse_otel_env_config_includes_v4_ingestion_header(+ self, mock_logs, mock_metrics, mock_tracing+ ):+ logger = LangfuseOtelLogger()++ headers = OpenTelemetry._get_headers_dictionary(logger.config.headers)++ self.assertEqual(+ headers["x-langfuse-ingestion-version"],+ "4",+ )+ self.assertTrue(headers["Authorization"].startswith("Basic "))++ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_tracing")+ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_metrics")+ @patch("litellm.integrations.opentelemetry.OpenTelemetry._init_logs")+ async def test_langfuse_otel_dynamic_headers_include_v4_ingestion_header(+ self, mock_logs, mock_metrics, mock_tracing+ ):+ logger = LangfuseOtelLogger()++ headers = logger.construct_dynamic_otel_headers(+ StandardCallbackDynamicParams(+ langfuse_public_key="pk-lf-dynamic",+ langfuse_secret_key="sk-lf-dynamic",+ )+ )++ self.assertIsNotNone(headers)+ self.assertEqual(+ headers["x-langfuse-ingestion-version"],+ "4",+ )+ self.assertTrue(headers["Authorization"].startswith("Basic "))+if __name__ == "__main__":unittest.main()