fasteval-core 1.0.3__tar.gz → 1.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.
Files changed (47) hide show
  1. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/PKG-INFO +1 -1
  2. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/__init__.py +13 -0
  3. fasteval_core-1.2.0/fasteval/collectors/__init__.py +23 -0
  4. fasteval_core-1.2.0/fasteval/collectors/collector.py +115 -0
  5. fasteval_core-1.2.0/fasteval/collectors/reporters/__init__.py +1 -0
  6. fasteval_core-1.2.0/fasteval/collectors/reporters/base.py +29 -0
  7. fasteval_core-1.2.0/fasteval/collectors/reporters/html_reporter.py +145 -0
  8. fasteval_core-1.2.0/fasteval/collectors/reporters/json_reporter.py +38 -0
  9. fasteval_core-1.2.0/fasteval/collectors/summary.py +128 -0
  10. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/core/scoring.py +6 -1
  11. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/providers/registry.py +8 -11
  12. fasteval_core-1.2.0/fasteval/testing/plugin.py +121 -0
  13. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/pyproject.toml +1 -1
  14. fasteval_core-1.0.3/fasteval/testing/plugin.py +0 -34
  15. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/README.md +0 -0
  16. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/cache/__init__.py +0 -0
  17. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/cache/memory.py +0 -0
  18. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/core/__init__.py +0 -0
  19. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/core/decorators.py +0 -0
  20. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/core/evaluator.py +0 -0
  21. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/__init__.py +0 -0
  22. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/audio.py +0 -0
  23. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/base.py +0 -0
  24. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/code_judge.py +0 -0
  25. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/conversation.py +0 -0
  26. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/deterministic.py +0 -0
  27. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/llm.py +0 -0
  28. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/multimodal.py +0 -0
  29. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/metrics/vision.py +0 -0
  30. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/models/__init__.py +0 -0
  31. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/models/config.py +0 -0
  32. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/models/evaluation.py +0 -0
  33. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/models/multimodal.py +0 -0
  34. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/providers/__init__.py +0 -0
  35. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/providers/anthropic.py +0 -0
  36. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/providers/base.py +0 -0
  37. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/providers/openai.py +0 -0
  38. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/py.typed +0 -0
  39. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/testing/__init__.py +0 -0
  40. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/__init__.py +0 -0
  41. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/async_helpers.py +0 -0
  42. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/audio.py +0 -0
  43. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/formatting.py +0 -0
  44. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/image.py +0 -0
  45. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/json_parsing.py +0 -0
  46. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/terminal_ui.py +0 -0
  47. {fasteval_core-1.0.3 → fasteval_core-1.2.0}/fasteval/utils/text.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: fasteval-core
3
- Version: 1.0.3
3
+ Version: 1.2.0
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
@@ -29,6 +29,13 @@ except PackageNotFoundError:
29
29
  # === Core API ===
30
30
 
31
31
  from fasteval.cache.memory import MemoryCache, clear_cache, get_cache
