Coverage for app / services / knowledge / retrievals.py: 100%

76 statements  

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

1"""The retrieval record: what each answered turn of an agent with knowledge 

2asked of it, and what each source gave. 

3 

4The citations record (``citations.py``) keeps which sources an answer cited. 

5This keeps the rest of what svc-ai reports (``app/util/knowledge_report.py``): 

6what each source the turn searched found, kept for the agent, or had ruled 

7out; whether the knowledge came up short; the gaps the quality check named 

8that it did not hold; the files named that no source has; and, for a turn 

9the web answered, the web hosts the answer cited. Read beside the citations, 

10it says what a source is retrieved for and how often that is used, and 

11which knowledge to add. 

12 

13:func:`prepared` makes svc-ai's report what is stored: the person's words 

14redacted by the turn's Input then Output rules, as the request and the 

15answer were, and none of them for a withheld answer. :func:`record` writes 

16it beside the citations, in the same savepoint of ``_persist_conversation``. 

17 

18Ids come from svc-ai, which is never trusted at a boundary: a source the 

19turn could not have read is not recorded (``citations._reach``). 

20""" 

21 

22from __future__ import annotations 

23 

24import logging 

25import re 

26from collections.abc import Iterable 

27from datetime import datetime, timedelta 

28from typing import Any 

29from urllib.parse import urlsplit 

30from uuid import UUID 

31 

32from sqlalchemy import or_ 

33from sqlalchemy.orm import Session 

34 

35from app.db.postgres.models import ( 

36 Agent, 

37 ChatMessage, 

38 Conversation, 

39 Knowledge, 

40 KnowledgeRetrieval, 

41 KnowledgeTurn, 

42) 

43from app.services import rule_engine 

44from app.services.knowledge import citations 

45from app.util import knowledge_categories 

46from app.util.knowledge_report import KnowledgeReport 

47from app.util.time import naive_utcnow 

48 

49logger = logging.getLogger(__name__) 

50 

51#: The web hosts a turn's record names at most. 

52MAX_HOSTS = 10 

53#: ``complexity`` is a short label (``prompts.TaskComplexity``). 

54COMPLEXITY_LENGTH = 16 

55#: The mix's labels (svc-ai ``knowledge.mix``): a profile and a role, each a 

56#: short lower-case word. svc-ai owns the vocabularies; svc-core keeps a 

57#: value only when it is shaped like one of them, never free text. 

58PROFILE_LENGTH = 24 

59ROLE_LENGTH = 16 

60_LABEL = re.compile(r"^[a-z_]+$") 

61 

62 

63def mix_label(value: str | None, length: int) -> str | None: 

64 """A profile or role as stored: a short ``snake_case`` word, else None.""" 

65 text = (value or "").strip() 

66 return text if text and len(text) <= length and _LABEL.match(text) else None 

67 

68 

69def prepared( 

70 report: KnowledgeReport | None, 

71 *, 

72 input_rules: Any = None, 

73 output_rules: Any = None, 

74 withheld: bool = False, 

75) -> KnowledgeReport | None: 

76 """``report`` as it is stored: for a withheld answer none of the 

77 person's words, else each through the turn's Input then Output 

78 redaction (``RulePass.redact``), as the request and the answer were.""" 

79 if report is None: 

80 return None 

81 if withheld: 

82 return report.without_text() 

83 for rules in (input_rules, output_rules): 

84 if isinstance(rules, rule_engine.RulePass): 

85 report = report.redacted(rules.redact) 

86 return report 

87 

88 

89def cited_hosts(cited: Iterable[Any] | None) -> list[str]: 

90 """The hosts of the web pages an answer's stored sources name, in their 

91 order, at most :data:`MAX_HOSTS`: what a turn the web answered drew on.""" 

92 hosts: list[str] = [] 

93 for entry in cited or (): 

94 if ( 

95 not isinstance(entry, dict) 

96 or entry.get("kb_id") 

97 or entry.get("document_id") 

98 ): 

99 continue 

100 url = str(entry.get("url") or "") 

101 if not url.lower().startswith(("http://", "https://")): 

102 continue 

103 host = (urlsplit(url).hostname or "").removeprefix("www.") 

104 if host and host not in hosts: 

105 hosts.append(host) 

106 return hosts[:MAX_HOSTS] 

107 

108 

109def _uuid(value: Any) -> UUID | None: 

110 try: 

111 return UUID(str(value)) 

112 except ValueError: 

113 return None 

114 

115 

116def record( 

117 db: Session, 

118 message: ChatMessage, 

119 report: KnowledgeReport | None, 

120 *, 

121 agent: Agent | None, 

122 conversation: Conversation, 

123 cited: Iterable[Any] | None = None, 

124) -> KnowledgeTurn | None: 

