您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

tool_entities.py 16KB

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