Coverage for app / util / neo4j_client.py: 25%

145 statements  

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

1""" 

2Neo4j client utility for svc-ai. 

3 

4Uses the async driver (neo4j.AsyncGraphDatabase) since all svc-ai service 

5endpoints are async. Provides graph traversal helpers for the 

6query_knowledge_graph tool. 

7 

8Graph data model (mirrors svc-core): 

9 Nodes — :Entity { id, knowledge_id, label, name, properties } 

10 Edges — :RELATES_TO { id, knowledge_id, relationship, properties } 

11 

12All data is namespaced by knowledge_id so a single Neo4j instance can serve 

13multiple knowledge bases. 

14""" 

15 

16import json 

17import logging 

18from typing import Any 

19 

20from neo4j import AsyncGraphDatabase, AsyncDriver 

21 

22from app.common.settings import get_settings 

23from app.util import source_trailers 

24 

25logger = logging.getLogger(__name__) 

26 

27_driver: AsyncDriver | None = None 

28 

29_GRAPH_SOURCES_MARKER = source_trailers.GRAPH 

30 

31_MAX_DEPTH = 5 # hard cap on relationship traversal depth 

32 

33# Process-lifetime cache — graph schemas change rarely within a session. 

34_schema_cache: dict[str, dict[str, Any]] = {} 

35 

36 

37def _parse_properties(raw: Any) -> dict: 

38 """Normalise a Neo4j properties value to a plain dict. 

39 

40 svc-core stores ``e.properties`` as a JSON string; this helper 

41 parses it back to a dict so callers never have to handle strings. 

42 """ 

43 if isinstance(raw, str): 

44 try: 

45 parsed = json.loads(raw) 

46 return parsed if isinstance(parsed, dict) else {} 

47 except (json.JSONDecodeError, ValueError): 

48 return {} 

49 if isinstance(raw, dict): 

50 return raw 

51 return {} 

52 

53 

54def _clamp_depth(depth: int) -> int: 

55 """Clamp traversal depth to a safe range [1, _MAX_DEPTH].""" 

56 return max(1, min(int(depth), _MAX_DEPTH)) 

57 

58 

59async def get_driver() -> AsyncDriver: 

60 global _driver 

61 if _driver is None: 

62 s = get_settings() 

63 _driver = AsyncGraphDatabase.driver( 

64 s.neo4j_uri, 

65 auth=(s.neo4j_user, s.neo4j_password), 

66 max_connection_pool_size=10, 

67 connection_timeout=10.0, 

68 ) 

69 try: 

70 await _driver.verify_connectivity() 

71 logger.info("Neo4j connectivity verified") 

72 except Exception as exc: 

73 logger.error("Neo4j connectivity check failed: %s", exc) 

74 raise 

75 return _driver 

76 

77 

78async def close() -> None: 

79 global _driver 

80 if _driver is not None: 

81 await _driver.close() 

82 _driver = None 

83 

84 

85def invalidate_schema_cache(knowledge_id: str | None = None) -> None: 

86 """Evict cached schema for one graph (or all graphs if knowledge_id is None). 

87 

88 Call this whenever entities or relationships are added/removed so the next 

89 agent invocation fetches a fresh schema. 

90 """ 

91 if knowledge_id is None: 

92 _schema_cache.clear() 

93 else: 

94 _schema_cache.pop(knowledge_id, None) 

95 

96 

97# --------------------------------------------------------------------------- 

98# Query helpers 

99# --------------------------------------------------------------------------- 

100 

101 

