fasteval-langfuse 2.1.4__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: fasteval-langfuse
3
- Version: 2.1.4
3
+ Version: 2.2.0
4
4
  Summary: Langfuse integration for fasteval - evaluate production traces with fasteval metrics
5
5
  Author: Intuit
6
6
  License: Apache-2.0
7
- Requires-Dist: fasteval-core>=1.2.0
7
+ Requires-Dist: fasteval-core>=1.3.0
8
8
  Requires-Dist: langfuse>=2.0.0
9
9
  Requires-Dist: pydantic>=2.0.0
10
10
  Requires-Python: >=3.10, <4.0
@@ -43,8 +43,8 @@ def test_production_traces(trace_id, input, output, context, metadata):
43
43
  # Evaluate the trace
44
44
  fe.score(output, input=input)
45
45
 
46
- # Run with pytest - scores automatically pushed to Langfuse
47
- # pytest test_production.py -v
46
+ # Run with pytest: one test case per trace, scores pushed to Langfuse after each
47
+ # pytest test_production.py -v (or: fasteval run test_production.py)
48
48
  ```
49
49
 
50
50
  ### Sampling Strategies
@@ -31,8 +31,8 @@ def test_production_traces(trace_id, input, output, context, metadata):
31
31
  # Evaluate the trace
32
32
  fe.score(output, input=input)
33
33
 
34
- # Run with pytest - scores automatically pushed to Langfuse
35
- # pytest test_production.py -v
34
+ # Run with pytest: one test case per trace, scores pushed to Langfuse after each
35
+ # pytest test_production.py -v (or: fasteval run test_production.py)
36
36
  ```
37
37
 
38
38
  ### Sampling Strategies
