Coverage for app / routers / knowledge.py: 96%

162 statements  

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

1""" 

2Knowledge endpoints. 

3 

4* ``GET /knowledge/node-types`` — built-in graph node type definitions, 

5 served to svc-core (which proxies them to the frontend) so the knowledge 

6 graph builder stays in sync with the registry. 

7* ``POST /knowledge/retrieve`` — run the context-rich retrieval pipeline 

8 directly over a set of knowledge bases and return the evidence bundle. 

9 svc-core uses this for repository / knowledge-base search and for 

10 previewing exactly what an agent would see. 

11* ``POST /knowledge/embed`` — embed texts with the platform embedding 

12 model. svc-core's document ingestion calls this (it runs on internal 

13 networks without LLM egress) so index and query vectors always share the 

14 embedding space configured here. 

15* ``GET /knowledge/embedding`` — which embedding model is active, and the 

16 size and key of its vectors, so svc-core builds (and rebuilds) its 

17 collections to match (``app.services.embeddings``). 

18""" 

19 

20from __future__ import annotations 

21 

22from typing import Any 

23 

24from fastapi import APIRouter, Depends, Response 

25from pydantic import BaseModel, Field 

26from sqlalchemy.orm import Session 

27 

28from app.dependency.base import get_db 

29from app.knowledge.registry import BUILTIN_NODE_TYPES 

30from app.services import model_errors 

31from app.services.conversation import trace_invocation 

32from app.services.model_errors import ModelUnavailableError 

33from app.models.spec import ( 

34 GraphFact, 

35 KnowledgeBaseSpec, 

36 ModelConfig, 

37 RetrievalConfig, 

38 RetrievedPassage, 

39) 

40 

41router = APIRouter(prefix="/knowledge", tags=["knowledge"]) 

42 

43 

44# --------------------------------------------------------------------------- 

45# Response models 

46# --------------------------------------------------------------------------- 

47 

48 

49class NodePropertyDef(BaseModel): 

50 key: str 

51 label: str 

52 type: str 

53 required: bool 

54 placeholder: str 

55 

56 

57class NodeTypeDefinition(BaseModel): 

58 name: str 

59 display_name: str 

60 description: str 

61 category: str 

62 color: str 

63 property_schema: list[NodePropertyDef] 

64 

65 

66class NodeTypesResponse(BaseModel): 

67 node_types: list[NodeTypeDefinition] 

68 

69 

70class RetrieveRequest(BaseModel): 

71 """Direct retrieval over explicit knowledge bases (no agent execution).""" 

72 

73 query: str = Field(min_length=1) 

74 knowledge_bases: list[KnowledgeBaseSpec] 

75 retrieval: RetrievalConfig = Field(default_factory=RetrievalConfig) 

76 # Optional LLM enabling query planning + reranking. Without it the 

77 # deterministic stages still run (keywords as hints, fused ordering). 

78 model: ModelConfig | None = None 

79 kb_metadata: str = "" 

80 # Whose search this is, and what it searched — for the trace. 

81 user_id: str | None = None 

82 reference: dict[str, str] | None = None 

83 

84 

85class EmbedRequest(BaseModel): 

86 texts: list[str] = Field(min_length=1, max_length=2048) 

87 # Whose content is being indexed (None for a built-in source, whose cost 

88 # is the platform's), and which knowledge base — for the trace. 

89 user_id: str | None = None 

90 reference: dict[str, str] | None = None 

91 

92 

93class EmbedResponse(BaseModel): 

94 model: str 

95 dimensions: int 

96 embeddings: list[list[float]] 

97 

98 

99class EmbeddingIdentity(BaseModel): 

100 """The deployment's embedding model, as svc-core builds collections for 

101 it. ``key`` names its vector space: a collection stamped with another 

102 key holds vectors this model cannot be compared with.""" 

103 

104 provider: str 

105 model: str 

106 dimensions: int 

107 key: str 

108 backend: str 

109 #: Whether this deployment may call it (Bedrock model access). 

110 available: bool 

111 

112 

113class RetrieveResponse(BaseModel): 

114 query: str 

115 queries: list[str] 

116 passages: list[RetrievedPassage] 

117 graph_facts: list[GraphFact] 

118 citations: list[dict[str, Any]] 

119 kb_ids: list[str] 

120 skipped_kbs: list[str] 

121 errors: list[str] 

122 context_markdown: str 

123 #: The frameworks a reasoning knowledge base held, packed apart from the 

124 #: evidence (``RetrievalBundle.frameworks_markdown``); empty with none. 

125 frameworks_markdown: str = "" 

126 approx_tokens: int 

127 timings_ms: dict[str, int] 

128 

129 

130# --------------------------------------------------------------------------- 

131# Endpoints 

132# --------------------------------------------------------------------------- 

133 

134 

135@router.get("/node-types", response_model=NodeTypesResponse) 

136def list_node_types() -> NodeTypesResponse: 

