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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. import json
  2. import re
  3. import uuid
  4. from collections.abc import Mapping
  5. from datetime import datetime
  6. from enum import Enum, StrEnum
  7. from typing import TYPE_CHECKING, Any, Literal, Optional, cast
  8. import sqlalchemy as sa
  9. from flask import request
  10. from flask_login import UserMixin
  11. from sqlalchemy import Float, Index, PrimaryKeyConstraint, String, exists, func, select, text
  12. from sqlalchemy.orm import Mapped, Session, mapped_column
  13. from configs import dify_config
  14. from constants import DEFAULT_FILE_NUMBER_LIMITS
  15. from core.file import FILE_MODEL_IDENTITY, File, FileTransferMethod, FileType
  16. from core.file import helpers as file_helpers
  17. from core.tools.signature import sign_tool_file
  18. from core.workflow.enums import WorkflowExecutionStatus
  19. from libs.helper import generate_string
  20. from .account import Account, Tenant
  21. from .base import Base
  22. from .engine import db
  23. from .enums import CreatorUserRole
  24. from .provider_ids import GenericProviderID
  25. from .types import StringUUID
  26. if TYPE_CHECKING:
  27. from models.workflow import Workflow
  28. class DifySetup(Base):
  29. __tablename__ = "dify_setups"
  30. __table_args__ = (sa.PrimaryKeyConstraint("version", name="dify_setup_pkey"),)
  31. version: Mapped[str] = mapped_column(String(255), nullable=False)
  32. setup_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  33. class AppMode(StrEnum):
  34. COMPLETION = "completion"
  35. WORKFLOW = "workflow"
  36. CHAT = "chat"
  37. ADVANCED_CHAT = "advanced-chat"
  38. AGENT_CHAT = "agent-chat"
  39. CHANNEL = "channel"
  40. RAG_PIPELINE = "rag-pipeline"
  41. @classmethod
  42. def value_of(cls, value: str) -> "AppMode":
  43. """
  44. Get value of given mode.
  45. :param value: mode value
  46. :return: mode
  47. """
  48. for mode in cls:
  49. if mode.value == value:
  50. return mode
  51. raise ValueError(f"invalid mode value {value}")
  52. class IconType(Enum):
  53. IMAGE = "image"
  54. EMOJI = "emoji"
  55. class App(Base):
  56. __tablename__ = "apps"
  57. __table_args__ = (sa.PrimaryKeyConstraint("id", name="app_pkey"), sa.Index("app_tenant_id_idx", "tenant_id"))
  58. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  59. tenant_id: Mapped[str] = mapped_column(StringUUID)
  60. name: Mapped[str] = mapped_column(String(255))
  61. description: Mapped[str] = mapped_column(sa.Text, server_default=sa.text("''::character varying"))
  62. mode: Mapped[str] = mapped_column(String(255))
  63. icon_type: Mapped[Optional[str]] = mapped_column(String(255)) # image, emoji
  64. icon = mapped_column(String(255))
  65. icon_background: Mapped[Optional[str]] = mapped_column(String(255))
  66. app_model_config_id = mapped_column(StringUUID, nullable=True)
  67. workflow_id = mapped_column(StringUUID, nullable=True)
  68. status: Mapped[str] = mapped_column(String(255), server_default=sa.text("'normal'::character varying"))
  69. enable_site: Mapped[bool] = mapped_column(sa.Boolean)
  70. enable_api: Mapped[bool] = mapped_column(sa.Boolean)
  71. api_rpm: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"))
  72. api_rph: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"))
  73. is_demo: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  74. is_public: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  75. is_universal: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  76. tracing = mapped_column(sa.Text, nullable=True)
  77. max_active_requests: Mapped[Optional[int]]
  78. created_by = mapped_column(StringUUID, nullable=True)
  79. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  80. updated_by = mapped_column(StringUUID, nullable=True)
  81. updated_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  82. use_icon_as_answer_icon: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  83. @property
  84. def desc_or_prompt(self):
  85. if self.description:
  86. return self.description
  87. else:
  88. app_model_config = self.app_model_config
  89. if app_model_config:
  90. return app_model_config.pre_prompt
  91. else:
  92. return ""
  93. @property
  94. def site(self):
  95. site = db.session.query(Site).where(Site.app_id == self.id).first()
  96. return site
  97. @property
  98. def app_model_config(self):
  99. if self.app_model_config_id:
  100. return db.session.query(AppModelConfig).where(AppModelConfig.id == self.app_model_config_id).first()
  101. return None
  102. @property
  103. def workflow(self) -> Optional["Workflow"]:
  104. if self.workflow_id:
  105. from .workflow import Workflow
  106. return db.session.query(Workflow).where(Workflow.id == self.workflow_id).first()
  107. return None
  108. @property
  109. def api_base_url(self):
  110. return (dify_config.SERVICE_API_URL or request.host_url.rstrip("/")) + "/v1"
  111. @property
  112. def tenant(self):
  113. tenant = db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  114. return tenant
  115. @property
  116. def is_agent(self) -> bool:
  117. app_model_config = self.app_model_config
  118. if not app_model_config:
  119. return False
  120. if not app_model_config.agent_mode:
  121. return False
  122. if app_model_config.agent_mode_dict.get("enabled", False) and app_model_config.agent_mode_dict.get(
  123. "strategy", ""
  124. ) in {"function_call", "react"}:
  125. self.mode = AppMode.AGENT_CHAT.value
  126. db.session.commit()
  127. return True
  128. return False
  129. @property
  130. def mode_compatible_with_agent(self) -> str:
  131. if self.mode == AppMode.CHAT.value and self.is_agent:
  132. return AppMode.AGENT_CHAT.value
  133. return str(self.mode)
  134. @property
  135. def deleted_tools(self) -> list:
  136. from core.tools.entities.tool_entities import ToolProviderType
  137. from core.tools.tool_manager import ToolManager
  138. from services.plugin.plugin_service import PluginService
  139. # get agent mode tools
  140. app_model_config = self.app_model_config
  141. if not app_model_config:
  142. return []
  143. if not app_model_config.agent_mode:
  144. return []
  145. agent_mode = app_model_config.agent_mode_dict
  146. tools = agent_mode.get("tools", [])
  147. api_provider_ids: list[str] = []
  148. builtin_provider_ids: list[GenericProviderID] = []
  149. for tool in tools:
  150. keys = list(tool.keys())
  151. if len(keys) >= 4:
  152. provider_type = tool.get("provider_type", "")
  153. provider_id = tool.get("provider_id", "")
  154. if provider_type == ToolProviderType.API.value:
  155. try:
  156. uuid.UUID(provider_id)
  157. except Exception:
  158. continue
  159. api_provider_ids.append(provider_id)
  160. if provider_type == ToolProviderType.BUILT_IN.value:
  161. try:
  162. # check if it's hardcoded
  163. try:
  164. ToolManager.get_hardcoded_provider(provider_id)
  165. is_hardcoded = True
  166. except Exception:
  167. is_hardcoded = False
  168. provider_id = GenericProviderID(provider_id, is_hardcoded)
  169. except Exception:
  170. continue
  171. builtin_provider_ids.append(provider_id)
  172. if not api_provider_ids and not builtin_provider_ids:
  173. return []
  174. with Session(db.engine) as session:
  175. if api_provider_ids:
  176. existing_api_providers = [
  177. api_provider.id
  178. for api_provider in session.execute(
  179. text("SELECT id FROM tool_api_providers WHERE id IN :provider_ids"),
  180. {"provider_ids": tuple(api_provider_ids)},
  181. ).fetchall()
  182. ]
  183. else:
  184. existing_api_providers = []
  185. if builtin_provider_ids:
  186. # get the non-hardcoded builtin providers
  187. non_hardcoded_builtin_providers = [
  188. provider_id for provider_id in builtin_provider_ids if not provider_id.is_hardcoded
  189. ]
  190. if non_hardcoded_builtin_providers:
  191. existence = list(PluginService.check_tools_existence(self.tenant_id, non_hardcoded_builtin_providers))
  192. else:
  193. existence = []
  194. # add the hardcoded builtin providers
  195. existence.extend([True] * (len(builtin_provider_ids) - len(non_hardcoded_builtin_providers)))
  196. builtin_provider_ids = non_hardcoded_builtin_providers + [
  197. provider_id for provider_id in builtin_provider_ids if provider_id.is_hardcoded
  198. ]
  199. else:
  200. existence = []
  201. existing_builtin_providers = {
  202. provider_id.provider_name: existence[i] for i, provider_id in enumerate(builtin_provider_ids)
  203. }
  204. deleted_tools = []
  205. for tool in tools:
  206. keys = list(tool.keys())
  207. if len(keys) >= 4:
  208. provider_type = tool.get("provider_type", "")
  209. provider_id = tool.get("provider_id", "")
  210. if provider_type == ToolProviderType.API.value:
  211. if uuid.UUID(provider_id) not in existing_api_providers:
  212. deleted_tools.append(
  213. {
  214. "type": ToolProviderType.API.value,
  215. "tool_name": tool["tool_name"],
  216. "provider_id": provider_id,
  217. }
  218. )
  219. if provider_type == ToolProviderType.BUILT_IN.value:
  220. generic_provider_id = GenericProviderID(provider_id)
  221. if not existing_builtin_providers[generic_provider_id.provider_name]:
  222. deleted_tools.append(
  223. {
  224. "type": ToolProviderType.BUILT_IN.value,
  225. "tool_name": tool["tool_name"],
  226. "provider_id": provider_id, # use the original one
  227. }
  228. )
  229. return deleted_tools
  230. @property
  231. def tags(self):
  232. tags = (
  233. db.session.query(Tag)
  234. .join(TagBinding, Tag.id == TagBinding.tag_id)
  235. .where(
  236. TagBinding.target_id == self.id,
  237. TagBinding.tenant_id == self.tenant_id,
  238. Tag.tenant_id == self.tenant_id,
  239. Tag.type == "app",
  240. )
  241. .all()
  242. )
  243. return tags or []
  244. @property
  245. def author_name(self):
  246. if self.created_by:
  247. account = db.session.query(Account).where(Account.id == self.created_by).first()
  248. if account:
  249. return account.name
  250. return None
  251. class AppModelConfig(Base):
  252. __tablename__ = "app_model_configs"
  253. __table_args__ = (sa.PrimaryKeyConstraint("id", name="app_model_config_pkey"), sa.Index("app_app_id_idx", "app_id"))
  254. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  255. app_id = mapped_column(StringUUID, nullable=False)
  256. provider = mapped_column(String(255), nullable=True)
  257. model_id = mapped_column(String(255), nullable=True)
  258. configs = mapped_column(sa.JSON, nullable=True)
  259. created_by = mapped_column(StringUUID, nullable=True)
  260. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  261. updated_by = mapped_column(StringUUID, nullable=True)
  262. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  263. opening_statement = mapped_column(sa.Text)
  264. suggested_questions = mapped_column(sa.Text)
  265. suggested_questions_after_answer = mapped_column(sa.Text)
  266. speech_to_text = mapped_column(sa.Text)
  267. text_to_speech = mapped_column(sa.Text)
  268. more_like_this = mapped_column(sa.Text)
  269. model = mapped_column(sa.Text)
  270. user_input_form = mapped_column(sa.Text)
  271. dataset_query_variable = mapped_column(String(255))
  272. pre_prompt = mapped_column(sa.Text)
  273. agent_mode = mapped_column(sa.Text)
  274. sensitive_word_avoidance = mapped_column(sa.Text)
  275. retriever_resource = mapped_column(sa.Text)
  276. prompt_type = mapped_column(String(255), nullable=False, server_default=sa.text("'simple'::character varying"))
  277. chat_prompt_config = mapped_column(sa.Text)
  278. completion_prompt_config = mapped_column(sa.Text)
  279. dataset_configs = mapped_column(sa.Text)
  280. external_data_tools = mapped_column(sa.Text)
  281. file_upload = mapped_column(sa.Text)
  282. @property
  283. def app(self):
  284. app = db.session.query(App).where(App.id == self.app_id).first()
  285. return app
  286. @property
  287. def model_dict(self) -> dict:
  288. return json.loads(self.model) if self.model else {}
  289. @property
  290. def suggested_questions_list(self) -> list:
  291. return json.loads(self.suggested_questions) if self.suggested_questions else []
  292. @property
  293. def suggested_questions_after_answer_dict(self) -> dict:
  294. return (
  295. json.loads(self.suggested_questions_after_answer)
  296. if self.suggested_questions_after_answer
  297. else {"enabled": False}
  298. )
  299. @property
  300. def speech_to_text_dict(self) -> dict:
  301. return json.loads(self.speech_to_text) if self.speech_to_text else {"enabled": False}
  302. @property
  303. def text_to_speech_dict(self) -> dict:
  304. return json.loads(self.text_to_speech) if self.text_to_speech else {"enabled": False}
  305. @property
  306. def retriever_resource_dict(self) -> dict:
  307. return json.loads(self.retriever_resource) if self.retriever_resource else {"enabled": True}
  308. @property
  309. def annotation_reply_dict(self) -> dict:
  310. annotation_setting = (
  311. db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == self.app_id).first()
  312. )
  313. if annotation_setting:
  314. collection_binding_detail = annotation_setting.collection_binding_detail
  315. if not collection_binding_detail:
  316. raise ValueError("Collection binding detail not found")
  317. return {
  318. "id": annotation_setting.id,
  319. "enabled": True,
  320. "score_threshold": annotation_setting.score_threshold,
  321. "embedding_model": {
  322. "embedding_provider_name": collection_binding_detail.provider_name,
  323. "embedding_model_name": collection_binding_detail.model_name,
  324. },
  325. }
  326. else:
  327. return {"enabled": False}
  328. @property
  329. def more_like_this_dict(self) -> dict:
  330. return json.loads(self.more_like_this) if self.more_like_this else {"enabled": False}
  331. @property
  332. def sensitive_word_avoidance_dict(self) -> dict:
  333. return (
  334. json.loads(self.sensitive_word_avoidance)
  335. if self.sensitive_word_avoidance
  336. else {"enabled": False, "type": "", "configs": []}
  337. )
  338. @property
  339. def external_data_tools_list(self) -> list[dict]:
  340. return json.loads(self.external_data_tools) if self.external_data_tools else []
  341. @property
  342. def user_input_form_list(self):
  343. return json.loads(self.user_input_form) if self.user_input_form else []
  344. @property
  345. def agent_mode_dict(self) -> dict:
  346. return (
  347. json.loads(self.agent_mode)
  348. if self.agent_mode
  349. else {"enabled": False, "strategy": None, "tools": [], "prompt": None}
  350. )
  351. @property
  352. def chat_prompt_config_dict(self) -> dict:
  353. return json.loads(self.chat_prompt_config) if self.chat_prompt_config else {}
  354. @property
  355. def completion_prompt_config_dict(self) -> dict:
  356. return json.loads(self.completion_prompt_config) if self.completion_prompt_config else {}
  357. @property
  358. def dataset_configs_dict(self) -> dict:
  359. if self.dataset_configs:
  360. dataset_configs: dict = json.loads(self.dataset_configs)
  361. if "retrieval_model" not in dataset_configs:
  362. return {"retrieval_model": "single"}
  363. else:
  364. return dataset_configs
  365. return {
  366. "retrieval_model": "multiple",
  367. }
  368. @property
  369. def file_upload_dict(self) -> dict:
  370. return (
  371. json.loads(self.file_upload)
  372. if self.file_upload
  373. else {
  374. "image": {
  375. "enabled": False,
  376. "number_limits": DEFAULT_FILE_NUMBER_LIMITS,
  377. "detail": "high",
  378. "transfer_methods": ["remote_url", "local_file"],
  379. }
  380. }
  381. )
  382. def to_dict(self) -> dict:
  383. return {
  384. "opening_statement": self.opening_statement,
  385. "suggested_questions": self.suggested_questions_list,
  386. "suggested_questions_after_answer": self.suggested_questions_after_answer_dict,
  387. "speech_to_text": self.speech_to_text_dict,
  388. "text_to_speech": self.text_to_speech_dict,
  389. "retriever_resource": self.retriever_resource_dict,
  390. "annotation_reply": self.annotation_reply_dict,
  391. "more_like_this": self.more_like_this_dict,
  392. "sensitive_word_avoidance": self.sensitive_word_avoidance_dict,
  393. "external_data_tools": self.external_data_tools_list,
  394. "model": self.model_dict,
  395. "user_input_form": self.user_input_form_list,
  396. "dataset_query_variable": self.dataset_query_variable,
  397. "pre_prompt": self.pre_prompt,
  398. "agent_mode": self.agent_mode_dict,
  399. "prompt_type": self.prompt_type,
  400. "chat_prompt_config": self.chat_prompt_config_dict,
  401. "completion_prompt_config": self.completion_prompt_config_dict,
  402. "dataset_configs": self.dataset_configs_dict,
  403. "file_upload": self.file_upload_dict,
  404. }
  405. def from_model_config_dict(self, model_config: Mapping[str, Any]):
  406. self.opening_statement = model_config.get("opening_statement")
  407. self.suggested_questions = (
  408. json.dumps(model_config["suggested_questions"]) if model_config.get("suggested_questions") else None
  409. )
  410. self.suggested_questions_after_answer = (
  411. json.dumps(model_config["suggested_questions_after_answer"])
  412. if model_config.get("suggested_questions_after_answer")
  413. else None
  414. )
  415. self.speech_to_text = json.dumps(model_config["speech_to_text"]) if model_config.get("speech_to_text") else None
  416. self.text_to_speech = json.dumps(model_config["text_to_speech"]) if model_config.get("text_to_speech") else None
  417. self.more_like_this = json.dumps(model_config["more_like_this"]) if model_config.get("more_like_this") else None
  418. self.sensitive_word_avoidance = (
  419. json.dumps(model_config["sensitive_word_avoidance"])
  420. if model_config.get("sensitive_word_avoidance")
  421. else None
  422. )
  423. self.external_data_tools = (
  424. json.dumps(model_config["external_data_tools"]) if model_config.get("external_data_tools") else None
  425. )
  426. self.model = json.dumps(model_config["model"]) if model_config.get("model") else None
  427. self.user_input_form = (
  428. json.dumps(model_config["user_input_form"]) if model_config.get("user_input_form") else None
  429. )
  430. self.dataset_query_variable = model_config.get("dataset_query_variable")
  431. self.pre_prompt = model_config["pre_prompt"]
  432. self.agent_mode = json.dumps(model_config["agent_mode"]) if model_config.get("agent_mode") else None
  433. self.retriever_resource = (
  434. json.dumps(model_config["retriever_resource"]) if model_config.get("retriever_resource") else None
  435. )
  436. self.prompt_type = model_config.get("prompt_type", "simple")
  437. self.chat_prompt_config = (
  438. json.dumps(model_config.get("chat_prompt_config")) if model_config.get("chat_prompt_config") else None
  439. )
  440. self.completion_prompt_config = (
  441. json.dumps(model_config.get("completion_prompt_config"))
  442. if model_config.get("completion_prompt_config")
  443. else None
  444. )
  445. self.dataset_configs = (
  446. json.dumps(model_config.get("dataset_configs")) if model_config.get("dataset_configs") else None
  447. )
  448. self.file_upload = json.dumps(model_config.get("file_upload")) if model_config.get("file_upload") else None
  449. return self
  450. class RecommendedApp(Base):
  451. __tablename__ = "recommended_apps"
  452. __table_args__ = (
  453. sa.PrimaryKeyConstraint("id", name="recommended_app_pkey"),
  454. sa.Index("recommended_app_app_id_idx", "app_id"),
  455. sa.Index("recommended_app_is_listed_idx", "is_listed", "language"),
  456. )
  457. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  458. app_id = mapped_column(StringUUID, nullable=False)
  459. description = mapped_column(sa.JSON, nullable=False)
  460. copyright: Mapped[str] = mapped_column(String(255), nullable=False)
  461. privacy_policy: Mapped[str] = mapped_column(String(255), nullable=False)
  462. custom_disclaimer: Mapped[str] = mapped_column(sa.TEXT, default="")
  463. category: Mapped[str] = mapped_column(String(255), nullable=False)
  464. position: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  465. is_listed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
  466. install_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  467. language = mapped_column(String(255), nullable=False, server_default=sa.text("'en-US'::character varying"))
  468. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  469. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  470. @property
  471. def app(self):
  472. app = db.session.query(App).where(App.id == self.app_id).first()
  473. return app
  474. class InstalledApp(Base):
  475. __tablename__ = "installed_apps"
  476. __table_args__ = (
  477. sa.PrimaryKeyConstraint("id", name="installed_app_pkey"),
  478. sa.Index("installed_app_tenant_id_idx", "tenant_id"),
  479. sa.Index("installed_app_app_id_idx", "app_id"),
  480. sa.UniqueConstraint("tenant_id", "app_id", name="unique_tenant_app"),
  481. )
  482. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  483. tenant_id = mapped_column(StringUUID, nullable=False)
  484. app_id = mapped_column(StringUUID, nullable=False)
  485. app_owner_tenant_id = mapped_column(StringUUID, nullable=False)
  486. position: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  487. is_pinned: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  488. last_used_at = mapped_column(sa.DateTime, nullable=True)
  489. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  490. @property
  491. def app(self):
  492. app = db.session.query(App).where(App.id == self.app_id).first()
  493. return app
  494. @property
  495. def tenant(self):
  496. tenant = db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  497. return tenant
  498. class OAuthProviderApp(Base):
  499. """
  500. Globally shared OAuth provider app information.
  501. Only for Dify Cloud.
  502. """
  503. __tablename__ = "oauth_provider_apps"
  504. __table_args__ = (
  505. sa.PrimaryKeyConstraint("id", name="oauth_provider_app_pkey"),
  506. sa.Index("oauth_provider_app_client_id_idx", "client_id"),
  507. )
  508. id = mapped_column(StringUUID, server_default=sa.text("uuidv7()"))
  509. app_icon = mapped_column(String(255), nullable=False)
  510. app_label = mapped_column(sa.JSON, nullable=False, server_default="{}")
  511. client_id = mapped_column(String(255), nullable=False)
  512. client_secret = mapped_column(String(255), nullable=False)
  513. redirect_uris = mapped_column(sa.JSON, nullable=False, server_default="[]")
  514. scope = mapped_column(
  515. String(255),
  516. nullable=False,
  517. server_default=sa.text("'read:name read:email read:avatar read:interface_language read:timezone'"),
  518. )
  519. created_at = mapped_column(sa.DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)"))
  520. class Conversation(Base):
  521. __tablename__ = "conversations"
  522. __table_args__ = (
  523. sa.PrimaryKeyConstraint("id", name="conversation_pkey"),
  524. sa.Index("conversation_app_from_user_idx", "app_id", "from_source", "from_end_user_id"),
  525. )
  526. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  527. app_id = mapped_column(StringUUID, nullable=False)
  528. app_model_config_id = mapped_column(StringUUID, nullable=True)
  529. model_provider = mapped_column(String(255), nullable=True)
  530. override_model_configs = mapped_column(sa.Text)
  531. model_id = mapped_column(String(255), nullable=True)
  532. mode: Mapped[str] = mapped_column(String(255))
  533. name: Mapped[str] = mapped_column(String(255), nullable=False)
  534. summary = mapped_column(sa.Text)
  535. _inputs: Mapped[dict] = mapped_column("inputs", sa.JSON)
  536. introduction = mapped_column(sa.Text)
  537. system_instruction = mapped_column(sa.Text)
  538. system_instruction_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  539. status: Mapped[str] = mapped_column(String(255), nullable=False)
  540. # The `invoke_from` records how the conversation is created.
  541. #
  542. # Its value corresponds to the members of `InvokeFrom`.
  543. # (api/core/app/entities/app_invoke_entities.py)
  544. invoke_from = mapped_column(String(255), nullable=True)
  545. # ref: ConversationSource.
  546. from_source: Mapped[str] = mapped_column(String(255), nullable=False)
  547. from_end_user_id = mapped_column(StringUUID)
  548. from_account_id = mapped_column(StringUUID)
  549. read_at = mapped_column(sa.DateTime)
  550. read_account_id = mapped_column(StringUUID)
  551. dialogue_count: Mapped[int] = mapped_column(default=0)
  552. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  553. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  554. messages = db.relationship("Message", backref="conversation", lazy="select", passive_deletes="all")
  555. message_annotations = db.relationship(
  556. "MessageAnnotation", backref="conversation", lazy="select", passive_deletes="all"
  557. )
  558. is_deleted: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  559. @property
  560. def inputs(self):
  561. inputs = self._inputs.copy()
  562. # Convert file mapping to File object
  563. for key, value in inputs.items():
  564. # NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
  565. from factories import file_factory
  566. if isinstance(value, dict) and value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
  567. if value["transfer_method"] == FileTransferMethod.TOOL_FILE:
  568. value["tool_file_id"] = value["related_id"]
  569. elif value["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  570. value["upload_file_id"] = value["related_id"]
  571. inputs[key] = file_factory.build_from_mapping(mapping=value, tenant_id=value["tenant_id"])
  572. elif isinstance(value, list) and all(
  573. isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
  574. ):
  575. inputs[key] = []
  576. for item in value:
  577. if item["transfer_method"] == FileTransferMethod.TOOL_FILE:
  578. item["tool_file_id"] = item["related_id"]
  579. elif item["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  580. item["upload_file_id"] = item["related_id"]
  581. inputs[key].append(file_factory.build_from_mapping(mapping=item, tenant_id=item["tenant_id"]))
  582. return inputs
  583. @inputs.setter
  584. def inputs(self, value: Mapping[str, Any]):
  585. inputs = dict(value)
  586. for k, v in inputs.items():
  587. if isinstance(v, File):
  588. inputs[k] = v.model_dump()
  589. elif isinstance(v, list) and all(isinstance(item, File) for item in v):
  590. inputs[k] = [item.model_dump() for item in v]
  591. self._inputs = inputs
  592. @property
  593. def model_config(self):
  594. model_config = {}
  595. app_model_config: Optional[AppModelConfig] = None
  596. if self.mode == AppMode.ADVANCED_CHAT.value:
  597. if self.override_model_configs:
  598. override_model_configs = json.loads(self.override_model_configs)
  599. model_config = override_model_configs
  600. else:
  601. if self.override_model_configs:
  602. override_model_configs = json.loads(self.override_model_configs)
  603. if "model" in override_model_configs:
  604. app_model_config = AppModelConfig()
  605. app_model_config = app_model_config.from_model_config_dict(override_model_configs)
  606. model_config = app_model_config.to_dict()
  607. else:
  608. model_config["configs"] = override_model_configs
  609. else:
  610. app_model_config = (
  611. db.session.query(AppModelConfig).where(AppModelConfig.id == self.app_model_config_id).first()
  612. )
  613. if app_model_config:
  614. model_config = app_model_config.to_dict()
  615. model_config["model_id"] = self.model_id
  616. model_config["provider"] = self.model_provider
  617. return model_config
  618. @property
  619. def summary_or_query(self):
  620. if self.summary:
  621. return self.summary
  622. else:
  623. first_message = self.first_message
  624. if first_message:
  625. return first_message.query
  626. else:
  627. return ""
  628. @property
  629. def annotated(self):
  630. return db.session.query(MessageAnnotation).where(MessageAnnotation.conversation_id == self.id).count() > 0
  631. @property
  632. def annotation(self):
  633. return db.session.query(MessageAnnotation).where(MessageAnnotation.conversation_id == self.id).first()
  634. @property
  635. def message_count(self):
  636. return db.session.query(Message).where(Message.conversation_id == self.id).count()
  637. @property
  638. def user_feedback_stats(self):
  639. like = (
  640. db.session.query(MessageFeedback)
  641. .where(
  642. MessageFeedback.conversation_id == self.id,
  643. MessageFeedback.from_source == "user",
  644. MessageFeedback.rating == "like",
  645. )
  646. .count()
  647. )
  648. dislike = (
  649. db.session.query(MessageFeedback)
  650. .where(
  651. MessageFeedback.conversation_id == self.id,
  652. MessageFeedback.from_source == "user",
  653. MessageFeedback.rating == "dislike",
  654. )
  655. .count()
  656. )
  657. return {"like": like, "dislike": dislike}
  658. @property
  659. def admin_feedback_stats(self):
  660. like = (
  661. db.session.query(MessageFeedback)
  662. .where(
  663. MessageFeedback.conversation_id == self.id,
  664. MessageFeedback.from_source == "admin",
  665. MessageFeedback.rating == "like",
  666. )
  667. .count()
  668. )
  669. dislike = (
  670. db.session.query(MessageFeedback)
  671. .where(
  672. MessageFeedback.conversation_id == self.id,
  673. MessageFeedback.from_source == "admin",
  674. MessageFeedback.rating == "dislike",
  675. )
  676. .count()
  677. )
  678. return {"like": like, "dislike": dislike}
  679. @property
  680. def status_count(self):
  681. messages = db.session.query(Message).where(Message.conversation_id == self.id).all()
  682. status_counts = {
  683. WorkflowExecutionStatus.RUNNING: 0,
  684. WorkflowExecutionStatus.SUCCEEDED: 0,
  685. WorkflowExecutionStatus.FAILED: 0,
  686. WorkflowExecutionStatus.STOPPED: 0,
  687. WorkflowExecutionStatus.PARTIAL_SUCCEEDED: 0,
  688. }
  689. for message in messages:
  690. if message.workflow_run:
  691. status_counts[WorkflowExecutionStatus(message.workflow_run.status)] += 1
  692. return (
  693. {
  694. "success": status_counts[WorkflowExecutionStatus.SUCCEEDED],
  695. "failed": status_counts[WorkflowExecutionStatus.FAILED],
  696. "partial_success": status_counts[WorkflowExecutionStatus.PARTIAL_SUCCEEDED],
  697. }
  698. if messages
  699. else None
  700. )
  701. @property
  702. def first_message(self):
  703. return (
  704. db.session.query(Message)
  705. .where(Message.conversation_id == self.id)
  706. .order_by(Message.created_at.asc())
  707. .first()
  708. )
  709. @property
  710. def app(self):
  711. with Session(db.engine, expire_on_commit=False) as session:
  712. return session.query(App).where(App.id == self.app_id).first()
  713. @property
  714. def from_end_user_session_id(self):
  715. if self.from_end_user_id:
  716. end_user = db.session.query(EndUser).where(EndUser.id == self.from_end_user_id).first()
  717. if end_user:
  718. return end_user.session_id
  719. return None
  720. @property
  721. def from_account_name(self):
  722. if self.from_account_id:
  723. account = db.session.query(Account).where(Account.id == self.from_account_id).first()
  724. if account:
  725. return account.name
  726. return None
  727. @property
  728. def in_debug_mode(self):
  729. return self.override_model_configs is not None
  730. def to_dict(self):
  731. return {
  732. "id": self.id,
  733. "app_id": self.app_id,
  734. "app_model_config_id": self.app_model_config_id,
  735. "model_provider": self.model_provider,
  736. "override_model_configs": self.override_model_configs,
  737. "model_id": self.model_id,
  738. "mode": self.mode,
  739. "name": self.name,
  740. "summary": self.summary,
  741. "inputs": self.inputs,
  742. "introduction": self.introduction,
  743. "system_instruction": self.system_instruction,
  744. "system_instruction_tokens": self.system_instruction_tokens,
  745. "status": self.status,
  746. "invoke_from": self.invoke_from,
  747. "from_source": self.from_source,
  748. "from_end_user_id": self.from_end_user_id,
  749. "from_account_id": self.from_account_id,
  750. "read_at": self.read_at,
  751. "read_account_id": self.read_account_id,
  752. "dialogue_count": self.dialogue_count,
  753. "created_at": self.created_at,
  754. "updated_at": self.updated_at,
  755. }
  756. class Message(Base):
  757. __tablename__ = "messages"
  758. __table_args__ = (
  759. PrimaryKeyConstraint("id", name="message_pkey"),
  760. Index("message_app_id_idx", "app_id", "created_at"),
  761. Index("message_conversation_id_idx", "conversation_id"),
  762. Index("message_end_user_idx", "app_id", "from_source", "from_end_user_id"),
  763. Index("message_account_idx", "app_id", "from_source", "from_account_id"),
  764. Index("message_workflow_run_id_idx", "conversation_id", "workflow_run_id"),
  765. Index("message_created_at_idx", "created_at"),
  766. )
  767. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  768. app_id = mapped_column(StringUUID, nullable=False)
  769. model_provider = mapped_column(String(255), nullable=True)
  770. model_id = mapped_column(String(255), nullable=True)
  771. override_model_configs = mapped_column(sa.Text)
  772. conversation_id = mapped_column(StringUUID, sa.ForeignKey("conversations.id"), nullable=False)
  773. _inputs: Mapped[dict] = mapped_column("inputs", sa.JSON)
  774. query: Mapped[str] = mapped_column(sa.Text, nullable=False)
  775. message = mapped_column(sa.JSON, nullable=False)
  776. message_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  777. message_unit_price = mapped_column(sa.Numeric(10, 4), nullable=False)
  778. message_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  779. answer: Mapped[str] = mapped_column(sa.Text, nullable=False)
  780. answer_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  781. answer_unit_price = mapped_column(sa.Numeric(10, 4), nullable=False)
  782. answer_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  783. parent_message_id = mapped_column(StringUUID, nullable=True)
  784. provider_response_latency = mapped_column(sa.Float, nullable=False, server_default=sa.text("0"))
  785. total_price = mapped_column(sa.Numeric(10, 7))
  786. currency: Mapped[str] = mapped_column(String(255), nullable=False)
  787. status = mapped_column(String(255), nullable=False, server_default=sa.text("'normal'::character varying"))
  788. error = mapped_column(sa.Text)
  789. message_metadata = mapped_column(sa.Text)
  790. invoke_from: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
  791. from_source: Mapped[str] = mapped_column(String(255), nullable=False)
  792. from_end_user_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  793. from_account_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  794. created_at: Mapped[datetime] = mapped_column(sa.DateTime, server_default=func.current_timestamp())
  795. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  796. agent_based: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  797. workflow_run_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  798. @property
  799. def inputs(self):
  800. inputs = self._inputs.copy()
  801. for key, value in inputs.items():
  802. # NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
  803. from factories import file_factory
  804. if isinstance(value, dict) and value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
  805. if value["transfer_method"] == FileTransferMethod.TOOL_FILE:
  806. value["tool_file_id"] = value["related_id"]
  807. elif value["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  808. value["upload_file_id"] = value["related_id"]
  809. inputs[key] = file_factory.build_from_mapping(mapping=value, tenant_id=value["tenant_id"])
  810. elif isinstance(value, list) and all(
  811. isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
  812. ):
  813. inputs[key] = []
  814. for item in value:
  815. if item["transfer_method"] == FileTransferMethod.TOOL_FILE:
  816. item["tool_file_id"] = item["related_id"]
  817. elif item["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  818. item["upload_file_id"] = item["related_id"]
  819. inputs[key].append(file_factory.build_from_mapping(mapping=item, tenant_id=item["tenant_id"]))
  820. return inputs
  821. @inputs.setter
  822. def inputs(self, value: Mapping[str, Any]):
  823. inputs = dict(value)
  824. for k, v in inputs.items():
  825. if isinstance(v, File):
  826. inputs[k] = v.model_dump()
  827. elif isinstance(v, list) and all(isinstance(item, File) for item in v):
  828. inputs[k] = [item.model_dump() for item in v]
  829. self._inputs = inputs
  830. @property
  831. def re_sign_file_url_answer(self) -> str:
  832. if not self.answer:
  833. return self.answer
  834. pattern = r"\[!?.*?\]\((((http|https):\/\/.+)?\/files\/(tools\/)?[\w-]+.*?timestamp=.*&nonce=.*&sign=.*)\)"
  835. matches = re.findall(pattern, self.answer)
  836. if not matches:
  837. return self.answer
  838. urls = [match[0] for match in matches]
  839. # remove duplicate urls
  840. urls = list(set(urls))
  841. if not urls:
  842. return self.answer
  843. re_sign_file_url_answer = self.answer
  844. for url in urls:
  845. if "files/tools" in url:
  846. # get tool file id
  847. tool_file_id_pattern = r"\/files\/tools\/([\.\w-]+)?\?timestamp="
  848. result = re.search(tool_file_id_pattern, url)
  849. if not result:
  850. continue
  851. tool_file_id = result.group(1)
  852. # get extension
  853. if "." in tool_file_id:
  854. split_result = tool_file_id.split(".")
  855. extension = f".{split_result[-1]}"
  856. if len(extension) > 10:
  857. extension = ".bin"
  858. tool_file_id = split_result[0]
  859. else:
  860. extension = ".bin"
  861. if not tool_file_id:
  862. continue
  863. sign_url = sign_tool_file(tool_file_id=tool_file_id, extension=extension)
  864. elif "file-preview" in url:
  865. # get upload file id
  866. upload_file_id_pattern = r"\/files\/([\w-]+)\/file-preview?\?timestamp="
  867. result = re.search(upload_file_id_pattern, url)
  868. if not result:
  869. continue
  870. upload_file_id = result.group(1)
  871. if not upload_file_id:
  872. continue
  873. sign_url = file_helpers.get_signed_file_url(upload_file_id)
  874. elif "image-preview" in url:
  875. # image-preview is deprecated, use file-preview instead
  876. upload_file_id_pattern = r"\/files\/([\w-]+)\/image-preview?\?timestamp="
  877. result = re.search(upload_file_id_pattern, url)
  878. if not result:
  879. continue
  880. upload_file_id = result.group(1)
  881. if not upload_file_id:
  882. continue
  883. sign_url = file_helpers.get_signed_file_url(upload_file_id)
  884. else:
  885. continue
  886. # if as_attachment is in the url, add it to the sign_url.
  887. if "as_attachment" in url:
  888. sign_url += "&as_attachment=true"
  889. re_sign_file_url_answer = re_sign_file_url_answer.replace(url, sign_url)
  890. return re_sign_file_url_answer
  891. @property
  892. def user_feedback(self):
  893. feedback = (
  894. db.session.query(MessageFeedback)
  895. .where(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "user")
  896. .first()
  897. )
  898. return feedback
  899. @property
  900. def admin_feedback(self):
  901. feedback = (
  902. db.session.query(MessageFeedback)
  903. .where(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "admin")
  904. .first()
  905. )
  906. return feedback
  907. @property
  908. def feedbacks(self):
  909. feedbacks = db.session.query(MessageFeedback).where(MessageFeedback.message_id == self.id).all()
  910. return feedbacks
  911. @property
  912. def annotation(self):
  913. annotation = db.session.query(MessageAnnotation).where(MessageAnnotation.message_id == self.id).first()
  914. return annotation
  915. @property
  916. def annotation_hit_history(self):
  917. annotation_history = (
  918. db.session.query(AppAnnotationHitHistory).where(AppAnnotationHitHistory.message_id == self.id).first()
  919. )
  920. if annotation_history:
  921. annotation = (
  922. db.session.query(MessageAnnotation)
  923. .where(MessageAnnotation.id == annotation_history.annotation_id)
  924. .first()
  925. )
  926. return annotation
  927. return None
  928. @property
  929. def app_model_config(self):
  930. conversation = db.session.query(Conversation).where(Conversation.id == self.conversation_id).first()
  931. if conversation:
  932. return db.session.query(AppModelConfig).where(AppModelConfig.id == conversation.app_model_config_id).first()
  933. return None
  934. @property
  935. def in_debug_mode(self):
  936. return self.override_model_configs is not None
  937. @property
  938. def message_metadata_dict(self) -> dict:
  939. return json.loads(self.message_metadata) if self.message_metadata else {}
  940. @property
  941. def agent_thoughts(self):
  942. return (
  943. db.session.query(MessageAgentThought)
  944. .where(MessageAgentThought.message_id == self.id)
  945. .order_by(MessageAgentThought.position.asc())
  946. .all()
  947. )
  948. @property
  949. def retriever_resources(self):
  950. return self.message_metadata_dict.get("retriever_resources") if self.message_metadata else []
  951. @property
  952. def message_files(self):
  953. from factories import file_factory
  954. message_files = db.session.query(MessageFile).where(MessageFile.message_id == self.id).all()
  955. current_app = db.session.query(App).where(App.id == self.app_id).first()
  956. if not current_app:
  957. raise ValueError(f"App {self.app_id} not found")
  958. files = []
  959. for message_file in message_files:
  960. if message_file.transfer_method == FileTransferMethod.LOCAL_FILE.value:
  961. if message_file.upload_file_id is None:
  962. raise ValueError(f"MessageFile {message_file.id} is a local file but has no upload_file_id")
  963. file = file_factory.build_from_mapping(
  964. mapping={
  965. "id": message_file.id,
  966. "type": message_file.type,
  967. "transfer_method": message_file.transfer_method,
  968. "upload_file_id": message_file.upload_file_id,
  969. },
  970. tenant_id=current_app.tenant_id,
  971. )
  972. elif message_file.transfer_method == FileTransferMethod.REMOTE_URL.value:
  973. if message_file.url is None:
  974. raise ValueError(f"MessageFile {message_file.id} is a remote url but has no url")
  975. file = file_factory.build_from_mapping(
  976. mapping={
  977. "id": message_file.id,
  978. "type": message_file.type,
  979. "transfer_method": message_file.transfer_method,
  980. "upload_file_id": message_file.upload_file_id,
  981. "url": message_file.url,
  982. },
  983. tenant_id=current_app.tenant_id,
  984. )
  985. elif message_file.transfer_method == FileTransferMethod.TOOL_FILE.value:
  986. if message_file.upload_file_id is None:
  987. assert message_file.url is not None
  988. message_file.upload_file_id = message_file.url.split("/")[-1].split(".")[0]
  989. mapping = {
  990. "id": message_file.id,
  991. "type": message_file.type,
  992. "transfer_method": message_file.transfer_method,
  993. "tool_file_id": message_file.upload_file_id,
  994. }
  995. file = file_factory.build_from_mapping(
  996. mapping=mapping,
  997. tenant_id=current_app.tenant_id,
  998. )
  999. else:
  1000. raise ValueError(
  1001. f"MessageFile {message_file.id} has an invalid transfer_method {message_file.transfer_method}"
  1002. )
  1003. files.append(file)
  1004. result = [
  1005. {"belongs_to": message_file.belongs_to, "upload_file_id": message_file.upload_file_id, **file.to_dict()}
  1006. for (file, message_file) in zip(files, message_files)
  1007. ]
  1008. db.session.commit()
  1009. return result
  1010. @property
  1011. def workflow_run(self):
  1012. if self.workflow_run_id:
  1013. from .workflow import WorkflowRun
  1014. return db.session.query(WorkflowRun).where(WorkflowRun.id == self.workflow_run_id).first()
  1015. return None
  1016. def to_dict(self) -> dict:
  1017. return {
  1018. "id": self.id,
  1019. "app_id": self.app_id,
  1020. "conversation_id": self.conversation_id,
  1021. "model_id": self.model_id,
  1022. "inputs": self.inputs,
  1023. "query": self.query,
  1024. "total_price": self.total_price,
  1025. "message": self.message,
  1026. "answer": self.answer,
  1027. "status": self.status,
  1028. "error": self.error,
  1029. "message_metadata": self.message_metadata_dict,
  1030. "from_source": self.from_source,
  1031. "from_end_user_id": self.from_end_user_id,
  1032. "from_account_id": self.from_account_id,
  1033. "created_at": self.created_at.isoformat(),
  1034. "updated_at": self.updated_at.isoformat(),
  1035. "agent_based": self.agent_based,
  1036. "workflow_run_id": self.workflow_run_id,
  1037. }
  1038. @classmethod
  1039. def from_dict(cls, data: dict):
  1040. return cls(
  1041. id=data["id"],
  1042. app_id=data["app_id"],
  1043. conversation_id=data["conversation_id"],
  1044. model_id=data["model_id"],
  1045. inputs=data["inputs"],
  1046. total_price=data["total_price"],
  1047. query=data["query"],
  1048. message=data["message"],
  1049. answer=data["answer"],
  1050. status=data["status"],
  1051. error=data["error"],
  1052. message_metadata=json.dumps(data["message_metadata"]),
  1053. from_source=data["from_source"],
  1054. from_end_user_id=data["from_end_user_id"],
  1055. from_account_id=data["from_account_id"],
  1056. created_at=data["created_at"],
  1057. updated_at=data["updated_at"],
  1058. agent_based=data["agent_based"],
  1059. workflow_run_id=data["workflow_run_id"],
  1060. )
  1061. class MessageFeedback(Base):
  1062. __tablename__ = "message_feedbacks"
  1063. __table_args__ = (
  1064. sa.PrimaryKeyConstraint("id", name="message_feedback_pkey"),
  1065. sa.Index("message_feedback_app_idx", "app_id"),
  1066. sa.Index("message_feedback_message_idx", "message_id", "from_source"),
  1067. sa.Index("message_feedback_conversation_idx", "conversation_id", "from_source", "rating"),
  1068. )
  1069. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1070. app_id = mapped_column(StringUUID, nullable=False)
  1071. conversation_id = mapped_column(StringUUID, nullable=False)
  1072. message_id = mapped_column(StringUUID, nullable=False)
  1073. rating: Mapped[str] = mapped_column(String(255), nullable=False)
  1074. content = mapped_column(sa.Text)
  1075. from_source: Mapped[str] = mapped_column(String(255), nullable=False)
  1076. from_end_user_id = mapped_column(StringUUID)
  1077. from_account_id = mapped_column(StringUUID)
  1078. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1079. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1080. @property
  1081. def from_account(self):
  1082. account = db.session.query(Account).where(Account.id == self.from_account_id).first()
  1083. return account
  1084. def to_dict(self):
  1085. return {
  1086. "id": str(self.id),
  1087. "app_id": str(self.app_id),
  1088. "conversation_id": str(self.conversation_id),
  1089. "message_id": str(self.message_id),
  1090. "rating": self.rating,
  1091. "content": self.content,
  1092. "from_source": self.from_source,
  1093. "from_end_user_id": str(self.from_end_user_id) if self.from_end_user_id else None,
  1094. "from_account_id": str(self.from_account_id) if self.from_account_id else None,
  1095. "created_at": self.created_at.isoformat(),
  1096. "updated_at": self.updated_at.isoformat(),
  1097. }
  1098. class MessageFile(Base):
  1099. __tablename__ = "message_files"
  1100. __table_args__ = (
  1101. sa.PrimaryKeyConstraint("id", name="message_file_pkey"),
  1102. sa.Index("message_file_message_idx", "message_id"),
  1103. sa.Index("message_file_created_by_idx", "created_by"),
  1104. )
  1105. def __init__(
  1106. self,
  1107. *,
  1108. message_id: str,
  1109. type: FileType,
  1110. transfer_method: FileTransferMethod,
  1111. url: str | None = None,
  1112. belongs_to: Literal["user", "assistant"] | None = None,
  1113. upload_file_id: str | None = None,
  1114. created_by_role: CreatorUserRole,
  1115. created_by: str,
  1116. ):
  1117. self.message_id = message_id
  1118. self.type = type
  1119. self.transfer_method = transfer_method
  1120. self.url = url
  1121. self.belongs_to = belongs_to
  1122. self.upload_file_id = upload_file_id
  1123. self.created_by_role = created_by_role.value
  1124. self.created_by = created_by
  1125. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1126. message_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1127. type: Mapped[str] = mapped_column(String(255), nullable=False)
  1128. transfer_method: Mapped[str] = mapped_column(String(255), nullable=False)
  1129. url: Mapped[Optional[str]] = mapped_column(sa.Text, nullable=True)
  1130. belongs_to: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
  1131. upload_file_id: Mapped[Optional[str]] = mapped_column(StringUUID, nullable=True)
  1132. created_by_role: Mapped[str] = mapped_column(String(255), nullable=False)
  1133. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1134. created_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1135. class MessageAnnotation(Base):
  1136. __tablename__ = "message_annotations"
  1137. __table_args__ = (
  1138. sa.PrimaryKeyConstraint("id", name="message_annotation_pkey"),
  1139. sa.Index("message_annotation_app_idx", "app_id"),
  1140. sa.Index("message_annotation_conversation_idx", "conversation_id"),
  1141. sa.Index("message_annotation_message_idx", "message_id"),
  1142. )
  1143. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1144. app_id: Mapped[str] = mapped_column(StringUUID)
  1145. conversation_id: Mapped[Optional[str]] = mapped_column(StringUUID, sa.ForeignKey("conversations.id"))
  1146. message_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  1147. question = mapped_column(sa.Text, nullable=True)
  1148. content = mapped_column(sa.Text, nullable=False)
  1149. hit_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  1150. account_id = mapped_column(StringUUID, nullable=False)
  1151. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1152. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1153. @property
  1154. def account(self):
  1155. account = db.session.query(Account).where(Account.id == self.account_id).first()
  1156. return account
  1157. @property
  1158. def annotation_create_account(self):
  1159. account = db.session.query(Account).where(Account.id == self.account_id).first()
  1160. return account
  1161. class AppAnnotationHitHistory(Base):
  1162. __tablename__ = "app_annotation_hit_histories"
  1163. __table_args__ = (
  1164. sa.PrimaryKeyConstraint("id", name="app_annotation_hit_histories_pkey"),
  1165. sa.Index("app_annotation_hit_histories_app_idx", "app_id"),
  1166. sa.Index("app_annotation_hit_histories_account_idx", "account_id"),
  1167. sa.Index("app_annotation_hit_histories_annotation_idx", "annotation_id"),
  1168. sa.Index("app_annotation_hit_histories_message_idx", "message_id"),
  1169. )
  1170. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1171. app_id = mapped_column(StringUUID, nullable=False)
  1172. annotation_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1173. source = mapped_column(sa.Text, nullable=False)
  1174. question = mapped_column(sa.Text, nullable=False)
  1175. account_id = mapped_column(StringUUID, nullable=False)
  1176. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1177. score = mapped_column(Float, nullable=False, server_default=sa.text("0"))
  1178. message_id = mapped_column(StringUUID, nullable=False)
  1179. annotation_question = mapped_column(sa.Text, nullable=False)
  1180. annotation_content = mapped_column(sa.Text, nullable=False)
  1181. @property
  1182. def account(self):
  1183. account = (
  1184. db.session.query(Account)
  1185. .join(MessageAnnotation, MessageAnnotation.account_id == Account.id)
  1186. .where(MessageAnnotation.id == self.annotation_id)
  1187. .first()
  1188. )
  1189. return account
  1190. @property
  1191. def annotation_create_account(self):
  1192. account = db.session.query(Account).where(Account.id == self.account_id).first()
  1193. return account
  1194. class AppAnnotationSetting(Base):
  1195. __tablename__ = "app_annotation_settings"
  1196. __table_args__ = (
  1197. sa.PrimaryKeyConstraint("id", name="app_annotation_settings_pkey"),
  1198. sa.Index("app_annotation_settings_app_idx", "app_id"),
  1199. )
  1200. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1201. app_id = mapped_column(StringUUID, nullable=False)
  1202. score_threshold = mapped_column(Float, nullable=False, server_default=sa.text("0"))
  1203. collection_binding_id = mapped_column(StringUUID, nullable=False)
  1204. created_user_id = mapped_column(StringUUID, nullable=False)
  1205. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1206. updated_user_id = mapped_column(StringUUID, nullable=False)
  1207. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1208. @property
  1209. def collection_binding_detail(self):
  1210. from .dataset import DatasetCollectionBinding
  1211. collection_binding_detail = (
  1212. db.session.query(DatasetCollectionBinding)
  1213. .where(DatasetCollectionBinding.id == self.collection_binding_id)
  1214. .first()
  1215. )
  1216. return collection_binding_detail
  1217. class OperationLog(Base):
  1218. __tablename__ = "operation_logs"
  1219. __table_args__ = (
  1220. sa.PrimaryKeyConstraint("id", name="operation_log_pkey"),
  1221. sa.Index("operation_log_account_action_idx", "tenant_id", "account_id", "action"),
  1222. )
  1223. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1224. tenant_id = mapped_column(StringUUID, nullable=False)
  1225. account_id = mapped_column(StringUUID, nullable=False)
  1226. action: Mapped[str] = mapped_column(String(255), nullable=False)
  1227. content = mapped_column(sa.JSON)
  1228. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1229. created_ip: Mapped[str] = mapped_column(String(255), nullable=False)
  1230. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1231. class EndUser(Base, UserMixin):
  1232. __tablename__ = "end_users"
  1233. __table_args__ = (
  1234. sa.PrimaryKeyConstraint("id", name="end_user_pkey"),
  1235. sa.Index("end_user_session_id_idx", "session_id", "type"),
  1236. sa.Index("end_user_tenant_session_id_idx", "tenant_id", "session_id", "type"),
  1237. )
  1238. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1239. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1240. app_id = mapped_column(StringUUID, nullable=True)
  1241. type: Mapped[str] = mapped_column(String(255), nullable=False)
  1242. external_user_id = mapped_column(String(255), nullable=True)
  1243. name = mapped_column(String(255))
  1244. is_anonymous: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  1245. session_id: Mapped[str] = mapped_column()
  1246. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1247. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1248. class AppMCPServer(Base):
  1249. __tablename__ = "app_mcp_servers"
  1250. __table_args__ = (
  1251. sa.PrimaryKeyConstraint("id", name="app_mcp_server_pkey"),
  1252. sa.UniqueConstraint("tenant_id", "app_id", name="unique_app_mcp_server_tenant_app_id"),
  1253. sa.UniqueConstraint("server_code", name="unique_app_mcp_server_server_code"),
  1254. )
  1255. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1256. tenant_id = mapped_column(StringUUID, nullable=False)
  1257. app_id = mapped_column(StringUUID, nullable=False)
  1258. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1259. description: Mapped[str] = mapped_column(String(255), nullable=False)
  1260. server_code: Mapped[str] = mapped_column(String(255), nullable=False)
  1261. status = mapped_column(String(255), nullable=False, server_default=sa.text("'normal'::character varying"))
  1262. parameters = mapped_column(sa.Text, nullable=False)
  1263. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1264. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1265. @staticmethod
  1266. def generate_server_code(n):
  1267. while True:
  1268. result = generate_string(n)
  1269. while db.session.query(AppMCPServer).where(AppMCPServer.server_code == result).count() > 0:
  1270. result = generate_string(n)
  1271. return result
  1272. @property
  1273. def parameters_dict(self) -> dict[str, Any]:
  1274. return cast(dict[str, Any], json.loads(self.parameters))
  1275. class Site(Base):
  1276. __tablename__ = "sites"
  1277. __table_args__ = (
  1278. sa.PrimaryKeyConstraint("id", name="site_pkey"),
  1279. sa.Index("site_app_id_idx", "app_id"),
  1280. sa.Index("site_code_idx", "code", "status"),
  1281. )
  1282. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1283. app_id = mapped_column(StringUUID, nullable=False)
  1284. title: Mapped[str] = mapped_column(String(255), nullable=False)
  1285. icon_type = mapped_column(String(255), nullable=True)
  1286. icon = mapped_column(String(255))
  1287. icon_background = mapped_column(String(255))
  1288. description = mapped_column(sa.Text)
  1289. default_language: Mapped[str] = mapped_column(String(255), nullable=False)
  1290. chat_color_theme = mapped_column(String(255))
  1291. chat_color_theme_inverted: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  1292. copyright = mapped_column(String(255))
  1293. privacy_policy = mapped_column(String(255))
  1294. show_workflow_steps: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  1295. use_icon_as_answer_icon: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  1296. _custom_disclaimer: Mapped[str] = mapped_column("custom_disclaimer", sa.TEXT, default="")
  1297. customize_domain = mapped_column(String(255))
  1298. customize_token_strategy: Mapped[str] = mapped_column(String(255), nullable=False)
  1299. prompt_public: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  1300. status = mapped_column(String(255), nullable=False, server_default=sa.text("'normal'::character varying"))
  1301. created_by = mapped_column(StringUUID, nullable=True)
  1302. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1303. updated_by = mapped_column(StringUUID, nullable=True)
  1304. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1305. code = mapped_column(String(255))
  1306. @property
  1307. def custom_disclaimer(self):
  1308. return self._custom_disclaimer
  1309. @custom_disclaimer.setter
  1310. def custom_disclaimer(self, value: str):
  1311. if len(value) > 512:
  1312. raise ValueError("Custom disclaimer cannot exceed 512 characters.")
  1313. self._custom_disclaimer = value
  1314. @staticmethod
  1315. def generate_code(n):
  1316. while True:
  1317. result = generate_string(n)
  1318. while db.session.query(Site).where(Site.code == result).count() > 0:
  1319. result = generate_string(n)
  1320. return result
  1321. @property
  1322. def app_base_url(self):
  1323. return dify_config.APP_WEB_URL or request.url_root.rstrip("/")
  1324. class ApiToken(Base):
  1325. __tablename__ = "api_tokens"
  1326. __table_args__ = (
  1327. sa.PrimaryKeyConstraint("id", name="api_token_pkey"),
  1328. sa.Index("api_token_app_id_type_idx", "app_id", "type"),
  1329. sa.Index("api_token_token_idx", "token", "type"),
  1330. sa.Index("api_token_tenant_idx", "tenant_id", "type"),
  1331. )
  1332. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1333. app_id = mapped_column(StringUUID, nullable=True)
  1334. tenant_id = mapped_column(StringUUID, nullable=True)
  1335. type = mapped_column(String(16), nullable=False)
  1336. token: Mapped[str] = mapped_column(String(255), nullable=False)
  1337. last_used_at = mapped_column(sa.DateTime, nullable=True)
  1338. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1339. @staticmethod
  1340. def generate_api_key(prefix, n):
  1341. while True:
  1342. result = prefix + generate_string(n)
  1343. if db.session.scalar(select(exists().where(ApiToken.token == result))):
  1344. continue
  1345. return result
  1346. class UploadFile(Base):
  1347. __tablename__ = "upload_files"
  1348. __table_args__ = (
  1349. sa.PrimaryKeyConstraint("id", name="upload_file_pkey"),
  1350. sa.Index("upload_file_tenant_idx", "tenant_id"),
  1351. )
  1352. # NOTE: The `id` field is generated within the application to minimize extra roundtrips
  1353. # (especially when generating `source_url`).
  1354. # The `server_default` serves as a fallback mechanism.
  1355. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1356. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1357. storage_type: Mapped[str] = mapped_column(String(255), nullable=False)
  1358. key: Mapped[str] = mapped_column(String(255), nullable=False)
  1359. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1360. size: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1361. extension: Mapped[str] = mapped_column(String(255), nullable=False)
  1362. mime_type: Mapped[str] = mapped_column(String(255), nullable=True)
  1363. # The `created_by_role` field indicates whether the file was created by an `Account` or an `EndUser`.
  1364. # Its value is derived from the `CreatorUserRole` enumeration.
  1365. created_by_role: Mapped[str] = mapped_column(
  1366. String(255), nullable=False, server_default=sa.text("'account'::character varying")
  1367. )
  1368. # The `created_by` field stores the ID of the entity that created this upload file.
  1369. #
  1370. # If `created_by_role` is `ACCOUNT`, it corresponds to `Account.id`.
  1371. # Otherwise, it corresponds to `EndUser.id`.
  1372. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1373. created_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1374. # The fields `used` and `used_by` are not consistently maintained.
  1375. #
  1376. # When using this model in new code, ensure the following:
  1377. #
  1378. # 1. Set `used` to `true` when the file is utilized.
  1379. # 2. Assign `used_by` to the corresponding `Account.id` or `EndUser.id` based on the `created_by_role`.
  1380. # 3. Avoid relying on these fields for logic, as their values may not always be accurate.
  1381. #
  1382. # `used` may indicate whether the file has been utilized by another service.
  1383. used: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  1384. # `used_by` may indicate the ID of the user who utilized this file.
  1385. used_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
  1386. used_at: Mapped[datetime | None] = mapped_column(sa.DateTime, nullable=True)
  1387. hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
  1388. source_url: Mapped[str] = mapped_column(sa.TEXT, default="")
  1389. def __init__(
  1390. self,
  1391. *,
  1392. tenant_id: str,
  1393. storage_type: str,
  1394. key: str,
  1395. name: str,
  1396. size: int,
  1397. extension: str,
  1398. mime_type: str,
  1399. created_by_role: CreatorUserRole,
  1400. created_by: str,
  1401. created_at: datetime,
  1402. used: bool,
  1403. used_by: str | None = None,
  1404. used_at: datetime | None = None,
  1405. hash: str | None = None,
  1406. source_url: str = "",
  1407. ):
  1408. self.id = str(uuid.uuid4())
  1409. self.tenant_id = tenant_id
  1410. self.storage_type = storage_type
  1411. self.key = key
  1412. self.name = name
  1413. self.size = size
  1414. self.extension = extension
  1415. self.mime_type = mime_type
  1416. self.created_by_role = created_by_role.value
  1417. self.created_by = created_by
  1418. self.created_at = created_at
  1419. self.used = used
  1420. self.used_by = used_by
  1421. self.used_at = used_at
  1422. self.hash = hash
  1423. self.source_url = source_url
  1424. class ApiRequest(Base):
  1425. __tablename__ = "api_requests"
  1426. __table_args__ = (
  1427. sa.PrimaryKeyConstraint("id", name="api_request_pkey"),
  1428. sa.Index("api_request_token_idx", "tenant_id", "api_token_id"),
  1429. )
  1430. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1431. tenant_id = mapped_column(StringUUID, nullable=False)
  1432. api_token_id = mapped_column(StringUUID, nullable=False)
  1433. path: Mapped[str] = mapped_column(String(255), nullable=False)
  1434. request = mapped_column(sa.Text, nullable=True)
  1435. response = mapped_column(sa.Text, nullable=True)
  1436. ip: Mapped[str] = mapped_column(String(255), nullable=False)
  1437. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1438. class MessageChain(Base):
  1439. __tablename__ = "message_chains"
  1440. __table_args__ = (
  1441. sa.PrimaryKeyConstraint("id", name="message_chain_pkey"),
  1442. sa.Index("message_chain_message_id_idx", "message_id"),
  1443. )
  1444. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1445. message_id = mapped_column(StringUUID, nullable=False)
  1446. type: Mapped[str] = mapped_column(String(255), nullable=False)
  1447. input = mapped_column(sa.Text, nullable=True)
  1448. output = mapped_column(sa.Text, nullable=True)
  1449. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1450. class MessageAgentThought(Base):
  1451. __tablename__ = "message_agent_thoughts"
  1452. __table_args__ = (
  1453. sa.PrimaryKeyConstraint("id", name="message_agent_thought_pkey"),
  1454. sa.Index("message_agent_thought_message_id_idx", "message_id"),
  1455. sa.Index("message_agent_thought_message_chain_id_idx", "message_chain_id"),
  1456. )
  1457. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1458. message_id = mapped_column(StringUUID, nullable=False)
  1459. message_chain_id = mapped_column(StringUUID, nullable=True)
  1460. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1461. thought = mapped_column(sa.Text, nullable=True)
  1462. tool = mapped_column(sa.Text, nullable=True)
  1463. tool_labels_str = mapped_column(sa.Text, nullable=False, server_default=sa.text("'{}'::text"))
  1464. tool_meta_str = mapped_column(sa.Text, nullable=False, server_default=sa.text("'{}'::text"))
  1465. tool_input = mapped_column(sa.Text, nullable=True)
  1466. observation = mapped_column(sa.Text, nullable=True)
  1467. # plugin_id = mapped_column(StringUUID, nullable=True) ## for future design
  1468. tool_process_data = mapped_column(sa.Text, nullable=True)
  1469. message = mapped_column(sa.Text, nullable=True)
  1470. message_token: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1471. message_unit_price = mapped_column(sa.Numeric, nullable=True)
  1472. message_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  1473. message_files = mapped_column(sa.Text, nullable=True)
  1474. answer = mapped_column(sa.Text, nullable=True)
  1475. answer_token: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1476. answer_unit_price = mapped_column(sa.Numeric, nullable=True)
  1477. answer_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  1478. tokens: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1479. total_price = mapped_column(sa.Numeric, nullable=True)
  1480. currency = mapped_column(String, nullable=True)
  1481. latency: Mapped[Optional[float]] = mapped_column(sa.Float, nullable=True)
  1482. created_by_role = mapped_column(String, nullable=False)
  1483. created_by = mapped_column(StringUUID, nullable=False)
  1484. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1485. @property
  1486. def files(self) -> list:
  1487. if self.message_files:
  1488. return cast(list[Any], json.loads(self.message_files))
  1489. else:
  1490. return []
  1491. @property
  1492. def tools(self) -> list[str]:
  1493. return self.tool.split(";") if self.tool else []
  1494. @property
  1495. def tool_labels(self) -> dict:
  1496. try:
  1497. if self.tool_labels_str:
  1498. return cast(dict, json.loads(self.tool_labels_str))
  1499. else:
  1500. return {}
  1501. except Exception:
  1502. return {}
  1503. @property
  1504. def tool_meta(self) -> dict:
  1505. try:
  1506. if self.tool_meta_str:
  1507. return cast(dict, json.loads(self.tool_meta_str))
  1508. else:
  1509. return {}
  1510. except Exception:
  1511. return {}
  1512. @property
  1513. def tool_inputs_dict(self) -> dict:
  1514. tools = self.tools
  1515. try:
  1516. if self.tool_input:
  1517. data = json.loads(self.tool_input)
  1518. result = {}
  1519. for tool in tools:
  1520. if tool in data:
  1521. result[tool] = data[tool]
  1522. else:
  1523. if len(tools) == 1:
  1524. result[tool] = data
  1525. else:
  1526. result[tool] = {}
  1527. return result
  1528. else:
  1529. return {tool: {} for tool in tools}
  1530. except Exception:
  1531. return {}
  1532. @property
  1533. def tool_outputs_dict(self):
  1534. tools = self.tools
  1535. try:
  1536. if self.observation:
  1537. data = json.loads(self.observation)
  1538. result = {}
  1539. for tool in tools:
  1540. if tool in data:
  1541. result[tool] = data[tool]
  1542. else:
  1543. if len(tools) == 1:
  1544. result[tool] = data
  1545. else:
  1546. result[tool] = {}
  1547. return result
  1548. else:
  1549. return {tool: {} for tool in tools}
  1550. except Exception:
  1551. if self.observation:
  1552. return dict.fromkeys(tools, self.observation)
  1553. else:
  1554. return {}
  1555. class DatasetRetrieverResource(Base):
  1556. __tablename__ = "dataset_retriever_resources"
  1557. __table_args__ = (
  1558. sa.PrimaryKeyConstraint("id", name="dataset_retriever_resource_pkey"),
  1559. sa.Index("dataset_retriever_resource_message_id_idx", "message_id"),
  1560. )
  1561. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1562. message_id = mapped_column(StringUUID, nullable=False)
  1563. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1564. dataset_id = mapped_column(StringUUID, nullable=False)
  1565. dataset_name = mapped_column(sa.Text, nullable=False)
  1566. document_id = mapped_column(StringUUID, nullable=True)
  1567. document_name = mapped_column(sa.Text, nullable=False)
  1568. data_source_type = mapped_column(sa.Text, nullable=True)
  1569. segment_id = mapped_column(StringUUID, nullable=True)
  1570. score: Mapped[Optional[float]] = mapped_column(sa.Float, nullable=True)
  1571. content = mapped_column(sa.Text, nullable=False)
  1572. hit_count: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1573. word_count: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1574. segment_position: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1575. index_node_hash = mapped_column(sa.Text, nullable=True)
  1576. retriever_from = mapped_column(sa.Text, nullable=False)
  1577. created_by = mapped_column(StringUUID, nullable=False)
  1578. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1579. class Tag(Base):
  1580. __tablename__ = "tags"
  1581. __table_args__ = (
  1582. sa.PrimaryKeyConstraint("id", name="tag_pkey"),
  1583. sa.Index("tag_type_idx", "type"),
  1584. sa.Index("tag_name_idx", "name"),
  1585. )
  1586. TAG_TYPE_LIST = ["knowledge", "app"]
  1587. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1588. tenant_id = mapped_column(StringUUID, nullable=True)
  1589. type = mapped_column(String(16), nullable=False)
  1590. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1591. created_by = mapped_column(StringUUID, nullable=False)
  1592. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1593. class TagBinding(Base):
  1594. __tablename__ = "tag_bindings"
  1595. __table_args__ = (
  1596. sa.PrimaryKeyConstraint("id", name="tag_binding_pkey"),
  1597. sa.Index("tag_bind_target_id_idx", "target_id"),
  1598. sa.Index("tag_bind_tag_id_idx", "tag_id"),
  1599. )
  1600. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1601. tenant_id = mapped_column(StringUUID, nullable=True)
  1602. tag_id = mapped_column(StringUUID, nullable=True)
  1603. target_id = mapped_column(StringUUID, nullable=True)
  1604. created_by = mapped_column(StringUUID, nullable=False)
  1605. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1606. class TraceAppConfig(Base):
  1607. __tablename__ = "trace_app_config"
  1608. __table_args__ = (
  1609. sa.PrimaryKeyConstraint("id", name="tracing_app_config_pkey"),
  1610. sa.Index("trace_app_config_app_id_idx", "app_id"),
  1611. )
  1612. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1613. app_id = mapped_column(StringUUID, nullable=False)
  1614. tracing_provider = mapped_column(String(255), nullable=True)
  1615. tracing_config = mapped_column(sa.JSON, nullable=True)
  1616. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1617. updated_at = mapped_column(
  1618. sa.DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  1619. )
  1620. is_active: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  1621. @property
  1622. def tracing_config_dict(self):
  1623. return self.tracing_config or {}
  1624. @property
  1625. def tracing_config_str(self):
  1626. return json.dumps(self.tracing_config_dict)
  1627. def to_dict(self):
  1628. return {
  1629. "id": self.id,
  1630. "app_id": self.app_id,
  1631. "tracing_provider": self.tracing_provider,
  1632. "tracing_config": self.tracing_config_dict,
  1633. "is_active": self.is_active,
  1634. "created_at": str(self.created_at) if self.created_at else None,
  1635. "updated_at": str(self.updated_at) if self.updated_at else None,
  1636. }