-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
2938 lines (2524 loc) · 102 KB
/
app.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import eventlet
# eventlet.monkey_patch()
import gevent
from gevent import monkey
monkey.patch_all()
import json
import yaml
import os
import random
import boto3
import tiktoken
import together
from flask import (
Flask,
render_template,
request,
send_from_directory,
jsonify,
Response,
)
from flask_socketio import SocketIO, emit, join_room
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import InvalidRequestError
from groq import Groq
from mistralai import Mistral
from openai import OpenAI
app = Flask(__name__)
app.config["SECRET_KEY"] = "your_secret_key"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///chat.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# socketio = SocketIO(app, async_mode="eventlet")
socketio = SocketIO(app, async_mode="gevent")
# Global dictionary to keep track of cancellation requests
cancellation_requests = {}
system_users = [
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-5-sonnet-20240620-v1:0",
"anthropic.claude-3-opus-20240229-v1:0",
"gpt-3.5-turbo",
"gpt-4",
"gpt-4o",
"gpt-4o-mini",
"gpt-4o-2024-08-06",
"gpt-4-1106-preview",
"gpt-4-turbo-preview",
"gpt-4-turbo",
"o1-mini",
"mistral",
"mistral-tiny",
"mistral-small",
"mistral-medium",
"mistral-large-latest",
"mistralai/Mixtral-8x7B-v0.1",
"mistralai/Mistral-7B-Instruct-v0.1",
"mixtral-8x7b-32768",
"open-mistral-nemo",
"llama2-70b-4096",
"llama3-70b-8192",
"gemma-7b-it",
"openchat/openchat-3.5-1210",
"openchat/openchat-3.5-0106",
"upstage/SOLAR-10.7B-Instruct-v1.0",
"teknium/OpenHermes-2.5-Mistral-7B",
"NousResearch/Hermes-2-Pro-Llama-3-8B",
"NousResearch/Hermes-3-Llama-3.1-8B",
"mistral-7b-instruct-v0.2.Q3_K_L.gguf",
"mistral-7b-instruct-v0.2-code-ft.Q3_K_L.gguf",
"openhermes-2.5-mistral-7b.Q6_K.gguf",
"System",
]
HELP_MESSAGE = """
**Available Commands:**
- `/activity [s3_file_path]`: Start an activity from the specified S3 file path.
- `/activity cancel`: Cancel the current activity.
- `/activity info`: Display information about the current activity.
- `/activity metadata`: Display metadata for the current activity.
- `/s3 ls [s3_file_path_pattern]`: List files in S3 matching the pattern.
- `/s3 load [s3_file_path]`: Load a file from S3.
- `/s3 save [s3_key_path]`: Save the most recent code block from the chatroom to S3.
- `/title new`: Generates a new title which reflects conversation content for the current chatroom using gpt-4.
- `/cancel`: Cancel the most recent chat completion from streaming into the chatroom.
- `/help`: Display this help message.
**Available Models:**
- `gpt-3`: For GPT-3, send a message with `gpt-3` and include your prompt.
- `gpt-4`: For GPT-4, send a message with `gpt-4` and include your prompt.
- `gpt-4o-2024-08-06`: For the cheapest version of GPT-4o, send a message with `gpt-4o-2024-08-06` and include your prompt.
- `gpt-mini`: For GPT-4o-mini, send a message with `gpt-mini` and include your prompt.
- `gpt-o1-mini`: For GPT-o1-mini, send a message with `gpt-o1-mini` and include your prompt.
- `claude-haiku`: For Claude-haiku, send a message with `claude-haiku` and include your prompt.
- `claude-sonnet`: For Claude-sonnet, send a message with `claude-sonnet` and include your prompt.
- `claude-opus`: For Claude-opus, send a message with `claude-opus` and include your prompt.
- `mistral-tiny`: For Mistral-tiny, send a message with `mistral-tiny` and include your prompt.
- `mistral-small`: For Mistral-small, send a message with `mistral-small` and include your prompt.
- `mistral-medium`: For Mistral-medium, send a message with `mistral-medium` and include your prompt.
- `mistral-large`: For Mistral-large, send a message with `mistral-large` and include your prompt.
- `mistral-nemo`: For Mistral-large, send a message with `mistral-nemo` and include your prompt.
- `together/openchat`: For Together OpenChat, send a message with `together/openchat` and include your prompt.
- `together/mistral`: For Together Mistral, send a message with `together/mistral` and include your prompt.
- `together/mixtral`: For Together Mixtral, send a message with `together/mixtral` and include your prompt.
- `together/solar`: For Together Solar, send a message with `together/solar` and include your prompt.
- `groq/mixtral`: For Groq Mixtral, send a message with `groq/mixtral` and include your prompt.
- `groq/llama2`: For Groq Llama-2, send a message with `groq/llama2` and include your prompt.
- `groq/llama3`: For Groq Llama-3, send a message with `groq/llama3` and include your prompt.
- `groq/gemma`: For Groq Gemma, send a message with `groq/gemma` and include your prompt.
- `vllm/hermes-llama-3`: For vLLM Hermes, send a message with `vllm/hermes-llama-3` and include your prompt.
- `dall-e-3`: For Dall-e-3, send a message with `dall-e-3` and include your prompt.
**Getting Started:**
Welcome to the chatroom! Here, you can explore various AI models and engage in interactive activities. Here's how you can get started:
1. **Explore the Chatroom:**
- Join a chatroom by navigating to its unique URL. You can see the list of available chatrooms on the main page.
- Once inside, you can start a conversation by typing your message in the chatbox.
2. **Start an Activity:**
- To begin an educational activity, use the `/activity` command followed by the path to the activity YAML file. For example:
```
/activity research/activity0.yaml
```
- The AI will guide you through the activity, providing feedback and information as you progress.
3. **Interact with AI Models:**
- To interact with a specific AI model, simply type the model's command followed by your prompt. For example:
```
gpt-4 What is the capital of France?
```
- The system will process your message and provide a response from the selected model.
4. **Manage Files with S3:**
- Use the `/s3` commands to load, save, or list files in your S3 bucket. For example, to list all files, use:
```
/s3 ls *
```
5. **Get Help:**
- If you need assistance or want to see a list of available commands, type `/help` to display this message.
Feel free to explore and experiment with different commands and models. Enjoy your time in the chatroom!
"""
class Room(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False, unique=True)
title = db.Column(db.String(128), nullable=True)
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(128), nullable=False)
content = db.Column(db.String(1024), nullable=False)
token_count = db.Column(db.Integer)
room_id = db.Column(db.Integer, db.ForeignKey("room.id"), nullable=False)
def __init__(self, username, content, room_id):
self.username = username
self.content = content
self.room_id = room_id
self.count_tokens()
def count_tokens(self):
if self.token_count is None:
if self.is_base64_image():
self.token_count = 0
else:
encoding = tiktoken.encoding_for_model("gpt-4")
self.token_count = len(encoding.encode(self.content))
return self.token_count
def is_base64_image(self):
return (
'<img src="data:image/jpeg;base64,' in self.content
or '<img alt="Plot Image" src="data:image/png;base64,' in self.content
)
class ActivityState(db.Model):
id = db.Column(db.Integer, primary_key=True)
room_id = db.Column(db.Integer, db.ForeignKey("room.id"), nullable=False)
section_id = db.Column(db.String(128), nullable=False)
step_id = db.Column(db.String(128), nullable=False)
attempts = db.Column(db.Integer, default=0)
max_attempts = db.Column(db.Integer, default=3)
s3_file_path = db.Column(db.String(256), nullable=False)
json_metadata = db.Column(db.UnicodeText, default="{}")
@property
def dict_metadata(self):
return json.loads(self.json_metadata) if self.json_metadata else {}
@dict_metadata.setter
def dict_metadata(self, value):
self.json_metadata = json.dumps(value)
def add_metadata(self, key, value):
metadata = self.dict_metadata
metadata[key] = value
self.dict_metadata = metadata
def remove_metadata(self, key):
metadata = self.dict_metadata
if key in metadata:
del metadata[key]
self.dict_metadata = metadata
def clear_metadata(self):
self.dict_metadata = {}
def get_room(room_name):
"""Utility function to get room from room name."""
room = Room.query.filter_by(name=room_name).first()
if room:
return room
else:
# Create a new room since it doesn't exist
new_room = Room()
new_room.name = room_name
db.session.add(new_room)
db.session.commit()
return new_room
def get_s3_client():
"""Utility function to get the S3 client with the appropriate profile."""
if app.config.get("PROFILE_NAME"):
session = boto3.Session(profile_name=app.config["PROFILE_NAME"])
s3_client = session.client("s3")
else:
s3_client = boto3.client("s3")
return s3_client
from flask_migrate import Migrate
migrate = Migrate(app, db)
@app.route("/favicon.ico")
def favicon():
return send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/chat/<room_name>")
def chat(room_name):
# Query all rooms so that newest is first.
rooms = Room.query.order_by(Room.id.desc()).all()
# Get username from query parameters
username = request.args.get("username", "guest")
# Pass username and rooms into the template
return render_template(
"chat.html", room_name=room_name, rooms=rooms, username=username
)
@app.route("/download_chat_history", methods=["GET"])
def download_chat_history():
room_name = request.args.get("room_name")
room = get_room(room_name)
if not room:
return jsonify({"error": "Room not found"}), 404
messages = Message.query.filter_by(room_id=room.id).all()
if not messages:
return jsonify({"error": "No messages found"}), 404
chat_history = [
{
"role": "system" if message.username in system_users else "user",
"content": message.content,
}
for message in messages
if not message.is_base64_image()
]
if not chat_history:
return jsonify({"error": "No valid messages found"}), 404
response = Response(
response=json.dumps(chat_history, indent=2),
status=200,
mimetype="application/json",
)
response.headers["Content-Disposition"] = f"attachment; filename={room.name}.json"
return response
@app.route("/download_chat_history_md", methods=["GET"])
def download_chat_history_md():
room_name = request.args.get("room_name")
room = get_room(room_name)
if not room:
return jsonify({"error": "Room not found"}), 404
messages = Message.query.filter_by(room_id=room.id).all()
if not messages:
return jsonify({"error": "No messages found"}), 404
# Access system users from the existing context
chat_history_md = []
toc = []
for index, message in enumerate(messages):
if not message.is_base64_image(): # Correctly call the method
role = "System" if message.username in system_users else "User"
header = f"### {role}: {message.username} (Turn {index + 1})"
toc.append(
f"- [{role}: {message.username} (Turn {index + 1})](#{role.lower()}-{message.username.lower().replace(' ', '-')}-turn-{index + 1})"
)
chat_history_md.append(f"{header}\n\n{message.content}\n\n---\n")
if not chat_history_md:
return jsonify({"error": "No valid messages found"}), 404
markdown_content = (
f"# Chat History for {room.name}\n\n## Table of Contents\n"
+ "\n".join(toc)
+ "\n\n"
+ "\n".join(chat_history_md)
)
response = Response(response=markdown_content, status=200, mimetype="text/markdown")
response.headers["Content-Disposition"] = f'attachment; filename="{room.name}.md"'
return response
@app.route("/search")
def search_page():
# Query all rooms so that newest is first.
rooms = Room.query.order_by(Room.id.desc()).all()
keywords = request.args.get("keywords", "")
username = request.args.get("username", "guest")
if not keywords:
return render_template(
"search.html",
rooms=rooms,
keywords=keywords,
results=[],
username=username,
error="Keywords are required",
)
# Call the function to search messages
search_results = search_messages(keywords)
return render_template(
"search.html",
rooms=rooms,
keywords=keywords,
results=search_results,
username=username,
error=None,
)
def search_messages(keywords):
search_results = {}
# Split the keywords by spaces
keyword_list = keywords.lower().split()
# Search for messages containing any of the keywords
messages = Message.query.filter(
db.or_(*[Message.content.ilike(f"%{keyword}%") for keyword in keyword_list])
).all()
for message in messages:
room = Room.query.get(message.room_id)
if room:
# Calculate the score based on the number of occurrences of all keywords
score = sum(
message.content.lower().count(keyword) for keyword in keyword_list
)
if room.id not in search_results:
search_results[room.id] = {
"room_id": room.id,
"room_name": room.name,
"room_title": room.title,
"score": 0,
}
search_results[room.id]["score"] += score
# Convert the dictionary to a list and sort results by score in descending order
search_results_list = list(search_results.values())
search_results_list.sort(key=lambda x: x["score"], reverse=True)
return search_results_list
@socketio.on("join")
def on_join(data):
room_name = data["room_name"]
room = get_room(room_name)
# this makes the client start listening for new events for this room.
join_room(room_name)
# update the title bar with the proper room title, if it exists for just this new client.
if room.title:
socketio.emit("update_room_title", {"title": room.title}, room=request.sid)
# Fetch previous messages from the database
previous_messages = Message.query.filter_by(room_id=room.id).all()
# count the number of tokens in this room.
total_token_count = 0
# Send the history of messages only to the newly connected client.
# The reason for using `request.sid` here is to target the specific session (or client) that
# just connected, so only they receive the backlog of messages, rather than broadcasting
# this information to all clients in the room.
for message in previous_messages:
if not message.is_base64_image():
total_token_count += message.token_count
emit(
"previous_messages",
{
"id": message.id,
"username": message.username,
"content": message.content,
},
room=request.sid,
)
message_count = len(previous_messages)
if room.title is None and message_count >= 6:
room.title = gpt_generate_room_title(previous_messages)
db.session.add(room)
db.session.commit()
socketio.emit("update_room_title", {"title": room.title}, room=room.name)
# Emit an event to update this rooms title in the sidebar for all users.
updated_room_data = {"id": room.id, "name": room.name, "title": room.title}
socketio.emit("update_room_list", updated_room_data, room=None)
# Broadcast to all clients in the room that a new user has joined.
# Here, `room=room` ensures the message is sent to everyone in that specific room.
emit(
"chat_message",
{"id": None, "content": f"{data['username']} has joined the room."},
room=room.name,
)
emit(
"chat_message",
{
"id": None,
"content": f"Estimated {total_token_count} total tokens in conversation.",
},
room=request.sid,
)
@socketio.on("chat_message")
def handle_message(data):
room_name = data["room_name"]
room = get_room(room_name)
# Save the message to the database
new_message = Message(
username=data["username"],
content=data["message"],
room_id=room.id,
)
db.session.add(new_message)
db.session.commit()
emit(
"chat_message",
{
"id": new_message.id,
"username": data["username"],
"content": data["message"],
},
room=room.name,
)
# detect and process special commands.
commands = data["message"].splitlines()
for command in commands:
if command.startswith("/help"):
# Emit the help message
socketio.emit(
"chat_message",
{
"id": "tmp-1",
"username": "System",
"content": HELP_MESSAGE,
},
room=room_name,
)
return
if command.startswith("/activity cancel"):
gevent.spawn(cancel_activity, room_name, data["username"])
# Exit early since we're canceling the activity
return
if command.startswith("/activity info"):
gevent.spawn(display_activity_info, room_name, data["username"])
# Exit early since we're displaying activity info
return
if command.startswith("/activity metadata"):
gevent.spawn(display_activity_metadata, room_name, data["username"])
# Exit early since we're displaying activity metadata
return
if command.startswith("/activity"):
s3_file_path = command.split(" ", 1)[1].strip()
gevent.spawn(start_activity, room_name, s3_file_path, data["username"])
# Exit early since we're starting an activity
return
if command.startswith("/s3 ls"):
# Extract the S3 file path pattern
s3_file_path_pattern = command.split(" ", 2)[2].strip()
# List files from S3 and emit their names
gevent.spawn(
list_s3_files, room.name, s3_file_path_pattern, data["username"]
)
if command.startswith("/s3 load"):
# Extract the S3 file path
s3_file_path = command.split(" ", 2)[2].strip()
# Load the file from S3 and emit its content
gevent.spawn(load_s3_file, room_name, s3_file_path, data["username"])
if command.startswith("/s3 save"):
# Extract the S3 key path
s3_key_path = command.split(" ", 2)[2].strip()
# Save the most recent code block to S3
gevent.spawn(
save_code_block_to_s3, room_name, s3_key_path, data["username"]
)
if command.startswith("/title new"):
gevent.spawn(generate_new_title, room_name, data["username"])
if command.startswith("/cancel"):
# Cancel the most recent generation request
gevent.spawn(cancel_generation, room_name)
# Check if the user is in activity mode
activity_state = ActivityState.query.filter_by(room_id=room.id).first()
if activity_state:
gevent.spawn(
handle_activity_response, room_name, data["message"], data["username"]
)
if "dall-e-3" in data["message"]:
# Use the entire message as the prompt for DALL-E 3
# Generate the image and emit its URL
gevent.spawn(
generate_dalle_image, data["room_name"], data["message"], data["username"]
)
if (
"claude-" in data["message"]
or "gpt-" in data["message"]
or "mistral-" in data["message"]
or "together/" in data["message"]
or "localhost/" in data["message"]
or "vllm/" in data["message"]
or "groq/" in data["message"]
):
# Emit a temporary message indicating that the llm is processing
emit(
"chat_message",
{"id": None, "content": "<span id='processing'>Processing...</span>"},
room=room.name,
)
if "claude-haiku" in data["message"]:
gevent.spawn(
chat_claude,
data["username"],
room.name,
model_name="anthropic.claude-3-haiku-20240307-v1:0",
)
if "claude-sonnet" in data["message"]:
gevent.spawn(chat_claude, data["username"], room.name)
if "claude-opus" in data["message"]:
gevent.spawn(
chat_claude,
data["username"],
room.name,
model_name="anthropic.claude-3-opus-20240229-v1:0",
)
if "gpt-3" in data["message"]:
gevent.spawn(chat_gpt, data["username"], room.name)
if "gpt-4o-2024-08-06" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
model_name="gpt-4o-2024-08-06",
)
elif "gpt-4" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
# model_name="gpt-4o",
model_name="gpt-4o-2024-08-06",
)
if "gpt-o1-mini" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
model_name="o1-mini",
)
if "gpt-mini" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
model_name="gpt-4o-mini",
)
if "mistral-tiny" in data["message"]:
gevent.spawn(
chat_mistral,
data["username"],
room.name,
model_name="mistral-tiny",
)
if "mistral-small" in data["message"]:
gevent.spawn(
chat_mistral,
data["username"],
room.name,
model_name="mistral-small",
)
if "mistral-medium" in data["message"]:
gevent.spawn(
chat_mistral,
data["username"],
room.name,
model_name="mistral-medium",
)
if "mistral-nemo" in data["message"]:
gevent.spawn(
chat_mistral,
data["username"],
room.name,
model_name="open-mistral-nemo",
)
if "mistral-large" in data["message"]:
gevent.spawn(
chat_mistral,
data["username"],
room.name,
model_name="mistral-large-latest",
)
if "together/openchat" in data["message"]:
gevent.spawn(
chat_together,
data["username"],
room.name,
model_name="openchat/openchat-3.5-1210",
stop=["<|end_of_turn|>", "</s>"],
)
if "together/mixtral" in data["message"]:
gevent.spawn(
chat_together,
data["username"],
room.name,
model_name="mistralai/Mixtral-8x7B-v0.1",
)
if "together/mistral" in data["message"]:
gevent.spawn(
chat_together,
data["username"],
room.name,
model_name="mistralai/Mistral-7B-Instruct-v0.1",
)
if "together/solar" in data["message"]:
gevent.spawn(
chat_together,
data["username"],
room.name,
model_name="upstage/SOLAR-10.7B-Instruct-v1.0",
stop=["###", "</s>"],
)
if "groq/mixtral" in data["message"]:
gevent.spawn(
chat_groq,
data["username"],
room.name,
model_name="mixtral-8x7b-32768",
)
if "groq/llama2" in data["message"]:
gevent.spawn(
chat_groq,
data["username"],
room.name,
model_name="llama2-70b-4096",
)
if "groq/llama3" in data["message"]:
gevent.spawn(
chat_groq,
data["username"],
room.name,
model_name="llama3-70b-8192",
)
if "groq/gemma" in data["message"]:
gevent.spawn(
chat_groq,
data["username"],
room.name,
model_name="gemma-7b-it",
)
if "vllm/openchat" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
model_name="openchat/openchat-3.5-0106",
)
if "vllm/hermes-llama-3" in data["message"]:
gevent.spawn(
chat_gpt,
data["username"],
room.name,
model_name="NousResearch/Hermes-3-Llama-3.1-8B",
)
if "localhost/mistral" in data["message"]:
gevent.spawn(
chat_llama,
data["username"],
room.name,
model_name="mistral-7b-instruct-v0.2.Q3_K_L.gguf",
)
if "localhost/mistral-code" in data["message"]:
gevent.spawn(
chat_llama,
data["username"],
room.name,
model_name="mistral-7b-instruct-v0.2-code-ft.Q3_K_L.gguf",
)
if "localhost/openhermes" in data["message"]:
gevent.spawn(
chat_llama,
data["username"],
room.name,
model_name="openhermes-2.5-mistral-7b.Q6_K.gguf",
)
@socketio.on("delete_message")
def handle_delete_message(data):
msg_id = data["message_id"]
# Delete the message from the database
message = db.session.query(Message).filter(Message.id == msg_id).one_or_none()
if message:
db.session.delete(message)
db.session.commit()
# Notify all clients in the room to remove the message from their DOM
emit("message_deleted", {"message_id": msg_id}, room=data["room_name"])
@socketio.on("update_message")
def handle_update_message(data):
message_id = data["message_id"]
new_content = data["content"]
room_name = data["room_name"]
# Find the message by ID
message = Message.query.get(message_id)
if message:
# Update the message content
message.content = new_content
message.count_tokens()
db.session.add(message)
db.session.commit()
# Emit an event to update the message on all clients
emit(
"message_updated",
{
"message_id": message_id,
"content": new_content,
"username": message.username,
},
room=room_name,
)
def group_consecutive_roles(messages):
if not messages:
return []
grouped_messages = []
current_role = messages[0]["role"]
current_content = []
for message in messages:
if message["role"] == current_role:
current_content.append(message["content"])
else:
grouped_messages.append(
{"role": current_role, "content": " ".join(current_content)}
)
current_role = message["role"]
current_content = [message["content"]]
# Append the last grouped message
grouped_messages.append(
{"role": current_role, "content": " ".join(current_content)}
)
return grouped_messages
def chat_claude(
# username, room_name, model_name="anthropic.claude-3-5-sonnet-20240620-v1:0"
username,
room_name,
model_name="anthropic.claude-3-sonnet-20240229-v1:0",
):
with app.app_context():
room = get_room(room_name)
# claude has a 200,000 token context window for prompts.
all_messages = (
Message.query.filter_by(room_id=room.id).order_by(Message.id.desc()).all()
)
chat_history = []
for msg in reversed(all_messages):
if msg.is_base64_image():
continue
role = "assistant" if msg.username in system_users else "user"
chat_history.append({"role": role, "content": msg.content})
# only claude cares about this constrant.
chat_history = group_consecutive_roles(chat_history)
# Initialize the Bedrock client using boto3 and profile name.
if app.config.get("PROFILE_NAME"):
session = boto3.Session(profile_name=app.config["PROFILE_NAME"])
client = session.client("bedrock-runtime", region_name="us-west-2")
else:
client = boto3.client("bedrock-runtime", region_name="us-west-2")
# Define the request parameters
params = {
"modelId": model_name,
"contentType": "application/json",
"accept": "*/*",
"body": json.dumps(
{
"messages": chat_history,
"max_tokens": 4096,
"temperature": 0,
"top_k": 250,
"top_p": 0.999,
"stop_sequences": ["\n\nHuman:"],
"anthropic_version": "bedrock-2023-05-31",
}
).encode(),
}
# Process the event stream
buffer = ""
# save empty message, we need the ID when we chunk the response.
with app.app_context():
new_message = Message(username=model_name, content=buffer, room_id=room.id)
db.session.add(new_message)
db.session.commit()
msg_id = new_message.id
try:
# Invoke the model with response stream
response = client.invoke_model_with_response_stream(**params)["body"]
first_chunk = True
for event in response:
content = ""
# Check if there has been a cancellation request, break if there is.
if cancellation_requests.get(msg_id):
del cancellation_requests[msg_id]
break
if "chunk" in event:
chunk_data = json.loads(event["chunk"]["bytes"].decode())
if chunk_data["type"] == "content_block_delta":
if chunk_data["delta"]["type"] == "text_delta":
content = chunk_data["delta"]["text"]
if content:
buffer += content # Accumulate content
if first_chunk:
socketio.emit(
"message_chunk",
{
"id": msg_id,
"content": f"**{username} ({model_name}):**\n\n{content}",
},
room=room.name,
)
first_chunk = False
else:
socketio.emit(
"message_chunk",
{"id": msg_id, "content": content},
room=room.name,
)
socketio.sleep(0) # Force immediate handling
except Exception as e:
with app.app_context():
message_content = f"AWS Bedrock Error: {e}"
new_message = (
db.session.query(Message).filter(Message.id == msg_id).one_or_none()
)
if new_message:
new_message.content = message_content
new_message.count_tokens()
db.session.add(new_message)
db.session.commit()
socketio.emit(
"chat_message",
{
"id": msg_id,
"username": model_name,
"content": message_content,
},
room=room_name,
)
socketio.emit("delete_processing_message", msg_id, room=room.name)
# exit early to avoid clobbering the error message.
return None
# Save the entire completion to the database
with app.app_context():
new_message = (
db.session.query(Message).filter(Message.id == msg_id).one_or_none()
)
if new_message:
new_message.content = buffer
new_message.count_tokens()
db.session.add(new_message)
db.session.commit()
socketio.emit("delete_processing_message", msg_id, room=room.name)
def get_openai_client_and_model(model_name="NousResearch/Hermes-3-Llama-3.1-8B"):
vllm_endpoint = os.environ.get("VLLM_ENDPOINT")
vllm_api_key = os.environ.get("VLLM_API_KEY", "not-needed")
is_openai_model = "gpt" in model_name.lower() or "o1" in model_name.lower()
if vllm_endpoint and not is_openai_model:
openai_client = OpenAI(base_url=vllm_endpoint, api_key=vllm_api_key)
else:
openai_client = OpenAI()
return openai_client, model_name
def chat_gpt(username, room_name, model_name="gpt-4o-mini"):
openai_client, model_name = get_openai_client_and_model(model_name)
temperature = 0
limit = 20
if "gpt-4" in model_name:
limit = 1000
if "o1" in model_name:
temperature = 1