137 """ 

138 Return all built-in knowledge graph node type definitions. 

139 

140 Each definition includes a property_schema that describes the fields 

141 available for that entity type, used by the frontend to render 

142 schema-driven property editing forms. 

143 """ 

144 return NodeTypesResponse( 

145 node_types=[NodeTypeDefinition(**nt) for nt in BUILTIN_NODE_TYPES.values()] 

146 ) 

147 

148 

149#: Trace purposes of the knowledge endpoints' model work. 

150RETRIEVAL_PURPOSE = "knowledge_retrieval" 

151INDEXING_PURPOSE = "knowledge_indexing" 

152 

153 

154def _trace_config(reference: dict[str, str] | None, **detail: Any) -> dict: 

155 return {**detail, **({"reference": dict(reference)} if reference else {})} 

156 

157 

158@router.post("/retrieve", response_model=RetrieveResponse) 

159async def retrieve( 

160 request: RetrieveRequest, db: Session = Depends(get_db) 

161) -> RetrieveResponse: 

162 """ 

163 Run the retrieval pipeline over the given knowledge bases. 

164 

165 Returns ranked passages (with document / page / chunk provenance), graph 

166 facts, the rendered Markdown context an agent would receive, and the 

167 machine-readable citation list. Traced: the query embeddings, and the 

168 planning and reranking calls when a model is given. 

169 """ 

170 from app.knowledge.retrieval import retrieve_context 

171 

172 llm = None 

173 if request.model is not None: 

174 from app.services.llm import build_langchain_llm 

175 

176 llm = build_langchain_llm(request.model) 

177 

178 with trace_invocation( 

179 db, 

180 purpose=RETRIEVAL_PURPOSE, 

181 provider=request.model.provider if request.model else None, 

182 model=request.model.model if request.model else None, 

183 user_id=request.user_id, 

184 request_config=_trace_config( 

185 request.reference, 

186 knowledge_bases=[str(kb.id) for kb in request.knowledge_bases], 

187 ), 

188 ): 

189 bundle = await retrieve_context( 

190 request.query, 

191 [kb.model_dump() for kb in request.knowledge_bases], 

192 request.retrieval, 

193 llm=llm, 

194 kb_metadata=request.kb_metadata, 

195 ) 

196 return RetrieveResponse( 

197 query=bundle.query, 

198 queries=bundle.queries, 

199 passages=bundle.passages, 

200 graph_facts=bundle.graph_facts, 

201 citations=bundle.citations, 

202 kb_ids=bundle.kb_ids, 

203 skipped_kbs=bundle.skipped_kbs, 

204 errors=bundle.errors, 

205 context_markdown=bundle.context_markdown, 

206 frameworks_markdown=bundle.frameworks_markdown, 

207 approx_tokens=bundle.approx_tokens, 

208 timings_ms=bundle.timings_ms, 

209 ) 

210 

211 

212@router.get("/embedding", response_model=EmbeddingIdentity) 

213def embedding_identity() -> EmbeddingIdentity: 

214 """The deployment's active embedding model. 

215 

216 svc-core sizes its collections by it and stamps them with its key.""" 

217 from app.services import embeddings 

218 

219 return EmbeddingIdentity(**embeddings.active().identity()) 

220 

221 

222@router.post("/embed", response_model=EmbedResponse) 

223async def embed(request: EmbedRequest, db: Session = Depends(get_db)) -> EmbedResponse: 

224 """Embed *texts* with the deployment's embedding model (batched, ordered). 

225 

226 Traced against the embedding model, one row per request. 

227 """ 

228 from fastapi import HTTPException 

229 

230 from app.services import embeddings 

231 from app.services import rag as rag_service 

232 

233 texts = [t if isinstance(t, str) else str(t) for t in request.texts] 

234 if any(not t.strip() for t in texts): 

235 raise HTTPException(status_code=422, detail="texts must be non-empty strings") 

236 embedder = embeddings.active() 

237 model = embedder.model 

238 failure: Exception | None = None 

239 with trace_invocation( 

240 db, 

241 purpose=INDEXING_PURPOSE, 

242 provider=embedder.provider, 

243 model=model, 

244 user_id=request.user_id, 

245 request_config=_trace_config(request.reference, texts=len(texts)), 

246 ) as outcome: 

247 try: 

248 vectors = await rag_service.embed_texts(texts) 

249 except ModelUnavailableError: 

250 # The spending ceiling, or credentials / access / quota: traced as 

251 # it escapes, then main.py answers 502 with what to fix. 

252 raise 

253 except Exception as exc: 

254 # The trace keeps the provider's own line; the response does not. 

255 outcome.error = f"{type(exc).__name__}: {exc}" 

256 failure = exc 

257 if failure is not None: 

258 raise HTTPException( 

259 status_code=502, 

260 detail=f"Embedding provider error: {model_errors.user_message(failure)}", 

261 ) from failure 

262 return EmbedResponse( 

263 model=model, 

264 dimensions=len(vectors[0]) if vectors else embedder.dimensions, 

265 embeddings=vectors, 

266 ) 

