ragflow.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from datetime import datetime
  2. import httpx
  3. from typing import Union, Dict, List
  4. from fastapi import HTTPException
  5. from starlette import status
  6. # from Log import logger
  7. from app.config.config import settings
  8. from app.utils.rsa_crypto import RagflowCrypto
  9. class RagflowService:
  10. def __init__(self, base_url: str):
  11. self.base_url = base_url
  12. def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
  13. if response.status_code != 200:
  14. return {}
  15. data = response.json()
  16. ret_code = data.get("retcode")
  17. if ret_code == 401:
  18. raise HTTPException(
  19. status_code=status.HTTP_401_UNAUTHORIZED,
  20. detail="登录过期",
  21. )
  22. if ret_code != 0:
  23. return {}
  24. # 检查返回的数据类型
  25. if isinstance(data.get("data"), dict):
  26. return data.get("data", {})
  27. elif isinstance(data.get("data"), list):
  28. return data.get("data", [])
  29. else:
  30. return {}
  31. async def register(self, username: str, password: str, token:str=""):
  32. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  33. async with httpx.AsyncClient() as client:
  34. response = await client.post(
  35. f"{self.base_url}/v1/user/register",
  36. headers={'Content-Type': 'application/json'},
  37. json={"nickname": username, "email": f"{username}@example.com", "password": password}
  38. )
  39. if response.status_code != 200:
  40. raise Exception(f"Ragflow registration failed: {response.text}")
  41. return self._handle_response(response)
  42. async def login(self, username: str, password: str) -> str:
  43. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  44. async with httpx.AsyncClient() as client:
  45. response = await client.post(
  46. f"{self.base_url}/v1/user/login",
  47. headers={'Content-Type': 'application/json'},
  48. json={"email": f"{username}@example.com", "password": password}
  49. )
  50. if response.status_code != 200:
  51. raise Exception(f"Ragflow login failed: {response.text}")
  52. authorization = response.headers.get('Authorization')
  53. if not authorization:
  54. raise Exception("Authorization header not found in response")
  55. return authorization
  56. async def chat(self, token: str, chat_id: str, chat_history: list):
  57. data = {
  58. "conversation_id": chat_id,
  59. "messages": chat_history
  60. }
  61. print(f"send to ragflow chat: {data}")
  62. target_url = f"{self.base_url}/v1/conversation/completion"
  63. async with httpx.AsyncClient(timeout=300.0) as client:
  64. headers = {
  65. 'Content-Type': 'application/json',
  66. 'Authorization': token
  67. }
  68. async with client.stream("POST", target_url, json=data, headers=headers) as response:
  69. if response.status_code == 200:
  70. try:
  71. async for answer in response.aiter_text():
  72. print(f"response of ragflow chat: {answer}")
  73. yield answer
  74. except GeneratorExit as e:
  75. print(e)
  76. return
  77. else:
  78. yield f"Error: {response.status_code}"
  79. async def get_chat_sessions(self, token: str, dialog_id: str) -> list:
  80. url = f"{self.base_url}/v1/conversation/list?dialog_id={dialog_id}"
  81. headers = {"Authorization": token}
  82. async with httpx.AsyncClient() as client:
  83. response = await client.get(url, headers=headers)
  84. data = self._handle_response(response)
  85. result = [
  86. {
  87. "id": item["id"],
  88. "name": item["name"],
  89. "updated_time": item["update_time"],
  90. "update_date": datetime.fromtimestamp(item["update_time"] / 1000.0).strftime('%Y-%m-%d %H:%M:%S')
  91. }
  92. for item in data
  93. if "id" in item and "name" in item and item["name"]
  94. ]
  95. return result
  96. async def get_session_log(self, token: str, conversation_id: str) -> dict:
  97. url = f"{self.base_url}/v1/conversation/get?conversation_id={conversation_id}"
  98. headers = {"Authorization": token}
  99. async with httpx.AsyncClient() as client:
  100. response = await client.get(url, headers=headers)
  101. data = self._handle_response(response)
  102. session_log = {
  103. "session_log": [
  104. {
  105. "message": message.get("content"),
  106. "role": message.get("role"),
  107. }
  108. for message in data.get("message", [])
  109. ],
  110. "reference": data.get("reference"),
  111. }
  112. return session_log
  113. async def set_session(self, token: str, dialog_id: str, message: dict, chat_id: str, is_new: bool) -> list:
  114. url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}"
  115. headers = {"Authorization": token}
  116. data = {
  117. "dialog_id": dialog_id,
  118. "name": message["message"],
  119. "is_new": is_new,
  120. "conversation_id": chat_id,
  121. }
  122. async with httpx.AsyncClient() as client:
  123. response = await client.post(url, headers=headers, json=data)
  124. data = self._handle_response(response)
  125. return [
  126. {
  127. "content": "你好! 我是你的助理,有什么可以帮到你的吗?",
  128. "role": "assistant"
  129. },
  130. {
  131. "content": message["message"],
  132. "doc_ids":message.get("doc_ids", []),
  133. "role": "user"
  134. }
  135. ] if data else []
  136. async def get_session_history(self, token: str, chat_id: str, is_all: int=0):
  137. url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
  138. headers = {"Authorization": token}
  139. async with httpx.AsyncClient() as client:
  140. response = await client.get(url, headers=headers)
  141. data = self._handle_response(response)
  142. # print("----------------data----------------------:", data)
  143. if is_all:
  144. return data
  145. return data.get("message", [])
  146. async def upload_and_parse(self, token: str, chat_id: str, filename: str, file: bytes) -> str:
  147. url = f"{self.base_url}/v1/document/upload_and_parse"
  148. headers = {"Authorization": token}
  149. data = {"conversation_id": chat_id}
  150. # 创建表单数据,包含文件
  151. files = {"file": (filename, file)}
  152. async with httpx.AsyncClient(timeout=60) as client:
  153. response = await client.post(url, headers=headers, files=files, data=data)
  154. data = self._handle_response(response)
  155. return data
  156. async def add_user_tenant(self, token: str, tenant_id: str, email: str, user_id: str) -> str:
  157. url = f"{self.base_url}/v1/tenant/{tenant_id}/user"
  158. headers = {"Authorization": token}
  159. data = {"email": email, "user_id": user_id}
  160. async with httpx.AsyncClient(timeout=60) as client:
  161. response = await client.post(url, headers=headers, json=data)
  162. print(response.text)
  163. if response.status_code != 200:
  164. raise Exception(f"Ragflow add user to tenant failed: {response.text}")
  165. async def get_knowledge_list(self, token: str, page_index: int, page_size: int) -> str:
  166. url = f"{self.base_url}/v1/kb/list"
  167. headers = {"Authorization": token}
  168. # params = {"page": page_index, "page_size": page_size}
  169. params = {}
  170. async with httpx.AsyncClient(timeout=60) as client:
  171. response = await client.get(url, headers=headers, params=params)
  172. res = self._handle_response(response)
  173. return res
  174. async def set_user_password(self, token: str, password: str, new_password: str) -> str:
  175. # print("password:", password)
  176. # print("new_password:", new_password)
  177. headers = {
  178. 'Content-Type': 'application/json',
  179. 'Authorization': token
  180. }
  181. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  182. new_password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(new_password)
  183. url = f"{self.base_url}/v1/user/setting"
  184. # headers = {"Authorization": token}
  185. data = {"password": password, "new_password":new_password}
  186. async with httpx.AsyncClient(timeout=60) as client:
  187. response = await client.post(url, headers=headers, json=data)
  188. data = self._handle_response(response)
  189. # logger.info("set_user_password:{}".format(data))
  190. return data
  191. async def agree_tenant_role(self, token: str, tenant_id: str) -> str:
  192. url = f"{self.base_url}/v1/tenant/agree/{tenant_id}"
  193. headers = {"Authorization": token}
  194. data = {}
  195. async with httpx.AsyncClient(timeout=60) as client:
  196. response = await client.put(url, headers=headers, json=data)
  197. print(response.text)
  198. if response.status_code != 200:
  199. raise Exception(f"Ragflow add user to tenant failed: {response.text}")
  200. if __name__ == "__main__":
  201. async def a():
  202. a = RagflowService("http://192.168.20.119:11080")
  203. b = await a.agree_tenant_role("ImQ3MGY1NGFhYzFkZjExZWY5MDFmMDI0MmFjMTMwMDA2Ig.Z2qJfA.hJX4rPnnmlkUzpjIl0YGcM-yp1M", "fe24dd2c9be611ef92880242ac160006")
  204. print(b)
  205. print(b)
  206. import asyncio
  207. asyncio.run(a())
  208. # password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt("123456")
  209. # print(password)