"""Per-user memory in Supabase Storage.""" import json import re import httpx from fastapi import APIRouter, Depends, HTTPException import groq_router from auth import SERVICE_KEY, SUPABASE_URL, get_user_sync router = APIRouter() BUCKET = "surf-memory" MAX_BYTES = 100_000 HEAD = {"Authorization": f"Bearer {SERVICE_KEY}", "apikey": SERVICE_KEY} def _url(uid: str) -> str: return f"{SUPABASE_URL}/storage/v1/object/{BUCKET}/{uid}/memory.json" async def load_memory(uid: str) -> dict: async with httpx.AsyncClient(timeout=15) as c: r = await c.get(_url(uid), headers=HEAD) if r.status_code != 200: return {} try: return r.json() except ValueError: return {} @router.get("/memory") async def get_memory(user: dict = Depends(get_user_sync)): return {"facts": await load_memory(user["id"])} @router.put("/memory") async def put_memory(body: dict, user: dict = Depends(get_user_sync)): facts = body.get("facts") if not isinstance(facts, dict): raise HTTPException(400, "facts must be an object") blob = json.dumps(facts).encode() if len(blob) > MAX_BYTES: raise HTTPException(413, "Memory too large") async with httpx.AsyncClient(timeout=15) as c: r = await c.post(_url(user["id"]), content=blob, headers={**HEAD, "Content-Type": "application/json", "x-upsert": "true"}) if r.status_code not in (200, 201): raise HTTPException(502, "Storage error") return {"ok": True} @router.delete("/memory") async def clear_memory(user: dict = Depends(get_user_sync)): async with httpx.AsyncClient(timeout=15) as c: await c.delete(_url(user["id"]), headers=HEAD) return {"ok": True} async def save_memory(uid: str, facts: dict) -> bool: blob = json.dumps(facts).encode() if len(blob) > MAX_BYTES: return False async with httpx.AsyncClient(timeout=15) as c: r = await c.post(_url(uid), content=blob, headers={**HEAD, "Content-Type": "application/json", "x-upsert": "true"}) return r.status_code in (200, 201) TRIGGER = re.compile( r"\b(my name is|call me|i am|i'm|i live|i work|i study|i like|i love|i hate|i prefer|" r"remember|my \w+ (is|are)|i have)\b", re.I) # FIX: Stricter extraction prompt EXTRACT = ( "Extract durable personal facts the user explicitly states about themselves. " "Pay close attention to names (e.g., 'My name is Kevin') and preferences (e.g., 'I love Rolex'). " "Do not guess. Do not summarize. Reply with JSON only: " '{"facts": {"name": "Kevin", "favorite_food": "Rolex"}}. ' 'Use {"facts": {}} if there is nothing explicitly stated.' ) async def remember_from_turn(uid: str, user_text: str, is_private: bool = False) -> None: """Background task: cheap regex gate, then one small model call to pull out new facts.""" if is_private: return if not user_text or not TRIGGER.search(user_text): return try: data = await groq_router.chat( [{"role": "system", "content": EXTRACT}, {"role": "user", "content": user_text[:1000]}], temperature=0, max_tokens=300, response_format={"type": "json_object"}, **groq_router.reasoning_kw(None)) new = json.loads(data["choices"][0]["message"]["content"]).get("facts", {}) if isinstance(new, dict) and new: facts = await load_memory(uid) facts.update({str(k)[:40]: str(v)[:200] for k, v in new.items()}) await save_memory(uid, facts) except Exception: pass