fasteval-core 1.3.1__tar.gz → 1.3.2__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.
Files changed (65) hide show
  1. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/PKG-INFO +1 -1
  2. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/decorators.py +1 -1
  3. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/judges.py +54 -0
  4. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/deterministic.py +1 -1
  5. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/providers/anthropic.py +18 -1
  6. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/providers/openai.py +18 -1
  7. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/testing/plugin.py +98 -0
  8. fasteval_core-1.3.2/fasteval/ui/judge_worker.py +194 -0
  9. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/server.py +63 -76
  10. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/static/dist/app.js +15 -15
  11. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/pyproject.toml +1 -1
  12. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/pyproject.toml.orig +1 -1
  13. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/README.md +0 -0
  14. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/__init__.py +0 -0
  15. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/__main__.py +0 -0
  16. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cache/__init__.py +0 -0
  17. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cache/memory.py +0 -0
  18. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cli/__init__.py +0 -0
  19. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cli/config.py +0 -0
  20. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cli/main.py +0 -0
  21. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/cli/ui.py +0 -0
  22. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/__init__.py +0 -0
  23. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/collector.py +0 -0
  24. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/reporters/__init__.py +0 -0
  25. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/reporters/base.py +0 -0
  26. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/reporters/html_reporter.py +0 -0
  27. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/reporters/json_reporter.py +0 -0
  28. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/collectors/summary.py +0 -0
  29. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/__init__.py +0 -0
  30. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/api.py +0 -0
  31. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/datasets.py +0 -0
  32. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/evaluator.py +0 -0
  33. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/core/scoring.py +0 -0
  34. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/__init__.py +0 -0
  35. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/audio.py +0 -0
  36. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/base.py +0 -0
  37. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/code_judge.py +0 -0
  38. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/conversation.py +0 -0
  39. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/llm.py +0 -0
  40. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/multimodal.py +0 -0
  41. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/metrics/vision.py +0 -0
  42. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/models/__init__.py +0 -0
  43. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/models/config.py +0 -0
  44. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/models/evaluation.py +0 -0
  45. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/models/multimodal.py +0 -0
  46. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/providers/__init__.py +0 -0
  47. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/providers/base.py +0 -0
  48. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/providers/registry.py +0 -0
  49. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/py.typed +0 -0
  50. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/testing/__init__.py +0 -0
  51. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/testing/events.py +0 -0
  52. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/__init__.py +0 -0
  53. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/export.py +0 -0
  54. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/runs.py +0 -0
  55. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/static/dist/app.css +0 -0
  56. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/ui/static/dist/index.html +0 -0
  57. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/__init__.py +0 -0
  58. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/async_helpers.py +0 -0
  59. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/audio.py +0 -0
  60. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/formatting.py +0 -0
  61. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/image.py +0 -0
  62. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/json_parsing.py +0 -0
  63. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/judge_trace.py +0 -0
  64. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/terminal_ui.py +0 -0
  65. {fasteval_core-1.3.1 → fasteval_core-1.3.2}/fasteval/utils/text.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: fasteval-core
3
- Version: 1.3.1
3
+ Version: 1.3.2
4
4
  Summary: A decorator-first LLM evaluation library for testing AI agents
5
5
  Keywords: llm,evaluation,testing,ai,agents,pytest
6
6
  Author: Intuit
@@ -754,7 +754,7 @@ def regex(
754
754
  name: Optional[str] = None,
755
755
  **config: Any,
756
756
  ) -> Callable[[F], F]:
757
- """
757
+ r"""
758
758
  Attach regex pattern matching metric.
759
759
 
760
760
  Validates that the output matches a regular expression pattern.
@@ -391,3 +391,57 @@ def set_overrides(overrides: Dict[str, JudgeSpec]) -> None:
391
391
 
392
392
  def get_override(metric_name: str) -> Optional[JudgeSpec]:
393
393
  return _overrides.get(metric_name)
