0% found this document useful (0 votes)
13 views58 pages

Sem 6 Final Version)

The project report details the development of a generative AI chatbot utilizing DeepSeek LLM to provide engaging and humorous interactions, while ensuring user authentication and session management. It highlights the advantages of personalized conversations, cloud-based storage, and a user-friendly interface built with Streamlit, alongside addressing challenges like server congestion. Future enhancements aim to improve scalability, offline functionality, and user experience through multi-LLM integration and advanced features.

Uploaded by

kkunalsingh1269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views58 pages

Sem 6 Final Version)

The project report details the development of a generative AI chatbot utilizing DeepSeek LLM to provide engaging and humorous interactions, while ensuring user authentication and session management. It highlights the advantages of personalized conversations, cloud-based storage, and a user-friendly interface built with Streamlit, alongside addressing challenges like server congestion. Future enhancements aim to improve scalability, offline functionality, and user experience through multi-LLM integration and advanced features.

Uploaded by

kkunalsingh1269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

A PROJECT REPORT

ON

GENERATIVE ARTIFICIAL INTELLIGENCE CHATBOT

submitted by

MR. MADHAVAN ARJUN AYYAVU

in partial fulfillment of the requirements for the degree

of

Bachelor of Science
in
Computer Science
Under the guidance of
Prof. THIRU MENAGA PRABHU NADAR
Department of Computer Science

Mahendra Pratap Sharada Prasad Singh College of Arts, Commerce and Science
(SEM VI)
(2024 - 2025)
CERTIFICATE
The report titled

GENERATIVE ARTIFICIAL INTELLIGENCE CHATBOT


​ ​ ​ ​ ​ completed by

​ ​ ​ ​ MR. MADHAVAN ARJUN AYYAVU


​ ​ ​
as a partial fulfillment of the
requirements for the degree of

Bachelor of Science

in

Computer Science
from

The University of Mumbai

Project Guide​ Examiner​

Head of Department​ Principle


DECLARATION

I, __________________________, hereby declare that this project entitled


___________________________________________ represents my ideas in my own
words, and where others' ideas or words have been included, I have adequately cited
and referenced the sources. I also declare that I have adhered to all academic honesty
and integrity principles and have not misrepresented, fabricated or falsified any
idea/data/fact/source in my submission. I understand that any violation of the above
will cause disciplinary action by the Institute and can also evoke penal action from
the sources which have thus not been properly cited or from whom proper permission
has not been taken when needed.

SIGNATURE OF THE STUDENT:

PLACE:

DATE:
ACKNOWLEDGEMENT

I am pleased to present the “GENERATIVE ARTIFICIAL INTELLIGENCE CHATBOT”


project and take this opportunity to express my sincere gratitude to our Prof. Thiru Menaga Prabhu
Nadar who motivated and supported me in completing this project.

No project is ever complete without the guidance of those experts who have previously walked this
path and mastered it, becoming mentors in the process. I would like to take this opportunity to thank
all the individuals who helped me in bringing this project to life.

I am thankful to my college for providing excellent facilities that helped me complete and present
this project.

I express my deepest gratitude to my project guide for their valuable and timely advice during the
various phases of the project. I am also grateful for the facilities, support, and patience they provided,
along with their trust in my abilities and the flexibility they offered in terms of working and reporting
schedules.
INDEX

Sr. No Topics Page No

1 Introduction 2
1.1​ Overview of the Project
1.2​ Purpose and Objectives
1.3​ Problem Statement
2 Advantages and Disadvantages 4
2.1​ Key Benefits of the System
2.2 Limitations and Challenges
3 Scope of the Project 6
3.1​ Scope of Implementation
3.2​ Future Enhancements
4 Features 10
4.1​ Major Functionalities
4.2​ User Interface and Experience
5 Feasibility Study 12
5.1​ Technical Feasibility
5.2​ Operational Feasibility
5.3​ Economic Feasibility
6 System Analysis 15
6.1​ Existing System
6.2​ Proposed System

7 System Design 17
7.1​ ER
7.2​ Database ER
8 Project Coding 19
8.1​ Code Implementation
8.2​ Explanation of Key Algorithms
and Functions
9 Project Output Screens 36
9.1​ Screenshots
10 Hardware and Software 46
Requirements
10.1​Minimum and Recommended
Hardware Specifications
10.2​Software Tools and Platforms
Used
11 Conclusion 48
11.1​Summary of the Project
12 Bibliography 50
12.1​List of References
ABSTRACT

Artificial intelligence has revolutionized digital interactions, making chatbots essential for
automating conversations, delivering information, and enhancing user engagement. This project
introduces an AI-powered chatbot that leverages the DeepSeek LLM to generate concise, engaging,
and humor-infused responses, creating a dynamic and enjoyable user experience. The chatbot
integrates authentication, session management, and message storage, allowing users to maintain
continuous and personalized conversations.

Built using Streamlit, the chatbot offers a clean and intuitive user interface, ensuring accessibility for
both technical and non-technical users. The core language model integration is powered by Hugging
Face, enabling seamless connectivity with DeepSeek for intelligent response generation. To
efficiently manage user data, Astra DB (NoSQL) is used, ensuring fast, scalable, and reliable storage
for chat histories and user sessions. This architecture enables smooth, real-time interactions while
preserving context across different sessions.

