Coverage for app / services / evaluation / criteria.py: 96%

101 statements  

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

1""" 

2Criteria and facts — the itemised half of a case's label. 

3 

4**Criteria** are a list of items, each a thing a good answer does, in words: 

5``{"text": "Discounts each cash flow correctly", "gate": false}``. The 

6dataset carries items every case inherits; each case adds its own. An LLM 

7judge marks every item met or not met with a reason, and the case score is 

8the share met — so a result says *which* criterion failed, not just a number, 

9and a criterion can be reported across a whole dataset ("does not fabricate: 

10failed 30% of the time"). A **gate** is an item whose failure fails the case 

11outright, whatever else was met: an answer that invents a share price is not 

12three-quarters correct. 

13 

14**Facts** are what a correct answer must state, checked by code rather than a 

15model: ``{"label": "NPV", "value": 19781, "tolerance_pct": 1}``. A number is 

16found anywhere in the answer, whatever its formatting — "£19,781", "19,780.99", 

17"£2.2m", "30%" — and matches within the tolerance. A text fact matches when 

18any of its accepted spellings appears. Facts live in a case's checks 

19(``expectation["facts"]``) and are applied by both the text-check scorer and 

20the LLM judge, because a figure is either right or it is not, and a judge's 

21opinion of whether 19,780 "is about" 19,781 is not the measurement. 

22 

23Criteria used to be one block of text. :func:`items` still reads that shape — 

24lines beginning ``-``, ``*`` or ``1.`` become items, anything else one item — 

25so historical rows, old API clients and imported files all normalise the same 

26way. 

27""" 

28 

29from __future__ import annotations 

30 

31import re 

32from typing import Any 

33 

34#: The tolerance a numeric fact gets when it names none: 1% either side. 

35#: Wide enough for rounding ("£19,781" against 19,781.30), narrow enough that 

36#: a different answer does not pass. 

37DEFAULT_TOLERANCE_PCT = 1.0 

38 

39MAX_ITEM_CHARS = 1000 

40 

41_BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+") 

42 

43 

44def items(value: Any) -> list[dict[str, Any]]: 

45 """Normalise criteria in any accepted shape to ``[{text, gate}]``. 

46 

47 Accepts a list of items or strings, or text. Text is split into items when 

48 it is written as a list (every non-blank line a bullet or a number), and 

49 kept as one item otherwise — a paragraph is one criterion, not a list of 

50 sentences. 

51 """ 

52 if value is None: 

53 return [] 

54 if isinstance(value, list): 

55 out = [] 

56 for entry in value: 

57 if isinstance(entry, dict): 

58 text = str(entry.get("text") or "").strip() 

59 gate = entry.get("gate") is True 

60 else: 

61 text, gate = str(entry or "").strip(), False 

62 if text: 

63 out.append({"text": text[:MAX_ITEM_CHARS], "gate": gate}) 

64 return out 

65 text = str(value).strip() 

66 if not text: 

67 return [] 

68 lines = [line for line in text.splitlines() if line.strip()] 

69 if len(lines) > 1 and all(_BULLET.match(line) for line in lines): 

70 return [ 

71 {"text": _BULLET.sub("", line).strip()[:MAX_ITEM_CHARS], "gate": False} 

72 for line in lines 

73 ] 

74 return [{"text": text[:MAX_ITEM_CHARS], "gate": False}] 

75 

76 

77def as_text(value: Any) -> str: 

78 """Criteria as one bulleted block, for a reader that wants prose.""" 

79 return "\n".join( 

80 f"- {item['text']}" + (" (must pass)" if item["gate"] else "") 

81 for item in items(value) 

82 ) 

83 

84 

85# ── Facts ───────────────────────────────────────────────────────────────────── 

86 

87_SUFFIXES = { 

88 "k": 1e3, 

89 "thousand": 1e3, 

90 "m": 1e6, 

91 "mn": 1e6, 

92 "million": 1e6, 

93 "b": 1e9, 

94 "bn": 1e9, 

95 "billion": 1e9, 

96} 

97 

98#: A number as people write one: optional sign and currency, thousands 

99#: separators, decimals, and a scale word or a percent sign after it. 

100_NUMBER = re.compile( 

101 # A sign only counts where it cannot be a hyphen: "2020-2021" is two 

102 # years, not 2020 and minus 2021. 

103 r"(?:(?<![\w.])(?P<sign>[-−–]))?\s?[£$€]?\s?(?:(?<![\w.])(?P<sign2>[-−–]))?" 

104 r"(?P<num>\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)" 

105 r"(?:\s?(?P<suffix>thousand|million|billion|bn|mn|[kmb])(?![a-z]))?", 

106 re.IGNORECASE, 

107) 

108 

109 

110def numbers_in(text: str) -> list[float]: 

111 """Every number written in ``text``, scaled and signed.""" 

112 out = [] 

113 for match in _NUMBER.finditer(text or ""): 

114 value = float(match.group("num").replace(",", "")) 

