|
| 1 | +"""Reusable FastAPI component for the Lance knowledge graph service.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any, Dict, List, Optional |
| 6 | + |
| 7 | +import pyarrow as pa |
| 8 | +import yaml |
| 9 | +from fastapi import APIRouter, HTTPException |
| 10 | +from pydantic import BaseModel |
| 11 | + |
| 12 | +from .config import KnowledgeGraphConfig |
| 13 | +from .service import LanceKnowledgeGraph |
| 14 | +from .store import LanceGraphStore |
| 15 | + |
| 16 | + |
| 17 | +class QueryRequest(BaseModel): |
| 18 | + query: str |
| 19 | + |
| 20 | + |
| 21 | +class QueryResponse(BaseModel): |
| 22 | + rows: List[Dict[str, Any]] |
| 23 | + row_count: int |
| 24 | + |
| 25 | + |
| 26 | +class DatasetUpsertRequest(BaseModel): |
| 27 | + records: List[Dict[str, Any]] |
| 28 | + merge: bool = True |
| 29 | + |
| 30 | + |
| 31 | +class KnowledgeGraphComponent: |
| 32 | + """Bundle FastAPI routes that expose the Lance knowledge graph.""" |
| 33 | + |
| 34 | + def __init__(self, config: Optional[KnowledgeGraphConfig] = None): |
| 35 | + self._config = config or KnowledgeGraphConfig.default() |
| 36 | + self._service: Optional[LanceKnowledgeGraph] = None |
| 37 | + self.router = APIRouter(tags=["knowledge-graph"]) |
| 38 | + self._setup_routes() |
| 39 | + |
| 40 | + def _get_service(self) -> LanceKnowledgeGraph: |
| 41 | + if self._service is None: |
| 42 | + try: |
| 43 | + self._service = _create_service(self._config) |
| 44 | + except FileNotFoundError as exc: |
| 45 | + raise HTTPException(status_code=500, detail=str(exc)) from exc |
| 46 | + return self._service |
| 47 | + |
| 48 | + def _setup_routes(self) -> None: |
| 49 | + @self.router.get("/health") |
| 50 | + async def health() -> Dict[str, str]: |
| 51 | + return {"status": "healthy", "service": "lance-knowledge-graph"} |
| 52 | + |
| 53 | + @self.router.get("/datasets") |
| 54 | + async def list_datasets() -> Dict[str, List[str]]: |
| 55 | + service = self._get_service() |
| 56 | + names = list(service.dataset_names()) |
| 57 | + return {"datasets": names} |
| 58 | + |
| 59 | + @self.router.get("/datasets/{name}") |
| 60 | + async def get_dataset(name: str, limit: int = 100) -> Dict[str, Any]: |
| 61 | + service = self._get_service() |
| 62 | + if not service.has_dataset(name): |
| 63 | + raise HTTPException( |
| 64 | + status_code=404, detail=f"Dataset '{name}' not found" |
| 65 | + ) |
| 66 | + |
| 67 | + table = service.load_table(name) |
| 68 | + rows = table.to_pylist() |
| 69 | + if limit is not None: |
| 70 | + rows = rows[:limit] |
| 71 | + return {"name": name, "row_count": len(rows), "rows": rows} |
| 72 | + |
| 73 | + @self.router.post("/datasets/{name}") |
| 74 | + async def upsert_dataset( |
| 75 | + name: str, request: DatasetUpsertRequest |
| 76 | + ) -> Dict[str, Any]: |
| 77 | + if not request.records: |
| 78 | + raise HTTPException(status_code=400, detail="records cannot be empty") |
| 79 | + |
| 80 | + table = pa.Table.from_pylist(request.records) |
| 81 | + service = self._get_service() |
| 82 | + service.upsert_table(name, table, merge=request.merge) |
| 83 | + return {"status": "ok", "dataset": name, "row_count": table.num_rows} |
| 84 | + |
| 85 | + @self.router.post("/query", response_model=QueryResponse) |
| 86 | + async def execute_query(request: QueryRequest) -> QueryResponse: |
| 87 | + service = self._get_service() |
| 88 | + result = service.query(request.query) |
| 89 | + rows = result.to_pylist() |
| 90 | + return QueryResponse(rows=rows, row_count=len(rows)) |
| 91 | + |
| 92 | + @self.router.get("/schema") |
| 93 | + async def get_schema() -> Dict[str, Any]: |
| 94 | + schema_path = self._config.resolved_schema_path() |
| 95 | + if not schema_path.exists(): |
| 96 | + raise HTTPException(status_code=404, detail="Schema file not found") |
| 97 | + with schema_path.open("r", encoding="utf-8") as handle: |
| 98 | + payload = yaml.safe_load(handle) or {} |
| 99 | + return {"path": str(schema_path), "schema": payload} |
| 100 | + |
| 101 | + def close(self) -> None: |
| 102 | + """Release retained resources.""" |
| 103 | + self._service = None |
| 104 | + |
| 105 | + |
| 106 | +def _create_service(config: KnowledgeGraphConfig) -> LanceKnowledgeGraph: |
| 107 | + graph_config = config.load_graph_config() |
| 108 | + storage = LanceGraphStore(config) |
| 109 | + service = LanceKnowledgeGraph(graph_config, storage=storage) |
| 110 | + service.ensure_initialized() |
| 111 | + return service |
0 commit comments