A key challenge addressed in this project is server congestion in DeepSeek LLM, which can lead to
delays or unavailability. To mitigate this, the chatbot features a fallback mechanism, ensuring
uninterrupted usability even during high traffic. Future improvements may include integrating
alternative LLMs, implementing local model hosting, or leveraging caching techniques to enhance
response speed and reliability.

This project highlights the potential of large language models in creating intelligent and engaging
chatbots. By incorporating secure authentication, session persistence, and scalable database
management, it delivers an efficient, responsive, and enjoyable conversational experience, making
AI-driven interactions more accessible and reliable for users.

1
1. INTRODUCTION
1.1​Overview of the Project -

Artificial Intelligence (AI) has revolutionized human-computer interactions, with chatbots playing a
key role in automating conversations, assisting users, and delivering personalized responses. This
project introduces an AI-powered chatbot leveraging DeepSeek LLM to generate concise,
engaging, and humor-infused responses, making AI interactions more enjoyable and dynamic.
Unlike traditional chatbots that often produce generic replies, this chatbot is designed to create an
interactive and entertaining user experience.

The chatbot incorporates secure authentication, session management, and message storage,
ensuring users can maintain conversation context across sessions. It features a user-friendly
interface built with Streamlit, making it accessible to both technical and non-technical users. The
chatbot seamlessly integrates with Hugging Face for DeepSeek LLM connectivity, while Astra DB
(NoSQL) serves as an efficient online database for storing user sessions and chat histories.

One of the major challenges of utilizing DeepSeek LLM is server congestion, which can cause
response delays or unavailability. This project addresses this issue by implementing strategies to
enhance chatbot usability even when DeepSeek’s servers are overloaded. Future improvements may
include fallback mechanisms, model switching, or local LLM hosting to improve reliability and
reduce dependency on external servers.

1.2​Purpose and Objectives -

The primary goal of this project is to develop an intelligent and engaging AI chatbot that provides
users with quick, interactive, and context-aware responses while ensuring a smooth and
uninterrupted experience.

●​ Develop an AI chatbot using DeepSeek LLM for generating natural and engaging

2
conversations.
●​ Ensure a seamless user experience through authentication and session persistence.
●​ Implement a scalable database using Astra DB (NoSQL) for efficient chat history storage.
●​ Design a user-friendly interface with Streamlit for easy and intuitive interaction.
●​ Address server congestion issues by implementing fallback mechanisms or alternative
strategies to ensure chatbot availability.
●​ Explore future enhancements, such as integrating multiple LLMs or deploying a local/offline
model for improved reliability.

1.3 Problem Statement -

Traditional chatbots often produce generic, repetitive, and unengaging responses, leading to a poor
user experience. While large language models like DeepSeek LLM offer advanced conversational
capabilities, they frequently face server congestion, resulting in delayed or unavailable responses.

This project aims to tackle these challenges by:

●​ Enhancing chatbot engagement through a humorous and interactive conversational tone.


●​ Ensuring chat continuity by integrating session management and database storage.
●​ Overcoming LLM server issues by introducing fallback mechanisms, enabling uninterrupted
chatbot usage even during DeepSeek overload.

By addressing these limitations, this project contributes to building a more engaging, scalable, and
efficient AI-powered chatbot, enhancing user interaction while minimizing disruptions caused by
external dependencies.

3
2. Advantages and Disadvantages

2.1 Key Benefits of the System -

●​ Personalized and Engaging Conversations – Unlike traditional AI chatbots that generate


formal or generic responses, this chatbot adopts a lighthearted and humorous tone, making
interactions more dynamic and enjoyable.
●​ Secure & Persistent Sessions – The system incorporates authentication and session
tracking, ensuring users can resume conversations seamlessly across multiple sessions.
●​ OTP-Based Password Reset – Users can reset their passwords securely using OTP
verification via email, enhancing account security and accessibility.
●​ Cloud-Based Storage for Chat History – Astra DB ensures fast, scalable, and efficient
storage, preserving chat history without performance issues.
●​ Easy-to-Use Interface – Streamlit provides a minimalist and user-friendly UI, making the
chatbot accessible to both technical and non-technical users.
●​ Integration with Advanced AI Models – Leveraging DeepSeek LLM via Hugging Face,
the chatbot delivers context-aware, intelligent responses that improve over time.
●​ Scalability & Future Expansion Possibilities – The system supports future enhancements
such as multi-LLM integration, local AI hosting, or fallback response strategies for
greater flexibility.
●​ Handling LLM Downtime or Server Overload – The chatbot is equipped with
mechanisms to ensure continued usability, even when DeepSeek’s servers are congested
or unavailable, making it more reliable than standard chatbots.

2.2​Limitations and Challenges -

●​ Dependency on External AI Models – Since the chatbot relies on DeepSeek LLM, its
performance is subject to external server availability, which may cause delays or failed
responses during outages.
●​ Lack of Offline Functionality – The chatbot currently does not support local inference,
meaning an internet connection is required for interaction.

4
●​ Limited Humor Moderation – While designed for entertainment, AI-generated humor
may sometimes be misinterpreted or inappropriate, necessitating manual moderation
and refinement.
●​ Scalability Costs – Cloud-based storage and API calls may incur additional costs as user
traffic grows, requiring efficient resource management to optimize expenses.
●​ Latency Issues During Peak Traffic – If DeepSeek’s servers are under high demand,
response times may increase, temporarily affecting the user experience.

5
3. Scope of the Project

