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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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.llm_service import LLMBundle
  21. from api.settings import retrievaler
  22. from agent.component.base import ComponentBase, ComponentParamBase
  23. class GenerateParam(ComponentParamBase):
  24. """
  25. Define the Generate component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.llm_id = ""
  30. self.prompt = ""
  31. self.max_tokens = 0
  32. self.temperature = 0
  33. self.top_p = 0
  34. self.presence_penalty = 0
  35. self.frequency_penalty = 0
  36. self.cite = True
  37. self.parameters = []
  38. def check(self):
  39. self.check_decimal_float(self.temperature, "[Generate] Temperature")
  40. self.check_decimal_float(self.presence_penalty, "[Generate] Presence penalty")
  41. self.check_decimal_float(self.frequency_penalty, "[Generate] Frequency penalty")
  42. self.check_nonnegative_number(self.max_tokens, "[Generate] Max tokens")
  43. self.check_decimal_float(self.top_p, "[Generate] Top P")
  44. self.check_empty(self.llm_id, "[Generate] LLM")
  45. # self.check_defined_type(self.parameters, "Parameters", ["list"])
  46. def gen_conf(self):
  47. conf = {}
  48. if self.max_tokens > 0: conf["max_tokens"] = self.max_tokens
  49. if self.temperature > 0: conf["temperature"] = self.temperature
  50. if self.top_p > 0: conf["top_p"] = self.top_p
  51. if self.presence_penalty > 0: conf["presence_penalty"] = self.presence_penalty
  52. if self.frequency_penalty > 0: conf["frequency_penalty"] = self.frequency_penalty
  53. return conf
  54. class Generate(ComponentBase):
  55. component_name = "Generate"
  56. def get_dependent_components(self):
  57. cpnts = [para["component_id"] for para in self._param.parameters]
  58. return cpnts
  59. def set_cite(self, retrieval_res, answer):
  60. answer, idx = retrievaler.insert_citations(answer, [ck["content_ltks"] for _, ck in retrieval_res.iterrows()],
  61. [ck["vector"] for _, ck in retrieval_res.iterrows()],
  62. LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
  63. self._canvas.get_embedding_model()), tkweight=0.7,
  64. vtweight=0.3)
  65. doc_ids = set([])
  66. recall_docs = []
  67. for i in idx:
  68. did = retrieval_res.loc[int(i), "doc_id"]
  69. if did in doc_ids: continue
  70. doc_ids.add(did)
  71. recall_docs.append({"doc_id": did, "doc_name": retrieval_res.loc[int(i), "docnm_kwd"]})
  72. del retrieval_res["vector"]
  73. del retrieval_res["content_ltks"]
  74. reference = {
  75. "chunks": [ck.to_dict() for _, ck in retrieval_res.iterrows()],
  76. "doc_aggs": recall_docs
  77. }
  78. if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
  79. answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
  80. res = {"content": answer, "reference": reference}
  81. return res
  82. def _run(self, history, **kwargs):
  83. chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
  84. prompt = self._param.prompt
  85. retrieval_res = self.get_input()
  86. input = (" - " + "\n - ".join(retrieval_res["content"])) if "content" in retrieval_res else ""
  87. for para in self._param.parameters:
  88. cpn = self._canvas.get_component(para["component_id"])["obj"]
  89. _, out = cpn.output(allow_partial=False)
  90. if "content" not in out.columns:
  91. kwargs[para["key"]] = "Nothing"
  92. else:
  93. kwargs[para["key"]] = " - " + "\n - ".join(out["content"])
  94. kwargs["input"] = input
  95. for n, v in kwargs.items():
  96. # prompt = re.sub(r"\{%s\}"%n, re.escape(str(v)), prompt)
  97. prompt = re.sub(r"\{%s\}" % n, str(v), prompt)
  98. downstreams = self._canvas.get_component(self._id)["downstream"]
  99. if kwargs.get("stream") and len(downstreams) == 1 and self._canvas.get_component(downstreams[0])[
  100. "obj"].component_name.lower() == "answer":
  101. return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
  102. if "empty_response" in retrieval_res.columns:
  103. return Generate.be_output(input)
  104. ans = chat_mdl.chat(prompt, self._canvas.get_history(self._param.message_history_window_size),
  105. self._param.gen_conf())
  106. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  107. df = self.set_cite(retrieval_res, ans)
  108. return pd.DataFrame(df)
  109. return Generate.be_output(ans)
  110. def stream_output(self, chat_mdl, prompt, retrieval_res):
  111. res = None
  112. if "empty_response" in retrieval_res.columns and "\n- ".join(retrieval_res["content"]):
  113. res = {"content": "\n- ".join(retrieval_res["content"]), "reference": []}
  114. yield res
  115. self.set_output(res)
  116. return
  117. answer = ""
  118. for ans in chat_mdl.chat_streamly(prompt, self._canvas.get_history(self._param.message_history_window_size),
  119. self._param.gen_conf()):
  120. res = {"content": ans, "reference": []}
  121. answer = ans
  122. yield res
  123. if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
  124. res = self.set_cite(retrieval_res, answer)
  125. yield res
  126. self.set_output(res)