394
+
395
+
396
+ async def run_judge_cases(
397
+ *,
398
+ template: str,
399
+ client: Any,
400
+ cases: List[Dict[str, Any]],
401
+ scoring: str,
402
+ threshold: float,
403
+ concurrency: int,
404
+ ) -> List[Dict[str, Any]]:
405
+ """Score playground cases with a template. Used by the UI server and by
406
+ ``pytest --fe-judge-test`` (the judge playground's subprocess)."""
407
+ import asyncio
408
+ import time
409
+
410
+ from fasteval.models.evaluation import EvalInput
411
+ from fasteval.utils import judge_trace
412
+
413
+ spec = JudgeSpec(
414
+ name="playground",
415
+ prompt=template,
416
+ scoring="binary" if scoring == "binary" else "continuous",
417
+ threshold=max(0.0, min(1.0, threshold)),
418
+ )
419
+ metric = PromptJudgeMetric(spec, name="playground", llm_client=client)
420
+ metric.max_retries = 1
421
+ semaphore = asyncio.Semaphore(max(1, min(concurrency, 8)))
422
+
423
+ async def one(case: Dict[str, Any]) -> Dict[str, Any]:
424
+ key = case.get("key")
425
+ try:
426
+ eval_input = EvalInput.model_validate(case.get("eval_input") or {})
427
+ except Exception as e:
428
+ return {"key": key, "error": f"Invalid eval_input: {e}"}
429
+ async with semaphore:
430
+ start = time.perf_counter()
431
+ with judge_trace.capture() as calls:
432
+ result = await metric.evaluate(eval_input)
433
+ call = calls[-1] if calls else {}
434
+ return {
435
+ "key": key,
436
+ "prompt": render_template(template, eval_input),
437
+ "response": call.get("response"),
438
+ "error": call.get("error") or result.details.get("error"),
439
+ "score": result.score,
440
+ "passed": result.passed,
441
+ "reasoning": result.reasoning,
442
+ "latency_ms": call.get(
443
+ "latency_ms", round((time.perf_counter() - start) * 1000, 1)
444
+ ),
445
+ }
446
+
447
+ return list(await asyncio.gather(*(one(c) for c in cases)))
@@ -308,7 +308,7 @@ class JsonMetric(Metric):
308
308
 
309
309
 
310
310
  class RegexMetric(Metric):
311
- """
311
+ r"""
312
312
  Regex pattern matching for structured outputs.
313
313
 
314
314
  Returns 1.0 if the pattern matches the actual output, 0.0 otherwise.
@@ -1,5 +1,6 @@
1
1
  """Anthropic LLM client implementation."""
2
2
 
3
+ import asyncio
3
4
  from typing import Any, Dict, List, Optional
4
5
 
5
6
 
@@ -40,10 +41,18 @@ class AnthropicClient:
40
41
  self.max_tokens = max_tokens
41
42
  self._kwargs = kwargs
42
43
  self._client: Optional[Any] = None
44
+ self._client_loop: Optional[Any] = None
43
45
 
44
46
  def _get_client(self) -> Any:
45
47
  """Lazy initialization of Anthropic client."""
46
- if self._client is None:
48
+ # The SDK's connection pool is bound to the event loop it first ran
49
+ # on, and each eval may run on a new loop (asyncio.run per test), so
50
+ # keep one SDK client per loop instead of failing with
51
+ # "Event loop is closed" on the next test.
52
+ loop = _running_loop()
53
+ if self._client is not None and self._client_loop is None:
54
+ self._client_loop = loop # first use of a client set from outside
55
+ if self._client is None or self._client_loop is not loop:
47
56
  try:
48
57
  from anthropic import AsyncAnthropic
49
58
  except ImportError:
@@ -52,6 +61,7 @@ class AnthropicClient:
52
61
  "Install it with: pip install anthropic"
53
62
  )
54
63
  self._client = AsyncAnthropic(api_key=self.api_key, **self._kwargs)
64
+ self._client_loop = loop
55
65
  return self._client
56
66
 
57
67
  async def invoke(self, messages: List[Dict[str, Any]]) -> str:
@@ -90,3 +100,10 @@ class AnthropicClient:
90
100
 
91
101
  def __repr__(self) -> str:
92
102
  return f"AnthropicClient(model={self.model!r})"
