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 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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.dialog_service import message_fit_in
  21. from api.db.services.llm_service import LLMBundle
  22. from api import settings
  23. from agent.component.base import ComponentBase, ComponentParamBase
  24. class GenerateParam(ComponentParamBase):
  25. """
  26. Define the Generate component parameters.
  27. """
  28. def __init__(self):
  29. super().__init__()
  30. self.llm_id = ""
  31. self.prompt = ""
  32. self.max_tokens = 0
  33. self.temperature = 0
  34. self.top_p = 0
  35. self.presence_penalty = 0
  36. self.frequency_penalty = 0
  37. self.cite = True
  38. self.parameters = []
  39. def check(self):
  40. self.check_decimal_float(self.temperature, "[Generate] Temperature")
  41. self.check_decimal_float(self.presence_penalty, "[Generate] Presence penalty")
  42. self.check_decimal_float(self.frequency_penalty, "[Generate] Frequency penalty")
  43. self.check_nonnegative_number(self.max_tokens, "[Generate] Max tokens")
  44. self.check_decimal_float(self.top_p, "[Generate] Top P")
  45. self.check_empty(self.llm_id, "[Generate] LLM")
  46. # self.check_defined_type(self.parameters, "Parameters", ["list"])
  47. def gen_conf(self):
  48. conf = {}
  49. if self.max_tokens > 0: conf["max_tokens"] = self.max_tokens
  50. if self.temperature > 0: conf["temperature"] = self.temperature
  51. if self.top_p > 0: conf["top_p"] = self.top_p
  52. if self.presence_penalty > 0: conf["presence_penalty"] = self.presence_penalty
  53. if self.frequency_penalty > 0: conf["frequency_penalty"] = self.frequency_penalty
  54. return conf
  55. class Generate(ComponentBase):
  56. component_name = "Generate"
  57. def get_dependent_components(self):
  58. cpnts = [para["component_id"] for para in self._param.parameters if
  59. para.get("component_id") and para["component_id"].lower().find("answer") < 0]
  60. return cpnts
  61. def set_cite(self, retrieval_res, answer):
  62. retrieval_res = retrieval_res.dropna(subset=["vector", "content_ltks"]).reset_index(drop=True)
  63. if "empty_response" in retrieval_res.columns:
  64. retrieval_res["empty_response"].fillna("", inplace=True)
  65. answer, idx = settings.retrievaler.insert_citations(answer,
  66. [ck["content_ltks"] for _, ck in retrieval_res.iterrows()],
  67. [ck["vector"] for _, ck in retrieval_res.iterrows()],
  68. LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
  69. self._canvas.get_embedding_model()), tkweight=0.7,
  70. vtweight=0.3)
  71. doc_ids = set([])
  72. recall_docs = []
  73. for i in idx:
  74. did = retrieval_res.loc[int(i), "doc_id"]
  75. if did in doc_ids: continue
  76. doc_ids.add(did)
  77. recall_docs.append({"doc_id": did, "doc_name": retrieval_res.loc[int(i), "docnm_kwd"]})
  78. del retrieval_res["vector"]
  79. del retrieval_res["content_ltks"]
  80. reference = {
  81. "chunks": [ck.to_dict() for _, ck in retrieval_res.iterrows()],
  82. "doc_aggs": recall_docs
  83. }
  84. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  85. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  86. res = {"content": answer, "reference": reference}
  87. return res
  88. def _run(self, history, **kwargs):
  89. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  90. prompt = self._param.prompt
  91. retrieval_res = []
  92. self._param.inputs = []
  93. for para in self._param.parameters:
  94. if not para.get("component_id"): continue
  95. if para["component_id"].split("@")[0].lower().find("begin") > 0:
  96. cpn_id, key = para["component_id"].split("@")
  97. for p in self._canvas.get_component(cpn_id)["obj"]._param.query:
  98. if p["key"] == key:
  99. kwargs[para["key"]] = p["value"]
  100. self._param.inputs.append(
  101. {"component_id": para["component_id"], "content": kwargs[para["key"]]})
  102. break
  103. else:
  104. assert False, f"Can't find parameter '{key}' for {cpn_id}"
  105. continue
  106. cpn = self._canvas.get_component(para["component_id"])["obj"]
  107. if cpn.component_name.lower() == "answer":
  108. kwargs[para["key"]] = self._canvas.get_history(1)[0]["content"]
  109. continue
  110. _, out = cpn.output(allow_partial=False)
  111. if "content" not in out.columns:
  112. kwargs[para["key"]] = "Nothing"
  113. else:
  114. if cpn.component_name.lower() == "retrieval":
  115. retrieval_res.append(out)
  116. kwargs[para["key"]] = " - " + "\n - ".join(
  117. [o if isinstance(o, str) else str(o) for o in out["content"]])
  118. self._param.inputs.append({"component_id": para["component_id"], "content": kwargs[para["key"]]})
  119. if retrieval_res:
  120. retrieval_res = pd.concat(retrieval_res, ignore_index=True)
  121. else:
  122. retrieval_res = pd.DataFrame([])
  123. for n, v in kwargs.items():
  124. prompt = re.sub(r"\{%s\}" % re.escape(n), re.escape(str(v)), prompt)
  125. if not self._param.inputs and prompt.find("{input}") >= 0:
  126. retrieval_res = self.get_input()
  127. input = (" - " + "\n - ".join(
  128. [c for c in retrieval_res["content"] if isinstance(c, str)])) if "content" in retrieval_res else ""
  129. prompt = re.sub(r"\{input\}", re.escape(input), prompt)
  130. downstreams = self._canvas.get_component(self._id)["downstream"]
  131. if kwargs.get("stream") and len(downstreams) == 1 and self._canvas.get_component(downstreams[0])[
  132. "obj"].component_name.lower() == "answer":
  133. return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
  134. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  135. res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
  136. retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
  137. return pd.DataFrame([res])
  138. msg = self._canvas.get_history(self._param.message_history_window_size)
  139. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  140. if len(msg) < 2: msg.append({"role": "user", "content": ""})
  141. ans = chat_mdl.chat(msg[0]["content"], msg[1:], self._param.gen_conf())
  142. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  143. res = self.set_cite(retrieval_res, ans)
  144. return pd.DataFrame([res])
  145. return Generate.be_output(ans)
  146. def stream_output(self, chat_mdl, prompt, retrieval_res):
  147. res = None
  148. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  149. res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
  150. retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
  151. yield res
  152. self.set_output(res)
  153. return
  154. msg = self._canvas.get_history(self._param.message_history_window_size)
  155. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  156. if len(msg) < 2: msg.append({"role": "user", "content": ""})
  157. answer = ""
  158. for ans in chat_mdl.chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf()):
  159. res = {"content": ans, "reference": []}
  160. answer = ans
  161. yield res
  162. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  163. res = self.set_cite(retrieval_res, answer)
  164. yield res
  165. self.set_output(res)