tool_entities.py 13 KB

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