AI Memory Therapist Project
I'll help you build this mental health chatbot with memory capabilities. Let's break this down into manageable steps and create a working solution that requires no coding experience on your part.
Project Overview
We'll create a Python-based chatbot that:
- Provides therapy-like responses
- Remembers past conversations
- Tracks emotional states
- Offers a simple interface
Let's start with the core structure and then build each component.
Step 1: Setting Up the Project
First, let's create the project structure:
# Create these files and folders in your project directory
# ai_memory_therapist/
# ├── app.py
# ├── ai_engine.py
# ├── emotion_analysis.py
# ├── memory_manager.py
# ├── templates/
# │ └── chat.html
# └── static/
# └── style.css
Before we begin coding, you'll need to install some Python packages. Open your terminal and run:
pip install flask openai python-dotenv textblob nltk matplotlib
Step 2: Creating the Memory Manager
Let's start with the memory management system that will store conversation history:
# memory_manager.py
import sqlite3
import json
from datetime import datetime
class MemoryManager:
def __init__(self, db_path="memory.db"):
self.db_path = db_path
self.setup_database()
def setup_database(self):
"""Initialize the SQLite database with required tables."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Create users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create conversations table
cursor.execute('''
CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY,
user_id INTEGER,
message TEXT,
response TEXT,
emotions TEXT,
keywords TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Create emotional_states table
cursor.execute('''
CREATE TABLE IF NOT EXISTS emotional_states (
id INTEGER PRIMARY KEY,
user_id INTEGER,
emotion TEXT,
intensity REAL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
conn.commit()
conn.close()
def get_or_create_user(self, username):
"""Get a user ID or create if not exists."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
if not user:
cursor.execute("INSERT INTO users (username) VALUES (?)", (username,))
conn.commit()
user_id = cursor.lastrowid
else:
user_id = user[0]
conn.close()
return user_id
def store_conversation(self, user_id, message, response, emotions=None, keywords=None):
"""Store a conversation entry."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
emotions_json = json.dumps(emotions) if emotions else None
keywords_json = json.dumps(keywords) if keywords else None
cursor.execute('''
INSERT INTO conversations (user_id, message, response, emotions, keywords)
VALUES (?, ?, ?, ?, ?)
''', (user_id, message, response, emotions_json, keywords_json))
conn.commit()
conn.close()
def store_emotional_state(self, user_id, emotion, intensity=1.0):
"""Store an emotional state entry."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO emotional_states (user_id, emotion, intensity)
VALUES (?, ?, ?)
''', (user_id, emotion, intensity))
conn.commit()
conn.close()
def get_conversation_history(self, user_id, limit=10):
"""Get recent conversation history for a user."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT message, response, emotions, keywords, timestamp
FROM conversations
WHERE user_id = ?
ORDER BY timestamp DESC
LIMIT ?
''', (user_id, limit))
history = cursor.fetchall()
conn.close()
formatted_history = []
for msg, resp, emotions_json, keywords_json, timestamp in history:
emotions = json.loads(emotions_json) if emotions_json else {}
keywords = json.loads(keywords_json) if keywords_json else []
formatted_history.append({
"message": msg,
"response": resp,
"emotions": emotions,
"keywords": keywords,
"timestamp": timestamp
})
return formatted_history
def get_emotional_trends(self, user_id, days=30):
"""Get emotional trends for a user over time."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT emotion, intensity, timestamp
FROM emotional_states
WHERE user_id = ? AND timestamp >= datetime('now', '-' || ? || ' days')
ORDER BY timestamp ASC
''', (user_id, days))
trends = cursor.fetchall()
conn.close()
return trends
def get_last_topics(self, user_id, limit=3):
"""Get the most recent topics discussed."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT keywords
FROM conversations
WHERE user_id = ? AND keywords IS NOT NULL
ORDER BY timestamp DESC
LIMIT ?
''', (user_id, limit))
topics = cursor.fetchall()
conn.close()
all_keywords = []
for keywords_json, in topics:
if keywords_json:
keywords = json.loads(keywords_json)
all_keywords.extend(keywords)
# Return unique keywords
return list(set(all_keywords))
def get_dominant_emotions(self, user_id, limit=3):
"""Get the most common emotions for a user."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT emotion, COUNT(*) as count
FROM emotional_states
WHERE user_id = ?
GROUP BY emotion
ORDER BY count DESC
LIMIT ?
''', (user_id, limit))
emotions = cursor.fetchall()
conn.close()
return emotions
Would you like me to explain how this memory manager works?