Coverage for app / knowledge / mix.py: 97%

165 statements  

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

1"""Which kinds of knowledge a request searches, and how much each counts: 

2the turn's **mix**, decided from triage's signals by a fixed table, never a 

3model. 

4 

5``categories.py`` says what each kind *does* (its window, its judge note, 

6packed apart or not). This says *whether* it runs for an input, and in what 

7**role**: 

8 

9- **primary** — the evidence the answer rests on: the most candidates, the 

10 most judge slots, the biggest share of the evidence budget; 

11- **supporting** — evidence beside it: half the candidates, a smaller share; 

12- **method** — a framework to apply (Reasoning), with its own reserved share. 

13 

14Each row of :data:`ROLES` is an input **profile**, matched in order from 

15the turn (``categories.RetrievalTurn``): whether triage could say anything 

16(``triage_failed`` runs every kind it holds, as before the mix), whether 

17the request is about what is current (``live``) and whether it is a worked 

18problem (moderate or complex). Then the modifiers: a knowledge base the 

19request names is searched; a period it names turns dated knowledge on; an 

20input with no evidence lane primary promotes one; an agent holding one kind 

21always searches it, at its configuration's own values; the Economy cost 

22profile leaves supporting lanes out. 

23 

24The mix is recorded for the turn (``state.context[MIX_KEY]``, the gate's 

25frame, the retrieval record). It holds knowledge base ids and fixed reasons 

26only, never the person's words: the batch response returns the context. 

27""" 

28 

29from __future__ import annotations 

30 

31from collections.abc import Iterable, Mapping 

32from dataclasses import dataclass, field 

33from typing import TYPE_CHECKING, Any, Literal 

34 

35from app.knowledge import categories 

36from app.knowledge.categories import RetrievalTurn 

37from app.util import vocab 

38from app.util.knowledge_categories import KnowledgeCategory 

39 

40if TYPE_CHECKING: 

41 from app.agents.effort import PipelineEffort 

42 from app.models.spec import RetrievalConfig 

43 

44#: Where the turn's mix travels in ``state.context``: set by the gate. 

45MIX_KEY = "knowledge_mix" 

46 

47Role = Literal["primary", "supporting", "method"] 

48 

49ROLE_MEANINGS: dict[str, str] = { 

50 "primary": "the evidence the answer rests on", 

51 "supporting": "evidence beside the primary", 

52 "method": "a framework to apply, not evidence", 

53} 

54vocab.check(ROLE_MEANINGS, Role) 

55 

56Profile = Literal[ 

57 "triage_failed", 

58 "current_web", 

59 "analysis_current", 

60 "current", 

61 "analysis", 

62 "lookup", 

63] 

64 

65PROFILES: dict[str, str] = { 

66 "triage_failed": "triage could not read the request: every kind it holds", 

67 "current_web": "about what is current, and sent to the web: dated knowledge only", 

68 "analysis_current": "a worked problem about what is current", 

69 "current": "about what is current", 

70 "analysis": "a worked problem: analysis or a decision", 

71 "lookup": "a lookup", 

72} 

73vocab.check(PROFILES, Profile) 

74 

75#: Triage's grades that make a request a worked problem. 

76WORKED = frozenset({"moderate", "complex"}) 

77 

78_D, _T, _R = ( 

79 KnowledgeCategory.domain, 

80 KnowledgeCategory.temporal, 

81 KnowledgeCategory.reasoning, 

82) 

83 

84#: Each profile's role for each kind; None leaves the kind out. 

85ROLES: dict[str, dict[KnowledgeCategory, str | None]] = { 

86 "triage_failed": {_D: "primary", _T: "supporting", _R: "method"}, 

87 "current_web": {_D: None, _T: "primary", _R: None}, 

88 "analysis_current": {_D: "supporting", _T: "primary", _R: "method"}, 

89 "current": {_D: "supporting", _T: "primary", _R: None}, 

90 "analysis": {_D: "primary", _T: None, _R: "method"}, 

91 "lookup": {_D: "primary", _T: None, _R: None}, 

92} 

93vocab.check(ROLES, Profile) 

94if any(set(row) != set(KnowledgeCategory) for row in ROLES.values()): 

95 raise RuntimeError("Every profile needs a role, or none, for every kind") 

96 

97#: Why a kind the agent holds is left out, by profile and kind. 

98LEFT_OUT: dict[tuple[str, KnowledgeCategory], str] = { 

99 ( 

100 "current_web", 

101 _D, 

102 ): "the web answers what is current; reference material is not searched", 

103 ("current_web", _R): "the web answers what is current; no method is needed", 

104 ("current", _R): "a simple request needs no method", 

105 ("analysis", _T): "nothing current or dated was asked", 

106 ("lookup", _T): "nothing current or dated was asked", 

107 ("lookup", _R): "a simple request needs no method", 

108} 

