tris4381 commited on
Commit
7ee062c
·
1 Parent(s): faa41a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -39
app.py CHANGED
@@ -1,6 +1,5 @@
1
  from __future__ import annotations
2
  from abc import ABC, abstractmethod
3
- from typing import List
4
  from openai_utils import chat_completion_request
5
  import gradio as gr
6
 
@@ -93,40 +92,47 @@ class NodeSingleChoice(Node):
93
 
94
  class NodeGptAnswer(Node):
95
  """
96
- genera e salva la risposta di gpt, poi salva i messages e passa al nodo successivo
97
  """
98
- def __init__(self, prompt: str, nextNode: str):
99
  self.prompt = prompt
 
100
  self.nextNode = nextNode
 
 
101
 
102
  def runNode(self, app_message):
103
  self.prompt = self.prompt.format(app_message)
104
- messages = self.chat.getmessages()
105
- if messages is not None:
106
- messages.append({'role':'user', 'content': self.prompt})
107
- else:
108
- messages = [{'role':'user', 'content': self.prompt}]
109
- response = chat_completion_request(messages)
110
- self.setmessages(app_message, response['choices'][0]['message']['content'])
111
- self.chat.setoutput(response['choices'][0]['message']['content'])
112
 
113
  def chooseNextNode(self):
114
- node_class = globals()[self.nextNode]
115
- self.chat.setNode(node_class())
116
-
117
- def setmessages(self, domanda, risposta):
118
- messages = self.chat.getmessages()
119
- if messages is not None:
120
- messages.append([{'role':'user', 'content':domanda}, {'role':'assistant', 'content':risposta}])
121
- self.chat.setmessages(messages)
122
 
123
 
124
  class NodePrintText(Node):
125
- def __init__(self, text: List[str], nextNode: str):
126
  self.text = text
127
  self.nextNode = nextNode
 
128
 
129
  def runNode(self, app_message):
 
 
 
 
 
 
130
  self.chat.setoutput(self.text)
131
  print(self.chat.getoutput())
132
 
@@ -141,11 +147,11 @@ class NodeTerminate(Node):
141
  """
142
  def runNode(self, app_message):
143
  self.chat.settermina('end')
144
- self.chat.setoutput(['fine chat'])
145
 
146
  def chooseNextNode(self):
147
  return None
148
-
149
 
150
  class NodeEntityExtraction(Node):
151
  """
@@ -202,39 +208,154 @@ class NodeEntityExtractionNextNode(NodeEntityExtraction):
202
  self.chat.setNode(node_class())
203
 
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  ###################################################################################################
206
  ########################################### CHATBOT ###############################################
207
  ###################################################################################################
208
 
209
 
210
- class domandacv(NodeGptAnswer):
211
- def __init__(self, prompt="""Rispondi a questa domanda: {}. Inizia la risposta dicendo "CV". Risposta: """, nextNode='termina'):
212
- super().__init__(prompt, nextNode)
 
213
 
214
- class domandallm(NodeGptAnswer):
215
- def __init__(self, prompt="""Rispondi a questa domanda: {}. Inizia la risposta dicendo "LLM". Risposta: """, nextNode='termina'):
216
- super().__init__(prompt, nextNode)
 
 
 
 
 
 
 
 
 
 
217
 
218
- class intro(NodePrintText):
219
- def __init__(self, text="Ciao! Sono un chatbot, quale ambito ti interessa: LLM oppure Computer Vision?", nextNode='entity'):
 
 
220
  super().__init__(text, nextNode)
221
 
222
- class repeat(NodePrintText):
223
- def __init__(self, text="repeatplease", nextNode='entity'):
 
224
  super().__init__(text, nextNode)
225
 
226
- class entity(NodeEntityExtractionNextNode):
227
- def __init__(self, prompt="""Che cosa vuole l'utente? Rispondi scegliendo una delle seguenti: "terminare la conversazione", "fare una domanda su LLM", "fare una domanda su computer vision". Domanda utente: {}""", entity_list=['terminare conversazione', 'domanda LLM', 'domanda computer vision'], entity_parsing_list=['terminare', 'llm', 'vision'], repeatNode='repeat', node_list=['termina', 'domandallm', 'domandacv']):
 
 
 
