ragflow.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import httpx
  2. from app.config.config import settings
  3. from app.utils.rsa_crypto import RagflowCrypto
  4. class RagflowService:
  5. def __init__(self, base_url: str):
  6. self.base_url = base_url
  7. async def register(self, username: str, password: str):
  8. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  9. async with httpx.AsyncClient() as client:
  10. response = await client.post(
  11. f"{self.base_url}/v1/user/register",
  12. json={"nickname": username, "email": f"{username}@example.com", "password": password},
  13. headers={'Content-Type': 'application/json'}
  14. )
  15. if response.status_code != 200:
  16. raise Exception(f"Ragflow registration failed: {response.text}")
  17. async def login(self, username: str, password: str) -> str:
  18. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  19. async with httpx.AsyncClient() as client:
  20. response = await client.post(
  21. f"{self.base_url}/v1/user/login",
  22. json={"email": f"{username}@example.com", "password": password},
  23. headers={'Content-Type': 'application/json'}
  24. )
  25. if response.status_code != 200:
  26. raise Exception(f"Ragflow login failed: {response.text}")
  27. # 从响应头中提取 Authorization 字段
  28. authorization = response.headers.get('Authorization')
  29. if not authorization:
  30. raise Exception("Authorization header not found in response")
  31. return authorization
  32. async def chat(self, token: str, chat_id: str, chat_history: list):
  33. data = {
  34. "conversation_id": chat_id,
  35. "messages": chat_history
  36. }
  37. target_url = f"{self.base_url}/v1/conversation/completion"
  38. async with httpx.AsyncClient() as client:
  39. headers = {
  40. 'Content-Type': 'application/json',
  41. 'Authorization': token
  42. }
  43. # 创建流式请求
  44. async with client.stream("POST", target_url, json=data, headers=headers) as response:
  45. # 检查响应状态码
  46. if response.status_code == 200:
  47. # 流式读取响应
  48. try:
  49. async for answer in response.aiter_text():
  50. yield answer
  51. except GeneratorExit as e:
  52. print(e)
  53. return
  54. else:
  55. yield f"Error: {response.status_code}"
  56. async def get_chat_sessions(self, token: str, dialog_id: str) -> list:
  57. url = f"{self.base_url}/v1/conversation/list?dialog_id={dialog_id}"
  58. headers = {
  59. "Authorization": token
  60. }
  61. async with httpx.AsyncClient() as client:
  62. response = await client.get(url, headers=headers)
  63. if response.status_code != 200:
  64. raise Exception(f"Failed to fetch data from Ragflow API: {response.text}")
  65. data = response.json().get("data", [])
  66. result = [
  67. {
  68. "id": item["id"],
  69. "name": item["name"],
  70. "updated_time": item["update_time"]
  71. }
  72. for item in data
  73. ]
  74. return result
  75. async def set_session(self, token: str, dialog_id: str, name: str, chat_id: str, is_new: bool) -> bool:
  76. url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}"
  77. headers = {
  78. "Authorization": token
  79. }
  80. data = {"dialog_id": dialog_id,
  81. "name": name,
  82. "is_new": is_new,
  83. "conversation_id": chat_id,
  84. }
  85. async with httpx.AsyncClient() as client:
  86. response = await client.post(url, headers=headers, json=data)
  87. if response.status_code != 200:
  88. return False
  89. return True