@@ -0,0 +1,559 @@
1
+ """Decorators for Langfuse integration.
2
+
3
+ Under pytest, ``@langfuse_traces`` and ``@langfuse_dataset`` expand into one
4
+ test case per trace / dataset item (via fasteval-core's dataset support), so
5
+ each trace passes or fails on its own, shows up individually in reports and
6
+ the fasteval UI, and can be re-run (``--lf``) or parallelized (``-n``).
7
+ Scores are pushed to Langfuse after every case, including failing ones.
8
+
9
+ Called directly (outside pytest), a decorated function evaluates every trace
10
+ in turn, pushes all scores, and raises once at the end if any trace failed.
11
+ """
12
+
13
+ import functools
14
+ import hashlib
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import time
20
+ from datetime import datetime
21
+ from typing import Any, Callable, Dict, Iterator, List, Optional, TypeVar
22
+
23
+ from fasteval.core.datasets import Case, Dataset
24
+ from fasteval_langfuse.client import LangfuseClient
25
+ from fasteval_langfuse.config import get_config
26
+ from fasteval_langfuse.sampling.base import BaseSamplingStrategy
27
+ from fasteval_langfuse.score_reporter import ScoreReporter
28
+ from fasteval_langfuse.trace_fetcher import TraceFetcher
29
+ from fasteval_langfuse.utils import format_sampling_stats
30
+
31
+ F = TypeVar("F", bound=Callable[..., Any])
32
+
33
+ # Marker attributes from fasteval core
34
+ FASTEVAL_METRICS_ATTR = "_fasteval_metrics"
35
+ FASTEVAL_DATA_ATTR = "_fasteval_data"
36
+
37
+ # Hidden per-case parameter carrying what the wrapper needs (trace id, dataset
38
+ # item, run name). Never passed to the user's function.
39
+ CASE_PARAM = "_fe_langfuse"
40
+
41
+ # How long xdist workers wait for the worker that fetches shared traces.
42
+ SHARED_FETCH_TIMEOUT_S = 300.0
43
+
44
+
45
+ def langfuse_traces(
46
+ project: Optional[str] = None,
47
+ filter_tags: Optional[List[str]] = None,
48
+ time_range: Optional[str] = None,
49
+ user_id: Optional[str] = None,
50
+ session_id: Optional[str] = None,
51
+ limit: Optional[int] = None,
52
+ sampling: Optional[BaseSamplingStrategy] = None,
53
+ auto_push_scores: Optional[bool] = None,
54
+ ) -> Callable[[F], F]:
55
+ """
56
+ Fetch and evaluate traces from Langfuse, one test case per trace.
57
+
58
+ Fetches traces (at pytest collection time), applies sampling, and runs the
59
+ test function once per trace with trace data as parameters: trace_id,
60
+ input, output, context, metadata. Declare the ones you need.
61
+
62
+ Args:
63
+ project: Project name to filter traces
64
+ filter_tags: Tags to filter by
65
+ time_range: Time range (e.g., "last_24h", "last_7d")
66
+ user_id: Filter by user ID
67
+ session_id: Filter by session ID
68
+ limit: Max traces to fetch before sampling
69
+ sampling: Sampling strategy (default: evaluate all)
70
+ auto_push_scores: Override config auto_push_scores
71
+
72
+ Example:
73
+ from fasteval_langfuse import langfuse_traces
74
+ from fasteval_langfuse.sampling import RandomSamplingStrategy
75
+ import fasteval as fe
76
+
77
+ @fe.correctness(threshold=0.8)
78
+ @langfuse_traces(
79
+ project="production",
80
+ filter_tags=["customer-support"],
81
+ time_range="last_24h",
82
+ sampling=RandomSamplingStrategy(sample_size=200)
83
+ )
84
+ def test_support_traces(trace_id, input, output, context, metadata):
85
+ fe.score(output, input=input)
86
+
87
+ # pytest test_production.py -v -> test_support_traces[<trace_id>] ...
88
+ """
89
+ query: Dict[str, Any] = {
90
+ "project": project,
91
+ "filter_tags": filter_tags,
92
+ "time_range": time_range,
93
+ "user_id": user_id,
94
+ "session_id": session_id,
95
+ "limit": limit,
96
+ }
97
+
98
+ def decorator(func: F) -> F:
99
+ is_async = inspect.iscoroutinefunction(func)
100
+ state: Dict[str, Any] = {}
101
+
102
+ def client() -> LangfuseClient:
103
+ if "client" not in state:
104
+ state["client"] = LangfuseClient()
105
+ return state["client"]
106
+
107
+ def fetch() -> List[Dict[str, Any]]:
108
+ """Fetched + sampled trace params (identical across xdist workers)."""
109
+
110
+ def do_fetch() -> List[Dict[str, Any]]:
111
+ fetcher = TraceFetcher(client())
112
+ traces, total_count = fetcher.fetch_and_sample(
113
+ sampling=sampling, **query
114
+ )
115
+ if sampling:
116
+ stats = format_sampling_stats(
117
+ len(traces), total_count, sampling.name
118
+ )
119
+ print(f"\n{stats}\n")
120
+ return [fetcher.map_trace_to_params(t) for t in traces]
121
+
122
+ key = {
123
+ "func": f"{func.__module__}.{func.__qualname__}",
124
+ "sampling": sampling.name if sampling else None,
125
+ **query,
126
+ }
127
+ return _shared_across_xdist_workers(key, do_fetch)
128
+
129
+ def cases() -> Iterator[Any]:
130
+ for params in fetch():
131
+ # Case(...) rather than case(**...): trace/item fields may be
132
+ # named "id" or "tags", which case() would treat as options.
133
+ yield Case(
134
+ values={**params, CASE_PARAM: {"trace_id": params["trace_id"]}},
135
+ id=str(params["trace_id"]),
136
+ )
137
+
138
+ def push(trace_id: Any, result: Any) -> None:
139
+ if result is None or auto_push_scores is False:
140
+ return
141
+ reporter = ScoreReporter(client())
142
+ reporter.push_evaluation_result(
143
+ trace_id=trace_id,
144
+ metric_results=result.metric_results,
145
+ aggregate_score=result.aggregate_score,
146
+ )
147
+ reporter.flush()
148
+
149
+ @functools.wraps(func)
150
+ def wrapper(*args: Any, **kwargs: Any) -> None:
151
+ payload = kwargs.pop(CASE_PARAM, None)
152
+ if payload is None:
153
+ # Called directly (not by pytest): evaluate every trace.
154
+ _execute_trace_evaluation(
155
+ func=func,
156
+ is_async=is_async,
157
+ sampling=sampling,
158
+ auto_push_scores=auto_push_scores,
159
+ args=args,
160
+ kwargs=kwargs,
161
+ **query,
162
+ )
163
+ return
164
+ _run_case(
165
+ func,
166
+ is_async,
167
+ args,
168
+ kwargs,
169
+ on_result=lambda r: push(payload["trace_id"], r),
170
+ )
171
+
172
+ _finish(
173
+ wrapper,
174
+ func,
175
+ Dataset(
176
+ cases,
177
+ name=func.__name__,
178
+ info={
179
+ "type": "langfuse_traces",
180
+ "project": project,
181
+ "sampling": sampling.name if sampling else "NoSamplingStrategy",
182
+ },
183
+ ),
184
+ )
185
+ return wrapper # type: ignore
186
+
187
+ return decorator
188
+
189
+
190
+ def _execute_trace_evaluation(
191
+ func: Callable,
192
+ is_async: bool,
193
+ project: Optional[str],
194
+ filter_tags: Optional[List[str]],
195
+ time_range: Optional[str],
196
+ user_id: Optional[str],
197
+ session_id: Optional[str],
198
+ limit: Optional[int],
199
+ sampling: Optional[BaseSamplingStrategy],
200
+ auto_push_scores: Optional[bool],
201
+ args: tuple,
202
+ kwargs: dict,
203
+ ) -> None:
204
+ """Evaluate every trace in one call (direct, non-pytest use).
205
+
206
+ Every trace is evaluated and its scores pushed, even after a failure;
207
+ scores are flushed; then the first failure is raised, listing them all.
208
+ """
209
+ client = LangfuseClient()
210
+ fetcher = TraceFetcher(client)
211
+ reporter = ScoreReporter(client)
212
+
213
+ traces, total_count = fetcher.fetch_and_sample(
214
+ project=project,
215
+ filter_tags=filter_tags,
216
+ time_range=time_range,
217
+ user_id=user_id,
218
+ session_id=session_id,
219
+ limit=limit,
220
+ sampling=sampling,
221
+ )
222
+
223
+ if sampling:
224
+ stats = format_sampling_stats(len(traces), total_count, sampling.name)
225
+ print(f"\n{stats}\n")
226
+
227
+ def push(trace_id: Any, result: Any) -> None:
228
+ if result and auto_push_scores is not False:
229
+ reporter.push_evaluation_result(
230
+ trace_id=trace_id,
231
+ metric_results=result.metric_results,
232
+ aggregate_score=result.aggregate_score,
233
+ )
234
+
235
+ failures: List[tuple] = []
236
+ try:
237
+ for trace in traces:
238
+ params = fetcher.map_trace_to_params(trace)
239
+ try:
240
+ _run_case(
241
+ func,
242
+ is_async,
243
+ args,
244
+ {**kwargs, **params},
245
+ on_result=functools.partial(push, params["trace_id"]),
246
+ )
247
+ except Exception as e: # keep evaluating the remaining traces
248
+ failures.append((params["trace_id"], e))
249
+ finally:
250
+ reporter.flush()
251
+ _raise_failures(failures, len(traces), "traces")
252
+
253
+
254
+ def langfuse_dataset(
255
+ name: str,
256
+ version: Optional[str] = None,
257
+ ) -> Callable[[F], F]:
258
+ """
259
+ Fetch and evaluate dataset items from Langfuse, one test case per item.
260
+
261
+ Similar to @fe.csv(), but fetches data from Langfuse datasets. Dataset
262
+ fields (input, expected_output, item_id, and item metadata keys) are
263
+ passed as parameters - declare what you need in the function signature.
264
+ Every item is linked to one Langfuse experiment run (item.run()), so runs
265
+ can be compared side by side in Langfuse.
266
+
267
+ Args:
268
+ name: Dataset name in Langfuse
269
+ version: Optional dataset version
270
+
271
+ Example:
272
+ from fasteval_langfuse import langfuse_dataset
273
+ import fasteval as fe
274
+
275
+ @fe.correctness(threshold=0.8)
276
+ @langfuse_dataset(name="qa-golden-set", version="v2")
277
+ def test_qa_dataset(input, expected_output):
278
+ response = my_agent(input)
279
+ fe.score(response, expected_output, input=input)
280
+
281
+ # With custom metadata fields (absent ones are passed as None)
282
+ @fe.correctness(threshold=0.8)
283
+ @langfuse_dataset(name="qa-golden-set", version="v2")
284
+ def test_with_metadata(input, expected_output, user_type, complexity):
285
+ response = my_agent(input)
286
+ fe.score(response, expected_output, input=input)
287
+ """
288
+
289
+ def decorator(func: F) -> F:
290
+ is_async = inspect.iscoroutinefunction(func)
291
+ state: Dict[str, Any] = {}
292
+
293
+ def client() -> LangfuseClient:
294
+ if "client" not in state:
295
+ state["client"] = LangfuseClient()
296
+ return state["client"]
297
+
298
+ def cases() -> Iterator[Any]:
299
+ raw_items = client().fetch_dataset_raw(name=name, version=version)
300
+ run_name = _experiment_run_name(func.__name__)
301
+ print(
302
+ f"\nEvaluating {len(raw_items)} items from dataset '{name}' "
303
+ f"(run: {run_name})\n"
304
+ )
305
+ rows = [(item, _dataset_item_params(item)) for item in raw_items]
306
+ # Every case must provide every field some item has (metadata
307
+ # keys vary between items); missing ones are passed as None.
308
+ fields = sorted({k for _, params in rows for k in params})
309
+ for index, (item, params) in enumerate(rows):
310
+ values = {k: params.get(k) for k in fields}
311
+ values[CASE_PARAM] = {"item": item, "run_name": run_name}
312
+ yield Case(
313
+ values=values,
314
+ id=str(item.id if item.id is not None else f"{name}-{index}"),
315
+ )
316
+
317
+ @functools.wraps(func)
318
+ def wrapper(*args: Any, **kwargs: Any) -> None:
319
+ payload = kwargs.pop(CASE_PARAM, None)
320
+ if payload is None:
321
+ _execute_dataset_evaluation(
322
+ func=func,
323
+ is_async=is_async,
324
+ name=name,
325
+ version=version,
326
+ args=args,
327
+ kwargs=kwargs,
328
+ )
329
+ return
330
+ try:
331
+ _run_dataset_item(
332
+ func, is_async, payload["item"], payload["run_name"], args, kwargs
333
+ )
334
+ finally:
335
+ client().flush()
336
+
337
+ _finish(
338
+ wrapper,
339
+ func,
340
+ Dataset(
341
+ cases,
342
+ name=func.__name__,
343
+ info={"type": "langfuse_dataset", "name": name, "version": version},
344
+ ),
345
+ )
346
+ return wrapper # type: ignore
347
+
348
+ return decorator
349
+
350
+
351
+ def _execute_dataset_evaluation(
352
+ func: Callable,
353
+ is_async: bool,
354
+ name: str,
355
+ version: Optional[str],
356
+ args: tuple,
357
+ kwargs: dict,
358
+ ) -> None:
359
+ """Evaluate every dataset item in one call (direct, non-pytest use).
360
+
361
+ Uses item.run() to create linked traces in Langfuse, enabling the
362
+ Experiments comparison UI for side-by-side run analysis. Every item is
363
+ evaluated and scored even after a failure; failures are raised at the end.
364
+ """
365
+ client = LangfuseClient()
366
+ raw_items = client.fetch_dataset_raw(name=name, version=version)
367
+ run_name = _experiment_run_name(func.__name__)
368
+
369
+ print(
370
+ f"\nEvaluating {len(raw_items)} items from dataset '{name}' (run: {run_name})\n"
371
+ )
372
+
373
+ # Same as under pytest: fields only some items have are passed as None.
374
+ fields = {k for item in raw_items for k in _dataset_item_params(item)}
375
+ defaults = {k: None for k in fields}
376
+
377
+ failures: List[tuple] = []
378
+ try:
379
+ for item in raw_items:
380
+ try:
381
+ _run_dataset_item(
382
+ func, is_async, item, run_name, args, kwargs, defaults
383
+ )
384
+ except Exception as e:
385
+ failures.append((item.id, e))
386
+ finally:
387
+ client.flush()
388
+ _raise_failures(failures, len(raw_items), "dataset items")
389
+
390
+
391
+ # ── helpers ──────────────────────────────────────────────────────────────────
392
+
393
+
394
+ def _finish(wrapper: Callable, func: Callable, dataset: Dataset) -> None:
395
+ """Attach dataset/metric markers and the pytest-facing signature."""
396
+ dataset(wrapper) # sets _fasteval_dataset and _fasteval_data
397
+ if hasattr(func, FASTEVAL_METRICS_ATTR):
398
+ setattr(wrapper, FASTEVAL_METRICS_ATTR, getattr(func, FASTEVAL_METRICS_ATTR))
399
+ # pytest sees the test's own parameters plus the hidden case parameter,
400
+ # so dataset fields are parametrized and other params stay fixtures.
401
+ sig = inspect.signature(func)
402
+ hidden = inspect.Parameter(CASE_PARAM, inspect.Parameter.KEYWORD_ONLY)
403
+ params = [
404
+ p
405
+ for p in sig.parameters.values()
406
+ if p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
407
+ ]
408
+ setattr(wrapper, "__signature__", sig.replace(parameters=[*params, hidden]))
409
+
410
+
411
+ def _run_case(
412
+ func: Callable,
413
+ is_async: bool,
414
+ args: tuple,
415
+ kwargs: dict,
416
+ on_result: Callable[[Any], None],
417
+ ) -> None:
418
+ """Call the test function; hand its fe.score() result to on_result even if it failed."""
419
+ from fasteval.core.scoring import clear_last_score_result, get_last_score_result
420
+
421
+ clear_last_score_result()
422
+ if not is_async:
423
+ try:
424
+ func(*args, **_accepted(func, kwargs))
425
+ finally:
426
+ on_result(get_last_score_result())
427
+ return
428
+
429
+ # fe.score() records its result in a context variable. The coroutine runs
430
+ # in its own asyncio task with a *copy* of the context, so read the result
431
+ # inside that task; reading it afterwards here would always see None.
432
+ from fasteval.utils import run_async
433
+
434
+ captured: Dict[str, Any] = {}
435
+
436
+ async def run_and_capture() -> None:
437
+ try:
438
+ await func(*args, **_accepted(func, kwargs))
439
+ finally:
440
+ captured["result"] = get_last_score_result()
441
+
442
+ try:
443
+ run_async(run_and_capture())
444
+ finally:
445
+ on_result(captured.get("result"))
446
+
447
+
448
+ def _run_dataset_item(
449
+ func: Callable,
450
+ is_async: bool,
451
+ item: Any,
452
+ run_name: str,
453
+ args: tuple,
454
+ kwargs: dict,
455
+ defaults: Optional[Dict[str, Any]] = None,
456
+ ) -> None:
457
+ config = get_config()
458
+ params = {**(defaults or {}), **_dataset_item_params(item)}
459
+ with item.run(run_name=run_name) as root_span:
460
+
461
+ def score(result: Any) -> None:
462
+ if not result:
463
+ return
464
+ for mr in result.metric_results:
465
+ root_span.score_trace(
466
+ name=f"{config.score_name_prefix}{mr.metric_name}",
467
+ value=mr.score,
468
+ comment=getattr(mr, "reasoning", None),
469
+ )
470
+ root_span.score_trace(
471
+ name=f"{config.score_name_prefix}aggregate",
472
+ value=result.aggregate_score,
473
+ )
474
+
475
+ _run_case(func, is_async, args, {**params, **kwargs}, on_result=score)
476
+
477
+
478
+ def _dataset_item_params(item: Any) -> Dict[str, Any]:
479
+ params: Dict[str, Any] = {}
480
+ if item.input is not None:
481
+ params["input"] = item.input
482
+ if item.expected_output is not None:
483
+ params["expected_output"] = item.expected_output
484
+ if item.id is not None:
485
+ params["item_id"] = item.id
486
+ metadata = getattr(item, "metadata", None) or {}
487
+ if isinstance(metadata, dict):
488
+ params.update(metadata)
489
+ return params
490
+
491
+
492
+ def _accepted(func: Callable, kwargs: dict) -> dict:
493
+ """Keep only kwargs the function accepts (all of them with **kwargs)."""
494
+ params = inspect.signature(func).parameters
495
+ if any(p.kind is p.VAR_KEYWORD for p in params.values()):
496
+ return kwargs
497
+ return {k: v for k, v in kwargs.items() if k in params}
498
+
499
+
500
+ def _raise_failures(failures: List[tuple], total: int, what: str) -> None:
501
+ if not failures:
502
+ return
503
+ ids = ", ".join(str(i) for i, _ in failures[:10])
504
+ more = f" (+{len(failures) - 10} more)" if len(failures) > 10 else ""
505
+ raise AssertionError(
506
+ f"{len(failures)} of {total} {what} failed: {ids}{more}"
507
+ ) from failures[0][1]
508
+
509
+
510
+ def _experiment_run_name(func_name: str) -> str:
511
+ """One Langfuse experiment run per test session, shared by xdist workers."""
512
+ run = os.environ.get("FASTEVAL_RUN_ID") or os.environ.get("PYTEST_XDIST_TESTRUNUID")
513
+ return f"fasteval-{func_name}-{run or datetime.now().isoformat()}"
514
+
515
+
516
+ def _shared_across_xdist_workers(
517
+ key: Dict[str, Any], produce: Callable[[], List[Dict[str, Any]]]
518
+ ) -> List[Dict[str, Any]]:
519
+ """
520
+ Under pytest-xdist every worker collects separately, and all must collect
521
+ the same cases. With relative time windows or unseeded sampling, separate
522
+ fetches can differ, so the first worker fetches and the rest reuse it.
523
+ Outside xdist this is a plain call.
524
+ """
525
+ run_uid = os.environ.get("PYTEST_XDIST_TESTRUNUID")
526
+ if not run_uid:
527
+ return produce()
528
+ digest = hashlib.sha256(
529
+ json.dumps(key, sort_keys=True, default=str).encode()
530
+ ).hexdigest()[:16]
531
+ base = os.path.join(
532
+ tempfile.gettempdir(), f"fasteval-langfuse-{run_uid[:16]}-{digest}"
533
+ )
534
+ data_path, lock_path = base + ".json", base + ".lock"
535
+ try:
536
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
537
+ except FileExistsError:
538
+ deadline = time.monotonic() + SHARED_FETCH_TIMEOUT_S
539
+ while not os.path.exists(data_path):
540
+ if time.monotonic() > deadline:
541
+ raise TimeoutError(
542
+ "Timed out waiting for another pytest-xdist worker to fetch "
543
+ f"Langfuse traces ({data_path})"
544
+ )
545
+ time.sleep(0.1)
546
+ with open(data_path, encoding="utf-8") as f:
547
+ result: List[Dict[str, Any]] = json.load(f)
548
+ return result
549
+ os.close(fd)
550
+ produced = produce()
551
+ tmp = data_path + f".{os.getpid()}.tmp"
552
+ with open(tmp, "w", encoding="utf-8") as f:
553
+ json.dump(produced, f, default=str)
554
+ os.replace(tmp, data_path)
555
+ # Workers that load the file see JSON-normalized values; reload it here
556
+ # too so this worker's cases are identical to theirs.
557
+ with open(data_path, encoding="utf-8") as f:
558
+ result = json.load(f)
559
+ return result
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "fasteval-langfuse"
3
+ version = "2.2.0"
4
+ description = "Langfuse integration for fasteval - evaluate production traces with fasteval metrics"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<4.0"
7
+ dependencies = [
8
+ "fasteval-core>=1.3.0",
9
+ "langfuse>=2.0.0",
10
+ "pydantic>=2.0.0",
11
+ ]
12
+
13
+ [[project.authors]]
14
+ name = "Intuit"
15
+
16
+ [project.license]
17
+ text = "Apache-2.0"
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "pytest>=8.0.0",
22
+ "pytest-asyncio>=0.21.0",
23
+ "pytest-xdist>=3.0.0",
24
+ "black>=23.0.0",
25
+ "mypy>=1.0.0",
26
+ "isort>=5.0.0",
27
+ ]
28
+
29
+ [tool.uv.build-backend]
30
+ module-name = "fasteval_langfuse"
31
+ module-root = ""
32
+
33
+ [tool.black]
34
+ line-length = 88
35
+ target-version = [
36
+ "py310",
37
+ "py311",
38
+ "py312",
39
+ "py313",
40
+ ]
41
+
42
+ [tool.isort]
43
+ profile = "black"
44
+ known_first_party = [
45
+ "fasteval",
46
+ "fasteval_langfuse",
47
+ ]
48
+
49
+ [tool.pytest.ini_options]
50
+ pythonpath = "."
51
+ testpaths = ["tests"]
52
+ asyncio_mode = "auto"
53
+
54
+ [build-system]
55
+ requires = ["uv_build>=0.9.3,<0.10.0"]
56
+ build-backend = "uv_build"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fasteval-langfuse"
3
- version = "2.1.4"
3
+ version = "2.2.0"
4
4
  description = "Langfuse integration for fasteval - evaluate production traces with fasteval metrics"
