ragflow.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. async def login(self, username: str, password: str) -> str:
  40. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  41. async with httpx.AsyncClient() as client:
  42. response = await client.post(
  43. f"{self.base_url}/v1/user/login",
  44. headers={'Content-Type': 'application/json'},
  45. json={"email": f"{username}@example.com", "password": password}
  46. )
  47. if response.status_code != 200:
  48. raise Exception(f"Ragflow login failed: {response.text}")
  49. authorization = response.headers.get('Authorization')
  50. if not authorization:
  51. raise Exception("Authorization header not found in response")
  52. return authorization
  53. async def chat(self, token: str, chat_id: str, chat_history: list):
  54. data = {
  55. "conversation_id": chat_id,
  56. "messages": chat_history
  57. }
  58. print(f"send to ragflow chat: {data}")
  59. target_url = f"{self.base_url}/v1/conversation/completion"
  60. async with httpx.AsyncClient(timeout=300.0) as client:
  61. headers = {
  62. 'Content-Type': 'application/json',
  63. 'Authorization': token
  64. }
  65. async with client.stream("POST", target_url, json=data, headers=headers) as response:
  66. if response.status_code == 200:
  67. try:
  68. async for answer in response.aiter_text():
  69. print(f"response of ragflow chat: {answer}")
  70. yield answer
  71. except GeneratorExit as e:
  72. print(e)
  73. return
  74. else:
  75. yield f"Error: {response.status_code}"
  76. async def get_chat_sessions(self, token: str, dialog_id: str) -> list:
  77. url = f"{self.base_url}/v1/conversation/list?dialog_id={dialog_id}"
  78. headers = {"Authorization": token}
  79. async with httpx.AsyncClient() as client:
  80. response = await client.get(url, headers=headers)
  81. data = self._handle_response(response)
  82. result = [
  83. {
  84. "id": item["id"],
  85. "name": item["name"],
  86. "updated_time": item["update_time"]
  87. }
  88. for item in data
  89. ]
  90. return result
  91. async def set_session(self, token: str, dialog_id: str, message: dict, chat_id: str, is_new: bool) -> list:
  92. url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}"
  93. headers = {"Authorization": token}
  94. data = {
  95. "dialog_id": dialog_id,
  96. "name": message["message"],
  97. "is_new": is_new,
  98. "conversation_id": chat_id,
  99. }
  100. async with httpx.AsyncClient() as client:
  101. response = await client.post(url, headers=headers, json=data)
  102. data = self._handle_response(response)
  103. return [
  104. {
  105. "content": "你好! 我是你的助理,有什么可以帮到你的吗?",
  106. "role": "assistant"
  107. },
  108. {
  109. "content": message["message"],
  110. "doc_ids":message.get("doc_ids", []),
  111. "role": "user"
  112. }
  113. ] if data else []
  114. async def get_session_history(self, token: str, chat_id: str) -> list:
  115. url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
  116. headers = {"Authorization": token}
  117. async with httpx.AsyncClient() as client:
  118. response = await client.get(url, headers=headers)
  119. data = self._handle_response(response)
  120. return data.get("message", [])
  121. async def upload_and_parse(self, token: str, chat_id: str, filename: str, file: bytes) -> str:
  122. url = f"{self.base_url}/v1/document/upload_and_parse"
  123. headers = {"Authorization": token}
  124. data = {"conversation_id": chat_id}
  125. # 创建表单数据,包含文件
  126. files = {"file": (filename, file)}
  127. async with httpx.AsyncClient(timeout=60) as client:
  128. response = await client.post(url, headers=headers, files=files, data=data)
  129. data = self._handle_response(response)
  130. return data