|
| 1 | +"""PowerMem REST endpoints for search / list / delete.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from fastapi import APIRouter, HTTPException, Query |
| 9 | +from pydantic import BaseModel, Field |
| 10 | + |
| 11 | +from app.memory import get_memory_engine |
| 12 | + |
| 13 | +router = APIRouter(prefix="/memory", tags=["memory"]) |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class MemoryItem(BaseModel): |
| 18 | + id: str | None = None |
| 19 | + content: str = "" |
| 20 | + score: float | None = None |
| 21 | + created_at: str | None = None |
| 22 | + metadata: dict[str, Any] = Field(default_factory=dict) |
| 23 | + |
| 24 | + |
| 25 | +class MemoryListResponse(BaseModel): |
| 26 | + items: list[MemoryItem] |
| 27 | + offset: int = 0 |
| 28 | + limit: int = 20 |
| 29 | + |
| 30 | + |
| 31 | +def _require_engine() -> Any: |
| 32 | + engine = get_memory_engine() |
| 33 | + if engine is None: |
| 34 | + raise HTTPException(status_code=503, detail="Memory engine unavailable") |
| 35 | + return engine |
| 36 | + |
| 37 | + |
| 38 | +def _normalize_item(item: Any) -> MemoryItem: |
| 39 | + if isinstance(item, dict): |
| 40 | + return MemoryItem( |
| 41 | + id=_as_optional_str(item.get("id") or item.get("memory_id")), |
| 42 | + content=str(item.get("content") or item.get("memory") or ""), |
| 43 | + score=_as_optional_float(item.get("score")), |
| 44 | + created_at=_as_optional_str(item.get("created_at")), |
| 45 | + metadata=item.get("metadata") if isinstance(item.get("metadata"), dict) else {}, |
| 46 | + ) |
| 47 | + |
| 48 | + return MemoryItem( |
| 49 | + id=_as_optional_str(getattr(item, "id", None) or getattr(item, "memory_id", None)), |
| 50 | + content=str( |
| 51 | + getattr(item, "content", None) or getattr(item, "memory", None) or "" |
| 52 | + ), |
| 53 | + score=_as_optional_float(getattr(item, "score", None)), |
| 54 | + created_at=_as_optional_str(getattr(item, "created_at", None)), |
| 55 | + metadata=getattr(item, "metadata", None) |
| 56 | + if isinstance(getattr(item, "metadata", None), dict) |
| 57 | + else {}, |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def _as_optional_str(value: Any) -> str | None: |
| 62 | + if value is None: |
| 63 | + return None |
| 64 | + return str(value) |
| 65 | + |
| 66 | + |
| 67 | +def _as_optional_float(value: Any) -> float | None: |
| 68 | + if value is None: |
| 69 | + return None |
| 70 | + try: |
| 71 | + return float(value) |
| 72 | + except (TypeError, ValueError): |
| 73 | + return None |
| 74 | + |
| 75 | + |
| 76 | +def _call_search(engine: Any, query: str, limit: int) -> list[Any]: |
| 77 | + if hasattr(engine, "search"): |
| 78 | + result = engine.search(query, limit=limit) |
| 79 | + elif hasattr(engine, "query"): |
| 80 | + result = engine.query(query, limit=limit) |
| 81 | + else: |
| 82 | + raise HTTPException(status_code=503, detail="Memory engine has no search API") |
| 83 | + return list(result or []) |
| 84 | + |
| 85 | + |
| 86 | +def _call_list(engine: Any, offset: int, limit: int) -> list[Any]: |
| 87 | + if hasattr(engine, "list"): |
| 88 | + result = engine.list(offset=offset, limit=limit) |
| 89 | + elif hasattr(engine, "get_all"): |
| 90 | + result = engine.get_all() |
| 91 | + result = list(result or [])[offset : offset + limit] |
| 92 | + else: |
| 93 | + raise HTTPException(status_code=503, detail="Memory engine has no list API") |
| 94 | + return list(result or []) |
| 95 | + |
| 96 | + |
| 97 | +def _call_delete(engine: Any, memory_id: str) -> None: |
| 98 | + if hasattr(engine, "delete"): |
| 99 | + engine.delete(memory_id) |
| 100 | + return |
| 101 | + if hasattr(engine, "remove"): |
| 102 | + engine.remove(memory_id) |
| 103 | + return |
| 104 | + raise HTTPException(status_code=503, detail="Memory engine has no delete API") |
| 105 | + |
| 106 | + |
| 107 | +@router.get("/search", response_model=MemoryListResponse) |
| 108 | +async def memory_search( |
| 109 | + query: str = Query(..., min_length=1), |
| 110 | + limit: int = Query(5, ge=1, le=100), |
| 111 | +) -> MemoryListResponse: |
| 112 | + engine = _require_engine() |
| 113 | + try: |
| 114 | + items = [_normalize_item(item) for item in _call_search(engine, query, limit)] |
| 115 | + except HTTPException: |
| 116 | + raise |
| 117 | + except Exception as exc: |
| 118 | + logger.exception("memory search failed") |
| 119 | + raise HTTPException(status_code=500, detail=str(exc)) from exc |
| 120 | + return MemoryListResponse(items=items, offset=0, limit=limit) |
| 121 | + |
| 122 | + |
| 123 | +@router.get("/list", response_model=MemoryListResponse) |
| 124 | +async def memory_list( |
| 125 | + offset: int = Query(0, ge=0), |
| 126 | + limit: int = Query(20, ge=1, le=100), |
| 127 | +) -> MemoryListResponse: |
| 128 | + engine = _require_engine() |
| 129 | + try: |
| 130 | + items = [_normalize_item(item) for item in _call_list(engine, offset, limit)] |
| 131 | + except HTTPException: |
| 132 | + raise |
| 133 | + except Exception as exc: |
| 134 | + logger.exception("memory list failed") |
| 135 | + raise HTTPException(status_code=500, detail=str(exc)) from exc |
| 136 | + return MemoryListResponse(items=items, offset=offset, limit=limit) |
| 137 | + |
| 138 | + |
| 139 | +@router.delete("/{memory_id}") |
| 140 | +async def memory_delete(memory_id: str) -> dict[str, str]: |
| 141 | + engine = _require_engine() |
| 142 | + try: |
| 143 | + _call_delete(engine, memory_id) |
| 144 | + except HTTPException: |
| 145 | + raise |
| 146 | + except Exception as exc: |
| 147 | + logger.exception("memory delete failed") |
| 148 | + raise HTTPException(status_code=500, detail=str(exc)) from exc |
| 149 | + return {"status": "deleted", "id": memory_id} |
0 commit comments