5
5
  authors = [{name = "Intuit"}]
6
6
  license = {text = "Apache-2.0"}
@@ -8,7 +8,7 @@ readme = "README.md"
8
8
  requires-python = ">=3.10,<4.0"
9
9
 
10
10
  dependencies = [
11
- "fasteval-core>=1.2.0",
11
+ "fasteval-core>=1.3.0",
12
12
  "langfuse>=2.0.0",
13
13
  "pydantic>=2.0.0",
14
14
  ]
@@ -17,6 +17,7 @@ dependencies = [
17
17
  dev = [
18
18
  "pytest>=8.0.0",
19
19
  "pytest-asyncio>=0.21.0",
20
+ "pytest-xdist>=3.0.0",
20
21
  "black>=23.0.0",
21
22
  "mypy>=1.0.0",
22
23
  "isort>=5.0.0",
@@ -1,340 +0,0 @@
1
- """Decorators for Langfuse integration."""
2
-
3
- import functools
4
- import inspect
5
- from datetime import datetime
6
- from typing import Any, Callable, List, Optional, TypeVar
7
-
8
- from fasteval_langfuse.client import LangfuseClient
9
- from fasteval_langfuse.config import get_config
10
- from fasteval_langfuse.sampling.base import BaseSamplingStrategy
11
- from fasteval_langfuse.score_reporter import ScoreReporter
12
- from fasteval_langfuse.trace_fetcher import TraceFetcher
13
- from fasteval_langfuse.utils import format_sampling_stats
14
-
15
- F = TypeVar("F", bound=Callable[..., Any])
16
-
17
- # Marker attributes from fasteval core
18
- FASTEVAL_METRICS_ATTR = "_fasteval_metrics"
19
- FASTEVAL_DATA_ATTR = "_fasteval_data"
20
-
21
-
22
- def langfuse_traces(
23
- project: Optional[str] = None,
24
- filter_tags: Optional[List[str]] = None,
25
- time_range: Optional[str] = None,
26
- user_id: Optional[str] = None,
27
- session_id: Optional[str] = None,
28
- limit: Optional[int] = None,
29
- sampling: Optional[BaseSamplingStrategy] = None,
30
- auto_push_scores: Optional[bool] = None,
31
- ) -> Callable[[F], F]:
32
- """
33
- Fetch and evaluate traces from Langfuse.
34
-
35
- Fetches traces, applies sampling, and calls the test function once per trace
36
- with trace data as parameters: trace_id, input, output, context, metadata.
37
-
38
- Args:
39
- project: Project name to filter traces
40
- filter_tags: Tags to filter by
41
- time_range: Time range (e.g., "last_24h", "last_7d")
42
- user_id: Filter by user ID
43
- session_id: Filter by session ID
44
- limit: Max traces to fetch before sampling
45
- sampling: Sampling strategy (default: evaluate all)
46
- auto_push_scores: Override config auto_push_scores
47
-
48
- Example:
49
- from fasteval_langfuse import langfuse_traces
50
- from fasteval_langfuse.sampling import RandomSamplingStrategy
51
- import fasteval as fe
52
-
53
- @fe.correctness(threshold=0.8)
54
- @langfuse_traces(
55
- project="production",
56
- filter_tags=["customer-support"],
57
- time_range="last_24h",
58
- sampling=RandomSamplingStrategy(sample_size=200)
59
- )
60
- def test_support_traces(trace_id, input, output, context, metadata):
61
- fe.score(output, input=input)
62
-
63
- # Run with pytest:
64
- # pytest test_production.py -v
65
- """
66
-
67
- def decorator(func: F) -> F:
68
- is_async = inspect.iscoroutinefunction(func)
69
-
70
- @functools.wraps(func)
71
- def sync_wrapper(*args: Any, **kwargs: Any) -> None:
72
- _execute_trace_evaluation(
73
- func=func,
74
- is_async=False,
75
- project=project,
76
- filter_tags=filter_tags,
77
- time_range=time_range,
78
- user_id=user_id,
79
- session_id=session_id,
80
- limit=limit,
81
- sampling=sampling,
82
- auto_push_scores=auto_push_scores,
83
- args=args,
84
- kwargs=kwargs,
85
- )
86
-
87
- @functools.wraps(func)
88
- async def async_wrapper(*args: Any, **kwargs: Any) -> None:
89
- _execute_trace_evaluation(
90
- func=func,
91
- is_async=True,
92
- project=project,
93
- filter_tags=filter_tags,
94
- time_range=time_range,
95
- user_id=user_id,
96
- session_id=session_id,
97
- limit=limit,
98
- sampling=sampling,
99
- auto_push_scores=auto_push_scores,
100
- args=args,
101
- kwargs=kwargs,
102
- )
103
-
104
- wrapper = async_wrapper if is_async else sync_wrapper
105
-
106
- # Preserve fasteval metrics
107
- if hasattr(func, FASTEVAL_METRICS_ATTR):
108
- setattr(
109
- wrapper, FASTEVAL_METRICS_ATTR, getattr(func, FASTEVAL_METRICS_ATTR)
110
- )
111
-
112
- # Mark as data-decorated
113
- setattr(
114
- wrapper,
115
- FASTEVAL_DATA_ATTR,
116
- {
117
- "type": "langfuse_traces",
118
- "project": project,
119
- "sampling": sampling.name if sampling else "NoSamplingStrategy",
120
- },
121
- )
122
-
123
- return wrapper # type: ignore
124
-
125
- return decorator
126
-
127
-
128
- def _execute_trace_evaluation(
129
- func: Callable,
130
- is_async: bool,
131
- project: Optional[str],
132
- filter_tags: Optional[List[str]],
133
- time_range: Optional[str],
134
- user_id: Optional[str],
135
- session_id: Optional[str],
136
- limit: Optional[int],
137
- sampling: Optional[BaseSamplingStrategy],
138
- auto_push_scores: Optional[bool],
139
- args: tuple,
140
- kwargs: dict,
141
- ) -> None:
142
- """Execute trace evaluation (internal implementation)."""
143
- # Initialize components
144
- client = LangfuseClient()
145
- fetcher = TraceFetcher(client)
146
- reporter = ScoreReporter(client)
147
-
148
- # Fetch and sample traces
149
- traces, total_count = fetcher.fetch_and_sample(
150
- project=project,
151
- filter_tags=filter_tags,
152
- time_range=time_range,
153
- user_id=user_id,
154
- session_id=session_id,
155
- limit=limit,
156
- sampling=sampling,
157
- )
158
-
159
- # Print sampling stats
160
- if sampling:
161
- stats = format_sampling_stats(len(traces), total_count, sampling.name)
162
- print(f"\n{stats}\n")
163
-
164
- # Import here to avoid circular dependency
165
- from fasteval.core.scoring import get_last_score_result
166
-
167
- # Evaluate each trace
168
- for trace in traces:
169
- # Map trace to function parameters
170
- params = fetcher.map_trace_to_params(trace)
171
-
172
- # Call the test function
173
- if is_async:
174
- from fasteval.utils import run_async
175
-
176
- run_async(func(*args, **{**kwargs, **params}))
177
- else:
178
- func(*args, **{**kwargs, **params})
179
-
180
- # Get evaluation result
181
- result = get_last_score_result()
182
-
183
- # Push scores back to Langfuse
184
- if result and auto_push_scores is not False:
185
- reporter.push_evaluation_result(
186
- trace_id=params["trace_id"],
187
- metric_results=result.metric_results,
188
- aggregate_score=result.aggregate_score,
189
- )
190
-
191
- # Flush scores
192
- reporter.flush()
193
-
194
-
195
- def langfuse_dataset(
196
- name: str,
197
- version: Optional[str] = None,
198
- ) -> Callable[[F], F]:
199
- """
200
- Fetch and evaluate dataset items from Langfuse.
201
-
202
- Similar to @fe.csv(), but fetches data from Langfuse datasets.
203
- All dataset columns are passed as kwargs - declare what you need in the function signature.
204
-
205
- Args:
206
- name: Dataset name in Langfuse
207
- version: Optional dataset version
208
-
209
- Example:
210
- from fasteval_langfuse import langfuse_dataset
211
- import fasteval as fe
212
-
213
- # Basic usage - standard fields
214
- @fe.correctness(threshold=0.8)
215
- @langfuse_dataset(name="qa-golden-set", version="v2")
216
- def test_qa_dataset(input, expected_output):
217
- response = my_agent(input)
218
- fe.score(response, expected_output, input=input)
219
-
220
- # With custom metadata fields
221
- @fe.correctness(threshold=0.8)
222
- @langfuse_dataset(name="qa-golden-set", version="v2")
223
- def test_with_metadata(input, expected_output, user_type, complexity):
224
- # user_type and complexity come from item.metadata
225
- response = my_agent(input)
226
- fe.score(response, expected_output, input=input)
227
-
228
- # Only what you need
229
- @fe.correctness(threshold=0.8)
230
- @langfuse_dataset(name="qa-golden-set")
231
- def test_minimal(input):
232
- # Only declare input, ignore other fields
233
- response = my_agent(input)
234
- fe.score(response, input=input)
235
- """
236
-
237
- def decorator(func: F) -> F:
238
- is_async = inspect.iscoroutinefunction(func)
239
-
240
- @functools.wraps(func)
241
- def sync_wrapper(*args: Any, **kwargs: Any) -> None:
242
- _execute_dataset_evaluation(
243
- func=func,
244
- is_async=False,
245
- name=name,
246
- version=version,
247
- args=args,
248
- kwargs=kwargs,
249
- )
250
-
251
- @functools.wraps(func)
252
- async def async_wrapper(*args: Any, **kwargs: Any) -> None:
253
- _execute_dataset_evaluation(
254
- func=func,
255
- is_async=True,
256
- name=name,
257
- version=version,
258
- args=args,
259
- kwargs=kwargs,
260
- )
261
-
262
- wrapper = async_wrapper if is_async else sync_wrapper
263
-
264
- # Preserve fasteval metrics
265
- if hasattr(func, FASTEVAL_METRICS_ATTR):
266
- setattr(
267
- wrapper, FASTEVAL_METRICS_ATTR, getattr(func, FASTEVAL_METRICS_ATTR)
268
- )
269
-
270
- # Mark as data-decorated
271
- setattr(
272
- wrapper,
273
- FASTEVAL_DATA_ATTR,
274
- {"type": "langfuse_dataset", "name": name, "version": version},
275
- )
276
-
277
- return wrapper # type: ignore
278
-
279
- return decorator
280
-
281
-
282
- def _execute_dataset_evaluation(
283
- func: Callable,
284
- is_async: bool,
285
- name: str,
286
- version: Optional[str],
287
- args: tuple,
288
- kwargs: dict,
289
- ) -> None:
290
- """Execute dataset evaluation with Langfuse Experiments integration.
291
-
292
- Uses item.run() to create linked traces in Langfuse, enabling the
293
- Experiments comparison UI for side-by-side run analysis.
294
- """
295
- from fasteval.core.scoring import get_last_score_result
296
-
297
- client = LangfuseClient()
298
- config = get_config()
299
- raw_items = client.fetch_dataset_raw(name=name, version=version)
300
- run_name = f"fasteval-{func.__name__}-{datetime.now().isoformat()}"
301
-
302
- print(
303
- f"\nEvaluating {len(raw_items)} items from dataset '{name}' (run: {run_name})\n"
304
- )
305
-
306
- for item in raw_items:
307
- with item.run(run_name=run_name) as root_span:
308
- params: dict[str, Any] = {}
309
-
310
- if item.input is not None:
311
- params["input"] = item.input
312
- if item.expected_output is not None:
313
- params["expected_output"] = item.expected_output
314
- if item.id is not None:
315
- params["item_id"] = item.id
316
-
317
- metadata = getattr(item, "metadata", None) or {}
318
- if metadata:
319
- params.update(metadata)
320
-
321
- if is_async:
322
- from fasteval.utils import run_async
323
-
324
- run_async(func(*args, **{**kwargs, **params}))
325
- else:
326
- func(*args, **{**kwargs, **params})
327
- result = get_last_score_result()
328
- if result:
329
- for mr in result.metric_results:
330
- root_span.score_trace(
331
- name=f"{config.score_name_prefix}{mr.metric_name}",
332
- value=mr.score,
333
- comment=getattr(mr, "reasoning", None),
334
- )
335
- root_span.score_trace(
336
- name=f"{config.score_name_prefix}aggregate",
337
- value=result.aggregate_score,
338
- )
339
-
340
- client.flush()