您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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. @property
  247. def author_name(self):
  248. if self.created_by:
  249. account = db.session.query(Account).filter(Account.id == self.created_by).first()
  250. if account:
  251. return account.name
  252. return None
  253. class AppModelConfig(Base):
  254. __tablename__ = "app_model_configs"
  255. __table_args__ = (db.PrimaryKeyConstraint("id", name="app_model_config_pkey"), db.Index("app_app_id_idx", "app_id"))
  256. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  257. app_id = db.Column(StringUUID, nullable=False)
  258. provider = db.Column(db.String(255), nullable=True)
  259. model_id = db.Column(db.String(255), nullable=True)
  260. configs = db.Column(db.JSON, nullable=True)
  261. created_by = db.Column(StringUUID, nullable=True)
  262. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  263. updated_by = db.Column(StringUUID, nullable=True)
  264. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  265. opening_statement = db.Column(db.Text)
  266. suggested_questions = db.Column(db.Text)
  267. suggested_questions_after_answer = db.Column(db.Text)
  268. speech_to_text = db.Column(db.Text)
  269. text_to_speech = db.Column(db.Text)
  270. more_like_this = db.Column(db.Text)
  271. model = db.Column(db.Text)
  272. user_input_form = db.Column(db.Text)
  273. dataset_query_variable = db.Column(db.String(255))
  274. pre_prompt = db.Column(db.Text)
  275. agent_mode = db.Column(db.Text)
  276. sensitive_word_avoidance = db.Column(db.Text)
  277. retriever_resource = db.Column(db.Text)
  278. prompt_type = db.Column(db.String(255), nullable=False, server_default=db.text("'simple'::character varying"))
  279. chat_prompt_config = db.Column(db.Text)
  280. completion_prompt_config = db.Column(db.Text)
  281. dataset_configs = db.Column(db.Text)
  282. external_data_tools = db.Column(db.Text)
  283. file_upload = db.Column(db.Text)
  284. @property
  285. def app(self):
  286. app = db.session.query(App).filter(App.id == self.app_id).first()
  287. return app
  288. @property
  289. def model_dict(self) -> dict:
  290. return json.loads(self.model) if self.model else {}
  291. @property
  292. def suggested_questions_list(self) -> list:
  293. return json.loads(self.suggested_questions) if self.suggested_questions else []
  294. @property
  295. def suggested_questions_after_answer_dict(self) -> dict:
  296. return (
  297. json.loads(self.suggested_questions_after_answer)
  298. if self.suggested_questions_after_answer
  299. else {"enabled": False}
  300. )
  301. @property
  302. def speech_to_text_dict(self) -> dict:
  303. return json.loads(self.speech_to_text) if self.speech_to_text else {"enabled": False}
  304. @property
  305. def text_to_speech_dict(self) -> dict:
  306. return json.loads(self.text_to_speech) if self.text_to_speech else {"enabled": False}
  307. @property
  308. def retriever_resource_dict(self) -> dict:
  309. return json.loads(self.retriever_resource) if self.retriever_resource else {"enabled": True}
  310. @property
  311. def annotation_reply_dict(self) -> dict:
  312. annotation_setting = (
  313. db.session.query(AppAnnotationSetting).filter(AppAnnotationSetting.app_id == self.app_id).first()
  314. )
  315. if annotation_setting:
  316. collection_binding_detail = annotation_setting.collection_binding_detail
  317. if not collection_binding_detail:
  318. raise ValueError("Collection binding detail not found")
  319. return {
  320. "id": annotation_setting.id,
  321. "enabled": True,
  322. "score_threshold": annotation_setting.score_threshold,
  323. "embedding_model": {
  324. "embedding_provider_name": collection_binding_detail.provider_name,
  325. "embedding_model_name": collection_binding_detail.model_name,
  326. },
  327. }
  328. else:
  329. return {"enabled": False}
  330. @property
  331. def more_like_this_dict(self) -> dict:
  332. return json.loads(self.more_like_this) if self.more_like_this else {"enabled": False}
  333. @property
  334. def sensitive_word_avoidance_dict(self) -> dict:
  335. return (
  336. json.loads(self.sensitive_word_avoidance)
  337. if self.sensitive_word_avoidance
  338. else {"enabled": False, "type": "", "configs": []}
  339. )
  340. @property
  341. def external_data_tools_list(self) -> list[dict]:
  342. return json.loads(self.external_data_tools) if self.external_data_tools else []
  343. @property
  344. def user_input_form_list(self):
  345. return json.loads(self.user_input_form) if self.user_input_form else []
  346. @property
  347. def agent_mode_dict(self) -> dict:
  348. return (
  349. json.loads(self.agent_mode)
  350. if self.agent_mode
  351. else {"enabled": False, "strategy": None, "tools": [], "prompt": None}
  352. )
  353. @property
  354. def chat_prompt_config_dict(self) -> dict:
  355. return json.loads(self.chat_prompt_config) if self.chat_prompt_config else {}
  356. @property
  357. def completion_prompt_config_dict(self) -> dict:
  358. return json.loads(self.completion_prompt_config) if self.completion_prompt_config else {}
  359. @property
  360. def dataset_configs_dict(self) -> dict:
  361. if self.dataset_configs:
  362. dataset_configs: dict = json.loads(self.dataset_configs)
  363. if "retrieval_model" not in dataset_configs:
  364. return {"retrieval_model": "single"}
  365. else:
  366. return dataset_configs
  367. return {
  368. "retrieval_model": "multiple",
  369. }
  370. @property
  371. def file_upload_dict(self) -> dict:
  372. return (
  373. json.loads(self.file_upload)
  374. if self.file_upload
  375. else {
  376. "image": {
  377. "enabled": False,
  378. "number_limits": DEFAULT_FILE_NUMBER_LIMITS,
  379. "detail": "high",
  380. "transfer_methods": ["remote_url", "local_file"],
  381. }
  382. }
  383. )
  384. def to_dict(self) -> dict:
  385. return {
  386. "opening_statement": self.opening_statement,
  387. "suggested_questions": self.suggested_questions_list,
  388. "suggested_questions_after_answer": self.suggested_questions_after_answer_dict,
  389. "speech_to_text": self.speech_to_text_dict,
  390. "text_to_speech": self.text_to_speech_dict,
  391. "retriever_resource": self.retriever_resource_dict,
  392. "annotation_reply": self.annotation_reply_dict,
  393. "more_like_this": self.more_like_this_dict,
  394. "sensitive_word_avoidance": self.sensitive_word_avoidance_dict,
  395. "external_data_tools": self.external_data_tools_list,
  396. "model": self.model_dict,
  397. "user_input_form": self.user_input_form_list,
  398. "dataset_query_variable": self.dataset_query_variable,
  399. "pre_prompt": self.pre_prompt,
  400. "agent_mode": self.agent_mode_dict,
  401. "prompt_type": self.prompt_type,
  402. "chat_prompt_config": self.chat_prompt_config_dict,
  403. "completion_prompt_config": self.completion_prompt_config_dict,
  404. "dataset_configs": self.dataset_configs_dict,
  405. "file_upload": self.file_upload_dict,
  406. }
  407. def from_model_config_dict(self, model_config: Mapping[str, Any]):
  408. self.opening_statement = model_config.get("opening_statement")
  409. self.suggested_questions = (
  410. json.dumps(model_config["suggested_questions"]) if model_config.get("suggested_questions") else None
  411. )
  412. self.suggested_questions_after_answer = (
  413. json.dumps(model_config["suggested_questions_after_answer"])
  414. if model_config.get("suggested_questions_after_answer")
  415. else None
  416. )
  417. self.speech_to_text = json.dumps(model_config["speech_to_text"]) if model_config.get("speech_to_text") else None
  418. self.text_to_speech = json.dumps(model_config["text_to_speech"]) if model_config.get("text_to_speech") else None
  419. self.more_like_this = json.dumps(model_config["more_like_this"]) if model_config.get("more_like_this") else None
  420. self.sensitive_word_avoidance = (
  421. json.dumps(model_config["sensitive_word_avoidance"])
  422. if model_config.get("sensitive_word_avoidance")
  423. else None
  424. )
  425. self.external_data_tools = (
  426. json.dumps(model_config["external_data_tools"]) if model_config.get("external_data_tools") else None
  427. )
  428. self.model = json.dumps(model_config["model"]) if model_config.get("model") else None
  429. self.user_input_form = (
  430. json.dumps(model_config["user_input_form"]) if model_config.get("user_input_form") else None
  431. )
  432. self.dataset_query_variable = model_config.get("dataset_query_variable")
  433. self.pre_prompt = model_config["pre_prompt"]
  434. self.agent_mode = json.dumps(model_config["agent_mode"]) if model_config.get("agent_mode") else None
  435. self.retriever_resource = (
  436. json.dumps(model_config["retriever_resource"]) if model_config.get("retriever_resource") else None
  437. )
  438. self.prompt_type = model_config.get("prompt_type", "simple")
  439. self.chat_prompt_config = (
  440. json.dumps(model_config.get("chat_prompt_config")) if model_config.get("chat_prompt_config") else None
  441. )
  442. self.completion_prompt_config = (
  443. json.dumps(model_config.get("completion_prompt_config"))
  444. if model_config.get("completion_prompt_config")
  445. else None
  446. )
  447. self.dataset_configs = (
  448. json.dumps(model_config.get("dataset_configs")) if model_config.get("dataset_configs") else None
  449. )
  450. self.file_upload = json.dumps(model_config.get("file_upload")) if model_config.get("file_upload") else None
  451. return self
  452. def copy(self):
  453. new_app_model_config = AppModelConfig(
  454. id=self.id,
  455. app_id=self.app_id,
  456. opening_statement=self.opening_statement,
  457. suggested_questions=self.suggested_questions,
  458. suggested_questions_after_answer=self.suggested_questions_after_answer,
  459. speech_to_text=self.speech_to_text,
  460. text_to_speech=self.text_to_speech,
  461. more_like_this=self.more_like_this,
  462. sensitive_word_avoidance=self.sensitive_word_avoidance,
  463. external_data_tools=self.external_data_tools,
  464. model=self.model,
  465. user_input_form=self.user_input_form,
  466. dataset_query_variable=self.dataset_query_variable,
  467. pre_prompt=self.pre_prompt,
  468. agent_mode=self.agent_mode,
  469. retriever_resource=self.retriever_resource,
  470. prompt_type=self.prompt_type,
  471. chat_prompt_config=self.chat_prompt_config,
  472. completion_prompt_config=self.completion_prompt_config,
  473. dataset_configs=self.dataset_configs,
  474. file_upload=self.file_upload,
  475. )
  476. return new_app_model_config
  477. class RecommendedApp(Base):
  478. __tablename__ = "recommended_apps"
  479. __table_args__ = (
  480. db.PrimaryKeyConstraint("id", name="recommended_app_pkey"),
  481. db.Index("recommended_app_app_id_idx", "app_id"),
  482. db.Index("recommended_app_is_listed_idx", "is_listed", "language"),
  483. )
  484. id = db.Column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  485. app_id = db.Column(StringUUID, nullable=False)
  486. description = db.Column(db.JSON, nullable=False)
  487. copyright = db.Column(db.String(255), nullable=False)
  488. privacy_policy = db.Column(db.String(255), nullable=False)
  489. custom_disclaimer: Mapped[str] = mapped_column(sa.TEXT, default="")
  490. category = db.Column(db.String(255), nullable=False)
  491. position = db.Column(db.Integer, nullable=False, default=0)
  492. is_listed = db.Column(db.Boolean, nullable=False, default=True)
  493. install_count = db.Column(db.Integer, nullable=False, default=0)
  494. language = db.Column(db.String(255), nullable=False, server_default=db.text("'en-US'::character varying"))
  495. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  496. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  497. @property
  498. def app(self):
  499. app = db.session.query(App).filter(App.id == self.app_id).first()
  500. return app
  501. class InstalledApp(Base):
  502. __tablename__ = "installed_apps"
  503. __table_args__ = (
  504. db.PrimaryKeyConstraint("id", name="installed_app_pkey"),
  505. db.Index("installed_app_tenant_id_idx", "tenant_id"),
  506. db.Index("installed_app_app_id_idx", "app_id"),
  507. db.UniqueConstraint("tenant_id", "app_id", name="unique_tenant_app"),
  508. )
  509. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  510. tenant_id = db.Column(StringUUID, nullable=False)
  511. app_id = db.Column(StringUUID, nullable=False)
  512. app_owner_tenant_id = db.Column(StringUUID, nullable=False)
  513. position = db.Column(db.Integer, nullable=False, default=0)
  514. is_pinned = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  515. last_used_at = db.Column(db.DateTime, nullable=True)
  516. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  517. @property
  518. def app(self):
  519. app = db.session.query(App).filter(App.id == self.app_id).first()
  520. return app
  521. @property
  522. def tenant(self):
  523. tenant = db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
  524. return tenant
  525. class Conversation(Base):
  526. __tablename__ = "conversations"
  527. __table_args__ = (
  528. db.PrimaryKeyConstraint("id", name="conversation_pkey"),
  529. db.Index("conversation_app_from_user_idx", "app_id", "from_source", "from_end_user_id"),
  530. )
  531. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  532. app_id = db.Column(StringUUID, nullable=False)
  533. app_model_config_id = db.Column(StringUUID, nullable=True)
  534. model_provider = db.Column(db.String(255), nullable=True)
  535. override_model_configs = db.Column(db.Text)
  536. model_id = db.Column(db.String(255), nullable=True)
  537. mode: Mapped[str] = mapped_column(db.String(255))
  538. name = db.Column(db.String(255), nullable=False)
  539. summary = db.Column(db.Text)
  540. _inputs: Mapped[dict] = mapped_column("inputs", db.JSON)
  541. introduction = db.Column(db.Text)
  542. system_instruction = db.Column(db.Text)
  543. system_instruction_tokens = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  544. status = db.Column(db.String(255), nullable=False)
  545. invoke_from = db.Column(db.String(255), nullable=True)
  546. from_source = db.Column(db.String(255), nullable=False)
  547. from_end_user_id = db.Column(StringUUID)
  548. from_account_id = db.Column(StringUUID)
  549. read_at = db.Column(db.DateTime)
  550. read_account_id = db.Column(StringUUID)
  551. dialogue_count: Mapped[int] = mapped_column(default=0)
  552. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  553. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  554. messages = db.relationship("Message", backref="conversation", lazy="select", passive_deletes="all")
  555. message_annotations = db.relationship(
  556. "MessageAnnotation", backref="conversation", lazy="select", passive_deletes="all"
  557. )
  558. is_deleted = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  559. @property
  560. def inputs(self):
  561. inputs = self._inputs.copy()
  562. # Convert file mapping to File object
  563. for key, value in inputs.items():
  564. # NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
  565. from factories import file_factory
  566. if isinstance(value, dict) and value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
  567. if value["transfer_method"] == FileTransferMethod.TOOL_FILE:
  568. value["tool_file_id"] = value["related_id"]
  569. elif value["transfer_method"] == FileTransferMethod.LOCAL_FILE:
  570. value["upload_file_id"] = value["related_id"]
  571. inputs[key] = file_factory.build_from_mapping(mapping=value, tenant_id=value["tenant_id"])
  572. elif isinstance(value, list) and all(
  573. isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
  574. ):
  575. inputs[key] = []
  576. for item in value:
  577. if item["transfer_method"] == FileTransferMethod.TOOL_FILE:
  578. item["tool_file_id"] = item["related_id"]
  579. elif item["transfer_method"] == FileTransferMethod.LOCAL_FILE:
  580. item["upload_file_id"] = item["related_id"]
  581. inputs[key].append(file_factory.build_from_mapping(mapping=item, tenant_id=item["tenant_id"]))
  582. return inputs
  583. @inputs.setter
  584. def inputs(self, value: Mapping[str, Any]):
  585. inputs = dict(value)
  586. for k, v in inputs.items():
  587. if isinstance(v, File):
  588. inputs[k] = v.model_dump()
  589. elif isinstance(v, list) and all(isinstance(item, File) for item in v):
  590. inputs[k] = [item.model_dump() for item in v]
  591. self._inputs = inputs
  592. @property
  593. def model_config(self):
  594. model_config = {}
  595. app_model_config: Optional[AppModelConfig] = None
  596. if self.mode == AppMode.ADVANCED_CHAT.value:
  597. if self.override_model_configs:
  598. override_model_configs = json.loads(self.override_model_configs)
  599. model_config = override_model_configs
  600. else:
  601. if self.override_model_configs:
  602. override_model_configs = json.loads(self.override_model_configs)
  603. if "model" in override_model_configs:
  604. app_model_config = AppModelConfig()
  605. app_model_config = app_model_config.from_model_config_dict(override_model_configs)
  606. assert app_model_config is not None, "app model config not found"
  607. model_config = app_model_config.to_dict()
  608. else:
  609. model_config["configs"] = override_model_configs
  610. else:
  611. app_model_config = (
  612. db.session.query(AppModelConfig).filter(AppModelConfig.id == self.app_model_config_id).first()
  613. )
  614. if app_model_config:
  615. model_config = app_model_config.to_dict()
  616. model_config["model_id"] = self.model_id
  617. model_config["provider"] = self.model_provider
  618. return model_config
  619. @property
  620. def summary_or_query(self):
  621. if self.summary:
  622. return self.summary
  623. else:
  624. first_message = self.first_message
  625. if first_message:
  626. return first_message.query
  627. else:
  628. return ""
  629. @property
  630. def annotated(self):
  631. return db.session.query(MessageAnnotation).filter(MessageAnnotation.conversation_id == self.id).count() > 0
  632. @property
  633. def annotation(self):
  634. return db.session.query(MessageAnnotation).filter(MessageAnnotation.conversation_id == self.id).first()
  635. @property
  636. def message_count(self):
  637. return db.session.query(Message).filter(Message.conversation_id == self.id).count()
  638. @property
  639. def user_feedback_stats(self):
  640. like = (
  641. db.session.query(MessageFeedback)
  642. .filter(
  643. MessageFeedback.conversation_id == self.id,
  644. MessageFeedback.from_source == "user",
  645. MessageFeedback.rating == "like",
  646. )
  647. .count()
  648. )
  649. dislike = (
  650. db.session.query(MessageFeedback)
  651. .filter(
  652. MessageFeedback.conversation_id == self.id,
  653. MessageFeedback.from_source == "user",
  654. MessageFeedback.rating == "dislike",
  655. )
  656. .count()
  657. )
  658. return {"like": like, "dislike": dislike}
  659. @property
  660. def admin_feedback_stats(self):
  661. like = (
  662. db.session.query(MessageFeedback)
  663. .filter(
  664. MessageFeedback.conversation_id == self.id,
  665. MessageFeedback.from_source == "admin",
  666. MessageFeedback.rating == "like",
  667. )
  668. .count()
  669. )
  670. dislike = (
  671. db.session.query(MessageFeedback)
  672. .filter(
  673. MessageFeedback.conversation_id == self.id,
  674. MessageFeedback.from_source == "admin",
  675. MessageFeedback.rating == "dislike",
  676. )
  677. .count()
  678. )
  679. return {"like": like, "dislike": dislike}
  680. @property
  681. def status_count(self):
  682. messages = db.session.query(Message).filter(Message.conversation_id == self.id).all()
  683. status_counts = {
  684. WorkflowRunStatus.RUNNING: 0,
  685. WorkflowRunStatus.SUCCEEDED: 0,
  686. WorkflowRunStatus.FAILED: 0,
  687. WorkflowRunStatus.STOPPED: 0,
  688. WorkflowRunStatus.PARTIAL_SUCCEEDED: 0,
  689. }
  690. for message in messages:
  691. if message.workflow_run:
  692. status_counts[WorkflowRunStatus(message.workflow_run.status)] += 1
  693. return (
  694. {
  695. "success": status_counts[WorkflowRunStatus.SUCCEEDED],
  696. "failed": status_counts[WorkflowRunStatus.FAILED],
  697. "partial_success": status_counts[WorkflowRunStatus.PARTIAL_SUCCEEDED],
  698. }
  699. if messages
  700. else None
  701. )
  702. @property
  703. def first_message(self):
  704. return db.session.query(Message).filter(Message.conversation_id == self.id).first()
  705. @property
  706. def app(self):
  707. return db.session.query(App).filter(App.id == self.app_id).first()
  708. @property
  709. def from_end_user_session_id(self):
  710. if self.from_end_user_id:
  711. end_user = db.session.query(EndUser).filter(EndUser.id == self.from_end_user_id).first()
  712. if end_user:
  713. return end_user.session_id
  714. return None
  715. @property
  716. def from_account_name(self):
  717. if self.from_account_id:
  718. account = db.session.query(Account).filter(Account.id == self.from_account_id).first()
  719. if account:
  720. return account.name
  721. return None
  722. @property
  723. def in_debug_mode(self):
  724. return self.override_model_configs is not None
  725. def to_dict(self):
  726. return {
  727. "id": self.id,
  728. "app_id": self.app_id,
  729. "app_model_config_id": self.app_model_config_id,
  730. "model_provider": self.model_provider,
  731. "override_model_configs": self.override_model_configs,
  732. "model_id": self.model_id,
  733. "mode": self.mode,
  734. "name": self.name,
  735. "summary": self.summary,
  736. "inputs": self.inputs,
  737. "introduction": self.introduction,
  738. "system_instruction": self.system_instruction,
  739. "system_instruction_tokens": self.system_instruction_tokens,
  740. "status": self.status,
  741. "invoke_from": self.invoke_from,
  742. "from_source": self.from_source,
  743. "from_end_user_id": self.from_end_user_id,
  744. "from_account_id": self.from_account_id,
  745. "read_at": self.read_at,
  746. "read_account_id": self.read_account_id,
  747. "dialogue_count": self.dialogue_count,
  748. "created_at": self.created_at,
  749. "updated_at": self.updated_at,
  750. }
  751. class Message(Base):
  752. __tablename__ = "messages"
  753. __table_args__ = (
  754. PrimaryKeyConstraint("id", name="message_pkey"),
  755. Index("message_app_id_idx", "app_id", "created_at"),
  756. Index("message_conversation_id_idx", "conversation_id"),
  757. Index("message_end_user_idx", "app_id", "from_source", "from_end_user_id"),
  758. Index("message_account_idx", "app_id", "from_source", "from_account_id"),
  759. Index("message_workflow_run_id_idx", "conversation_id", "workflow_run_id"),
  760. Index("message_created_at_idx", "created_at"),
  761. )
  762. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  763. app_id = db.Column(StringUUID, nullable=False)
  764. model_provider = db.Column(db.String(255), nullable=True)
  765. model_id = db.Column(db.String(255), nullable=True)
  766. override_model_configs = db.Column(db.Text)
  767. conversation_id = db.Column(StringUUID, db.ForeignKey("conversations.id"), nullable=False)
  768. _inputs: Mapped[dict] = mapped_column("inputs", db.JSON)
  769. query: Mapped[str] = db.Column(db.Text, nullable=False)
  770. message = db.Column(db.JSON, nullable=False)
  771. message_tokens = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  772. message_unit_price = db.Column(db.Numeric(10, 4), nullable=False)
  773. message_price_unit = db.Column(db.Numeric(10, 7), nullable=False, server_default=db.text("0.001"))
  774. answer: Mapped[str] = db.Column(db.Text, nullable=False)
  775. answer_tokens = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  776. answer_unit_price = db.Column(db.Numeric(10, 4), nullable=False)
  777. answer_price_unit = db.Column(db.Numeric(10, 7), nullable=False, server_default=db.text("0.001"))
  778. parent_message_id = db.Column(StringUUID, nullable=True)
  779. provider_response_latency = db.Column(db.Float, nullable=False, server_default=db.text("0"))
  780. total_price = db.Column(db.Numeric(10, 7))
  781. currency = db.Column(db.String(255), nullable=False)
  782. status = db.Column(db.String(255), nullable=False, server_default=db.text("'normal'::character varying"))
  783. error = db.Column(db.Text)
  784. message_metadata = db.Column(db.Text)
  785. invoke_from: Mapped[Optional[str]] = db.Column(db.String(255), nullable=True)
  786. from_source = db.Column(db.String(255), nullable=False)
  787. from_end_user_id: Mapped[Optional[str]] = db.Column(StringUUID)
  788. from_account_id: Mapped[Optional[str]] = db.Column(StringUUID)
  789. created_at: Mapped[datetime] = mapped_column(db.DateTime, server_default=func.current_timestamp())
  790. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  791. agent_based = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  792. workflow_run_id = db.Column(StringUUID)
  793. @property
  794. def inputs(self):
  795. inputs = self._inputs.copy()
  796. for key, value in inputs.items():
  797. # NOTE: It's not the best way to implement this, but it's the only way to avoid circular import for now.
  798. from factories import file_factory
  799. if isinstance(value, dict) and value.get("dify_model_identity") == FILE_MODEL_IDENTITY:
  800. if value["transfer_method"] == FileTransferMethod.TOOL_FILE:
  801. value["tool_file_id"] = value["related_id"]
  802. elif value["transfer_method"] == FileTransferMethod.LOCAL_FILE:
  803. value["upload_file_id"] = value["related_id"]
  804. inputs[key] = file_factory.build_from_mapping(mapping=value, tenant_id=value["tenant_id"])
  805. elif isinstance(value, list) and all(
  806. isinstance(item, dict) and item.get("dify_model_identity") == FILE_MODEL_IDENTITY for item in value
  807. ):
  808. inputs[key] = []
  809. for item in value:
  810. if item["transfer_method"] == FileTransferMethod.TOOL_FILE:
  811. item["tool_file_id"] = item["related_id"]
  812. elif item["transfer_method"] == FileTransferMethod.LOCAL_FILE:
  813. item["upload_file_id"] = item["related_id"]
  814. inputs[key].append(file_factory.build_from_mapping(mapping=item, tenant_id=item["tenant_id"]))
  815. return inputs
  816. @inputs.setter
  817. def inputs(self, value: Mapping[str, Any]):
  818. inputs = dict(value)
  819. for k, v in inputs.items():
  820. if isinstance(v, File):
  821. inputs[k] = v.model_dump()
  822. elif isinstance(v, list) and all(isinstance(item, File) for item in v):
  823. inputs[k] = [item.model_dump() for item in v]
  824. self._inputs = inputs
  825. @property
  826. def re_sign_file_url_answer(self) -> str:
  827. if not self.answer:
  828. return self.answer
  829. pattern = r"\[!?.*?\]\((((http|https):\/\/.+)?\/files\/(tools\/)?[\w-]+.*?timestamp=.*&nonce=.*&sign=.*)\)"
  830. matches = re.findall(pattern, self.answer)
  831. if not matches:
  832. return self.answer
  833. urls = [match[0] for match in matches]
  834. # remove duplicate urls
  835. urls = list(set(urls))
  836. if not urls:
  837. return self.answer
  838. re_sign_file_url_answer = self.answer
  839. for url in urls:
  840. if "files/tools" in url:
  841. # get tool file id
  842. tool_file_id_pattern = r"\/files\/tools\/([\.\w-]+)?\?timestamp="
  843. result = re.search(tool_file_id_pattern, url)
  844. if not result:
  845. continue
  846. tool_file_id = result.group(1)
  847. # get extension
  848. if "." in tool_file_id:
  849. split_result = tool_file_id.split(".")
  850. extension = f".{split_result[-1]}"
  851. if len(extension) > 10:
  852. extension = ".bin"
  853. tool_file_id = split_result[0]
  854. else:
  855. extension = ".bin"
  856. if not tool_file_id:
  857. continue
  858. sign_url = sign_tool_file(tool_file_id=tool_file_id, extension=extension)
  859. elif "file-preview" in url:
  860. # get upload file id
  861. upload_file_id_pattern = r"\/files\/([\w-]+)\/file-preview?\?timestamp="
  862. result = re.search(upload_file_id_pattern, url)
  863. if not result:
  864. continue
  865. upload_file_id = result.group(1)
  866. if not upload_file_id:
  867. continue
  868. sign_url = file_helpers.get_signed_file_url(upload_file_id)
  869. elif "image-preview" in url:
  870. # image-preview is deprecated, use file-preview instead
  871. upload_file_id_pattern = r"\/files\/([\w-]+)\/image-preview?\?timestamp="
  872. result = re.search(upload_file_id_pattern, url)
  873. if not result:
  874. continue
  875. upload_file_id = result.group(1)
  876. if not upload_file_id:
  877. continue
  878. sign_url = file_helpers.get_signed_file_url(upload_file_id)
  879. else:
  880. continue
  881. # if as_attachment is in the url, add it to the sign_url.
  882. if "as_attachment" in url:
  883. sign_url += "&as_attachment=true"
  884. re_sign_file_url_answer = re_sign_file_url_answer.replace(url, sign_url)
  885. return re_sign_file_url_answer
  886. @property
  887. def user_feedback(self):
  888. feedback = (
  889. db.session.query(MessageFeedback)
  890. .filter(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "user")
  891. .first()
  892. )
  893. return feedback
  894. @property
  895. def admin_feedback(self):
  896. feedback = (
  897. db.session.query(MessageFeedback)
  898. .filter(MessageFeedback.message_id == self.id, MessageFeedback.from_source == "admin")
  899. .first()
  900. )
  901. return feedback
  902. @property
  903. def feedbacks(self):
  904. feedbacks = db.session.query(MessageFeedback).filter(MessageFeedback.message_id == self.id).all()
  905. return feedbacks
  906. @property
  907. def annotation(self):
  908. annotation = db.session.query(MessageAnnotation).filter(MessageAnnotation.message_id == self.id).first()
  909. return annotation
  910. @property
  911. def annotation_hit_history(self):
  912. annotation_history = (
  913. db.session.query(AppAnnotationHitHistory).filter(AppAnnotationHitHistory.message_id == self.id).first()
  914. )
  915. if annotation_history:
  916. annotation = (
  917. db.session.query(MessageAnnotation)
  918. .filter(MessageAnnotation.id == annotation_history.annotation_id)
  919. .first()
  920. )
  921. return annotation
  922. return None
  923. @property
  924. def app_model_config(self):
  925. conversation = db.session.query(Conversation).filter(Conversation.id == self.conversation_id).first()
  926. if conversation:
  927. return (
  928. db.session.query(AppModelConfig).filter(AppModelConfig.id == conversation.app_model_config_id).first()
  929. )
  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) -> dict:
  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. .filter(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).filter(MessageFile.message_id == self.id).all()
  952. current_app = db.session.query(App).filter(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).filter(WorkflowRun.id == self.workflow_run_id).first()
  1012. return None
  1013. def to_dict(self) -> dict:
  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. db.PrimaryKeyConstraint("id", name="message_feedback_pkey"),
  1062. db.Index("message_feedback_app_idx", "app_id"),
  1063. db.Index("message_feedback_message_idx", "message_id", "from_source"),
  1064. db.Index("message_feedback_conversation_idx", "conversation_id", "from_source", "rating"),
  1065. )
  1066. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1067. app_id = db.Column(StringUUID, nullable=False)
  1068. conversation_id = db.Column(StringUUID, nullable=False)
  1069. message_id = db.Column(StringUUID, nullable=False)
  1070. rating = db.Column(db.String(255), nullable=False)
  1071. content = db.Column(db.Text)
  1072. from_source = db.Column(db.String(255), nullable=False)
  1073. from_end_user_id = db.Column(StringUUID)
  1074. from_account_id = db.Column(StringUUID)
  1075. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1076. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1077. @property
  1078. def from_account(self):
  1079. account = db.session.query(Account).filter(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. db.PrimaryKeyConstraint("id", name="message_file_pkey"),
  1099. db.Index("message_file_message_idx", "message_id"),
  1100. db.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] = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1123. message_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  1124. type: Mapped[str] = db.Column(db.String(255), nullable=False)
  1125. transfer_method: Mapped[str] = db.Column(db.String(255), nullable=False)
  1126. url: Mapped[Optional[str]] = db.Column(db.Text, nullable=True)
  1127. belongs_to: Mapped[Optional[str]] = db.Column(db.String(255), nullable=True)
  1128. upload_file_id: Mapped[Optional[str]] = db.Column(StringUUID, nullable=True)
  1129. created_by_role: Mapped[str] = db.Column(db.String(255), nullable=False)
  1130. created_by: Mapped[str] = db.Column(StringUUID, nullable=False)
  1131. created_at: Mapped[datetime] = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1132. class MessageAnnotation(Base):
  1133. __tablename__ = "message_annotations"
  1134. __table_args__ = (
  1135. db.PrimaryKeyConstraint("id", name="message_annotation_pkey"),
  1136. db.Index("message_annotation_app_idx", "app_id"),
  1137. db.Index("message_annotation_conversation_idx", "conversation_id"),
  1138. db.Index("message_annotation_message_idx", "message_id"),
  1139. )
  1140. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1141. app_id = db.Column(StringUUID, nullable=False)
  1142. conversation_id = db.Column(StringUUID, db.ForeignKey("conversations.id"), nullable=True)
  1143. message_id = db.Column(StringUUID, nullable=True)
  1144. question = db.Column(db.Text, nullable=True)
  1145. content = db.Column(db.Text, nullable=False)
  1146. hit_count = db.Column(db.Integer, nullable=False, server_default=db.text("0"))
  1147. account_id = db.Column(StringUUID, nullable=False)
  1148. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1149. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1150. @property
  1151. def account(self):
  1152. account = db.session.query(Account).filter(Account.id == self.account_id).first()
  1153. return account
  1154. @property
  1155. def annotation_create_account(self):
  1156. account = db.session.query(Account).filter(Account.id == self.account_id).first()
  1157. return account
  1158. class AppAnnotationHitHistory(Base):
  1159. __tablename__ = "app_annotation_hit_histories"
  1160. __table_args__ = (
  1161. db.PrimaryKeyConstraint("id", name="app_annotation_hit_histories_pkey"),
  1162. db.Index("app_annotation_hit_histories_app_idx", "app_id"),
  1163. db.Index("app_annotation_hit_histories_account_idx", "account_id"),
  1164. db.Index("app_annotation_hit_histories_annotation_idx", "annotation_id"),
  1165. db.Index("app_annotation_hit_histories_message_idx", "message_id"),
  1166. )
  1167. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1168. app_id = db.Column(StringUUID, nullable=False)
  1169. annotation_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  1170. source = db.Column(db.Text, nullable=False)
  1171. question = db.Column(db.Text, nullable=False)
  1172. account_id = db.Column(StringUUID, nullable=False)
  1173. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1174. score = db.Column(Float, nullable=False, server_default=db.text("0"))
  1175. message_id = db.Column(StringUUID, nullable=False)
  1176. annotation_question = db.Column(db.Text, nullable=False)
  1177. annotation_content = db.Column(db.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. .filter(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).filter(Account.id == self.account_id).first()
  1190. return account
  1191. class AppAnnotationSetting(Base):
  1192. __tablename__ = "app_annotation_settings"
  1193. __table_args__ = (
  1194. db.PrimaryKeyConstraint("id", name="app_annotation_settings_pkey"),
  1195. db.Index("app_annotation_settings_app_idx", "app_id"),
  1196. )
  1197. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1198. app_id = db.Column(StringUUID, nullable=False)
  1199. score_threshold = db.Column(Float, nullable=False, server_default=db.text("0"))
  1200. collection_binding_id = db.Column(StringUUID, nullable=False)
  1201. created_user_id = db.Column(StringUUID, nullable=False)
  1202. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1203. updated_user_id = db.Column(StringUUID, nullable=False)
  1204. updated_at = db.Column(db.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. .filter(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. db.PrimaryKeyConstraint("id", name="operation_log_pkey"),
  1218. db.Index("operation_log_account_action_idx", "tenant_id", "account_id", "action"),
  1219. )
  1220. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1221. tenant_id = db.Column(StringUUID, nullable=False)
  1222. account_id = db.Column(StringUUID, nullable=False)
  1223. action = db.Column(db.String(255), nullable=False)
  1224. content = db.Column(db.JSON)
  1225. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1226. created_ip = db.Column(db.String(255), nullable=False)
  1227. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1228. class EndUser(Base, UserMixin):
  1229. __tablename__ = "end_users"
  1230. __table_args__ = (
  1231. db.PrimaryKeyConstraint("id", name="end_user_pkey"),
  1232. db.Index("end_user_session_id_idx", "session_id", "type"),
  1233. db.Index("end_user_tenant_session_id_idx", "tenant_id", "session_id", "type"),
  1234. )
  1235. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1236. tenant_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  1237. app_id = db.Column(StringUUID, nullable=True)
  1238. type = db.Column(db.String(255), nullable=False)
  1239. external_user_id = db.Column(db.String(255), nullable=True)
  1240. name = db.Column(db.String(255))
  1241. is_anonymous = db.Column(db.Boolean, nullable=False, server_default=db.text("true"))
  1242. session_id: Mapped[str] = mapped_column()
  1243. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1244. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1245. class Site(Base):
  1246. __tablename__ = "sites"
  1247. __table_args__ = (
  1248. db.PrimaryKeyConstraint("id", name="site_pkey"),
  1249. db.Index("site_app_id_idx", "app_id"),
  1250. db.Index("site_code_idx", "code", "status"),
  1251. )
  1252. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1253. app_id = db.Column(StringUUID, nullable=False)
  1254. title = db.Column(db.String(255), nullable=False)
  1255. icon_type = db.Column(db.String(255), nullable=True)
  1256. icon = db.Column(db.String(255))
  1257. icon_background = db.Column(db.String(255))
  1258. description = db.Column(db.Text)
  1259. default_language = db.Column(db.String(255), nullable=False)
  1260. chat_color_theme = db.Column(db.String(255))
  1261. chat_color_theme_inverted = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  1262. copyright = db.Column(db.String(255))
  1263. privacy_policy = db.Column(db.String(255))
  1264. show_workflow_steps = db.Column(db.Boolean, nullable=False, server_default=db.text("true"))
  1265. use_icon_as_answer_icon = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  1266. _custom_disclaimer: Mapped[str] = mapped_column("custom_disclaimer", sa.TEXT, default="")
  1267. customize_domain = db.Column(db.String(255))
  1268. customize_token_strategy = db.Column(db.String(255), nullable=False)
  1269. prompt_public = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  1270. status = db.Column(db.String(255), nullable=False, server_default=db.text("'normal'::character varying"))
  1271. created_by = db.Column(StringUUID, nullable=True)
  1272. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1273. updated_by = db.Column(StringUUID, nullable=True)
  1274. updated_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1275. code = db.Column(db.String(255))
  1276. @property
  1277. def custom_disclaimer(self):
  1278. return self._custom_disclaimer
  1279. @custom_disclaimer.setter
  1280. def custom_disclaimer(self, value: str):
  1281. if len(value) > 512:
  1282. raise ValueError("Custom disclaimer cannot exceed 512 characters.")
  1283. self._custom_disclaimer = value
  1284. @staticmethod
  1285. def generate_code(n):
  1286. while True:
  1287. result = generate_string(n)
  1288. while db.session.query(Site).filter(Site.code == result).count() > 0:
  1289. result = generate_string(n)
  1290. return result
  1291. @property
  1292. def app_base_url(self):
  1293. return dify_config.APP_WEB_URL or request.url_root.rstrip("/")
  1294. class ApiToken(Base):
  1295. __tablename__ = "api_tokens"
  1296. __table_args__ = (
  1297. db.PrimaryKeyConstraint("id", name="api_token_pkey"),
  1298. db.Index("api_token_app_id_type_idx", "app_id", "type"),
  1299. db.Index("api_token_token_idx", "token", "type"),
  1300. db.Index("api_token_tenant_idx", "tenant_id", "type"),
  1301. )
  1302. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1303. app_id = db.Column(StringUUID, nullable=True)
  1304. tenant_id = db.Column(StringUUID, nullable=True)
  1305. type = db.Column(db.String(16), nullable=False)
  1306. token = db.Column(db.String(255), nullable=False)
  1307. last_used_at = db.Column(db.DateTime, nullable=True)
  1308. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1309. @staticmethod
  1310. def generate_api_key(prefix, n):
  1311. while True:
  1312. result = prefix + generate_string(n)
  1313. if db.session.query(ApiToken).filter(ApiToken.token == result).count() > 0:
  1314. continue
  1315. return result
  1316. class UploadFile(Base):
  1317. __tablename__ = "upload_files"
  1318. __table_args__ = (
  1319. db.PrimaryKeyConstraint("id", name="upload_file_pkey"),
  1320. db.Index("upload_file_tenant_idx", "tenant_id"),
  1321. )
  1322. id: Mapped[str] = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1323. tenant_id: Mapped[str] = db.Column(StringUUID, nullable=False)
  1324. storage_type: Mapped[str] = db.Column(db.String(255), nullable=False)
  1325. key: Mapped[str] = db.Column(db.String(255), nullable=False)
  1326. name: Mapped[str] = db.Column(db.String(255), nullable=False)
  1327. size: Mapped[int] = db.Column(db.Integer, nullable=False)
  1328. extension: Mapped[str] = db.Column(db.String(255), nullable=False)
  1329. mime_type: Mapped[str] = db.Column(db.String(255), nullable=True)
  1330. created_by_role: Mapped[str] = db.Column(
  1331. db.String(255), nullable=False, server_default=db.text("'account'::character varying")
  1332. )
  1333. created_by: Mapped[str] = db.Column(StringUUID, nullable=False)
  1334. created_at: Mapped[datetime] = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1335. used: Mapped[bool] = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
  1336. used_by: Mapped[str | None] = db.Column(StringUUID, nullable=True)
  1337. used_at: Mapped[datetime | None] = db.Column(db.DateTime, nullable=True)
  1338. hash: Mapped[str | None] = db.Column(db.String(255), nullable=True)
  1339. source_url: Mapped[str] = mapped_column(sa.TEXT, default="")
  1340. def __init__(
  1341. self,
  1342. *,
  1343. tenant_id: str,
  1344. storage_type: str,
  1345. key: str,
  1346. name: str,
  1347. size: int,
  1348. extension: str,
  1349. mime_type: str,
  1350. created_by_role: CreatorUserRole,
  1351. created_by: str,
  1352. created_at: datetime,
  1353. used: bool,
  1354. used_by: str | None = None,
  1355. used_at: datetime | None = None,
  1356. hash: str | None = None,
  1357. source_url: str = "",
  1358. ):
  1359. self.tenant_id = tenant_id
  1360. self.storage_type = storage_type
  1361. self.key = key
  1362. self.name = name
  1363. self.size = size
  1364. self.extension = extension
  1365. self.mime_type = mime_type
  1366. self.created_by_role = created_by_role.value
  1367. self.created_by = created_by
  1368. self.created_at = created_at
  1369. self.used = used
  1370. self.used_by = used_by
  1371. self.used_at = used_at
  1372. self.hash = hash
  1373. self.source_url = source_url
  1374. class ApiRequest(Base):
  1375. __tablename__ = "api_requests"
  1376. __table_args__ = (
  1377. db.PrimaryKeyConstraint("id", name="api_request_pkey"),
  1378. db.Index("api_request_token_idx", "tenant_id", "api_token_id"),
  1379. )
  1380. id = db.Column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  1381. tenant_id = db.Column(StringUUID, nullable=False)
  1382. api_token_id = db.Column(StringUUID, nullable=False)
  1383. path = db.Column(db.String(255), nullable=False)
  1384. request = db.Column(db.Text, nullable=True)
  1385. response = db.Column(db.Text, nullable=True)
  1386. ip = db.Column(db.String(255), nullable=False)
  1387. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1388. class MessageChain(Base):
  1389. __tablename__ = "message_chains"
  1390. __table_args__ = (
  1391. db.PrimaryKeyConstraint("id", name="message_chain_pkey"),
  1392. db.Index("message_chain_message_id_idx", "message_id"),
  1393. )
  1394. id = db.Column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  1395. message_id = db.Column(StringUUID, nullable=False)
  1396. type = db.Column(db.String(255), nullable=False)
  1397. input = db.Column(db.Text, nullable=True)
  1398. output = db.Column(db.Text, nullable=True)
  1399. created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1400. class MessageAgentThought(Base):
  1401. __tablename__ = "message_agent_thoughts"
  1402. __table_args__ = (
  1403. db.PrimaryKeyConstraint("id", name="message_agent_thought_pkey"),
  1404. db.Index("message_agent_thought_message_id_idx", "message_id"),
  1405. db.Index("message_agent_thought_message_chain_id_idx", "message_chain_id"),
  1406. )
  1407. id = db.Column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  1408. message_id = db.Column(StringUUID, nullable=False)
  1409. message_chain_id = db.Column(StringUUID, nullable=True)
  1410. position = db.Column(db.Integer, nullable=False)
  1411. thought = db.Column(db.Text, nullable=True)
  1412. tool = db.Column(db.Text, nullable=True)
  1413. tool_labels_str = db.Column(db.Text, nullable=False, server_default=db.text("'{}'::text"))
  1414. tool_meta_str = db.Column(db.Text, nullable=False, server_default=db.text("'{}'::text"))
  1415. tool_input = db.Column(db.Text, nullable=True)
  1416. observation = db.Column(db.Text, nullable=True)
  1417. # plugin_id = db.Column(StringUUID, nullable=True) ## for future design
  1418. tool_process_data = db.Column(db.Text, nullable=True)
  1419. message = db.Column(db.Text, nullable=True)
  1420. message_token = db.Column(db.Integer, nullable=True)
  1421. message_unit_price = db.Column(db.Numeric, nullable=True)
  1422. message_price_unit = db.Column(db.Numeric(10, 7), nullable=False, server_default=db.text("0.001"))
  1423. message_files = db.Column(db.Text, nullable=True)
  1424. answer = db.Column(db.Text, nullable=True)
  1425. answer_token = db.Column(db.Integer, nullable=True)
  1426. answer_unit_price = db.Column(db.Numeric, nullable=True)
  1427. answer_price_unit = db.Column(db.Numeric(10, 7), nullable=False, server_default=db.text("0.001"))
  1428. tokens = db.Column(db.Integer, nullable=True)
  1429. total_price = db.Column(db.Numeric, nullable=True)
  1430. currency = db.Column(db.String, nullable=True)
  1431. latency = db.Column(db.Float, nullable=True)
  1432. created_by_role = db.Column(db.String, nullable=False)
  1433. created_by = db.Column(StringUUID, nullable=False)
  1434. created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1435. @property
  1436. def files(self) -> list:
  1437. if self.message_files:
  1438. return cast(list[Any], json.loads(self.message_files))
  1439. else:
  1440. return []
  1441. @property
  1442. def tools(self) -> list[str]:
  1443. return self.tool.split(";") if self.tool else []
  1444. @property
  1445. def tool_labels(self) -> dict:
  1446. try:
  1447. if self.tool_labels_str:
  1448. return cast(dict, json.loads(self.tool_labels_str))
  1449. else:
  1450. return {}
  1451. except Exception:
  1452. return {}
  1453. @property
  1454. def tool_meta(self) -> dict:
  1455. try:
  1456. if self.tool_meta_str:
  1457. return cast(dict, json.loads(self.tool_meta_str))
  1458. else:
  1459. return {}
  1460. except Exception:
  1461. return {}
  1462. @property
  1463. def tool_inputs_dict(self) -> dict:
  1464. tools = self.tools
  1465. try:
  1466. if self.tool_input:
  1467. data = json.loads(self.tool_input)
  1468. result = {}
  1469. for tool in tools:
  1470. if tool in data:
  1471. result[tool] = data[tool]
  1472. else:
  1473. if len(tools) == 1:
  1474. result[tool] = data
  1475. else:
  1476. result[tool] = {}
  1477. return result
  1478. else:
  1479. return {tool: {} for tool in tools}
  1480. except Exception:
  1481. return {}
  1482. @property
  1483. def tool_outputs_dict(self):
  1484. tools = self.tools
  1485. try:
  1486. if self.observation:
  1487. data = json.loads(self.observation)
  1488. result = {}
  1489. for tool in tools:
  1490. if tool in data:
  1491. result[tool] = data[tool]
  1492. else:
  1493. if len(tools) == 1:
  1494. result[tool] = data
  1495. else:
  1496. result[tool] = {}
  1497. return result
  1498. else:
  1499. return {tool: {} for tool in tools}
  1500. except Exception:
  1501. if self.observation:
  1502. return dict.fromkeys(tools, self.observation)
  1503. else:
  1504. return {}
  1505. class DatasetRetrieverResource(Base):
  1506. __tablename__ = "dataset_retriever_resources"
  1507. __table_args__ = (
  1508. db.PrimaryKeyConstraint("id", name="dataset_retriever_resource_pkey"),
  1509. db.Index("dataset_retriever_resource_message_id_idx", "message_id"),
  1510. )
  1511. id = db.Column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  1512. message_id = db.Column(StringUUID, nullable=False)
  1513. position = db.Column(db.Integer, nullable=False)
  1514. dataset_id = db.Column(StringUUID, nullable=False)
  1515. dataset_name = db.Column(db.Text, nullable=False)
  1516. document_id = db.Column(StringUUID, nullable=True)
  1517. document_name = db.Column(db.Text, nullable=False)
  1518. data_source_type = db.Column(db.Text, nullable=True)
  1519. segment_id = db.Column(StringUUID, nullable=True)
  1520. score = db.Column(db.Float, nullable=True)
  1521. content = db.Column(db.Text, nullable=False)
  1522. hit_count = db.Column(db.Integer, nullable=True)
  1523. word_count = db.Column(db.Integer, nullable=True)
  1524. segment_position = db.Column(db.Integer, nullable=True)
  1525. index_node_hash = db.Column(db.Text, nullable=True)
  1526. retriever_from = db.Column(db.Text, nullable=False)
  1527. created_by = db.Column(StringUUID, nullable=False)
  1528. created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
  1529. class Tag(Base):
  1530. __tablename__ = "tags"
  1531. __table_args__ = (
  1532. db.PrimaryKeyConstraint("id", name="tag_pkey"),
  1533. db.Index("tag_type_idx", "type"),
  1534. db.Index("tag_name_idx", "name"),
  1535. )
  1536. TAG_TYPE_LIST = ["knowledge", "app"]
  1537. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1538. tenant_id = db.Column(StringUUID, nullable=True)
  1539. type = db.Column(db.String(16), nullable=False)
  1540. name = db.Column(db.String(255), nullable=False)
  1541. created_by = db.Column(StringUUID, nullable=False)
  1542. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1543. class TagBinding(Base):
  1544. __tablename__ = "tag_bindings"
  1545. __table_args__ = (
  1546. db.PrimaryKeyConstraint("id", name="tag_binding_pkey"),
  1547. db.Index("tag_bind_target_id_idx", "target_id"),
  1548. db.Index("tag_bind_tag_id_idx", "tag_id"),
  1549. )
  1550. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1551. tenant_id = db.Column(StringUUID, nullable=True)
  1552. tag_id = db.Column(StringUUID, nullable=True)
  1553. target_id = db.Column(StringUUID, nullable=True)
  1554. created_by = db.Column(StringUUID, nullable=False)
  1555. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1556. class TraceAppConfig(Base):
  1557. __tablename__ = "trace_app_config"
  1558. __table_args__ = (
  1559. db.PrimaryKeyConstraint("id", name="tracing_app_config_pkey"),
  1560. db.Index("trace_app_config_app_id_idx", "app_id"),
  1561. )
  1562. id = db.Column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1563. app_id = db.Column(StringUUID, nullable=False)
  1564. tracing_provider = db.Column(db.String(255), nullable=True)
  1565. tracing_config = db.Column(db.JSON, nullable=True)
  1566. created_at = db.Column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1567. updated_at = db.Column(
  1568. db.DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  1569. )
  1570. is_active = db.Column(db.Boolean, nullable=False, server_default=db.text("true"))
  1571. @property
  1572. def tracing_config_dict(self):
  1573. return self.tracing_config or {}
  1574. @property
  1575. def tracing_config_str(self):
  1576. return json.dumps(self.tracing_config_dict)
  1577. def to_dict(self):
  1578. return {
  1579. "id": self.id,
  1580. "app_id": self.app_id,
  1581. "tracing_provider": self.tracing_provider,
  1582. "tracing_config": self.tracing_config_dict,
  1583. "is_active": self.is_active,
  1584. "created_at": str(self.created_at) if self.created_at else None,
  1585. "updated_at": str(self.updated_at) if self.updated_at else None,
  1586. }