Spaces:
Configuration error
Configuration error
Download src/core/memory.py from Darshankumarr03/JanSahayak: direct link, hf CLI and curl.
- Browser
- Download file 2.85 kB
-
https://huggingface.co/spaces/Darshankumarr03/JanSahayak/resolve/main/src/core/memory.py
- Command line
-
hf download hf://spaces/Darshankumarr03/JanSahayak/src/core/memory.py
-
curl -L -o memory.py https://huggingface.co/spaces/Darshankumarr03/JanSahayak/resolve/main/src/core/memory.py
2.85 kB
| import os | |
| from mem0 import Memory | |
| from src.utils.logger import setup_logger | |
| logger = setup_logger("Memory") | |
| class Mem0Service: | |
| """ | |
| Service for long-term user memory powered by mem0 and Supabase. | |
| """ | |
| def __init__(self): | |
| # Supabase PostgreSQL connection string from environment | |
| # Format: postgresql://postgres.xxxx:[Password]@aws-0-us-east-1.pooler.supabase.com:6543/postgres | |
| connection_string = os.getenv("SUPABASE_POSTGRES_URL") | |
| if not connection_string: | |
| logger.warning("SUPABASE_POSTGRES_URL not found. Using simple local memory fallback.") | |
| # For local fallback without OpenAI, we can specify a simple config | |
| # or just a mock if we want to avoid dependency on OpenAI. | |
| self.memory = None | |
| else: | |
| config = { | |
| "vector_store": { | |
| "provider": "supabase", | |
| "config": { | |
| "connection_string": connection_string, | |
| "collection_name": "memories", | |
| } | |
| }, | |
| "llm": { | |
| "provider": "ollama", | |
| "config": { | |
| "model": "smollm2:1.7b", | |
| } | |
| } | |
| } | |
| try: | |
| self.memory = Memory.from_config(config) | |
| logger.info("Mem0 successfully initialized with Supabase backend.") | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Mem0 with Supabase: {e}. Memory disabled.") | |
| self.memory = None | |
| def add_memory(self, user_id: str, text: str, metadata: dict = None): | |
| """Adds a fact to the user's long-term memory.""" | |
| try: | |
| self.memory.add(text, user_id=user_id, metadata=metadata or {}) | |
| logger.info(f"Memory added for user {user_id}") | |
| except Exception as e: | |
| logger.error(f"Error adding memory: {e}") | |
| def search_memory(self, user_id: str, query: str): | |
| """Searches for relevant facts in the user's history.""" | |
| try: | |
| results = self.memory.search(query, user_id=user_id, limit=5) | |
| logger.info(f"Retrieved {len(results)} long-term memories for user {user_id}") | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error searching memory: {e}") | |
| return [] | |
| def get_context_string(self, user_id: str, query: str) -> str: | |
| """Helper to get a combined string of relevant memories.""" | |
| memories = self.search_memory(user_id, query) | |
| if not memories: | |
| return "" | |
| formatted_memories = [f"- {m['memory']}" for m in memories] | |
| return "\n".join(formatted_memories) | |
| # Singleton instance | |
| memory_service = Mem0Service() | |