Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): replace KeyError/ValueError with HTTPException across all routes, fix temporal pattern method, add SPA root handler (#463)

Mohd Kaif8eafd2d024f4
diff --git a/semantica/explorer/app.py b/semantica/explorer/app.py
index 93674e8f..852db430 100644
--- a/semantica/explorer/app.py
+++ b/semantica/explorer/app.py
@@ -10,7 +10,7 @@ from typing import Optional
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import FileResponse, JSONResponse
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from .. import __version__
@@ -129,12 +129,14 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:
@app.get("/", include_in_schema=False)
async def root():
- return {
- "message": "Welcome to Semantica Knowledge Explorer",
- "version": __version__,
- "ui": "http://localhost:5174",
- "docs": "http://localhost:8000/docs",
- }
+ index_path = Path(__file__).resolve().parent.parent / "static" / "index.html"
+ if index_path.is_file():
+ return FileResponse(index_path)
+ return HTMLResponse(
+ '<!doctype html><html lang="en"><head><meta charset="UTF-8">'
+ '<title>Semantica Knowledge Explorer</title></head>'
+ '<body><div id="root"></div></body></html>'
+ )
@app.get("/api/health")
async def health():
diff --git a/semantica/explorer/routes/annotations.py b/semantica/explorer/routes/annotations.py
index f32f478d..4b649f02 100644
--- a/semantica/explorer/routes/annotations.py
+++ b/semantica/explorer/routes/annotations.py
@@ -8,7 +8,7 @@ modify Semantica core.
import asyncio
from typing import Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from ..dependencies import get_session
from ..schemas import AnnotationCreate, AnnotationResponse
@@ -35,7 +35,7 @@ async def create_annotation(
"""Create a new annotation on a node."""
node = await asyncio.to_thread(session.get_node, body.node_id)
if node is None:
- raise KeyError(body.node_id)
+ raise HTTPException(status_code=404, detail=f"Node '{body.node_id}' not found")
ann_data = body.model_dump()
ann_id = await asyncio.to_thread(session.add_annotation, ann_data)
@@ -61,5 +61,5 @@ async def delete_annotation(
"""Delete an annotation by ID."""
deleted = await asyncio.to_thread(session.delete_annotation, annotation_id)
if not deleted:
- raise KeyError(annotation_id)
+ raise HTTPException(status_code=404, detail=f"Annotation '{annotation_id}' not found")
return None
diff --git a/semantica/explorer/routes/decisions.py b/semantica/explorer/routes/decisions.py
index fdea8d2c..159c6392 100644
--- a/semantica/explorer/routes/decisions.py
+++ b/semantica/explorer/routes/decisions.py
@@ -5,7 +5,7 @@ Decision routes using ContextGraph-native fallbacks.
import asyncio
from typing import Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from ..dependencies import get_session
from ..schemas import CausalChainResponse, ComplianceResponse, DecisionResponse
@@ -59,7 +59,7 @@ async def get_decision(
):
node = await asyncio.to_thread(session.get_node, decision_id)
if node is None:
- raise KeyError(decision_id)
+ raise HTTPException(status_code=404, detail=f"Decision '{decision_id}' not found")
return _node_to_decision(node)
@@ -70,7 +70,7 @@ async def get_causal_chain(
):
node = await asyncio.to_thread(session.get_node, decision_id)
if node is None:
- raise KeyError(decision_id)
+ raise HTTPException(status_code=404, detail=f"Decision '{decision_id}' not found")
neighbors = await asyncio.to_thread(session.get_neighbors, decision_id, 5)
chain = [
@@ -94,7 +94,7 @@ async def get_precedents(
):
node = await asyncio.to_thread(session.get_node, decision_id)
if node is None:
- raise KeyError(decision_id)
+ raise HTTPException(status_code=404, detail=f"Decision '{decision_id}' not found")
properties = node.get("properties", {})
category = str(properties.get("category", ""))
@@ -132,7 +132,7 @@ async def check_compliance(
):
node = await asyncio.to_thread(session.get_node, decision_id)
if node is None:
- raise KeyError(decision_id)
+ raise HTTPException(status_code=404, detail=f"Decision '{decision_id}' not found")
edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)
violation_types = {"violates", "non_compliant", "breaches"}
diff --git a/semantica/explorer/routes/enrich.py b/semantica/explorer/routes/enrich.py
index be87c783..ffdae97a 100644
--- a/semantica/explorer/routes/enrich.py
+++ b/semantica/explorer/routes/enrich.py
@@ -6,7 +6,7 @@ import asyncio
import re
from typing import Dict, List, Optional, Tuple
-from fastapi import APIRouter, Depends
+from fastapi import APIRouter, Depends, HTTPException
from ..dependencies import get_session
from ..schemas import (
@@ -173,11 +173,12 @@ async def extract_entities(
relations=[_safe_dict(relation) for relation in rel_list],
)
except ImportError:
- raise ValueError(
- "semantic_extract module not available. Ensure spacy and transformers are installed."
+ raise HTTPException(
+ status_code=503,
+ detail="semantic_extract module not available. Ensure spacy and transformers are installed.",
)
except Exception as exc:
- raise ValueError(f"Extraction failed: {exc}")
+ raise HTTPException(status_code=422, detail=f"Extraction failed: {exc}")
@router.post("/api/enrich/links", response_model=LinkPredictionResponse)
@@ -187,11 +188,11 @@ async def predict_links(
):
predictor = session.link_predictor
if predictor is None:
- raise ValueError("LinkPredictor not available; KG extras may not be installed.")
+ raise HTTPException(status_code=503, detail="LinkPredictor not available; KG extras may not be installed.")
node = await asyncio.to_thread(session.get_node, body.node_id)
if node is None:
- raise KeyError(body.node_id)
+ raise HTTPException(status_code=404, detail=f"Node '{body.node_id}' not found")
nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)
edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)
@@ -248,9 +249,9 @@ async def detect_duplicates(
duplicate_list = duplicates if isinstance(duplicates, list) else getattr(duplicates, "duplicates", [])
return DedupResponse(duplicates=[_safe_dict(item) for item in duplicate_list], total_flagged=len(duplicate_list))
except ImportError:
- raise ValueError("Deduplication module not available.")
+ raise HTTPException(status_code=503, detail="Deduplication module not available.")
except Exception as exc:
- raise ValueError(f"Dedup scan failed: {exc}")
+ raise HTTPException(status_code=422, detail=f"Dedup scan failed: {exc}")
@router.post("/api/reason", response_model=ReasoningResponse)
@@ -295,7 +296,7 @@ async def merge_nodes(
node = await asyncio.to_thread(session.get_node, primary_id)
if node is None:
- raise ValueError(f"Primary node {primary_id} not found")
+ raise HTTPException(status_code=404, detail=f"Primary node '{primary_id}' not found")
def _do_merge() -> tuple[list[str], int]:
removed: list[str] = []
diff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.py
index 92da3bc7..13ed49e9 100644
--- a/semantica/explorer/routes/graph.py
+++ b/semantica/explorer/routes/graph.py
@@ -6,7 +6,7 @@ import asyncio
from enum import Enum
from typing import Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from ..dependencies import get_session
from ..schemas import (
@@ -83,7 +83,7 @@ async def get_node(
):
node = await asyncio.to_thread(session.get_node, node_id)
if node is None:
- raise KeyError(node_id)
+ raise HTTPException(status_code=404, detail=f"Node '{node_id}' not found")
return _node_response(node)
@@ -150,7 +150,7 @@ async def find_path(
):
path_finder = session.path_finder
if path_finder is None:
- raise ValueError("PathFinder not available; KG extras may not be installed.")
+ raise HTTPException(status_code=503, detail="PathFinder not available; KG extras may not be installed.")
graph_dict = await asyncio.to_thread(session.build_graph_dict)
path_fn = (
@@ -158,7 +158,10 @@ async def find_path(
if algorithm == _PathAlgorithm.dijkstra
else path_finder.bfs_shortest_path
)
- result = await asyncio.to_thread(path_fn, graph_dict, node_id, target)
+ try:
+ result = await asyncio.to_thread(path_fn, graph_dict, node_id, target)
+ except Exception as exc:
+ raise HTTPException(status_code=404, detail=f"No path found from '{node_id}' to '{target}': {exc}")
path_nodes = result.get("path", []) if isinstance(result, dict) else (result or [])
total_weight = result.get("total_weight", 0.0) if isinstance(result, dict) else 0.0
diff --git a/semantica/explorer/routes/temporal.py b/semantica/explorer/routes/temporal.py
index 04167ba3..4da29d8c 100644
--- a/semantica/explorer/routes/temporal.py
+++ b/semantica/explorer/routes/temporal.py
@@ -103,7 +103,7 @@ async def temporal_patterns(
detector = TemporalPatternDetector()
graph_dict = await asyncio.to_thread(session.build_graph_dict)
- patterns = await asyncio.to_thread(detector.detect_patterns, graph_dict)
+ patterns = await asyncio.to_thread(detector.detect_temporal_patterns, graph_dict)
if isinstance(patterns, dict):
patterns = patterns.get("patterns", [])
return TemporalPatternResponse(patterns=patterns if isinstance(patterns, list) else [])
diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.py
index f0d56859..3213db23 100644
--- a/tests/explorer/test_explorer_api.py
+++ b/tests/explorer/test_explorer_api.py
@@ -372,7 +372,7 @@ class TestEnrichment:
def test_extract(self, client):
response = client.post("/api/enrich/extract", json={"text": "Alice works at Acme Corp."})
- assert response.status_code in (200, 422)
+ assert response.status_code in (200, 422, 503)
def test_link_prediction(self, client):
response = client.post("/api/enrich/links", json={"node_id": "python", "top_n": 5})