evalpen 0.0.1__py3-none-any.whl

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.
evalpen/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """EvalPen: LLM evaluation you can trust."""
2
+
3
+ from evalpen.calibrate import CalibrationReport, calibrate_judge
4
+ from evalpen.stats import cohen_kappa, raw_agreement, wilson_interval
5
+
6
+ __version__ = "0.0.1"
7
+
8
+ __all__ = [
9
+ "__version__",
10
+ "CalibrationReport",
11
+ "calibrate_judge",
12
+ "cohen_kappa",
13
+ "raw_agreement",
14
+ "wilson_interval",
15
+ ]
evalpen/calibrate.py ADDED
@@ -0,0 +1,89 @@
1
+ """calibrate_judge: how much can you trust your LLM judge?
2
+
3
+ Compares the judge's labels with human labels on the same examples.
4
+ Input is a JSONL file, one example per line, with at least:
5
+
6
+ {"id": "case_1", "human": "pass", "judge": "pass"}
7
+
8
+ Labels can be any strings or numbers (pass/fail, A/B, 1-5...).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from evalpen.stats import cohen_kappa, interpret_kappa, raw_agreement, wilson_interval
18
+
19
+ RELIABLE_KAPPA = 0.6
20
+
21
+
22
+ @dataclass
23
+ class CalibrationReport:
24
+ n: int
25
+ agreement: float
26
+ agreement_ci: tuple[float, float]
27
+ kappa: float
28
+ kappa_label: str
29
+ disagreements: list[dict] = field(default_factory=list)
30
+
31
+ @property
32
+ def reliable(self) -> bool:
33
+ return self.kappa >= RELIABLE_KAPPA
34
+
35
+ def to_markdown(self, max_examples: int = 10) -> str:
36
+ verdict = "reliable" if self.reliable else "NOT reliable yet"
37
+ lo, hi = self.agreement_ci
38
+ lines = [
39
+ f"Judge calibration on {self.n} examples: **{verdict}**",
40
+ "",
41
+ f"- Raw agreement: {self.agreement:.0%} (95% CI {lo:.0%}–{hi:.0%})",
42
+ f"- Cohen's kappa: {self.kappa:.2f} ({self.kappa_label})",
43
+ f"- Threshold used: kappa >= {RELIABLE_KAPPA}",
44
+ ]
45
+ if self.disagreements:
46
+ lines += ["", f"Disagreements ({len(self.disagreements)}):"]
47
+ for row in self.disagreements[:max_examples]:
48
+ lines.append(f"- {row['id']}: human={row['human']!r}, judge={row['judge']!r}")
49
+ if len(self.disagreements) > max_examples:
50
+ lines.append(f"- ... and {len(self.disagreements) - max_examples} more")
51
+ return "\n".join(lines)
52
+
53
+
54
+ def load_labels(path: str | Path) -> list[dict]:
55
+ rows = []
56
+ with open(path, encoding="utf-8") as f:
57
+ for i, line in enumerate(f, start=1):
58
+ line = line.strip()
59
+ if not line:
60
+ continue
61
+ row = json.loads(line)
62
+ missing = {"human", "judge"} - row.keys()
63
+ if missing:
64
+ raise ValueError(f"line {i}: missing field(s) {sorted(missing)}")
65
+ row.setdefault("id", f"line_{i}")
66
+ rows.append(row)
67
+ if not rows:
68
+ raise ValueError(f"no examples found in {path}")
69
+ return rows
70
+
71
+
72
+ def calibrate_judge(rows: list[dict]) -> CalibrationReport:
73
+ human = [r["human"] for r in rows]
74
+ judge = [r["judge"] for r in rows]
75
+ n = len(rows)
76
+ agree = raw_agreement(human, judge)
77
+ kappa = cohen_kappa(human, judge)
78
+ return CalibrationReport(
79
+ n=n,
80
+ agreement=agree,
81
+ agreement_ci=wilson_interval(round(agree * n), n),
82
+ kappa=kappa,
83
+ kappa_label=interpret_kappa(kappa),
84
+ disagreements=[r for r in rows if r["human"] != r["judge"]],
85
+ )
86
+
87
+
88
+ def calibrate_judge_file(path: str | Path) -> CalibrationReport:
89
+ return calibrate_judge(load_labels(path))
evalpen/cli.py ADDED
@@ -0,0 +1,54 @@
1
+ """Command-line interface: `evalpen ...`"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from evalpen import __version__
9
+ from evalpen.calibrate import calibrate_judge_file
10
+
11
+
12
+ def main(argv: list[str] | None = None) -> int:
13
+ parser = argparse.ArgumentParser(
14
+ prog="evalpen",
15
+ description="LLM evaluation you can trust.",
16
+ )
17
+ parser.add_argument("--version", action="version", version=f"evalpen {__version__}")
18
+ sub = parser.add_subparsers(dest="command")
19
+
20
+ cal = sub.add_parser("calibrate", help="Check judge vs. human agreement (Cohen's kappa).")
21
+ cal.add_argument("file", help="JSONL file with 'human' and 'judge' labels per line.")
22
+ cal.add_argument(
23
+ "--fail-if-unreliable",
24
+ action="store_true",
25
+ help="Exit with code 1 if the judge is not reliable (for CI).",
26
+ )
27
+
28
+ sub.add_parser("mcp", help="Run the EvalPen MCP server (stdio).")
29
+
30
+ args = parser.parse_args(argv)
31
+
32
+ if args.command == "calibrate":
33
+ try:
34
+ report = calibrate_judge_file(args.file)
35
+ except (OSError, ValueError) as err:
36
+ print(f"error: {err}", file=sys.stderr)
37
+ return 2
38
+ print(report.to_markdown())
39
+ if args.fail_if_unreliable and not report.reliable:
40
+ return 1
41
+ return 0
42
+
43
+ if args.command == "mcp":
44
+ from evalpen.mcp_server import run
45
+
46
+ run()
47
+ return 0
48
+
49
+ parser.print_help()
50
+ return 0
51
+
52
+
53
+ if __name__ == "__main__":
54
+ sys.exit(main())
evalpen/mcp_server.py ADDED
@@ -0,0 +1,44 @@
1
+ """EvalPen MCP server. A thin layer over the core library.
2
+
3
+ Run with: `evalpen mcp` (or `uvx evalpen mcp`).
4
+ Add to Claude Code: `claude mcp add evalpen -- uvx evalpen mcp`
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from mcp.server.mcpserver import MCPServer
10
+
11
+ from evalpen import __version__
12
+ from evalpen.calibrate import calibrate_judge_file
13
+
14
+ mcp = MCPServer(
15
+ "evalpen",
16
+ version=__version__,
17
+ instructions=(
18
+ "EvalPen evaluates LLM outputs. Use calibrate_judge to check whether an "
19
+ "LLM judge agrees with human labels before trusting its scores."
20
+ ),
21
+ )
22
+
23
+
24
+ @mcp.tool()
25
+ def calibrate_judge(path: str) -> str:
26
+ """Check how far an LLM judge can be trusted, by comparing it with human labels.
27
+
28
+ Args:
29
+ path: Path to a JSONL file. Each line is one example with a "human"
30
+ label, a "judge" label, and optionally an "id".
31
+ Example line: {"id": "case_1", "human": "pass", "judge": "fail"}
32
+
33
+ Returns a Markdown report: raw agreement with a 95% confidence interval,
34
+ Cohen's kappa, a reliable / not reliable verdict, and the disagreements
35
+ to review by hand.
36
+ """
37
+ try:
38
+ return calibrate_judge_file(path).to_markdown()
39
+ except (OSError, ValueError) as err:
40
+ return f"Error: {err}"
41
+
42
+
43
+ def run() -> None:
44
+ mcp.run()
evalpen/stats.py ADDED
@@ -0,0 +1,70 @@
1
+ """Statistics used across EvalPen. Pure Python, no dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections import Counter
7
+ from collections.abc import Hashable, Sequence
8
+
9
+
10
+ def raw_agreement(a: Sequence[Hashable], b: Sequence[Hashable]) -> float:
11
+ """Share of items where both raters gave the same label."""
12
+ _check_pairs(a, b)
13
+ return sum(x == y for x, y in zip(a, b)) / len(a)
14
+
15
+
16
+ def cohen_kappa(a: Sequence[Hashable], b: Sequence[Hashable]) -> float:
17
+ """Cohen's kappa between two raters: agreement corrected for chance.
18
+
19
+ kappa = (p_o - p_e) / (1 - p_e)
20
+
21
+ Returns 1.0 when both raters agree perfectly and only one label is used
22
+ (p_e == 1), since there is no disagreement to correct for.
23
+ """
24
+ _check_pairs(a, b)
25
+ n = len(a)
26
+ p_o = raw_agreement(a, b)
27
+ count_a, count_b = Counter(a), Counter(b)
28
+ p_e = sum(count_a[label] * count_b[label] for label in count_a) / (n * n)
29
+ if p_e == 1.0:
30
+ return 1.0
31
+ return (p_o - p_e) / (1 - p_e)
32
+
33
+
34
+ def wilson_interval(successes: int, total: int, z: float = 1.96) -> tuple[float, float]:
35
+ """Wilson score interval for a proportion (95% by default).
36
+
37
+ More reliable than the normal approximation on small samples,
38
+ which is the usual case for prompt evals (20 to 100 cases).
39
+ """
40
+ if total <= 0:
41
+ raise ValueError("total must be positive")
42
+ if not 0 <= successes <= total:
43
+ raise ValueError("successes must be between 0 and total")
44
+ p = successes / total
45
+ denom = 1 + z * z / total
46
+ centre = (p + z * z / (2 * total)) / denom
47
+ half = z * math.sqrt(p * (1 - p) / total + z * z / (4 * total * total)) / denom
48
+ return max(0.0, centre - half), min(1.0, centre + half)
49
+
50
+
51
+ def interpret_kappa(kappa: float) -> str:
52
+ """Landis & Koch (1977) scale, the usual reading of kappa."""
53
+ if kappa < 0:
54
+ return "poor (worse than chance)"
55
+ if kappa <= 0.20:
56
+ return "slight"
57
+ if kappa <= 0.40:
58
+ return "fair"
59
+ if kappa <= 0.60:
60
+ return "moderate"
61
+ if kappa <= 0.80:
62
+ return "substantial"
63
+ return "almost perfect"
64
+
65
+
66
+ def _check_pairs(a: Sequence[Hashable], b: Sequence[Hashable]) -> None:
67
+ if len(a) != len(b):
68
+ raise ValueError(f"raters have different lengths: {len(a)} vs {len(b)}")
69
+ if len(a) == 0:
70
+ raise ValueError("need at least one item")
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: evalpen
3
+ Version: 0.0.1
4
+ Summary: LLM evaluation you can trust: compare prompts, catch hallucinations, and calibrate your LLM judge. From your coding agent, CLI, Python or CI.
5
+ Project-URL: Homepage, https://github.com/Emmrui/evalpen
6
+ Project-URL: Issues, https://github.com/Emmrui/evalpen/issues
7
+ Author: Emmanuelle Ruimy
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: evaluation,hallucination,llm,llm-as-a-judge,mcp,prompt-engineering
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: mcp<3,>=2.0
18
+ Description-Content-Type: text/markdown
19
+
20
+ # EvalPen
21
+
22
+ **Know if your prompt change actually made things better, with a judge you've verified.**
23
+
24
+ EvalPen is a Python library for LLM evaluation, with four ways in: an MCP server and skill for your coding agent (Claude Code, Cursor, or any MCP client), a CLI, a Python API and a CI check. There's no dashboard and no account. In your agent, you ask in plain language and get a report back in the conversation.
25
+
26
+ > "Compare prompt v1 and v2 on my 50 test cases."
27
+ > "Is this answer supported by these documents?"
28
+ > "Here are 30 hand-labeled examples. Can I trust my judge?"
29
+
30
+ > ⚠️ Work in progress. Name and API may change before v0.1.
31
+
32
+ ## Why
33
+
34
+ - **Prompt changes get tested by vibes.** Three examples, eyeballed. Regressions ship.
35
+ - **LLM judges get trusted blindly.** Judges have known biases (position, length) and can disagree with humans on hard cases. Most setups never check.
36
+ - **Eval frameworks take setup.** Many teams never get past it.
37
+
38
+ EvalPen makes evaluation a one-sentence ask, and every report states how reliable its judge is.
39
+
40
+ ## Tools
41
+
42
+ | Tool | What it does |
43
+ | --- | --- |
44
+ | `create_eval_set` | Builds a varied test set (JSONL) from logs or a task description |
45
+ | `compare_prompts` | Pairwise comparison of two prompts: win rate, confidence interval, regressions with explanations |
46
+ | `check_faithfulness` | Splits an answer into atomic claims and checks each against the source documents |
47
+ | `calibrate_judge` | Measures judge vs. human agreement (raw agreement, Cohen's kappa, position bias) |
48
+
49
+ ## Example report
50
+
51
+ ```
52
+ Prompt v2 wins 34/50 (68%, 95% CI: 54–80%)
53
+ Judge: kappa = 0.78 vs. human labels (reliable)
54
+
55
+ Regressions (4):
56
+ - case_12: v2 drops the currency from the amount
57
+ - case_27: v2 answers in English to a French question
58
+ ...
59
+ ```
60
+
61
+ *(Illustrative format, not real results.)*
62
+
63
+ ## How it works
64
+
65
+ - **Pairwise judging.** The judge picks the better of two answers against your criteria. This is more stable than absolute 1–10 scores.
66
+ - **Position-bias control.** Each pair is judged twice with A/B swapped. A flipped verdict counts as a tie and gets flagged.
67
+ - **Confidence intervals.** Win rates come with an interval, so you don't conclude from 10 examples.
68
+ - **Local first.** Test cases, runs and reports stay on your machine as JSONL and Markdown. LLM calls use your own API key.
69
+
70
+ ## Try it now (v0.0.1)
71
+
72
+ v0.0.1 ships the first tool: **judge calibration**. Give it a JSONL file where each line has a human label and your LLM judge's label:
73
+
74
+ ```json
75
+ {"id": "case_01", "human": "pass", "judge": "pass"}
76
+ {"id": "case_05", "human": "fail", "judge": "pass"}
77
+ ```
78
+
79
+ ```bash
80
+ uvx evalpen calibrate examples/judge_vs_human.jsonl
81
+ ```
82
+
83
+ ```
84
+ Judge calibration on 20 examples: **reliable**
85
+
86
+ - Raw agreement: 85% (95% CI 64%–95%)
87
+ - Cohen's kappa: 0.69 (substantial)
88
+ - Threshold used: kappa >= 0.6
89
+
90
+ Disagreements (3):
91
+ - case_05: human='fail', judge='pass'
92
+ ...
93
+ ```
94
+
95
+ Add `--fail-if-unreliable` to exit with code 1 in CI when kappa is below 0.6.
96
+
97
+ The same tool is available to your agent through the MCP server:
98
+
99
+ ```bash
100
+ claude mcp add evalpen -- uvx evalpen mcp
101
+ ```
102
+
103
+ ## Usage (planned for v0.1)
104
+
105
+ *The commands below are the target interface. They may change.*
106
+
107
+ **In your agent (MCP + skill)**
108
+
109
+ ```bash
110
+ claude mcp add evalpen -- uvx evalpen mcp
111
+ ```
112
+
113
+ Then just ask: *"I changed the classification prompt. Compare it with the old one on my test cases."* The agent calls `compare_prompts`, summarizes the regressions, and can fix the prompt and re-run.
114
+
115
+ **From the terminal (CLI)**
116
+
117
+ ```bash
118
+ evalpen compare prompts/v1.txt prompts/v2.txt --cases tests.jsonl
119
+ ```
120
+
121
+ **From Python**
122
+
123
+ ```python
124
+ from evalpen import compare, check_faithfulness
125
+
126
+ result = compare(prompt_a, prompt_b, cases="tests.jsonl", judge="claude-haiku")
127
+ claims = check_faithfulness(answer, sources=docs)
128
+ ```
129
+
130
+ **In CI (block regressions before merge)**
131
+
132
+ ```yaml
133
+ - run: evalpen compare main.txt pr.txt --cases tests.jsonl --fail-if-win-rate-below 0.5
134
+ ```
135
+
136
+ ## Architecture
137
+
138
+ ```
139
+ MCP + skill CLI Python API CI
140
+ \ | | /
141
+ ────── evalpen core library ──────
142
+ create_eval_set · compare_prompts
143
+ check_faithfulness · calibrate_judge
144
+ runner · judge · stats
145
+ / \
146
+ local files (JSONL) LLM APIs (your key)
147
+ ```
148
+
149
+ All logic lives in the core library. The CLI, MCP server, skill and CI check are thin layers on top.
150
+
151
+ ## Roadmap
152
+
153
+ - [x] Core library + CLI + MCP server skeleton
154
+ - [x] `calibrate_judge` + Cohen's kappa (v0.0.1)
155
+ - [ ] `check_faithfulness`
156
+ - [ ] `compare_prompts` with position-bias control and CIs
157
+ - [ ] `create_eval_set`
158
+ - [ ] MCP server, skill, GitHub Action
159
+ - [ ] Demo dataset, GIF, tests
160
+ - [ ] v0.1 release: PyPI + MCP registry
161
+
162
+ ## Background
163
+
164
+ Built by an AI engineer who shipped LLM classification and recommendation systems at scale, where every release was validated with human review plus LLM-as-a-judge. EvalPen packages that workflow so anyone can use it from their agent.
165
+
166
+ ## License
167
+
168
+ MIT
@@ -0,0 +1,10 @@
1
+ evalpen/__init__.py,sha256=-1GZaiZ7XM517ni1IJE8mm2QNSOBQ8_y_JYrbEYtPt4,349
2
+ evalpen/calibrate.py,sha256=JVqHCEIZfhabMPIKJmGuD4PDgIMeds6ceBWpeWGdi3c,2972
3
+ evalpen/cli.py,sha256=Cw7EExaVO4WlrAC1orHLr9kXFIc6WVJcYLUK2UvbaAE,1503
4
+ evalpen/mcp_server.py,sha256=9IqYgL5lmuxuQPRhv8PIyQw9CY_wsjofjsOmE6Ys-Rg,1300
5
+ evalpen/stats.py,sha256=S8ceyW5M8inHndEgEQ0XloGSZiTT_sLlqdWfst3nE6Q,2361
6
+ evalpen-0.0.1.dist-info/METADATA,sha256=94w_9TPkplFGBFpcYyOMHEnRZfQgSRaQD_REoi36JWs,5857
7
+ evalpen-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ evalpen-0.0.1.dist-info/entry_points.txt,sha256=KgkFroqYh6ktjSVkC2AzS4Nc0wHadPV89elQ4cfCvIw,45
9
+ evalpen-0.0.1.dist-info/licenses/LICENSE,sha256=oAoVqjuWIw5B4XLpSbWdLHLdldMI9r-tYo14T0gj-g4,1073
10
+ evalpen-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ evalpen = evalpen.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Emmanuelle Ruimy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.