tools.py 12 KB

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