A complete, working AI chatbot web application you can run, extend and submit: user registration and login, multiple saved conversations per user, real conversation memory, a history page, and an AI model that runs on your own PC for free. It comes with everything the project report needs — database schema, ER diagram, an SRS outline, a test plan and 25 viva questions with answers.
Most “AI chatbot project” pages give you 30 lines that forget the previous message and have no database. Evaluators notice. This one is built the way a real app is built, and every design decision is explained so you can defend it in the viva.
github.com/techprofree/ai-chatbot-final-year-project
Project overview
| Item | Details |
|---|---|
| Project title | AI Chatbot Web Application with User Accounts and Conversation History |
| Type | Web application (full stack) — suitable for BS/BSc CS, SE, IT final year or semester project |
| Language | Python 3.9+ |
| Backend | Flask |
| Database | SQLite (3 tables) |
| AI model | Llama 3.2 running locally via Ollama — no API key, no cost |
| Frontend | HTML, CSS, vanilla JavaScript |
| Hardware | Any laptop with 8 GB RAM; no GPU needed |
[SCREENSHOT: the chat screen with a few messages — alt text: “AI chatbot final year project chat interface built with Flask”]
Features
- Register / login / logout — passwords stored as salted hashes, never plain text
- Multiple conversations per user, auto-titled from the first message
- Memory — the model receives the previous messages, so “what did I just ask?” works
- History page with message counts and delete
- Data isolation — users can’t open each other’s conversations
- Typing indicator, Enter-to-send, responsive layout
- Clear error handling when the model server is down
System architecture
Three layers. The browser talks only to Flask; Flask talks to SQLite for data and to Ollama for answers. Ollama is a separate program running on the same computer, listening on port 11434.
Browser (HTML/JS)
│ HTTP / JSON
▼
Flask app (app.py) ──── SQLite (chatbot.db)
│ HTTP (localhost:11434)
▼
Ollama → llama3.2 modelDatabase design (ER diagram)
Three tables with two one-to-many relationships. A user owns many conversations; a conversation contains many messages; each message is either from the user or the assistant.
[IMAGE: insert docs/er-diagram.svg here — alt text: “ER diagram for AI chatbot project: users, conversations, messages”]
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title TEXT NOT NULL DEFAULT 'New chat',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);Two things worth saying in your report: ON DELETE CASCADE means deleting a conversation automatically removes its messages, and the CHECK constraint on role stops bad data getting in at the database level, not just in Python.
Step 1 — Set up
You need Python and Ollama. If Ollama is new to you, do the 10-minute setup guide first.
$ git clone https://github.com/techprofree/ai-chatbot-final-year-project.git
$ cd ai-chatbot-final-year-project
$ pip install -r requirements.txt
$ ollama pull llama3.2
$ python app.pyOpen http://localhost:5000, register an account, and start chatting. The database file chatbot.db is created automatically on first run.
[SCREENSHOT: register page — alt text: “Registration page of the Flask AI chatbot project”]
Step 2 — Project structure
ai-chatbot-final-year-project/
├── app.py # Flask app: routes, auth, chat API (≈170 lines)
├── schema.sql # database tables
├── requirements.txt # flask, ollama
├── templates/
│ ├── base.html # shared layout and CSS
│ ├── login.html
│ ├── register.html
│ ├── chat.html # chat UI + JavaScript
│ └── history.html
└── docs/
├── er-diagram.svg
├── srs-outline.md # report outline
└── viva-questions.mdStep 3 — How the backend works (app.py)
The full file is on GitHub; here are the four parts an evaluator will ask about.
Database connection per request
def get_db():
if "db" not in g:
g.db = sqlite3.connect(DB_PATH)
g.db.row_factory = sqlite3.Row # rows behave like dicts
g.db.execute("PRAGMA foreign_keys = ON")
return g.db
@app.teardown_appcontext
def close_db(_exc):
db = g.pop("db", None)
if db is not None:
db.close()One connection per request, closed automatically. SQLite doesn’t enforce foreign keys unless you turn them on — that PRAGMA line is what makes the cascade delete actually work.
Login with hashed passwords
from werkzeug.security import generate_password_hash, check_password_hash
# on register
get_db().execute(
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, generate_password_hash(password)),
)
# on login
if user and check_password_hash(user["password_hash"], request.form["password"]):
session.clear()
session["user_id"] = user["id"]
# protect a route
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
if "user_id" not in session:
return redirect(url_for("login"))
return view(*args, **kwargs)
return wrappedViva question you will get: “how are passwords stored?” Answer: salted and hashed by Werkzeug; the plain password is never written anywhere. Second question: “what stops SQL injection?” Answer: every query uses ? placeholders.
The chat API — where memory happens
@app.route("/api/chat/<int:conv_id>", methods=["POST"])
@login_required
def api_chat(conv_id):
db = get_db()
conv = db.execute(
"SELECT * FROM conversations WHERE id = ? AND user_id = ?", (conv_id, session["user_id"])
).fetchone()
if conv is None:
return jsonify({"error": "conversation not found"}), 404
user_text = (request.get_json(silent=True) or {}).get("message", "").strip()
if not user_text:
return jsonify({"error": "empty message"}), 400
# 1. save the user's message
db.execute("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'user', ?)",
(conv_id, user_text))
# 2. load recent history so the model remembers the conversation
rows = db.execute(
"SELECT role, content FROM messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?",
(conv_id, MEMORY_LIMIT),
).fetchall()
history = [{"role": r["role"], "content": r["content"]} for r in reversed(rows)]
# 3. ask the local model
try:
response = ollama.chat(model=MODEL,
messages=[{"role": "system", "content": SYSTEM_PROMPT}] + history)
reply = response["message"]["content"]
except Exception as e:
db.rollback()
return jsonify({"error": f"Ollama error: {e}"}), 500
# 4. save the reply; title the conversation after the first message
db.execute("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'assistant', ?)",
(conv_id, reply))
if conv["title"] == "New chat":
db.execute("UPDATE conversations SET title = ? WHERE id = ?", (user_text[:40], conv_id))
db.commit()
return jsonify({"reply": reply})This is the heart of the project and the part to walk through slowly in your presentation. The model has no memory of its own — step 2 is what gives the chatbot memory: the last 20 messages are read from the database and sent with every request. The AND user_id = ? on the first query is what stops one user reading another’s chat.
[SCREENSHOT: memory test — “My name is Ali” then “What is my name?” with the correct answer — alt text: “Chatbot remembering the user’s name across messages”]
[YOUR TEST: one sentence on how long the reply took on your laptop.]
The frontend (chat.html)
async function send() {
const text = input.value.trim();
if (!text) return;
add(text, "user");
input.value = "";
btn.disabled = true;
const typing = add("AI is typing...", "assistant");
try {
const res = await fetch("/api/chat/{{ conv.id }}", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text })
});
const data = await res.json();
typing.textContent = data.reply || ("Error: " + data.error);
} catch (e) {
typing.textContent = "Error: could not reach the server.";
}
btn.disabled = false;
}Plain fetch, no framework. The “AI is typing…” bubble is created immediately and then replaced with the reply, which is why the page never reloads.
[SCREENSHOT: history page — alt text: “Conversation history page with delete buttons”]
Routes summary (for the report)
| URL | Method | Purpose |
|---|---|---|
/register | GET, POST | Create account |
/login / /logout | GET, POST | Session login/logout |
/ | GET | Redirect to latest conversation |
/new | GET | Create a conversation |
/chat/<id> | GET | Chat page |
/api/chat/<id> | POST | Send message, get reply (JSON) |
/history | GET | List conversations |
/delete/<id> | POST | Delete a conversation |
Test plan
| Test | Input | Expected result |
|---|---|---|
| Duplicate username | Register an existing name | “That username is taken” |
| Wrong password | Login with bad password | “Wrong username or password” |
| Protected page | Open / logged out | Redirect to /login |
| Memory | “My name is Ali” → “What is my name?” | Reply contains “Ali” |
| Isolation | Open another user’s /chat/<id> | 404 |
| Empty message | POST with blank text | 400 error |
| Model down | Stop Ollama, send a message | Readable error in the chat |
All seven pass on the code in the repo. Put screenshots of each in the Testing chapter — evaluators like evidence more than claims.
Report structure (SRS outline)
The repo’s docs/srs-outline.md has a full chapter-by-chapter outline: introduction, scope, functional requirements (FR-1 to FR-9), non-functional requirements, architecture, ER diagram, data dictionary, sequence diagram, implementation, testing, results, limitations and future scope. Fill it in with your own words and the screenshots above and the report writes itself.
Viva questions you will be asked
Twenty-five questions with answers are in docs/viva-questions.md. The five that come up most:
- How does the chatbot remember earlier messages? — The model has no memory; the last 20 messages are loaded from the database and sent with every request.
- Why run the model locally? — No cost, no API key, works offline, and user data never leaves the machine.
- How are passwords stored? — Salted hashes via Werkzeug; plain text is never written.
- What prevents SQL injection? — Parameterised queries with
?placeholders everywhere. - What are the limitations? — Answer quality depends on a small local model; no streaming; single server; no admin role.
Extensions for extra marks
- Streaming replies — pass
stream=Truetoollama.chatand send chunks with Flask’s streaming response; the “typing” effect becomes real. - Chat with a PDF — add an upload page and the pipeline from the RAG tutorial. This alone turns it into a “document assistant” project.
- Tools — let the bot calculate or search files using the AI agent tutorial.
- Admin dashboard — user count, message count, most active users; one more table (
roles) and two routes. - Deployment — run under Waitress on Windows or Gunicorn on Linux, set a real
secret_key.
Common errors and fixes
jinja2.exceptions.TemplateNotFound: chat.html
The templates folder isn’t next to app.py, or you ran Python from a different folder. cd into the project folder and run python app.py there.
Ollama error: Connection refused
Ollama isn’t running. Start it from the Start menu (look for the tray icon) or run ollama serve. Details in the Ollama errors guide.
model ‘llama3.2’ not found
Run ollama pull llama3.2, or change MODEL in app.py to a model you already have (ollama list).
sqlite3.OperationalError: no such table: users
The database wasn’t initialised — init_db() runs only when you start with python app.py. If you ran it another way (e.g. flask run), delete chatbot.db and start with python app.py once.
Address already in use / port 5000
Another app is on port 5000. Change the last line to app.run(debug=True, port=5001).
Replies are very slow
Normal on CPU for the first message (the model loads into RAM); later messages are faster. If every reply is slow, close heavy apps or use a smaller model such as qwen3:4b. Lower MEMORY_LIMIT if conversations get long.
Changes to HTML don’t show
Hard-refresh the browser (Ctrl+F5). With debug=True Flask reloads templates, but the browser may cache the old page.
Yes, if it’s a real application rather than a demo. This version has authentication, a relational database, a JSON API, conversation memory and a documented design — enough to be assessed as a full-stack project, with the AI as one component.
No. The model runs locally through Ollama, which is free. The whole project works offline once the model is downloaded.
Yes. Llama 3.2 (3B) runs on 8 GB RAM on CPU; replies take a few seconds. For faster answers on the same hardware, use qwen3:4b; with 16 GB you can use an 8B model for better answers.
Yes — the schema is standard SQL. Replace sqlite3 with a MySQL connector and change the placeholders from ? to %s. SQLite is used here because it needs zero setup for the demo.
Demo the flow live (register → chat → ask a follow-up to show memory → history), then walk through the ER diagram and the api_chat function. Keep the model small so the demo doesn’t stall.
Voice input is a browser feature (Web Speech API) and needs only JavaScript. WhatsApp needs the Business API or a third-party gateway — possible, but keep it as “future scope” unless you have time.



