File size: 2,779 Bytes
481dfe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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():
    """

    Get singleton 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.

    """
    global _langfuse_handler

    if _langfuse_handler is not None:
        return _langfuse_handler

    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

        _langfuse_handler = CallbackHandler()
        logger.info("Langfuse CallbackHandler initialized successfully via environment")
        return _langfuse_handler

    except ImportError as e:
        logger.debug(
            "Langfuse CallbackHandler not available in this environment: %s — "
            "tracing will use LangRecorder (local) instead",
            e,
        )
        _langfuse_handler = None
        return None
    except Exception as e:
        logger.warning(
            "Failed to initialize Langfuse CallbackHandler: %s — tracing disabled", e
        )
        _langfuse_handler = None
        return None


def flush_langfuse() -> None:
    """Flush pending Langfuse events (call on shutdown)."""
    # The CallbackHandler handles flushing automatically
    # This is a no-op but kept for API compatibility
    logger.debug("Langfuse shutdown hook called")