tool_entities.py 14 KB

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