tool_entities.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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: Union[str, bytes, dict] = None
  92. meta: dict[str, Any] = 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[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(cls,
  135. name: str, llm_description: str, type: ToolParameterType,
  136. required: bool, options: Optional[list[str]] = None) -> 'ToolParameter':
  137. """
  138. get a simple tool parameter
  139. :param name: the name of the parameter
  140. :param llm_description: the description presented to the LLM
  141. :param type: the type of the parameter
  142. :param required: if the parameter is required
  143. :param options: the options of the parameter
  144. """
  145. # convert options to ToolParameterOption
  146. if options:
  147. options = [ToolParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options]
  148. return cls(
  149. name=name,
  150. label=I18nObject(en_US='', zh_Hans=''),
  151. human_description=I18nObject(en_US='', zh_Hans=''),
  152. type=type,
  153. form=cls.ToolParameterForm.LLM,
  154. llm_description=llm_description,
  155. required=required,
  156. options=options,
  157. )
  158. class ToolProviderIdentity(BaseModel):
  159. author: str = Field(..., description="The author of the tool")
  160. name: str = Field(..., description="The name of the tool")
  161. description: I18nObject = Field(..., description="The description of the tool")
  162. icon: str = Field(..., description="The icon of the tool")
  163. label: I18nObject = Field(..., description="The label of the tool")
  164. tags: Optional[list[ToolLabelEnum]] = Field(default=[], description="The tags of the tool", )
  165. class ToolDescription(BaseModel):
  166. human: I18nObject = Field(..., description="The description presented to the user")
  167. llm: str = Field(..., description="The description presented to the LLM")
  168. class ToolIdentity(BaseModel):
  169. author: str = Field(..., description="The author of the tool")
  170. name: str = Field(..., description="The name of the tool")
  171. label: I18nObject = Field(..., description="The label of the tool")
  172. provider: str = Field(..., description="The provider of the tool")
  173. icon: Optional[str] = None
  174. class ToolCredentialsOption(BaseModel):
  175. value: str = Field(..., description="The value of the option")
  176. label: I18nObject = Field(..., description="The label of the option")
  177. class ToolProviderCredentials(BaseModel):
  178. class CredentialsType(Enum):
  179. SECRET_INPUT = "secret-input"
  180. TEXT_INPUT = "text-input"
  181. SELECT = "select"
  182. BOOLEAN = "boolean"
  183. @classmethod
  184. def value_of(cls, value: str) -> "ToolProviderCredentials.CredentialsType":
  185. """
  186. Get value of given mode.
  187. :param value: mode value
  188. :return: mode
  189. """
  190. for mode in cls:
  191. if mode.value == value:
  192. return mode
  193. raise ValueError(f'invalid mode value {value}')
  194. @staticmethod
  195. def default(value: str) -> str:
  196. return ""
  197. name: str = Field(..., description="The name of the credentials")
  198. type: CredentialsType = Field(..., description="The type of the credentials")
  199. required: bool = False
  200. default: Optional[Union[int, str]] = None
  201. options: Optional[list[ToolCredentialsOption]] = None
  202. label: Optional[I18nObject] = None
  203. help: Optional[I18nObject] = None
  204. url: Optional[str] = None
  205. placeholder: Optional[I18nObject] = None
  206. def to_dict(self) -> dict:
  207. return {
  208. 'name': self.name,
  209. 'type': self.type.value,
  210. 'required': self.required,
  211. 'default': self.default,
  212. 'options': self.options,
  213. 'help': self.help.to_dict() if self.help else None,
  214. 'label': self.label.to_dict(),
  215. 'url': self.url,
  216. 'placeholder': self.placeholder.to_dict() if self.placeholder else None,
  217. }
  218. class ToolRuntimeVariableType(Enum):
  219. TEXT = "text"
  220. IMAGE = "image"
  221. class ToolRuntimeVariable(BaseModel):
  222. type: ToolRuntimeVariableType = Field(..., description="The type of the variable")
  223. name: str = Field(..., description="The name of the variable")
  224. position: int = Field(..., description="The position of the variable")
  225. tool_name: str = Field(..., description="The name of the tool")
  226. class ToolRuntimeTextVariable(ToolRuntimeVariable):
  227. value: str = Field(..., description="The value of the variable")
  228. class ToolRuntimeImageVariable(ToolRuntimeVariable):
  229. value: str = Field(..., description="The path of the image")
  230. class ToolRuntimeVariablePool(BaseModel):
  231. conversation_id: str = Field(..., description="The conversation id")
  232. user_id: str = Field(..., description="The user id")
  233. tenant_id: str = Field(..., description="The tenant id of assistant")
  234. pool: list[ToolRuntimeVariable] = Field(..., description="The pool of variables")
  235. def __init__(self, **data: Any):
  236. pool = data.get('pool', [])
  237. # convert pool into correct type
  238. for index, variable in enumerate(pool):
  239. if variable['type'] == ToolRuntimeVariableType.TEXT.value:
  240. pool[index] = ToolRuntimeTextVariable(**variable)
  241. elif variable['type'] == ToolRuntimeVariableType.IMAGE.value:
  242. pool[index] = ToolRuntimeImageVariable(**variable)
  243. super().__init__(**data)
  244. def dict(self) -> dict:
  245. return {
  246. 'conversation_id': self.conversation_id,
  247. 'user_id': self.user_id,
  248. 'tenant_id': self.tenant_id,
  249. 'pool': [variable.model_dump() for variable in self.pool],
  250. }
  251. def set_text(self, tool_name: str, name: str, value: str) -> None:
  252. """
  253. set a text variable
  254. """
  255. for variable in self.pool:
  256. if variable.name == name:
  257. if variable.type == ToolRuntimeVariableType.TEXT:
  258. variable = cast(ToolRuntimeTextVariable, variable)
  259. variable.value = value
  260. return
  261. variable = ToolRuntimeTextVariable(
  262. type=ToolRuntimeVariableType.TEXT,
  263. name=name,
  264. position=len(self.pool),
  265. tool_name=tool_name,
  266. value=value,
  267. )
  268. self.pool.append(variable)
  269. def set_file(self, tool_name: str, value: str, name: str = None) -> None:
  270. """
  271. set an image variable
  272. :param tool_name: the name of the tool
  273. :param value: the id of the file
  274. """
  275. # check how many image variables are there
  276. image_variable_count = 0
  277. for variable in self.pool:
  278. if variable.type == ToolRuntimeVariableType.IMAGE:
  279. image_variable_count += 1
  280. if name is None:
  281. name = f"file_{image_variable_count}"
  282. for variable in self.pool:
  283. if variable.name == name:
  284. if variable.type == ToolRuntimeVariableType.IMAGE:
  285. variable = cast(ToolRuntimeImageVariable, variable)
  286. variable.value = value
  287. return
  288. variable = ToolRuntimeImageVariable(
  289. type=ToolRuntimeVariableType.IMAGE,
  290. name=name,
  291. position=len(self.pool),
  292. tool_name=tool_name,
  293. value=value,
  294. )
  295. self.pool.append(variable)
  296. class ModelToolPropertyKey(Enum):
  297. IMAGE_PARAMETER_NAME = "image_parameter_name"
  298. class ModelToolConfiguration(BaseModel):
  299. """
  300. Model tool configuration
  301. """
  302. type: str = Field(..., description="The type of the model tool")
  303. model: str = Field(..., description="The model")
  304. label: I18nObject = Field(..., description="The label of the model tool")
  305. properties: dict[ModelToolPropertyKey, Any] = Field(..., description="The properties of the model tool")
  306. class ModelToolProviderConfiguration(BaseModel):
  307. """
  308. Model tool provider configuration
  309. """
  310. provider: str = Field(..., description="The provider of the model tool")
  311. models: list[ModelToolConfiguration] = Field(..., description="The models of the model tool")
  312. label: I18nObject = Field(..., description="The label of the model tool")
  313. class WorkflowToolParameterConfiguration(BaseModel):
  314. """
  315. Workflow tool configuration
  316. """
  317. name: str = Field(..., description="The name of the parameter")
  318. description: str = Field(..., description="The description of the parameter")
  319. form: ToolParameter.ToolParameterForm = Field(..., description="The form of the parameter")
  320. class ToolInvokeMeta(BaseModel):
  321. """
  322. Tool invoke meta
  323. """
  324. time_cost: float = Field(..., description="The time cost of the tool invoke")
  325. error: Optional[str] = None
  326. tool_config: Optional[dict] = None
  327. @classmethod
  328. def empty(cls) -> 'ToolInvokeMeta':
  329. """
  330. Get an empty instance of ToolInvokeMeta
  331. """
  332. return cls(time_cost=0.0, error=None, tool_config={})
  333. @classmethod
  334. def error_instance(cls, error: str) -> 'ToolInvokeMeta':
  335. """
  336. Get an instance of ToolInvokeMeta with error
  337. """
  338. return cls(time_cost=0.0, error=error, tool_config={})
  339. def to_dict(self) -> dict:
  340. return {
  341. 'time_cost': self.time_cost,
  342. 'error': self.error,
  343. 'tool_config': self.tool_config,
  344. }
  345. class ToolLabel(BaseModel):
  346. """
  347. Tool label
  348. """
  349. name: str = Field(..., description="The name of the tool")
  350. label: I18nObject = Field(..., description="The label of the tool")
  351. icon: str = Field(..., description="The icon of the tool")
  352. class ToolInvokeFrom(Enum):
  353. """
  354. Enum class for tool invoke
  355. """
  356. WORKFLOW = "workflow"
  357. AGENT = "agent"