3.1 Scope of Implementation -

The AI-powered chatbot is designed to provide users with humorous, engaging, and context-aware
conversations using DeepSeek LLM. The system integrates with Hugging Face for AI interaction,
Astra DB for cloud-based chat storage, and Streamlit for a simple yet functional UI. It also includes
authentication and session management to enhance user experience.

Key Areas Covered in the Project Scope:

●​ User Authentication & Session Management – Users can sign up, log in, and maintain
persistent sessions to access past conversations.
●​ AI-Powered Conversational Experience – The chatbot generates short, humorous, and
engaging responses using DeepSeek LLM to keep interactions fun and interactive.
●​ Handling AI Model Downtime & Server Overload – Designed to mitigate delays and
server overload by implementing fallback mechanisms.
●​ Cloud-Based Storage & Data Management – Chat history, user data, and session logs are
stored using Astra DB, ensuring seamless retrieval for future interactions.
●​ Minimalist & User-Friendly Interface – A Streamlit-based UI makes the chatbot
accessible, even for non-technical users.
●​ Integration with Hugging Face API – The chatbot accesses DeepSeek LLM via Hugging
Face, making it adaptable to future AI model upgrades.
●​ Scalability & Performance Optimization – The system is cloud-based and scalable,
allowing future expansion for more users, additional AI models, and improved response
times.

Scope of Implementation:

1.​ Frontend: Streamline-Based User Interface


1.1.​ Purpose: Provides a simple and intuitive web-based interface.
1.2.​ Features:
1.2.1.​ User authentication (Login/Signup with OTP-based password reset).

6
1.2.2.​ Chat window for real-time AI interactions.
1.2.3.​ Session tracking to allow users to continue conversations seamlessly.
2.​ Backend: AI Processing & Response Generation
2.1.​ DeepSeek LLM (via Hugging Face API) – Generates engaging and humorous
responses to user queries.
2.2.​ Session Management System – Ensures users can resume previous chats without
losing data.
2.3.​ Handling Server Load – Implements fallback strategies to manage DeepSeek
server overload.
3.​ Database: Astra DB for Storage
3.1.​ Purpose: Stores chat history, user authentication details, and session logs for data
retrieval.
3.2.​ Features:
3.2.1.​ NoSQL-based storage ensures high scalability.
3.2.2.​ Fast and efficient data retrieval for personalization.
4.​ Deployment & Hosting
4.1.​ Cloud-Based Deployment – Ensures 24/7 accessibility from anywhere.​
Hugging Face API Integration – Allows seamless AI model updates and
enhancements
4.2.​ Optimized API Call Management – Reduces latency and enhances response
times.

3.2 Future Enhancements

To improve efficiency, scalability, and user experience, the following enhancements are planned for
future updates:

1. Multi-LLM Integration & Fallback Mechanism

●​ The chatbot currently depends on DeepSeek LLM, which may cause delays due to server
congestion.
●​ Future updates will integrate multiple AI models (e.g., LLaMA, GPT, Mistral AI) to
switch dynamically based on performance and availability.

7
2. AI Fine-Tuning & Personalization

●​ User-Based Humor Preferences – The chatbot will adapt its tone, style, and response
length based on past user interactions.
●​ Enhanced AI Training – Fine-tuning DeepSeek LLM to improve accuracy, humor quality,
and contextual awareness.

3. Offline Mode & Local AI Hosting

●​ Instead of relying solely on external APIs, a locally hosted AI model will be introduced for
offline functionality.
●​ Benefits:
○​ Eliminates server dependency.
○​ Faster response times.
○​ Greater data privacy.

4. Advanced UI Features

●​ Dark mode for user convenience.


●​ Message reactions (like emojis) to enhance engagement.
●​ Mobile-friendly version for better usability on smartphones.

5. Voice-to-Text & Speech Generation

●​ Speech-to-Text Input – Users can talk instead of typing for a more natural interaction.
●​ AI-Generated Voice Responses – The chatbot will speak its replies to create an immersive
conversational experience.

6. Security & Data Privacy Enhancements

●​ End-to-End Encryption for chat storage, ensuring maximum privacy.


●​ User-Controlled Chat Deletion – Users can permanently delete their chat history if desired.

7. Monetization & API Access for Developers

●​ Third-Party API Access – Developers can integrate the chatbot into their applications.
●​ Premium AI Plans – Users can subscribe to faster response plans with additional

8
customization options.

9
4. Features

4.1 Major Functionalities -

●​ AI Chatbot Response Generation


○​ Accepts user inputs and generates short, funny, and engaging responses using
DeepSeek LLM.
○​ Uses context retention to maintain meaningful conversations.
●​ User Authentication & Management
○​ Users can sign up, log in, and manage their accounts securely.
○​ Session tracking allows users to continue their conversation from where they left off.
●​ Chat History Management
○​ Users can view past conversations stored in Astra DB.
○​ Conversations are linked to user accounts, ensuring personalized interactions.
●​ Handling AI Model Downtime & Overload
○​ If DeepSeek servers are busy, the chatbot displays an informative message and
attempts to retry.
○​ Future updates will allow the system to switch to backup AI models automatically.
●​ Streamline-Based UI for User Interaction
○​ Real-time message rendering for an interactive experience.
○​ Auto-scroll feature ensures smooth navigation through the conversation.
●​ Database Integration with Astra DB
○​ Stores user login credentials, chat history, and session details securely.
○​ NoSQL database ensures high availability and quick retrieval of user data.
●​ API-Based AI Integration
○​ The chatbot communicates with DeepSeek LLM via Hugging Face API, allowing
dynamic AI improvements.
○​ Future versions may support custom AI model fine-tuning.

