-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathlangfuse_utils.py
More file actions
318 lines (251 loc) · 9.34 KB
/
langfuse_utils.py
File metadata and controls
318 lines (251 loc) · 9.34 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""Langfuse tracking utilities"""
from contextlib import contextmanager
from langfuse import Langfuse, get_client
from shared.config.base_config import get_config
from shared.utils.logging_utils import get_logger
log = get_logger(__name__)
config = get_config()
_client = None
_initialized = False
def init_langfuse():
"""Initialize Langfuse with proper configuration"""
global _client, _initialized
if _initialized:
log.debug("Langfuse already initialized")
return _client
if not config.LANGFUSE_ENABLED:
log.info("Langfuse tracking is disabled")
return None
try:
from opentelemetry import trace as _otel_trace
from opentelemetry.sdk.trace import TracerProvider as _OtelTracerProvider
# Give Langfuse its own dedicated TracerProvider so it is isolated from
# the global OTel provider that third-party libraries (fastmcp) share.
langfuse_provider = _OtelTracerProvider()
_client = Langfuse(
secret_key=config.LANGFUSE_SECRET_KEY,
public_key=config.LANGFUSE_PUBLIC_KEY,
host=config.LANGFUSE_HOST,
release=config.LANGFUSE_RELEASE,
environment=config.LANGFUSE_ENVIRONMENT,
tracer_provider=langfuse_provider,
)
# Reset the global OTel provider to a bare no-op (no exporters/processors).
# fastmcp's client_span() calls otel_get_tracer() against this global
# provider and will now get a no-op tracer, eliminating the duplicate
# 'tools/call <name>' child spans and orphan traces from health checks.
_otel_trace.set_tracer_provider(_OtelTracerProvider())
_initialized = True
log.info(
f"Langfuse initialized successfully (host: {config.LANGFUSE_HOST}, release: {config.LANGFUSE_RELEASE}, env: {config.LANGFUSE_ENVIRONMENT})"
)
return _client
except Exception as e:
log.error(f"Failed to initialize Langfuse: {e}")
log.warning("Langfuse tracking will be disabled")
return None
def is_langfuse_enabled() -> bool:
"""Check if Langfuse tracking is enabled and initialized"""
return config.LANGFUSE_ENABLED and _initialized
def get_langfuse_client() -> Langfuse | None:
"""Get or initialize Langfuse client"""
global _client
if not _initialized:
init_langfuse()
return _client
def get_raw_langfuse_prompt(prompt_name: str, **kwargs):
"""Return the raw Langfuse prompt object (not compiled) for linking to generation spans.
Returns None if Langfuse is disabled, unavailable, or the prompt is not found.
Pass the returned object to call_sync/call_async via the langfuse_prompt parameter.
"""
client = get_langfuse_client()
if not client:
return None
try:
return client.get_prompt(prompt_name, type="text", **kwargs)
except Exception as e:
log.debug("Could not fetch raw prompt '%s': %s", prompt_name, e)
return None
def fetch_langfuse_prompt(
prompt_name: str,
variables: dict | None = None,
*,
label: str | None = None,
version: int | None = None,
cache_ttl_seconds: int | None = None,
) -> str:
"""
Fetch a prompt from Langfuse by name.
When variables are provided, they are substituted into the prompt using
Langfuse's {{variable}} syntax.
Args:
prompt_name: Name of the prompt in Langfuse
variables: Optional dictionary of variables to substitute into the prompt
label: Optional label (e.g. "production", "latest"). Defaults to "production" in Langfuse.
version: Optional specific version number to fetch
cache_ttl_seconds: Optional cache TTL override in seconds
Returns:
Compiled prompt content as string
Raises:
RuntimeError: If Langfuse client is not initialized
Exception: If prompt not found in Langfuse
"""
client = get_langfuse_client()
if client is None:
raise RuntimeError("Langfuse client not initialized")
kwargs = {}
if label is not None:
kwargs["label"] = label
if version is not None:
kwargs["version"] = version
if cache_ttl_seconds is not None:
kwargs["cache_ttl_seconds"] = cache_ttl_seconds
prompt = client.get_prompt(prompt_name, type="text", **kwargs)
return prompt.compile(**(variables or {}))
def flush_langfuse():
"""Flush any pending Langfuse events (for short-lived applications)"""
if _client and is_langfuse_enabled():
try:
_client.flush()
log.debug("Langfuse events flushed")
except Exception as e:
log.debug(f"Failed to flush Langfuse: {e}")
def score_validation(
name: str,
passed: bool,
trace_id: str | None,
observation_id: str | None = None,
config_id: str | None = None,
comment: str | None = None,
score_id: str | None = None,
) -> None:
"""Write a boolean validation result as a Langfuse score (1 = pass, 0 = fail).
Pass `score_id` to upsert: re-using the same id on a later call overwrites the previous score.
"""
client = get_langfuse_client()
if not config.LANGFUSE_ENABLED:
return
if not client or not trace_id:
return
try:
kwargs: dict = {
"trace_id": trace_id,
"name": name,
"value": 1.0 if passed else 0.0,
"data_type": "BOOLEAN",
}
if config_id:
kwargs["config_id"] = config_id
if observation_id:
kwargs["observation_id"] = observation_id
if comment:
kwargs["comment"] = comment
if score_id:
kwargs["score_id"] = score_id
client.create_score(**kwargs)
log.debug(
"Langfuse score '%s' = %s written to trace %s", name, passed, trace_id
)
except Exception as e:
log.debug("Failed to create Langfuse score '%s': %s", name, e)
# For backward compatibility with code that expects these functions
# These are no-ops now since Langfuse handles things differently
def start_run_safe(run_name: str = None, **kwargs):
"""
Legacy compatibility function. Langfuse uses traces instead of runs.
Returns a dummy context manager.
"""
class DummyContext:
def __enter__(self):
return self
def __exit__(self, *args):
pass
return DummyContext()
def log_param_safe(key: str, value):
"""
Legacy compatibility function. Langfuse uses metadata instead of params.
This is now a no-op - use metadata on spans/traces instead.
"""
pass
def log_metric_safe(key: str, value: float):
"""
Legacy compatibility function. Langfuse uses scores instead of metrics.
This is now a no-op - use scores on traces instead.
"""
pass
def log_text_safe(text: str, artifact_file: str):
"""
Legacy compatibility function. Langfuse stores outputs directly.
This is now a no-op - use outputs on spans instead.
"""
pass
class _NoopSpan:
"""Dummy span returned when there is no active Langfuse trace context."""
def update(self, **kwargs):
pass
def __enter__(self):
return self
def __exit__(self, *args):
pass
def get_trace_developer(trace_id: str) -> str | None:
"""Return the developer stored on a Langfuse trace's root-span metadata."""
client = get_langfuse_client()
if not client or not trace_id:
return None
try:
trace = client.api.trace.get(trace_id)
except Exception as exc:
log.debug("Langfuse trace lookup failed for %s: %s", trace_id, exc)
return None
observations = getattr(trace, "observations", None) or []
root_observation = next(
(
obs
for obs in observations
if not getattr(obs, "parent_observation_id", None)
),
None,
)
if root_observation is None:
return None
metadata = getattr(root_observation, "metadata", None) or {}
return metadata.get("developer")
def get_current_trace_id() -> str | None:
"""Return the current Langfuse trace id, or None if unavailable or disabled."""
if not is_langfuse_enabled():
return None
try:
return get_client().get_current_trace_id()
except Exception:
log.exception("Failed to get current Langfuse trace ID")
return None
def _has_active_trace() -> bool:
"""Return True when a Langfuse trace context is currently active."""
return get_current_trace_id() is not None
@contextmanager
def trace_span(name: str, **kwargs):
"""
Creates a Langfuse span only when an active parent trace exists.
Falls back to a no-op when called outside a traced workflow,
preventing orphan spans with null input / undefined output.
"""
if not is_langfuse_enabled() or not _has_active_trace():
yield _NoopSpan()
return
with get_client().start_as_current_observation(
as_type="span", name=name, **kwargs
) as span:
yield span
@contextmanager
def trace_generation(name: str, **kwargs):
"""
Creates a Langfuse generation observation only when an active parent trace exists.
Falls back to a no-op otherwise.
"""
if not is_langfuse_enabled() or not _has_active_trace():
yield _NoopSpan()
return
with get_client().start_as_current_observation(
name=name, as_type="generation", **kwargs
) as span:
yield span