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.

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