Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

canvas.py 13KB

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