tools.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import json
  2. from datetime import datetime
  3. from typing import Optional
  4. from deprecated import deprecated
  5. from sqlalchemy import ForeignKey
  6. from sqlalchemy.orm import Mapped, mapped_column
  7. from core.tools.entities.common_entities import I18nObject
  8. from core.tools.entities.tool_bundle import ApiToolBundle
  9. from core.tools.entities.tool_entities import ApiProviderSchemaType, WorkflowToolParameterConfiguration
  10. from extensions.ext_database import db
  11. from models.base import Base
  12. from .model import Account, App, Tenant
  13. from .types import StringUUID
  14. class BuiltinToolProvider(Base):
  15. """
  16. This table stores the tool provider information for built-in tools for each tenant.
  17. """
  18. __tablename__ = "tool_builtin_providers"
  19. __table_args__ = (
  20. db.PrimaryKeyConstraint("id", name="tool_builtin_provider_pkey"),
  21. # one tenant can only have one tool provider with the same name
  22. db.UniqueConstraint("tenant_id", "provider", name="unique_builtin_tool_provider"),
  23. )
  24. # id of the tool provider
  25. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  26. # id of the tenant
  27. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=True)
  28. # who created this tool provider
  29. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  30. # name of the tool provider
  31. provider: Mapped[str] = mapped_column(db.String(256), nullable=False)
  32. # credential of the tool provider
  33. encrypted_credentials: Mapped[str] = mapped_column(db.Text, nullable=True)
  34. created_at: Mapped[datetime] = mapped_column(
  35. db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)")
  36. )
  37. updated_at: Mapped[datetime] = mapped_column(
  38. db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)")
  39. )
  40. @property
  41. def credentials(self) -> dict:
  42. return json.loads(self.encrypted_credentials)
  43. class ApiToolProvider(Base):
  44. """
  45. The table stores the api providers.
  46. """
  47. __tablename__ = "tool_api_providers"
  48. __table_args__ = (
  49. db.PrimaryKeyConstraint("id", name="tool_api_provider_pkey"),
  50. db.UniqueConstraint("name", "tenant_id", name="unique_api_tool_provider"),
  51. )
  52. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  53. # name of the api provider
  54. name = db.Column(db.String(40), nullable=False)
  55. # icon
  56. icon = db.Column(db.String(255), nullable=False)
  57. # original schema
  58. schema = db.Column(db.Text, nullable=False)
  59. schema_type_str: Mapped[str] = db.Column(db.String(40), nullable=False)
  60. # who created this tool
  61. user_id = db.Column(StringUUID, nullable=False)
  62. # tenant id
  63. tenant_id = db.Column(StringUUID, nullable=False)
  64. # description of the provider
  65. description = db.Column(db.Text, nullable=False)
  66. # json format tools
  67. tools_str = db.Column(db.Text, nullable=False)
  68. # json format credentials
  69. credentials_str = db.Column(db.Text, nullable=False)
  70. # privacy policy
  71. privacy_policy = db.Column(db.String(255), nullable=True)
  72. # custom_disclaimer
  73. custom_disclaimer = db.Column(db.String(255), nullable=True)
  74. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  75. updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  76. @property
  77. def schema_type(self) -> ApiProviderSchemaType:
  78. return ApiProviderSchemaType.value_of(self.schema_type_str)
  79. @property
  80. def tools(self) -> list[ApiToolBundle]:
  81. return [ApiToolBundle(**tool) for tool in json.loads(self.tools_str)]
  82. @property
  83. def credentials(self) -> dict:
  84. return json.loads(self.credentials_str)
  85. @property
  86. def user(self) -> Account | None:
  87. return db.session.query(Account).filter(Account.id == self.user_id).first()
  88. @property
  89. def tenant(self) -> Tenant | None:
  90. return db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
  91. class ToolLabelBinding(Base):
  92. """
  93. The table stores the labels for tools.
  94. """
  95. __tablename__ = "tool_label_bindings"
  96. __table_args__ = (
  97. db.PrimaryKeyConstraint("id", name="tool_label_bind_pkey"),
  98. db.UniqueConstraint("tool_id", "label_name", name="unique_tool_label_bind"),
  99. )
  100. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  101. # tool id
  102. tool_id: Mapped[str] = mapped_column(db.String(64), nullable=False)
  103. # tool type
  104. tool_type: Mapped[str] = mapped_column(db.String(40), nullable=False)
  105. # label name
  106. label_name: Mapped[str] = mapped_column(db.String(40), nullable=False)
  107. class WorkflowToolProvider(Base):
  108. """
  109. The table stores the workflow providers.
  110. """
  111. __tablename__ = "tool_workflow_providers"
  112. __table_args__ = (
  113. db.PrimaryKeyConstraint("id", name="tool_workflow_provider_pkey"),
  114. db.UniqueConstraint("name", "tenant_id", name="unique_workflow_tool_provider"),
  115. db.UniqueConstraint("tenant_id", "app_id", name="unique_workflow_tool_provider_app_id"),
  116. )
  117. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  118. # name of the workflow provider
  119. name: Mapped[str] = mapped_column(db.String(40), nullable=False)
  120. # label of the workflow provider
  121. label: Mapped[str] = mapped_column(db.String(255), nullable=False, server_default="")
  122. # icon
  123. icon: Mapped[str] = mapped_column(db.String(255), nullable=False)
  124. # app id of the workflow provider
  125. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  126. # version of the workflow provider
  127. version: Mapped[str] = mapped_column(db.String(255), nullable=False, server_default="")
  128. # who created this tool
  129. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  130. # tenant id
  131. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  132. # description of the provider
  133. description: Mapped[str] = mapped_column(db.Text, nullable=False)
  134. # parameter configuration
  135. parameter_configuration: Mapped[str] = mapped_column(db.Text, nullable=False, server_default="[]")
  136. # privacy policy
  137. privacy_policy: Mapped[str] = mapped_column(db.String(255), nullable=True, server_default="")
  138. created_at: Mapped[datetime] = mapped_column(
  139. db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)")
  140. )
  141. updated_at: Mapped[datetime] = mapped_column(
  142. db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)")
  143. )
  144. @property
  145. def schema_type(self) -> ApiProviderSchemaType:
  146. return ApiProviderSchemaType.value_of(self.schema_type_str)
  147. @property
  148. def user(self) -> Account | None:
  149. return db.session.query(Account).filter(Account.id == self.user_id).first()
  150. @property
  151. def tenant(self) -> Tenant | None:
  152. return db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
  153. @property
  154. def parameter_configurations(self) -> list[WorkflowToolParameterConfiguration]:
  155. return [WorkflowToolParameterConfiguration(**config) for config in json.loads(self.parameter_configuration)]
  156. @property
  157. def app(self) -> App | None:
  158. return db.session.query(App).filter(App.id == self.app_id).first()
  159. class ToolModelInvoke(Base):
  160. """
  161. store the invoke logs from tool invoke
  162. """
  163. __tablename__ = "tool_model_invokes"
  164. __table_args__ = (db.PrimaryKeyConstraint("id", name="tool_model_invoke_pkey"),)
  165. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  166. # who invoke this tool
  167. user_id = db.Column(StringUUID, nullable=False)
  168. # tenant id
  169. tenant_id = db.Column(StringUUID, nullable=False)
  170. # provider
  171. provider = db.Column(db.String(40), nullable=False)
  172. # type
  173. tool_type = db.Column(db.String(40), nullable=False)
  174. # tool name
  175. tool_name = db.Column(db.String(40), nullable=False)
  176. # invoke parameters
  177. model_parameters = db.Column(db.Text, nullable=False)
  178. # prompt messages
  179. prompt_messages = db.Column(db.Text, nullable=False)
  180. # invoke response
  181. model_response = db.Column(db.Text, nullable=False)
  182. prompt_tokens = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  183. answer_tokens = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  184. answer_unit_price = db.Column(db.Numeric(10, 4), nullable=False)
  185. answer_price_unit = db.Column(db.Numeric(10, 7), nullable=False, server_default=db.text("0.001"))
  186. provider_response_latency = db.Column(db.Float, nullable=False, server_default=db.text("0"))
  187. total_price = db.Column(db.Numeric(10, 7))
  188. currency = db.Column(db.String(255), nullable=False)
  189. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  190. updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  191. @deprecated
  192. class ToolConversationVariables(Base):
  193. """
  194. store the conversation variables from tool invoke
  195. """
  196. __tablename__ = "tool_conversation_variables"
  197. __table_args__ = (
  198. db.PrimaryKeyConstraint("id", name="tool_conversation_variables_pkey"),
  199. # add index for user_id and conversation_id
  200. db.Index("user_id_idx", "user_id"),
  201. db.Index("conversation_id_idx", "conversation_id"),
  202. )
  203. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  204. # conversation user id
  205. user_id = db.Column(StringUUID, nullable=False)
  206. # tenant id
  207. tenant_id = db.Column(StringUUID, nullable=False)
  208. # conversation id
  209. conversation_id = db.Column(StringUUID, nullable=False)
  210. # variables pool
  211. variables_str = db.Column(db.Text, nullable=False)
  212. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  213. updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  214. @property
  215. def variables(self) -> dict:
  216. return json.loads(self.variables_str)
  217. class ToolFile(Base):
  218. """
  219. store the file created by agent
  220. """
  221. __tablename__ = "tool_files"
  222. __table_args__ = (
  223. db.PrimaryKeyConstraint("id", name="tool_file_pkey"),
  224. db.Index("tool_file_conversation_id_idx", "conversation_id"),
  225. )
  226. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  227. # conversation user id
  228. user_id: Mapped[str] = mapped_column(StringUUID)
  229. # tenant id
  230. tenant_id: Mapped[str] = mapped_column(StringUUID)
  231. # conversation id
  232. conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=True)
  233. # file key
  234. file_key: Mapped[str] = mapped_column(db.String(255), nullable=False)
  235. # mime type
  236. mimetype: Mapped[str] = mapped_column(db.String(255), nullable=False)
  237. # original url
  238. original_url: Mapped[str] = mapped_column(db.String(2048), nullable=True)
  239. @deprecated
  240. class DeprecatedPublishedAppTool(Base):
  241. """
  242. The table stores the apps published as a tool for each person.
  243. """
  244. __tablename__ = "tool_published_apps"
  245. __table_args__ = (
  246. db.PrimaryKeyConstraint("id", name="published_app_tool_pkey"),
  247. db.UniqueConstraint("app_id", "user_id", name="unique_published_app_tool"),
  248. )
  249. # id of the tool provider
  250. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  251. # id of the app
  252. app_id = db.Column(StringUUID, ForeignKey("apps.id"), nullable=False)
  253. # who published this tool
  254. user_id = db.Column(StringUUID, nullable=False)
  255. # description of the tool, stored in i18n format, for human
  256. description = db.Column(db.Text, nullable=False)
  257. # llm_description of the tool, for LLM
  258. llm_description = db.Column(db.Text, nullable=False)
  259. # query description, query will be seem as a parameter of the tool,
  260. # to describe this parameter to llm, we need this field
  261. query_description = db.Column(db.Text, nullable=False)
  262. # query name, the name of the query parameter
  263. query_name = db.Column(db.String(40), nullable=False)
  264. # name of the tool provider
  265. tool_name = db.Column(db.String(40), nullable=False)
  266. # author
  267. author = db.Column(db.String(40), nullable=False)
  268. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  269. updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  270. @property
  271. def description_i18n(self) -> I18nObject:
  272. return I18nObject(**json.loads(self.description))
  273. @property
  274. def app(self) -> App:
  275. return db.session.query(App).filter(App.id == self.app_id).first()
  276. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  277. user_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  278. tenant_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  279. conversation_id: Mapped[Optional[str]] = db.Column(StringUUID, nullable=True)
  280. file_key: Mapped[str] = db.Column(db.String(255), nullable=False)
  281. mimetype: Mapped[str] = db.Column(db.String(255), nullable=False)
  282. original_url: Mapped[Optional[str]] = db.Column(db.String(2048), nullable=True)
  283. name: Mapped[str] = mapped_column(default="")
  284. size: Mapped[int] = mapped_column(default=-1)
  285. def __init__(
  286. self,
  287. *,
  288. user_id: str,
  289. tenant_id: str,
  290. conversation_id: Optional[str] = None,
  291. file_key: str,
  292. mimetype: str,
  293. original_url: Optional[str] = None,
  294. name: str,
  295. size: int,
  296. ):
  297. self.user_id = user_id
  298. self.tenant_id = tenant_id
  299. self.conversation_id = conversation_id
  300. self.file_key = file_key
  301. self.mimetype = mimetype
  302. self.original_url = original_url
  303. self.name = name
  304. self.size = size