Project Overview
This chatbot is built for college-level demonstration but designed like a real mini-product: clean folder structure, editable dataset, confidence threshold, and logs for debugging. You can extend it into a web chatbot later.
Key Features
- Intent-based replies using patterns and responses from JSON
- Smart fallback using TF-IDF similarity (no heavy deep learning required)
- Configurable confidence threshold to reduce wrong answers
- Easy customization: add new intents without changing code
- Conversation loop with exit commands
Project tutorials, coding guides & placement tips for students.
Why this project is new
Most “chatbot projects” online are either only rule-based (fails on real user typing), or they jump straight to deep learning (heavy setup, slow, not easy for viva). This project is new in the sense that it stays lightweight but still feels intelligent: it combines intent matching with a similarity fallback so even if a user writes a sentence differently, the bot can still respond in a relevant way. Also, your dataset remains 100% in your control, so it is safer for demos.
Architecture (How it works)
- Load intents.json (tags, patterns, responses).
- Preprocess patterns and build a TF-IDF vectorizer.
- User message is vectorized and compared with all patterns.
- If similarity score ≥ threshold → reply from matched intent.
- Else → fallback response (ask rephrase / show help).


Feature Table
| Module / Feature | What it does | Why it matters |
|---|---|---|
| Intents JSON | Stores tags, patterns, responses | Easy to edit without coding |
| TF-IDF Similarity | Finds closest pattern to user input | Handles variations in text |
| Confidence Threshold | Rejects weak matches | Reduces wrong replies, improves trust |
| Logging | Prints matched tag + similarity score | Helps in viva + debugging |
Folder Structure
chat-bot/
├─ chatbot.py
├─ intents.json
├─ requirements.txt
└─ README.md
Source Code
1) intents.json
Customize this dataset as you want. Add more intents for your domain (college, banking, shopping, etc.).
{
"intents": [
{
"tag": "greeting",
"patterns": ["hi", "hello", "hey", "good morning", "good evening"],
"responses": ["Hello! How can I help you?", "Hi there, tell me what you need.", "Hey! What's up?"]
},
{
"tag": "about",
"patterns": ["what is this project", "tell me about this chatbot", "project overview"],
"responses": ["This is a Python chatbot using intents + similarity fallback.", "It is a lightweight chatbot built for fast demos."]
},
{
"tag": "features",
"patterns": ["what are the features", "features of chatbot", "what can you do"],
"responses": ["I can answer based on intents.json and also handle similar sentences using TF-IDF.", "I support intents, thresholding, and safe fallback responses."]
},
{
"tag": "exit",
"patterns": ["bye", "exit", "quit", "goodbye"],
"responses": ["Bye! Take care.", "Goodbye. See you again.", "Exiting. Have a nice day."]
}
],
"fallback_responses": [
"I didn't understand that clearly. Can you rephrase it?",
"I am not sure about that. Try asking in a simpler way.",
"Sorry, I don't have an answer for this yet. You can add it in intents.json."
]
}
2) requirements.txt
scikit-learn==1.5.2
3) chatbot.py
import json
import random
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
@dataclass
class Intent:
tag: str
patterns: List[str]
responses: List[str]
class ChatBot:
def __init__(self, intents_path: str, threshold: float = 0.35, debug: bool = True):
self.intents_path = Path(intents_path)
self.threshold = float(threshold)
self.debug = bool(debug)
self.intents: List[Intent] = []
self.fallback_responses: List[str] = []
# Flattened patterns store (pattern_text, tag)
self.pattern_index: List[Tuple[str, str]] = []
# ML components
self.vectorizer = TfidfVectorizer(lowercase=True, stop_words=None)
self.pattern_matrix = None
self._load_intents()
self._build_index()
def _load_intents(self) -> None:
if not self.intents_path.exists():
raise FileNotFoundError(f"intents file not found: {self.intents_path}")
data = json.loads(self.intents_path.read_text(encoding="utf-8"))
intents_raw = data.get("intents", [])
self.fallback_responses = data.get("fallback_responses", ["Sorry, I don't understand."])
self.intents = []
for item in intents_raw:
self.intents.append(
Intent(
tag=item.get("tag", "unknown"),
patterns=item.get("patterns", []),
responses=item.get("responses", []),
)
)
def _build_index(self) -> None:
self.pattern_index = []
for intent in self.intents:
for p in intent.patterns:
p_clean = p.strip()
if p_clean:
self.pattern_index.append((p_clean, intent.tag))
patterns_only = [p for p, _ in self.pattern_index]
if not patterns_only:
raise ValueError("No patterns found in intents.json")
self.pattern_matrix = self.vectorizer.fit_transform(patterns_only)
def _get_intent_by_tag(self, tag: str) -> Intent:
for intent in self.intents:
if intent.tag == tag:
return intent
return Intent(tag="unknown", patterns=[], responses=[])
def predict_tag(self, user_text: str) -> Tuple[str, float]:
user_text = (user_text or "").strip()
if not user_text:
return "unknown", 0.0
user_vec = self.vectorizer.transform([user_text])
scores = cosine_similarity(user_vec, self.pattern_matrix)[0]
best_idx = int(scores.argmax())
best_score = float(scores[best_idx])
best_tag = self.pattern_index[best_idx][1]
return best_tag, best_score
def reply(self, user_text: str) -> str:
tag, score = self.predict_tag(user_text)
if self.debug:
print(f"[debug] tag={tag} score={score:.3f}")
if score >= self.threshold:
intent = self._get_intent_by_tag(tag)
if intent.responses:
return random.choice(intent.responses)
return random.choice(self.fallback_responses)
def run_cli(self) -> None:
print("ChatBot started. Type 'exit' / 'bye' to stop.")
while True:
try:
user = input("\nYou: ").strip()
except (KeyboardInterrupt, EOFError):
print("\nExiting...")
return
if not user:
print("Bot: Please type something.")
continue
# Quick exit check
if user.lower() in {"exit", "quit", "bye", "goodbye"}:
print("Bot:", self.reply("bye"))
return
print("Bot:", self.reply(user))
def main():
intents_file = "intents.json"
threshold = 0.35
debug = True
# Optional CLI args: python chatbot.py intents.json 0.4
if len(sys.argv) >= 2:
intents_file = sys.argv[1]
if len(sys.argv) >= 3:
threshold = float(sys.argv[2])
bot = ChatBot(intents_path=intents_file, threshold=threshold, debug=debug)
bot.run_cli()
if __name__ == "__main__":
main()
Setup & Run (Windows / Linux / macOS)
Step 1: Clone or create folder
mkdir chat-bot
cd chat-bot
Put these files inside the folder: chatbot.py, intents.json, requirements.txt
Step 2: Create virtual environment
# Windows
python -m venv .venv
.venv\Scripts\activate
# Linux / macOS
python3 -m venv .venv
source .venv/bin/activate
Step 3: Install dependencies
pip install -r requirements.txt
Step 4: Run the chatbot
python chatbot.py
Optional: Tune threshold
If chatbot answers wrongly, increase threshold. If it replies fallback too much, decrease it.
python chatbot.py intents.json 0.45
How to Customize for Your College Project
- Add 10–20 intents for your project domain (library, hospital, banking, placement help, etc.).
- Keep patterns realistic: include short + long questions.
- For each intent, add at least 3–6 responses to avoid repeating same reply.
- Test with wrong spellings and adjust threshold a bit.
Common Viva Questions (Add these in your report)
- What is the difference between a rule-based chatbot and an NLP-based chatbot?
- Why did you use TF-IDF similarity and what are its limitations?
- What is the role of the confidence threshold and how do you decide its value?
Conclusion
This Python chatbot project is simple to run, easy to explain in viva, and still feels smart because of the similarity fallback. If you want, you can extend it into a Flask web app, connect it to a database, or build an admin panel to edit intents from a UI.
If you are publishing this on your site, you can internally link it to your other posts like: Python Projects, Machine Learning Projects, Final Year Projects.
chatbot project in python with source code
chatbot project in python github
chatbot project in python with source code pdf
chatbot project in python example
chatbot project in python with source code free download
chatbot project in python with source code download
python chatbot code copy and paste
chatbot project with source code github
🎓 Need Complete Final Year Project?
Get Source Code + Report + PPT + Viva Questions (Instant Access)
🛒 Visit UpdateGadh Store →