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.

ragflow.py 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. from typing import List
  16. import requests
  17. from .modules.assistant import Assistant
  18. from .modules.dataset import DataSet
  19. from .modules.document import Document
  20. class RAGFlow:
  21. def __init__(self, user_key, base_url, version='v1'):
  22. """
  23. api_url: http://<host_address>/api/v1
  24. """
  25. self.user_key = user_key
  26. self.api_url = f"{base_url}/api/{version}"
  27. self.authorization_header = {"Authorization": "{} {}".format("Bearer", self.user_key)}
  28. def post(self, path, param, stream=False):
  29. res = requests.post(url=self.api_url + path, json=param, headers=self.authorization_header, stream=stream)
  30. return res
  31. def get(self, path, params=None):
  32. res = requests.get(url=self.api_url + path, params=params, headers=self.authorization_header)
  33. return res
  34. def delete(self, path, params):
  35. res = requests.delete(url=self.api_url + path, params=params, headers=self.authorization_header)
  36. return res
  37. def create_dataset(self, name: str, avatar: str = "", description: str = "", language: str = "English",
  38. permission: str = "me",
  39. document_count: int = 0, chunk_count: int = 0, parse_method: str = "naive",
  40. parser_config: DataSet.ParserConfig = None) -> DataSet:
  41. if parser_config is None:
  42. parser_config = DataSet.ParserConfig(self, {"chunk_token_count": 128, "layout_recognize": True,
  43. "delimiter": "\n!?。;!?", "task_page_size": 12})
  44. parser_config = parser_config.to_json()
  45. res = self.post("/dataset/save",
  46. {"name": name, "avatar": avatar, "description": description, "language": language,
  47. "permission": permission,
  48. "document_count": document_count, "chunk_count": chunk_count, "parse_method": parse_method,
  49. "parser_config": parser_config
  50. }
  51. )
  52. res = res.json()
  53. if res.get("retmsg") == "success":
  54. return DataSet(self, res["data"])
  55. raise Exception(res["retmsg"])
  56. def list_datasets(self, page: int = 1, page_size: int = 1024, orderby: str = "create_time", desc: bool = True) -> \
  57. List[DataSet]:
  58. res = self.get("/dataset/list", {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc})
  59. res = res.json()
  60. result_list = []
  61. if res.get("retmsg") == "success":
  62. for data in res['data']:
  63. result_list.append(DataSet(self, data))
  64. return result_list
  65. raise Exception(res["retmsg"])
  66. def get_dataset(self, id: str = None, name: str = None) -> DataSet:
  67. res = self.get("/dataset/detail", {"id": id, "name": name})
  68. res = res.json()
  69. if res.get("retmsg") == "success":
  70. return DataSet(self, res['data'])
  71. raise Exception(res["retmsg"])
  72. def create_assistant(self, name: str = "assistant", avatar: str = "path", knowledgebases: List[DataSet] = [],
  73. llm: Assistant.LLM = None, prompt: Assistant.Prompt = None) -> Assistant:
  74. datasets = []
  75. for dataset in knowledgebases:
  76. datasets.append(dataset.to_json())
  77. if llm is None:
  78. llm = Assistant.LLM(self, {"model_name": None,
  79. "temperature": 0.1,
  80. "top_p": 0.3,
  81. "presence_penalty": 0.4,
  82. "frequency_penalty": 0.7,
  83. "max_tokens": 512, })
  84. if prompt is None:
  85. prompt = Assistant.Prompt(self, {"similarity_threshold": 0.2,
  86. "keywords_similarity_weight": 0.7,
  87. "top_n": 8,
  88. "variables": [{
  89. "key": "knowledge",
  90. "optional": True
  91. }], "rerank_model": "",
  92. "empty_response": None,
  93. "opener": None,
  94. "show_quote": True,
  95. "prompt": None})
  96. if prompt.opener is None:
  97. prompt.opener = "Hi! I'm your assistant, what can I do for you?"
  98. if prompt.prompt is None:
  99. prompt.prompt = (
  100. "You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. "
  101. "Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, "
  102. "your answer must include the sentence 'The answer you are looking for is not found in the knowledge base!' "
  103. "Answers need to consider chat history.\nHere is the knowledge base:\n{knowledge}\nThe above is the knowledge base."
  104. )
  105. temp_dict = {"name": name,
  106. "avatar": avatar,
  107. "knowledgebases": datasets,
  108. "llm": llm.to_json(),
  109. "prompt": prompt.to_json()}
  110. res = self.post("/assistant/save", temp_dict)
  111. res = res.json()
  112. if res.get("retmsg") == "success":
  113. return Assistant(self, res["data"])
  114. raise Exception(res["retmsg"])
  115. def get_assistant(self, id: str = None, name: str = None) -> Assistant:
  116. res = self.get("/assistant/get", {"id": id, "name": name})
  117. res = res.json()
  118. if res.get("retmsg") == "success":
  119. return Assistant(self, res['data'])
  120. raise Exception(res["retmsg"])
  121. def list_assistants(self) -> List[Assistant]:
  122. res = self.get("/assistant/list")
  123. res = res.json()
  124. result_list = []
  125. if res.get("retmsg") == "success":
  126. for data in res['data']:
  127. result_list.append(Assistant(self, data))
  128. return result_list
  129. raise Exception(res["retmsg"])
  130. def create_document(self, ds:DataSet, name: str, blob: bytes) -> bool:
  131. url = f"/doc/dataset/{ds.id}/documents/upload"
  132. files = {
  133. 'file': (name, blob)
  134. }
  135. data = {
  136. 'kb_id': ds.id
  137. }
  138. headers = {
  139. 'Authorization': f"Bearer {ds.rag.user_key}"
  140. }
  141. response = requests.post(self.api_url + url, data=data, files=files,
  142. headers=headers)
  143. if response.status_code == 200 and response.json().get('retmsg') == 'success':
  144. return True
  145. else:
  146. raise Exception(f"Upload failed: {response.json().get('retmsg')}")
  147. return False
  148. def get_document(self, id: str = None, name: str = None) -> Document:
  149. res = self.get("/doc/infos", {"id": id, "name": name})
  150. res = res.json()
  151. if res.get("retmsg") == "success":
  152. return Document(self, res['data'])
  153. raise Exception(res["retmsg"])