Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import json
  2. import logging
  3. from typing import TypedDict, cast
  4. from flask_sqlalchemy.pagination import Pagination
  5. from configs import dify_config
  6. from constants.model_template import default_app_templates
  7. from core.agent.entities import AgentToolEntity
  8. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  9. from core.model_manager import ModelManager
  10. from core.model_runtime.entities.model_entities import ModelPropertyKey, ModelType
  11. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  12. from core.tools.tool_manager import ToolManager
  13. from core.tools.utils.configuration import ToolParameterConfigurationManager
  14. from events.app_event import app_was_created
  15. from extensions.ext_database import db
  16. from libs.datetime_utils import naive_utc_now
  17. from libs.login import current_user
  18. from models.account import Account
  19. from models.model import App, AppMode, AppModelConfig, Site
  20. from models.tools import ApiToolProvider
  21. from services.billing_service import BillingService
  22. from services.enterprise.enterprise_service import EnterpriseService
  23. from services.feature_service import FeatureService
  24. from services.tag_service import TagService
  25. from tasks.remove_app_and_related_data_task import remove_app_and_related_data_task
  26. logger = logging.getLogger(__name__)
  27. class AppService:
  28. def get_paginate_apps(self, user_id: str, tenant_id: str, args: dict) -> Pagination | None:
  29. """
  30. Get app list with pagination
  31. :param user_id: user id
  32. :param tenant_id: tenant id
  33. :param args: request args
  34. :return:
  35. """
  36. filters = [App.tenant_id == tenant_id, App.is_universal == False]
  37. if args["mode"] == "workflow":
  38. filters.append(App.mode == AppMode.WORKFLOW)
  39. elif args["mode"] == "completion":
  40. filters.append(App.mode == AppMode.COMPLETION)
  41. elif args["mode"] == "chat":
  42. filters.append(App.mode == AppMode.CHAT)
  43. elif args["mode"] == "advanced-chat":
  44. filters.append(App.mode == AppMode.ADVANCED_CHAT)
  45. elif args["mode"] == "agent-chat":
  46. filters.append(App.mode == AppMode.AGENT_CHAT)
  47. if args.get("is_created_by_me", False):
  48. filters.append(App.created_by == user_id)
  49. if args.get("name"):
  50. name = args["name"][:30]
  51. filters.append(App.name.ilike(f"%{name}%"))
  52. # Check if tag_ids is not empty to avoid WHERE false condition
  53. if args.get("tag_ids") and len(args["tag_ids"]) > 0:
  54. target_ids = TagService.get_target_ids_by_tag_ids("app", tenant_id, args["tag_ids"])
  55. if target_ids and len(target_ids) > 0:
  56. filters.append(App.id.in_(target_ids))
  57. else:
  58. return None
  59. app_models = db.paginate(
  60. db.select(App).where(*filters).order_by(App.created_at.desc()),
  61. page=args["page"],
  62. per_page=args["limit"],
  63. error_out=False,
  64. )
  65. return app_models
  66. def create_app(self, tenant_id: str, args: dict, account: Account) -> App:
  67. """
  68. Create app
  69. :param tenant_id: tenant id
  70. :param args: request args
  71. :param account: Account instance
  72. """
  73. app_mode = AppMode.value_of(args["mode"])
  74. app_template = default_app_templates[app_mode]
  75. # get model config
  76. default_model_config = app_template.get("model_config")
  77. default_model_config = default_model_config.copy() if default_model_config else None
  78. if default_model_config and "model" in default_model_config:
  79. # get model provider
  80. model_manager = ModelManager()
  81. # get default model instance
  82. try:
  83. model_instance = model_manager.get_default_model_instance(
  84. tenant_id=account.current_tenant_id or "", model_type=ModelType.LLM
  85. )
  86. except (ProviderTokenNotInitError, LLMBadRequestError):
  87. model_instance = None
  88. except Exception:
  89. logger.exception("Get default model instance failed, tenant_id: %s", tenant_id)
  90. model_instance = None
  91. if model_instance:
  92. if (
  93. model_instance.model == default_model_config["model"]["name"]
  94. and model_instance.provider == default_model_config["model"]["provider"]
  95. ):
  96. default_model_dict = default_model_config["model"]
  97. else:
  98. llm_model = cast(LargeLanguageModel, model_instance.model_type_instance)
  99. model_schema = llm_model.get_model_schema(model_instance.model, model_instance.credentials)
  100. if model_schema is None:
  101. raise ValueError(f"model schema not found for model {model_instance.model}")
  102. default_model_dict = {
  103. "provider": model_instance.provider,
  104. "name": model_instance.model,
  105. "mode": model_schema.model_properties.get(ModelPropertyKey.MODE),
  106. "completion_params": {},
  107. }
  108. else:
  109. provider, model = model_manager.get_default_provider_model_name(
  110. tenant_id=account.current_tenant_id or "", model_type=ModelType.LLM
  111. )
  112. default_model_config["model"]["provider"] = provider
  113. default_model_config["model"]["name"] = model
  114. default_model_dict = default_model_config["model"]
  115. default_model_config["model"] = json.dumps(default_model_dict)
  116. app = App(**app_template["app"])
  117. app.name = args["name"]
  118. app.description = args.get("description", "")
  119. app.mode = args["mode"]
  120. app.icon_type = args.get("icon_type", "emoji")
  121. app.icon = args["icon"]
  122. app.icon_background = args["icon_background"]
  123. app.tenant_id = tenant_id
  124. app.api_rph = args.get("api_rph", 0)
  125. app.api_rpm = args.get("api_rpm", 0)
  126. app.created_by = account.id
  127. app.updated_by = account.id
  128. db.session.add(app)
  129. db.session.flush()
  130. if default_model_config:
  131. app_model_config = AppModelConfig(**default_model_config)
  132. app_model_config.app_id = app.id
  133. app_model_config.created_by = account.id
  134. app_model_config.updated_by = account.id
  135. db.session.add(app_model_config)
  136. db.session.flush()
  137. app.app_model_config_id = app_model_config.id
  138. db.session.commit()
  139. app_was_created.send(app, account=account)
  140. if FeatureService.get_system_features().webapp_auth.enabled:
  141. # update web app setting as private
  142. EnterpriseService.WebAppAuth.update_app_access_mode(app.id, "private")
  143. if dify_config.BILLING_ENABLED:
  144. BillingService.clean_billing_info_cache(app.tenant_id)
  145. return app
  146. def get_app(self, app: App) -> App:
  147. """
  148. Get App
  149. """
  150. assert isinstance(current_user, Account)
  151. assert current_user.current_tenant_id is not None
  152. # get original app model config
  153. if app.mode == AppMode.AGENT_CHAT or app.is_agent:
  154. model_config = app.app_model_config
  155. if not model_config:
  156. return app
  157. agent_mode = model_config.agent_mode_dict
  158. # decrypt agent tool parameters if it's secret-input
  159. for tool in agent_mode.get("tools") or []:
  160. if not isinstance(tool, dict) or len(tool.keys()) <= 3:
  161. continue
  162. agent_tool_entity = AgentToolEntity(**tool)
  163. # get tool
  164. try:
  165. tool_runtime = ToolManager.get_agent_tool_runtime(
  166. tenant_id=current_user.current_tenant_id,
  167. app_id=app.id,
  168. agent_tool=agent_tool_entity,
  169. )
  170. manager = ToolParameterConfigurationManager(
  171. tenant_id=current_user.current_tenant_id,
  172. tool_runtime=tool_runtime,
  173. provider_name=agent_tool_entity.provider_id,
  174. provider_type=agent_tool_entity.provider_type,
  175. identity_id=f"AGENT.{app.id}",
  176. )
  177. # get decrypted parameters
  178. if agent_tool_entity.tool_parameters:
  179. parameters = manager.decrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  180. masked_parameter = manager.mask_tool_parameters(parameters or {})
  181. else:
  182. masked_parameter = {}
  183. # override tool parameters
  184. tool["tool_parameters"] = masked_parameter
  185. except Exception:
  186. pass
  187. # override agent mode
  188. if model_config:
  189. model_config.agent_mode = json.dumps(agent_mode)
  190. class ModifiedApp(App):
  191. """
  192. Modified App class
  193. """
  194. def __init__(self, app):
  195. self.__dict__.update(app.__dict__)
  196. @property
  197. def app_model_config(self):
  198. return model_config
  199. app = ModifiedApp(app)
  200. return app
  201. class ArgsDict(TypedDict):
  202. name: str
  203. description: str
  204. icon_type: str
  205. icon: str
  206. icon_background: str
  207. use_icon_as_answer_icon: bool
  208. max_active_requests: int
  209. def update_app(self, app: App, args: ArgsDict) -> App:
  210. """
  211. Update app
  212. :param app: App instance
  213. :param args: request args
  214. :return: App instance
  215. """
  216. assert current_user is not None
  217. app.name = args["name"]
  218. app.description = args["description"]
  219. app.icon_type = args["icon_type"]
  220. app.icon = args["icon"]
  221. app.icon_background = args["icon_background"]
  222. app.use_icon_as_answer_icon = args.get("use_icon_as_answer_icon", False)
  223. app.max_active_requests = args.get("max_active_requests")
  224. app.updated_by = current_user.id
  225. app.updated_at = naive_utc_now()
  226. db.session.commit()
  227. return app
  228. def update_app_name(self, app: App, name: str) -> App:
  229. """
  230. Update app name
  231. :param app: App instance
  232. :param name: new name
  233. :return: App instance
  234. """
  235. assert current_user is not None
  236. app.name = name
  237. app.updated_by = current_user.id
  238. app.updated_at = naive_utc_now()
  239. db.session.commit()
  240. return app
  241. def update_app_icon(self, app: App, icon: str, icon_background: str) -> App:
  242. """
  243. Update app icon
  244. :param app: App instance
  245. :param icon: new icon
  246. :param icon_background: new icon_background
  247. :return: App instance
  248. """
  249. assert current_user is not None
  250. app.icon = icon
  251. app.icon_background = icon_background
  252. app.updated_by = current_user.id
  253. app.updated_at = naive_utc_now()
  254. db.session.commit()
  255. return app
  256. def update_app_site_status(self, app: App, enable_site: bool) -> App:
  257. """
  258. Update app site status
  259. :param app: App instance
  260. :param enable_site: enable site status
  261. :return: App instance
  262. """
  263. if enable_site == app.enable_site:
  264. return app
  265. assert current_user is not None
  266. app.enable_site = enable_site
  267. app.updated_by = current_user.id
  268. app.updated_at = naive_utc_now()
  269. db.session.commit()
  270. return app
  271. def update_app_api_status(self, app: App, enable_api: bool) -> App:
  272. """
  273. Update app api status
  274. :param app: App instance
  275. :param enable_api: enable api status
  276. :return: App instance
  277. """
  278. if enable_api == app.enable_api:
  279. return app
  280. assert current_user is not None
  281. app.enable_api = enable_api
  282. app.updated_by = current_user.id
  283. app.updated_at = naive_utc_now()
  284. db.session.commit()
  285. return app
  286. def delete_app(self, app: App):
  287. """
  288. Delete app
  289. :param app: App instance
  290. """
  291. db.session.delete(app)
  292. db.session.commit()
  293. # clean up web app settings
  294. if FeatureService.get_system_features().webapp_auth.enabled:
  295. EnterpriseService.WebAppAuth.cleanup_webapp(app.id)
  296. if dify_config.BILLING_ENABLED:
  297. BillingService.clean_billing_info_cache(app.tenant_id)
  298. # Trigger asynchronous deletion of app and related data
  299. remove_app_and_related_data_task.delay(tenant_id=app.tenant_id, app_id=app.id)
  300. def get_app_meta(self, app_model: App):
  301. """
  302. Get app meta info
  303. :param app_model: app model
  304. :return:
  305. """
  306. app_mode = AppMode.value_of(app_model.mode)
  307. meta: dict = {"tool_icons": {}}
  308. if app_mode in {AppMode.ADVANCED_CHAT, AppMode.WORKFLOW}:
  309. workflow = app_model.workflow
  310. if workflow is None:
  311. return meta
  312. graph = workflow.graph_dict
  313. nodes = graph.get("nodes", [])
  314. tools = []
  315. for node in nodes:
  316. if node.get("data", {}).get("type") == "tool":
  317. node_data = node.get("data", {})
  318. tools.append(
  319. {
  320. "provider_type": node_data.get("provider_type"),
  321. "provider_id": node_data.get("provider_id"),
  322. "tool_name": node_data.get("tool_name"),
  323. "tool_parameters": {},
  324. }
  325. )
  326. else:
  327. app_model_config: AppModelConfig | None = app_model.app_model_config
  328. if not app_model_config:
  329. return meta
  330. agent_config = app_model_config.agent_mode_dict
  331. # get all tools
  332. tools = agent_config.get("tools", [])
  333. url_prefix = dify_config.CONSOLE_API_URL + "/console/api/workspaces/current/tool-provider/builtin/"
  334. for tool in tools:
  335. keys = list(tool.keys())
  336. if len(keys) >= 4:
  337. # current tool standard
  338. provider_type = tool.get("provider_type", "")
  339. provider_id = tool.get("provider_id", "")
  340. tool_name = tool.get("tool_name", "")
  341. if provider_type == "builtin":
  342. meta["tool_icons"][tool_name] = url_prefix + provider_id + "/icon"
  343. elif provider_type == "api":
  344. try:
  345. provider: ApiToolProvider | None = (
  346. db.session.query(ApiToolProvider).where(ApiToolProvider.id == provider_id).first()
  347. )
  348. if provider is None:
  349. raise ValueError(f"provider not found for tool {tool_name}")
  350. meta["tool_icons"][tool_name] = json.loads(provider.icon)
  351. except:
  352. meta["tool_icons"][tool_name] = {"background": "#252525", "content": "\ud83d\ude01"}
  353. return meta
  354. @staticmethod
  355. def get_app_code_by_id(app_id: str) -> str:
  356. """
  357. Get app code by app id
  358. :param app_id: app id
  359. :return: app code
  360. """
  361. site = db.session.query(Site).where(Site.app_id == app_id).first()
  362. if not site:
  363. raise ValueError(f"App with id {app_id} not found")
  364. return str(site.code)
  365. @staticmethod
  366. def get_app_id_by_code(app_code: str) -> str:
  367. """
  368. Get app id by app code
  369. :param app_code: app code
  370. :return: app id
  371. """
  372. site = db.session.query(Site).where(Site.code == app_code).first()
  373. if not site:
  374. raise ValueError(f"App with code {app_code} not found")
  375. return str(site.app_id)