You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import json
  2. from datetime import datetime
  3. from typing import TYPE_CHECKING, Any, Optional, cast
  4. from urllib.parse import urlparse
  5. import sqlalchemy as sa
  6. from deprecated import deprecated
  7. from sqlalchemy import ForeignKey, String, func
  8. from sqlalchemy.orm import Mapped, mapped_column
  9. from core.helper import encrypter
  10. from core.tools.entities.common_entities import I18nObject
  11. from core.tools.entities.tool_bundle import ApiToolBundle
  12. from core.tools.entities.tool_entities import ApiProviderSchemaType, WorkflowToolParameterConfiguration
  13. from models.base import Base, TypeBase
  14. from .engine import db
  15. from .model import Account, App, Tenant
  16. from .types import StringUUID
  17. if TYPE_CHECKING:
  18. from core.mcp.types import Tool as MCPTool
  19. from core.tools.entities.common_entities import I18nObject
  20. from core.tools.entities.tool_bundle import ApiToolBundle
  21. from core.tools.entities.tool_entities import ApiProviderSchemaType, WorkflowToolParameterConfiguration
  22. # system level tool oauth client params (client_id, client_secret, etc.)
  23. class ToolOAuthSystemClient(TypeBase):
  24. __tablename__ = "tool_oauth_system_clients"
  25. __table_args__ = (
  26. sa.PrimaryKeyConstraint("id", name="tool_oauth_system_client_pkey"),
  27. sa.UniqueConstraint("plugin_id", "provider", name="tool_oauth_system_client_plugin_id_provider_idx"),
  28. )
  29. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"), init=False)
  30. plugin_id: Mapped[str] = mapped_column(String(512), nullable=False)
  31. provider: Mapped[str] = mapped_column(String(255), nullable=False)
  32. # oauth params of the tool provider
  33. encrypted_oauth_params: Mapped[str] = mapped_column(sa.Text, nullable=False)
  34. # tenant level tool oauth client params (client_id, client_secret, etc.)
  35. class ToolOAuthTenantClient(Base):
  36. __tablename__ = "tool_oauth_tenant_clients"
  37. __table_args__ = (
  38. sa.PrimaryKeyConstraint("id", name="tool_oauth_tenant_client_pkey"),
  39. sa.UniqueConstraint("tenant_id", "plugin_id", "provider", name="unique_tool_oauth_tenant_client"),
  40. )
  41. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  42. # tenant id
  43. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  44. plugin_id: Mapped[str] = mapped_column(String(512), nullable=False)
  45. provider: Mapped[str] = mapped_column(String(255), nullable=False)
  46. enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  47. # oauth params of the tool provider
  48. encrypted_oauth_params: Mapped[str] = mapped_column(sa.Text, nullable=False)
  49. @property
  50. def oauth_params(self) -> dict[str, Any]:
  51. return cast(dict[str, Any], json.loads(self.encrypted_oauth_params or "{}"))
  52. class BuiltinToolProvider(Base):
  53. """
  54. This table stores the tool provider information for built-in tools for each tenant.
  55. """
  56. __tablename__ = "tool_builtin_providers"
  57. __table_args__ = (
  58. sa.PrimaryKeyConstraint("id", name="tool_builtin_provider_pkey"),
  59. sa.UniqueConstraint("tenant_id", "provider", "name", name="unique_builtin_tool_provider"),
  60. )
  61. # id of the tool provider
  62. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  63. name: Mapped[str] = mapped_column(
  64. String(256), nullable=False, server_default=sa.text("'API KEY 1'::character varying")
  65. )
  66. # id of the tenant
  67. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=True)
  68. # who created this tool provider
  69. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  70. # name of the tool provider
  71. provider: Mapped[str] = mapped_column(String(256), nullable=False)
  72. # credential of the tool provider
  73. encrypted_credentials: Mapped[str] = mapped_column(sa.Text, nullable=True)
  74. created_at: Mapped[datetime] = mapped_column(
  75. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  76. )
  77. updated_at: Mapped[datetime] = mapped_column(
  78. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  79. )
  80. is_default: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  81. # credential type, e.g., "api-key", "oauth2"
  82. credential_type: Mapped[str] = mapped_column(
  83. String(32), nullable=False, server_default=sa.text("'api-key'::character varying")
  84. )
  85. expires_at: Mapped[int] = mapped_column(sa.BigInteger, nullable=False, server_default=sa.text("-1"))
  86. @property
  87. def credentials(self) -> dict[str, Any]:
  88. return cast(dict[str, Any], json.loads(self.encrypted_credentials))
  89. class ApiToolProvider(Base):
  90. """
  91. The table stores the api providers.
  92. """
  93. __tablename__ = "tool_api_providers"
  94. __table_args__ = (
  95. sa.PrimaryKeyConstraint("id", name="tool_api_provider_pkey"),
  96. sa.UniqueConstraint("name", "tenant_id", name="unique_api_tool_provider"),
  97. )
  98. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  99. # name of the api provider
  100. name = mapped_column(String(255), nullable=False, server_default=sa.text("'API KEY 1'::character varying"))
  101. # icon
  102. icon: Mapped[str] = mapped_column(String(255), nullable=False)
  103. # original schema
  104. schema = mapped_column(sa.Text, nullable=False)
  105. schema_type_str: Mapped[str] = mapped_column(String(40), nullable=False)
  106. # who created this tool
  107. user_id = mapped_column(StringUUID, nullable=False)
  108. # tenant id
  109. tenant_id = mapped_column(StringUUID, nullable=False)
  110. # description of the provider
  111. description = mapped_column(sa.Text, nullable=False)
  112. # json format tools
  113. tools_str = mapped_column(sa.Text, nullable=False)
  114. # json format credentials
  115. credentials_str = mapped_column(sa.Text, nullable=False)
  116. # privacy policy
  117. privacy_policy = mapped_column(String(255), nullable=True)
  118. # custom_disclaimer
  119. custom_disclaimer: Mapped[str] = mapped_column(sa.TEXT, default="")
  120. created_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  121. updated_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  122. @property
  123. def schema_type(self) -> "ApiProviderSchemaType":
  124. from core.tools.entities.tool_entities import ApiProviderSchemaType
  125. return ApiProviderSchemaType.value_of(self.schema_type_str)
  126. @property
  127. def tools(self) -> list["ApiToolBundle"]:
  128. from core.tools.entities.tool_bundle import ApiToolBundle
  129. return [ApiToolBundle(**tool) for tool in json.loads(self.tools_str)]
  130. @property
  131. def credentials(self) -> dict[str, Any]:
  132. return dict[str, Any](json.loads(self.credentials_str))
  133. @property
  134. def user(self) -> Account | None:
  135. if not self.user_id:
  136. return None
  137. return db.session.query(Account).where(Account.id == self.user_id).first()
  138. @property
  139. def tenant(self) -> Tenant | None:
  140. return db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  141. class ToolLabelBinding(TypeBase):
  142. """
  143. The table stores the labels for tools.
  144. """
  145. __tablename__ = "tool_label_bindings"
  146. __table_args__ = (
  147. sa.PrimaryKeyConstraint("id", name="tool_label_bind_pkey"),
  148. sa.UniqueConstraint("tool_id", "label_name", name="unique_tool_label_bind"),
  149. )
  150. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"), init=False)
  151. # tool id
  152. tool_id: Mapped[str] = mapped_column(String(64), nullable=False)
  153. # tool type
  154. tool_type: Mapped[str] = mapped_column(String(40), nullable=False)
  155. # label name
  156. label_name: Mapped[str] = mapped_column(String(40), nullable=False)
  157. class WorkflowToolProvider(Base):
  158. """
  159. The table stores the workflow providers.
  160. """
  161. __tablename__ = "tool_workflow_providers"
  162. __table_args__ = (
  163. sa.PrimaryKeyConstraint("id", name="tool_workflow_provider_pkey"),
  164. sa.UniqueConstraint("name", "tenant_id", name="unique_workflow_tool_provider"),
  165. sa.UniqueConstraint("tenant_id", "app_id", name="unique_workflow_tool_provider_app_id"),
  166. )
  167. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  168. # name of the workflow provider
  169. name: Mapped[str] = mapped_column(String(255), nullable=False)
  170. # label of the workflow provider
  171. label: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
  172. # icon
  173. icon: Mapped[str] = mapped_column(String(255), nullable=False)
  174. # app id of the workflow provider
  175. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  176. # version of the workflow provider
  177. version: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
  178. # who created this tool
  179. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  180. # tenant id
  181. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  182. # description of the provider
  183. description: Mapped[str] = mapped_column(sa.Text, nullable=False)
  184. # parameter configuration
  185. parameter_configuration: Mapped[str] = mapped_column(sa.Text, nullable=False, server_default="[]")
  186. # privacy policy
  187. privacy_policy: Mapped[str] = mapped_column(String(255), nullable=True, server_default="")
  188. created_at: Mapped[datetime] = mapped_column(
  189. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  190. )
  191. updated_at: Mapped[datetime] = mapped_column(
  192. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  193. )
  194. @property
  195. def user(self) -> Account | None:
  196. return db.session.query(Account).where(Account.id == self.user_id).first()
  197. @property
  198. def tenant(self) -> Tenant | None:
  199. return db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  200. @property
  201. def parameter_configurations(self) -> list["WorkflowToolParameterConfiguration"]:
  202. from core.tools.entities.tool_entities import WorkflowToolParameterConfiguration
  203. return [WorkflowToolParameterConfiguration(**config) for config in json.loads(self.parameter_configuration)]
  204. @property
  205. def app(self) -> App | None:
  206. return db.session.query(App).where(App.id == self.app_id).first()
  207. class MCPToolProvider(Base):
  208. """
  209. The table stores the mcp providers.
  210. """
  211. __tablename__ = "tool_mcp_providers"
  212. __table_args__ = (
  213. sa.PrimaryKeyConstraint("id", name="tool_mcp_provider_pkey"),
  214. sa.UniqueConstraint("tenant_id", "server_url_hash", name="unique_mcp_provider_server_url"),
  215. sa.UniqueConstraint("tenant_id", "name", name="unique_mcp_provider_name"),
  216. sa.UniqueConstraint("tenant_id", "server_identifier", name="unique_mcp_provider_server_identifier"),
  217. )
  218. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  219. # name of the mcp provider
  220. name: Mapped[str] = mapped_column(String(40), nullable=False)
  221. # server identifier of the mcp provider
  222. server_identifier: Mapped[str] = mapped_column(String(64), nullable=False)
  223. # encrypted url of the mcp provider
  224. server_url: Mapped[str] = mapped_column(sa.Text, nullable=False)
  225. # hash of server_url for uniqueness check
  226. server_url_hash: Mapped[str] = mapped_column(String(64), nullable=False)
  227. # icon of the mcp provider
  228. icon: Mapped[str] = mapped_column(String(255), nullable=True)
  229. # tenant id
  230. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  231. # who created this tool
  232. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  233. # encrypted credentials
  234. encrypted_credentials: Mapped[str] = mapped_column(sa.Text, nullable=True)
  235. # authed
  236. authed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
  237. # tools
  238. tools: Mapped[str] = mapped_column(sa.Text, nullable=False, default="[]")
  239. created_at: Mapped[datetime] = mapped_column(
  240. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  241. )
  242. updated_at: Mapped[datetime] = mapped_column(
  243. sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  244. )
  245. timeout: Mapped[float] = mapped_column(sa.Float, nullable=False, server_default=sa.text("30"))
  246. sse_read_timeout: Mapped[float] = mapped_column(sa.Float, nullable=False, server_default=sa.text("300"))
  247. def load_user(self) -> Account | None:
  248. return db.session.query(Account).where(Account.id == self.user_id).first()
  249. @property
  250. def tenant(self) -> Tenant | None:
  251. return db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  252. @property
  253. def credentials(self) -> dict[str, Any]:
  254. try:
  255. return cast(dict[str, Any], json.loads(self.encrypted_credentials)) or {}
  256. except Exception:
  257. return {}
  258. @property
  259. def mcp_tools(self) -> list["MCPTool"]:
  260. from core.mcp.types import Tool as MCPTool
  261. return [MCPTool(**tool) for tool in json.loads(self.tools)]
  262. @property
  263. def provider_icon(self) -> dict[str, str] | str:
  264. from core.file import helpers as file_helpers
  265. try:
  266. return cast(dict[str, str], json.loads(self.icon))
  267. except json.JSONDecodeError:
  268. return file_helpers.get_signed_file_url(self.icon)
  269. @property
  270. def decrypted_server_url(self) -> str:
  271. return encrypter.decrypt_token(self.tenant_id, self.server_url)
  272. @property
  273. def masked_server_url(self) -> str:
  274. def mask_url(url: str, mask_char: str = "*") -> str:
  275. """
  276. mask the url to a simple string
  277. """
  278. parsed = urlparse(url)
  279. base_url = f"{parsed.scheme}://{parsed.netloc}"
  280. if parsed.path and parsed.path != "/":
  281. return f"{base_url}/{mask_char * 6}"
  282. else:
  283. return base_url
  284. return mask_url(self.decrypted_server_url)
  285. @property
  286. def decrypted_credentials(self) -> dict[str, Any]:
  287. from core.helper.provider_cache import NoOpProviderCredentialCache
  288. from core.tools.mcp_tool.provider import MCPToolProviderController
  289. from core.tools.utils.encryption import create_provider_encrypter
  290. provider_controller = MCPToolProviderController.from_db(self)
  291. encrypter, _ = create_provider_encrypter(
  292. tenant_id=self.tenant_id,
  293. config=[x.to_basic_provider_config() for x in provider_controller.get_credentials_schema()],
  294. cache=NoOpProviderCredentialCache(),
  295. )
  296. return encrypter.decrypt(self.credentials)
  297. class ToolModelInvoke(Base):
  298. """
  299. store the invoke logs from tool invoke
  300. """
  301. __tablename__ = "tool_model_invokes"
  302. __table_args__ = (sa.PrimaryKeyConstraint("id", name="tool_model_invoke_pkey"),)
  303. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  304. # who invoke this tool
  305. user_id = mapped_column(StringUUID, nullable=False)
  306. # tenant id
  307. tenant_id = mapped_column(StringUUID, nullable=False)
  308. # provider
  309. provider: Mapped[str] = mapped_column(String(255), nullable=False)
  310. # type
  311. tool_type = mapped_column(String(40), nullable=False)
  312. # tool name
  313. tool_name = mapped_column(String(128), nullable=False)
  314. # invoke parameters
  315. model_parameters = mapped_column(sa.Text, nullable=False)
  316. # prompt messages
  317. prompt_messages = mapped_column(sa.Text, nullable=False)
  318. # invoke response
  319. model_response = mapped_column(sa.Text, nullable=False)
  320. prompt_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  321. answer_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  322. answer_unit_price = mapped_column(sa.Numeric(10, 4), nullable=False)
  323. answer_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  324. provider_response_latency = mapped_column(sa.Float, nullable=False, server_default=sa.text("0"))
  325. total_price = mapped_column(sa.Numeric(10, 7))
  326. currency: Mapped[str] = mapped_column(String(255), nullable=False)
  327. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  328. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  329. @deprecated
  330. class ToolConversationVariables(Base):
  331. """
  332. store the conversation variables from tool invoke
  333. """
  334. __tablename__ = "tool_conversation_variables"
  335. __table_args__ = (
  336. sa.PrimaryKeyConstraint("id", name="tool_conversation_variables_pkey"),
  337. # add index for user_id and conversation_id
  338. sa.Index("user_id_idx", "user_id"),
  339. sa.Index("conversation_id_idx", "conversation_id"),
  340. )
  341. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  342. # conversation user id
  343. user_id = mapped_column(StringUUID, nullable=False)
  344. # tenant id
  345. tenant_id = mapped_column(StringUUID, nullable=False)
  346. # conversation id
  347. conversation_id = mapped_column(StringUUID, nullable=False)
  348. # variables pool
  349. variables_str = mapped_column(sa.Text, nullable=False)
  350. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  351. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  352. @property
  353. def variables(self):
  354. return json.loads(self.variables_str)
  355. class ToolFile(TypeBase):
  356. """This table stores file metadata generated in workflows,
  357. not only files created by agent.
  358. """
  359. __tablename__ = "tool_files"
  360. __table_args__ = (
  361. sa.PrimaryKeyConstraint("id", name="tool_file_pkey"),
  362. sa.Index("tool_file_conversation_id_idx", "conversation_id"),
  363. )
  364. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"), init=False)
  365. # conversation user id
  366. user_id: Mapped[str] = mapped_column(StringUUID)
  367. # tenant id
  368. tenant_id: Mapped[str] = mapped_column(StringUUID)
  369. # conversation id
  370. conversation_id: Mapped[Optional[str]] = mapped_column(StringUUID, nullable=True)
  371. # file key
  372. file_key: Mapped[str] = mapped_column(String(255), nullable=False)
  373. # mime type
  374. mimetype: Mapped[str] = mapped_column(String(255), nullable=False)
  375. # original url
  376. original_url: Mapped[Optional[str]] = mapped_column(String(2048), nullable=True, default=None)
  377. # name
  378. name: Mapped[str] = mapped_column(default="")
  379. # size
  380. size: Mapped[int] = mapped_column(default=-1)
  381. @deprecated
  382. class DeprecatedPublishedAppTool(Base):
  383. """
  384. The table stores the apps published as a tool for each person.
  385. """
  386. __tablename__ = "tool_published_apps"
  387. __table_args__ = (
  388. sa.PrimaryKeyConstraint("id", name="published_app_tool_pkey"),
  389. sa.UniqueConstraint("app_id", "user_id", name="unique_published_app_tool"),
  390. )
  391. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  392. # id of the app
  393. app_id = mapped_column(StringUUID, ForeignKey("apps.id"), nullable=False)
  394. user_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  395. # who published this tool
  396. description = mapped_column(sa.Text, nullable=False)
  397. # llm_description of the tool, for LLM
  398. llm_description = mapped_column(sa.Text, nullable=False)
  399. # query description, query will be seem as a parameter of the tool,
  400. # to describe this parameter to llm, we need this field
  401. query_description = mapped_column(sa.Text, nullable=False)
  402. # query name, the name of the query parameter
  403. query_name = mapped_column(String(40), nullable=False)
  404. # name of the tool provider
  405. tool_name = mapped_column(String(40), nullable=False)
  406. # author
  407. author = mapped_column(String(40), nullable=False)
  408. created_at = mapped_column(sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)"))
  409. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)"))
  410. @property
  411. def description_i18n(self) -> "I18nObject":
  412. from core.tools.entities.common_entities import I18nObject
  413. return I18nObject(**json.loads(self.description))