Vedanshipanda/layer10-api
0
1from fastapi import FastAPI2from fastapi.middleware.cors import CORSMiddleware3import json4import os5 6app = FastAPI()7 8app.add_middleware(9 CORSMiddleware,10 allow_origins=["*"],11 allow_methods=["*"],12 allow_headers=["*"],13)14 15GRAPH_PATH = os.path.join("data", "memory_graph.json")16 17# fallback to knowledge_graph.json if memory_graph.json not found18if not os.path.exists(GRAPH_PATH):19 GRAPH_PATH = os.path.join("data", "knowledge_graph.json")20 21 22@app.get("/graph")23def get_graph():24 if not os.path.exists(GRAPH_PATH):25 return {"nodes": [], "links": []}26 27 with open(GRAPH_PATH, "r", encoding="utf-8") as f:28 data = json.load(f)29 30 nodes = data.get("nodes", [])31 32 # Build index → id map for networkx integer-index links33 index_to_id = {}34 for i, n in enumerate(nodes):35 index_to_id[i] = n.get("id", str(i))36 37 # networkx exports "edges" not "links" — normalise to "links"38 raw_links = data.get("links", data.get("edges", []))39 40 links = []41 for l in raw_links:42 src = l.get("source")43 tgt = l.get("target")44 # Resolve integer indices to string IDs45 if isinstance(src, int):46 src = index_to_id.get(src, src)47 if isinstance(tgt, int):48 tgt = index_to_id.get(tgt, tgt)49 links.append({**l, "source": src, "target": tgt})50 51 return {"nodes": nodes, "links": links}52 53 54@app.get("/retrieve")55def retrieve(query: str):56 if not os.path.exists(GRAPH_PATH):57 return {"context_pack": []}58 59 with open(GRAPH_PATH, "r", encoding="utf-8") as f:60 data = json.load(f)61 62 results = []63 q = query.lower()64 65 for node in data.get("nodes", []):66 node_id = str(node.get("id", ""))67 node_type = str(node.get("type", "Unknown"))68 node_desc = str(node.get("description", node.get("summary", "")))69 70 if q in node_id.lower() or q in node_desc.lower():71 results.append({72 "entity": node_id,73 "type": node_type,74 "description": node_desc or f"{node_type} entity",75 })76 77 return {"context_pack": results[:10]}78 79 80@app.get("/health")81def health():82 return {"status": "ok", "graph": os.path.exists(GRAPH_PATH)}83 84 85if __name__ == "__main__":86 import uvicorn87 uvicorn.run(app, host="0.0.0.0", port=7860)