Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

model.py 76KB

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