base.py 6.6 KB

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