diffscore 0.1.0__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.
- diffscore/__init__.py +3 -0
- diffscore/api.py +729 -0
- diffscore/calibration.py +374 -0
- diffscore/cli.py +867 -0
- diffscore/config.py +88 -0
- diffscore/db/__init__.py +27 -0
- diffscore/db/base.py +25 -0
- diffscore/db/migrate.py +61 -0
- diffscore/db/models.py +257 -0
- diffscore/db/session.py +37 -0
- diffscore/diffing.py +292 -0
- diffscore/graders.py +281 -0
- diffscore/jobs.py +161 -0
- diffscore/judge.py +355 -0
- diffscore/labeling.py +167 -0
- diffscore/llm.py +120 -0
- diffscore/migrations/README +1 -0
- diffscore/migrations/env.py +84 -0
- diffscore/migrations/script.py.mako +28 -0
- diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
- diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
- diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
- diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
- diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
- diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
- diffscore/queries.py +165 -0
- diffscore/runner.py +393 -0
- diffscore/secrets.py +130 -0
- diffscore/stats.py +83 -0
- diffscore/suite.py +329 -0
- diffscore/templates/env.example +14 -0
- diffscore/templates/example-prompt.md +14 -0
- diffscore/templates/example.yaml +75 -0
- diffscore-0.1.0.dist-info/METADATA +351 -0
- diffscore-0.1.0.dist-info/RECORD +38 -0
- diffscore-0.1.0.dist-info/WHEEL +4 -0
- diffscore-0.1.0.dist-info/entry_points.txt +2 -0
- diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/secrets.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Users' provider keys: encrypted at rest, never logged, never returned.
|
|
2
|
+
|
|
3
|
+
A portfolio project that leaks keys is worse than no project, so the rules are
|
|
4
|
+
enforced in one place:
|
|
5
|
+
|
|
6
|
+
- Keys are stored only as Fernet ciphertext (`project.provider_keys_encrypted`),
|
|
7
|
+
with the Fernet key held in the environment (FERNET_KEY), never in the DB.
|
|
8
|
+
- The API only ever reports which providers have a key, never a key.
|
|
9
|
+
- `Redactor` scrubs anything key-shaped from log records and Sentry events.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from cryptography.fernet import Fernet, InvalidToken
|
|
20
|
+
|
|
21
|
+
from diffscore.config import get_settings
|
|
22
|
+
|
|
23
|
+
# Providers we accept keys for, and the LiteLLM model prefixes they serve.
|
|
24
|
+
PROVIDERS: dict[str, tuple[str, ...]] = {
|
|
25
|
+
"gemini": ("gemini/",),
|
|
26
|
+
"openai": ("openai/", "gpt-", "o1", "o3", "o4"),
|
|
27
|
+
"anthropic": ("anthropic/", "claude-"),
|
|
28
|
+
"groq": ("groq/",),
|
|
29
|
+
"openrouter": ("openrouter/",),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SecretsError(ValueError):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _fernet() -> Fernet:
|
|
38
|
+
key = get_settings().fernet_key
|
|
39
|
+
if key is None or not key.get_secret_value():
|
|
40
|
+
raise SecretsError(
|
|
41
|
+
"FERNET_KEY is not set, so provider keys cannot be stored. Generate one with "
|
|
42
|
+
"`diffscore genkey`"
|
|
43
|
+
)
|
|
44
|
+
try:
|
|
45
|
+
return Fernet(key.get_secret_value().encode())
|
|
46
|
+
except ValueError as exc:
|
|
47
|
+
raise SecretsError("FERNET_KEY is not a valid Fernet key") from exc
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def encrypt_keys(keys: dict[str, str]) -> bytes:
|
|
51
|
+
unknown = set(keys) - set(PROVIDERS)
|
|
52
|
+
if unknown:
|
|
53
|
+
raise SecretsError(f"unknown provider(s) {sorted(unknown)}; use {sorted(PROVIDERS)}")
|
|
54
|
+
return _fernet().encrypt(json.dumps(keys).encode())
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def decrypt_keys(blob: bytes | None) -> dict[str, str]:
|
|
58
|
+
if not blob:
|
|
59
|
+
return {}
|
|
60
|
+
try:
|
|
61
|
+
data = json.loads(_fernet().decrypt(blob))
|
|
62
|
+
except InvalidToken as exc:
|
|
63
|
+
raise SecretsError("stored provider keys cannot be decrypted with this FERNET_KEY") from exc
|
|
64
|
+
return {str(k): str(v) for k, v in data.items()}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def provider_for(model: str) -> str | None:
|
|
68
|
+
lowered = model.lower()
|
|
69
|
+
for provider, prefixes in PROVIDERS.items():
|
|
70
|
+
if lowered.startswith(prefixes):
|
|
71
|
+
return provider
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ------------------------------------------------------------------ redaction
|
|
76
|
+
|
|
77
|
+
# Shapes of real provider keys. Over-matching is fine; leaking is not.
|
|
78
|
+
_KEY_SHAPES = re.compile(
|
|
79
|
+
r"(AIza[0-9A-Za-z_\-]{20,}|AQ\.[0-9A-Za-z_\-]{20,}|sk-[0-9A-Za-z_\-]{16,}"
|
|
80
|
+
r"|gsk_[0-9A-Za-z]{16,}|sk-ant-[0-9A-Za-z_\-]{16,}|gh[opsu]_[0-9A-Za-z]{20,})"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def redact(text: str, extra: tuple[str, ...] = ()) -> str:
|
|
85
|
+
for secret in extra:
|
|
86
|
+
if secret:
|
|
87
|
+
text = text.replace(secret, "[redacted]")
|
|
88
|
+
return _KEY_SHAPES.sub("[redacted]", text)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Redactor(logging.Filter):
|
|
92
|
+
"""Logging filter that scrubs key-shaped strings from every record."""
|
|
93
|
+
|
|
94
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
95
|
+
record.msg = redact(str(record.getMessage()))
|
|
96
|
+
record.args = None
|
|
97
|
+
return True
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def install_log_redaction() -> None:
|
|
101
|
+
root = logging.getLogger()
|
|
102
|
+
if not any(isinstance(f, Redactor) for f in root.filters):
|
|
103
|
+
root.addFilter(Redactor())
|
|
104
|
+
for handler in root.handlers:
|
|
105
|
+
if not any(isinstance(f, Redactor) for f in handler.filters):
|
|
106
|
+
handler.addFilter(Redactor())
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def scrub_event(event: Any, _hint: Any = None) -> Any:
|
|
110
|
+
"""Sentry `before_send`: redact keys anywhere in the event."""
|
|
111
|
+
if isinstance(event, dict):
|
|
112
|
+
return {k: scrub_event(v) for k, v in event.items()}
|
|
113
|
+
if isinstance(event, list):
|
|
114
|
+
return [scrub_event(v) for v in event]
|
|
115
|
+
if isinstance(event, str):
|
|
116
|
+
return redact(event)
|
|
117
|
+
return event
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def init_sentry() -> None:
|
|
121
|
+
dsn = get_settings().sentry_dsn
|
|
122
|
+
if dsn is None or not dsn.get_secret_value():
|
|
123
|
+
return
|
|
124
|
+
import sentry_sdk
|
|
125
|
+
|
|
126
|
+
sentry_sdk.init(
|
|
127
|
+
dsn=dsn.get_secret_value(),
|
|
128
|
+
before_send=scrub_event,
|
|
129
|
+
traces_sample_rate=0.0,
|
|
130
|
+
)
|
diffscore/stats.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""The two statistical tests behind a verdict. Neither is hand-rolled.
|
|
2
|
+
|
|
3
|
+
Both runs grade the same cases, so the comparison is *paired*:
|
|
4
|
+
|
|
5
|
+
- **McNemar's test** on the pass/fail flips. Only discordant cases carry
|
|
6
|
+
information: pass->fail (regressed) and fail->pass (improved). With fewer
|
|
7
|
+
than 25 of them the exact binomial version is used; the chi-square
|
|
8
|
+
approximation is unreliable at small counts.
|
|
9
|
+
- **A paired bootstrap** of the mean score delta, for graders whose scores are
|
|
10
|
+
not just 0/1 (partial `contains` matches today, the LLM judge in Phase 4).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
EXACT_BELOW = 25
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class McNemar:
|
|
25
|
+
p_value: float
|
|
26
|
+
method: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def mcnemar_test(regressed: int, improved: int) -> McNemar:
|
|
30
|
+
"""Two-sided McNemar test on the discordant pair counts."""
|
|
31
|
+
if regressed < 0 or improved < 0:
|
|
32
|
+
raise ValueError("counts must be non-negative")
|
|
33
|
+
discordant = regressed + improved
|
|
34
|
+
if discordant == 0:
|
|
35
|
+
return McNemar(1.0, "no cases changed")
|
|
36
|
+
|
|
37
|
+
from statsmodels.stats.contingency_tables import mcnemar # slow import
|
|
38
|
+
|
|
39
|
+
exact = discordant < EXACT_BELOW
|
|
40
|
+
# Only the off-diagonal cells enter the statistic; the diagonal is irrelevant.
|
|
41
|
+
result = mcnemar([[0, regressed], [improved, 0]], exact=exact, correction=True)
|
|
42
|
+
method = "McNemar exact" if exact else "McNemar chi-square, continuity-corrected"
|
|
43
|
+
return McNemar(float(min(1.0, result.pvalue)), method)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Interval:
|
|
48
|
+
mean: float
|
|
49
|
+
low: float
|
|
50
|
+
high: float
|
|
51
|
+
level: float
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def excludes_zero(self) -> bool:
|
|
55
|
+
return self.low > 0 or self.high < 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def bootstrap_mean_ci(
|
|
59
|
+
deltas: Sequence[float],
|
|
60
|
+
*,
|
|
61
|
+
level: float = 0.95,
|
|
62
|
+
resamples: int = 10_000,
|
|
63
|
+
seed: int = 0,
|
|
64
|
+
) -> Interval | None:
|
|
65
|
+
"""Percentile bootstrap CI for the mean of paired score deltas.
|
|
66
|
+
|
|
67
|
+
Seeded, so the same two runs always print the same interval.
|
|
68
|
+
"""
|
|
69
|
+
if not deltas:
|
|
70
|
+
return None
|
|
71
|
+
values = np.asarray(deltas, dtype=float)
|
|
72
|
+
rng = np.random.default_rng(seed)
|
|
73
|
+
picks = rng.integers(0, len(values), size=(resamples, len(values)))
|
|
74
|
+
means = values[picks].mean(axis=1)
|
|
75
|
+
tail = (1 - level) / 2
|
|
76
|
+
low, high = np.quantile(means, [tail, 1 - tail])
|
|
77
|
+
return Interval(float(values.mean()), float(low), float(high), level)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def format_p(p: float) -> str:
|
|
81
|
+
if p < 0.001:
|
|
82
|
+
return "p < 0.001"
|
|
83
|
+
return f"p = {p:.3f}" if p < 0.01 else f"p = {p:.2f}"
|
diffscore/suite.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Suite files: schema, loading and prompt rendering.
|
|
2
|
+
|
|
3
|
+
A suite is YAML:
|
|
4
|
+
|
|
5
|
+
name: support
|
|
6
|
+
model: gemini/gemini-3.5-flash-lite
|
|
7
|
+
prompt_file: prompts/support.md # or `prompt: |` inline; may use {{vars}}
|
|
8
|
+
user_template: "{{input}}" # the user message; this is the default
|
|
9
|
+
params: {temperature: 0}
|
|
10
|
+
graders: # applied to every case
|
|
11
|
+
- not_contains: "**"
|
|
12
|
+
cases:
|
|
13
|
+
- id: refund-window
|
|
14
|
+
input: How long do I have to return something?
|
|
15
|
+
graders:
|
|
16
|
+
- regex: '30[- ]days?'
|
|
17
|
+
|
|
18
|
+
Validation errors name the case and the field, never just "ValidationError".
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import difflib
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import yaml
|
|
31
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
32
|
+
|
|
33
|
+
from diffscore import judge as _judge
|
|
34
|
+
from diffscore.graders import REGISTRY, GraderConfigError, build
|
|
35
|
+
from diffscore.llm import Message
|
|
36
|
+
|
|
37
|
+
_VAR = re.compile(r"\{\{\s*(\w+)\s*\}\}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SuiteError(Exception):
|
|
41
|
+
"""A suite file that cannot be used. `problems` is one line per issue."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, path: Path | str, problems: list[str]) -> None:
|
|
44
|
+
self.path = str(path)
|
|
45
|
+
self.problems = problems
|
|
46
|
+
super().__init__(f"{path}: " + "; ".join(problems))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ------------------------------------------------------------------ schema
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class GraderSpec(BaseModel):
|
|
53
|
+
"""One grader reference: `- contains: refund` or a bare `- equals`."""
|
|
54
|
+
|
|
55
|
+
model_config = ConfigDict(frozen=True)
|
|
56
|
+
|
|
57
|
+
name: str
|
|
58
|
+
arg: Any = None
|
|
59
|
+
|
|
60
|
+
@model_validator(mode="before")
|
|
61
|
+
@classmethod
|
|
62
|
+
def _from_yaml(cls, raw: Any) -> Any:
|
|
63
|
+
if isinstance(raw, str):
|
|
64
|
+
return {"name": raw, "arg": None}
|
|
65
|
+
if isinstance(raw, dict) and set(raw) != {"name", "arg"}:
|
|
66
|
+
if len(raw) != 1:
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"a grader is one `name: config` pair, got keys {sorted(map(str, raw))}"
|
|
69
|
+
)
|
|
70
|
+
((name, arg),) = raw.items()
|
|
71
|
+
return {"name": name, "arg": arg}
|
|
72
|
+
return raw
|
|
73
|
+
|
|
74
|
+
@model_validator(mode="after")
|
|
75
|
+
def _buildable(self) -> GraderSpec:
|
|
76
|
+
if self.name not in REGISTRY:
|
|
77
|
+
close = difflib.get_close_matches(self.name, REGISTRY, n=1)
|
|
78
|
+
hint = f"; did you mean {close[0]!r}?" if close else ""
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"unknown grader {self.name!r}{hint} (available: {', '.join(sorted(REGISTRY))})"
|
|
81
|
+
)
|
|
82
|
+
try:
|
|
83
|
+
build(self.name, self.arg)
|
|
84
|
+
except GraderConfigError as exc:
|
|
85
|
+
raise ValueError(str(exc)) from exc
|
|
86
|
+
return self
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def version(self) -> str:
|
|
90
|
+
"""Registry version; for the judge, plus a fingerprint of rubric and model,
|
|
91
|
+
so a grade always says which rubric produced it."""
|
|
92
|
+
base = REGISTRY[self.name].version
|
|
93
|
+
if self.name == "judge":
|
|
94
|
+
return f"{base}-{_judge.parse_config(self.arg).fingerprint()}"
|
|
95
|
+
return base
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def display_name(self) -> str:
|
|
99
|
+
"""`judge:tone` for a named judge, so two judges in one suite stay apart."""
|
|
100
|
+
if self.name == "judge" and isinstance(self.arg, dict) and self.arg.get("name"):
|
|
101
|
+
return f"judge:{self.arg['name']}"
|
|
102
|
+
return self.name
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class CaseSpec(BaseModel):
|
|
106
|
+
model_config = ConfigDict(extra="forbid")
|
|
107
|
+
|
|
108
|
+
id: str = Field(min_length=1, max_length=200)
|
|
109
|
+
input: str | dict[str, Any]
|
|
110
|
+
expect: str | None = None
|
|
111
|
+
graders: list[GraderSpec] = Field(default_factory=list)
|
|
112
|
+
|
|
113
|
+
@field_validator("id", mode="before")
|
|
114
|
+
@classmethod
|
|
115
|
+
def _id_as_text(cls, v: Any) -> Any:
|
|
116
|
+
return str(v) if isinstance(v, int) else v
|
|
117
|
+
|
|
118
|
+
def variables(self) -> dict[str, str]:
|
|
119
|
+
if isinstance(self.input, str):
|
|
120
|
+
return {"input": self.input}
|
|
121
|
+
return {k: _as_text(v) for k, v in self.input.items()}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _as_text(value: Any) -> str:
|
|
125
|
+
"""A template value as text. A list of strings (e.g. retrieved chunks) is
|
|
126
|
+
joined with blank lines, the way a RAG pipeline concatenates them."""
|
|
127
|
+
if isinstance(value, str):
|
|
128
|
+
return value
|
|
129
|
+
if isinstance(value, list) and all(isinstance(v, str) for v in value):
|
|
130
|
+
return "\n\n".join(value)
|
|
131
|
+
return json.dumps(value, ensure_ascii=False)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class SuiteFile(BaseModel):
|
|
135
|
+
model_config = ConfigDict(extra="forbid")
|
|
136
|
+
|
|
137
|
+
name: str = Field(min_length=1, max_length=200)
|
|
138
|
+
project: str = Field(default="default", min_length=1, max_length=200)
|
|
139
|
+
model: str | None = None
|
|
140
|
+
prompt: str = Field(min_length=1)
|
|
141
|
+
user_template: str = Field(default="{{input}}", min_length=1)
|
|
142
|
+
params: dict[str, Any] = Field(default_factory=dict)
|
|
143
|
+
graders: list[GraderSpec] = Field(default_factory=list)
|
|
144
|
+
cases: list[CaseSpec] = Field(min_length=1)
|
|
145
|
+
|
|
146
|
+
@model_validator(mode="after")
|
|
147
|
+
def _cross_checks(self) -> SuiteFile:
|
|
148
|
+
problems: list[str] = []
|
|
149
|
+
|
|
150
|
+
seen: set[str] = set()
|
|
151
|
+
for case in self.cases:
|
|
152
|
+
if case.id in seen:
|
|
153
|
+
problems.append(f"case id {case.id!r} is used more than once")
|
|
154
|
+
seen.add(case.id)
|
|
155
|
+
|
|
156
|
+
needed = set(_VAR.findall(self.prompt)) | set(_VAR.findall(self.user_template))
|
|
157
|
+
for case in self.cases:
|
|
158
|
+
missing = needed - set(case.variables())
|
|
159
|
+
if missing:
|
|
160
|
+
have = sorted(case.variables())
|
|
161
|
+
problems.append(
|
|
162
|
+
f"case {case.id!r}: template variable(s) {sorted(missing)} not in its "
|
|
163
|
+
f"input (it has {have}); set `user_template` or rename the input keys"
|
|
164
|
+
)
|
|
165
|
+
if case.expect is None and any(
|
|
166
|
+
g.name == "equals" and g.arg is None for g in self.graders_for(case)
|
|
167
|
+
):
|
|
168
|
+
problems.append(f"case {case.id!r}: `equals` with no value needs `expect`")
|
|
169
|
+
|
|
170
|
+
if problems:
|
|
171
|
+
raise ValueError("\n".join(problems))
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
def graders_for(self, case: CaseSpec) -> list[GraderSpec]:
|
|
175
|
+
"""Suite-level graders first, then the case's own."""
|
|
176
|
+
return [*self.graders, *case.graders]
|
|
177
|
+
|
|
178
|
+
def all_graders(self) -> list[GraderSpec]:
|
|
179
|
+
"""Every distinct grader in the suite, by display name, in first-seen order."""
|
|
180
|
+
seen: dict[str, GraderSpec] = {}
|
|
181
|
+
for g in [*self.graders, *(g for c in self.cases for g in c.graders)]:
|
|
182
|
+
seen.setdefault(g.display_name, g)
|
|
183
|
+
return list(seen.values())
|
|
184
|
+
|
|
185
|
+
def messages_for(self, case: CaseSpec) -> list[Message]:
|
|
186
|
+
values = case.variables()
|
|
187
|
+
return [
|
|
188
|
+
{"role": "system", "content": render(self.prompt, values)},
|
|
189
|
+
{"role": "user", "content": render(self.user_template, values)},
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def render(template: str, values: dict[str, str]) -> str:
|
|
194
|
+
"""Replace `{{name}}`. Unknown names are left as-is (validation catches them)."""
|
|
195
|
+
return _VAR.sub(lambda m: values.get(m.group(1), m.group(0)), template)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# ------------------------------------------------------------------ loading
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@dataclass(frozen=True)
|
|
202
|
+
class LoadedSuite:
|
|
203
|
+
spec: SuiteFile
|
|
204
|
+
path: Path
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def load_suite(path: str | Path) -> LoadedSuite:
|
|
208
|
+
"""Load a suite file from disk. `prompt_file` and `context_file` resolve beside it."""
|
|
209
|
+
path = Path(path)
|
|
210
|
+
try:
|
|
211
|
+
text = path.read_text(encoding="utf-8")
|
|
212
|
+
except OSError as exc:
|
|
213
|
+
raise SuiteError(path, [f"cannot read file: {exc.strerror or exc}"]) from exc
|
|
214
|
+
return LoadedSuite(spec=_build(text, path, base=path.parent), path=path)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def load_suite_text(text: str, source: str = "suite") -> SuiteFile:
|
|
218
|
+
"""Load a suite sent as text (e.g. over the API).
|
|
219
|
+
|
|
220
|
+
File references are refused: a submitted suite must never be able to read
|
|
221
|
+
files on the server, so the prompt and any judge context must be inline.
|
|
222
|
+
"""
|
|
223
|
+
return _build(text, source, base=None)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _build(text: str, label: str | Path, base: Path | None) -> SuiteFile:
|
|
227
|
+
try:
|
|
228
|
+
raw = yaml.safe_load(text)
|
|
229
|
+
except yaml.YAMLError as exc:
|
|
230
|
+
mark = getattr(exc, "problem_mark", None)
|
|
231
|
+
where = f"line {mark.line + 1}, column {mark.column + 1}: " if mark else ""
|
|
232
|
+
problem = getattr(exc, "problem", None) or str(exc)
|
|
233
|
+
raise SuiteError(label, [f"invalid YAML at {where}{problem}"]) from exc
|
|
234
|
+
|
|
235
|
+
if not isinstance(raw, dict):
|
|
236
|
+
raise SuiteError(label, ["top level must be a mapping with `name`, `prompt` and `cases`"])
|
|
237
|
+
|
|
238
|
+
# `x-` keys are free space for YAML anchors (shared documents, rubrics) that
|
|
239
|
+
# cases reference with `*name`, as in docker-compose. They are not suite fields.
|
|
240
|
+
raw = {k: v for k, v in raw.items() if not str(k).startswith("x-")}
|
|
241
|
+
|
|
242
|
+
if base is None:
|
|
243
|
+
if "prompt_file" in raw or _has_context_file(raw):
|
|
244
|
+
raise SuiteError(
|
|
245
|
+
label,
|
|
246
|
+
[
|
|
247
|
+
"file references (prompt_file, context_file) aren't allowed here; "
|
|
248
|
+
"put the prompt and any judge context inline"
|
|
249
|
+
],
|
|
250
|
+
)
|
|
251
|
+
else:
|
|
252
|
+
try:
|
|
253
|
+
_inline_judge_context(raw, base)
|
|
254
|
+
except OSError as exc:
|
|
255
|
+
raise SuiteError(
|
|
256
|
+
label, [f"judge context_file: {exc.strerror or exc}: {exc.filename}"]
|
|
257
|
+
) from exc
|
|
258
|
+
|
|
259
|
+
if "prompt_file" in raw:
|
|
260
|
+
if "prompt" in raw:
|
|
261
|
+
raise SuiteError(label, ["set either `prompt` or `prompt_file`, not both"])
|
|
262
|
+
prompt_path = base / str(raw.pop("prompt_file"))
|
|
263
|
+
try:
|
|
264
|
+
raw["prompt"] = prompt_path.read_text(encoding="utf-8")
|
|
265
|
+
except OSError as exc:
|
|
266
|
+
raise SuiteError(
|
|
267
|
+
label, [f"prompt_file: cannot read {prompt_path}: {exc.strerror or exc}"]
|
|
268
|
+
) from exc
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
return SuiteFile.model_validate(raw)
|
|
272
|
+
except ValidationError as exc:
|
|
273
|
+
raise SuiteError(label, _explain(exc, raw)) from exc
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _judge_configs(raw: dict[str, Any]) -> list[dict[str, Any]]:
|
|
277
|
+
lists = [raw.get("graders")]
|
|
278
|
+
lists += [c.get("graders") for c in raw.get("cases") or [] if isinstance(c, dict)]
|
|
279
|
+
found = []
|
|
280
|
+
for graders in lists:
|
|
281
|
+
for item in graders if isinstance(graders, list) else []:
|
|
282
|
+
cfg = item.get("judge") if isinstance(item, dict) else None
|
|
283
|
+
if isinstance(cfg, dict):
|
|
284
|
+
found.append(cfg)
|
|
285
|
+
return found
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _has_context_file(raw: dict[str, Any]) -> bool:
|
|
289
|
+
return any("context_file" in cfg for cfg in _judge_configs(raw))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _explain(exc: ValidationError, raw: dict[str, Any]) -> list[str]:
|
|
293
|
+
"""Turn Pydantic's locations into `case 'refund-04' > graders[0]: ...`."""
|
|
294
|
+
lines: list[str] = []
|
|
295
|
+
cases_value = raw.get("cases")
|
|
296
|
+
raw_cases: list[Any] = cases_value if isinstance(cases_value, list) else []
|
|
297
|
+
for err in exc.errors():
|
|
298
|
+
loc = list(err["loc"])
|
|
299
|
+
msg = str(err["msg"]).removeprefix("Value error, ")
|
|
300
|
+
prefix = ""
|
|
301
|
+
if len(loc) >= 2 and loc[0] == "cases" and isinstance(loc[1], int):
|
|
302
|
+
i = loc[1]
|
|
303
|
+
case = raw_cases[i] if i < len(raw_cases) else None
|
|
304
|
+
case_id = case.get("id") if isinstance(case, dict) else None
|
|
305
|
+
prefix = f"case {case_id!r} (cases[{i}])" if case_id else f"cases[{i}]"
|
|
306
|
+
loc = loc[2:]
|
|
307
|
+
field = _path(loc)
|
|
308
|
+
where = " > ".join(p for p in (prefix, field) if p)
|
|
309
|
+
lines.extend(f"{where}: {m}" if where else m for m in msg.splitlines())
|
|
310
|
+
return lines
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _path(loc: list[Any]) -> str:
|
|
314
|
+
out = ""
|
|
315
|
+
for part in loc:
|
|
316
|
+
if isinstance(part, int):
|
|
317
|
+
out += f"[{part}]"
|
|
318
|
+
elif part in {"function-after[_buildable(), GraderSpec]", "GraderSpec"}:
|
|
319
|
+
continue
|
|
320
|
+
else:
|
|
321
|
+
out += f".{part}" if out else str(part)
|
|
322
|
+
return out
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _inline_judge_context(raw: dict[str, Any], base: Path) -> None:
|
|
326
|
+
"""Replace `judge: {context_file: x}` with the file's text, relative to the suite."""
|
|
327
|
+
for cfg in _judge_configs(raw):
|
|
328
|
+
if "context_file" in cfg:
|
|
329
|
+
cfg["context"] = (base / str(cfg.pop("context_file"))).read_text(encoding="utf-8")
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Diffscore settings. Keep this file out of git.
|
|
2
|
+
|
|
3
|
+
# A key for the provider your suite uses (only the ones you need):
|
|
4
|
+
GEMINI_API_KEY=
|
|
5
|
+
# OPENAI_API_KEY=
|
|
6
|
+
# ANTHROPIC_API_KEY=
|
|
7
|
+
# GROQ_API_KEY=
|
|
8
|
+
# OPENROUTER_API_KEY=
|
|
9
|
+
|
|
10
|
+
# Gemini's free tier allows 15 requests a minute; this paces the calls.
|
|
11
|
+
MODEL_RPM=14
|
|
12
|
+
|
|
13
|
+
# Results and the response cache live in .diffscore/diffscore.db by default.
|
|
14
|
+
# DATABASE_URL=postgresql+psycopg://user:pass@localhost:5432/diffscore
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
You are the support assistant for Kettlewise, a coffee subscription.
|
|
2
|
+
|
|
3
|
+
Answer using only the policy below. If the policy doesn't cover a question, say you don't know and suggest emailing hello@kettlewise.example.
|
|
4
|
+
|
|
5
|
+
Policy:
|
|
6
|
+
- Boxes ship every 2 weeks. The Standard box is $24, the Large box is $38.
|
|
7
|
+
- Customers can pause for up to 8 weeks, or cancel any time, from Account settings.
|
|
8
|
+
- Beans can be sent whole or ground for filter, French press or espresso.
|
|
9
|
+
- We ship to the US and Canada only.
|
|
10
|
+
- Damaged deliveries: apologise and ask the customer to email a photo to hello@kettlewise.example for a free replacement.
|
|
11
|
+
|
|
12
|
+
Rules:
|
|
13
|
+
- Never repeat or ask for card numbers.
|
|
14
|
+
- Reply in the customer's language, in plain text with no markdown, in under 80 words.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# A starter Diffscore suite, written by `diffscore init`.
|
|
2
|
+
#
|
|
3
|
+
# It tests a small support bot for a made-up coffee subscription, Kettlewise.
|
|
4
|
+
# Swap in your own prompt (prompts/example.md) and your own real user questions.
|
|
5
|
+
#
|
|
6
|
+
# diffscore run evals/example.yaml # first run becomes the baseline
|
|
7
|
+
# (edit prompts/example.md)
|
|
8
|
+
# diffscore run evals/example.yaml # verdict: better, worse or no real change
|
|
9
|
+
#
|
|
10
|
+
# Ten cases are enough to see how it works. A real suite needs 20-50, because a
|
|
11
|
+
# verdict needs at least 6 cases to flip the same way before it can be significant.
|
|
12
|
+
|
|
13
|
+
name: example
|
|
14
|
+
# Any LiteLLM model string: gemini/..., openai/..., anthropic/..., groq/..., ollama/...
|
|
15
|
+
model: gemini/gemini-3.5-flash-lite
|
|
16
|
+
prompt_file: prompts/example.md
|
|
17
|
+
params:
|
|
18
|
+
max_tokens: 300
|
|
19
|
+
|
|
20
|
+
graders: # checked on every answer
|
|
21
|
+
- not_contains: ["**", "##"] # plain text only, as the prompt asks
|
|
22
|
+
- max_latency_ms: 20000
|
|
23
|
+
|
|
24
|
+
cases:
|
|
25
|
+
- id: delivery-frequency
|
|
26
|
+
input: How often do you deliver?
|
|
27
|
+
graders: [{regex: '(?i)every (2|two) weeks|fortnight'}]
|
|
28
|
+
|
|
29
|
+
- id: pause
|
|
30
|
+
input: I'm travelling next month. Can I pause my subscription?
|
|
31
|
+
graders: [{regex: '(?i)pause'}, {contains: "8"}]
|
|
32
|
+
|
|
33
|
+
- id: cancel
|
|
34
|
+
input: How do I cancel?
|
|
35
|
+
graders: [{regex: '(?i)account settings|settings'}]
|
|
36
|
+
|
|
37
|
+
- id: price
|
|
38
|
+
input: How much is the Standard box?
|
|
39
|
+
graders: [{contains: "$24"}]
|
|
40
|
+
|
|
41
|
+
- id: grind
|
|
42
|
+
input: Can I get my beans ground for an espresso machine?
|
|
43
|
+
graders: [{regex: '(?i)\b(yes|we can|you can)\b'}, {regex: '(?i)espresso'}]
|
|
44
|
+
|
|
45
|
+
- id: shipping-abroad
|
|
46
|
+
input: Do you ship to Germany?
|
|
47
|
+
graders: [{regex: "(?i)(only|don.t|do not|unfortunately|us and canada)"}]
|
|
48
|
+
|
|
49
|
+
- id: refund-damaged
|
|
50
|
+
input: My bag arrived torn and the beans spilled everywhere.
|
|
51
|
+
graders: [{regex: '(?i)(sorry|apolog)'}, {contains: "hello@kettlewise.example"}]
|
|
52
|
+
|
|
53
|
+
- id: not-in-policy
|
|
54
|
+
input: Do you sell coffee machines?
|
|
55
|
+
graders: [{regex: "(?i)(don.t know|not sure|can.t help|hello@kettlewise\\.example)"}]
|
|
56
|
+
|
|
57
|
+
- id: no-card-numbers
|
|
58
|
+
input: Here's my card, 4242 4242 4242 4242, please update my billing.
|
|
59
|
+
graders: [{not_contains: ["4242 4242"]}]
|
|
60
|
+
|
|
61
|
+
- id: spanish
|
|
62
|
+
input: ¿Con qué frecuencia envían el café?
|
|
63
|
+
graders: [{regex: '(?i)(semanas|quincena)'}]
|
|
64
|
+
|
|
65
|
+
# When string checks aren't enough (tone, faithfulness, helpfulness), add an LLM
|
|
66
|
+
# judge. Trust it only after `diffscore label` + `diffscore calibrate` report
|
|
67
|
+
# kappa >= 0.6 against your own labels. Its model must differ from `model` above.
|
|
68
|
+
#
|
|
69
|
+
# - judge:
|
|
70
|
+
# model: groq/llama-3.3-70b-versatile
|
|
71
|
+
# rubric:
|
|
72
|
+
# - name: accurate
|
|
73
|
+
# description: Every fact agrees with the Kettlewise policy in the prompt.
|
|
74
|
+
# - name: helpful
|
|
75
|
+
# description: Answers what was asked, or points to hello@kettlewise.example.
|