Invent Ree
Invent Ree
A
MAJOR PROJECT REPORT
By
Aarushi Yadav
(01714902023)
Maanik Khattar
(01814902023)
Sambhav Makhija
(35814902023)
1
SELF CERTIFICATE
This is to certify that the dissertation/project report entitled “InvenTree: Smart Inventory
Management”, done by us is an authentic work carried out for the partial fulfilment of the
requirements for the award of the degree of Bachelor of Computer Applications under the
guidance of Dr. Ravinder Singh. The matter embodied in this project work has not been sub-
mitted earlier for award of any degree or diploma to the best of my knowledge and belief.
Signature:
Maanik Khattar
(01814902023)
Signature:
Sambhav Makhija
(35814902023)
Signature:
Angad Singh Chhabra
(35614902023)
2
ACKNOWLEDGEMENT
With gratitude and pleasure, we extend our heartfelt thanks to our esteemed guide, Dr.
Ravinder Singh whose valuable guidance, unwavering support, and cooperation made the
completion of the project, “InvenTree: Smart Inventory Management”, possible. His ex-
pertise and encouragement were instrumental in every step of this journey. We are also thank-
ful to the staff members of our college for providing us with the essential resources and a
supportive environment that facilitated our work. Lastly, we express our sincere appreciation
to everyone who contributed with their suggestions to improve the project. A special thanks
to our family for their encouragement and patience, and to the Almighty, whose blessings
Signature:
Aarushi Yadav
(01714902023)
Signature:
Maanik Khattar
(01814902023)
Signature:
Sambhav Makhija
(35614902023)
Signature:
Angad Singh Chhabra
(35814902023)
3
BONAFIDE CERTIFICATE
This is to certify that this project entitled "InvenTree: Smart Inventory Management” submit-
ted in the partial fulfilment of the degree of Bachelor of Computer Applications to the Guru
Gobind
guidance. The matter embodied in this project work has not been submitted earlier for award
Signature:
Maanik Khattar
(01814902023)
Signature:
Sambhav Makhija
(35814902023)
Signature:
Angad Singh Chhabra
(35614902023)
4
TABLE OF CONTENTS
1. SYNOPSIS ..............................................................................................................6
5. REFERENCES.......................................................................................................73
5
1. SYNOPSIS
In India, a vast majority of small-scale retailers and neighborhood kirana stores face signifi-
cant operational hurdles such as manual inventory tracking, recurring stockouts of essential
items, and heavy financial losses due to expired goods. Despite their critical role in the econ -
omy, these retailers often struggle with the complexity of modern POS systems, high costs of
enterprise software, and a lack of data-driven insights into consumer purchasing patterns.
Without accurate sales forecasting and real-time monitoring, store owners find themselves ei-
mand for high-velocity goods. This digital divide leaves them vulnerable to competition from
large organized retail chains, as they lack the tools to bridge the gap between their daily oper -
To address these pressing needs, the InvenTree Smart Inventory Management project was
conceptualized as a localized, AI-powered solution designed specifically for the Indian retail
landscape. InvenTree transforms raw sales data into actionable business intelligence. The sys-
tem acts as a virtual warehouse manager, providing 24/7 visibility into stock levels and au-
tomating the tedious process of inventory auditing. By integrating Natural Language Process-
ing (NLP), the platform allows non-technical users to query their business data through a
smart assistant, making complex analytics as simple as sending a text. Whether it’s identify-
ing which dairy products are nearing expiry or predicting next week's demand for grains, the
The main objectives of the project are to design an intelligent dashboard that simplifies stock
management, reduces wastage, and empowers small business owners with professional-grade
6
forecasting tools. Key features include an AI Business Assistant for instant data queries, Real-
time Notifications for low-stock and expiry alerts, and Automated Sales Forecasting that
identifies monthly and weekly trends. The system also supports Professional PDF Reporting,
allowing users to generate detailed inventory and sales summaries for financial auditing with
a single click. Through its intuitive interface, offline-first database approach, and AI-driven
recommendations, InvenTree ensures that high-tech retail tools become affordable and acces-
By democratizing access to artificial intelligence and data analytics, InvenTree empowers In-
dian retailers to minimize losses, maximize profits, and scale their businesses in a rapidly
7
2. MAIN REPORT
The InvenTree Smart Inventory Management System is designed to solve the common
inventory management problems faced by small retailers, kirana stores, grocery shops, and
medium-sized businesses in India. Traditional methods such as manual stock registers,
notebooks, and spreadsheets often lead to stock mismanagement, delayed updates, product
expiry losses, overstocking, understocking, and poor business decisions. These issues directly
affect profitability and customer satisfaction.
The system helps users manage products, monitor stock levels, track expiry dates, analyze
sales trends, and generate professional reports. One of the major goals is to provide intelligent
recommendations using Artificial Intelligence through the integration of the Google Gemini
API. This allows users to interact with the system using natural language queries such as
checking low-stock items, sales predictions, or expiry alerts without requiring technical
knowledge.
Another important objective is to reduce wastage caused by expired products and prevent
revenue loss due to stock shortages. The forecasting feature helps business owners plan
inventory purchases based on sales patterns, ensuring better financial management and
optimized stock investment.
The scope of the project includes frontend development using React and TypeScript for a
modern and responsive user interface, backend development using [Link] and [Link] for
handling server operations, SQLite for secure local database storage, and AI integration for
smart decision-making support.
The system is suitable for grocery stores, medical shops, dairy shops, wholesalers, and other
retail businesses that require daily stock monitoring. It supports report generation in PDF
format, interactive dashboards, graphical sales analysis, and notification systems for better
operational control.
Thus, InvenTree is not only an inventory management software but also a complete smart
business assistant that improves efficiency, saves time, reduces losses, and helps small
businesses compete in the modern digital market.
8
2.2. THEORETICAL BACKGROUND:
Inventory management is the process of ordering, storing, tracking, and controlling goods and
materials in a business. It ensures that the right products are available at the right time in the
right quantity. Effective inventory management helps businesses reduce operational costs,
avoid product shortages, and improve customer satisfaction.
Traditional inventory systems used by small retailers are mostly manual, where stock records
are maintained using registers, notebooks, or spreadsheets. These methods are time-
consuming, error-prone, and inefficient for handling real-time business operations. They do
not provide forecasting capabilities, expiry monitoring, or analytical insights.
Modern inventory management systems use digital platforms to automate stock updates,
monitor transactions, and generate reports. These systems improve accuracy and reduce
dependency on manual labor. However, many enterprise-level solutions are expensive and
too complex for small businesses.
The concept behind InvenTree is based on combining inventory management with Artificial
Intelligence and data analytics. AI helps transform raw business data into meaningful insights
that support better decision-making. By analyzing sales patterns and stock movement, the
system can forecast future demand, detect unusual trends, and recommend actions.
Natural Language Processing (NLP) plays a major role in this project through the AI
Business Assistant. NLP enables users to communicate with the system using simple human
language instead of technical commands. For example, users can ask questions like “Which
products are low in stock?” or “Show sales prediction for next week,” and receive instant
responses.
The frontend of the project is built using React, which supports Single Page Application
(SPA) architecture for faster performance and better user experience. TypeScript improves
code reliability and maintainability. Tailwind CSS is used for responsive and efficient styling.
The backend uses [Link] with [Link] to handle API requests, user operations, and
system logic. SQLite is selected as the database because it is lightweight, fast, offline-first,
and suitable for local business applications without requiring expensive server infrastructure.
Data visualization using Recharts helps users understand inventory performance through
charts and graphs. PDF reporting tools such as jsPDF and jsPDF-AutoTable provide
professional business reports for auditing and financial review.
Therefore, the theoretical foundation of InvenTree lies in inventory control systems, database
management, artificial intelligence, forecasting techniques, natural language processing, and
full-stack web application development.
9
2.3. SYSTEM ANALYSIS AND DESIGN:
Small retailers often face difficulties in maintaining proper inventory records due to
dependence on manual systems. Common problems include:
Users of the system mainly include shop owners, store managers, and inventory staff. Their
expectations from the system are:
The system must be simple enough for non-technical users while providing advanced
business intelligence.
10
Functional Requirements
• Product Management
Add, update, delete, and search products.
• Inventory Tracking
Monitor stock quantity, stock movement, and product availability.
• Expiry Management
Identify products nearing expiry and generate alerts.
• Low-Stock Notifications
Notify users when stock reaches below minimum threshold.
• Sales Recording
Store and manage sales transaction data.
• Sales Forecasting
Predict future demand based on historical sales patterns.
• AI Business Assistant
Answer inventory-related questions using Gemini AI integration.
• Dashboard Analytics
Display charts, graphs, and summary cards for quick insights.
• PDF Report Generation
Export inventory and sales reports in professional PDF format.
• User-Friendly Interface
Provide easy navigation and responsive design.
Non-Functional Requirements
• Performance
Fast loading speed and quick data retrieval.
• Reliability
Accurate data storage and stable system operations.
• Security
Safe handling of inventory and sales records.
• Scalability
Ability to manage increasing products and transactions.
• Usability
Simple interface for users with limited technical knowledge.
• Maintainability
Easy to update and improve system features.
11
• Compatibility
Smooth functioning across desktop and modern browsers.
• Availability
System should work efficiently even in offline-first environments.
System design defines how the system will be structured and how different components
interact to perform required operations.
• System Architecture:
Functions:
• User interface
• Dashboard display
• Forms for inventory management
• Charts and reports
• AI assistant interaction
•
2. Application Layer (Backend)
Functions:
Functions:
• Product storage
• Sales records
• Inventory history
12
• Forecasting data
• System reports
This architecture ensures modularity, maintainability, and efficient
performance.
• DFD:
Level 0 DFD
Processes:
• Manage Inventory
• Generate Reports
• AI Query Processing
• Forecast Sales
Data Store:
• Product Database
• Sales Database
Flow:
User →
Inventory
Input → System → Database
Database → Processed Information → User
13
• Use Case Diagram:
Actors:
• Admin
• Store Owner
• Inventory Staff
Use Cases:
• Login
• Add Product
• Update Product
• Delete Product
• Check Stock
• Receive Notifications
• View Dashboard
• Generate
PDF
Report
• Ask AI
Assistant
• View Sales Forecast
All actors interact with the central inventory management system according to permissions.
14
Figure 2: Use Case Diagram of the Model
• Activity Diagram:
Process Flow:
Start
↓
User Login
↓
Dashboard Access
↓
Choose Operation
↓
Manage Inventory / Check Forecast / Generate Report / Ask AI
↓
System Processes Request
↓
Display Results
↓
Logout
↓
End
15
Figure 3: Activity Diagram of the Model
• Sequence Diagram:
16
Figure 4: Sequence Diagram of the Model
17
2.4. SYSTEM PLANNING:
The first phase involved understanding the needs of users who frequently face legal issues re-
lated to tenancy, consumer rights, workplace disputes, traffic laws, and cybercrime. The anal-
ysis identified the essential system features such as natural-language query handling, step-by-
step legal guidance, citation of applicable laws, and generation of legal document templates.
This stage also reviewed user expectations, including easy accessibility, clarity of responses,
and 24/7 availability. The legal domains to be covered and the procedures to be supported
Relevant legal information was collected from verified sources such as government websites,
legal acts, public legal resources, and existing online complaint portals. This includes sec-
tions from applicable Indian laws, helpline numbers, procedures for filing complaints, and
formats of commonly used legal documents. Additionally, frequently asked legal questions
from online legal forums were analyzed to understand common user issues. This assembled
The collected data was cleaned, simplified, and organized to ensure consistent and accurate
responses. Complex legal language was rewritten in simple, citizen-friendly terms so users
can understand their rights without difficulty. Duplicate or outdated information was re-
moved, and laws were arranged into categories like tenancy, cybercrime, workplace issues,
etc. The information was then structured into prompt formats suitable for the pre-trained NLP
18
models used through the API. Preprocessing ensures that the chatbot provides accurate and
Since the system uses pre-trained models through the Hugging Face API, no model training
was required. Instead, detailed prompt engineering was performed to instruct the AI model to
behave as an expert Indian legal advisor. The system prompt was designed to enforce rules
such as summarizing the user's problem, citing laws, providing documents, and giving step-
by-step guidance. Multiple prompts were tested with real-world questions to ensure clarity,
accuracy, and consistency. This phase ensures that the AI produces high-quality legal an-
The user interface of the chatbot was developed using Streamlit to provide a clean and inter-
active experience. Custom CSS was added to create a professional legal theme. Features such
as chat display boxes, conversation history, example questions, emergency helplines, and
message formatting were developed. The interface was intentionally designed to be simple so
that even users with minimal technical skill can access legal guidance easily.
The chatbot system was integrated with the Hugging Face InferenceClient API to generate
real-time responses based on user messages. Environment variables were used to secure the
through an SQLite database, allowing each message—user and assistant—to be stored along
with timestamps and user roles. This enables viewing chat history and supports future en-
hancements such as exporting or sharing conversations. The integration ensures smooth inter-
19
2.4.7. Testing and Debugging:
Comprehensive testing was performed to verify the chatbot's accuracy, interface usability,
and error handling. Functional testing ensured correct responses across all legal categories.
Scenario testing checked how the chatbot responds to vague or incomplete queries. Interface
testing verified that text formatting, buttons, scroll areas, and warnings displayed correctly.
Bugs identified during testing were fixed, and prompts were refined to improve accuracy.
A PERT (Program Evaluation and Review Technique) chart was created to visualize the se-
quence of development activities, dependencies, and critical path of the Legal Advice Chat-
bot project. It helped plan execution flow from requirement gathering to deployment, identify
necessary parallel tasks, and minimize project delays. The chart represents major phases in-
cluding requirement analysis, data preparation, UI creation, AI integration, database setup us-
20
ment (Streamlit + interface
CSS)
21
2.5. METHODOLOGY:
The methodology adopted for the development of the AI-powered Legal Advice Chatbot fol-
lows a systematic and iterative approach to ensure accuracy, usability, and effective legal as-
sistance. The process is divided into several structured steps that guide the development from
conceptualization to deployment.
The first step involved gathering relevant and authentic legal information from official and
publicly available sources. This included Indian laws such as the Consumer Protection Act,
Rent Control Acts, Motor Vehicles Act, IT Act, labour laws, and family law guidelines. Ad-
ditional resources such as government helplines, complaint procedures, legal templates, and
FAQs were collected to build a strong and reliable knowledge base. Common citizen ques-
tions were also studied from online legal forums to understand real-world user needs.
After collecting the information, the data underwent preprocessing to ensure clarity and con-
sistency. This process included simplifying legal language into easy, understandable terms
and organizing the content into different legal categories such as tenancy, consumer com-
plaints, workplace issues, traffic laws, and cybercrime. Outdated information was removed,
and all content was structured into prompt-friendly formats. Sample responses, templates, and
conversational examples were cleaned and refined to help the chatbot generate clear and ac-
curate answers.
Since the system uses pre-trained models (such as DeepSeek and Qwen) through API calls,
no model training was required. Instead, prompt engineering formed the core methodology
22
for generating accurate legal responses. A detailed system prompt was designed that instructs
the AI on how to behave like an Indian legal advisor, what laws to cite, how to present infor-
mation, and how to maintain conversation context. Various prompt formats were tested and
refined to ensure step-by-step guidance, accuracy of laws, question summarization, and clar-
ity of explanation. This step ensures that the chatbot behaves consistently and provides high-
The web interface of the chatbot was developed using Streamlit, chosen for its simplicity and
ability to create interactive UI elements. Custom CSS was applied to create a professional
and visually appealing legal theme. Features such as chat history display, message format-
ting, legal categories in the sidebar, emergency helplines, and conversation clearing were im-
plemented. The interface was designed to be intuitive, enabling users to ask questions effort-
To enable chat history storage and retrieval, SQLite database integration was implemented.
A database named chat_history.db was created, and a table was designed to store role-based
conversations (user / assistant) along with timestamps. The datetime library with Asia/
Kolkata timezone was used to save and convert timestamps into IST format. Every message
sent or generated is automatically inserted into the database. The “Show Chat History” side -
bar feature allows users to view previous messages stored in SQLite. This ensures persistent
and organized conversation records for legal tracking and project demonstration.
2.5.5. Integration:
23
Once the system prompt and interface were ready, the chatbot was integrated with the Hug -
ging Face Inference API using the InferenceClient. API tokens were securely stored using en-
vironment variables. Each user query is sent to the selected AI model along with the conver-
sation history, and the model-generated response is displayed on the interface. Multiple fall-
back models were configured to ensure uninterrupted functioning even if one model becomes
unavailable. Error handling mechanisms were added to manage failures, slow responses, or
connectivity issues.
Extensive testing was conducted to ensure the chatbot delivers accurate and reliable legal as-
sistance. Functional testing checked whether the chatbot correctly responded to questions
across different legal domains. Scenario testing evaluated its performance with incomplete,
unclear, or multi-step questions. Usability testing ensured that the interface is simple, read-
able, and beginner-friendly. The chatbot was evaluated based on accuracy of legal informa-
tion, clarity of stepwise guidance, response speed, and overall user experience. Improvements
were made based on test results to refine prompts, enhance context retention, and ensure con-
sistent performance.
24
2.6. SYSTEM IMPLEMENTATION:
The implementation of the AI-powered Legal Advice Chatbot consists of multiple compo-
nents, including the front-end user interface, the integration with pre-trained AI models
through APIs, and the backend logic that manages conversation flow and data processing.
Each layer is designed to ensure that users receive accurate, easy-to-understand, and timely
legal guidance. The system focuses on accessibility, simplicity, and high responsiveness so
that even individuals with no legal background can interact with it easily.
The front-end implementation focuses on creating a clean, professional, and user-friendly in-
terface that allows users to ask legal questions and receive AI-generated responses smoothly.
The chatbot interface was built using Streamlit, supported by custom HTML and CSS ele-
Technologies Used:
1. Streamlit
Streamlit serves as the primary framework for building the interactive web interface. It han-
dles UI components such as chat messages, input fields, sidebars, buttons, containers, and
organized structure. It provides built-in components like st.chat_input, [Link], and [Link] to
2. HTML Components
25
HTML structures inside [Link]() were used to create formatted chat bubbles, headings,
badges, and custom sections like emergency helplines and coverage areas. HTML helps de-
fine the layout of user messages and assistant messages, improving readability and visual
flow.
Custom CSS embedded through [Link]() enhances the visual appeal of the interface. CSS
is used to:
guidance platform.
· Chat history
· Conversation context
tion.
The combination of Streamlit + HTML + CSS creates a responsive, clean, and modern UI
26
2.6.2. AI Model Integration
Unlike systems that train their own model, this chatbot uses pre-trained Large Language
Models hosted on Hugging Face, accessed through the InferenceClient API. This ensures
high accuracy and advanced language understanding without requiring training or maintain-
ing ML infrastructure.
Key Components:
to connect to multiple LLMs. These models are selected based on availability and perfor-
mance, including:
· DeepSeek V3
· Qwen2.5 Instruct
Environment variables were used to securely store the Hugging Face API key:
27
This prevents hardcoding sensitive credentials in the code.
· No training
· No datasets
· No CNNs
· No TensorFlow
Instead, a highly detailed system prompt is engineered to guide the model's behavior.
· Cite laws
st.session_state.conversation_history
28
2.6.3. Backend Implementation
The backend controls the core logical flow between the UI, AI, and database.
Python manages:
· Input processing
· Database interaction
The chatbot uses SQLite for storing and retrieving chat history. A database file chat_histo-
· role (user/assistant)
· message (content)
Table creation:
role TEXT,
message TEXT,
timestamp TEXT
29
Saving data to DB
save_message("user", user_input)
save_message("assistant", answer)
Display history
Step-by-step processing:
30
31
2.7. HARDWARE & SOFTWARE USED:
• RAM: 8.00 GB
o Streamlit: A Python-based web framework used to design and deploy the ap-
plication's user interface, including chat layout, buttons, and interactive com-
ponents.
o Python: The primary programming language used for backend logic, API
with and generate responses from large language models hosted on Hugging-
Face Hub.
o SQLite3: A lightweight relational database used to store and retrieve chat his-
32
o Datetime / Timezone Libraries: Used for generating accurate timestamps
and converting them to IST (Indian Standard Time) for chat storage and dis-
play.
33
2.8. SYSTEM EVALUATION
The AI-powered Legal Advice Chatbot was evaluated based on functional performance,
response quality, interface usability, and database efficiency, rather than classification
metrics, since the system does not involve model training or dataset-based classification. The
and legal usefulness of the chatbot for Indian citizens seeking legal guidance.
· Accuracy:
Accuracy measures the proportion of correct predictions made by the model across all
it may not always be reliable for imbalanced datasets. Correct predictions include
True Positives (TP) and True Negatives (TN), while total predictions consist of TP,
It is calculated as:
· Precision:
Precision evaluates the model’s ability to correctly identify only positive instances.
High precision indicates that when the model predicts a positive class, it is more
likely to be correct. It is computed as the ratio of True Positives to the sum of True
34
· Recall (Sensitivity):
Recall measures the model's ability to identify all actual positive instances in the
dataset. High recall ensures that most positive samples are correctly detected, reduc-
· F1-Score:
The F1-score is the harmonic mean of precision and recall. It provides a balanced
measure, especially useful when dealing with imbalanced classes. A high F1-score in-
dicates a good balance between precision and recall, making the model reliable for
classification tasks.
2.8.2. Results:
The evaluation results demonstrate that the chatbot performs effectively as a legal guidance
tool:
· High accuracy and relevance of legal responses across multiple categories (tenancy,
chats
35
User feedback indicated that the platform provides helpful, structured legal instructions and
makes legal information easy to understand without technical or legal expertise. The ability to
Overall, the evaluation confirms that the developed system is efficient, responsive, and ready
for practical deployment. It successfully meets its objectives of offering accessible, step-by-
step legal support, with opportunities for future enhancement such as multilingual support,
[Link]
36
import streamlit as st
import os
import sqlite3
conn = [Link]("chat_history.db",
check_same_thread=False)
cursor = [Link]()
try:
KOLKATA = ZoneInfo("Asia/Kolkata")
except Exception:
import pytz
KOLKATA = [Link]("Asia/Kolkata")
[Link]("""
role TEXT,
37
message TEXT,
timestamp TEXT
""")
[Link]()
try:
now_ist = [Link](KOLKATA)
except Exception:
now_ist =
[Link]([Link]).astimezone(KOLKATA)
[Link](
[Link]()
38
# Robust parser to convert stored timestamps to IST display
format
def parse_to_ist(ts_str):
"""
"""
if not ts_str:
return ""
+0530"
try:
ts_str.strip()[-5:].lstrip("-").isdigit()):
%z")
ist_dt = [Link](KOLKATA)
39
except Exception:
pass
try:
dt = [Link](tzinfo=[Link])
ist_dt = [Link](KOLKATA)
except Exception:
pass
try:
dt = [Link](ts_str)
if [Link] is None:
dt = [Link](tzinfo=[Link])
ist_dt = [Link](KOLKATA)
except Exception:
pass
40
load_dotenv()
HFTOKEN= [Link]("HFTOKEN")
# Page configuration
st.set_page_config(
page_icon="⚖️",
layout="centered"
[Link]("""
<style>
width: 100%;
background-color: #1e3a8a;
color: white;
font-weight: bold;
border-radius: 8px;
41
padding: 0.7rem;
font-size: 1.1rem;
background-color: #1e40af;
.error-box {
background-color: #fef2f2;
padding: 1.5rem;
border-radius: 10px;
.disclaimer-box {
background-color: #fffbeb;
padding: 1.2rem;
border-radius: 8px;
margin: 1.5rem 0;
42
font-size: 0.9rem;
.category-badge {
display: inline-block;
background: #9D9D9D;
color: black;
border-radius: 15px;
font-size: 0.85rem;
margin: 0.2rem;
font-weight: 600;
width: 180px;
display:flex;
text-align: center;
43
background-color: rgba(16, 163, 127, 0.35) !important; /*
transparent #10A37F */
[Link] {
44
.main-header {
text-align: center;
color: #1e3a8a;
padding: 1rem 0;
font-size: 2.5rem;
font-weight: 700;
.sub-header {
text-align: center;
color: #D8D0D0;
font-size: 1.2rem;
margin-bottom: 2rem;
line-height: 1.6;
.chat-wrapper {
max-width: 800px;
margin: 0 auto;
background: #10A37F;
padding: 10px;
45
}
.message {
margin: 10px 0;
border-radius: 14px;
font-size: 1.05rem;
line-height: 1.5;
max-width: 80%;
.user {
margin-left: auto;
background: #10A37F;
color: black;
46
.assistant {
margin-right: auto;
background: #9D9D9D;
color: black;
.avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background: #e5e5e5;
display: inline-block;
margin-right: 8px;
.message-row {
display: flex;
47
align-items: flex-start;
margin-top: 18px;
.message-text {
flex: 1;
</style>
""", unsafe_allow_html=True)
st.session_state.messages = []
st.session_state.conversation_history = []
# Header
Bot</h1>", unsafe_allow_html=True)
48
[Link]("<p class='sub-header'>Free AI-Powered Legal
laws</p>", unsafe_allow_html=True)
# Sidebar
with [Link]:
[Link]("""
<div class='sidebar-info'>
</div>
""", unsafe_allow_html=True)
[Link]("")
49
[Link]("""
- **Police:** 100
""")
st.session_state.messages = []
st.session_state.conversation_history = []
[Link]()
chat_container = [Link]()
with chat_container:
if message["role"] == "user":
[Link](f"""
50
<div class="message-row" style="justify-content:
flex-end;">
{message['content']}
</div>
</div>
""", unsafe_allow_html=True)
else:
[Link](f"""
flex-start;">
{message['content']}
</div>
</div>
""", unsafe_allow_html=True)
# Chat input
51
[Link]("---")
press Enter...")
if user_input:
st.session_state.[Link]({"role": "user",
"content": user_input})
try:
client = InferenceClient(token=HFTOKEN)
conversation_context = ""
if len(st.session_state.conversation_history) > 0:
52
conversation_context = "\n\n**PREVIOUS
CONVERSATION CONTEXT:**\n"
for msg in
st.session_state.conversation_history[-6:]: # Last 3
exchanges
conversation_context +=
f"{msg['role'].upper()}: {msg['content']}\n"
conversation context
citizens.
**CRITICAL INSTRUCTIONS:**
understand
applicable
53
4. Provide step-by-step actionable guidance
user
**SCOPE OF EXPERTISE:**
54
{conversation_context}
{user_input}
follow-ups):**
just respond with the summary first and follow the rest dont
**Applicable Laws:**
[List the relevant Indian laws, acts, and sections that apply
to this situation]
[Clearly explain what rights the user has under Indian law]
55
**Step-by-Step Action Plan:**
**Required Documents:**
**Where to File/Approach:**
should be taken]
56
**Estimated Costs:**
if applicable]
**Important Deadlines:**
requirements]
application if relevant]
**Important Warnings:**
57
[Any pitfalls to avoid or critical considerations]
**Recommendation:**
---
**SPECIAL HANDLING:**
58
- If information is insufficient: Ask specific clarifying
questions
system_prompt}]
models_to_try = [
"deepseek-ai/DeepSeek-V3-0324",
"Qwen/Qwen2.5-7B-Instruct",
"meta-llama/Llama-3.2-3B-Instruct",
success = False
try:
59
response = client.chat_completion(
messages=messages,
model=model,
max_tokens=2500,
answer =
[Link][0].[Link]
success = True
st.session_state.[Link]({"role":
st.session_state.conversation_history.append({"role": "user",
"content": user_input})
save_message("user", user_input)
60
st.session_state.conversation_history.append({"role":
save_message("assistant", answer)
[Link]()
break
except Exception as e:
continue
if not success:
your question."
st.session_state.[Link]({"role":
[Link]()
except Exception as e:
[:100]}"
st.session_state.[Link]({"role":
61
[Link]()
if len(st.session_state.messages) == 0:
[Link]("""
begin!
""")
# Footer
62
Project Interface
63
Project Working
64
65
66
4. CONCLUSION AND FUTURE SCOPE
4.1 Conclusion
The LawPilot project successfully demonstrates the potential of artificial intelligence to rev-
olutionize the legal consulting domain. By integrating a user-friendly interface with a legal
knowledge base (implemented via [Link]), the project achieves the following:
· Democratization of Law: It bridges the gap between complex legal terminology and
the common user, making legal information more accessible and affordable to the
general public.
answer queries regarding rights, laws (e.g., IPC sections), and legal procedures.
· Initial Guidance: While not a replacement for a human lawyer, it effectively handles
preliminary legal inquiries, allowing users to understand their situation before seeking
professional counsel.
· Efficiency: It reduces the time and effort required for basic legal research, benefiting
The project has significant potential for expansion and technical enhancement. The following
67
1. Integration of Large Language Models (LLMs):
LLMs (like GPT) can improve the bot's ability to understand context, handle
o The system can be upgraded to assist users in drafting legal documents such
questionnaire.
o It could also offer automated review services for simple contracts (e.g., NDAs)
3. Multilingual Support:
tongue.
4. Voice-Enabled Interaction:
o The platform can be expanded to include a robust booking and referral sys-
tem, connecting users directly with specialized lawyers (Criminal, Civil, Cor-
68
6. Jurisdictional Expansion:
o Currently focused on specific laws (e.g., Indian Penal Code), the knowledge
69
5. REFERENCES
Python documentation.
2. OpenAI – Natural Language Processing Models (if used for legal text processing)
3. spaCy – Industrial-strength NLP Library in Python (if used/required for future de-
velopment)
70