tool.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. from collections.abc import Generator
  2. from typing import Any
  3. from core.plugin.entities.plugin_daemon import PluginBasicBooleanResponse, PluginToolProviderEntity
  4. from core.plugin.manager.base import BasePluginManager
  5. from core.tools.entities.tool_entities import ToolInvokeMessage
  6. class PluginToolManager(BasePluginManager):
  7. def fetch_tool_providers(self, tenant_id: str) -> list[PluginToolProviderEntity]:
  8. """
  9. Fetch tool providers for the given asset.
  10. """
  11. def transformer(json_response: dict[str, Any]) -> dict:
  12. for provider in json_response.get("data", []):
  13. declaration = provider.get("declaration", {}) or {}
  14. provider_name = declaration.get("identity", {}).get("name")
  15. for tool in declaration.get("tools", []):
  16. tool["identity"]["provider"] = provider_name
  17. return json_response
  18. response = self._request_with_plugin_daemon_response(
  19. "GET",
  20. f"plugin/{tenant_id}/management/tools",
  21. list[PluginToolProviderEntity],
  22. params={"page": 1, "page_size": 256},
  23. transformer=transformer,
  24. )
  25. return response
  26. def invoke(
  27. self,
  28. tenant_id: str,
  29. user_id: str,
  30. plugin_unique_identifier: str,
  31. tool_provider: str,
  32. tool_name: str,
  33. credentials: dict[str, Any],
  34. tool_parameters: dict[str, Any],
  35. ) -> Generator[ToolInvokeMessage, None, None]:
  36. response = self._request_with_plugin_daemon_response_stream(
  37. "POST",
  38. f"plugin/{tenant_id}/dispatch/tool/invoke",
  39. ToolInvokeMessage,
  40. data={
  41. "plugin_unique_identifier": plugin_unique_identifier,
  42. "user_id": user_id,
  43. "data": {
  44. "provider": tool_provider,
  45. "tool": tool_name,
  46. "credentials": credentials,
  47. "tool_parameters": tool_parameters,
  48. },
  49. },
  50. headers={
  51. "X-Plugin-Identifier": plugin_unique_identifier,
  52. "Content-Type": "application/json",
  53. }
  54. )
  55. return response
  56. def validate_provider_credentials(
  57. self, tenant_id: str, user_id: str, plugin_unique_identifier: str, provider: str, credentials: dict[str, Any]
  58. ) -> bool:
  59. """
  60. validate the credentials of the provider
  61. """
  62. response = self._request_with_plugin_daemon_response_stream(
  63. "POST",
  64. f"plugin/{tenant_id}/dispatch/tool/validate_credentials",
  65. PluginBasicBooleanResponse,
  66. data={
  67. "plugin_unique_identifier": plugin_unique_identifier,
  68. "user_id": user_id,
  69. "data": {
  70. "provider": provider,
  71. "credentials": credentials,
  72. },
  73. },
  74. headers={
  75. "X-Plugin-Identifier": plugin_unique_identifier,
  76. "Content-Type": "application/json",
  77. }
  78. )
  79. for resp in response:
  80. return resp.result
  81. return False