Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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