tool_entities.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. from enum import Enum
  2. from typing import Any, Optional, Union, cast
  3. from pydantic import BaseModel, Field, field_validator
  4. from core.tools.entities.common_entities import I18nObject
  5. class ToolLabelEnum(Enum):
  6. SEARCH = "search"
  7. IMAGE = "image"
  8. VIDEOS = "videos"
  9. WEATHER = "weather"
  10. FINANCE = "finance"
  11. DESIGN = "design"
  12. TRAVEL = "travel"
  13. SOCIAL = "social"
  14. NEWS = "news"
  15. MEDICAL = "medical"
  16. PRODUCTIVITY = "productivity"
  17. EDUCATION = "education"
  18. BUSINESS = "business"
  19. ENTERTAINMENT = "entertainment"
  20. UTILITIES = "utilities"
  21. OTHER = "other"
  22. class ToolProviderType(Enum):
  23. """
  24. Enum class for tool provider
  25. """
  26. BUILT_IN = "builtin"
  27. WORKFLOW = "workflow"
  28. API = "api"
  29. APP = "app"
  30. DATASET_RETRIEVAL = "dataset-retrieval"
  31. @classmethod
  32. def value_of(cls, value: str) -> "ToolProviderType":
  33. """
  34. Get value of given mode.
  35. :param value: mode value
  36. :return: mode
  37. """
  38. for mode in cls:
  39. if mode.value == value:
  40. return mode
  41. raise ValueError(f"invalid mode value {value}")
  42. class ApiProviderSchemaType(Enum):
  43. """
  44. Enum class for api provider schema type.
  45. """
  46. OPENAPI = "openapi"
  47. SWAGGER = "swagger"
  48. OPENAI_PLUGIN = "openai_plugin"
  49. OPENAI_ACTIONS = "openai_actions"
  50. @classmethod
  51. def value_of(cls, value: str) -> "ApiProviderSchemaType":
  52. """
  53. Get value of given mode.
  54. :param value: mode value
  55. :return: mode
  56. """
  57. for mode in cls:
  58. if mode.value == value:
  59. return mode
  60. raise ValueError(f"invalid mode value {value}")
  61. class ApiProviderAuthType(Enum):
  62. """
  63. Enum class for api provider auth type.
  64. """
  65. NONE = "none"
  66. API_KEY = "api_key"
  67. @classmethod
  68. def value_of(cls, value: str) -> "ApiProviderAuthType":
  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 ToolInvokeMessage(BaseModel):
  79. class MessageType(Enum):
  80. TEXT = "text"
  81. IMAGE = "image"
  82. LINK = "link"
  83. BLOB = "blob"
  84. JSON = "json"
  85. IMAGE_LINK = "image_link"
  86. FILE_VAR = "file_var"
  87. type: MessageType = MessageType.TEXT
  88. """
  89. plain text, image url or link url
  90. """
  91. message: str | bytes | dict | None = None
  92. meta: dict[str, Any] | None = None
  93. save_as: str = ""
  94. class ToolInvokeMessageBinary(BaseModel):
  95. mimetype: str = Field(..., description="The mimetype of the binary")
  96. url: str = Field(..., description="The url of the binary")
  97. save_as: str = ""
  98. file_var: Optional[dict[str, Any]] = None
  99. class ToolParameterOption(BaseModel):
  100. value: str = Field(..., description="The value of the option")
  101. label: I18nObject = Field(..., description="The label of the option")
  102. @field_validator("value", mode="before")
  103. @classmethod
  104. def transform_id_to_str(cls, value) -> str:
  105. if not isinstance(value, str):
  106. return str(value)
  107. else:
  108. return value
  109. class ToolParameter(BaseModel):
  110. class ToolParameterType(str, Enum):
  111. STRING = "string"
  112. NUMBER = "number"
  113. BOOLEAN = "boolean"
  114. SELECT = "select"
  115. SECRET_INPUT = "secret-input"
  116. FILE = "file"
  117. class ToolParameterForm(Enum):
  118. SCHEMA = "schema" # should be set while adding tool
  119. FORM = "form" # should be set before invoking tool
  120. LLM = "llm" # will be set by LLM
  121. name: str = Field(..., description="The name of the parameter")
  122. label: I18nObject = Field(..., description="The label presented to the user")
  123. human_description: Optional[I18nObject] = Field(None, description="The description presented to the user")
  124. placeholder: Optional[I18nObject] = Field(None, description="The placeholder presented to the user")
  125. type: ToolParameterType = Field(..., description="The type of the parameter")
  126. form: ToolParameterForm = Field(..., description="The form of the parameter, schema/form/llm")
  127. llm_description: Optional[str] = None
  128. required: Optional[bool] = False
  129. default: Optional[Union[float, int, str]] = None
  130. min: Optional[Union[float, int]] = None
  131. max: Optional[Union[float, int]] = None
  132. options: Optional[list[ToolParameterOption]] = None
  133. @classmethod
  134. def get_simple_instance(
  135. cls,
  136. name: str,
  137. llm_description: str,
  138. type: ToolParameterType,
  139. required: bool,
  140. options: Optional[list[str]] = None,
  141. ) -> "ToolParameter":
  142. """
  143. get a simple tool parameter
  144. :param name: the name of the parameter
  145. :param llm_description: the description presented to the LLM
  146. :param type: the type of the parameter
  147. :param required: if the parameter is required
  148. :param options: the options of the parameter
  149. """
  150. # convert options to ToolParameterOption
  151. if options:
  152. options = [
  153. ToolParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options
  154. ]
  155. return cls(
  156. name=name,
  157. label=I18nObject(en_US="", zh_Hans=""),
  158. human_description=I18nObject(en_US="", zh_Hans=""),
  159. type=type,
  160. form=cls.ToolParameterForm.LLM,
  161. llm_description=llm_description,
  162. required=required,
  163. options=options,
  164. )
  165. class ToolProviderIdentity(BaseModel):
  166. author: str = Field(..., description="The author of the tool")
  167. name: str = Field(..., description="The name of the tool")
  168. description: I18nObject = Field(..., description="The description of the tool")
  169. icon: str = Field(..., description="The icon of the tool")
  170. label: I18nObject = Field(..., description="The label of the tool")
  171. tags: Optional[list[ToolLabelEnum]] = Field(
  172. default=[],
  173. description="The tags of the tool",
  174. )
  175. class ToolDescription(BaseModel):
  176. human: I18nObject = Field(..., description="The description presented to the user")
  177. llm: str = Field(..., description="The description presented to the LLM")
  178. class ToolIdentity(BaseModel):
  179. author: str = Field(..., description="The author of the tool")
  180. name: str = Field(..., description="The name of the tool")
  181. label: I18nObject = Field(..., description="The label of the tool")
  182. provider: str = Field(..., description="The provider of the tool")
  183. icon: Optional[str] = None
  184. class ToolCredentialsOption(BaseModel):
  185. value: str = Field(..., description="The value of the option")
  186. label: I18nObject = Field(..., description="The label of the option")
  187. class ToolProviderCredentials(BaseModel):
  188. class CredentialsType(Enum):
  189. SECRET_INPUT = "secret-input"
  190. TEXT_INPUT = "text-input"
  191. SELECT = "select"
  192. BOOLEAN = "boolean"
  193. @classmethod
  194. def value_of(cls, value: str) -> "ToolProviderCredentials.CredentialsType":
  195. """
  196. Get value of given mode.
  197. :param value: mode value
  198. :return: mode
  199. """
  200. for mode in cls:
  201. if mode.value == value:
  202. return mode
  203. raise ValueError(f"invalid mode value {value}")
  204. @staticmethod
  205. def default(value: str) -> str:
  206. return ""
  207. name: str = Field(..., description="The name of the credentials")
  208. type: CredentialsType = Field(..., description="The type of the credentials")
  209. required: bool = False
  210. default: Optional[Union[int, str]] = None
  211. options: Optional[list[ToolCredentialsOption]] = None
  212. label: Optional[I18nObject] = None
  213. help: Optional[I18nObject] = None
  214. url: Optional[str] = None
  215. placeholder: Optional[I18nObject] = None
  216. def to_dict(self) -> dict:
  217. return {
  218. "name": self.name,
  219. "type": self.type.value,
  220. "required": self.required,
  221. "default": self.default,
  222. "options": self.options,
  223. "help": self.help.to_dict() if self.help else None,
  224. "label": self.label.to_dict(),
  225. "url": self.url,
  226. "placeholder": self.placeholder.to_dict() if self.placeholder else None,
  227. }
  228. class ToolRuntimeVariableType(Enum):
  229. TEXT = "text"
  230. IMAGE = "image"
  231. class ToolRuntimeVariable(BaseModel):
  232. type: ToolRuntimeVariableType = Field(..., description="The type of the variable")
  233. name: str = Field(..., description="The name of the variable")
  234. position: int = Field(..., description="The position of the variable")
  235. tool_name: str = Field(..., description="The name of the tool")
  236. class ToolRuntimeTextVariable(ToolRuntimeVariable):
  237. value: str = Field(..., description="The value of the variable")
  238. class ToolRuntimeImageVariable(ToolRuntimeVariable):
  239. value: str = Field(..., description="The path of the image")
  240. class ToolRuntimeVariablePool(BaseModel):
  241. conversation_id: str = Field(..., description="The conversation id")
  242. user_id: str = Field(..., description="The user id")
  243. tenant_id: str = Field(..., description="The tenant id of assistant")
  244. pool: list[ToolRuntimeVariable] = Field(..., description="The pool of variables")
  245. def __init__(self, **data: Any):
  246. pool = data.get("pool", [])
  247. # convert pool into correct type
  248. for index, variable in enumerate(pool):
  249. if variable["type"] == ToolRuntimeVariableType.TEXT.value:
  250. pool[index] = ToolRuntimeTextVariable(**variable)
  251. elif variable["type"] == ToolRuntimeVariableType.IMAGE.value:
  252. pool[index] = ToolRuntimeImageVariable(**variable)
  253. super().__init__(**data)
  254. def dict(self) -> dict:
  255. return {
  256. "conversation_id": self.conversation_id,
  257. "user_id": self.user_id,
  258. "tenant_id": self.tenant_id,
  259. "pool": [variable.model_dump() for variable in self.pool],
  260. }
  261. def set_text(self, tool_name: str, name: str, value: str) -> None:
  262. """
  263. set a text variable
  264. """
  265. for variable in self.pool:
  266. if variable.name == name:
  267. if variable.type == ToolRuntimeVariableType.TEXT:
  268. variable = cast(ToolRuntimeTextVariable, variable)
  269. variable.value = value
  270. return
  271. variable = ToolRuntimeTextVariable(
  272. type=ToolRuntimeVariableType.TEXT,
  273. name=name,
  274. position=len(self.pool),
  275. tool_name=tool_name,
  276. value=value,
  277. )
  278. self.pool.append(variable)
  279. def set_file(self, tool_name: str, value: str, name: str = None) -> None:
  280. """
  281. set an image variable
  282. :param tool_name: the name of the tool
  283. :param value: the id of the file
  284. """
  285. # check how many image variables are there
  286. image_variable_count = 0
  287. for variable in self.pool:
  288. if variable.type == ToolRuntimeVariableType.IMAGE:
  289. image_variable_count += 1
  290. if name is None:
  291. name = f"file_{image_variable_count}"
  292. for variable in self.pool:
  293. if variable.name == name:
  294. if variable.type == ToolRuntimeVariableType.IMAGE:
  295. variable = cast(ToolRuntimeImageVariable, variable)
  296. variable.value = value
  297. return
  298. variable = ToolRuntimeImageVariable(
  299. type=ToolRuntimeVariableType.IMAGE,
  300. name=name,
  301. position=len(self.pool),
  302. tool_name=tool_name,
  303. value=value,
  304. )
  305. self.pool.append(variable)
  306. class ModelToolPropertyKey(Enum):
  307. IMAGE_PARAMETER_NAME = "image_parameter_name"
  308. class ModelToolConfiguration(BaseModel):
  309. """
  310. Model tool configuration
  311. """
  312. type: str = Field(..., description="The type of the model tool")
  313. model: str = Field(..., description="The model")
  314. label: I18nObject = Field(..., description="The label of the model tool")
  315. properties: dict[ModelToolPropertyKey, Any] = Field(..., description="The properties of the model tool")
  316. class ModelToolProviderConfiguration(BaseModel):
  317. """
  318. Model tool provider configuration
  319. """
  320. provider: str = Field(..., description="The provider of the model tool")
  321. models: list[ModelToolConfiguration] = Field(..., description="The models of the model tool")
  322. label: I18nObject = Field(..., description="The label of the model tool")
  323. class WorkflowToolParameterConfiguration(BaseModel):
  324. """
  325. Workflow tool configuration
  326. """
  327. name: str = Field(..., description="The name of the parameter")
  328. description: str = Field(..., description="The description of the parameter")
  329. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  330. class ToolInvokeMeta(BaseModel):
  331. """
  332. Tool invoke meta
  333. """
  334. time_cost: float = Field(..., description="The time cost of the tool invoke")
  335. error: Optional[str] = None
  336. tool_config: Optional[dict] = None
  337. @classmethod
  338. def empty(cls) -> "ToolInvokeMeta":
  339. """
  340. Get an empty instance of ToolInvokeMeta
  341. """
  342. return cls(time_cost=0.0, error=None, tool_config={})
  343. @classmethod
  344. def error_instance(cls, error: str) -> "ToolInvokeMeta":
  345. """
  346. Get an instance of ToolInvokeMeta with error
  347. """
  348. return cls(time_cost=0.0, error=error, tool_config={})
  349. def to_dict(self) -> dict:
  350. return {
  351. "time_cost": self.time_cost,
  352. "error": self.error,
  353. "tool_config": self.tool_config,
  354. }
  355. class ToolLabel(BaseModel):
  356. """
  357. Tool label
  358. """
  359. name: str = Field(..., description="The name of the tool")
  360. label: I18nObject = Field(..., description="The label of the tool")
  361. icon: str = Field(..., description="The icon of the tool")
  362. class ToolInvokeFrom(Enum):
  363. """
  364. Enum class for tool invoke
  365. """
  366. WORKFLOW = "workflow"
  367. AGENT = "agent"