File size: 2,113 Bytes
613af80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()