pbesa 4.0.2__tar.gz → 4.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. {pbesa-4.0.2 → pbesa-4.0.4}/PKG-INFO +1 -1
  2. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/cognitive.py +145 -88
  3. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/collaborative_team.py +32 -3
  4. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/dispatcher_team.py +15 -39
  5. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/selected_dispatcher_team.py +13 -10
  6. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/worker.py +39 -10
  7. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa.egg-info/PKG-INFO +1 -1
  8. {pbesa-4.0.2 → pbesa-4.0.4}/setup.py +1 -1
  9. {pbesa-4.0.2 → pbesa-4.0.4}/.gitignore +0 -0
  10. {pbesa-4.0.2 → pbesa-4.0.4}/LICENSE +0 -0
  11. {pbesa-4.0.2 → pbesa-4.0.4}/LICENSE.txt +0 -0
  12. {pbesa-4.0.2 → pbesa-4.0.4}/MANIFEST +0 -0
  13. {pbesa-4.0.2 → pbesa-4.0.4}/README.md +0 -0
  14. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/db.sqlite3 +0 -0
  15. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__init__.py +0 -0
  16. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__pycache__/__init__.cpython-36.pyc +0 -0
  17. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__pycache__/pbesa.cpython-36.pyc +0 -0
  18. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__pycache__/settings.cpython-36.pyc +0 -0
  19. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__pycache__/urls.cpython-36.pyc +0 -0
  20. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/__pycache__/wsgi.cpython-36.pyc +0 -0
  21. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/asgi.py +0 -0
  22. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/pbesa.py +0 -0
  23. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/settings.py +0 -0
  24. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/urls.py +0 -0
  25. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/helloworld/wsgi.py +0 -0
  26. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/manage.py +0 -0
  27. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__init__.py +0 -0
  28. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/__init__.cpython-36.pyc +0 -0
  29. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/admin.cpython-36.pyc +0 -0
  30. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/apps.cpython-36.pyc +0 -0
  31. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/models.cpython-36.pyc +0 -0
  32. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/urls.cpython-36.pyc +0 -0
  33. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/__pycache__/views.cpython-36.pyc +0 -0
  34. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/admin.py +0 -0
  35. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/apps.py +0 -0
  36. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/__pycache__/translatecontroller.cpython-36.pyc +0 -0
  37. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/__pycache__/translatedelegate.cpython-36.pyc +0 -0
  38. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/__pycache__/translateresponse.cpython-36.pyc +0 -0
  39. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/translatecontroller.py +0 -0
  40. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/translatedelegate.py +0 -0
  41. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/controller/translateresponse.py +0 -0
  42. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/worker/__pycache__/translatetask.cpython-36.pyc +0 -0
  43. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/worker/__pycache__/workeragent.cpython-36.pyc +0 -0
  44. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/worker/translatetask.py +0 -0
  45. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/mas/worker/workeragent.py +0 -0
  46. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/migrations/__init__.py +0 -0
  47. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/migrations/__pycache__/__init__.cpython-36.pyc +0 -0
  48. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/models.py +0 -0
  49. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/tests.py +0 -0
  50. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/urls.py +0 -0
  51. {pbesa-4.0.2 → pbesa-4.0.4}/examples/django/helloworld/translate/views.py +0 -0
  52. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/countercontroller.cpython-36.pyc +0 -0
  53. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/counterdelegate.cpython-36.pyc +0 -0
  54. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/counterresponse.cpython-36.pyc +0 -0
  55. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/translatecontroller.cpython-36.pyc +0 -0
  56. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/translatedelegate.cpython-36.pyc +0 -0
  57. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/__pycache__/translateresponse.cpython-36.pyc +0 -0
  58. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/countercontroller.py +0 -0
  59. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/counterdelegate.py +0 -0
  60. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/controller/counterresponse.py +0 -0
  61. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/__pycache__/counteragent.cpython-36.pyc +0 -0
  62. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/__pycache__/countertask.cpython-36.pyc +0 -0
  63. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/__pycache__/translatetask.cpython-36.pyc +0 -0
  64. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/__pycache__/workeragent.cpython-36.pyc +0 -0
  65. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/counteragent.py +0 -0
  66. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/mas/worker/countertask.py +0 -0
  67. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/remote_a.py +0 -0
  68. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/remote_b.py +0 -0
  69. {pbesa-4.0.2 → pbesa-4.0.4}/examples/remote/remote_c.py +0 -0
  70. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/__init__.py +0 -0
  71. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/__init__.py +0 -0
  72. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/adapter.py +0 -0
  73. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/agent.py +0 -0
  74. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/io/__init__.py +0 -0
  75. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/io/system_file.py +0 -0
  76. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/io/tcp_server.py +0 -0
  77. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/__init__.py +0 -0
  78. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/__pycache__/__init__.cpython-36.pyc +0 -0
  79. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/__pycache__/__init__.cpython-37.pyc +0 -0
  80. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/__pycache__/__init__.cpython-38.pyc +0 -0
  81. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/__pycache__/__init__.cpython-39.pyc +0 -0
  82. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/res/conf.json +0 -0
  83. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/util.py +0 -0
  84. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/kernel/world.py +0 -0
  85. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/mas.py +0 -0
  86. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/models.py +0 -0
  87. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/__init__.py +0 -0
  88. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/adm_listener.py +0 -0
  89. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/adm_listener_handler.py +0 -0
  90. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/exceptions.py +0 -0
  91. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/remote_adm.py +0 -0
  92. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/remote/remote_adm_handler.py +0 -0
  93. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/__init__.py +0 -0
  94. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/delegator.py +0 -0
  95. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/delegator_team.py +0 -0
  96. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/dialog.py +0 -0
  97. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/prompts.py +0 -0
  98. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa/social/templates.py +0 -0
  99. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa.egg-info/SOURCES.txt +0 -0
  100. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa.egg-info/dependency_links.txt +0 -0
  101. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa.egg-info/requires.txt +0 -0
  102. {pbesa-4.0.2 → pbesa-4.0.4}/pbesa.egg-info/top_level.txt +0 -0
  103. {pbesa-4.0.2 → pbesa-4.0.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: pbesa
3
- Version: 4.0.2
3
+ Version: 4.0.4
4
4
  License-File: LICENSE
5
5
  License-File: LICENSE.txt
6
6
  Requires-Dist: pymongo==4.6.3
@@ -13,7 +13,8 @@
13
13
  # Define resources
14
14
  # --------------------------------------------------------
15
15
 
16
- import re
16
+ import json
17
+ import logging
17
18
  import traceback
18
19
  from pydantic import BaseModel
19
20
  from typing import List, Optional
@@ -263,7 +264,7 @@ class AugmentedGeneration(ABC):
263
264
  """ Reset method """
264
265
  self.__work_memory = []
265
266
  # Set up model
266
- self.set_up_model()
267
+ self.setup_world()
267
268
 
268
269
  def derive(self, query) -> str:
269
270
  """ Generate method
@@ -275,7 +276,7 @@ class AugmentedGeneration(ABC):
275
276
  instantane_memory = self.__work_memory.copy()
276
277
  instantane_memory.append({"role": "user", "content": prompt})
277
278
  text = self.__ai_service.generate(instantane_memory)
278
- print("Pensamiento:", text)
279
+ logging.info(f"Thought: {text}")
279
280
  if self.__def_tool_dict:
280
281
  tool = self.__def_tool_dict.get(self.__role.tool)
281
282
  if tool:
@@ -285,6 +286,10 @@ class AugmentedGeneration(ABC):
285
286
  return text
286
287
  except Exception as e:
287
288
  traceback.print_exc()
289
+
290
+ logging.info(f"------------RESET---------------")
291
+ self.reset()
292
+
288
293
  return "Lo lamento, no puedo responder en este momento"
289
294
 
290
295
  def get_role(self) -> Role:
@@ -461,13 +466,24 @@ class Dialog(ABC):
461
466
  # Define deep
462
467
  self.__deep_count = 0
463
468
  self.__deep_limit = 3
469
+ # Define knowledge
470
+ self.knowledge = None
464
471
 
465
472
  def setup_world(self):
466
473
  """ Set up model method """
467
474
  # Define role
468
- self.__work_memory.append({"role": "user", "content": self.__role.objective})
469
- self.__work_memory.append({"role": "user", "content": self.__role.arquetype})
470
- self.__work_memory.append({"role": "user", "content": self.__role.example})
475
+ instrucciones = f"Instrucciones:\n{self.__role.description}\n Tu tarea: {self.__role.objective}\n"
476
+ requisitos = f"Requisitos:\n{self.__role.arquetype}\n"
477
+ ejemplo = f"Ejemplo:\n{self.__role.example}\n"
478
+ if self.knowledge:
479
+ conocimiento = f"Conocimiento:\n{self.knowledge}\n"
480
+ continuar = "Ahora, evalúa el siguiente caso:\n"
481
+ self.__work_memory.append({"role": "user", "content": instrucciones})
482
+ self.__work_memory.append({"role": "user", "content": requisitos})
483
+ self.__work_memory.append({"role": "user", "content": ejemplo})
484
+ if self.knowledge:
485
+ self.__work_memory.append({"role": "user", "content": conocimiento})
486
+ self.__work_memory.append({"role": "user", "content": continuar})
471
487
 
472
488
  def get_model(self) -> any:
473
489
  """ Get model method
@@ -502,29 +518,29 @@ class Dialog(ABC):
502
518
  self.setup_world()
503
519
  interations = agent_metadata.role.interactions
504
520
  grafo = recorrer_interacciones(interations)
505
- print("")
521
+ logging.info("")
506
522
  # Si el grafo es una lista de nodos, lo imprimimos cada uno
507
523
  if isinstance(grafo, list):
508
524
  for nodo in grafo:
509
525
  imprimir_grafo(nodo)
510
526
  else:
511
527
  imprimir_grafo(grafo)
512
- print("")
528
+ logging.info("")
513
529
  # Ejemplo de uso:
514
530
  self.__dfa = extraer_diccionario_nodos(grafo)
515
531
  # Mostrar el diccionario
516
532
  for clave, valor in self.__dfa.items():
517
- print(f"{clave}: {valor.text}")
518
- print("")
533
+ logging.info(f"{clave}: {valor.text}")
534
+ logging.info("")
519
535
  iniciadores = []
520
536
  for item in interations:
521
537
  for clave, valor in self.__dfa.items():
522
538
  if valor.text == item['texto']:
523
539
  iniciadores.append(valor)
524
- print("Iniciadores:")
540
+ logging.info("Iniciadores:")
525
541
  for iniciador in iniciadores:
526
- print(iniciador.text)
527
- print("")
542
+ logging.info(iniciador.text)
543
+ logging.info("")
528
544
  # Set dialog state
529
545
  self.__dfa['start'] = iniciadores
530
546
 
@@ -544,7 +560,7 @@ class Dialog(ABC):
544
560
  """ Reset method """
545
561
  self.__work_memory = []
546
562
  # Set up model
547
- self.set_up_model()
563
+ self.setup_world()
548
564
 
549
565
  def team_inquiry(self, team, data, operation, session_flag) -> str:
550
566
  canales = self.state['canales']
@@ -559,15 +575,11 @@ class Dialog(ABC):
559
575
  }
