選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

canvas.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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"]:continue
  130. dsl[k] = deepcopy(self.dsl[k])
  131. for k, cpn in self.components.items():
  132. if k not in dsl["components"]:
  133. dsl["components"][k] = {}
  134. for c in cpn.keys():
  135. if c == "obj":
  136. dsl["components"][k][c] = json.loads(str(cpn["obj"]))
  137. continue
  138. dsl["components"][k][c] = deepcopy(cpn[c])
  139. return json.dumps(dsl, ensure_ascii=False)
  140. def reset(self):
  141. self.path = []
  142. self.history = []
  143. self.messages = []
  144. self.answer = []
  145. self.reference = []
  146. for k, cpn in self.components.items():
  147. self.components[k]["obj"].reset()
  148. self._embed_id = ""
  149. def get_compnent_name(self, cid):
  150. for n in self.dsl["graph"]["nodes"]:
  151. if cid == n["id"]: return n["data"]["name"]
  152. return ""
  153. def run(self, **kwargs):
  154. if self.answer:
  155. cpn_id = self.answer[0]
  156. self.answer.pop(0)
  157. try:
  158. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  159. except Exception as e:
  160. ans = ComponentBase.be_output(str(e))
  161. self.path[-1].append(cpn_id)
  162. if kwargs.get("stream"):
  163. for an in ans():
  164. yield an
  165. else: yield ans
  166. return
  167. if not self.path:
  168. self.components["begin"]["obj"].run(self.history, **kwargs)
  169. self.path.append(["begin"])
  170. self.path.append([])
  171. ran = -1
  172. waiting = []
  173. without_dependent_checking = []
  174. def prepare2run(cpns):
  175. nonlocal ran, ans
  176. for c in cpns:
  177. if self.path[-1] and c == self.path[-1][-1]: continue
  178. cpn = self.components[c]["obj"]
  179. if cpn.component_name == "Answer":
  180. self.answer.append(c)
  181. else:
  182. logging.debug(f"Canvas.prepare2run: {c}")
  183. if c not in without_dependent_checking:
  184. cpids = cpn.get_dependent_components()
  185. if any([cc not in self.path[-1] for cc in cpids]):
  186. if c not in waiting: waiting.append(c)
  187. continue
  188. yield "*'{}'* is running...🕞".format(self.get_compnent_name(c))
  189. ans = cpn.run(self.history, **kwargs)
  190. self.path[-1].append(c)
  191. ran += 1
  192. for m in prepare2run(self.components[self.path[-2][-1]]["downstream"]):
  193. yield {"content": m, "running_status": True}
  194. while 0 <= ran < len(self.path[-1]):
  195. logging.debug(f"Canvas.run: {ran} {self.path}")
  196. cpn_id = self.path[-1][ran]
  197. cpn = self.get_component(cpn_id)
  198. if not cpn["downstream"]: break
  199. loop = self._find_loop()
  200. if loop: raise OverflowError(f"Too much loops: {loop}")
  201. if cpn["obj"].component_name.lower() in ["switch", "categorize", "relevant"]:
  202. switch_out = cpn["obj"].output()[1].iloc[0, 0]
  203. assert switch_out in self.components, \
  204. "{}'s output: {} not valid.".format(cpn_id, switch_out)
  205. try:
  206. for m in prepare2run([switch_out]):
  207. yield {"content": m, "running_status": True}
  208. except Exception as e:
  209. yield {"content": "*Exception*: {}".format(e), "running_status": True}
  210. logging.exception("Canvas.run got exception")
  211. continue
  212. try:
  213. for m in prepare2run(cpn["downstream"]):
  214. yield {"content": m, "running_status": True}
  215. except Exception as e:
  216. yield {"content": "*Exception*: {}".format(e), "running_status": True}
  217. logging.exception("Canvas.run got exception")
  218. if ran >= len(self.path[-1]) and waiting:
  219. without_dependent_checking = waiting
  220. waiting = []
  221. for m in prepare2run(without_dependent_checking):
  222. yield {"content": m, "running_status": True}
  223. ran -= 1
  224. if self.answer:
  225. cpn_id = self.answer[0]
  226. self.answer.pop(0)
  227. ans = self.components[cpn_id]["obj"].run(self.history, **kwargs)
  228. self.path[-1].append(cpn_id)
  229. if kwargs.get("stream"):
  230. assert isinstance(ans, partial)
  231. for an in ans():
  232. yield an
  233. else:
  234. yield ans
  235. else:
  236. raise Exception("The dialog flow has no way to interact with you. Please add an 'Interact' component to the end of the flow.")
  237. def get_component(self, cpn_id):
  238. return self.components[cpn_id]
  239. def get_tenant_id(self):
  240. return self._tenant_id
  241. def get_history(self, window_size):
  242. convs = []
  243. for role, obj in self.history[window_size * -1:]:
  244. if isinstance(obj, list) and obj and all([isinstance(o, dict) for o in obj]):
  245. convs.append({"role": role, "content": '\n'.join([str(s.get("content", "")) for s in obj])})
  246. else:
  247. convs.append({"role": role, "content": str(obj)})
  248. return convs
  249. def add_user_input(self, question):
  250. self.history.append(("user", question))
  251. def set_embedding_model(self, embed_id):
  252. self._embed_id = embed_id
  253. def get_embedding_model(self):
  254. return self._embed_id
  255. def _find_loop(self, max_loops=6):
  256. path = self.path[-1][::-1]
  257. if len(path) < 2: return False
  258. for i in range(len(path)):
  259. if path[i].lower().find("answer") >= 0:
  260. path = path[:i]
  261. break
  262. if len(path) < 2: return False
  263. for l in range(2, len(path) // 2):
  264. pat = ",".join(path[0:l])
  265. path_str = ",".join(path)
  266. if len(pat) >= len(path_str): return False
  267. loop = max_loops
  268. while path_str.find(pat) == 0 and loop >= 0:
  269. loop -= 1
  270. if len(pat)+1 >= len(path_str):
  271. return False
  272. path_str = path_str[len(pat)+1:]
  273. if loop < 0:
  274. pat = " => ".join([p.split(":")[0] for p in path[0:l]])
  275. return pat + " => " + pat
  276. return False
  277. def get_prologue(self):
  278. return self.components["begin"]["obj"]._param.prologue