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.

generate.py 11KB

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