tools.py 12 KB

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