Coverage for app / services / retrieval.py: 100%

40 statements  

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

1""" 

2Knowledge retrieval service — the svc-core side of the context-rich RAG flow. 

3 

4svc-core owns *which* knowledge an agent or user may see (repositories, 

5knowledge bases, access checks) and svc-ai owns *how* it is retrieved (the 

6pipeline in ``app.knowledge.retrieval``). This module is the seam between 

7the two: 

8 

9* ``knowledge_spec`` — serialise a Knowledge row into svc-ai's 

10 ``KnowledgeBaseSpec`` shape (shared by agent execution 

11 and direct search so both see identical descriptors). 

12* ``search_knowledge`` — run svc-ai's retrieval pipeline over explicit 

13 knowledge bases (repository / KB search endpoints). 

14""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from collections.abc import Iterable 

20from typing import Any 

21from uuid import UUID 

22 

23from sqlalchemy.orm import Session 

24 

25from app.db.postgres.models import Knowledge, KnowledgeDocument 

26from app.services import ai_client 

27from app.services.knowledge import repositories 

28from app.util import knowledge_categories 

29from app.util.knowledge_categories import KnowledgeCategory 

30 

31logger = logging.getLogger(__name__) 

32 

33# Deterministic settings for the optional planner / reranker LLM. svc-ai's 

34# direct search (``POST /knowledge/retrieve``) runs both steps on the one 

35# model, so the output cap is the larger step's: the relevance judge's, the 

36# cap an agent's retrieval node gives it (svc-ai ``graph._RERANKER_MAX_TOKENS``). 

37# A query plan is a few hundred tokens and stops well short of it. svc-ai now 

38# fails a structured reply cut off at the cap rather than salvaging part of 

39# it, and at 1,024 a reasoning model can be cut off while still thinking, 

40# which would leave a knowledge search unplanned and unjudged. 

41_RETRIEVAL_MODEL_TEMPERATURE = 0.0 

42_RETRIEVAL_MODEL_MAX_TOKENS = 8192 

43 

44 

45def document_manifest_entry(doc: KnowledgeDocument) -> dict[str, Any]: 

46 """Serialise a document row into the manifest shape svc-ai expects. 

47 

48 The manifest is the authoritative list of what a knowledge base holds — 

49 independent of whether indexing has completed or the vector store is 

50 reachable — so an agent can always resolve a file the user names. 

51 """ 

52 meta = doc.document_metadata or {} 

53 return { 

54 "id": str(doc.id), 

55 "name": meta.get("original_filename") or doc.source_id, 

56 "source_id": doc.source_id, 

57 "folder_path": doc.folder_path or "", 

58 "mime_type": meta.get("mime_type", ""), 

59 "size_bytes": meta.get("size_bytes"), 

60 "index_status": meta.get("index_status", "unknown"), 

61 "index_error": meta.get("index_error"), 

62 "chunk_count": meta.get("chunk_count"), 

63 } 

64 

65 

66def load_document_manifests( 

67 db: Session, knowledge_ids: list[str] 

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

69 """``{knowledge_id: [manifest entries]}`` for every id in one query.""" 

70 if not knowledge_ids: 

71 return {} 

72 rows = ( 

73 db.query(KnowledgeDocument) 

74 .filter(KnowledgeDocument.knowledge_id.in_(knowledge_ids)) 

75 .order_by(KnowledgeDocument.created_at.asc()) 

76 .all() 

77 ) 

78 out: dict[str, list[dict[str, Any]]] = {kid: [] for kid in knowledge_ids} 

79 for doc in rows: 

80 out.setdefault(str(doc.knowledge_id), []).append(document_manifest_entry(doc)) 

81 return out 

82 

83 

84def knowledge_spec( 

85 kb: Knowledge, 

86 config: dict | None = None, 

87 documents: list[dict[str, Any]] | None = None, 

88 *, 

89 category: KnowledgeCategory | str | None = None, 

90 repositories: Iterable[str] = (), 

91) -> dict[str, Any]: 

92 """Serialise a Knowledge row into svc-ai's ``KnowledgeBaseSpec`` dict. 

93 

94 ``category`` is the kind of the repositories it was reached through 

95 (``knowledge/repositories.one_category``), which decides how svc-ai uses 

96 it; none is ``domain``. ``repositories`` are their names: a request that 

97 names one names its knowledge bases ("According to the Security guidance 

98 repository…" had matched none, as only a source's own name counted). 

99 """ 

100 return { 

101 "id": str(kb.id), 

102 "name": kb.name, 

103 "description": kb.description or "", 

104 "source_type": kb.source_type, 

105 "source_config": kb.source_config or {}, 

106 "config": dict(config or {}), 

107 "documents": list(documents or []), 

108 "category": knowledge_categories.of(category).value, 

109 "repositories": sorted({str(name) for name in repositories if name}), 

110 } 

111 

112 

113def resolve_retrieval_model(ai_model_id: UUID | None) -> dict[str, Any] | None: 

114 """Turn an svc-ai model id into a ``ModelConfig`` dict for planning/reranking. 

115 

116 Returns ``None`` when no model is requested so svc-ai runs the 

117 deterministic stages only. Propagates ``ModelNotAvailableError`` / 

118 ``AIServiceError`` from the lookup so callers can map them to HTTP errors. 

119 """ 

120 if not ai_model_id: 

121 return None 

122 info = ai_client.get_model(ai_model_id) 

123 return { 

124 "provider": info["provider"]["name"], 

125 "model": info["model_name"], 

126 "temperature": _RETRIEVAL_MODEL_TEMPERATURE, 

127 "max_tokens": _RETRIEVAL_MODEL_MAX_TOKENS, 

128 } 

129 

130 

131def search_knowledge( 

132 knowledge: list[Knowledge], 

133 query: str, 

134 retrieval: dict[str, Any] | None = None, 

135 ai_model_id: UUID | None = None, 

136 db: Session | None = None, 

137 *, 

138 via_repository_ids: list[UUID] | None = None, 

139) -> dict[str, Any]: 

140 """Run svc-ai's retrieval pipeline over *knowledge* and return the bundle. 

141 

142 ``retrieval`` holds ``RetrievalConfig`` overrides; ``mode`` is forced to 

143 ``pipeline`` because direct search has no agentic tool loop to seed. 

144 When ``db`` is given the document manifests are attached so named files 

145 resolve even before indexing completes, and each base is searched as the 

146 kind it is: through ``via_repository_ids`` (a repository's search), else 

147 through the repositories holding it. 

148 """ 

149 manifests = ( 

150 load_document_manifests(db, [str(kb.id) for kb in knowledge]) if db else {} 

151 ) 

152 categories = ( 

153 repositories.categories_of( 

154 db, [kb.id for kb in knowledge], via_repository_ids=via_repository_ids 

155 ) 

156 if db 

157 else {} 

158 ) 

159 specs = [ 

160 knowledge_spec( 

161 kb, documents=manifests.get(str(kb.id)), category=categories.get(kb.id) 

162 ) 

163 for kb in knowledge 

164 ] 

165 overrides = {**(retrieval or {}), "mode": "pipeline"} 

166 model = resolve_retrieval_model(ai_model_id) 

167 logger.info( 

168 "Knowledge search over %d KB(s) model=%s query_chars=%d", 

169 len(specs), 

170 model["model"] if model else None, 

171 len(query), 

172 ) 

173 return ai_client.retrieve_knowledge(query, specs, overrides, model)