Skip to content

Commit 754f035

Browse files
committed
Add: Memory with multi user support with MongoDB
1 parent 83967f9 commit 754f035

4 files changed

Lines changed: 106 additions & 5 deletions

File tree

dependencies.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ langchain-community
77
langchain-text-splitters
88
langchain-ollama
99
pymupdf
10-
protobuf==3.20.3
10+
protobuf==3.20.3
11+
pymongo

main.py

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,37 @@
33
from langchain_text_splitters import RecursiveCharacterTextSplitter
44
from langchain_community.vectorstores import Chroma
55
from langchain_ollama import OllamaEmbeddings
6+
from pymongo import MongoClient
7+
import datetime
68
import ollama
79

10+
# MongoDB Setup
11+
print("[INFO] Connecting to MongoDB...")
12+
try:
13+
# Connecting to default local MongoDB Port
14+
mongo_client = MongoClient("mongodb://localhost:27017/", serverSelectionTimeoutMS=2000)
15+
16+
# Forcing a connection test
17+
mongo_client.server_info()
18+
db = mongo_client["hr_assistant"]
19+
chat_collection = db["chat_history"]
20+
print("[OK] Connected to MongoDB!")
21+
except Exception as e:
22+
print("[ERROR] Could not connect to MongoDB. Is the server running?")
23+
exit(1)
24+
25+
# Dynamic Session ID for handling users and their past questions
26+
print("\nWelcome to HR Buddy")
27+
SESSION_ID = input("Please enter your name to login: ").strip()
28+
29+
# Fallback support as a guest session
30+
if not SESSION_ID:
31+
SESSION_ID = "guest_user"
32+
print("[INFO] No name provided. Logging in as 'guest_user'.")
33+
else:
34+
print(f"[INFO] Hello, {SESSION_ID}! Fetching your records...")
35+
36+
837
# Load and Chunk the Data
938
print("[INFO] Reading HR Policy PDF...")
1039
loader = PyMuPDFLoader("rag_source/nasscom-hr-manual-2016.pdf")
@@ -15,7 +44,8 @@
1544
chunks = text_splitter.split_documents(pages)
1645

1746
# Embed and Store in Vector DB
18-
print("[INFO] Embedding text and building Chroma database...")
47+
print(f"[INFO] Chunking complete. Found {len(chunks)} text chunks.")
48+
print("[INFO] Sending chunks to Ollama to create embeddings...")
1949
# fast, local nomic model to turn text into math
2050
embeddings = OllamaEmbeddings(model="nomic-embed-text")
2151
vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings)
@@ -30,7 +60,14 @@
3060
while True:
3161
user_input = input("\n:> ")
3262

33-
# Semantic Search: Find the relevant policy paragraphs
63+
# Get last 10 messages from the user
64+
past_messages_cursor = chat_collection.find({"session_id": SESSION_ID}).sort("timestamp", -1).limit(10)
65+
66+
# Convert cursor to list and reverse for reading it from start to end
67+
past_messages = list(past_messages_cursor)[::-1]
68+
history_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in past_messages])
69+
70+
# Semantic Search: Find the relevant policy paragraphs from the RAG source
3471
docs = retriever.invoke(user_input)
3572
context_block = "\n\n".join([doc.page_content for doc in docs])
3673

@@ -41,9 +78,13 @@
4178
4279
If the Context does not contain the exact answer, simply reply: "I cannot find the answer to that in the current policy."
4380
44-
Context:
81+
--- PAST CONVERSATION MEMORY ---
82+
{history_text}
83+
84+
--- CURRENT HR CONTEXT ---
4585
{context_block}
4686
87+
--- CURRENT QUESTION ---
4788
Question: {user_input}
4889
Answer:"""
4990

@@ -52,7 +93,13 @@
5293
{'role': 'user', 'content': rag_prompt}
5394
])
5495

55-
print(f"\nAI: {response['message']['content']}")
96+
ai_answer = response['message']['content']
97+
print(f"\nAI: {ai_answer}")
98+
99+
chat_collection.insert_many([
100+
{"session_id": SESSION_ID, "role": "User", "content": user_input, "timestamp": datetime.datetime.now(datetime.timezone.utc)},
101+
{"session_id": SESSION_ID, "role": "AI", "content": ai_answer, "timestamp": datetime.datetime.now(datetime.timezone.utc)}
102+
])
56103

57104
except KeyboardInterrupt:
58105
print("\n\n[INFO] Closing Chat.")

run.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,10 @@ else
8585
echo "[OK] Python recognizes 'pymupdf'."
8686
fi
8787

88+
# Check and configure MongoDB
89+
chmod +x scripts/mongodb_cfg.sh
90+
./scripts/mongodb_cfg.sh
91+
8892
# Required Models for RAG
8993
echo "[INFO] Verifying AI models (Llama3.2 & Nomic)..."
9094
ollama pull llama3.2

scripts/mongodb_cfg.sh

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# System MongoDB Engine Check & Install
2+
echo "[INFO] Checking for MongoDB..."
3+
if ! command -v mongod &> /dev/null && ! command -v mongo &> /dev/null; then
4+
echo "[WARNING] MongoDB not found. Detecting OS to install..."
5+
6+
# Detect the operating system
7+
if [ -f /etc/os-release ]; then
8+
. /etc/os-release
9+
case "$ID_LIKE" in
10+
*fedora*|*rhel*|*centos*)
11+
echo "[INFO] Detected RedHat/Fedora base. Installing via dnf..."
12+
sudo dnf install -y mongodb-server
13+
SVC_NAME="mongod"
14+
;;
15+
*debian*|*ubuntu*)
16+
echo "[INFO] Detected Debian/Ubuntu base. Installing via apt..."
17+
sudo apt-get update
18+
sudo apt-get install -y mongodb
19+
SVC_NAME="mongodb"
20+
;;
21+
*archlinux*)
22+
echo "[INFO] Detected Arch base. Installing via pacman..."
23+
sudo pacman -S --noconfirm mongodb
24+
SVC_NAME="mongodb"
25+
;;
26+
*)
27+
echo "[ERROR] Auto-install for this OS is not supported. Please install MongoDB manually."
28+
exit 1
29+
;;
30+
esac
31+
32+
echo "[OK] MongoDB installed successfully."
33+
34+
# Automatically enable and start the background service
35+
echo "[INFO] Starting MongoDB service..."
36+
sudo systemctl enable --now $SVC_NAME
37+
else
38+
echo "[ERROR] Could not detect OS. Please install MongoDB manually."
39+
exit 1
40+
fi
41+
else
42+
echo "[OK] MongoDB is already installed."
43+
44+
# Ensure the service is actually awake and running
45+
if ! systemctl is-active --quiet mongod && ! systemctl is-active --quiet mongodb; then
46+
echo "[INFO] Waking up stopped MongoDB service..."
47+
sudo systemctl start mongod || sudo systemctl start mongodb
48+
fi
49+
fi

0 commit comments

Comments
 (0)