Coverage for app / services / evaluation / risk.py: 82%

77 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Expected quality and risk — an agent's answers read like an asset's returns. 

3 

4A mean score says how good an agent's answers are *on average*. It does not 

5say how far one answer may fall from that average, and two agents with the 

6same mean can differ exactly there: one gives steady answers a little short of 

7perfect, the other mostly perfect answers and now and then a useless one. The 

8second is the riskier one to put in front of a customer, though its average 

9reads the same. That is the question portfolio theory asks of an asset — 

10expected return and volatility — and it is answered the same way here: 

11 

12* **Expected quality** (``mean``) — the average answer score across the 

13 datasets, **each dataset weighted equally**. A dataset is one capability 

14 (grounding, refusal, tool use …), and the number of cases each happens to 

15 carry is not a reason to count one capability for more than another. 

16* **Risk** (``sd``) — the standard deviation of individual answer scores 

17 under the same weights: how far one answer may land from the average. 

18 Every answer counts, repeats included, because every answer is one a 

19 person could have been given. 

20 

21The variance splits into two parts that call for different fixes: 

22 

23* **within** — answers to one kind of question disagree with each other: the 

24 agent is erratic. Read the low-scoring cells of the dataset concerned. 

25* **between** — the agent is steady inside each dataset but much better at 

26 some than at others: one capability is weak. Work on that dataset. 

27 

