您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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