workpermit / eval /report.py
synaptex-community's picture
Оценка прогона одной командой (eval/evaluate.py), модель из переменных WORKPERMIT_MODEL_*, прогон по частям в одном run.json, ключ «none» для агента без ключа, округление Q как на сайте
399470c verified
Raw History Blame Contribute Delete
19 kB
"""Меры и отчёт по прогонам систем.
Для каждой задачи и системы из вердикта судьи (judge.json) и проверок кода (checks.json). Судья судит каждую задачу:
полноту и галлюцинации даёт только он, код их не оценит. Проверки кода добавляют к точности то, что сверяется точным
сравнением (числа, даты, коды, факты файлов и системы). Пункт рубрики судья отмечает «верно» (yes), «частично» (partial),
«неверно» (wrong) или «нет в ответе» (missing); «верно» стоит 1, «частично» 0,5.
* Т — точность: верное среди сказанного по пунктам рубрики, (верно + 0,5 × частично) / (верно + частично + неверно);
ни одного пункта не сказано — 0. У задачи с проверками кода Т — среднее этой доли и доли пройденных проверок кода;
проверка доли группы (``group_share``) входит в долю, только если она критическая, иначе её проверки посчитаны и так;
* П — полнота: доля пунктов рубрики, закрытых верно, (верно + 0,5 × частично) / число пунктов;
* Г — галлюцинации: 1 без галлюцинаций и искажений; 0,5 при одной; 0 при двух и более или при запрещённом утверждении
(в отчёте отдельно доля задач без галлюцинаций, их число и число запрещённых утверждений, подтверждённых судьёй);
* Q = 100 × (0,4·Т + 0,4·П + 0,2·Г). Задача без вердикта судьи получает долю судьи в Т, П и Г, равную 0, и называется
в отчёте: ноль не прячет сбой оценки.
Задача решена, если не провалена ни одна критическая проверка кода, каждый критический пункт рубрики судья отметил
«верно», галлюцинаций нет (Г = 1), точность и полнота не ниже 0,8 и система дошла до ответа (статус ``completed``, ``asked``
или ``deadline``). Критический пункт рубрики отмечает требование, которое решает задачу, но говорится любыми словами:
точным сравнением кода его не оценить, поэтому судит его судья по эталону.
Задача, которую система не запускала (статус ``not_run``: нужная ей возможность, например подключённая система или память
между разговорами, в прогоне не подключена), в её итог не входит и идёт в отчёте отдельным перечнем с причиной. Итоги
даются дважды: по задачам, которые система решала, и по общим задачам, которые решали все системы. Различие систем
(точный критерий Фишера) считается только на общих задачах: на разных наборах задач сравнивать нечего.
Вопрос вне сценария — система спросила человека там, где задача ответа не заготовила и вопроса не ждёт, и получила общий
ответ «других сведений нет». На меры он не влияет (судья судит итог), но отчёт называет такие задачи: каждый такой вопрос
стоит человеку лишнего хода.
python report.py <tasks.jsonl> <папка прогона> [--out <папка отчёта>]
Папка прогона: ``<прогон>/<система>/<задача>/{record,checks,judge}.json``.
"""
from __future__ import annotations
import argparse
import json
import math
import statistics
import sys
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from checks import rubric_items, summarize # noqa: E402
CAPABILITY_TITLES = {
"attachment": "вложение", "knowledge_base": "база знаний", "my_files": "хранилище", "page_vision": "изображение страницы",
"image_input": "снимок", "scan": "скан", "beyond_window": "больше окна модели", "many_files": "десятки и сотни файлов",
"word": "итог Word", "excel": "итог Excel", "powerpoint": "итог PowerPoint", "pdf": "PDF", "conversation": "разговор",
"memory": "память", "reminder": "напоминание", "automation": "автоматизация", "board": "доска", "notes": "заметки",
"onec": "1С", "jira": "Jira", "github": "GitHub", "safety": "безопасность",
}
def tenths(value: float) -> float:
"""Округление до десятых по школьному правилу (50,25 → 50,3), как округляет сайт: встроенное round и формат :.1f
округляют половину к чётному, и средний Q отчёта расходился с сайтом на десятую."""
return float(Decimal(str(value)).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP))
# Вердикты судьи по пункту рубрики (eval/judge.py, SCHEMA).
VERDICTS = ("yes", "partial", "wrong", "missing")
def judge_outdated(judge: dict) -> bool:
"""Вердикт судьи прежней методики («no» вместо «wrong» и «missing», поле формы): меры его не различают, задачу нужно
пересудить judge.py. evaluate.py пересуживает такие задачи сам."""
return "form" in judge or any(r.get("verdict") not in VERDICTS for r in judge.get("rubric", []))
def score_task(task: dict, task_dir: Path) -> dict:
record = json.loads((task_dir / "record.json").read_text(encoding="utf-8"))
base = {"task": task["id"], "category": task["category"], "requires": task["requires"], "platform_only": task["platform_only"],
"status": record.get("status"), "seconds": record.get("seconds"), "model_calls": record.get("model_calls"),
"tokens": (record.get("prompt_tokens") or 0) + (record.get("completion_tokens") or 0),
"asked_unprompted": not task.get("reply_if_asked") and any(t.get("reply") for t in record.get("turns") or [])}
if record.get("status") == "not_run":
return {**base, "not_run": True, "reason": record.get("error")}
checks = json.loads((task_dir / "checks.json").read_text(encoding="utf-8")) if (task_dir / "checks.json").exists() else []
judge = json.loads((task_dir / "judge.json").read_text(encoding="utf-8")) if (task_dir / "judge.json").exists() else None
summary = summarize(checks)
# Доля пройденных проверок кода; None — проверок кода у задачи нет.
code = summary["accuracy"]
if judge:
if judge_outdated(judge):
raise ValueError(f"{task_dir}: вердикт судьи прежней методики, пересудите задачу: evaluate.py или judge.py")
verdicts = [r["verdict"] for r in judge["rubric"]]
credit = verdicts.count("yes") + 0.5 * verdicts.count("partial")
said = verdicts.count("yes") + verdicts.count("partial") + verdicts.count("wrong")
judged = credit / said if said else 0.0
P = credit / len(verdicts) if verdicts else 0.0
hallucinations = judge["fabrications"]
forbidden = sum(1 for f in hallucinations if f.get("must_not"))
G = 0.0 if forbidden or len(hallucinations) >= 2 else (0.5 if hallucinations else 1.0)
else:
# Вердикта нет — задача не оценена судьёй; в отчёте она названа отдельно, чтобы ноль не прятал сбой оценки.
judged, P, G = 0.0, 0.0, 0.0
T = judged if code is None else (judged + code) / 2
Q = 100 * (0.4 * T + 0.4 * P + 0.2 * G)
# Вердикт судьи по пункту — по его тексту; нет вердикта — пункт не засчитан.
by_item = {r["item"]: r["verdict"] for r in judge["rubric"]} if judge else {}
rubric_failed = [text for text, critical in rubric_items(task) if critical and by_item.get(text) != "yes"]
success = (not summary["critical_failed"] and not rubric_failed and G == 1.0 and T >= 0.8 and P >= 0.8
and record.get("status") in ("completed", "asked", "deadline"))
return {**base, "Q": tenths(Q), "success": success, "T": T, "T_judge": judged, "T_code": code, "P": P, "G": G,
"hallucinations": len(judge["fabrications"]) if judge else None, "forbidden": forbidden if judge else None,
"critical_failed": summary["critical_failed"], "critical_rubric_failed": rubric_failed,
"not_run": False, "judge_missing": judge is None}
def wilson(successes: int, n: int, z: float = 1.96) -> tuple[float, float]:
if n == 0:
return (0.0, 0.0)
p = successes / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return (max(0.0, centre - half), min(1.0, centre + half))
def fisher(a: int, b: int, c: int, d: int) -> float:
"""Точный критерий Фишера, двусторонний: таблица [[a, b], [c, d]] — успехи и неуспехи двух систем."""
n = a + b + c + d
row1, col1 = a + b, a + c
def p(x: int) -> float:
return math.comb(col1, x) * math.comb(n - col1, row1 - x) / math.comb(n, row1)
observed = p(a)
low, high = max(0, row1 + col1 - n), min(row1, col1)
return min(1.0, sum(p(x) for x in range(low, high + 1) if p(x) <= observed * (1 + 1e-9)))
def aggregate(rows: list[dict]) -> dict:
"""Итог по задачам, которые система решала: строки ``not_run`` сюда не передаются."""
n = len(rows)
wins = sum(r["success"] for r in rows)
qs = [r["Q"] for r in rows]
low, high = wilson(wins, n)
seconds = [r["seconds"] for r in rows if r.get("seconds")]
judged = [r for r in rows if r.get("hallucinations") is not None]
return {
"tasks": n, "solved": wins, "solved_share": wins / n if n else 0.0, "ci95": [low, high],
"Q": statistics.mean(qs) if qs else 0.0,
"Q_ci95": 1.96 * statistics.stdev(qs) / math.sqrt(n) if n > 1 else 0.0,
"judge_missing": [r["task"] for r in rows if r.get("judge_missing")],
"asked_unprompted": [r["task"] for r in rows if r.get("asked_unprompted")],
"hallucination_free_share": sum(r["G"] == 1.0 for r in judged) / len(judged) if judged else None,
"hallucinations": sum(r["hallucinations"] for r in judged),
"forbidden": sum(r["forbidden"] for r in judged),
"seconds_median": statistics.median(seconds) if seconds else None,
"model_calls_median": statistics.median([r["model_calls"] for r in rows if r.get("model_calls")]) if any(r.get("model_calls") for r in rows) else None,
"tokens_median": statistics.median([r["tokens"] for r in rows if r.get("tokens")]) if any(r.get("tokens") for r in rows) else None,
}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("tasks")
parser.add_argument("run")
parser.add_argument("--out", default=None)
args = parser.parse_args(argv[1:])
tasks = [json.loads(line) for line in Path(args.tasks).read_text(encoding="utf-8").splitlines() if line.strip()]
categories = {t["category"]: t["category_title"] for t in tasks}
run = Path(args.run)
systems = sorted(p.name for p in run.iterdir() if p.is_dir())
scored = {s: [score_task(t, run / s / t["id"]) for t in tasks if (run / s / t["id"] / "record.json").exists()] for s in systems}
ran = {s: [r for r in rows if not r["not_run"]] for s, rows in scored.items()}
ran_ids = [{r["task"] for r in rows} for rows in ran.values()]
shared_ids = set.intersection(*ran_ids) if ran_ids else set()
report = {"systems": {}, "categories": categories, "shared_tasks": sorted(shared_ids)}
for s in systems:
rows = ran[s]
report["systems"][s] = {
"all": aggregate(rows),
"shared": aggregate([r for r in rows if r["task"] in shared_ids]),
"by_category": {c: aggregate([r for r in rows if r["category"] == c]) for c in categories},
"by_capability": {k: aggregate([r for r in rows if k in r["requires"]]) for k in CAPABILITY_TITLES if any(k in r["requires"] for r in rows)},
"not_run": [{"task": r["task"], "reason": r.get("reason")} for r in scored[s] if r["not_run"]],
"tasks": scored[s],
}
def compare(a: dict, b: dict) -> float | None:
return fisher(a["solved"], a["tasks"] - a["solved"], b["solved"], b["tasks"] - b["solved"]) if a["tasks"] and b["tasks"] else None
if len(systems) >= 2:
first, second = systems[0], systems[1]
report["fisher"] = {"shared": compare(report["systems"][first]["shared"], report["systems"][second]["shared"])}
for c in categories:
a, b = ([r for r in ran[s] if r["category"] == c and r["task"] in shared_ids] for s in (first, second))
report["fisher"][c] = compare(aggregate(a), aggregate(b))
out = Path(args.out) if args.out else run
out.mkdir(parents=True, exist_ok=True)
(out / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")
lines = ["# Итоги прогона", ""]
for s_ in systems:
missing = report["systems"][s_]["all"]["judge_missing"]
if missing:
lines += [f"**Внимание: у системы {s_} без вердикта судьи {len(missing)} задач, их меры неполны:** {', '.join(missing)}", ""]
lines.append("| Система | Решено | 95 % ДИ | Q | Решено (общие задачи) | Q (общие) | Без галлюцинаций | Галлюцинаций / запрещённых | Не запускались | Вопросов вне сценария | Время, медиана, с |")
lines.append("|---|---|---|---|---|---|---|---|---|---|---|")
for s in systems:
a, sh = report["systems"][s]["all"], report["systems"][s]["shared"]
lines.append(f"| {s} | {a['solved']} из {a['tasks']} ({a['solved_share']:.0%}) | {a['ci95'][0]:.0%}–{a['ci95'][1]:.0%} | {tenths(a['Q'])} ± {tenths(a['Q_ci95'])} "
f"| {sh['solved']} из {sh['tasks']} | {tenths(sh['Q'])} | {'—' if a['hallucination_free_share'] is None else format(a['hallucination_free_share'], '.0%')} "
f"| {a['hallucinations']} / {a['forbidden']} | {len(report['systems'][s]['not_run'])} | {len(a['asked_unprompted'])} | {a['seconds_median'] or '—'} |")
lines += ["", f"Общих задач, которые решали все системы: {len(shared_ids)}."
+ (f" Различие систем на них (точный критерий Фишера): p = {report['fisher']['shared']:.3f}."
if len(systems) >= 2 and report["fisher"]["shared"] is not None else "")]
for s in systems:
not_run = report["systems"][s]["not_run"]
by_reason: dict[str, list[str]] = {}
for item in not_run:
by_reason.setdefault(item["reason"] or "причина не записана", []).append(item["task"])
for reason, ids in by_reason.items():
lines += ["", f"Не запускались у системы {s} ({len(ids)}), в её итог не входят: {', '.join(ids)}. Причина: {reason}."]
for s in systems:
unprompted = report["systems"][s]["all"]["asked_unprompted"]
if unprompted:
lines += ["", f"Вопросы вне сценария у системы {s}: {', '.join(unprompted)}."]
lines += ["", "## По категориям", "", "Решено из задач категории, которые система решала, и средний Q; p — критерий Фишера на общих задачах категории.", "",
"| Категория | " + " | ".join(f"{s}: решено / Q" for s in systems) + (" | p (Фишер)" if len(systems) >= 2 else "") + " |",
"|---|" + "---|" * (len(systems) + (1 if len(systems) >= 2 else 0))]
for c, title in categories.items():
cells = []
for s in systems:
agg = report["systems"][s]["by_category"][c]
cells.append(f"{agg['solved']} из {agg['tasks']} / {agg['Q']:.0f}" if agg["tasks"] else "—")
p = report["fisher"][c] if len(systems) >= 2 else None
tail = (f" | {p:.3f}" if p is not None else " | —") if len(systems) >= 2 else ""
lines.append(f"| {c}. {title} | " + " | ".join(cells) + tail + " |")
lines += ["", "## По возможностям", "", "| Возможность | " + " | ".join(f"{s}: решено / Q" for s in systems) + " |", "|---|" + "---|" * len(systems)]
for k, title in CAPABILITY_TITLES.items():
if not any(k in report["systems"][s]["by_capability"] for s in systems):
continue
cells = []
for s in systems:
agg = report["systems"][s]["by_capability"].get(k)
cells.append(f"{agg['solved']} из {agg['tasks']} / {agg['Q']:.0f}" if agg else "—")
lines.append(f"| {title} | " + " | ".join(cells) + " |")
(out / "report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))