109for (_profile, _kind), _reason in LEFT_OUT.items(): 

110 if ROLES[_profile][_kind] is not None: 

111 raise RuntimeError(f"{_profile} runs {_kind}; it has no reason to leave it out") 

112for _profile, _row in ROLES.items(): 

113 for _kind, _role in _row.items(): 

114 if _role is None and (_profile, _kind) not in LEFT_OUT: 

115 raise RuntimeError(f"{_profile} leaves {_kind} out without a reason") 

116 

117Modifier = Literal["named", "window", "worked", "promoted", "single_kind", "economy"] 

118 

119MODIFIERS: dict[str, str] = { 

120 "named": "named by the request", 

121 "window": "the request names a period", 

122 "worked": "a problem worked through on what is current", 

123 "promoted": "the strongest evidence it holds for this request", 

124 "single_kind": "the only kind it holds", 

125 "economy": "left out by the Economy cost profile", 

126} 

127vocab.check(MODIFIERS, Modifier) 

128 

129#: Why a knowledge base confirmed empty is left out of every lane: searching 

130#: one found nothing, judged nothing and sent the agent's own pass to search 

131#: it again (a first scenario run, every web built-in not yet crawled). 

132EMPTY = "nothing indexed yet" 

133 

134#: A role's part of the budget for evidence (Domain and Temporal lanes); 

135#: a method lane reserves its kind's own ``budget_share`` of the whole. 

136EVIDENCE_SHARES: dict[str, float] = {"primary": 0.7, "supporting": 0.3} 

137 

138 

139@dataclass(frozen=True) 

140class Lane: 

141 """One kind of knowledge a turn searches, in its role, and how much it 

142 may take: candidates per search, passages the judge rates, queries, and 

143 its share of the whole context budget.""" 

144 

145 category: str 

146 role: str 

147 kb_ids: tuple[str, ...] 

148 share: float 

149 candidate_k: int 

150 judge_slots: int 

151 max_queries: int 

152 reason: str 

153 

154 def wire(self) -> dict[str, Any]: 

155 return { 

156 "category": self.category, 

157 "role": self.role, 

158 "kb_ids": list(self.kb_ids), 

159 "share": self.share, 

160 "candidate_k": self.candidate_k, 

161 "judge_slots": self.judge_slots, 

162 "max_queries": self.max_queries, 

163 "reason": self.reason, 

164 } 

165 

166 

167@dataclass(frozen=True) 

168class ScopedOut: 

169 """A kind the agent holds that the turn leaves out, and why.""" 

170 

171 category: str 

172 kb_ids: tuple[str, ...] 

173 reason: str 

174 

175 def wire(self) -> dict[str, Any]: 

176 return { 

177 "category": self.category, 

178 "kb_ids": list(self.kb_ids), 

179 "reason": self.reason, 

180 } 

181 

182 

183@dataclass(frozen=True) 

184class Mix: 

185 """A turn's mix: its profile, what changed it, the lanes it searches 

186 and what it leaves out.""" 

187 

188 profile: str 

189 modifiers: tuple[str, ...] = () 

190 lanes: tuple[Lane, ...] = () 

191 scoped_out: tuple[ScopedOut, ...] = () 

192 #: The triage signals it was read from (no words of the person's). 

193 signals: Mapping[str, Any] = field(default_factory=dict) 

194 

195 def lane(self, category: KnowledgeCategory | str) -> Lane | None: 

196 key = getattr(category, "value", category) 

197 return next((lane for lane in self.lanes if lane.category == key), None) 

198 

199 def role_of(self, kb_id: str) -> str: 

200 return next((lane.role for lane in self.lanes if kb_id in lane.kb_ids), "") 

201 

202 def wire(self) -> dict[str, Any]: 

203 return { 

204 "profile": self.profile, 

205 "modifiers": list(self.modifiers), 

206 "lanes": [lane.wire() for lane in self.lanes], 

207 "scoped_out": [s.wire() for s in self.scoped_out], 

208 "signals": dict(self.signals), 

209 } 

210 

211 @classmethod 

212 def read(cls, raw: object) -> Mix | None: 

213 """A wired mix, or None when there is none to read (a checkpoint from 

214 before the mix).""" 

215 if not isinstance(raw, Mapping) or raw.get("profile") not in PROFILES: 

216 return None 

217 try: 