267 

268 

269# --------------------------------------------------------------------------- 

270# Website knowledge — one page per call; svc-core runs the crawl 

271# --------------------------------------------------------------------------- 

272 

273 

274class WebFetchRequest(BaseModel): 

275 url: str = Field(..., max_length=2048) 

276 #: Validators from the page's last stored version, for a conditional GET. 

277 etag: str | None = Field(default=None, max_length=512) 

278 last_modified: str | None = Field(default=None, max_length=128) 

279 #: The page is one article (a feed listed it): prefer its article text 

280 #: to the whole page, navigation and cookie banners included. 

281 article: bool = False 

282 

283 

284class WebFetchResponse(BaseModel): 

285 requested_url: str 

286 #: ok | not_modified | blocked_by_robots | unsafe | http_error | 

287 #: unsupported | auth_required | error 

288 status: str 

289 url: str = "" 

290 http_status: int | None = None 

291 title: str | None = None 

292 published: str | None = None 

293 markdown: str = "" 

294 content_hash: str | None = None 

295 html: str | None = None 

296 content_type: str | None = None 

297 etag: str | None = None 

298 last_modified: str | None = None 

299 #: ``{url, text, category, in_content, external}`` per link; category is 

300 #: content | action | account | asset | feed (knowledge/web_extract.py). 

301 links: list[dict] = Field(default_factory=list) 

302 #: Set instead of content when the URL was a sitemap or sitemap index. 

303 sitemap_urls: list[str] = Field(default_factory=list) 

304 #: Set instead of content when the URL was an RSS or Atom feed: 

305 #: ``{url, title, published, summary, author}`` per entry. 

306 feed_entries: list[dict] = Field(default_factory=list) 

307 crawl_delay: float | None = None 

308 error: str | None = None 

309 

310 

311@router.post("/web/fetch", response_model=WebFetchResponse) 

312async def web_fetch(request: WebFetchRequest) -> WebFetchResponse: 

313 """Fetch one page of a website knowledge source. 

314 

315 Always 200: a page that could not be read is a result the crawl records 

316 (``status`` says why), not a failure of this call. 

317 """ 

318 from dataclasses import asdict 

319 

320 from app.knowledge.web import fetch_page 

321 

322 result = await fetch_page( 

323 request.url, 

324 etag=request.etag, 

325 last_modified=request.last_modified, 

326 article=request.article, 

327 ) 

328 return WebFetchResponse(**asdict(result)) 

329 

330 

331class DocumentFetchRequest(BaseModel): 

332 url: str = Field(..., max_length=2048) 

333 

334 

335@router.post( 

336 "/web/document", 

337 response_class=Response, 

338 responses={200: {"content": {"application/octet-stream": {}}}}, 

339) 

340async def web_document(request: DocumentFetchRequest) -> Response: 

341 """Download one document for a file knowledge source — a PDF or an 

342 office or text document, never a page (``knowledge/web.fetch_document``). 

343 

344 The bytes come back as they are, with where they came from in headers 

345 (percent-encoded: a header is ASCII). A document that could not be had 

346 is a 422 saying why, safe to show beside the URL. 

347 """ 

348 from urllib.parse import quote 

349 

350 from fastapi.responses import JSONResponse 

351 

352 from app.knowledge.web import fetch_document 

353 

354 result = await fetch_document(request.url) 

355 if result.status != "ok" or result.content is None: 

356 return JSONResponse( 

357 status_code=422, 

358 content={"detail": {"status": result.status, "message": result.error}}, 

359 ) 

360 headers = { 

361 "X-Document-Url": quote(result.url, safe=":/?&=%#@+,;~"), 

362 "X-Document-Filename": quote(result.filename or "document", safe=""), 

363 } 

364 if result.last_modified: 

365 headers["X-Document-Last-Modified"] = quote(result.last_modified, safe=" ,:") 

366 return Response( 

367 content=result.content, media_type=result.mime_type, headers=headers 

368 ) 

369 

370 

371class FaviconRequest(BaseModel): 

372 domain: str = Field(..., max_length=253) 

373 

374 

375class FaviconResponse(BaseModel): 

376 #: ok | missing | unsafe | invalid 

377 status: str 

378 content_type: str | None = None 

379 #: The icon, base64 — a verified raster image (PNG, ICO, GIF, JPEG, WebP). 

380 data_b64: str | None = None 

381 source_url: str | None = None 

382 error: str | None = None 

383 

384 

385@router.post("/web/favicon", response_model=FaviconResponse) 

386async def web_favicon(request: FaviconRequest) -> FaviconResponse: 

387 """A site's icon, fetched by the platform so the user's browser never asks 

388 a third party (knowledge/favicon.py). svc-core caches the result.""" 

389 from dataclasses import asdict 

390 

391 from app.knowledge.favicon import fetch_icon 

392 

393 return FaviconResponse(**asdict(await fetch_icon(request.domain)))