Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. if not isinstance(current_user, Account):
  101. raise ValueError("current_user must be an Account instance")
  102. if current_user.current_tenant_id is None:
  103. raise ValueError("current_user.current_tenant_id cannot be None")
  104. app = app_service.create_app(current_user.current_tenant_id, args, current_user)
  105. return app, 201
  106. class AppApi(Resource):
  107. @setup_required
  108. @login_required
  109. @account_initialization_required
  110. @enterprise_license_required
  111. @get_app_model
  112. @marshal_with(app_detail_fields_with_site)
  113. def get(self, app_model):
  114. """Get app detail"""
  115. app_service = AppService()
  116. app_model = app_service.get_app(app_model)
  117. if FeatureService.get_system_features().webapp_auth.enabled:
  118. app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))
  119. app_model.access_mode = app_setting.access_mode
  120. return app_model
  121. @setup_required
  122. @login_required
  123. @account_initialization_required
  124. @get_app_model
  125. @marshal_with(app_detail_fields_with_site)
  126. def put(self, app_model):
  127. """Update app"""
  128. # The role of the current user in the ta table must be admin, owner, or editor
  129. if not current_user.is_editor:
  130. raise Forbidden()
  131. parser = reqparse.RequestParser()
  132. parser.add_argument("name", type=str, required=True, nullable=False, location="json")
  133. parser.add_argument("description", type=_validate_description_length, location="json")
  134. parser.add_argument("icon_type", type=str, location="json")
  135. parser.add_argument("icon", type=str, location="json")
  136. parser.add_argument("icon_background", type=str, location="json")
  137. parser.add_argument("use_icon_as_answer_icon", type=bool, location="json")
  138. parser.add_argument("max_active_requests", type=int, location="json")
  139. args = parser.parse_args()
  140. app_service = AppService()
  141. # Construct ArgsDict from parsed arguments
  142. from services.app_service import AppService as AppServiceType
  143. args_dict: AppServiceType.ArgsDict = {
  144. "name": args["name"],
  145. "description": args.get("description", ""),
  146. "icon_type": args.get("icon_type", ""),
  147. "icon": args.get("icon", ""),
  148. "icon_background": args.get("icon_background", ""),
  149. "use_icon_as_answer_icon": args.get("use_icon_as_answer_icon", False),
  150. "max_active_requests": args.get("max_active_requests", 0),
  151. }
  152. app_model = app_service.update_app(app_model, args_dict)
  153. return app_model
  154. @get_app_model
  155. @setup_required
  156. @login_required
  157. @account_initialization_required
  158. def delete(self, app_model):
  159. """Delete app"""
  160. # The role of the current user in the ta table must be admin, owner, or editor
  161. if not current_user.is_editor:
  162. raise Forbidden()
  163. app_service = AppService()
  164. app_service.delete_app(app_model)
  165. return {"result": "success"}, 204
  166. class AppCopyApi(Resource):
  167. @setup_required
  168. @login_required
  169. @account_initialization_required
  170. @get_app_model
  171. @marshal_with(app_detail_fields_with_site)
  172. def post(self, app_model):
  173. """Copy app"""
  174. # The role of the current user in the ta table must be admin, owner, or editor
  175. if not current_user.is_editor:
  176. raise Forbidden()
  177. parser = reqparse.RequestParser()
  178. parser.add_argument("name", type=str, location="json")
  179. parser.add_argument("description", type=_validate_description_length, location="json")
  180. parser.add_argument("icon_type", type=str, location="json")
  181. parser.add_argument("icon", type=str, location="json")
  182. parser.add_argument("icon_background", type=str, location="json")
  183. args = parser.parse_args()
  184. with Session(db.engine) as session:
  185. import_service = AppDslService(session)
  186. yaml_content = import_service.export_dsl(app_model=app_model, include_secret=True)
  187. account = cast(Account, current_user)
  188. result = import_service.import_app(
  189. account=account,
  190. import_mode=ImportMode.YAML_CONTENT.value,
  191. yaml_content=yaml_content,
  192. name=args.get("name"),
  193. description=args.get("description"),
  194. icon_type=args.get("icon_type"),
  195. icon=args.get("icon"),
  196. icon_background=args.get("icon_background"),
  197. )
  198. session.commit()
  199. stmt = select(App).where(App.id == result.app_id)
  200. app = session.scalar(stmt)
  201. return app, 201
  202. class AppExportApi(Resource):
  203. @get_app_model
  204. @setup_required
  205. @login_required
  206. @account_initialization_required
  207. def get(self, app_model):
  208. """Export app"""
  209. # The role of the current user in the ta table must be admin, owner, or editor
  210. if not current_user.is_editor:
  211. raise Forbidden()
  212. # Add include_secret params
  213. parser = reqparse.RequestParser()
  214. parser.add_argument("include_secret", type=inputs.boolean, default=False, location="args")
  215. parser.add_argument("workflow_id", type=str, location="args")
  216. args = parser.parse_args()
  217. return {
  218. "data": AppDslService.export_dsl(
  219. app_model=app_model, include_secret=args["include_secret"], workflow_id=args.get("workflow_id")
  220. )
  221. }
  222. class AppNameApi(Resource):
  223. @setup_required
  224. @login_required
  225. @account_initialization_required
  226. @get_app_model
  227. @marshal_with(app_detail_fields)
  228. def post(self, app_model):
  229. # The role of the current user in the ta table must be admin, owner, or editor
  230. if not current_user.is_editor:
  231. raise Forbidden()
  232. parser = reqparse.RequestParser()
  233. parser.add_argument("name", type=str, required=True, location="json")
  234. args = parser.parse_args()
  235. app_service = AppService()
  236. app_model = app_service.update_app_name(app_model, args["name"])
  237. return app_model
  238. class AppIconApi(Resource):
  239. @setup_required
  240. @login_required
  241. @account_initialization_required
  242. @get_app_model
  243. @marshal_with(app_detail_fields)
  244. def post(self, app_model):
  245. # The role of the current user in the ta table must be admin, owner, or editor
  246. if not current_user.is_editor:
  247. raise Forbidden()
  248. parser = reqparse.RequestParser()
  249. parser.add_argument("icon", type=str, location="json")
  250. parser.add_argument("icon_background", type=str, location="json")
  251. args = parser.parse_args()
  252. app_service = AppService()
  253. app_model = app_service.update_app_icon(app_model, args.get("icon") or "", args.get("icon_background") or "")
  254. return app_model
  255. class AppSiteStatus(Resource):
  256. @setup_required
  257. @login_required
  258. @account_initialization_required
  259. @get_app_model
  260. @marshal_with(app_detail_fields)
  261. def post(self, app_model):
  262. # The role of the current user in the ta table must be admin, owner, or editor
  263. if not current_user.is_editor:
  264. raise Forbidden()
  265. parser = reqparse.RequestParser()
  266. parser.add_argument("enable_site", type=bool, required=True, location="json")
  267. args = parser.parse_args()
  268. app_service = AppService()
  269. app_model = app_service.update_app_site_status(app_model, args["enable_site"])
  270. return app_model
  271. class AppApiStatus(Resource):
  272. @setup_required
  273. @login_required
  274. @account_initialization_required
  275. @get_app_model
  276. @marshal_with(app_detail_fields)
  277. def post(self, app_model):
  278. # The role of the current user in the ta table must be admin or owner
  279. if not current_user.is_admin_or_owner:
  280. raise Forbidden()
  281. parser = reqparse.RequestParser()
  282. parser.add_argument("enable_api", type=bool, required=True, location="json")
  283. args = parser.parse_args()
  284. app_service = AppService()
  285. app_model = app_service.update_app_api_status(app_model, args["enable_api"])
  286. return app_model
  287. class AppTraceApi(Resource):
  288. @setup_required
  289. @login_required
  290. @account_initialization_required
  291. def get(self, app_id):
  292. """Get app trace"""
  293. app_trace_config = OpsTraceManager.get_app_tracing_config(app_id=app_id)
  294. return app_trace_config
  295. @setup_required
  296. @login_required
  297. @account_initialization_required
  298. def post(self, app_id):
  299. # add app trace
  300. if not current_user.is_editor:
  301. raise Forbidden()
  302. parser = reqparse.RequestParser()
  303. parser.add_argument("enabled", type=bool, required=True, location="json")
  304. parser.add_argument("tracing_provider", type=str, required=True, location="json")
  305. args = parser.parse_args()
  306. OpsTraceManager.update_app_tracing_config(
  307. app_id=app_id,
  308. enabled=args["enabled"],
  309. tracing_provider=args["tracing_provider"],
  310. )
  311. return {"result": "success"}
  312. api.add_resource(AppListApi, "/apps")
  313. api.add_resource(AppApi, "/apps/<uuid:app_id>")
  314. api.add_resource(AppCopyApi, "/apps/<uuid:app_id>/copy")
  315. api.add_resource(AppExportApi, "/apps/<uuid:app_id>/export")
  316. api.add_resource(AppNameApi, "/apps/<uuid:app_id>/name")
  317. api.add_resource(AppIconApi, "/apps/<uuid:app_id>/icon")
  318. api.add_resource(AppSiteStatus, "/apps/<uuid:app_id>/site-enable")
  319. api.add_resource(AppApiStatus, "/apps/<uuid:app_id>/api-enable")
  320. api.add_resource(AppTraceApi, "/apps/<uuid:app_id>/trace")