Coverage for app / services / knowledge / recommendations / answers.py: 99%

144 statements  

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

1"""Recommendations from what agents were asked: the retrieval record 

2(``knowledge_turns``) says which questions an agent's knowledge could not 

3answer, which sites its answers went to instead, and which questions were 

4about what is current. 

5 

6Each counts the workspace's answers; its examples, and the questions a 

7generation is described from, are the viewer's own. 

8""" 

9 

10from __future__ import annotations 

11 

12from collections import defaultdict 

13from uuid import UUID 

14 

15from app.services.knowledge import web_config 

16from app.services.knowledge.recommendations.base import ( 

17 Action, 

18 Example, 

19 Figure, 

20 Flow, 

21 Prefill, 

22 Recommendation, 

23 RecommendationKind, 

24 Section, 

25 Subject, 

26 SubjectKind, 

27 Touches, 

28 band, 

29 fingerprint, 

30 plural, 

31 register_kind, 

32) 

33from app.services.knowledge.recommendations.context import ( 

34 RECENT_DAYS, 

35 RecommendationContext, 

36 Turn, 

37) 

38from app.util import knowledge_categories, web_domains 

39from app.util.knowledge_categories import KnowledgeCategory 

40 

41#: Questions an agent's knowledge left unanswered before it is worth saying. 

42MIN_UNANSWERED = 3 

43#: Questions about what is current, for an agent with no dated knowledge. 

44MIN_LIVE = 3 

45#: Worked problems, for an agent with no method knowledge. 

46MIN_WORKED = 3 

47#: Answers citing one site that nothing here holds. 

48MIN_SITE_ANSWERS = 3 

49#: The sites recommended at once: the most cited. 

50MAX_SITES = 5 

51#: The viewer's own questions shown as examples. 

52MAX_EXAMPLES = 3 

53#: The viewer's own questions a generation is described from. 

54MAX_FROM_TURNS = 20 

55#: Triage's grades that call for a method, not only facts. 

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

57#: The knowledge mix's profiles of a request that works a problem through 

58#: (svc-ai ``knowledge/mix.py``, stored since migration 115). Complexity 

59#: alone counted news questions graded moderate as worked problems, and 

60#: offered a news-asking agent frameworks. 

61WORKED_PROFILES = frozenset({"analysis", "analysis_current"}) 

62 

63 

64def is_worked(turn: Turn) -> bool: 

65 """Whether ``turn`` worked a problem through: its mix's profile, or its 

66 complexity for a turn stored before profiles were.""" 

67 if turn.profile: 

68 return turn.profile in WORKED_PROFILES 

69 return turn.complexity in WORKED 

70 

71 

72def examples( 

73 ctx: RecommendationContext, turns: list[Turn], detail=None 

74) -> tuple[Example, ...]: 

75 """The viewer's own newest of ``turns``, as examples.""" 

76 return tuple( 

77 Example(text=t.query or "", detail=detail(t) if detail else None, at=t.asked_at) 

78 for t in ctx.own(turns)[:MAX_EXAMPLES] 

79 ) 

80 

81 

82def own_turn_ids(ctx: RecommendationContext, turns: list[Turn]) -> tuple[UUID, ...]: 

83 return tuple(t.id for t in ctx.own(turns)[:MAX_FROM_TURNS]) 

84 

85 

86def suggested_category(turns: list[Turn]) -> KnowledgeCategory: 

87 """The kind of knowledge questions like these want: dated when most were 

88 about what is current, a method when most were worked problems, else 

89 reference material. A suggestion; the generate dialog lets it change.""" 

90 if sum(t.live for t in turns) * 2 >= len(turns): 

91 return KnowledgeCategory.temporal 

92 if sum(is_worked(t) for t in turns) * 2 >= len(turns): 

93 return KnowledgeCategory.reasoning 

94 return KnowledgeCategory.domain 

95 

96 

97def _by_agent(turns: list[Turn]) -> dict[UUID, list[Turn]]: 

98 out: dict[UUID, list[Turn]] = defaultdict(list) 

99 for turn in turns: 

100 if turn.agent_id is not None: 

101 out[turn.agent_id].append(turn) 

102 return out 

