Coverage for app / services / rules / fields.py: 96%

278 statements  

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

1""" 

2Condition fields — everything a rule can ask a question about. 

3 

4One class per field, registered with :func:`register_field`. A field owns 

5three things: the value type it resolves to (which decides the operators it 

6may be paired with), the phases it is available in, and how to *resolve* it 

7from the evaluation context. 

8 

9Resolution is the reason most of this vocabulary needed no call-site change. 

10``prompt_tokens`` is not something an invocation has to remember to pass — the 

11field derives it from the prompt already in the context, and uses a value the 

12caller did pass in preference to its own. Call sites stay as they are, and a 

13field that later becomes cheap to pass exactly can start being passed exactly 

14without the rules that read it changing. 

15 

16A field absent from the context resolves to None, which the evaluator treats 

17as a non-match. That is deliberate: a policy rule conditioned on a latency 

18figure that does not exist yet must not fire, and must not block. 

19""" 

20 

21from __future__ import annotations 

22 

23import logging 

24from abc import ABC, abstractmethod 

25from enum import StrEnum 

26from typing import Any, ClassVar 

27 

28from app.db.postgres.enums import UsageEnum 

29from app.services import quality_check 

30from app.services.rules import pii 

31from app.services.rules.operators import Operator, ValueType, operators_for 

32 

33logger = logging.getLogger(__name__) 

34 

35 

36class Phase(StrEnum): 

37 """When a condition is evaluated, and therefore what it can see. 

38 

39 A field is offered by the rule builder only for the layers whose phase it 

40 belongs to (``layers.Layer.phase``) — which is what stops someone writing 

41 an Input rule against ``response``, a value that does not exist until 

42 after the model has already been called. 

43 """ 

44 

45 #: Before the prompt reaches the model — Access and Input rules. 

46 input = "input" 

47 #: After the response returns — Output rules. 

48 output = "output" 

49 

50 

51#: Phases in which the invocation's own identity is known. Used by the many 

52#: fields that describe *who and what* is running rather than the text. 

53IDENTITY_PHASES: frozenset[Phase] = frozenset({Phase.input, Phase.output}) 

54 

55 

56class Field(ABC): 

57 """Base class for every value a condition can be written against.""" 

58 

59 #: Stable key stored in the condition block and sent over the API. 

60 key: ClassVar[str] 

61 #: Human label for the rule builder. 

62 label: ClassVar[str] 

63 #: One line explaining what the value is, surfaced in the catalogue. 

64 description: ClassVar[str] = "" 

65 #: Grouping for the builder's field picker. 

66 group: ClassVar[str] = "general" 

67 #: What this field resolves to — decides which operators may be paired. 

68 value_type: ClassVar[ValueType] 

69 #: Phases in which this field has a value. 

70 phases: ClassVar[frozenset[Phase]] 

71 #: Closed value set — an ``enum`` field's choices, or the members a 

72 #: ``list`` field can hold. Empty otherwise. 

73 options: ClassVar[tuple[str, ...]] = () 

74 #: The catalogue section that describes ``options`` (``"pii_kinds"``), 

75 #: so the builder can show each one's label and group instead of a key. 

76 vocabulary: ClassVar[str | None] = None 

77 

78 @abstractmethod 

79 def resolve(self, context: dict[str, Any]) -> Any: 

80 """The field's value for this invocation, or None if unavailable.""" 

81 

82 def spec(self) -> dict[str, Any]: 

83 """Catalogue entry for this field, including its legal operators.""" 

84 return { 

85 "key": self.key, 

86 "label": self.label, 

87 "description": self.description, 

88 "group": self.group, 

89 "value_type": self.value_type.value, 

90 "phases": sorted(phase.value for phase in self.phases), 

91 "options": list(self.options), 

92 "vocabulary": self.vocabulary, 

93 "operators": [operator.key for operator in operators_for(self.value_type)], 

94 } 

95 

96 

97# ── Registry ────────────────────────────────────────────────────────────────── 

98 

99_REGISTRY: dict[str, Field] = {} 

100 

101 

102def register_field(cls: type[Field]) -> type[Field]: 

103 """Class decorator adding one field to the registry.""" 

104 instance = cls() 

105 if instance.key in _REGISTRY: 

106 raise RuntimeError(f"Condition field '{instance.key}' is already registered.") 

107 _REGISTRY[instance.key] = instance 

108 return cls 

109 

110 

111def get_field(key: str) -> Field | None: 

112 """The field registered under ``key``, or None if there is none.""" 

113 return _REGISTRY.get(key) 

114 

115 

116def field_keys() -> frozenset[str]: 

117 """Every registered field key.""" 