28``within + between`` is the total (the law of total variance over an 

29equally weighted mixture of the datasets' answers), so both are reported as 

30standard deviations and as the share of the variance each explains. 

31 

32Bands (``RISK_BANDS``) put a name to ``sd`` on the 0–1 score scale. The 

33cut-offs come from the shape the gold datasets' judge gives scores: a passed 

34answer scores around 0.9–1.0 and a failed gate scores 0, so ``sd`` is driven 

35mostly by how often an answer fails outright. Among otherwise ~0.95 answers, 

36about one in forty failing gives ``sd`` ≈ 0.15, and about one in nine gives 

37≈ 0.30. 

38 

39Fewer than ``MIN_ANSWERS`` answers give no band: the standard deviation of a 

40handful of answers moves by most of a band's width from one run to the next. 

41""" 

42 

43from __future__ import annotations 

44 

45import math 

46from collections.abc import Iterable, Mapping, Sequence 

47from dataclasses import dataclass 

48from typing import Any, Optional 

49from uuid import UUID 

50 

51from sqlalchemy.orm import Session 

52 

53from app.db.postgres.models import ExperimentRun 

54from app.services.evaluation.scorers import stored_value 

55 

56#: ``(band, sd below which it applies)``, lowest first; the last band takes 

57#: everything above. See the module docstring for where the cut-offs come from. 

58RISK_BANDS: tuple[tuple[str, float], ...] = ( 

59 ("low", 0.15), 

60 ("moderate", 0.30), 

61 ("high", math.inf), 

62) 

63 

64#: Answers below which the standard deviation is too unsteady to band. 

65MIN_ANSWERS = 10 

66 

67 

68def band(sd: Optional[float], answers: int) -> Optional[str]: 

69 """The risk band for ``sd`` over ``answers`` answers, or None when there 

70 are too few to say.""" 

71 if sd is None or answers < MIN_ANSWERS: 

72 return None 

73 for name, below in RISK_BANDS: 

74 if sd < below: 

75 return name 

76 return RISK_BANDS[-1][0] 

77 

78 

79def _round(value: float) -> float: 

80 return round(value, 4) 

81 

82 

83@dataclass(frozen=True) 

84class QualityProfile: 

85 """Expected quality and risk over one or more datasets' answers.""" 

86 

87 mean: float 

88 sd: float 

89 within_sd: float 

90 between_sd: float 

91 #: Share of the variance from answers disagreeing inside a dataset; None 

92 #: when every answer scored the same (there is no variance to share). 

93 within_share: Optional[float] 

94 answers: int 

95 datasets: int 

96 risk: Optional[str] 

97 

98 def as_json(self) -> dict[str, Any]: 

99 return { 

100 "mean": _round(self.mean), 

101 "sd": _round(self.sd), 

102 "within_sd": _round(self.within_sd), 

103 "between_sd": _round(self.between_sd), 

104 "within_share": ( 

105 _round(self.within_share) if self.within_share is not None else None 

106 ), 

107 "answers": self.answers, 

108 "datasets": self.datasets, 

109 "risk": self.risk, 

110 } 

111 

112 

113def profile(samples: Mapping[Any, Sequence[float]]) -> Optional[QualityProfile]: 

114 """The profile of ``{dataset: [answer score, …]}``, each dataset weighted 

115 equally. Datasets with no scored answer are left out; None when none has 

116 one.""" 

117 groups = [list(scores) for scores in samples.values() if scores] 

118 if not groups: 

119 return None 

120 means = [sum(g) / len(g) for g in groups] 

121 variances = [sum((x - m) ** 2 for x in g) / len(g) for g, m in zip(groups, means)] 

122 weight = 1 / len(groups) 

123 mean = sum(means) * weight 

124 within = sum(variances) * weight 

125 between = sum((m - mean) ** 2 for m in means) * weight 

126 total = within + between 

127 sd = math.sqrt(total) 

128 answers = sum(len(g) for g in groups) 

129 return QualityProfile( 

130 mean=mean, 

131 sd=sd, 

132 within_sd=math.sqrt(within), 

133 between_sd=math.sqrt(between), 

134 within_share=(within / total) if total > 0 else None, 

135 answers=answers, 

136 datasets=len(groups), 

137 risk=band(sd, answers), 

138 ) 

139 

140 

141def _uuid(value: Any) -> Optional[UUID]: 

142 try: 

143 return value if isinstance(value, UUID) else UUID(str(value)) 

144 except (TypeError, ValueError): 

145 return None 

146 

147 

148def answer_scores( 

149 db: Session, batch_ids: Iterable[Any] 

150) -> dict[tuple[str, Optional[str]], list[float]]: 

151 """Every scored answer of ``batch_ids``, as ``{(batch, variant): [score, 

152 …]}`` — the cells a run's ``mean_score`` was taken over.""" 

153 ids = list(dict.fromkeys(_uuid(b) for b in batch_ids)) 

154 ids = [i for i in ids if i is not None] 

155 if not ids: 

156 return {} 

157 rows = ( 

158 db.query(ExperimentRun.batch_id, ExperimentRun.variant_id, ExperimentRun.score) 

159 .filter(ExperimentRun.batch_id.in_(ids)) 

160 .all() 

161 ) 

162 out: dict[tuple[str, Optional[str]], list[float]] = {} 

163 for batch_id, variant_id, score in rows: 

164 value = stored_value(score) 

165 if value is None: 

166 continue 

167 key = (str(batch_id), str(variant_id) if variant_id else None) 

168 out.setdefault(key, []).append(value) 

169 return out 

170 

171 

172def scores_of( 

173 scores: Mapping[tuple[str, Optional[str]], list[float]], 

174 batch_id: Any, 

175 variant_id: Any = None, 

176) -> list[float]: 

177 """One variant's answers in one run, or — with no variant named — every 

178 answer of the run.""" 

179 batch = str(batch_id) 

180 if variant_id is not None: 

181 return list(scores.get((batch, str(variant_id)), [])) 

182 return [x for (b, _), values in scores.items() if b == batch for x in values] 

183 

184 

185def efficient(points: Mapping[Any, tuple[float, float]]) -> set[Any]: 

186 """The keys of ``{key: (mean, sd)}`` no other point beats on both — as 

187 good an average for no more risk. The efficient frontier of portfolio 

188 theory: everything off it has a rival that is at least as good on one 

189 count and better on the other.""" 

190 out: set[Any] = set() 

191 for key, (mean, sd) in points.items(): 

192 beaten = any( 

193 other != key and m >= mean and s <= sd and (m > mean or s < sd) 

194 for other, (m, s) in points.items() 

195 ) 

196 if not beaten: 

197 out.add(key) 

198 return out