102async def text_search_entities( 

103 knowledge_id: str, 

104 term: str, 

105 limit: int = 10, 

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

107 """Find Entity nodes whose name or label contains any word from *term*. 

108 

109 Tokenises the query so natural-language input like "who is Alice Smith" 

110 also matches an entity named "Alice" or "Smith". 

111 """ 

112 # Build a token list; fall back to the full term if it's a single word. 

113 tokens = [t for t in term.strip().split() if t] or [term] 

114 

115 driver = await get_driver() 

116 async with driver.session() as session: 

117 result = await session.run( 

118 """ 

119 MATCH (e:Entity {knowledge_id: $kid}) 

120 WHERE ANY(token IN $tokens WHERE 

121 toLower(e.name) CONTAINS toLower(token) 

122 OR toLower(e.label) CONTAINS toLower(token) 

123 ) 

124 RETURN e.id AS id, e.name AS name, e.label AS label, 

125 e.properties AS properties 

126 LIMIT $limit 

127 """, 

128 kid=knowledge_id, 

129 tokens=tokens, 

130 limit=limit, 

131 ) 

132 rows = await result.data() 

133 

134 logger.debug( 

135 "text_search_entities knowledge_id=%s term=%r tokens=%s → %d results", 

136 knowledge_id, 

137 term, 

138 tokens, 

139 len(rows), 

140 ) 

141 return [ 

142 { 

143 "id": r["id"], 

144 "name": r["name"] or "", 

145 "label": r["label"] or "", 

146 "properties": _parse_properties(r["properties"]), 

147 } 

148 for r in rows 

149 ] 

150 

151 

152async def find_neighbors( 

153 knowledge_id: str, 

154 entity_name: str, 

155 depth: int = 2, 

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

157 """Return all relationships reachable within *depth* hops from entities 

158 whose name contains *entity_name*. 

159 

160 Results are flattened to a list of: 

161 {from_name, from_label, relationship, to_name, to_label} 

162 

163 Neo4j does not support query parameters for variable-length path bounds, 

164 so the (validated) depth integer is injected directly into the query string. 

165 """ 

166 safe_depth = _clamp_depth(depth) 

167 

168 # Build the query with a literal depth bound — Neo4j requires this. 

169 # safe_depth is a server-controlled integer so string interpolation is safe. 

170 cypher = f""" 

171 MATCH (start:Entity {{knowledge_id: $kid}}) 

172 WHERE toLower(start.name) CONTAINS toLower($name) 

173 MATCH path = (start)-[:RELATES_TO*1..{safe_depth}]-(neighbor:Entity {{knowledge_id: $kid}}) 

174 WITH relationships(path) AS rels 

175 UNWIND rels AS rel 

176 WITH startNode(rel) AS a, rel, endNode(rel) AS b 

177 WHERE a.knowledge_id = $kid AND b.knowledge_id = $kid 

178 RETURN DISTINCT 

179 a.name AS from_name, a.label AS from_label, 

180 rel.relationship AS relationship, 

181 b.name AS to_name, b.label AS to_label 

182 LIMIT 100 

183 """ 

184 

185 driver = await get_driver() 

186 async with driver.session() as session: 

187 result = await session.run(cypher, kid=knowledge_id, name=entity_name) 

188 rows = await result.data() 

189 

190 logger.debug( 

191 "find_neighbors knowledge_id=%s entity=%r depth=%d → %d relationships", 

192 knowledge_id, 

193 entity_name, 

194 safe_depth, 

195 len(rows), 

196 ) 

197 return [ 

198 { 

199 "from_name": r["from_name"] or "", 

200 "from_label": r["from_label"] or "", 

201 "relationship": r["relationship"] or "", 

202 "to_name": r["to_name"] or "", 

203 "to_label": r["to_label"] or "", 

204 } 

205 for r in rows 

206 ] 

207 

208 

209# --------------------------------------------------------------------------- 

210# Formatting 

211# --------------------------------------------------------------------------- 

212 

213 

214def _format_results( 

215 entities: list[dict[str, Any]], 

216 relationships: list[dict[str, Any]], 

217 query: str, 

218 knowledge_id: str, 

219) -> str: 

220 source_tag = _GRAPH_SOURCES_MARKER + json.dumps([f"kb_{knowledge_id}"]) 

221 

222 if not entities: 

223 return ( 

224 f'No entities found matching "{query}" in the knowledge graph.' + source_tag 

225 ) 

226 

227 lines: list[str] = [f'Knowledge graph results for: "{query}"', ""] 

228 

229 for entity in entities: 

230 lines.append(f"Entity: {entity['name']} ({entity['label']})") 

231 if entity.get("properties"): 

232 for k, v in entity["properties"].items(): 

233 lines.append(f" {k}: {v}") 

234 

235 entity_rels = [ 

236 r 

237 for r in relationships 

238 if r["from_name"] == entity["name"] or r["to_name"] == entity["name"] 

239 ] 

240 if entity_rels: 

241 lines.append(" Relationships:") 

242 for r in entity_rels: 

243 if r["from_name"] == entity["name"]: 

244 lines.append( 

245 f" → {r['relationship']} → {r['to_name']} ({r['to_label']})" 

246 ) 

247 else: 

248 lines.append( 

249 f" ← {r['relationship']} ← {r['from_name']} ({r['from_label']})" 

250 ) 

251 lines.append("") 

252 

253 return "\n".join(lines).rstrip() + source_tag 

254 

255 

256# --------------------------------------------------------------------------- 

257# Schema introspection 

258# --------------------------------------------------------------------------- 

259 

260 

261_SCHEMA_NAME_LIMIT = 25 # names collected per label; enough to enumerate small graphs 

262 

263 

264async def get_graph_schema(knowledge_id: str) -> dict[str, Any]: 

265 """Return schema metadata for a knowledge graph. 

266 

267 Queries distinct entity labels with their full name lists (up to 

268 _SCHEMA_NAME_LIMIT per label), sample property keys, and all distinct 

269 relationship types. Results are cached for the process lifetime. 

270 

271 Schema dict shape:: 

272 

273 { 

274 "entity_types": [ 

275 { 

276 "label": "Person", 

277 "count": 42, 

278 "names": ["Alice Smith", "Bob Jones", ...], # up to _SCHEMA_NAME_LIMIT 

279 "names_complete": False, # True when count <= _SCHEMA_NAME_LIMIT 

280 "property_keys": ["age", "email", "occupation"], 

281 } 

282 ], 

283 "relationship_types": ["KNOWS", "MANAGES", "WORKS_AT"], 

284 "total_entities": 87, 

285 } 

286 """ 

287 if knowledge_id in _schema_cache: 

288 return _schema_cache[knowledge_id] 

289 

290 driver = await get_driver() 

291 async with driver.session() as session: 

292 label_result = await session.run( 

293 """ 

294 MATCH (e:Entity {knowledge_id: $kid}) 

295 WITH e.label AS label, 

296 count(*) AS cnt, 

297 collect(e.name)[0..$name_limit] AS names, 

298 collect(e.properties)[0..5] AS sample_props 

299 RETURN label, cnt, names, sample_props 

300 ORDER BY cnt DESC 

301 LIMIT 50 

302 """, 

303 kid=knowledge_id, 

304 name_limit=_SCHEMA_NAME_LIMIT, 

305 ) 

306 label_rows = await label_result.data() 

307 

308 rel_result = await session.run( 

309 """ 

310 MATCH (:Entity {knowledge_id: $kid})-[r:RELATES_TO]-(:Entity {knowledge_id: $kid}) 

311 RETURN DISTINCT r.relationship AS relationship 

312 ORDER BY relationship 

313 """, 

314 kid=knowledge_id, 

315 ) 

316 rel_rows = await rel_result.data() 

317 

318 entity_types: list[dict[str, Any]] = [] 

319 total_entities = 0 

320 for row in label_rows: 

321 label = row["label"] or "Unknown" 

322 cnt = row["cnt"] or 0 

323 total_entities += cnt 

324 names = [n for n in (row["names"] or []) if n] 

325 

326 prop_keys: set[str] = set() 

327 for raw in row["sample_props"] or []: 

328 prop_keys.update(_parse_properties(raw).keys()) 

329 

330 entity_types.append( 

331 { 

332 "label": label, 

333 "count": cnt, 

334 "names": names, 

335 "names_complete": cnt <= _SCHEMA_NAME_LIMIT, 

336 "property_keys": sorted(prop_keys), 

337 } 

338 ) 

339 

340 relationship_types = [r["relationship"] for r in rel_rows if r.get("relationship")] 

341 

342 schema: dict[str, Any] = { 

343 "entity_types": entity_types, 

344 "relationship_types": relationship_types, 

345 "total_entities": total_entities, 

346 } 

347 _schema_cache[knowledge_id] = schema 

348 logger.debug( 

349 "Cached schema for knowledge_id=%s: %d entity types, %d rel types, %d total entities", 

350 knowledge_id, 

351 len(entity_types), 

352 len(relationship_types), 

353 total_entities, 

354 ) 

355 return schema 

356 

357 

358def format_schema_as_context(schema: dict[str, Any]) -> str: 

359 """Render a graph schema dict as a structured Markdown block for system prompts. 

360 

361 Produces a per-entity-type listing with all known names so the model can 

362 form precise queries rather than guessing. Explicitly signals empty graphs 

363 so the model skips the tool instead of issuing futile queries. 

364 """ 

365 total_entities: int = schema.get("total_entities", 0) 

366 

367 if total_entities == 0: 

368 return ( 

369 "**Graph status: EMPTY** — this knowledge graph has no entities yet. " 

370 "Do not call this tool; it will return no results." 

371 ) 

372 

373 entity_types: list[dict[str, Any]] = schema.get("entity_types", []) 

374 rel_types: list[str] = schema.get("relationship_types", []) 

375 

376 total_labels = len(entity_types) 

377 lines: list[str] = [ 

378 f"**Graph contents — {total_entities} " 

379 f"{'entity' if total_entities == 1 else 'entities'} " 

380 f"across {total_labels} {'type' if total_labels == 1 else 'types'}:**", 

381 ] 

382 

383 for et in entity_types: 

384 label = et["label"] 

385 count = et["count"] 

386 names: list[str] = et["names"] 

387 names_complete: bool = et["names_complete"] 

388 prop_keys: list[str] = et["property_keys"] 

389 

390 completeness = "all" if names_complete else f"first {len(names)} of {count}" 

391 header = f"- **{label}** ({completeness}):" 

392 lines.append(header) 

393 if names: 

394 lines.append(f" Names: {', '.join(names)}") 

395 if prop_keys: 

396 lines.append(f" Properties: {', '.join(prop_keys)}") 

397 

398 if rel_types: 

399 lines.append(f"- **Relationship types:** {', '.join(rel_types)}") 

400 

401 lines += [ 

402 "", 

403 "**Querying rules — follow exactly:**", 

404 "1. Use an exact entity name from the lists above (e.g. `Docker`, not `container technology`).", 

405 "2. To retrieve all entities of one type, query by label (e.g. `Technology`, `Person`).", 

406 "3. Never pass natural-language phrases or questions as the query — match only names or labels.", 

407 "4. If you need everything, call the tool once per entity type using the label as the query.", 

408 ] 

409 

410 return "\n".join(lines) 

411 

412 

413# --------------------------------------------------------------------------- 

414# Public entry point 

415# --------------------------------------------------------------------------- 

416 

417 

418async def query_and_format( 

419 knowledge_id: str, 

420 query: str, 

421 depth: int = 2, 

422 limit: int = 10, 

423) -> str: 

424 """High-level entry point used by the query_knowledge_graph tool. 

425 

426 Finds matching entities then expands to their neighborhood. 

427 """ 

428 try: 

429 entities = await text_search_entities(knowledge_id, query, limit=limit) 

430 relationships: list[dict[str, Any]] = [] 

431 seen: set[tuple] = set() 

432 for entity in entities: 

433 rels = await find_neighbors(knowledge_id, entity["name"], depth=depth) 

434 for r in rels: 

435 key = (r["from_name"], r["relationship"], r["to_name"]) 

436 if key not in seen: 

437 seen.add(key) 

438 relationships.append(r) 

439 return _format_results(entities, relationships, query, knowledge_id) 

440 except Exception: 

441 logger.exception("Failed to query knowledge graph %s", knowledge_id) 

442 return ( 

443 f"query_knowledge_graph: Failed to query graph for knowledge base " 

444 f"{knowledge_id!r}. Check service logs for details." 

445 )