-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
76 lines (59 loc) · 2.53 KB
/
Copy pathserver.py
File metadata and controls
76 lines (59 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import asyncio
import websockets
import json
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
import threading
from autocomplete import get_suggestion
PORT = 8000
WS_PORT = 8765
chat_history = []
clients = set()
async def handle_ws(websocket):
clients.add(websocket)
try:
async for msg in websocket:
data = json.loads(msg)
if data["type"] == "message":
chat_history.append((data["sender"], data["text"]))
payload = json.dumps({"type": "message", "sender": data["sender"], "text": data["text"]})
await asyncio.gather(*[client.send(payload) for client in clients])
elif data["type"] == "suggest":
prompt = "You are a helpful assistant. You are given a conversation history. You are supposed to keep the conversation alive. Conversation history:"
# Build full prompt from history
print("\n Suggestion Request From:", websocket.remote_address)
for sender, text in chat_history:
prompt += f"{text}\n"
prompt += f"You: {data['text']}"
print("Full Prompt:\n", prompt)
suggestion = get_suggestion(prompt)
print("Generated Suggestion:", suggestion)
await websocket.send(json.dumps({
"type": "suggestion",
"text": suggestion
}))
finally:
clients.remove(websocket)
def serve_static():
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=".", **kwargs)
def translate_path(self, path):
# Remove any query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
if path == "/":
path = "/static/index.html"
elif path == "/main.js":
path = "/static/main.js"
return SimpleHTTPRequestHandler.translate_path(self, path)
with TCPServer(("", PORT), Handler) as httpd:
print(f"[HTTP] Serving static files at http://localhost:{PORT}")
httpd.serve_forever()
async def run_ws_server():
print(f"[WebSocket] Running on ws://localhost:{WS_PORT}")
async with websockets.serve(handle_ws, "0.0.0.0", WS_PORT):
await asyncio.Future()
if __name__ == "__main__":
threading.Thread(target=serve_static, daemon=True).start()
asyncio.run(run_ws_server())