118 return frozenset(_REGISTRY) 

119 

120 

121def catalogue(phase: Phase | None = None) -> list[dict[str, Any]]: 

122 """Registered fields, optionally narrowed to those available in ``phase``.""" 

123 return [ 

124 field.spec() 

125 for field in _REGISTRY.values() 

126 if phase is None or phase in field.phases 

127 ] 

128 

129 

130def supports(field: Field, operator: Operator) -> bool: 

131 """Whether ``operator`` may be paired with ``field``.""" 

132 return field.value_type in operator.applies_to 

133 

134 

135# ── Derivation helpers ──────────────────────────────────────────────────────── 

136 

137 

138def _passthrough(context: dict[str, Any], *keys: str) -> Any: 

139 """First non-None value among ``keys``, so a field can accept aliases. 

140 

141 Call sites were written at different times and name the same thing 

142 differently (``model_name`` in one, ``model`` in another). Accepting both 

143 is cheaper than a migration that has to touch every invocation path. 

144 """ 

145 for key in keys: 

146 value = context.get(key) 

147 if value is not None: 

148 return value 

149 return None 

150 

151 

152_TOKENISER = None 

153 

154 

155def _count_tokens(text: str) -> int: 

156 """Token count for ``text`` using the same encoding svc-core chunks with. 

157 

158 Loaded lazily and cached: importing the encoding costs real time, and the 

159 overwhelming majority of invocations are governed by rules that never ask 

160 about tokens. Falls back to a four-characters-per-token estimate if the 

161 encoding is unavailable, because a governance rule that silently stops 

162 being evaluated is worse than one evaluated against an approximation. 

163 """ 

164 global _TOKENISER 

165 if not text: 

166 return 0 

167 if _TOKENISER is None: 

168 try: 

169 import tiktoken 

170 

171 _TOKENISER = tiktoken.get_encoding("cl100k_base") 

172 except Exception: # noqa: BLE001 — a missing tokeniser must not fail the turn 

173 logger.warning( 

174 "tiktoken unavailable — token-count conditions will use an estimate" 

175 ) 

176 _TOKENISER = False 

177 if _TOKENISER is False: 

