ragflow.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import httpx
  2. from typing import Union, Dict, List
  3. from app.config.config import settings
  4. from app.utils.rsa_crypto import RagflowCrypto
  5. class RagflowService:
  6. def __init__(self, base_url: str):
  7. self.base_url = base_url
  8. async def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
  9. if response.status_code != 200:
  10. return {}
  11. data = response.json()
  12. ret_code = data.get("retcode")
  13. if ret_code != 0:
  14. return {}
  15. # 检查返回的数据类型
  16. if isinstance(data.get("data"), dict):
  17. return data.get("data", {})
  18. elif isinstance(data.get("data"), list):
  19. return data.get("data", [])
  20. else:
  21. return {}
  22. async def register(self, username: str, password: str):
  23. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  24. async with httpx.AsyncClient() as client:
  25. response = await client.post(
  26. f"{self.base_url}/v1/user/register",
  27. headers={'Content-Type': 'application/json'},
  28. json={"nickname": username, "email": f"{username}@example.com", "password": password}
  29. )
  30. if response.status_code != 200:
  31. raise Exception(f"Ragflow registration failed: {response.text}")
  32. async def login(self, username: str, password: str) -> str:
  33. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  34. async with httpx.AsyncClient() as client:
  35. response = await client.post(
  36. f"{self.base_url}/v1/user/login",
  37. headers={'Content-Type': 'application/json'},
  38. json={"email": f"{username}@example.com", "password": password}
  39. )
  40. if response.status_code != 200:
  41. raise Exception(f"Ragflow login failed: {response.text}")
  42. authorization = response.headers.get('Authorization')
  43. if not authorization:
  44. raise Exception("Authorization header not found in response")
  45. return authorization
  46. async def chat(self, token: str, chat_id: str, chat_history: list):
  47. data = {
  48. "conversation_id": chat_id,
  49. "messages": chat_history
  50. }
  51. print(data)
  52. target_url = f"{self.base_url}/v1/conversation/completion"
  53. async with httpx.AsyncClient(timeout=300.0) as client:
  54. headers = {
  55. 'Content-Type': 'application/json',
  56. 'Authorization': token
  57. }
  58. async with client.stream("POST", target_url, json=data, headers=headers) as response:
  59. if response.status_code == 200:
  60. try:
  61. async for answer in response.aiter_text():
  62. yield answer
  63. except GeneratorExit as e:
  64. print(e)
  65. return
  66. else:
  67. yield f"Error: {response.status_code}"
  68. async def get_chat_sessions(self, token: str, dialog_id: str) -> list:
  69. url = f"{self.base_url}/v1/conversation/list?dialog_id={dialog_id}"
  70. headers = {"Authorization": token}
  71. async with httpx.AsyncClient() as client:
  72. response = await client.get(url, headers=headers)
  73. data = await self._handle_response(response)
  74. result = [
  75. {
  76. "id": item["id"],
  77. "name": item["name"],
  78. "updated_time": item["update_time"]
  79. }
  80. for item in data
  81. ]
  82. return result
  83. async def set_session(self, token: str, dialog_id: str, name: str, chat_id: str, is_new: bool) -> list:
  84. url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}"
  85. headers = {"Authorization": token}
  86. data = {
  87. "dialog_id": dialog_id,
  88. "name": name,
  89. "is_new": is_new,
  90. "conversation_id": chat_id,
  91. }
  92. async with httpx.AsyncClient() as client:
  93. response = await client.post(url, headers=headers, json=data)
  94. data = await self._handle_response(response)
  95. return [
  96. {
  97. "content": "你好! 我是你的助理,有什么可以帮到你的吗?",
  98. "role": "assistant"
  99. },
  100. {
  101. "content": name,
  102. "doc_ids": [],
  103. "role": "user"
  104. }
  105. ] if data else []
  106. async def get_session_history(self, token: str, chat_id: str) -> list:
  107. url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
  108. headers = {"Authorization": token}
  109. async with httpx.AsyncClient() as client:
  110. response = await client.get(url, headers=headers)
  111. data = await self._handle_response(response)
  112. return data.get("message", [])