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.

model.py 77KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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, String, 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. class DifySetup(Base):
  30. __tablename__ = "dify_setups"
  31. __table_args__ = (sa.PrimaryKeyConstraint("version", name="dify_setup_pkey"),)
  32. version: Mapped[str] = mapped_column(String(255), nullable=False)
  33. setup_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  34. class AppMode(StrEnum):
  35. COMPLETION = "completion"
  36. WORKFLOW = "workflow"
  37. CHAT = "chat"
  38. ADVANCED_CHAT = "advanced-chat"
  39. AGENT_CHAT = "agent-chat"
  40. @classmethod
  41. def value_of(cls, value: str) -> "AppMode":
  42. """
  43. Get value of given mode.
  44. :param value: mode value
  45. :return: mode
  46. """
  47. for mode in cls:
  48. if mode.value == value:
  49. return mode
  50. raise ValueError(f"invalid mode value {value}")
  51. class IconType(Enum):
  52. IMAGE = "image"
  53. EMOJI = "emoji"
  54. class App(Base):
  55. __tablename__ = "apps"
  56. __table_args__ = (sa.PrimaryKeyConstraint("id", name="app_pkey"), sa.Index("app_tenant_id_idx", "tenant_id"))
  57. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  58. tenant_id: Mapped[str] = mapped_column(StringUUID)
  59. name: Mapped[str] = mapped_column(String(255))
  60. description: Mapped[str] = mapped_column(sa.Text, server_default=sa.text("''::character varying"))
  61. mode: Mapped[str] = mapped_column(String(255))
  62. icon_type: Mapped[Optional[str]] = mapped_column(String(255)) # image, emoji
  63. icon = db.Column(String(255))
  64. icon_background: Mapped[Optional[str]] = mapped_column(String(255))
  65. app_model_config_id = mapped_column(StringUUID, nullable=True)
  66. workflow_id = mapped_column(StringUUID, nullable=True)
  67. status: Mapped[str] = mapped_column(String(255), server_default=sa.text("'normal'::character varying"))
  68. enable_site: Mapped[bool] = mapped_column(sa.Boolean)
  69. enable_api: Mapped[bool] = mapped_column(sa.Boolean)
  70. api_rpm: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"))
  71. api_rph: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"))
  72. is_demo: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  73. is_public: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  74. is_universal: Mapped[bool] = mapped_column(sa.Boolean, server_default=sa.text("false"))
  75. tracing = mapped_column(sa.Text, nullable=True)
  76. max_active_requests: Mapped[Optional[int]]
  77. created_by = mapped_column(StringUUID, nullable=True)
  78. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  79. updated_by = mapped_column(StringUUID, nullable=True)
  80. updated_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  81. use_icon_as_answer_icon: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  82. @property
  83. def desc_or_prompt(self):
  84. if self.description:
  85. return self.description
  86. else:
  87. app_model_config = self.app_model_config
  88. if app_model_config:
  89. return app_model_config.pre_prompt
  90. else:
  91. return ""
  92. @property
  93. def site(self):
  94. site = db.session.query(Site).where(Site.app_id == self.id).first()
  95. return site
  96. @property
  97. def app_model_config(self):
  98. if self.app_model_config_id:
  99. return db.session.query(AppModelConfig).where(AppModelConfig.id == self.app_model_config_id).first()
  100. return None
  101. @property
  102. def workflow(self) -> Optional["Workflow"]:
  103. if self.workflow_id:
  104. from .workflow import Workflow
  105. return db.session.query(Workflow).where(Workflow.id == self.workflow_id).first()
  106. return None
  107. @property
  108. def api_base_url(self):
  109. return (dify_config.SERVICE_API_URL or request.host_url.rstrip("/")) + "/v1"
  110. @property
  111. def tenant(self):
  112. tenant = db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  113. return tenant
  114. @property
  115. def is_agent(self) -> bool:
  116. app_model_config = self.app_model_config
  117. if not app_model_config:
  118. return False
  119. if not app_model_config.agent_mode:
  120. return False
  121. if app_model_config.agent_mode_dict.get("enabled", False) and app_model_config.agent_mode_dict.get(
  122. "strategy", ""
  123. ) in {"function_call", "react"}:
  124. self.mode = AppMode.AGENT_CHAT.value
  125. db.session.commit()
  126. return True
  127. return False
  128. @property
  129. def mode_compatible_with_agent(self) -> str:
  130. if self.mode == AppMode.CHAT.value and self.is_agent:
  131. return AppMode.AGENT_CHAT.value
  132. return str(self.mode)
  133. @property
  134. def deleted_tools(self) -> list:
  135. from core.tools.tool_manager import ToolManager
  136. from services.plugin.plugin_service import PluginService
  137. # get agent mode tools
  138. app_model_config = self.app_model_config
  139. if not app_model_config:
  140. return []
  141. if not app_model_config.agent_mode:
  142. return []
  143. agent_mode = app_model_config.agent_mode_dict
  144. tools = agent_mode.get("tools", [])
  145. api_provider_ids: list[str] = []
  146. builtin_provider_ids: list[GenericProviderID] = []
  147. for tool in tools:
  148. keys = list(tool.keys())
  149. if len(keys) >= 4:
  150. provider_type = tool.get("provider_type", "")
  151. provider_id = tool.get("provider_id", "")
  152. if provider_type == ToolProviderType.API.value:
  153. try:
  154. uuid.UUID(provider_id)
  155. except Exception:
  156. continue
  157. api_provider_ids.append(provider_id)
  158. if provider_type == ToolProviderType.BUILT_IN.value:
  159. try:
  160. # check if it's hardcoded
  161. try:
  162. ToolManager.get_hardcoded_provider(provider_id)
  163. is_hardcoded = True
  164. except Exception:
  165. is_hardcoded = False
  166. provider_id = GenericProviderID(provider_id, is_hardcoded)
  167. except Exception:
  168. continue
  169. builtin_provider_ids.append(provider_id)
  170. if not api_provider_ids and not builtin_provider_ids:
  171. return []
  172. with Session(db.engine) as session:
  173. if api_provider_ids:
  174. existing_api_providers = [
  175. api_provider.id
  176. for api_provider in session.execute(
  177. text("SELECT id FROM tool_api_providers WHERE id IN :provider_ids"),
  178. {"provider_ids": tuple(api_provider_ids)},
  179. ).fetchall()
  180. ]
  181. else:
  182. existing_api_providers = []
  183. if builtin_provider_ids:
  184. # get the non-hardcoded builtin providers
  185. non_hardcoded_builtin_providers = [
  186. provider_id for provider_id in builtin_provider_ids if not provider_id.is_hardcoded
  187. ]
  188. if non_hardcoded_builtin_providers:
  189. existence = list(PluginService.check_tools_existence(self.tenant_id, non_hardcoded_builtin_providers))
  190. else:
  191. existence = []
  192. # add the hardcoded builtin providers
  193. existence.extend([True] * (len(builtin_provider_ids) - len(non_hardcoded_builtin_providers)))
  194. builtin_provider_ids = non_hardcoded_builtin_providers + [
  195. provider_id for provider_id in builtin_provider_ids if provider_id.is_hardcoded
  196. ]
  197. else:
  198. existence = []
  199. existing_builtin_providers = {
  200. provider_id.provider_name: existence[i] for i, provider_id in enumerate(builtin_provider_ids)
  201. }
  202. deleted_tools = []
  203. for tool in tools:
  204. keys = list(tool.keys())
  205. if len(keys) >= 4:
  206. provider_type = tool.get("provider_type", "")
  207. provider_id = tool.get("provider_id", "")
  208. if provider_type == ToolProviderType.API.value:
  209. if uuid.UUID(provider_id) not in existing_api_providers:
  210. deleted_tools.append(
  211. {
  212. "type": ToolProviderType.API.value,
  213. "tool_name": tool["tool_name"],
  214. "provider_id": provider_id,
  215. }
  216. )
  217. if provider_type == ToolProviderType.BUILT_IN.value:
  218. generic_provider_id = GenericProviderID(provider_id)
  219. if not existing_builtin_providers[generic_provider_id.provider_name]:
  220. deleted_tools.append(
  221. {
  222. "type": ToolProviderType.BUILT_IN.value,
  223. "tool_name": tool["tool_name"],
  224. "provider_id": provider_id, # use the original one
  225. }
  226. )
  227. return deleted_tools
  228. @property
  229. def tags(self):
  230. tags = (
  231. db.session.query(Tag)
  232. .join(TagBinding, Tag.id == TagBinding.tag_id)
  233. .where(
  234. TagBinding.target_id == self.id,
  235. TagBinding.tenant_id == self.tenant_id,
  236. Tag.tenant_id == self.tenant_id,
  237. Tag.type == "app",
  238. )
  239. .all()
  240. )
  241. return tags or []
  242. @property
  243. def author_name(self):
  244. if self.created_by:
  245. account = db.session.query(Account).where(Account.id == self.created_by).first()
  246. if account:
  247. return account.name
  248. return None
  249. class AppModelConfig(Base):
  250. __tablename__ = "app_model_configs"
  251. __table_args__ = (sa.PrimaryKeyConstraint("id", name="app_model_config_pkey"), sa.Index("app_app_id_idx", "app_id"))
  252. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  253. app_id = mapped_column(StringUUID, nullable=False)
  254. provider = mapped_column(String(255), nullable=True)
  255. model_id = mapped_column(String(255), nullable=True)
  256. configs = mapped_column(sa.JSON, nullable=True)
  257. created_by = mapped_column(StringUUID, nullable=True)
  258. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  259. updated_by = mapped_column(StringUUID, nullable=True)
  260. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  261. opening_statement = mapped_column(sa.Text)
  262. suggested_questions = mapped_column(sa.Text)
  263. suggested_questions_after_answer = mapped_column(sa.Text)
  264. speech_to_text = mapped_column(sa.Text)
  265. text_to_speech = mapped_column(sa.Text)
  266. more_like_this = mapped_column(sa.Text)
  267. model = mapped_column(sa.Text)
  268. user_input_form = mapped_column(sa.Text)
  269. dataset_query_variable = mapped_column(String(255))
  270. pre_prompt = mapped_column(sa.Text)
  271. agent_mode = mapped_column(sa.Text)
  272. sensitive_word_avoidance = mapped_column(sa.Text)
  273. retriever_resource = mapped_column(sa.Text)
  274. prompt_type = mapped_column(String(255), nullable=False, server_default=sa.text("'simple'::character varying"))
  275. chat_prompt_config = mapped_column(sa.Text)
  276. completion_prompt_config = mapped_column(sa.Text)
  277. dataset_configs = mapped_column(sa.Text)
  278. external_data_tools = mapped_column(sa.Text)
  279. file_upload = mapped_column(sa.Text)
  280. @property
  281. def app(self):
  282. app = db.session.query(App).where(App.id == self.app_id).first()
  283. return app
  284. @property
  285. def model_dict(self) -> dict:
  286. return json.loads(self.model) if self.model else {}
  287. @property
  288. def suggested_questions_list(self) -> list:
  289. return json.loads(self.suggested_questions) if self.suggested_questions else []
  290. @property
  291. def suggested_questions_after_answer_dict(self) -> dict:
  292. return (
  293. json.loads(self.suggested_questions_after_answer)
  294. if self.suggested_questions_after_answer
  295. else {"enabled": False}
  296. )
  297. @property
  298. def speech_to_text_dict(self) -> dict:
  299. return json.loads(self.speech_to_text) if self.speech_to_text else {"enabled": False}
  300. @property
  301. def text_to_speech_dict(self) -> dict:
  302. return json.loads(self.text_to_speech) if self.text_to_speech else {"enabled": False}
  303. @property
  304. def retriever_resource_dict(self) -> dict:
  305. return json.loads(self.retriever_resource) if self.retriever_resource else {"enabled": True}
  306. @property
  307. def annotation_reply_dict(self) -> dict:
  308. annotation_setting = (
  309. db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == self.app_id).first()
  310. )
  311. if annotation_setting:
  312. collection_binding_detail = annotation_setting.collection_binding_detail
  313. if not collection_binding_detail:
  314. raise ValueError("Collection binding detail not found")
  315. return {
  316. "id": annotation_setting.id,
  317. "enabled": True,
  318. "score_threshold": annotation_setting.score_threshold,
  319. "embedding_model": {
  320. "embedding_provider_name": collection_binding_detail.provider_name,
  321. "embedding_model_name": collection_binding_detail.model_name,
  322. },
  323. }
  324. else:
  325. return {"enabled": False}
  326. @property
  327. def more_like_this_dict(self) -> dict:
  328. return json.loads(self.more_like_this) if self.more_like_this else {"enabled": False}
  329. @property
  330. def sensitive_word_avoidance_dict(self) -> dict:
  331. return (
  332. json.loads(self.sensitive_word_avoidance)
  333. if self.sensitive_word_avoidance
  334. else {"enabled": False, "type": "", "configs": []}
  335. )
  336. @property
  337. def external_data_tools_list(self) -> list[dict]:
  338. return json.loads(self.external_data_tools) if self.external_data_tools else []
  339. @property
  340. def user_input_form_list(self):
  341. return json.loads(self.user_input_form) if self.user_input_form else []
  342. @property
  343. def agent_mode_dict(self) -> dict:
  344. return (
  345. json.loads(self.agent_mode)
  346. if self.agent_mode
  347. else {"enabled": False, "strategy": None, "tools": [], "prompt": None}
  348. )
  349. @property
  350. def chat_prompt_config_dict(self) -> dict:
  351. return json.loads(self.chat_prompt_config) if self.chat_prompt_config else {}
  352. @property
  353. def completion_prompt_config_dict(self) -> dict:
  354. return json.loads(self.completion_prompt_config) if self.completion_prompt_config else {}
  355. @property
  356. def dataset_configs_dict(self) -> dict:
  357. if self.dataset_configs:
  358. dataset_configs: dict = json.loads(self.dataset_configs)
  359. if "retrieval_model" not in dataset_configs:
  360. return {"retrieval_model": "single"}
  361. else:
  362. return dataset_configs
  363. return {
  364. "retrieval_model": "multiple",
  365. }
  366. @property
  367. def file_upload_dict(self) -> dict:
  368. return (
  369. json.loads(self.file_upload)
  370. if self.file_upload
  371. else {
  372. "image": {
  373. "enabled": False,
  374. "number_limits": DEFAULT_FILE_NUMBER_LIMITS,
  375. "detail": "high",
  376. "transfer_methods": ["remote_url", "local_file"],
  377. }
  378. }
  379. )
  380. def to_dict(self) -> dict:
  381. return {
  382. "opening_statement": self.opening_statement,
  383. "suggested_questions": self.suggested_questions_list,
  384. "suggested_questions_after_answer": self.suggested_questions_after_answer_dict,
  385. "speech_to_text": self.speech_to_text_dict,
  386. "text_to_speech": self.text_to_speech_dict,
  387. "retriever_resource": self.retriever_resource_dict,
  388. "annotation_reply": self.annotation_reply_dict,
  389. "more_like_this": self.more_like_this_dict,
  390. "sensitive_word_avoidance": self.sensitive_word_avoidance_dict,
  391. "external_data_tools": self.external_data_tools_list,
  392. "model": self.model_dict,
  393. "user_input_form": self.user_input_form_list,
  394. "dataset_query_variable": self.dataset_query_variable,
  395. "pre_prompt": self.pre_prompt,
  396. "agent_mode": self.agent_mode_dict,
  397. "prompt_type": self.prompt_type,
  398. "chat_prompt_config": self.chat_prompt_config_dict,
  399. "completion_prompt_config": self.completion_prompt_config_dict,
  400. "dataset_configs": self.dataset_configs_dict,
  401. "file_upload": self.file_upload_dict,
  402. }
  403. def from_model_config_dict(self, model_config: Mapping[str, Any]):
  404. self.opening_statement = model_config.get("opening_statement")
  405. self.suggested_questions = (
  406. json.dumps(model_config["suggested_questions"]) if model_config.get("suggested_questions") else None
  407. )
  408. self.suggested_questions_after_answer = (
  409. json.dumps(model_config["suggested_questions_after_answer"])
  410. if model_config.get("suggested_questions_after_answer")
  411. else None
  412. )
  413. self.speech_to_text = json.dumps(model_config["speech_to_text"]) if model_config.get("speech_to_text") else None
  414. self.text_to_speech = json.dumps(model_config["text_to_speech"]) if model_config.get("text_to_speech") else None
  415. self.more_like_this = json.dumps(model_config["more_like_this"]) if model_config.get("more_like_this") else None
  416. self.sensitive_word_avoidance = (
  417. json.dumps(model_config["sensitive_word_avoidance"])
  418. if model_config.get("sensitive_word_avoidance")
  419. else None
  420. )
  421. self.external_data_tools = (
  422. json.dumps(model_config["external_data_tools"]) if model_config.get("external_data_tools") else None
  423. )
  424. self.model = json.dumps(model_config["model"]) if model_config.get("model") else None
  425. self.user_input_form = (
  426. json.dumps(model_config["user_input_form"]) if model_config.get("user_input_form") else None
  427. )
  428. self.dataset_query_variable = model_config.get("dataset_query_variable")
  429. self.pre_prompt = model_config["pre_prompt"]
  430. self.agent_mode = json.dumps(model_config["agent_mode"]) if model_config.get("agent_mode") else None
  431. self.retriever_resource = (
  432. json.dumps(model_config["retriever_resource"]) if model_config.get("retriever_resource") else None
  433. )
  434. self.prompt_type = model_config.get("prompt_type", "simple")
  435. self.chat_prompt_config = (
  436. json.dumps(model_config.get("chat_prompt_config")) if model_config.get("chat_prompt_config") else None
  437. )
  438. self.completion_prompt_config = (
  439. json.dumps(model_config.get("completion_prompt_config"))
  440. if model_config.get("completion_prompt_config")
  441. else None
  442. )
  443. self.dataset_configs = (
  444. json.dumps(model_config.get("dataset_configs")) if model_config.get("dataset_configs") else None
  445. )
  446. self.file_upload = json.dumps(model_config.get("file_upload")) if model_config.get("file_upload") else None
  447. return self
  448. def copy(self):
  449. new_app_model_config = AppModelConfig(
  450. id=self.id,
  451. app_id=self.app_id,
  452. opening_statement=self.opening_statement,
  453. suggested_questions=self.suggested_questions,
  454. suggested_questions_after_answer=self.suggested_questions_after_answer,
  455. speech_to_text=self.speech_to_text,
  456. text_to_speech=self.text_to_speech,
  457. more_like_this=self.more_like_this,
  458. sensitive_word_avoidance=self.sensitive_word_avoidance,
  459. external_data_tools=self.external_data_tools,
  460. model=self.model,
  461. user_input_form=self.user_input_form,
  462. dataset_query_variable=self.dataset_query_variable,
  463. pre_prompt=self.pre_prompt,
  464. agent_mode=self.agent_mode,
  465. retriever_resource=self.retriever_resource,
  466. prompt_type=self.prompt_type,
  467. chat_prompt_config=self.chat_prompt_config,
  468. completion_prompt_config=self.completion_prompt_config,
  469. dataset_configs=self.dataset_configs,
  470. file_upload=self.file_upload,
  471. )
  472. return new_app_model_config
  473. class RecommendedApp(Base):
  474. __tablename__ = "recommended_apps"
  475. __table_args__ = (
  476. sa.PrimaryKeyConstraint("id", name="recommended_app_pkey"),
  477. sa.Index("recommended_app_app_id_idx", "app_id"),
  478. sa.Index("recommended_app_is_listed_idx", "is_listed", "language"),
  479. )
  480. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  481. app_id = mapped_column(StringUUID, nullable=False)
  482. description = mapped_column(sa.JSON, nullable=False)
  483. copyright: Mapped[str] = mapped_column(String(255), nullable=False)
  484. privacy_policy: Mapped[str] = mapped_column(String(255), nullable=False)
  485. custom_disclaimer: Mapped[str] = mapped_column(sa.TEXT, default="")
  486. category: Mapped[str] = mapped_column(String(255), nullable=False)
  487. position: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  488. is_listed: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
  489. install_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  490. language = mapped_column(String(255), nullable=False, server_default=sa.text("'en-US'::character varying"))
  491. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  492. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  493. @property
  494. def app(self):
  495. app = db.session.query(App).where(App.id == self.app_id).first()
  496. return app
  497. class InstalledApp(Base):
  498. __tablename__ = "installed_apps"
  499. __table_args__ = (
  500. sa.PrimaryKeyConstraint("id", name="installed_app_pkey"),
  501. sa.Index("installed_app_tenant_id_idx", "tenant_id"),
  502. sa.Index("installed_app_app_id_idx", "app_id"),
  503. sa.UniqueConstraint("tenant_id", "app_id", name="unique_tenant_app"),
  504. )
  505. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  506. tenant_id = mapped_column(StringUUID, nullable=False)
  507. app_id = mapped_column(StringUUID, nullable=False)
  508. app_owner_tenant_id = mapped_column(StringUUID, nullable=False)
  509. position: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  510. is_pinned: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  511. last_used_at = mapped_column(sa.DateTime, nullable=True)
  512. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  513. @property
  514. def app(self):
  515. app = db.session.query(App).where(App.id == self.app_id).first()
  516. return app
  517. @property
  518. def tenant(self):
  519. tenant = db.session.query(Tenant).where(Tenant.id == self.tenant_id).first()
  520. return tenant
  521. class Conversation(Base):
  522. __tablename__ = "conversations"
  523. __table_args__ = (
  524. sa.PrimaryKeyConstraint("id", name="conversation_pkey"),
  525. sa.Index("conversation_app_from_user_idx", "app_id", "from_source", "from_end_user_id"),
  526. )
  527. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  528. app_id = mapped_column(StringUUID, nullable=False)
  529. app_model_config_id = mapped_column(StringUUID, nullable=True)
  530. model_provider = mapped_column(String(255), nullable=True)
  531. override_model_configs = mapped_column(sa.Text)
  532. model_id = mapped_column(String(255), nullable=True)
  533. mode: Mapped[str] = mapped_column(String(255))
  534. name: Mapped[str] = mapped_column(String(255), nullable=False)
  535. summary = mapped_column(sa.Text)
  536. _inputs: Mapped[dict] = mapped_column("inputs", sa.JSON)
  537. introduction = mapped_column(sa.Text)
  538. system_instruction = mapped_column(sa.Text)
  539. system_instruction_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0"))
  540. status: Mapped[str] = mapped_column(String(255), nullable=False)
  541. # The `invoke_from` records how the conversation is created.
  542. #
  543. # Its value corresponds to the members of `InvokeFrom`.
  544. # (api/core/app/entities/app_invoke_entities.py)
  545. invoke_from = mapped_column(String(255), nullable=True)
  546. # ref: ConversationSource.
  547. from_source: Mapped[str] = mapped_column(String(255), nullable=False)
  548. from_end_user_id = mapped_column(StringUUID)
  549. from_account_id = mapped_column(StringUUID)
  550. read_at = mapped_column(sa.DateTime)
  551. read_account_id = mapped_column(StringUUID)
  552. dialogue_count: Mapped[int] = mapped_column(default=0)
  553. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  554. updated_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  555. messages = db.relationship("Message", backref="conversation", lazy="select", passive_deletes="all")
  556. message_annotations = db.relationship(
  557. "MessageAnnotation", backref="conversation", lazy="select", passive_deletes="all"
  558. )
  559. is_deleted: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  560. @property
  561. def inputs(self):
  562. inputs = self._inputs.copy()
  563. # Convert file mapping to File object
  564. for key, value in inputs.items():
  565. # NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
  566. from factories import file_factory
  567. if isinstance(value, dict) and value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
  568. if value["transfer_method"] == FileTransferMethod.TOOL_FILE:
  569. value["tool_file_id"] = value["related_id"]
  570. elif value["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  571. value["upload_file_id"] = value["related_id"]
  572. inputs[key] = file_factory.build_from_mapping(mapping=value, tenant_id=value["tenant_id"])
  573. elif isinstance(value, list) and all(
  574. isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
  575. ):
  576. inputs[key] = []
  577. for item in value:
  578. if item["transfer_method"] == FileTransferMethod.TOOL_FILE:
  579. item["tool_file_id"] = item["related_id"]
  580. elif item["transfer_method"] in [FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL]:
  581. item["upload_file_id"] = item["related_id"]
  582. inputs[key].append(file_factory.build_from_mapping(mapping=item, tenant_id=item["tenant_id"]))
  583. return inputs
  584. @inputs.setter
  585. def inputs(self, value: Mapping[str, Any]):
  586. inputs = dict(value)
  587. for k, v in inputs.items():
  588. if isinstance(v, File):
  589. inputs[k] = v.model_dump()
  590. elif isinstance(v, list) and all(isinstance(item, File) for item in v):
  591. inputs[k] = [item.model_dump() for item in v]
  592. self._inputs = inputs
  593. @property
  594. def model_config(self):
  595. model_config = {}
  596. app_model_config: Optional[AppModelConfig] = None
  597. if self.mode == AppMode.ADVANCED_CHAT.value:
  598. if self.override_model_configs:
  599. override_model_configs = json.loads(self.override_model_configs)
  600. model_config = override_model_configs
  601. else:
  602. if self.override_model_configs:
  603. override_model_configs = json.loads(self.override_model_configs)
  604. if "model" in override_model_configs:
  605. app_model_config = AppModelConfig()
  606. app_model_config = app_model_config.from_model_config_dict(override_model_configs)
  607. model_config = app_model_config.to_dict()
  608. else:
  609. model_config["configs"] = override_model_configs
  610. else:
  611. app_model_config = (
  612. db.session.query(AppModelConfig).where(AppModelConfig.id == self.app_model_config_id).first()
  613. )
  614. if app_model_config:
  615. model_config = app_model_config.to_dict()
  616. model_config["model_id"] = self.model_id
  617. model_config["provider"] = self.model_provider
  618. return model_config
  619. @property
  620. def summary_or_query(self):
  621. if self.summary:
  622. return self.summary
  623. else:
  624. first_message = self.first_message
  625. if first_message:
  626. return first_message.query
  627. else:
  628. return ""
  629. @property
  630. def annotated(self):
  631. return db.session.query(MessageAnnotation).where(MessageAnnotation.conversation_id == self.id).count() > 0
  632. @property
  633. def annotation(self):
  634. return db.session.query(MessageAnnotation).where(MessageAnnotation.conversation_id == self.id).first()
  635. @property
  636. def message_count(self):
  637. return db.session.query(Message).where(Message.conversation_id == self.id).count()
  638. @property
  639. def user_feedback_stats(self):
  640. like = (
  641. db.session.query(MessageFeedback)
  642. .where(
  643. MessageFeedback.conversation_id == self.id,
  644. MessageFeedback.from_source == "user",
  645. MessageFeedback.rating == "like",
  646. )
  647. .count()
  648. )
  649. dislike = (
  650. db.session.query(MessageFeedback)
  651. .where(
  652. MessageFeedback.conversation_id == self.id,
  653. MessageFeedback.from_source == "user",
  654. MessageFeedback.rating == "dislike",
  655. )
  656. .count()
  657. )
  658. return {"like": like, "dislike": dislike}
  659. @property
  660. def admin_feedback_stats(self):
  661. like = (
  662. db.session.query(MessageFeedback)
  663. .where(
  664. MessageFeedback.conversation_id == self.id,
  665. MessageFeedback.from_source == "admin",
  666. MessageFeedback.rating == "like",
  667. )
  668. .count()
  669. )
  670. dislike = (
  671. db.session.query(MessageFeedback)
  672. .where(
  673. MessageFeedback.conversation_id == self.id,
  674. MessageFeedback.from_source == "admin",
  675. MessageFeedback.rating == "dislike",
  676. )
  677. .count()
  678. )
  679. return {"like": like, "dislike": dislike}
  680. @property
  681. def status_count(self):
  682. messages = db.session.query(Message).where(Message.conversation_id == self.id).all()
  683. status_counts = {
  684. WorkflowExecutionStatus.RUNNING: 0,
  685. WorkflowExecutionStatus.SUCCEEDED: 0,
  686. WorkflowExecutionStatus.FAILED: 0,
  687. WorkflowExecutionStatus.STOPPED: 0,
  688. WorkflowExecutionStatus.PARTIAL_SUCCEEDED: 0,
  689. }
  690. for message in messages:
  691. if message.workflow_run:
  692. status_counts[WorkflowExecutionStatus(message.workflow_run.status)] += 1
  693. return (
  694. {
  695. "success": status_counts[WorkflowExecutionStatus.SUCCEEDED],
  696. "failed": status_counts[WorkflowExecutionStatus.FAILED],
  697. "partial_success": status_counts[WorkflowExecutionStatus.PARTIAL_SUCCEEDED],
  698. }
  699. if messages
  700. else None
  701. )
  702. @property
  703. def first_message(self):
  704. return (
  705. db.session.query(Message)
  706. .where(Message.conversation_id == self.id)
  707. .order_by(Message.created_at.asc())
  708. .first()
  709. )
  710. @property
  711. def app(self):
  712. return db.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] = db.Column(sa.Text, nullable=False) # TODO make it mapped_column
  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 = db.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.query(ApiToken).where(ApiToken.token == result).count() > 0:
  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. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1353. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1354. storage_type: Mapped[str] = mapped_column(String(255), nullable=False)
  1355. key: Mapped[str] = mapped_column(String(255), nullable=False)
  1356. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1357. size: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1358. extension: Mapped[str] = mapped_column(String(255), nullable=False)
  1359. mime_type: Mapped[str] = mapped_column(String(255), nullable=True)
  1360. created_by_role: Mapped[str] = mapped_column(
  1361. String(255), nullable=False, server_default=sa.text("'account'::character varying")
  1362. )
  1363. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  1364. created_at: Mapped[datetime] = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1365. used: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  1366. used_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
  1367. used_at: Mapped[datetime | None] = mapped_column(sa.DateTime, nullable=True)
  1368. hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
  1369. source_url: Mapped[str] = mapped_column(sa.TEXT, default="")
  1370. def __init__(
  1371. self,
  1372. *,
  1373. tenant_id: str,
  1374. storage_type: str,
  1375. key: str,
  1376. name: str,
  1377. size: int,
  1378. extension: str,
  1379. mime_type: str,
  1380. created_by_role: CreatorUserRole,
  1381. created_by: str,
  1382. created_at: datetime,
  1383. used: bool,
  1384. used_by: str | None = None,
  1385. used_at: datetime | None = None,
  1386. hash: str | None = None,
  1387. source_url: str = "",
  1388. ):
  1389. self.tenant_id = tenant_id
  1390. self.storage_type = storage_type
  1391. self.key = key
  1392. self.name = name
  1393. self.size = size
  1394. self.extension = extension
  1395. self.mime_type = mime_type
  1396. self.created_by_role = created_by_role.value
  1397. self.created_by = created_by
  1398. self.created_at = created_at
  1399. self.used = used
  1400. self.used_by = used_by
  1401. self.used_at = used_at
  1402. self.hash = hash
  1403. self.source_url = source_url
  1404. class ApiRequest(Base):
  1405. __tablename__ = "api_requests"
  1406. __table_args__ = (
  1407. sa.PrimaryKeyConstraint("id", name="api_request_pkey"),
  1408. sa.Index("api_request_token_idx", "tenant_id", "api_token_id"),
  1409. )
  1410. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1411. tenant_id = mapped_column(StringUUID, nullable=False)
  1412. api_token_id = mapped_column(StringUUID, nullable=False)
  1413. path: Mapped[str] = mapped_column(String(255), nullable=False)
  1414. request = mapped_column(sa.Text, nullable=True)
  1415. response = mapped_column(sa.Text, nullable=True)
  1416. ip: Mapped[str] = mapped_column(String(255), nullable=False)
  1417. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1418. class MessageChain(Base):
  1419. __tablename__ = "message_chains"
  1420. __table_args__ = (
  1421. sa.PrimaryKeyConstraint("id", name="message_chain_pkey"),
  1422. sa.Index("message_chain_message_id_idx", "message_id"),
  1423. )
  1424. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1425. message_id = mapped_column(StringUUID, nullable=False)
  1426. type: Mapped[str] = mapped_column(String(255), nullable=False)
  1427. input = mapped_column(sa.Text, nullable=True)
  1428. output = mapped_column(sa.Text, nullable=True)
  1429. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1430. class MessageAgentThought(Base):
  1431. __tablename__ = "message_agent_thoughts"
  1432. __table_args__ = (
  1433. sa.PrimaryKeyConstraint("id", name="message_agent_thought_pkey"),
  1434. sa.Index("message_agent_thought_message_id_idx", "message_id"),
  1435. sa.Index("message_agent_thought_message_chain_id_idx", "message_chain_id"),
  1436. )
  1437. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1438. message_id = mapped_column(StringUUID, nullable=False)
  1439. message_chain_id = mapped_column(StringUUID, nullable=True)
  1440. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1441. thought = mapped_column(sa.Text, nullable=True)
  1442. tool = mapped_column(sa.Text, nullable=True)
  1443. tool_labels_str = mapped_column(sa.Text, nullable=False, server_default=sa.text("'{}'::text"))
  1444. tool_meta_str = mapped_column(sa.Text, nullable=False, server_default=sa.text("'{}'::text"))
  1445. tool_input = mapped_column(sa.Text, nullable=True)
  1446. observation = mapped_column(sa.Text, nullable=True)
  1447. # plugin_id = mapped_column(StringUUID, nullable=True) ## for future design
  1448. tool_process_data = mapped_column(sa.Text, nullable=True)
  1449. message = mapped_column(sa.Text, nullable=True)
  1450. message_token: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1451. message_unit_price = mapped_column(sa.Numeric, nullable=True)
  1452. message_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  1453. message_files = mapped_column(sa.Text, nullable=True)
  1454. answer = db.Column(sa.Text, nullable=True)
  1455. answer_token: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1456. answer_unit_price = mapped_column(sa.Numeric, nullable=True)
  1457. answer_price_unit = mapped_column(sa.Numeric(10, 7), nullable=False, server_default=sa.text("0.001"))
  1458. tokens: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1459. total_price = mapped_column(sa.Numeric, nullable=True)
  1460. currency = mapped_column(String, nullable=True)
  1461. latency: Mapped[Optional[float]] = mapped_column(sa.Float, nullable=True)
  1462. created_by_role = mapped_column(String, nullable=False)
  1463. created_by = mapped_column(StringUUID, nullable=False)
  1464. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1465. @property
  1466. def files(self) -> list:
  1467. if self.message_files:
  1468. return cast(list[Any], json.loads(self.message_files))
  1469. else:
  1470. return []
  1471. @property
  1472. def tools(self) -> list[str]:
  1473. return self.tool.split(";") if self.tool else []
  1474. @property
  1475. def tool_labels(self) -> dict:
  1476. try:
  1477. if self.tool_labels_str:
  1478. return cast(dict, json.loads(self.tool_labels_str))
  1479. else:
  1480. return {}
  1481. except Exception:
  1482. return {}
  1483. @property
  1484. def tool_meta(self) -> dict:
  1485. try:
  1486. if self.tool_meta_str:
  1487. return cast(dict, json.loads(self.tool_meta_str))
  1488. else:
  1489. return {}
  1490. except Exception:
  1491. return {}
  1492. @property
  1493. def tool_inputs_dict(self) -> dict:
  1494. tools = self.tools
  1495. try:
  1496. if self.tool_input:
  1497. data = json.loads(self.tool_input)
  1498. result = {}
  1499. for tool in tools:
  1500. if tool in data:
  1501. result[tool] = data[tool]
  1502. else:
  1503. if len(tools) == 1:
  1504. result[tool] = data
  1505. else:
  1506. result[tool] = {}
  1507. return result
  1508. else:
  1509. return {tool: {} for tool in tools}
  1510. except Exception:
  1511. return {}
  1512. @property
  1513. def tool_outputs_dict(self):
  1514. tools = self.tools
  1515. try:
  1516. if self.observation:
  1517. data = json.loads(self.observation)
  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. if self.observation:
  1532. return dict.fromkeys(tools, self.observation)
  1533. else:
  1534. return {}
  1535. class DatasetRetrieverResource(Base):
  1536. __tablename__ = "dataset_retriever_resources"
  1537. __table_args__ = (
  1538. sa.PrimaryKeyConstraint("id", name="dataset_retriever_resource_pkey"),
  1539. sa.Index("dataset_retriever_resource_message_id_idx", "message_id"),
  1540. )
  1541. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  1542. message_id = mapped_column(StringUUID, nullable=False)
  1543. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  1544. dataset_id = mapped_column(StringUUID, nullable=False)
  1545. dataset_name = mapped_column(sa.Text, nullable=False)
  1546. document_id = mapped_column(StringUUID, nullable=True)
  1547. document_name = mapped_column(sa.Text, nullable=False)
  1548. data_source_type = mapped_column(sa.Text, nullable=True)
  1549. segment_id = mapped_column(StringUUID, nullable=True)
  1550. score: Mapped[Optional[float]] = mapped_column(sa.Float, nullable=True)
  1551. content = mapped_column(sa.Text, nullable=False)
  1552. hit_count: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1553. word_count: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1554. segment_position: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  1555. index_node_hash = mapped_column(sa.Text, nullable=True)
  1556. retriever_from = mapped_column(sa.Text, nullable=False)
  1557. created_by = mapped_column(StringUUID, nullable=False)
  1558. created_at = mapped_column(sa.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1559. class Tag(Base):
  1560. __tablename__ = "tags"
  1561. __table_args__ = (
  1562. sa.PrimaryKeyConstraint("id", name="tag_pkey"),
  1563. sa.Index("tag_type_idx", "type"),
  1564. sa.Index("tag_name_idx", "name"),
  1565. )
  1566. TAG_TYPE_LIST = ["knowledge", "app"]
  1567. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1568. tenant_id = mapped_column(StringUUID, nullable=True)
  1569. type = mapped_column(String(16), nullable=False)
  1570. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1571. created_by = mapped_column(StringUUID, nullable=False)
  1572. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1573. class TagBinding(Base):
  1574. __tablename__ = "tag_bindings"
  1575. __table_args__ = (
  1576. sa.PrimaryKeyConstraint("id", name="tag_binding_pkey"),
  1577. sa.Index("tag_bind_target_id_idx", "target_id"),
  1578. sa.Index("tag_bind_tag_id_idx", "tag_id"),
  1579. )
  1580. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1581. tenant_id = mapped_column(StringUUID, nullable=True)
  1582. tag_id = mapped_column(StringUUID, nullable=True)
  1583. target_id = mapped_column(StringUUID, nullable=True)
  1584. created_by = mapped_column(StringUUID, nullable=False)
  1585. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1586. class TraceAppConfig(Base):
  1587. __tablename__ = "trace_app_config"
  1588. __table_args__ = (
  1589. sa.PrimaryKeyConstraint("id", name="tracing_app_config_pkey"),
  1590. sa.Index("trace_app_config_app_id_idx", "app_id"),
  1591. )
  1592. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1593. app_id = mapped_column(StringUUID, nullable=False)
  1594. tracing_provider = mapped_column(String(255), nullable=True)
  1595. tracing_config = mapped_column(sa.JSON, nullable=True)
  1596. created_at = mapped_column(sa.DateTime, nullable=False, server_default=func.current_timestamp())
  1597. updated_at = mapped_column(
  1598. sa.DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  1599. )
  1600. is_active: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  1601. @property
  1602. def tracing_config_dict(self):
  1603. return self.tracing_config or {}
  1604. @property
  1605. def tracing_config_str(self):
  1606. return json.dumps(self.tracing_config_dict)
  1607. def to_dict(self):
  1608. return {
  1609. "id": self.id,
  1610. "app_id": self.app_id,
  1611. "tracing_provider": self.tracing_provider,
  1612. "tracing_config": self.tracing_config_dict,
  1613. "is_active": self.is_active,
  1614. "created_at": str(self.created_at) if self.created_at else None,
  1615. "updated_at": str(self.updated_at) if self.updated_at else None,
  1616. }