from __future__ import annotations import math from collections.abc import Callable from dataclasses import dataclass from typing import Literal Same = Callable[[str, str], bool] @dataclass(frozen=True) class Vote: answer: str | None confidence: float @dataclass(frozen=True) class Decision: answer: str | None share: float n_used: int def tail_confidence(logprobs: list[float], window: int = 2048) -> float: tail = logprobs[-window:] if not tail: raise ValueError("logprobs is empty") return sum(tail) / len(tail) def cluster(answers: list[str | None], same: Same) -> list[list[int]]: groups: list[list[int]] = [] for i, answer in enumerate(answers): if answer is None: continue for group in groups: if same(answers[group[0]], answer): # type: ignore[arg-type] group.append(i) break else: groups.append([i]) return groups def decide( votes: list[Vote], same: Same, keep_top: float = 1.0, weighting: Literal["count", "confidence"] = "count", ) -> Decision: # Votes without an answer carry no information, so they neither count towards keep_top nor the share. answered = [v for v in votes if v.answer is not None] if not answered: return Decision(None, 0.0, 0) n_keep = max(1, math.ceil(round(keep_top * len(answered), 9))) kept = sorted(answered, key=lambda v: -v.confidence)[:n_keep] top = kept[0].confidence weights = [math.exp(v.confidence - top) if weighting == "confidence" else 1.0 for v in kept] groups = cluster([v.answer for v in kept], same) best_group = max( groups, key=lambda g: (sum(weights[i] for i in g), max(kept[i].confidence for i in g)), ) winner = max(best_group, key=lambda i: kept[i].confidence) return Decision( answer=kept[winner].answer, share=sum(weights[i] for i in best_group) / sum(weights), n_used=len(kept), ) def should_stop( votes: list[Vote], same: Same, min_votes: int = 8, threshold: float = 0.75, **decide_kwargs ) -> bool: if len(votes) < min_votes: return False decision = decide(votes, same, **decide_kwargs) return decision.answer is not None and decision.share >= threshold