4.2 User Interface and Experience -

●​ Simple, Lightweight, and User-Friendly Design


10
○​ Built using Streamlit, which ensures a clean and smooth interface.
○​ Minimalist design keeps user interactions straightforward and enjoyable.
●​ Easy-to-Use Chat Interface
○​ The chatbot follows a standard messaging UI, making interactions familiar and
accessible.
○​ The chat history remains available for continued conversations.
●​ Mobile & Desktop Compatibility
○​ The chatbot runs on a web-based interface, making it usable on both PC and mobile
devices.
●​ Fast & Responsive Performance
○​ Real-time message updates ensure smooth conversations.
○​ Cloud-based database and API integration minimize delays.
●​ Error Handling & Feedback Mechanisms
○​ If an AI model error or API issue occurs, the chatbot informs the user immediately.
○​ The chatbot provides suggestions if the AI fails to generate a response.
●​ Secure & Private Conversations
○​ User authentication ensures only authorized access to chat history.
○​ Future updates may include end-to-end encryption for enhanced security.

11
5. Feasibility Study

5.1. Technical Feasibility -

●​ AI Model Integration
○​ The project utilizes DeepSeek LLM via Hugging Face, which provides
state-of-the-art AI responses.
○​ Potential challenges: DeepSeek's busy servers may cause delays or failures in
generating responses.
○​ Solution: Future versions may integrate alternative fallback AI models to
maintain uninterrupted service.
●​ Backend and Database Selection
○​ The chatbot uses Astra DB (NoSQL) for storing user data, chat history, and
session details.
○​ NoSQL databases are chosen because they provide:
■​ High scalability and fast read/write operations.
■​ Flexible data structure that allows easy modifications.
●​ API & Cloud Integration
○​ The chatbot integrates Hugging Face APIs to fetch responses from DeepSeek
LLM.
○​ Challenges:
■​ API latency may affect response times.
■​ Cloud costs may increase with high API usage.
○​ Solution: Implementing caching mechanisms for frequently asked queries to
reduce API calls.
●​ Development Tools & Frameworks
○​ Streamlit: Used for creating a simple and responsive UI for the chatbot.
○​ Python: The primary programming language for backend development.
○​ Database Connector (for authentication): Used to manage user login credentials
securely.
○​ Astra DB (NoSQL): Used for efficient data storage.
●​ Deployment & Scalability

12
○​ The chatbot can be deployed on cloud platforms such as AWS, Google Cloud, or
Hugging Face Spaces.
○​ The system is scalable, allowing future improvements like multi-model AI
switching when DeepSeek is unavailable.

5.2. Operational Feasibility -

●​ User Experience & Accessibility


○​ The chatbot is designed for ease of use, requiring minimal user effort to log in
and start chatting.
○​ The authentication system ensures secure user sessions.
○​ The chatbot provides quick, short, and humorous responses, making it engaging
for users.
●​ System Reliability & Maintenance
○​ Potential Challenge: If DeepSeek LLM is overloaded, users might experience
delayed or failed responses.
○​ Solution: Implement a retry mechanism or alternative AI models.
○​ Database reliability: Astra DB is a highly scalable NoSQL database, ensuring
fast data retrieval.
●​ Security & Data Privacy
○​ User authentication ensures that only authorized users can access their chat
history.
○​ Potential Risk: If stored data is not encrypted, it might be vulnerable to
breaches.
○​ Solution: Implement data encryption for stored chat logs and user credentials.
●​ Performance & Server Load
○​ The system is built using cloud-based APIs, ensuring that performance scales
with demand.
○​ Potential Challenge: High API request volumes may increase operational costs.
○​ Solution: Implement rate limiting and optimize API usage.

13
5.3. Economic Feasibility

●​ Development Costs
○​ Technology Stack:
■​ DeepSeek LLM via Hugging Face (Free-tier available, but may require a
paid plan for high usage).
■​ Astra DB (NoSQL) – Free tier available but may incur costs with heavy
usage.
■​ Streamlit (Free for local use, paid options for cloud deployment).
■​ Cloud Hosting (AWS/GCP) (Optional for scaling).
○​ Estimated Initial Costs: Low, as free tiers cover most development needs.
●​ API Costs
○​ Hugging Face APIs might incur costs based on usage limits.
○​ Solution: Implement rate-limiting and caching to minimize API calls.
●​ Deployment & Maintenance Costs
○​ If deployed on cloud servers, monthly costs depend on traffic and storage
requirements.
○​ Solution: Optimize database queries and storage usage to reduce costs.
●​ Potential Revenue Models
○​ Freemium Model:
■​ Free users get a limited number of interactions per day.
■​ Premium users get unlimited access and extra features.
○​ API Integration for Businesses:
■​ Offer chatbot integration as a service for customer support.
○​ Advertisements:
■​ Display non-intrusive ads in the UI for revenue generation.

14
6. System Analysis

6.1 Existing System -

The current landscape of AI chatbots consists of various models and platforms. However, they
come with certain limitations that impact their usability.

●​ Server Overload & Downtime


