Skip to content
This repository was archived by the owner on Sep 16, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added ai-ml/LLMChatbot/Architecture Diagram.pdf
Binary file not shown.
Binary file added ai-ml/LLMChatbot/Flask_flowchart.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ai-ml/LLMChatbot/GPT Chatbot_Documentation.pdf
Binary file not shown.
21 changes: 21 additions & 0 deletions ai-ml/LLMChatbot/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# NutriHelp Chatbot

NutriHelp Chatbot is an AI-powered application developed as part of the NutriHelp project at Deakin University, spearheaded by Gopher Industries. It serves as a tool to address inquiries related to nutrition and health. The chatbot leverages the cutting-edge GPT-3.5 Model from OpenAI to provide intelligent responses to user queries.

## Implementations

### Flask Implementation

The Flask implementation of NutriHelp Chatbot is contained within the file `flask_chatbot_implementation.py`. To run this implementation, you will need the `flask` library installed in your Python environment. The `templates` folder holds HTML scripts necessary for Flask to render the user interface. This implementation is ideal for developers who wish to work directly on the Python script, customize the chatbot, and conduct further prompt engineering.

### Node.js Implementation

The `nodejs-chatbot-implementation` directory contains a demonstration of integrating the Python script with a Node.js server. This implementation showcases how the chatbot can be seamlessly integrated into the NutriHelp website using a Node.js server with the `child-process` module. Developers can follow a similar procedure to incorporate the chatbot functionality into their web applications.

## Additional Resources

### PDF Documentation

1. **Dialogflow vs. GPT Comparison**: This document provides an in-depth comparison between Dialogflow and the GPT approach, supporting the superiority of the LLM (Large Language Model) approach over Dialogflow.

2. **GPT-Chatbot Documentation**: This comprehensive document breaks down the code structure, functionality, and architecture of the NutriHelp Chatbot implemented with Flask. It serves as a valuable resource for developers seeking to understand the inner workings of the chatbot.
Binary file added ai-ml/LLMChatbot/dialogflow vs gpt.pdf
Binary file not shown.
98 changes: 98 additions & 0 deletions ai-ml/LLMChatbot/flask_chatbot_implementation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
from flask import Flask, request, jsonify, render_template, session
from flask_session import Session # You need to install Flask-Session
from openai import OpenAI
import secrets
from flask_cors import CORS

client = OpenAI(api_key="")
# Generate a secret key for the Flask application
def generate_secret_key():
# Generate a 256-bit (32 bytes) secret key
return secrets.token_hex(32)

# Generate a session key for a user session
def generate_session_key():
# Generate a 256-bit (32 bytes) session key
return secrets.token_hex(32)



app = Flask(__name__)
app.config["SECRET_KEY"] = generate_secret_key()
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


def is_relevant_question(question):
"""
Use OpenAI to determine if the question is relevant to NutriHelp or nutrition.
"""
# This prompt asks the model to classify if the question is about NutriHelp or nutrition
messages = [{"role": "system", "content": """You are a chatbot related to Nutrition. Your job is to see if the following message matches to any of the following:
1 - nutrition, food facts, food comparison, related information
2 - Is a common conversational message such as greetings or something similar
3 - Is a question about NutriHelp/Deakin University.
Only reply 'no' if the message is clearly irrelevant to the conversation, nutrition and does not match with any of the above.
Answer with 'yes' or 'no' only."""},
{"role": "user", "content": question}
]
chat_completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages
)
response_content = chat_completion.choices[0].message.content
print(response_content.strip().lower())
return response_content.strip().lower() == "yes"

def ask_gpt(question):
# Initialize conversation history if it doesn't exist
if "chat_history" not in session:
session["chat_history"] = []

if not is_relevant_question(question):
return "I can only provide information about NutriHelp or nutrition. Please ask a relevant question."

if not session["chat_history"]:
session["chat_history"].append({
"role": "system",
"content": "Hello, I am Roy, a chatbot working for NutriHelp. NutriHelp is a project at Deakin University under Gopher Industries, focusing on MedTech. We leverage AI to help people track their nutrition. Feel free to ask me anything about NutriHelp or general nutrition, or just say hi!"
})

# Append the new question to the conversation history
session["chat_history"].append({"role": "user", "content": question})

# Make the request to OpenAI API with the conversation history
chat_completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=session["chat_history"]
)

print(session["chat_history"])

# Extract the response and add it to the conversation history
response_content = chat_completion.choices[0].message.content
session["chat_history"].append({"role": "system", "content": response_content})

return response_content


@app.route("/")
def index():
return render_template("chat.html")

@app.route("/ask", methods=["POST"])
def chat_with_gpt():
data = request.json
question = data.get("question", "")
if not question:
return jsonify({"error": "No question provided"}), 400
response = ask_gpt(question)
return jsonify({"response": response})

@app.route("/reset_session", methods=["GET"])
def reset_session():
session.clear() # This clears the session data, including the conversation history
return jsonify({"message": "Session reset successfully"}), 200

if __name__ == "__main__":
app.run(debug=True)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Chatbot Project

## Description
This project is a simple chatbot interface that integrates a Node.js server with a Python script to handle user questions related to nutrition.

## Installation

1. Clone the repository:

git clone <repository-url>
cd <repository-directory>


2. Install Node.js dependencies:

npm install


3. Ensure you have Python installed and the required packages:

pip install openai


## Configuration

1. Update the `pythonExecutablePath` in `server.js` to the path of your Python executable


2. Add your OpenAI API key in `chatbot.py`


## Usage

1. Start the Node.js server:

node server.js

2. Open your browser and navigate to `http://localhost:3000`.

3. Ask questions through the web interface.

## Project Structure

- `public/`
- `index.html`: The main HTML file.
- `styles.css`: The CSS file for styling.
- `script.js`: The JavaScript file for handling user interactions.
- `server.js`: The Node.js server file.
- `chatbot.py`: The Python script for handling chatbot logic.

44 changes: 44 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/chatbot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import sys
import secrets
from openai import OpenAI

client = OpenAI(api_key="")

def is_relevant_question(question):
messages = [{"role": "system", "content": """You are a chatbot related to Nutrition. Your job is to see if the following message matches to any of the following:
1 - nutrition, food facts, food comparison, related information
2 - Is a common conversational message such as greetings or something similar
3 - Is a question about NutriHelp/Deakin University.
Only reply 'no' if the message is clearly irrelevant to the conversation, nutrition and does not match with any of the above.
Answer with 'yes' or 'no' only."""},
{"role": "user", "content": question}]
chat_completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages
)
response_content = chat_completion.choices[0].message.content.strip().lower()
return response_content == "yes"

def ask_gpt(question):
if not is_relevant_question(question):
print("I can only provide information about NutriHelp or nutrition. Please ask a relevant question.")
return

# Simulate conversation history for demonstration
chat_history = [{"role": "system", "content": "Hello, I am Roy, a chatbot working for NutriHelp. NutriHelp is a project at Deakin University under Gopher Industries, focusing on MedTech. We leverage AI to help people track their nutrition. Feel free to ask me anything about NutriHelp or general nutrition, or just say hi!"}]
chat_history.append({"role": "user", "content": question})

chat_completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=chat_history
)

response_content = chat_completion.choices[0].message.content
print(response_content)

if __name__ == "__main__":
if len(sys.argv) > 1:
question = sys.argv[1]
ask_gpt(question)
else:
print("No question provided")
17 changes: 17 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatbot Interface</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chat-container">
<div id="chat-output"></div>
<input type="text" id="user-input" placeholder="Ask a question...">
<button onclick="sendQuestion()">Ask</button>
</div>
<script src="script.js"></script>
</body>
</html>
21 changes: 21 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// script.js
function sendQuestion() {
const userInput = document.getElementById('user-input');
const chatOutput = document.getElementById('chat-output');
const question = userInput.value;

fetch('http://localhost:3000/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ question: question })
})
.then(response => response.json())
.then(data => {
chatOutput.innerHTML += `<div>User: ${question}</div>`;
chatOutput.innerHTML += `<div>Bot: ${data.response}</div>`;
userInput.value = ''; // clear input after sending
})
.catch(error => console.error('Error:', error));
}
29 changes: 29 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* styles.css */
body {
font-family: Arial, sans-serif;
}

.chat-container {
width: 300px;
margin: 50px auto;
border: 1px solid #ccc;
padding: 10px;
}

#chat-output {
height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
margin-bottom: 10px;
padding: 5px;
}

#user-input {
width: calc(100% - 90px);
padding: 5px;
}

button {
width: 80px;
padding: 5px;
}
42 changes: 42 additions & 0 deletions ai-ml/LLMChatbot/nodejs-chatbot-implementation/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const express = require('express');
const bodyParser = require('body-parser');
const { spawn } = require('child_process');

const app = express();
const port = 3000;

app.use(bodyParser.json());

app.use(express.static('public'));

app.post('/ask', (req, res) => {
const question = req.body.question;
if (!question) {
return res.status(400).json({ error: "No question provided" });
}

const pythonExecutablePath = 'C:/Users/tahat/anaconda3/envs/chatbot/python.exe'; // Adjust this path
const pythonProcess = spawn(pythonExecutablePath, ['chatbot.py', question]);

pythonProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
res.json({ response: data.toString() });
});

pythonProcess.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
res.status(500).json({ error: "Error in Python script" });
});

pythonProcess.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
});

app.get('/', (req, res) => {
res.send('Node.js and Python integration example');
});

app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
51 changes: 51 additions & 0 deletions ai-ml/LLMChatbot/templates/chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatbot Interface</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; flex-direction: column; }
#chatbox { width: 300px; height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: scroll; margin-bottom: 10px; }
#userInput { width: 300px; padding: 10px; }
</style>
</head>
<body>
<div id="chatbox"></div>
<input type="text" id="userInput" placeholder="Type your question here..." autofocus>
<script>
const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');

userInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
const question = userInput.value;
userInput.value = '';
addMessage('You: ' + question, 'right');
fetch('/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ question: question }),
})
.then(response => response.json())
.then(data => {
addMessage('Bot: ' + data.response, 'left');
})
.catch((error) => {
console.error('Error:', error);
});
}
});

function addMessage(text, align) {
const messageElement = document.createElement('div');
messageElement.textContent = text;
messageElement.style.textAlign = align;
chatbox.appendChild(messageElement);
chatbox.scrollTop = chatbox.scrollHeight;
}
</script>
</body>
</html>