workflow.py 18 KB

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