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

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