Pecximenes commited on
Commit
247406d
·
1 Parent(s): 0746d2c

Adding login and feedback to agent

Browse files
Files changed (3) hide show
  1. interface/app.py +1 -1
  2. interface/chatbot.py +87 -13
  3. interface/login.py +34 -12
interface/app.py CHANGED
@@ -33,8 +33,8 @@ def display_page_message(message):
33
 
34
 
35
  def main():
36
- app = Chatbot()
37
  login = Login()
 
38
 
39
  if not st.session_state.user_authorized:
40
  login.mount_login_page()
 
33
 
34
 
35
  def main():
 
36
  login = Login()
37
+ app = Chatbot()
38
 
39
  if not st.session_state.user_authorized:
40
  login.mount_login_page()
interface/chatbot.py CHANGED
@@ -11,7 +11,8 @@ from interface.auxiliary_functions import (
11
  extract_content,
12
  extract_links,
13
  fetch_webpage_content,
14
- url_to_suggestion
 
15
  )
16
 
17
  class Chatbot:
@@ -25,6 +26,24 @@ class Chatbot:
25
  "links": []
26
  }]
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # Conteúdo dos botões do sidebar
29
  if "topics" not in st.session_state:
30
  st.session_state["topics"] = [
@@ -40,6 +59,43 @@ class Chatbot:
40
  # Pergunta do usuário no chatbot
41
  self.response = ""
42
  self.links = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def create_sidebar(self):
45
  """Cria o sidebar com tópicos e opções."""
@@ -134,6 +190,20 @@ class Chatbot:
134
  all_links = extracted_links + original_links
135
  self.links.extend(all_links)
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  def display_feedback(self):
138
  user_input = st.session_state.chat_history[-2]["content"]
139
  bot_output = st.session_state.chat_history[-1]["content"]
@@ -151,23 +221,27 @@ class Chatbot:
151
  if rate is not None:
152
  if st.button("Enviar Avaliação"):
153
  try:
 
 
154
  feedback_rate = rate + 1
155
  # TODO Colocar nessa parte a estrutura para adicionar o feedback_data ao banco de dados
156
- # st.session_state.services["edgedb_client"].query('''
157
- # INSERT Feedback {
158
- # rating := <int16>$rating,
159
- # content := <str>$content,
160
- # message := <str>$content
161
- # }
162
- # ''',
163
- # message_id=bot_output,
164
- # rating=feedback_rate,
165
- # content=text_feedback,
166
- # )
 
 
167
  # st.session_state.chat_history
168
  st.success(f"Avaliação enviada!")
169
  except Exception as e:
170
  print(e)
171
  st.error("Erro ao enviar avaliação!")
172
 
173
- st.session_state.is_feedback_active = False # Desativando o feedback
 
11
  extract_content,
12
  extract_links,
13
  fetch_webpage_content,
14
+ url_to_suggestion,
15
+ connect_to_services
16
  )
17
 
18
  class Chatbot:
 
26
  "links": []
27
  }]
28
 
29
+ if "chat" not in st.session_state and st.session_state.get('username'):
30
+ chat = st.session_state.services["edgedb_client"].query('''
31
+ Select Chat {
32
+ id
33
+ } filter .user.username = <str>$username and .prototipo.id = <uuid>$prototipo_id
34
+ ''',
35
+ username=st.session_state.username,
36
+ prototipo_id=st.session_state.prototipo_id
37
+ )
38
+
39
+ if not chat:
40
+ chat = self._create_default_chat()
41
+ else:
42
+ chat = chat[0]
43
+ self.update_messages(chat)
44
+
45
+ st.session_state.chat = chat
46
+
47
  # Conteúdo dos botões do sidebar
48
  if "topics" not in st.session_state:
