Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Chatbot Project in Python

Chatbot Project in Python – Free Source Code

Posted on February 27, 2026March 15, 2026 By Updategadh No Comments on Chatbot Project in Python – Free Source Code

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
▶ Subscribe on YouTube: DecodeIT2

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)

  1. Load intents.json (tags, patterns, responses).
  2. Preprocess patterns and build a TF-IDF vectorizer.
  3. User message is vectorized and compared with all patterns.
  4. If similarity score ≥ threshold → reply from matched intent.
  5. Else → fallback response (ask rephrase / show help).
Chatbot Project in Python
Chatbot Project in Python

Feature Table

Module / FeatureWhat it doesWhy it matters
Intents JSONStores tags, patterns, responsesEasy to edit without coding
TF-IDF SimilarityFinds closest pattern to user inputHandles variations in text
Confidence ThresholdRejects weak matchesReduces wrong replies, improves trust
LoggingPrints matched tag + similarity scoreHelps 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)

  1. What is the difference between a rule-based chatbot and an NLP-based chatbot?
  2. Why did you use TF-IDF similarity and what are its limitations?
  3. 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

Post Views: 176
Python Projects Tags:ai-chatbot project github, chatbot project example, chatbot project for students, chatbot project free download, chatbot project github, chatbot project ideas, chatbot project in python with source code pdf, chatbot project pdf, chatbot project using python, chatbot project with source code, chatGpt

Post navigation

Previous Post: Top 10 AI Agent Project Ideas for Final Year Students in 2026
Next Post: Instagram Bot Using Python (Automation Project)

More Related Articles

Hospital Appointment System in Python Best Hospital Appointment System in Python Python Projects
Posture Detection Using Machine Learning in Python Posture Detection Using Machine Learning in Python Python Projects
YouTube Videos Downloader Best Project Using Django Python YouTube Videos Downloader Best Project Using Django Python Python Projects

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. Food Management System in Python [Django Framework ]
  2. Online Grocery Shop Using Python with Source code setup
  3. File Sharing Website Using Python in Django
  4. Library Management System in Python (Flask)
  5. Best Currency Converter Web Application Using Python – Complete Professional Project
  6. Pharmacy Management System Project using Python Django

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,614)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,215)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,869)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme