AI FAQ Chatbot Project with Python

Artificial Intelligence project 01

AI FAQ Chatbot Project with Python

Build a complete faq chatbot workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Return the most relevant approved answer for a user question while declining queries below a similarity threshold.

Data or knowledge source

Six approved FAQ question-and-answer pairs embedded in the program. No conversation history or personal data is collected.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install scikit-learn
  • About 45-60 minutes to build and review

How the system works

Fit TF-IDF unigram and bigram features on FAQ questions, compute cosine similarity for a new query, and return the matched answer only when the best score clears the threshold.

Validation checklist

  • Empty input receives a clear prompt
  • Low-confidence questions fall back to support
  • The matched FAQ and similarity score remain visible
  • The bot never invents an answer outside the approved list

Complete Python code

Save the program as ai_faq_chatbot.py. The code runs locally and requires no paid API key or model download.

"""A retrieval-based FAQ chatbot that answers only from approved content."""

from __future__ import annotations

from dataclasses import dataclass
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


FAQS = [
    ("What are the class timings?", "Weekday and weekend batch timings are listed on the current course page."),
    ("Do you provide certificates?", "Course-completion certificates are issued according to the published eligibility requirements."),
    ("Is online training available?", "Online and classroom options depend on the course and current batch schedule."),
    ("How can I contact support?", "Use the contact page to reach the training support team."),
    ("Are projects included?", "Project practice is included where it is listed in the selected course curriculum."),
    ("Where is the institute located?", "Check the contact page for the current address and directions."),
]


@dataclass(frozen=True)
class BotReply:
    answer: str
    matched_question: str | None
    confidence: float


class FaqBot:
    def __init__(self, faqs=FAQS, threshold: float = 0.18):
        self.questions = [item[0] for item in faqs]
        self.answers = [item[1] for item in faqs]
        self.threshold = threshold
        self.vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
        self.matrix = self.vectorizer.fit_transform(self.questions)

    def answer(self, query: str) -> BotReply:
        if not query.strip():
            return BotReply("Please enter a question.", None, 0.0)
        scores = cosine_similarity(self.vectorizer.transform([query]), self.matrix)[0]
        index = int(scores.argmax())
        confidence = float(scores[index])
        if confidence < self.threshold:
            return BotReply("I could not find that in the approved FAQs. Please contact support.", None, confidence)
        return BotReply(self.answers[index], self.questions[index], confidence)


def main() -> None:
    bot = FaqBot()
    for query in ("Can I attend online?", "When are classes held?", "Can you repair my laptop?"):
        print(query, "->", bot.answer(query))


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install scikit-learn when packages are required.
  3. Run python ai_faq_chatbot.py.
  4. Review confidence, fallbacks, sources, or error metrics rather than accepting output automatically.
  5. Test additional normal, edge, unsupported, and adversarial inputs.

Expected output

A structured reply containing the answer, matched question, and similarity confidence.

Accuracy, privacy, and responsible-use limits

Similarity is not factual understanding. Keep approved answers current, test paraphrases and multilingual queries, protect user messages, and provide human escalation.

Ways to extend the project

Add multilingual FAQs, typo handling, feedback logging without sensitive data, category filters, and versioned content ownership.

Continue learning Artificial Intelligence

Try the next project, return to the Softenant project library, or explore the AI training in Vizag for guided NLP, retrieval, evaluation, automation, and responsible AI practice.