tool_entities.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import base64
  2. import enum
  3. from enum import Enum
  4. from typing import Any, 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 MessageType(Enum):
  124. TEXT = "text"
  125. IMAGE = "image"
  126. LINK = "link"
  127. BLOB = "blob"
  128. JSON = "json"
  129. IMAGE_LINK = "image_link"
  130. VARIABLE = "variable"
  131. FILE = "file"
  132. type: MessageType = MessageType.TEXT
  133. """
  134. plain text, image url or link url
  135. """
  136. message: JsonMessage | TextMessage | BlobMessage | VariableMessage | FileMessage | None
  137. meta: dict[str, Any] | None = None
  138. @field_validator("message", mode="before")
  139. @classmethod
  140. def decode_blob_message(cls, v):
  141. if isinstance(v, dict) and "blob" in v:
  142. try:
  143. v["blob"] = base64.b64decode(v["blob"])
  144. except Exception:
  145. pass
  146. return v
  147. @field_serializer("message")
  148. def serialize_message(self, v):
  149. if isinstance(v, self.BlobMessage):
  150. return {"blob": base64.b64encode(v.blob).decode("utf-8")}
  151. return v
  152. class ToolInvokeMessageBinary(BaseModel):
  153. mimetype: str = Field(..., description="The mimetype of the binary")
  154. url: str = Field(..., description="The url of the binary")
  155. file_var: Optional[dict[str, Any]] = None
  156. class ToolParameterOption(BaseModel):
  157. value: str = Field(..., description="The value of the option")
  158. label: I18nObject = Field(..., description="The label of the option")
  159. @field_validator("value", mode="before")
  160. @classmethod
  161. def transform_id_to_str(cls, value) -> str:
  162. if not isinstance(value, str):
  163. return str(value)
  164. else:
  165. return value
  166. class ToolParameter(BaseModel):
  167. class ToolParameterType(enum.StrEnum):
  168. STRING = CommonParameterType.STRING.value
  169. NUMBER = CommonParameterType.NUMBER.value
  170. BOOLEAN = CommonParameterType.BOOLEAN.value
  171. SELECT = CommonParameterType.SELECT.value
  172. SECRET_INPUT = CommonParameterType.SECRET_INPUT.value
  173. FILE = CommonParameterType.FILE.value
  174. FILES = CommonParameterType.FILES.value
  175. APP_SELECTOR = CommonParameterType.APP_SELECTOR.value
  176. TOOL_SELECTOR = CommonParameterType.TOOL_SELECTOR.value
  177. MODEL_SELECTOR = CommonParameterType.MODEL_SELECTOR.value
  178. # deprecated, should not use.
  179. SYSTEM_FILES = CommonParameterType.SYSTEM_FILES.value
  180. def as_normal_type(self):
  181. if self in {
  182. ToolParameter.ToolParameterType.SECRET_INPUT,
  183. ToolParameter.ToolParameterType.SELECT,
  184. }:
  185. return "string"
  186. return self.value
  187. def cast_value(self, value: Any, /):
  188. try:
  189. match self:
  190. case (
  191. ToolParameter.ToolParameterType.STRING
  192. | ToolParameter.ToolParameterType.SECRET_INPUT
  193. | ToolParameter.ToolParameterType.SELECT
  194. ):
  195. if value is None:
  196. return ""
  197. else:
  198. return value if isinstance(value, str) else str(value)
  199. case ToolParameter.ToolParameterType.BOOLEAN:
  200. if value is None:
  201. return False
  202. elif isinstance(value, str):
  203. # Allowed YAML boolean value strings: https://yaml.org/type/bool.html
  204. # and also '0' for False and '1' for True
  205. match value.lower():
  206. case "true" | "yes" | "y" | "1":
  207. return True
  208. case "false" | "no" | "n" | "0":
  209. return False
  210. case _:
  211. return bool(value)
  212. else:
  213. return value if isinstance(value, bool) else bool(value)
  214. case ToolParameter.ToolParameterType.NUMBER:
  215. if isinstance(value, int | float):
  216. return value
  217. elif isinstance(value, str) and value:
  218. if "." in value:
  219. return float(value)
  220. else:
  221. return int(value)
  222. case ToolParameter.ToolParameterType.SYSTEM_FILES | ToolParameter.ToolParameterType.FILES:
  223. if not isinstance(value, list):
  224. return [value]
  225. return value
  226. case ToolParameter.ToolParameterType.FILE:
  227. if isinstance(value, list):
  228. if len(value) != 1:
  229. raise ValueError(
  230. "This parameter only accepts one file but got multiple files while invoking."
  231. )
  232. else:
  233. return value[0]
  234. return value
  235. case (
  236. ToolParameter.ToolParameterType.TOOL_SELECTOR
  237. | ToolParameter.ToolParameterType.MODEL_SELECTOR
  238. | ToolParameter.ToolParameterType.APP_SELECTOR
  239. ):
  240. if not isinstance(value, dict):
  241. raise ValueError("The selector must be a dictionary.")
  242. return value
  243. case _:
  244. return str(value)
  245. except Exception:
  246. raise ValueError(f"The tool parameter value {value} is not in correct type of {self.as_normal_type()}.")
  247. class ToolParameterForm(Enum):
  248. SCHEMA = "schema" # should be set while adding tool
  249. FORM = "form" # should be set before invoking tool
  250. LLM = "llm" # will be set by LLM
  251. name: str = Field(..., description="The name of the parameter")
  252. label: I18nObject = Field(..., description="The label presented to the user")
  253. human_description: Optional[I18nObject] = Field(default=None, description="The description presented to the user")
  254. placeholder: Optional[I18nObject] = Field(default=None, description="The placeholder presented to the user")
  255. type: ToolParameterType = Field(..., description="The type of the parameter")
  256. scope: AppSelectorScope | ModelSelectorScope | ToolSelectorScope | None = None
  257. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  258. llm_description: Optional[str] = None
  259. required: Optional[bool] = False
  260. default: Optional[Union[float, int, str]] = None
  261. min: Optional[Union[float, int]] = None
  262. max: Optional[Union[float, int]] = None
  263. options: list[ToolParameterOption] = Field(default_factory=list)
  264. @field_validator("options", mode="before")
  265. @classmethod
  266. def transform_options(cls, v):
  267. if not isinstance(v, list):
  268. return []
  269. return v
  270. @classmethod
  271. def get_simple_instance(
  272. cls,
  273. name: str,
  274. llm_description: str,
  275. type: ToolParameterType,
  276. required: bool,
  277. options: Optional[list[str]] = None,
  278. ) -> "ToolParameter":
  279. """
  280. get a simple tool parameter
  281. :param name: the name of the parameter
  282. :param llm_description: the description presented to the LLM
  283. :param type: the type of the parameter
  284. :param required: if the parameter is required
  285. :param options: the options of the parameter
  286. """
  287. # convert options to ToolParameterOption
  288. if options:
  289. option_objs = [
  290. ToolParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options
  291. ]
  292. else:
  293. option_objs = []
  294. return cls(
  295. name=name,
  296. label=I18nObject(en_US="", zh_Hans=""),
  297. placeholder=None,
  298. human_description=I18nObject(en_US="", zh_Hans=""),
  299. type=type,
  300. form=cls.ToolParameterForm.LLM,
  301. llm_description=llm_description,
  302. required=required,
  303. options=option_objs,
  304. )
  305. class ToolProviderIdentity(BaseModel):
  306. author: str = Field(..., description="The author of the tool")
  307. name: str = Field(..., description="The name of the tool")
  308. description: I18nObject = Field(..., description="The description of the tool")
  309. icon: str = Field(..., description="The icon of the tool")
  310. label: I18nObject = Field(..., description="The label of the tool")
  311. tags: Optional[list[ToolLabelEnum]] = Field(
  312. default=[],
  313. description="The tags of the tool",
  314. )
  315. class ToolIdentity(BaseModel):
  316. author: str = Field(..., description="The author of the tool")
  317. name: str = Field(..., description="The name of the tool")
  318. label: I18nObject = Field(..., description="The label of the tool")
  319. provider: str = Field(..., description="The provider of the tool")
  320. icon: Optional[str] = None
  321. class ToolDescription(BaseModel):
  322. human: I18nObject = Field(..., description="The description presented to the user")
  323. llm: str = Field(..., description="The description presented to the LLM")
  324. class ToolEntity(BaseModel):
  325. identity: ToolIdentity
  326. parameters: list[ToolParameter] = Field(default_factory=list)
  327. description: Optional[ToolDescription] = None
  328. output_schema: Optional[dict] = None
  329. has_runtime_parameters: bool = Field(default=False, description="Whether the tool has runtime parameters")
  330. # pydantic configs
  331. model_config = ConfigDict(protected_namespaces=())
  332. @field_validator("parameters", mode="before")
  333. @classmethod
  334. def set_parameters(cls, v, validation_info: ValidationInfo) -> list[ToolParameter]:
  335. return v or []
  336. class ToolProviderEntity(BaseModel):
  337. identity: ToolProviderIdentity
  338. plugin_id: Optional[str] = Field(None, description="The id of the plugin")
  339. credentials_schema: list[ProviderConfig] = Field(default_factory=list)
  340. class ToolProviderEntityWithPlugin(ToolProviderEntity):
  341. tools: list[ToolEntity] = Field(default_factory=list)
  342. class WorkflowToolParameterConfiguration(BaseModel):
  343. """
  344. Workflow tool configuration
  345. """
  346. name: str = Field(..., description="The name of the parameter")
  347. description: str = Field(..., description="The description of the parameter")
  348. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  349. class ToolInvokeMeta(BaseModel):
  350. """
  351. Tool invoke meta
  352. """
  353. time_cost: float = Field(..., description="The time cost of the tool invoke")
  354. error: Optional[str] = None
  355. tool_config: Optional[dict] = None
  356. @classmethod
  357. def empty(cls) -> "ToolInvokeMeta":
  358. """
  359. Get an empty instance of ToolInvokeMeta
  360. """
  361. return cls(time_cost=0.0, error=None, tool_config={})
  362. @classmethod
  363. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  364. """
  365. Get an instance of ToolInvokeMeta with error
  366. """
  367. return cls(time_cost=0.0, error=error, tool_config={})
  368. def to_dict(self) -> dict:
  369. return {
  370. "time_cost": self.time_cost,
  371. "error": self.error,
  372. "tool_config": self.tool_config,
  373. }
  374. class ToolLabel(BaseModel):
  375. """
  376. Tool label
  377. """
  378. name: str = Field(..., description="The name of the tool")
  379. label: I18nObject = Field(..., description="The label of the tool")
  380. icon: str = Field(..., description="The icon of the tool")
  381. class ToolInvokeFrom(Enum):
  382. """
  383. Enum class for tool invoke
  384. """
  385. WORKFLOW = "workflow"
  386. AGENT = "agent"
  387. PLUGIN = "plugin"