Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

tool_entities.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. # deprecated, should not use.
  202. SYSTEM_FILES = PluginParameterType.SYSTEM_FILES.value
  203. def as_normal_type(self):
  204. return as_normal_type(self)
  205. def cast_value(self, value: Any):
  206. return cast_parameter_value(self, value)
  207. class ToolParameterForm(Enum):
  208. SCHEMA = "schema" # should be set while adding tool
  209. FORM = "form" # should be set before invoking tool
  210. LLM = "llm" # will be set by LLM
  211. type: ToolParameterType = Field(..., description="The type of the parameter")
  212. human_description: Optional[I18nObject] = Field(default=None, description="The description presented to the user")
  213. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  214. llm_description: Optional[str] = None
  215. @classmethod
  216. def get_simple_instance(
  217. cls,
  218. name: str,
  219. llm_description: str,
  220. typ: ToolParameterType,
  221. required: bool,
  222. options: Optional[list[str]] = None,
  223. ) -> "ToolParameter":
  224. """
  225. get a simple tool parameter
  226. :param name: the name of the parameter
  227. :param llm_description: the description presented to the LLM
  228. :param typ: the type of the parameter
  229. :param required: if the parameter is required
  230. :param options: the options of the parameter
  231. """
  232. # convert options to ToolParameterOption
  233. if options:
  234. option_objs = [
  235. PluginParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option))
  236. for option in options
  237. ]
  238. else:
  239. option_objs = []
  240. return cls(
  241. name=name,
  242. label=I18nObject(en_US="", zh_Hans=""),
  243. placeholder=None,
  244. human_description=I18nObject(en_US="", zh_Hans=""),
  245. type=typ,
  246. form=cls.ToolParameterForm.LLM,
  247. llm_description=llm_description,
  248. required=required,
  249. options=option_objs,
  250. )
  251. def init_frontend_parameter(self, value: Any):
  252. return init_frontend_parameter(self, self.type, value)
  253. class ToolProviderIdentity(BaseModel):
  254. author: str = Field(..., description="The author of the tool")
  255. name: str = Field(..., description="The name of the tool")
  256. description: I18nObject = Field(..., description="The description of the tool")
  257. icon: str = Field(..., description="The icon of the tool")
  258. label: I18nObject = Field(..., description="The label of the tool")
  259. tags: Optional[list[ToolLabelEnum]] = Field(
  260. default=[],
  261. description="The tags of the tool",
  262. )
  263. class ToolIdentity(BaseModel):
  264. author: str = Field(..., description="The author of the tool")
  265. name: str = Field(..., description="The name of the tool")
  266. label: I18nObject = Field(..., description="The label of the tool")
  267. provider: str = Field(..., description="The provider of the tool")
  268. icon: Optional[str] = None
  269. class ToolDescription(BaseModel):
  270. human: I18nObject = Field(..., description="The description presented to the user")
  271. llm: str = Field(..., description="The description presented to the LLM")
  272. class ToolEntity(BaseModel):
  273. identity: ToolIdentity
  274. parameters: list[ToolParameter] = Field(default_factory=list)
  275. description: Optional[ToolDescription] = None
  276. output_schema: Optional[dict] = None
  277. has_runtime_parameters: bool = Field(default=False, description="Whether the tool has runtime parameters")
  278. # pydantic configs
  279. model_config = ConfigDict(protected_namespaces=())
  280. @field_validator("parameters", mode="before")
  281. @classmethod
  282. def set_parameters(cls, v, validation_info: ValidationInfo) -> list[ToolParameter]:
  283. return v or []
  284. class ToolProviderEntity(BaseModel):
  285. identity: ToolProviderIdentity
  286. plugin_id: Optional[str] = None
  287. credentials_schema: list[ProviderConfig] = Field(default_factory=list)
  288. class ToolProviderEntityWithPlugin(ToolProviderEntity):
  289. tools: list[ToolEntity] = Field(default_factory=list)
  290. class WorkflowToolParameterConfiguration(BaseModel):
  291. """
  292. Workflow tool configuration
  293. """
  294. name: str = Field(..., description="The name of the parameter")
  295. description: str = Field(..., description="The description of the parameter")
  296. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  297. class ToolInvokeMeta(BaseModel):
  298. """
  299. Tool invoke meta
  300. """
  301. time_cost: float = Field(..., description="The time cost of the tool invoke")
  302. error: Optional[str] = None
  303. tool_config: Optional[dict] = None
  304. @classmethod
  305. def empty(cls) -> "ToolInvokeMeta":
  306. """
  307. Get an empty instance of ToolInvokeMeta
  308. """
  309. return cls(time_cost=0.0, error=None, tool_config={})
  310. @classmethod
  311. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  312. """
  313. Get an instance of ToolInvokeMeta with error
  314. """
  315. return cls(time_cost=0.0, error=error, tool_config={})
  316. def to_dict(self) -> dict:
  317. return {
  318. "time_cost": self.time_cost,
  319. "error": self.error,
  320. "tool_config": self.tool_config,
  321. }
  322. class ToolLabel(BaseModel):
  323. """
  324. Tool label
  325. """
  326. name: str = Field(..., description="The name of the tool")
  327. label: I18nObject = Field(..., description="The label of the tool")
  328. icon: str = Field(..., description="The icon of the tool")
  329. class ToolInvokeFrom(Enum):
  330. """
  331. Enum class for tool invoke
  332. """
  333. WORKFLOW = "workflow"
  334. AGENT = "agent"
  335. PLUGIN = "plugin"
  336. class ToolSelector(BaseModel):
  337. dify_model_identity: str = TOOL_SELECTOR_MODEL_IDENTITY
  338. class Parameter(BaseModel):
  339. name: str = Field(..., description="The name of the parameter")
  340. type: ToolParameter.ToolParameterType = Field(..., description="The type of the parameter")
  341. required: bool = Field(..., description="Whether the parameter is required")
  342. description: str = Field(..., description="The description of the parameter")
  343. default: Optional[Union[int, float, str]] = None
  344. options: Optional[list[PluginParameterOption]] = None
  345. provider_id: str = Field(..., description="The id of the provider")
  346. tool_name: str = Field(..., description="The name of the tool")
  347. tool_description: str = Field(..., description="The description of the tool")
  348. tool_configuration: Mapping[str, Any] = Field(..., description="Configuration, type form")
  349. tool_parameters: Mapping[str, Parameter] = Field(..., description="Parameters, type llm")
  350. def to_plugin_parameter(self) -> dict[str, Any]:
  351. return self.model_dump()