tools.py 12 KB

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