Coverage for app / services / knowledge / usage.py: 91%
94 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What a knowledge source or repository is used for: the answers citing it.
3Read from the citations record (``knowledge_citations``,
4``services/knowledge/citations.py``), counted in **distinct answers**, and
5always the request workspace's (``Workspace.stamped``): how other
6workspaces use a built-in source is theirs. The answers it lists are the
7viewer's own — a conversation is its person's — while every count includes
8the workspace's members' answers.
10A repository's figures are the answers citing any of its sources. A source
11in two repositories counts in both, so repositories' figures do not add up
12to the workspace's, and a page says so.
13"""
15from __future__ import annotations
17from collections.abc import Sequence
18from dataclasses import dataclass, field
19from datetime import date, datetime, timedelta
20from typing import Any
21from uuid import UUID
23from sqlalchemy import func
24from sqlalchemy.orm import Session
26from app.db.postgres.models import (
27 Agent,
28 ChatMessage,
29 Knowledge,
30 KnowledgeCitation,
31 KnowledgeDocument,
32)
33from app.util.time import naive_utcnow
35#: The window a usage page reads by default, and its bounds.
36DEFAULT_DAYS = 90
37MIN_DAYS = 7
38MAX_DAYS = 365
39#: How many agents, sources and documents a page ranks.
40TOP = 10
41#: How many of the viewer's own answers it lists.
42RECENT = 10
45@dataclass(frozen=True)
46class Ranked:
47 """An agent, source or document, by the answers citing it. ``id`` is
48 None for one deleted since (folded into one row)."""
50 id: UUID | None
51 name: str
52 answers: int
53 is_system: bool = False
54 url: str | None = None
55 knowledge_id: UUID | None = None
58@dataclass(frozen=True)
59class RecentAnswer:
60 message_id: UUID
61 conversation_id: UUID
62 agent_id: UUID | None
63 agent_name: str | None
64 cited_at: datetime
67@dataclass
68class Usage:
69 days: int
70 since: datetime
71 answers: int
72 #: The same length of time before ``since``: the trend's baseline.
73 previous_answers: int
74 daily: list[tuple[date, int]]
75 agents: list[Ranked] = field(default_factory=list)
76 documents: list[Ranked] = field(default_factory=list)
77 sources: list[Ranked] = field(default_factory=list)
78 recent: list[RecentAnswer] = field(default_factory=list)
81def clamp_days(days: int | None) -> int:
82 if days is None:
83 return DEFAULT_DAYS
84 return max(MIN_DAYS, min(MAX_DAYS, int(days)))
87def _scope(ws: Any, knowledge_ids: Sequence[UUID]):
88 return (
89 KnowledgeCitation.knowledge_id.in_(list(knowledge_ids)),
90 ws.stamped(KnowledgeCitation, projects=False),
91 )
94def _answers(db: Session, scope: tuple, start: datetime, end: datetime) -> int:
95 return int(
96 db.query(func.count(func.distinct(KnowledgeCitation.message_id)))
97 .filter(
98 *scope,
99 KnowledgeCitation.cited_at >= start,
100 KnowledgeCitation.cited_at < end,
101 )
102 .scalar()
103 or 0
104 )
107def _document_name(row: Any) -> tuple[str, str | None]:
108 meta = row.document_metadata if isinstance(row.document_metadata, dict) else {}
109 name = meta.get("title") or meta.get("original_filename") or row.source_id
110 url = meta.get("source_url") or (
111 row.source_id if str(row.source_id).startswith("http") else None
112 )
113 return str(name), url
116def usage(
117 db: Session,
118 ws: Any,
119 knowledge_ids: Sequence[UUID],
120 *,
121 viewer_id: UUID,
122 days: int | None = None,
123 rank_sources: bool = False,
124 now: datetime | None = None,
125) -> Usage:
126 """The answers in ``ws`` citing any of ``knowledge_ids`` over the last
127 ``days``: their count and the period before's, per day, by agent, by
128 document (and with ``rank_sources``, by source), and the viewer's own
129 newest ones."""
130 days = clamp_days(days)
131 now = now or naive_utcnow()
132 today = now.date()
133 since = datetime.combine(today - timedelta(days=days - 1), datetime.min.time())
134 until = now + timedelta(seconds=1)
135 if not knowledge_ids:
136 return Usage(
137 days,
138 since,
139 0,
140 0,
141 [(since.date() + timedelta(days=n), 0) for n in range(days)],
142 )
143 scope = _scope(ws, knowledge_ids)
144 window = (*scope, KnowledgeCitation.cited_at >= since)
145 answers = func.count(func.distinct(KnowledgeCitation.message_id))
147 day = func.date_trunc("day", KnowledgeCitation.cited_at)
148 per_day = {
149 (d.date() if isinstance(d, datetime) else d): int(n)
150 for d, n in db.query(day, answers).filter(*window).group_by(day).all()
151 }
152 daily = [
153 (
154 since.date() + timedelta(days=n),
155 per_day.get(since.date() + timedelta(days=n), 0),
156 )
157 for n in range(days)
158 ]
160 agent_rows = (
161 db.query(KnowledgeCitation.agent_id, answers.label("answers"))
162 .filter(*window)
163 .group_by(KnowledgeCitation.agent_id)
164 .order_by(answers.desc())
165 .limit(TOP)
166 .all()
167 )
168 agent_ids = [a for a, _ in agent_rows if a is not None]
169 agents = (
170 {
171 a.id: a
172 for a in db.query(Agent.id, Agent.name, Agent.is_system)
173 .filter(Agent.id.in_(agent_ids))
174 .all()
175 }
176 if agent_ids
177 else {}
178 )
179 ranked_agents = [
180 Ranked(
181 agent_id if agent_id in agents else None,
182 agents[agent_id].name if agent_id in agents else "Deleted agent",
183 int(n),
184 is_system=bool(agents[agent_id].is_system) if agent_id in agents else False,
185 )
186 for agent_id, n in agent_rows
187 ]
189 document_rows = (
190 db.query(
191 KnowledgeCitation.document_id,
192 KnowledgeCitation.knowledge_id,
193 answers.label("answers"),
194 )
195 .filter(*window)
196 .group_by(KnowledgeCitation.document_id, KnowledgeCitation.knowledge_id)
197 .order_by(answers.desc())
198 .limit(TOP)
199 .all()
200 )
201 document_ids = [d for d, _, _ in document_rows if d is not None]
202 documents = (
203 {
204 row.id: row
205 for row in db.query(
206 KnowledgeDocument.id,
207 KnowledgeDocument.source_id,
208 KnowledgeDocument.document_metadata,
209 )
210 .filter(KnowledgeDocument.id.in_(document_ids))
211 .all()
212 }
213 if document_ids
214 else {}
215 )
216 ranked_documents: list[Ranked] = []
217 for document_id, knowledge_id, n in document_rows:
218 if document_id in documents:
219 name, url = _document_name(documents[document_id])
220 ranked_documents.append(
221 Ranked(document_id, name, int(n), url=url, knowledge_id=knowledge_id)
222 )
223 else:
224 # Cited whole (a graph's facts), or a document deleted since.
225 ranked_documents.append(
226 Ranked(None, "The source as a whole", int(n), knowledge_id=knowledge_id)
227 )
229 ranked_sources: list[Ranked] = []
230 if rank_sources:
231 source_rows = (
232 db.query(KnowledgeCitation.knowledge_id, answers.label("answers"))
233 .filter(*window)
234 .group_by(KnowledgeCitation.knowledge_id)
235 .order_by(answers.desc())
236 .limit(TOP)
237 .all()
238 )
239 names = (
240 dict(
241 db.query(Knowledge.id, Knowledge.name)
242 .filter(Knowledge.id.in_([k for k, _ in source_rows]))
243 .all()
244 )
245 if source_rows
246 else {}
247 )
248 ranked_sources = [
249 Ranked(k, names.get(k, "Source"), int(n)) for k, n in source_rows
250 ]
252 newest = func.max(KnowledgeCitation.cited_at)
253 recent_rows = (
254 db.query(
255 KnowledgeCitation.message_id,
256 ChatMessage.conversation_id,
257 KnowledgeCitation.agent_id,
258 newest.label("cited_at"),
259 )
260 .join(ChatMessage, ChatMessage.id == KnowledgeCitation.message_id)
261 .filter(*window, KnowledgeCitation.owner_user_id == viewer_id)
262 .group_by(
263 KnowledgeCitation.message_id,
264 ChatMessage.conversation_id,
265 KnowledgeCitation.agent_id,
266 )
267 .order_by(newest.desc())
268 .limit(RECENT)
269 .all()
270 )
271 recent = [
272 RecentAnswer(
273 message_id=r.message_id,
274 conversation_id=r.conversation_id,
275 agent_id=r.agent_id,
276 agent_name=agents[r.agent_id].name if r.agent_id in agents else None,
277 cited_at=r.cited_at,
278 )
279 for r in recent_rows
280 ]
281 # An agent among the recent answers but outside the top ten is named too.
282 unnamed = {r.agent_id for r in recent if r.agent_id and r.agent_name is None}
283 if unnamed:
284 names = dict(
285 db.query(Agent.id, Agent.name).filter(Agent.id.in_(list(unnamed))).all()
286 )
287 recent = [
288 RecentAnswer(
289 r.message_id,
290 r.conversation_id,
291 r.agent_id,
292 r.agent_name or names.get(r.agent_id),
293 r.cited_at,
294 )
295 for r in recent
296 ]
298 return Usage(
299 days=days,
300 since=since,
301 answers=_answers(db, scope, since, until),
302 previous_answers=_answers(db, scope, since - timedelta(days=days), since),
303 daily=daily,
304 agents=ranked_agents,
305 documents=ranked_documents,
306 sources=ranked_sources,
307 recent=recent,
308 )