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_entities.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import base64
  2. import enum
  3. from collections.abc import Mapping
  4. from enum import Enum
  5. from typing import Any, Optional, Union
  6. from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_serializer, field_validator, model_validator
  7. from core.entities.provider_entities import ProviderConfig
  8. from core.plugin.entities.parameters import (
  9. MCPServerParameterType,
  10. PluginParameter,
  11. PluginParameterOption,
  12. PluginParameterType,
  13. as_normal_type,
  14. cast_parameter_value,
  15. init_frontend_parameter,
  16. )
  17. from core.tools.entities.common_entities import I18nObject
  18. from core.tools.entities.constants import TOOL_SELECTOR_MODEL_IDENTITY
  19. class ToolLabelEnum(Enum):
  20. SEARCH = "search"
  21. IMAGE = "image"
  22. VIDEOS = "videos"
  23. WEATHER = "weather"
  24. FINANCE = "finance"
  25. DESIGN = "design"
  26. TRAVEL = "travel"
  27. SOCIAL = "social"
  28. NEWS = "news"
  29. MEDICAL = "medical"
  30. PRODUCTIVITY = "productivity"
  31. EDUCATION = "education"
  32. BUSINESS = "business"
  33. ENTERTAINMENT = "entertainment"
  34. UTILITIES = "utilities"
  35. OTHER = "other"
  36. class ToolProviderType(enum.StrEnum):
  37. """
  38. Enum class for tool provider
  39. """
  40. PLUGIN = "plugin"
  41. BUILT_IN = "builtin"
  42. WORKFLOW = "workflow"
  43. API = "api"
  44. APP = "app"
  45. DATASET_RETRIEVAL = "dataset-retrieval"
  46. MCP = "mcp"
  47. @classmethod
  48. def value_of(cls, value: str) -> "ToolProviderType":
  49. """
  50. Get value of given mode.
  51. :param value: mode value
  52. :return: mode
  53. """
  54. for mode in cls:
  55. if mode.value == value:
  56. return mode
  57. raise ValueError(f"invalid mode value {value}")
  58. class ApiProviderSchemaType(Enum):
  59. """
  60. Enum class for api provider schema type.
  61. """
  62. OPENAPI = "openapi"
  63. SWAGGER = "swagger"
  64. OPENAI_PLUGIN = "openai_plugin"
  65. OPENAI_ACTIONS = "openai_actions"
  66. @classmethod
  67. def value_of(cls, value: str) -> "ApiProviderSchemaType":
  68. """
  69. Get value of given mode.
  70. :param value: mode value
  71. :return: mode
  72. """
  73. for mode in cls:
  74. if mode.value == value:
  75. return mode
  76. raise ValueError(f"invalid mode value {value}")
  77. class ApiProviderAuthType(Enum):
  78. """
  79. Enum class for api provider auth type.
  80. """
  81. NONE = "none"
  82. API_KEY = "api_key"
  83. @classmethod
  84. def value_of(cls, value: str) -> "ApiProviderAuthType":
  85. """
  86. Get value of given mode.
  87. :param value: mode value
  88. :return: mode
  89. """
  90. for mode in cls:
  91. if mode.value == value:
  92. return mode
  93. raise ValueError(f"invalid mode value {value}")
  94. class ToolInvokeMessage(BaseModel):
  95. class TextMessage(BaseModel):
  96. text: str
  97. class JsonMessage(BaseModel):
  98. json_object: dict
  99. class BlobMessage(BaseModel):
  100. blob: bytes
  101. class BlobChunkMessage(BaseModel):
  102. id: str = Field(..., description="The id of the blob")
  103. sequence: int = Field(..., description="The sequence of the chunk")
  104. total_length: int = Field(..., description="The total length of the blob")
  105. blob: bytes = Field(..., description="The blob data of the chunk")
  106. end: bool = Field(..., description="Whether the chunk is the last chunk")
  107. class FileMessage(BaseModel):
  108. pass
  109. class VariableMessage(BaseModel):
  110. variable_name: str = Field(..., description="The name of the variable")
  111. variable_value: Any = Field(..., description="The value of the variable")
  112. stream: bool = Field(default=False, description="Whether the variable is streamed")
  113. @model_validator(mode="before")
  114. @classmethod
  115. def transform_variable_value(cls, values) -> Any:
  116. """
  117. Only basic types and lists are allowed.
  118. """
  119. value = values.get("variable_value")
  120. if not isinstance(value, dict | list | str | int | float | bool):
  121. raise ValueError("Only basic types and lists are allowed.")
  122. # if stream is true, the value must be a string
  123. if values.get("stream"):
  124. if not isinstance(value, str):
  125. raise ValueError("When 'stream' is True, 'variable_value' must be a string.")
  126. return values
  127. @field_validator("variable_name", mode="before")
  128. @classmethod
  129. def transform_variable_name(cls, value: str) -> str:
  130. """
  131. The variable name must be a string.
  132. """
  133. if value in {"json", "text", "files"}:
  134. raise ValueError(f"The variable name '{value}' is reserved.")
  135. return value
  136. class LogMessage(BaseModel):
  137. class LogStatus(Enum):
  138. START = "start"
  139. ERROR = "error"
  140. SUCCESS = "success"
  141. id: str
  142. label: str = Field(..., description="The label of the log")
  143. parent_id: Optional[str] = Field(default=None, description="Leave empty for root log")
  144. error: Optional[str] = Field(default=None, description="The error message")
  145. status: LogStatus = Field(..., description="The status of the log")
  146. data: Mapping[str, Any] = Field(..., description="Detailed log data")
  147. metadata: Optional[Mapping[str, Any]] = Field(default=None, description="The metadata of the log")
  148. class MessageType(Enum):
  149. TEXT = "text"
  150. IMAGE = "image"
  151. LINK = "link"
  152. BLOB = "blob"
  153. JSON = "json"
  154. IMAGE_LINK = "image_link"
  155. BINARY_LINK = "binary_link"
  156. VARIABLE = "variable"
  157. FILE = "file"
  158. LOG = "log"
  159. BLOB_CHUNK = "blob_chunk"
  160. type: MessageType = MessageType.TEXT
  161. """
  162. plain text, image url or link url
  163. """
  164. message: (
  165. JsonMessage | TextMessage | BlobChunkMessage | BlobMessage | LogMessage | FileMessage | None | VariableMessage
  166. )
  167. meta: dict[str, Any] | None = None
  168. @field_validator("message", mode="before")
  169. @classmethod
  170. def decode_blob_message(cls, v):
  171. if isinstance(v, dict) and "blob" in v:
  172. try:
  173. v["blob"] = base64.b64decode(v["blob"])
  174. except Exception:
  175. pass
  176. return v
  177. @field_serializer("message")
  178. def serialize_message(self, v):
  179. if isinstance(v, self.BlobMessage):
  180. return {"blob": base64.b64encode(v.blob).decode("utf-8")}
  181. return v
  182. class ToolInvokeMessageBinary(BaseModel):
  183. mimetype: str = Field(..., description="The mimetype of the binary")
  184. url: str = Field(..., description="The url of the binary")
  185. file_var: Optional[dict[str, Any]] = None
  186. class ToolParameter(PluginParameter):
  187. """
  188. Overrides type
  189. """
  190. class ToolParameterType(enum.StrEnum):
  191. """
  192. removes TOOLS_SELECTOR from PluginParameterType
  193. """
  194. STRING = PluginParameterType.STRING.value
  195. NUMBER = PluginParameterType.NUMBER.value
  196. BOOLEAN = PluginParameterType.BOOLEAN.value
  197. SELECT = PluginParameterType.SELECT.value
  198. SECRET_INPUT = PluginParameterType.SECRET_INPUT.value
  199. FILE = PluginParameterType.FILE.value
  200. FILES = PluginParameterType.FILES.value
  201. APP_SELECTOR = PluginParameterType.APP_SELECTOR.value
  202. MODEL_SELECTOR = PluginParameterType.MODEL_SELECTOR.value
  203. DYNAMIC_SELECT = PluginParameterType.DYNAMIC_SELECT.value
  204. # MCP object and array type parameters
  205. ARRAY = MCPServerParameterType.ARRAY.value
  206. OBJECT = MCPServerParameterType.OBJECT.value
  207. # deprecated, should not use.
  208. SYSTEM_FILES = PluginParameterType.SYSTEM_FILES.value
  209. def as_normal_type(self):
  210. return as_normal_type(self)
  211. def cast_value(self, value: Any):
  212. return cast_parameter_value(self, value)
  213. class ToolParameterForm(Enum):
  214. SCHEMA = "schema" # should be set while adding tool
  215. FORM = "form" # should be set before invoking tool
  216. LLM = "llm" # will be set by LLM
  217. type: ToolParameterType = Field(..., description="The type of the parameter")
  218. human_description: Optional[I18nObject] = Field(default=None, description="The description presented to the user")
  219. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  220. llm_description: Optional[str] = None
  221. # MCP object and array type parameters use this field to store the schema
  222. input_schema: Optional[dict] = None
  223. @classmethod
  224. def get_simple_instance(
  225. cls,
  226. name: str,
  227. llm_description: str,
  228. typ: ToolParameterType,
  229. required: bool,
  230. options: Optional[list[str]] = None,
  231. ) -> "ToolParameter":
  232. """
  233. get a simple tool parameter
  234. :param name: the name of the parameter
  235. :param llm_description: the description presented to the LLM
  236. :param typ: the type of the parameter
  237. :param required: if the parameter is required
  238. :param options: the options of the parameter
  239. """
  240. # convert options to ToolParameterOption
  241. if options:
  242. option_objs = [
  243. PluginParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option))
  244. for option in options
  245. ]
  246. else:
  247. option_objs = []
  248. return cls(
  249. name=name,
  250. label=I18nObject(en_US="", zh_Hans=""),
  251. placeholder=None,
  252. human_description=I18nObject(en_US="", zh_Hans=""),
  253. type=typ,
  254. form=cls.ToolParameterForm.LLM,
  255. llm_description=llm_description,
  256. required=required,
  257. options=option_objs,
  258. )
  259. def init_frontend_parameter(self, value: Any):
  260. return init_frontend_parameter(self, self.type, value)
  261. class ToolProviderIdentity(BaseModel):
  262. author: str = Field(..., description="The author of the tool")
  263. name: str = Field(..., description="The name of the tool")
  264. description: I18nObject = Field(..., description="The description of the tool")
  265. icon: str = Field(..., description="The icon of the tool")
  266. label: I18nObject = Field(..., description="The label of the tool")
  267. tags: Optional[list[ToolLabelEnum]] = Field(
  268. default=[],
  269. description="The tags of the tool",
  270. )
  271. class ToolIdentity(BaseModel):
  272. author: str = Field(..., description="The author of the tool")
  273. name: str = Field(..., description="The name of the tool")
  274. label: I18nObject = Field(..., description="The label of the tool")
  275. provider: str = Field(..., description="The provider of the tool")
  276. icon: Optional[str] = None
  277. class ToolDescription(BaseModel):
  278. human: I18nObject = Field(..., description="The description presented to the user")
  279. llm: str = Field(..., description="The description presented to the LLM")
  280. class ToolEntity(BaseModel):
  281. identity: ToolIdentity
  282. parameters: list[ToolParameter] = Field(default_factory=list)
  283. description: Optional[ToolDescription] = None
  284. output_schema: Optional[dict] = None
  285. has_runtime_parameters: bool = Field(default=False, description="Whether the tool has runtime parameters")
  286. # pydantic configs
  287. model_config = ConfigDict(protected_namespaces=())
  288. @field_validator("parameters", mode="before")
  289. @classmethod
  290. def set_parameters(cls, v, validation_info: ValidationInfo) -> list[ToolParameter]:
  291. return v or []
  292. class ToolProviderEntity(BaseModel):
  293. identity: ToolProviderIdentity
  294. plugin_id: Optional[str] = None
  295. credentials_schema: list[ProviderConfig] = Field(default_factory=list)
  296. class ToolProviderEntityWithPlugin(ToolProviderEntity):
  297. tools: list[ToolEntity] = Field(default_factory=list)
  298. class WorkflowToolParameterConfiguration(BaseModel):
  299. """
  300. Workflow tool configuration
  301. """
  302. name: str = Field(..., description="The name of the parameter")
  303. description: str = Field(..., description="The description of the parameter")
  304. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  305. class ToolInvokeMeta(BaseModel):
  306. """
  307. Tool invoke meta
  308. """
  309. time_cost: float = Field(..., description="The time cost of the tool invoke")
  310. error: Optional[str] = None
  311. tool_config: Optional[dict] = None
  312. @classmethod
  313. def empty(cls) -> "ToolInvokeMeta":
  314. """
  315. Get an empty instance of ToolInvokeMeta
  316. """
  317. return cls(time_cost=0.0, error=None, tool_config={})
  318. @classmethod
  319. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  320. """
  321. Get an instance of ToolInvokeMeta with error
  322. """
  323. return cls(time_cost=0.0, error=error, tool_config={})
  324. def to_dict(self) -> dict:
  325. return {
  326. "time_cost": self.time_cost,
  327. "error": self.error,
  328. "tool_config": self.tool_config,
  329. }
  330. class ToolLabel(BaseModel):
  331. """
  332. Tool label
  333. """
  334. name: str = Field(..., description="The name of the tool")
  335. label: I18nObject = Field(..., description="The label of the tool")
  336. icon: str = Field(..., description="The icon of the tool")
  337. class ToolInvokeFrom(Enum):
  338. """
  339. Enum class for tool invoke
  340. """
  341. WORKFLOW = "workflow"
  342. AGENT = "agent"
  343. PLUGIN = "plugin"
  344. class ToolSelector(BaseModel):
  345. dify_model_identity: str = TOOL_SELECTOR_MODEL_IDENTITY
  346. class Parameter(BaseModel):
  347. name: str = Field(..., description="The name of the parameter")
  348. type: ToolParameter.ToolParameterType = Field(..., description="The type of the parameter")
  349. required: bool = Field(..., description="Whether the parameter is required")
  350. description: str = Field(..., description="The description of the parameter")
  351. default: Optional[Union[int, float, str]] = None
  352. options: Optional[list[PluginParameterOption]] = None
  353. provider_id: str = Field(..., description="The id of the provider")
  354. tool_name: str = Field(..., description="The name of the tool")
  355. tool_description: str = Field(..., description="The description of the tool")
  356. tool_configuration: Mapping[str, Any] = Field(..., description="Configuration, type form")
  357. tool_parameters: Mapping[str, Parameter] = Field(..., description="Parameters, type llm")
  358. def to_plugin_parameter(self) -> dict[str, Any]:
  359. return self.model_dump()