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/api.py
ADDED
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
"""HTTP API for the web app.
|
|
2
|
+
|
|
3
|
+
Routes are thin: they call the same service functions as the CLI (`prepare_run`,
|
|
4
|
+
`diff_runs`, `run_detail`, ...) and only translate to and from JSON. No business
|
|
5
|
+
logic lives here.
|
|
6
|
+
|
|
7
|
+
Access model (v1, single user):
|
|
8
|
+
- With `Authorization: Bearer <API_KEY>` you can read and do everything.
|
|
9
|
+
- Without it you can read the public projects (PUBLIC_PROJECTS, default
|
|
10
|
+
`sample` and `playground`), run a curated sample suite, or run your own suite
|
|
11
|
+
with your own provider key. Both are rate limited per IP, and own-key runs are
|
|
12
|
+
capped at MAX_CASES_ANONYMOUS cases. Your key is encrypted, used for that run
|
|
13
|
+
only, and wiped when it finishes.
|
|
14
|
+
- If API_KEY is unset (local development) every request is treated as the owner.
|
|
15
|
+
|
|
16
|
+
uvicorn diffscore.api:app --reload
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hmac
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Iterator
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from datetime import datetime
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Annotated, Any
|
|
28
|
+
|
|
29
|
+
from fastapi import Depends, FastAPI, Header, HTTPException, Request, status
|
|
30
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
31
|
+
from pydantic import BaseModel, Field
|
|
32
|
+
from redis import Redis
|
|
33
|
+
from rq import Queue
|
|
34
|
+
from sqlalchemy import func, select
|
|
35
|
+
from sqlalchemy.orm import Session
|
|
36
|
+
|
|
37
|
+
from diffscore import __version__, jobs
|
|
38
|
+
from diffscore.config import get_settings
|
|
39
|
+
from diffscore.db import JudgeCalibration, Project, Run, Suite
|
|
40
|
+
from diffscore.db.session import make_session
|
|
41
|
+
from diffscore.diffing import (
|
|
42
|
+
Diff,
|
|
43
|
+
DiffError,
|
|
44
|
+
baseline_ids,
|
|
45
|
+
diff_runs,
|
|
46
|
+
previous_run,
|
|
47
|
+
set_baseline,
|
|
48
|
+
suite_baseline,
|
|
49
|
+
)
|
|
50
|
+
from diffscore.graders import GraderConfigError
|
|
51
|
+
from diffscore.judge import parse_config
|
|
52
|
+
from diffscore.labeling import judges_in_run
|
|
53
|
+
from diffscore.queries import RunRow, list_runs, load_run, run_detail
|
|
54
|
+
from diffscore.runner import prepare_run
|
|
55
|
+
from diffscore.secrets import (
|
|
56
|
+
PROVIDERS,
|
|
57
|
+
SecretsError,
|
|
58
|
+
decrypt_keys,
|
|
59
|
+
encrypt_keys,
|
|
60
|
+
init_sentry,
|
|
61
|
+
install_log_redaction,
|
|
62
|
+
provider_for,
|
|
63
|
+
)
|
|
64
|
+
from diffscore.suite import SuiteError, SuiteFile, load_suite, load_suite_text
|
|
65
|
+
|
|
66
|
+
install_log_redaction()
|
|
67
|
+
init_sentry()
|
|
68
|
+
|
|
69
|
+
app = FastAPI(
|
|
70
|
+
title="Diffscore API",
|
|
71
|
+
version=__version__,
|
|
72
|
+
description="Pre-deploy regression tests for LLM prompts, with scoring you can verify.",
|
|
73
|
+
)
|
|
74
|
+
app.add_middleware(
|
|
75
|
+
CORSMiddleware,
|
|
76
|
+
allow_origins=get_settings().cors_origin_list(),
|
|
77
|
+
allow_methods=["GET", "POST", "PUT", "DELETE"],
|
|
78
|
+
allow_headers=["Authorization", "Content-Type"],
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# Model params a visitor may set. Anything else (api_base, base_url, headers ...)
|
|
82
|
+
# could point the server's HTTP client at an internal address.
|
|
83
|
+
VISITOR_PARAMS = {"max_tokens", "temperature", "top_p", "stop", "seed", "response_format"}
|
|
84
|
+
|
|
85
|
+
PLAYGROUND = "playground"
|
|
86
|
+
SAMPLE = "sample"
|
|
87
|
+
MAX_SUITE_BYTES = 200_000
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------ dependencies
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_session() -> Iterator[Session]:
|
|
94
|
+
session = make_session()
|
|
95
|
+
try:
|
|
96
|
+
yield session
|
|
97
|
+
finally:
|
|
98
|
+
session.close()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def get_redis() -> Redis:
|
|
102
|
+
return jobs.redis_connection()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def get_queue(redis: Annotated[Redis, Depends(get_redis)]) -> Queue:
|
|
106
|
+
return jobs.get_queue(redis)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class Viewer:
|
|
111
|
+
owner: bool
|
|
112
|
+
ip: str
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def projects(self) -> set[str] | None:
|
|
116
|
+
"""Projects this viewer may read; None means all of them."""
|
|
117
|
+
return None if self.owner else get_settings().public_project_set()
|
|
118
|
+
|
|
119
|
+
def can_read(self, project: str) -> bool:
|
|
120
|
+
return self.projects is None or project in self.projects
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def viewer(request: Request, authorization: Annotated[str | None, Header()] = None) -> Viewer:
|
|
124
|
+
settings = get_settings()
|
|
125
|
+
secret = settings.api_key.get_secret_value() if settings.api_key else ""
|
|
126
|
+
if not secret:
|
|
127
|
+
owner = True # local development: no API_KEY configured
|
|
128
|
+
else:
|
|
129
|
+
token = (authorization or "").removeprefix("Bearer ").strip()
|
|
130
|
+
owner = bool(token) and hmac.compare_digest(token, secret)
|
|
131
|
+
ip = request.client.host if request.client else "unknown"
|
|
132
|
+
if settings.trust_proxy and (fwd := request.headers.get("x-forwarded-for")):
|
|
133
|
+
ip = fwd.split(",")[0].strip()
|
|
134
|
+
return Viewer(owner=owner, ip=ip)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def owner_only(v: Annotated[Viewer, Depends(viewer)]) -> Viewer:
|
|
138
|
+
if not v.owner:
|
|
139
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "this needs the API key")
|
|
140
|
+
return v
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
SessionDep = Annotated[Session, Depends(get_session)]
|
|
144
|
+
ViewerDep = Annotated[Viewer, Depends(viewer)]
|
|
145
|
+
OwnerDep = Annotated[Viewer, Depends(owner_only)]
|
|
146
|
+
QueueDep = Annotated[Queue, Depends(get_queue)]
|
|
147
|
+
RedisDep = Annotated[Redis, Depends(get_redis)]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def rate_limit(redis: Redis, v: Viewer) -> None:
|
|
151
|
+
"""Anonymous runs: a fixed number per IP per hour. The owner is not limited."""
|
|
152
|
+
if v.owner:
|
|
153
|
+
return
|
|
154
|
+
hour = int(time.time() // 3600)
|
|
155
|
+
key = f"diffscore:rl:{v.ip}:{hour}"
|
|
156
|
+
count = int(redis.incr(key))
|
|
157
|
+
if count == 1:
|
|
158
|
+
redis.expire(key, 3600)
|
|
159
|
+
limit = get_settings().anon_runs_per_hour
|
|
160
|
+
if count > limit:
|
|
161
|
+
raise HTTPException(
|
|
162
|
+
status.HTTP_429_TOO_MANY_REQUESTS,
|
|
163
|
+
f"limit of {limit} runs an hour reached; try again later",
|
|
164
|
+
headers={"Retry-After": str(3600 - int(time.time()) % 3600)},
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# ------------------------------------------------------------------ response models
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class RunOut(BaseModel):
|
|
172
|
+
id: int
|
|
173
|
+
suite: str
|
|
174
|
+
suite_id: int
|
|
175
|
+
project: str
|
|
176
|
+
model: str
|
|
177
|
+
status: str
|
|
178
|
+
created_at: datetime
|
|
179
|
+
finished_at: datetime | None
|
|
180
|
+
error: str | None
|
|
181
|
+
passed: int
|
|
182
|
+
failed: int
|
|
183
|
+
errors: int
|
|
184
|
+
ungraded: int
|
|
185
|
+
done: int
|
|
186
|
+
case_count: int
|
|
187
|
+
cache_hits: int
|
|
188
|
+
tokens: int
|
|
189
|
+
cost_usd: float
|
|
190
|
+
is_baseline: bool
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def of(cls, r: RunRow, baselines: set[int]) -> RunOut:
|
|
194
|
+
return cls(
|
|
195
|
+
id=r.id,
|
|
196
|
+
suite=r.suite,
|
|
197
|
+
suite_id=r.suite_id,
|
|
198
|
+
project=r.project,
|
|
199
|
+
model=r.model,
|
|
200
|
+
status=r.status,
|
|
201
|
+
created_at=r.created_at,
|
|
202
|
+
finished_at=r.finished_at,
|
|
203
|
+
error=r.error,
|
|
204
|
+
passed=r.outcomes["pass"],
|
|
205
|
+
failed=r.outcomes["fail"],
|
|
206
|
+
errors=r.outcomes["error"],
|
|
207
|
+
ungraded=r.outcomes["ungraded"],
|
|
208
|
+
done=r.done,
|
|
209
|
+
case_count=r.case_count,
|
|
210
|
+
cache_hits=r.cache_hits,
|
|
211
|
+
tokens=r.tokens,
|
|
212
|
+
cost_usd=float(r.cost),
|
|
213
|
+
is_baseline=r.id in baselines,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class GradeOut(BaseModel):
|
|
218
|
+
grader: str
|
|
219
|
+
verdict: str
|
|
220
|
+
score: float
|
|
221
|
+
reason: str | None
|
|
222
|
+
details: dict[str, Any]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class CaseOut(BaseModel):
|
|
226
|
+
key: str
|
|
227
|
+
outcome: str
|
|
228
|
+
failures: list[str]
|
|
229
|
+
input: str
|
|
230
|
+
expect: str | None
|
|
231
|
+
output: str | None
|
|
232
|
+
latency_ms: int | None
|
|
233
|
+
tokens: int | None
|
|
234
|
+
cache_hit: bool
|
|
235
|
+
grades: list[GradeOut]
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class RunDetailOut(BaseModel):
|
|
239
|
+
run: RunOut
|
|
240
|
+
cases: list[CaseOut]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class ProgressOut(BaseModel):
|
|
244
|
+
id: int
|
|
245
|
+
status: str
|
|
246
|
+
done: int
|
|
247
|
+
total: int
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class IntervalOut(BaseModel):
|
|
251
|
+
mean: float
|
|
252
|
+
low: float
|
|
253
|
+
high: float
|
|
254
|
+
level: float
|
|
255
|
+
excludes_zero: bool
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class CaseDiffOut(BaseModel):
|
|
259
|
+
key: str
|
|
260
|
+
change: str
|
|
261
|
+
before: str | None
|
|
262
|
+
after: str | None
|
|
263
|
+
score_before: float | None
|
|
264
|
+
score_after: float | None
|
|
265
|
+
why: list[str]
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
class DiffOut(BaseModel):
|
|
269
|
+
baseline: RunOut
|
|
270
|
+
candidate: RunOut
|
|
271
|
+
verdict: str
|
|
272
|
+
headline: str
|
|
273
|
+
p_value: float
|
|
274
|
+
method: str
|
|
275
|
+
alpha: float
|
|
276
|
+
regressed: int
|
|
277
|
+
improved: int
|
|
278
|
+
unchanged: int
|
|
279
|
+
new: int
|
|
280
|
+
removed: int
|
|
281
|
+
excluded: int
|
|
282
|
+
interval: IntervalOut | None
|
|
283
|
+
what_changed: str
|
|
284
|
+
too_small_note: str | None
|
|
285
|
+
exit_code: int
|
|
286
|
+
cases: list[CaseDiffOut]
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class CalibrationOut(BaseModel):
|
|
290
|
+
grader: str
|
|
291
|
+
version: str
|
|
292
|
+
judge_model: str
|
|
293
|
+
labels: int
|
|
294
|
+
kappa: float | None
|
|
295
|
+
agreement: float
|
|
296
|
+
trustworthy: bool
|
|
297
|
+
judge_pass_human_fail: int
|
|
298
|
+
judge_fail_human_pass: int
|
|
299
|
+
verbosity_r: float | None
|
|
300
|
+
self_preference_ok: bool
|
|
301
|
+
position_pairs: int | None
|
|
302
|
+
position_consistent: int | None
|
|
303
|
+
variance_cases: int | None
|
|
304
|
+
variance_flipped: int | None
|
|
305
|
+
evidence_found: int
|
|
306
|
+
evidence_total: int
|
|
307
|
+
created_at: datetime
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class SuiteOut(BaseModel):
|
|
311
|
+
id: int
|
|
312
|
+
name: str
|
|
313
|
+
project: str
|
|
314
|
+
baseline_run_id: int | None
|
|
315
|
+
runs: int
|
|
316
|
+
latest_run_id: int | None
|
|
317
|
+
judge_graders: list[str] # every judge in the suite, calibrated or not
|
|
318
|
+
judges: list[CalibrationOut] # the latest calibration of each, where one exists
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class SampleOut(BaseModel):
|
|
322
|
+
name: str
|
|
323
|
+
suite: str
|
|
324
|
+
cases: int
|
|
325
|
+
model: str
|
|
326
|
+
has_judge: bool
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
class StartRunIn(BaseModel):
|
|
330
|
+
suite_yaml: str = Field(max_length=MAX_SUITE_BYTES)
|
|
331
|
+
model: str | None = None
|
|
332
|
+
# Your own keys for this run only, e.g. {"gemini": "..."}; never stored past the run.
|
|
333
|
+
provider_keys: dict[str, str] | None = None
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class StartedOut(BaseModel):
|
|
337
|
+
run_id: int
|
|
338
|
+
status: str
|
|
339
|
+
case_count: int
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class KeysIn(BaseModel):
|
|
343
|
+
keys: dict[str, str]
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
class KeysOut(BaseModel):
|
|
347
|
+
project: str
|
|
348
|
+
providers: list[str] # which providers have a key; never the keys themselves
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ------------------------------------------------------------------ helpers
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _run_out(session: Session, run_id: int, v: Viewer) -> RunOut:
|
|
355
|
+
rows = list_runs(session, limit=1, projects=v.projects, run_id=run_id)
|
|
356
|
+
if not rows:
|
|
357
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"no run {run_id}")
|
|
358
|
+
return RunOut.of(rows[0], baseline_ids(session))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _visible_run(session: Session, run_id: int, v: Viewer) -> Run:
|
|
362
|
+
try:
|
|
363
|
+
run = load_run(session, run_id)
|
|
364
|
+
except LookupError:
|
|
365
|
+
run = None
|
|
366
|
+
if run is None or not v.can_read(run.suite.project.name):
|
|
367
|
+
# 404, not 403: don't confirm that a private run exists.
|
|
368
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"no run {run_id}")
|
|
369
|
+
return run
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _diff_out(session: Session, d: Diff, v: Viewer) -> DiffOut:
|
|
373
|
+
c = d.counts
|
|
374
|
+
i = d.interval
|
|
375
|
+
return DiffOut(
|
|
376
|
+
baseline=_run_out(session, d.a.id, v),
|
|
377
|
+
candidate=_run_out(session, d.b.id, v),
|
|
378
|
+
verdict=d.verdict,
|
|
379
|
+
headline=d.headline,
|
|
380
|
+
p_value=d.p_value,
|
|
381
|
+
method=d.method,
|
|
382
|
+
alpha=d.alpha,
|
|
383
|
+
regressed=c["regressed"],
|
|
384
|
+
improved=c["improved"],
|
|
385
|
+
unchanged=c["unchanged"],
|
|
386
|
+
new=c["new"],
|
|
387
|
+
removed=c["removed"],
|
|
388
|
+
excluded=c["excluded"],
|
|
389
|
+
interval=IntervalOut(
|
|
390
|
+
mean=i.mean, low=i.low, high=i.high, level=i.level, excludes_zero=i.excludes_zero
|
|
391
|
+
)
|
|
392
|
+
if i
|
|
393
|
+
else None,
|
|
394
|
+
what_changed=d.what_changed,
|
|
395
|
+
too_small_note=d.too_small_note,
|
|
396
|
+
exit_code=d.exit_code,
|
|
397
|
+
cases=[
|
|
398
|
+
CaseDiffOut(
|
|
399
|
+
key=x.key,
|
|
400
|
+
change=x.change,
|
|
401
|
+
before=x.before,
|
|
402
|
+
after=x.after,
|
|
403
|
+
score_before=x.score_before,
|
|
404
|
+
score_after=x.score_after,
|
|
405
|
+
why=x.why,
|
|
406
|
+
)
|
|
407
|
+
for x in d.cases
|
|
408
|
+
],
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _calibration_out(row: JudgeCalibration) -> CalibrationOut:
|
|
413
|
+
return CalibrationOut(
|
|
414
|
+
grader=row.grader_name,
|
|
415
|
+
version=row.grader_version,
|
|
416
|
+
judge_model=row.judge_model,
|
|
417
|
+
labels=row.labels,
|
|
418
|
+
kappa=row.kappa,
|
|
419
|
+
agreement=row.agreement,
|
|
420
|
+
trustworthy=row.kappa is not None and row.kappa >= 0.6,
|
|
421
|
+
judge_pass_human_fail=row.judge_pass_human_fail,
|
|
422
|
+
judge_fail_human_pass=row.judge_fail_human_pass,
|
|
423
|
+
verbosity_r=row.verbosity_r,
|
|
424
|
+
self_preference_ok=row.self_preference_ok,
|
|
425
|
+
position_pairs=row.position_pairs,
|
|
426
|
+
position_consistent=row.position_consistent,
|
|
427
|
+
variance_cases=row.variance_cases,
|
|
428
|
+
variance_flipped=row.variance_flipped,
|
|
429
|
+
evidence_found=row.evidence_found,
|
|
430
|
+
evidence_total=row.evidence_total,
|
|
431
|
+
created_at=row.created_at,
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _samples() -> dict[str, Path]:
|
|
436
|
+
root = Path(get_settings().samples_dir)
|
|
437
|
+
if not root.is_dir():
|
|
438
|
+
return {}
|
|
439
|
+
return {p.relative_to(root).with_suffix("").as_posix(): p for p in sorted(root.rglob("*.yaml"))}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _submit(
|
|
443
|
+
session: Session,
|
|
444
|
+
queue: Queue,
|
|
445
|
+
spec: SuiteFile,
|
|
446
|
+
model: str,
|
|
447
|
+
provider_keys: dict[str, str] | None = None,
|
|
448
|
+
) -> StartedOut:
|
|
449
|
+
try:
|
|
450
|
+
run = prepare_run(session, spec, model=model)
|
|
451
|
+
except GraderConfigError as exc:
|
|
452
|
+
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
|
|
453
|
+
if provider_keys:
|
|
454
|
+
run.provider_keys_encrypted = encrypt_keys(provider_keys)
|
|
455
|
+
session.commit()
|
|
456
|
+
jobs.enqueue_run(queue, run.id, list(run.case_keys))
|
|
457
|
+
session.refresh(run)
|
|
458
|
+
return StartedOut(run_id=run.id, status=run.status, case_count=len(run.case_keys))
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _models_needing_keys(spec: SuiteFile, model: str) -> set[str]:
|
|
462
|
+
models = {model}
|
|
463
|
+
models |= {parse_config(g.arg).judge_model() for g in spec.all_graders() if g.name == "judge"}
|
|
464
|
+
return models
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
# ------------------------------------------------------------------ routes: reading
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
@app.get("/api/health")
|
|
471
|
+
def health() -> dict[str, Any]:
|
|
472
|
+
settings = get_settings()
|
|
473
|
+
return {
|
|
474
|
+
"status": "ok",
|
|
475
|
+
"version": __version__,
|
|
476
|
+
"auth": "on" if settings.api_key and settings.api_key.get_secret_value() else "off",
|
|
477
|
+
"queue": "inline" if settings.queue_sync else "worker",
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@app.get("/api/suites", response_model=list[SuiteOut])
|
|
482
|
+
def suites(session: SessionDep, v: ViewerDep) -> list[SuiteOut]:
|
|
483
|
+
stmt = select(Suite).join(Suite.project).order_by(Suite.id)
|
|
484
|
+
if v.projects is not None:
|
|
485
|
+
stmt = stmt.where(Project.name.in_(v.projects))
|
|
486
|
+
out = []
|
|
487
|
+
for s in session.scalars(stmt):
|
|
488
|
+
runs = session.scalar(select(func.count()).select_from(Run).where(Run.suite_id == s.id))
|
|
489
|
+
latest = session.scalar(select(func.max(Run.id)).where(Run.suite_id == s.id))
|
|
490
|
+
newest: dict[str, JudgeCalibration] = {}
|
|
491
|
+
for row in session.scalars(
|
|
492
|
+
select(JudgeCalibration)
|
|
493
|
+
.where(JudgeCalibration.suite_id == s.id)
|
|
494
|
+
.order_by(JudgeCalibration.id)
|
|
495
|
+
):
|
|
496
|
+
newest[row.grader_name] = row
|
|
497
|
+
out.append(
|
|
498
|
+
SuiteOut(
|
|
499
|
+
id=s.id,
|
|
500
|
+
name=s.name,
|
|
501
|
+
project=s.project.name,
|
|
502
|
+
baseline_run_id=s.baseline_run_id,
|
|
503
|
+
runs=runs or 0,
|
|
504
|
+
latest_run_id=latest,
|
|
505
|
+
judge_graders=judges_in_run(session, latest) if latest else [],
|
|
506
|
+
judges=[_calibration_out(r) for r in newest.values()],
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
return out
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
@app.get("/api/runs", response_model=list[RunOut])
|
|
513
|
+
def runs(
|
|
514
|
+
session: SessionDep, v: ViewerDep, suite_id: int | None = None, limit: int = 50
|
|
515
|
+
) -> list[RunOut]:
|
|
516
|
+
rows = list_runs(session, limit=min(limit, 200), projects=v.projects, suite_id=suite_id)
|
|
517
|
+
baselines = baseline_ids(session)
|
|
518
|
+
return [RunOut.of(r, baselines) for r in rows]
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
@app.get("/api/runs/{run_id}", response_model=RunDetailOut)
|
|
522
|
+
def run(run_id: int, session: SessionDep, v: ViewerDep) -> RunDetailOut:
|
|
523
|
+
_visible_run(session, run_id, v)
|
|
524
|
+
row, cases = run_detail(session, run_id)
|
|
525
|
+
return RunDetailOut(
|
|
526
|
+
run=RunOut.of(row, baseline_ids(session)),
|
|
527
|
+
cases=[
|
|
528
|
+
CaseOut(
|
|
529
|
+
key=c.key,
|
|
530
|
+
outcome=c.outcome,
|
|
531
|
+
failures=c.failures,
|
|
532
|
+
input=c.input,
|
|
533
|
+
expect=c.expect,
|
|
534
|
+
output=c.output,
|
|
535
|
+
latency_ms=c.latency_ms,
|
|
536
|
+
tokens=c.tokens,
|
|
537
|
+
cache_hit=c.cache_hit,
|
|
538
|
+
grades=[
|
|
539
|
+
GradeOut(
|
|
540
|
+
grader=g.grader,
|
|
541
|
+
verdict=g.verdict,
|
|
542
|
+
score=g.score,
|
|
543
|
+
reason=g.reason,
|
|
544
|
+
details=g.details,
|
|
545
|
+
)
|
|
546
|
+
for g in c.grades
|
|
547
|
+
],
|
|
548
|
+
)
|
|
549
|
+
for c in cases
|
|
550
|
+
],
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
@app.get("/api/runs/{run_id}/progress", response_model=ProgressOut)
|
|
555
|
+
def progress(run_id: int, session: SessionDep, v: ViewerDep) -> ProgressOut:
|
|
556
|
+
r = _visible_run(session, run_id, v)
|
|
557
|
+
return ProgressOut(id=r.id, status=r.status, done=len(r.results), total=len(r.case_keys))
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
@app.get("/api/runs/{run_id}/diff", response_model=DiffOut)
|
|
561
|
+
def diff_vs_baseline(
|
|
562
|
+
run_id: int, session: SessionDep, v: ViewerDep, baseline: str | None = None
|
|
563
|
+
) -> DiffOut:
|
|
564
|
+
"""Diff a run against its suite's baseline, a given run id, or 'previous'."""
|
|
565
|
+
_visible_run(session, run_id, v)
|
|
566
|
+
if baseline is None:
|
|
567
|
+
base = suite_baseline(session, run_id)
|
|
568
|
+
elif baseline == "previous":
|
|
569
|
+
base = previous_run(session, run_id)
|
|
570
|
+
elif baseline.isdigit():
|
|
571
|
+
base = int(baseline)
|
|
572
|
+
else:
|
|
573
|
+
raise HTTPException(
|
|
574
|
+
status.HTTP_422_UNPROCESSABLE_CONTENT, "baseline is a run id or 'previous'"
|
|
575
|
+
)
|
|
576
|
+
if base is None:
|
|
577
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, "nothing to compare this run against")
|
|
578
|
+
return diff(base, run_id, session, v)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
@app.get("/api/diff", response_model=DiffOut)
|
|
582
|
+
def diff(
|
|
583
|
+
baseline: int, candidate: int, session: SessionDep, v: ViewerDep, alpha: float = 0.05
|
|
584
|
+
) -> DiffOut:
|
|
585
|
+
_visible_run(session, baseline, v)
|
|
586
|
+
_visible_run(session, candidate, v)
|
|
587
|
+
try:
|
|
588
|
+
d = diff_runs(session, baseline, candidate, alpha=alpha)
|
|
589
|
+
except DiffError as exc:
|
|
590
|
+
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
|
|
591
|
+
return _diff_out(session, d, v)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
@app.get("/api/samples", response_model=list[SampleOut])
|
|
595
|
+
def samples() -> list[SampleOut]:
|
|
596
|
+
out = []
|
|
597
|
+
for name, path in _samples().items():
|
|
598
|
+
try:
|
|
599
|
+
spec = load_suite(path).spec
|
|
600
|
+
except SuiteError:
|
|
601
|
+
continue
|
|
602
|
+
out.append(
|
|
603
|
+
SampleOut(
|
|
604
|
+
name=name,
|
|
605
|
+
suite=spec.name,
|
|
606
|
+
cases=len(spec.cases),
|
|
607
|
+
model=spec.model or get_settings().default_model,
|
|
608
|
+
has_judge=any(g.name == "judge" for g in spec.all_graders()),
|
|
609
|
+
)
|
|
610
|
+
)
|
|
611
|
+
return out
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
# ------------------------------------------------------------------ routes: running
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
@app.post("/api/samples/{name:path}/runs", response_model=StartedOut, status_code=201)
|
|
618
|
+
def run_sample(
|
|
619
|
+
name: str, session: SessionDep, v: ViewerDep, queue: QueueDep, redis: RedisDep
|
|
620
|
+
) -> StartedOut:
|
|
621
|
+
"""Run a curated suite on the server's key. Answers are cached, so repeats are free."""
|
|
622
|
+
path = _samples().get(name)
|
|
623
|
+
if path is None:
|
|
624
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"no sample {name!r}")
|
|
625
|
+
rate_limit(redis, v)
|
|
626
|
+
spec = load_suite(path).spec.model_copy(update={"project": SAMPLE})
|
|
627
|
+
return _submit(session, queue, spec, spec.model or get_settings().default_model)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
@app.post("/api/runs", response_model=StartedOut, status_code=201)
|
|
631
|
+
def start_run(
|
|
632
|
+
body: StartRunIn, session: SessionDep, v: ViewerDep, queue: QueueDep, redis: RedisDep
|
|
633
|
+
) -> StartedOut:
|
|
634
|
+
"""Run your own suite. Visitors bring their own provider key; the owner needn't."""
|
|
635
|
+
try:
|
|
636
|
+
spec = load_suite_text(body.suite_yaml)
|
|
637
|
+
except SuiteError as exc:
|
|
638
|
+
raise HTTPException(
|
|
639
|
+
status.HTTP_422_UNPROCESSABLE_CONTENT, {"problems": exc.problems}
|
|
640
|
+
) from exc
|
|
641
|
+
settings = get_settings()
|
|
642
|
+
model = body.model or spec.model or settings.default_model
|
|
643
|
+
keys = body.provider_keys or {}
|
|
644
|
+
|
|
645
|
+
if not v.owner:
|
|
646
|
+
rate_limit(redis, v)
|
|
647
|
+
cap = settings.max_cases_anonymous
|
|
648
|
+
if len(spec.cases) > cap:
|
|
649
|
+
raise HTTPException(
|
|
650
|
+
status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
651
|
+
f"{len(spec.cases)} cases; without the API key a run is capped at {cap}",
|
|
652
|
+
)
|
|
653
|
+
blocked = sorted(set(spec.params) - VISITOR_PARAMS)
|
|
654
|
+
if blocked:
|
|
655
|
+
raise HTTPException(
|
|
656
|
+
status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
657
|
+
f"params {blocked} need the API key; visitors may set {sorted(VISITOR_PARAMS)}",
|
|
658
|
+
)
|
|
659
|
+
models = _models_needing_keys(spec, model)
|
|
660
|
+
unknown = sorted(m for m in models if provider_for(m) is None)
|
|
661
|
+
if unknown:
|
|
662
|
+
raise HTTPException(
|
|
663
|
+
status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
664
|
+
f"models {unknown} aren't available without the API key; "
|
|
665
|
+
f"use one from {sorted(PROVIDERS)}",
|
|
666
|
+
)
|
|
667
|
+
needed = {provider_for(m) for m in models}
|
|
668
|
+
missing = sorted(p for p in needed if p and p not in keys)
|
|
669
|
+
if missing:
|
|
670
|
+
raise HTTPException(
|
|
671
|
+
status.HTTP_403_FORBIDDEN,
|
|
672
|
+
f"bring your own provider key for: {', '.join(missing)} "
|
|
673
|
+
"(it is used for this run only), or run a sample suite",
|
|
674
|
+
)
|
|
675
|
+
spec = spec.model_copy(update={"project": PLAYGROUND})
|
|
676
|
+
|
|
677
|
+
try:
|
|
678
|
+
return _submit(session, queue, spec, model, keys or None)
|
|
679
|
+
except SecretsError as exc:
|
|
680
|
+
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from exc
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
@app.post("/api/runs/{run_id}/baseline", response_model=RunOut)
|
|
684
|
+
def make_baseline(run_id: int, session: SessionDep, v: OwnerDep) -> RunOut:
|
|
685
|
+
try:
|
|
686
|
+
set_baseline(session, run_id)
|
|
687
|
+
except DiffError as exc:
|
|
688
|
+
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
|
|
689
|
+
return _run_out(session, run_id, v)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
# ------------------------------------------------------------------ routes: provider keys
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _project(session: Session, name: str) -> Project:
|
|
696
|
+
project = session.scalar(select(Project).where(Project.name == name))
|
|
697
|
+
if project is None:
|
|
698
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"no project {name!r}")
|
|
699
|
+
return project
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
@app.get("/api/projects/{name}/provider-keys", response_model=KeysOut)
|
|
703
|
+
def get_keys(name: str, session: SessionDep, _: OwnerDep) -> KeysOut:
|
|
704
|
+
project = _project(session, name)
|
|
705
|
+
return KeysOut(project=name, providers=sorted(decrypt_keys(project.provider_keys_encrypted)))
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
@app.put("/api/projects/{name}/provider-keys", response_model=KeysOut)
|
|
709
|
+
def put_keys(name: str, body: KeysIn, session: SessionDep, _: OwnerDep) -> KeysOut:
|
|
710
|
+
project = _project(session, name)
|
|
711
|
+
try:
|
|
712
|
+
keys = decrypt_keys(project.provider_keys_encrypted) | body.keys
|
|
713
|
+
project.provider_keys_encrypted = encrypt_keys(keys)
|
|
714
|
+
except SecretsError as exc:
|
|
715
|
+
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
|
|
716
|
+
session.commit()
|
|
717
|
+
return KeysOut(project=name, providers=sorted(keys))
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
@app.delete("/api/projects/{name}/provider-keys/{provider}", response_model=KeysOut)
|
|
721
|
+
def delete_key(name: str, provider: str, session: SessionDep, _: OwnerDep) -> KeysOut:
|
|
722
|
+
if provider not in PROVIDERS:
|
|
723
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"unknown provider {provider!r}")
|
|
724
|
+
project = _project(session, name)
|
|
725
|
+
keys = decrypt_keys(project.provider_keys_encrypted)
|
|
726
|
+
keys.pop(provider, None)
|
|
727
|
+
project.provider_keys_encrypted = encrypt_keys(keys) if keys else None
|
|
728
|
+
session.commit()
|
|
729
|
+
return KeysOut(project=name, providers=sorted(keys))
|