Compare commits
9 Commits
UpdatePerm
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d1e65cb9e | |||
| dedf35c513 | |||
| b2e51be8e5 | |||
| 1abb1b5106 | |||
| 49d924be20 | |||
| 0be88678df | |||
| dea4b79014 | |||
| 694947f225 | |||
| 08cc5dd165 |
@@ -30,5 +30,9 @@
|
|||||||
"client_id":"client_id",
|
"client_id":"client_id",
|
||||||
"client_secret":"client_secret"
|
"client_secret":"client_secret"
|
||||||
},
|
},
|
||||||
"mongo_password":"yourMongoPassword"
|
"mongo_password":"yourMongoPassword",
|
||||||
|
"mongo_host":"localhost",
|
||||||
|
"mongo_port":"27017",
|
||||||
|
"mongo_db":"database",
|
||||||
|
"mongo_user":"root"
|
||||||
}
|
}
|
||||||
108
main.py
108
main.py
@@ -1,6 +1,8 @@
|
|||||||
from flask import Flask, jsonify, request, render_template
|
from flask import Flask, jsonify, request, render_template, Response
|
||||||
|
from flask_cors import CORS, cross_origin
|
||||||
from pymongo import MongoClient
|
from pymongo import MongoClient
|
||||||
from bson.objectid import ObjectId
|
from bson.objectid import ObjectId
|
||||||
|
from bson.json_util import dumps, loads
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from argon2 import PasswordHasher
|
from argon2 import PasswordHasher
|
||||||
import random
|
import random
|
||||||
@@ -8,6 +10,7 @@ import string
|
|||||||
import json
|
import json
|
||||||
import requests
|
import requests
|
||||||
from urllib.parse import parse_qs
|
from urllib.parse import parse_qs
|
||||||
|
from ollama import chat
|
||||||
|
|
||||||
with open("config/settings.json", "r") as f:
|
with open("config/settings.json", "r") as f:
|
||||||
settings = json.load(f)
|
settings = json.load(f)
|
||||||
@@ -22,11 +25,11 @@ github_auth_endpoint = f"https://github.com/login/oauth/authorize?response_type=
|
|||||||
github_token_endpoint = "https://github.com/login/oauth/access_token"
|
github_token_endpoint = "https://github.com/login/oauth/access_token"
|
||||||
github_user_endpoint = "https://api.github.com/user"
|
github_user_endpoint = "https://api.github.com/user"
|
||||||
|
|
||||||
mongoUser = 'root'
|
mongoUser = settings["mongo_user"]
|
||||||
mongoPassword = settings["mongo_password"]
|
mongoPassword = settings["mongo_password"]
|
||||||
mongoHost = 'localhost'
|
mongoHost = settings["mongo_host"]
|
||||||
mongoPort = '27017'
|
mongoPort = int(settings["mongo_port"])
|
||||||
mongoDatabase = 'database'
|
mongoDatabase = settings["mongo_db"]
|
||||||
mongoUri = f'mongodb://{mongoUser}:{mongoPassword}@{mongoHost}:{mongoPort}/'
|
mongoUri = f'mongodb://{mongoUser}:{mongoPassword}@{mongoHost}:{mongoPort}/'
|
||||||
|
|
||||||
print(mongoUri)
|
print(mongoUri)
|
||||||
@@ -43,6 +46,7 @@ except Exception as e:
|
|||||||
print("Error connecting to MongoDB:", e)
|
print("Error connecting to MongoDB:", e)
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
CORS(app)
|
||||||
|
|
||||||
def checkUserPermission(token, permission):
|
def checkUserPermission(token, permission):
|
||||||
# Find the correct user token in user db
|
# Find the correct user token in user db
|
||||||
@@ -73,32 +77,83 @@ def checkChatPermission(token, chatId, permission):
|
|||||||
returnedChat = chatCollection.find_one({'_id': ObjectId(chatId)})
|
returnedChat = chatCollection.find_one({'_id': ObjectId(chatId)})
|
||||||
# Convert chatId into string
|
# Convert chatId into string
|
||||||
returnedChat['_id'] = str(returnedChat['_id'])
|
returnedChat['_id'] = str(returnedChat['_id'])
|
||||||
if permission in returnedChat['permissions']:
|
if permission in returnedChat['permissions'][userId]:
|
||||||
|
return True, userId
|
||||||
|
elif (permission == True):
|
||||||
return True, userId
|
return True, userId
|
||||||
else:
|
else:
|
||||||
return False, "Incorrect permissions"
|
return False, "Incorrect permissions"
|
||||||
else:
|
else:
|
||||||
return False, "Invalid Token"
|
return False, "Invalid Token"
|
||||||
|
|
||||||
|
# Message Generation Endpoint
|
||||||
|
# Generate a new message on a specific chat
|
||||||
|
# Arguments: token (required), chatId (required), message
|
||||||
|
@app.route('/api/chat/<_id>/generate', methods =['POST'])
|
||||||
|
@cross_origin()
|
||||||
|
def generateMessage(_id):
|
||||||
|
# Get user auth token
|
||||||
|
token = request.headers['token']
|
||||||
|
a, userId = checkChatPermission(token, _id, "view")
|
||||||
|
if (a == True):
|
||||||
|
returnedChat = chatCollection.find_one({'_id': ObjectId(_id)})
|
||||||
|
message = request.json['message']
|
||||||
|
messages = returnedChat['messages']
|
||||||
|
messages.append({'role':'user', 'content':message})
|
||||||
|
stream = chat(
|
||||||
|
model=returnedChat['model'],
|
||||||
|
messages=messages,
|
||||||
|
stream=True
|
||||||
|
)
|
||||||
|
def generateStream():
|
||||||
|
response = ""
|
||||||
|
for chunk in stream:
|
||||||
|
print(chunk['message']['content'], end='', flush=True)
|
||||||
|
content = chunk['message']['content']
|
||||||
|
response += content
|
||||||
|
yield f"data: {response}\n\n"
|
||||||
|
|
||||||
|
return Response(generateStream(), mimetype='text/event-stream')
|
||||||
|
else:
|
||||||
|
return userId
|
||||||
|
|
||||||
|
# Chat List Endpoint:
|
||||||
|
# Get all the chats associated with a user
|
||||||
|
# Arguments: token (required)
|
||||||
|
@app.route('/api/user/chats', methods = ['GET'])
|
||||||
|
def getUserChats():
|
||||||
|
# Get user auth token
|
||||||
|
token = request.headers['token']
|
||||||
|
a, userId = checkUserPermission(token, True)
|
||||||
|
if (a == True):
|
||||||
|
returnedChats = list(chatCollection.find({'permissions.' + userId : "view"}))
|
||||||
|
chats = []
|
||||||
|
for doc in returnedChats:
|
||||||
|
if '_id' in doc and isinstance(doc['_id'], ObjectId):
|
||||||
|
doc['_id'] = str(doc['_id'])
|
||||||
|
chats.append(doc)
|
||||||
|
|
||||||
|
jsonChats = json.dumps(chats, indent=2)
|
||||||
|
return jsonChats
|
||||||
|
|
||||||
# Chat Details Endpoint:
|
# Chat Details Endpoint:
|
||||||
# Get or change details about a chat using the chatId
|
# Get or change details about a chat using the chatId
|
||||||
# Arguments: token (required), details (required), model, name
|
# Arguments: token (required), details (required), model, name
|
||||||
@app.route('/api/chat/<_id>/details', methods = ['GET', 'POST'])
|
@app.route('/api/chat/<_id>/details/<details>', methods = ['GET', 'POST'])
|
||||||
def getChatHistory(_id):
|
def getChatHistory(_id, details):
|
||||||
# Get user auth token
|
# Get user auth token
|
||||||
token = request.json['token']
|
token = request.headers['token']
|
||||||
a, userId = checkUserPermission(token, True)
|
a, userId = checkChatPermission(token, _id, True)
|
||||||
if (a == True):
|
if (a == True):
|
||||||
# Get the request details
|
|
||||||
details = request.json['details']
|
|
||||||
# If the user is trying to GET data
|
# If the user is trying to GET data
|
||||||
if (request.method == 'GET'):
|
if (request.method == 'GET'):
|
||||||
# Get the chat from the chatId
|
# Get the chat from the chatId
|
||||||
returnedChat = chatCollection.find_one({'_id': ObjectId(_id)})
|
returnedChat = chatCollection.find_one({'_id': ObjectId(_id)})
|
||||||
# Convert chatId into string
|
# Convert chatId into string
|
||||||
returnedChat['_id'] = str(returnedChat['_id'])
|
returnedChat['_id'] = str(returnedChat['_id'])
|
||||||
try:
|
# Get chat permissions
|
||||||
returnedChat["permissions"][userId].index("view")
|
a, userId = checkChatPermission(token, _id, "view")
|
||||||
|
if (a == True):
|
||||||
print("Chat " + _id + " has been found with token " + token)
|
print("Chat " + _id + " has been found with token " + token)
|
||||||
# Check for detail type and return correct value from db
|
# Check for detail type and return correct value from db
|
||||||
if (details == "history"):
|
if (details == "history"):
|
||||||
@@ -109,11 +164,11 @@ def getChatHistory(_id):
|
|||||||
return jsonify(returnedChat["model"])
|
return jsonify(returnedChat["model"])
|
||||||
elif (details == "name"):
|
elif (details == "name"):
|
||||||
return jsonify(returnedChat["name"])
|
return jsonify(returnedChat["name"])
|
||||||
except:
|
else:
|
||||||
return jsonify("Invalid Permissions")
|
return jsonify("Invalid Permissions")
|
||||||
else:
|
else:
|
||||||
try:
|
a, userId = checkChatPermission(token, _id, "view")
|
||||||
returnedChat["permissions"][userId].index("edit")
|
if (a == True):
|
||||||
# Check for the detail type and add data to db
|
# Check for the detail type and add data to db
|
||||||
if (details == "model"):
|
if (details == "model"):
|
||||||
model = request.json['model']
|
model = request.json['model']
|
||||||
@@ -122,7 +177,7 @@ def getChatHistory(_id):
|
|||||||
name = request.json['name']
|
name = request.json['name']
|
||||||
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "name": name } })
|
chatCollection.update_one({'_id': ObjectId(_id)}, { "$set": { "name": name } })
|
||||||
return jsonify("Success")
|
return jsonify("Success")
|
||||||
except:
|
else:
|
||||||
return jsonify("Invalid Permissions")
|
return jsonify("Invalid Permissions")
|
||||||
else:
|
else:
|
||||||
return jsonify("User token is invalid")
|
return jsonify("User token is invalid")
|
||||||
@@ -133,7 +188,7 @@ def getChatHistory(_id):
|
|||||||
@app.route('/api/chat/create', methods = ['POST'])
|
@app.route('/api/chat/create', methods = ['POST'])
|
||||||
def createChat():
|
def createChat():
|
||||||
# Get user auth token
|
# Get user auth token
|
||||||
token = request.json['token']
|
token = request.headers['token']
|
||||||
a, userId = checkUserPermission(token, "createChat")
|
a, userId = checkUserPermission(token, "createChat")
|
||||||
if (a == True):
|
if (a == True):
|
||||||
name = request.json['name']
|
name = request.json['name']
|
||||||
@@ -182,6 +237,19 @@ def index():
|
|||||||
else:
|
else:
|
||||||
render_template('logout.html', appName=appName)
|
render_template('logout.html', appName=appName)
|
||||||
|
|
||||||
|
@app.route('/chat/<_id>', methods = ['GET'])
|
||||||
|
def chatPage(_id):
|
||||||
|
token = request.cookies.get('auth_token', 'none')
|
||||||
|
if (token == 'none'):
|
||||||
|
return render_template('login.html', appName=appName, githubUrl=github_auth_endpoint, githublogin=settings["github_oauth"]["enabled"], oauthlogin=settings["oauth_login"])
|
||||||
|
else:
|
||||||
|
a, userId = checkUserPermission(token, True)
|
||||||
|
if (a == True):
|
||||||
|
return render_template('chat.html', appName=appName, chatId=_id)
|
||||||
|
else:
|
||||||
|
render_template('logout.html', appName=appName)
|
||||||
|
|
||||||
|
|
||||||
# Login endpoint
|
# Login endpoint
|
||||||
# Api backend for login screen, check for user and returns token
|
# Api backend for login screen, check for user and returns token
|
||||||
# Arguments: username (required), password (required)
|
# Arguments: username (required), password (required)
|
||||||
@@ -368,7 +436,7 @@ def handleSignup():
|
|||||||
def logout():
|
def logout():
|
||||||
token = request.cookies.get('auth_token', 'none')
|
token = request.cookies.get('auth_token', 'none')
|
||||||
try:
|
try:
|
||||||
token = request.json['remove_token']
|
token = request.headers['remove-token']
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
user = usersCollection.update_one({'tokens.token': token}, {"$pull":{'tokens':{'token':token}}})
|
user = usersCollection.update_one({'tokens.token': token}, {"$pull":{'tokens':{'token':token}}})
|
||||||
|
|||||||
@@ -4,8 +4,493 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Chat | {{ appName }}</title>
|
<title>Chat | {{ appName }}</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: 'Inter', sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background-color: #f0f4f9;
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar {
|
||||||
|
width: 280px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
color: #333;
|
||||||
|
padding: 20px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
border-right: 1px solid #e2e8f0;
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed {
|
||||||
|
width: 60px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed .chat-item-text {
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.1s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar {
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 8px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
color: #4a5568;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar:hover {
|
||||||
|
color: #1a73e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar svg {
|
||||||
|
transition: transform 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed #toggle-sidebar svg {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item {
|
||||||
|
padding: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 12px;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item:hover {
|
||||||
|
background-color: #f1f5f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item-text {
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-left: 10px;
|
||||||
|
opacity: 1;
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item svg {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#new-chat-button {
|
||||||
|
margin-top: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
#main-content {
|
||||||
|
flex-grow: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 24px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-area {
|
||||||
|
flex-grow: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding-bottom: 120px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-area::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
#chat-area::-webkit-scrollbar-track {
|
||||||
|
background: #f1f5f9;
|
||||||
|
}
|
||||||
|
#chat-area::-webkit-scrollbar-thumb {
|
||||||
|
background-color: #94a3b8;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
max-width: 70%;
|
||||||
|
word-wrap: break-word;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background-color: transparent;
|
||||||
|
border-radius: 0;
|
||||||
|
/* REQUIRED: Enable stacking of main text and thinking box */
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
/* REQUIRED: Stable target for streaming text updates */
|
||||||
|
#main-text {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
min-height: 1.5em; /* Prevent jump when text starts arriving */
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-message {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-message .message-content {
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-message {
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding-bottom: 16px;
|
||||||
|
border-bottom: 1px solid #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-message .message-content {
|
||||||
|
color: #333;
|
||||||
|
font-size: 1rem;
|
||||||
|
/* line-height: 1.5; */ /* REMOVED: Line height moved to #main-text */
|
||||||
|
}
|
||||||
|
|
||||||
|
#message-box-container {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px 24px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
border-top: 1px solid #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message-input {
|
||||||
|
flex-grow: 1;
|
||||||
|
padding: 12px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 0;
|
||||||
|
outline: none;
|
||||||
|
font-size: 16px;
|
||||||
|
background-color: transparent;
|
||||||
|
margin-right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-button {
|
||||||
|
padding: 10px;
|
||||||
|
border: none;
|
||||||
|
background-color: #1a73e8;
|
||||||
|
color: white;
|
||||||
|
border-radius: 50%;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-button:hover {
|
||||||
|
background-color: #1669c5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.think-container {
|
||||||
|
/* Mimics the overall <details> element: border and padding */
|
||||||
|
border: 1px solid #aaaaaa;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0.5em;
|
||||||
|
margin-top: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-sizing: border-box;
|
||||||
|
/* FIX: Prevent children from stretching horizontally (cross-axis alignment in column direction) */
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
/* MODIFIED: Styling applied to a <span> instead of a <button> */
|
||||||
|
#think-button {
|
||||||
|
/* Mimics the <summary> element: bold, no button chrome */
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #333;
|
||||||
|
font-size: 1rem;
|
||||||
|
transition: color 0.2s;
|
||||||
|
/* FIX: Ensure button size is strictly content-based to prevent horizontal stretching */
|
||||||
|
display: block;
|
||||||
|
width: fit-content;
|
||||||
|
}
|
||||||
|
#think-button:hover {
|
||||||
|
color: #1a73e8;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
#think-content {
|
||||||
|
/* Content area formatting: adds separator line when visible */
|
||||||
|
border-top: 1px solid #e2e8f0; /* Separator line */
|
||||||
|
padding-top: 0.5em;
|
||||||
|
background-color: transparent;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: #444;
|
||||||
|
}
|
||||||
|
.hidden {
|
||||||
|
display: none !important;
|
||||||
|
/* Ensure the separator is removed when content is hidden */
|
||||||
|
border-top: none !important;
|
||||||
|
padding-top: 0 !important;
|
||||||
|
margin-top: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body class="bg-gray-900 text-gray-100 flex h-screen overflow-hidden">
|
||||||
|
|
||||||
|
<aside id="sidebar">
|
||||||
|
<button id="toggle-sidebar">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<div class="chat-item">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 19L19 12M5 12L12 19M12 5L19 12L5 12L12 5Z" fill="none"/>
|
||||||
|
</svg>
|
||||||
|
<span class="chat-item-text">Chat with AI #1</span>
|
||||||
|
</div>
|
||||||
|
<div class="chat-item" id="new-chat-button">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 5L12 19M5 12L19 12"/>
|
||||||
|
</svg>
|
||||||
|
<span class="chat-item-text">New Chat</span>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<main id="main-content">
|
||||||
|
<div id="chat-area">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="message-box-container">
|
||||||
|
<input type="text" id="message-input" placeholder="Type your message...">
|
||||||
|
<button id="send-button">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
function toggleThink(aiMessageDiv) {
|
||||||
|
const isCurrentlyOpen = aiMessageDiv.getAttribute("data-thinkopen") === "true";
|
||||||
|
|
||||||
|
// 1. Get the content element by ID inside the message
|
||||||
|
const contentElement = aiMessageDiv.querySelector('#think-content');
|
||||||
|
const buttonElement = aiMessageDiv.querySelector('#think-button');
|
||||||
|
|
||||||
|
if (isCurrentlyOpen) {
|
||||||
|
// Set state to false (closed)
|
||||||
|
aiMessageDiv.setAttribute("data-thinkopen", "false");
|
||||||
|
// Hide the content
|
||||||
|
if (contentElement) contentElement.classList.add('hidden');
|
||||||
|
if (buttonElement) buttonElement.textContent = 'Show thinking';
|
||||||
|
} else {
|
||||||
|
// Set state to true (open)
|
||||||
|
aiMessageDiv.setAttribute("data-thinkopen", "true");
|
||||||
|
// Show the content
|
||||||
|
if (contentElement) contentElement.classList.remove('hidden');
|
||||||
|
if (buttonElement) buttonElement.textContent = 'Hide thinking';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCookie(cname) {
|
||||||
|
let name = cname + "=";
|
||||||
|
let decodedCookie = decodeURIComponent(document.cookie);
|
||||||
|
let ca = decodedCookie.split(';');
|
||||||
|
for(let i = 0; i <ca.length; i++) {
|
||||||
|
let c = ca[i];
|
||||||
|
while (c.charAt(0) == ' ') {
|
||||||
|
c = c.substring(1);
|
||||||
|
}
|
||||||
|
if (c.indexOf(name) == 0) {
|
||||||
|
return c.substring(name.length, c.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('toggle-sidebar').addEventListener('click', function() {
|
||||||
|
const sidebar = document.getElementById('sidebar');
|
||||||
|
sidebar.classList.toggle('collapsed');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('send-button').addEventListener('click', function() {
|
||||||
|
sendMessage();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('message-input').addEventListener('keypress', function(e) {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
sendMessage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function sendMessage() {
|
||||||
|
const input = document.getElementById('message-input');
|
||||||
|
let chatArea = document.getElementById('chat-area');
|
||||||
|
const messageText = input.value.trim();
|
||||||
|
const chatId = "{{ chatId }}"
|
||||||
|
const endpointUrl = "{{ url_for('generateMessage', _id='PLACEHOLDER') }}".replace('PLACEHOLDER', chatId);
|
||||||
|
const authToken = getCookie('auth_token');
|
||||||
|
|
||||||
|
if (messageText !== '') {
|
||||||
|
const messageblock = document.createElement('div');
|
||||||
|
chatArea = chatArea.appendChild(messageblock)
|
||||||
|
|
||||||
|
const userMessageDiv = document.createElement('div');
|
||||||
|
userMessageDiv.classList.add('message', 'user-message');
|
||||||
|
userMessageDiv.innerHTML = `<div class="message-content">${messageText}</div>`;
|
||||||
|
chatArea.appendChild(userMessageDiv);
|
||||||
|
input.value = '';
|
||||||
|
|
||||||
|
const aiMessageDiv = document.createElement('div');
|
||||||
|
aiMessageDiv.classList.add('message', 'ai-message');
|
||||||
|
// Inject a stable span for streaming content
|
||||||
|
aiMessageDiv.innerHTML = `<div class="message-content"><span id="main-text">Generating response...</span></div>`;
|
||||||
|
const responseDiv = chatArea.appendChild(aiMessageDiv);
|
||||||
|
|
||||||
|
// Initialize state
|
||||||
|
aiMessageDiv.setAttribute("data-thinkopen", "true");
|
||||||
|
|
||||||
|
const postData = {
|
||||||
|
"message": messageText
|
||||||
|
};
|
||||||
|
|
||||||
|
// Streaming state management (CRITICAL for non-destructive streaming)
|
||||||
|
let fullResponseString = '';
|
||||||
|
let mainContentText = '';
|
||||||
|
let thinkingContentText = '';
|
||||||
|
let inThinkBlock = false;
|
||||||
|
let thinkingBlockInjected = false;
|
||||||
|
let mainTextElement = null;
|
||||||
|
let thinkingContentElement = null;
|
||||||
|
const messageContentContainer = responseDiv.querySelector('.message-content');
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpointUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'token': authToken
|
||||||
|
},
|
||||||
|
body: JSON.stringify(postData)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder('utf-8');
|
||||||
|
|
||||||
|
// Get references after DOM elements are created
|
||||||
|
mainTextElement = responseDiv.querySelector('#main-text');
|
||||||
|
mainTextElement.textContent = ''; // Clear initial "Generating response..."
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value, { stream: true });
|
||||||
|
|
||||||
|
// DO NOT CHANGE THIS: CHUNKS CONTAIN THE WHOLE MESSAGE
|
||||||
|
fullResponseString = chunk.substring(6);
|
||||||
|
|
||||||
|
// Replaced old destructive logic with non-destructive state machine
|
||||||
|
// Check for state changes based on tags
|
||||||
|
if (fullResponseString.includes("<think>") && !inThinkBlock) {
|
||||||
|
inThinkBlock = true;
|
||||||
|
// Content before <think> is finalized in mainContentText
|
||||||
|
mainContentText = fullResponseString.substring(0, fullResponseString.indexOf("<think>"));
|
||||||
|
mainTextElement.textContent = mainContentText; // Update main text immediately
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fullResponseString.includes("</think>") && inThinkBlock) {
|
||||||
|
inThinkBlock = false;
|
||||||
|
// Content inside <think> is finalized in thinkingContentText
|
||||||
|
thinkingContentText = fullResponseString.substring(
|
||||||
|
fullResponseString.indexOf("<think>") + 7,
|
||||||
|
fullResponseString.lastIndexOf("</think>")
|
||||||
|
);
|
||||||
|
// Content after </think> becomes the new main content buffer
|
||||||
|
mainContentText = fullResponseString.substring(fullResponseString.lastIndexOf("</think>") + 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Injection logic: Only inject the button/span once
|
||||||
|
if (!thinkingBlockInjected && (inThinkBlock || fullResponseString.includes("</think>"))) {
|
||||||
|
|
||||||
|
const isThinkOpen = aiMessageDiv.getAttribute("data-thinkopen") === "true";
|
||||||
|
const hiddenClass = isThinkOpen ? '' : ' hidden';
|
||||||
|
const buttonText = isThinkOpen ? 'Hide thinking' : 'Show thinking';
|
||||||
|
const onClickHandler = `toggleThink(this.closest('.ai-message'))`;
|
||||||
|
|
||||||
|
// Injected a <span> with role="button" instead of a <button>
|
||||||
|
messageContentContainer.insertAdjacentHTML('afterbegin',
|
||||||
|
`<div class="think-container">` +
|
||||||
|
`<span id="think-button" role="button" tabindex="0" onclick="${onClickHandler}">${buttonText}</span>` +
|
||||||
|
`<span id="think-content" class="${hiddenClass}"></span>` +
|
||||||
|
`</div>`
|
||||||
|
);
|
||||||
|
|
||||||
|
thinkingContentElement = responseDiv.querySelector('#think-content');
|
||||||
|
thinkingBlockInjected = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update streaming text based on state (NON-DESTRUCTIVE)
|
||||||
|
if (inThinkBlock) {
|
||||||
|
// Extract only the new streaming content for the thinking box
|
||||||
|
let currentContent = fullResponseString.substring(fullResponseString.indexOf("<think>") + 7);
|
||||||
|
if (currentContent.includes("</think>")) {
|
||||||
|
currentContent = currentContent.substring(0, currentContent.lastIndexOf("</think>"));
|
||||||
|
}
|
||||||
|
if (thinkingContentElement) thinkingContentElement.textContent = currentContent;
|
||||||
|
} else if (thinkingBlockInjected) {
|
||||||
|
// Correctly combine the prefix (A) and the suffix (C) from the full string
|
||||||
|
// This ensures the final text is not duplicated.
|
||||||
|
let currentMainText = fullResponseString.substring(0, fullResponseString.indexOf("<think>"));
|
||||||
|
currentMainText = fullResponseString.substring(fullResponseString.lastIndexOf("</think>") + 8);
|
||||||
|
|
||||||
|
if (thinkingContentElement) thinkingContentElement.textContent = thinkingContentText;
|
||||||
|
if (mainTextElement) mainTextElement.textContent = currentMainText.trim();
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Initial state: streaming only to the main text element
|
||||||
|
mainTextElement.textContent = fullResponseString.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('An error has occurred:', error);
|
||||||
|
// Ensure error message is appended correctly
|
||||||
|
if (mainTextElement) mainTextElement.textContent += `\n\n--- An error has occurred: ${error.message} ---`;
|
||||||
|
else messageContentContainer.innerHTML = `\n\n--- An error has occurred: ${error.message} ---`;
|
||||||
|
}
|
||||||
|
|
||||||
|
chatArea.scrollTop = chatArea.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
434
templates/chat.html.bak
Normal file
434
templates/chat.html.bak
Normal file
@@ -0,0 +1,434 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Chat | {{ appName }}</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: 'Inter', sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background-color: #f0f4f9;
|
||||||
|
display: flex;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar {
|
||||||
|
width: 280px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
color: #333;
|
||||||
|
padding: 20px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
border-right: 1px solid #e2e8f0;
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed {
|
||||||
|
width: 60px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed .chat-item-text {
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.1s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar {
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 8px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
align-items: center;
|
||||||
|
color: #4a5568;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar:hover {
|
||||||
|
color: #1a73e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-sidebar svg {
|
||||||
|
transition: transform 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
#sidebar.collapsed #toggle-sidebar svg {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item {
|
||||||
|
padding: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 12px;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item:hover {
|
||||||
|
background-color: #f1f5f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item-text {
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-left: 10px;
|
||||||
|
opacity: 1;
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-item svg {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#new-chat-button {
|
||||||
|
margin-top: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
#main-content {
|
||||||
|
flex-grow: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 24px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-area {
|
||||||
|
flex-grow: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding-bottom: 120px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-area::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
#chat-area::-webkit-scrollbar-track {
|
||||||
|
background: #f1f5f9;
|
||||||
|
}
|
||||||
|
#chat-area::-webkit-scrollbar-thumb {
|
||||||
|
background-color: #94a3b8;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
max-width: 70%;
|
||||||
|
word-wrap: break-word;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background-color: transparent;
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
.user-message {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-message .message-content {
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-message {
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding-bottom: 16px;
|
||||||
|
border-bottom: 1px solid #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-message .message-content {
|
||||||
|
color: #333;
|
||||||
|
font-size: 1rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message-box-container {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px 24px;
|
||||||
|
background-color: #ffffff;
|
||||||
|
border-top: 1px solid #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message-input {
|
||||||
|
flex-grow: 1;
|
||||||
|
padding: 12px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 0;
|
||||||
|
outline: none;
|
||||||
|
font-size: 16px;
|
||||||
|
background-color: transparent;
|
||||||
|
margin-right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-button {
|
||||||
|
padding: 10px;
|
||||||
|
border: none;
|
||||||
|
background-color: #1a73e8;
|
||||||
|
color: white;
|
||||||
|
border-radius: 50%;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-button:hover {
|
||||||
|
background-color: #1669c5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.think-container {
|
||||||
|
/* Mimics the overall <details> element: border and padding */
|
||||||
|
border: 1px solid #aaaaaa;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0.5em;
|
||||||
|
margin-top: 8px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
#think-button {
|
||||||
|
/* Mimics the <summary> element: bold, no button chrome */
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #333;
|
||||||
|
font-size: 1rem;
|
||||||
|
transition: color 0.2s;
|
||||||
|
}
|
||||||
|
#think-button:hover {
|
||||||
|
color: #1a73e8;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
#think-content {
|
||||||
|
/* Content area formatting: adds separator line when visible */
|
||||||
|
border-top: 1px solid #e2e8f0; /* Separator line */
|
||||||
|
padding-top: 0.5em;
|
||||||
|
background-color: transparent;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: #444;
|
||||||
|
}
|
||||||
|
.hidden {
|
||||||
|
display: none !important;
|
||||||
|
/* Ensure the separator is removed when content is hidden */
|
||||||
|
border-top: none !important;
|
||||||
|
padding-top: 0 !important;
|
||||||
|
margin-top: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="bg-gray-900 text-gray-100 flex h-screen overflow-hidden">
|
||||||
|
|
||||||
|
<aside id="sidebar">
|
||||||
|
<button id="toggle-sidebar">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<div class="chat-item">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 19L19 12M5 12L12 19M12 5L19 12L5 12L12 5Z" fill="none"/>
|
||||||
|
</svg>
|
||||||
|
<span class="chat-item-text">Chat with AI #1</span>
|
||||||
|
</div>
|
||||||
|
<div class="chat-item" id="new-chat-button">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 5L12 19M5 12L19 12"/>
|
||||||
|
</svg>
|
||||||
|
<span class="chat-item-text">New Chat</span>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<main id="main-content">
|
||||||
|
<div id="chat-area">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="message-box-container">
|
||||||
|
<input type="text" id="message-input" placeholder="Type your message...">
|
||||||
|
<button id="send-button">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
function toggleThink(aiMessageDiv) {
|
||||||
|
const isCurrentlyOpen = aiMessageDiv.getAttribute("data-thinkopen") === "true";
|
||||||
|
|
||||||
|
// 1. Get the content element by ID inside the message
|
||||||
|
const contentElement = aiMessageDiv.querySelector('#think-content');
|
||||||
|
const buttonElement = aiMessageDiv.querySelector('#think-button');
|
||||||
|
|
||||||
|
if (isCurrentlyOpen) {
|
||||||
|
// Set state to false (closed)
|
||||||
|
aiMessageDiv.setAttribute("data-thinkopen", "false");
|
||||||
|
// Hide the content
|
||||||
|
if (contentElement) contentElement.classList.add('hidden');
|
||||||
|
if (buttonElement) buttonElement.textContent = 'Show thinking';
|
||||||
|
} else {
|
||||||
|
// Set state to true (open)
|
||||||
|
aiMessageDiv.setAttribute("data-thinkopen", "true");
|
||||||
|
// Show the content
|
||||||
|
if (contentElement) contentElement.classList.remove('hidden');
|
||||||
|
if (buttonElement) buttonElement.textContent = 'Hide thinking';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCookie(cname) {
|
||||||
|
let name = cname + "=";
|
||||||
|
let decodedCookie = decodeURIComponent(document.cookie);
|
||||||
|
let ca = decodedCookie.split(';');
|
||||||
|
for(let i = 0; i <ca.length; i++) {
|
||||||
|
let c = ca[i];
|
||||||
|
while (c.charAt(0) == ' ') {
|
||||||
|
c = c.substring(1);
|
||||||
|
}
|
||||||
|
if (c.indexOf(name) == 0) {
|
||||||
|
return c.substring(name.length, c.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('toggle-sidebar').addEventListener('click', function() {
|
||||||
|
const sidebar = document.getElementById('sidebar');
|
||||||
|
sidebar.classList.toggle('collapsed');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('send-button').addEventListener('click', function() {
|
||||||
|
sendMessage();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('message-input').addEventListener('keypress', function(e) {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
sendMessage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function sendMessage() {
|
||||||
|
const input = document.getElementById('message-input');
|
||||||
|
let chatArea = document.getElementById('chat-area');
|
||||||
|
const messageText = input.value.trim();
|
||||||
|
const chatId = "{{ chatId }}"
|
||||||
|
const endpointUrl = "{{ url_for('generateMessage', _id='PLACEHOLDER') }}".replace('PLACEHOLDER', chatId);
|
||||||
|
const authToken = getCookie('auth_token');
|
||||||
|
|
||||||
|
if (messageText !== '') {
|
||||||
|
const messageblock = document.createElement('div');
|
||||||
|
chatArea = chatArea.appendChild(messageblock)
|
||||||
|
|
||||||
|
const userMessageDiv = document.createElement('div');
|
||||||
|
userMessageDiv.classList.add('message', 'user-message');
|
||||||
|
userMessageDiv.innerHTML = `<div class="message-content">${messageText}</div>`;
|
||||||
|
chatArea.appendChild(userMessageDiv);
|
||||||
|
input.value = '';
|
||||||
|
|
||||||
|
const aiMessageDiv = document.createElement('div');
|
||||||
|
aiMessageDiv.classList.add('message', 'ai-message');
|
||||||
|
aiMessageDiv.innerHTML = `<div class="message-content">Generating response...</div>`;
|
||||||
|
const responseDiv = chatArea.appendChild(aiMessageDiv);
|
||||||
|
|
||||||
|
const postData = {
|
||||||
|
"message": messageText
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpointUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'token': authToken
|
||||||
|
},
|
||||||
|
body: JSON.stringify(postData)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder('utf-8');
|
||||||
|
|
||||||
|
let responseString = '';
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value, { stream: true });
|
||||||
|
|
||||||
|
responseString = chunk.substring(6);
|
||||||
|
|
||||||
|
const isThinkOpen = aiMessageDiv.getAttribute("data-thinkopen") === "true";
|
||||||
|
// Now used for visibility class
|
||||||
|
const hiddenClass = isThinkOpen ? '' : ' hidden';
|
||||||
|
const buttonText = isThinkOpen ? 'Hide thinking' : 'Show thinking';
|
||||||
|
|
||||||
|
if (responseString.includes("<think>")) {
|
||||||
|
// Handler no longer needs preventDefault as it's not a native <details>
|
||||||
|
const onClickHandler = `toggleThink(this.closest('.ai-message'))`;
|
||||||
|
|
||||||
|
const contentBeforeThink = responseString.substring(0, responseString.indexOf("<think>"));
|
||||||
|
|
||||||
|
let contentInsideThink = '';
|
||||||
|
let contentAfterThink = '';
|
||||||
|
|
||||||
|
if (responseString.includes("</think>")) {
|
||||||
|
contentInsideThink = responseString.substring(
|
||||||
|
responseString.indexOf("<think>") + 7,
|
||||||
|
responseString.lastIndexOf("</think>")
|
||||||
|
);
|
||||||
|
contentAfterThink = responseString.substring(responseString.lastIndexOf("</think>") + 8);
|
||||||
|
} else {
|
||||||
|
contentInsideThink = responseString.substring(responseString.indexOf("<think>") + 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
responseString =
|
||||||
|
contentBeforeThink +
|
||||||
|
`<div class="think-container">` +
|
||||||
|
`<button id="think-button" onclick="${onClickHandler}">${buttonText}</button>` +
|
||||||
|
`<span id="think-content" class="${hiddenClass}">` +
|
||||||
|
contentInsideThink +
|
||||||
|
`</span>` +
|
||||||
|
`</div>` +
|
||||||
|
contentAfterThink;
|
||||||
|
}
|
||||||
|
|
||||||
|
responseDiv.innerHTML = `<div class="message-content">${responseString}</div>`;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('An error has occurred:', error);
|
||||||
|
responseDiv.innerHTML = `<div class="message-content">\n\n--- An error has occurred: ${error.message} ---</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
chatArea.scrollTop = chatArea.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
71
templates/chattest.html
Normal file
71
templates/chattest.html
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Streaming Response</title>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<h1>AiThingy</h1>
|
||||||
|
<p>Enter a message, chatId, and auth token below:</p>
|
||||||
|
<input placeholder="Message" id="message"></input>
|
||||||
|
<input placeholder="ChatId" id="chatid"></input>
|
||||||
|
<input placeholder="Token" id="token"></input>
|
||||||
|
<button onclick="startStreaming()">Send Message</button>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<textarea id="response-output" readonly placeholder="Waiting for streaming data..."></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
async function startStreaming() {
|
||||||
|
const outputArea = document.getElementById('response-output');
|
||||||
|
outputArea.value = 'Connecting to endpoint...\n';
|
||||||
|
const chatId = document.getElementById("chatid").value;
|
||||||
|
const endpointUrl = 'http://127.0.0.1:5000/api/chat/' + chatId + '/generate';
|
||||||
|
const postData = {
|
||||||
|
"message": document.getElementById("message").value
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpointUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'token': document.getElementById("token").value
|
||||||
|
},
|
||||||
|
body: JSON.stringify(postData)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder('utf-8');
|
||||||
|
let receivedChunks = '';
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value, { stream: true });
|
||||||
|
const responseString = chunk.substring(6);
|
||||||
|
outputArea.value = responseString;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('An error has occurred:', error);
|
||||||
|
outputArea.value += `\n\n--- An error has occurred: ${error.message} ---`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user