103 

104 

105def _lacked(turn: Turn) -> str: 

106 if turn.gaps: 

107 return "Missing: " + "; ".join(turn.gaps[:2]) 

108 if turn.unresolved: 

109 return "Not held: " + ", ".join(turn.unresolved[:2]) 

110 if turn.nothing_relevant: 

111 return "Nothing it held bore on this" 

112 return "Nothing it held was kept" 

113 

114 

115def _generate( 

116 ctx: RecommendationContext, 

117 turns: list[Turn], 

118 category: KnowledgeCategory, 

119 agent_id: UUID, 

120 agent_name: str, 

121) -> Action: 

122 mine = own_turn_ids(ctx, turns) 

123 return Action( 

124 Flow.generate_knowledge, 

125 "Generate knowledge from these questions" 

126 if mine 

127 else f"Generate {knowledge_categories.LABELS[category].lower()} knowledge", 

128 Prefill( 

129 category=category.value, 

130 from_turns=mine, 

131 agent_id=agent_id, 

132 agent_name=agent_name, 

133 ), 

134 ) 

135 

136 

137#: Built-ins one recommendation offers to attach at most. 

138MAX_ATTACH = 2 

139 

140 

141def _attach(entry, agent_id: UUID, agent_name: str) -> Action: 

142 """Grant a built-in repository to the agent, in one step.""" 

143 return Action( 

144 Flow.attach_repository, 

145 f"Attach {entry.name}", 

146 Prefill( 

147 agent_id=agent_id, 

148 agent_name=agent_name, 

149 repository_id=entry.id, 

150 repository_name=entry.name, 

151 ), 

152 ) 

153 

154 

155def _built_ins_for( 

156 turns: list[Turn], 

157 category: KnowledgeCategory, 

158 granted: list[UUID], 

159 fallback=None, 

160) -> list: 

161 """The built-ins of ``category`` to offer for these questions: those 

162 whose topics the questions share, best match first, else ``fallback`` 

163 (else the first the deployment provides). Matched on every question's 

164 words; only the choice of repository comes of it, never the text.""" 

165 from app.services.system_resources import knowledge as built_in 

166 

167 asked = " ".join(t.query or "" for t in turns) 

168 matched = built_in.matching(category, asked, exclude=granted)[:MAX_ATTACH] 

169 if matched: 

170 return matched 

171 offered = built_in.suggested(category, exclude=granted) 

172 if fallback is not None and fallback in offered: 

173 return [fallback] 

174 return offered[:1] 

175 

176 

177@register_kind 

178class Unanswered(RecommendationKind): 

179 key = "unanswered" 

180 section = Section.answers 

181 label = "Questions its knowledge could not answer" 

182 description = ( 

183 "An agent's knowledge was searched and held nothing that answered the " 

184 "question, the quality check named something it lacked, or the " 

185 "question named a file no source holds." 

186 ) 

187 

188 def find(self, ctx: RecommendationContext) -> list[Recommendation]: 

189 out = [] 

190 short = [t for t in ctx.turns if t.came_up_short or t.unresolved] 

191 for agent_id, turns in _by_agent(short).items(): 

192 if len(turns) < MIN_UNANSWERED: 

193 continue 

194 agent = ctx.agents[agent_id] 

195 category = suggested_category(turns) 

196 figures = [Figure("Questions", len(turns))] 

197 for label, n in ( 

198 ("Held nothing relevant", sum(t.nothing_relevant for t in turns)), 

199 ("Gaps named", sum(bool(t.gaps) for t in turns)), 

200 ("Files it lacked", sum(bool(t.unresolved) for t in turns)), 

201 ): 

202 if n: 

203 figures.append(Figure(label, n)) 

204 out.append( 

205 self.recommendation( 

206 subject=Subject(SubjectKind.agent, str(agent_id), agent.name), 

207 title=( 

208 f"{agent.name} could not answer " 

209 f"{plural(len(turns), 'question')} from its knowledge" 

210 ), 

211 why=( 

212 f"In the last {RECENT_DAYS} days its knowledge was searched " 

213 f"for {plural(len(turns), 'question')} and held nothing that " 

214 "answered them. Knowledge on what they asked would." 

215 ), 

216 figures=tuple(figures), 

217 examples=examples(ctx, turns, _lacked), 

218 actions=(_generate(ctx, turns, category, agent_id, agent.name),), 

219 fingerprint=fingerprint(band(len(turns)), category.value), 

220 touches=Touches(agents=frozenset({agent_id})), 

221 weight=len(turns), 

222 ) 

223 ) 

