memorymind / memory.py
killbizz's picture
fix: replace sentence-transformers with fastembed to reduce image size from 8.7GB to ~1GB
4428b01
Raw History Blame Contribute Delete
4.62 kB
import os
import re
import uuid
from datetime import datetime, timezone
from dotenv import load_dotenv
from fastembed import TextEmbedding
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, PointStruct, VectorParams
load_dotenv()
_model = TextEmbedding("BAAI/bge-small-en-v1.5")
_EMBEDDING_DIM = 384
_client = QdrantClient(
url=os.getenv("QDRANT_CLUSTER_ENDPOINT"),
api_key=os.getenv("QDRANT_API_KEY"),
)
def _col(user_id: str) -> str:
return "user_" + re.sub(r"[^a-z0-9]", "_", user_id.lower())
def _ensure_collection(name: str) -> None:
existing = {c.name for c in _client.get_collections().collections}
if name not in existing:
_client.create_collection(
collection_name=name,
vectors_config=VectorParams(size=_EMBEDDING_DIM, distance=Distance.COSINE),
)
def get_embedding(text: str) -> list[float]:
return list(list(_model.embed([text]))[0])
def add_memory(fact: str, metadata: dict, user_id: str = "guest") -> str:
col = _col(user_id)
_ensure_collection(col)
memory_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
payload = {
"fact": fact,
"timestamp": now,
"last_used": now,
"usage_count": 0,
"confidence": 1,
"type": metadata.get("type", "general"),
}
_client.upsert(
collection_name=col,
points=[PointStruct(id=memory_id, vector=get_embedding(fact), payload=payload)],
)
return memory_id
def retrieve_relevant(query: str, user_id: str = "guest", top_k: int = 5) -> list[dict]:
col = _col(user_id)
_ensure_collection(col)
count = _client.get_collection(col).points_count
if count == 0:
return []
response = _client.query_points(
collection_name=col,
query=get_embedding(query),
limit=min(top_k, count),
with_payload=True,
)
memories = []
now = datetime.now(timezone.utc).isoformat()
for hit in response.points:
memories.append({"id": hit.id, "fact": hit.payload["fact"], "metadata": hit.payload})
_client.set_payload(
collection_name=col,
payload={
"usage_count": hit.payload.get("usage_count", 0) + 1,
"last_used": now,
},
points=[hit.id],
)
return memories
def get_all_memories(user_id: str = "guest") -> list[dict]:
col = _col(user_id)
_ensure_collection(col)
points, _ = _client.scroll(collection_name=col, limit=500, with_payload=True)
memories = [
{"id": str(p.id), "fact": p.payload["fact"], "metadata": p.payload}
for p in points
]
return sorted(memories, key=lambda m: m["metadata"].get("timestamp", ""), reverse=True)
def is_duplicate(new_fact: str, user_id: str = "guest", threshold: float = 0.92) -> bool:
col = _col(user_id)
_ensure_collection(col)
if _client.get_collection(col).points_count == 0:
return False
response = _client.query_points(collection_name=col, query=get_embedding(new_fact), limit=1)
return bool(response.points) and response.points[0].score >= threshold
def get_contradiction_candidate(new_fact: str, user_id: str = "guest") -> dict | None:
col = _col(user_id)
_ensure_collection(col)
if _client.get_collection(col).points_count == 0:
return None
response = _client.query_points(
collection_name=col,
query=get_embedding(new_fact),
limit=1,
with_payload=True,
)
if not response.points:
return None
hit = response.points[0]
if 0.75 <= hit.score < 0.92:
return {"id": str(hit.id), "fact": hit.payload["fact"], "similarity": hit.score}
return None
def correct_memory(old_memory_id: str, new_fact: str, user_id: str = "guest") -> None:
col = _col(user_id)
existing = _client.retrieve(collection_name=col, ids=[old_memory_id], with_payload=True)
old_payload = existing[0].payload if existing else {}
_client.upsert(
collection_name=col,
points=[
PointStruct(
id=old_memory_id,
vector=get_embedding(new_fact),
payload={
**old_payload,
"fact": new_fact,
"timestamp": datetime.now(timezone.utc).isoformat(),
"corrected": True,
},
)
],
)
def delete_all_memories(user_id: str = "guest") -> None:
try:
_client.delete_collection(_col(user_id))
except Exception:
pass