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

model.py 73KB

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