"""Optional observability with Langfuse: traces, LLM generations, durations and quality scores. If Langfuse is not installed or the keys are missing, every method does nothing: the system works exactly the same without it. Keys (environment variables): LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_HOST for a US project (Europe by default). Traces contain the notes: invented or public cases only. """ from __future__ import annotations import os from typing import Callable class Tracer: def __init__(self, enabled: bool | None = None): self.client = None self._observe = None if enabled is False: return if not (os.environ.get("LANGFUSE_PUBLIC_KEY") and os.environ.get("LANGFUSE_SECRET_KEY")): if enabled: raise RuntimeError("LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY are missing.") return os.environ.setdefault("LANGFUSE_HOST", "https://cloud.langfuse.com") try: from langfuse import get_client, observe except ImportError: if enabled: raise return self.client, self._observe = get_client(), observe @property def enabled(self) -> bool: return self.client is not None def wrap(self, fn: Callable, name: str, as_type: str | None = None) -> Callable: """Turn a function into a Langfuse span (or generation); unchanged if disabled.""" if not self.enabled: return fn return self._observe(name=name, as_type=as_type)(fn) if as_type else self._observe(name=name)(fn) def update_generation(self, **kwargs) -> None: if self.enabled: self.client.update_current_generation(**kwargs) def update_span(self, **kwargs) -> None: if self.enabled: self.client.update_current_span(**kwargs) def score(self, name: str, value: float) -> None: if self.enabled: self.client.score_current_trace(name=name, value=float(value)) def flush(self) -> None: if self.enabled: self.client.flush()