diff --git a/smartassist/src/backend.py b/smartassist/src/backend.py index b0ee1a0..c7148a2 100644 --- a/smartassist/src/backend.py +++ b/smartassist/src/backend.py @@ -2,26 +2,23 @@ # Import the necessary functions from ollama, Flask, requests, threading from ollama import Client from flask import Flask, request, jsonify -#import requests +import requests #import threading # Initialize a Flask application app = Flask(__name__) -def get_response(user_query): - # Create a client object for interacting with OLLAMA API - client = Client() - - # Generate and retrieve the response based on user's query - response = client.generate_response(user_query) - - # Return the generated response - return response - -def run_flask(): - # Flask endpoint for user interaction - app.run(port=5000, debug=True) +@app.route('/api/chat', methods=['POST']) +def chat(): + # Get the message from the JSON in the request body + data = request.get_json() + message = data.get('query') + if message: + response = requests.post('localhost::11434', json={"model": "llama3",'prompt': message}) + return jsonify({'response': response.json().get('result')}) + else: + return jsonify({'error': 'No query provided'}), 400 @app.route('/smartassist', methods=['POST']) @@ -37,13 +34,30 @@ def smartassist(): # Return the response as a JSON object in the HTTP response return jsonify({"response": response}) +def get_response(user_query): + # Create a client object for interacting with OLLAMA API + client = Client() + + # Generate and retrieve the response based on user's query + response = client.generate_response(user_query) + + # Return the generated response + return response + +def run_flask(): + # Flask endpoint for user interaction + app.run(port=5000, debug=True) + # app.run(port=5000, debug=True, use_reloader=False) + + +# @app.route('/api/chat', methods=['POST']) +# def chat(): +# data = request.get_json() +# query = data['query'] +# # response = requests.post('http://ollama-server/api/v1/chat', json={'prompt': query}) +# response = requests.post('localhost::11434', json={"model": "llama3",'prompt': query}) +# return jsonify({'response': response.json().get('result')}) -@app.route('/api/chat', methods=['POST']) -def chat(): - data = request.get_json() - query = data['query'] - response = requests.post('http://ollama-server/api/v1/chat', json={'prompt': query}) - return jsonify({'response': response.json().get('result')}) if __name__ == '__main__': diff --git a/smartassist/src/client.html b/smartassist/src/client.html index 3fe0471..9b3cacb 100644 --- a/smartassist/src/client.html +++ b/smartassist/src/client.html @@ -1,7 +1,8 @@ - + @@ -24,12 +25,12 @@ Open your web browser and navigate to http://localhost:8000/client.html margin-bottom: 10px; } .user-message { - background-color: #f0f0f0; + background-color: #eae2d5; padding: 10px; border-radius: 10px; } .ai-response { - background-color: #ccc; + background-color: #cfc68b; padding: 10px; border-radius: 10px; } diff --git a/smartassist/src/frontend.js b/smartassist/src/frontend.js index f35f6ad..0b80540 100644 --- a/smartassist/src/frontend.js +++ b/smartassist/src/frontend.js @@ -4,36 +4,63 @@ const chatbox = document.getElementById('chatbox'); const userInput = document.getElementById('userInput'); // Define a function to send the user's message to the AI +// function sendMessage() { +// // Get the user's input message and trim any whitespace +// const message = userInput.value.trim(); + +// // Check if the message is not empty +// if (message !== '') { +// // Send a POST request to the /api/chat endpoint with the message +// fetch('/api/chat', { +// method: 'POST', +// headers: { 'Content-Type': 'application/json' }, +// body: JSON.stringify({ message }), +// }) +// .then(response => response.json()) +// .then(data => { +// // Get the AI's response from the API data +// const aiResponse = data.response; + +// // Render the user's original message in the chatbox +// renderMessage(message, 'user-message'); + +// // Render the AI's response in the chatbox +// renderMessage(aiResponse, 'ai-response'); + +// // Clear the user input field for the next message +// userInput.value = ''; +// }) +// .catch(error => console.error('Error sending message:', error)); +// } +// } + function sendMessage() { - // Get the user's input message and trim any whitespace - const message = userInput.value.trim(); + const message = userInput.value.trim(); + if (message !== '') { + // Create a new XMLHttpRequest object + const xhr = new XMLHttpRequest(); - // Check if the message is not empty - if (message !== '') { - // Send a POST request to the /api/chat endpoint with the message - fetch('/api/chat', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message }), - }) - .then(response => response.json()) - .then(data => { - // Get the AI's response from the API data - const aiResponse = data.response; + // Configure the request + xhr.open('POST', '/api/chat'); // Set method to POST and URL + xhr.setRequestHeader('Content-Type', 'application/json'); // Essential for sending JSON - // Render the user's original message in the chatbox - renderMessage(message, 'user-message'); + // Handle response data + xhr.onload = function() { + if (xhr.status >= 200 && xhr.status < 300) { // Successful response + const data = JSON.parse(xhr.responseText); + renderMessage(data.response, 'ai-response'); - // Render the AI's response in the chatbox - renderMessage(aiResponse, 'ai-response'); + } else { + console.error('Request failed. Status:', xhr.status); + } + }; - // Clear the user input field for the next message - userInput.value = ''; - }) - .catch(error => console.error('Error sending message:', error)); - } + // Send the request + xhr.send(JSON.stringify({ message })); + } } + // Define a function to render a message in the chatbox with a specific class name function renderMessage(text, className) { // Create a new div element to hold the message diff --git a/smartassist/src/startservices.py b/smartassist/src/startservices.py index 76e94c0..1b4e5c1 100644 --- a/smartassist/src/startservices.py +++ b/smartassist/src/startservices.py @@ -4,20 +4,39 @@ import threading from backend import run_flask +import socket + def start_frontend(): - try: - # Start frontend (web server) as a separate process - subprocess.Popen(["python", "-m", "http.server", "8000"]) - except Exception as e: - print(f"Failed to start frontend: {e}") + host = 'localhost' # or the address of your server + port = 8000 # change to your server's port + + # Use the socket module in Python to check whether a port is in use, + # which would indicate that a server is already running on that port. + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + try: + s.bind((host, port)) + print("No server is running on this host and port.") + # Start frontend (web server) as a separate process + subprocess.Popen(["python", "-m", "http.server", str(port)]) + except socket.error as e: + if e.errno == 48: + print("Another server is already running on this host and port. Assumes it is a web server, will continue.") + else: + raise # Unexpected error, re-raise it so we can see the traceback + except Exception as e: + print(f"Failed to start frontend: {e}") + def start_backend(): try: # Start backend as a separate thread - threading.Thread(target=run_flask).start() + # threading.Thread(target=run_flask).start() # Flask's built-in server doesn't support running in a separate thread. + run_flask() except Exception as e: print(f"Failed to start backend: {e}") if __name__ == '__main__': - start_backend() start_frontend() + start_backend() +