218 return cls( 

219 profile=str(raw["profile"]), 

220 modifiers=tuple( 

221 str(m) for m in raw.get("modifiers") or () if m in MODIFIERS 

222 ), 

223 lanes=tuple( 

224 Lane( 

225 category=str(lane["category"]), 

226 role=str(lane["role"]), 

227 kb_ids=tuple(str(i) for i in lane.get("kb_ids") or ()), 

228 share=float(lane.get("share", 1.0)), 

229 candidate_k=int(lane.get("candidate_k", 0)), 

230 judge_slots=int(lane.get("judge_slots", 0)), 

231 max_queries=int(lane.get("max_queries", 0)), 

232 reason=str(lane.get("reason", "")), 

233 ) 

234 for lane in raw.get("lanes") or () 

235 ), 

236 scoped_out=tuple( 

237 ScopedOut( 

238 category=str(s["category"]), 

239 kb_ids=tuple(str(i) for i in s.get("kb_ids") or ()), 

240 reason=str(s.get("reason", "")), 

241 ) 

242 for s in raw.get("scoped_out") or () 

243 ), 

244 signals=dict(raw.get("signals") or {}), 

245 ) 

246 except (KeyError, TypeError, ValueError): 

247 return None 

248 

249 

250def profile_of(turn: RetrievalTurn) -> str: 

251 """The first row of :data:`ROLES` the turn matches.""" 

252 if turn.complexity is None: 

253 return "triage_failed" 

254 if turn.web_led: 

255 return "current_web" 

256 worked = turn.complexity in WORKED 

257 if turn.live: 

258 return "analysis_current" if worked else "current" 

259 return "analysis" if worked else "lookup" 

260 

261 

262def _held( 

263 knowledge_bases: Iterable[Mapping[str, Any]], 

264) -> dict[KnowledgeCategory, list[str]]: 

265 """The agent's knowledge base ids by kind, in its order.""" 

266 held: dict[KnowledgeCategory, list[str]] = {} 

267 for kb in knowledge_bases: 

268 held.setdefault(categories.category_of(kb), []).append(str(kb.get("id", ""))) 

269 return held 

270 

271 

272def _role_reason(profile: str, category: KnowledgeCategory, role: str) -> str: 

273 return f"{PROFILES[profile]}: {ROLE_MEANINGS[role]}" 

274 

275 

276def decide( 

277 knowledge_bases: Iterable[Mapping[str, Any]], 

278 turn: RetrievalTurn, 

279 *, 

280 internal: bool, 

281 cfg: RetrievalConfig, 

282 effort: PipelineEffort | None = None, 

283 empty: Iterable[str] = (), 

284) -> Mix: 

285 """The turn's mix. ``internal``: the route searches the agent's 

286 knowledge; without it there are no lanes (the web or the agent's own 

287 tools answer), and nothing is reported left out. ``empty``: knowledge 

288 bases confirmed to hold nothing (``rag.collection_metadata``), which no 

289 lane searches — the mix is decided over the rest, as if the agent held 

290 only those, and they are listed left out (:data:`EMPTY`).""" 

291 profile = profile_of(turn) 

292 signals = { 

293 "live": turn.live, 

294 "complexity": turn.complexity, 

295 "window_days": turn.window_days, 

296 "web_led": turn.web_led, 

297 "named": sorted(turn.named), 

298 } 

299 nothing = {str(kb_id) for kb_id in empty} 

300 every = list(knowledge_bases) 

301 held = _held([kb for kb in every if str(kb.get("id", "")) not in nothing]) 

302 empty_out = tuple( 

303 ScopedOut(kind.value, tuple(ids), EMPTY) 

304 for kind, ids in _held( 

305 [kb for kb in every if str(kb.get("id", "")) in nothing] 

306 ).items() 

307 ) 

308 if not internal: 

309 return Mix(profile=profile, signals=signals) 

310 if not held: 

311 return Mix(profile=profile, signals=signals, scoped_out=empty_out) 

312 

313 modifiers: list[str] = [] 

314 roles: dict[KnowledgeCategory, tuple[str, list[str], str]] = {} 

315 if len(held) == 1: 

316 # One kind: it is what the agent knows. Searched whatever the 

317 # request, at the configuration's own values — how an agent with 

318 # one kind of knowledge searched before the mix. 

319 ((kind, ids),) = held.items() 

320 role = "method" if kind is _R else "primary" 

321 lane = Lane( 

322 category=kind.value, 

323 role=role, 

324 kb_ids=tuple(ids), 

325 share=1.0, 

326 candidate_k=cfg.candidate_k, 

327 judge_slots=cfg.rerank_candidates, 

328 max_queries=cfg.max_queries, 

329 reason=MODIFIERS["single_kind"], 

330 ) 

331 return Mix( 

332 profile=profile, 

333 modifiers=("single_kind",), 

334 lanes=(lane,), 

335 scoped_out=empty_out, 

336 signals=signals, 

337 ) 

338 

339 for kind, ids in held.items(): 

340 role = ROLES[profile][kind] 

341 if role is not None: 

342 roles[kind] = (role, ids, _role_reason(profile, kind, role)) 

343 # A knowledge base the request names is searched — that one, in the 

344 # role its kind takes beside the rest. 