224 return out 

225 

226 

227@register_kind 

228class NoDatedKnowledge(RecommendationKind): 

229 key = "no_dated_knowledge" 

230 section = Section.answers 

231 label = "Questions about what is current, and no dated knowledge" 

232 description = ( 

233 "An agent is asked about what is current and holds no temporal " 

234 "knowledge: it can only answer from the web." 

235 ) 

236 

237 def find(self, ctx: RecommendationContext) -> list[Recommendation]: 

238 from app.services.system_resources import knowledge as built_in 

239 

240 out = [] 

241 live = [t for t in ctx.turns if t.live] 

242 for agent_id, turns in _by_agent(live).items(): 

243 if len(turns) < MIN_LIVE: 

244 continue 

245 granted = ctx.grants.get(agent_id, []) 

246 if any( 

247 ctx.granted_categories.get(rid) is KnowledgeCategory.temporal 

248 for rid in granted 

249 ): 

250 continue 

251 agent = ctx.agents[agent_id] 

252 # News, or the updates whose topics the questions share. 

253 offered = _built_ins_for( 

254 turns, KnowledgeCategory.temporal, granted, fallback=built_in.NEWS 

255 ) 

256 actions = [_attach(entry, agent_id, agent.name) for entry in offered] 

257 actions.append( 

258 _generate(ctx, turns, KnowledgeCategory.temporal, agent_id, agent.name) 

259 ) 

260 out.append( 

261 self.recommendation( 

262 subject=Subject(SubjectKind.agent, str(agent_id), agent.name), 

263 title=( 

264 f"{agent.name} is asked about what is current and holds " 

265 "no dated knowledge" 

266 ), 

267 why=( 

268 f"{plural(len(turns), 'question')} in the last " 

269 f"{RECENT_DAYS} days needed current information. Temporal " 

270 "knowledge is read newest first, kept to the question's " 

271 "time window, beside the web." 

272 ), 

273 figures=(Figure("Questions about what is current", len(turns)),), 

274 examples=examples(ctx, turns), 

275 actions=tuple(actions), 

276 fingerprint=fingerprint( 

277 band(len(turns)), *sorted(str(e.id) for e in offered) 

278 ), 

279 touches=Touches(agents=frozenset({agent_id})), 

280 weight=len(turns), 

281 ) 

282 ) 

283 return out 

284 

285 

286@register_kind 

287class NoMethodKnowledge(RecommendationKind): 

288 key = "no_method_knowledge" 

289 section = Section.answers 

290 label = "Worked problems, and no method knowledge" 

291 description = ( 

292 "An agent is asked for analysis or decisions and holds no reasoning " 

293 "knowledge: it works each one out without a framework of its own." 

294 ) 

295 

296 def find(self, ctx: RecommendationContext) -> list[Recommendation]: 

297 from app.services.system_resources import reasoning 

298 

299 out = [] 

300 worked = [t for t in ctx.turns if is_worked(t)] 

301 for agent_id, turns in _by_agent(worked).items(): 

302 if len(turns) < MIN_WORKED: 

303 continue 

304 granted = ctx.grants.get(agent_id, []) 

305 if any( 

306 ctx.granted_categories.get(rid) is KnowledgeCategory.reasoning 

307 for rid in granted 

308 ): 

309 continue 

310 agent = ctx.agents[agent_id] 

311 # The frameworks the questions call for, else the general ones. 

312 offered = _built_ins_for( 

313 turns, 

314 KnowledgeCategory.reasoning, 

315 granted, 

316 fallback=reasoning.PROBLEM_SOLVING, 

317 ) 

