app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # -*- coding:utf-8 -*-
  2. import json
  3. import logging
  4. from datetime import datetime
  5. from flask_login import current_user
  6. from libs.login import login_required
  7. from flask_restful import Resource, reqparse, marshal_with, abort, inputs
  8. from werkzeug.exceptions import Forbidden
  9. from constants.model_template import model_templates, demo_model_templates
  10. from controllers.console import api
  11. from controllers.console.app.error import AppNotFoundError, ProviderNotInitializeError
  12. from controllers.console.setup import setup_required
  13. from controllers.console.wraps import account_initialization_required
  14. from core.model_providers.error import ProviderTokenNotInitError, LLMBadRequestError
  15. from core.model_providers.model_factory import ModelFactory
  16. from core.model_providers.model_provider_factory import ModelProviderFactory
  17. from events.app_event import app_was_created, app_was_deleted
  18. from fields.app_fields import app_pagination_fields, app_detail_fields, template_list_fields, \
  19. app_detail_fields_with_site
  20. from extensions.ext_database import db
  21. from models.model import App, AppModelConfig, Site
  22. from services.app_model_config_service import AppModelConfigService
  23. def _get_app(app_id, tenant_id):
  24. app = db.session.query(App).filter(App.id == app_id, App.tenant_id == tenant_id).first()
  25. if not app:
  26. raise AppNotFoundError
  27. return app
  28. class AppListApi(Resource):
  29. @setup_required
  30. @login_required
  31. @account_initialization_required
  32. @marshal_with(app_pagination_fields)
  33. def get(self):
  34. """Get app list"""
  35. parser = reqparse.RequestParser()
  36. parser.add_argument('page', type=inputs.int_range(1, 99999), required=False, default=1, location='args')
  37. parser.add_argument('limit', type=inputs.int_range(1, 100), required=False, default=20, location='args')
  38. args = parser.parse_args()
  39. app_models = db.paginate(
  40. db.select(App).where(App.tenant_id == current_user.current_tenant_id,
  41. App.is_universal == False).order_by(App.created_at.desc()),
  42. page=args['page'],
  43. per_page=args['limit'],
  44. error_out=False)
  45. return app_models
  46. @setup_required
  47. @login_required
  48. @account_initialization_required
  49. @marshal_with(app_detail_fields)
  50. def post(self):
  51. """Create app"""
  52. parser = reqparse.RequestParser()
  53. parser.add_argument('name', type=str, required=True, location='json')
  54. parser.add_argument('mode', type=str, choices=['completion', 'chat'], location='json')
  55. parser.add_argument('icon', type=str, location='json')
  56. parser.add_argument('icon_background', type=str, location='json')
  57. parser.add_argument('model_config', type=dict, location='json')
  58. args = parser.parse_args()
  59. # The role of the current user in the ta table must be admin or owner
  60. if current_user.current_tenant.current_role not in ['admin', 'owner']:
  61. raise Forbidden()
  62. try:
  63. default_model = ModelFactory.get_text_generation_model(
  64. tenant_id=current_user.current_tenant_id
  65. )
  66. except (ProviderTokenNotInitError, LLMBadRequestError):
  67. default_model = None
  68. except Exception as e:
  69. logging.exception(e)
  70. default_model = None
  71. if args['model_config'] is not None:
  72. # validate config
  73. model_config_dict = args['model_config']
  74. # get model provider
  75. model_provider = ModelProviderFactory.get_preferred_model_provider(
  76. current_user.current_tenant_id,
  77. model_config_dict["model"]["provider"]
  78. )
  79. if not model_provider:
  80. if not default_model:
  81. raise ProviderNotInitializeError(
  82. f"No Default System Reasoning Model available. Please configure "
  83. f"in the Settings -> Model Provider.")
  84. else:
  85. model_config_dict["model"]["provider"] = default_model.model_provider.provider_name
  86. model_config_dict["model"]["name"] = default_model.name
  87. model_configuration = AppModelConfigService.validate_configuration(
  88. tenant_id=current_user.current_tenant_id,
  89. account=current_user,
  90. config=model_config_dict,
  91. mode=args['mode']
  92. )
  93. app = App(
  94. enable_site=True,
  95. enable_api=True,
  96. is_demo=False,
  97. api_rpm=0,
  98. api_rph=0,
  99. status='normal'
  100. )
  101. app_model_config = AppModelConfig()
  102. app_model_config = app_model_config.from_model_config_dict(model_configuration)
  103. else:
  104. if 'mode' not in args or args['mode'] is None:
  105. abort(400, message="mode is required")
  106. model_config_template = model_templates[args['mode'] + '_default']
  107. app = App(**model_config_template['app'])
  108. app_model_config = AppModelConfig(**model_config_template['model_config'])
  109. # get model provider
  110. model_provider = ModelProviderFactory.get_preferred_model_provider(
  111. current_user.current_tenant_id,
  112. app_model_config.model_dict["provider"]
  113. )
  114. if not model_provider:
  115. if not default_model:
  116. raise ProviderNotInitializeError(
  117. f"No Default System Reasoning Model available. Please configure "
  118. f"in the Settings -> Model Provider.")
  119. else:
  120. model_dict = app_model_config.model_dict
  121. model_dict['provider'] = default_model.model_provider.provider_name
  122. model_dict['name'] = default_model.name
  123. app_model_config.model = json.dumps(model_dict)
  124. app.name = args['name']
  125. app.mode = args['mode']
  126. app.icon = args['icon']
  127. app.icon_background = args['icon_background']
  128. app.tenant_id = current_user.current_tenant_id
  129. db.session.add(app)
  130. db.session.flush()
  131. app_model_config.app_id = app.id
  132. db.session.add(app_model_config)
  133. db.session.flush()
  134. app.app_model_config_id = app_model_config.id
  135. account = current_user
  136. site = Site(
  137. app_id=app.id,
  138. title=app.name,
  139. default_language=account.interface_language,
  140. customize_token_strategy='not_allow',
  141. code=Site.generate_code(16)
  142. )
  143. db.session.add(site)
  144. db.session.commit()
  145. app_was_created.send(app)
  146. return app, 201
  147. class AppTemplateApi(Resource):
  148. @setup_required
  149. @login_required
  150. @account_initialization_required
  151. @marshal_with(template_list_fields)
  152. def get(self):
  153. """Get app demo templates"""
  154. account = current_user
  155. interface_language = account.interface_language
  156. templates = demo_model_templates.get(interface_language)
  157. if not templates:
  158. templates = demo_model_templates.get('en-US')
  159. return {'data': templates}
  160. class AppApi(Resource):
  161. @setup_required
  162. @login_required
  163. @account_initialization_required
  164. @marshal_with(app_detail_fields_with_site)
  165. def get(self, app_id):
  166. """Get app detail"""
  167. app_id = str(app_id)
  168. app = _get_app(app_id, current_user.current_tenant_id)
  169. return app
  170. @setup_required
  171. @login_required
  172. @account_initialization_required
  173. def delete(self, app_id):
  174. """Delete app"""
  175. app_id = str(app_id)
  176. if current_user.current_tenant.current_role not in ['admin', 'owner']:
  177. raise Forbidden()
  178. app = _get_app(app_id, current_user.current_tenant_id)
  179. db.session.delete(app)
  180. db.session.commit()
  181. # todo delete related data??
  182. # model_config, site, api_token, conversation, message, message_feedback, message_annotation
  183. app_was_deleted.send(app)
  184. return {'result': 'success'}, 204
  185. class AppNameApi(Resource):
  186. @setup_required
  187. @login_required
  188. @account_initialization_required
  189. @marshal_with(app_detail_fields)
  190. def post(self, app_id):
  191. app_id = str(app_id)
  192. app = _get_app(app_id, current_user.current_tenant_id)
  193. parser = reqparse.RequestParser()
  194. parser.add_argument('name', type=str, required=True, location='json')
  195. args = parser.parse_args()
  196. app.name = args.get('name')
  197. app.updated_at = datetime.utcnow()
  198. db.session.commit()
  199. return app
  200. class AppIconApi(Resource):
  201. @setup_required
  202. @login_required
  203. @account_initialization_required
  204. @marshal_with(app_detail_fields)
  205. def post(self, app_id):
  206. app_id = str(app_id)
  207. app = _get_app(app_id, current_user.current_tenant_id)
  208. parser = reqparse.RequestParser()
  209. parser.add_argument('icon', type=str, location='json')
  210. parser.add_argument('icon_background', type=str, location='json')
  211. args = parser.parse_args()
  212. app.icon = args.get('icon')
  213. app.icon_background = args.get('icon_background')
  214. app.updated_at = datetime.utcnow()
  215. db.session.commit()
  216. return app
  217. class AppSiteStatus(Resource):
  218. @setup_required
  219. @login_required
  220. @account_initialization_required
  221. @marshal_with(app_detail_fields)
  222. def post(self, app_id):
  223. parser = reqparse.RequestParser()
  224. parser.add_argument('enable_site', type=bool, required=True, location='json')
  225. args = parser.parse_args()
  226. app_id = str(app_id)
  227. app = db.session.query(App).filter(App.id == app_id, App.tenant_id == current_user.current_tenant_id).first()
  228. if not app:
  229. raise AppNotFoundError
  230. if args.get('enable_site') == app.enable_site:
  231. return app
  232. app.enable_site = args.get('enable_site')
  233. app.updated_at = datetime.utcnow()
  234. db.session.commit()
  235. return app
  236. class AppApiStatus(Resource):
  237. @setup_required
  238. @login_required
  239. @account_initialization_required
  240. @marshal_with(app_detail_fields)
  241. def post(self, app_id):
  242. parser = reqparse.RequestParser()
  243. parser.add_argument('enable_api', type=bool, required=True, location='json')
  244. args = parser.parse_args()
  245. app_id = str(app_id)
  246. app = _get_app(app_id, current_user.current_tenant_id)
  247. if args.get('enable_api') == app.enable_api:
  248. return app
  249. app.enable_api = args.get('enable_api')
  250. app.updated_at = datetime.utcnow()
  251. db.session.commit()
  252. return app
  253. class AppCopy(Resource):
  254. @staticmethod
  255. def create_app_copy(app):
  256. copy_app = App(
  257. name=app.name + ' copy',
  258. icon=app.icon,
  259. icon_background=app.icon_background,
  260. tenant_id=app.tenant_id,
  261. mode=app.mode,
  262. app_model_config_id=app.app_model_config_id,
  263. enable_site=app.enable_site,
  264. enable_api=app.enable_api,
  265. api_rpm=app.api_rpm,
  266. api_rph=app.api_rph
  267. )
  268. return copy_app
  269. @staticmethod
  270. def create_app_model_config_copy(app_config, copy_app_id):
  271. copy_app_model_config = app_config.copy()
  272. copy_app_model_config.app_id = copy_app_id
  273. return copy_app_model_config
  274. @setup_required
  275. @login_required
  276. @account_initialization_required
  277. @marshal_with(app_detail_fields)
  278. def post(self, app_id):
  279. app_id = str(app_id)
  280. app = _get_app(app_id, current_user.current_tenant_id)
  281. copy_app = self.create_app_copy(app)
  282. db.session.add(copy_app)
  283. app_config = db.session.query(AppModelConfig). \
  284. filter(AppModelConfig.app_id == app_id). \
  285. one_or_none()
  286. if app_config:
  287. copy_app_model_config = self.create_app_model_config_copy(app_config, copy_app.id)
  288. db.session.add(copy_app_model_config)
  289. db.session.commit()
  290. copy_app.app_model_config_id = copy_app_model_config.id
  291. db.session.commit()
  292. return copy_app, 201
  293. api.add_resource(AppListApi, '/apps')
  294. api.add_resource(AppTemplateApi, '/app-templates')
  295. api.add_resource(AppApi, '/apps/<uuid:app_id>')
  296. api.add_resource(AppCopy, '/apps/<uuid:app_id>/copy')
  297. api.add_resource(AppNameApi, '/apps/<uuid:app_id>/name')
  298. api.add_resource(AppIconApi, '/apps/<uuid:app_id>/icon')
  299. api.add_resource(AppSiteStatus, '/apps/<uuid:app_id>/site-enable')
  300. api.add_resource(AppApiStatus, '/apps/<uuid:app_id>/api-enable')