app.py 13 KB

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