difyService.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import json
  2. from datetime import datetime
  3. import httpx
  4. from typing import Union, Dict, List
  5. from fastapi import HTTPException
  6. from starlette import status
  7. from Log import logger
  8. from app.config.config import settings
  9. from app.utils.rsa_crypto import RagflowCrypto
  10. class DifyService:
  11. def __init__(self, base_url: str):
  12. self.base_url = base_url
  13. def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
  14. if response.status_code != 200:
  15. if response.status_code == 201:
  16. return response.json()
  17. return {}
  18. data = response.json()
  19. ret_code = data.get("retcode")
  20. if ret_code == 401:
  21. raise HTTPException(
  22. status_code=status.HTTP_401_UNAUTHORIZED,
  23. detail="登录过期",
  24. )
  25. # if ret_code != 0:
  26. # return {}
  27. # 检查返回的数据类型
  28. if isinstance(data.get("data"), dict):
  29. return data.get("data", {})
  30. elif isinstance(data.get("data"), list):
  31. return data.get("data", [])
  32. else:
  33. return data
  34. async def register(self, username: str, password: str):
  35. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  36. async with httpx.AsyncClient() as client:
  37. response = await client.post(
  38. f"{self.base_url}/v1/user/register",
  39. headers={'Content-Type': 'application/json'},
  40. json={"nickname": username, "email": f"{username}@example.com", "password": password}
  41. )
  42. if response.status_code != 200:
  43. raise Exception(f"Ragflow registration failed: {response.text}")
  44. return self._handle_response(response)
  45. async def login(self, username: str, password: str) -> str:
  46. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  47. async with httpx.AsyncClient() as client:
  48. response = await client.post(
  49. f"{self.base_url}/v1/user/login",
  50. headers={'Content-Type': 'application/json'},
  51. json={"email": f"{username}@example.com", "password": password}
  52. )
  53. if response.status_code != 200:
  54. raise Exception(f"Ragflow login failed: {response.text}")
  55. authorization = response.headers.get('Authorization')
  56. if not authorization:
  57. raise Exception("Authorization header not found in response")
  58. return authorization
  59. async def chat(self, token: str, user_id: int, message: str, upload_file_id: str, conversation_id: str):
  60. target_url = f"{self.base_url}/v1/chat-messages"
  61. files = []
  62. if upload_file_id:
  63. files = [
  64. {
  65. "type": "image",
  66. "transfer_method": "local_file",
  67. "url": "",
  68. "upload_file_id": upload_file_id
  69. }
  70. ]
  71. data = {
  72. "inputs": {},
  73. "query": message,
  74. "response_mode": "streaming",
  75. "conversation_id": "",
  76. "user": str(user_id),
  77. "files": files
  78. }
  79. async with httpx.AsyncClient(timeout=300.0) as client:
  80. headers = {
  81. 'Content-Type': 'application/json',
  82. 'Authorization': f'Bearer {token}'
  83. }
  84. async with client.stream("POST", target_url, data=json.dumps(data), headers=headers) as response:
  85. if response.status_code == 200:
  86. try:
  87. async for answer in response.aiter_text():
  88. # print(f"response of ragflow chat: {answer}")
  89. yield answer
  90. except GeneratorExit as e:
  91. print(e)
  92. return
  93. else:
  94. yield f"Error: {response.status_code}"
  95. async def get_session_history(self, token: str, conversation_id: str, user: str):
  96. url = f"{self.base_url}/v1/messages"
  97. params = {
  98. 'user': user,
  99. 'conversation_id': conversation_id
  100. }
  101. headers = {"Authorization": f'Bearer {token}'}
  102. async with httpx.AsyncClient() as client:
  103. response = await client.get(url, params=params, headers=headers)
  104. # print(response.text)
  105. # print(response.status_code)
  106. # print(response.res)
  107. data = self._handle_response(response)
  108. # print("----------------data----------------------:", data)
  109. return data
  110. async def upload(self, token: str, filename: str, file: bytes, user_id) -> dict:
  111. url = f"{self.base_url}/v1/files/upload"
  112. headers = {
  113. # 'Content-Type': 'application/json',
  114. 'Authorization': f'Bearer {token}'
  115. }
  116. data = {
  117. 'user': str(user_id)
  118. }
  119. # 创建表单数据,包含文件
  120. files = {"file": (filename, file)}
  121. async with httpx.AsyncClient() as client:
  122. response = await client.post(url, headers=headers, files=files, data=data)
  123. data = self._handle_response(response)
  124. return data
  125. if __name__ == "__main__":
  126. async def a():
  127. a = DifyService("http://192.168.20.119:11080")
  128. b = await a.get_knowledge_list("ImY3ZTZlZWQwYTY2NTExZWY5ZmFiMDI0MmFjMTMwMDA2Ig.Zzxwmw.uI_HAWzOkipQuga1aeQtoeIc3IM", 1,
  129. 10)
  130. print(b)
  131. import asyncio
  132. asyncio.run(a())