Refaktoriseringar och test av alternativa lösningar.
This commit is contained in:
+34
-20
@@ -2,26 +2,23 @@
|
|||||||
# Import the necessary functions from ollama, Flask, requests, threading
|
# Import the necessary functions from ollama, Flask, requests, threading
|
||||||
from ollama import Client
|
from ollama import Client
|
||||||
from flask import Flask, request, jsonify
|
from flask import Flask, request, jsonify
|
||||||
#import requests
|
import requests
|
||||||
#import threading
|
#import threading
|
||||||
|
|
||||||
# Initialize a Flask application
|
# Initialize a Flask application
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
def get_response(user_query):
|
@app.route('/api/chat', methods=['POST'])
|
||||||
# Create a client object for interacting with OLLAMA API
|
def chat():
|
||||||
client = Client()
|
# Get the message from the JSON in the request body
|
||||||
|
data = request.get_json()
|
||||||
# Generate and retrieve the response based on user's query
|
message = data.get('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)
|
|
||||||
|
|
||||||
|
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'])
|
@app.route('/smartassist', methods=['POST'])
|
||||||
@@ -37,13 +34,30 @@ def smartassist():
|
|||||||
# Return the response as a JSON object in the HTTP response
|
# Return the response as a JSON object in the HTTP response
|
||||||
return jsonify({"response": 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__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<!-->
|
<!--
|
||||||
Run a simple HTTP server in the directory containing your HTML file
|
Run a simple HTTP server in the directory containing your HTML file
|
||||||
python -m http.server 8000
|
python -m http.server 8000
|
||||||
Open your web browser and navigate to http://localhost:8000/client.html
|
Open your web browser and navigate to http://localhost:8000/smartassist/src/client.html
|
||||||
|
Note that the path starts from where the python venv was defined (project root)
|
||||||
-->
|
-->
|
||||||
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
@@ -24,12 +25,12 @@ Open your web browser and navigate to http://localhost:8000/client.html
|
|||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
}
|
}
|
||||||
.user-message {
|
.user-message {
|
||||||
background-color: #f0f0f0;
|
background-color: #eae2d5;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
}
|
}
|
||||||
.ai-response {
|
.ai-response {
|
||||||
background-color: #ccc;
|
background-color: #cfc68b;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-21
@@ -4,36 +4,63 @@ const chatbox = document.getElementById('chatbox');
|
|||||||
const userInput = document.getElementById('userInput');
|
const userInput = document.getElementById('userInput');
|
||||||
|
|
||||||
// Define a function to send the user's message to the AI
|
// 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() {
|
function sendMessage() {
|
||||||
// Get the user's input message and trim any whitespace
|
|
||||||
const message = userInput.value.trim();
|
const message = userInput.value.trim();
|
||||||
|
|
||||||
// Check if the message is not empty
|
|
||||||
if (message !== '') {
|
if (message !== '') {
|
||||||
// Send a POST request to the /api/chat endpoint with the message
|
// Create a new XMLHttpRequest object
|
||||||
fetch('/api/chat', {
|
const xhr = new XMLHttpRequest();
|
||||||
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
|
// Configure the request
|
||||||
renderMessage(message, 'user-message');
|
xhr.open('POST', '/api/chat'); // Set method to POST and URL
|
||||||
|
xhr.setRequestHeader('Content-Type', 'application/json'); // Essential for sending JSON
|
||||||
|
|
||||||
// Render the AI's response in the chatbox
|
// Handle response data
|
||||||
renderMessage(aiResponse, 'ai-response');
|
xhr.onload = function() {
|
||||||
|
if (xhr.status >= 200 && xhr.status < 300) { // Successful response
|
||||||
|
const data = JSON.parse(xhr.responseText);
|
||||||
|
renderMessage(data.response, 'ai-response');
|
||||||
|
|
||||||
// Clear the user input field for the next message
|
} else {
|
||||||
userInput.value = '';
|
console.error('Request failed. Status:', xhr.status);
|
||||||
})
|
}
|
||||||
.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
|
// Define a function to render a message in the chatbox with a specific class name
|
||||||
function renderMessage(text, className) {
|
function renderMessage(text, className) {
|
||||||
// Create a new div element to hold the message
|
// Create a new div element to hold the message
|
||||||
|
|||||||
@@ -4,20 +4,39 @@ import threading
|
|||||||
|
|
||||||
from backend import run_flask
|
from backend import run_flask
|
||||||
|
|
||||||
|
import socket
|
||||||
|
|
||||||
def start_frontend():
|
def start_frontend():
|
||||||
|
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:
|
try:
|
||||||
|
s.bind((host, port))
|
||||||
|
print("No server is running on this host and port.")
|
||||||
# Start frontend (web server) as a separate process
|
# Start frontend (web server) as a separate process
|
||||||
subprocess.Popen(["python", "-m", "http.server", "8000"])
|
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:
|
except Exception as e:
|
||||||
print(f"Failed to start frontend: {e}")
|
print(f"Failed to start frontend: {e}")
|
||||||
|
|
||||||
|
|
||||||
def start_backend():
|
def start_backend():
|
||||||
try:
|
try:
|
||||||
# Start backend as a separate thread
|
# 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:
|
except Exception as e:
|
||||||
print(f"Failed to start backend: {e}")
|
print(f"Failed to start backend: {e}")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
start_backend()
|
|
||||||
start_frontend()
|
start_frontend()
|
||||||
|
start_backend()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user