○​ Many AI chatbots, including DeepSeek LLM, experience high traffic and server
unavailability.
○​ Users may face delays or failure in getting responses due to busy servers.
●​ Lack of Personalization & Session Management
○​ Most chatbots do not store user interactions efficiently.
○​ Users must restart conversations from scratch, losing context from previous
interactions.
●​ Limited UI and User Engagement
○​ Some existing chatbots have complex interfaces that are not beginner-friendly.
○​ Lack of humor or interactive responses makes conversations dull and robotic.
●​ Security & Authentication Gaps
○​ Many chatbots do not offer proper user authentication

6.2 Proposed System -


To address these issues, the proposed system is an AI-powered chatbot with the following
improvements:

●​ Backup System for AI Downtime


○​ If DeepSeek LLM is unavailable, the chatbot switches to an alternative AI model.
○​ This ensures that users always get responses, reducing frustration.
●​ Session Management & Conversation Storage
○​ The chatbot stores past conversations using Astra DB (NoSQL).
○​ Users can resume chats from where they left off, enhancing context retention.
●​ Simple & Engaging UI with Humor

15
○​ Developed using Streamlit, ensuring a clean and interactive UI.
○​ The chatbot responds in a funny and engaging tone, making interactions more
enjoyable.
●​ Authentication & Security
○​ Uses a secure login system to ensure that each user has a private session.
○​ Prevents unauthorized access and protects chat history.
●​ Optimized API Calls to Reduce Costs
○​ Implements response caching to reduce unnecessary API requests.
○​ Reduces operational costs while maintaining fast responses.

16
7. System Design

7.1. ER Diagram -

17
7.2. Database ER Diagram -

18
8.Project Coding

Initialization
import streamlit as st
from huggingface_hub import InferenceClient
import random
from astrapy.db import AstraDB
import uuid
from datetime import datetime
import hashlib
import requests

# Constants
👤"
USER_AVATAR = "
BOT_AVATAR = "🤖"

# API Keys and Endpoints


HUGGINGFACE_API_KEY = "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"
ASTRA_DB_TOKEN =
"AstraCS:BhEjmCnFpQhIEQaHjuqyzrAv:ea0c7688db5f04d6493f3cdf956caf4de8ac6bab0458134e4
e007a0dbfc1301f"
ASTRA_DB_ENDPOINT =
"https://349bd626-3660-4c56-88b9-290e7fe1e064-us-east1.apps.astra.datastax.com"

# Database and API Initialization


def initialize_services():
db = AstraDB(token=ASTRA_DB_TOKEN, api_endpoint=ASTRA_DB_ENDPOINT)

def get_or_create_collection(name):
collections = db.get_collections()['status']['collections']
return db.create_collection(name) if name not in collections else db.collection(name)

19
return (
get_or_create_collection("users"),
get_or_create_collection("chat_sessions"),
get_or_create_collection("messages"),
InferenceClient(api_key=HUGGINGFACE_API_KEY)
)

# Initialize global services


users_collection, sessions_collection, messages_collection, client = initialize_services()

# Session State Management


def initialize_session_state():
required_keys = {
"all_sessions": {},
"current_session": None,
"messages": [],
"context": "",
"last_input": "",
"editing_session_name": False,
"authenticated": False,
"user_email": None,
"username": None,
"current_session_id": None,
"new_password": None,
"forgetEmail": None,
"otp_sent": False,
"otp_verify": None,
"show_signup": False,
"render_OTP": False,
"render_forget_password": False,
"otp_timestamp": None, # Add timestamp for OTP expiration
"otp_attempts": 0 # Track failed attempts
}
20
for key, default_value in required_keys.items():
if key not in st.session_state:
st.session_state[key] = default_value

# User Authentication Functions


def create_user(email, username, password):
hashed_password = hashlib.sha256(password.encode()).hexdigest()
user_doc = {
"_id": str(uuid.uuid4()),
"email": email,
"username": username,
"password": hashed_password,
"created_at": datetime.now().isoformat()
}
users_collection.insert_one(user_doc)
return "[SUCCESS]"

def verify_user(email, password):


hashed_password = hashlib.sha256(password.encode()).hexdigest()
try:
user = users_collection.find_one({"email": email})

if not user or 'data' not in user:


st.error("User not found. Please try again.")
return None

user_data = user['data']['document']

if user_data['password'] != hashed_password:
st.error("Incorrect password. Please try again.")
return None

return user_data['username']
21
except Exception as e:
st.error(f"Incorrect email. Please try again.")
return None

def new_password(email, password):


hashed_password = hashlib.sha256(password.encode()).hexdigest()
users_collection.update_one({"email": email}, {"$set": {"password": hashed_password}})
return True

def check_email(email):
try:
user = users_collection.find_one({"email": email})

# Debug print to see the actual structure


print(f"User lookup structure: {user}")

# Check if response contains a document


if user and 'data' in user and 'document' in user['data']:
return user['data']['document']['email'] == email

return False

except Exception as e:
print(f"Error checking email: {str(e)}")
st.error(f"Error checking email: {str(e)}")
return False

define otpEmail(email):

otp = random.randint(100000, 999999)

url = "https://send-bulk-emails.p.rapidapi.com/api/send/otp/mail"

22
payload = {
"subject": "Password Recovery OTP",
"from": "[email protected]",
"to": f"{email}",
"senders_name": "EKKO AI",
"body": f"Your OTP is {otp}"
}

