tool_entities.py 15 KB

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