difyService.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 watchdog.observers.fsevents2 import message
  8. # from Log import logger
  9. from app.config.config import settings
  10. from app.utils.rsa_crypto import RagflowCrypto
  11. class DifyService:
  12. def __init__(self, base_url: str):
  13. self.base_url = base_url
  14. def _handle_response(self, response: httpx.Response) -> Union[Dict, List]:
  15. if response.status_code != 200:
  16. return {}
  17. data = response.json()
  18. ret_code = data.get("retcode")
  19. if ret_code == 401:
  20. raise HTTPException(
  21. status_code=status.HTTP_401_UNAUTHORIZED,
  22. detail="登录过期",
  23. )
  24. if ret_code != 0:
  25. return {}
  26. # 检查返回的数据类型
  27. if isinstance(data.get("data"), dict):
  28. return data.get("data", {})
  29. elif isinstance(data.get("data"), list):
  30. return data.get("data", [])
  31. else:
  32. return {}
  33. async def register(self, username: str, password: str):
  34. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  35. async with httpx.AsyncClient() as client:
  36. response = await client.post(
  37. f"{self.base_url}/v1/user/register",
  38. headers={'Content-Type': 'application/json'},
  39. json={"nickname": username, "email": f"{username}@example.com", "password": password}
  40. )
  41. if response.status_code != 200:
  42. raise Exception(f"Ragflow registration failed: {response.text}")
  43. return self._handle_response(response)
  44. async def login(self, username: str, password: str) -> str:
  45. password = RagflowCrypto(settings.PUBLIC_KEY, settings.PRIVATE_KEY).encrypt(password)
  46. async with httpx.AsyncClient() as client:
  47. response = await client.post(
  48. f"{self.base_url}/v1/user/login",
  49. headers={'Content-Type': 'application/json'},
  50. json={"email": f"{username}@example.com", "password": password}
  51. )
  52. if response.status_code != 200:
  53. raise Exception(f"Ragflow login failed: {response.text}")
  54. authorization = response.headers.get('Authorization')
  55. if not authorization:
  56. raise Exception("Authorization header not found in response")
  57. return authorization
  58. async def chat(self, token: str, chat_id: str, message: str, upload_file_id: str, conversation_id: str):
  59. target_url = f"{self.base_url}/v1/chat-messages"
  60. files = [
  61. {
  62. "type": "image",
  63. "transfer_method": "remote_url",
  64. "url": "https://cloud.dify.ai/logo/logo-site.png",
  65. "upload_file_id":""
  66. }
  67. ]
  68. if upload_file_id:
  69. files[0]["transfer_method"] = "local_file"
  70. files[0]["upload_file_id"] = upload_file_id
  71. data = {
  72. "inputs": {},
  73. "query": message,
  74. "response_mode": "streaming",
  75. "conversation_id": conversation_id,
  76. "user": chat_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, chat_id: str, is_all: int=0):
  96. url = f"{self.base_url}/v1/conversation/get?conversation_id={chat_id}"
  97. headers = {"Authorization": token}
  98. async with httpx.AsyncClient() as client:
  99. response = await client.get(url, headers=headers)
  100. data = self._handle_response(response)
  101. # print("----------------data----------------------:", data)
  102. if is_all:
  103. return data
  104. return data.get("message", [])
  105. async def upload(self, token: str, filename: str, file: bytes) -> dict:
  106. url = f"{self.base_url}/console/api/files/upload"
  107. headers = {
  108. 'Content-Type': 'application/json',
  109. 'Authorization': f'Bearer {token}'
  110. }
  111. # 创建表单数据,包含文件
  112. files = {"file": (filename, file)}
  113. async with httpx.AsyncClient() as client:
  114. response = await client.post(url, headers=headers, files=files)
  115. data = self._handle_response(response)
  116. # file_path = data.get("file_path", "")
  117. result = {
  118. "file_path": data
  119. }
  120. return result
  121. if __name__ == "__main__":
  122. async def a():
  123. a = DifyService("http://192.168.20.119:11080")
  124. b = await a.get_knowledge_list("ImY3ZTZlZWQwYTY2NTExZWY5ZmFiMDI0MmFjMTMwMDA2Ig.Zzxwmw.uI_HAWzOkipQuga1aeQtoeIc3IM", 1,
  125. 10)
  126. print(b)
  127. import asyncio
  128. asyncio.run(a())