Spaces:
Sleeping
Sleeping
feat: multi-user memory namespacing and FastAPI backend
Browse files- api.py +40 -0
- app.py +13 -6
- chatbot.py +13 -10
- memory.py +34 -30
- requirements.txt +2 -0
api.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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):
|
| 11 |
+
user_id: str
|
| 12 |
+
message: str
|
| 13 |
+
chat_history: list[dict] = []
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ChatResponse(BaseModel):
|
| 17 |
+
reply: str
|
| 18 |
+
used_memory_ids: list[str]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 22 |
+
def chat_endpoint(req: ChatRequest):
|
| 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 |
+
def get_memories(user_id: str):
|
| 29 |
+
return get_all_memories(user_id=user_id)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@app.delete("/memories/{user_id}")
|
| 33 |
+
def reset_memories(user_id: str):
|
| 34 |
+
delete_all_memories(user_id=user_id)
|
| 35 |
+
return {"status": "ok", "user_id": user_id}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@app.get("/health")
|
| 39 |
+
def health():
|
| 40 |
+
return {"status": "ok"}
|
app.py
CHANGED
|
@@ -33,9 +33,16 @@ def _relative_time(iso_str: str) -> str:
|
|
| 33 |
|
| 34 |
# --- sidebar ---
|
| 35 |
with st.sidebar:
|
| 36 |
-
st.title("🧠
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
st.divider()
|
| 40 |
|
| 41 |
if not memories:
|
|
@@ -67,11 +74,11 @@ with st.sidebar:
|
|
| 67 |
st.divider()
|
| 68 |
|
| 69 |
if st.session_state.confirm_reset:
|
| 70 |
-
st.warning("
|
| 71 |
col1, col2 = st.columns(2)
|
| 72 |
with col1:
|
| 73 |
if st.button("Yes, reset", type="primary", use_container_width=True):
|
| 74 |
-
delete_all_memories()
|
| 75 |
st.session_state.chat_history = []
|
| 76 |
st.session_state.last_used_ids = []
|
| 77 |
st.session_state.confirm_reset = False
|
|
@@ -100,7 +107,7 @@ if prompt := st.chat_input("Say something..."):
|
|
| 100 |
|
| 101 |
with st.chat_message("assistant"):
|
| 102 |
with st.spinner("Thinking..."):
|
| 103 |
-
reply, used_ids = chat(prompt, st.session_state.chat_history)
|
| 104 |
st.write(reply)
|
| 105 |
if used_ids:
|
| 106 |
st.caption(f"💡 {len(used_ids)} memor{'ies' if len(used_ids) != 1 else 'y'} used")
|
|
|
|
| 33 |
|
| 34 |
# --- sidebar ---
|
| 35 |
with st.sidebar:
|
| 36 |
+
st.title("🧠 MemoryMind")
|
| 37 |
+
st.divider()
|
| 38 |
+
|
| 39 |
+
username = st.text_input("Who are you?", placeholder="Enter your name...", key="username_input")
|
| 40 |
+
user_id = username.strip().lower().replace(" ", "_") or "guest"
|
| 41 |
+
|
| 42 |
+
st.divider()
|
| 43 |
+
|
| 44 |
+
memories = get_all_memories(user_id=user_id)
|
| 45 |
+
st.caption(f"{len(memories)} fact{'s' if len(memories) != 1 else ''} stored for **{username or 'guest'}**")
|
| 46 |
st.divider()
|
| 47 |
|
| 48 |
if not memories:
|
|
|
|
| 74 |
st.divider()
|
| 75 |
|
| 76 |
if st.session_state.confirm_reset:
|
| 77 |
+
st.warning(f"Wipe all memories for **{username or 'guest'}**?")
|
| 78 |
col1, col2 = st.columns(2)
|
| 79 |
with col1:
|
| 80 |
if st.button("Yes, reset", type="primary", use_container_width=True):
|
| 81 |
+
delete_all_memories(user_id=user_id)
|
| 82 |
st.session_state.chat_history = []
|
| 83 |
st.session_state.last_used_ids = []
|
| 84 |
st.session_state.confirm_reset = False
|
|
|
|
| 107 |
|
| 108 |
with st.chat_message("assistant"):
|
| 109 |
with st.spinner("Thinking..."):
|
| 110 |
+
reply, used_ids = chat(prompt, st.session_state.chat_history, user_id=user_id)
|
| 111 |
st.write(reply)
|
| 112 |
if used_ids:
|
| 113 |
st.caption(f"💡 {len(used_ids)} memor{'ies' if len(used_ids) != 1 else 'y'} used")
|
chatbot.py
CHANGED
|
@@ -80,40 +80,43 @@ def _is_contradiction(fact_a: str, fact_b: str) -> bool:
|
|
| 80 |
return False
|
| 81 |
|
| 82 |
|
| 83 |
-
def _process_new_facts(user_message: str, bot_reply: str) -> None:
|
| 84 |
facts = extract_facts(user_message, bot_reply)
|
| 85 |
for fact_data in facts:
|
| 86 |
fact = fact_data["fact"]
|
| 87 |
-
if is_duplicate(fact):
|
| 88 |
continue
|
| 89 |
-
candidate = get_contradiction_candidate(fact)
|
| 90 |
if candidate and _is_contradiction(candidate["fact"], fact):
|
| 91 |
-
correct_memory(candidate["id"], fact)
|
| 92 |
else:
|
| 93 |
-
add_memory(fact, {"type": fact_data.get("type", "general")})
|
| 94 |
|
| 95 |
|
| 96 |
-
def chat(
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
used_ids = [m["id"] for m in memories]
|
| 99 |
|
| 100 |
system_prompt = build_system_prompt(memories)
|
| 101 |
messages = build_messages(system_prompt, chat_history, user_message)
|
| 102 |
|
| 103 |
bot_reply = call_llm(messages)
|
| 104 |
-
_process_new_facts(user_message, bot_reply)
|
| 105 |
|
| 106 |
return bot_reply, used_ids
|
| 107 |
|
| 108 |
|
| 109 |
if __name__ == "__main__":
|
| 110 |
-
|
|
|
|
| 111 |
history = []
|
| 112 |
while True:
|
| 113 |
user_input = input("You: ").strip()
|
| 114 |
if user_input.lower() == "quit":
|
| 115 |
break
|
| 116 |
-
reply, used = chat(user_input, history)
|
| 117 |
history.append({"role": "user", "content": user_input})
|
| 118 |
history.append({"role": "assistant", "content": reply})
|
| 119 |
print(f"Bot: {reply}")
|
|
|
|
| 80 |
return False
|
| 81 |
|
| 82 |
|
| 83 |
+
def _process_new_facts(user_message: str, bot_reply: str, user_id: str) -> None:
|
| 84 |
facts = extract_facts(user_message, bot_reply)
|
| 85 |
for fact_data in facts:
|
| 86 |
fact = fact_data["fact"]
|
| 87 |
+
if is_duplicate(fact, user_id=user_id):
|
| 88 |
continue
|
| 89 |
+
candidate = get_contradiction_candidate(fact, user_id=user_id)
|
| 90 |
if candidate and _is_contradiction(candidate["fact"], fact):
|
| 91 |
+
correct_memory(candidate["id"], fact, user_id=user_id)
|
| 92 |
else:
|
| 93 |
+
add_memory(fact, {"type": fact_data.get("type", "general")}, user_id=user_id)
|
| 94 |
|
| 95 |
|
| 96 |
+
def chat(
|
| 97 |
+
user_message: str, chat_history: list[dict], user_id: str = "guest"
|
| 98 |
+
) -> tuple[str, list[str]]:
|
| 99 |
+
memories = retrieve_relevant(user_message, user_id=user_id)
|
| 100 |
used_ids = [m["id"] for m in memories]
|
| 101 |
|
| 102 |
system_prompt = build_system_prompt(memories)
|
| 103 |
messages = build_messages(system_prompt, chat_history, user_message)
|
| 104 |
|
| 105 |
bot_reply = call_llm(messages)
|
| 106 |
+
_process_new_facts(user_message, bot_reply, user_id=user_id)
|
| 107 |
|
| 108 |
return bot_reply, used_ids
|
| 109 |
|
| 110 |
|
| 111 |
if __name__ == "__main__":
|
| 112 |
+
uid = input("Your username: ").strip() or "guest"
|
| 113 |
+
print(f"Chatting as '{uid}' — type 'quit' to exit\n")
|
| 114 |
history = []
|
| 115 |
while True:
|
| 116 |
user_input = input("You: ").strip()
|
| 117 |
if user_input.lower() == "quit":
|
| 118 |
break
|
| 119 |
+
reply, used = chat(user_input, history, user_id=uid)
|
| 120 |
history.append({"role": "user", "content": user_input})
|
| 121 |
history.append({"role": "assistant", "content": reply})
|
| 122 |
print(f"Bot: {reply}")
|
memory.py
CHANGED
|
@@ -6,17 +6,23 @@ from sentence_transformers import SentenceTransformer
|
|
| 6 |
|
| 7 |
_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 8 |
_client = chromadb.PersistentClient(path="./chroma_store")
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def get_embedding(text: str) -> list[float]:
|
| 16 |
return _model.encode(text).tolist()
|
| 17 |
|
| 18 |
|
| 19 |
-
def add_memory(fact: str, metadata: dict) -> str:
|
| 20 |
memory_id = str(uuid.uuid4())
|
| 21 |
embedding = get_embedding(fact)
|
| 22 |
meta = {
|
|
@@ -25,7 +31,7 @@ def add_memory(fact: str, metadata: dict) -> str:
|
|
| 25 |
"type": metadata.get("type", "general"),
|
| 26 |
**metadata,
|
| 27 |
}
|
| 28 |
-
|
| 29 |
ids=[memory_id],
|
| 30 |
embeddings=[embedding],
|
| 31 |
documents=[fact],
|
|
@@ -34,25 +40,26 @@ def add_memory(fact: str, metadata: dict) -> str:
|
|
| 34 |
return memory_id
|
| 35 |
|
| 36 |
|
| 37 |
-
def retrieve_relevant(query: str, top_k: int = 5) -> list[dict]:
|
| 38 |
-
|
|
|
|
| 39 |
if count == 0:
|
| 40 |
return []
|
| 41 |
n = min(top_k, count)
|
| 42 |
embedding = get_embedding(query)
|
| 43 |
-
results =
|
| 44 |
memories = []
|
| 45 |
for memory_id, fact, meta in zip(
|
| 46 |
results["ids"][0], results["documents"][0], results["metadatas"][0]
|
| 47 |
):
|
| 48 |
memories.append({"id": memory_id, "fact": fact, "metadata": meta})
|
| 49 |
updated_meta = {**meta, "usage_count": meta.get("usage_count", 0) + 1}
|
| 50 |
-
|
| 51 |
return memories
|
| 52 |
|
| 53 |
|
| 54 |
-
def get_all_memories() -> list[dict]:
|
| 55 |
-
results =
|
| 56 |
memories = [
|
| 57 |
{"id": mid, "fact": doc, "metadata": meta}
|
| 58 |
for mid, doc, meta in zip(
|
|
@@ -64,24 +71,24 @@ def get_all_memories() -> list[dict]:
|
|
| 64 |
)
|
| 65 |
|
| 66 |
|
| 67 |
-
def is_duplicate(new_fact: str, threshold: float = 0.92) -> bool:
|
| 68 |
-
|
|
|
|
| 69 |
return False
|
| 70 |
embedding = get_embedding(new_fact)
|
| 71 |
-
results =
|
| 72 |
if not results["distances"][0]:
|
| 73 |
return False
|
| 74 |
similarity = 1 - results["distances"][0][0]
|
| 75 |
return similarity >= threshold
|
| 76 |
|
| 77 |
|
| 78 |
-
def get_contradiction_candidate(new_fact: str) -> dict | None:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
if _collection.count() == 0:
|
| 82 |
return None
|
| 83 |
embedding = get_embedding(new_fact)
|
| 84 |
-
results =
|
| 85 |
if not results["distances"][0]:
|
| 86 |
return None
|
| 87 |
distance = results["distances"][0][0]
|
|
@@ -95,16 +102,17 @@ def get_contradiction_candidate(new_fact: str) -> dict | None:
|
|
| 95 |
return None
|
| 96 |
|
| 97 |
|
| 98 |
-
def correct_memory(old_memory_id: str, new_fact: str) -> None:
|
|
|
|
| 99 |
embedding = get_embedding(new_fact)
|
| 100 |
-
existing =
|
| 101 |
old_meta = existing["metadatas"][0] if existing["metadatas"] else {}
|
| 102 |
updated_meta = {
|
| 103 |
**old_meta,
|
| 104 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 105 |
"corrected": True,
|
| 106 |
}
|
| 107 |
-
|
| 108 |
ids=[old_memory_id],
|
| 109 |
embeddings=[embedding],
|
| 110 |
documents=[new_fact],
|
|
@@ -112,10 +120,6 @@ def correct_memory(old_memory_id: str, new_fact: str) -> None:
|
|
| 112 |
)
|
| 113 |
|
| 114 |
|
| 115 |
-
def delete_all_memories() -> None:
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
_collection = _client.get_or_create_collection(
|
| 119 |
-
name="user_memories",
|
| 120 |
-
metadata={"hnsw:space": "cosine"},
|
| 121 |
-
)
|
|
|
|
| 6 |
|
| 7 |
_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 8 |
_client = chromadb.PersistentClient(path="./chroma_store")
|
| 9 |
+
_collections: dict[str, chromadb.Collection] = {}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _get_collection(user_id: str) -> chromadb.Collection:
|
| 13 |
+
if user_id not in _collections:
|
| 14 |
+
_collections[user_id] = _client.get_or_create_collection(
|
| 15 |
+
name=f"user_{user_id}",
|
| 16 |
+
metadata={"hnsw:space": "cosine"},
|
| 17 |
+
)
|
| 18 |
+
return _collections[user_id]
|
| 19 |
|
| 20 |
|
| 21 |
def get_embedding(text: str) -> list[float]:
|
| 22 |
return _model.encode(text).tolist()
|
| 23 |
|
| 24 |
|
| 25 |
+
def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
|
| 26 |
memory_id = str(uuid.uuid4())
|
| 27 |
embedding = get_embedding(fact)
|
| 28 |
meta = {
|
|
|
|
| 31 |
"type": metadata.get("type", "general"),
|
| 32 |
**metadata,
|
| 33 |
}
|
| 34 |
+
_get_collection(user_id).add(
|
| 35 |
ids=[memory_id],
|
| 36 |
embeddings=[embedding],
|
| 37 |
documents=[fact],
|
|
|
|
| 40 |
return memory_id
|
| 41 |
|
| 42 |
|
| 43 |
+
def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> list[dict]:
|
| 44 |
+
col = _get_collection(user_id)
|
| 45 |
+
count = col.count()
|
| 46 |
if count == 0:
|
| 47 |
return []
|
| 48 |
n = min(top_k, count)
|
| 49 |
embedding = get_embedding(query)
|
| 50 |
+
results = col.query(query_embeddings=[embedding], n_results=n)
|
| 51 |
memories = []
|
| 52 |
for memory_id, fact, meta in zip(
|
| 53 |
results["ids"][0], results["documents"][0], results["metadatas"][0]
|
| 54 |
):
|
| 55 |
memories.append({"id": memory_id, "fact": fact, "metadata": meta})
|
| 56 |
updated_meta = {**meta, "usage_count": meta.get("usage_count", 0) + 1}
|
| 57 |
+
col.update(ids=[memory_id], metadatas=[updated_meta])
|
| 58 |
return memories
|
| 59 |
|
| 60 |
|
| 61 |
+
def get_all_memories(user_id: str = "guest") -> list[dict]:
|
| 62 |
+
results = _get_collection(user_id).get()
|
| 63 |
memories = [
|
| 64 |
{"id": mid, "fact": doc, "metadata": meta}
|
| 65 |
for mid, doc, meta in zip(
|
|
|
|
| 71 |
)
|
| 72 |
|
| 73 |
|
| 74 |
+
def is_duplicate(new_fact: str, user_id: str = "guest", threshold: float = 0.92) -> bool:
|
| 75 |
+
col = _get_collection(user_id)
|
| 76 |
+
if col.count() == 0:
|
| 77 |
return False
|
| 78 |
embedding = get_embedding(new_fact)
|
| 79 |
+
results = col.query(query_embeddings=[embedding], n_results=1)
|
| 80 |
if not results["distances"][0]:
|
| 81 |
return False
|
| 82 |
similarity = 1 - results["distances"][0][0]
|
| 83 |
return similarity >= threshold
|
| 84 |
|
| 85 |
|
| 86 |
+
def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
|
| 87 |
+
col = _get_collection(user_id)
|
| 88 |
+
if col.count() == 0:
|
|
|
|
| 89 |
return None
|
| 90 |
embedding = get_embedding(new_fact)
|
| 91 |
+
results = col.query(query_embeddings=[embedding], n_results=1)
|
| 92 |
if not results["distances"][0]:
|
| 93 |
return None
|
| 94 |
distance = results["distances"][0][0]
|
|
|
|
| 102 |
return None
|
| 103 |
|
| 104 |
|
| 105 |
+
def correct_memory(old_memory_id: str, new_fact: str, user_id: str = "guest") -> None:
|
| 106 |
+
col = _get_collection(user_id)
|
| 107 |
embedding = get_embedding(new_fact)
|
| 108 |
+
existing = col.get(ids=[old_memory_id])
|
| 109 |
old_meta = existing["metadatas"][0] if existing["metadatas"] else {}
|
| 110 |
updated_meta = {
|
| 111 |
**old_meta,
|
| 112 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 113 |
"corrected": True,
|
| 114 |
}
|
| 115 |
+
col.update(
|
| 116 |
ids=[old_memory_id],
|
| 117 |
embeddings=[embedding],
|
| 118 |
documents=[new_fact],
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
|
| 123 |
+
def delete_all_memories(user_id: str = "guest") -> None:
|
| 124 |
+
_client.delete_collection(f"user_{user_id}")
|
| 125 |
+
_collections.pop(user_id, None)
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -3,3 +3,5 @@ groq>=0.4.0
|
|
| 3 |
chromadb>=0.5.0
|
| 4 |
sentence-transformers>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
|
|
|
|
|
|
|
|
| 3 |
chromadb>=0.5.0
|
| 4 |
sentence-transformers>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
+
fastapi>=0.110.0
|
| 7 |
+
uvicorn>=0.29.0
|