32
+ from fasteval.collectors import (
33
+ EvalRunSummary,
34
+ OutputReporter,
35
+ ResultCollector,
36
+ get_collector,
37
+ reset_collector,
38
+ )
32
39
  from fasteval.core.decorators import ( # LLM Metrics; Quality Metrics; RAG Metrics; Deterministic Metrics; Tool Trajectory; Conversation Metrics; Generic; Data Decorators; Human Review; Stack; Vision; Audio; Multi-Modal; Vision metrics; Audio metrics; Multi-modal metrics
33
40
  aesthetic_score,
34
41
  answer_correctness,
@@ -306,4 +313,10 @@ __all__ = [
306
313
  # Evaluator
307
314
  "Evaluator",
308
315
  "create_evaluator",
316
+ # Collectors
317
+ "ResultCollector",
318
+ "get_collector",
319
+ "reset_collector",
320
+ "EvalRunSummary",
321
+ "OutputReporter",
309
322
  ]
@@ -0,0 +1,23 @@
1
+ """
2
+ FastEval output collectors and reporters.
3
+
4
+ Provides result collection, aggregation, and export in multiple formats.
5
+ """
6
+
7
+ from fasteval.collectors.collector import (
8
+ ResultCollector,
9
+ get_collector,
10
+ reset_collector,
11
+ )
12
+ from fasteval.collectors.reporters.base import OutputReporter
13
+ from fasteval.collectors.summary import EvalRunSummary, MetricAggregate, TestCaseSummary
14
+
15
+ __all__ = [
16
+ "ResultCollector",
17
+ "get_collector",
18
+ "reset_collector",
19
+ "EvalRunSummary",
20
+ "MetricAggregate",
21
+ "TestCaseSummary",
22
+ "OutputReporter",
23
+ ]
@@ -0,0 +1,115 @@
1
+ """Core result collector for fasteval evaluation runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Type
8
+
9
+ from fasteval.collectors.reporters.html_reporter import HtmlReporter
10
+ from fasteval.collectors.reporters.json_reporter import JsonReporter
11
+ from fasteval.collectors.summary import EvalRunSummary
12
+
13
+ if TYPE_CHECKING:
14
+ from fasteval.collectors.reporters.base import OutputReporter
15
+ from fasteval.models.evaluation import EvalResult
16
+
17
+
18
+ class ResultCollector:
19
+ """
20
+ Collects EvalResult objects during an evaluation run.
21
+
22
+ Thread-safe. Each call to fe.score() automatically registers
23
+ its result here via the global singleton.
24
+
25
+ Usage (standalone):
26
+ collector = get_collector()
27
+ # ... run evaluations with fe.score() ...
28
+ summary = collector.summary()
29
+ collector.report("json", path="results.json")
30
+ """
31
+
32
+ def __init__(self) -> None:
33
+ self._results: List[EvalResult] = []
34
+ self._test_names: List[str] = []
35
+ self._reporters: Dict[str, Type[OutputReporter]] = {}
36
+ self._lock = threading.Lock()
37
+ self._register_builtins()
38
+
39
+ def collect(self, result: EvalResult, test_name: str = "unknown") -> None:
40
+ """Add a result. Called automatically by fe.score()."""
41
+ with self._lock:
42
+ self._results.append(result)
43
+ self._test_names.append(test_name)
44
+
45
+ @property
46
+ def results(self) -> List[EvalResult]:
47
+ """All collected results (read-only copy)."""
48
+ return list(self._results)
49
+
50
+ def summary(self) -> EvalRunSummary:
51
+ """Compute aggregate statistics from collected results."""
52
+ return EvalRunSummary.from_results(self._results, self._test_names)
53
+
54
+ def report(
55
+ self,
56
+ format: str,
57
+ *,
58
+ path: Optional[str] = None,
59
+ **kwargs: object,
60
+ ) -> str:
61
+ """
62
+ Generate a report in the given format.
63
+
64
+ Args:
65
+ format: "json", "html", or a custom registered name.
66
+ path: Optional file path to write to. If None, returns string only.
67
+ **kwargs: Format-specific options passed to reporter constructor.
68
+
69
+ Returns:
70
+ The report content as a string.
71
+ """
72
+ reporter_cls = self._reporters.get(format)
73
+ if not reporter_cls:
74
+ available = list(self._reporters.keys())
75
+ raise ValueError(f"Unknown format: {format!r}. Available: {available}")
76
+ reporter = reporter_cls(**kwargs)
77
+ content = reporter.generate(self.summary(), self._results)
78
+ if path:
79
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
80
+ Path(path).write_text(content, encoding="utf-8")
81
+ return content
82
+
83
+ def register_reporter(self, name: str, reporter_cls: Type[OutputReporter]) -> None:
84
+ """Register a custom reporter format."""
85
+ self._reporters[name] = reporter_cls
86
+
87
+ def reset(self) -> None:
88
+ """Clear all collected results."""
89
+ with self._lock:
90
+ self._results.clear()
91
+ self._test_names.clear()
92
+
93
+ def _register_builtins(self) -> None:
94
+ self._reporters = {
95
+ "json": JsonReporter,
96
+ "html": HtmlReporter,
97
+ }
98
+
99
+
100
+ _collector: Optional[ResultCollector] = None
101
+
102
+
103
+ def get_collector() -> ResultCollector:
104
+ """Get (or create) the global result collector."""
105
+ global _collector
106
+ if _collector is None:
107
+ _collector = ResultCollector()
108
+ return _collector
109
+
110
+
111
+ def reset_collector() -> None:
112
+ """Reset the global collector. Used between test sessions."""
113
+ global _collector
114
+ if _collector is not None:
115
+ _collector.reset()
@@ -0,0 +1 @@
1
+ """FastEval output reporters."""
@@ -0,0 +1,29 @@
1
+ """Base class for output reporters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import TYPE_CHECKING, List
7
+
8
+ if TYPE_CHECKING:
9
+ from fasteval.collectors.summary import EvalRunSummary
10
+ from fasteval.models.evaluation import EvalResult
11
+
12
+
13
+ class OutputReporter(ABC):
14
+ """
15
+ Base class for output format reporters.
16
+
17
+ Subclass and implement `generate()` to create custom reporters:
18
+
19
+ class SlackReporter(OutputReporter):
20
+ def generate(self, summary, results):
21
+ return f"Eval: {summary.pass_rate:.0%} pass"
22
+
23
+ get_collector().register_reporter("slack", SlackReporter)
24
+ """
25
+
26
+ @abstractmethod
27
+ def generate(self, summary: EvalRunSummary, results: List[EvalResult]) -> str:
28
+ """Generate report content as a string."""
29
+ raise NotImplementedError
@@ -0,0 +1,145 @@
1
+ """HTML output reporter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from html import escape
6
+ from typing import List
7
+
8
+ from fasteval.collectors.reporters.base import OutputReporter
9
+ from fasteval.collectors.summary import EvalRunSummary
10
+ from fasteval.models.evaluation import EvalResult
11
+
12
+ _CSS = """
13
+ * { margin: 0; padding: 0; box-sizing: border-box; }
14
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; padding: 24px; }
15
+ h1 { font-size: 24px; margin-bottom: 16px; }
16
+ h2 { font-size: 18px; margin: 24px 0 12px; }
17
+ .cards { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 24px; }
18
+ .card { background: #fff; border-radius: 8px; padding: 16px 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); min-width: 140px; }
19
+ .card .label { font-size: 12px; text-transform: uppercase; color: #888; margin-bottom: 4px; }
20
+ .card .value { font-size: 28px; font-weight: 600; }
21
+ .card .value.pass { color: #16a34a; }
22
+ .card .value.fail { color: #dc2626; }
23
+ .card .value.neutral { color: #2563eb; }
24
+ table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 24px; }
25
+ th { background: #f8f8f8; text-align: left; padding: 10px 14px; font-size: 13px; text-transform: uppercase; color: #666; border-bottom: 2px solid #eee; }
26
+ td { padding: 10px 14px; border-bottom: 1px solid #eee; font-size: 14px; }
27
+ tr:last-child td { border-bottom: none; }
28
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
29
+ .badge.pass { background: #dcfce7; color: #16a34a; }
30
+ .badge.fail { background: #fee2e2; color: #dc2626; }
31
+ details { background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 8px; }
32
+ details summary { padding: 12px 16px; cursor: pointer; font-size: 14px; }
33
+ details summary:hover { background: #f8f8f8; }
34
+ details .detail-body { padding: 0 16px 16px; }
35
+ .reasoning { background: #f8f8f8; padding: 8px 12px; border-radius: 4px; font-size: 13px; margin-top: 6px; white-space: pre-wrap; }
36
+ .bar { height: 8px; border-radius: 4px; background: #eee; margin-top: 4px; }
37
+ .bar-fill { height: 100%; border-radius: 4px; }
38
+ .bar-fill.pass { background: #16a34a; }
39
+ .bar-fill.fail { background: #dc2626; }
40
+ .timestamp { font-size: 12px; color: #999; margin-top: 24px; }
41
+ """
42
+
43
+
44
+ class HtmlReporter(OutputReporter):
45
+ """Generates a self-contained HTML report with inline CSS."""
46
+
47
+ def generate(self, summary: EvalRunSummary, results: List[EvalResult]) -> str:
48
+ parts = [
49
+ "<!DOCTYPE html>",
50
+ '<html lang="en"><head><meta charset="utf-8">',
51
+ "<title>FastEval Report</title>",
52
+ f"<style>{_CSS}</style>",
53
+ "</head><body>",
54
+ "<h1>FastEval Evaluation Report</h1>",
55
+ self._render_cards(summary),
56
+ "<h2>Metric Breakdown</h2>",
57
+ self._render_metric_table(summary),
58
+ "<h2>Test Results</h2>",
59
+ self._render_test_details(summary, results),
60
+ f'<p class="timestamp">Generated: {escape(summary.timestamp)}</p>',
61
+ "</body></html>",
62
+ ]
63
+ return "\n".join(parts)
64
+
65
+ def _render_cards(self, summary: EvalRunSummary) -> str:
66
+ pass_rate_pct = f"{summary.pass_rate:.0%}"
67
+ avg_score = f"{summary.avg_aggregate_score:.2f}"
68
+ time_s = f"{summary.total_execution_time_ms / 1000:.1f}s"
69
+ return f"""<div class="cards">
70
+ <div class="card"><div class="label">Total Tests</div><div class="value neutral">{summary.total_tests}</div></div>
71
+ <div class="card"><div class="label">Passed</div><div class="value pass">{summary.passed_tests}</div></div>
72
+ <div class="card"><div class="label">Failed</div><div class="value fail">{summary.failed_tests}</div></div>
73
+ <div class="card"><div class="label">Pass Rate</div><div class="value {'pass' if summary.pass_rate >= 0.5 else 'fail'}">{pass_rate_pct}</div></div>
74
+ <div class="card"><div class="label">Avg Score</div><div class="value neutral">{avg_score}</div></div>
75
+ <div class="card"><div class="label">Total Time</div><div class="value neutral">{time_s}</div></div>
76
+ </div>"""
77
+
78
+ def _render_metric_table(self, summary: EvalRunSummary) -> str:
79
+ if not summary.metric_aggregates:
80
+ return "<p>No metrics recorded.</p>"
81
+ rows = []
82
+ for m in summary.metric_aggregates:
83
+ badge_cls = "pass" if m.pass_rate >= 0.5 else "fail"
84
+ bar_pct = f"{m.pass_rate * 100:.0f}%"
85
+ rows.append(
86
+ f"<tr><td>{escape(m.metric_name)}</td>"
87
+ f"<td>{m.count}</td>"
88
+ f'<td><span class="badge {badge_cls}">{m.pass_rate:.0%}</span></td>'
89
+ f"<td>{m.avg_score:.3f}</td>"
90
+ f"<td>{m.min_score:.3f}</td>"
91
+ f"<td>{m.max_score:.3f}</td>"
92
+ f'<td><div class="bar"><div class="bar-fill {badge_cls}" style="width:{bar_pct}"></div></div></td>'
93
+ f"</tr>"
94
+ )
95
+ return f"""<table>
96
+ <thead><tr><th>Metric</th><th>Count</th><th>Pass Rate</th><th>Avg</th><th>Min</th><th>Max</th><th>Distribution</th></tr></thead>
97
+ <tbody>{"".join(rows)}</tbody>
98
+ </table>"""
99
+
100
+ def _render_test_details(
101
+ self, summary: EvalRunSummary, results: List[EvalResult]
102
+ ) -> str:
103
+ if not results:
104
+ return "<p>No test results.</p>"
105
+ parts = []
106
+ for i, result in enumerate(results):
107
+ test_name = (
108
+ summary.test_summaries[i].test_name
109
+ if i < len(summary.test_summaries)
110
+ else "unknown"
111
+ )
112
+ badge = "pass" if result.passed else "fail"
113
+ label = "PASS" if result.passed else "FAIL"
114
+ metric_rows = []
115
+ for mr in result.metric_results:
116
+ m_badge = "pass" if mr.passed else "fail"
117
+ reasoning_html = ""
118
+ if mr.reasoning:
119
+ reasoning_html = (
120
+ f'<div class="reasoning">{escape(mr.reasoning)}</div>'
121
+ )
122
+ metric_rows.append(
123
+ f"<tr><td>{escape(mr.metric_name)}</td>"
124
+ f"<td>{mr.score:.3f}</td>"
125
+ f"<td>{mr.threshold:.2f}</td>"
126
+ f'<td><span class="badge {m_badge}">{"PASS" if mr.passed else "FAIL"}</span></td>'
127
+ f"<td>{reasoning_html}</td></tr>"
128
+ )
129
+ metrics_table = (
130
+ f"""<table>
131
+ <thead><tr><th>Metric</th><th>Score</th><th>Threshold</th><th>Status</th><th>Reasoning</th></tr></thead>
132
+ <tbody>{"".join(metric_rows)}</tbody>
133
+ </table>"""
134
+ if metric_rows
135
+ else "<p>No metrics.</p>"
136
+ )
137
+
138
+ parts.append(
139
+ f'<details><summary><span class="badge {badge}">{label}</span> '
140
+ f"{escape(test_name)} "
141
+ f"(score: {result.aggregate_score:.3f}, "
142
+ f"{result.execution_time_ms:.0f}ms)</summary>"
143
+ f'<div class="detail-body">{metrics_table}</div></details>'
144
+ )
145
+ return "\n".join(parts)
@@ -0,0 +1,38 @@
1
+ """JSON output reporter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Dict, List
7
+
8
+ from fasteval.collectors.reporters.base import OutputReporter
9
+ from fasteval.collectors.summary import EvalRunSummary
10
+ from fasteval.models.evaluation import EvalResult
11
+
12
+
13
+ class JsonReporter(OutputReporter):
14
+ """Generates a JSON report with summary and per-test results."""
15
+
16
+ def __init__(self, *, indent: int = 2, include_inputs: bool = True) -> None:
17
+ self.indent = indent
18
+ self.include_inputs = include_inputs
19
+
20
+ def generate(self, summary: EvalRunSummary, results: List[EvalResult]) -> str:
21
+ output: Dict[str, Any] = {
22
+ "summary": summary.model_dump(mode="json"),
23
+ "results": [],
24
+ }
25
+
26
+ for i, result in enumerate(results):
27
+ test_name = (
28
+ summary.test_summaries[i].test_name
29
+ if i < len(summary.test_summaries)
30
+ else "unknown"
31
+ )
32
+ result_dict = result.model_dump(mode="json")
33
+ if not self.include_inputs:
34
+ result_dict.pop("eval_input", None)
35
+ result_dict["test_name"] = test_name
36
+ output["results"].append(result_dict)
37
+
38
+ return json.dumps(output, indent=self.indent, default=str)
@@ -0,0 +1,128 @@
1
+ """Aggregate data models for evaluation run summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import statistics
6
+ from datetime import datetime, timezone
7
+ from typing import Dict, List
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+ from fasteval.models.evaluation import EvalResult
12
+
13
+
14
+ class MetricAggregate(BaseModel):
15
+ """Aggregate statistics for a single metric type across all results."""
16
+
17
+ metric_name: str
18
+ count: int = 0
19
+ pass_count: int = 0
20
+ fail_count: int = 0
21
+ pass_rate: float = 0.0
22
+ avg_score: float = 0.0
23
+ min_score: float = 0.0
24
+ max_score: float = 0.0
25
+ std_score: float = 0.0
26
+
27
+
28
+ class TestCaseSummary(BaseModel):
29
+ """Summary for a single test case."""
30
+
31
+ test_name: str
32
+ passed: bool
33
+ aggregate_score: float
34
+ metric_count: int
35
+ execution_time_ms: float
36
+ error: str | None = None
37
+
38
+
39
+ class EvalRunSummary(BaseModel):
40
+ """Complete summary of an evaluation run."""
41
+
42
+ total_tests: int = 0
43
+ passed_tests: int = 0
44
+ failed_tests: int = 0
45
+ pass_rate: float = 0.0
46
+ avg_aggregate_score: float = 0.0
47
+ total_execution_time_ms: float = 0.0
48
+
49
+ metric_aggregates: List[MetricAggregate] = Field(default_factory=list)
50
+ test_summaries: List[TestCaseSummary] = Field(default_factory=list)
51
+
52
+ timestamp: str = ""
53
+
54
+ @classmethod
55
+ def from_results(
56
+ cls, results: List[EvalResult], test_names: List[str]
57
+ ) -> EvalRunSummary:
58
+ """Compute summary from a list of EvalResult objects."""
59
+ if not results:
60
+ return cls(timestamp=datetime.now(timezone.utc).isoformat())
61
+
62
+ total = len(results)
63
+ passed = sum(1 for r in results if r.passed)
64
+ failed = total - passed
65
+ scores = [r.aggregate_score for r in results]
66
+ total_time = sum(r.execution_time_ms for r in results)
67
+
68
+ # Per-test summaries
69
+ test_summaries = []
70
+ for result, name in zip(results, test_names):
71
+ test_summaries.append(
72
+ TestCaseSummary(
73
+ test_name=name,
74
+ passed=result.passed,
75
+ aggregate_score=result.aggregate_score,
76
+ metric_count=len(result.metric_results),
77
+ execution_time_ms=result.execution_time_ms,
78
+ error=result.error,
79
+ )
80
+ )
81
+
82
+ # Per-metric aggregates
83
+ metric_scores: Dict[str, List[float]] = {}
84
+ metric_passed: Dict[str, int] = {}
85
+ metric_count: Dict[str, int] = {}
86
+
87
+ for result in results:
88
+ for mr in result.metric_results:
89
+ name = mr.metric_name
90
+ if name not in metric_scores:
91
+ metric_scores[name] = []
92
+ metric_passed[name] = 0
93
+ metric_count[name] = 0
94
+ metric_scores[name].append(mr.score)
95
+ metric_count[name] += 1
96
+ if mr.passed:
97
+ metric_passed[name] += 1
98
+
99
+ metric_aggregates = []
100
+ for name in sorted(metric_scores.keys()):
101
+ s = metric_scores[name]
102
+ count = metric_count[name]
103
+ pc = metric_passed[name]
104
+ metric_aggregates.append(
105
+ MetricAggregate(
106
+ metric_name=name,
107
+ count=count,
108
+ pass_count=pc,
109
+ fail_count=count - pc,
110
+ pass_rate=pc / count if count > 0 else 0.0,
111
+ avg_score=statistics.mean(s),
112
+ min_score=min(s),
113
+ max_score=max(s),
114
+ std_score=statistics.stdev(s) if len(s) > 1 else 0.0,
115
+ )
116
+ )
117
+
118
+ return cls(
119
+ total_tests=total,
120
+ passed_tests=passed,
121
+ failed_tests=failed,
122
+ pass_rate=passed / total if total > 0 else 0.0,
123
+ avg_aggregate_score=statistics.mean(scores),
124
+ total_execution_time_ms=total_time,
125
+ metric_aggregates=metric_aggregates,
126
+ test_summaries=test_summaries,
127
+ timestamp=datetime.now(timezone.utc).isoformat(),
128
+ )
@@ -347,9 +347,14 @@ def score(
347
347
  # Store result for conversation decorator to access (context-local)
348
348
  _last_score_result.set(result)
349
349
 
350
+ # Auto-collect result for reporting
351
+ from fasteval.collectors.collector import get_collector
352
+
353
+ test_name = _get_test_name_from_caller()
354
+ get_collector().collect(result, test_name=test_name)
355
+
350
356
  # If evaluation failed, raise an exception with the formatted report
351
357
  if not result.passed:
352
- test_name = _get_test_name_from_caller()
353
358
  report = format_evaluation_report(test_name, [result], [eval_input])
354
359
  raise EvaluationFailedError(report, result)
355
360
 
@@ -1,16 +1,13 @@
1
1
  """Provider registry for managing default LLM client."""
2
2
 
3
3
  import os
4
- from contextvars import ContextVar
5
4
  from typing import TYPE_CHECKING, Optional
6
5
 
7
6
  if TYPE_CHECKING:
8
7
  from fasteval.providers.base import LLMClient
9
8
 
10
- # Global default provider storage
11
- _default_provider: ContextVar[Optional["LLMClient"]] = ContextVar(
12
- "fasteval_default_provider", default=None
13
- )
9
+ # Global default provider storage (module-level to work across async contexts)
10
+ _default_provider: Optional["LLMClient"] = None
14
11
 
15
12
 
16
13
  def set_default_provider(provider: "LLMClient") -> None:
@@ -25,7 +22,8 @@ def set_default_provider(provider: "LLMClient") -> None:
25
22
 
26
23
  set_default_provider(OpenAIClient(model="gpt-4o"))
27
24
  """
28
- _default_provider.set(provider)
25
+ global _default_provider
26
+ _default_provider = provider
29
27
 
30
28
 
31
29
  def get_default_provider() -> "LLMClient":
@@ -42,11 +40,9 @@ def get_default_provider() -> "LLMClient":
42
40
  Raises:
43
41
  ValueError: If no provider configured and no env vars found
44
42
  """
45
- provider = _default_provider.get()
46
- if provider is not None:
47
- return provider
43
+ if _default_provider is not None:
44
+ return _default_provider
48
45
 
49
- # Auto-detect from environment
50
46
  return _create_provider_from_env()
51
47
 
52
48
 
@@ -76,7 +72,8 @@ def _create_provider_from_env() -> "LLMClient":
76
72
 
77
73
  def clear_default_provider() -> None:
78
74
  """Clear the default provider (mainly for testing)."""
79
- _default_provider.set(None)
75
+ global _default_provider
76
+ _default_provider = None
80
77
 
81
78
 
82
79
  def create_provider_for_model(model_name: str) -> "LLMClient":
@@ -0,0 +1,121 @@
1
+ """
2
+ FastEval pytest plugin.
3
+
4
+ Provides pytest integration for fasteval, including:
5
+ - --no-interactive flag to skip human review prompts in CI/CD
6
+ - --fe-output flag to export evaluation results (json, html)
7
+ - --fe-summary flag to print a console summary after the run
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ from typing import Any
13
+
14
+
15
+ def pytest_addoption(parser: Any) -> None:
16
+ """Add fasteval-specific command line options to pytest."""
17
+ parser.addoption(
18
+ "--no-interactive",
19
+ action="store_true",
20
+ default=False,
21
+ help="Skip human review prompts (for CI/CD pipelines)",
22
+ )
23
+ parser.addoption(
24
+ "--fe-output",
25
+ action="append",
26
+ default=[],
27
+ help=(
28
+ "Export evaluation results. Format: type:path "
29
+ "(e.g., json:results.json, html:report.html). "
30
+ "Can be specified multiple times."
31
+ ),
32
+ )
33
+ parser.addoption(
34
+ "--fe-summary",
35
+ action="store_true",
36
+ default=False,
37
+ help="Print evaluation summary to console after test run",
38
+ )
39
+
40
+
41
+ def pytest_configure(config: Any) -> None:
42
+ """Configure fasteval based on pytest options."""
43
+ # Set environment variable if --no-interactive flag is passed
44
+ if config.getoption("--no-interactive", default=False):
45
+ os.environ["FASTEVAL_NO_INTERACTIVE"] = "1"
46
+
47
+
48
+ def pytest_sessionstart(session: Any) -> None:
49
+ """Reset collector at the start of each test session."""
50
+ from fasteval.collectors.collector import reset_collector
51
+
52
+ reset_collector()
53
+
54
+
55
+ def pytest_sessionfinish(session: Any, exitstatus: int) -> None:
56
+ """Generate reports after all tests complete."""
57
+ from fasteval.collectors.collector import get_collector
58
+
59
+ collector = get_collector()
60
+
61
+ if not collector.results:
62
+ return
63
+
64
+ # Print console summary if requested
65
+ if session.config.getoption("--fe-summary", default=False):
66
+ summary = collector.summary()
67
+ _print_console_summary(summary)
68
+
69
+ # Process --fe-output flags
70
+ outputs = session.config.getoption("--fe-output", default=[])
71
+ for output_spec in outputs:
72
+ if ":" in output_spec:
73
+ fmt, path = output_spec.split(":", 1)
74
+ collector.report(fmt.strip(), path=path.strip())
75
+ else:
76
+ # No path = print to stdout
77
+ content = collector.report(output_spec.strip())
78
+ sys.stdout.write(content + "\n")
79
+
80
+
81
+ def pytest_unconfigure(config: Any) -> None:
82
+ """Clean up after pytest run."""
83
+ # Remove the environment variable if we set it
84
+ if "FASTEVAL_NO_INTERACTIVE" in os.environ:
85
+ if config.getoption("--no-interactive", default=False):
86
+ del os.environ["FASTEVAL_NO_INTERACTIVE"]
87
+
88
+
89
+ def _print_console_summary(summary: Any) -> None:
90
+ """Print a compact console summary of evaluation results."""
91
+ sep = "=" * 60
92
+ print(f"\n{sep}")
93
+ print(" FastEval Summary")
94
+ print(sep)
95
+ print(
96
+ f" Tests: {summary.total_tests} total, "
97
+ f"{summary.passed_tests} passed, "
98
+ f"{summary.failed_tests} failed"
99
+ )
100
+
101
+ print(f" Pass Rate: {summary.pass_rate:.0%}")
102
+ print(f" Avg Score: {summary.avg_aggregate_score:.3f}")
103
+ print(f" Time: {summary.total_execution_time_ms:.0f}ms")
104
+
105
+ if summary.metric_aggregates:
106
+ print(f"\n {'Metric':<25} {'Pass Rate':>10} {'Avg':>8} {'Min':>8} {'Max':>8}")
107
+ print(f" {'-' * 25} {'-' * 10} {'-' * 8} {'-' * 8} {'-' * 8}")
108
+ for m in summary.metric_aggregates:
109
+ print(
110
+ f" {m.metric_name:<25} {m.pass_rate:>9.0%} "
111
+ f"{m.avg_score:>8.3f} {m.min_score:>8.3f} {m.max_score:>8.3f}"
112
+ )
113
+
114
+ if summary.failed_tests > 0:
115
+ print(f"\n Failed tests:")
116
+ for t in summary.test_summaries:
117
+ if not t.passed:
118
+ err = f" - {t.error}" if t.error else ""
119
+ print(f" x {t.test_name} (score: {t.aggregate_score:.3f}){err}")
120
+
121
+ print(sep + "\n")
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fasteval-core"
3
- version = "1.0.3"
3
+ version = "1.2.0"
4
4
  description = "A decorator-first LLM evaluation library for testing AI agents"
5
5
  authors = [{name = "Intuit"}]
6
6
  license = {text = "Apache-2.0"}
@@ -1,34 +0,0 @@
1
- """
2
- FastEval pytest plugin.
3
-
4
- Provides pytest integration for fasteval, including:
5
- - --no-interactive flag to skip human review prompts in CI/CD
6
- """
7
-
8
- import os
9
- from typing import Any
10
-
11
-
12
- def pytest_addoption(parser: Any) -> None:
13
- """Add fasteval-specific command line options to pytest."""
14
- parser.addoption(
15
- "--no-interactive",
16
- action="store_true",
17
- default=False,
18
- help="Skip human review prompts (for CI/CD pipelines)",
19
- )
20
-
21
-
22
- def pytest_configure(config: Any) -> None:
23
- """Configure fasteval based on pytest options."""
24
- # Set environment variable if --no-interactive flag is passed
25
- if config.getoption("--no-interactive", default=False):
26
- os.environ["FASTEVAL_NO_INTERACTIVE"] = "1"
27
-
28
-
29
- def pytest_unconfigure(config: Any) -> None:
30
- """Clean up after pytest run."""
31
- # Remove the environment variable if we set it
32
- if "FASTEVAL_NO_INTERACTIVE" in os.environ:
33
- if config.getoption("--no-interactive", default=False):
34
- del os.environ["FASTEVAL_NO_INTERACTIVE"]
File without changes