"""Langfuse LLM tracing - opt-in via env vars. Safe no-op when LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY are unset or the `langfuse` package is not installed. """ import os LANGFUSE_ENABLED = bool( os.getenv("LANGFUSE_PUBLIC_KEY", "") and os.getenv("LANGFUSE_SECRET_KEY", "") ) LANGFUSE_HOST = os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com") _initialized = False def init_langfuse() -> bool: """Initialize the Langfuse client. Returns True on success.""" global _initialized if not LANGFUSE_ENABLED: return False try: from langfuse import Langfuse # noqa: F401 Langfuse( public_key=os.getenv("LANGFUSE_PUBLIC_KEY"), secret_key=os.getenv("LANGFUSE_SECRET_KEY"), host=LANGFUSE_HOST, ) _initialized = True return True except ImportError: return False except Exception: return False def flush_langfuse() -> None: """Flush any pending Langfuse events. Safe to call on shutdown.""" if not _initialized: return try: from langfuse import Langfuse Langfuse().flush() except ImportError: pass except Exception: pass