This commit is contained in:
James Ketr 2025-03-20 17:42:35 -07:00
parent 0a4587437d
commit ce6cdac00b
22 changed files with 17194 additions and 30 deletions

View File

@ -229,7 +229,7 @@ RUN pip install setuptools --upgrade
RUN pip install ollama
RUN pip install feedparser bs4 chromadb
RUN pip install tiktoken
RUN pip install flask flask_cors
RUN pip install flask flask_cors flask_sock
RUN pip install peft datasets
COPY --from=ipex-llm-src /opt/ipex-llm/python/llm/dist/*.whl /opt/wheels/
@ -253,7 +253,7 @@ RUN pip3 install 'bigdl-core-xe-all>=2.6.0b'
RUN pip install einops diffusers # Required for IPEX optimize(), which is required to convert from Params4bit
# Install packages needed for stock.py
RUN pip install yfinance pyzt geopy PyHyphen
RUN pip install yfinance pyzt geopy PyHyphen nltk
SHELL [ "/bin/bash", "-c" ]

View File

@ -69,7 +69,7 @@ services:
- 8888:8888 # Jupyter Notebook
- 60673:60673 # Gradio
- 5000:5000 # Flask React server
- 8081:8081 # REACT expo
- 3000:3000 # REACT expo
networks:
- internal
volumes:

View File

@ -14,6 +14,7 @@ from datetime import datetime
import textwrap
import threading
import uuid
import random
def try_import(module_name, pip_name=None):
try:
@ -36,7 +37,10 @@ try_import('hyphen', 'PyHyphen')
try_import('bs4', 'beautifulsoup4')
try_import('flask')
try_import('flask_cors')
try_import('flask_sock')
try_import('nltk')
import nltk
from dotenv import load_dotenv
from geopy.geocoders import Nominatim
import gradio as gr
@ -50,6 +54,7 @@ from hyphen import hyphenator
from bs4 import BeautifulSoup
from flask import Flask, request, jsonify, render_template, send_from_directory, redirect
from flask_cors import CORS
from flask_sock import Sock
from tools import (
get_weather_by_location,
@ -98,6 +103,7 @@ command_log = []
model = None
client = None
irc_bot = None
web_server = None
# %%
# Cmd line overrides
@ -130,6 +136,24 @@ def setup_logging(level):
logging.info(f"Logging is set to {level} level.")
# %%
def is_words_downloaded():
try:
from nltk.corpus import words
words.words() # Attempt to access the dataset
return True
except LookupError:
return False
if not is_words_downloaded():
logging.info("Downloading nltk words corpus for random nick generation")
nltk.download('words')
def random_nick():
from nltk.corpus import words
word_list = words.words()
return random.choice(word_list).capitalize()
# %%
def split_paragraph_with_hyphenation(text, line_length=80, language='en_US'):
"""
@ -320,7 +344,7 @@ async def summarize_site(url, question):
return f"Error processing the website content: {str(e)}"
async def chat(history):
global client, model, irc_bot, system_log, tool_log
global client, model, irc_bot, system_log, tool_log, web_server
if not client:
return history
@ -373,7 +397,7 @@ async def chat(history):
class DynamicIRCBot(pydle.Client):
def __init__(self, nickname, channel, bot_admin, system_info, burst_limit = 5, rate_limit = 1.0, burst_reset_timeout = 10.0, **kwargs):
super().__init__(nickname, **kwargs)
self.history = []
self.histories = {}
self.channel = channel
self.bot_admin = bot_admin
self.system_info = system_info
@ -386,6 +410,7 @@ class DynamicIRCBot(pydle.Client):
self.last_message_time = None # Track last message time
self._message_queue = asyncio.Queue()
self._task = asyncio.create_task(self._send_from_queue())
self.processing = False
async def _send_from_queue(self):
"""Background task that sends queued messages with burst + rate limiting."""
@ -451,16 +476,25 @@ class DynamicIRCBot(pydle.Client):
await super().on_part(channel, user)
logging.info(f"PART: {channel} => {user}")
async def on_message(self, target, source, message, local_user=None):
global system_log, tool_log, system_log, command_log
async def on_message(self, target, source, message, session, local_user=None):
global system_log, tool_log, system_log, command_log, web_server
if not local_user:
await super().on_message(target, source, message)
message = message.strip()
logging.info(f"MESSAGE: {source} => {target}: {message}")
if source == self.nickname and not local_user:
return
last_message = self.history[-1] if len(self.history) > 0 and self.history[-1]["role"] == "user" else None
if self.processing:
await self.message(target, f"I'm already processing a query.")
return
if session not in self.histories:
self.histories[session] = []
history = self.histories[session]
last_message = history[-1] if len(history) > 0 and history[-1]["role"] == "user" else None
try:
matches = re.match(r"^([^:]+)\s*:\s*(.*)$", message)
if matches:
@ -484,12 +518,18 @@ class DynamicIRCBot(pydle.Client):
"role": "user",
"content": f"{source}: {content}"
}
self.history.append(last_message)
history.append(last_message)
return
matches = re.match(r"^!([^\s]+)\s*(.*)?$", content)
if not matches:
logging.info(f"Non-command directed message to {self.nickname}: Invoking chat...")
self.processing = True
if web_server:
for session in web_server.sessions.values():
for socket in session['sockets']:
socket.send(json.dumps({"type": "processing", "value": self.processing}))
# Add this message to the history either to the current 'user' context or create
# add a new message
if last_message:
@ -501,10 +541,17 @@ class DynamicIRCBot(pydle.Client):
"role": "user",
"content": f"{source}: {content}"
}
self.history.append(last_message)
self.history = await chat(self.history)
chat_response = self.history[-1]
history.append(last_message)
history = await chat(history)
chat_response = history[-1]
await self.message(target, chat_response['content'])
self.processing = False
if web_server:
for session in web_server.sessions.values():
for socket in session['sockets']:
socket.send(json.dumps({"type": "processing", "value": self.processing}))
return
command = matches.group(1)
@ -520,18 +567,18 @@ class DynamicIRCBot(pydle.Client):
case "context":
system_log_size = total_json_length(system_log)
history_size = total_json_length(self.history)
history_size = total_json_length(history)
tools_size = total_json_length(tools)
total_size = system_log_size + history_size + tools_size
response = f"\nsystem prompt: {system_log_size}"
response += f"\nhistory: {history_size} in {len(self.history)} entries."
response += f"\nhistory: {history_size} in {len(history)} entries."
response += f"\ntools: {tools_size} in {len(tools)} tools."
response += f"\ntotal context: {total_size}"
response += f"\ntotal tool calls: {len(tool_log)}"
case "reset":
system_log = [{"role": "system", "content": system_message}]
self.history = []
history.clear()
tool_log = []
command_log = []
response = 'All contexts reset'
@ -641,7 +688,7 @@ async def create_ui():
if not irc_bot:
return gr.skip()
await irc_bot.message(irc_bot.channel, f"[console] {message}")
await irc_bot.on_message(irc_bot.channel, irc_bot.nickname, f"{irc_bot.nickname}: {message}", local_user="gradio")
await irc_bot.on_message(irc_bot.channel, irc_bot.nickname, f"{irc_bot.nickname}: {message}", session="gradio", local_user="gradio")
return "", irc_bot.history
def do_clear():
@ -679,6 +726,14 @@ async def create_ui():
return ui
# %%
def is_valid_uuid(value):
try:
uuid_obj = uuid.UUID(value, version=4)
return str(uuid_obj) == value
except (ValueError, TypeError):
return False
# %%
class WebServer:
"""Web interface"""
@ -686,43 +741,137 @@ class WebServer:
def __init__(self, logging):
self.logging = logging
self.app = Flask(__name__, static_folder='/opt/airc/src/client/dist', static_url_path='')
CORS(self.app, resources={r"/*": {"origins": "http://battle-linux.ketrenos.com:5000"}})
self.sock = Sock(self.app)
self.sessions = {}
CORS(self.app, resources={r"/*": {"origins": "http://battle-linux.ketrenos.com:3000"}})
# Setup routes
self.setup_routes()
# Generate a unique session ID
def generate_session_id(self):
return str(uuid.uuid4())
def generate_session(self, socket, existing_uuid=None):
session = {
"id": existing_uuid if existing_uuid else str(uuid.uuid4()),
"system": system_message,
"users": [],
"history": [],
"sockets": [socket]
}
logging.info(f"{session['id']} created and added to sessions.")
self.sessions[session['id']] = session
return session
def setup_routes(self):
"""Setup Flask routes"""
@self.sock.route('/api/ws/<session_id>')
def websocket(ws, session_id):
user = random_nick()
if not session_id in self.sessions:
self.generate_session(ws, session_id)
else:
self.sessions[session_id]['sockets'].append(ws)
while True:
try:
data = ws.receive()
data = json.loads(data)
logging.info(f"Message received from {user}: {data['type']}")
if 'session' not in data or 'type' not in data:
ws.send(json.dumps({"type": "error", "error": f"Invalid request: {data}"}))
continue
if session_id != data['session']:
ws.send(json.dumps({"type": "error", "error": f"Invalid request: {data}"}))
self.sessions[session_id]['last_access'] = datetime.now()
if user not in self.sessions[session_id]['users']:
logging.info(f"Adding {user} to session {session_id}. Existing users: {self.sessions[session_id]['users']}")
self.sessions[session_id]['users'].append(user)
for socket in self.sessions[session_id]['sockets']:
socket.send(json.dumps({"type": "users", "update": self.sessions[session_id]['users']}))
match data['type']:
case "processing":
if irc_bot:
ws.send(json.dumps({"type": "processing", "value": irc_bot.processing}))
else:
ws.send(json.dumps({"type": "processing", "value": False}))
case "user-change":
if data['value'] in self.sessions[session_id]['users']:
ws.send(json.dumps({"type": "user", "update": user}))
else:
self.sessions[session_id]['users'] = [data['value'] if name == user else name for name in self.sessions[session_id]['users']]
user = data['value']
ws.send(json.dumps({"type": "user", "update": user}))
for socket in self.sessions[session_id]['sockets']:
socket.send(json.dumps({"type": "users", "update": self.sessions[session_id]['users']}))
case "user":
ws.send(json.dumps({"type": "user", "update": user}))
case "users":
ws.send(json.dumps({"type": "users", "update": self.sessions[session_id]['users']}))
case "history":
if not irc_bot:
ws.send(json.dumps({"type": "history", "update": []}))
else:
if session_id in irc_bot.histories:
ws.send(json.dumps({"type": "history", "update": irc_bot.histories[session_id]}))
else:
ws.send(json.dumps({"type": "history", "update": []}))
case _:
ws.send(json.dumps({"type": "error", "error": f"Invalid request type: {data['type']}"}))
except Exception as e:
logging.error(f"WebSocket error: {str(e)}")
self.sessions[session_id]['users'].remove(user)
self.sessions[session_id]['sockets'].remove(ws)
for socket in self.sessions[session_id]['sockets']:
socket.send(json.dumps({"type": "users", "update": self.sessions[session_id]['users']}))
# Serve React app - This catches all routes not matched by API endpoints
@self.app.route('/')
def root():
# Generate a new unique session ID
session_id = self.generate_session_id()
session = self.generate_session(None)
# Redirect to the unique session path
self.logging.info(f"Redirecting non-session to {session_id}")
return redirect(f'/{session_id}')
self.logging.info(f"Redirecting non-session to {session['id']}")
return redirect(f"/{session['id']}")
# Basic endpoint for chat completions
@self.app.route('/api/chat', methods=['POST'])
async def chat():
@self.app.route('/api/chat/<session_id>', methods=['POST'])
async def chat(session_id):
if not irc_bot:
return jsonify({ "error": "Bot not initialized" }), 400
try:
data = request.get_json()
logging.info(f"/chat data={data}")
await irc_bot.on_message(irc_bot.channel, irc_bot.nickname, f"{irc_bot.nickname}: {data}", local_user="web")
return jsonify(irc_bot.history)
await irc_bot.on_message(irc_bot.channel, irc_bot.nickname, f"{irc_bot.nickname}: {data}", session=session_id, local_user="web")
if session_id in irc_bot.histories:
for socket in self.sessions[session_id]['sockets']:
socket.send(json.dumps({"type": "history", "update": irc_bot.histories[session_id]}))
return jsonify({ "success": "Message submitted to chat agent" }), 200
except Exception as e:
logging.exception(data)
return jsonify({
"error": "Invalid request"
}), 400
# Basic endpoint for chat completions
@self.app.route('/api/session', methods=['GET'])
async def create_session():
# Generate a new unique session ID
session = self.generate_session(None)
# Redirect to the unique session path
self.logging.info(f"Generating new session as {session['id']}")
return jsonify(session), 200
# Context requests
@self.app.route('/api/history', methods=['GET'])
def http_history():
@ -799,7 +948,7 @@ class WebServer:
# Main function to run everything
async def main():
global irc_bot, client, model
global irc_bot, client, model, web_server
# Parse command-line arguments
args = parse_args()
if not re.match(r"^#", args.irc_channel):
@ -819,9 +968,9 @@ async def main():
logging.info(args)
if not args.web_disable:
server = WebServer(logging)
web_server = WebServer(logging)
logging.info(f"Starting web server at http://{args.web_host}:{args.web_port}")
threading.Thread(target=lambda: server.run(host=args.web_host, port=args.web_port, debug=True, use_reloader=False)).start()
threading.Thread(target=lambda: web_server.run(host=args.web_host, port=args.web_port, debug=True, use_reloader=False)).start()
await irc_bot.handle_forever()

23
src/ketr-chat/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

46
src/ketr-chat/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

16239
src/ketr-chat/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
{
"name": "ketr-chat",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.126",
"@types/react": "^19.0.12",
"@types/react-dom": "^19.0.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-scripts": "5.0.1",
"react-spinners": "^0.15.0",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

130
src/ketr-chat/src/App.css Normal file
View File

@ -0,0 +1,130 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.container {
display: flex;
flex-direction: column;
height: 100vh;
max-height: 100vh;
overflow: auto;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.query-box,
.user-box {
display: flex;
margin-bottom: 20px;
}
.query-box input,
.user-box input {
flex-grow: 1;
padding: 8px;
font-size: 1rem;
}
.query-box button,
.user-box button {
padding: 0.5rem 1rem;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
.conversation {
background-color: #F5F5F5;
border: 1px solid #E0E0E0;
flex-grow: 1;
overflow-y: auto;
padding: 10px;
margin-bottom: 20px;
}
.user-message {
background-color: #DCF8C6;
border: 1px solid #B2E0A7;
color: #333333;
padding: 0.5rem;
margin-bottom: 0.75rem;
margin-left: 1rem;
border-radius: 0.25rem;
min-width: 70%;
max-width: 70%;
justify-self: right;
display: flex;
white-space: pre-wrap;
overflow-wrap: break-word;
word-break: break-word;
flex-direction: column;
}
.assistant-message {
background-color: #FFFFFF;
border: 1px solid #E0E0E0;
color: #333333;
padding: 0.5rem;
margin-bottom: 0.75rem;
margin-right: 1rem;
min-width: 70%;
max-width: 70%;
border-radius: 0.25rem;
justify-self: left;
display: flex;
white-space: pre-wrap;
overflow-wrap: break-word;
word-break: break-word;
flex-direction: column;
}
.users > div {
padding: 0.25rem;
}
.user-active {
font-weight: bold;
}
.metadata {
border: 1px solid #E0E0E0;
font-size: 0.75rem;
padding: 0.125rem;
}

381
src/ketr-chat/src/App.tsx Normal file
View File

@ -0,0 +1,381 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import PropagateLoader from "react-spinners/PropagateLoader";
//import Markdown from 'react-native-markdown-display';
import './App.css';
import { createSemanticDiagnosticsBuilderProgram } from 'typescript';
const welcome_message = "Welcome to Ketr-Chat. I have real-time access to a lot of information. Ask things like 'What are the headlines from cnn.com?' or 'What is the weather in Portland, OR?'";
const url: string = "http://battle-linux.ketrenos.com:5000"
const App = () => {
const [query, setQuery] = useState('');
const [conversation, setConversation] = useState<MessageList>([{"role": "assistant", "content": "Connecting to server..."}]);
const conversationRef = useRef(null);
const [processing, setProcessing] = useState(false);
const [ws, setWs] = useState<WebSocket | undefined>(undefined);
const [loaded, setLoaded] = useState<boolean>(false);
const [connection, setConnection] = useState<any | undefined>(undefined);
const [sessionId, setSessionId] = useState<string | undefined>(undefined);
const [users, setUsers] = useState<string[]>([]);
const [user, setUser] = useState<string>("");
const [userChange, setUserChange] = useState<string>("");
const getApiUrl = (endpoint: string) => {
return `${url}/${endpoint}?sessionId=${sessionId}`;
};
useEffect(() => {
const url = new URL(window.location.href);
const pathParts = url.pathname.split('/').filter(Boolean);
if (!pathParts.length) {
console.log("No session id -- creating a new session")
fetch(getApiUrl('/api/session'))
.then(response => response.json())
.then(data => {
console.log(`Session id: ${data.id} -- returned from server`)
setSessionId(data.id);
window.history.replaceState({}, '', `/${data.id}`);
})
.catch(error => console.error('Error generating session ID:', error));
} else {
console.log(`Session id: ${pathParts[0]} -- existing session`)
setSessionId(pathParts[0]);
}
}, [setSessionId]);
const onWsOpen = (event: any) => {
console.log(`ws: open`);
/* We do not set the socket as connected until the 'open' message
* comes through */
setConnection(event.target);
/* Request a full history update */
event.target.send(JSON.stringify({
session: sessionId,
type: 'history'
}));
event.target.send(JSON.stringify({
session: sessionId,
type: 'users'
}));
event.target.send(JSON.stringify({
session: sessionId,
type: 'user'
}));
event.target.send(JSON.stringify({
session: sessionId,
type: 'processing'
}));
};
const onWsMessage = (event:any) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'error':
console.error(`App - error`, data.error);
break;
case 'warning':
console.warn(`App - warning`, data.warning);
break;
case 'history':
if (!loaded) {
setLoaded(true);
}
if (data.update.length) {
setConversation(data.update);
} else {
setConversation([{
role: "assistant",
content: welcome_message
}])
}
break;
case 'user':
if (!loaded) {
setLoaded(true);
}
setUser(data.update);
console.log(`user = ${data.update}`)
break;
case 'users':
if (!loaded) {
setLoaded(true);
}
setUsers(data.update);
console.log(`users = ${data.update}`)
break;
case 'processing':
console.log(`processing = ${data.value}`)
setProcessing(data.value);
break;
default:
break;
}
};
const resetConnection = useCallback(() => {
let timer: any = 0;
function reset() {
timer = 0;
setConnection(undefined);
};
return (_: any) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(reset, 5000);
};
}, [setConnection]);
const onWsError = (event: any) => {
console.error(`ws: error`, event);
setWs(undefined);
resetConnection();
};
const onWsClose = (event: any) => {
console.warn(`ws: close`);
setWs(undefined);
resetConnection();
};
/* callback refs are used to provide correct state reference
* in the callback handlers, while also preventing rebinding
* of event handlers on every render */
const refWsOpen = useRef(onWsOpen);
useEffect(() => { refWsOpen.current = onWsOpen; });
const refWsMessage = useRef(onWsMessage);
useEffect(() => { refWsMessage.current = onWsMessage; });
const refWsClose = useRef(onWsClose);
useEffect(() => { refWsClose.current = onWsClose; });
const refWsError = useRef(onWsError);
useEffect(() => { refWsError.current = onWsError; });
/* Once a session id is known, create the sole WebSocket connection
* to the backend. This WebSocket is then shared with any component
* that performs game state updates. Those components should
* bind to the 'message:update' WebSocket event and parse
* their update information from those messages
*/
useEffect(() => {
if (!sessionId) {
return;
}
const unbind = () => {
console.log(`App - unbind`);
}
console.log(`App - bind`);
let socket = ws;
if (!socket && !connection) {
let loc = window.location, new_uri;
if (loc.protocol === "https:") {
new_uri = "wss://";
} else {
new_uri = "ws://";
}
//new_uri += loc.host + `/api/ws/${sessionId}`;
new_uri += `battle-linux.ketrenos.com:5000/api/ws/${sessionId}`;
console.log(`Attempting WebSocket connection to ${new_uri}`);
socket = new WebSocket(new_uri)
setWs(socket);
setConnection(undefined);
return unbind;
}
if (!socket) {
return unbind;
}
const cbOpen = (e: any) => refWsOpen.current(e);
const cbMessage = (e: any) => refWsMessage.current(e);
const cbClose = (e: any) => refWsClose.current(e);
const cbError = (e: any) => refWsError.current(e);
socket.addEventListener('open', cbOpen);
socket.addEventListener('close', cbClose);
socket.addEventListener('error', cbError);
socket.addEventListener('message', cbMessage);
return () => {
unbind();
if (ws) {
ws.removeEventListener('open', cbOpen);
ws.removeEventListener('close', cbClose);
ws.removeEventListener('error', cbError);
ws.removeEventListener('message', cbMessage);
}
}
}, [ setWs, connection, setConnection, sessionId, ws, refWsOpen, refWsMessage, refWsClose, refWsError ]);
const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
switch (event.currentTarget.id) {
case 'query-input':
sendQuery();
break;
case 'user-input':
sendUserChange();
break;
}
}
};
type MessageMetadata = {
title: string
};
type Message = {
role: string,
content: string,
user?: string,
metadata?: MessageMetadata
};
type MessageList = Message[];
const sendQuery = async () => {
if (!query.trim()) return;
// Add user message to conversation
const newConversation: MessageList = [
...conversation,
{ role: 'user', content: query }
];
setConversation(newConversation);
// Clear input
setQuery('');
try {
setProcessing(true);
// Send query to server
const response = await fetch(getApiUrl(`/api/chat/${sessionId}`), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(query.trim()),
});
const data = await response.json();
if (data.error) {
console.error(data);
} else if (data.success) {
console.log(data);
}
} catch (error) {
console.error('Error:', error);
setConversation([
...newConversation,
{ role: 'assistant', content: 'Error processing your query. Please try again.' }
]);
}
};
const sendUserChange = async () => {
if (!userChange.trim()) return;
setUserChange('');
connection.send(JSON.stringify({
session: sessionId,
type: 'user-change',
value: userChange
}));
};
return (
<>
<div className="container">
<div style={{display: "flex", flexDirection: "column"}}>
<div className="conversation" ref={conversationRef}>
{conversation.map((message, index) => {
const formattedContent = message.content
.split("\n")
.map((line) => line.replace(/^[^\s:]+:\s*/, ''))
.join("\n");
return (
<div key={index} className={message.role === 'user' ? 'user-message' : 'assistant-message'}>
{message.metadata ? (
<>
<div className="metadata">{message.metadata.title}</div>
{ message.user && (
<div>{message.user}</div>
) }
<div>{formattedContent}</div>
</>
) : (
<>
{ message.user && (
<div>{message.user}</div>
) }
<div>{formattedContent}</div>
</>
)}
</div>
);
})}
<div style={{justifyContent: "center", display: "flex", paddingBottom: "0.5rem"}}>
<PropagateLoader
size="10px"
loading={processing}
aria-label="Loading Spinner"
data-testid="loader"
/>
</div>
</div>
</div>
<div className="users" style={{display: "flex", flexDirection: "row"}}>
<div>Users in this session: </div>
{users.map((name, index) => (
<div key={index} className={user === name ? `user-active` : `user`}>
{name}
</div>
))}
</div>
<div className="query-box">
<input
disabled={connection ? false : true || processing}
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={handleKeyPress}
placeholder="Enter your query..."
id="query-input"
/>
<button onClick={sendQuery}>Send</button>
</div>
<div className="user-box">
<input
disabled={connection ? false : true}
type="text"
value={userChange}
onChange={(e) => setUserChange(e.target.value)}
onKeyDown={handleKeyPress}
placeholder="Change your name..."
id="user-input"
/>
<button onClick={sendUserChange}>Send</button>
</div>
</div>
</>
);
};
export default App;

View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

1
src/ketr-chat/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}