103
+
104
+
105
+ def _running_loop() -> Optional[asyncio.AbstractEventLoop]:
106
+ try:
107
+ return asyncio.get_running_loop()
108
+ except RuntimeError:
109
+ return None
@@ -1,5 +1,6 @@
1
1
  """OpenAI LLM client implementation."""
2
2
 
3
+ import asyncio
3
4
  from typing import Any, Dict, List, Optional
4
5
 
5
6
 
@@ -37,10 +38,18 @@ class OpenAIClient:
37
38
  self.temperature = temperature
38
39
  self._kwargs = kwargs
39
40
  self._client: Optional[Any] = None
41
+ self._client_loop: Optional[Any] = None
40
42
 
41
43
  def _get_client(self) -> Any:
42
44
  """Lazy initialization of OpenAI client."""
43
- if self._client is None:
45
+ # The SDK's connection pool is bound to the event loop it first ran
46
+ # on, and each eval may run on a new loop (asyncio.run per test), so
47
+ # keep one SDK client per loop instead of failing with
48
+ # "Event loop is closed" on the next test.
49
+ loop = _running_loop()
50
+ if self._client is not None and self._client_loop is None:
51
+ self._client_loop = loop # first use of a client set from outside
52
+ if self._client is None or self._client_loop is not loop:
44
53
  try:
45
54
  from openai import AsyncOpenAI
46
55
  except ImportError:
@@ -49,6 +58,7 @@ class OpenAIClient:
49
58
  "Install it with: pip install openai"
50
59
  )
51
60
  self._client = AsyncOpenAI(api_key=self.api_key, **self._kwargs)
61
+ self._client_loop = loop
52
62
  return self._client
53
63
 
54
64
  async def invoke(self, messages: List[Dict[str, Any]]) -> str:
@@ -71,3 +81,10 @@ class OpenAIClient:
71
81
 
72
82
  def __repr__(self) -> str:
73
83
  return f"OpenAIClient(model={self.model!r})"
84
+
85
+
86
+ def _running_loop() -> Optional[asyncio.AbstractEventLoop]:
87
+ try:
88
+ return asyncio.get_running_loop()
89
+ except RuntimeError:
90
+ return None
@@ -112,6 +112,16 @@ def pytest_addoption(parser: Any) -> None:
112
112
  metavar="METRIC=JUDGE",
113
113
  help="Swap metric METRIC for saved prompt judge JUDGE (judges/JUDGE.toml)",
114
114
  )
