tool_entities.py 16 KB

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