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

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