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

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. import requests
  16. from .modules.chat import Chat
  17. from .modules.chunk import Chunk
  18. from .modules.dataset import DataSet
  19. from .modules.agent import Agent
  20. class RAGFlow:
  21. def __init__(self, api_key, base_url, version='v1'):
  22. """
  23. api_url: http://<host_address>/api/v1
  24. """
  25. self.user_key = api_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, json=None, stream=False, files=None):
  29. res = requests.post(url=self.api_url + path, json=json, headers=self.authorization_header, stream=stream,files=files)
  30. return res
  31. def get(self, path, params=None, json=None):
  32. res = requests.get(url=self.api_url + path, params=params, headers=self.authorization_header,json=json)
  33. return res
  34. def delete(self, path, json):
  35. res = requests.delete(url=self.api_url + path, json=json, headers=self.authorization_header)
  36. return res
  37. def put(self, path, json):
  38. res = requests.put(url=self.api_url + path, json= json,headers=self.authorization_header)
  39. return res
  40. def create_dataset(self, name: str, avatar: str = "", description: str = "", language: str = "English",
  41. permission: str = "me",chunk_method: str = "naive",
  42. parser_config: DataSet.ParserConfig = None) -> DataSet:
  43. if parser_config:
  44. parser_config = parser_config.to_json()
  45. res = self.post("/datasets",
  46. {"name": name, "avatar": avatar, "description": description, "language": language,
  47. "permission": permission, "chunk_method": chunk_method,
  48. "parser_config": parser_config
  49. }
  50. )
  51. res = res.json()
  52. if res.get("code") == 0:
  53. return DataSet(self, res["data"])
  54. raise Exception(res["message"])
  55. def delete_datasets(self, ids: list[str] | None = None):
  56. res = self.delete("/datasets",{"ids": ids})
  57. res=res.json()
  58. if res.get("code") != 0:
  59. raise Exception(res["message"])
  60. def get_dataset(self,name: str):
  61. _list = self.list_datasets(name=name)
  62. if len(_list) > 0:
  63. return _list[0]
  64. raise Exception("Dataset %s not found" % name)
  65. def list_datasets(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True,
  66. id: str | None = None, name: str | None = None) -> \
  67. list[DataSet]:
  68. res = self.get("/datasets",
  69. {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name})
  70. res = res.json()
  71. result_list = []
  72. if res.get("code") == 0:
  73. for data in res['data']:
  74. result_list.append(DataSet(self, data))
  75. return result_list
  76. raise Exception(res["message"])
  77. def create_chat(self, name: str, avatar: str = "", dataset_ids=None,
  78. llm: Chat.LLM | None = None, prompt: Chat.Prompt | None = None) -> Chat:
  79. if dataset_ids is None:
  80. dataset_ids = []
  81. dataset_list = []
  82. for id in dataset_ids:
  83. dataset_list.append(id)
  84. if llm is None:
  85. llm = Chat.LLM(self, {"model_name": None,
  86. "temperature": 0.1,
  87. "top_p": 0.3,
  88. "presence_penalty": 0.4,
  89. "frequency_penalty": 0.7,
  90. "max_tokens": 512, })
  91. if prompt is None:
  92. prompt = Chat.Prompt(self, {"similarity_threshold": 0.2,
  93. "keywords_similarity_weight": 0.7,
  94. "top_n": 8,
  95. "variables": [{
  96. "key": "knowledge",
  97. "optional": True
  98. }], "rerank_model": "",
  99. "empty_response": None,
  100. "opener": None,
  101. "show_quote": True,
  102. "prompt": None})
  103. if prompt.opener is None:
  104. prompt.opener = "Hi! I'm your assistant, what can I do for you?"
  105. if prompt.prompt is None:
  106. prompt.prompt = (
  107. "You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. "
  108. "Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, "
  109. "your answer must include the sentence 'The answer you are looking for is not found in the knowledge base!' "
  110. "Answers need to consider chat history.\nHere is the knowledge base:\n{knowledge}\nThe above is the knowledge base."
  111. )
  112. temp_dict = {"name": name,
  113. "avatar": avatar,
  114. "dataset_ids": dataset_list,
  115. "llm": llm.to_json(),
  116. "prompt": prompt.to_json()}
  117. res = self.post("/chats", temp_dict)
  118. res = res.json()
  119. if res.get("code") == 0:
  120. return Chat(self, res["data"])
  121. raise Exception(res["message"])
  122. def delete_chats(self,ids: list[str] | None = None):
  123. res = self.delete('/chats',
  124. {"ids":ids})
  125. res = res.json()
  126. if res.get("code") != 0:
  127. raise Exception(res["message"])
  128. def list_chats(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True,
  129. id: str | None = None, name: str | None = None) -> list[Chat]:
  130. res = self.get("/chats",{"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name})
  131. res = res.json()
  132. result_list = []
  133. if res.get("code") == 0:
  134. for data in res['data']:
  135. result_list.append(Chat(self, data))
  136. return result_list
  137. raise Exception(res["message"])
  138. def retrieve(self, dataset_ids, document_ids=None, question="", page=1, page_size=30, similarity_threshold=0.2, vector_similarity_weight=0.3, top_k=1024, rerank_id: str | None = None, keyword:bool=False, ):
  139. if document_ids is None:
  140. document_ids = []
  141. data_json ={
  142. "page": page,
  143. "page_size": page_size,
  144. "similarity_threshold": similarity_threshold,
  145. "vector_similarity_weight": vector_similarity_weight,
  146. "top_k": top_k,
  147. "rerank_id": rerank_id,
  148. "keyword": keyword,
  149. "question": question,
  150. "dataset_ids": dataset_ids,
  151. "documents": document_ids
  152. }
  153. # Send a POST request to the backend service (using requests library as an example, actual implementation may vary)
  154. res = self.post('/retrieval',json=data_json)
  155. res = res.json()
  156. if res.get("code") ==0:
  157. chunks=[]
  158. for chunk_data in res["data"].get("chunks"):
  159. chunk=Chunk(self,chunk_data)
  160. chunks.append(chunk)
  161. return chunks
  162. raise Exception(res.get("message"))
  163. def list_agents(self, page: int = 1, page_size: int = 30, orderby: str = "update_time", desc: bool = True,
  164. id: str | None = None, title: str | None = None) -> list[Agent]:
  165. res = self.get("/agents",{"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "title": title})
  166. res = res.json()
  167. result_list = []
  168. if res.get("code") == 0:
  169. for data in res['data']:
  170. result_list.append(Agent(self, data))
  171. return result_list
  172. raise Exception(res["message"])