workflow.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import json
  2. import logging
  3. from flask import abort, request
  4. from flask_restful import Resource, marshal_with, reqparse
  5. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  6. import services
  7. from controllers.console import api
  8. from controllers.console.app.error import ConversationCompletedError, DraftWorkflowNotExist, DraftWorkflowNotSync
  9. from controllers.console.app.wraps import get_app_model
  10. from controllers.console.setup import setup_required
  11. from controllers.console.wraps import account_initialization_required
  12. from core.app.apps.base_app_queue_manager import AppQueueManager
  13. from core.app.entities.app_invoke_entities import InvokeFrom
  14. from core.app.segments import factory
  15. from core.errors.error import AppInvokeQuotaExceededError
  16. from fields.workflow_fields import workflow_fields
  17. from fields.workflow_run_fields import workflow_run_node_execution_fields
  18. from libs import helper
  19. from libs.helper import TimestampField, uuid_value
  20. from libs.login import current_user, login_required
  21. from models.account import Account
  22. from models.model import App, AppMode
  23. from services.app_dsl_service import AppDslService
  24. from services.app_generate_service import AppGenerateService
  25. from services.errors.app import WorkflowHashNotEqualError
  26. from services.workflow_service import WorkflowService
  27. logger = logging.getLogger(__name__)
  28. class DraftWorkflowApi(Resource):
  29. @setup_required
  30. @login_required
  31. @account_initialization_required
  32. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  33. @marshal_with(workflow_fields)
  34. def get(self, app_model: App):
  35. """
  36. Get draft workflow
  37. """
  38. # The role of the current user in the ta table must be admin, owner, or editor
  39. if not current_user.is_editor:
  40. raise Forbidden()
  41. # fetch draft workflow by app_model
  42. workflow_service = WorkflowService()
  43. workflow = workflow_service.get_draft_workflow(app_model=app_model)
  44. if not workflow:
  45. raise DraftWorkflowNotExist()
  46. # return workflow, if not found, return None (initiate graph by frontend)
  47. return workflow
  48. @setup_required
  49. @login_required
  50. @account_initialization_required
  51. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  52. def post(self, app_model: App):
  53. """
  54. Sync draft workflow
  55. """
  56. # The role of the current user in the ta table must be admin, owner, or editor
  57. if not current_user.is_editor:
  58. raise Forbidden()
  59. content_type = request.headers.get("Content-Type", "")
  60. if "application/json" in content_type:
  61. parser = reqparse.RequestParser()
  62. parser.add_argument("graph", type=dict, required=True, nullable=False, location="json")
  63. parser.add_argument("features", type=dict, required=True, nullable=False, location="json")
  64. parser.add_argument("hash", type=str, required=False, location="json")
  65. # TODO: set this to required=True after frontend is updated
  66. parser.add_argument("environment_variables", type=list, required=False, location="json")
  67. parser.add_argument("conversation_variables", type=list, required=False, location="json")
  68. args = parser.parse_args()
  69. elif "text/plain" in content_type:
  70. try:
  71. data = json.loads(request.data.decode("utf-8"))
  72. if "graph" not in data or "features" not in data:
  73. raise ValueError("graph or features not found in data")
  74. if not isinstance(data.get("graph"), dict) or not isinstance(data.get("features"), dict):
  75. raise ValueError("graph or features is not a dict")
  76. args = {
  77. "graph": data.get("graph"),
  78. "features": data.get("features"),
  79. "hash": data.get("hash"),
  80. "environment_variables": data.get("environment_variables"),
  81. "conversation_variables": data.get("conversation_variables"),
  82. }
  83. except json.JSONDecodeError:
  84. return {"message": "Invalid JSON data"}, 400
  85. else:
  86. abort(415)
  87. if not isinstance(current_user, Account):
  88. raise Forbidden()
  89. workflow_service = WorkflowService()
  90. try:
  91. environment_variables_list = args.get("environment_variables") or []
  92. environment_variables = [factory.build_variable_from_mapping(obj) for obj in environment_variables_list]
  93. conversation_variables_list = args.get("conversation_variables") or []
  94. conversation_variables = [factory.build_variable_from_mapping(obj) for obj in conversation_variables_list]
  95. workflow = workflow_service.sync_draft_workflow(
  96. app_model=app_model,
  97. graph=args["graph"],
  98. features=args["features"],
  99. unique_hash=args.get("hash"),
  100. account=current_user,
  101. environment_variables=environment_variables,
  102. conversation_variables=conversation_variables,
  103. )
  104. except WorkflowHashNotEqualError:
  105. raise DraftWorkflowNotSync()
  106. return {
  107. "result": "success",
  108. "hash": workflow.unique_hash,
  109. "updated_at": TimestampField().format(workflow.updated_at or workflow.created_at),
  110. }
  111. class DraftWorkflowImportApi(Resource):
  112. @setup_required
  113. @login_required
  114. @account_initialization_required
  115. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  116. @marshal_with(workflow_fields)
  117. def post(self, app_model: App):
  118. """
  119. Import draft workflow
  120. """
  121. # The role of the current user in the ta table must be admin, owner, or editor
  122. if not current_user.is_editor:
  123. raise Forbidden()
  124. if not isinstance(current_user, Account):
  125. raise Forbidden()
  126. parser = reqparse.RequestParser()
  127. parser.add_argument("data", type=str, required=True, nullable=False, location="json")
  128. args = parser.parse_args()
  129. workflow = AppDslService.import_and_overwrite_workflow(
  130. app_model=app_model, data=args["data"], account=current_user
  131. )
  132. return workflow
  133. class AdvancedChatDraftWorkflowRunApi(Resource):
  134. @setup_required
  135. @login_required
  136. @account_initialization_required
  137. @get_app_model(mode=[AppMode.ADVANCED_CHAT])
  138. def post(self, app_model: App):
  139. """
  140. Run draft workflow
  141. """
  142. # The role of the current user in the ta table must be admin, owner, or editor
  143. if not current_user.is_editor:
  144. raise Forbidden()
  145. if not isinstance(current_user, Account):
  146. raise Forbidden()
  147. parser = reqparse.RequestParser()
  148. parser.add_argument("inputs", type=dict, location="json")
  149. parser.add_argument("query", type=str, required=True, location="json", default="")
  150. parser.add_argument("files", type=list, location="json")
  151. parser.add_argument("conversation_id", type=uuid_value, location="json")
  152. parser.add_argument("parent_message_id", type=uuid_value, required=False, location="json")
  153. args = parser.parse_args()
  154. try:
  155. response = AppGenerateService.generate(
  156. app_model=app_model, user=current_user, args=args, invoke_from=InvokeFrom.DEBUGGER, streaming=True
  157. )
  158. return helper.compact_generate_response(response)
  159. except services.errors.conversation.ConversationNotExistsError:
  160. raise NotFound("Conversation Not Exists.")
  161. except services.errors.conversation.ConversationCompletedError:
  162. raise ConversationCompletedError()
  163. except ValueError as e:
  164. raise e
  165. except Exception as e:
  166. logging.exception("internal server error.")
  167. raise InternalServerError()
  168. class AdvancedChatDraftRunIterationNodeApi(Resource):
  169. @setup_required
  170. @login_required
  171. @account_initialization_required
  172. @get_app_model(mode=[AppMode.ADVANCED_CHAT])
  173. def post(self, app_model: App, node_id: str):
  174. """
  175. Run draft workflow iteration node
  176. """
  177. # The role of the current user in the ta table must be admin, owner, or editor
  178. if not current_user.is_editor:
  179. raise Forbidden()
  180. if not isinstance(current_user, Account):
  181. raise Forbidden()
  182. parser = reqparse.RequestParser()
  183. parser.add_argument("inputs", type=dict, location="json")
  184. args = parser.parse_args()
  185. try:
  186. response = AppGenerateService.generate_single_iteration(
  187. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  188. )
  189. return helper.compact_generate_response(response)
  190. except services.errors.conversation.ConversationNotExistsError:
  191. raise NotFound("Conversation Not Exists.")
  192. except services.errors.conversation.ConversationCompletedError:
  193. raise ConversationCompletedError()
  194. except ValueError as e:
  195. raise e
  196. except Exception as e:
  197. logging.exception("internal server error.")
  198. raise InternalServerError()
  199. class WorkflowDraftRunIterationNodeApi(Resource):
  200. @setup_required
  201. @login_required
  202. @account_initialization_required
  203. @get_app_model(mode=[AppMode.WORKFLOW])
  204. def post(self, app_model: App, node_id: str):
  205. """
  206. Run draft workflow iteration node
  207. """
  208. # The role of the current user in the ta table must be admin, owner, or editor
  209. if not current_user.is_editor:
  210. raise Forbidden()
  211. if not isinstance(current_user, Account):
  212. raise Forbidden()
  213. parser = reqparse.RequestParser()
  214. parser.add_argument("inputs", type=dict, location="json")
  215. args = parser.parse_args()
  216. try:
  217. response = AppGenerateService.generate_single_iteration(
  218. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  219. )
  220. return helper.compact_generate_response(response)
  221. except services.errors.conversation.ConversationNotExistsError:
  222. raise NotFound("Conversation Not Exists.")
  223. except services.errors.conversation.ConversationCompletedError:
  224. raise ConversationCompletedError()
  225. except ValueError as e:
  226. raise e
  227. except Exception as e:
  228. logging.exception("internal server error.")
  229. raise InternalServerError()
  230. class DraftWorkflowRunApi(Resource):
  231. @setup_required
  232. @login_required
  233. @account_initialization_required
  234. @get_app_model(mode=[AppMode.WORKFLOW])
  235. def post(self, app_model: App):
  236. """
  237. Run draft workflow
  238. """
  239. # The role of the current user in the ta table must be admin, owner, or editor
  240. if not current_user.is_editor:
  241. raise Forbidden()
  242. if not isinstance(current_user, Account):
  243. raise Forbidden()
  244. parser = reqparse.RequestParser()
  245. parser.add_argument("inputs", type=dict, required=True, nullable=False, location="json")
  246. parser.add_argument("files", type=list, required=False, location="json")
  247. args = parser.parse_args()
  248. try:
  249. response = AppGenerateService.generate(
  250. app_model=app_model, user=current_user, args=args, invoke_from=InvokeFrom.DEBUGGER, streaming=True
  251. )
  252. return helper.compact_generate_response(response)
  253. except (ValueError, AppInvokeQuotaExceededError) as e:
  254. raise e
  255. except Exception as e:
  256. logging.exception("internal server error.")
  257. raise InternalServerError()
  258. class WorkflowTaskStopApi(Resource):
  259. @setup_required
  260. @login_required
  261. @account_initialization_required
  262. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  263. def post(self, app_model: App, task_id: str):
  264. """
  265. Stop workflow task
  266. """
  267. # The role of the current user in the ta table must be admin, owner, or editor
  268. if not current_user.is_editor:
  269. raise Forbidden()
  270. AppQueueManager.set_stop_flag(task_id, InvokeFrom.DEBUGGER, current_user.id)
  271. return {"result": "success"}
  272. class DraftWorkflowNodeRunApi(Resource):
  273. @setup_required
  274. @login_required
  275. @account_initialization_required
  276. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  277. @marshal_with(workflow_run_node_execution_fields)
  278. def post(self, app_model: App, node_id: str):
  279. """
  280. Run draft workflow node
  281. """
  282. # The role of the current user in the ta table must be admin, owner, or editor
  283. if not current_user.is_editor:
  284. raise Forbidden()
  285. if not isinstance(current_user, Account):
  286. raise Forbidden()
  287. parser = reqparse.RequestParser()
  288. parser.add_argument("inputs", type=dict, required=True, nullable=False, location="json")
  289. args = parser.parse_args()
  290. inputs = args.get("inputs")
  291. if inputs == None:
  292. raise ValueError("missing inputs")
  293. workflow_service = WorkflowService()
  294. workflow_node_execution = workflow_service.run_draft_workflow_node(
  295. app_model=app_model, node_id=node_id, user_inputs=inputs, account=current_user
  296. )
  297. return workflow_node_execution
  298. class PublishedWorkflowApi(Resource):
  299. @setup_required
  300. @login_required
  301. @account_initialization_required
  302. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  303. @marshal_with(workflow_fields)
  304. def get(self, app_model: App):
  305. """
  306. Get published workflow
  307. """
  308. # The role of the current user in the ta table must be admin, owner, or editor
  309. if not current_user.is_editor:
  310. raise Forbidden()
  311. # fetch published workflow by app_model
  312. workflow_service = WorkflowService()
  313. workflow = workflow_service.get_published_workflow(app_model=app_model)
  314. # return workflow, if not found, return None
  315. return workflow
  316. @setup_required
  317. @login_required
  318. @account_initialization_required
  319. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  320. def post(self, app_model: App):
  321. """
  322. Publish workflow
  323. """
  324. # The role of the current user in the ta table must be admin, owner, or editor
  325. if not current_user.is_editor:
  326. raise Forbidden()
  327. if not isinstance(current_user, Account):
  328. raise Forbidden()
  329. workflow_service = WorkflowService()
  330. workflow = workflow_service.publish_workflow(app_model=app_model, account=current_user)
  331. return {"result": "success", "created_at": TimestampField().format(workflow.created_at)}
  332. class DefaultBlockConfigsApi(Resource):
  333. @setup_required
  334. @login_required
  335. @account_initialization_required
  336. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  337. def get(self, app_model: App):
  338. """
  339. Get default block config
  340. """
  341. # The role of the current user in the ta table must be admin, owner, or editor
  342. if not current_user.is_editor:
  343. raise Forbidden()
  344. # Get default block configs
  345. workflow_service = WorkflowService()
  346. return workflow_service.get_default_block_configs()
  347. class DefaultBlockConfigApi(Resource):
  348. @setup_required
  349. @login_required
  350. @account_initialization_required
  351. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  352. def get(self, app_model: App, block_type: str):
  353. """
  354. Get default block config
  355. """
  356. # The role of the current user in the ta table must be admin, owner, or editor
  357. if not current_user.is_editor:
  358. raise Forbidden()
  359. if not isinstance(current_user, Account):
  360. raise Forbidden()
  361. parser = reqparse.RequestParser()
  362. parser.add_argument("q", type=str, location="args")
  363. args = parser.parse_args()
  364. q = args.get("q")
  365. filters = None
  366. if q:
  367. try:
  368. filters = json.loads(q)
  369. except json.JSONDecodeError:
  370. raise ValueError("Invalid filters")
  371. # Get default block configs
  372. workflow_service = WorkflowService()
  373. return workflow_service.get_default_block_config(node_type=block_type, filters=filters)
  374. class ConvertToWorkflowApi(Resource):
  375. @setup_required
  376. @login_required
  377. @account_initialization_required
  378. @get_app_model(mode=[AppMode.CHAT, AppMode.COMPLETION])
  379. def post(self, app_model: App):
  380. """
  381. Convert basic mode of chatbot app to workflow mode
  382. Convert expert mode of chatbot app to workflow mode
  383. Convert Completion App to Workflow App
  384. """
  385. # The role of the current user in the ta table must be admin, owner, or editor
  386. if not current_user.is_editor:
  387. raise Forbidden()
  388. if not isinstance(current_user, Account):
  389. raise Forbidden()
  390. if request.data:
  391. parser = reqparse.RequestParser()
  392. parser.add_argument("name", type=str, required=False, nullable=True, location="json")
  393. parser.add_argument("icon_type", type=str, required=False, nullable=True, location="json")
  394. parser.add_argument("icon", type=str, required=False, nullable=True, location="json")
  395. parser.add_argument("icon_background", type=str, required=False, nullable=True, location="json")
  396. args = parser.parse_args()
  397. else:
  398. args = {}
  399. # convert to workflow mode
  400. workflow_service = WorkflowService()
  401. new_app_model = workflow_service.convert_to_workflow(app_model=app_model, account=current_user, args=args)
  402. # return app id
  403. return {
  404. "new_app_id": new_app_model.id,
  405. }
  406. api.add_resource(DraftWorkflowApi, "/apps/<uuid:app_id>/workflows/draft")
  407. api.add_resource(DraftWorkflowImportApi, "/apps/<uuid:app_id>/workflows/draft/import")
  408. api.add_resource(AdvancedChatDraftWorkflowRunApi, "/apps/<uuid:app_id>/advanced-chat/workflows/draft/run")
  409. api.add_resource(DraftWorkflowRunApi, "/apps/<uuid:app_id>/workflows/draft/run")
  410. api.add_resource(WorkflowTaskStopApi, "/apps/<uuid:app_id>/workflow-runs/tasks/<string:task_id>/stop")
  411. api.add_resource(DraftWorkflowNodeRunApi, "/apps/<uuid:app_id>/workflows/draft/nodes/<string:node_id>/run")
  412. api.add_resource(
  413. AdvancedChatDraftRunIterationNodeApi,
  414. "/apps/<uuid:app_id>/advanced-chat/workflows/draft/iteration/nodes/<string:node_id>/run",
  415. )
  416. api.add_resource(
  417. WorkflowDraftRunIterationNodeApi, "/apps/<uuid:app_id>/workflows/draft/iteration/nodes/<string:node_id>/run"
  418. )
  419. api.add_resource(PublishedWorkflowApi, "/apps/<uuid:app_id>/workflows/publish")
  420. api.add_resource(DefaultBlockConfigsApi, "/apps/<uuid:app_id>/workflows/default-workflow-block-configs")
  421. api.add_resource(
  422. DefaultBlockConfigApi, "/apps/<uuid:app_id>/workflows/default-workflow-block-configs/<string:block_type>"
  423. )
  424. api.add_resource(ConvertToWorkflowApi, "/apps/<uuid:app_id>/convert-to-workflow")