You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import uuid
  2. from typing import cast
  3. from flask_login import current_user
  4. from flask_restx import Resource, inputs, marshal, marshal_with, reqparse
  5. from sqlalchemy import select
  6. from sqlalchemy.orm import Session
  7. from werkzeug.exceptions import BadRequest, Forbidden, abort
  8. from controllers.console import api
  9. from controllers.console.app.wraps import get_app_model
  10. from controllers.console.wraps import (
  11. account_initialization_required,
  12. cloud_edition_billing_resource_check,
  13. enterprise_license_required,
  14. setup_required,
  15. )
  16. from core.ops.ops_trace_manager import OpsTraceManager
  17. from extensions.ext_database import db
  18. from fields.app_fields import app_detail_fields, app_detail_fields_with_site, app_pagination_fields
  19. from libs.login import login_required
  20. from models import Account, App
  21. from services.app_dsl_service import AppDslService, ImportMode
  22. from services.app_service import AppService
  23. from services.enterprise.enterprise_service import EnterpriseService
  24. from services.feature_service import FeatureService
  25. ALLOW_CREATE_APP_MODES = ["chat", "agent-chat", "advanced-chat", "workflow", "completion"]
  26. def _validate_description_length(description):
  27. if description and len(description) > 400:
  28. raise ValueError("Description cannot exceed 400 characters.")
  29. return description
  30. class AppListApi(Resource):
  31. @setup_required
  32. @login_required
  33. @account_initialization_required
  34. @enterprise_license_required
  35. def get(self):
  36. """Get app list"""
  37. def uuid_list(value):
  38. try:
  39. return [str(uuid.UUID(v)) for v in value.split(",")]
  40. except ValueError:
  41. abort(400, message="Invalid UUID format in tag_ids.")
  42. parser = reqparse.RequestParser()
  43. parser.add_argument("page", type=inputs.int_range(1, 99999), required=False, default=1, location="args")
  44. parser.add_argument("limit", type=inputs.int_range(1, 100), required=False, default=20, location="args")
  45. parser.add_argument(
  46. "mode",
  47. type=str,
  48. choices=[
  49. "completion",
  50. "chat",
  51. "advanced-chat",
  52. "workflow",
  53. "agent-chat",
  54. "channel",
  55. "all",
  56. ],
  57. default="all",
  58. location="args",
  59. required=False,
  60. )
  61. parser.add_argument("name", type=str, location="args", required=False)
  62. parser.add_argument("tag_ids", type=uuid_list, location="args", required=False)
  63. parser.add_argument("is_created_by_me", type=inputs.boolean, location="args", required=False)
  64. args = parser.parse_args()
  65. # get app list
  66. app_service = AppService()
  67. app_pagination = app_service.get_paginate_apps(current_user.id, current_user.current_tenant_id, args)
  68. if not app_pagination:
  69. return {"data": [], "total": 0, "page": 1, "limit": 20, "has_more": False}
  70. if FeatureService.get_system_features().webapp_auth.enabled:
  71. app_ids = [str(app.id) for app in app_pagination.items]
  72. res = EnterpriseService.WebAppAuth.batch_get_app_access_mode_by_id(app_ids=app_ids)
  73. if len(res) != len(app_ids):
  74. raise BadRequest("Invalid app id in webapp auth")
  75. for app in app_pagination.items:
  76. if str(app.id) in res:
  77. app.access_mode = res[str(app.id)].access_mode
  78. return marshal(app_pagination, app_pagination_fields), 200
  79. @setup_required
  80. @login_required
  81. @account_initialization_required
  82. @marshal_with(app_detail_fields)
  83. @cloud_edition_billing_resource_check("apps")
  84. def post(self):
  85. """Create app"""
  86. parser = reqparse.RequestParser()
  87. parser.add_argument("name", type=str, required=True, location="json")
  88. parser.add_argument("description", type=_validate_description_length, location="json")
  89. parser.add_argument("mode", type=str, choices=ALLOW_CREATE_APP_MODES, location="json")
  90. parser.add_argument("icon_type", type=str, location="json")
  91. parser.add_argument("icon", type=str, location="json")
  92. parser.add_argument("icon_background", type=str, location="json")
  93. args = parser.parse_args()
  94. # The role of the current user in the ta table must be admin, owner, or editor
  95. if not current_user.is_editor:
  96. raise Forbidden()
  97. if "mode" not in args or args["mode"] is None:
  98. raise BadRequest("mode is required")
  99. app_service = AppService()
  100. app = app_service.create_app(current_user.current_tenant_id, args, current_user)
  101. return app, 201
  102. class AppApi(Resource):
  103. @setup_required
  104. @login_required
  105. @account_initialization_required
  106. @enterprise_license_required
  107. @get_app_model
  108. @marshal_with(app_detail_fields_with_site)
  109. def get(self, app_model):
  110. """Get app detail"""
  111. app_service = AppService()
  112. app_model = app_service.get_app(app_model)
  113. if FeatureService.get_system_features().webapp_auth.enabled:
  114. app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))
  115. app_model.access_mode = app_setting.access_mode
  116. return app_model
  117. @setup_required
  118. @login_required
  119. @account_initialization_required
  120. @get_app_model
  121. @marshal_with(app_detail_fields_with_site)
  122. def put(self, app_model):
  123. """Update app"""
  124. # The role of the current user in the ta table must be admin, owner, or editor
  125. if not current_user.is_editor:
  126. raise Forbidden()
  127. parser = reqparse.RequestParser()
  128. parser.add_argument("name", type=str, required=True, nullable=False, location="json")
  129. parser.add_argument("description", type=_validate_description_length, location="json")
  130. parser.add_argument("icon_type", type=str, location="json")
  131. parser.add_argument("icon", type=str, location="json")
  132. parser.add_argument("icon_background", type=str, location="json")
  133. parser.add_argument("use_icon_as_answer_icon", type=bool, location="json")
  134. parser.add_argument("max_active_requests", type=int, location="json")
  135. args = parser.parse_args()
  136. app_service = AppService()
  137. app_model = app_service.update_app(app_model, args)
  138. return app_model
  139. @setup_required
  140. @login_required
  141. @account_initialization_required
  142. @get_app_model
  143. def delete(self, app_model):
  144. """Delete app"""
  145. # The role of the current user in the ta table must be admin, owner, or editor
  146. if not current_user.is_editor:
  147. raise Forbidden()
  148. app_service = AppService()
  149. app_service.delete_app(app_model)
  150. return {"result": "success"}, 204
  151. class AppCopyApi(Resource):
  152. @setup_required
  153. @login_required
  154. @account_initialization_required
  155. @get_app_model
  156. @marshal_with(app_detail_fields_with_site)
  157. def post(self, app_model):
  158. """Copy app"""
  159. # The role of the current user in the ta table must be admin, owner, or editor
  160. if not current_user.is_editor:
  161. raise Forbidden()
  162. parser = reqparse.RequestParser()
  163. parser.add_argument("name", type=str, location="json")
  164. parser.add_argument("description", type=_validate_description_length, location="json")
  165. parser.add_argument("icon_type", type=str, location="json")
  166. parser.add_argument("icon", type=str, location="json")
  167. parser.add_argument("icon_background", type=str, location="json")
  168. args = parser.parse_args()
  169. with Session(db.engine) as session:
  170. import_service = AppDslService(session)
  171. yaml_content = import_service.export_dsl(app_model=app_model, include_secret=True)
  172. account = cast(Account, current_user)
  173. result = import_service.import_app(
  174. account=account,
  175. import_mode=ImportMode.YAML_CONTENT.value,
  176. yaml_content=yaml_content,
  177. name=args.get("name"),
  178. description=args.get("description"),
  179. icon_type=args.get("icon_type"),
  180. icon=args.get("icon"),
  181. icon_background=args.get("icon_background"),
  182. )
  183. session.commit()
  184. stmt = select(App).where(App.id == result.app_id)
  185. app = session.scalar(stmt)
  186. return app, 201
  187. class AppExportApi(Resource):
  188. @setup_required
  189. @login_required
  190. @account_initialization_required
  191. @get_app_model
  192. def get(self, app_model):
  193. """Export app"""
  194. # The role of the current user in the ta table must be admin, owner, or editor
  195. if not current_user.is_editor:
  196. raise Forbidden()
  197. # Add include_secret params
  198. parser = reqparse.RequestParser()
  199. parser.add_argument("include_secret", type=inputs.boolean, default=False, location="args")
  200. parser.add_argument("workflow_id", type=str, location="args")
  201. args = parser.parse_args()
  202. return {
  203. "data": AppDslService.export_dsl(
  204. app_model=app_model, include_secret=args["include_secret"], workflow_id=args.get("workflow_id")
  205. )
  206. }
  207. class AppNameApi(Resource):
  208. @setup_required
  209. @login_required
  210. @account_initialization_required
  211. @get_app_model
  212. @marshal_with(app_detail_fields)
  213. def post(self, app_model):
  214. # The role of the current user in the ta table must be admin, owner, or editor
  215. if not current_user.is_editor:
  216. raise Forbidden()
  217. parser = reqparse.RequestParser()
  218. parser.add_argument("name", type=str, required=True, location="json")
  219. args = parser.parse_args()
  220. app_service = AppService()
  221. app_model = app_service.update_app_name(app_model, args.get("name"))
  222. return app_model
  223. class AppIconApi(Resource):
  224. @setup_required
  225. @login_required
  226. @account_initialization_required
  227. @get_app_model
  228. @marshal_with(app_detail_fields)
  229. def post(self, app_model):
  230. # The role of the current user in the ta table must be admin, owner, or editor
  231. if not current_user.is_editor:
  232. raise Forbidden()
  233. parser = reqparse.RequestParser()
  234. parser.add_argument("icon", type=str, location="json")
  235. parser.add_argument("icon_background", type=str, location="json")
  236. args = parser.parse_args()
  237. app_service = AppService()
  238. app_model = app_service.update_app_icon(app_model, args.get("icon"), args.get("icon_background"))
  239. return app_model
  240. class AppSiteStatus(Resource):
  241. @setup_required
  242. @login_required
  243. @account_initialization_required
  244. @get_app_model
  245. @marshal_with(app_detail_fields)
  246. def post(self, app_model):
  247. # The role of the current user in the ta table must be admin, owner, or editor
  248. if not current_user.is_editor:
  249. raise Forbidden()
  250. parser = reqparse.RequestParser()
  251. parser.add_argument("enable_site", type=bool, required=True, location="json")
  252. args = parser.parse_args()
  253. app_service = AppService()
  254. app_model = app_service.update_app_site_status(app_model, args.get("enable_site"))
  255. return app_model
  256. class AppApiStatus(Resource):
  257. @setup_required
  258. @login_required
  259. @account_initialization_required
  260. @get_app_model
  261. @marshal_with(app_detail_fields)
  262. def post(self, app_model):
  263. # The role of the current user in the ta table must be admin or owner
  264. if not current_user.is_admin_or_owner:
  265. raise Forbidden()
  266. parser = reqparse.RequestParser()
  267. parser.add_argument("enable_api", type=bool, required=True, location="json")
  268. args = parser.parse_args()
  269. app_service = AppService()
  270. app_model = app_service.update_app_api_status(app_model, args.get("enable_api"))
  271. return app_model
  272. class AppTraceApi(Resource):
  273. @setup_required
  274. @login_required
  275. @account_initialization_required
  276. def get(self, app_id):
  277. """Get app trace"""
  278. app_trace_config = OpsTraceManager.get_app_tracing_config(app_id=app_id)
  279. return app_trace_config
  280. @setup_required
  281. @login_required
  282. @account_initialization_required
  283. def post(self, app_id):
  284. # add app trace
  285. if not current_user.is_editor:
  286. raise Forbidden()
  287. parser = reqparse.RequestParser()
  288. parser.add_argument("enabled", type=bool, required=True, location="json")
  289. parser.add_argument("tracing_provider", type=str, required=True, location="json")
  290. args = parser.parse_args()
  291. OpsTraceManager.update_app_tracing_config(
  292. app_id=app_id,
  293. enabled=args["enabled"],
  294. tracing_provider=args["tracing_provider"],
  295. )
  296. return {"result": "success"}
  297. api.add_resource(AppListApi, "/apps")
  298. api.add_resource(AppApi, "/apps/<uuid:app_id>")
  299. api.add_resource(AppCopyApi, "/apps/<uuid:app_id>/copy")
  300. api.add_resource(AppExportApi, "/apps/<uuid:app_id>/export")
  301. api.add_resource(AppNameApi, "/apps/<uuid:app_id>/name")
  302. api.add_resource(AppIconApi, "/apps/<uuid:app_id>/icon")
  303. api.add_resource(AppSiteStatus, "/apps/<uuid:app_id>/site-enable")
  304. api.add_resource(AppApiStatus, "/apps/<uuid:app_id>/api-enable")
  305. api.add_resource(AppTraceApi, "/apps/<uuid:app_id>/trace")