workflow.py 19 KB

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