headers = {
"x-rapidapi-key": "e448bfa06emsh9053d11a8be63ddp188ae7jsnf440b6eadba1",
"x-rapidapi-host": "send-bulk-emails.p.rapidapi.com",
"Content-Type": "application/json"
}

try:
response = requests.post(url, json=payload, headers=headers)
data = response.json()

print(f"API response: {data}") # Debug print

if response.status_code == 200:
return otp
else:
st.error(f"Failed to send OTP: {data.get('message', 'Unknown error')}")
return None
except Exception as e:
st.error(f"Failed to send OTP: {str(e)}")
return None

# Chat Session Management Functions


def save_session(email, session_name):
session_id = str(uuid.uuid4())
session_doc = {
"_id": session_id,
23
"email": email,
"session_name": session_name,
"created_at": datetime.now().isoformat()
}
sessions_collection.insert_one(session_doc)
return session_id

def save_message(session_id, role, content):


message_doc = {
"_id": str(uuid.uuid4()),
"session_id": session_id,
"role": role,
"content": content,
"timestamp": datetime.now().isoformat()
}
messages_collection.insert_one(message_doc)
return True

def get_user_sessions(email):
if not email:
return []
response = sessions_collection.find({'email': email})
return [{
'_id': doc['_id'],
'session_name': doc['session_name'],
'created_at': doc.get('created_at', '')
} for doc in response['data']['documents']]

def get_session_messages(session_id):
response = messages_collection.find({"session_id": session_id})
return sorted(response['data']['documents'], key=lambda x: x['timestamp'])

