base.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import inspect
  2. import json
  3. import logging
  4. from collections.abc import Callable, Generator
  5. from typing import Optional, TypeVar
  6. import requests
  7. from pydantic import BaseModel
  8. from yarl import URL
  9. from configs import dify_config
  10. from core.model_runtime.errors.invoke import (
  11. InvokeAuthorizationError,
  12. InvokeBadRequestError,
  13. InvokeConnectionError,
  14. InvokeRateLimitError,
  15. InvokeServerUnavailableError,
  16. )
  17. from core.plugin.entities.plugin_daemon import PluginDaemonBasicResponse, PluginDaemonError, PluginDaemonInnerError
  18. from core.plugin.manager.exc import (
  19. PluginDaemonBadRequestError,
  20. PluginDaemonInternalServerError,
  21. PluginDaemonNotFoundError,
  22. PluginDaemonUnauthorizedError,
  23. PluginPermissionDeniedError,
  24. PluginUniqueIdentifierError,
  25. )
  26. plugin_daemon_inner_api_baseurl = dify_config.PLUGIN_API_URL
  27. plugin_daemon_inner_api_key = dify_config.PLUGIN_API_KEY
  28. T = TypeVar("T", bound=(BaseModel | dict | list | bool | str))
  29. logger = logging.getLogger(__name__)
  30. class BasePluginManager:
  31. def _request(
  32. self,
  33. method: str,
  34. path: str,
  35. headers: dict | None = None,
  36. data: bytes | dict | str | None = None,
  37. params: dict | None = None,
  38. files: dict | None = None,
  39. stream: bool = False,
  40. ) -> requests.Response:
  41. """
  42. Make a request to the plugin daemon inner API.
  43. """
  44. url = URL(str(plugin_daemon_inner_api_baseurl)) / path
  45. headers = headers or {}
  46. headers["X-Api-Key"] = plugin_daemon_inner_api_key
  47. headers["Accept-Encoding"] = "gzip, deflate, br"
  48. if headers.get("Content-Type") == "application/json" and isinstance(data, dict):
  49. data = json.dumps(data)
  50. try:
  51. response = requests.request(
  52. method=method, url=str(url), headers=headers, data=data, params=params, stream=stream, files=files
  53. )
  54. except requests.exceptions.ConnectionError:
  55. logger.exception("Request to Plugin Daemon Service failed")
  56. raise PluginDaemonInnerError(code=-500, message="Request to Plugin Daemon Service failed")
  57. return response
  58. def _stream_request(
  59. self,
  60. method: str,
  61. path: str,
  62. params: dict | None = None,
  63. headers: dict | None = None,
  64. data: bytes | dict | None = None,
  65. files: dict | None = None,
  66. ) -> Generator[bytes, None, None]:
  67. """
  68. Make a stream request to the plugin daemon inner API
  69. """
  70. response = self._request(method, path, headers, data, params, files, stream=True)
  71. for line in response.iter_lines():
  72. line = line.decode("utf-8").strip()
  73. if line.startswith("data:"):
  74. line = line[5:].strip()
  75. if line:
  76. yield line
  77. def _stream_request_with_model(
  78. self,
  79. method: str,
  80. path: str,
  81. type: type[T],
  82. headers: dict | None = None,
  83. data: bytes | dict | None = None,
  84. params: dict | None = None,
  85. files: dict | None = None,
  86. ) -> Generator[T, None, None]:
  87. """
  88. Make a stream request to the plugin daemon inner API and yield the response as a model.
  89. """
  90. for line in self._stream_request(method, path, params, headers, data, files):
  91. yield type(**json.loads(line))
  92. def _request_with_model(
  93. self,
  94. method: str,
  95. path: str,
  96. type: type[T],
  97. headers: dict | None = None,
  98. data: bytes | None = None,
  99. params: dict | None = None,
  100. files: dict | None = None,
  101. ) -> T:
  102. """
  103. Make a request to the plugin daemon inner API and return the response as a model.
  104. """
  105. response = self._request(method, path, headers, data, params, files)
  106. return type(**response.json())
  107. def _request_with_plugin_daemon_response(
  108. self,
  109. method: str,
  110. path: str,
  111. type: type[T],
  112. headers: dict | None = None,
  113. data: bytes | dict | None = None,
  114. params: dict | None = None,
  115. files: dict | None = None,
  116. transformer: Callable[[dict], dict] | None = None,
  117. ) -> T:
  118. """
  119. Make a request to the plugin daemon inner API and return the response as a model.
  120. """
  121. response = self._request(method, path, headers, data, params, files)
  122. json_response = response.json()
  123. if transformer:
  124. json_response = transformer(json_response)
  125. rep = PluginDaemonBasicResponse[type](**json_response)
  126. if rep.code != 0:
  127. try:
  128. error = PluginDaemonError(**json.loads(rep.message))
  129. except Exception as e:
  130. raise ValueError(f"{rep.message}, code: {rep.code}")
  131. self._handle_plugin_daemon_error(error.error_type, error.message, error.args)
  132. if rep.data is None:
  133. frame = inspect.currentframe()
  134. raise ValueError(f"got empty data from plugin daemon: {frame.f_lineno if frame else 'unknown'}")
  135. return rep.data
  136. def _request_with_plugin_daemon_response_stream(
  137. self,
  138. method: str,
  139. path: str,
  140. type: type[T],
  141. headers: dict | None = None,
  142. data: bytes | dict | None = None,
  143. params: dict | None = None,
  144. files: dict | None = None,
  145. ) -> Generator[T, None, None]:
  146. """
  147. Make a stream request to the plugin daemon inner API and yield the response as a model.
  148. """
  149. for line in self._stream_request(method, path, params, headers, data, files):
  150. line_data = None
  151. try:
  152. line_data = json.loads(line)
  153. rep = PluginDaemonBasicResponse[type](**line_data)
  154. except Exception as e:
  155. # TODO modify this when line_data has code and message
  156. if line_data and "error" in line_data:
  157. raise ValueError(line_data["error"])
  158. else:
  159. raise ValueError(line)
  160. if rep.code != 0:
  161. if rep.code == -500:
  162. try:
  163. error = PluginDaemonError(**json.loads(rep.message))
  164. except Exception as e:
  165. raise PluginDaemonInnerError(code=rep.code, message=rep.message)
  166. self._handle_plugin_daemon_error(error.error_type, error.message, error.args)
  167. raise ValueError(f"plugin daemon: {rep.message}, code: {rep.code}")
  168. if rep.data is None:
  169. frame = inspect.currentframe()
  170. raise ValueError(f"got empty data from plugin daemon: {frame.f_lineno if frame else 'unknown'}")
  171. yield rep.data
  172. def _handle_plugin_daemon_error(self, error_type: str, message: str, args: Optional[dict] = None):
  173. """
  174. handle the error from plugin daemon
  175. """
  176. args = args or {}
  177. match error_type:
  178. case PluginDaemonInnerError.__name__:
  179. raise PluginDaemonInnerError(code=-500, message=message)
  180. case InvokeRateLimitError.__name__:
  181. raise InvokeRateLimitError(description=args.get("description"))
  182. case InvokeAuthorizationError.__name__:
  183. raise InvokeAuthorizationError(description=args.get("description"))
  184. case InvokeBadRequestError.__name__:
  185. raise InvokeBadRequestError(description=args.get("description"))
  186. case InvokeConnectionError.__name__:
  187. raise InvokeConnectionError(description=args.get("description"))
  188. case InvokeServerUnavailableError.__name__:
  189. raise InvokeServerUnavailableError(description=args.get("description"))
  190. case PluginDaemonInternalServerError.__name__:
  191. raise PluginDaemonInternalServerError(description=message)
  192. case PluginDaemonBadRequestError.__name__:
  193. raise PluginDaemonBadRequestError(description=message)
  194. case PluginDaemonNotFoundError.__name__:
  195. raise PluginDaemonNotFoundError(description=message)
  196. case PluginUniqueIdentifierError.__name__:
  197. raise PluginUniqueIdentifierError(description=message)
  198. case PluginDaemonUnauthorizedError.__name__:
  199. raise PluginDaemonUnauthorizedError(description=message)
  200. case PluginPermissionDeniedError.__name__:
  201. raise PluginPermissionDeniedError(description=message)
  202. case _:
  203. raise Exception(f"got unknown error from plugin daemon: {error_type}, message: {message}, args: {args}")