tool_entities.py 14 KB

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