tool_entities.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 VariableMessage(BaseModel):
  91. variable_name: str = Field(..., description="The name of the variable")
  92. variable_value: str = Field(..., description="The value of the variable")
  93. stream: bool = Field(default=False, description="Whether the variable is streamed")
  94. @field_validator("variable_value", mode="before")
  95. @classmethod
  96. def transform_variable_value(cls, value, values) -> Any:
  97. """
  98. Only basic types and lists are allowed.
  99. """
  100. if not isinstance(value, dict | list | str | int | float | bool):
  101. raise ValueError("Only basic types and lists are allowed.")
  102. # if stream is true, the value must be a string
  103. if values.get("stream"):
  104. if not isinstance(value, str):
  105. raise ValueError("When 'stream' is True, 'variable_value' must be a string.")
  106. return value
  107. @field_validator("variable_name", mode="before")
  108. @classmethod
  109. def transform_variable_name(cls, value) -> str:
  110. """
  111. The variable name must be a string.
  112. """
  113. if value in {"json", "text", "files"}:
  114. raise ValueError(f"The variable name '{value}' is reserved.")
  115. return value
  116. class MessageType(Enum):
  117. TEXT = "text"
  118. IMAGE = "image"
  119. LINK = "link"
  120. BLOB = "blob"
  121. JSON = "json"
  122. IMAGE_LINK = "image_link"
  123. FILE_VAR = "file_var"
  124. VARIABLE = "variable"
  125. type: MessageType = MessageType.TEXT
  126. """
  127. plain text, image url or link url
  128. """
  129. message: JsonMessage | TextMessage | BlobMessage | VariableMessage | None
  130. meta: dict[str, Any] | None = None
  131. save_as: str = ""
  132. @field_validator("message", mode="before")
  133. @classmethod
  134. def decode_blob_message(cls, v):
  135. if isinstance(v, dict) and "blob" in v:
  136. try:
  137. v["blob"] = base64.b64decode(v["blob"])
  138. except Exception:
  139. pass
  140. return v
  141. @field_serializer("message")
  142. def serialize_message(self, v):
  143. if isinstance(v, self.BlobMessage):
  144. return {"blob": base64.b64encode(v.blob).decode("utf-8")}
  145. return v
  146. class ToolInvokeMessageBinary(BaseModel):
  147. mimetype: str = Field(..., description="The mimetype of the binary")
  148. url: str = Field(..., description="The url of the binary")
  149. save_as: str = ""
  150. file_var: Optional[dict[str, Any]] = None
  151. class ToolParameterOption(BaseModel):
  152. value: str = Field(..., description="The value of the option")
  153. label: I18nObject = Field(..., description="The label of the option")
  154. @field_validator("value", mode="before")
  155. @classmethod
  156. def transform_id_to_str(cls, value) -> str:
  157. if not isinstance(value, str):
  158. return str(value)
  159. else:
  160. return value
  161. class ToolParameter(BaseModel):
  162. class ToolParameterType(str, Enum):
  163. STRING = CommonParameterType.STRING.value
  164. NUMBER = CommonParameterType.NUMBER.value
  165. BOOLEAN = CommonParameterType.BOOLEAN.value
  166. SELECT = CommonParameterType.SELECT.value
  167. SECRET_INPUT = CommonParameterType.SECRET_INPUT.value
  168. FILE = CommonParameterType.FILE.value
  169. class ToolParameterForm(Enum):
  170. SCHEMA = "schema" # should be set while adding tool
  171. FORM = "form" # should be set before invoking tool
  172. LLM = "llm" # will be set by LLM
  173. name: str = Field(..., description="The name of the parameter")
  174. label: I18nObject = Field(..., description="The label presented to the user")
  175. human_description: Optional[I18nObject] = Field(default=None, description="The description presented to the user")
  176. placeholder: Optional[I18nObject] = Field(default=None, description="The placeholder presented to the user")
  177. type: ToolParameterType = Field(..., description="The type of the parameter")
  178. scope: AppSelectorScope | ModelConfigScope | None = None
  179. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  180. llm_description: Optional[str] = None
  181. required: Optional[bool] = False
  182. default: Optional[Union[float, int, str]] = None
  183. min: Optional[Union[float, int]] = None
  184. max: Optional[Union[float, int]] = None
  185. options: list[ToolParameterOption] = Field(default_factory=list)
  186. @field_validator("options", mode="before")
  187. @classmethod
  188. def transform_options(cls, v):
  189. if not isinstance(v, list):
  190. return []
  191. return v
  192. @classmethod
  193. def get_simple_instance(
  194. cls,
  195. name: str,
  196. llm_description: str,
  197. type: ToolParameterType,
  198. required: bool,
  199. options: Optional[list[str]] = None,
  200. ) -> "ToolParameter":
  201. """
  202. get a simple tool parameter
  203. :param name: the name of the parameter
  204. :param llm_description: the description presented to the LLM
  205. :param type: the type of the parameter
  206. :param required: if the parameter is required
  207. :param options: the options of the parameter
  208. """
  209. # convert options to ToolParameterOption
  210. if options:
  211. option_objs = [
  212. ToolParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options
  213. ]
  214. else:
  215. option_objs = []
  216. return cls(
  217. name=name,
  218. label=I18nObject(en_US="", zh_Hans=""),
  219. placeholder=None,
  220. human_description=I18nObject(en_US="", zh_Hans=""),
  221. type=type,
  222. form=cls.ToolParameterForm.LLM,
  223. llm_description=llm_description,
  224. required=required,
  225. options=option_objs,
  226. )
  227. class ToolProviderIdentity(BaseModel):
  228. author: str = Field(..., description="The author of the tool")
  229. name: str = Field(..., description="The name of the tool")
  230. description: I18nObject = Field(..., description="The description of the tool")
  231. icon: str = Field(..., description="The icon of the tool")
  232. label: I18nObject = Field(..., description="The label of the tool")
  233. tags: Optional[list[ToolLabelEnum]] = Field(
  234. default=[],
  235. description="The tags of the tool",
  236. )
  237. class ToolIdentity(BaseModel):
  238. author: str = Field(..., description="The author of the tool")
  239. name: str = Field(..., description="The name of the tool")
  240. label: I18nObject = Field(..., description="The label of the tool")
  241. provider: str = Field(..., description="The provider of the tool")
  242. icon: Optional[str] = None
  243. class ToolDescription(BaseModel):
  244. human: I18nObject = Field(..., description="The description presented to the user")
  245. llm: str = Field(..., description="The description presented to the LLM")
  246. class ToolEntity(BaseModel):
  247. identity: ToolIdentity
  248. parameters: list[ToolParameter] = Field(default_factory=list)
  249. description: Optional[ToolDescription] = None
  250. output_schema: Optional[dict] = None
  251. has_runtime_parameters: bool = Field(default=False, description="Whether the tool has runtime parameters")
  252. # pydantic configs
  253. model_config = ConfigDict(protected_namespaces=())
  254. @field_validator("parameters", mode="before")
  255. @classmethod
  256. def set_parameters(cls, v, validation_info: ValidationInfo) -> list[ToolParameter]:
  257. return v or []
  258. class ToolProviderEntity(BaseModel):
  259. identity: ToolProviderIdentity
  260. credentials_schema: list[ProviderConfig] = Field(default_factory=list)
  261. class ToolProviderEntityWithPlugin(ToolProviderEntity):
  262. tools: list[ToolEntity] = Field(default_factory=list)
  263. class WorkflowToolParameterConfiguration(BaseModel):
  264. """
  265. Workflow tool configuration
  266. """
  267. name: str = Field(..., description="The name of the parameter")
  268. description: str = Field(..., description="The description of the parameter")
  269. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  270. class ToolInvokeMeta(BaseModel):
  271. """
  272. Tool invoke meta
  273. """
  274. time_cost: float = Field(..., description="The time cost of the tool invoke")
  275. error: Optional[str] = None
  276. tool_config: Optional[dict] = None
  277. @classmethod
  278. def empty(cls) -> "ToolInvokeMeta":
  279. """
  280. Get an empty instance of ToolInvokeMeta
  281. """
  282. return cls(time_cost=0.0, error=None, tool_config={})
  283. @classmethod
  284. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  285. """
  286. Get an instance of ToolInvokeMeta with error
  287. """
  288. return cls(time_cost=0.0, error=error, tool_config={})
  289. def to_dict(self) -> dict:
  290. return {
  291. "time_cost": self.time_cost,
  292. "error": self.error,
  293. "tool_config": self.tool_config,
  294. }
  295. class ToolLabel(BaseModel):
  296. """
  297. Tool label
  298. """
  299. name: str = Field(..., description="The name of the tool")
  300. label: I18nObject = Field(..., description="The label of the tool")
  301. icon: str = Field(..., description="The icon of the tool")
  302. class ToolInvokeFrom(Enum):
  303. """
  304. Enum class for tool invoke
  305. """
  306. WORKFLOW = "workflow"
  307. AGENT = "agent"
  308. PLUGIN = "plugin"
  309. class ToolProviderID:
  310. organization: str
  311. plugin_name: str
  312. provider_name: str
  313. def __str__(self) -> str:
  314. return f"{self.organization}/{self.plugin_name}/{self.provider_name}"
  315. def __init__(self, value: str) -> None:
  316. # check if the value is a valid plugin id with format: $organization/$plugin_name/$provider_name
  317. if not re.match(r"^[a-z0-9_-]+\/[a-z0-9_-]+\/[a-z0-9_-]+$", value):
  318. raise ValueError("Invalid plugin id")
  319. self.organization, self.plugin_name, self.provider_name = value.split("/")