ragflow.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import httpx
  2. from typing import Union, Dict, List
  3. from fastapi import HTTPException
  4. from starlette import status
  5. from app.config.config import settings
  6. from app.utils.rsa_crypto import RagflowCrypto
  7. class RagflowService:
  8. def __init__(self, base_url: str):
  9. self.base_url = base_url
  10. def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
  11. if response.status_code != 200:
  12. return {}
  13. data = response.json()
  14. ret_code = data.get("retcode")
  15. if ret_code == 401:
  16. raise HTTPException(
  17. status_code=status.HTTP_401_UNAUTHORIZED,
  18. detail="登录过期",
  19. )
  20. if ret_code != 0:
  21. return {}
  22. # 检查返回的数据类型
  23. if isinstance(data.get("data"), dict):
  24. return data.get("data", {})
  25. elif isinstance(data.get("data"), list):
  26. return data.get("data", [])
  27. else:
  28. return {}
  29. async def register(self, username: str, password: str):
  30. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  31. async with httpx.AsyncClient() as client:
  32. response = await client.post(
  33. f"{self.base_url}/v1/user/register",
  34. headers={'Content-Type': 'application/json'},
  35. json={"nickname": username, "email": f"{username}@example.com", "password": password}
  36. )
  37. if response.status_code != 200:
  38. raise Exception(f"Ragflow registration failed: {response.text}")
  39. return self._handle_response(response)
  40. async def login(self, username: str, password: str) -> str:
  41. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  42. async with httpx.AsyncClient() as client:
  43. response = await client.post(
  44. f"{self.base_url}/v1/user/login",
  45. headers={'Content-Type': 'application/json'},
  46. json={"email": f"{username}@example.com", "password": password}
  47. )
  48. if response.status_code != 200:
  49. raise Exception(f"Ragflow login failed: {response.text}")
  50. authorization = response.headers.get('Authorization')
  51. if not authorization:
  52. raise Exception("Authorization header not found in response")
  53. return authorization
  54. async def chat(self, token: str, chat_id: str, chat_history: list):
  55. data = {
  56. "conversation_id": chat_id,
  57. "messages": chat_history
  58. }
  59. print(f"send to ragflow chat: {data}")
  60. target_url = f"{self.base_url}/v1/conversation/completion"
  61. async with httpx.AsyncClient(timeout=300.0) as client:
  62. headers = {
  63. 'Content-Type': 'application/json',
  64. 'Authorization': token
  65. }
  66. async with client.stream("POST", target_url, json=data, headers=headers) as response:
  67. if response.status_code == 200:
  68. try:
  69. async for answer in response.aiter_text():
  70. print(f"response of ragflow chat: {answer}")
  71. yield answer
  72. except GeneratorExit as e:
  73. print(e)
  74. return
  75. else:
  76. yield f"Error: {response.status_code}"
  77. async def get_chat_sessions(self, token: str, dialog_id: str) -> list:
  78. url = f"{self.base_url}/v1/conversation/list?dialog_id={dialog_id}"
  79. headers = {"Authorization": token}
  80. async with httpx.AsyncClient() as client:
  81. response = await client.get(url, headers=headers)
  82. data = self._handle_response(response)
  83. result = [
  84. {
  85. "id": item["id"],
  86. "name": item["name"],
  87. "updated_time": item["update_time"]
  88. }
  89. for item in data
  90. ]
  91. return result
  92. async def get_session_log(self, token: str, conversation_id: str) -> dict:
  93. url = f"{self.base_url}/v1/conversation/get?conversation_id={conversation_id}"
  94. headers = {"Authorization": token}
  95. async with httpx.AsyncClient() as client:
  96. response = await client.get(url, headers=headers)
  97. data = self._handle_response(response)
  98. session_log = {
  99. "dialog_id": data.get("dialog_id"),
  100. "id": data.get("id"),
  101. "message": [
  102. {
  103. "content": message.get("content"),
  104. "role": message.get("role"),
  105. }
  106. for message in data.get("message", [])
  107. ],
  108. "name": data.get("name"),
  109. "reference": data.get("reference"),
  110. }
  111. return session_log
  112. async def set_session(self, token: str, dialog_id: str, message: dict, chat_id: str, is_new: bool) -> list:
  113. url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}"
  114. headers = {"Authorization": token}
  115. data = {
  116. "dialog_id": dialog_id,
  117. "name": message["message"],
  118. "is_new": is_new,
  119. "conversation_id": chat_id,
  120. }
  121. async with httpx.AsyncClient() as client:
  122. response = await client.post(url, headers=headers, json=data)
  123. data = self._handle_response(response)
  124. return [
  125. {
  126. "content": "你好! 我是你的助理,有什么可以帮到你的吗?",
  127. "role": "assistant"
  128. },
  129. {
  130. "content": message["message"],
  131. "doc_ids":message.get("doc_ids", []),
  132. "role": "user"
  133. }
  134. ] if data else []
  135. async def get_session_history(self, token: str, chat_id: str) -> list:
  136. url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
  137. headers = {"Authorization": token}
  138. async with httpx.AsyncClient() as client:
  139. response = await client.get(url, headers=headers)
  140. data = self._handle_response(response)
  141. return data.get("message", [])
  142. async def upload_and_parse(self, token: str, chat_id: str, filename: str, file: bytes) -> str:
  143. url = f"{self.base_url}/v1/document/upload_and_parse"
  144. headers = {"Authorization": token}
  145. data = {"conversation_id": chat_id}
  146. # 创建表单数据,包含文件
  147. files = {"file": (filename, file)}
  148. async with httpx.AsyncClient(timeout=60) as client:
  149. response = await client.post(url, headers=headers, files=files, data=data)
  150. data = self._handle_response(response)
  151. return data
  152. async def add_user_tenant(self, token: str, tenant_id: str, email: str, user_id: str) -> str:
  153. url = f"{self.base_url}/v1/tenant/{tenant_id}/user"
  154. headers = {"Authorization": token}
  155. data = {"email": email, "user_id": user_id}
  156. async with httpx.AsyncClient(timeout=60) as client:
  157. response = await client.post(url, headers=headers, json=data)
  158. if response.status_code != 200:
  159. raise Exception(f"Ragflow add user to tenant failed: {response.text}")