Spaces:
Sleeping
Sleeping
feat: rate limiting on API, memory staleness + confidence scoring, Railway config
Browse files- Procfile +1 -0
- api.py +13 -4
- app.py +15 -2
- memory.py +9 -2
- railway.json +11 -0
- requirements.txt +1 -0
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: uvicorn api:app --host 0.0.0.0 --port $PORT
|
api.py
CHANGED
|
@@ -1,10 +1,16 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
from chatbot import chat
|
| 5 |
from memory import delete_all_memories, get_all_memories
|
| 6 |
|
|
|
|
| 7 |
app = FastAPI(title="MemoryMind API", version="1.0.0")
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
class ChatRequest(BaseModel):
|
|
@@ -19,18 +25,21 @@ class ChatResponse(BaseModel):
|
|
| 19 |
|
| 20 |
|
| 21 |
@app.post("/chat", response_model=ChatResponse)
|
| 22 |
-
|
|
|
|
| 23 |
reply, used_ids = chat(req.message, req.chat_history, user_id=req.user_id)
|
| 24 |
return ChatResponse(reply=reply, used_memory_ids=used_ids)
|
| 25 |
|
| 26 |
|
| 27 |
@app.get("/memories/{user_id}")
|
| 28 |
-
|
|
|
|
| 29 |
return get_all_memories(user_id=user_id)
|
| 30 |
|
| 31 |
|
| 32 |
@app.delete("/memories/{user_id}")
|
| 33 |
-
|
|
|
|
| 34 |
delete_all_memories(user_id=user_id)
|
| 35 |
return {"status": "ok", "user_id": user_id}
|
| 36 |
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
from pydantic import BaseModel
|
| 3 |
+
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 4 |
+
from slowapi.errors import RateLimitExceeded
|
| 5 |
+
from slowapi.util import get_remote_address
|
| 6 |
|
| 7 |
from chatbot import chat
|
| 8 |
from memory import delete_all_memories, get_all_memories
|
| 9 |
|
| 10 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 11 |
app = FastAPI(title="MemoryMind API", version="1.0.0")
|
| 12 |
+
app.state.limiter = limiter
|
| 13 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 14 |
|
| 15 |
|
| 16 |
class ChatRequest(BaseModel):
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
@app.post("/chat", response_model=ChatResponse)
|
| 28 |
+
@limiter.limit("20/minute")
|
| 29 |
+
def chat_endpoint(request: Request, req: ChatRequest):
|
| 30 |
reply, used_ids = chat(req.message, req.chat_history, user_id=req.user_id)
|
| 31 |
return ChatResponse(reply=reply, used_memory_ids=used_ids)
|
| 32 |
|
| 33 |
|
| 34 |
@app.get("/memories/{user_id}")
|
| 35 |
+
@limiter.limit("60/minute")
|
| 36 |
+
def get_memories(request: Request, user_id: str):
|
| 37 |
return get_all_memories(user_id=user_id)
|
| 38 |
|
| 39 |
|
| 40 |
@app.delete("/memories/{user_id}")
|
| 41 |
+
@limiter.limit("10/minute")
|
| 42 |
+
def reset_memories(request: Request, user_id: str):
|
| 43 |
delete_all_memories(user_id=user_id)
|
| 44 |
return {"status": "ok", "user_id": user_id}
|
| 45 |
|
app.py
CHANGED
|
@@ -51,21 +51,34 @@ with st.sidebar:
|
|
| 51 |
for m in memories:
|
| 52 |
is_used = m["id"] in st.session_state.last_used_ids
|
| 53 |
meta = m["metadata"]
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
bg_color = "#1a2e1a" if is_used else "#1a1a1a"
|
|
|
|
| 56 |
checkmark = " ✓" if is_used else ""
|
|
|
|
|
|
|
| 57 |
|
| 58 |
st.markdown(
|
| 59 |
f"""
|
| 60 |
<div style="background:{bg_color};border-left:3px solid {border_color};
|
| 61 |
padding:8px 12px;border-radius:4px;margin-bottom:8px;line-height:1.4;">
|
| 62 |
-
<div style="font-size:0.85rem;color:
|
| 63 |
<div style="font-size:0.7rem;color:#888;margin-top:5px;">
|
| 64 |
<span style="background:#2a2a2a;padding:1px 7px;border-radius:10px;color:#aaa;">
|
| 65 |
{meta.get('type', '—')}
|
| 66 |
</span>
|
| 67 |
· {_relative_time(meta.get('timestamp', ''))}
|
| 68 |
· used {meta.get('usage_count', 0)}×
|
|
|
|
| 69 |
</div>
|
| 70 |
</div>""",
|
| 71 |
unsafe_allow_html=True,
|
|
|
|
| 51 |
for m in memories:
|
| 52 |
is_used = m["id"] in st.session_state.last_used_ids
|
| 53 |
meta = m["metadata"]
|
| 54 |
+
|
| 55 |
+
# staleness — gray out if not used in 7+ days
|
| 56 |
+
try:
|
| 57 |
+
last_used_dt = datetime.fromisoformat(meta.get("last_used", meta.get("timestamp", "")))
|
| 58 |
+
days_stale = (datetime.now(timezone.utc) - last_used_dt).days
|
| 59 |
+
is_stale = days_stale >= 7
|
| 60 |
+
except Exception:
|
| 61 |
+
is_stale = False
|
| 62 |
+
|
| 63 |
+
border_color = "#4caf50" if is_used else ("#555" if is_stale else "#444")
|
| 64 |
bg_color = "#1a2e1a" if is_used else "#1a1a1a"
|
| 65 |
+
text_color = "#888" if is_stale else "#e0e0e0"
|
| 66 |
checkmark = " ✓" if is_used else ""
|
| 67 |
+
confidence = meta.get("confidence", 1)
|
| 68 |
+
confidence_stars = "★" * min(confidence, 5)
|
| 69 |
|
| 70 |
st.markdown(
|
| 71 |
f"""
|
| 72 |
<div style="background:{bg_color};border-left:3px solid {border_color};
|
| 73 |
padding:8px 12px;border-radius:4px;margin-bottom:8px;line-height:1.4;">
|
| 74 |
+
<div style="font-size:0.85rem;color:{text_color};">{m['fact']}{checkmark}</div>
|
| 75 |
<div style="font-size:0.7rem;color:#888;margin-top:5px;">
|
| 76 |
<span style="background:#2a2a2a;padding:1px 7px;border-radius:10px;color:#aaa;">
|
| 77 |
{meta.get('type', '—')}
|
| 78 |
</span>
|
| 79 |
· {_relative_time(meta.get('timestamp', ''))}
|
| 80 |
· used {meta.get('usage_count', 0)}×
|
| 81 |
+
· <span style="color:#f4c542;">{confidence_stars}</span>
|
| 82 |
</div>
|
| 83 |
</div>""",
|
| 84 |
unsafe_allow_html=True,
|
memory.py
CHANGED
|
@@ -39,10 +39,13 @@ def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
|
|
| 39 |
col = _col(user_id)
|
| 40 |
_ensure_collection(col)
|
| 41 |
memory_id = str(uuid.uuid4())
|
|
|
|
| 42 |
payload = {
|
| 43 |
"fact": fact,
|
| 44 |
-
"timestamp":
|
|
|
|
| 45 |
"usage_count": 0,
|
|
|
|
| 46 |
"type": metadata.get("type", "general"),
|
| 47 |
}
|
| 48 |
_client.upsert(
|
|
@@ -65,11 +68,15 @@ def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> lis
|
|
| 65 |
with_payload=True,
|
| 66 |
)
|
| 67 |
memories = []
|
|
|
|
| 68 |
for hit in response.points:
|
| 69 |
memories.append({"id": hit.id, "fact": hit.payload["fact"], "metadata": hit.payload})
|
| 70 |
_client.set_payload(
|
| 71 |
collection_name=col,
|
| 72 |
-
payload={
|
|
|
|
|
|
|
|
|
|
| 73 |
points=[hit.id],
|
| 74 |
)
|
| 75 |
return memories
|
|
|
|
| 39 |
col = _col(user_id)
|
| 40 |
_ensure_collection(col)
|
| 41 |
memory_id = str(uuid.uuid4())
|
| 42 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 43 |
payload = {
|
| 44 |
"fact": fact,
|
| 45 |
+
"timestamp": now,
|
| 46 |
+
"last_used": now,
|
| 47 |
"usage_count": 0,
|
| 48 |
+
"confidence": 1,
|
| 49 |
"type": metadata.get("type", "general"),
|
| 50 |
}
|
| 51 |
_client.upsert(
|
|
|
|
| 68 |
with_payload=True,
|
| 69 |
)
|
| 70 |
memories = []
|
| 71 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 72 |
for hit in response.points:
|
| 73 |
memories.append({"id": hit.id, "fact": hit.payload["fact"], "metadata": hit.payload})
|
| 74 |
_client.set_payload(
|
| 75 |
collection_name=col,
|
| 76 |
+
payload={
|
| 77 |
+
"usage_count": hit.payload.get("usage_count", 0) + 1,
|
| 78 |
+
"last_used": now,
|
| 79 |
+
},
|
| 80 |
points=[hit.id],
|
| 81 |
)
|
| 82 |
return memories
|
railway.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://railway.app/railway.schema.json",
|
| 3 |
+
"build": {
|
| 4 |
+
"builder": "NIXPACKS"
|
| 5 |
+
},
|
| 6 |
+
"deploy": {
|
| 7 |
+
"startCommand": "uvicorn api:app --host 0.0.0.0 --port $PORT",
|
| 8 |
+
"restartPolicyType": "ON_FAILURE",
|
| 9 |
+
"restartPolicyMaxRetries": 3
|
| 10 |
+
}
|
| 11 |
+
}
|
requirements.txt
CHANGED
|
@@ -5,3 +5,4 @@ sentence-transformers>=3.0.0
|
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
fastapi>=0.110.0
|
| 7 |
uvicorn>=0.29.0
|
|
|
|
|
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
fastapi>=0.110.0
|
| 7 |
uvicorn>=0.29.0
|
| 8 |
+
slowapi>=0.1.9
|