base.py 7.5 KB

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