Artteiv commited on
Commit
46d747a
1 Parent(s): bdc6187
chat/apps.py CHANGED
@@ -1,9 +1,6 @@
1
  from django.apps import AppConfig
2
  import google.generativeai as genai
3
 
4
-
5
-
6
-
7
  class MembersConfig(AppConfig):
8
  default_auto_field = 'django.db.models.BigAutoField'
9
  name = 'chat'
 
1
  from django.apps import AppConfig
2
  import google.generativeai as genai
3
 
 
 
 
4
  class MembersConfig(AppConfig):
5
  default_auto_field = 'django.db.models.BigAutoField'
6
  name = 'chat'
chat/consumers.py CHANGED
@@ -1,19 +1,30 @@
1
  import json
2
  from . import model_manage2 as md
3
  from channels.generic.websocket import WebsocketConsumer
4
-
5
 
6
  class ChatConsumer(WebsocketConsumer):
7
  def connect(self):
8
- self.accept()
9
- self.model, self.session = md.init_model("auto")
 
 
 
 
10
 
11
  def disconnect(self, close_code):
12
  del self.model, self.session
13
  pass
14
 
15
  def receive(self, text_data):
 
 
 
 
 
16
  text_data_json = json.loads(text_data)
 
 
17
  message = text_data_json["messages"]
18
  print(message)
19
  question = message[-1]['content']
@@ -22,4 +33,5 @@ class ChatConsumer(WebsocketConsumer):
22
  print("Session history:")
23
  md.print_history(history_state)
24
  self.send(text_data=json.dumps({"message": response}))
 
25
 
 
1
  import json
2
  from . import model_manage2 as md
3
  from channels.generic.websocket import WebsocketConsumer
4
+ from .database_manage import DataManage
5
 
6
  class ChatConsumer(WebsocketConsumer):
7
  def connect(self):
8
+ self.user = self.scope["user"]
9
+ if self.user.is_authenticated:
10
+ self.accept()
11
+ self.model, self.session = md.init_model("auto")
12
+ else:
13
+ self.close()
14
 
15
  def disconnect(self, close_code):
16
  del self.model, self.session
17
  pass
18
 
19
  def receive(self, text_data):
20
+ """
21
+ After socket create with:
22
+ username: self.user
23
+ roomid: self.roomid
24
+ """
25
  text_data_json = json.loads(text_data)
26
+ self.database = DataManage()
27
+ roomid = text_data_json["roomid"]
28
  message = text_data_json["messages"]
29
  print(message)
30
  question = message[-1]['content']
 
33
  print("Session history:")
34
  md.print_history(history_state)
35
  self.send(text_data=json.dumps({"message": response}))
36
+ self.database.Add_prompt_response(roomid,question,response)
37
 