49
  st.session_state["topics"] = [
 
59
  # Pergunta do usuário no chatbot
60
  self.response = ""
61
  self.links = []
62
+
63
+ def _create_default_chat(self):
64
+ chat = st.session_state.services["edgedb_client"].query('''
65
+ INSERT Chat {
66
+ user := (SELECT User FILTER .username = <str>$username),
67
+ prototipo := (SELECT Prototipo FILTER .id = <uuid>$prototipo_id)
68
+ }
69
+ ''',
70
+ username=st.session_state.username,
71
+ prototipo_id=st.session_state.prototipo_id
72
+ )
73
+ message = st.session_state.services["edgedb_client"].query('''
74
+ SELECT (
75
+ INSERT Message {
76
+ content := "Como eu posso ajudar?",
77
+ role := "assistant",
78
+ chat := (SELECT Chat FILTER .id = <uuid>$chat_id)
79
+ }
80
+ ) {
81
+ content,
82
+ role
83
+ }
84
+ ''', chat_id=chat[0].id)
85
+ # st.session_state.chat_history = message
86
+ return chat[0]
87
+
88
+ def update_messages(self, chat):
89
+ messages = st.session_state.services["edgedb_client"].query('''
90
+ SELECT Message {
91
+ id,
92
+ content,
93
+ role
94
+ }
95
+ FILTER .chat.id = <uuid>$chat_id
96
+ ORDER BY .created_at ASC;
97
+ ''', chat_id=chat.id)
98
+ # st.session_state.chat_history = messages
99
 
100
  def create_sidebar(self):
101
  """Cria o sidebar com tópicos e opções."""
 
190
  all_links = extracted_links + original_links
191
  self.links.extend(all_links)
192
 
193
+ def _save_msg_to_db(self, msg, role):
194
+ message = st.session_state.services["edgedb_client"].query('''
195
+ SELECT (
196
+ INSERT Message {
197
+ content := <str>$content,
198
+ chat := (SELECT Chat FILTER .id = <uuid>$chat_id),
199
+ role := <str>$role
200
+ }
201
+ ) {
202
+ id
203
+ }
204
+ ''', content=msg, chat_id=st.session_state.chat.id, role=role)
205
+ return message
206
+
207
  def display_feedback(self):
208
  user_input = st.session_state.chat_history[-2]["content"]
209
  bot_output = st.session_state.chat_history[-1]["content"]
 
221
  if rate is not None:
222
  if st.button("Enviar Avaliação"):
223
  try:
224
+ msg = self._save_msg_to_db(bot_output, "assistant")
225
+
226
  feedback_rate = rate + 1
227
  # TODO Colocar nessa parte a estrutura para adicionar o feedback_data ao banco de dados
228
+ st.session_state.services["edgedb_client"].query('''
229
+ INSERT Feedback {
230
+ rating := <int16>$rating,
231
+ content := <str>$content,
232
+ message := (SELECT Message FILTER .id = <uuid>$message_id),
233
+ prototipo := (SELECT Prototipo FILTER .id = <uuid>$prototipo_id)
234
+ }
235
+ ''',
236
+ message_id=msg[-1].id,
237
+ rating=feedback_rate,
238
+ content=text_feedback,
239
+ prototipo_id=st.session_state.prototipo_id
240
+ )
241
  # st.session_state.chat_history
242
  st.success(f"Avaliação enviada!")
243
  except Exception as e:
244
  print(e)
245
  st.error("Erro ao enviar avaliação!")
246
 
247
+ st.session_state.is_feedback_active = False # Desativando o feedback
interface/login.py CHANGED
@@ -11,12 +11,6 @@ from auxiliary_functions import connect_to_services
11
 
12
  class Login:
13
  def __init__(self):
14
- if "username" not in st.session_state:
15
- st.session_state.username = ""
16
-
17
- if "user_authorized" not in st.session_state:
18
- st.session_state.user_authorized = False
19
-
20
  if "services" not in st.session_state:
21
  oa_client, qdrant_client, edgedb_client = connect_to_services()
22
  st.session_state.services = {
@@ -24,7 +18,20 @@ class Login:
24
  "qdrant_client": qdrant_client,
25
  "edgedb_client": edgedb_client
26
  }
 
 
 
 
 
 
 
 
27
 
 
 
 
 
 
28
 
29
  self.username = ""
30
  self.password = ""
@@ -36,22 +43,35 @@ class Login:
36
  with st.form("login_form"):
37
  st.title("Login")
38
 
39
- username = st.text_input('E-mail:')
40
  password = st.text_input('Senha:', type='password')
41
  submitted = st.form_submit_button("Entrar")
42
- st.text("Não possui uma conta?")
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  create_account = st.form_submit_button("Criar uma conta")
44
 
45
  if create_account:
46
  if not username:
47
- st.warning("Digite um email para cadastrar a conta.")
48
 
49
  if not password:
50
  st.warning("Digite uma senha para cadastrar a conta.")
51
 
52
  if username and password:
53
- if "@" not in username:
54
- st.warning("Digite um email válido para cadastrar a conta.")
55
 
56
  else:
57
  user = self.validate_credentials(username, password, return_just_user=True)
@@ -65,11 +85,13 @@ class Login:
65
  st.session_state.services["edgedb_client"].query('''
66
  INSERT User {
67
  username := <str>$username,
68
- password := <str>$password
 
69
  }
70
  ''',
71
  username=username, \
72
  password=hashed_password_str, \
 
73
  )
74
 
75
  st.success("Conta cadastrada com sucesso.")
 
11
 
12
  class Login:
13
  def __init__(self):
 
 
 
 
 
 
14
  if "services" not in st.session_state:
15
  oa_client, qdrant_client, edgedb_client = connect_to_services()
16
  st.session_state.services = {
 
18
  "qdrant_client": qdrant_client,
19
  "edgedb_client": edgedb_client
20
  }
21
+
22
+ if "prototipo" not in st.session_state:
23
+ prototipo = st.session_state.services["edgedb_client"].query('''
24
+ Select Prototipo {
25
+ id
26
+ } filter .name = <str>'agente'
27
+ ''')
28
+ st.session_state.prototipo_id = prototipo[0].id
29
 
30
+ if "username" not in st.session_state:
31
+ st.session_state.username = ""
32
+
33
+ if "user_authorized" not in st.session_state:
34
+ st.session_state.user_authorized = False
35
 
36
  self.username = ""
37
  self.password = ""
 
43
  with st.form("login_form"):
44
  st.title("Login")
45
 
46
+ username = st.text_input('Nome de usuário:')
47
  password = st.text_input('Senha:', type='password')
48
  submitted = st.form_submit_button("Entrar")
49
+
50
+ # Instruções de criação de conta
51
+ st.subheader("Não tem uma conta?")
52
+ st.write(
53
+ "Crie uma conta utilizando o seguinte formato para o nome de usuário: "
54
+ "@[PrimeiroNome][ÚltimoNome] - Certifique-se de usar um identificador para cada protótipo."
55
+ )
56
+
57
+ # Avisos sobre a criação de contas
58
+ st.warning(
59
+ "Lembre-se: você deverá criar **duas contas distintas**, uma para cada protótipo. "
60
+ "Para diferenciá-las, adicione um identificador no nome de usuário."
61
+ )
62
+ st.write("Exemplo: `@GabrielSilva-agente`")
63
  create_account = st.form_submit_button("Criar uma conta")
64
 
65
  if create_account:
66
  if not username:
67
+ st.warning("Digite um nome de usuário para cadastrar a conta.")
68
 
69
  if not password:
70
  st.warning("Digite uma senha para cadastrar a conta.")
71
 
72
  if username and password:
73
+ if username[0] != "@":
74
+ st.warning("Acrescente um '@' no início do nome de usuário para validar a conta.")
75
 
76
  else:
77
  user = self.validate_credentials(username, password, return_just_user=True)
 
85
  st.session_state.services["edgedb_client"].query('''
86
  INSERT User {
87
  username := <str>$username,
88
+ password := <str>$password,
89
+ prototipo := (SELECT Prototipo FILTER .id = <uuid>$prototipo_id)
90
  }
91
  ''',
92
  username=username, \
93
  password=hashed_password_str, \
94
+ prototipo_id=st.session_state.prototipo_id
95
  )
96
 
97
  st.success("Conta cadastrada com sucesso.")