|
| 1 | +"""Entity API endpoints for AutoMem. |
| 2 | +
|
| 3 | +Provides CRUD and query operations for first-class Entity nodes. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import json |
| 9 | +import logging |
| 10 | +from typing import Any, Callable, Dict, List, Optional |
| 11 | + |
| 12 | +from flask import Blueprint, abort, jsonify, request |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +def _parse_aliases(raw: Any) -> List[str]: |
| 18 | + """Safely parse aliases from a graph result (may be list or JSON string).""" |
| 19 | + if not raw: |
| 20 | + return [] |
| 21 | + if isinstance(raw, list): |
| 22 | + return raw |
| 23 | + if isinstance(raw, str): |
| 24 | + try: |
| 25 | + parsed = json.loads(raw) |
| 26 | + return parsed if isinstance(parsed, list) else [] |
| 27 | + except Exception: |
| 28 | + return [] |
| 29 | + return [] |
| 30 | + |
| 31 | + |
| 32 | +def _serialize_entity_row(row: list) -> Dict[str, Any]: |
| 33 | + """Convert a result row into a serialisable entity dict. |
| 34 | +
|
| 35 | + Expected column order (12 columns): |
| 36 | + 0: e.id, 1: e.slug, 2: e.category, 3: e.name, 4: e.aliases, |
| 37 | + 5: e.identity, 6: e.identity_version, 7: e.identity_updated_at, |
| 38 | + 8: e.identity_source_count, 9: ref_count, |
| 39 | + 10: e.created_at, 11: e.last_referenced_at |
| 40 | + """ |
| 41 | + return { |
| 42 | + "id": row[0], |
| 43 | + "slug": row[1], |
| 44 | + "category": row[2], |
| 45 | + "name": row[3], |
| 46 | + "aliases": _parse_aliases(row[4]), |
| 47 | + "identity": row[5], |
| 48 | + "identity_version": int(row[6] or 0), |
| 49 | + "identity_updated_at": row[7], |
| 50 | + "identity_source_count": int(row[8] or 0), |
| 51 | + "reference_count": int(row[9] or 0), |
| 52 | + "created_at": row[10] if len(row) > 10 else None, |
| 53 | + "last_referenced_at": row[11] if len(row) > 11 else None, |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | +def create_entity_blueprint( |
| 58 | + get_memory_graph: Callable[[], Any], |
| 59 | + logger: Any, |
| 60 | +) -> Blueprint: |
| 61 | + """Create the entity API blueprint.""" |
| 62 | + |
| 63 | + bp = Blueprint("entity", __name__) |
| 64 | + |
| 65 | + @bp.route("/entities", methods=["GET"]) |
| 66 | + def list_entities() -> Any: |
| 67 | + graph = get_memory_graph() |
| 68 | + if graph is None: |
| 69 | + abort(503, description="FalkorDB is unavailable") |
| 70 | + |
| 71 | + category = request.args.get("category") |
| 72 | + limit = min(int(request.args.get("limit", 100)), 500) |
| 73 | + |
| 74 | + if category: |
| 75 | + result = graph.query( |
| 76 | + """ |
| 77 | + MATCH (e:Entity) |
| 78 | + WHERE e.merged_into IS NULL AND e.category = $category |
| 79 | + OPTIONAL MATCH (e)-[ref:REFERENCED_IN]->() |
| 80 | + WITH e, count(ref) as ref_count |
| 81 | + RETURN e.id, e.slug, e.category, e.name, e.aliases, |
| 82 | + e.identity, e.identity_version, e.identity_updated_at, |
| 83 | + e.identity_source_count, ref_count, |
| 84 | + e.created_at, e.last_referenced_at |
| 85 | + ORDER BY ref_count DESC |
| 86 | + LIMIT $limit |
| 87 | + """, |
| 88 | + {"category": category, "limit": limit}, |
| 89 | + ) |
| 90 | + else: |
| 91 | + result = graph.query( |
| 92 | + """ |
| 93 | + MATCH (e:Entity) |
| 94 | + WHERE e.merged_into IS NULL |
| 95 | + OPTIONAL MATCH (e)-[ref:REFERENCED_IN]->() |
| 96 | + WITH e, count(ref) as ref_count |
| 97 | + RETURN e.id, e.slug, e.category, e.name, e.aliases, |
| 98 | + e.identity, e.identity_version, e.identity_updated_at, |
| 99 | + e.identity_source_count, ref_count, |
| 100 | + e.created_at, e.last_referenced_at |
| 101 | + ORDER BY ref_count DESC |
| 102 | + LIMIT $limit |
| 103 | + """, |
| 104 | + {"limit": limit}, |
| 105 | + ) |
| 106 | + |
| 107 | + entities = [] |
| 108 | + for row in getattr(result, "result_set", []) or []: |
| 109 | + entities.append(_serialize_entity_row(row)) |
| 110 | + |
| 111 | + return jsonify({"status": "success", "entities": entities, "count": len(entities)}) |
| 112 | + |
| 113 | + @bp.route("/entity/<slug>", methods=["GET"]) |
| 114 | + def get_entity(slug: str) -> Any: |
| 115 | + graph = get_memory_graph() |
| 116 | + if graph is None: |
| 117 | + abort(503, description="FalkorDB is unavailable") |
| 118 | + |
| 119 | + # Try direct slug match first, then alias lookup |
| 120 | + result = graph.query( |
| 121 | + """ |
| 122 | + MATCH (e:Entity) |
| 123 | + WHERE e.merged_into IS NULL AND (e.slug = $slug OR $slug IN e.aliases) |
| 124 | + OPTIONAL MATCH (e)-[ref:REFERENCED_IN]->() |
| 125 | + WITH e, count(ref) as ref_count |
| 126 | + RETURN e.id, e.slug, e.category, e.name, e.aliases, |
| 127 | + e.identity, e.identity_version, e.identity_updated_at, |
| 128 | + e.identity_source_count, ref_count, |
| 129 | + e.created_at, e.last_referenced_at |
| 130 | + LIMIT 1 |
| 131 | + """, |
| 132 | + {"slug": slug}, |
| 133 | + ) |
| 134 | + |
| 135 | + rows = getattr(result, "result_set", []) or [] |
| 136 | + if not rows: |
| 137 | + abort(404, description=f"Entity '{slug}' not found") |
| 138 | + |
| 139 | + entity = _serialize_entity_row(rows[0]) |
| 140 | + return jsonify({"status": "success", "entity": entity}) |
| 141 | + |
| 142 | + @bp.route("/entities/merge-candidates", methods=["GET"]) |
| 143 | + def merge_candidates() -> Any: |
| 144 | + graph = get_memory_graph() |
| 145 | + if graph is None: |
| 146 | + abort(503, description="FalkorDB is unavailable") |
| 147 | + |
| 148 | + try: |
| 149 | + from automem.consolidation.entity_dedup import find_merge_candidates |
| 150 | + |
| 151 | + auto_merge, review = find_merge_candidates(graph) |
| 152 | + auto_merge_ids = {(c.entity_a_id, c.entity_b_id) for c in auto_merge} |
| 153 | + candidates = [] |
| 154 | + for c in auto_merge + review: |
| 155 | + candidates.append({ |
| 156 | + "entity_a": c.entity_a_id, |
| 157 | + "entity_b": c.entity_b_id, |
| 158 | + "canonical": c.canonical_id, |
| 159 | + "alias": c.alias_id, |
| 160 | + "confidence": c.confidence, |
| 161 | + "reason": c.reason, |
| 162 | + "auto_merge": (c.entity_a_id, c.entity_b_id) in auto_merge_ids, |
| 163 | + }) |
| 164 | + return jsonify({"status": "success", "candidates": candidates, "count": len(candidates)}) |
| 165 | + except Exception as exc: |
| 166 | + logger.exception("Failed to find merge candidates") |
| 167 | + return jsonify({"error": "Failed to find merge candidates", "details": str(exc)}), 500 |
| 168 | + |
| 169 | + @bp.route("/entity/<slug>/merge", methods=["POST"]) |
| 170 | + def merge_entity(slug: str) -> Any: |
| 171 | + graph = get_memory_graph() |
| 172 | + if graph is None: |
| 173 | + abort(503, description="FalkorDB is unavailable") |
| 174 | + |
| 175 | + data = request.get_json(silent=True) or {} |
| 176 | + target_slug = data.get("merge_into") |
| 177 | + if not target_slug: |
| 178 | + abort(400, description="'merge_into' slug is required") |
| 179 | + |
| 180 | + # Resolve both entities |
| 181 | + alias_result = graph.query( |
| 182 | + "MATCH (e:Entity) WHERE e.slug = $slug AND e.merged_into IS NULL RETURN e.id LIMIT 1", |
| 183 | + {"slug": slug}, |
| 184 | + ) |
| 185 | + canonical_result = graph.query( |
| 186 | + "MATCH (e:Entity) WHERE e.slug = $slug AND e.merged_into IS NULL RETURN e.id LIMIT 1", |
| 187 | + {"slug": target_slug}, |
| 188 | + ) |
| 189 | + |
| 190 | + alias_rows = getattr(alias_result, "result_set", []) or [] |
| 191 | + canonical_rows = getattr(canonical_result, "result_set", []) or [] |
| 192 | + |
| 193 | + if not alias_rows: |
| 194 | + abort(404, description=f"Entity '{slug}' not found") |
| 195 | + if not canonical_rows: |
| 196 | + abort(404, description=f"Target entity '{target_slug}' not found") |
| 197 | + |
| 198 | + alias_id = alias_rows[0][0] |
| 199 | + canonical_id = canonical_rows[0][0] |
| 200 | + |
| 201 | + try: |
| 202 | + from automem.consolidation.entity_dedup import merge_entities |
| 203 | + |
| 204 | + merge_result = merge_entities(graph, canonical_id, alias_id) |
| 205 | + return jsonify({ |
| 206 | + "status": "success", |
| 207 | + "merge": { |
| 208 | + "canonical": merge_result.canonical_id, |
| 209 | + "alias": merge_result.alias_id, |
| 210 | + "alias_slug": merge_result.alias_slug, |
| 211 | + "edges_moved": merge_result.edges_moved, |
| 212 | + }, |
| 213 | + }) |
| 214 | + except Exception as exc: |
| 215 | + logger.exception("Merge failed") |
| 216 | + return jsonify({"error": "Merge failed", "details": str(exc)}), 500 |
| 217 | + |
| 218 | + return bp |
0 commit comments