560
576
  else:
561
577
  if session_flag:
562
- pass
563
- #session_id = self.state['session_id']
564
- #print("=> session_flag -> " + session_id)
565
- #dto = {
566
- # "data": {
567
- # 'text': data,
568
- # 'session_id': session_id
569
- # },
570
- #}
578
+ logging.info(f"Session flag: {session_flag}")
579
+ logging.info(f"------------RESET--------------- {data}")
580
+ self.reset()
581
+ return data
582
+
571
583
  else:
572
584
  dto = {
573
585
  "data": {
@@ -577,63 +589,75 @@ class Dialog(ABC):
577
589
  response = canal.post(team.lower(), dto)
578
590
  if response['status']:
579
591
  return response['message']['response']
592
+
593
+ logging.info(f"------------RESET---------------")
594
+ self.reset()
580
595
  return "Lo lamento, no puedo responder en este momento"
581
596
 
582
- def get_text(self, inputs) -> str:
583
- matches = re.findall(r'<\|im_start\|>(user|assistant)\n(.*?)<\|im_end\|>', inputs, re.DOTALL)
584
- if matches:
585
- messages = []
586
- for speaker, text in matches:
587
- messages.append({
588
- "Assistant": speaker.capitalize(),
589
- "User": text.strip()
590
- })
591
- if len(messages) > 0:
592
- return messages[-1]["Assistant"]
593
- else:
594
- return messages[-1]["User"]
595
- return inputs
597
+ def get_text(self, mensaje) -> str:
598
+ mensaje_limpio = mensaje.replace("<|im_start|>user<|im_sep|>", "").replace("<|im_start|>system<|im_sep|>", "")
599
+ mensaje_limpio = mensaje_limpio.replace("<|im_start|>", "").replace("<|im_sep|>", "").replace("<|im_end|>", "")
600
+ mensaje_limpio = mensaje_limpio.replace("[Usuario]: ", "").replace("[Sistema]: ", "")
601
+ return mensaje_limpio.strip()
596
602
 
597
603
  def transition(self, owner, dialog_state, query, team_source=False) -> str:
604
+ logging.info(f"Transition: {owner} -> {dialog_state}, Team: {team_source}, Query: {query}")
598
605
  text = ""
606
+
607
+ # Verifica que exista la performativa
608
+ if not dialog_state in self.__dfa:
609
+ logging.warning(f"------------Performativa no existe---------------")
610
+ self.reset()
611
+ return "Web", DialogState.START, "Lo lamento, no puedo responder en este momento", "Web"
612
+
599
613
  node = self.__dfa[dialog_state]
600
614
  if not isinstance(node, list):
601
615
  node = node.children
602
- options = ""
603
- cont = 1
604
- for item in node:
605
- options += f"{cont}) {item.text}\n"
606
- cont += 1
607
- prompt = CLASSIFICATION_PROMPT % (query, options)
608
- print("Query:", query, "\n", "Options:", options)
609
- self.__meta_work_memory.append({"role": "user", "content": prompt})
610
- text = self.__ai_service.generate(self.__meta_work_memory)
611
- self.__meta_work_memory = []
612
- print("Pensamiento:", text)
613
-
614
- select_node = None
615
- for option in range(1, cont):
616
- if str(option) in text:
617
- select_node = node[option-1]
618
- break
619
- if not select_node:
620
- print("=> No se seleccionó ninguna opción")
621
- print("=> Node:", node)
622
- print("=> len node:", len(node))
623
- if node and len(node)> 0:
616
+
617
+ # Flujo de selección
618
+ if node and len(node)> 1:
619
+ logging.info(f"--> Más de una opción.")
620
+ options = ""
621
+ cont = 1
622
+ for item in node:
623
+ options += f"{cont}) {item.text}\n"
624
+ cont += 1
625
+ prompt = CLASSIFICATION_PROMPT % (query, options)
626
+ logging.info(f"Query: {query},\n Options:\n{options}")
627
+ self.__meta_work_memory.append({"role": "user", "content": prompt})
628
+ text = self.__ai_service.generate(self.__meta_work_memory)
629
+ logging.info(f"Thought: {text}")
630
+ self.__meta_work_memory = []
631
+ text = self.get_text(text)
632
+ select_node = None
633
+ for option in range(1, cont):
634
+ if str(option) in text:
635
+ select_node = node[option-1]
636
+ logging.info(f"Select node: {select_node.text}")
637
+ break
638
+ if not select_node:
639
+ logging.info("=> No se seleccionó ninguna opción")
640
+ logging.info(f"=> Node: {node}")
641
+ logging.info(f"=> len node: {len(node)}")
624
642
  select_node = node[0]
625
- print(select_node.text)
626
- text = "Lo lamento, no puedo responder en este momento"
627
- print("???> text:", text)
643
+ logging.info(f"=> Selecciona el primer nodo: {select_node.text}")
644
+ elif node and len(node) == 1:
645
+ logging.info(f"--> Una opción.")
646
+ select_node = node[0]
647
+ else:
648
+ logging.info(f"------------RESET---------------")
649
+ self.reset()
650
+ logging.info(f"???> text: {text} es terminal")
628
651
  text = self.get_text(text)
629
652
  return owner, DialogState.START, text, owner
630
-
653
+
654
+ # Flujo normal
655
+ logging.info(f"Flujo normal: {select_node.text}")
631
656
  if team_source:
632
657
  self.__work_memory.append({"role": "user", "content": select_node.text})
633
658
  else:
634
659
  self.__work_memory.append({"role": "user", "content": query})
635
660
  self.__work_memory.append({"role": "user", "content": select_node.text})
636
-
637
661
  new_owner, new_dialog_state, text, team = self.do_transition(owner, select_node.children[0], query)
638
662
  text = self.get_text(text)
639
663
  return new_owner, new_dialog_state, text, team
@@ -643,7 +667,7 @@ class Dialog(ABC):
643
667
  :return: str
644
668
  """
645
669
  if isinstance(node, DeclarativeNode):
646
- print("-> node:", node.text)
670
+ logging.info(f"D -> node: {node.text}")
647
671
  self.__work_memory.append({"role": "user", "content": node.text})
648
672
  elif isinstance(node, ActionNode):
649
673
 
@@ -651,76 +675,109 @@ class Dialog(ABC):
651
675
  # Accion
652
676
  #------------------------------
653
677
 
654
- print("-> node action:", node.action)
678
+ logging.info(f"-> node action: {node.action}")
655
679
  if node.tool and not node.tool == "Ninguno":
656
- print("-> node tool:", node.tool)
657
- self.__work_memory.append({"role": "user", "content": node.text})
680
+ logging.info(f"-> node tool: {node.tool}")
681
+ self.__work_memory.append({"role": "user", "content": node.text})
682
+ logging.info("-----")
683
+ logging.info("\n%s", json.dumps(self.__work_memory, indent=4))
684
+ logging.info("-----")
658
685
  res = self.__ai_service.generate(self.__work_memory)
659
-
686
+ logging.info(f"-> node tool: {res}")
687
+ res = self.get_text(res)
660
688
  # Check if res is empty
661
689
  if not res or res == "":
690
+ logging.info("1 -> res vacio")
662
691
  res = "Lo lamento, no puedo responder en este momento"
663
- return owner, DialogState.START, res, owner
664
692
 
665
- print("-> node tool: envia", res)
693
+ logging.info(f"------------RESET---------------")
694
+ self.reset()
666
695
 
696
+ return owner, DialogState.START, res, owner
697
+ logging.info(f"-> node tool: envia -> {res}")
667
698
  text = self.team_inquiry(node.team, res, node.tool, False)
668
699
  else:
669
-
670
700
  #------------------------------
671
701
  # Lllamada
672
702
  #------------------------------
673
-
674
- print("-> node team:", node.team)
703
+ logging.info(f"-> node team: {node.team}")
675
704
  # Verifica si el nodo es termianl ya que significa
676
705
  # que el dialogo cambia de agente
677
706
  if node.is_terminal:
678
- print("-> node team -> es terminal -> " + node.text)
707
+ logging.info(f"-> node team -> es terminal -> {node.text}")
679
708
  self.__work_memory.append({"role": "user", "content": node.text})
709
+ logging.info("-----")
710
+ logging.info("\n%s", json.dumps(self.__work_memory, indent=4))
711
+ logging.info("-----")
680
712
  res = self.__ai_service.generate(self.__work_memory)
681
713
  res = self.get_text(res)
682
714
  self.__work_memory.append({"role": "system", "content": res})
683
-
684
715
  # Check if res is empty
685
716
  if not res or res == "":
717
+ logging.info("2 -> res vacio")
686
718
  res = "Lo lamento, no puedo responder en este momento"
719
+ logging.info(f"------------RESET---------------")
720
+ self.reset()
687
721
  return owner, DialogState.START, res, owner
688
-
689
- print("-> node team -> envia:", res)
690
- #text = self.team_inquiry(node.team, res, None, True)
722
+ logging.info(f"-> node team -> envia: {res}")
723
+ text = self.team_inquiry(node.team, res, None, True)
691
724
  return node.team, DialogState.START, res, node.team
692
725
  else:
693
- print("-> node team -> continua")
726
+ logging.info("-> node team -> continua")
694
727
  self.__work_memory.append({"role": "user", "content": node.text})
695
- print("-> node team -> envia:", query)
728
+ logging.info(f"-> node team -> envia: {query}")
696
729
  text = self.team_inquiry(node.team, query, node.tool, False)
697
-
730
+ logging.info(f"-> node team -> text: {text}")
731
+ if text:
732
+ logging.info(f"-> Adicion WM node team -> text: {text}")
733
+ self.__work_memory.append({"role": "system", "content": text})
698
734
  self.__deep_count += 1
699
735
  if self.__deep_count < self.__deep_limit:
700
736
  return self.transition(owner, node.performative, text, True)
701
737
  else:
702
738
  self.__deep_count = 0
739
+ logging.info("-> node team -> deep limit")
740
+
741
+ logging.info(f"------------RESET---------------")
742
+ self.reset()
743
+
703
744
  return "Web", DialogState.START, "Lo lamento me he perdido, ¿podrías repetir la pregunta?"
704
745
  else:
705
- print("!!!!!!!!!!!!!!!!!!!!!!!> Otro tipo de nodo:", node.text)
746
+ logging.info(f"!!!!!!!!!!!!!!!!!!!!!!!> Otro tipo de nodo: {node.text}")
706
747
 
748
+ logging.info(f"=> !!!!: {query}")
749
+ logging.info("-----")
750
+ logging.info("\n%s", json.dumps(self.__work_memory, indent=4))
751
+ logging.info("-----")
707
752
  res = self.__ai_service.generate(self.__work_memory)
753
+ logging.info(f"=> res: {res}")
708
754
  res = self.get_text(res)
709
755
  self.__work_memory.append({"role": "system", "content": res})
710
-
711
756
  # Check if res is empty
712
757
  if not res or res == "":
758
+ logging.info("3 -> res vacio")
759
+
760
+ logging.info(f"------------RESET---------------")
761
+ self.reset()
762
+
713
763
  res = "Lo lamento, no puedo responder en este momento"
714
764
  return owner, DialogState.START, res, owner
715
765
 
716
- print("=> Pensamiento DEEP:", res)
766
+ logging.info(f"=> Thought DEEP: {res}")
717
767
 
718
768
  new_dialog_state = node.performative
719
769
  if not node.is_terminal:
720
- print("=> new_owner:", owner, "new_dialog_state:", new_dialog_state)
770
+ logging.info(f"=> new_owner: {owner} new_dialog_state: {new_dialog_state}")
721
771
  return owner, new_dialog_state, res, owner
722
772
 
723
- print(f"Tipe node: {type(node)}")
773
+ logging.info(f"Tipe node: {type(node)}")
724
774
 
725
- print("$$$> new_owner:", owner, "new_dialog_state:", new_dialog_state)
775
+ logging.info(f"$$$> new_owner: {owner} new_dialog_state: {new_dialog_state}")
726
776
  return owner, new_dialog_state, res, owner
777
+
778
+ def set_knowledge(self, knowledge) -> str:
779
+ """ Set knowledge method
780
+ :param query: query
781
+ :return: str
782
+ """
783
+ self.knowledge = knowledge
@@ -33,6 +33,7 @@ clear and unified results.
33
33
  # Define resources
34
34
  # --------------------------------------------------------
35
35
 
36
+ import logging
36
37
  from threading import Timer
37
38
  from abc import abstractmethod
38
39
  from ..kernel.agent import Agent
@@ -94,7 +95,7 @@ class DelegateAction(Action):
94
95
  self.agent.reset()
95
96
  self.delegate(data['dto'])
96
97
 
97
- def activeTimeout(self, time:int) -> None:
98
+ def active_timeout(self, time:int) -> None:
98
99
  """ Active timeout
99
100
  @param time: Time
100
101
  """
@@ -109,6 +110,27 @@ class DelegateAction(Action):
109
110
  self.adm.send_event(ag, 'task', data)
110
111
  else:
111
112
  raise CollaborativeException('[Warn, toAssign]: The number of data packets exceeds the number of agents')
113
+
114
+ def get_list_agents(self) -> list:
115
+ """ Get list of agents
116
+ @return: List of agents
117
+ """
118
+ return self.agent.get_free_list()
119
+
120
+ def to_individual_assign(self, ag_id, data:any) -> bool:
121
+ """ Assign data to an agent
122
+ @param data: Data
123
+ """
124
+ if len(self.agent.get_free_list()) > 0:
125
+ index = self.agent.get_free_list().index(ag_id)
126
+ if index >= 0:
127
+ self.agent.get_free_list().pop(index)
128
+ self.adm.send_event(ag_id, 'task', data)
129
+ else:
130
+ return False
131
+ else:
132
+ raise CollaborativeException('[Warn, toAssign]: The number of data packets exceeds the number of agents')
133
+ return True
112
134
 
113
135
  @abstractmethod
114
136
  def delegate(self, data:any) -> None:
@@ -129,17 +151,24 @@ class ResponseAction(Action):
129
151
  @param data: Event data
130
152
  """
131
153
  if 'timeout' == data:
154
+ logging.info('Stopping timeout')
132
155
  results = {}
133
156
  for key, res in self.agent.get_check_dict().items():
134
157
  results[key] = res
135
158
  self.end_of_process(results, True)
136
159
  else:
160
+ logging.info("Response received")
161
+ logging.info(data)
137
162
  result = 'None'
138
163
  agentID = data['source']
139
- if data['result']:
164
+ if 'result' in data and data['result']:
140
165
  result = data['result']
141
- self.agent.get_check_dict()[agentID] = result
166
+ self.agent.get_check_dict()[agentID] = result
167
+ else:
168
+ logging.warning(f"No result received for agent {agentID}")
169
+ self.agent.get_check_dict()[agentID] = "None"
142
170
  if self.check():
171
+ logging.info("All agents have responded")
143
172
  results = {}
144
173
  for key, res in self.agent.get_check_dict().items():
145
174
  results[key] = res
@@ -33,8 +33,8 @@ operate in an agile and effective manner.
33
33
  # Define resources
34
34
  # --------------------------------------------------------
35
35
 
36
+ import logging
36
37
  from abc import abstractmethod
37
-
38
38
  from .worker import Task, Worker
39
39
  from ..kernel.agent import Queue
40
40
  from ..kernel.agent import Agent
@@ -56,54 +56,28 @@ class DispatcherException(Exception):
56
56
  class Delegate(Action):
57
57
  """ An action is a response to the occurrence of an event """
58
58
 
59
- def execute(self, data: any) -> None:
60
- """
61
- Response.
62
- @param data Event data
59
+ def active_timeout(self, ag, time: int) -> None:
60
+ """ Active timeout
61
+ @param time: Time
63
62
  """
64
- ag = self.agent.get_free_queue().get()
65
- self.agent.get_request_dict()[ag] = {
66
- 'gateway': data['gateway'],
67
- 'dtoList': []
68
- }
69
- self.adm.send_event(ag, 'task', data['dto'])
70
-
71
- # --------------------------------------------------------
72
- # Define DelegateAction
73
- # --------------------------------------------------------
74
-
75
- class DelegateAction(Action):
76
- """ An action is a response to the occurrence of an event """
63
+ logging.info(f"[Delegate] Send event timeout {time}")
64
+ self.adm.send_event(ag, 'timeout', {'time': time, 'command': 'start'})
77
65
 
78
66
  def execute(self, data: any) -> None:
79
67
  """
80
68
  Response.
81
69
  @param data Event data
82
70
  """
83
- self.delegate(data)
84
-
85
- def active_timeout(self, time: int) -> None:
86
- """ Active timeout
87
- @param time: Time
88
- """
89
- self.adm.send_event(self.agent.id, 'timeout', {'time': time, 'dto': None})
90
-
91
- def to_assign(self, data: any) -> None:
92
- """ Assign
93
- @param data: Data
94
- """
95
71
  ag = self.agent.get_free_queue().get()
96
72
  self.agent.get_request_dict()[ag] = {
73
+ 'gateway': data['gateway'],
97
74
  'dtoList': []
98
75
  }
99
- self.adm.send_event(ag, 'task', data)
100
-
101
- @abstractmethod
102
- def delegate(self, data: any) -> None:
103
- """ Delegate
104
- @param data: Data
105
- """
106
- pass
76
+ self.adm.send_event(ag, 'task', data['dto'])
77
+ if 'timeout' in self.agent.state:
78
+ self.active_timeout(ag, self.agent.state['timeout'])
79
+ else:
80
+ raise DispatcherException('[Delegate]: Timeout not defined in the state as "timeout" key')
107
81
 
108
82
  # --------------------------------------------------------
109
83
  # Define Action
@@ -141,11 +115,13 @@ class ResponseAction(Action):
141
115
  """
142
116
  request = self.agent.get_request_dict()[data['source']]
143
117
  if 'timeout' in data:
144
- self.send_response(request)
118
+ logging.info(f"[ResponseAction][{self.agent.id}]: Timeout ******************")
119
+ request['gateway'].put("TIMEOUT")
145
120
  else:
146
121
  request['dtoList'].append(data['result'])
147
122
  if len(request['dtoList']) >= self.agent.get_buffer_size():
148
123
  self.send_response(request)
124
+ self.adm.send_event(data['source'], 'timeout', {'command': 'stop'})
149
125
 
150
126
  # --------------------------------------------------------
151
127
  # Define component
@@ -34,16 +34,14 @@ operate in an agile and effective manner.
34
34
  # Define resources
35
35
  # --------------------------------------------------------
36
36
 
37
+ import logging
37
38
  from abc import abstractmethod
38
-
39
- from pbesa.cognitive import AugmentedGeneration, Dialog
40
- from pbesa.mas import Directory
41
-
42
39
  from .worker import Task, Worker
43
40
  from ..kernel.agent import Queue
44
41
  from ..kernel.agent import Agent
45
42
  from ..kernel.agent import Action
46
43
  from ..kernel.util import generate_short_uuid
44
+ from pbesa.cognitive import AugmentedGeneration, Dialog
47
45
 
48
46
  # ----------------------------------------------------------
49
47
  # Defines system component exceptions
@@ -82,19 +80,22 @@ class DelegateAction(Action):
82
80
  """ Assign
83
81
  @param data: Data
84
82
  """
85
- print('Assign to agent')
83
+ logging.info('Assign to agent...')
86
84
  ag = self.agent.get_free_queue().get()
87
85
  agent_obj = self.adm.get_agent(ag)
88
- agent_count = len(self.agent.get_agent_list())
86
+ agent_count = len(self.agent.get_agent_list())
87
+ logging.info('List of agents: ' + str(self.agent.get_agent_list()))
89
88
  if operation:
90
- print(f'With operation {operation}')
89
+ logging.info(f'With operation {operation}')
91
90
  exit = False
92
91
  while not exit:
93
92
  # Chec if the agent is instance of AugmentedGeneration
94
93
  if isinstance(agent_obj, AugmentedGeneration) or isinstance(agent_obj, Dialog):
95
94
  # Get the role
96
95
  role = agent_obj.get_role()
96
+ logging.info(f"Comparing {role.tool} with {operation}")
97
97
  if role.tool == operation:
98
+ logging.info('The agent is operational')
98
99
  self.agent.get_request_dict()[ag] = {
99
100
  'gateway': data['gateway'],
100
101
  'dtoList': []
@@ -103,25 +104,27 @@ class DelegateAction(Action):
103
104
  self.__rewier[ag] = 0
104
105
  exit = True
105
106
  else:
106
- print('The agent is not available')
107
+ logging.info('The agent is not available')
107
108
  self.adm.send_event(agent_obj.get_controller(), 'notify', ag)
108
109
  if ag in self.__rewier:
109
110
  self.__rewier[ag] = self.__rewier[ag] + 1
110
111
  else:
111
112
  self.__rewier[ag] = 0
112
113
  if self.__rewier[ag] >= agent_count * 3:
114
+ data['gateway'].put('ERROR')
113
115
  raise SelectedDispatcherException('[Error, toAssign]: The agent is not available')
114
116
  else:
115
- print('The agent is operational')
117
+ logging.info('The agent is operational')
116
118
  self.adm.send_event(agent_obj.get_controller(), 'notify', ag)
117
119
  if ag in self.__rewier:
118
120
  self.__rewier[ag] = self.__rewier[ag] + 1
119
121
  else:
120
122
  self.__rewier[ag] = 0
121
123
  if self.__rewier[ag] >= agent_count * 3:
124
+ data['gateway'].put('ERROR')
122
125
  raise SelectedDispatcherException('[Error, toAssign]: The agent is not available')
123
126
  else:
124
- print('Without operation')
127
+ logging.info('Without operation')
125
128
  self.agent.get_request_dict()[ag] = {
126
129
  'gateway': data['gateway'],
127
130
  'dtoList': []
@@ -13,6 +13,7 @@
13
13
  # Define resources
14
14
  # --------------------------------------------------------
15
15
 
16
+ import logging
16
17
  from threading import Timer
17
18
  from abc import abstractmethod
18
19
  from ..kernel.agent import Agent
@@ -35,24 +36,39 @@ class WorkerException(Exception):
35
36
  # ----------------------------------------------------------
36
37
 
37
38
  class TimeoutAction(Action):
38
- """
39
- @See Action
40
- """
39
+ """ Represents the action that manages the timeout """
40
+
41
+ def __init__(self) -> None:
42
+ """ Constructor """
43
+ self.__timer = None
44
+ super().__init__()
41
45
 
42
46
  def handler(self) -> None:
43
47
  """ Timeout handler """
44
48
  if self.agent.is_timeout():
45
49
  self.agent.set_timeout(False)
46
- self.adm.send_event(self.agent.id, 'response', 'timeout')
50
+ response = {
51
+ 'timeout': True,
52
+ 'source': self.agent.id
53
+ }
54
+ self.adm.send_event(self.agent.get_controller(), 'response', response)
47
55
 
48
56
  def execute(self, data:any) -> None:
49
- """ Execute
50
- @param data: Data
57
+ """ Execute the action
58
+ @param data: Event data
51
59
  """
52
- if not self.agent.is_timeout():
53
- self.agent.set_timeout(True)
54
- r = Timer(data['time'], self.handler)
55
- r.start()
60
+ logging.info(f"[TimeoutAction][{self.agent.id}]: Execute {data}")
61
+ if data['command'] == 'start':
62
+ if not self.agent.is_timeout():
63
+ self.agent.set_timeout(True)
64
+ self.__timer = Timer(data['time'], self.handler)
65
+ self.__timer.start()
66
+ logging.info(f"[TimeoutAction][{self.agent.id}]: Timer started")
67
+ else:
68
+ if self.__timer:
69
+ self.__timer.cancel()
70
+ self.__timer = None
71
+ logging.info(f"[TimeoutAction][{self.agent.id}]: Timer stopped")
56
72
 
57
73
  # --------------------------------------------------------
58
74
  # Define Task Action
@@ -126,6 +142,7 @@ class Worker(Agent):
126
142
  @param agent_id: Agent ID
127
143
  """
128
144
  self.__task_list = []
145
+ self.__timeout = False
129
146
  self.__controller = None
130
147
  self.__controller_type = None
131
148
  super().__init__(agent_id)
@@ -158,6 +175,18 @@ class Worker(Agent):
158
175
  action.set_is_pool(False)
159
176
  action.set_enable_response(True)
160
177
 
178
+ def is_timeout(self) -> bool:
179
+ """ Check if the controller has a timeout
180
+ @return: True if the controller has a timeout, False otherwise
181
+ """
182
+ return self.__timeout
183
+
184
+ def set_timeout(self, timeout:bool) -> None:
185
+ """ Set timeout
186
+ @param timeout: Timeout
187
+ """
188
+ self.__timeout = timeout
189
+
161
190
  @abstractmethod
162
191
  def build(self) -> None:
163
192
  """ Build """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: pbesa
3
- Version: 4.0.2
3
+ Version: 4.0.4
4
4
  License-File: LICENSE
5
5
  License-File: LICENSE.txt
6
6
  Requires-Dist: pymongo==4.6.3
@@ -4,7 +4,7 @@ from setuptools import setup, find_packages
4
4
 
5
5
  setup(
6
6
  name='pbesa',
7
- version='4.0.002',
7
+ version='4.0.4',
8
8
  packages=find_packages(),
9
9
  install_requires=[
10
10
  'pymongo==4.6.3',
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes