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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 json
  17. import re
  18. from functools import partial
  19. import pandas as pd
  20. from api.db import LLMType
  21. from api.db.services.conversation_service import structure_answer
  22. from api.db.services.llm_service import LLMBundle
  23. from api import settings
  24. from agent.component.base import ComponentBase, ComponentParamBase
  25. from rag.prompts import message_fit_in
  26. class GenerateParam(ComponentParamBase):
  27. """
  28. Define the Generate component parameters.
  29. """
  30. def __init__(self):
  31. super().__init__()
  32. self.llm_id = ""
  33. self.prompt = ""
  34. self.max_tokens = 0
  35. self.temperature = 0
  36. self.top_p = 0
  37. self.presence_penalty = 0
  38. self.frequency_penalty = 0
  39. self.cite = True
  40. self.parameters = []
  41. def check(self):
  42. self.check_decimal_float(self.temperature, "[Generate] Temperature")
  43. self.check_decimal_float(self.presence_penalty, "[Generate] Presence penalty")
  44. self.check_decimal_float(self.frequency_penalty, "[Generate] Frequency penalty")
  45. self.check_nonnegative_number(self.max_tokens, "[Generate] Max tokens")
  46. self.check_decimal_float(self.top_p, "[Generate] Top P")
  47. self.check_empty(self.llm_id, "[Generate] LLM")
  48. # self.check_defined_type(self.parameters, "Parameters", ["list"])
  49. def gen_conf(self):
  50. conf = {}
  51. if self.max_tokens > 0:
  52. conf["max_tokens"] = self.max_tokens
  53. if self.temperature > 0:
  54. conf["temperature"] = self.temperature
  55. if self.top_p > 0:
  56. conf["top_p"] = self.top_p
  57. if self.presence_penalty > 0:
  58. conf["presence_penalty"] = self.presence_penalty
  59. if self.frequency_penalty > 0:
  60. conf["frequency_penalty"] = self.frequency_penalty
  61. return conf
  62. class Generate(ComponentBase):
  63. component_name = "Generate"
  64. def get_dependent_components(self):
  65. inputs = self.get_input_elements()
  66. cpnts = set([i["key"] for i in inputs[1:] if i["key"].lower().find("answer") < 0 and i["key"].lower().find("begin") < 0])
  67. return list(cpnts)
  68. def set_cite(self, retrieval_res, answer):
  69. if "empty_response" in retrieval_res.columns:
  70. retrieval_res["empty_response"].fillna("", inplace=True)
  71. chunks = json.loads(retrieval_res["chunks"][0])
  72. answer, idx = settings.retrievaler.insert_citations(answer,
  73. [ck["content_ltks"] for ck in chunks],
  74. [ck["vector"] for ck in chunks],
  75. LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
  76. self._canvas.get_embedding_model()), tkweight=0.7,
  77. vtweight=0.3)
  78. doc_ids = set([])
  79. recall_docs = []
  80. for i in idx:
  81. did = chunks[int(i)]["doc_id"]
  82. if did in doc_ids:
  83. continue
  84. doc_ids.add(did)
  85. recall_docs.append({"doc_id": did, "doc_name": chunks[int(i)]["docnm_kwd"]})
  86. for c in chunks:
  87. del c["vector"]
  88. del c["content_ltks"]
  89. reference = {
  90. "chunks": chunks,
  91. "doc_aggs": recall_docs
  92. }
  93. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  94. answer += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'"
  95. res = {"content": answer, "reference": reference}
  96. res = structure_answer(None, res, "", "")
  97. return res
  98. def get_input_elements(self):
  99. key_set = set([])
  100. res = [{"key": "user", "name": "Input your question here:"}]
  101. for r in re.finditer(r"\{([a-z]+[:@][a-z0-9_-]+)\}", self._param.prompt, flags=re.IGNORECASE):
  102. cpn_id = r.group(1)
  103. if cpn_id in key_set:
  104. continue
  105. if cpn_id.lower().find("begin@") == 0:
  106. cpn_id, key = cpn_id.split("@")
  107. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  108. if p["key"] != key:
  109. continue
  110. res.append({"key": r.group(1), "name": p["name"]})
  111. key_set.add(r.group(1))
  112. continue
  113. cpn_nm = self._canvas.get_component_name(cpn_id)
  114. if not cpn_nm:
  115. continue
  116. res.append({"key": cpn_id, "name": cpn_nm})
  117. key_set.add(cpn_id)
  118. return res
  119. def _run(self, history, **kwargs):
  120. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  121. prompt = self._param.prompt
  122. retrieval_res = []
  123. self._param.inputs = []
  124. for para in self.get_input_elements()[1:]:
  125. if para["key"].lower().find("begin@") == 0:
  126. cpn_id, key = para["key"].split("@")
  127. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  128. if p["key"] == key:
  129. kwargs[para["key"]] = p.get("value", "")
  130. self._param.inputs.append(
  131. {"component_id": para["key"], "content": kwargs[para["key"]]})
  132. break
  133. else:
  134. assert False, f"Can't find parameter '{key}' for {cpn_id}"
  135. continue
  136. component_id = para["key"]
  137. cpn = self._canvas.get_component(component_id)["obj"]
  138. if cpn.component_name.lower() == "answer":
  139. hist = self._canvas.get_history(1)
  140. if hist:
  141. hist = hist[0]["content"]
  142. else:
  143. hist = ""
  144. kwargs[para["key"]] = hist
  145. continue
  146. _, out = cpn.output(allow_partial=False)
  147. if "content" not in out.columns:
  148. kwargs[para["key"]] = ""
  149. else:
  150. if cpn.component_name.lower() == "retrieval":
  151. retrieval_res.append(out)
  152. kwargs[para["key"]] = " - " + "\n - ".join([o if isinstance(o, str) else str(o) for o in out["content"]])
  153. self._param.inputs.append({"component_id": para["key"], "content": kwargs[para["key"]]})
  154. if retrieval_res:
  155. retrieval_res = pd.concat(retrieval_res, ignore_index=True)
  156. else:
  157. retrieval_res = pd.DataFrame([])
  158. for n, v in kwargs.items():
  159. prompt = re.sub(r"\{%s\}" % re.escape(n), str(v).replace("\\", " "), prompt)
  160. if not self._param.inputs and prompt.find("{input}") >= 0:
  161. retrieval_res = self.get_input()
  162. input = (" - " + "\n - ".join(
  163. [c for c in retrieval_res["content"] if isinstance(c, str)])) if "content" in retrieval_res else ""
  164. prompt = re.sub(r"\{input\}", re.escape(input), prompt)
  165. downstreams = self._canvas.get_component(self._id)["downstream"]
  166. if kwargs.get("stream") and len(downstreams) == 1 and self._canvas.get_component(downstreams[0])[
  167. "obj"].component_name.lower() == "answer":
  168. return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
  169. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  170. empty_res = "\n- ".join([str(t) for t in retrieval_res["empty_response"] if str(t)])
  171. res = {"content": empty_res if empty_res else "Nothing found in knowledgebase!", "reference": []}
  172. return pd.DataFrame([res])
  173. msg = self._canvas.get_history(self._param.message_history_window_size)
  174. if len(msg) < 1:
  175. msg.append({"role": "user", "content": "Output: "})
  176. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  177. if len(msg) < 2:
  178. msg.append({"role": "user", "content": "Output: "})
  179. ans = chat_mdl.chat(msg[0]["content"], msg[1:], self._param.gen_conf())
  180. ans = re.sub(r"^.*</think>", "", ans, flags=re.DOTALL)
  181. self._canvas.set_component_infor(self._id, {"prompt":msg[0]["content"],"messages": msg[1:],"conf": self._param.gen_conf()})
  182. if self._param.cite and "chunks" in retrieval_res.columns:
  183. res = self.set_cite(retrieval_res, ans)
  184. return pd.DataFrame([res])
  185. return Generate.be_output(ans)
  186. def stream_output(self, chat_mdl, prompt, retrieval_res):
  187. res = None
  188. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  189. empty_res = "\n- ".join([str(t) for t in retrieval_res["empty_response"] if str(t)])
  190. res = {"content": empty_res if empty_res else "Nothing found in knowledgebase!", "reference": []}
  191. yield res
  192. self.set_output(res)
  193. return
  194. msg = self._canvas.get_history(self._param.message_history_window_size)
  195. if msg and msg[0]['role'] == 'assistant':
  196. msg.pop(0)
  197. if len(msg) < 1:
  198. msg.append({"role": "user", "content": "Output: "})
  199. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  200. if len(msg) < 2:
  201. msg.append({"role": "user", "content": "Output: "})
  202. answer = ""
  203. for ans in chat_mdl.chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf()):
  204. res = {"content": ans, "reference": []}
  205. answer = ans
  206. yield res
  207. if self._param.cite and "chunks" in retrieval_res.columns:
  208. res = self.set_cite(retrieval_res, answer)
  209. yield res
  210. self._canvas.set_component_infor(self._id, {"prompt":msg[0]["content"],"messages": msg[1:],"conf": self._param.gen_conf()})
  211. self.set_output(Generate.be_output(res))
  212. def debug(self, **kwargs):
  213. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  214. prompt = self._param.prompt
  215. for para in self._param.debug_inputs:
  216. kwargs[para["key"]] = para.get("value", "")
  217. for n, v in kwargs.items():
  218. prompt = re.sub(r"\{%s\}" % re.escape(n), str(v).replace("\\", " "), prompt)
  219. u = kwargs.get("user")
  220. ans = chat_mdl.chat(prompt, [{"role": "user", "content": u if u else "Output: "}], self._param.gen_conf())
  221. return pd.DataFrame([ans])