您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

generate.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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.settings import retrievaler
  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]
  59. return cpnts
  60. def set_cite(self, retrieval_res, answer):
  61. retrieval_res = retrieval_res.dropna(subset=["vector", "content_ltks"]).reset_index(drop=True)
  62. if "empty_response" in retrieval_res.columns:
  63. retrieval_res["empty_response"].fillna("", inplace=True)
  64. answer, idx = retrievaler.insert_citations(answer, [ck["content_ltks"] for _, ck in retrieval_res.iterrows()],
  65. [ck["vector"] for _, ck in retrieval_res.iterrows()],
  66. LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
  67. self._canvas.get_embedding_model()), tkweight=0.7,
  68. vtweight=0.3)
  69. doc_ids = set([])
  70. recall_docs = []
  71. for i in idx:
  72. did = retrieval_res.loc[int(i), "doc_id"]
  73. if did in doc_ids: continue
  74. doc_ids.add(did)
  75. recall_docs.append({"doc_id": did, "doc_name": retrieval_res.loc[int(i), "docnm_kwd"]})
  76. del retrieval_res["vector"]
  77. del retrieval_res["content_ltks"]
  78. reference = {
  79. "chunks": [ck.to_dict() for _, ck in retrieval_res.iterrows()],
  80. "doc_aggs": recall_docs
  81. }
  82. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  83. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  84. res = {"content": answer, "reference": reference}
  85. return res
  86. def _run(self, history, **kwargs):
  87. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  88. prompt = self._param.prompt
  89. retrieval_res = self.get_input()
  90. input = (" - "+"\n - ".join([c for c in retrieval_res["content"] if isinstance(c, str)])) if "content" in retrieval_res else ""
  91. for para in self._param.parameters:
  92. cpn = self._canvas.get_component(para["component_id"])["obj"]
  93. _, out = cpn.output(allow_partial=False)
  94. if "content" not in out.columns:
  95. kwargs[para["key"]] = "Nothing"
  96. else:
  97. kwargs[para["key"]] = " - "+"\n - ".join([o if isinstance(o, str) else str(o) for o in out["content"]])
  98. kwargs["input"] = input
  99. for n, v in kwargs.items():
  100. prompt = re.sub(r"\{%s\}" % re.escape(n), re.escape(str(v)), prompt)
  101. downstreams = self._canvas.get_component(self._id)["downstream"]
  102. if kwargs.get("stream") and len(downstreams) == 1 and self._canvas.get_component(downstreams[0])[
  103. "obj"].component_name.lower() == "answer":
  104. return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
  105. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  106. res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
  107. retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
  108. return pd.DataFrame([res])
  109. msg = self._canvas.get_history(self._param.message_history_window_size)
  110. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  111. ans = chat_mdl.chat(msg[0]["content"], msg[1:], self._param.gen_conf())
  112. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  113. res = self.set_cite(retrieval_res, ans)
  114. return pd.DataFrame([res])
  115. return Generate.be_output(ans)
  116. def stream_output(self, chat_mdl, prompt, retrieval_res):
  117. res = None
  118. if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
  119. res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
  120. retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
  121. yield res
  122. self.set_output(res)
  123. return
  124. msg = self._canvas.get_history(self._param.message_history_window_size)
  125. _, msg = message_fit_in([{"role": "system", "content": prompt}, *msg], int(chat_mdl.max_length * 0.97))
  126. answer = ""
  127. for ans in chat_mdl.chat_streamly(msg[0]["content"], msg[1:], self._param.gen_conf()):
  128. res = {"content": ans, "reference": []}
  129. answer = ans
  130. yield res
  131. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  132. res = self.set_cite(retrieval_res, answer)
  133. yield res
  134. self.set_output(res)