Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import uuid
  2. from typing import cast
  3. from flask_login import current_user
  4. from flask_restful 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. args = parser.parse_args()
  201. return {"data": AppDslService.export_dsl(app_model=app_model, include_secret=args["include_secret"])}
  202. class AppNameApi(Resource):
  203. @setup_required
  204. @login_required
  205. @account_initialization_required
  206. @get_app_model
  207. @marshal_with(app_detail_fields)
  208. def post(self, app_model):
  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. parser = reqparse.RequestParser()
  213. parser.add_argument("name", type=str, required=True, location="json")
  214. args = parser.parse_args()
  215. app_service = AppService()
  216. app_model = app_service.update_app_name(app_model, args.get("name"))
  217. return app_model
  218. class AppIconApi(Resource):
  219. @setup_required
  220. @login_required
  221. @account_initialization_required
  222. @get_app_model
  223. @marshal_with(app_detail_fields)
  224. def post(self, app_model):
  225. # The role of the current user in the ta table must be admin, owner, or editor
  226. if not current_user.is_editor:
  227. raise Forbidden()
  228. parser = reqparse.RequestParser()
  229. parser.add_argument("icon", type=str, location="json")
  230. parser.add_argument("icon_background", type=str, location="json")
  231. args = parser.parse_args()
  232. app_service = AppService()
  233. app_model = app_service.update_app_icon(app_model, args.get("icon"), args.get("icon_background"))
  234. return app_model
  235. class AppSiteStatus(Resource):
  236. @setup_required
  237. @login_required
  238. @account_initialization_required
  239. @get_app_model
  240. @marshal_with(app_detail_fields)
  241. def post(self, app_model):
  242. # The role of the current user in the ta table must be admin, owner, or editor
  243. if not current_user.is_editor:
  244. raise Forbidden()
  245. parser = reqparse.RequestParser()
  246. parser.add_argument("enable_site", type=bool, required=True, location="json")
  247. args = parser.parse_args()
  248. app_service = AppService()
  249. app_model = app_service.update_app_site_status(app_model, args.get("enable_site"))
  250. return app_model
  251. class AppApiStatus(Resource):
  252. @setup_required
  253. @login_required
  254. @account_initialization_required
  255. @get_app_model
  256. @marshal_with(app_detail_fields)
  257. def post(self, app_model):
  258. # The role of the current user in the ta table must be admin or owner
  259. if not current_user.is_admin_or_owner:
  260. raise Forbidden()
  261. parser = reqparse.RequestParser()
  262. parser.add_argument("enable_api", type=bool, required=True, location="json")
  263. args = parser.parse_args()
  264. app_service = AppService()
  265. app_model = app_service.update_app_api_status(app_model, args.get("enable_api"))
  266. return app_model
  267. class AppTraceApi(Resource):
  268. @setup_required
  269. @login_required
  270. @account_initialization_required
  271. def get(self, app_id):
  272. """Get app trace"""
  273. app_trace_config = OpsTraceManager.get_app_tracing_config(app_id=app_id)
  274. return app_trace_config
  275. @setup_required
  276. @login_required
  277. @account_initialization_required
  278. def post(self, app_id):
  279. # add app trace
  280. if not current_user.is_editor:
  281. raise Forbidden()
  282. parser = reqparse.RequestParser()
  283. parser.add_argument("enabled", type=bool, required=True, location="json")
  284. parser.add_argument("tracing_provider", type=str, required=True, location="json")
  285. args = parser.parse_args()
  286. OpsTraceManager.update_app_tracing_config(
  287. app_id=app_id,
  288. enabled=args["enabled"],
  289. tracing_provider=args["tracing_provider"],
  290. )
  291. return {"result": "success"}
  292. api.add_resource(AppListApi, "/apps")
  293. api.add_resource(AppApi, "/apps/<uuid:app_id>")
  294. api.add_resource(AppCopyApi, "/apps/<uuid:app_id>/copy")
  295. api.add_resource(AppExportApi, "/apps/<uuid:app_id>/export")
  296. api.add_resource(AppNameApi, "/apps/<uuid:app_id>/name")
  297. api.add_resource(AppIconApi, "/apps/<uuid:app_id>/icon")
  298. api.add_resource(AppSiteStatus, "/apps/<uuid:app_id>/site-enable")
  299. api.add_resource(AppApiStatus, "/apps/<uuid:app_id>/api-enable")
  300. api.add_resource(AppTraceApi, "/apps/<uuid:app_id>/trace")