178 return max(1, len(text) // 4) 

179 return len(_TOKENISER.encode(text)) 

180 

181 

182# ── Special ─────────────────────────────────────────────────────────────────── 

183 

184 

185@register_field 

186class AlwaysField(Field): 

187 key = "always" 

188 label = "Always" 

189 description = "Matches every invocation — the rule fires unconditionally." 

190 group = "general" 

191 value_type = ValueType.none 

192 phases = IDENTITY_PHASES 

193 

194 def resolve(self, context: dict[str, Any]) -> Any: 

195 return True 

196 

197 

198# ── Content ─────────────────────────────────────────────────────────────────── 

199 

200 

201@register_field 

202class PromptField(Field): 

203 key = "prompt" 

204 label = "Prompt" 

205 description = "The full input text sent to the model." 

206 group = "content" 

207 value_type = ValueType.text 

208 phases = IDENTITY_PHASES 

209 

210 def resolve(self, context: dict[str, Any]) -> Any: 

211 return context.get("prompt") 

212 

213 

214@register_field 

215class ResponseField(Field): 

216 key = "response" 

217 label = "Response" 

218 description = "The model's output text. Audit rules only." 

219 group = "content" 

220 value_type = ValueType.text 

221 phases = frozenset({Phase.output}) 

222 

223 def resolve(self, context: dict[str, Any]) -> Any: 

224 return context.get("response") 

225 

226 

227def _phase_text(context: dict[str, Any]) -> str | None: 

228 """Whichever text this phase is about: audit rules evaluate the response, 

229 policy rules the prompt.""" 

230 text = context.get("response") 

231 if text is None: 

232 text = context.get("prompt") 

233 return None if text is None else str(text) 

234 

235 

236@register_field 

237class PiiDetectedField(Field): 

238 key = "pii_detected" 

239 label = "PII detected" 

240 description = ( 

241 "Whether the text under evaluation holds personal data of a kind the " 

242 "redaction actions remove by default — " 

243 f"{len(pii.DEFAULT_KINDS)} kinds, from email addresses to national " 

244 "identity numbers. To ask about particular kinds, use " 

245 "'PII types found' (pii_types)." 

246 ) 

247 group = "classifier" 

248 value_type = ValueType.boolean 

249 phases = frozenset({Phase.input, Phase.output}) 

250 

251 def resolve(self, context: dict[str, Any]) -> Any: 

252 text = _phase_text(context) 

253 return None if text is None else pii.detect_pii(text) 

254 

255 

256@register_field 

257class PiiTypesField(Field): 

258 """The kinds of personal data in the text — so a rule can refuse a prompt 

259 holding an NHS number while letting one with an email address through, 

260 which a yes/no answer cannot express.""" 

261 

262 key = "pii_types" 

263 label = "PII types found" 

264 description = ( 

265 "Every kind of personal data in the text under evaluation, from the " 

266 "same detectors the redaction actions use — including the kinds they " 

267 "skip by default. Compare with 'has any of' / 'has none of'." 

268 ) 

269 group = "classifier" 

270 value_type = ValueType.list 

271 phases = frozenset({Phase.input, Phase.output}) 

272 options = pii.KINDS 

273 vocabulary = "pii_kinds" 

274 

275 def resolve(self, context: dict[str, Any]) -> Any: 

276 text = _phase_text(context) 

277 return None if text is None else pii.detected_kinds(text) 

278 

279 

280# ── Invocation identity ─────────────────────────────────────────────────────── 

281 

282 

283@register_field 

284class ExecutionTypeField(Field): 

285 key = "execution_type" 

286 label = "Execution type" 

287 description = ( 

288 "What kind of work is being run, as the usage ledger records it — so " 

289 "a rule can single out evaluations or dashboard tiles as well as " 

290 "chats and direct prompts." 

291 ) 

292 group = "invocation" 

293 value_type = ValueType.enum 

294 phases = IDENTITY_PHASES 

295 #: The ledger's own vocabulary, which every svc-core path governs under. 

296 #: It used to offer svc-ai's request types (``worker``, ``graph``, 

297 #: ``pipeline``), which no svc-core context carries, and lacked the 

298 #: evaluation and dashboard work that every such context does. 

299 options = tuple(kind.value for kind in UsageEnum.ExecutionType) 

300 

301 def resolve(self, context: dict[str, Any]) -> Any: 

302 return context.get("execution_type") 

303 

304 

305@register_field 

306class UserIdField(Field): 

307 key = "user_id" 

308 label = "User" 

309 description = "UUID of the user making the request." 

310 group = "invocation" 

311 value_type = ValueType.text 

312 phases = IDENTITY_PHASES 

313 

314 def resolve(self, context: dict[str, Any]) -> Any: 

315 return context.get("user_id") 

316 

317 

318@register_field 

319class AgentIdField(Field): 

320 key = "agent_id" 

321 label = "Agent" 

322 description = "UUID of the agent being invoked, if any." 

323 group = "invocation" 

324 value_type = ValueType.text 

325 phases = IDENTITY_PHASES 

326 

327 def resolve(self, context: dict[str, Any]) -> Any: 

328 return context.get("agent_id") 

329 

330 

331@register_field 

332class AgentNameField(Field): 

333 key = "agent_name" 

334 label = "Agent name" 

335 description = "Display name of the agent being invoked, if any." 

336 group = "invocation" 

337 value_type = ValueType.text 

338 phases = IDENTITY_PHASES 

339 

340 def resolve(self, context: dict[str, Any]) -> Any: 

341 return context.get("agent_name") 

342 

343 

344@register_field 

345class TagsField(Field): 

346 key = "tags" 

347 label = "Tags" 

348 description = ( 

349 "Industry and role tags on the resource being invoked, so a rule can " 

350 "govern a category of agents without naming each one." 

351 ) 

352 group = "invocation" 

353 value_type = ValueType.list 

354 phases = IDENTITY_PHASES 

355 

356 def resolve(self, context: dict[str, Any]) -> Any: 

357 return context.get("tags") 

358 

359 

360# ── Model ───────────────────────────────────────────────────────────────────── 

361 

362 

363@register_field 

364class ModelNameField(Field): 

365 key = "model_name" 

366 label = "Model" 

367 description = "Name of the model selected for this invocation." 

368 group = "model" 

369 value_type = ValueType.text 

370 phases = IDENTITY_PHASES 

371 

372 def resolve(self, context: dict[str, Any]) -> Any: 

373 return _passthrough(context, "model_name", "model") 

374 

375 

376@register_field 

377class ProviderField(Field): 

378 key = "provider" 

379 label = "Provider" 

380 description = "Provider serving the selected model — openai, anthropic, …" 

381 group = "model" 

382 value_type = ValueType.text 

383 phases = IDENTITY_PHASES 

384 

385 def resolve(self, context: dict[str, Any]) -> Any: 

386 return context.get("provider") 

387 

388 

389# ── Cost and size ───────────────────────────────────────────────────────────── 

390 

391 

392@register_field 

393class PromptTokensField(Field): 

394 key = "prompt_tokens" 

395 label = "Prompt tokens" 

396 description = ( 

397 "Token count of the input. Derived from the prompt when the caller " 

398 "does not supply an exact figure." 

399 ) 

400 group = "cost" 

401 value_type = ValueType.number 

402 phases = IDENTITY_PHASES 

403 

404 def resolve(self, context: dict[str, Any]) -> Any: 

405 supplied = _passthrough(context, "prompt_tokens", "input_tokens") 

406 if supplied is not None: 

407 return supplied 

408 prompt = context.get("prompt") 

409 return _count_tokens(str(prompt)) if prompt is not None else None 

410 

411 

412@register_field 

413class ResponseTokensField(Field): 

414 key = "response_tokens" 

415 label = "Response tokens" 

416 description = ( 

417 "Token count of the output. Derived from the response when the caller " 

418 "does not supply an exact figure. Audit rules only." 

419 ) 

420 group = "cost" 

421 value_type = ValueType.number 

422 phases = frozenset({Phase.output}) 

423 

424 def resolve(self, context: dict[str, Any]) -> Any: 

425 supplied = _passthrough(context, "response_tokens", "output_tokens") 

426 if supplied is not None: 

427 return supplied 

428 response = context.get("response") 

429 return _count_tokens(str(response)) if response is not None else None 

430 

431 

432@register_field 

433class TotalTokensField(Field): 

434 key = "total_tokens" 

435 label = "Total tokens" 

436 description = "Prompt plus response tokens for this invocation." 

437 group = "cost" 

438 value_type = ValueType.number 

439 phases = frozenset({Phase.output}) 

440 

441 def resolve(self, context: dict[str, Any]) -> Any: 

442 supplied = context.get("total_tokens") 

443 if supplied is not None: 

444 return supplied 

445 prompt_tokens = PromptTokensField().resolve(context) 

446 response_tokens = ResponseTokensField().resolve(context) 

447 if prompt_tokens is None and response_tokens is None: 

448 return None 

449 return (prompt_tokens or 0) + (response_tokens or 0) 

450 

451 

452@register_field 

453class EstimatedCostField(Field): 

454 key = "estimated_cost_usd" 

455 label = "Estimated cost (USD)" 

456 description = ( 

457 "What this invocation cost in USD, metered across every model call it " 

458 "made — the figure the usage ledger records. A model with no price " 

459 "leaves it unknown, and a condition on an unknown cost does not " 

460 "match. Audit rules only: a call's cost is known once it returns." 

461 ) 

462 group = "cost" 

463 value_type = ValueType.number 

464 phases = frozenset({Phase.output}) 

465 

466 def resolve(self, context: dict[str, Any]) -> Any: 

467 return _passthrough(context, "estimated_cost_usd", "cost_usd") 

468 

469 

470@register_field 

471class LatencyField(Field): 

472 key = "latency_ms" 

473 label = "Latency (ms)" 

474 description = ( 

475 "How long the model took to answer, in milliseconds — timed around " 

476 "the call, not counting time spent waiting for a person to answer " 

477 "its questions. Audit rules only." 

478 ) 

479 group = "cost" 

480 value_type = ValueType.number 

481 phases = frozenset({Phase.output}) 

482 

483 def resolve(self, context: dict[str, Any]) -> Any: 

484 return context.get("latency_ms") 

485 

486 

487@register_field 

488class QualityCheckField(Field): 

489 key = "quality_check" 

490 label = "Quality check" 

491 description = ( 

492 "What became of the answer at the agent's quality check: passed, " 

493 "revised (it failed and was rewritten), failed (nothing fixed it) or " 

494 "unavailable (no check ran). An answer that never reaches a check, " 

495 "such as a direct model prompt, has none, and a condition on it does " 

496 "not match. Audit rules only." 

497 ) 

498 group = "quality" 

499 value_type = ValueType.enum 

500 phases = frozenset({Phase.output}) 

501 options = tuple(outcome.value for outcome in quality_check.Outcome) 

502 

503 def resolve(self, context: dict[str, Any]) -> Any: 

504 return context.get("quality_check") 

505 

506 

507@register_field 

508class QualityScoreField(Field): 

509 key = "quality_score" 

510 label = "Quality score" 

511 description = ( 

512 "The quality check's score out of 100: the evaluator model's judgement " 

513 "of the draft, not a calibrated confidence. Unknown when no check " 

514 "ran, and a condition on an unknown score does not match. Audit rules " 

515 "only." 

516 ) 

517 group = "quality" 

518 value_type = ValueType.number 

519 phases = frozenset({Phase.output}) 

520 

521 def resolve(self, context: dict[str, Any]) -> Any: 

522 return context.get("quality_score")