選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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