Spaces:
Configuration error
Configuration error
File size: 3,221 Bytes
abd4a7f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import logging
import os
from app.config import settings
logger = logging.getLogger(__name__)
_langfuse_handler = None
def _configure_langfuse_env():
"""Configure Langfuse environment variables from settings."""
if settings.langfuse_public_key:
os.environ["LANGFUSE_PUBLIC_KEY"] = settings.langfuse_public_key
if settings.langfuse_secret_key:
os.environ["LANGFUSE_SECRET_KEY"] = settings.langfuse_secret_key
if settings.langfuse_host:
os.environ["LANGFUSE_BASE_URL"] = settings.langfuse_host
def get_langfuse_callback_handler(**kwargs):
"""
Get a new Langfuse CallbackHandler for LangChain.
Uses environment-based configuration per official Langfuse docs:
https://langfuse.com/guides/cookbook/integration_langchain
The handler is automatically initialized via environment variables,
so no explicit initialization is needed.
Returns None if Langfuse is not configured or if the integration
is not available.
"""
if not settings.langfuse_public_key:
logger.debug("Langfuse not configured (no public key) — tracing disabled")
return None
try:
# Configure environment variables
_configure_langfuse_env()
# Try modern import path first (langfuse 3.x+)
try:
from langfuse.langchain import CallbackHandler
except ImportError:
# Try alternative path for different versions
try:
from langfuse.callback.langchain import CallbackHandler
except ImportError:
# Try direct import with environment-based init
from langfuse import CallbackHandler # type: ignore
handler = CallbackHandler(**kwargs)
logger.info("Langfuse CallbackHandler initialized successfully via environment")
return handler
except ImportError as e:
logger.debug(
"Langfuse CallbackHandler not available in this environment: %s — "
"tracing will use LangRecorder (local) instead",
e,
)
return None
except Exception as e:
logger.warning(
"Failed to initialize Langfuse CallbackHandler: %s — tracing disabled", e
)
return None
def get_langfuse_client():
if not settings.langfuse_public_key:
return None
try:
from langfuse import Langfuse
_configure_langfuse_env()
return Langfuse()
except Exception as e:
logger.warning("Failed to initialize Langfuse client: %s", e)
return None
def flush_langfuse() -> None:
"""Flush pending Langfuse events (call on shutdown)."""
try:
from langfuse import Langfuse
# Configure environment variables just in case
_configure_langfuse_env()
langfuse = Langfuse()
langfuse.flush()
logger.info("Langfuse events flushed successfully")
except ImportError:
logger.debug("Langfuse not available — skipping flush")
except Exception as e:
logger.warning("Failed to flush Langfuse events: %s", e)
|