gateledger 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.
gateledger/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """gateledger: 多段の LLM パイプラインに、合否と料金の受領記録を残す。サーバー不要。"""
2
+
3
+ __version__ = "0.1.0" # ledger が記録に書くので、下の import より先に置く
4
+
5
+ from .calibration import MIN_KAPPA, MIN_LABELS, Calibration
6
+ from .gate import Gate, GateBlocked
7
+ from .judge import Judge, Rubric
8
+ from .ledger import Ledger
9
+ from .pipeline import Pipeline, RunResult, StageContext
10
+ from .prices import PriceTable, UnknownModelError, Usage
11
+ from .providers import AnthropicProvider, Completion, FakeProvider, FakeReply, Provider
12
+ from .report import summarize
13
+ from .watch import WatchReport, watch
14
+
15
+ __all__ = [
16
+ "MIN_KAPPA",
17
+ "MIN_LABELS",
18
+ "AnthropicProvider",
19
+ "Calibration",
20
+ "Completion",
21
+ "FakeProvider",
22
+ "FakeReply",
23
+ "Gate",
24
+ "GateBlocked",
25
+ "Judge",
26
+ "Ledger",
27
+ "Pipeline",
28
+ "PriceTable",
29
+ "Provider",
30
+ "Rubric",
31
+ "RunResult",
32
+ "StageContext",
33
+ "UnknownModelError",
34
+ "Usage",
35
+ "WatchReport",
36
+ "summarize",
37
+ "watch",
38
+ ]
@@ -0,0 +1,123 @@
1
+ """校正: 採点役の判定と人のラベルの一致を測り、止める権限 (block) を与えるかを決める。
2
+
3
+ 決まり (README の「採点役に止める権限を与える線」):
4
+ - 基準の版 × 応えたモデル の組ごとに、人のラベルとの Cohen の κ を測る。
5
+ - κ が MIN_KAPPA 以上、かつ件数が MIN_LABELS 以上の組の判定だけが、block のゲートで止められる。
6
+ - 応えたモデルが頼んだモデルと違う判定は、校正があっても止める根拠に使わない。
7
+ - 線は引数で下げられない (飛ばす引数を作らないのと同じ理由)。
8
+ - ラベルの出どころ (source) を校正に残す。人のラベル (human) でなく、別のモデルの合議で作ったラベル (model_panel・silver)
9
+ だけで校正した採点役には、既定では止める権限を与えない (人との一致を測っていないため)。使う人が
10
+ Pipeline(allow_panel_calibration=True) を明示した時だけ、合議の校正でも止められる。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import random
16
+ from typing import Literal
17
+
18
+ from pydantic import BaseModel, ConfigDict, Field
19
+
20
+ from .records import CalibrationRef, now
21
+
22
+ MIN_KAPPA = 0.6 # Landis & Koch の「かなりの一致 (0.61〜0.80)」の下の端
23
+ MIN_LABELS = 100 # 100 件で κ の 95% 区間が約 ±0.14 (一致率 0.85・偶然の一致 0.5 の時)
24
+
25
+ Label = Literal["pass", "fail"]
26
+ Source = Literal["human", "model_panel"] # ラベルを付けたのが人か、別のモデルの合議か
27
+ _LABELS: tuple[Label, ...] = ("pass", "fail")
28
+
29
+
30
+ class Calibration(BaseModel):
31
+ """1 回の校正の結果。台帳の calibration/calibrations.jsonl に 1 行ずつ追記する。"""
32
+
33
+ model_config = ConfigDict(extra="forbid", frozen=True)
34
+
35
+ type: Literal["calibration"] = "calibration"
36
+ ts: str = Field(default_factory=now)
37
+ rubric: str
38
+ model: str # 応えたモデル
39
+ n: int
40
+ agreement: float # 一致率
41
+ kappa: float | None # None はどちらかが全部同じ判定で、κ を出せない
42
+ kappa_ci: tuple[float, float] | None # 95% 区間 (ラベルの単位で引き直すブートストラップ)
43
+ confusion: dict[str, dict[str, int]] # 人の判定 → 採点役の判定 → 件数
44
+ labels_fp: str # 使ったラベルの指紋
45
+ source: Source = "human" # ラベルの出どころ (前の版の記録には無いので既定は human)
46
+
47
+ @property
48
+ def shortfall(self) -> str | None:
49
+ """止める権限の線に届かない理由。届いていれば None。"""
50
+ if self.kappa is None:
51
+ return f"κ cannot be computed ({self.n} labels; one side gave the same verdict every time)"
52
+ if self.kappa < MIN_KAPPA:
53
+ return f"κ {self.kappa:.2f} is below {MIN_KAPPA} ({self.n} labels)"
54
+ if self.n < MIN_LABELS:
55
+ return f"{self.n} labels, fewer than {MIN_LABELS} (κ {self.kappa:.2f})"
56
+ return None
57
+
58
+ def block_reason(self, allow_panel: bool = False) -> str | None:
59
+ """止める根拠に使えない理由。合議のラベルだけの校正は、allow_panel を明示した時だけ線の判定へ進む。"""
60
+ if self.source == "model_panel" and not allow_panel:
61
+ return "calibrated on model-panel labels only (agreement with people not measured; allow_panel_calibration=True accepts it)"
62
+ return self.shortfall
63
+
64
+ def ref(self) -> CalibrationRef:
65
+ return CalibrationRef(kappa=self.kappa, n=self.n, at=self.ts, source=self.source)
66
+
67
+
68
+ def cohen_kappa(pairs: list[tuple[Label, Label]]) -> float | None:
69
+ """(採点役, 人) の組の列から Cohen の κ。偶然の一致が 1 になる (片方が全部同じ) 時は None。"""
70
+ n = len(pairs)
71
+ if n == 0:
72
+ return None
73
+ observed = sum(a == b for a, b in pairs) / n
74
+ expected = sum((sum(a == lab for a, _ in pairs) / n) * (sum(b == lab for _, b in pairs) / n) for lab in _LABELS)
75
+ if expected >= 1:
76
+ return None
77
+ return (observed - expected) / (1 - expected)
78
+
79
+
80
+ def _kappa_ci(pairs: list[tuple[Label, Label]], rounds: int = 2000) -> tuple[float, float] | None:
81
+ rng = random.Random(0) # 同じラベルなら同じ区間
82
+ values = []
83
+ for _ in range(rounds):
84
+ k = cohen_kappa([pairs[rng.randrange(len(pairs))] for _ in pairs])
85
+ if k is not None:
86
+ values.append(k)
87
+ if len(values) < rounds // 2: # 引き直しの半分以上で κ が出ない時は、区間を出さない
88
+ return None
89
+ values.sort()
90
+ return values[int(0.025 * len(values))], values[int(0.975 * len(values)) - 1]
91
+
92
+
93
+ def measure(
94
+ rubric: str, model: str, pairs: list[tuple[Label, Label]], labels_fp: str, source: Source = "human"
95
+ ) -> Calibration:
96
+ """(採点役の判定, ラベル) の組から校正の結果を作る。"""
97
+ if not pairs:
98
+ raise ValueError("ラベルが 0 件です")
99
+ confusion: dict[str, dict[str, int]] = {
100
+ h: {j: sum(1 for a, b in pairs if (b, a) == (h, j)) for j in _LABELS} for h in _LABELS
101
+ }
102
+ return Calibration(
103
+ rubric=rubric,
104
+ model=model,
105
+ n=len(pairs),
106
+ agreement=sum(a == b for a, b in pairs) / len(pairs),
107
+ kappa=cohen_kappa(pairs),
108
+ kappa_ci=_kappa_ci(pairs),
109
+ confusion=confusion,
110
+ labels_fp=labels_fp,
111
+ source=source,
112
+ )
113
+
114
+
115
+ def advisory_reason(
116
+ calibration: Calibration | None, requested: str, served: str, allow_panel: bool = False
117
+ ) -> str | None:
118
+ """判定を止める根拠に使えない理由。使えるなら None。"""
119
+ if served != requested:
120
+ return f"served model differs from the requested one ({requested} requested, {served} answered)"
121
+ if calibration is None:
122
+ return "not calibrated (agreement with human labels not measured)"
123
+ return calibration.block_reason(allow_panel)
gateledger/cli.py ADDED
@@ -0,0 +1,107 @@
1
+ """コマンドの入口。`gateledger report` (1 回の実行)・`gateledger calibrate` (採点役とラベルの一致)・`gateledger watch` (劣化の見張り)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .calibration import MIN_KAPPA, MIN_LABELS, Calibration
10
+ from .judge import Rubric
11
+ from .ledger import Ledger
12
+ from .report import render_html, render_svg, render_text, summarize
13
+ from .watch import parse_duration, render_watch, select_runs, watch
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> int:
17
+ parser = argparse.ArgumentParser(prog="gateledger", description="Read the receipts of a multi-stage LLM pipeline")
18
+ sub = parser.add_subparsers(dest="command", required=True)
19
+ report = sub.add_parser("report", help="Show one run by stage (tokens, cost, pass/fail)")
20
+ report.add_argument("run_id", nargs="?", help="Run id. Defaults to the latest run")
21
+ report.add_argument("--dir", default="runs", help="Ledger directory (default: runs)")
22
+ report.add_argument("--svg", type=Path, help="Write the README image here")
23
+ report.add_argument("--html", type=Path, help="Write the page with tables here")
24
+ cal = sub.add_parser(
25
+ "calibrate",
26
+ help="Measure and record how a judge agrees with labels (human or model panel): agreement, κ, confusion matrix",
27
+ )
28
+ cal.add_argument("rubric", type=Path, help="Rubric file (its version comes from the content)")
29
+ cal.add_argument(
30
+ "labels",
31
+ type=Path,
32
+ help="Labels as JSONL (judged_fp and human = pass / fail per line; model-panel labels use label and source = model_panel)",
33
+ )
34
+ cal.add_argument("--model", required=True, help="Judge to calibrate (the served model)")
35
+ cal.add_argument("--dir", default="runs", help="Ledger directory (default: runs)")
36
+ w = sub.add_parser(
37
+ "watch",
38
+ help="Compare recent runs with a baseline period and flag degradation (exit 1 when suspected)",
39
+ )
40
+ w.add_argument("--dir", default="runs", help="Ledger directory (default: runs)")
41
+ w.add_argument("--window", default="1d", help="Recent period to check, ending now (default: 1d; e.g. 30m, 12h)")
42
+ w.add_argument("--baseline", default="14d", help="Baseline period just before the window (default: 14d)")
43
+ w.add_argument("--pipeline", help="Pipeline name. Required when the ledger holds more than one")
44
+ w.add_argument("--alpha", type=float, default=0.05, help="Family-wise error rate for the shifts (default: 0.05)")
45
+ args = parser.parse_args(argv)
46
+
47
+ ledger = Ledger(args.dir)
48
+ if args.command == "watch":
49
+ try:
50
+ base, cur = select_runs(
51
+ ledger,
52
+ window=parse_duration(args.window),
53
+ baseline=parse_duration(args.baseline),
54
+ pipeline=args.pipeline,
55
+ )
56
+ found = watch(base, cur, alpha=args.alpha)
57
+ except ValueError as e:
58
+ parser.error(str(e))
59
+ sys.stdout.write(render_watch(found))
60
+ return 1 if found.suspect else 0
61
+ if args.command == "calibrate":
62
+ result = ledger.calibrate(Rubric.load(args.rubric).id, args.model, args.labels)
63
+ sys.stdout.write(render_calibration(result))
64
+ print(f"Recorded: {ledger.calibrations_path}")
65
+ return 0
66
+ try:
67
+ run = summarize(ledger.read(args.run_id or ledger.latest()))
68
+ except FileNotFoundError as e:
69
+ parser.error(f"{e} (set the ledger directory with --dir)")
70
+ sys.stdout.write(render_text(run))
71
+ for path, render in ((args.svg, render_svg), (args.html, render_html)):
72
+ if path is not None:
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+ path.write_text(render(run), encoding="utf-8")
75
+ print(f"Wrote: {path}")
76
+ return 0
77
+
78
+
79
+ def render_calibration(c: Calibration) -> str:
80
+ ci = f" [{c.kappa_ci[0]:.2f}, {c.kappa_ci[1]:.2f}]" if c.kappa_ci else ""
81
+ kappa = "n/a" if c.kappa is None else f"{c.kappa:.2f}{ci}"
82
+ m = c.confusion
83
+ reason = c.block_reason()
84
+ power = "yes" if reason is None else f"no ({reason})"
85
+ who = "human" if c.source == "human" else "model panel (silver, not checked by people)"
86
+ side = "human" if c.source == "human" else "panel"
87
+ return (
88
+ "\n".join(
89
+ [
90
+ f"Calibration rubric {c.rubric} judge {c.model}",
91
+ f"Label source: {who}",
92
+ f"n {c.n} agreement {c.agreement:.0%} κ {kappa}",
93
+ "",
94
+ f"Confusion matrix (rows = {side}, columns = judge)",
95
+ " pass fail",
96
+ f" pass {m['pass']['pass']:5d} {m['pass']['fail']:5d}",
97
+ f" fail {m['fail']['pass']:5d} {m['fail']['fail']:5d}",
98
+ "",
99
+ f"May block (κ ≥ {MIN_KAPPA}, ≥ {MIN_LABELS} labels): {power}",
100
+ ]
101
+ )
102
+ + "\n"
103
+ )
104
+
105
+
106
+ if __name__ == "__main__":
107
+ raise SystemExit(main())
gateledger/gate.py ADDED
@@ -0,0 +1,64 @@
1
+ """ゲート: ステージの出力に掛ける点検。
2
+
3
+ 点検は 2 種類:
4
+ - 機械的な点検 (LLM を使わず、同じ入力に必ず同じ結果を返す照合)。関数は `check(output, stage_input)` の形で
5
+ 呼ばれ、次のどちらかを返す。
6
+ - bool: True で合格
7
+ - 指摘の列 (文字列か dict): 空なら合格。指摘は記録に残り、repair の時はステージへ渡る
8
+ - 採点役 (`Judge`)。Pipeline が LLM を呼んで評価し、判定を記録する (judge.py)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Any, get_args
16
+
17
+ from .judge import Judge
18
+ from .records import Finding, OnFail
19
+
20
+ Check = Callable[[Any, Any], bool | Sequence[Finding]]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Gate:
25
+ """落ちた時の扱い `on_fail` は省略できない。
26
+
27
+ - block: 止める (GateBlocked を投げる)。採点役のゲートは、止める権限のある判定の時だけ止め、
28
+ ほかは記録だけして進む (calibration.py)
29
+ - repair: 指摘を渡してステージを 1 回だけやり直し、残れば記録して進む
30
+ - record: 記録だけして進む
31
+ """
32
+
33
+ name: str
34
+ check: Check | Judge
35
+ on_fail: OnFail
36
+
37
+ def __post_init__(self) -> None:
38
+ if self.on_fail not in get_args(OnFail):
39
+ raise ValueError(f"on_fail は {get_args(OnFail)} のどれかです: {self.on_fail!r}")
40
+
41
+ def evaluate(self, output: Any, stage_input: Any) -> tuple[bool, list[Finding]]:
42
+ """機械的な点検を掛ける。採点役のゲートは Pipeline が評価する。"""
43
+ if isinstance(self.check, Judge):
44
+ raise TypeError(f"ゲート {self.name!r} は採点役です。Pipeline.gate で足して、Pipeline.run の中で評価します")
45
+ result = self.check(output, stage_input)
46
+ if isinstance(result, bool):
47
+ return result, []
48
+ if result is None or isinstance(result, (str, dict)): # 1 字ずつ・キーだけの指摘に化けるのを止める
49
+ raise TypeError(
50
+ f"ゲート {self.name!r} の check は bool か指摘の list を返してください: {type(result).__name__}"
51
+ )
52
+ findings = list(result)
53
+ return not findings, findings
54
+
55
+
56
+ class GateBlocked(Exception):
57
+ """block のゲートが落ちて、実行を止めた。`result` に止まるまでの結果が入る。"""
58
+
59
+ def __init__(self, stage: str, gate: str, findings: list[Finding]) -> None:
60
+ super().__init__(f"stopped at gate {gate!r} (stage {stage!r}): {findings}")
61
+ self.stage = stage
62
+ self.gate = gate
63
+ self.findings = findings
64
+ self.result: Any = None # Pipeline.run が RunResult を入れる
gateledger/judge.py ADDED
@@ -0,0 +1,100 @@
1
+ """採点役 (Judge): 版つきの基準で、LLM にステージの出力を採点させるゲートの点検。
2
+
3
+ 使い方は機械的な点検と同じで、`Gate(名前, check=Judge(...), on_fail=...)` と書く。
4
+ 採点役のゲートは、同じステージの機械的なゲートの後に回る (安い点検で落ちた物に払わない)。
5
+
6
+ - 基準の版は、基準のファイルの中身 (と採点を頼む決まり文句) の SHA-256 から作る。中身を直せば版が変わり、
7
+ 前の判定も校正も使われなくなる。版の付け忘れが起きない。
8
+ - 判定の再利用は「採点役に見せた物の指紋 + 基準の版」で引く。モデルは鍵に入れず、記録に残す。
9
+ - 止める権限 (block) は、人との一致を測って基準を満たした採点役の判定にだけある (calibration.py)。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Literal
20
+
21
+ from pydantic import BaseModel, Field, ValidationError
22
+
23
+ from .records import Finding, _jsonable
24
+
25
+ View = Callable[[Any, Any], Any]
26
+
27
+ # 採点を頼む決まり文句。基準 (system に置く) の後ろに、採点する物と答えの形を渡す。
28
+ # ここを変えると判定が変わり得るので、基準の版の計算に含める。
29
+ TASK = """Grade the item below against the rubric in the system prompt.
30
+ Reply with exactly one JSON object and nothing else:
31
+ {"verdict": "pass" or "fail", "score": a number from 0 to 1 (optional), "findings": [{"reason": "why it fails", ...}]}
32
+ List one finding per problem. Use an empty list when the verdict is pass.
33
+
34
+ Item (JSON):
35
+ """
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Rubric:
40
+ """採点の基準。`id` (名前@版) が記録と再利用の鍵に入る。"""
41
+
42
+ name: str
43
+ text: str
44
+
45
+ @classmethod
46
+ def load(cls, path: str | Path) -> Rubric:
47
+ p = Path(path)
48
+ return cls(p.stem, p.read_text(encoding="utf-8"))
49
+
50
+ @property
51
+ def version(self) -> str:
52
+ return hashlib.sha256((TASK + self.text).encode("utf-8")).hexdigest()[:12]
53
+
54
+ @property
55
+ def id(self) -> str:
56
+ return f"{self.name}@{self.version}"
57
+
58
+
59
+ def _output_only(output: Any, stage_input: Any) -> Any:
60
+ return output
61
+
62
+
63
+ class JudgeReply(BaseModel):
64
+ verdict: Literal["pass", "fail"]
65
+ score: float | None = Field(default=None, ge=0, le=1)
66
+ findings: list[Finding] = []
67
+
68
+
69
+ class Judge:
70
+ """採点役。`model` は頼むモデル (料金表に無ければゲートを足す時点でエラー)。
71
+
72
+ `view(output, stage_input)` で、採点役に見せる物を選ぶ (既定は出力だけ)。引用の支えを見るなら根拠も入れる。
73
+ None を返すと、見せる物が無いとして採点しない (払わず合格。数の決まらない主張を 1 つずつ採点する時の空きの枠)。
74
+ 再利用の鍵の指紋は、この見せた物から取る。見せる物が変われば採点し直す。
75
+ """
76
+
77
+ def __init__(self, rubric: str | Path | Rubric, *, model: str, view: View = _output_only) -> None:
78
+ self.rubric = rubric if isinstance(rubric, Rubric) else Rubric.load(rubric)
79
+ self.model = model
80
+ self.view = view
81
+
82
+ def __repr__(self) -> str:
83
+ return f"Judge({self.rubric.id!r}, model={self.model!r})"
84
+
85
+ def messages(self, shown: Any) -> list[dict[str, Any]]:
86
+ item = json.dumps(shown, ensure_ascii=False, indent=1, sort_keys=True, default=_jsonable)
87
+ return [{"role": "user", "content": TASK + item}]
88
+
89
+ def parse(self, text: str, served: str) -> JudgeReply:
90
+ """応答から判定の JSON を読む。読めなければ止める (中身の失敗では別のモデルへ替えない)。"""
91
+ start, end = text.find("{"), text.rfind("}")
92
+ try:
93
+ if start < 0 or end < start:
94
+ raise ValueError("JSON がありません")
95
+ return JudgeReply.model_validate(json.loads(text[start : end + 1]))
96
+ except (ValueError, ValidationError) as e:
97
+ raise ValueError(
98
+ f"採点役 {served} の応答を判定として読めません ({self.rubric.id}): {e}。"
99
+ f"応答の頭: {text[:200]!r}。基準のファイルが答えの形を上書きしていないか見てください"
100
+ ) from None
gateledger/ledger.py ADDED
@@ -0,0 +1,168 @@
1
+ """受領記録の置き場。実行ごとに 1 つの JSONL へ追記するだけで、サーバーは要らない。
2
+
3
+ 採点役の判定の再利用と校正も、この置き場の記録から引く。
4
+ - 判定の索引: 全部の実行の記録から、再利用の元になる判定 (再利用でない物) を (基準の版, 見せた物の指紋) で引く。
5
+ JSONL からいつでも作り直せるので、別のファイルには書かない (同じ Ledger の中では、書いた判定をその場で足す)。
6
+ - 校正: `calibration/calibrations.jsonl` に追記する。同じ (基準の版, モデル) は最後の行が効く。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import secrets
13
+ from collections.abc import Callable
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ from . import __version__
19
+ from .calibration import Calibration, Label, Source, measure
20
+ from .prices import PriceTable
21
+ from .records import CallRecord, GateRecord, Record, RunEnd, RunStart, fingerprint, record_adapter
22
+
23
+ JudgmentKey = tuple[str, str] # (基準の版, 見せた物の指紋)
24
+
25
+
26
+ def new_run_id() -> str:
27
+ """時刻 (ミリ秒まで) + 乱数 4 桁。ファイル名に使えて、名前の順が時刻の順になる。"""
28
+ t = datetime.now(UTC)
29
+ return t.strftime("%Y%m%dT%H%M%S") + f"{t.microsecond // 1000:03d}Z-" + secrets.token_hex(2)
30
+
31
+
32
+ class RunWriter:
33
+ """1 回の実行の記録を書く口。書いた順に 1 行ずつ追記する。"""
34
+
35
+ def __init__(self, path: Path, run_id: str, on_write: Callable[[Record], None] | None = None) -> None:
36
+ self.path = path
37
+ self.run_id = run_id
38
+ self.cost_usd = 0.0
39
+ self._on_write = on_write
40
+
41
+ def write(self, record: Record) -> None:
42
+ with self.path.open("a", encoding="utf-8") as f:
43
+ f.write(record.model_dump_json() + "\n")
44
+ if isinstance(record, CallRecord) and record.cost_usd is not None:
45
+ self.cost_usd += record.cost_usd
46
+ if self._on_write is not None:
47
+ self._on_write(record)
48
+
49
+ def end(self, status: Literal["ok", "blocked", "error"], error: str | None = None) -> None:
50
+ self.write(RunEnd(run_id=self.run_id, status=status, error=error))
51
+
52
+
53
+ class Ledger:
54
+ def __init__(self, root: str | Path) -> None:
55
+ self.root = Path(root)
56
+ self._judgments: dict[JudgmentKey, list[GateRecord]] | None = None # 初めて引く時に作る
57
+
58
+ def path(self, run_id: str) -> Path:
59
+ return self.root / f"{run_id}.jsonl"
60
+
61
+ def open_run(self, pipeline: str, prices: PriceTable) -> RunWriter:
62
+ self.root.mkdir(parents=True, exist_ok=True)
63
+ run_id = new_run_id()
64
+ while self.path(run_id).exists(): # 同じミリ秒に 2 本始めた時だけ引き直す
65
+ run_id = new_run_id()
66
+ writer = RunWriter(self.path(run_id), run_id, on_write=self._remember)
67
+ writer.write(RunStart(run_id=run_id, pipeline=pipeline, prices=prices.as_of, version=__version__))
68
+ return writer
69
+
70
+ def runs(self) -> list[str]:
71
+ """記録のある実行の id を古い順に。"""
72
+ return sorted(p.stem for p in self.root.glob("*.jsonl"))
73
+
74
+ def latest(self) -> str:
75
+ runs = self.runs()
76
+ if not runs:
77
+ raise FileNotFoundError(f"{self.root} に実行の記録がありません")
78
+ return runs[-1]
79
+
80
+ def read(self, run_id: str) -> list[Record]:
81
+ with self.path(run_id).open(encoding="utf-8") as f:
82
+ return [record_adapter.validate_json(line) for line in f if line.strip()]
83
+
84
+ # ------------------------------------------------------------ 判定の再利用
85
+
86
+ def judgments(self, rubric: str, *, judged_fp: str | None = None) -> list[GateRecord]:
87
+ """再利用の元になる採点役の判定 (再利用でない物) を古い順に。judged_fp で 1 つの見せた物に絞る。"""
88
+ if self._judgments is None:
89
+ self._judgments = {}
90
+ for run_id in self.runs():
91
+ for r in self.read(run_id):
92
+ self._remember(r)
93
+ if judged_fp is not None:
94
+ return list(self._judgments.get((rubric, judged_fp), []))
95
+ return [r for (rub, _), rs in self._judgments.items() if rub == rubric for r in rs]
96
+
97
+ def _remember(self, record: Record) -> None:
98
+ if self._judgments is None or not isinstance(record, GateRecord) or record.judge is None:
99
+ return
100
+ if record.judge.reused_from is None:
101
+ self._judgments.setdefault((record.judge.rubric, record.judge.judged_fp), []).append(record)
102
+
103
+ # ------------------------------------------------------------ 校正
104
+
105
+ @property
106
+ def calibrations_path(self) -> Path:
107
+ return self.root / "calibration" / "calibrations.jsonl"
108
+
109
+ def calibration(self, rubric: str, model: str) -> Calibration | None:
110
+ """(基準の版, 応えたモデル) の一番新しい校正。無ければ None。"""
111
+ if not self.calibrations_path.exists():
112
+ return None
113
+ found = None
114
+ with self.calibrations_path.open(encoding="utf-8") as f:
115
+ for line in f:
116
+ if line.strip():
117
+ cal = Calibration.model_validate_json(line)
118
+ if (cal.rubric, cal.model) == (rubric, model):
119
+ found = cal
120
+ return found
121
+
122
+ def calibrate(self, rubric: str, model: str, labels: str | Path) -> Calibration:
123
+ """ラベル (JSONL・1 行に judged_fp と human か label) を、台帳にある `model` の判定と突き合わせて校正する。
124
+
125
+ 判定は "pass" か "fail" (採点役の判定の正否ではなく、ラベルを付けた側の判定)。人のラベルは `human`、
126
+ 別のモデルの合議で作ったラベルは `label` と `"source": "model_panel"` で書く (source の既定は human)。
127
+ 出どころの混ざったファイルは止める (校正の結果に出どころを 1 つだけ残すため)。同じ judged_fp は後の行が効く。
128
+ 台帳に判定の無いラベルがあれば止める (黙って外すと、件数と κ が実際と違って見える)。
129
+ """
130
+ human: dict[str, Label] = {}
131
+ sources: set[str] = set()
132
+ with Path(labels).open(encoding="utf-8") as f:
133
+ for i, line in enumerate(f, 1):
134
+ if not line.strip():
135
+ continue
136
+ row = json.loads(line)
137
+ value = row.get("label", row.get("human"))
138
+ if value not in ("pass", "fail"):
139
+ raise ValueError(f"{labels}:{i} の human (または label) は 'pass' か 'fail' です: {value!r}")
140
+ origin = row.get("source", "human")
141
+ if origin not in ("human", "model_panel"):
142
+ raise ValueError(f"{labels}:{i} の source は 'human' か 'model_panel' です: {origin!r}")
143
+ sources.add(origin)
144
+ human[row["judged_fp"]] = value
145
+ if len(sources) > 1:
146
+ raise ValueError(
147
+ f"{labels} に人のラベルとモデルの合議のラベルが混ざっています。出どころごとに分けてください"
148
+ )
149
+ pairs: list[tuple[Label, Label]] = []
150
+ missing: list[str] = []
151
+ for fp, label in human.items():
152
+ mine = [r for r in self.judgments(rubric, judged_fp=fp) if r.judge and r.judge.model_served == model]
153
+ if not mine or mine[0].verdict not in ("pass", "fail"):
154
+ missing.append(fp)
155
+ continue
156
+ verdict: Label = "pass" if mine[0].verdict == "pass" else "fail"
157
+ pairs.append((verdict, label))
158
+ if missing:
159
+ raise LookupError(
160
+ f"{len(missing)} 件のラベルに、台帳 {self.root} の判定がありません (基準 {rubric}・モデル {model})。"
161
+ f"例: {missing[0]}。基準の版とモデルが、ラベルを付けた判定と同じか見てください"
162
+ )
163
+ source: Source = "model_panel" if sources == {"model_panel"} else "human"
164
+ cal = measure(rubric, model, pairs, fingerprint(sorted(human.items())), source)
165
+ self.calibrations_path.parent.mkdir(parents=True, exist_ok=True)
166
+ with self.calibrations_path.open("a", encoding="utf-8") as f:
167
+ f.write(cal.model_dump_json() + "\n")
168
+ return cal