diff --git a/ai-ml/LLMChatbot/Architecture Diagram.pdf b/ai-ml/LLMChatbot/Architecture Diagram.pdf new file mode 100644 index 00000000..57dbf1cf Binary files /dev/null and b/ai-ml/LLMChatbot/Architecture Diagram.pdf differ diff --git a/ai-ml/LLMChatbot/Flask_flowchart.png b/ai-ml/LLMChatbot/Flask_flowchart.png new file mode 100644 index 00000000..0ef460cb Binary files /dev/null and b/ai-ml/LLMChatbot/Flask_flowchart.png differ diff --git a/ai-ml/LLMChatbot/GPT Chatbot_Documentation.pdf b/ai-ml/LLMChatbot/GPT Chatbot_Documentation.pdf new file mode 100644 index 00000000..c750b6a1 Binary files /dev/null and b/ai-ml/LLMChatbot/GPT Chatbot_Documentation.pdf differ diff --git a/ai-ml/LLMChatbot/Readme.md b/ai-ml/LLMChatbot/Readme.md new file mode 100644 index 00000000..b76311b0 --- /dev/null +++ b/ai-ml/LLMChatbot/Readme.md @@ -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. diff --git a/ai-ml/LLMChatbot/dialogflow vs gpt.pdf b/ai-ml/LLMChatbot/dialogflow vs gpt.pdf new file mode 100644 index 00000000..818d03a8 Binary files /dev/null and b/ai-ml/LLMChatbot/dialogflow vs gpt.pdf differ diff --git a/ai-ml/LLMChatbot/flask_chatbot_implementation.py b/ai-ml/LLMChatbot/flask_chatbot_implementation.py new file mode 100644 index 00000000..2c4828fd --- /dev/null +++ b/ai-ml/LLMChatbot/flask_chatbot_implementation.py @@ -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) diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Node_Flowchart.png b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Node_Flowchart.png new file mode 100644 index 00000000..21bfdcd3 Binary files /dev/null and b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Node_Flowchart.png differ diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Readme.md b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Readme.md new file mode 100644 index 00000000..2a454fe5 --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/Readme.md @@ -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 +cd + + +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. + diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/chatbot.py b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/chatbot.py new file mode 100644 index 00000000..b89c5416 --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/chatbot.py @@ -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") \ No newline at end of file diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/index.html b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/index.html new file mode 100644 index 00000000..e5ab7405 --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/index.html @@ -0,0 +1,17 @@ + + + + + + Chatbot Interface + + + +
+
+ + +
+ + + diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/script.js b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/script.js new file mode 100644 index 00000000..0476157b --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/script.js @@ -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 += `
User: ${question}
`; + chatOutput.innerHTML += `
Bot: ${data.response}
`; + userInput.value = ''; // clear input after sending + }) + .catch(error => console.error('Error:', error)); +} \ No newline at end of file diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/styles.css b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/styles.css new file mode 100644 index 00000000..667dab0e --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/public/styles.css @@ -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; +} \ No newline at end of file diff --git a/ai-ml/LLMChatbot/nodejs-chatbot-implementation/server.js b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/server.js new file mode 100644 index 00000000..3dd55cad --- /dev/null +++ b/ai-ml/LLMChatbot/nodejs-chatbot-implementation/server.js @@ -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}`); +}); \ No newline at end of file diff --git a/ai-ml/LLMChatbot/templates/chat.html b/ai-ml/LLMChatbot/templates/chat.html new file mode 100644 index 00000000..4da091ef --- /dev/null +++ b/ai-ml/LLMChatbot/templates/chat.html @@ -0,0 +1,51 @@ + + + + + + Chatbot Interface + + + +
+ + + +