workflow.py 19 KB

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