228
  super().__init__(prompt, entity_list, entity_parsing_list, repeatNode, node_list)
229
 
230
- class termina(NodeTerminate):
231
- def __init__(self, nextNode='stampa1'):
232
- super().__init__(nextNode)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
 
235
 
236
- ######################################################################
237
- chatbot = Chat(intro())
238
 
239
  def generate_message(message, history):
240
  output = None
 
1
  from __future__ import annotations
2
  from abc import ABC, abstractmethod
 
3
  from openai_utils import chat_completion_request
4
  import gradio as gr
5
 
 
92
 
93
  class NodeGptAnswer(Node):
94
  """
95
+ genera e salva la risposta di gpt, passa al nodo successivo
96
  """
97
+ def __init__(self, prompt: str, set_variable_response: str, nextNode: str, errorNode: str):
98
  self.prompt = prompt
99
+ self.set_variable_response = set_variable_response
100
  self.nextNode = nextNode
101
+ self.errorNode = errorNode
102
+ error = None
103
 
104
  def runNode(self, app_message):
105
  self.prompt = self.prompt.format(app_message)
106
+ messages = [{'role':'user', 'content': self.prompt}]
107
+ try:
108
+ response = chat_completion_request(messages)
109
+ setattr(self.chat, self.set_variable_response, response['choices'][0]['message']['content'])
110
+ except:
111
+ self.error = 'error'
112
+ self.chat.setoutput(None)
 
113
 
114
  def chooseNextNode(self):
115
+ if self.error is None:
116
+ node_class = globals()[self.nextNode]
117
+ self.chat.setNode(node_class())
118
+ else:
119
+ node_class = globals()[self.errorNode]
120
+ self.chat.setNode(node_class())
 
 
121
 
122
 
123
  class NodePrintText(Node):
124
+ def __init__(self, text: str, nextNode: str, get_variable_list: list = None):
125
  self.text = text
126
  self.nextNode = nextNode
127
+ self.get_variable_list = get_variable_list
128
 
129
  def runNode(self, app_message):
130
+ if self.get_variable_list is not None:
131
+ list_variable = []
132
+ for get_variable in self.get_variable_list:
133
+ variable = getattr(self.chat, get_variable)
134
+ list_variable.append(variable)
135
+ self.text = self.text.format(*list_variable)
136
  self.chat.setoutput(self.text)
137
  print(self.chat.getoutput())
138
 
 
147
  """
148
  def runNode(self, app_message):
149
  self.chat.settermina('end')
150
+ self.chat.setoutput('fine chat')
151
 
152
  def chooseNextNode(self):
153
  return None
154
+
155
 
156
  class NodeEntityExtraction(Node):
157
  """
 
208
  self.chat.setNode(node_class())
209
 
210
 
211
+ class NodeEntityExtractionStore(NodeEntityExtraction):
212
+ def __init__(self, prompt: str, entity_list: str, entity_parsing_list: str, repeatNode: str, set_variable: str, nextNode: str):
213
+ super().__init__(prompt, entity_list, entity_parsing_list, repeatNode)
214
+ self.set_variable = set_variable
215
+ self.nextNode = nextNode
216
+
217
+ def runNode(self, app_message):
218
+ super().runNode(app_message)
219
+ setattr(self.chat, self.set_variable, self._user_intent)
220
+
221
+ def chooseNextNode(self):
222
+ super().chooseNextNode()
223
+ if self._user_intent is not None:
224
+ node_class = globals()[self.nextNode]
225
+ self.chat.setNode(node_class())
226
+
227
+
228
+ class NodeSingleChoiceNextNode(NodeSingleChoice):
229
+ """
230
+ sceglie il prossimo nodo in base a input utente
231
+ """
232
+ def __init__(self, choice_list: list, repeatNode: str, node_list: list):
233
+ super().__init__(choice_list, repeatNode)
234
+ self.node_list = node_list
235
+
236
+ def chooseNextNode(self):
237
+ super().chooseNextNode()
238
+ for choice, node in zip(self.choice_list, self.node_list):
239
+ if self._user_choice == choice:
240
+ node_class = globals()[node]
241
+ self.chat.setNode(node_class())
242
+
243
+
244
  ###################################################################################################
