選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

model.py 73KB

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