tinyevals 0.1.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.
- tinyevals-0.1.0/.gitignore +7 -0
- tinyevals-0.1.0/CHANGELOG.md +29 -0
- tinyevals-0.1.0/LICENSE +9 -0
- tinyevals-0.1.0/PKG-INFO +181 -0
- tinyevals-0.1.0/README.md +148 -0
- tinyevals-0.1.0/examples/llm_judge.py +37 -0
- tinyevals-0.1.0/examples/quickstart.py +10 -0
- tinyevals-0.1.0/pyproject.toml +50 -0
- tinyevals-0.1.0/src/tinyevals/__init__.py +27 -0
- tinyevals-0.1.0/src/tinyevals/adapters/__init__.py +1 -0
- tinyevals-0.1.0/src/tinyevals/adapters/anthropic.py +36 -0
- tinyevals-0.1.0/src/tinyevals/graders.py +79 -0
- tinyevals-0.1.0/src/tinyevals/jsonl.py +57 -0
- tinyevals-0.1.0/src/tinyevals/judge.py +117 -0
- tinyevals-0.1.0/src/tinyevals/models.py +34 -0
- tinyevals-0.1.0/src/tinyevals/py.typed +0 -0
- tinyevals-0.1.0/src/tinyevals/report.py +49 -0
- tinyevals-0.1.0/src/tinyevals/runner.py +38 -0
- tinyevals-0.1.0/tests/test_anthropic_adapter.py +106 -0
- tinyevals-0.1.0/tests/test_basics.py +20 -0
- tinyevals-0.1.0/tests/test_graders.py +174 -0
- tinyevals-0.1.0/tests/test_jsonl.py +135 -0
- tinyevals-0.1.0/tests/test_judge.py +165 -0
- tinyevals-0.1.0/tests/test_report.py +75 -0
- tinyevals-0.1.0/tests/test_runner.py +89 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-11-30
|
|
8
|
+
|
|
9
|
+
First public release.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `Case`, `Grade`, `CaseResult` Pydantic models. `Case` rejects unknown fields, and
|
|
14
|
+
`Grade.score` must be between 0 and 1.
|
|
15
|
+
- `run(system, cases, grader)`. When the system or grader raises, the case gets a failed `Grade`
|
|
16
|
+
(`error: <Type>: <message>`) and the run continues. Each result records `duration_ms`.
|
|
17
|
+
- Graders: `exact_match`, `numeric_close(tol)` (ints, floats, numpy scalars; float-tolerant
|
|
18
|
+
boundary), `contains(substring, case_sensitive=False)`.
|
|
19
|
+
- `llm_judge(rubric, judge, pass_threshold=0.7)` with an injected `str -> str` judge. It parses
|
|
20
|
+
`{"score", "reason"}` JSON (code fences tolerated) and turns judge failures into
|
|
21
|
+
`judge error: ...` grades.
|
|
22
|
+
- `tinyevals.adapters.anthropic.anthropic_judge(model, max_tokens=300)` behind the optional
|
|
23
|
+
`anthropic` extra, imported lazily.
|
|
24
|
+
- `summarize(results) -> Summary` and `print_table(results)`.
|
|
25
|
+
- `load_cases(path)` and `save_results(results, path)` for JSONL, with line-numbered errors for
|
|
26
|
+
malformed lines, missing fields and duplicate ids.
|
|
27
|
+
- `py.typed` marker. CI runs on Python 3.10–3.13.
|
|
28
|
+
|
|
29
|
+
[0.1.0]: https://github.com/shivshashaang/tinyevals/releases/tag/v0.1.0
|
tinyevals-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shivshashaang Haribhaskar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
tinyevals-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tinyevals
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Small, typed evals for functions and LLMs: cases, graders, and a runner.
|
|
5
|
+
Project-URL: Repository, https://github.com/shivshashaang/tinyevals
|
|
6
|
+
Project-URL: Changelog, https://github.com/shivshashaang/tinyevals/blob/main/CHANGELOG.md
|
|
7
|
+
Author: Shivshashaang Haribhaskar
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: evals,llm,llm-as-judge,pydantic,testing
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: pydantic>=2.11
|
|
23
|
+
Provides-Extra: anthropic
|
|
24
|
+
Requires-Dist: anthropic>=0.51; extra == 'anthropic'
|
|
25
|
+
Requires-Dist: numpy; extra == 'anthropic'
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: anthropic>=0.51; extra == 'dev'
|
|
28
|
+
Requires-Dist: mypy==2.4.1; extra == 'dev'
|
|
29
|
+
Requires-Dist: numpy; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff==0.17.6; extra == 'dev'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# tinyevals
|
|
35
|
+
|
|
36
|
+
[](https://github.com/shivshashaang/tinyevals/actions/workflows/ci.yml)
|
|
37
|
+
[](https://pypi.org/project/tinyevals/)
|
|
38
|
+
|
|
39
|
+
Small, typed evals for functions and LLMs: define cases, run them, grade the outputs.
|
|
40
|
+
One dependency (pydantic). Python 3.10+.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install tinyevals
|
|
46
|
+
pip install "tinyevals[anthropic]" # optional: use Claude as an LLM judge
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quickstart
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from tinyevals import Case, exact_match, print_table, run
|
|
53
|
+
|
|
54
|
+
cases = [
|
|
55
|
+
Case(id="double-2", input=2, expected=4),
|
|
56
|
+
Case(id="double-3", input=3, expected=6),
|
|
57
|
+
Case(id="double-x", input="x", expected="xx"),
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
results = run(lambda x: x * 2, cases, exact_match)
|
|
61
|
+
print_table(results)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
id result score ms reason
|
|
66
|
+
double-2 PASS 1.00 0.0
|
|
67
|
+
double-3 PASS 1.00 0.0
|
|
68
|
+
double-x PASS 1.00 0.0
|
|
69
|
+
|
|
70
|
+
3/3 passed (100%), mean score 1.00
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Concepts
|
|
74
|
+
|
|
75
|
+
- **Case**: an `id`, an `input`, and optionally the `expected` output.
|
|
76
|
+
- **Grader**: a function `(case, output) -> Grade`. A `Grade` has `passed`, a `score` from 0 to 1,
|
|
77
|
+
and a `reason`.
|
|
78
|
+
- **run(system, cases, grader)**: calls `system(case.input)` for every case and grades the output.
|
|
79
|
+
Returns a list of `CaseResult` (case, output, grade, `duration_ms`).
|
|
80
|
+
|
|
81
|
+
## Graders
|
|
82
|
+
|
|
83
|
+
**`exact_match`**: passes when `output == expected`.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
run(my_fn, cases, exact_match)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**`numeric_close(tol)`**: passes when `abs(output - expected) <= tol`. Works with ints, floats and
|
|
90
|
+
numpy scalars. Anything else is a failed grade.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
run(estimate_ate, cases, numeric_close(0.10))
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**`contains(substring, case_sensitive=False)`**: passes when the output string contains `substring`.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
run(chatbot, cases, contains("paris"))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Your own grader**: any function with the same signature works.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from tinyevals import Case, Grade
|
|
106
|
+
|
|
107
|
+
def short_answer(case: Case, output: str) -> Grade:
|
|
108
|
+
ok = len(output) <= 100
|
|
109
|
+
return Grade(passed=ok, score=1.0 if ok else 0.0, reason="" if ok else "too long")
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## LLM judge
|
|
113
|
+
|
|
114
|
+
`llm_judge(rubric, judge, pass_threshold=0.7)` asks a model to score each output against a rubric.
|
|
115
|
+
`judge` is any function `str -> str`, so any provider works. The model must reply with
|
|
116
|
+
`{"score": 0-1, "reason": "..."}`. Markdown code fences around the JSON are fine.
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from tinyevals import Case, llm_judge, print_table, run
|
|
120
|
+
from tinyevals.adapters.anthropic import anthropic_judge # pip install "tinyevals[anthropic]"
|
|
121
|
+
|
|
122
|
+
grader = llm_judge(
|
|
123
|
+
rubric="The answer is factually correct and directly answers the question.",
|
|
124
|
+
judge=anthropic_judge(model="claude-opus-5-5", max_tokens=1024),
|
|
125
|
+
)
|
|
126
|
+
cases = [Case(id="capital", input="What is the capital of Australia?", expected="Canberra")]
|
|
127
|
+
print_table(run(my_chatbot, cases, grader))
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Using another provider means writing a judge function yourself:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
def my_judge(prompt: str) -> str:
|
|
134
|
+
return some_client.generate(prompt).text
|
|
135
|
+
|
|
136
|
+
grader = llm_judge("Is the answer polite?", my_judge)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
If the judge raises, returns malformed JSON, or returns a score outside 0–1, the case fails with
|
|
140
|
+
reason `judge error: ...`. The run does not stop. See `examples/llm_judge.py`.
|
|
141
|
+
|
|
142
|
+
## Reports and files
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from tinyevals import load_cases, save_results, summarize
|
|
146
|
+
|
|
147
|
+
cases = load_cases("cases.jsonl") # one {"id", "input", "expected"?} object per line
|
|
148
|
+
results = run(my_fn, cases, exact_match)
|
|
149
|
+
save_results(results, "results.jsonl") # one CaseResult per line
|
|
150
|
+
|
|
151
|
+
s = summarize(results) # Summary(total, passed, pass_rate, mean_score, failures)
|
|
152
|
+
assert s.pass_rate >= 0.9, s.failures
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`load_cases` raises `ValueError("cases.jsonl:7: missing required field(s): id")` for a bad line,
|
|
156
|
+
naming the file and line number.
|
|
157
|
+
|
|
158
|
+
## Design choices
|
|
159
|
+
|
|
160
|
+
- **The judge is injected.** `llm_judge` takes a plain `str -> str` function instead of a client.
|
|
161
|
+
The core has no provider SDK, tests use fake judges and never call an API, and switching
|
|
162
|
+
providers means changing one argument.
|
|
163
|
+
- **Graders and the runner never raise because of a case.** If your system throws on case 37 of
|
|
164
|
+
500, case 37 fails with reason `error: <Type>: <message>` and the other 499 still run. The same
|
|
165
|
+
goes for broken graders, bad judge replies and outputs of the wrong type. Ctrl-C still stops
|
|
166
|
+
the run. Bad configuration (like `numeric_close(-1)`) raises straight away.
|
|
167
|
+
- **JSONL in and out.** One case or result per line, so files are easy to append to, stream, grep
|
|
168
|
+
and diff. A bad line gives an error with its line number.
|
|
169
|
+
- **Small, typed API.** Pydantic models, full type hints, `py.typed`, and checked with mypy
|
|
170
|
+
`--strict`.
|
|
171
|
+
|
|
172
|
+
## Development
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
pip install -e ".[dev]"
|
|
176
|
+
pytest -q && ruff check . && mypy src
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
MIT
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# tinyevals
|
|
2
|
+
|
|
3
|
+
[](https://github.com/shivshashaang/tinyevals/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/tinyevals/)
|
|
5
|
+
|
|
6
|
+
Small, typed evals for functions and LLMs: define cases, run them, grade the outputs.
|
|
7
|
+
One dependency (pydantic). Python 3.10+.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install tinyevals
|
|
13
|
+
pip install "tinyevals[anthropic]" # optional: use Claude as an LLM judge
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from tinyevals import Case, exact_match, print_table, run
|
|
20
|
+
|
|
21
|
+
cases = [
|
|
22
|
+
Case(id="double-2", input=2, expected=4),
|
|
23
|
+
Case(id="double-3", input=3, expected=6),
|
|
24
|
+
Case(id="double-x", input="x", expected="xx"),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
results = run(lambda x: x * 2, cases, exact_match)
|
|
28
|
+
print_table(results)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
id result score ms reason
|
|
33
|
+
double-2 PASS 1.00 0.0
|
|
34
|
+
double-3 PASS 1.00 0.0
|
|
35
|
+
double-x PASS 1.00 0.0
|
|
36
|
+
|
|
37
|
+
3/3 passed (100%), mean score 1.00
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Concepts
|
|
41
|
+
|
|
42
|
+
- **Case**: an `id`, an `input`, and optionally the `expected` output.
|
|
43
|
+
- **Grader**: a function `(case, output) -> Grade`. A `Grade` has `passed`, a `score` from 0 to 1,
|
|
44
|
+
and a `reason`.
|
|
45
|
+
- **run(system, cases, grader)**: calls `system(case.input)` for every case and grades the output.
|
|
46
|
+
Returns a list of `CaseResult` (case, output, grade, `duration_ms`).
|
|
47
|
+
|
|
48
|
+
## Graders
|
|
49
|
+
|
|
50
|
+
**`exact_match`**: passes when `output == expected`.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
run(my_fn, cases, exact_match)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**`numeric_close(tol)`**: passes when `abs(output - expected) <= tol`. Works with ints, floats and
|
|
57
|
+
numpy scalars. Anything else is a failed grade.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
run(estimate_ate, cases, numeric_close(0.10))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
**`contains(substring, case_sensitive=False)`**: passes when the output string contains `substring`.
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
run(chatbot, cases, contains("paris"))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**Your own grader**: any function with the same signature works.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from tinyevals import Case, Grade
|
|
73
|
+
|
|
74
|
+
def short_answer(case: Case, output: str) -> Grade:
|
|
75
|
+
ok = len(output) <= 100
|
|
76
|
+
return Grade(passed=ok, score=1.0 if ok else 0.0, reason="" if ok else "too long")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## LLM judge
|
|
80
|
+
|
|
81
|
+
`llm_judge(rubric, judge, pass_threshold=0.7)` asks a model to score each output against a rubric.
|
|
82
|
+
`judge` is any function `str -> str`, so any provider works. The model must reply with
|
|
83
|
+
`{"score": 0-1, "reason": "..."}`. Markdown code fences around the JSON are fine.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from tinyevals import Case, llm_judge, print_table, run
|
|
87
|
+
from tinyevals.adapters.anthropic import anthropic_judge # pip install "tinyevals[anthropic]"
|
|
88
|
+
|
|
89
|
+
grader = llm_judge(
|
|
90
|
+
rubric="The answer is factually correct and directly answers the question.",
|
|
91
|
+
judge=anthropic_judge(model="claude-opus-5-5", max_tokens=1024),
|
|
92
|
+
)
|
|
93
|
+
cases = [Case(id="capital", input="What is the capital of Australia?", expected="Canberra")]
|
|
94
|
+
print_table(run(my_chatbot, cases, grader))
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Using another provider means writing a judge function yourself:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
def my_judge(prompt: str) -> str:
|
|
101
|
+
return some_client.generate(prompt).text
|
|
102
|
+
|
|
103
|
+
grader = llm_judge("Is the answer polite?", my_judge)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
If the judge raises, returns malformed JSON, or returns a score outside 0–1, the case fails with
|
|
107
|
+
reason `judge error: ...`. The run does not stop. See `examples/llm_judge.py`.
|
|
108
|
+
|
|
109
|
+
## Reports and files
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from tinyevals import load_cases, save_results, summarize
|
|
113
|
+
|
|
114
|
+
cases = load_cases("cases.jsonl") # one {"id", "input", "expected"?} object per line
|
|
115
|
+
results = run(my_fn, cases, exact_match)
|
|
116
|
+
save_results(results, "results.jsonl") # one CaseResult per line
|
|
117
|
+
|
|
118
|
+
s = summarize(results) # Summary(total, passed, pass_rate, mean_score, failures)
|
|
119
|
+
assert s.pass_rate >= 0.9, s.failures
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`load_cases` raises `ValueError("cases.jsonl:7: missing required field(s): id")` for a bad line,
|
|
123
|
+
naming the file and line number.
|
|
124
|
+
|
|
125
|
+
## Design choices
|
|
126
|
+
|
|
127
|
+
- **The judge is injected.** `llm_judge` takes a plain `str -> str` function instead of a client.
|
|
128
|
+
The core has no provider SDK, tests use fake judges and never call an API, and switching
|
|
129
|
+
providers means changing one argument.
|
|
130
|
+
- **Graders and the runner never raise because of a case.** If your system throws on case 37 of
|
|
131
|
+
500, case 37 fails with reason `error: <Type>: <message>` and the other 499 still run. The same
|
|
132
|
+
goes for broken graders, bad judge replies and outputs of the wrong type. Ctrl-C still stops
|
|
133
|
+
the run. Bad configuration (like `numeric_close(-1)`) raises straight away.
|
|
134
|
+
- **JSONL in and out.** One case or result per line, so files are easy to append to, stream, grep
|
|
135
|
+
and diff. A bad line gives an error with its line number.
|
|
136
|
+
- **Small, typed API.** Pydantic models, full type hints, `py.typed`, and checked with mypy
|
|
137
|
+
`--strict`.
|
|
138
|
+
|
|
139
|
+
## Development
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
pip install -e ".[dev]"
|
|
143
|
+
pytest -q && ruff check . && mypy src
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Grade three short answers with Claude as the judge.
|
|
2
|
+
|
|
3
|
+
Needs: pip install "tinyevals[anthropic]" and ANTHROPIC_API_KEY set. This calls the API.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from tinyevals import Case, llm_judge, print_table, run
|
|
7
|
+
from tinyevals.adapters.anthropic import anthropic_judge
|
|
8
|
+
|
|
9
|
+
cases = [
|
|
10
|
+
Case(id="capital", input="What is the capital of Australia?", expected="Canberra"),
|
|
11
|
+
Case(
|
|
12
|
+
id="boiling",
|
|
13
|
+
input="At what temperature does water boil at sea level?",
|
|
14
|
+
expected="100 °C / 212 °F",
|
|
15
|
+
),
|
|
16
|
+
Case(id="photosynthesis", input="In one sentence, what is photosynthesis?"),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
# The "system" under test. Here it's canned answers; in real use it would call your model.
|
|
20
|
+
answers = {
|
|
21
|
+
"What is the capital of Australia?": "Sydney.",
|
|
22
|
+
"At what temperature does water boil at sea level?": "100 degrees Celsius.",
|
|
23
|
+
"In one sentence, what is photosynthesis?": "Plants use sunlight, water and CO2 to make glucose and release oxygen.",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
grader = llm_judge(
|
|
27
|
+
rubric="The answer is factually correct and directly answers the question.",
|
|
28
|
+
judge=anthropic_judge(model="claude-opus-5-5", max_tokens=1024),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def system(question: str) -> str:
|
|
34
|
+
return answers[question]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
print_table(run(system, cases, grader))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from tinyevals import Case, exact_match, print_table, run
|
|
2
|
+
|
|
3
|
+
cases = [
|
|
4
|
+
Case(id="double-2", input=2, expected=4),
|
|
5
|
+
Case(id="double-3", input=3, expected=6),
|
|
6
|
+
Case(id="double-x", input="x", expected="xx"),
|
|
7
|
+
]
|
|
8
|
+
|
|
9
|
+
results = run(lambda x: x * 2, cases, exact_match)
|
|
10
|
+
print_table(results)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tinyevals"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Small, typed evals for functions and LLMs: cases, graders, and a runner."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Shivshashaang Haribhaskar" }]
|
|
13
|
+
dependencies = ["pydantic>=2.11"]
|
|
14
|
+
keywords = ["evals", "llm", "testing", "llm-as-judge", "pydantic"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Software Development :: Testing",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
anthropic = ["anthropic>=0.51", "numpy"]
|
|
30
|
+
# Linters pinned so a new release can't turn CI red without a code change.
|
|
31
|
+
dev = ["pytest>=8", "ruff==0.17.6", "mypy==2.4.1", "anthropic>=0.51", "numpy"]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Repository = "https://github.com/shivshashaang/tinyevals"
|
|
35
|
+
Changelog = "https://github.com/shivshashaang/tinyevals/blob/main/CHANGELOG.md"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.version]
|
|
38
|
+
path = "src/tinyevals/__init__.py"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.sdist]
|
|
41
|
+
include = ["src", "tests", "examples", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.wheel]
|
|
44
|
+
packages = ["src/tinyevals"]
|
|
45
|
+
|
|
46
|
+
[tool.ruff]
|
|
47
|
+
line-length = 100
|
|
48
|
+
|
|
49
|
+
[tool.mypy]
|
|
50
|
+
strict = true
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""tinyevals: small, typed evals for functions and LLMs."""
|
|
2
|
+
|
|
3
|
+
from tinyevals.graders import contains, exact_match, numeric_close
|
|
4
|
+
from tinyevals.jsonl import load_cases, save_results
|
|
5
|
+
from tinyevals.judge import Judge, llm_judge
|
|
6
|
+
from tinyevals.models import Case, CaseResult, Grade
|
|
7
|
+
from tinyevals.report import Summary, print_table, summarize
|
|
8
|
+
from tinyevals.runner import Grader, run
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Case",
|
|
12
|
+
"CaseResult",
|
|
13
|
+
"Grade",
|
|
14
|
+
"Grader",
|
|
15
|
+
"Judge",
|
|
16
|
+
"Summary",
|
|
17
|
+
"contains",
|
|
18
|
+
"exact_match",
|
|
19
|
+
"llm_judge",
|
|
20
|
+
"load_cases",
|
|
21
|
+
"numeric_close",
|
|
22
|
+
"print_table",
|
|
23
|
+
"run",
|
|
24
|
+
"save_results",
|
|
25
|
+
"summarize",
|
|
26
|
+
]
|
|
27
|
+
__version__ = "0.1.0" # the single source of truth; pyproject reads it
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional adapters that turn a provider SDK into a `Judge` (str -> str)."""
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from tinyevals.judge import Judge
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def anthropic_judge(model: str, max_tokens: int = 300) -> Judge:
|
|
5
|
+
"""Return a `Judge` that sends each prompt to Claude and returns the reply text.
|
|
6
|
+
|
|
7
|
+
Needs the optional extra: `pip install "tinyevals[anthropic]"`. The client reads
|
|
8
|
+
credentials the usual way (e.g. `ANTHROPIC_API_KEY`). Models that think before
|
|
9
|
+
answering may need a larger `max_tokens`.
|
|
10
|
+
|
|
11
|
+
API errors and refusals raise inside the judge; `llm_judge` records them as a failed
|
|
12
|
+
Grade ("judge error: ..."), so a run never stops because of them.
|
|
13
|
+
"""
|
|
14
|
+
try:
|
|
15
|
+
import anthropic
|
|
16
|
+
except ImportError as exc:
|
|
17
|
+
raise ImportError(
|
|
18
|
+
"anthropic_judge needs the Anthropic SDK: pip install \"tinyevals[anthropic]\""
|
|
19
|
+
) from exc
|
|
20
|
+
|
|
21
|
+
client = anthropic.Anthropic()
|
|
22
|
+
|
|
23
|
+
def judge(prompt: str) -> str:
|
|
24
|
+
response = client.messages.create(
|
|
25
|
+
model=model,
|
|
26
|
+
max_tokens=max_tokens,
|
|
27
|
+
messages=[{"role": "user", "content": prompt}],
|
|
28
|
+
)
|
|
29
|
+
if response.stop_reason == "refusal":
|
|
30
|
+
raise RuntimeError(f"{model} refused to grade")
|
|
31
|
+
text = "".join(block.text for block in response.content if block.type == "text")
|
|
32
|
+
if not text and response.stop_reason == "max_tokens":
|
|
33
|
+
raise RuntimeError(f"no text before max_tokens={max_tokens}; raise max_tokens")
|
|
34
|
+
return text
|
|
35
|
+
|
|
36
|
+
return judge
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import numbers
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from tinyevals.models import Case, Grade
|
|
6
|
+
from tinyevals.runner import Grader
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _is_number(value: Any) -> bool:
|
|
10
|
+
# numbers.Real covers int, float, Fraction and numpy scalars (np.float32, np.int64).
|
|
11
|
+
# bool is a subclass of int, but True == 1 is almost never what an eval means.
|
|
12
|
+
return isinstance(value, numbers.Real) and not isinstance(value, bool)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _pass() -> Grade:
|
|
16
|
+
return Grade(passed=True, score=1.0)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _fail(reason: str) -> Grade:
|
|
20
|
+
return Grade(passed=False, score=0.0, reason=reason)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def exact_match(case: Case, output: Any) -> Grade:
|
|
24
|
+
"""Pass when the output equals the expected value exactly."""
|
|
25
|
+
try:
|
|
26
|
+
equal = bool(output == case.expected)
|
|
27
|
+
except Exception as exc: # noqa: BLE001 - e.g. numpy arrays have no single truth value
|
|
28
|
+
return _fail(f"cannot compare output with expected: {type(exc).__name__}: {exc}")
|
|
29
|
+
if equal:
|
|
30
|
+
return _pass()
|
|
31
|
+
return _fail(f"expected {case.expected!r}, got {output!r}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def numeric_close(tol: float) -> Grader:
|
|
35
|
+
"""Return a grader that passes when `abs(output - expected) <= tol`.
|
|
36
|
+
|
|
37
|
+
The boundary is inclusive and tolerant of float rounding, so `numeric_close(0.1)`
|
|
38
|
+
passes 1.1 against 1.0.
|
|
39
|
+
|
|
40
|
+
Fails (never raises) when the output or expected value is not an int or float.
|
|
41
|
+
"""
|
|
42
|
+
if not _is_number(tol) or math.isnan(tol) or tol < 0:
|
|
43
|
+
raise ValueError(f"tol must be a non-negative number, got {tol!r}")
|
|
44
|
+
|
|
45
|
+
def grade(case: Case, output: Any) -> Grade:
|
|
46
|
+
if not _is_number(output):
|
|
47
|
+
return _fail(f"output is not a number: {output!r}")
|
|
48
|
+
if not _is_number(case.expected):
|
|
49
|
+
return _fail(f"expected value is not a number: {case.expected!r}")
|
|
50
|
+
try:
|
|
51
|
+
diff = abs(float(output) - float(case.expected))
|
|
52
|
+
except OverflowError:
|
|
53
|
+
return _fail(f"number too large to compare: {output!r} vs {case.expected!r}")
|
|
54
|
+
# isclose absorbs float noise on the boundary: abs(1.1 - 1.0) is 0.10000000000000009.
|
|
55
|
+
if diff <= tol or math.isclose(diff, tol):
|
|
56
|
+
return _pass()
|
|
57
|
+
return _fail(f"expected {case.expected!r} +/- {tol}, got {output!r} (off by {diff:g})")
|
|
58
|
+
|
|
59
|
+
return grade
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def contains(substring: str, case_sensitive: bool = False) -> Grader:
|
|
63
|
+
"""Return a grader that passes when the output string contains `substring`.
|
|
64
|
+
|
|
65
|
+
Fails (never raises) when the output is not a string.
|
|
66
|
+
"""
|
|
67
|
+
if not isinstance(substring, str):
|
|
68
|
+
raise TypeError(f"substring must be a str, got {type(substring).__name__}")
|
|
69
|
+
needle = substring if case_sensitive else substring.casefold()
|
|
70
|
+
|
|
71
|
+
def grade(case: Case, output: Any) -> Grade:
|
|
72
|
+
if not isinstance(output, str):
|
|
73
|
+
return _fail(f"output is not a string: {output!r}")
|
|
74
|
+
haystack = output if case_sensitive else output.casefold()
|
|
75
|
+
if needle in haystack:
|
|
76
|
+
return _pass()
|
|
77
|
+
return _fail(f"{substring!r} not found in output")
|
|
78
|
+
|
|
79
|
+
return grade
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from pydantic import ValidationError
|
|
7
|
+
|
|
8
|
+
from tinyevals.models import Case, CaseResult
|
|
9
|
+
|
|
10
|
+
StrPath = str | os.PathLike[str]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_cases(path: StrPath) -> list[Case]:
|
|
14
|
+
"""Read cases from a JSONL file: one JSON object per line, blank lines skipped.
|
|
15
|
+
|
|
16
|
+
Each object needs `id` (string) and `input`; `expected` is optional. Ids must be unique.
|
|
17
|
+
Raises ValueError naming the line number when a line is malformed.
|
|
18
|
+
"""
|
|
19
|
+
cases = []
|
|
20
|
+
first_seen: dict[str, int] = {}
|
|
21
|
+
# utf-8-sig also reads files saved "UTF-8 with BOM", e.g. by Windows Notepad.
|
|
22
|
+
with Path(path).open(encoding="utf-8-sig") as f:
|
|
23
|
+
for lineno, line in enumerate(f, start=1):
|
|
24
|
+
if not line.strip():
|
|
25
|
+
continue
|
|
26
|
+
try:
|
|
27
|
+
data = json.loads(line)
|
|
28
|
+
except json.JSONDecodeError as exc:
|
|
29
|
+
raise ValueError(f"{path}:{lineno}: invalid JSON: {exc.msg}") from exc
|
|
30
|
+
if not isinstance(data, dict):
|
|
31
|
+
# ValueError, not TypeError: callers catch one error type for any bad line.
|
|
32
|
+
raise ValueError( # noqa: TRY004
|
|
33
|
+
f"{path}:{lineno}: expected a JSON object, got {type(data).__name__}"
|
|
34
|
+
)
|
|
35
|
+
missing = [key for key in ("id", "input") if key not in data]
|
|
36
|
+
if missing:
|
|
37
|
+
raise ValueError(f"{path}:{lineno}: missing required field(s): {', '.join(missing)}")
|
|
38
|
+
try:
|
|
39
|
+
case = Case.model_validate(data)
|
|
40
|
+
except ValidationError as exc:
|
|
41
|
+
problems = "; ".join(
|
|
42
|
+
f"{'.'.join(str(p) for p in err['loc'])}: {err['msg']}" for err in exc.errors()
|
|
43
|
+
)
|
|
44
|
+
raise ValueError(f"{path}:{lineno}: invalid case: {problems}") from exc
|
|
45
|
+
if case.id in first_seen:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"{path}:{lineno}: duplicate id {case.id!r} (first on line {first_seen[case.id]})"
|
|
48
|
+
)
|
|
49
|
+
first_seen[case.id] = lineno
|
|
50
|
+
cases.append(case)
|
|
51
|
+
return cases
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def save_results(results: Iterable[CaseResult], path: StrPath) -> None:
|
|
55
|
+
"""Write one JSON object per result. Values JSON can't encode are written as their repr()."""
|
|
56
|
+
with Path(path).open("w", encoding="utf-8") as f:
|
|
57
|
+
f.writelines(result.model_dump_json(fallback=repr) + "\n" for result in results)
|