245
  ########################################### CHATBOT ###############################################
246
  ###################################################################################################
247
 
248
 
249
+ class introduzione(NodePrintText):
250
+ def __init__(self, text="Ciao! Sono un chatbot, sono qui per rispondere alle tue domande. Scegli la tipologia di richiesta: scrivi 'a' per domanda aperta e 'b' per risolvere una operazione matematica.",
251
+ nextNode='tipologiadomanda'):
252
+ super().__init__(text, nextNode)
253
 
254
+ class introduzioneripeti(NodePrintText):
255
+ def __init__(self, text="Scusa non ho capito, puoi ripetere? Scrivi 'a' per domanda aperta e 'b' per risolvere una operazione matematica.",
256
+ nextNode='tipologiadomanda'):
257
+ super().__init__(text, nextNode)
258
+
259
+ class tipologiadomanda(NodeSingleChoiceNextNode):
260
+ def __init__(self, choice_list=['a', 'b'], repeatNode='introduzioneripeti', node_list=['domandaaperta', 'operazionemate']):
261
+ super().__init__(choice_list, repeatNode, node_list)
262
+
263
+ class introduzionecambio(NodePrintText):
264
+ def __init__(self, text="Certo che puoi cambiare tipo di richiesta: scrivi 'a' per domanda aperta e 'b' per risolvere una operazione matematica.",
265
+ nextNode='tipologiadomanda'):
266
+ super().__init__(text, nextNode)
267
 
268
+ # lato domanda aperta
269
+ class domandaaperta(NodePrintText):
270
+ def __init__(self, text="Bene, risponderò alla tua domanda aperta! Sono un esperto di scienze, storia e geografia. Fammi pure una domanda breve!",
271
+ nextNode='controlladomandaaperta'):
272
  super().__init__(text, nextNode)
273
 
274
+ class domandaapertaripeti(NodePrintText):
275
+ def __init__(self, text="Scusa non ho capito, puoi ripetere? Sono un esperto di scienze, storia e geografia. Fammi pure una domanda breve!",
276
+ nextNode='controlladomandaaperta'):
277
  super().__init__(text, nextNode)
278
 
279
+ class controlladomandaaperta(NodeEntityExtractionNextNode):
280
+ def __init__(self, prompt="Leggi l'input utente e scrivi una delle seguenti opzioni, in base a cosa sta chiedendo l'utente: 'terminare conversazione', 'cambiare tipo domanda', 'fare domanda'. Input utente: {}",
281
+ entity_list=['terminare conversazione', 'cambiare tipo richiesta', 'fare domanda'],
282
+ entity_parsing_list=['terminare', 'tipo', 'domanda'], repeatNode='domandaapertaripeti',
283
+ node_list=['NodeTerminate', 'introduzionecambio', 'controlladomandaapertatema']):
284
  super().__init__(prompt, entity_list, entity_parsing_list, repeatNode, node_list)
285
 
