tool_entities.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. 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. @model_validator(mode="before")
  106. @classmethod
  107. def transform_variable_value(cls, values) -> Any:
  108. """
  109. Only basic types and lists are allowed.
  110. """
  111. value = values.get("variable_value")
  112. if not isinstance(value, dict | list | str | int | float | bool):
  113. raise ValueError("Only basic types and lists are allowed.")
  114. # if stream is true, the value must be a string
  115. if values.get("stream"):
  116. if not isinstance(value, str):
  117. raise ValueError("When 'stream' is True, 'variable_value' must be a string.")
  118. return values
  119. @field_validator("variable_name", mode="before")
  120. @classmethod
  121. def transform_variable_name(cls, value) -> str:
  122. """
  123. The variable name must be a string.
  124. """
  125. if value in {"json", "text", "files"}:
  126. raise ValueError(f"The variable name '{value}' is reserved.")
  127. return value
  128. class LogMessage(BaseModel):
  129. class LogStatus(Enum):
  130. START = "start"
  131. ERROR = "error"
  132. SUCCESS = "success"
  133. id: str
  134. label: str = Field(..., description="The label of the log")
  135. parent_id: Optional[str] = Field(default=None, description="Leave empty for root log")
  136. error: Optional[str] = Field(default=None, description="The error message")
  137. status: LogStatus = Field(..., description="The status of the log")
  138. data: Mapping[str, Any] = Field(..., description="Detailed log data")
  139. class MessageType(Enum):
  140. TEXT = "text"
  141. IMAGE = "image"
  142. LINK = "link"
  143. BLOB = "blob"
  144. JSON = "json"
  145. IMAGE_LINK = "image_link"
  146. BINARY_LINK = "binary_link"
  147. VARIABLE = "variable"
  148. FILE = "file"
  149. LOG = "log"
  150. type: MessageType = MessageType.TEXT
  151. """
  152. plain text, image url or link url
  153. """
  154. message: JsonMessage | TextMessage | BlobMessage | VariableMessage | FileMessage | LogMessage | None
  155. meta: dict[str, Any] | None = None
  156. @field_validator("message", mode="before")
  157. @classmethod
  158. def decode_blob_message(cls, v):
  159. if isinstance(v, dict) and "blob" in v:
  160. try:
  161. v["blob"] = base64.b64decode(v["blob"])
  162. except Exception:
  163. pass
  164. return v
  165. @field_serializer("message")
  166. def serialize_message(self, v):
  167. if isinstance(v, self.BlobMessage):
  168. return {"blob": base64.b64encode(v.blob).decode("utf-8")}
  169. return v
  170. class ToolInvokeMessageBinary(BaseModel):
  171. mimetype: str = Field(..., description="The mimetype of the binary")
  172. url: str = Field(..., description="The url of the binary")
  173. file_var: Optional[dict[str, Any]] = None
  174. class ToolParameter(PluginParameter):
  175. """
  176. Overrides type
  177. """
  178. class ToolParameterType(enum.StrEnum):
  179. """
  180. removes TOOLS_SELECTOR from PluginParameterType
  181. """
  182. STRING = PluginParameterType.STRING.value
  183. NUMBER = PluginParameterType.NUMBER.value
  184. BOOLEAN = PluginParameterType.BOOLEAN.value
  185. SELECT = PluginParameterType.SELECT.value
  186. SECRET_INPUT = PluginParameterType.SECRET_INPUT.value
  187. FILE = PluginParameterType.FILE.value
  188. FILES = PluginParameterType.FILES.value
  189. APP_SELECTOR = PluginParameterType.APP_SELECTOR.value
  190. MODEL_SELECTOR = PluginParameterType.MODEL_SELECTOR.value
  191. # deprecated, should not use.
  192. SYSTEM_FILES = PluginParameterType.SYSTEM_FILES.value
  193. def as_normal_type(self):
  194. return as_normal_type(self)
  195. def cast_value(self, value: Any):
  196. return cast_parameter_value(self, value)
  197. class ToolParameterForm(Enum):
  198. SCHEMA = "schema" # should be set while adding tool
  199. FORM = "form" # should be set before invoking tool
  200. LLM = "llm" # will be set by LLM
  201. type: ToolParameterType = Field(..., description="The type of the parameter")
  202. human_description: Optional[I18nObject] = Field(default=None, description="The description presented to the user")
  203. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  204. llm_description: Optional[str] = None
  205. @classmethod
  206. def get_simple_instance(
  207. cls,
  208. name: str,
  209. llm_description: str,
  210. typ: ToolParameterType,
  211. required: bool,
  212. options: Optional[list[str]] = None,
  213. ) -> "ToolParameter":
  214. """
  215. get a simple tool parameter
  216. :param name: the name of the parameter
  217. :param llm_description: the description presented to the LLM
  218. :param type: the type of the parameter
  219. :param required: if the parameter is required
  220. :param options: the options of the parameter
  221. """
  222. # convert options to ToolParameterOption
  223. # FIXME fix the type error
  224. if options:
  225. option_objs = [
  226. PluginParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option))
  227. for option in options
  228. ]
  229. else:
  230. option_objs = []
  231. return cls(
  232. name=name,
  233. label=I18nObject(en_US="", zh_Hans=""),
  234. placeholder=None,
  235. human_description=I18nObject(en_US="", zh_Hans=""),
  236. type=typ,
  237. form=cls.ToolParameterForm.LLM,
  238. llm_description=llm_description,
  239. required=required,
  240. options=option_objs,
  241. )
  242. def init_frontend_parameter(self, value: Any):
  243. return init_frontend_parameter(self, self.type, value)
  244. class ToolProviderIdentity(BaseModel):
  245. author: str = Field(..., description="The author of the tool")
  246. name: str = Field(..., description="The name of the tool")
  247. description: I18nObject = Field(..., description="The description of the tool")
  248. icon: str = Field(..., description="The icon of the tool")
  249. label: I18nObject = Field(..., description="The label of the tool")
  250. tags: Optional[list[ToolLabelEnum]] = Field(
  251. default=[],
  252. description="The tags of the tool",
  253. )
  254. class ToolIdentity(BaseModel):
  255. author: str = Field(..., description="The author of the tool")
  256. name: str = Field(..., description="The name of the tool")
  257. label: I18nObject = Field(..., description="The label of the tool")
  258. provider: str = Field(..., description="The provider of the tool")
  259. icon: Optional[str] = None
  260. class ToolDescription(BaseModel):
  261. human: I18nObject = Field(..., description="The description presented to the user")
  262. llm: str = Field(..., description="The description presented to the LLM")
  263. class ToolEntity(BaseModel):
  264. identity: ToolIdentity
  265. parameters: list[ToolParameter] = Field(default_factory=list)
  266. description: Optional[ToolDescription] = None
  267. output_schema: Optional[dict] = None
  268. has_runtime_parameters: bool = Field(default=False, description="Whether the tool has runtime parameters")
  269. # pydantic configs
  270. model_config = ConfigDict(protected_namespaces=())
  271. @field_validator("parameters", mode="before")
  272. @classmethod
  273. def set_parameters(cls, v, validation_info: ValidationInfo) -> list[ToolParameter]:
  274. return v or []
  275. class ToolProviderEntity(BaseModel):
  276. identity: ToolProviderIdentity
  277. plugin_id: Optional[str] = None
  278. credentials_schema: list[ProviderConfig] = Field(default_factory=list)
  279. class ToolProviderEntityWithPlugin(ToolProviderEntity):
  280. tools: list[ToolEntity] = Field(default_factory=list)
  281. class WorkflowToolParameterConfiguration(BaseModel):
  282. """
  283. Workflow tool configuration
  284. """
  285. name: str = Field(..., description="The name of the parameter")
  286. description: str = Field(..., description="The description of the parameter")
  287. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  288. class ToolInvokeMeta(BaseModel):
  289. """
  290. Tool invoke meta
  291. """
  292. time_cost: float = Field(..., description="The time cost of the tool invoke")
  293. error: Optional[str] = None
  294. tool_config: Optional[dict] = None
  295. @classmethod
  296. def empty(cls) -> "ToolInvokeMeta":
  297. """
  298. Get an empty instance of ToolInvokeMeta
  299. """
  300. return cls(time_cost=0.0, error=None, tool_config={})
  301. @classmethod
  302. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  303. """
  304. Get an instance of ToolInvokeMeta with error
  305. """
  306. return cls(time_cost=0.0, error=error, tool_config={})
  307. def to_dict(self) -> dict:
  308. return {
  309. "time_cost": self.time_cost,
  310. "error": self.error,
  311. "tool_config": self.tool_config,
  312. }
  313. class ToolLabel(BaseModel):
  314. """
  315. Tool label
  316. """
  317. name: str = Field(..., description="The name of the tool")
  318. label: I18nObject = Field(..., description="The label of the tool")
  319. icon: str = Field(..., description="The icon of the tool")
  320. class ToolInvokeFrom(Enum):
  321. """
  322. Enum class for tool invoke
  323. """
  324. WORKFLOW = "workflow"
  325. AGENT = "agent"
  326. PLUGIN = "plugin"
  327. class ToolSelector(BaseModel):
  328. dify_model_identity: str = TOOL_SELECTOR_MODEL_IDENTITY
  329. class Parameter(BaseModel):
  330. name: str = Field(..., description="The name of the parameter")
  331. type: ToolParameter.ToolParameterType = Field(..., description="The type of the parameter")
  332. required: bool = Field(..., description="Whether the parameter is required")
  333. description: str = Field(..., description="The description of the parameter")
  334. default: Optional[Union[int, float, str]] = None
  335. options: Optional[list[PluginParameterOption]] = None
  336. provider_id: str = Field(..., description="The id of the provider")
  337. tool_name: str = Field(..., description="The name of the tool")
  338. tool_description: str = Field(..., description="The description of the tool")
  339. tool_configuration: Mapping[str, Any] = Field(..., description="Configuration, type form")
  340. tool_parameters: Mapping[str, Parameter] = Field(..., description="Parameters, type llm")
  341. def to_plugin_parameter(self) -> dict[str, Any]:
  342. return self.model_dump()