Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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