app_service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import json
  2. import logging
  3. from datetime import datetime, timezone
  4. from typing import cast
  5. import yaml
  6. from flask import current_app
  7. from flask_login import current_user
  8. from flask_sqlalchemy.pagination import Pagination
  9. from constants.model_template import default_app_templates
  10. from core.agent.entities import AgentToolEntity
  11. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  12. from core.model_manager import ModelManager
  13. from core.model_runtime.entities.model_entities import ModelPropertyKey, ModelType
  14. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  15. from core.tools.tool_manager import ToolManager
  16. from core.tools.utils.configuration import ToolParameterConfigurationManager
  17. from events.app_event import app_model_config_was_updated, app_was_created, app_was_deleted
  18. from extensions.ext_database import db
  19. from models.account import Account
  20. from models.model import App, AppMode, AppModelConfig
  21. from models.tools import ApiToolProvider
  22. from services.tag_service import TagService
  23. from services.workflow_service import WorkflowService
  24. class AppService:
  25. def get_paginate_apps(self, tenant_id: str, args: dict) -> Pagination | None:
  26. """
  27. Get app list with pagination
  28. :param tenant_id: tenant id
  29. :param args: request args
  30. :return:
  31. """
  32. filters = [
  33. App.tenant_id == tenant_id,
  34. App.is_universal == False
  35. ]
  36. if args['mode'] == 'workflow':
  37. filters.append(App.mode.in_([AppMode.WORKFLOW.value, AppMode.COMPLETION.value]))
  38. elif args['mode'] == 'chat':
  39. filters.append(App.mode.in_([AppMode.CHAT.value, AppMode.ADVANCED_CHAT.value]))
  40. elif args['mode'] == 'agent-chat':
  41. filters.append(App.mode == AppMode.AGENT_CHAT.value)
  42. elif args['mode'] == 'channel':
  43. filters.append(App.mode == AppMode.CHANNEL.value)
  44. if 'name' in args and args['name']:
  45. name = args['name'][:30]
  46. filters.append(App.name.ilike(f'%{name}%'))
  47. if 'tag_ids' in args and args['tag_ids']:
  48. target_ids = TagService.get_target_ids_by_tag_ids('app',
  49. tenant_id,
  50. args['tag_ids'])
  51. if target_ids:
  52. filters.append(App.id.in_(target_ids))
  53. else:
  54. return None
  55. app_models = db.paginate(
  56. db.select(App).where(*filters).order_by(App.created_at.desc()),
  57. page=args['page'],
  58. per_page=args['limit'],
  59. error_out=False
  60. )
  61. return app_models
  62. def create_app(self, tenant_id: str, args: dict, account: Account) -> App:
  63. """
  64. Create app
  65. :param tenant_id: tenant id
  66. :param args: request args
  67. :param account: Account instance
  68. """
  69. app_mode = AppMode.value_of(args['mode'])
  70. app_template = default_app_templates[app_mode]
  71. # get model config
  72. default_model_config = app_template.get('model_config')
  73. default_model_config = default_model_config.copy() if default_model_config else None
  74. if default_model_config and 'model' in default_model_config:
  75. # get model provider
  76. model_manager = ModelManager()
  77. # get default model instance
  78. try:
  79. model_instance = model_manager.get_default_model_instance(
  80. tenant_id=account.current_tenant_id,
  81. model_type=ModelType.LLM
  82. )
  83. except (ProviderTokenNotInitError, LLMBadRequestError):
  84. model_instance = None
  85. except Exception as e:
  86. logging.exception(e)
  87. model_instance = None
  88. if model_instance:
  89. if model_instance.model == default_model_config['model']['name']:
  90. default_model_dict = default_model_config['model']
  91. else:
  92. llm_model = cast(LargeLanguageModel, model_instance.model_type_instance)
  93. model_schema = llm_model.get_model_schema(model_instance.model, model_instance.credentials)
  94. default_model_dict = {
  95. 'provider': model_instance.provider,
  96. 'name': model_instance.model,
  97. 'mode': model_schema.model_properties.get(ModelPropertyKey.MODE),
  98. 'completion_params': {}
  99. }
  100. else:
  101. default_model_dict = default_model_config['model']
  102. default_model_config['model'] = json.dumps(default_model_dict)
  103. app = App(**app_template['app'])
  104. app.name = args['name']
  105. app.description = args.get('description', '')
  106. app.mode = args['mode']
  107. app.icon = args['icon']
  108. app.icon_background = args['icon_background']
  109. app.tenant_id = tenant_id
  110. db.session.add(app)
  111. db.session.flush()
  112. if default_model_config:
  113. app_model_config = AppModelConfig(**default_model_config)
  114. app_model_config.app_id = app.id
  115. db.session.add(app_model_config)
  116. db.session.flush()
  117. app.app_model_config_id = app_model_config.id
  118. db.session.commit()
  119. app_was_created.send(app, account=account)
  120. return app
  121. def import_app(self, tenant_id: str, data: str, args: dict, account: Account) -> App:
  122. """
  123. Import app
  124. :param tenant_id: tenant id
  125. :param data: import data
  126. :param args: request args
  127. :param account: Account instance
  128. """
  129. try:
  130. import_data = yaml.safe_load(data)
  131. except yaml.YAMLError as e:
  132. raise ValueError("Invalid YAML format in data argument.")
  133. app_data = import_data.get('app')
  134. model_config_data = import_data.get('model_config')
  135. workflow = import_data.get('workflow')
  136. if not app_data:
  137. raise ValueError("Missing app in data argument")
  138. app_mode = AppMode.value_of(app_data.get('mode'))
  139. if app_mode in [AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]:
  140. if not workflow:
  141. raise ValueError("Missing workflow in data argument "
  142. "when app mode is advanced-chat or workflow")
  143. elif app_mode in [AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.COMPLETION]:
  144. if not model_config_data:
  145. raise ValueError("Missing model_config in data argument "
  146. "when app mode is chat, agent-chat or completion")
  147. else:
  148. raise ValueError("Invalid app mode")
  149. app = App(
  150. tenant_id=tenant_id,
  151. mode=app_data.get('mode'),
  152. name=args.get("name") if args.get("name") else app_data.get('name'),
  153. description=args.get("description") if args.get("description") else app_data.get('description', ''),
  154. icon=args.get("icon") if args.get("icon") else app_data.get('icon'),
  155. icon_background=args.get("icon_background") if args.get("icon_background") \
  156. else app_data.get('icon_background'),
  157. enable_site=True,
  158. enable_api=True
  159. )
  160. db.session.add(app)
  161. db.session.commit()
  162. app_was_created.send(app, account=account)
  163. if workflow:
  164. # init draft workflow
  165. workflow_service = WorkflowService()
  166. draft_workflow = workflow_service.sync_draft_workflow(
  167. app_model=app,
  168. graph=workflow.get('graph'),
  169. features=workflow.get('features'),
  170. account=account
  171. )
  172. workflow_service.publish_workflow(
  173. app_model=app,
  174. account=account,
  175. draft_workflow=draft_workflow
  176. )
  177. if model_config_data:
  178. app_model_config = AppModelConfig()
  179. app_model_config = app_model_config.from_model_config_dict(model_config_data)
  180. app_model_config.app_id = app.id
  181. db.session.add(app_model_config)
  182. db.session.commit()
  183. app.app_model_config_id = app_model_config.id
  184. app_model_config_was_updated.send(
  185. app,
  186. app_model_config=app_model_config
  187. )
  188. return app
  189. def export_app(self, app: App) -> str:
  190. """
  191. Export app
  192. :param app: App instance
  193. :return:
  194. """
  195. app_mode = AppMode.value_of(app.mode)
  196. export_data = {
  197. "app": {
  198. "name": app.name,
  199. "mode": app.mode,
  200. "icon": app.icon,
  201. "icon_background": app.icon_background,
  202. "description": app.description
  203. }
  204. }
  205. if app_mode in [AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]:
  206. workflow_service = WorkflowService()
  207. workflow = workflow_service.get_draft_workflow(app)
  208. export_data['workflow'] = {
  209. "graph": workflow.graph_dict,
  210. "features": workflow.features_dict
  211. }
  212. else:
  213. app_model_config = app.app_model_config
  214. export_data['model_config'] = app_model_config.to_dict()
  215. return yaml.dump(export_data)
  216. def get_app(self, app: App) -> App:
  217. """
  218. Get App
  219. """
  220. # get original app model config
  221. if app.mode == AppMode.AGENT_CHAT.value or app.is_agent:
  222. model_config: AppModelConfig = app.app_model_config
  223. agent_mode = model_config.agent_mode_dict
  224. # decrypt agent tool parameters if it's secret-input
  225. for tool in agent_mode.get('tools') or []:
  226. if not isinstance(tool, dict) or len(tool.keys()) <= 3:
  227. continue
  228. agent_tool_entity = AgentToolEntity(**tool)
  229. # get tool
  230. try:
  231. tool_runtime = ToolManager.get_agent_tool_runtime(
  232. tenant_id=current_user.current_tenant_id,
  233. app_id=app.id,
  234. agent_tool=agent_tool_entity,
  235. )
  236. manager = ToolParameterConfigurationManager(
  237. tenant_id=current_user.current_tenant_id,
  238. tool_runtime=tool_runtime,
  239. provider_name=agent_tool_entity.provider_id,
  240. provider_type=agent_tool_entity.provider_type,
  241. identity_id=f'AGENT.{app.id}'
  242. )
  243. # get decrypted parameters
  244. if agent_tool_entity.tool_parameters:
  245. parameters = manager.decrypt_tool_parameters(agent_tool_entity.tool_parameters or {})
  246. masked_parameter = manager.mask_tool_parameters(parameters or {})
  247. else:
  248. masked_parameter = {}
  249. # override tool parameters
  250. tool['tool_parameters'] = masked_parameter
  251. except Exception as e:
  252. pass
  253. # override agent mode
  254. model_config.agent_mode = json.dumps(agent_mode)
  255. class ModifiedApp(App):
  256. """
  257. Modified App class
  258. """
  259. def __init__(self, app):
  260. self.__dict__.update(app.__dict__)
  261. @property
  262. def app_model_config(self):
  263. return model_config
  264. app = ModifiedApp(app)
  265. return app
  266. def update_app(self, app: App, args: dict) -> App:
  267. """
  268. Update app
  269. :param app: App instance
  270. :param args: request args
  271. :return: App instance
  272. """
  273. app.name = args.get('name')
  274. app.description = args.get('description', '')
  275. app.icon = args.get('icon')
  276. app.icon_background = args.get('icon_background')
  277. app.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  278. db.session.commit()
  279. return app
  280. def update_app_name(self, app: App, name: str) -> App:
  281. """
  282. Update app name
  283. :param app: App instance
  284. :param name: new name
  285. :return: App instance
  286. """
  287. app.name = name
  288. app.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  289. db.session.commit()
  290. return app
  291. def update_app_icon(self, app: App, icon: str, icon_background: str) -> App:
  292. """
  293. Update app icon
  294. :param app: App instance
  295. :param icon: new icon
  296. :param icon_background: new icon_background
  297. :return: App instance
  298. """
  299. app.icon = icon
  300. app.icon_background = icon_background
  301. app.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  302. db.session.commit()
  303. return app
  304. def update_app_site_status(self, app: App, enable_site: bool) -> App:
  305. """
  306. Update app site status
  307. :param app: App instance
  308. :param enable_site: enable site status
  309. :return: App instance
  310. """
  311. if enable_site == app.enable_site:
  312. return app
  313. app.enable_site = enable_site
  314. app.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  315. db.session.commit()
  316. return app
  317. def update_app_api_status(self, app: App, enable_api: bool) -> App:
  318. """
  319. Update app api status
  320. :param app: App instance
  321. :param enable_api: enable api status
  322. :return: App instance
  323. """
  324. if enable_api == app.enable_api:
  325. return app
  326. app.enable_api = enable_api
  327. app.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  328. db.session.commit()
  329. return app
  330. def delete_app(self, app: App) -> None:
  331. """
  332. Delete app
  333. :param app: App instance
  334. """
  335. db.session.delete(app)
  336. db.session.commit()
  337. app_was_deleted.send(app)
  338. # todo async delete related data by event
  339. # app_model_configs, site, api_tokens, installed_apps, recommended_apps BY app
  340. # app_annotation_hit_histories, app_annotation_settings, app_dataset_joins BY app
  341. # workflows, workflow_runs, workflow_node_executions, workflow_app_logs BY app
  342. # conversations, pinned_conversations, messages BY app
  343. # message_feedbacks, message_annotations, message_chains BY message
  344. # message_agent_thoughts, message_files, saved_messages BY message
  345. def get_app_meta(self, app_model: App) -> dict:
  346. """
  347. Get app meta info
  348. :param app_model: app model
  349. :return:
  350. """
  351. app_mode = AppMode.value_of(app_model.mode)
  352. meta = {
  353. 'tool_icons': {}
  354. }
  355. if app_mode in [AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]:
  356. workflow = app_model.workflow
  357. if workflow is None:
  358. return meta
  359. graph = workflow.graph_dict
  360. nodes = graph.get('nodes', [])
  361. tools = []
  362. for node in nodes:
  363. if node.get('data', {}).get('type') == 'tool':
  364. node_data = node.get('data', {})
  365. tools.append({
  366. 'provider_type': node_data.get('provider_type'),
  367. 'provider_id': node_data.get('provider_id'),
  368. 'tool_name': node_data.get('tool_name'),
  369. 'tool_parameters': {}
  370. })
  371. else:
  372. app_model_config: AppModelConfig = app_model.app_model_config
  373. if not app_model_config:
  374. return meta
  375. agent_config = app_model_config.agent_mode_dict or {}
  376. # get all tools
  377. tools = agent_config.get('tools', [])
  378. url_prefix = (current_app.config.get("CONSOLE_API_URL")
  379. + "/console/api/workspaces/current/tool-provider/builtin/")
  380. for tool in tools:
  381. keys = list(tool.keys())
  382. if len(keys) >= 4:
  383. # current tool standard
  384. provider_type = tool.get('provider_type')
  385. provider_id = tool.get('provider_id')
  386. tool_name = tool.get('tool_name')
  387. if provider_type == 'builtin':
  388. meta['tool_icons'][tool_name] = url_prefix + provider_id + '/icon'
  389. elif provider_type == 'api':
  390. try:
  391. provider: ApiToolProvider = db.session.query(ApiToolProvider).filter(
  392. ApiToolProvider.id == provider_id
  393. )
  394. meta['tool_icons'][tool_name] = json.loads(provider.icon)
  395. except:
  396. meta['tool_icons'][tool_name] = {
  397. "background": "#252525",
  398. "content": "\ud83d\ude01"
  399. }
  400. return meta