You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

canvas.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import json
  18. from abc import ABC
  19. from copy import deepcopy
  20. from functools import partial
  21. from agent.component import component_class
  22. from agent.component.base import ComponentBase
  23. class Canvas(ABC):
  24. """
  25. dsl = {
  26. "components": {
  27. "begin": {
  28. "obj":{
  29. "component_name": "Begin",
  30. "params": {},
  31. },
  32. "downstream": ["answer_0"],
  33. "upstream": [],
  34. },
  35. "answer_0": {
  36. "obj": {
  37. "component_name": "Answer",
  38. "params": {}
  39. },
  40. "downstream": ["retrieval_0"],
  41. "upstream": ["begin", "generate_0"],
  42. },
  43. "retrieval_0": {
  44. "obj": {
  45. "component_name": "Retrieval",
  46. "params": {}
  47. },
  48. "downstream": ["generate_0"],
  49. "upstream": ["answer_0"],
  50. },
  51. "generate_0": {
  52. "obj": {
  53. "component_name": "Generate",
  54. "params": {}
  55. },
  56. "downstream": ["answer_0"],
  57. "upstream": ["retrieval_0"],
  58. }
  59. },
  60. "history": [],
  61. "messages": [],
  62. "reference": [],
  63. "path": [["begin"]],
  64. "answer": []
  65. }
  66. """
  67. def __init__(self, dsl: str, tenant_id=None):
  68. self.path = []
  69. self.history = []
  70. self.messages = []
  71. self.answer = []
  72. self.components = {}
  73. self.dsl = json.loads(dsl) if dsl else {
  74. "components": {
  75. "begin": {
  76. "obj": {
  77. "component_name": "Begin",
  78. "params": {
  79. "prologue": "Hi there!"
  80. }
  81. },
  82. "downstream": [],
  83. "upstream": []
  84. }
  85. },
  86. "history": [],
  87. "messages": [],
  88. "reference": [],
  89. "path": [],
  90. "answer": []
  91. }
  92. self._tenant_id = tenant_id
  93. self._embed_id = ""
  94. self.load()
  95. def load(self):
  96. self.components = self.dsl["components"]
  97. cpn_nms = set([])
  98. for k, cpn in self.components.items():
  99. cpn_nms.add(cpn["obj"]["component_name"])
  100. assert "Begin" in cpn_nms, "There have to be an 'Begin' component."
  101. assert "Answer" in cpn_nms, "There have to be an 'Answer' component."
  102. for k, cpn in self.components.items():
  103. cpn_nms.add(cpn["obj"]["component_name"])
  104. param = component_class(cpn["obj"]["component_name"] + "Param")()
  105. param.update(cpn["obj"]["params"])
  106. param.check()
  107. cpn["obj"] = component_class(cpn["obj"]["component_name"])(self, k, param)
  108. if cpn["obj"].component_name == "Categorize":
  109. for _, desc in param.category_description.items():
  110. if desc["to"] not in cpn["downstream"]:
  111. cpn["downstream"].append(desc["to"])
  112. self.path = self.dsl["path"]
  113. self.history = self.dsl["history"]
  114. self.messages = self.dsl["messages"]
  115. self.answer = self.dsl["answer"]
  116. self.reference = self.dsl["reference"]
  117. self._embed_id = self.dsl.get("embed_id", "")
  118. def __str__(self):
  119. self.dsl["path"] = self.path
  120. self.dsl["history"] = self.history
  121. self.dsl["messages"] = self.messages
  122. self.dsl["answer"] = self.answer
  123. self.dsl["reference"] = self.reference
  124. self.dsl["embed_id"] = self._embed_id
  125. dsl = {
  126. "components": {}
  127. }
  128. for k in self.dsl.keys():
  129. if k in ["components"]:
  130. continue
  131. dsl[k] = deepcopy(self.dsl[k])
  132. for k, cpn in self.components.items():
  133. if k not in dsl["components"]:
  134. dsl["components"][k] = {}
  135. for c in cpn.keys():
  136. if c == "obj":
  137. dsl["components"][k][c] = json.loads(str(cpn["obj"]))
  138. continue
  139. dsl["components"][k][c] = deepcopy(cpn[c])
  140. return json.dumps(dsl, ensure_ascii=False)
  141. def reset(self):
  142. self.path = []
  143. self.history = []
  144. self.messages = []
  145. self.answer = []
  146. self.reference = []
  147. for k, cpn in self.components.items():
  148. self.components[k]["obj"].reset()
  149. self._embed_id = ""
  150. def get_compnent_name(self, cid):
  151. for n in self.dsl["graph"]["nodes"]:
  152. if cid == n["id"]:
  153. return n["data"]["name"]
  154. return ""
  155. def run(self, **kwargs):
  156. if self.answer:
  157. cpn_id = self.answer[0]
  158. self.answer.pop(0)
  159. try:
  160. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  161. except Exception as e:
  162. ans = ComponentBase.be_output(str(e))
  163. self.path[-1].append(cpn_id)
  164. if kwargs.get("stream"):
  165. for an in ans():
  166. yield an
  167. else:
  168. yield ans
  169. return
  170. if not self.path:
  171. self.components["begin"]["obj"].run(self.history, **kwargs)
  172. self.path.append(["begin"])
  173. self.path.append([])
  174. ran = -1
  175. waiting = []
  176. without_dependent_checking = []
  177. def prepare2run(cpns):
  178. nonlocal ran, ans
  179. for c in cpns:
  180. if self.path[-1] and c == self.path[-1][-1]:
  181. continue
  182. cpn = self.components[c]["obj"]
  183. if cpn.component_name == "Answer":
  184. self.answer.append(c)
  185. else:
  186. logging.debug(f"Canvas.prepare2run: {c}")
  187. if c not in without_dependent_checking:
  188. cpids = cpn.get_dependent_components()
  189. if any([cc not in self.path[-1] for cc in cpids]):
  190. if c not in waiting:
  191. waiting.append(c)
  192. continue
  193. yield "*'{}'* is running...🕞".format(self.get_compnent_name(c))
  194. try:
  195. ans = cpn.run(self.history, **kwargs)
  196. except Exception as e:
  197. logging.exception(f"Canvas.run got exception: {e}")
  198. self.path[-1].append(c)
  199. ran += 1
  200. raise e
  201. self.path[-1].append(c)
  202. ran += 1
  203. for m in prepare2run(self.components[self.path[-2][-1]]["downstream"]):
  204. yield {"content": m, "running_status": True}
  205. while 0 <= ran < len(self.path[-1]):
  206. logging.debug(f"Canvas.run: {ran} {self.path}")
  207. cpn_id = self.path[-1][ran]
  208. cpn = self.get_component(cpn_id)
  209. if not cpn["downstream"]:
  210. break
  211. loop = self._find_loop()
  212. if loop:
  213. raise OverflowError(f"Too much loops: {loop}")
  214. if cpn["obj"].component_name.lower() in ["switch", "categorize", "relevant"]:
  215. switch_out = cpn["obj"].output()[1].iloc[0, 0]
  216. assert switch_out in self.components, \
  217. "{}'s output: {} not valid.".format(cpn_id, switch_out)
  218. for m in prepare2run([switch_out]):
  219. yield {"content": m, "running_status": True}
  220. continue
  221. for m in prepare2run(cpn["downstream"]):
  222. yield {"content": m, "running_status": True}
  223. if ran >= len(self.path[-1]) and waiting:
  224. without_dependent_checking = waiting
  225. waiting = []
  226. for m in prepare2run(without_dependent_checking):
  227. yield {"content": m, "running_status": True}
  228. ran -= 1
  229. if self.answer:
  230. cpn_id = self.answer[0]
  231. self.answer.pop(0)
  232. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  233. self.path[-1].append(cpn_id)
  234. if kwargs.get("stream"):
  235. assert isinstance(ans, partial)
  236. for an in ans():
  237. yield an
  238. else:
  239. yield ans
  240. else:
  241. raise Exception("The dialog flow has no way to interact with you. Please add an 'Interact' component to the end of the flow.")
  242. def get_component(self, cpn_id):
  243. return self.components[cpn_id]
  244. def get_tenant_id(self):
  245. return self._tenant_id
  246. def get_history(self, window_size):
  247. convs = []
  248. for role, obj in self.history[window_size * -1:]:
  249. if isinstance(obj, list) and obj and all([isinstance(o, dict) for o in obj]):
  250. convs.append({"role": role, "content": '\n'.join([str(s.get("content", "")) for s in obj])})
  251. else:
  252. convs.append({"role": role, "content": str(obj)})
  253. return convs
  254. def add_user_input(self, question):
  255. self.history.append(("user", question))
  256. def set_embedding_model(self, embed_id):
  257. self._embed_id = embed_id
  258. def get_embedding_model(self):
  259. return self._embed_id
  260. def _find_loop(self, max_loops=6):
  261. path = self.path[-1][::-1]
  262. if len(path) < 2:
  263. return False
  264. for i in range(len(path)):
  265. if path[i].lower().find("answer") >= 0:
  266. path = path[:i]
  267. break
  268. if len(path) < 2:
  269. return False
  270. for loc in range(2, len(path) // 2):
  271. pat = ",".join(path[0:loc])
  272. path_str = ",".join(path)
  273. if len(pat) >= len(path_str):
  274. return False
  275. loop = max_loops
  276. while path_str.find(pat) == 0 and loop >= 0:
  277. loop -= 1
  278. if len(pat)+1 >= len(path_str):
  279. return False
  280. path_str = path_str[len(pat)+1:]
  281. if loop < 0:
  282. pat = " => ".join([p.split(":")[0] for p in path[0:loc]])
  283. return pat + " => " + pat
  284. return False
  285. def get_prologue(self):
  286. return self.components["begin"]["obj"]._param.prologue
  287. def set_global_param(self, **kwargs):
  288. for k, v in kwargs.items():
  289. for q in self.components["begin"]["obj"]._param.query:
  290. if k != q["key"]:
  291. continue
  292. q["value"] = v
  293. def get_preset_param(self):
  294. return self.components["begin"]["obj"]._param.query
  295. def get_component_input_elements(self, cpnnm):
  296. return self.components[cpnnm]["obj"].get_input_elements()