Mhalexmd/ChatBot

A ChatBot Project as an assignment for LinearAlgebra

5

stars

31

commits

Python

primary language

Jan 1, 2026

updated

README

๐Ÿ’ป Computer Engineering Q&A Chatbot

Python Streamlit PyTorch Hugging Face Repo License Code Style

A deterministic, embedding-based questionโ€“answer retrieval system for core Computer Engineering topics, built using sentence embeddings and cosine similarity.

Author: MA Dehghan
Project Type: Linear Algebra Assignment
Last Updated: January 01, 2026


๐Ÿ“‘ Table of Contents


๐Ÿ” Project Overview

This project implements a semantic questionโ€“answer retrieval system using vector embeddings and cosine similarity. Rather than generating answers, the chatbot retrieves the most semantically similar predefined question from a curated question bank.

The goal of the project is to demonstrate practical applications of linear algebra concepts โ€” vector spaces, normalization, dot products, and similarity metrics โ€” in natural language processing.


๐ŸŽจ Demo

Chatbot Demo

Example Interaction:

  • User Query: "What is Moore's Law?"
  • Chatbot Response: "Moore's Law states that the number of transistors on a microchip doubles approximately every two years, leading to exponential growth in computing power..."

If no strong match (similarity โ‰ค 0.3), it responds:

"I don't know!"


โœจ Unique Features

FeatureDescriptionBenefits & Implementation Notes
๐Ÿง  Sentence EmbeddingsTransforms questions into 384-dimensional vectors using all-MiniLM-L6-v2.Handles synonyms/paraphrases; mean pooling of transformer outputs ensures fixed-length vectors.
๐Ÿ” Semantic Similarity SearchUses cosine similarity to find the best match from the question bank.Threshold (0.3) ensures weak matches are ignored.
๐Ÿƒ Word-by-Word StreamingResponses are streamed word by word via Python generator and Streamlit.Simulates real-time conversation without AI generation.
๐Ÿ› ๏ธ Extensible Question BankJSON-based (questionBank.json) with precomputed embeddings.Easily add/edit entries; recompute embeddings for new questions.
โšก Lightweight & Efficient~90MB model; CPU-friendly via PyTorch.Fast responses for small-medium question banks.
๐Ÿ”’ Deterministic & ReproducibleOutputs are fully deterministic.Same query always yields same response; ideal for assignments.
๐Ÿ“œ Chat History PersistenceUses Streamlit session state.Maintains conversation display, though matching is per query.

๐Ÿ› ๏ธ Tech Stack

  • Language: Python 3.8+ ๐Ÿ
  • Web Framework: Streamlit ๐ŸŒŸ
  • Embedding Model: Sentence Transformers - all-MiniLM-L6-v2 ๐Ÿค— (Model Hub)
  • Core Libraries: PyTorch โšก, NumPy ๐Ÿ”ข, Transformers ๐Ÿ“ฆ, JSON ๐Ÿ“„
  • Additional Utilities: Torch Functional (normalization, pooling); Streamlit Session State & Caching

๐Ÿ“š How It Works

  1. Initialization: Load question bank from questionBank.json. Cache tokenizer/model.
  2. User Input Handling: Accept query via Streamlit chat; append to session history.
  3. Embedding Computation: Tokenize, run through model, mean pooling, L2 normalization.
  4. Similarity Matching: Dot product with bank entries; select highest score. If โ‰ค 0.3 โ†’ "I don't know!".
  5. Response Delivery: Split answer into words; stream to user via generator.

Install dependencies:

pip install streamlit torch transformers numpy

๐Ÿงฎ Mathematical Foundation

Embeddings

  • Questions are embedded into a 384-dimensional vector space (โ„ยณโธโด) using the all-MiniLM-L6-v2 model.
  • Token-level embeddings are aggregated using mean pooling.
  • Resulting vectors are L2-normalized to unit length.

Similarity Metric

Cosine similarity is used to measure semantic similarity between the user query and stored questions:

$\cos(\theta) = \frac{u \cdot q}{\lVert u \rVert \lVert q \rVert}$

Where:

  • q = query embedding
  • u = stored question embedding

Because all vectors are L2-normalized, cosine similarity reduces to a dot product between vectors, enabling efficient similarity computation.


๐Ÿ› ๏ธ Installation and Setup

Prerequisites

Python 3.8+

Git

Install Dependencies pip install streamlit torch numpy transformers sentence-transformers


โ–ถ๏ธ How to Run

git clone https://github.com/Mhalexmd/ChatBot
cd ChatBot
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt
streamlit run app.py

Access at http://localhost:8501.


โž• Adding or Customizing Questions

questionBank.json format:

{
  "questions": [
    {
      "question": "What is a CPU?",
      "answer": "The central processing unit, executing instructions and managing data flow.",
      "embedding": [0.12, -0.34, ...]
    }
  ]
}

Generate embeddings with Python:

from sentence_transformers import SentenceTransformer
import json

model = SentenceTransformer('all-MiniLM-L6-v2')
questions = [{"question": "Your question", "answer": "Your answer"}]

for q in questions:
    q['embedding'] = model.encode(q['question']).tolist()

with open('questionBank.json', 'w') as f:
    json.dump({"questions": questions}, f)

โš ๏ธ Limitations

Only answers in question bank

No multi-turn context

Slow for >1k questions without indexing

English-only for now


๐Ÿค Contributing

Fork โ†’ Branch โ†’ Pull Request. Focus: New CE questions, optimizations, bug fixes.


๐Ÿ™ Acknowledgments

Hugging Face, Streamlit, PyTorch

Linear algebra applications in NLP

Assignment inspiration

Contributors

Mhalexmd

31 commits

Mhalexmd/ChatBot

A ChatBot Project as an assignment for LinearAlgebra

5

stars

31

commits

Python

primary language

Jan 1, 2026

updated

README

๐Ÿ’ป Computer Engineering Q&A Chatbot

Python Streamlit PyTorch Hugging Face Repo License Code Style

A deterministic, embedding-based questionโ€“answer retrieval system for core Computer Engineering topics, built using sentence embeddings and cosine similarity.

Author: MA Dehghan
Project Type: Linear Algebra Assignment
Last Updated: January 01, 2026


๐Ÿ“‘ Table of Contents


๐Ÿ” Project Overview

This project implements a semantic questionโ€“answer retrieval system using vector embeddings and cosine similarity. Rather than generating answers, the chatbot retrieves the most semantically similar predefined question from a curated question bank.

The goal of the project is to demonstrate practical applications of linear algebra concepts โ€” vector spaces, normalization, dot products, and similarity metrics โ€” in natural language processing.


๐ŸŽจ Demo

Chatbot Demo

Example Interaction:

  • User Query: "What is Moore's Law?"
  • Chatbot Response: "Moore's Law states that the number of transistors on a microchip doubles approximately every two years, leading to exponential growth in computing power..."

If no strong match (similarity โ‰ค 0.3), it responds:

"I don't know!"


โœจ Unique Features

FeatureDescriptionBenefits & Implementation Notes
๐Ÿง  Sentence EmbeddingsTransforms questions into 384-dimensional vectors using all-MiniLM-L6-v2.Handles synonyms/paraphrases; mean pooling of transformer outputs ensures fixed-length vectors.
๐Ÿ” Semantic Similarity SearchUses cosine similarity to find the best match from the question bank.Threshold (0.3) ensures weak matches are ignored.
๐Ÿƒ Word-by-Word StreamingResponses are streamed word by word via Python generator and Streamlit.Simulates real-time conversation without AI generation.
๐Ÿ› ๏ธ Extensible Question BankJSON-based (questionBank.json) with precomputed embeddings.Easily add/edit entries; recompute embeddings for new questions.
โšก Lightweight & Efficient~90MB model; CPU-friendly via PyTorch.Fast responses for small-medium question banks.
๐Ÿ”’ Deterministic & ReproducibleOutputs are fully deterministic.Same query always yields same response; ideal for assignments.
๐Ÿ“œ Chat History PersistenceUses Streamlit session state.Maintains conversation display, though matching is per query.

๐Ÿ› ๏ธ Tech Stack

  • Language: Python 3.8+ ๐Ÿ
  • Web Framework: Streamlit ๐ŸŒŸ
  • Embedding Model: Sentence Transformers - all-MiniLM-L6-v2 ๐Ÿค— (Model Hub)
  • Core Libraries: PyTorch โšก, NumPy ๐Ÿ”ข, Transformers ๐Ÿ“ฆ, JSON ๐Ÿ“„
  • Additional Utilities: Torch Functional (normalization, pooling); Streamlit Session State & Caching

๐Ÿ“š How It Works

  1. Initialization: Load question bank from questionBank.json. Cache tokenizer/model.
  2. User Input Handling: Accept query via Streamlit chat; append to session history.
  3. Embedding Computation: Tokenize, run through model, mean pooling, L2 normalization.
  4. Similarity Matching: Dot product with bank entries; select highest score. If โ‰ค 0.3 โ†’ "I don't know!".
  5. Response Delivery: Split answer into words; stream to user via generator.

Install dependencies:

pip install streamlit torch transformers numpy

๐Ÿงฎ Mathematical Foundation

Embeddings

  • Questions are embedded into a 384-dimensional vector space (โ„ยณโธโด) using the all-MiniLM-L6-v2 model.
  • Token-level embeddings are aggregated using mean pooling.
  • Resulting vectors are L2-normalized to unit length.

Similarity Metric

Cosine similarity is used to measure semantic similarity between the user query and stored questions:

$\cos(\theta) = \frac{u \cdot q}{\lVert u \rVert \lVert q \rVert}$

Where:

  • q = query embedding
  • u = stored question embedding

Because all vectors are L2-normalized, cosine similarity reduces to a dot product between vectors, enabling efficient similarity computation.


๐Ÿ› ๏ธ Installation and Setup

Prerequisites

Python 3.8+

Git

Install Dependencies pip install streamlit torch numpy transformers sentence-transformers


โ–ถ๏ธ How to Run

git clone https://github.com/Mhalexmd/ChatBot
cd ChatBot
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt
streamlit run app.py

Access at http://localhost:8501.


โž• Adding or Customizing Questions

questionBank.json format:

{
  "questions": [
    {
      "question": "What is a CPU?",
      "answer": "The central processing unit, executing instructions and managing data flow.",
      "embedding": [0.12, -0.34, ...]
    }
  ]
}

Generate embeddings with Python:

from sentence_transformers import SentenceTransformer
import json

model = SentenceTransformer('all-MiniLM-L6-v2')
questions = [{"question": "Your question", "answer": "Your answer"}]

for q in questions:
    q['embedding'] = model.encode(q['question']).tolist()

with open('questionBank.json', 'w') as f:
    json.dump({"questions": questions}, f)

โš ๏ธ Limitations

Only answers in question bank

No multi-turn context

Slow for >1k questions without indexing

English-only for now


๐Ÿค Contributing

Fork โ†’ Branch โ†’ Pull Request. Focus: New CE questions, optimizations, bug fixes.


๐Ÿ™ Acknowledgments

Hugging Face, Streamlit, PyTorch

Linear algebra applications in NLP

Assignment inspiration

Contributors

Mhalexmd

31 commits

Languages

Python

100.0%