125 """Add the turn's record: one row for the answer, one per source it 

126 searched that it could have read. ``report`` is :func:`prepared`; 

127 ``cited`` the answer's stored ``meta.cited_sources``. Does not commit: 

128 the caller adds this to the transaction that stores the answer, flushed 

129 first. Returns the turn's row; never raises for what svc-ai sent.""" 

130 if report is None or message.id is None: 

131 return None 

132 ws = citations.conversation_workspace(db, conversation) 

133 stamp = ( 

134 ws.ledger_stamp() 

135 if ws is not None 

136 else { 

137 "owner_organisation_id": None, 

138 "owner_project_id": None, 

139 "workspace_user_id": None, 

140 } 

141 ) 

142 by_id = { 

143 kid: source 

144 for source in report.sources 

145 if (kid := _uuid(source.knowledge_id)) is not None 

146 } 

147 readable = ( 

148 { 

149 knowledge_id 

150 for (knowledge_id,) in db.query(Knowledge.id) 

151 .filter(Knowledge.id.in_(list(by_id)), citations._reach(db, agent, ws)) 

152 .all() 

153 } 

154 if by_id 

155 else set() 

156 ) 

157 who = { 

158 "agent_id": getattr(agent, "id", None), 

159 "owner_user_id": conversation.owner_user_id, 

160 **stamp, 

161 } 

162 hosts = cited_hosts(cited) 

163 turn = KnowledgeTurn( 

164 message_id=message.id, 

165 invocation_id=message.invocation_id, 

166 query=report.query or None, 

167 live=report.live, 

168 complexity=(report.complexity or "")[:COMPLEXITY_LENGTH] or None, 

169 profile=mix_label(report.profile, PROFILE_LENGTH), 

170 searched=report.searched, 

171 nothing_relevant=report.nothing_relevant, 

172 came_up_short=report.came_up_short, 

173 gaps=report.gaps or None, 

174 unresolved=report.unresolved or None, 

175 web_hosts=hosts or None, 

176 scoped_out=report.scoped_out or None, 

177 asked_at=message.sent_at, 

178 sources=[ 

179 KnowledgeRetrieval( 

180 knowledge_id=knowledge_id, 

181 category=knowledge_categories.of(source.category).value, 

182 role=mix_label(source.role, ROLE_LENGTH), 

183 found=source.found, 

184 kept=source.kept, 

185 ruled_out=source.ruled_out, 

186 out_of_window=source.out_of_window, 

187 tool_searches=source.tool_searches, 

188 asked_at=message.sent_at, 

189 **who, 

190 ) 

191 for knowledge_id, source in by_id.items() 

192 if knowledge_id in readable 

193 ], 

194 **who, 

195 ) 

196 db.add(turn) 

197 return turn 

198 

199 

200def text_retention_days() -> int | None: 

201 """How long a turn's record keeps the person's words 

202 (``KNOWLEDGE_TURN_TEXT_RETENTION_DAYS``); None when it is off (0 or 

203 less), and they are kept as long as the answer.""" 

204 from app.common.settings import get_settings 

205 

206 days = int(get_settings().KNOWLEDGE_TURN_TEXT_RETENTION_DAYS or 0) 

207 return days if days > 0 else None 

208 

209 

210def clear_expired_text(db: Session, *, now: datetime | None = None) -> int: 

211 """Clear the person's words — the request as searched, the gaps, the 

212 files named — from every turn's record older than the retention window, 

213 across every owner; the counts stay. Commits. Returns how many records 

214 were cleared.""" 

215 days = text_retention_days() 

216 if days is None: 

217 return 0 

218 cutoff = (now or naive_utcnow()) - timedelta(days=days) 

219 cleared = ( 

220 db.query(KnowledgeTurn) 

221 .filter( 

222 KnowledgeTurn.asked_at < cutoff, 

223 or_( 

224 KnowledgeTurn.query.isnot(None), 

225 KnowledgeTurn.gaps.isnot(None), 

226 KnowledgeTurn.unresolved.isnot(None), 

227 ), 

228 ) 

229 .update( 

230 { 

231 KnowledgeTurn.query: None, 

232 KnowledgeTurn.gaps: None, 

233 KnowledgeTurn.unresolved: None, 

234 }, 

235 synchronize_session=False, 

236 ) 

237 ) 

238 db.commit() 

239 return int(cleared or 0) 

240 

241 

242__all__ = [ 

243 "MAX_HOSTS", 

244 "PROFILE_LENGTH", 

245 "ROLE_LENGTH", 

246 "cited_hosts", 

247 "clear_expired_text", 

248 "mix_label", 

249 "prepared", 

250 "record", 

251 "text_retention_days", 

252]