115
+ parser.addoption(
116
+ "--fe-judge-test",
117
+ default=None,
118
+ metavar="FILE",
119
+ help=(
120
+ "Internal (fasteval ui judge playground): import the test files, "
121
+ "then score the request in FILE ('-': requests on stdin) with the "
122
+ "default judge"
123
+ ),
124
+ )
115
125
  parser.addoption(
116
126
  "--fe-events",
117
127
  default=None,
@@ -241,6 +251,8 @@ def pytest_pycollect_makeitem(collector: Any, name: str, obj: Any) -> Any:
241
251
  evaluated against the metrics stacked on the generator. The function
242
252
  doesn't need a ``test_`` name; it must live in a collected test module.
243
253
  """
254
+ if _judge_test_file(collector.config):
255
+ return [] # judge playground: import the module only, build no tests
244
256
  if not (callable(obj) and getattr(obj, "_fasteval_traces", False)):
245
257
  return None
246
258
  if not isinstance(collector, pytest.Module):
@@ -378,6 +390,9 @@ def pytest_collection_modifyitems(config: Any, items: List[Any]) -> None:
378
390
  def pytest_collection_finish(session: Any) -> None:
379
391
  """Write the eval inventory and/or the ``collected`` event if requested."""
380
392
  config = session.config
393
+ if _judge_test_file(config):
394
+ _serve_judge_tests(session)
395
+ return
381
396
  path = config.getoption("--fe-inventory", default=None)
382
397
  events = _events(config)
383
398
  worker = _is_xdist_worker(config)
@@ -691,3 +706,86 @@ def _print_console_summary(summary: Any) -> None:
691
706
  print(f" x {t.test_name} (score: {t.aggregate_score:.3f}){err}")
692
707
 
693
708
  print(sep + "\n")
709
+
710
+
711
+ # ── judge playground (fasteval ui) ───────────────────────────────────────────
712
+ #
713
+ # The playground's "Test" runs in a pytest process that imported the tests
714
+ # (see fasteval.ui.judge_worker), so the judge is whatever they configure:
715
+ # fe.set_default_provider(...) in a test module or conftest.py, else
716
+ # [tool.fasteval] judge_client: the judge a real run uses. Modules are imported
717
+ # but no test items are built, so datasets aren't loaded and nothing runs.
718
+
719
+ JUDGE_TEST_DONE = "@@fasteval-judge-test-done@@"
720
+
721
+ _JUDGE_TEST_ERRORS: "pytest.StashKey[List[str]]" = pytest.StashKey()
722
+
723
+
724
+ def _judge_test_file(config: Any) -> Optional[str]:
725
+ value = config.getoption("--fe-judge-test", default=None)
726
+ return value if isinstance(value, str) and value else None
727
+
728
+
729
+ def pytest_collectreport(report: Any) -> None:
730
+ config = _current_config
731
+ if config is None or not _judge_test_file(config) or not report.failed:
732
+ return
733
+ config.stash.setdefault(_JUDGE_TEST_ERRORS, []).append(
734
+ f"{report.nodeid or 'collection'}: {report.longreprtext}"
735
+ )
736
+
737
+
738
+ def _serve_judge_tests(session: Any) -> None:
739
+ """
740
+ ``--fe-judge-test=FILE`` answers the request in FILE; ``-`` keeps serving:
741
+ each stdin line is a request file, acknowledged with a ``JUDGE_TEST_DONE``
742
+ line on stdout (run with ``-s``). Serving keeps the imported tests warm,
743
+ so slow setup (auth, SDK clients) is paid once.
744
+ """
745
+ import asyncio
746
+
747
+ path = _judge_test_file(session.config)
748
+ errors = session.config.stash.get(_JUDGE_TEST_ERRORS, [])
749
+ # One loop for every request: SDK clients (e.g. AsyncOpenAI) keep
750
+ # connections bound to the loop they were first used on.
751
+ loop = asyncio.new_event_loop()
752
+ try:
753
+ if path != "-":
754
+ _answer_judge_test(str(path), errors, loop)
755
+ return
756
+ for line in sys.stdin:
757
+ request_path = line.strip()
758
+ if request_path:
759
+ _answer_judge_test(request_path, errors, loop)
760
+ print(f"{JUDGE_TEST_DONE} {request_path}", flush=True)
761
+ finally:
762
+ loop.close()
763
+
764
+
765
+ def _answer_judge_test(path: str, errors: List[str], loop: Any) -> None:
766
+ from fasteval import judges
767
+ from fasteval.providers.registry import get_default_provider
768
+ from fasteval.utils.judge_trace import describe_judge
769
+
770
+ request = json.loads(Path(path).read_text())
771
+ output: Dict[str, Any]
772
+ if errors:
773
+ # A failed import may have skipped fe.set_default_provider(...).
774
+ output = {"error": "Couldn't import the test files:\n" + "\n".join(errors)}
775
+ else:
776
+ try:
777
+ client = get_default_provider()
778
+ results = loop.run_until_complete(
779
+ judges.run_judge_cases(
780
+ template=request["template"],
781
+ client=client,
782
+ cases=request["cases"],
783
+ scoring=request.get("scoring") or "continuous",
784
+ threshold=float(request.get("threshold", 0.5)),
785
+ concurrency=int(request.get("concurrency", 4)),
786
+ )
787
+ )
788
+ output = {"judge": describe_judge(client), "results": results}
789
+ except Exception as e: # report it in the playground, don't crash pytest
790
+ output = {"error": f"{type(e).__name__}: {e}"}
791
+ Path(request["output"]).write_text(json.dumps(output, default=str))
@@ -0,0 +1,194 @@
1
+ """
2
+ The judge playground's worker: a warm ``pytest --fe-judge-test=-`` process.
3
+
4
+ The playground must judge with the same LLM client a real run uses, and that
5
+ client usually only exists once the tests are imported
6
+ (``fe.set_default_provider(...)`` in a test module or conftest.py). So
7
+ playground tests run in a pytest process that imported them. It's kept alive
8
+ because importing can be slow (auth, SDK clients), and restarted when the test
9
+ files change, a different set of files is needed, it dies, or it gets old
10
+ (credentials fetched at import time can expire).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import queue
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ import threading
22
+ import time
23
+ from pathlib import Path
24
+ from typing import IO, Any, Dict, List, Optional, Tuple
25
+
26
+ from fasteval.testing.plugin import JUDGE_TEST_DONE
27
+
28
+ # A judge call takes seconds; a test holds at most 100 cases.
29
+ REQUEST_TIMEOUT_S = 300
30
+ # Restart after this long so credentials fetched at import time stay fresh.
31
+ MAX_AGE_S = 30 * 60
32
+ OUTPUT_TAIL = 2000
33
+
34
+
35
+ class JudgeWorkerError(Exception):
36
+ """The worker couldn't answer; the message is shown in the playground."""
37
+
38
+
39
+ class JudgeWorker:
40
+ def __init__(self, root: Path, env: Dict[str, str]):
41
+ self.root = root
42
+ self.env = env
43
+ self.lock = threading.Lock()
44
+ self.proc: Optional["subprocess.Popen[str]"] = None
45
+ self.lines: "queue.Queue[Optional[str]]" = queue.Queue()
46
+ self.output: List[str] = [] # recent console lines, for errors
47
+ self.key: Optional[Tuple[Any, ...]] = None
48
+ self.started = 0.0
49
+ self.tmp = tempfile.TemporaryDirectory(prefix="fasteval-judge-")
50
+ self.counter = 0
51
+
52
+ def run(
53
+ self, paths: List[str], request: Dict[str, Any], default_paths: List[str]
54
+ ) -> Dict[str, Any]:
55
+ """
56
+ Score a playground request with the judge the tests in ``paths`` set
57
+ up. Without ``paths`` (hand-written cases) any warm worker will do,
58
+ else ``default_paths`` (the default profile's) are imported.
59
+ """
60
+ with self.lock:
61
+ if not paths:
62
+ paths = (
63
+ list(self.key[0]) if self.key and self._alive() else default_paths
64
+ )
65
+ key = self._key(paths)
66
+ if (
67
+ not self._alive()
68
+ or key != self.key
69
+ or time.monotonic() - self.started > MAX_AGE_S
70
+ ):
71
+ self._start(paths, key)
72
+ assert self.proc is not None and self.proc.stdin is not None
73
+ self.counter += 1
74
+ folder = Path(self.tmp.name)
75
+ req_path = folder / f"request-{self.counter}.json"
76
+ out_path = folder / f"output-{self.counter}.json"
77
+ req_path.write_text(json.dumps({**request, "output": str(out_path)}))
78
+ try:
79
+ self.proc.stdin.write(f"{req_path}\n")
80
+ self.proc.stdin.flush()
81
+ except OSError:
82
+ pass # it died; reported below
83
+ self._wait_for(f"{JUDGE_TEST_DONE} {req_path}", paths)
84
+ output: Dict[str, Any] = json.loads(out_path.read_text())
85
+ req_path.unlink(missing_ok=True)
86
+ out_path.unlink(missing_ok=True)
87
+ if "error" in output:
88
+ if str(output["error"]).startswith("Couldn't import"):
89
+ self.stop() # retry the import next time (the user may fix it)
90
+ raise JudgeWorkerError(str(output["error"])[-OUTPUT_TAIL:])
91
+ return output
92
+
93
+ def stop(self) -> None:
94
+ proc, self.proc = self.proc, None
95
+ if proc is not None and proc.poll() is None:
96
+ try:
97
+ if proc.stdin is not None:
98
+ proc.stdin.close() # ends its request loop
99
+ proc.wait(timeout=5)
100
+ except (OSError, subprocess.TimeoutExpired):
101
+ proc.kill()
102
+
103
+ def close(self) -> None:
104
+ self.stop()
105
+ self.tmp.cleanup()
106
+
107
+ # ── internals ──
108
+
109
+ def _alive(self) -> bool:
110
+ return self.proc is not None and self.proc.poll() is None
111
+
112
+ def _key(self, paths: List[str]) -> Tuple[Any, ...]:
113
+ """Changes when the files (or any Python file under a folder) change."""
114
+ files: List[Path] = []
115
+ root = self.root.resolve()
116
+ for p in paths:
117
+ path = (self.root / p).resolve()
118
+ if path.is_dir():
119
+ files += [f for f in sorted(path.rglob("*.py")) if not _hidden(f, path)]
120
+ else:
121
+ files.append(path)
122
+ folder = path if path.is_dir() else path.parent
123
+ while folder == root or root in folder.parents: # pytest's conftests
124
+ files.append(folder / "conftest.py")
125
+ if folder == root:
126
+ break
127
+ folder = folder.parent
128
+ files += [root / "pyproject.toml", root / "pytest.ini", root / "setup.cfg"]
129
+ return (tuple(paths), tuple((str(f), _mtime(f)) for f in files))
130
+
131
+ def _start(self, paths: List[str], key: Tuple[Any, ...]) -> None:
132
+ self.stop()
133
+ argv = [
134
+ sys.executable, "-m", "pytest", *paths,
135
+ "--collect-only", "-q", "-s", "-p", "no:cacheprovider",
136
+ "--fe-judge-test=-",
137
+ ] # fmt: skip
138
+ self.proc = subprocess.Popen(
139
+ argv,
140
+ cwd=self.root,
141
+ env=self.env,
142
+ stdin=subprocess.PIPE,
143
+ stdout=subprocess.PIPE,
144
+ stderr=subprocess.STDOUT,
145
+ text=True,
146
+ bufsize=1,
147
+ )
148
+ self.key, self.started = key, time.monotonic()
149
+ self.lines = queue.Queue()
150
+ self.output = []
151
+ threading.Thread(
152
+ target=_pump, args=(self.proc.stdout, self.lines), daemon=True
153
+ ).start()
154
+
155
+ def _wait_for(self, marker: str, paths: List[str]) -> None:
156
+ deadline = time.monotonic() + REQUEST_TIMEOUT_S
157
+ while True:
158
+ remaining = deadline - time.monotonic()
159
+ if remaining <= 0:
160
+ self.stop()
161
+ raise JudgeWorkerError(f"Judge test took over {REQUEST_TIMEOUT_S}s")
162
+ try:
163
+ line = self.lines.get(timeout=remaining)
164
+ except queue.Empty:
165
+ continue
166
+ if line is None: # the process exited
167
+ self.stop()
168
+ tail = "".join(self.output)[-OUTPUT_TAIL:].strip()
169
+ raise JudgeWorkerError(
170
+ "Couldn't load the tests to find the judge "
171
+ f"(pytest {' '.join(paths)}):\n{tail}"
172
+ )
173
+ if line.rstrip("\n") == marker:
174
+ return
175
+ self.output = [*self.output[-200:], line]
176
+
177
+
178
+ def _pump(stream: Optional[IO[str]], lines: "queue.Queue[Optional[str]]") -> None:
179
+ if stream is not None:
180
+ for line in stream:
181
+ lines.put(line)
182
+ lines.put(None)
183
+
184
+
185
+ def _hidden(path: Path, under: Path) -> bool:
186
+ parts = path.relative_to(under).parts[:-1]
187
+ return any(p.startswith(".") or p in ("node_modules", "__pycache__") for p in parts)
188
+
189
+
190
+ def _mtime(path: Path) -> float:
191
+ try:
192
+ return os.stat(path).st_mtime
193
+ except OSError:
194
+ return 0.0
@@ -46,6 +46,7 @@ class UIApp:
46
46
  self.procs: Dict[str, "subprocess.Popen[bytes]"] = {}
47
47
  self.lock = threading.Lock()
48
48
  self.httpd: Optional[ThreadingHTTPServer] = None
49
+ self.judge_worker: Any = None # fasteval.ui.judge_worker.JudgeWorker
49
50
 
50
51
  # ── lifecycle ──
51
52
 
@@ -106,6 +107,8 @@ class UIApp:
106
107
  threading.Thread(target=wait_then_open, daemon=True).start()
107
108
 
108
109
  def shutdown(self) -> None:
110
+ if self.judge_worker is not None:
111
+ self.judge_worker.close()
109
112
  if self.httpd is not None:
110
113
  self.httpd.shutdown()
111
114
  self.httpd.server_close()
@@ -154,26 +157,50 @@ class UIApp:
154
157
 
155
158
  # ── judges ──
156
159
 
157
- def judge_client(self, model: Optional[str], temperature: Optional[float]) -> Any:
158
- """Client for playground calls: explicit model > judge_client > default."""
160
+ def judge_client(self, model: str, temperature: Optional[float]) -> Any:
161
+ """Client for a playground call that names a model explicitly."""
159
162
  from fasteval.judges import JudgeSpec, client_for_spec
160
163
 
161
- if model:
162
- return client_for_spec(
163
- JudgeSpec(
164
- name="playground", prompt="x", model=model, temperature=temperature
165
- )
164
+ return client_for_spec(
165
+ JudgeSpec(
166
+ name="playground", prompt="x", model=model, temperature=temperature
166
167
  )
167
- if self.config.judge_client:
168
- from fasteval.judges import JudgeError, load_judge_client
168
+ )
169
169
 
170
- try:
171
- return load_judge_client(self.config.judge_client, self.config.root)
172
- except JudgeError as e:
173
- raise HTTPError(HTTPStatus.BAD_REQUEST, str(e))
174
- from fasteval.providers.registry import get_default_provider
170
+ def judge_test_files(self, nodeids: List[str]) -> List[str]:
171
+ """Test files the playground cases came from (relative to the root)."""
172
+ files: List[str] = []
173
+ root = self.config.root.resolve()
174
+ for nodeid in nodeids:
175
+ rel = nodeid.split("::", 1)[0]
176
+ path = (root / rel).resolve()
177
+ if rel and rel not in files and path.is_file() and root in path.parents:
178
+ files.append(rel)
179
+ return files
180
+
181
+ def judge_test_in_tests(
182
+ self, request: Dict[str, Any], files: List[str]
183
+ ) -> Dict[str, Any]:
184
+ """
185
+ Run a playground test where the tests are imported (a warm pytest
186
+ worker), so the judge is the one a real run uses:
187
+ ``fe.set_default_provider(...)`` or ``[tool.fasteval] judge_client``.
188
+ """
189
+ import os
175
190
 
176
- return get_default_provider()
191
+ from fasteval.ui.judge_worker import JudgeWorker, JudgeWorkerError
192
+
193
+ profile = self.config.resolve(None)
194
+ with self.lock:
195
+ if self.judge_worker is None:
196
+ env = {**os.environ, **profile.env, "FASTEVAL_PROFILE": profile.name}
197
+ self.judge_worker = JudgeWorker(self.config.root, env)
198
+ worker = self.judge_worker
199
+ try:
200
+ defaults = [_display(self.config, p) for p in profile.paths]
201
+ return worker.run(files, request, defaults)
202
+ except JudgeWorkerError as e:
203
+ raise HTTPError(HTTPStatus.BAD_GATEWAY, str(e))
177
204
 
178
205
 
179
206
  # ── request handling ─────────────────────────────────────────────────────────
@@ -513,20 +540,30 @@ class _Handler(BaseHTTPRequestHandler):
513
540
  raise HTTPError(HTTPStatus.BAD_REQUEST, "Add at least one case")
514
541
  if len(cases) > 100:
515
542
  raise HTTPError(HTTPStatus.BAD_REQUEST, "At most 100 cases per test")
516
- temperature = _number(body, "temperature", 0.0, 0.0, 2.0)
517
- client = self.app.judge_client(body.get("model") or None, temperature)
518
- results = asyncio.run(
519
- _run_judge_cases(
520
- template=template,
521
- client=client,
522
- cases=cases,
523
- scoring=body.get("scoring") or "continuous",
524
- threshold=_number(body, "threshold", 0.5, 0.0, 1.0),
525
- concurrency=int(_number(body, "concurrency", 4, 1, 8)),
543
+ request: Dict[str, Any] = {
544
+ "template": template,
545
+ "cases": cases,
546
+ "scoring": body.get("scoring") or "continuous",
547
+ "threshold": _number(body, "threshold", 0.5, 0.0, 1.0),
548
+ "concurrency": int(_number(body, "concurrency", 4, 1, 8)),
549
+ }
550
+ model = body.get("model") or None
551
+ if not model:
552
+ # The judge the tests configure, found by importing them.
553
+ nodeids = [c.get("nodeid") for c in cases if isinstance(c, dict)]
554
+ if isinstance(body.get("source"), str):
555
+ nodeids.append(body["source"])
556
+ files = self.app.judge_test_files(
557
+ [n for n in nodeids if isinstance(n, str)]
526
558
  )
527
- )
559
+ self._json(self.app.judge_test_in_tests(request, files))
560
+ return
561
+ from fasteval.judges import run_judge_cases
528
562
  from fasteval.utils.judge_trace import describe_judge
529
563
 
564
+ temperature = _number(body, "temperature", 0.0, 0.0, 2.0)
565
+ client = self.app.judge_client(model, temperature)
566
+ results = asyncio.run(run_judge_cases(client=client, **request))
530
567
  self._json({"judge": describe_judge(client), "results": results})
531
568
 
532
569
  def api_save_judge(self, parts: List[str], query: Dict[str, str]) -> None:
@@ -595,56 +632,6 @@ def _read_new_events(path: Path, offsets: Dict[str, int]) -> List[Tuple[float, b
595
632
  return batch
596
633
 
597
634
 
598
- async def _run_judge_cases(
599
- *,
600
- template: str,
601
- client: Any,
602
- cases: List[Dict[str, Any]],
603
- scoring: str,
604
- threshold: float,
605
- concurrency: int,
606
- ) -> List[Dict[str, Any]]:
607
- from fasteval.judges import JudgeSpec, PromptJudgeMetric, render_template
608
- from fasteval.models.evaluation import EvalInput
609
- from fasteval.utils import judge_trace
610
-
611
- spec = JudgeSpec(
612
- name="playground",
613
- prompt=template,
614
- scoring="binary" if scoring == "binary" else "continuous",
615
- threshold=max(0.0, min(1.0, threshold)),
616
- )
617
- metric = PromptJudgeMetric(spec, name="playground", llm_client=client)
618
- metric.max_retries = 1
619
- semaphore = asyncio.Semaphore(max(1, min(concurrency, 8)))
620
-
621
- async def one(case: Dict[str, Any]) -> Dict[str, Any]:
622
- key = case.get("key")
623
- try:
624
- eval_input = EvalInput.model_validate(case.get("eval_input") or {})
625
- except Exception as e:
626
- return {"key": key, "error": f"Invalid eval_input: {e}"}
627
- async with semaphore:
628
- start = time.perf_counter()
629
- with judge_trace.capture() as calls:
630
- result = await metric.evaluate(eval_input)
631
- call = calls[-1] if calls else {}
632
- return {
633
- "key": key,
634
- "prompt": render_template(template, eval_input),
635
- "response": call.get("response"),
636
- "error": call.get("error") or result.details.get("error"),
637
- "score": result.score,
638
- "passed": result.passed,
639
- "reasoning": result.reasoning,
640
- "latency_ms": call.get(
641
- "latency_ms", round((time.perf_counter() - start) * 1000, 1)
642
- ),
643
- }
644
-
645
- return list(await asyncio.gather(*(one(c) for c in cases)))
646
-
647
-
648
635
  def _route_key(parts: List[str]) -> Tuple[str, ...]:
649
636
  """Normalize a path into a route key; ids become '*'."""
650
637
  if len(parts) >= 3 and parts[:2] == ["api", "runs"]: