ragflow.py 6.5 KB

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