345 for kind, ids in held.items(): 

346 named = [i for i in ids if i in turn.named] 

347 if named and kind not in roles: 

348 role = "method" if kind is _R else "supporting" 

349 roles[kind] = (role, named, MODIFIERS["named"]) 

350 modifiers.append("named") 

351 # A period named, though nothing current was asked: dated knowledge too. 

352 if turn.window_days and _T in held and _T not in roles: 

353 roles[_T] = ("supporting", held[_T], MODIFIERS["window"]) 

354 modifiers.append("window") 

355 # A problem worked through on what is current: the web leads, and the 

356 # method still applies ("given the latest advisories, what should we 

357 # patch first, and how should we decide?" had searched no framework). 

358 if turn.web_led and turn.complexity in WORKED and _R in held and _R not in roles: 

359 roles[_R] = ("method", held[_R], MODIFIERS["worked"]) 

360 modifiers.append("worked") 

361 # Some evidence must lead: the first held of Domain, then Temporal. 

362 evidence = [k for k in (_D, _T) if k in roles] 

363 if not any(roles[k][0] == "primary" for k in evidence): 

364 lead = next((k for k in (_D, _T) if k in held), None) 

365 if lead is not None: 

366 roles[lead] = ("primary", held[lead], MODIFIERS["promoted"]) 

367 modifiers.append("promoted") 

368 scoped_out: list[ScopedOut] = [] 

369 if effort is not None and not effort.supporting_lanes: 

370 for kind in [k for k, (role, _, _) in roles.items() if role == "supporting"]: 

371 _, ids, _ = roles.pop(kind) 

372 scoped_out.append(ScopedOut(kind.value, tuple(ids), MODIFIERS["economy"])) 

373 if "economy" not in modifiers: 

374 modifiers.append("economy") 

375 for kind, ids in held.items(): 

376 if kind in roles: 

377 leftover = [i for i in ids if i not in roles[kind][1]] 

378 if leftover: 

379 scoped_out.append( 

380 ScopedOut(kind.value, tuple(leftover), "not named by the request") 

381 ) 

382 elif not any(s.category == kind.value for s in scoped_out): 

383 scoped_out.append( 

384 ScopedOut(kind.value, tuple(ids), LEFT_OUT.get((profile, kind), "")) 

385 ) 

386 

387 method_share = sum( 

388 categories.REGISTRY[k].budget_share 

389 for k, (role, _, _) in roles.items() 

390 if role == "method" 

391 ) 

392 evidence_share = 1.0 - method_share 

393 has_supporting = any(role == "supporting" for role, _, _ in roles.values()) 

394 lanes: list[Lane] = [] 

395 for kind in (_D, _T, _R): 

396 if kind not in roles: 

397 continue 

398 role, ids, reason = roles[kind] 

399 if role == "method": 

400 share = categories.REGISTRY[kind].budget_share 

401 elif role == "primary": 

402 share = evidence_share * ( 

403 EVIDENCE_SHARES["primary"] if has_supporting else 1.0 

404 ) 

405 else: 

406 share = evidence_share * EVIDENCE_SHARES["supporting"] 

407 lead = role == "primary" 

408 lanes.append( 

409 Lane( 

410 category=kind.value, 

411 role=role, 

412 kb_ids=tuple(ids), 

413 share=round(share, 4), 

414 candidate_k=cfg.candidate_k if lead else max(1, cfg.candidate_k // 2), 

415 judge_slots=( 

416 cfg.rerank_candidates 

417 if lead 

418 else max( 

419 1, cfg.rerank_candidates // (2 if role == "supporting" else 3) 

420 ) 

421 ), 

422 max_queries=cfg.max_queries if lead else min(2, cfg.max_queries), 

423 reason=reason, 

424 ) 

425 ) 

426 return Mix( 

427 profile=profile, 

428 modifiers=tuple(modifiers), 

429 lanes=tuple(lanes), 

430 scoped_out=(*scoped_out, *empty_out), 

431 signals=signals, 

432 ) 

433 

434 

435def searched( 

436 knowledge_bases: Iterable[Mapping[str, Any]], mix: Mix 

437) -> list[dict[str, Any]]: 

438 """The knowledge bases the mix searches, in the agent's order.""" 

439 ids = {kb_id for lane in mix.lanes for kb_id in lane.kb_ids} 

440 return [dict(kb) for kb in knowledge_bases if str(kb.get("id", "")) in ids] 

441 

442 

443__all__ = [ 

444 "LEFT_OUT", 

445 "MIX_KEY", 

446 "MODIFIERS", 

447 "PROFILES", 

448 "ROLES", 

449 "Lane", 

450 "Mix", 

451 "Modifier", 

452 "Profile", 

453 "Role", 

454 "ScopedOut", 

455 "decide", 

456 "profile_of", 

457 "searched", 

458]