286
+ class controlladomandaapertatema(NodeEntityExtractionStore):
287
+ def __init__(self, prompt="Leggi l'input utente e scrivi una delle seguenti opzioni, in base a cosa sta chiedendo l'utente: 'geografia', 'storia', 'scienze'. Input utente: {}",
288
+ entity_list=['geografia', 'storia', 'scienze'],
289
+ entity_parsing_list=['geografia', 'storia', 'scienze'], repeatNode='domandaapertaripeti',
290
+ set_variable='tema', nextNode='rispondidomandaaperta'):
291
+ super().__init__(prompt, entity_list, entity_parsing_list, repeatNode, set_variable, nextNode)
292
+
293
+ class rispondidomandaaperta(NodeGptAnswer):
294
+ def __init__(self, prompt="Rispondi in 6/7 parole massimo. Domanda: {} Risposta: ",
295
+ set_variable_response='risposta', nextNode='stamparispostaaperta', errorNode='erroregptdomandaaperta'):
296
+ super().__init__(prompt, set_variable_response, nextNode, errorNode)
297
+
298
+ class erroregptdomandaaperta(NodePrintText):
299
+ def __init__(self, text="C'è stato un errore. Rifai la domanda.", nextNode='controlladomandaapertatema'):
300
+ super().__init__(text, nextNode)
301
+
302
+ class stamparispostaaperta(NodePrintText):
303
+ def __init__(self, text="Hai fatto una domanda di {}. Risposta: {}. Desideri fare un'altra domanda aperta? Rispondi con 'si' o 'no'.", nextNode='altradomandaapertaclassifica', get_variable_list=['tema', 'risposta']):
304
+ super().__init__(text, nextNode, get_variable_list)
305
+
306
+ class altradomandaapertaripeti(NodePrintText):
307
+ def __init__(self, text="Scusa non ho capito, puoi ripetere? Rispondi con 'si' o 'no'.", nextNode='altradomandaapertaclassifica'):
308
+ super().__init__(text, nextNode)
309
+
310
+ class altradomandaapertaclassifica(NodeSingleChoiceNextNode):
311
+ def __init__(self, choice_list=['si', 'no'], repeatNode='altradomandaapertaripeti', node_list=['domandaaperta', 'NodeTerminate']):
312
+ super().__init__(choice_list, repeatNode, node_list)
313
+
314
+
315
+ # lato operazione matematica
316
+ class operazionemate(NodePrintText):
317
+ def __init__(self, text="Bene, risolverò le tue operazioni matematiche. Scrivi qui l'operazione da svolgere!",
318
+ nextNode='controllamate'):
319
+ super().__init__(text, nextNode)
320
+
321
+ class operazionemateripeti(NodePrintText):
322
+ def __init__(self, text="Non ho capito, puoi ripetere? Scrivi qui l'operazione da svolgere!",
323
+ nextNode='controllamate'):
324
+ super().__init__(text, nextNode)
325
+
326
+ class controllamate(NodeEntityExtractionNextNode):
327
+ def __init__(self, prompt="Leggi l'input utente e scrivi una delle seguenti opzioni, in base a cosa sta chiedendo l'utente: 'terminare conversazione', 'cambiare tipo domanda', 'operazione matematica'. Input utente: {}",
328
+ entity_list=['terminare conversazione', 'cambiare tipo richiesta', 'operazione matematica'],
329
+ entity_parsing_list=['terminare', 'tipo', 'mate'], repeatNode='operazionemateripeti',
330
+ node_list=['NodeTerminate', 'introduzionecambio', 'rispondimate']):
331
+ super().__init__(prompt, entity_list, entity_parsing_list, repeatNode, node_list)
332
+
333
+ class rispondimate(NodeGptAnswer):
334
+ def __init__(self, prompt="Risolvi questa operazione, rispondi solo con la cifra. Operazione: {} Soluzione: ",
335
+ set_variable_response='risposta', nextNode='stamparispostamate', errorNode='erroregptmate'):
336
+ super().__init__(prompt, set_variable_response, nextNode, errorNode)
337
+
338
+ class erroregptmate(NodePrintText):
339
+ def __init__(self, text="C'è stato un errore. Riscrivi l'operazione.", nextNode='controllamate'):
340
+ super().__init__(text, nextNode)
341
+
342
+ class stamparispostamate(NodePrintText):
343
+ def __init__(self, text="Soluzione: {}. Desideri fare un'altra domanda di matematica? Rispondi con 'si' o 'no'.", nextNode='altradomandamateclassifica',
344
+ get_variable_list=['risposta']):
345
+ super().__init__(text, nextNode, get_variable_list)
346
+
347
+ class altradomandamateripeti(NodePrintText):
348
+ def __init__(self, text="Non ho capito, puoi ripetere? Rispondi con 'si' o 'no'.", nextNode='altradomandamateclassifica'):
349
+ super().__init__(text, nextNode)
350
+
351
+ class altradomandamateclassifica(NodeSingleChoiceNextNode):
352
+ def __init__(self, choice_list=['si', 'no'], repeatNode='altradomandaapertaripeti', node_list=['operazionemate', 'NodeTerminate']):
353
+ super().__init__(choice_list, repeatNode, node_list)
354
 
355
 
356
 
357
+ ######################################################################################
358
+ chatbot = Chat(introduzione())
359
 
360
  def generate_message(message, history):
361
  output = None