tool.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from collections.abc import Generator
  2. from typing import Any
  3. from core.callback_handler.workflow_tool_callback_handler import DifyWorkflowCallbackHandler
  4. from core.plugin.backwards_invocation.base import BaseBackwardsInvocation
  5. from core.tools.entities.tool_entities import ToolInvokeMessage, ToolProviderType
  6. from core.tools.tool_engine import ToolEngine
  7. from core.tools.tool_manager import ToolManager
  8. from core.tools.utils.message_transformer import ToolFileMessageTransformer
  9. class PluginToolBackwardsInvocation(BaseBackwardsInvocation):
  10. """
  11. Backwards invocation for plugin tools.
  12. """
  13. @classmethod
  14. def invoke_tool(
  15. cls,
  16. tenant_id: str,
  17. user_id: str,
  18. tool_type: ToolProviderType,
  19. provider: str,
  20. tool_name: str,
  21. tool_parameters: dict[str, Any],
  22. ) -> Generator[ToolInvokeMessage, None, None]:
  23. """
  24. invoke tool
  25. """
  26. # get tool runtime
  27. try:
  28. tool_runtime = ToolManager.get_tool_runtime_from_plugin(
  29. tool_type, tenant_id, provider, tool_name, tool_parameters
  30. )
  31. response = ToolEngine.generic_invoke(
  32. tool_runtime, tool_parameters, user_id, DifyWorkflowCallbackHandler(), workflow_call_depth=1
  33. )
  34. response = ToolFileMessageTransformer.transform_tool_invoke_messages(
  35. response, user_id=user_id, tenant_id=tenant_id
  36. )
  37. return response
  38. except Exception as e:
  39. raise e