chat/database_manage.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .models import Room, ChatDetails
2
+ import uuid
3
+
4
+ class DataManage:
5
+ def __init__(self):
6
+ pass
7
+
8
+ def DeleteRoom(self, roomid):
9
+ try:
10
+ room = Room.objects.get(RoomID=roomid)
11
+ room.delete()
12
+ return True
13
+ except Room.DoesNotExist:
14
+ return False
15
+
16
+ def InsertRoom(self, username,roomname = "New chat"):
17
+ new_room = Room(UserName=username,Name=roomname)
18
+ new_room.save()
19
+ return str(new_room.RoomID)
20
+
21
+ def Add_prompt_response(self, roomid, prompt, response):
22
+ try:
23
+ room = Room.objects.get(RoomID=roomid)
24
+ new_chat_detail = ChatDetails(RoomID=room, UserPrompt=prompt, BotResponse=response)
25
+ new_chat_detail.save()
26
+ return True
27
+ except Room.DoesNotExist:
28
+ return False
29
+
30
+ def LoadRoomDetail(self, roomid):
31
+ room = Room.objects.get(RoomID=roomid)
32
+ print(room)
33
+ print(room==None)
34
+ chat_details = ChatDetails.objects.filter(RoomID=room.RoomID).order_by('order')
35
+ print(chat_details)
36
+ mes = []
37
+ for x in chat_details:
38
+ mes.append({'role':"user",'content':x.UserPrompt})
39
+ mes.append({'role':"model",'content':x.BotResponse})
40
+
41
+ return {'id':str(room.RoomID), 'user':room.UserName,'messages':mes}
42
+ def LoadRooms(self,username):
43
+ #return list of {id,name}
44
+ try:
45
+ rooms = Room.objects.filter(UserName=username)
46
+ room_ids = [{'id':str(room.RoomID),'name':room.Name} for room in rooms]
47
+ return room_ids
48
+ except Room.DoesNotExist:
49
+ return []
chat/migrations/0002_chatdetails_room_delete_member_chatdetails_roomid.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by Django 5.0.4 on 2024-05-21 07:21
2
+
3
+ import django.db.models.deletion
4
+ import uuid
5
+ from django.db import migrations, models
6
+
7
+
8
+ class Migration(migrations.Migration):
9
+
10
+ dependencies = [
11
+ ('chat', '0001_initial'),
12
+ ]
13
+
14
+ operations = [
15
+ migrations.CreateModel(
16
+ name='ChatDetails',
17
+ fields=[
18
+ ('order', models.AutoField(primary_key=True, serialize=False)),
19
+ ('UserPrompt', models.TextField()),
20
+ ('BotResponse', models.TextField()),
21
+ ],
22
+ options={
23
+ 'ordering': ['order'],
24
+ },
25
+ ),
26
+ migrations.CreateModel(
27
+ name='Room',
28
+ fields=[
29
+ ('RoomID', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
30
+ ('UserName', models.CharField(max_length=50)),
31
+ ],
32
+ ),
33
+ migrations.DeleteModel(
34
+ name='Member',
35
+ ),
36
+ migrations.AddField(
37
+ model_name='chatdetails',
38
+ name='RoomID',
39
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.room'),
40
+ ),
41
+ ]
chat/migrations/0003_room_name_alter_chatdetails_botresponse.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by Django 5.0.4 on 2024-05-21 12:36
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('chat', '0002_chatdetails_room_delete_member_chatdetails_roomid'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AddField(
14
+ model_name='room',
15
+ name='Name',
16
+ field=models.CharField(max_length=50, null=True),
17
+ ),
18
+ migrations.AlterField(
19
+ model_name='chatdetails',
20
+ name='BotResponse',
21
+ field=models.TextField(null=True),
22
+ ),
23
+ ]
chat/models.py CHANGED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.db import models
2
+ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
3
+ import uuid
4
+ # ChatHistory Model
5
+ class Room(models.Model):
6
+ RoomID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
7
+ UserName = models.CharField(max_length=50)
8
+ Name = models.CharField(max_length=50,null=True)
9
+ def __str__(self):
10
+ return f'Chat {self.RoomID} by {self.UserName}'
11
+
12
+ # ChatDetails Model
13
+ class ChatDetails(models.Model):
14
+ RoomID = models.ForeignKey(Room, on_delete=models.CASCADE)
15
+ order = models.AutoField(primary_key=True)
16
+ UserPrompt = models.TextField()
17
+ BotResponse = models.TextField(null=True)
18
+
19
+ class Meta:
20
+ ordering = ['order']
21
+
22
+ def __str__(self):
23
+ return f'Message {self.order} in Chat {self.RoomID}'
chat/templates/index.html CHANGED
@@ -6,6 +6,14 @@
6
  <meta charset="UTF-8">
7
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
8
  <script src="https://cdn.tailwindcss.com"></script>
 
 
 
 
 
 
 
 
9
  <style>
10
  body {
11
  margin: 0;
@@ -13,16 +21,19 @@
13
  background-color: #2A2A2A;
14
  color: white;
15
  }
 
16
  .container {
17
  display: flex;
18
  height: 100vh;
19
  }
 
20
  .left-column {
21
  width: 25%;
22
  background-color: #3A3A3A;
23
  padding: 20px;
24
  overflow-y: auto;
25
  }
 
26
  .right-column {
27
  width: 75%;
28
  background-color: #2E2E2E;
@@ -34,230 +45,253 @@
34
  <script>
35
  function textAreaAdjust(element) {
36
  element.style.height = "1px";
37
- element.style.height = (25+element.scrollHeight)+"px";
38
  }
39
  </script>
 
40
  <body>
41
- <div class="container">
42
- <div class="left-column">
43
- <h2 class="text-xl font-medium mb-4">Lịch sử đoạn chat</h2>
44
- <ul class="list-none">
45
- <li class="p-2 bg-[#4A4A4A] mb-2 rounded cursor-pointer">Đoạn chat 1</li>
46
- <li class="p-2 bg-[#4A4A4A] mb-2 rounded cursor-pointer">Đoạn chat 2</li>
47
- <li class="p-2 bg-[#4A4A4A] mb-2 rounded cursor-pointer">Đoạn chat 3</li>
48
- <!-- Thêm các đoạn chat khác tại đây -->
49
- </ul>
50
- </div>
51
-
52
- <div id="app" class="right-column flex flex-col md:mx-auto mx-0 bg-[#2E2E2E] w-full h-screen">
 
 
53
 
54
- <div class="flex flex-col h-full">
55
- <!-- head -->
56
- <div class="flex flex-row justify-between items-center p-4 select-none">
57
- <h1 class="text-2xl font-medium text-center">
58
- TinyChat
59
- </h1>
60
- <div>
61
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"
62
- class="cursor-pointer" :class="{'text-white':!showConfig,'text-[#919191]':showConfig}"
63
- @click="showConfig=!showConfig">
64
- <path
65
- d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92001 3.98596L9.49643 4.70605C8.96183 5.61487 7.98937 6.17632 6.935 6.18489L6.09966 6.19168C5.39095 6.19744 4.73822 6.57783 4.38385 7.19161L4.02775 7.80841C3.67338 8.42219 3.67031 9.17767 4.01968 9.7943L4.4315 10.5212C4.95126 11.4386 4.95126 12.5615 4.4315 13.4788L4.01968 14.2057C3.67031 14.8224 3.67338 15.5778 4.02775 16.1916L4.38385 16.8084C4.73822 17.4222 5.39095 17.8026 6.09965 17.8083L6.93501 17.8151C7.98938 17.8237 8.96184 18.3851 9.49644 19.294L9.92001 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
66
- stroke="white" stroke-width="2" stroke-linejoin="round" />
67
- <path
68
- d="M12 14.5C13.3807 14.5 14.5 13.3807 14.5 12C14.5 10.6193 13.3807 9.5 12 9.5C10.6193 9.5 9.5 10.6193 9.5 12C9.5 13.3807 10.6193 14.5 12 14.5Z"
69
- stroke="white" stroke-width="2" />
70
- </svg>
 
 
71
 
 
72
  </div>
73
- </div>
74
- <!-- config -->
75
- <div v-show="showConfig" class="flex flex-col gap-4 p-4 select-none">
76
- <!-- render configFields -->
77
- <div v-for="field in configFields" :key="field.name" class="flex flex-col gap-2">
78
- <label class="text-sm text-gray-400">
79
- {{ field.label }}
80
- </label>
81
- <input v-if="field.type=='text'" type="text"
82
- class="bg-transparent border border-[#919191] rounded-lg p-2" v-model="config[field.name]" />
83
- <input v-if="field.type=='number'" type="number"
84
- class="bg-transparent border border-[#919191] rounded-lg p-2" v-model="config[field.name]" />
 
 
85
  </div>
86
- </div>
87
- <!-- messages -->
88
- <div class="flex flex-col overflow-y-auto scroll-smooth" id="messages">
89
- <div v-for="(message,index) in messages" :key="message.id"
90
- class="flex flex-col odd:bg-[#F7F7F7]/10 group">
91
- <div class="p-4 flex flex-col justify-between gap-4">
92
- <div class="flex flex-row gap-4 capitalize">
93
- <div class="text-gray-400 text-sm" >
94
- <textarea
95
- class="text-gray-400 text-sm size-full outline-0 bg-transparent border-none text-white rounded-lg resize-none"
96
- :rows="message.role" v-model="message.role"></textarea>
97
- </div>
98
- <div class="flex flex-col w-full">
99
- <textarea
100
- onkeyup="textAreaAdjust(this)" style="overflow:hidden"
101
- class="size-full outline-0 bg-transparent border-none text-white rounded-lg resize-y"
102
- :rows="message.content.split('\n').length" v-model="message.content"></textarea>
103
- <div class="mt-4" v-if="index==messages.length-1 && message.role=='assistant'">
104
- <svg stroke="currentColor" fill="none" stroke-width="1.5" viewBox="0 0 24 24"
105
- stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em"
106
- xmlns="http://www.w3.org/2000/svg" v-if="index==messages.length-1"
107
- class="group-hover:block cursor-pointer h-3 w-3" @click="refresh"
108
- :class="{'animate-spin':isLoading}">
109
- >
110
- >
111
- >
112
- <polyline points="1 4 1 10 7 10"></polyline>
113
- <polyline points="23 20 23 14 17 14"></polyline>
114
- <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15">
115
- </path>
116
 
117
- </svg>
 
118
  </div>
119
  </div>
120
  </div>
121
  </div>
122
  </div>
123
  </div>
124
- </div>
125
- <!-- send message -->
126
- <div class="flex flex-row justify-between items-center p-4 sticky bottom-0 bg-[#2E2E2E]" v-if="!showConfig">
127
- <div class="w-full flex flex-row border border-1 border-[#919191] rounded-xl px-4 py-6 items-center">
128
- <textarea
129
- class="w-full h-full outline-0 bg-transparent border-none text-white resize-none text-md max-h-[100px]"
130
- v-on:keyup.enter="sendMessage" placeholder="Type a message" :rows="message.split('\n').length"
131
- v-model="message"></textarea>
132
- <div class="flex flex-col justify-end gap-4 text-[#2E2E2E] rounded-md p-1"
133
- :class="{'bg-white':message!='','bg-white/10':message==''}">
134
- <button @click="sendMessage">
135
- <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
136
- xmlns="http://www.w3.org/2000/svg">
137
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
138
- d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
139
- </svg>
140
- </button>
141
  </div>
142
  </div>
143
- </div>
144
-
145
- </div>
146
- <script type="module">
147
- import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
148
- import { SSE } from "https://cdn.jsdelivr.net/npm/sse.js@2.1.0/lib/sse.min.js"
149
 
150
- createApp({
151
- data() {
152
- return {
153
- showConfig: false,
154
- configFields: [
155
- {
156
- name: "endPoint",
157
- type: "text",
158
- label: "End Point"
159
- },
160
- {
161
- name: "apiKey",
162
- type: "text",
163
- label: "API Key"
164
- },
165
- {
166
- name: "model",
167
- type: "text",
168
- label: "Model"
169
- },
170
- {
171
- name: "temperature",
172
- type: "number",
173
- label: "Temperature"
174
- },
175
- {
176
- name: "presence_penalty",
177
- type: "number",
178
- label: "Presence Penalty"
179
- },
180
- {
181
- name: "top_p",
182
- type: "number",
183
- label: "Top P"
184
- },
185
- {
186
- name: "frequency_penalty",
187
- type: "number",
188
- label: "Frequency Penalty"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  },
190
- ],
191
- isLoading: false,
192
- message: '',
193
- messages: [],
194
-
195
- chatSocket : new WebSocket(
196
- 'ws://'
197
- + window.location.host
198
- + '/ws/chat'
199
- ),
200
- config: {
201
- endPoint: "",
202
- apiKey: "",
203
- model: "gpt-3.5-turbo",
204
- temperature: 1,
205
- presence_penalty: 0,
206
- top_p: 1,
207
- frequency_penalty: 0,
208
- stream: true
209
  }
210
- }
211
 
212
- },
213
- created() {
214
- this.connect();
215
- },
216
- methods: {
217
- refresh() {
218
- this.send(true);
219
  },
220
- sendMessage() {
221
- this.messages.push({
222
- role: "user",
223
- content: this.message
224
- });
225
- this.chatSocket.send(JSON.stringify({
226
- 'message':this.message,
227
- 'messages': this.messages,
228
- }));
229
- console.log(JSON.stringify({
230
- 'messages': this.messages
231
- }))
232
- this.message = "";
233
  },
234
- connect() {
235
- this.chatSocket.onopen = () => {
236
- this.connectionStatus = 'Connected';
237
- console.log('WebSocket connected');
238
- };
239
-
240
- this.chatSocket.onmessage = (event) => {
241
- var mes = JSON.parse(event.data)
 
242
  this.messages.push({
243
- role: "model",
244
- content: mes.message
245
  });
246
- console.log('Message received: ', event.data);
247
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
249
- this.chatSocket.onclose = () => {
250
- this.connectionStatus = 'Disconnected';
251
- console.log('WebSocket disconnected');
252
- };
253
 
254
- this.chatSocket.onerror = (error) => {
255
- console.error('WebSocket Error: ', error);
256
- };
257
- }
258
- },
259
- }).mount('#app')
260
- </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  </div>
262
  </body>
263
 
 
6
  <meta charset="UTF-8">
7
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
8
  <script src="https://cdn.tailwindcss.com"></script>
9
+ <!-- <script>
10
+ // const roomdata = JSON.parse('{{ roomdata|safe }}');
11
+ var roomdata = JSON.parse('{{ roomdata|safe }}');
12
+ console.log(roomdata)
13
+ function call() {
14
+ return roomdata;
15
+ }
16
+ </script> -->
17
  <style>
18
  body {
19
  margin: 0;
 
21
  background-color: #2A2A2A;
22
  color: white;
23
  }
24
+
25
  .container {
26
  display: flex;
27
  height: 100vh;
28
  }
29
+
30
  .left-column {
31
  width: 25%;
32
  background-color: #3A3A3A;
33
  padding: 20px;
34
  overflow-y: auto;
35
  }
36
+
37
  .right-column {
38
  width: 75%;
39
  background-color: #2E2E2E;
 
45
  <script>
46
  function textAreaAdjust(element) {
47
  element.style.height = "1px";
48
+ element.style.height = (25 + element.scrollHeight) + "px";
49
  }
50
  </script>
51
+
52
  <body>
53
+ <div id="app" class="container">
54
+ <div class="left-column">
55
+ <h2 class="text-xl font-medium mb-4">Lịch sử đoạn chat</h2>
56
+ <ul class="list-none">
57
+ {% for x in rooms %}
58
+ <li class="p-2 bg-[#4A4A4A] mb-2 rounded flex justify-between items-center">
59
+ <a :href="`/chat?id={{x.id}}`" class="cursor-pointer">{{ x.name }}</a>
60
+ <button @click="deleteChat(index)" class="bg-red-500 text-white px-2 py-1 rounded">
61
+ Xoá
62
+ </button>
63
+ </li>
64
+ {% endfor %}
65
+ </ul>
66
+ </div>
67
 
68
+ <div class="right-column flex flex-col md:mx-auto mx-0 bg-[#2E2E2E] w-full h-screen">
69
+
70
+ <div class="flex flex-col h-full">
71
+ <!-- head -->
72
+ <div class="flex flex-row justify-between items-center p-4 select-none">
73
+ <h1 class="text-2xl font-medium text-center">
74
+ TinyChat
75
+ </h1>
76
+ <div>
77
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"
78
+ class="cursor-pointer" :class="{'text-white':!showConfig,'text-[#919191]':showConfig}"
79
+ @click="showConfig=!showConfig">
80
+ <path
81
+ d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92001 3.98596L9.49643 4.70605C8.96183 5.61487 7.98937 6.17632 6.935 6.18489L6.09966 6.19168C5.39095 6.19744 4.73822 6.57783 4.38385 7.19161L4.02775 7.80841C3.67338 8.42219 3.67031 9.17767 4.01968 9.7943L4.4315 10.5212C4.95126 11.4386 4.95126 12.5615 4.4315 13.4788L4.01968 14.2057C3.67031 14.8224 3.67338 15.5778 4.02775 16.1916L4.38385 16.8084C4.73822 17.4222 5.39095 17.8026 6.09965 17.8083L6.93501 17.8151C7.98938 17.8237 8.96184 18.3851 9.49644 19.294L9.92001 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
82
+ stroke="white" stroke-width="2" stroke-linejoin="round" />
83
+ <path
84
+ d="M12 14.5C13.3807 14.5 14.5 13.3807 14.5 12C14.5 10.6193 13.3807 9.5 12 9.5C10.6193 9.5 9.5 10.6193 9.5 12C9.5 13.3807 10.6193 14.5 12 14.5Z"
85
+ stroke="white" stroke-width="2" />
86
+ </svg>
87
 
88
+ </div>
89
  </div>
90
+ <!-- config -->
91
+ <div v-show="showConfig" class="flex flex-col gap-4 p-4 select-none">
92
+ <!-- render configFields -->
93
+ <div v-for="field in configFields" :key="field.name" class="flex flex-col gap-2">
94
+ <label class="text-sm text-gray-400">
95
+ {{ field.label }}
96
+ </label>
97
+ <input v-if="field.type=='text'" type="text"
98
+ class="bg-transparent border border-[#919191] rounded-lg p-2"
99
+ v-model="config[field.name]" />
100
+ <input v-if="field.type=='number'" type="number"
101
+ class="bg-transparent border border-[#919191] rounded-lg p-2"
102
+ v-model="config[field.name]" />
103
+ </div>
104
  </div>
105
+ <!-- messages -->
106
+ <div class="flex flex-col overflow-y-auto scroll-smooth" id="messages">
107
+ <div v-for="(message,index) in messages" :key="message.id"
108
+ class="flex flex-col odd:bg-[#F7F7F7]/10 group">
109
+ <div class="p-4 flex flex-col justify-between gap-4">
110
+ <div class="flex flex-row gap-4 capitalize">
111
+ <div class="text-gray-400 text-sm">
112
+ <textarea
113
+ class="text-gray-400 text-sm size-full outline-0 bg-transparent border-none text-white rounded-lg resize-none"
114
+ :rows="message.role" v-model="message.role"></textarea>
115
+ </div>
116
+ <div class="flex flex-col w-full">
117
+ <textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"
118
+ class="size-full outline-0 bg-transparent border-none text-white rounded-lg resize-y"
119
+ :rows="message.content.split('\n').length" v-model="message.content"></textarea>
120
+ <div class="mt-4" v-if="index==messages.length-1 && message.role=='assistant'">
121
+ <svg stroke="currentColor" fill="none" stroke-width="1.5" viewBox="0 0 24 24"
122
+ stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em"
123
+ xmlns="http://www.w3.org/2000/svg" v-if="index==messages.length-1"
124
+ class="group-hover:block cursor-pointer h-3 w-3" @click="refresh"
125
+ :class="{'animate-spin':isLoading}">
126
+ >
127
+ >
128
+ >
129
+ <polyline points="1 4 1 10 7 10"></polyline>
130
+ <polyline points="23 20 23 14 17 14"></polyline>
131
+ <path
132
+ d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15">
133
+ </path>
 
134
 
135
+ </svg>
136
+ </div>
137
  </div>
138
  </div>
139
  </div>
140
  </div>
141
  </div>
142
  </div>
143
+ <!-- send message -->
144
+ <div class="flex flex-row justify-between items-center p-4 sticky bottom-0 bg-[#2E2E2E]" v-if="!showConfig">
145
+ <div class="w-full flex flex-row border border-1 border-[#919191] rounded-xl px-4 py-6 items-center">
146
+ <textarea
147
+ class="w-full h-full outline-0 bg-transparent border-none text-white resize-none text-md max-h-[100px]"
148
+ v-on:keyup.enter="sendMessage" placeholder="Type a message" :rows="message.split('\n').length"
149
+ v-model="message"></textarea>
150
+ <div class="flex flex-col justify-end gap-4 text-[#2E2E2E] rounded-md p-1"
151
+ :class="{'bg-white':message!='','bg-white/10':message==''}">
152
+ <button @click="sendMessage">
153
+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
154
+ xmlns="http://www.w3.org/2000/svg">
155
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
156
+ d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
157
+ </svg>
158
+ </button>
159
+ </div>
160
  </div>
161
  </div>
 
 
 
 
 
 
162
 
163
+ </div>
164
+
165
+ <script type="module">
166
+ import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
167
+ // import { SSE } from "https://cdn.jsdelivr.net/npm/sse.js@2.1.0/lib/sse.min.js"
168
+
169
+ var roomdata = {{ roomdata|safe }};
170
+
171
+ createApp({
172
+ data() {
173
+ return {
174
+ showConfig: false,
175
+ configFields: [
176
+ {
177
+ name: "endPoint",
178
+ type: "text",
179
+ label: "End Point"
180
+ },
181
+ {
182
+ name: "apiKey",
183
+ type: "text",
184
+ label: "API Key"
185
+ },
186
+ {
187
+ name: "model",
188
+ type: "text",
189
+ label: "Model"
190
+ },
191
+ {
192
+ name: "temperature",
193
+ type: "number",
194
+ label: "Temperature"
195
+ },
196
+ {
197
+ name: "presence_penalty",
198
+ type: "number",
199
+ label: "Presence Penalty"
200
+ },
201
+ {
202
+ name: "top_p",
203
+ type: "number",
204
+ label: "Top P"
205
+ },
206
+ {
207
+ name: "frequency_penalty",
208
+ type: "number",
209
+ label: "Frequency Penalty"
210
+ },
211
+ ],
212
+ isLoading: false,
213
+ message: '',
214
+ messages: roomdata.messages,
215
+ // cs:roomdata,
216
+ chatSocket: null,
217
+ config: {
218
+ endPoint: "",
219
+ apiKey: "",
220
+ model: "gpt-3.5-turbo",
221
+ temperature: 1,
222
+ presence_penalty: 0,
223
+ top_p: 1,
224
+ frequency_penalty: 0,
225
+ stream: true
226
  },
227
+ // roomdata: roomdata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  }
 
229
 
 
 
 
 
 
 
 
230
  },
231
+ created() {
232
+ // const roomdata = JSON.parse('roomdata');
233
+ const params = new URLSearchParams(window.location.search);
234
+ this.id = params.get('id');//chat id
235
+ if (this.id == null) {
236
+ return
237
+ }
238
+ this.connect()
 
 
 
 
 
239
  },
240
+ methods: {
241
+ refresh() {
242
+ this.send(true);
243
+ },
244
+ sendMessage() {
245
+ if (this.id == null) {
246
+ window.location.href = '/chat/newchat?ques=' + this.message;
247
+ return;
248
+ }
249
  this.messages.push({
250
+ role: "user",
251
+ content: this.message
252
  });
253
+ this.chatSocket.send(JSON.stringify({
254
+ 'roomid':this.id,
255
+ 'message': this.message,
256
+ 'messages': this.messages,
257
+ }));
258
+ console.log(JSON.stringify({
259
+ 'messages': this.messages
260
+ }))
261
+ this.message = "";
262
+ },
263
+
264
+ connect() {
265
+ this.chatSocket = new WebSocket(
266
+ 'ws://' + window.location.host + '/ws/chat'
267
+ );
268
 
269
+ this.chatSocket.onopen = () => {
270
+ this.connectionStatus = 'Connected';
271
+ console.log('WebSocket connected');
272
+ };
273
 
274
+ this.chatSocket.onmessage = (event) => {
275
+ var mes = JSON.parse(event.data)
276
+ this.messages.push({
277
+ role: "model",
278
+ content: mes.message
279
+ });
280
+ console.log('Message received: ', event.data);
281
+ };
282
+
283
+ this.chatSocket.onclose = () => {
284
+ this.connectionStatus = 'Disconnected';
285
+ console.log('WebSocket disconnected');
286
+ };
287
+
288
+ this.chatSocket.onerror = (error) => {
289
+ console.error('WebSocket Error: ', error);
290
+ };
291
+ }
292
+ },
293
+ }).mount('#app')
294
+ </script>
295
  </div>
296
  </body>
297
 
chat/urls.py CHANGED
@@ -1,7 +1,10 @@
1
  from django.urls import path
2
  from . import views
3
 
 
 
4
  urlpatterns = [
5
  path('', views.index, name='index'),
 
6
  path("<str:room_name>/", views.room, name="room"),
7
  ]
 
1
  from django.urls import path
2
  from . import views
3
 
4
+ app_name = 'chat'
5
+
6
  urlpatterns = [
7
  path('', views.index, name='index'),
8
+ path('newchat/',views.newchat,name = 'newchat'),
9
  path("<str:room_name>/", views.room, name="room"),
10
  ]
chat/views.py CHANGED
@@ -1,9 +1,39 @@
1
  # chat/views.py
2
- from django.shortcuts import render
3
-
4
-
 
 
 
 
5
  def index(request):
6
- return render(request, "index.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
 
9
  def room(request, room_name):
 
1
  # chat/views.py
2
+ from django.shortcuts import render,redirect
3
+ from django.http import HttpResponse
4
+ from django.contrib.auth.decorators import login_required
5
+ from .database_manage import DataManage
6
+ import uuid
7
+ import json
8
+ @login_required
9
  def index(request):
10
+ roomid = request.GET.get('id')
11
+ data = DataManage()
12
+ rooms = data.LoadRooms(username=request.user.username)
13
+ if roomid:
14
+ # try:
15
+ roomdata = data.LoadRoomDetail(roomid=roomid)
16
+ if roomdata==None:
17
+ raise("Room not found")
18
+ context = {
19
+ 'rooms': rooms,
20
+ 'roomdata': json.dumps(roomdata),
21
+ }
22
+ return render(request, 'index.html',context=context)
23
+ # except Exception as e:
24
+ # print(e)
25
+ # return HttpResponse("Room not found", status=404)
26
+ else:
27
+ roomdata = {'messages':[]}
28
+ return render(request, "index.html",{"rooms":rooms,'roomdata':roomdata})
29
+
30
+ @login_required
31
+ def newchat(request):
32
+ data = DataManage()
33
+ user = request.user.username
34
+ ques = request.GET.get('ques')
35
+ room = data.InsertRoom(user,ques[:23])
36
+ return redirect(f'/chat?id={room}&ques={ques}')
37
 
38
 
39
  def room(request, room_name):
chatbot_django/settings.py CHANGED
@@ -22,6 +22,9 @@ BASE_DIR = Path(__file__).resolve().parent.parent
22
  # SECURITY WARNING: keep the secret key used in production secret!
23
  SECRET_KEY = 'django-insecure-l39x6jgx075p9bw8^px-c=pys%&$bzdo_sz_oabf#5bv@^isj9'
24
 
 
 
 
25
  # SECURITY WARNING: don't run with debug turned on in production!
26
  DEBUG = True
27
 
 
22
  # SECURITY WARNING: keep the secret key used in production secret!
23
  SECRET_KEY = 'django-insecure-l39x6jgx075p9bw8^px-c=pys%&$bzdo_sz_oabf#5bv@^isj9'
24
 
25
+ LOGIN_URL = '/users/login/'
26
+
27
+
28
  # SECURITY WARNING: don't run with debug turned on in production!
29
  DEBUG = True
30
 
chatbot_django/urls.py CHANGED
@@ -16,9 +16,14 @@ Including another URLconf
16
  """
17
  from django.contrib import admin
18
  from django.urls import path,include
 
 
 
 
19
 
20
  urlpatterns = [
21
  path('chat/',include('chat.urls')),
22
  path('admin/', admin.site.urls),
23
- path('users/', include('users.urls'))
 
24
  ]
 
16
  """
17
  from django.contrib import admin
18
  from django.urls import path,include
19
+ from django.shortcuts import redirect
20
+
21
+ def redirect_to_chat(request):
22
+ return redirect('chat:index')
23
 
24
  urlpatterns = [
25
  path('chat/',include('chat.urls')),
26
  path('admin/', admin.site.urls),
27
+ path('users/', include('users.urls')),
28
+ path('',redirect_to_chat)
29
  ]
db.sqlite3 CHANGED
Binary files a/db.sqlite3 and b/db.sqlite3 differ
 
test.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ a = [(1,2),(4,5),(3,5)]
2
+
3
+ dic = [{"id1":x[0]},{"id":x[1]} for x in a]
users/views.py CHANGED
@@ -8,14 +8,14 @@ def register_view(request):
8
  form = UserCreationForm(request.POST)
9
  if form.is_valid():
10
  login(request, form.save())
11
- return redirect("chat:room")
12
  else:
13
  form = UserCreationForm()
14
  return render(request, "users/register.html", { "form": form })
15
 
16
  def login_view(request):
17
  if request.user.is_authenticated:
18
- return redirect("../chat/room.html")
19
  if request.method == "POST":
20
  form = AuthenticationForm(data=request.POST)
21
  if form.is_valid():
@@ -25,15 +25,14 @@ def login_view(request):
25
  if 'next' in request.POST:
26
  return redirect(request.POST.get('next'))
27
  else:
28
- return redirect("chat.views.room")
29
  else:
30
  form = AuthenticationForm()
31
  return render(request, "users/login.html", { "form": form })
32
 
33
  def logout_view(request):
34
- if request.method == "POST":
35
- logout(request)
36
- return redirect("chat:room")
37
 
38
  def index_view(request):
39
  return render(request, "users/index.html")
 
8
  form = UserCreationForm(request.POST)
9
  if form.is_valid():
10
  login(request, form.save())
11
+ return redirect("chat:index")
12
  else:
13
  form = UserCreationForm()
14
  return render(request, "users/register.html", { "form": form })
15
 
16
  def login_view(request):
17
  if request.user.is_authenticated:
18
+ return redirect("chat:index")
19
  if request.method == "POST":
20
  form = AuthenticationForm(data=request.POST)
21
  if form.is_valid():
 
25
  if 'next' in request.POST:
26
  return redirect(request.POST.get('next'))
27
  else:
28
+ return redirect("chat:index")
29
  else:
30
  form = AuthenticationForm()
31
  return render(request, "users/login.html", { "form": form })
32
 
33
  def logout_view(request):
34
+ logout(request)
35
+ return redirect("chat:index")
 
36
 
37
  def index_view(request):
38
  return render(request, "users/index.html")