318 out.append( 

319 self.recommendation( 

320 subject=Subject(SubjectKind.agent, str(agent_id), agent.name), 

321 title=( 

322 f"{agent.name} is asked to analyse and decide, and holds " 

323 "no method knowledge" 

324 ), 

325 why=( 

326 f"{plural(len(turns), 'question')} in the last " 

327 f"{RECENT_DAYS} days were worked problems. Reasoning " 

328 "knowledge — your frameworks, criteria and checklists — " 

329 "is applied as the method for them, apart from the " 

330 "evidence." 

331 ), 

332 figures=(Figure("Worked problems", len(turns)),), 

333 examples=examples(ctx, turns), 

334 actions=( 

335 *(_attach(entry, agent_id, agent.name) for entry in offered), 

336 _generate( 

337 ctx, 

338 turns, 

339 KnowledgeCategory.reasoning, 

340 agent_id, 

341 agent.name, 

342 ), 

343 ), 

344 fingerprint=fingerprint( 

345 band(len(turns)), *sorted(str(e.id) for e in offered) 

346 ), 

347 touches=Touches(agents=frozenset({agent_id})), 

348 weight=len(turns), 

349 ) 

350 ) 

351 return out 

352 

353 

354@register_kind 

355class AnsweredFromTheWeb(RecommendationKind): 

356 key = "answered_from_the_web" 

357 section = Section.answers 

358 label = "A site its answers went to instead" 

359 description = ( 

360 "Answers of agents with knowledge cited the same web site, which no " 

361 "knowledge here holds: a source for it would answer from what is kept." 

362 ) 

363 

364 def find(self, ctx: RecommendationContext) -> list[Recommendation]: 

365 by_host: dict[str, list[Turn]] = defaultdict(list) 

366 for turn in ctx.turns: 

367 for host in dict.fromkeys(turn.web_hosts): 

368 by_host[host].append(turn) 

369 held = tuple(ctx.hosts_here) 

370 found = sorted( 

371 ( 

372 (host, turns) 

373 for host, turns in by_host.items() 

374 if len(turns) >= MIN_SITE_ANSWERS 

375 and not web_domains.covered(host, held) 

376 ), 

377 key=lambda item: (-len(item[1]), item[0]), 

378 )[:MAX_SITES] 

379 out = [] 

380 for host, turns in found: 

381 category = ( 

382 KnowledgeCategory.temporal 

383 if sum(t.live for t in turns) * 2 >= len(turns) 

384 else KnowledgeCategory.domain 

385 ) 

386 agents = frozenset(t.agent_id for t in turns if t.agent_id is not None) 

387 names = sorted(ctx.agents[a].name for a in agents if a in ctx.agents) 

388 out.append( 

389 self.recommendation( 

390 subject=Subject(SubjectKind.site, host, host), 

391 title=f"Answers went to {host}, which no knowledge here holds", 

392 why=( 

393 f"{plural(len(turns), 'answer')} in the last {RECENT_DAYS} " 

394 f"days cited it ({', '.join(names[:3])}" 

395 f"{f' +{len(names) - 3}' if len(names) > 3 else ''}). A " 

396 "website source for it, in a repository they hold, keeps " 

397 "what they read." 

398 ), 

399 figures=( 

400 Figure("Answers citing it", len(turns)), 

401 Figure("Agents", len(agents)), 

402 ), 

403 examples=examples(ctx, turns), 

404 actions=( 

405 Action( 

406 Flow.add_website, 

407 f"Add {host} as a website source", 

408 Prefill( 

409 category=category.value, 

410 url=f"https://{host}/", 

411 name=host, 

412 refresh=web_config.refresh_for(category), 

413 max_age_days=( 

414 web_config.TEMPORAL_MAX_AGE_DAYS 

415 if category is KnowledgeCategory.temporal 

416 else None 

417 ), 

418 ), 

419 ), 

420 ), 

421 fingerprint=fingerprint(band(len(turns))), 

422 touches=Touches(agents=agents), 

423 weight=len(turns), 

424 ) 

425 ) 

426 return out 

427 

428 

429__all__ = [ 

430 "MAX_FROM_TURNS", 

431 "AnsweredFromTheWeb", 

432 "NoDatedKnowledge", 

433 "NoMethodKnowledge", 

434 "Unanswered", 

435 "suggested_category", 

436]