6 Commits

Author SHA1 Message Date
Joakim Persson 99e3737718 Startar upp allla tjänster 2024-07-16 17:19:39 +02:00
Joakim Persson c39b831a59 Omdöpt till backend.py 2024-07-16 17:19:20 +02:00
Joakim Persson 3b70ab6eb9 Javascript som interagerar med Flask och webläsaren 2024-07-16 17:18:42 +02:00
Joakim Persson 4743fc26ad Webbsidaa för chatt 2024-07-16 17:18:01 +02:00
Joakim Persson 3ad564a75d Rensat överflödig kod 2024-07-16 17:17:08 +02:00
Joakim Persson 9ea88d693d Bytt namn. 2024-07-16 17:16:31 +02:00
4 changed files with 137 additions and 8 deletions
@@ -1,6 +1,12 @@
# Import the necessary library from ollama module # Import the necessary functions from ollama, Flask, requests, threading
from ollama import Client from ollama import Client
from flask import Flask, request, jsonify
#import requests
#import threading
# Initialize a Flask application
app = Flask(__name__)
def get_response(user_query): def get_response(user_query):
# Create a client object for interacting with OLLAMA API # Create a client object for interacting with OLLAMA API
@@ -12,12 +18,11 @@ def get_response(user_query):
# Return the generated response # Return the generated response
return response return response
# Flask endpoint for user interaction def run_flask():
from flask import Flask, request, jsonify # Flask endpoint for user interaction
import requests app.run(port=5000, debug=True)
# Initialize a Flask application
app = Flask(__name__)
@app.route('/smartassist', methods=['POST']) @app.route('/smartassist', methods=['POST'])
def smartassist(): def smartassist():
@@ -26,6 +31,7 @@ def smartassist():
user_query = data['query'] user_query = data['query']
# Get the response from the OLLAMA API based on the user's query # Get the response from the OLLAMA API based on the user's query
# NOTE: Should we append message history here? Maybe interact with SQLlite?
response = get_response(user_query) response = get_response(user_query)
# Return the response as a JSON object in the HTTP response # Return the response as a JSON object in the HTTP response
@@ -41,6 +47,7 @@ def chat():
if __name__ == '__main__': if __name__ == '__main__':
# Run the Flask application on port 5000 # Run the Flask application
app.run(port=5000, debug=True) run_flask()
+49
View File
@@ -0,0 +1,49 @@
<!-->
Run a simple HTTP server in the directory containing your HTML file
python -m http.server 8000
Open your web browser and navigate to http://localhost:8000/client.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ollama Interaction</title>
<style>
/* Basic styling */
body { font-family: Arial, sans-serif; }
#chatbox {
width: 80%; /* responsive width */
max-width: 400px;
height: 300px;
border: 1px solid #ccc;
overflow-y: scroll;
padding: 10px;
}
.message {
margin-bottom: 10px;
}
.user-message {
background-color: #f0f0f0;
padding: 10px;
border-radius: 10px;
}
.ai-response {
background-color: #ccc;
padding: 10px;
border-radius: 10px;
}
</style>
</head>
<body>
<h1>Ollama Interaction</h1>
<div id="chatbox">
<!-- messages will be rendered here -->
</div>
<input type="text" id="userInput" placeholder="Type your message here...">
<button onclick="sendMessage()">Send</button>
<!-- Link to the external frontend.js script (relative or absolute path)-->
<script src="frontend.js"></script>
</body>
</html>
+50
View File
@@ -0,0 +1,50 @@
// Get the user input element from the DOM
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));
}
}
// 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
const messageElement = document.createElement('div');
// Add the specified class name to the element
messageElement.className = className;
// Set the text content of the element to the message text
messageElement.textContent = text;
// Append the message element to the chatbox
chatbox.appendChild(messageElement);
}
+23
View File
@@ -0,0 +1,23 @@
# Start all services
import subprocess
import threading
from backend import run_flask
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}")
def start_backend():
try:
# Start backend as a separate thread
threading.Thread(target=run_flask).start()
except Exception as e:
print(f"Failed to start backend: {e}")
if __name__ == '__main__':
start_backend()
start_frontend()