You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. from collections.abc import Generator
  2. from typing import Any, Optional
  3. from pydantic import BaseModel
  4. from core.plugin.entities.plugin import DatasourceProviderID, GenericProviderID, ToolProviderID
  5. from core.plugin.entities.plugin_daemon import (
  6. PluginBasicBooleanResponse,
  7. PluginDatasourceProviderEntity,
  8. PluginToolProviderEntity,
  9. )
  10. from core.plugin.impl.base import BasePluginClient
  11. from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParameter
  12. class PluginToolManager(BasePluginClient):
  13. def fetch_tool_providers(self, tenant_id: str) -> list[PluginToolProviderEntity]:
  14. """
  15. Fetch tool providers for the given tenant.
  16. """
  17. def transformer(json_response: dict[str, Any]) -> dict:
  18. for provider in json_response.get("data", []):
  19. declaration = provider.get("declaration", {}) or {}
  20. provider_name = declaration.get("identity", {}).get("name")
  21. for tool in declaration.get("tools", []):
  22. tool["identity"]["provider"] = provider_name
  23. return json_response
  24. response = self._request_with_plugin_daemon_response(
  25. "GET",
  26. f"plugin/{tenant_id}/management/tools",
  27. list[PluginToolProviderEntity],
  28. params={"page": 1, "page_size": 256},
  29. transformer=transformer,
  30. )
  31. for provider in response:
  32. provider.declaration.identity.name = f"{provider.plugin_id}/{provider.declaration.identity.name}"
  33. # override the provider name for each tool to plugin_id/provider_name
  34. for tool in provider.declaration.tools:
  35. tool.identity.provider = provider.declaration.identity.name
  36. return response
  37. def fetch_datasources(self, tenant_id: str) -> list[PluginDatasourceProviderEntity]:
  38. """
  39. Fetch datasources for the given tenant.
  40. """
  41. def transformer(json_response: dict[str, Any]) -> dict:
  42. for provider in json_response.get("data", []):
  43. declaration = provider.get("declaration", {}) or {}
  44. provider_name = declaration.get("identity", {}).get("name")
  45. for tool in declaration.get("tools", []):
  46. tool["identity"]["provider"] = provider_name
  47. return json_response
  48. response = self._request_with_plugin_daemon_response(
  49. "GET",
  50. f"plugin/{tenant_id}/management/datasources",
  51. list[PluginToolProviderEntity],
  52. params={"page": 1, "page_size": 256},
  53. transformer=transformer,
  54. )
  55. for provider in response:
  56. provider.declaration.identity.name = f"{provider.plugin_id}/{provider.declaration.identity.name}"
  57. # override the provider name for each tool to plugin_id/provider_name
  58. for tool in provider.declaration.tools:
  59. tool.identity.provider = provider.declaration.identity.name
  60. return response
  61. def fetch_datasource_provider(self, tenant_id: str, provider: str) -> PluginDatasourceProviderEntity:
  62. """
  63. Fetch datasource provider for the given tenant and plugin.
  64. """
  65. datasource_provider_id = DatasourceProviderID(provider)
  66. def transformer(json_response: dict[str, Any]) -> dict:
  67. data = json_response.get("data")
  68. if data:
  69. for tool in data.get("declaration", {}).get("tools", []):
  70. tool["identity"]["provider"] = datasource_provider_id.provider_name
  71. return json_response
  72. response = self._request_with_plugin_daemon_response(
  73. "GET",
  74. f"plugin/{tenant_id}/management/datasource",
  75. PluginDatasourceProviderEntity,
  76. params={"provider": datasource_provider_id.provider_name, "plugin_id": datasource_provider_id.plugin_id},
  77. transformer=transformer,
  78. )
  79. response.declaration.identity.name = f"{response.plugin_id}/{response.declaration.identity.name}"
  80. # override the provider name for each tool to plugin_id/provider_name
  81. for tool in response.declaration.tools:
  82. tool.identity.provider = response.declaration.identity.name
  83. return response
  84. def fetch_tool_provider(self, tenant_id: str, provider: str) -> PluginToolProviderEntity:
  85. """
  86. Fetch tool provider for the given tenant and plugin.
  87. """
  88. tool_provider_id = ToolProviderID(provider)
  89. def transformer(json_response: dict[str, Any]) -> dict:
  90. data = json_response.get("data")
  91. if data:
  92. for tool in data.get("declaration", {}).get("tools", []):
  93. tool["identity"]["provider"] = tool_provider_id.provider_name
  94. return json_response
  95. response = self._request_with_plugin_daemon_response(
  96. "GET",
  97. f"plugin/{tenant_id}/management/tool",
  98. PluginToolProviderEntity,
  99. params={"provider": tool_provider_id.provider_name, "plugin_id": tool_provider_id.plugin_id},
  100. transformer=transformer,
  101. )
  102. response.declaration.identity.name = f"{response.plugin_id}/{response.declaration.identity.name}"
  103. # override the provider name for each tool to plugin_id/provider_name
  104. for tool in response.declaration.tools:
  105. tool.identity.provider = response.declaration.identity.name
  106. return response
  107. def invoke(
  108. self,
  109. tenant_id: str,
  110. user_id: str,
  111. tool_provider: str,
  112. tool_name: str,
  113. credentials: dict[str, Any],
  114. tool_parameters: dict[str, Any],
  115. conversation_id: Optional[str] = None,
  116. app_id: Optional[str] = None,
  117. message_id: Optional[str] = None,
  118. ) -> Generator[ToolInvokeMessage, None, None]:
  119. """
  120. Invoke the tool with the given tenant, user, plugin, provider, name, credentials and parameters.
  121. """
  122. tool_provider_id = GenericProviderID(tool_provider)
  123. response = self._request_with_plugin_daemon_response_stream(
  124. "POST",
  125. f"plugin/{tenant_id}/dispatch/tool/invoke",
  126. ToolInvokeMessage,
  127. data={
  128. "user_id": user_id,
  129. "conversation_id": conversation_id,
  130. "app_id": app_id,
  131. "message_id": message_id,
  132. "data": {
  133. "provider": tool_provider_id.provider_name,
  134. "tool": tool_name,
  135. "credentials": credentials,
  136. "tool_parameters": tool_parameters,
  137. },
  138. },
  139. headers={
  140. "X-Plugin-ID": tool_provider_id.plugin_id,
  141. "Content-Type": "application/json",
  142. },
  143. )
  144. class FileChunk:
  145. """
  146. Only used for internal processing.
  147. """
  148. bytes_written: int
  149. total_length: int
  150. data: bytearray
  151. def __init__(self, total_length: int):
  152. self.bytes_written = 0
  153. self.total_length = total_length
  154. self.data = bytearray(total_length)
  155. files: dict[str, FileChunk] = {}
  156. for resp in response:
  157. if resp.type == ToolInvokeMessage.MessageType.BLOB_CHUNK:
  158. assert isinstance(resp.message, ToolInvokeMessage.BlobChunkMessage)
  159. # Get blob chunk information
  160. chunk_id = resp.message.id
  161. total_length = resp.message.total_length
  162. blob_data = resp.message.blob
  163. is_end = resp.message.end
  164. # Initialize buffer for this file if it doesn't exist
  165. if chunk_id not in files:
  166. files[chunk_id] = FileChunk(total_length)
  167. # If this is the final chunk, yield a complete blob message
  168. if is_end:
  169. yield ToolInvokeMessage(
  170. type=ToolInvokeMessage.MessageType.BLOB,
  171. message=ToolInvokeMessage.BlobMessage(blob=files[chunk_id].data),
  172. meta=resp.meta,
  173. )
  174. else:
  175. # Check if file is too large (30MB limit)
  176. if files[chunk_id].bytes_written + len(blob_data) > 30 * 1024 * 1024:
  177. # Delete the file if it's too large
  178. del files[chunk_id]
  179. # Skip yielding this message
  180. raise ValueError("File is too large which reached the limit of 30MB")
  181. # Check if single chunk is too large (8KB limit)
  182. if len(blob_data) > 8192:
  183. # Skip yielding this message
  184. raise ValueError("File chunk is too large which reached the limit of 8KB")
  185. # Append the blob data to the buffer
  186. files[chunk_id].data[
  187. files[chunk_id].bytes_written : files[chunk_id].bytes_written + len(blob_data)
  188. ] = blob_data
  189. files[chunk_id].bytes_written += len(blob_data)
  190. else:
  191. yield resp
  192. def validate_provider_credentials(
  193. self, tenant_id: str, user_id: str, provider: str, credentials: dict[str, Any]
  194. ) -> bool:
  195. """
  196. validate the credentials of the provider
  197. """
  198. tool_provider_id = GenericProviderID(provider)
  199. response = self._request_with_plugin_daemon_response_stream(
  200. "POST",
  201. f"plugin/{tenant_id}/dispatch/tool/validate_credentials",
  202. PluginBasicBooleanResponse,
  203. data={
  204. "user_id": user_id,
  205. "data": {
  206. "provider": tool_provider_id.provider_name,
  207. "credentials": credentials,
  208. },
  209. },
  210. headers={
  211. "X-Plugin-ID": tool_provider_id.plugin_id,
  212. "Content-Type": "application/json",
  213. },
  214. )
  215. for resp in response:
  216. return resp.result
  217. return False
  218. def validate_datasource_credentials(
  219. self, tenant_id: str, user_id: str, provider: str, credentials: dict[str, Any]
  220. ) -> bool:
  221. """
  222. validate the credentials of the datasource
  223. """
  224. tool_provider_id = GenericProviderID(provider)
  225. response = self._request_with_plugin_daemon_response_stream(
  226. "POST",
  227. f"plugin/{tenant_id}/dispatch/datasource/validate_credentials",
  228. PluginBasicBooleanResponse,
  229. data={
  230. "user_id": user_id,
  231. "data": {
  232. "provider": tool_provider_id.provider_name,
  233. "credentials": credentials,
  234. },
  235. },
  236. headers={
  237. "X-Plugin-ID": tool_provider_id.plugin_id,
  238. "Content-Type": "application/json",
  239. },
  240. )
  241. for resp in response:
  242. return resp.result
  243. return False
  244. def get_runtime_parameters(
  245. self,
  246. tenant_id: str,
  247. user_id: str,
  248. provider: str,
  249. credentials: dict[str, Any],
  250. tool: str,
  251. conversation_id: Optional[str] = None,
  252. app_id: Optional[str] = None,
  253. message_id: Optional[str] = None,
  254. ) -> list[ToolParameter]:
  255. """
  256. get the runtime parameters of the tool
  257. """
  258. tool_provider_id = GenericProviderID(provider)
  259. class RuntimeParametersResponse(BaseModel):
  260. parameters: list[ToolParameter]
  261. response = self._request_with_plugin_daemon_response_stream(
  262. "POST",
  263. f"plugin/{tenant_id}/dispatch/tool/get_runtime_parameters",
  264. RuntimeParametersResponse,
  265. data={
  266. "user_id": user_id,
  267. "conversation_id": conversation_id,
  268. "app_id": app_id,
  269. "message_id": message_id,
  270. "data": {
  271. "provider": tool_provider_id.provider_name,
  272. "tool": tool,
  273. "credentials": credentials,
  274. },
  275. },
  276. headers={
  277. "X-Plugin-ID": tool_provider_id.plugin_id,
  278. "Content-Type": "application/json",
  279. },
  280. )
  281. for resp in response:
  282. return resp.parameters
  283. return []