Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 copy import deepcopy
  19. from functools import partial
  20. import pandas as pd
  21. from agent.component import component_class
  22. from agent.component.base import ComponentBase
  23. class Canvas:
  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. "parent_id": ""
  85. }
  86. },
  87. "history": [],
  88. "messages": [],
  89. "reference": [],
  90. "path": [],
  91. "answer": []
  92. }
  93. self._tenant_id = tenant_id
  94. self._embed_id = ""
  95. self.load()
  96. def load(self):
  97. self.components = self.dsl["components"]
  98. cpn_nms = set([])
  99. for k, cpn in self.components.items():
  100. cpn_nms.add(cpn["obj"]["component_name"])
  101. assert "Begin" in cpn_nms, "There have to be an 'Begin' component."
  102. assert "Answer" in cpn_nms, "There have to be an 'Answer' component."
  103. for k, cpn in self.components.items():
  104. cpn_nms.add(cpn["obj"]["component_name"])
  105. param = component_class(cpn["obj"]["component_name"] + "Param")()
  106. param.update(cpn["obj"]["params"])
  107. param.check()
  108. cpn["obj"] = component_class(cpn["obj"]["component_name"])(self, k, param)
  109. if cpn["obj"].component_name == "Categorize":
  110. for _, desc in param.category_description.items():
  111. if desc["to"] not in cpn["downstream"]:
  112. cpn["downstream"].append(desc["to"])
  113. self.path = self.dsl["path"]
  114. self.history = self.dsl["history"]
  115. self.messages = self.dsl["messages"]
  116. self.answer = self.dsl["answer"]
  117. self.reference = self.dsl["reference"]
  118. self._embed_id = self.dsl.get("embed_id", "")
  119. def __str__(self):
  120. self.dsl["path"] = self.path
  121. self.dsl["history"] = self.history
  122. self.dsl["messages"] = self.messages
  123. self.dsl["answer"] = self.answer
  124. self.dsl["reference"] = self.reference
  125. self.dsl["embed_id"] = self._embed_id
  126. dsl = {
  127. "components": {}
  128. }
  129. for k in self.dsl.keys():
  130. if k in ["components"]:
  131. continue
  132. dsl[k] = deepcopy(self.dsl[k])
  133. for k, cpn in self.components.items():
  134. if k not in dsl["components"]:
  135. dsl["components"][k] = {}
  136. for c in cpn.keys():
  137. if c == "obj":
  138. dsl["components"][k][c] = json.loads(str(cpn["obj"]))
  139. continue
  140. dsl["components"][k][c] = deepcopy(cpn[c])
  141. return json.dumps(dsl, ensure_ascii=False)
  142. def reset(self):
  143. self.path = []
  144. self.history = []
  145. self.messages = []
  146. self.answer = []
  147. self.reference = []
  148. for k, cpn in self.components.items():
  149. self.components[k]["obj"].reset()
  150. self._embed_id = ""
  151. def get_component_name(self, cid):
  152. for n in self.dsl["graph"]["nodes"]:
  153. if cid == n["id"]:
  154. return n["data"]["name"]
  155. return ""
  156. def run(self, **kwargs):
  157. if self.answer:
  158. cpn_id = self.answer[0]
  159. self.answer.pop(0)
  160. try:
  161. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  162. except Exception as e:
  163. ans = ComponentBase.be_output(str(e))
  164. self.path[-1].append(cpn_id)
  165. if kwargs.get("stream"):
  166. for an in ans():
  167. yield an
  168. else:
  169. yield ans
  170. return
  171. if not self.path:
  172. self.components["begin"]["obj"].run(self.history, **kwargs)
  173. self.path.append(["begin"])
  174. self.path.append([])
  175. ran = -1
  176. waiting = []
  177. without_dependent_checking = []
  178. def prepare2run(cpns):
  179. nonlocal ran, ans
  180. for c in cpns:
  181. if self.path[-1] and c == self.path[-1][-1]:
  182. continue
  183. cpn = self.components[c]["obj"]
  184. if cpn.component_name == "Answer":
  185. self.answer.append(c)
  186. else:
  187. logging.debug(f"Canvas.prepare2run: {c}")
  188. if c not in without_dependent_checking:
  189. cpids = cpn.get_dependent_components()
  190. if any([cc not in self.path[-1] for cc in cpids]):
  191. if c not in waiting:
  192. waiting.append(c)
  193. continue
  194. yield "*'{}'* is running...🕞".format(self.get_component_name(c))
  195. if cpn.component_name.lower() == "iteration":
  196. st_cpn = cpn.get_start()
  197. assert st_cpn, "Start component not found for Iteration."
  198. if not st_cpn["obj"].end():
  199. cpn = st_cpn["obj"]
  200. c = cpn._id
  201. try:
  202. ans = cpn.run(self.history, **kwargs)
  203. except Exception as e:
  204. logging.exception(f"Canvas.run got exception: {e}")
  205. self.path[-1].append(c)
  206. ran += 1
  207. raise e
  208. self.path[-1].append(c)
  209. ran += 1
  210. downstream = self.components[self.path[-2][-1]]["downstream"]
  211. if not downstream and self.components[self.path[-2][-1]].get("parent_id"):
  212. cid = self.path[-2][-1]
  213. pid = self.components[cid]["parent_id"]
  214. o, _ = self.components[cid]["obj"].output(allow_partial=False)
  215. oo, _ = self.components[pid]["obj"].output(allow_partial=False)
  216. self.components[pid]["obj"].set(pd.concat([oo, o], ignore_index=True))
  217. downstream = [pid]
  218. for m in prepare2run(downstream):
  219. yield {"content": m, "running_status": True}
  220. while 0 <= ran < len(self.path[-1]):
  221. logging.debug(f"Canvas.run: {ran} {self.path}")
  222. cpn_id = self.path[-1][ran]
  223. cpn = self.get_component(cpn_id)
  224. if not any([cpn["downstream"], cpn.get("parent_id"), waiting]):
  225. break
  226. loop = self._find_loop()
  227. if loop:
  228. raise OverflowError(f"Too much loops: {loop}")
  229. if cpn["obj"].component_name.lower() in ["switch", "categorize", "relevant"]:
  230. switch_out = cpn["obj"].output()[1].iloc[0, 0]
  231. assert switch_out in self.components, \
  232. "{}'s output: {} not valid.".format(cpn_id, switch_out)
  233. for m in prepare2run([switch_out]):
  234. yield {"content": m, "running_status": True}
  235. continue
  236. downstream = cpn["downstream"]
  237. if not downstream and cpn.get("parent_id"):
  238. pid = cpn["parent_id"]
  239. _, o = cpn["obj"].output(allow_partial=False)
  240. _, oo = self.components[pid]["obj"].output(allow_partial=False)
  241. self.components[pid]["obj"].set_output(pd.concat([oo.dropna(axis=1), o.dropna(axis=1)], ignore_index=True))
  242. downstream = [pid]
  243. for m in prepare2run(downstream):
  244. yield {"content": m, "running_status": True}
  245. if ran >= len(self.path[-1]) and waiting:
  246. without_dependent_checking = waiting
  247. waiting = []
  248. for m in prepare2run(without_dependent_checking):
  249. yield {"content": m, "running_status": True}
  250. without_dependent_checking = []
  251. ran -= 1
  252. if self.answer:
  253. cpn_id = self.answer[0]
  254. self.answer.pop(0)
  255. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  256. self.path[-1].append(cpn_id)
  257. if kwargs.get("stream"):
  258. assert isinstance(ans, partial)
  259. for an in ans():
  260. yield an
  261. else:
  262. yield ans
  263. else:
  264. raise Exception("The dialog flow has no way to interact with you. Please add an 'Interact' component to the end of the flow.")
  265. def get_component(self, cpn_id):
  266. return self.components[cpn_id]
  267. def get_tenant_id(self):
  268. return self._tenant_id
  269. def get_history(self, window_size):
  270. convs = []
  271. for role, obj in self.history[window_size * -1:]:
  272. if isinstance(obj, list) and obj and all([isinstance(o, dict) for o in obj]):
  273. convs.append({"role": role, "content": '\n'.join([str(s.get("content", "")) for s in obj])})
  274. else:
  275. convs.append({"role": role, "content": str(obj)})
  276. return convs
  277. def add_user_input(self, question):
  278. self.history.append(("user", question))
  279. def set_embedding_model(self, embed_id):
  280. self._embed_id = embed_id
  281. def get_embedding_model(self):
  282. return self._embed_id
  283. def _find_loop(self, max_loops=6):
  284. path = self.path[-1][::-1]
  285. if len(path) < 2:
  286. return False
  287. for i in range(len(path)):
  288. if path[i].lower().find("answer") == 0 or path[i].lower().find("iterationitem") == 0:
  289. path = path[:i]
  290. break
  291. if len(path) < 2:
  292. return False
  293. for loc in range(2, len(path) // 2):
  294. pat = ",".join(path[0:loc])
  295. path_str = ",".join(path)
  296. if len(pat) >= len(path_str):
  297. return False
  298. loop = max_loops
  299. while path_str.find(pat) == 0 and loop >= 0:
  300. loop -= 1
  301. if len(pat)+1 >= len(path_str):
  302. return False
  303. path_str = path_str[len(pat)+1:]
  304. if loop < 0:
  305. pat = " => ".join([p.split(":")[0] for p in path[0:loc]])
  306. return pat + " => " + pat
  307. return False
  308. def get_prologue(self):
  309. return self.components["begin"]["obj"]._param.prologue
  310. def set_global_param(self, **kwargs):
  311. for k, v in kwargs.items():
  312. for q in self.components["begin"]["obj"]._param.query:
  313. if k != q["key"]:
  314. continue
  315. q["value"] = v
  316. def get_preset_param(self):
  317. return self.components["begin"]["obj"]._param.query
  318. def get_component_input_elements(self, cpnnm):
  319. return self.components[cpnnm]["obj"].get_input_elements()