ragflow.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. async for answer in response.aiter_text():
  49. yield answer
  50. else:
  51. yield f"Error: {response.status_code}"