# AI Query Function
def query_huggingface(context, question):
24
try:
messages = [
{"role": "system", "content": "You are a funny and friendly AI and the most important thing
is you should answer in short and concise manner not giving long answers. Be honest, funny, and
slightly cursed."},
{"role": "user", "content": f"Context: {context}\nQuestion: {question}"}
]
completion = client.chat.completions.create(
model="deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
messages=messages,
max_tokens=1000
)

# Get the raw response


raw_response = completion.choices[0].message['content'].strip()

# Extract just the final answer if it contains reasoning


if "</think>" in raw_response:
# If response has a thinking section, extract only what comes after it
final_answer = raw_response.split("</think>")[-1].strip()
else:
# Otherwise use the full response
final_answer = raw_response

return final_answer
except Exception as e:
st.error(f"Error: {e}")
return "Sorry, I'm having trouble thinking right now. My brain cells are on strike! Please try
again."

# UI Components - Chat Interface


def chat_interface():
initialize_session_state()
st.set_page_config(layout="wide", initial_sidebar_state="expanded")
25
with st.sidebar:
render_sidebar()
render_main_content()

def render_sidebar():
st.title("EKKO AI")
if st.button("New Chat"):
handle_new_chat()

if st.session_state.current_session_id:
if st.session_state.editing_session_name:
new_name = st.text_input("Rename session:", value=st.session_state.current_session,
key="session_rename_input")
if st.button("Save", key="save_edit_btn"):
sessions_collection.update_one({"_id": st.session_state.current_session_id}, {"$set":
{"session_name": new_name}})
st.session_state.current_session = new_name
st.session_state.editing_session_name = False
st.rerun()
if st.button("Cancel", key="cancel_edit_btn"):
st.session_state.editing_session_name = False
st.rerun()
else:
col1, col2 = st.columns([4, 1])
with col1:
st.markdown(f"**{st.session_state.current_session}**")
with col2:
if st.button(" ✏️"):
st.session_state.editing_session_name = True
st.rerun()

sessions = get_user_sessions(st.session_state.user_email)
if sessions:
st.markdown("#### History:")
26
for session in sessions:
if st.button(f" {session['session_name']}", key=f"session_{session['_id']}"):
st.session_state.current_session_id = session['_id']
st.session_state.current_session = session['session_name']
st.session_state.messages = [
{"role": msg['role'], "content": msg['content']}
for msg in get_session_messages(session['_id'])
]
st.rerun()

st.markdown("---")
if st.button("Logout"):
reset_session_state()
st.caption(" 🚀 Powered by EKKO | © 2025")
def render_main_content():
initialize_session_state()
with st.columns([6,1])[1]:
render_user_profile()
display_chat_history()
handle_user_input()

def render_user_profile():
st.write(f"Welcome {st.session_state.username}!")

def display_chat_history():
initialize_session_state()
if not st.session_state.messages:
st.info(" 💬 Start a new conversation!")
else:
for message in st.session_state.messages:
with st.chat_message("user" if message['role'] == 'user' else "assistant",
avatar=USER_AVATAR if message['role'] == 'user' else BOT_AVATAR):
st.markdown(message['content'])
27
def handle_user_input():
if not st.session_state.current_session_id:
new_session_id = save_session(st.session_state.user_email, f"Chat
{len(get_user_sessions(st.session_state.user_email)) + 1}")
st.session_state.current_session_id = new_session_id
st.session_state.current_session = f"Chat {len(get_user_sessions(st.session_state.user_email))}"

user_input = st.chat_input("Ask EKKO anything...")


if user_input and user_input != st.session_state.last_input:
st.session_state.last_input = user_input

with st.chat_message("user", avatar=USER_AVATAR):


st.markdown(user_input)

with st.chat_message("assistant", avatar=BOT_AVATAR):


message_placeholder = st.empty()
message_placeholder.text(" 🤔 Thinking...")
try:
save_message(st.session_state.current_session_id, "user", user_input)
response = query_huggingface(st.session_state.context, user_input)
save_message(st.session_state.current_session_id, "assistant", response)

st.session_state.messages.extend([
{"role": "user", "content": user_input},
{"role": "assistant", "content": response}
])
message_placeholder.markdown(response)

except Exception as e:
message_placeholder.error(f"Sorry, something went wrong! {str(e)}")

def reset_session_state():
28
for key in list(st.session_state.keys()):
del st.session_state[key]
initialize_session_state()

def handle_new_chat():
if st.session_state.current_session_id and st.session_state.messages:
sessions_collection.update_one(
{"_id": st.session_state.current_session_id},
{"$set": {"session_name": st.session_state.current_session}}
)
st.session_state.update({
"messages": [],
"context": "",
"current_session_id": None,
"current_session": None,
"last_input": ""
})
st.rerun()

# UI Components - Authentication Pages


def auth_pages():
initialize_session_state()
if st.session_state.show_signup:
render_signup_page()
elif st.session_state.render_OTP:
render_otp_page()
elif st.session_state.render_forget_password:
render_forget_password_page()
else:
render_login_page()

def render_login_page():
st.title("Login")
email = st.text_input("Email")
29
password = st.text_input("Password", type="password")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Login"):
if username := verify_user(email, password):
st.session_state.update(authenticated=True, user_email=email, username=username)
st.rerun()
with col2:
if st.button("Go to Signup"):
st.session_state.show_signup = True
st.rerun()
with col3:
if st.button("Forget Password"):
st.session_state.render_OTP = True
st.rerun()

def render_otp_page():
st.title("Forget Password")
st.subheader("Enter your email to reset password")

# Initialize state if not already done


if "forgetEmail" not in st.session_state:
st.session_state.forgetEmail = None
if "otp_sent" not in st.session_state:
st.session_state.otp_sent = False
if "otp_verify" not in st.session_state:
st.session_state.otp_verify = None

# Email input
forgetEmail = st.text_input("Email", value=st.session_state.forgetEmail or "")

# Send OTP button logic


if st.button("Send OTP"):
if not forgetEmail:
30
st.error("Please enter your email address.")
return

# Validate email format first


if '@' not in forgetEmail or '.' not in forgetEmail:
st.error("Please enter a valid email address.")
return

# First, check if the email exists in the database


email_exists = check_email(forgetEmail)

if not email_exists:
st.error("Email not found. Please enter a registered email address.")
return

# If email exists, try to send OTP


otp_verify = otpEmail(forgetEmail)

# Only update state if OTP was successfully sent


if otp_verify:
st.session_state.forgetEmail = forgetEmail
st.session_state.otp_verify = otp_verify
st.session_state.otp_sent = True
st.success("OTP sent successfully! Please check your email.")
else:
# OTP sending failed
st.error("Failed to send OTP. Please try again later.")

# Only show OTP verification if an OTP was actually sent


if st.session_state.otp_sent and st.session_state.otp_verify:
st.markdown("---")
st.subheader("OTP Verification")
otp = st.text_input("Enter the OTP sent to your email", key="otp_input")

31
col1, col2 = st.columns(2)

with col1:
if st.button("Verify OTP"):
if not otp:
st.error("Please enter the OTP.")
elif otp == str(st.session_state.otp_verify):
st.success("OTP verified successfully!")
# Set state to show password reset form
st.session_state.render_forget_password = True
st.session_state.render_OTP = False
st.rerun()
else:
st.error("Invalid OTP. Please try again.")

with col2:
if st.button("Resend OTP"):
new_otp = otpEmail(st.session_state.forgetEmail)
if new_otp:
st.session_state.otp_verify = new_otp
st.success("New OTP sent successfully!")
else:
st.error("Failed to resend OTP. Please try again.")

# Back to login button


st.markdown("---")
if st.button("Back to Login"):
# Reset all OTP-related state
st.session_state.render_OTP = False
st.session_state.otp_sent = False
st.session_state.otp_verify = None
st.session_state.forgetEmail = None
st.rerun()

32
def render_forget_password_page():
st.title("Reset Password")

if not st.session_state.forgetEmail:
st.error("Email verification required. Please go back and verify your email.")
if st.button("Go Back to Email Verification"):
st.session_state.render_forget_password = False
st.session_state.render_OTP = True
st.rerun()
return

st.info(f"Setting new password for: {st.session_state.forgetEmail}")

newPassword = st.text_input("New Password", type="password")


newConfirmPassword = st.text_input("Confirm Password", type="password")

if st.button("Reset Password"):
if not newPassword or not newConfirmPassword:
st.error("All fields are required.")
return

if len(newPassword) < 6:
st.error("Password must be at least 6 characters long.")
return

if newPassword != newConfirmPassword:
st.error("Passwords do not match.")
return

try:
if new_password(st.session_state.forgetEmail, newPassword):
st.success("Password reset successfully!")

# Add a delay to show the success message before redirecting


33
import time
time.sleep(2)

# Reset state and redirect to login


st.session_state.render_forget_password = False
st.session_state.forgetEmail = None
st.session_state.otp_sent = False
st.session_state.otp_verify = None
st.rerun()
except Exception as e:
st.error(f"Failed to reset password: {str(e)}")

if st.button("Back to Login"):
# Reset all OTP-related state
st.session_state.render_forget_password = False
st.session_state.forgetEmail = None
st.session_state.otp_sent = False
st.session_state.otp_verify = None
st.rerun()

def render_signup_page():
st.title("Sign Up")
email = st.text_input("Email")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
confirm_password = st.text_input("Confirm Password", type="password")

col1, col2 = st.columns(2)


with col1:
if st.button("Sign Up"):
if not email or not username or not password or not confirm_password:
st.error("All fields are required.")
return
34
if '@' not in email or '.' not in email:
st.error("Please enter a valid email address.")
return

if len(username) < 3:
st.error("Username must be at least 3 characters long.")
return

if len(password) < 6:
st.error("Password must be at least 6 characters long.")
return

if password != confirm_password:
st.error("Passwords do not match.")
return

if create_user(email, username, password) == "[SUCCESS]":


st.success("Account created successfully!")
st.session_state.update(authenticated=True, user_email=email, username=username)
st.rerun()

with col2:
if st.button("Back to Login"):
st.session_state.show_signup = False
st.rerun()

# Main Application
if __name__ == "__main__":
initialize_session_state()
if st.session_state.authenticated:
chat_interface()
else:
auth_pages()
35
9. Project Output Screens

Login page

36
Signup page

37
New chat session

38
Forget Password Page

39
OTP Page

40
Reset Password Page

41
Thinking Stage

42
Response to the Prompt

43
New Session Chat

44
Renaming of Session

45
10. Minimum and Recommended Hardware
Specifications

10.1 Minimum and Recommended Hardware Specifications -


Minimum Hardware Requirements
●​ Processor: Intel Core i3
●​ RAM: 4 GB
●​ Storage: 100 GB HDD
●​ Graphics: Integrated Graphics or any basic GPU
●​ Operating System: Windows 10, macOS 10.13 (High Sierra), or Linux Ubuntu 18.04 LTS
●​ Display: 1024 x 768 resolution monitor
●​ Network: Internet connection for downloading dependencies and testing
Recommended Hardware Requirements
●​ Processor: Intel Core i5 (7th Gen) or above, or AMD Ryzen 5
●​ RAM: 8 GB or more
●​ Storage: 256 GB SSD for faster read/write operations
●​ Graphics: Dedicated GPU
●​ Operating System: Windows 11, macOS 11 (Big Sur), or Linux Ubuntu 20.04 LTS
●​ Display: Full HD (1920 x 1080) or higher
●​ Network: High-speed internet connection

10.2 Software Tools and Platforms Used -

Development Environment

●​ IDE/Text Editors:
o​ Visual Studio Code (for front-end and back-end coding)
●​ Programming Languages
o​ Python
●​ Database
o​ AstraDB Endpoint and Token

46
●​ Large Language Model
o​ Hugging Face API
o​ Deepseek LLM Endpoint​
●​ Application Programming Interface(API)
o​ Rapid API​

47
11. Conclusion

11.1. Summary of the Project -

The project aimed to develop a robust and efficient system that addresses specific user needs by
integrating cutting-edge technologies and streamlined functionalities. The primary objective was to
enhance usability, improve performance, and ensure a seamless experience for end-users.

Throughout the development process, various phases were meticulously executed, including
requirement gathering, system analysis, design, implementation, and testing. The project followed a
structured approach to ensure that all aspects were aligned with the defined objectives. By leveraging
advanced technologies, efficient algorithms, and user-centric design principles, the system
successfully delivered on its intended purpose.

The project demonstrated several key strengths, including high efficiency, scalability,
user-friendliness, and reliability. It not only met but exceeded initial expectations by providing
enhanced security, improved data management, and optimized resource utilization. The integration of
modern frameworks and tools further ensured that the system remains adaptable for future
enhancements.

11.2. Future Prospects -

●​ Integration of Artificial Intelligence (AI)​


Future developments could incorporate AI-driven analytics, machine learning models, or
automation features to enhance decision-making and efficiency.
●​ Cloud-Based Deployment​
Migrating the system to a cloud-based infrastructure would improve accessibility, scalability,
and remote functionality, making it easier for users to interact with the system from
anywhere.
●​ Enhanced Security Measures​
Strengthening security protocols, including advanced encryption, multi-factor authentication,

48
and real-time threat monitoring, will enhance data protection and system integrity.
●​ Cross-Platform Compatibility​
Expanding the system’s compatibility across multiple platforms, including mobile
applications and web-based versions, will broaden its accessibility and user base.
●​ Improved Data Analytics and Reporting​
Implementing more advanced data analytics tools, visualization techniques, and predictive
modeling will provide deeper insights and drive more informed decision-making.
●​ User Experience Refinements​
Continuous improvements in UI/UX design, incorporating feedback and usability testing, will
ensure that the system remains intuitive, engaging, and user-friendly.
●​ Support for Multi-Language and Localization​
Expanding language support and localization options will make the system more accessible to
a diverse user base worldwide.
●​ Integration with Emerging Technologies​
Future updates could explore integrations with blockchain, IoT, or augmented reality (AR) to
expand the system’s capabilities and industry applications.

49
12. Bibliography

12.1 Online Tutorials


●​ Create a Chatbot using Hugging Face and Streamlit | Python | ChatGPT

12.2 Chatbot
●​ Chatgpt 4.o & 4.o mini
●​ Claude
●​ Deepseek

12.3 Documents
●​ Astra DB Docs
●​ Hugging Face Docs

50
51

You might also like