115 suffix = (match.group("suffix") or "").lower() 

116 value *= _SUFFIXES.get(suffix, 1) 

117 if match.group("sign") or match.group("sign2"): 

118 value = -value 

119 out.append(value) 

120 return out 

121 

122 

123def _as_number(value: Any) -> float | None: 

124 if isinstance(value, bool): 

125 return None 

126 if isinstance(value, (int, float)): 

127 return float(value) 

128 if isinstance(value, str): 

129 found = numbers_in(value) 

130 # "30%" or "£19,781" is a number; "Project C" is text. 

131 if len(found) == 1 and not re.search(r"[a-z]{2,}", value, re.IGNORECASE): 

132 return found[0] 

133 return None 

134 

135 

136def facts(value: Any) -> list[dict[str, Any]]: 

137 """Normalise a case's facts to ``[{label, value, tolerance_pct, gate}]``. 

138 

139 Numeric values — including "30%" and "£19,781" — become numbers; anything 

140 else is a list of accepted spellings. Malformed entries are dropped. 

141 """ 

142 out = [] 

143 for entry in value if isinstance(value, list) else []: 

144 if not isinstance(entry, dict) or entry.get("value") in (None, "", []): 

145 continue 

146 raw = entry["value"] 

147 number = None if isinstance(raw, list) else _as_number(raw) 

148 fact: dict[str, Any] = { 

149 "label": str(entry.get("label") or "").strip() or None, 

150 "gate": entry.get("gate") is True, 

151 } 

152 if number is not None: 

153 fact["value"] = number 

154 try: 

155 tolerance = float(entry.get("tolerance_pct", DEFAULT_TOLERANCE_PCT)) 

156 except (TypeError, ValueError): 

157 tolerance = DEFAULT_TOLERANCE_PCT 

158 fact["tolerance_pct"] = max(0.0, tolerance) 

159 else: 

160 spellings = raw if isinstance(raw, list) else [raw] 

161 fact["value"] = [str(s).strip() for s in spellings if str(s).strip()] 

162 if not fact["value"]: 

163 continue 

164 out.append(fact) 

165 return out 

166 

167 

168def describe_fact(fact: dict[str, Any]) -> str: 

169 label = f"{fact['label']}: " if fact.get("label") else "" 

170 value = fact["value"] 

171 if isinstance(value, list): 

172 return f"{label}states {' / '.join(repr(v) for v in value)}" 

173 return f"{label}states {value:g} (±{fact['tolerance_pct']:g}%)" 

174 

175 

176def check_fact(fact: dict[str, Any], output: str) -> tuple[bool, str]: 

177 """Whether ``output`` states ``fact``, and what was found.""" 

178 value = fact["value"] 

179 if isinstance(value, list): 

180 haystack = (output or "").lower() 

181 hit = next((v for v in value if v.lower() in haystack), None) 

182 return (hit is not None, f"Found {hit!r}." if hit else "Not stated.") 

183 allowance = abs(value) * fact["tolerance_pct"] / 100 

184 found = numbers_in(output) 

185 close = [n for n in found if abs(n - value) <= allowance] 

186 if close: 

187 return True, f"Found {close[0]:g}." 

188 if not found: 

189 return False, "No number in the answer." 

190 nearest = min(found, key=lambda n: abs(n - value)) 

191 return False, f"Nearest figure {nearest:g}, expected {value:g}." 

192 

193 

194# ── Expected behaviour ──────────────────────────────────────────────────────── 

195 

196#: What a case expects the agent to *do*, and the criterion that says so. 

197#: Some questions are right to answer; some are right to question back 

198#: ("what return — ROI, IRR or payback?"); some are right to decline. A label 

199#: that only describes a correct answer cannot express the second two. 

200BEHAVIOURS: dict[str, str] = { 

201 "answer": "Answers the question, without asking for clarification or declining", 

202 "clarify": "Asks for clarification instead of answering — it does not guess", 

203 "decline": "Declines to answer, and says why", 

204} 

205 

206 

207def behaviour_verdict(expected: str | None, asked: bool) -> dict[str, Any] | None: 

208 """The behaviour criterion for a cell, decided by code where it can be. 

209 

210 ``asked`` is whether the agent paused on ``ask_user``. That settles it 

211 either way: asking is exactly right for ``clarify`` and exactly wrong for 

212 the other two. When it did not ask, whether the text answers, questions 

213 back or declines is a judgement — ``met`` is None, for the judge. 

214 Always a gate: an answer to a question that needed clarifying is not 

215 partly right. 

216 """ 

217 if expected not in BEHAVIOURS: 

218 return None 

219 verdict: dict[str, Any] = { 

220 "text": BEHAVIOURS[expected], 

221 "source": "behaviour", 

222 "gate": True, 

223 "met": None, 

224 "reason": None, 

225 } 

226 if asked: 

227 verdict["met"] = expected == "clarify" 

228 verdict["reason"] = "Paused to ask the user (ask_user)." 

229 return verdict