rexyang-ai преди 1 месец
родител
ревизия
8f25606b13
променени са 100 файла, в които са добавени 8630 реда и са изтрити 2 реда
  1. 6 0
      .editorconfig
  2. 192 0
      .gitignore
  3. 674 0
      LICENSE
  4. 5 2
      README.md
  5. 0 0
      apps/__init__.py
  6. 0 0
      apps/application/__init__.py
  7. 3 0
      apps/application/admin.py
  8. 35 0
      apps/application/api/application_access_token.py
  9. 240 0
      apps/application/api/application_api.py
  10. 61 0
      apps/application/api/application_api_key.py
  11. 141 0
      apps/application/api/application_chat.py
  12. 62 0
      apps/application/api/application_chat_link.py
  13. 180 0
      apps/application/api/application_chat_record.py
  14. 55 0
      apps/application/api/application_stats.py
  15. 96 0
      apps/application/api/application_version.py
  16. 6 0
      apps/application/apps.py
  17. 185 0
      apps/application/chat_pipeline/I_base_chat_pipeline.py
  18. 8 0
      apps/application/chat_pipeline/__init__.py
  19. 66 0
      apps/application/chat_pipeline/pipeline_manage.py
  20. 8 0
      apps/application/chat_pipeline/step/__init__.py
  21. 8 0
      apps/application/chat_pipeline/step/chat_step/__init__.py
  22. 121 0
      apps/application/chat_pipeline/step/chat_step/i_chat_step.py
  23. 541 0
      apps/application/chat_pipeline/step/chat_step/impl/base_chat_step.py
  24. 8 0
      apps/application/chat_pipeline/step/generate_human_message_step/__init__.py
  25. 82 0
      apps/application/chat_pipeline/step/generate_human_message_step/i_generate_human_message_step.py
  26. 79 0
      apps/application/chat_pipeline/step/generate_human_message_step/impl/base_generate_human_message_step.py
  27. 8 0
      apps/application/chat_pipeline/step/reset_problem_step/__init__.py
  28. 55 0
      apps/application/chat_pipeline/step/reset_problem_step/i_reset_problem_step.py
  29. 69 0
      apps/application/chat_pipeline/step/reset_problem_step/impl/base_reset_problem_step.py
  30. 8 0
      apps/application/chat_pipeline/step/search_dataset_step/__init__.py
  31. 77 0
      apps/application/chat_pipeline/step/search_dataset_step/i_search_dataset_step.py
  32. 150 0
      apps/application/chat_pipeline/step/search_dataset_step/impl/base_search_dataset_step.py
  33. 8 0
      apps/application/flow/__init__.py
  34. 0 0
      apps/application/flow/backend/__init__.py
  35. 69 0
      apps/application/flow/backend/sandbox_shell.py
  36. 284 0
      apps/application/flow/common.py
  37. 36 0
      apps/application/flow/compare/__init__.py
  38. 20 0
      apps/application/flow/compare/compare.py
  39. 26 0
      apps/application/flow/compare/contain_compare.py
  40. 22 0
      apps/application/flow/compare/end_with.py
  41. 21 0
      apps/application/flow/compare/equal_compare.py
  42. 28 0
      apps/application/flow/compare/ge_compare.py
  43. 28 0
      apps/application/flow/compare/gt_compare.py
  44. 21 0
      apps/application/flow/compare/is_not_null_compare.py
  45. 24 0
      apps/application/flow/compare/is_not_true.py
  46. 24 0
      apps/application/flow/compare/is_null_compare.py
  47. 24 0
      apps/application/flow/compare/is_true.py
  48. 28 0
      apps/application/flow/compare/le_compare.py
  49. 24 0
      apps/application/flow/compare/len_equal_compare.py
  50. 24 0
      apps/application/flow/compare/len_ge_compare.py
  51. 24 0
      apps/application/flow/compare/len_gt_compare.py
  52. 24 0
      apps/application/flow/compare/len_le_compare.py
  53. 24 0
      apps/application/flow/compare/len_lt_compare.py
  54. 28 0
      apps/application/flow/compare/lt_compare.py
  55. 26 0
      apps/application/flow/compare/not_contain_compare.py
  56. 21 0
      apps/application/flow/compare/not_equal_compare.py
  57. 40 0
      apps/application/flow/compare/regex_compare.py
  58. 22 0
      apps/application/flow/compare/start_with.py
  59. 43 0
      apps/application/flow/compare/wildcard_compare.py
  60. 451 0
      apps/application/flow/default_workflow.json
  61. 451 0
      apps/application/flow/default_workflow_en.json
  62. 451 0
      apps/application/flow/default_workflow_zh.json
  63. 451 0
      apps/application/flow/default_workflow_zh_Hant.json
  64. 369 0
      apps/application/flow/i_step_node.py
  65. 21 0
      apps/application/flow/knowledge_loop_workflow_manage.py
  66. 130 0
      apps/application/flow/knowledge_workflow_manage.py
  67. 199 0
      apps/application/flow/loop_workflow_manage.py
  68. 63 0
      apps/application/flow/step_node/__init__.py
  69. 9 0
      apps/application/flow/step_node/ai_chat_step_node/__init__.py
  70. 86 0
      apps/application/flow/step_node/ai_chat_step_node/i_chat_node.py
  71. 9 0
      apps/application/flow/step_node/ai_chat_step_node/impl/__init__.py
  72. 423 0
      apps/application/flow/step_node/ai_chat_step_node/impl/base_chat_node.py
  73. 2 0
      apps/application/flow/step_node/application_node/__init__.py
  74. 106 0
      apps/application/flow/step_node/application_node/i_application_node.py
  75. 2 0
      apps/application/flow/step_node/application_node/impl/__init__.py
  76. 298 0
      apps/application/flow/step_node/application_node/impl/base_application_node.py
  77. 9 0
      apps/application/flow/step_node/condition_node/__init__.py
  78. 42 0
      apps/application/flow/step_node/condition_node/i_condition_node.py
  79. 9 0
      apps/application/flow/step_node/condition_node/impl/__init__.py
  80. 64 0
      apps/application/flow/step_node/condition_node/impl/base_condition_node.py
  81. 8 0
      apps/application/flow/step_node/data_source_local_node/__init__.py
  82. 42 0
      apps/application/flow/step_node/data_source_local_node/i_data_source_local_node.py
  83. 8 0
      apps/application/flow/step_node/data_source_local_node/impl/__init__.py
  84. 52 0
      apps/application/flow/step_node/data_source_local_node/impl/base_data_source_local_node.py
  85. 8 0
      apps/application/flow/step_node/data_source_web_node/__init__.py
  86. 28 0
      apps/application/flow/step_node/data_source_web_node/i_data_source_web_node.py
  87. 8 0
      apps/application/flow/step_node/data_source_web_node/impl/__init__.py
  88. 98 0
      apps/application/flow/step_node/data_source_web_node/impl/base_data_source_web_node.py
  89. 9 0
      apps/application/flow/step_node/direct_reply_node/__init__.py
  90. 58 0
      apps/application/flow/step_node/direct_reply_node/i_reply_node.py
  91. 9 0
      apps/application/flow/step_node/direct_reply_node/impl/__init__.py
  92. 47 0
      apps/application/flow/step_node/direct_reply_node/impl/base_reply_node.py
  93. 1 0
      apps/application/flow/step_node/document_extract_node/__init__.py
  94. 30 0
      apps/application/flow/step_node/document_extract_node/i_document_extract_node.py
  95. 1 0
      apps/application/flow/step_node/document_extract_node/impl/__init__.py
  96. 95 0
      apps/application/flow/step_node/document_extract_node/impl/base_document_extract_node.py
  97. 1 0
      apps/application/flow/step_node/document_split_node/__init__.py
  98. 97 0
      apps/application/flow/step_node/document_split_node/i_document_split_node.py
  99. 1 0
      apps/application/flow/step_node/document_split_node/impl/__init__.py
  100. 192 0
      apps/application/flow/step_node/document_split_node/impl/base_document_split_node.py

+ 6 - 0
.editorconfig

@@ -0,0 +1,6 @@
+root = true
+
+[*.py]
+max_line_length = 120
+ij_visual_guides = 120
+

+ 192 - 0
.gitignore

@@ -0,0 +1,192 @@
+# Mac
+.DS_Store
+*/.DS_Store
+
+# VS Code
+.vscode
+*.project
+*.factorypath
+
+# IntelliJ IDEA
+.idea/*
+!.idea/icon.png
+*.iws
+*.iml
+*.ipr
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+#  Usually these files are written by a python script forms a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+#   For a library or package, you might want to ignore these files since the code is
+#   intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+#   However, in case of collaboration, if having platform-specific dependencies or dependencies
+#   having no cross-platform support, pipenv may install dependencies that don't work, or not
+#   install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+#   This is especially recommended for binary packages to ensure reproducibility, and is more
+#   commonly ignored for libraries.
+#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+#   in version control.
+#   https://pdm.fming.dev/#use-with-ide
+.pdm.toml
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+# env/
+venv/
+# ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+#  and can be added to the global gitignore or merged into this file.  For a more nuclear
+#  option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea/
+ui/package-lock.json
+ui/node_modules
+ui/dist
+apps/static
+models/
+apps/xpack
+!apps/**/models/
+data
+.dev
+poetry.lock
+uv.lock
+apps/models_provider/impl/*/icon/
+apps/models_provider/impl/tencent_model_provider/credential/stt.py
+apps/models_provider/impl/tencent_model_provider/model/stt.py
+tmp/
+config.yml
+.SANDBOX_BANNED_HOSTS

+ 674 - 0
LICENSE

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 5 - 2
README.md

@@ -1,3 +1,6 @@
-# ZhAgent
+\# ZhAgentOS
+
+
+
+AI Agent System
 
-ZhAgent

+ 0 - 0
apps/__init__.py


+ 0 - 0
apps/application/__init__.py


+ 3 - 0
apps/application/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 35 - 0
apps/application/api/application_access_token.py

@@ -0,0 +1,35 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application_access_token.py
+    @date:2025/6/9 17:46
+    @desc:
+"""
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_access_token import AccessTokenEditSerializer
+from common.mixins.api_mixin import APIMixin
+
+
+class ApplicationAccessTokenAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [OpenApiParameter(
+            name="workspace_id",
+            description="工作空间id",
+            type=OpenApiTypes.STR,
+            location='path',
+            required=True,
+        ), OpenApiParameter(
+            name="application_id",
+            description="应用id",
+            type=OpenApiTypes.STR,
+            location='path',
+            required=True,
+        )]
+
+    @staticmethod
+    def get_request():
+        return AccessTokenEditSerializer

+ 240 - 0
apps/application/api/application_api.py

@@ -0,0 +1,240 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application.py
+    @date:2025/5/26 16:59
+    @desc:
+"""
+from django.utils.translation import gettext_lazy as _
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+from rest_framework import serializers
+
+from application.serializers.application import ApplicationCreateSerializer, ApplicationListResponse, \
+    ApplicationImportRequest, ApplicationEditSerializer, TextToSpeechRequest, SpeechToTextRequest, PlayDemoTextRequest
+from common.mixins.api_mixin import APIMixin
+from common.result import ResultSerializer, ResultPageSerializer, DefaultResultSerializer
+from knowledge.serializers.common import BatchSerializer, BatchMoveSerializer
+
+
+class ApplicationCreateRequest(ApplicationCreateSerializer.SimplateRequest):
+    work_flow = serializers.DictField(required=True, label=_("Workflow Objects"))
+
+
+class ApplicationCreateResponse(ResultSerializer):
+    def get_data(self):
+        return ApplicationCreateSerializer.ApplicationResponse()
+
+
+class ApplicationListResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationListResponse(many=True)
+
+
+class ApplicationPageResult(ResultPageSerializer):
+    def get_data(self):
+        return ApplicationListResponse(many=True)
+
+
+class ApplicationQueryAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="current_page",
+                description=_("Current page"),
+                type=OpenApiTypes.INT,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="page_size",
+                description=_("Page size"),
+                type=OpenApiTypes.INT,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="folder_id",
+                description=_("folder id"),
+                type=OpenApiTypes.STR,
+                location='query',
+                required=False,
+            ),
+            OpenApiParameter(
+                name="name",
+                description=_("Application Name"),
+                type=OpenApiTypes.STR,
+                location='query',
+                required=False,
+            ),
+            OpenApiParameter(
+                name="desc",
+                description=_("Application Description"),
+                type=OpenApiTypes.STR,
+                location='query',
+                required=False,
+            ),
+            OpenApiParameter(
+                name="user_id",
+                description=_("User ID"),
+                type=OpenApiTypes.STR,
+                location='query',
+                required=False,
+            ),
+            OpenApiParameter(
+                name="publish_status",
+                description=_("Publish status") + '(published|unpublished)',
+                type=OpenApiTypes.STR,
+                location='query',
+                required=False,
+            )
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationListResult
+
+    @staticmethod
+    def get_page_response():
+        return ApplicationPageResult
+
+
+class ApplicationCreateAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+
+    @staticmethod
+    def get_request():
+        return ApplicationCreateRequest
+
+    @staticmethod
+    def get_response():
+        return ApplicationCreateResponse
+
+
+class ApplicationImportAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        ApplicationCreateAPI.get_parameters()
+
+    @staticmethod
+    def get_request():
+        return ApplicationImportRequest
+
+
+class ApplicationOperateAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="应用id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+
+
+class ApplicationBatchOperateAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+    @staticmethod
+    def get_request():
+        return BatchSerializer
+
+    @staticmethod
+    def get_move_request():
+        return BatchMoveSerializer
+
+
+class ApplicationExportAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return ApplicationOperateAPI.get_parameters()
+
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer
+
+
+class ApplicationEditAPI(APIMixin):
+    @staticmethod
+    def get_request():
+        return ApplicationEditSerializer
+
+
+class TextToSpeechAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return ApplicationOperateAPI.get_parameters()
+
+    @staticmethod
+    def get_request():
+        return TextToSpeechRequest
+
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer
+
+
+class SpeechToTextAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return ApplicationOperateAPI.get_parameters()
+
+    @staticmethod
+    def get_request():
+        return SpeechToTextRequest
+
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer
+
+
+class PlayDemoTextAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return ApplicationOperateAPI.get_parameters()
+
+    @staticmethod
+    def get_request():
+        return PlayDemoTextRequest
+
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer

+ 61 - 0
apps/application/api/application_api_key.py

@@ -0,0 +1,61 @@
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_api_key import EditApplicationKeySerializer, ApplicationKeySerializerModel
+from common.mixins.api_mixin import APIMixin
+from common.result import ResultSerializer
+
+
+class ApplicationKeyListResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationKeySerializerModel(many=True)
+
+
+class ApplicationKeyResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationKeySerializerModel()
+
+
+class ApplicationKeyAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationKeyResult
+
+    class List(APIMixin):
+        @staticmethod
+        def get_response():
+            return ApplicationKeyListResult
+
+    class Operate(APIMixin):
+        @staticmethod
+        def get_parameters():
+            return [*ApplicationKeyAPI.get_parameters(), OpenApiParameter(
+                name="api_key_id",
+                description="ApiKeyId",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )]
+
+        @staticmethod
+        def get_request():
+            return EditApplicationKeySerializer

+ 141 - 0
apps/application/api/application_chat.py

@@ -0,0 +1,141 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application_chat.py
+    @date:2025/6/10 13:54
+    @desc:
+"""
+from django.utils.translation import gettext_lazy as _
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_chat import ApplicationChatQuerySerializers, \
+    ApplicationChatResponseSerializers, ApplicationChatRecordExportRequest
+from common.mixins.api_mixin import APIMixin
+from common.result import ResultSerializer, ResultPageSerializer
+
+
+class ApplicationChatListResponseSerializers(ResultSerializer):
+    def get_data(self):
+        return ApplicationChatResponseSerializers(many=True)
+
+
+class ApplicationChatPageResponseSerializers(ResultPageSerializer):
+    def get_data(self):
+        return ApplicationChatResponseSerializers(many=True)
+
+
+class ApplicationChatQueryAPI(APIMixin):
+    @staticmethod
+    def get_request():
+        return ApplicationChatQuerySerializers
+
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ), OpenApiParameter(
+                name="start_time",
+                description="start Time",
+                type=OpenApiTypes.STR,
+                required=True,
+            ),
+            OpenApiParameter(
+                name="end_time",
+                description="end Time",
+                type=OpenApiTypes.STR,
+                required=True,
+            ),
+            OpenApiParameter(
+                name="abstract",
+                description="summary",
+                type=OpenApiTypes.STR,
+                required=False,
+            ),
+            OpenApiParameter(
+                name="username",
+                description="username",
+                type=OpenApiTypes.STR,
+                required=False,
+            ),
+            OpenApiParameter(
+                name="min_star",
+                description=_("Minimum number of likes"),
+                type=OpenApiTypes.INT,
+                required=False,
+            ),
+            OpenApiParameter(
+                name="min_trample",
+                description=_("Minimum number of clicks"),
+                type=OpenApiTypes.INT,
+                required=False,
+            ),
+            OpenApiParameter(
+                name="comparer",
+                description=_("Comparator"),
+                type=OpenApiTypes.STR,
+                required=False,
+            ),
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationChatListResponseSerializers
+
+
+class ApplicationChatQueryPageAPI(APIMixin):
+    @staticmethod
+    def get_request():
+        return ApplicationChatQueryAPI.get_request()
+
+    @staticmethod
+    def get_parameters():
+        return [
+            *ApplicationChatQueryAPI.get_parameters(),
+            OpenApiParameter(
+                name="current_page",
+                description=_("Current page"),
+                type=OpenApiTypes.INT,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="page_size",
+                description=_("Page size"),
+                type=OpenApiTypes.INT,
+                location='path',
+                required=True,
+            ),
+
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationChatPageResponseSerializers
+
+
+class ApplicationChatExportAPI(APIMixin):
+    @staticmethod
+    def get_request():
+        return ApplicationChatRecordExportRequest
+
+    @staticmethod
+    def get_parameters():
+        return ApplicationChatQueryAPI.get_parameters()
+
+    @staticmethod
+    def get_response():
+        return None

+ 62 - 0
apps/application/api/application_chat_link.py

@@ -0,0 +1,62 @@
+"""
+    @project: MaxKB
+    @Author: niu
+    @file: application_chat_link.py
+    @date: 2026/2/9 16:59
+    @desc:
+"""
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+from django.utils.translation import gettext_lazy as _
+
+from application.serializers.application_chat_link import ChatRecordShareLinkRequestSerializer
+from common.mixins.api_mixin import APIMixin
+from common.result import DefaultResultSerializer
+
+
+class ChatRecordLinkAPI(APIMixin):
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer
+
+    @staticmethod
+    def get_request():
+        return ChatRecordShareLinkRequestSerializer
+
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="application_id",
+                description="Application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="chat_id",
+                description=_("Chat ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+        ]
+
+class ChatRecordDetailShareAPI(APIMixin):
+    @staticmethod
+    def get_response():
+        return DefaultResultSerializer
+
+
+
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="link",
+                description="链接",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]

+ 180 - 0
apps/application/api/application_chat_record.py

@@ -0,0 +1,180 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application_chat_record.py
+    @date:2025/6/10 15:19
+    @desc:
+"""
+from django.utils.translation import gettext_lazy as _
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_chat_record import ApplicationChatRecordAddKnowledgeSerializer, \
+    ApplicationChatRecordImproveInstanceSerializer
+from common.mixins.api_mixin import APIMixin
+
+
+class ApplicationChatRecordQueryAPI(APIMixin):
+    @staticmethod
+    def get_response():
+        pass
+
+    @staticmethod
+    def get_request():
+        pass
+
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="Application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="chat_id",
+                description=_("Chat ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="order_asc",
+                description=_("Is it in order"),
+                type=OpenApiTypes.BOOL,
+                required=True,
+            )
+        ]
+
+
+class ApplicationChatRecordPageQueryAPI(APIMixin):
+    @staticmethod
+    def get_response():
+        pass
+
+    @staticmethod
+    def get_request():
+        pass
+
+    @staticmethod
+    def get_parameters():
+        return [*ApplicationChatRecordQueryAPI.get_parameters(),
+                OpenApiParameter(
+                    name="current_page",
+                    description=_("Current page"),
+                    type=OpenApiTypes.INT,
+                    location='path',
+                    required=True,
+                ),
+                OpenApiParameter(
+                    name="page_size",
+                    description=_("Page size"),
+                    type=OpenApiTypes.INT,
+                    location='path',
+                    required=True,
+                )]
+
+
+class ApplicationChatRecordImproveParagraphAPI(APIMixin):
+    @staticmethod
+    def get_response():
+        pass
+
+    @staticmethod
+    def get_request():
+        return ApplicationChatRecordImproveInstanceSerializer
+
+    @staticmethod
+    def get_parameters():
+        return [OpenApiParameter(
+            name="workspace_id",
+            description="工作空间id",
+            type=OpenApiTypes.STR,
+            location='path',
+            required=True,
+        ),
+            OpenApiParameter(
+                name="application_id",
+                description="Application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="chat_id",
+                description=_("Chat ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="chat_record_id",
+                description=_("Chat Record ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="knowledge_id",
+                description=_("Knowledge ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="document_id",
+                description=_("Document ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+
+    class Operate(APIMixin):
+        @staticmethod
+        def get_parameters():
+            return [*ApplicationChatRecordImproveParagraphAPI.get_parameters(), OpenApiParameter(
+                name="paragraph_id",
+                description=_("Paragraph ID"),
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )]
+
+
+class ApplicationChatRecordAddKnowledgeAPI(APIMixin):
+    @staticmethod
+    def get_request():
+        return ApplicationChatRecordAddKnowledgeSerializer
+
+    @staticmethod
+    def get_response():
+        return None
+
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="Application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )]

+ 55 - 0
apps/application/api/application_stats.py

@@ -0,0 +1,55 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application_stats.py
+    @date:2025/6/9 20:45
+    @desc:
+"""
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_stats import ApplicationStatsSerializer
+from common.mixins.api_mixin import APIMixin
+from common.result import ResultSerializer
+
+
+class ApplicationStatsResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationStatsSerializer(many=True)
+
+
+class ApplicationStatsAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [OpenApiParameter(
+            name="workspace_id",
+            description="工作空间id",
+            type=OpenApiTypes.STR,
+            location='path',
+            required=True,
+        ),
+            OpenApiParameter(
+                name="application_id",
+                description="application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="start_time",
+                description="start Time",
+                type=OpenApiTypes.STR,
+                required=True,
+            ),
+            OpenApiParameter(
+                name="end_time",
+                description="end Time",
+                type=OpenApiTypes.STR,
+                required=True,
+            ),
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationStatsResult

+ 96 - 0
apps/application/api/application_version.py

@@ -0,0 +1,96 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: application_version.py
+    @date:2025/6/4 17:33
+    @desc:
+"""
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+
+from application.serializers.application_version import ApplicationVersionModelSerializer
+from common.mixins.api_mixin import APIMixin
+from common.result import ResultSerializer, PageDataResponse, ResultPageSerializer
+
+
+class ApplicationListVersionResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationVersionModelSerializer(many=True)
+
+
+class ApplicationPageVersionResult(ResultPageSerializer):
+    def get_data(self):
+        return ApplicationVersionModelSerializer(many=True)
+
+
+class ApplicationWorkflowVersionResult(ResultSerializer):
+    def get_data(self):
+        return ApplicationVersionModelSerializer()
+
+
+class ApplicationVersionAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="workspace_id",
+                description="工作空间id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            ),
+            OpenApiParameter(
+                name="application_id",
+                description="application ID",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+        ]
+
+
+class ApplicationVersionOperateAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="application_version_id",
+                description="工作流版本id",
+                type=OpenApiTypes.STR,
+                location='path',
+                required=True,
+            )
+            , *ApplicationVersionAPI.get_parameters()
+        ]
+
+    @staticmethod
+    def get_response():
+        return ApplicationWorkflowVersionResult
+
+
+class ApplicationVersionListAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return [
+            OpenApiParameter(
+                name="name",
+                description="Version Name",
+                type=OpenApiTypes.STR,
+                required=False,
+            )
+            , *ApplicationVersionAPI.get_parameters()]
+
+    @staticmethod
+    def get_response():
+        return ApplicationListVersionResult
+
+
+class ApplicationVersionPageAPI(APIMixin):
+    @staticmethod
+    def get_parameters():
+        return ApplicationVersionListAPI.get_parameters()
+
+    @staticmethod
+    def get_response():
+        return ApplicationPageVersionResult

+ 6 - 0
apps/application/apps.py

@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class ApplicationConfig(AppConfig):
+    default_auto_field = 'django.db.models.BigAutoField'
+    name = 'application'

+ 185 - 0
apps/application/chat_pipeline/I_base_chat_pipeline.py

@@ -0,0 +1,185 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: I_base_chat_pipeline.py
+    @date:2024/1/9 17:25
+    @desc:
+"""
+import time
+from abc import abstractmethod
+from typing import Type
+import uuid_utils.compat as uuid
+from rest_framework import serializers
+
+from knowledge.models import Paragraph
+
+
+class ParagraphPipelineModel:
+
+    def __init__(self, _id: str, document_id: str, knowledge_id: str, content: str, title: str, status: str,
+                 is_active: bool, comprehensive_score: float, similarity: float, knowledge_name: str,
+                 document_name: str,
+                 hit_handling_method: str, directly_return_similarity: float, knowledge_type, meta: dict = None):
+        self.id = _id
+        self.document_id = document_id
+        self.knowledge_id = knowledge_id
+        self.content = content
+        self.title = title
+        self.status = status,
+        self.is_active = is_active
+        self.comprehensive_score = comprehensive_score
+        self.similarity = similarity
+        self.knowledge_name = knowledge_name
+        self.document_name = document_name
+        self.hit_handling_method = hit_handling_method
+        self.directly_return_similarity = directly_return_similarity
+        self.meta = meta
+        self.knowledge_type = knowledge_type
+
+    def to_dict(self):
+        return {
+            'id': self.id,
+            'document_id': self.document_id,
+            'knowledge_id': self.knowledge_id,
+            'content': self.content,
+            'title': self.title,
+            'status': self.status,
+            'is_active': self.is_active,
+            'comprehensive_score': self.comprehensive_score,
+            'similarity': self.similarity,
+            'knowledge_name': self.knowledge_name,
+            'document_name': self.document_name,
+            'knowledge_type': self.knowledge_type,
+            'meta': self.meta,
+        }
+
+    class builder:
+        def __init__(self):
+            self.similarity = None
+            self.paragraph = {}
+            self.comprehensive_score = None
+            self.document_name = None
+            self.knowledge_name = None
+            self.knowledge_type = None
+            self.hit_handling_method = None
+            self.directly_return_similarity = 0.9
+            self.meta = {}
+
+        def add_paragraph(self, paragraph):
+            if isinstance(paragraph, Paragraph):
+                self.paragraph = {'id': paragraph.id,
+                                  'document_id': paragraph.document_id,
+                                  'knowledge_id': paragraph.knowledge_id,
+                                  'content': paragraph.content,
+                                  'title': paragraph.title,
+                                  'status': paragraph.status,
+                                  'is_active': paragraph.is_active,
+                                  }
+            else:
+                self.paragraph = paragraph
+            return self
+
+        def add_knowledge_name(self, knowledge_name):
+            self.knowledge_name = knowledge_name
+            return self
+
+        def add_knowledge_type(self, knowledge_type):
+            self.knowledge_type = knowledge_type
+            return self
+
+        def add_document_name(self, document_name):
+            self.document_name = document_name
+            return self
+
+        def add_hit_handling_method(self, hit_handling_method):
+            self.hit_handling_method = hit_handling_method
+            return self
+
+        def add_directly_return_similarity(self, directly_return_similarity):
+            self.directly_return_similarity = directly_return_similarity
+            return self
+
+        def add_comprehensive_score(self, comprehensive_score: float):
+            self.comprehensive_score = comprehensive_score
+            return self
+
+        def add_similarity(self, similarity: float):
+            self.similarity = similarity
+            return self
+
+        def add_meta(self, meta: dict):
+            self.meta = meta
+            return self
+
+        def build(self):
+            return ParagraphPipelineModel(str(self.paragraph.get('id')), str(self.paragraph.get('document_id')),
+                                          str(self.paragraph.get('knowledge_id')),
+                                          self.paragraph.get('content'), self.paragraph.get('title'),
+                                          self.paragraph.get('status'),
+                                          self.paragraph.get('is_active'),
+                                          self.comprehensive_score, self.similarity, self.knowledge_name,
+                                          self.document_name, self.hit_handling_method, self.directly_return_similarity,
+                                          self.knowledge_type,
+                                          self.meta)
+
+
+class IBaseChatPipelineStep:
+    def __init__(self):
+        # 当前步骤上下文,用于存储当前步骤信息
+        self.context = {}
+        self.status = 200
+        self.err_message = ''
+
+    @abstractmethod
+    def get_step_serializer(self, manage) -> Type[serializers.Serializer]:
+        pass
+
+    def valid_args(self, manage):
+        step_serializer_clazz = self.get_step_serializer(manage)
+        step_serializer = step_serializer_clazz(data=manage.context)
+        step_serializer.is_valid(raise_exception=True)
+        self.context['step_args'] = step_serializer.data
+
+    def run(self, manage):
+        """
+
+        :param manage:      步骤管理器
+        :return: 执行结果
+        """
+        try:
+            start_time = time.time()
+            self.context['start_time'] = start_time
+            # 校验参数,
+            self.valid_args(manage)
+            self._run(manage)
+            self.context['run_time'] = time.time() - start_time
+        except Exception as e:
+            self.err_message = str(e)
+            self.status = 500
+            chat_record_id = manage.context.get('chat_record_id') or str(uuid.uuid7())
+            manage.context['message_tokens'] = 0
+            manage.context['answer_tokens'] = 0
+            end_time = time.time()
+            manage.context['run_time'] = end_time - (manage.context.get('start_time') or end_time)
+            post_response_handler = manage.context.get('post_response_handler')
+            post_response_handler.handler(manage.context.get('chat_id'), chat_record_id,
+                                          manage.context.get('paragraph_list') or [],
+                                          manage.context.get('problem_text'),
+                                          str(e), manage, self, manage.context.get('padding_problem_text'),
+                                          reasoning_content='')
+
+            raise e
+
+    def _run(self, manage):
+        pass
+
+    def execute(self, **kwargs):
+        pass
+
+    def get_details(self, manage, **kwargs):
+        """
+        运行详情
+        :return: 步骤详情
+        """
+        return None

+ 8 - 0
apps/application/chat_pipeline/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 17:23
+    @desc:
+"""

+ 66 - 0
apps/application/chat_pipeline/pipeline_manage.py

@@ -0,0 +1,66 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: pipeline_manage.py
+    @date:2024/1/9 17:40
+    @desc:
+"""
+import time
+from functools import reduce
+from typing import List, Type, Dict
+
+from application.chat_pipeline.I_base_chat_pipeline import IBaseChatPipelineStep
+from common.handle.base_to_response import BaseToResponse
+from common.handle.impl.response.system_to_response import SystemToResponse
+
+
+class PipelineManage:
+    def __init__(self, step_list: List[Type[IBaseChatPipelineStep]],
+                 base_to_response: BaseToResponse = SystemToResponse(),
+                 debug=False):
+        # 步骤执行器
+        self.step_list = [step() for step in step_list]
+        self.run_step_list = []
+        # 上下文
+        self.context = {'message_tokens': 0, 'answer_tokens': 0}
+        self.base_to_response = base_to_response
+        self.debug = debug
+
+    def run(self, context: Dict = None):
+        self.context['start_time'] = time.time()
+        if context is not None:
+            for key, value in context.items():
+                self.context[key] = value
+        for step in self.step_list:
+            self.run_step_list.append(step)
+            step.run(self)
+
+    def get_details(self):
+        return reduce(lambda x, y: {**x, **y}, [{item.get('step_type'): item} for item in
+                                                filter(lambda r: r is not None,
+                                                       [row.get_details(self) for row in self.run_step_list])], {})
+
+    def get_base_to_response(self):
+        return self.base_to_response
+
+    class builder:
+        def __init__(self):
+            self.step_list: List[Type[IBaseChatPipelineStep]] = []
+            self.base_to_response = SystemToResponse()
+            self.debug = False
+
+        def append_step(self, step: Type[IBaseChatPipelineStep]):
+            self.step_list.append(step)
+            return self
+
+        def add_base_to_response(self, base_to_response: BaseToResponse):
+            self.base_to_response = base_to_response
+            return self
+
+        def add_debug(self, debug):
+            self.debug = debug
+            return self
+
+        def build(self):
+            return PipelineManage(step_list=self.step_list, base_to_response=self.base_to_response, debug=self.debug)

+ 8 - 0
apps/application/chat_pipeline/step/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 18:23
+    @desc:
+"""

+ 8 - 0
apps/application/chat_pipeline/step/chat_step/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 18:23
+    @desc:
+"""

+ 121 - 0
apps/application/chat_pipeline/step/chat_step/i_chat_step.py

@@ -0,0 +1,121 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_chat_step.py
+    @date:2024/1/9 18:17
+    @desc: 对话
+"""
+from abc import abstractmethod
+from typing import Type, List
+
+from django.utils.translation import gettext_lazy as _
+from langchain.chat_models.base import BaseChatModel
+from langchain_core.messages import BaseMessage
+from rest_framework import serializers
+
+from application.chat_pipeline.I_base_chat_pipeline import IBaseChatPipelineStep, ParagraphPipelineModel
+from application.chat_pipeline.pipeline_manage import PipelineManage
+from application.serializers.application import NoReferencesSetting
+from common.field.common import InstanceField
+
+
+class ModelField(serializers.Field):
+    def to_internal_value(self, data):
+        if not isinstance(data, BaseChatModel):
+            self.fail(_('Model type error'), value=data)
+        return data
+
+    def to_representation(self, value):
+        return value
+
+
+class MessageField(serializers.Field):
+    def to_internal_value(self, data):
+        if not isinstance(data, BaseMessage):
+            self.fail(_('Message type error'), value=data)
+        return data
+
+    def to_representation(self, value):
+        return value
+
+
+class PostResponseHandler:
+    @abstractmethod
+    def handler(self, chat_id, chat_record_id, paragraph_list: List[ParagraphPipelineModel], problem_text: str,
+                answer_text,
+                manage, step, padding_problem_text: str = None, **kwargs):
+        pass
+
+
+class IChatStep(IBaseChatPipelineStep):
+    class InstanceSerializer(serializers.Serializer):
+        # 对话列表
+        message_list = serializers.ListField(required=True, child=MessageField(required=True),
+                                             label=_("Conversation list"))
+        model_id = serializers.UUIDField(required=False, allow_null=True, label=_("Model id"))
+        # 段落列表
+        paragraph_list = serializers.ListField(label=_("Paragraph List"))
+        # 对话id
+        chat_id = serializers.UUIDField(required=True, label=_("Conversation ID"))
+        # 用户问题
+        problem_text = serializers.CharField(required=True, label=_("User Questions"))
+        # 后置处理器
+        post_response_handler = InstanceField(model_type=PostResponseHandler,
+                                              label=_("Post-processor"))
+        # 补全问题
+        padding_problem_text = serializers.CharField(required=False,
+                                                     label=_("Completion Question"))
+        # 是否使用流的形式输出
+        stream = serializers.BooleanField(required=False, label=_("Streaming Output"))
+        chat_user_id = serializers.CharField(required=True, label=_("Chat user id"))
+        chat_record_id = serializers.CharField(required=False, label=_("Chat record id"))
+
+        chat_user_type = serializers.CharField(required=True, label=_("Chat user Type"))
+        # 未查询到引用分段
+        no_references_setting = NoReferencesSetting(required=True,
+                                                    label=_("No reference segment settings"))
+
+        workspace_id = serializers.CharField(required=True, label=_("Workspace ID"))
+
+        model_setting = serializers.DictField(required=True, allow_null=True,
+                                              label=_("Model settings"))
+
+        model_params_setting = serializers.DictField(required=False, allow_null=True,
+                                                     label=_("Model parameter settings"))
+        mcp_tool_ids = serializers.JSONField(label="MCP工具ID列表", required=False, default=list)
+        mcp_servers = serializers.JSONField(label="MCP服务列表", required=False, default=dict)
+        mcp_source = serializers.CharField(label="MCP Source", required=False, default="referencing")
+        tool_ids = serializers.JSONField(label="工具ID列表", required=False, default=list)
+        application_ids = serializers.JSONField(label="应用ID列表", required=False, default=list)
+        skill_tool_ids = serializers.JSONField(label="技能ID列表", required=False, default=list)
+        mcp_output_enable = serializers.BooleanField(label="MCP输出是否启用", required=False, default=True)
+
+        def is_valid(self, *, raise_exception=False):
+            super().is_valid(raise_exception=True)
+            message_list: List = self.initial_data.get('message_list')
+            for message in message_list:
+                if not isinstance(message, BaseMessage):
+                    raise Exception(_("message type error"))
+
+    def get_step_serializer(self, manage: PipelineManage) -> Type[serializers.Serializer]:
+        return self.InstanceSerializer
+
+    def _run(self, manage: PipelineManage):
+        chat_result = self.execute(**self.context['step_args'], manage=manage)
+        manage.context['chat_result'] = chat_result
+
+    @abstractmethod
+    def execute(self, message_list: List[BaseMessage],
+                chat_id, problem_text,
+                post_response_handler: PostResponseHandler,
+                model_id: str = None,
+                workspace_id: str = None,
+                paragraph_list=None,
+                manage: PipelineManage = None,
+                padding_problem_text: str = None, stream: bool = True, chat_user_id=None, chat_user_type=None,
+                no_references_setting=None, model_params_setting=None, model_setting=None,
+                mcp_tool_ids=None, mcp_servers='', mcp_source="referencing",
+                tool_ids=None, application_ids=None, skill_tool_ids=None, mcp_output_enable=True,
+                **kwargs):
+        pass

+ 541 - 0
apps/application/chat_pipeline/step/chat_step/impl/base_chat_step.py

@@ -0,0 +1,541 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_chat_step.py
+    @date:2024/1/9 18:25
+    @desc: 对话step Base实现
+"""
+import json
+import time
+import traceback
+from typing import List
+
+import uuid_utils.compat as uuid
+from django.db.models import QuerySet
+from django.http import StreamingHttpResponse
+from django.utils.translation import gettext as _
+from langchain.chat_models.base import BaseChatModel
+from langchain_core.messages import AIMessageChunk, SystemMessage, BaseMessage, HumanMessage, AIMessage
+from rest_framework import status
+
+from application.chat_pipeline.I_base_chat_pipeline import ParagraphPipelineModel
+from application.chat_pipeline.pipeline_manage import PipelineManage
+from application.chat_pipeline.step.chat_step.i_chat_step import IChatStep, PostResponseHandler
+from application.flow.tools import Reasoning, mcp_response_generator, get_tools
+from application.models import ApplicationChatUserStats, ChatUserType, Application, ApplicationApiKey, \
+    ApplicationAccessToken
+from common.exception.app_exception import AppApiException
+from common.utils.logger import maxkb_logger
+from common.utils.rsa_util import rsa_long_decrypt
+from common.utils.shared_resource_auth import filter_authorized_ids
+from common.utils.tool_code import ToolExecutor
+from models_provider.tools import get_model_instance_by_model_workspace_id
+from tools.models import Tool, ToolType
+
+
+def add_access_num(chat_user_id=None, chat_user_type=None, application_id=None):
+    if [ChatUserType.ANONYMOUS_USER.value, ChatUserType.CHAT_USER.value].__contains__(
+            chat_user_type) and application_id is not None:
+        application_public_access_client = (QuerySet(ApplicationChatUserStats).filter(chat_user_id=chat_user_id,
+                                                                                      chat_user_type=chat_user_type,
+                                                                                      application_id=application_id)
+                                            .first())
+        if application_public_access_client is not None:
+            application_public_access_client.access_num = application_public_access_client.access_num + 1
+            application_public_access_client.intraday_access_num = application_public_access_client.intraday_access_num + 1
+            application_public_access_client.save()
+
+
+def write_context(step, manage, request_token, response_token, all_text):
+    step.context['message_tokens'] = request_token
+    step.context['answer_tokens'] = response_token
+    current_time = time.time()
+    step.context['answer_text'] = all_text
+    step.context['run_time'] = current_time - step.context['start_time']
+    manage.context['run_time'] = current_time - manage.context['start_time']
+    manage.context['message_tokens'] = manage.context['message_tokens'] + request_token
+    manage.context['answer_tokens'] = manage.context['answer_tokens'] + response_token
+
+
+def event_content(response,
+                  chat_id,
+                  chat_record_id,
+                  paragraph_list: List[ParagraphPipelineModel],
+                  post_response_handler: PostResponseHandler,
+                  manage,
+                  step,
+                  chat_model,
+                  message_list: List[BaseMessage],
+                  problem_text: str,
+                  padding_problem_text: str = None,
+                  chat_user_id=None, chat_user_type=None,
+                  is_ai_chat: bool = None,
+                  model_setting=None):
+    if model_setting is None:
+        model_setting = {}
+    reasoning_content_enable = model_setting.get('reasoning_content_enable', False)
+    reasoning_content_start = model_setting.get('reasoning_content_start', '<think>')
+    reasoning_content_end = model_setting.get('reasoning_content_end', '</think>')
+    reasoning = Reasoning(reasoning_content_start,
+                          reasoning_content_end)
+    all_text = ''
+    reasoning_content = ''
+    try:
+        response_reasoning_content = False
+        for chunk in response:
+            reasoning_chunk = reasoning.get_reasoning_content(chunk)
+            content_chunk = reasoning_chunk.get('content')
+            if 'reasoning_content' in chunk.additional_kwargs:
+                response_reasoning_content = True
+                reasoning_content_chunk = chunk.additional_kwargs.get('reasoning_content', '')
+            else:
+                reasoning_content_chunk = reasoning_chunk.get('reasoning_content')
+            content_chunk = reasoning._normalize_content(content_chunk)
+            all_text += content_chunk
+            if reasoning_content_chunk is None:
+                reasoning_content_chunk = ''
+            reasoning_content += reasoning_content_chunk
+            yield manage.get_base_to_response().to_stream_chunk_response(chat_id, str(chat_record_id), 'ai-chat-node',
+                                                                         [], content_chunk,
+                                                                         False,
+                                                                         0, 0, {'node_is_end': False,
+                                                                                'view_type': 'many_view',
+                                                                                'node_type': 'ai-chat-node',
+                                                                                'real_node_id': 'ai-chat-node',
+                                                                                'reasoning_content': reasoning_content_chunk if reasoning_content_enable else ''})
+        reasoning_chunk = reasoning.get_end_reasoning_content()
+        all_text += reasoning_chunk.get('content')
+        reasoning_content_chunk = ""
+        if not response_reasoning_content:
+            reasoning_content_chunk = reasoning_chunk.get(
+                'reasoning_content')
+        yield manage.get_base_to_response().to_stream_chunk_response(chat_id, str(chat_record_id), 'ai-chat-node',
+                                                                     [], reasoning_chunk.get('content'),
+                                                                     False,
+                                                                     0, 0, {'node_is_end': False,
+                                                                            'view_type': 'many_view',
+                                                                            'node_type': 'ai-chat-node',
+                                                                            'real_node_id': 'ai-chat-node',
+                                                                            'reasoning_content'
+                                                                            : reasoning_content_chunk if reasoning_content_enable else ''})
+        # 获取token
+        if is_ai_chat:
+            try:
+                request_token = chat_model.get_num_tokens_from_messages(message_list)
+                response_token = chat_model.get_num_tokens(all_text)
+            except Exception as e:
+                request_token = 0
+                response_token = 0
+        else:
+            request_token = 0
+            response_token = 0
+        write_context(step, manage, request_token, response_token, all_text)
+        post_response_handler.handler(chat_id, chat_record_id, paragraph_list, problem_text,
+                                      all_text, manage, step, padding_problem_text,
+                                      reasoning_content=reasoning_content if reasoning_content_enable else '')
+        yield manage.get_base_to_response().to_stream_chunk_response(chat_id, str(chat_record_id), 'ai-chat-node',
+                                                                     [], '', True,
+                                                                     request_token, response_token,
+                                                                     {'node_is_end': True, 'view_type': 'many_view',
+                                                                      'node_type': 'ai-chat-node'})
+        if not manage.debug:
+            add_access_num(chat_user_id, chat_user_type, manage.context.get('application_id'))
+    except Exception as e:
+        maxkb_logger.error(f'{str(e)}:{traceback.format_exc()}')
+        all_text = 'Exception:' + str(e)
+        write_context(step, manage, 0, 0, all_text)
+        post_response_handler.handler(chat_id, chat_record_id, paragraph_list, problem_text,
+                                      all_text, manage, step, padding_problem_text, reasoning_content='')
+        if not manage.debug:
+            add_access_num(chat_user_id, chat_user_type, manage.context.get('application_id'))
+        yield manage.get_base_to_response().to_stream_chunk_response(chat_id, str(chat_record_id), 'ai-chat-node',
+                                                                     [], all_text,
+                                                                     False,
+                                                                     0, 0, {'node_is_end': False,
+                                                                            'view_type': 'many_view',
+                                                                            'node_type': 'ai-chat-node',
+                                                                            'real_node_id': 'ai-chat-node',
+                                                                            'reasoning_content': ''})
+
+
+class BaseChatStep(IChatStep):
+    def execute(self, message_list: List[BaseMessage],
+                chat_id,
+                problem_text,
+                post_response_handler: PostResponseHandler,
+                model_id: str = None,
+                workspace_id: str = None,
+                paragraph_list=None,
+                manage: PipelineManage = None,
+                padding_problem_text: str = None,
+                stream: bool = True,
+                chat_user_id=None, chat_user_type=None,
+                no_references_setting=None,
+                model_params_setting=None,
+                model_setting=None,
+                mcp_tool_ids=None,
+                mcp_servers='',
+                mcp_source="referencing",
+                tool_ids=None,
+                application_ids=None,
+                skill_tool_ids=None,
+                mcp_output_enable=True,
+                **kwargs):
+        chat_model = get_model_instance_by_model_workspace_id(model_id, workspace_id,
+                                                              **(model_params_setting or {})) if model_id is not None else None
+        if stream:
+            return self.execute_stream(message_list, chat_id, problem_text, post_response_handler, chat_model,
+                                       paragraph_list,
+                                       manage, padding_problem_text, chat_user_id, chat_user_type,
+                                       no_references_setting,
+                                       model_setting,
+                                       mcp_tool_ids, mcp_servers, mcp_source, tool_ids,
+                                       application_ids,
+                                       skill_tool_ids,
+                                       workspace_id,
+                                       mcp_output_enable)
+        else:
+            return self.execute_block(message_list, chat_id, problem_text, post_response_handler, chat_model,
+                                      paragraph_list,
+                                      manage, padding_problem_text, chat_user_id, chat_user_type, no_references_setting,
+                                      model_setting,
+                                      mcp_tool_ids, mcp_servers, mcp_source, tool_ids,
+                                      application_ids,
+                                      skill_tool_ids,
+                                      workspace_id,
+                                      mcp_output_enable)
+
+    def get_details(self, manage, **kwargs):
+        return {
+            'status': self.status,
+            'err_message': self.err_message,
+            'step_type': 'chat_step',
+            'run_time': self.context.get('run_time') or 0,
+            'model_id': str(manage.context['model_id']),
+            'message_list': self.reset_message_list(self.context['step_args'].get('message_list'),
+                                                    self.context.get('answer_text')),
+            'message_tokens': self.context.get('message_tokens'),
+            'answer_tokens': self.context.get('answer_tokens'),
+            'cost': 0,
+        }
+
+    @staticmethod
+    def reset_message_list(message_list: List[BaseMessage], answer_text):
+        result = [{'role': 'user' if isinstance(message, HumanMessage) else (
+            'system' if isinstance(message, SystemMessage) else 'ai'), 'content': message.content} for
+                  message
+                  in
+                  message_list]
+        result.append({'role': 'ai', 'content': answer_text})
+        return result
+
+    def _handle_mcp_request(self, mcp_source, mcp_servers, mcp_tool_ids, tool_ids,
+                            application_ids, skill_tool_ids, mcp_output_enable, chat_model, message_list, agent_id,
+                            chat_id, workspace_id):
+
+        mcp_servers_config = {}
+
+        # 迁移过来mcp_source是None
+        if mcp_source is None:
+            mcp_source = 'custom'
+        # 兼容老数据
+        if not mcp_tool_ids:
+            mcp_tool_ids = []
+        if mcp_source == 'custom' and mcp_servers:
+            ToolExecutor().validate_mcp_transport(mcp_servers)
+            mcp_servers_config = json.loads(mcp_servers)
+        elif mcp_tool_ids:
+            mcp_tools = QuerySet(Tool).filter(id__in=mcp_tool_ids).values()
+            for mcp_tool in mcp_tools:
+                if mcp_tool and mcp_tool['is_active']:
+                    mcp_servers_config = {**mcp_servers_config, **json.loads(mcp_tool['code'])}
+
+        tool_init_params = {}
+        tools = get_tools("APPLICATION", agent_id, tool_ids,
+                          workspace_id)
+        if tool_ids and len(tool_ids) > 0:  # 如果有工具ID,则将其转换为MCP
+            self.context['tool_ids'] = tool_ids
+            for tool_id in tool_ids:
+                tool = QuerySet(Tool).filter(id=tool_id, tool_type=ToolType.CUSTOM).first()
+                if tool is None or tool.is_active is False:
+                    continue
+                executor = ToolExecutor()
+                if tool.init_params is not None:
+                    params = json.loads(rsa_long_decrypt(tool.init_params))
+                    tool_init_params = json.loads(rsa_long_decrypt(tool.init_params))
+                else:
+                    params = {}
+                tool_config = executor.get_tool_mcp_config(tool, params)
+
+                mcp_servers_config[str(tool.id)] = tool_config
+
+        if application_ids and len(application_ids) > 0:
+            self.context['application_ids'] = application_ids
+            for application_id in application_ids:
+                app = QuerySet(Application).filter(id=application_id, is_publish=True).first()
+                if app is None:
+                    continue
+                app_key = QuerySet(ApplicationApiKey).filter(application_id=application_id, is_active=True).first()
+                if app_key is not None:
+                    api_key = app_key.secret_key
+                    application_access_token = QuerySet(ApplicationAccessToken).filter(
+                        application_id=app_key.application_id
+                    ).first()
+                    if application_access_token is not None and application_access_token.authentication:
+                        raise AppApiException(
+                            500,
+                            _('Agent 【{name}】 access token authentication is not supported for agent tool').format(
+                                name=app.name)
+                        )
+                else:
+                    raise AppApiException(
+                        500,
+                        _('Agent Key is required for agent tool 【{name}】').format(name=app.name)
+                    )
+                executor = ToolExecutor()
+                app_config = executor.get_app_mcp_config(api_key)
+                mcp_servers_config[app.name] = app_config
+
+        if skill_tool_ids and len(skill_tool_ids) > 0:
+            self.context['skill_tool_ids'] = skill_tool_ids
+            skill_file_items = []
+
+            for tool_id in skill_tool_ids:
+                tool = QuerySet(Tool).filter(id=tool_id, is_active=True).first()
+                if tool is None or tool.is_active is False:
+                    continue
+                init_params_default_value = {i["field"]: i.get('default_value') for i in tool.init_field_list}
+                if tool.init_params is not None:
+                    params = init_params_default_value | json.loads(rsa_long_decrypt(tool.init_params))
+                else:
+                    params = init_params_default_value
+
+                skill_file_items.append({
+                    'tool_id': str(tool.id),
+                    'file_id': tool.code,
+                    'params': params
+                })
+            mcp_servers_config['skills'] = skill_file_items
+
+        if len(mcp_servers_config) > 0 or len(tools) > 0:
+            source_id = agent_id
+            source_type = 'APPLICATION'
+            return mcp_response_generator(
+                chat_model, message_list, json.dumps(mcp_servers_config), mcp_output_enable,
+                tool_init_params, source_id, source_type, chat_id, tools
+            )
+
+        return None
+
+    def get_stream_result(self, message_list: List[BaseMessage],
+                          chat_model: BaseChatModel = None,
+                          paragraph_list=None,
+                          no_references_setting=None,
+                          problem_text=None,
+                          mcp_tool_ids=None,
+                          mcp_servers='',
+                          mcp_source="referencing",
+                          tool_ids=None,
+                          application_ids=None,
+                          skill_tool_ids=None,
+                          workspace_id=None,
+                          mcp_output_enable=True,
+                          agent_id=None,
+                          chat_id=None
+                          ):
+        if paragraph_list is None:
+            paragraph_list = []
+        directly_return_chunk_list = [AIMessageChunk(content=paragraph.content)
+                                      for paragraph in paragraph_list if (
+                                              paragraph.hit_handling_method == 'directly_return' and paragraph.similarity >= paragraph.directly_return_similarity)]
+        if directly_return_chunk_list is not None and len(directly_return_chunk_list) > 0:
+            return iter(directly_return_chunk_list), False
+        elif len(paragraph_list) == 0 and no_references_setting.get(
+                'status') == 'designated_answer':
+            return iter(
+                [AIMessageChunk(content=no_references_setting.get('value').replace('{question}', problem_text))]), False
+        if chat_model is None:
+            return iter([AIMessageChunk(
+                _('Sorry, the AI model is not configured. Please go to the application to set up the AI model first.'))]), False
+        else:
+            # 过滤tool_id
+            all_tool_ids = list(set(
+                (mcp_tool_ids or []) +
+                (tool_ids or []) +
+                (skill_tool_ids or [])
+            ))
+            authorized_set = set(filter_authorized_ids('tool', all_tool_ids, workspace_id))
+
+            mcp_tool_ids = [i for i in (mcp_tool_ids or []) if i in authorized_set]
+            tool_ids = [i for i in (tool_ids or []) if i in authorized_set]
+            skill_tool_ids = [i for i in (skill_tool_ids or []) if i in authorized_set]
+            # 处理 MCP 请求
+            mcp_result = self._handle_mcp_request(
+                mcp_source, mcp_servers, mcp_tool_ids, tool_ids,
+                application_ids, skill_tool_ids, mcp_output_enable, chat_model,
+                message_list, agent_id, chat_id, workspace_id
+            )
+            if mcp_result:
+                return mcp_result, True
+            return chat_model.stream(message_list), True
+
+    def execute_stream(self, message_list: List[BaseMessage],
+                       chat_id,
+                       problem_text,
+                       post_response_handler: PostResponseHandler,
+                       chat_model: BaseChatModel = None,
+                       paragraph_list=None,
+                       manage: PipelineManage = None,
+                       padding_problem_text: str = None,
+                       chat_user_id=None, chat_user_type=None,
+                       no_references_setting=None,
+                       model_setting=None,
+                       mcp_tool_ids=None,
+                       mcp_servers='',
+                       mcp_source="referencing",
+                       tool_ids=None,
+                       application_ids=None,
+                       skill_tool_ids=None,
+                       workspace_id=None,
+                       mcp_output_enable=True):
+        chat_result, is_ai_chat = self.get_stream_result(message_list, chat_model, paragraph_list,
+                                                         no_references_setting, problem_text, mcp_tool_ids,
+                                                         mcp_servers, mcp_source, tool_ids,
+                                                         application_ids, skill_tool_ids, workspace_id,
+                                                         mcp_output_enable, manage.context.get('application_id'),
+                                                         chat_id)
+        chat_record_id = self.context.get('step_args', {}).get('chat_record_id') if self.context.get('step_args',
+                                                                                                     {}).get(
+            'chat_record_id') else uuid.uuid7()
+        r = StreamingHttpResponse(
+            streaming_content=event_content(chat_result, chat_id, chat_record_id, paragraph_list,
+                                            post_response_handler, manage, self, chat_model, message_list, problem_text,
+                                            padding_problem_text, chat_user_id, chat_user_type, is_ai_chat,
+                                            model_setting),
+            content_type='text/event-stream;charset=utf-8')
+
+        r['Cache-Control'] = 'no-cache'
+        return r
+
+    def get_block_result(self, message_list: List[BaseMessage],
+                         chat_model: BaseChatModel = None,
+                         paragraph_list=None,
+                         no_references_setting=None,
+                         problem_text=None,
+                         mcp_tool_ids=None,
+                         mcp_servers='',
+                         mcp_source="referencing",
+                         tool_ids=None,
+                         application_ids=None,
+                         skill_tool_ids=None,
+                         workspace_id=None,
+                         mcp_output_enable=True,
+                         application_id=None,
+                         chat_id=None
+                         ):
+        if paragraph_list is None:
+            paragraph_list = []
+        directly_return_chunk_list = [AIMessageChunk(content=paragraph.content)
+                                      for paragraph in paragraph_list if (
+                                              paragraph.hit_handling_method == 'directly_return' and paragraph.similarity >= paragraph.directly_return_similarity)]
+        if directly_return_chunk_list is not None and len(directly_return_chunk_list) > 0:
+            return directly_return_chunk_list[0], False
+        elif len(paragraph_list) == 0 and no_references_setting.get(
+                'status') == 'designated_answer':
+            return AIMessage(no_references_setting.get('value').replace('{question}', problem_text)), False
+        if chat_model is None:
+            return AIMessage(
+                _('Sorry, the AI model is not configured. Please go to the application to set up the AI model first.')), False
+        else:
+            # 过滤tool_id
+            all_tool_ids = list(set(
+                (mcp_tool_ids or []) +
+                (tool_ids or []) +
+                (skill_tool_ids or [])
+            ))
+            authorized_set = set(filter_authorized_ids('tool', all_tool_ids, workspace_id))
+
+            mcp_tool_ids = [i for i in (mcp_tool_ids or []) if i in authorized_set]
+            tool_ids = [i for i in (tool_ids or []) if i in authorized_set]
+            skill_tool_ids = [i for i in (skill_tool_ids or []) if i in authorized_set]
+            # 处理 MCP 请求
+            mcp_result = self._handle_mcp_request(
+                mcp_source, mcp_servers, mcp_tool_ids, tool_ids,
+                application_ids, skill_tool_ids, mcp_output_enable,
+                chat_model, message_list, application_id, chat_id, workspace_id
+            )
+            if mcp_result:
+                return mcp_result, True
+            return chat_model.invoke(message_list), True
+
+    def execute_block(self, message_list: List[BaseMessage],
+                      chat_id,
+                      problem_text,
+                      post_response_handler: PostResponseHandler,
+                      chat_model: BaseChatModel = None,
+                      paragraph_list=None,
+                      manage: PipelineManage = None,
+                      padding_problem_text: str = None,
+                      chat_user_id=None, chat_user_type=None, no_references_setting=None,
+                      model_setting=None,
+                      mcp_tool_ids=None,
+                      mcp_servers='',
+                      mcp_source="referencing",
+                      tool_ids=None,
+                      application_ids=None,
+                      skill_tool_ids=None,
+                      workspace_id=None,
+                      mcp_output_enable=True):
+        reasoning_content_enable = model_setting.get('reasoning_content_enable', False)
+        reasoning_content_start = model_setting.get('reasoning_content_start', '<think>')
+        reasoning_content_end = model_setting.get('reasoning_content_end', '</think>')
+        reasoning = Reasoning(reasoning_content_start,
+                              reasoning_content_end)
+        chat_record_id = uuid.uuid7()
+        # 调用模型
+        try:
+            chat_result, is_ai_chat = self.get_block_result(message_list, chat_model, paragraph_list,
+                                                            no_references_setting, problem_text,
+                                                            mcp_tool_ids, mcp_servers, mcp_source,
+                                                            tool_ids, application_ids, skill_tool_ids, workspace_id,
+                                                            mcp_output_enable, manage.context.get('application_id'),
+                                                            chat_id)
+            if is_ai_chat:
+                request_token = chat_model.get_num_tokens_from_messages(message_list)
+                response_token = chat_model.get_num_tokens(chat_result.content)
+            else:
+                request_token = 0
+                response_token = 0
+            write_context(self, manage, request_token, response_token, chat_result.content)
+            reasoning_result = reasoning.get_reasoning_content(chat_result)
+            reasoning_result_end = reasoning.get_end_reasoning_content()
+            content = reasoning_result.get('content') + reasoning_result_end.get('content')
+            if 'reasoning_content' in chat_result.response_metadata:
+                reasoning_content = (chat_result.response_metadata.get('reasoning_content', '') or '')
+            else:
+                reasoning_content = (reasoning_result.get('reasoning_content') or "") + (reasoning_result_end.get(
+                    'reasoning_content') or "")
+            post_response_handler.handler(chat_id, chat_record_id, paragraph_list, problem_text,
+                                          content, manage, self, padding_problem_text,
+                                          reasoning_content=reasoning_content)
+            if not manage.debug:
+                add_access_num(chat_user_id, chat_user_type, manage.context.get('application_id'))
+            return manage.get_base_to_response().to_block_response(str(chat_id), str(chat_record_id),
+                                                                   content, True,
+                                                                   request_token, response_token,
+                                                                   {
+                                                                       'reasoning_content': reasoning_content if reasoning_content_enable else '',
+                                                                       'answer_list': [{
+                                                                           'content': content,
+                                                                           'reasoning_content': reasoning_content if reasoning_content_enable else ''
+                                                                       }]})
+        except Exception as e:
+            all_text = 'Exception:' + str(e)
+            write_context(self, manage, 0, 0, all_text)
+            post_response_handler.handler(chat_id, chat_record_id, paragraph_list, problem_text,
+                                          all_text, manage, self, padding_problem_text, reasoning_content='')
+            if not manage.debug:
+                add_access_num(chat_user_id, chat_user_type, manage.context.get('application_id'))
+            return manage.get_base_to_response().to_block_response(str(chat_id), str(chat_record_id), all_text, True, 0,
+                                                                   0, _status=status.HTTP_500_INTERNAL_SERVER_ERROR)

+ 8 - 0
apps/application/chat_pipeline/step/generate_human_message_step/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 18:23
+    @desc:
+"""

+ 82 - 0
apps/application/chat_pipeline/step/generate_human_message_step/i_generate_human_message_step.py

@@ -0,0 +1,82 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_generate_human_message_step.py
+    @date:2024/1/9 18:15
+    @desc: 生成对话模板
+"""
+from abc import abstractmethod
+from typing import Type, List
+
+from django.utils.translation import gettext_lazy as _
+from langchain_core.messages import BaseMessage
+from rest_framework import serializers
+
+from application.chat_pipeline.I_base_chat_pipeline import IBaseChatPipelineStep, ParagraphPipelineModel
+from application.chat_pipeline.pipeline_manage import PipelineManage
+from application.models import ChatRecord
+from application.serializers.application import NoReferencesSetting
+from common.field.common import InstanceField
+
+
+class IGenerateHumanMessageStep(IBaseChatPipelineStep):
+    class InstanceSerializer(serializers.Serializer):
+        # 问题
+        problem_text = serializers.CharField(required=True, label=_("question"))
+        # 段落列表
+        paragraph_list = serializers.ListField(child=InstanceField(model_type=ParagraphPipelineModel, required=True),
+                                               label=_("Paragraph List"))
+        # 历史对答
+        history_chat_record = serializers.ListField(child=InstanceField(model_type=ChatRecord, required=True),
+                                                    label=_("History Questions"))
+        # 多轮对话数量
+        dialogue_number = serializers.IntegerField(required=True, label=_("Number of multi-round conversations"))
+        # 最大携带知识库段落长度
+        max_paragraph_char_number = serializers.IntegerField(required=True,
+                                                             label=_("Maximum length of the knowledge base paragraph"))
+        # 模板
+        prompt = serializers.CharField(required=True, label=_("Prompt word"))
+        system = serializers.CharField(required=False, allow_null=True, allow_blank=True,
+                                       label=_("System prompt words (role)"))
+        # 补齐问题
+        padding_problem_text = serializers.CharField(required=False,
+                                                     label=_("Completion problem"))
+        # 未查询到引用分段
+        no_references_setting = NoReferencesSetting(required=True,
+                                                    label=_("No reference segment settings"))
+
+    def get_step_serializer(self, manage: PipelineManage) -> Type[serializers.Serializer]:
+        return self.InstanceSerializer
+
+    def _run(self, manage: PipelineManage):
+        message_list = self.execute(**self.context['step_args'])
+        manage.context['message_list'] = message_list
+
+    @abstractmethod
+    def execute(self,
+                problem_text: str,
+                paragraph_list: List[ParagraphPipelineModel],
+                history_chat_record: List[ChatRecord],
+                dialogue_number: int,
+                max_paragraph_char_number: int,
+                prompt: str,
+                padding_problem_text: str = None,
+                no_references_setting=None,
+                system=None,
+                **kwargs) -> List[BaseMessage]:
+        """
+
+        :param problem_text:               原始问题文本
+        :param paragraph_list:             段落列表
+        :param history_chat_record:        历史对话记录
+        :param dialogue_number:            多轮对话数量
+        :param max_paragraph_char_number:  最大段落长度
+        :param prompt:                     模板
+        :param padding_problem_text        用户修改文本
+        :param kwargs:                     其他参数
+        :param no_references_setting:     无引用分段设置
+        :param system                     系统提示称
+        :return:
+        """
+        pass

+ 79 - 0
apps/application/chat_pipeline/step/generate_human_message_step/impl/base_generate_human_message_step.py

@@ -0,0 +1,79 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_generate_human_message_step.py.py
+    @date:2024/1/10 17:50
+    @desc:
+"""
+from typing import List, Dict
+
+from langchain_core.messages import SystemMessage, BaseMessage, HumanMessage
+
+from application.chat_pipeline.I_base_chat_pipeline import ParagraphPipelineModel
+from application.chat_pipeline.step.generate_human_message_step.i_generate_human_message_step import \
+    IGenerateHumanMessageStep
+from application.models import ChatRecord
+from common.utils.common import flat_map
+
+
+class BaseGenerateHumanMessageStep(IGenerateHumanMessageStep):
+
+    def execute(self, problem_text: str,
+                paragraph_list: List[ParagraphPipelineModel],
+                history_chat_record: List[ChatRecord],
+                dialogue_number: int,
+                max_paragraph_char_number: int,
+                prompt: str,
+                padding_problem_text: str = None,
+                no_references_setting=None,
+                system=None,
+                **kwargs) -> List[BaseMessage]:
+        prompt = prompt if (paragraph_list is not None and len(paragraph_list) > 0) else no_references_setting.get(
+            'value')
+        exec_problem_text = padding_problem_text if padding_problem_text is not None else problem_text
+        start_index = len(history_chat_record) - dialogue_number
+        history_message = [[history_chat_record[index].get_human_message(), history_chat_record[index].get_ai_message()]
+                           for index in
+                           range(start_index if start_index > 0 else 0, len(history_chat_record))]
+        if system is not None and len(system) > 0:
+            return [SystemMessage(system), *flat_map(history_message),
+                    self.to_human_message(prompt, exec_problem_text, max_paragraph_char_number, paragraph_list,
+                                          no_references_setting)]
+
+        return [*flat_map(history_message),
+                self.to_human_message(prompt, exec_problem_text, max_paragraph_char_number, paragraph_list,
+                                      no_references_setting)]
+
+    @staticmethod
+    def to_human_message(prompt: str,
+                         problem: str,
+                         max_paragraph_char_number: int,
+                         paragraph_list: List[ParagraphPipelineModel],
+                         no_references_setting: Dict):
+        if paragraph_list is None or len(paragraph_list) == 0:
+            if no_references_setting.get('status') == 'ai_questioning':
+                return HumanMessage(
+                    content=no_references_setting.get('value').replace('{question}', problem))
+            else:
+                return HumanMessage(content=prompt.replace('{data}', "").replace('{question}', problem))
+        temp_data = ""
+        data_list = []
+        for p in paragraph_list:
+            content = f"{p.title}:{p.content}"
+            temp_data += content
+            if len(temp_data) > max_paragraph_char_number:
+                row_data = content[0:max_paragraph_char_number - len(temp_data)]
+                data_list.append(f"<data>{row_data}</data>")
+                break
+            else:
+                data_list.append(f"<data>{content}</data>")
+        data = "\n".join(data_list)
+        return HumanMessage(content=prompt.replace('{data}', data).replace('{question}', problem))
+
+    def get_details(self, manage, **kwargs):
+        return {
+            'status': self.status,
+            'err_message': self.err_message,
+            'step_type': 'generate_human_message',
+        }

+ 8 - 0
apps/application/chat_pipeline/step/reset_problem_step/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 18:23
+    @desc:
+"""

+ 55 - 0
apps/application/chat_pipeline/step/reset_problem_step/i_reset_problem_step.py

@@ -0,0 +1,55 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_reset_problem_step.py
+    @date:2024/1/9 18:12
+    @desc: 重写处理问题
+"""
+from abc import abstractmethod
+from typing import Type, List
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.chat_pipeline.I_base_chat_pipeline import IBaseChatPipelineStep
+from application.chat_pipeline.pipeline_manage import PipelineManage
+from application.models import ChatRecord
+from common.field.common import InstanceField
+
+
+class IResetProblemStep(IBaseChatPipelineStep):
+    class InstanceSerializer(serializers.Serializer):
+        # 问题文本
+        problem_text = serializers.CharField(required=True, label=_("question"))
+        # 历史对答
+        history_chat_record = serializers.ListField(child=InstanceField(model_type=ChatRecord, required=True),
+                                                    label=_("History Questions"))
+        # 大语言模型
+        model_id = serializers.UUIDField(required=False, allow_null=True, label=_("Model id"))
+        workspace_id = serializers.CharField(required=True, label=_("User ID"))
+        problem_optimization_prompt = serializers.CharField(required=False, max_length=102400,
+                                                            label=_("Question completion prompt"))
+
+    def get_step_serializer(self, manage: PipelineManage) -> Type[serializers.Serializer]:
+        return self.InstanceSerializer
+
+    def _run(self, manage: PipelineManage):
+        padding_problem = self.execute(**self.context.get('step_args'))
+        # 用户输入问题
+        source_problem_text = self.context.get('step_args').get('problem_text')
+        self.context['problem_text'] = source_problem_text
+        self.context['padding_problem_text'] = padding_problem
+        manage.context['problem_text'] = source_problem_text
+        manage.context['padding_problem_text'] = padding_problem
+        # 累加tokens
+        manage.context['message_tokens'] = manage.context.get('message_tokens', 0) + self.context.get('message_tokens',
+                                                                                                      0)
+        manage.context['answer_tokens'] = manage.context.get('answer_tokens', 0) + self.context.get('answer_tokens', 0)
+
+    @abstractmethod
+    def execute(self, problem_text: str, history_chat_record: List[ChatRecord] = None, model_id: str = None,
+                problem_optimization_prompt=None,
+                workspace_id=None,
+                **kwargs):
+        pass

+ 69 - 0
apps/application/chat_pipeline/step/reset_problem_step/impl/base_reset_problem_step.py

@@ -0,0 +1,69 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_reset_problem_step.py
+    @date:2024/1/10 14:35
+    @desc:
+"""
+from typing import List
+
+from django.utils.translation import gettext as _
+from langchain_core.messages import HumanMessage
+
+from application.chat_pipeline.step.reset_problem_step.i_reset_problem_step import IResetProblemStep
+from application.models import ChatRecord
+from common.utils.split_model import flat_map
+from models_provider.tools import get_model_instance_by_model_workspace_id
+
+prompt = _(
+    "() contains the user's question. Answer the guessed user's question based on the context ({question}) Requirement: Output a complete question and put it in the <data></data> tag")
+
+
+class BaseResetProblemStep(IResetProblemStep):
+    def execute(self, problem_text: str, history_chat_record: List[ChatRecord] = None, model_id: str = None,
+                problem_optimization_prompt=None,
+                workspace_id=None,
+                **kwargs) -> str:
+        chat_model = get_model_instance_by_model_workspace_id(model_id, workspace_id) if model_id is not None else None
+        if chat_model is None:
+            return problem_text
+        start_index = len(history_chat_record) - 3
+        history_message = [[history_chat_record[index].get_human_message(), history_chat_record[index].get_ai_message()]
+                           for index in
+                           range(start_index if start_index > 0 else 0, len(history_chat_record))]
+        reset_prompt = problem_optimization_prompt if problem_optimization_prompt else prompt
+        message_list = [*flat_map(history_message),
+                        HumanMessage(content=reset_prompt.replace('{question}', problem_text))]
+        response = chat_model.invoke(message_list)
+        padding_problem = problem_text
+        if response.content.__contains__("<data>") and response.content.__contains__('</data>'):
+            padding_problem_data = response.content[
+                                   response.content.index('<data>') + 6:response.content.index('</data>')]
+            if padding_problem_data is not None and len(padding_problem_data.strip()) > 0:
+                padding_problem = padding_problem_data
+        elif len(response.content) > 0:
+            padding_problem = response.content
+
+        try:
+            request_token = chat_model.get_num_tokens_from_messages(message_list)
+            response_token = chat_model.get_num_tokens(padding_problem)
+        except Exception as e:
+            request_token = 0
+            response_token = 0
+        self.context['message_tokens'] = request_token
+        self.context['answer_tokens'] = response_token
+        return padding_problem
+
+    def get_details(self, manage, **kwargs):
+        return {'status': self.status,
+                'err_message': self.err_message,
+                'step_type': 'problem_padding',
+                'run_time': self.context['run_time'],
+                'model_id': str(manage.context['model_id']) if 'model_id' in manage.context else None,
+                'message_tokens': self.context.get('message_tokens', 0),
+                'answer_tokens': self.context.get('answer_tokens', 0),
+                'cost': 0,
+                'padding_problem_text': self.context.get('padding_problem_text'),
+                'problem_text': self.context.get("step_args").get('problem_text'),
+                }

+ 8 - 0
apps/application/chat_pipeline/step/search_dataset_step/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/1/9 18:24
+    @desc:
+"""

+ 77 - 0
apps/application/chat_pipeline/step/search_dataset_step/i_search_dataset_step.py

@@ -0,0 +1,77 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_search_dataset_step.py
+    @date:2024/1/9 18:10
+    @desc: 检索知识库
+"""
+import re
+from abc import abstractmethod
+from typing import List, Type
+
+from django.core import validators
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.chat_pipeline.I_base_chat_pipeline import IBaseChatPipelineStep, ParagraphPipelineModel
+from application.chat_pipeline.pipeline_manage import PipelineManage
+
+
+class ISearchDatasetStep(IBaseChatPipelineStep):
+    class InstanceSerializer(serializers.Serializer):
+        # 原始问题文本
+        problem_text = serializers.CharField(required=True, label=_("question"))
+        # 系统补全问题文本
+        padding_problem_text = serializers.CharField(required=False,
+                                                     label=_("System completes question text"))
+        # 需要查询的数据集id列表
+        knowledge_id_list = serializers.ListField(required=True, child=serializers.UUIDField(required=True),
+                                                  label=_("Dataset id list"))
+        # 需要排除的文档id
+        exclude_document_id_list = serializers.ListField(required=True, child=serializers.UUIDField(required=True),
+                                                         label=_("List of document ids to exclude"))
+        # 需要排除向量id
+        exclude_paragraph_id_list = serializers.ListField(required=True, child=serializers.UUIDField(required=True),
+                                                          label=_("List of exclusion vector ids"))
+        # 需要查询的条数
+        top_n = serializers.IntegerField(required=True,
+                                         label=_("Reference segment number"))
+        # 相似度 0-1之间
+        similarity = serializers.FloatField(required=True, max_value=1, min_value=0,
+                                            label=_("Similarity"))
+        search_mode = serializers.CharField(required=True, validators=[
+            validators.RegexValidator(regex=re.compile("^embedding|keywords|blend$"),
+                                      message=_("The type only supports embedding|keywords|blend"), code=500)
+        ], label=_("Retrieval Mode"))
+        workspace_id = serializers.CharField(required=True, label=_("Workspace ID"))
+
+    def get_step_serializer(self, manage: PipelineManage) -> Type[InstanceSerializer]:
+        return self.InstanceSerializer
+
+    def _run(self, manage: PipelineManage):
+        paragraph_list = self.execute(**self.context['step_args'], manage=manage)
+        manage.context['paragraph_list'] = paragraph_list
+        self.context['paragraph_list'] = paragraph_list
+
+    @abstractmethod
+    def execute(self, problem_text: str, knowledge_id_list: list[str], exclude_document_id_list: list[str],
+                exclude_paragraph_id_list: list[str], top_n: int, similarity: float, padding_problem_text: str = None,
+                search_mode: str = None,
+                workspace_id=None,
+                manage: PipelineManage = None,
+                **kwargs) -> List[ParagraphPipelineModel]:
+        """
+        关于 用户和补全问题 说明: 补全问题如果有就使用补全问题去查询 反之就用用户原始问题查询
+        :param similarity:                         相关性
+        :param top_n:                              查询多少条
+        :param problem_text:                       用户问题
+        :param knowledge_id_list:                  需要查询的数据集id列表
+        :param exclude_document_id_list:           需要排除的文档id
+        :param exclude_paragraph_id_list:          需要排除段落id
+        :param padding_problem_text                补全问题
+        :param search_mode                         检索模式
+        :param workspace_id                        工作空间id
+        :return: 段落列表
+        """
+        pass

+ 150 - 0
apps/application/chat_pipeline/step/search_dataset_step/impl/base_search_dataset_step.py

@@ -0,0 +1,150 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_search_dataset_step.py
+    @date:2024/1/10 10:33
+    @desc:
+"""
+import os
+from typing import List, Dict
+
+from django.db.models import QuerySet
+from django.utils.translation import gettext_lazy as _
+from rest_framework.utils.formatting import lazy_format
+
+from application.chat_pipeline.I_base_chat_pipeline import ParagraphPipelineModel
+from application.chat_pipeline.step.search_dataset_step.i_search_dataset_step import ISearchDatasetStep
+from common.config.embedding_config import VectorStore, ModelManage
+from common.constants.permission_constants import RoleConstants
+from common.database_model_manage.database_model_manage import DatabaseModelManage
+from common.db.search import native_search
+from common.utils.common import get_file_content
+from knowledge.models import Paragraph, Knowledge
+from knowledge.models import SearchMode
+from maxkb.conf import PROJECT_DIR
+from models_provider.models import Model
+from models_provider.tools import get_model, get_model_by_id, get_model_default_params
+
+
+def reset_meta(meta):
+    if not meta.get('allow_download', False):
+        return {'allow_download': False}
+    return meta
+
+
+def get_embedding_id(knowledge_id_list):
+    knowledge_list = QuerySet(Knowledge).filter(id__in=knowledge_id_list)
+    if len(set([knowledge.embedding_model_id for knowledge in knowledge_list])) > 1:
+        raise Exception(
+            _("The vector model of the associated knowledge base is inconsistent and the segmentation cannot be recalled."))
+    if len(knowledge_list) == 0:
+        raise Exception(_("The knowledge base setting is wrong, please reset the knowledge base"))
+    return knowledge_list[0].embedding_model_id
+
+
+class BaseSearchDatasetStep(ISearchDatasetStep):
+
+    def execute(self, problem_text: str, knowledge_id_list: list[str], exclude_document_id_list: list[str],
+                exclude_paragraph_id_list: list[str], top_n: int, similarity: float, padding_problem_text: str = None,
+                search_mode: str = None,
+                workspace_id=None,
+                manage=None,
+                **kwargs) -> List[ParagraphPipelineModel]:
+        get_knowledge_list_of_authorized = DatabaseModelManage.get_model('get_knowledge_list_of_authorized')
+        chat_user_type = manage.context.get('chat_user_type')
+        if get_knowledge_list_of_authorized is not None and RoleConstants.CHAT_USER.value.name == chat_user_type:
+            knowledge_id_list = get_knowledge_list_of_authorized(manage.context.get('chat_user_id'),
+                                                                 knowledge_id_list)
+        if len(knowledge_id_list) == 0:
+            return []
+        exec_problem_text = padding_problem_text if padding_problem_text is not None else problem_text
+        model_id = get_embedding_id(knowledge_id_list)
+        model = get_model_by_id(model_id, workspace_id)
+        if model.model_type != "EMBEDDING":
+            raise Exception(_("Model does not exist"))
+        self.context['model_name'] = model.name
+        default_params = get_model_default_params(model)
+        embedding_model = ModelManage.get_model(model_id, lambda _id: get_model(model, **{**default_params}))
+        embedding_value = embedding_model.embed_query(exec_problem_text)
+        vector = VectorStore.get_embedding_vector()
+        embedding_list = vector.query(exec_problem_text, embedding_value, knowledge_id_list, None,
+                                      exclude_document_id_list,
+                                      exclude_paragraph_id_list, True, top_n, similarity, SearchMode(search_mode))
+        if embedding_list is None:
+            return []
+        paragraph_list = self.list_paragraph(embedding_list, vector)
+        result = [self.reset_paragraph(paragraph, embedding_list) for paragraph in paragraph_list]
+        return result
+
+    @staticmethod
+    def reset_paragraph(paragraph: Dict, embedding_list: List) -> ParagraphPipelineModel:
+        filter_embedding_list = [embedding for embedding in embedding_list if
+                                 str(embedding.get('paragraph_id')) == str(paragraph.get('id'))]
+        if filter_embedding_list is not None and len(filter_embedding_list) > 0:
+            find_embedding = filter_embedding_list[-1]
+            return (ParagraphPipelineModel.builder()
+                    .add_paragraph(paragraph)
+                    .add_similarity(find_embedding.get('similarity'))
+                    .add_comprehensive_score(find_embedding.get('comprehensive_score'))
+                    .add_knowledge_name(paragraph.get('knowledge_name'))
+                    .add_knowledge_type(paragraph.get('knowledge_type'))
+                    .add_document_name(paragraph.get('document_name'))
+                    .add_hit_handling_method(paragraph.get('hit_handling_method'))
+                    .add_directly_return_similarity(paragraph.get('directly_return_similarity'))
+                    .add_meta(reset_meta(paragraph.get('meta')))
+                    .build())
+
+    @staticmethod
+    def get_similarity(paragraph, embedding_list: List):
+        filter_embedding_list = [embedding for embedding in embedding_list if
+                                 str(embedding.get('paragraph_id')) == str(paragraph.get('id'))]
+        if filter_embedding_list is not None and len(filter_embedding_list) > 0:
+            find_embedding = filter_embedding_list[-1]
+            return find_embedding.get('comprehensive_score')
+        return 0
+
+    @staticmethod
+    def list_paragraph(embedding_list: List, vector):
+        paragraph_id_list = [row.get('paragraph_id') for row in embedding_list]
+        if paragraph_id_list is None or len(paragraph_id_list) == 0:
+            return []
+        paragraph_list = native_search(QuerySet(Paragraph).filter(id__in=paragraph_id_list),
+                                       get_file_content(
+                                           os.path.join(PROJECT_DIR, "apps", "application", 'sql',
+                                                        'list_knowledge_paragraph_by_paragraph_id.sql')),
+                                       with_table_name=True)
+        # 如果向量库中存在脏数据 直接删除
+        if len(paragraph_list) != len(paragraph_id_list):
+            exist_paragraph_list = [row.get('id') for row in paragraph_list]
+            for paragraph_id in paragraph_id_list:
+                if not exist_paragraph_list.__contains__(paragraph_id):
+                    vector.delete_by_paragraph_id(paragraph_id)
+        # 如果存在直接返回的则取直接返回段落
+        hit_handling_method_paragraph = [paragraph for paragraph in paragraph_list if
+                                         (paragraph.get(
+                                             'hit_handling_method') == 'directly_return' and BaseSearchDatasetStep.get_similarity(
+                                             paragraph, embedding_list) >= paragraph.get(
+                                             'directly_return_similarity'))]
+        if len(hit_handling_method_paragraph) > 0:
+            # 找到评分最高的
+            return [sorted(hit_handling_method_paragraph,
+                           key=lambda p: BaseSearchDatasetStep.get_similarity(p, embedding_list))[-1]]
+        return paragraph_list
+
+    def get_details(self, manage, **kwargs):
+        step_args = self.context.get('step_args') or {}
+
+        return {
+            'status': self.status,
+            'err_message': self.err_message,
+            'step_type': 'search_step',
+            'paragraph_list': [row.to_dict() for row in (self.context.get('paragraph_list') or [])],
+            'run_time': self.context.get('run_time') or 0,
+            'problem_text': step_args.get(
+                'padding_problem_text') if 'padding_problem_text' in step_args else step_args.get('problem_text'),
+            'model_name': self.context.get('model_name'),
+            'message_tokens': 0,
+            'answer_tokens': 0,
+            'cost': 0
+        }

+ 8 - 0
apps/application/flow/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/6/7 14:43
+    @desc:
+"""

+ 0 - 0
apps/application/flow/backend/__init__.py


+ 69 - 0
apps/application/flow/backend/sandbox_shell.py

@@ -0,0 +1,69 @@
+import getpass
+import os
+import re
+
+from deepagents.backends import LocalShellBackend
+from deepagents.backends.protocol import ExecuteResponse
+
+from maxkb.const import CONFIG
+
+_enable_sandbox = bool(int(CONFIG.get('SANDBOX', 0)))
+_run_user = 'sandbox' if _enable_sandbox else getpass.getuser()
+_sandbox_python_sys_path = CONFIG.get_sandbox_python_package_paths().replace(',', ':')
+
+
+class SandboxShellBackend(LocalShellBackend):
+    def __init__(self, root_dir: str, **kwargs):
+        if 'env' not in kwargs and not kwargs.get('inherit_env', False):
+            env = os.environ.copy()
+            path = env.get('PATH', '/usr/bin:/bin')
+
+            # 将 sandbox 路径分解为列表,检查每个路径是否已存在
+            existing_paths = set(path.split(os.pathsep))
+            sandbox_paths = _sandbox_python_sys_path.split(os.pathsep) if _sandbox_python_sys_path else []
+            new_paths = [p for p in sandbox_paths if p and p not in existing_paths]
+
+            if new_paths:
+                env['PATH'] = f"{os.pathsep.join(new_paths)}{os.pathsep}{path}"
+
+            kwargs['env'] = env
+        super().__init__(root_dir=root_dir, **kwargs)
+
+    def _translate_virtual_paths(self, command: str) -> str:
+        """Translate virtual absolute paths in the command to real filesystem paths.
+
+        In virtual_mode=True, file tools (ls, glob, read_file) return virtual absolute
+        paths like /skills/foo.py which map to {root_dir}/skills/foo.py.  But execute()
+        runs a real shell where /skills/foo.py does not exist.  This method replaces
+        any path token that exists under root_dir with its real path, while leaving
+        genuine system paths (e.g. /usr/bin/python3) untouched.
+        """
+        root = str(self.cwd)
+
+        def translate(m: re.Match) -> str:
+            virtual_path = m.group(0)
+            real_path = root + virtual_path
+            return real_path if os.path.lexists(real_path) else virtual_path
+
+        # Match absolute-path-like tokens: / followed by a non-whitespace sequence
+        # that isn't clearly a flag (e.g. avoid matching -/something).
+        # Only translate when virtual_mode is active.
+        return re.sub(r'(?<![.\w\-])/[A-Za-z_][^\s\'"\\;|&><:,]*', translate, command)
+
+    def execute(
+            self,
+            command: str,
+            *,
+            timeout: int | None = None,
+    ) -> ExecuteResponse:
+        if self.virtual_mode:
+            command = self._translate_virtual_paths(command)
+
+        if _enable_sandbox:
+            # 用 runuser 在子进程里切换用户,父进程凭据保持不变,
+            # 避免父进程 ruid/euid 不一致导致 execve 报 Permission denied
+            command = f"env -i LD_PRELOAD=/opt/maxkb-app/sandbox/lib/sandbox.so PATH=${{PATH}} gosu {_run_user} {command}"
+            # command = f"runuser -u {_run_user} -- env -i PATH=${{PATH}} {command}"
+
+        # print(f"Executing command in sandbox: {command}")
+        return super().execute(command=command, timeout=timeout)

+ 284 - 0
apps/application/flow/common.py

@@ -0,0 +1,284 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎
+    @file: common.py
+    @date:2024/12/11 17:57
+    @desc:
+"""
+from enum import Enum
+from typing import List, Dict
+
+from django.db.models import QuerySet
+from django.utils.translation import gettext as _
+from rest_framework.exceptions import ErrorDetail, ValidationError
+
+from common.exception.app_exception import AppApiException
+from common.utils.common import group_by
+from models_provider.models import Model
+from models_provider.tools import get_model_credential
+from tools.models.tool import Tool
+
+end_nodes = ['ai-chat-node', 'reply-node', 'function-node', 'function-lib-node', 'application-node',
+             'image-understand-node', 'speech-to-text-node', 'text-to-speech-node', 'image-generate-node',
+             'variable-assign-node']
+
+
+class Answer:
+    def __init__(self, content, view_type, runtime_node_id, chat_record_id, child_node, real_node_id,
+                 reasoning_content):
+        self.view_type = view_type
+        self.content = content
+        self.reasoning_content = reasoning_content
+        self.runtime_node_id = runtime_node_id
+        self.chat_record_id = chat_record_id
+        self.child_node = child_node
+        self.real_node_id = real_node_id
+
+    def to_dict(self):
+        return {'view_type': self.view_type, 'content': self.content, 'runtime_node_id': self.runtime_node_id,
+                'chat_record_id': self.chat_record_id,
+                'child_node': self.child_node,
+                'reasoning_content': self.reasoning_content,
+                'real_node_id': self.real_node_id}
+
+
+class NodeChunk:
+    def __init__(self):
+        self.status = 0
+        self.chunk_list = []
+
+    def add_chunk(self, chunk):
+        self.chunk_list.append(chunk)
+
+    def end(self, chunk=None):
+        if chunk is not None:
+            self.add_chunk(chunk)
+        self.status = 200
+
+    def is_end(self):
+        return self.status == 200
+
+
+class Edge:
+    def __init__(self, _id: str, _type: str, sourceNodeId: str, targetNodeId: str, **keywords):
+        self.id = _id
+        self.type = _type
+        self.sourceNodeId = sourceNodeId
+        self.targetNodeId = targetNodeId
+        for keyword in keywords:
+            self.__setattr__(keyword, keywords.get(keyword))
+
+
+class Node:
+    def __init__(self, _id: str, _type: str, x: int, y: int, properties: dict, **kwargs):
+        self.id = _id
+        self.type = _type
+        self.x = x
+        self.y = y
+        self.properties = properties
+        for keyword in kwargs:
+            self.__setattr__(keyword, kwargs.get(keyword))
+
+
+class EdgeNode:
+    edge: Edge
+    node: Node
+
+    def __init__(self, edge, node):
+        self.edge = edge
+        self.node = node
+
+
+class WorkflowMode(Enum):
+    APPLICATION = "application"
+
+    APPLICATION_LOOP = "application-loop"
+
+    KNOWLEDGE = "knowledge"
+
+    KNOWLEDGE_LOOP = "knowledge-loop"
+
+    TOOL = "tool"
+
+    TOOL_LOOP = "tool-loop"
+
+
+class Workflow:
+    """
+    节点列表
+    """
+    nodes: List[Node]
+    """
+    线列表
+    """
+    edges: List[Edge]
+    """
+    节点id:node
+    """
+    node_map: Dict[str, Node]
+    """
+    节点id:当前节点id上面的所有节点
+    """
+    up_node_map: Dict[str, List[EdgeNode]]
+    """
+     节点id:当前节点id下面的所有节点
+    """
+    next_node_map: Dict[str, List[EdgeNode]]
+
+    workflow_mode: WorkflowMode
+
+    def __init__(self, nodes: List[Node], edges: List[Edge],
+                 workflow_mode: WorkflowMode = WorkflowMode.APPLICATION.value):
+        self.nodes = nodes
+        self.edges = edges
+        self.node_map = {node.id: node for node in nodes}
+
+        self.up_node_map = {key: [EdgeNode(edge, self.node_map.get(edge.sourceNodeId)) for
+                                  edge in edges] for
+                            key, edges in
+                            group_by(edges, key=lambda edge: edge.targetNodeId).items()}
+
+        self.next_node_map = {key: [EdgeNode(edge, self.node_map.get(edge.targetNodeId)) for edge in edges] for
+                              key, edges in
+                              group_by(edges, key=lambda edge: edge.sourceNodeId).items()}
+        self.workflow_mode = workflow_mode
+
+    def get_node(self, node_id):
+        """
+        根据node_id 获取节点信息
+        @param node_id: node_id
+        @return: 节点信息
+        """
+        return self.node_map.get(node_id)
+
+    def get_up_edge_nodes(self, node_id) -> List[EdgeNode]:
+        """
+        根据节点id 获取当前连接前置节点和连线
+        @param node_id: 节点id
+        @return: 节点连线列表
+        """
+        return self.up_node_map.get(node_id)
+
+    def get_next_edge_nodes(self, node_id) -> List[EdgeNode]:
+        """
+        根据节点id 获取当前连接目标节点和连线
+        @param node_id: 节点id
+        @return: 节点连线列表
+        """
+        return self.next_node_map.get(node_id)
+
+    def get_up_nodes(self, node_id) -> List[Node]:
+        """
+        根据节点id 获取当前连接前置节点
+        @param node_id: 节点id
+        @return: 节点列表
+        """
+        return [en.node for en in (self.up_node_map.get(node_id) or [])]
+
+    def get_next_nodes(self, node_id) -> List[Node]:
+        """
+        根据节点id 获取当前连接目标节点
+        @param node_id: 节点id
+        @return: 节点列表
+        """
+        return [en.node for en in self.next_node_map.get(node_id, [])]
+
+    @staticmethod
+    def new_instance(flow_obj: Dict, workflow_mode: WorkflowMode = WorkflowMode.APPLICATION):
+        nodes = flow_obj.get('nodes')
+        edges = flow_obj.get('edges')
+        nodes = [Node(node.get('id'), node.get('type'), **node)
+                 for node in nodes]
+        edges = [Edge(edge.get('id'), edge.get('type'), **edge) for edge in edges]
+        return Workflow(nodes, edges, workflow_mode)
+
+    def get_start_node(self):
+        return self.get_node('start-node')
+
+    def get_search_node(self):
+        return [node for node in self.nodes if node.type == 'search-dataset-node']
+
+    def is_valid(self):
+        """
+        校验工作流数据
+        """
+        self.is_valid_model_params()
+        self.is_valid_start_node()
+        self.is_valid_base_node()
+        self.is_valid_work_flow()
+
+    def is_valid_node_params(self, node: Node):
+        from application.flow.step_node import get_node
+        get_node(node.type, self.workflow_mode)(node, None, None)
+
+    def is_valid_node(self, node: Node):
+        self.is_valid_node_params(node)
+        if node.type == 'condition-node':
+            branch_list = node.properties.get('node_data').get('branch')
+            for branch in branch_list:
+                source_anchor_id = f"{node.id}_{branch.get('id')}_right"
+                edge_list = [edge for edge in self.edges if edge.sourceAnchorId == source_anchor_id]
+                if len(edge_list) == 0:
+                    raise AppApiException(500,
+                                          _('The branch {branch} of the {node} node needs to be connected').format(
+                                              node=node.properties.get("stepName"), branch=branch.get("type")))
+
+        else:
+            edge_list = [edge for edge in self.edges if edge.sourceNodeId == node.id]
+            if len(edge_list) == 0 and not end_nodes.__contains__(node.type):
+                raise AppApiException(500, _("{node} Nodes cannot be considered as end nodes").format(
+                    node=node.properties.get("stepName")))
+
+    def is_valid_work_flow(self, up_node=None):
+        if up_node is None:
+            up_node = self.get_start_node()
+        self.is_valid_node(up_node)
+        next_nodes = self.get_next_nodes(up_node)
+        for next_node in next_nodes:
+            self.is_valid_work_flow(next_node)
+
+    def is_valid_start_node(self):
+        start_node_list = [node for node in self.nodes if node.id == 'start-node']
+        if len(start_node_list) == 0:
+            raise AppApiException(500, _('The starting node is required'))
+        if len(start_node_list) > 1:
+            raise AppApiException(500, _('There can only be one starting node'))
+
+    def is_valid_model_params(self):
+        node_list = [node for node in self.nodes if (
+                node.type == 'ai-chat-node' or node.type == 'question-node' or node.type == 'parameter-extraction-node')]
+        for node in node_list:
+            if (node.properties.get('node_data', {}).get('model_id_type') or 'custom') == 'reference':
+                continue
+            model = QuerySet(Model).filter(id=node.properties.get('node_data', {}).get('model_id')).first()
+            if model is None:
+                raise ValidationError(ErrorDetail(
+                    _('The node {node} model does not exist').format(node=node.properties.get("stepName"))))
+            credential = get_model_credential(model.provider, model.model_type, model.model_name)
+            model_params_setting = node.properties.get('node_data', {}).get('model_params_setting')
+            model_params_setting_form = credential.get_model_params_setting_form(
+                model.model_name)
+            if model_params_setting is None:
+                model_params_setting = model_params_setting_form.get_default_form_data()
+                node.properties.get('node_data', {})['model_params_setting'] = model_params_setting
+            if node.properties.get('status', 200) != 200:
+                raise ValidationError(
+                    ErrorDetail(_("Node {node} is unavailable").format(node=node.properties.get("stepName"))))
+        node_list = [node for node in self.nodes if (node.type == 'function-lib-node')]
+        for node in node_list:
+            function_lib_id = node.properties.get('node_data', {}).get('function_lib_id')
+            if function_lib_id is None:
+                raise ValidationError(ErrorDetail(
+                    _('The library ID of node {node} cannot be empty').format(node=node.properties.get("stepName"))))
+            f_lib = QuerySet(Tool).filter(id=function_lib_id).first()
+            if f_lib is None:
+                raise ValidationError(ErrorDetail(_("The function library for node {node} is not available").format(
+                    node=node.properties.get("stepName"))))
+
+    def is_valid_base_node(self):
+        base_node_list = [node for node in self.nodes if node.id == 'base-node']
+        if len(base_node_list) == 0:
+            raise AppApiException(500, _('Basic information node is required'))
+        if len(base_node_list) > 1:
+            raise AppApiException(500, _('There can only be one basic information node'))

+ 36 - 0
apps/application/flow/compare/__init__.py

@@ -0,0 +1,36 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/6/7 14:43
+    @desc:
+"""
+
+from .contain_compare import *
+from .end_with import EndWithCompare
+from .equal_compare import *
+from .ge_compare import *
+from .gt_compare import *
+from .is_not_null_compare import *
+from .is_not_true import IsNotTrueCompare
+from .is_null_compare import *
+from .is_true import IsTrueCompare
+from .le_compare import *
+from .len_equal_compare import *
+from .len_ge_compare import *
+from .len_gt_compare import *
+from .len_le_compare import *
+from .len_lt_compare import *
+from .lt_compare import *
+from .not_contain_compare import *
+from .not_equal_compare import *
+from .regex_compare import RegexCompare
+from .start_with import StartWithCompare
+from .wildcard_compare import WildcardCompare
+
+compare_handle_list = [GECompare(), GTCompare(), ContainCompare(), EqualCompare(), LTCompare(), LECompare(),
+                       LenLECompare(), LenGECompare(), LenEqualCompare(), LenGTCompare(), LenLTCompare(),
+                       IsNullCompare(),
+                       IsNotNullCompare(), NotContainCompare(), NotEqualCompare(), IsTrueCompare(), IsNotTrueCompare(), StartWithCompare(),
+                       EndWithCompare(), RegexCompare(), WildcardCompare()]

+ 20 - 0
apps/application/flow/compare/compare.py

@@ -0,0 +1,20 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: compare.py
+    @date:2024/6/7 14:37
+    @desc:
+"""
+from abc import abstractmethod
+from typing import List
+
+
+class Compare:
+    @abstractmethod
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        pass
+
+    @abstractmethod
+    def compare(self, source_value, compare, target_value):
+        pass

+ 26 - 0
apps/application/flow/compare/contain_compare.py

@@ -0,0 +1,26 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: contain_compare.py
+    @date:2024/6/11 10:02
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare.compare import Compare
+
+
+class ContainCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'contain':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        if isinstance(source_value, str):
+            return str(target_value) in source_value
+        elif isinstance(source_value, list):
+            return any([str(item) == str(target_value) for item in source_value])
+        else:
+            return str(target_value) in str(source_value)

+ 22 - 0
apps/application/flow/compare/end_with.py

@@ -0,0 +1,22 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: start_with.py
+    @date:2025/10/20 10:37
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class EndWithCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'end_with':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        source_value = str(source_value)
+        return source_value.endswith(str(target_value))

+ 21 - 0
apps/application/flow/compare/equal_compare.py

@@ -0,0 +1,21 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: equal_compare.py
+    @date:2024/6/7 14:44
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class EqualCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'eq':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        return str(source_value) == str(target_value)

+ 28 - 0
apps/application/flow/compare/ge_compare.py

@@ -0,0 +1,28 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 大于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class GECompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'ge':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return float(source_value) >= float(target_value)
+        except Exception as e:
+            try:
+                return str(source_value) >= str(target_value)
+            except Exception as _:
+                pass
+            return False

+ 28 - 0
apps/application/flow/compare/gt_compare.py

@@ -0,0 +1,28 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 大于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class GTCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'gt':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return float(source_value) > float(target_value)
+        except Exception as e:
+            try:
+                return str(source_value) > str(target_value)
+            except Exception as _:
+                pass
+            return False

+ 21 - 0
apps/application/flow/compare/is_not_null_compare.py

@@ -0,0 +1,21 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: is_not_null_compare.py
+    @date:2024/6/28 10:45
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class IsNotNullCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'is_not_null':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        return source_value is not None and len(source_value) > 0

+ 24 - 0
apps/application/flow/compare/is_not_true.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎
+    @file: is_not_true.py
+    @date:2025/4/7 13:44
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class IsNotTrueCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'is_not_true':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return source_value is False
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/is_null_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: is_null_compare.py
+    @date:2024/6/28 10:45
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class IsNullCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'is_null':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return source_value is None or len(source_value) == 0
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/is_true.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎
+    @file: IsTrue.py
+    @date:2025/4/7 13:38
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class IsTrueCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'is_true':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return source_value is True
+        except Exception as e:
+            return False

+ 28 - 0
apps/application/flow/compare/le_compare.py

@@ -0,0 +1,28 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 小于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LECompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'le':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return float(source_value) <= float(target_value)
+        except Exception as e:
+            try:
+                return str(source_value) <= str(target_value)
+            except Exception as _:
+                pass
+            return False

+ 24 - 0
apps/application/flow/compare/len_equal_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: equal_compare.py
+    @date:2024/6/7 14:44
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LenEqualCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'len_eq':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return len(source_value) == int(target_value)
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/len_ge_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 大于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LenGECompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'len_ge':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return len(source_value) >= int(target_value)
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/len_gt_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 大于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LenGTCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'len_gt':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return len(source_value) > int(target_value)
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/len_le_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 小于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LenLECompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'len_le':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return len(source_value) <= int(target_value)
+        except Exception as e:
+            return False

+ 24 - 0
apps/application/flow/compare/len_lt_compare.py

@@ -0,0 +1,24 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 小于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LenLTCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'len_lt':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return len(source_value) < int(target_value)
+        except Exception as e:
+            return False

+ 28 - 0
apps/application/flow/compare/lt_compare.py

@@ -0,0 +1,28 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: lt_compare.py
+    @date:2024/6/11 9:52
+    @desc: 小于比较器
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class LTCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'lt':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        try:
+            return float(source_value) < float(target_value)
+        except Exception as e:
+            try:
+                return str(source_value) < str(target_value)
+            except Exception as _:
+                pass
+            return False

+ 26 - 0
apps/application/flow/compare/not_contain_compare.py

@@ -0,0 +1,26 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: contain_compare.py
+    @date:2024/6/11 10:02
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class NotContainCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'not_contain':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        if isinstance(source_value, str):
+            return str(target_value) not in source_value
+        elif isinstance(self, list):
+            return not any([str(item) == str(target_value) for item in source_value])
+        else:
+            return str(target_value) not in str(source_value)

+ 21 - 0
apps/application/flow/compare/not_equal_compare.py

@@ -0,0 +1,21 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:wangliang181230
+    @file: not_equal_compare.py
+    @date:2026/3/17 9:41
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class NotEqualCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'not_eq':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        return str(source_value) != str(target_value)

+ 40 - 0
apps/application/flow/compare/regex_compare.py

@@ -0,0 +1,40 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:wangliang181230
+    @file: regex_compare.py
+    @date:2026/3/30 12:11
+    @desc:
+"""
+import re
+from typing import List
+
+from application.flow.compare import Compare
+from common.cache.mem_cache import MemCache
+
+
+match_cache = MemCache('regex', {
+    'TIMEOUT': 3600, # 缓存有效期为 1 小时
+    'OPTIONS': {
+        'MAX_ENTRIES': 500, # 最多缓存 500 个条目
+        'CULL_FREQUENCY': 10, # 达到上限时,删除约 1/10 的缓存
+    },
+})
+
+
+def compile_and_cache(regex):
+    match = match_cache.get(regex)
+    if not match:
+        match = re.compile(regex).match
+        match_cache.set(regex, match)
+    return match
+
+class RegexCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'regex':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        match = compile_and_cache(str(target_value))
+        return bool(match(str(source_value)))

+ 22 - 0
apps/application/flow/compare/start_with.py

@@ -0,0 +1,22 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: start_with.py
+    @date:2025/10/20 10:37
+    @desc:
+"""
+from typing import List
+
+from application.flow.compare import Compare
+
+
+class StartWithCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'start_with':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        source_value = str(source_value)
+        return source_value.startswith(str(target_value))

+ 43 - 0
apps/application/flow/compare/wildcard_compare.py

@@ -0,0 +1,43 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:wangliang181230
+    @file: wildcard_compare.py
+    @date:2026/3/30 12:11
+    @desc:
+"""
+import fnmatch
+import re
+from typing import List
+
+from application.flow.compare import Compare
+from common.cache.mem_cache import MemCache
+
+
+match_cache = MemCache('wildcard_to_regex', {
+    'TIMEOUT': 3600, # 缓存有效期为 1 小时
+    'OPTIONS': {
+        'MAX_ENTRIES': 500, # 最多缓存 500 个条目
+        'CULL_FREQUENCY': 10, # 达到上限时,删除约 1/10 的缓存
+    },
+})
+
+
+def translate_and_compile_and_cache(wildcard):
+    match = match_cache.get(wildcard)
+    if not match:
+        regex = fnmatch.translate(wildcard)
+        match = re.compile(regex).match
+        match_cache.set(wildcard, match)
+    return match
+
+class WildcardCompare(Compare):
+
+    def support(self, node_id, fields: List[str], source_value, compare, target_value):
+        if compare == 'wildcard':
+            return True
+
+    def compare(self, source_value, compare, target_value):
+        # 转成正则,性能更高
+        match = translate_and_compile_and_cache(str(target_value))
+        return bool(match(str(source_value)))

+ 451 - 0
apps/application/flow/default_workflow.json

@@ -0,0 +1,451 @@
+{
+    "nodes": [
+        {
+            "id": "base-node",
+            "type": "base-node",
+            "x": 360,
+            "y": 2810,
+            "properties": {
+                "config": {
+
+                },
+                "height": 825.6,
+                "stepName": "基本信息",
+                "node_data": {
+                    "desc": "",
+                    "name": "maxkbapplication",
+                    "prologue": "您好,我是 MaxKB 小助手,您可以向我提出 MaxKB 使用问题。\n- MaxKB 主要功能有什么?\n- MaxKB 支持哪些大语言模型?\n- MaxKB 支持哪些文档类型?"
+                },
+                "input_field_list": [
+
+                ]
+            }
+        },
+        {
+            "id": "start-node",
+            "type": "start-node",
+            "x": 430,
+            "y": 3660,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "用户问题",
+                            "value": "question"
+                        }
+                    ],
+                    "globalFields": [
+                        {
+                            "label": "当前时间",
+                            "value": "time"
+                        }
+                    ]
+                },
+                "fields": [
+                    {
+                        "label": "用户问题",
+                        "value": "question"
+                    }
+                ],
+                "height": 276,
+                "stepName": "开始",
+                "globalFields": [
+                    {
+                        "label": "当前时间",
+                        "value": "time"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "type": "search-dataset-node",
+            "x": 840,
+            "y": 3210,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "检索结果的分段列表",
+                            "value": "paragraph_list"
+                        },
+                        {
+                            "label": "满足直接回答的分段列表",
+                            "value": "is_hit_handling_method_list"
+                        },
+                        {
+                            "label": "检索结果",
+                            "value": "data"
+                        },
+                        {
+                            "label": "满足直接回答的分段内容",
+                            "value": "directly_return"
+                        }
+                    ]
+                },
+                "height": 794,
+                "stepName": "知识库检索",
+                "node_data": {
+                    "dataset_id_list": [
+
+                    ],
+                    "dataset_setting": {
+                        "top_n": 3,
+                        "similarity": 0.6,
+                        "search_mode": "embedding",
+                        "max_paragraph_char_number": 5000
+                    },
+                    "question_reference_address": [
+                        "start-node",
+                        "question"
+                    ],
+                    "source_dataset_id_list": [
+
+                    ]
+                }
+            }
+        },
+        {
+            "id": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "type": "condition-node",
+            "x": 1490,
+            "y": 3210,
+            "properties": {
+                "width": 600,
+                "config": {
+                    "fields": [
+                        {
+                            "label": "分支名称",
+                            "value": "branch_name"
+                        }
+                    ]
+                },
+                "height": 543.675,
+                "stepName": "判断器",
+                "node_data": {
+                    "branch": [
+                        {
+                            "id": "1009",
+                            "type": "IF",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "is_hit_handling_method_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "4908",
+                            "type": "ELSE IF 1",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "paragraph_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "161",
+                            "type": "ELSE",
+                            "condition": "and",
+                            "conditions": [
+
+                            ]
+                        }
+                    ]
+                },
+                "branch_condition_list": [
+                    {
+                        "index": 0,
+                        "height": 121.225,
+                        "id": "1009"
+                    },
+                    {
+                        "index": 1,
+                        "height": 121.225,
+                        "id": "4908"
+                    },
+                    {
+                        "index": 2,
+                        "height": 44,
+                        "id": "161"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "type": "reply-node",
+            "x": 2170,
+            "y": 2480,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 378,
+                "stepName": "指定回复",
+                "node_data": {
+                    "fields": [
+                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                        "directly_return"
+                    ],
+                    "content": "",
+                    "reply_type": "referencing",
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3200,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 对话",
+                "node_data": {
+                    "prompt": "已知信息:\n{{知识库检索.data}}\n问题:\n{{开始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3970,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 对话1",
+                "node_data": {
+                    "prompt": "{{开始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        }
+    ],
+    "edges": [
+        {
+            "id": "7d0f166f-c472-41b2-b9a2-c294f4c83d73",
+            "type": "app-edge",
+            "sourceNodeId": "start-node",
+            "targetNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "startPoint": {
+                "x": 590,
+                "y": 3660
+            },
+            "endPoint": {
+                "x": 680,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 590,
+                    "y": 3660
+                },
+                {
+                    "x": 700,
+                    "y": 3660
+                },
+                {
+                    "x": 570,
+                    "y": 3210
+                },
+                {
+                    "x": 680,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "start-node_right",
+            "targetAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_left"
+        },
+        {
+            "id": "35cb86dd-f328-429e-a973-12fd7218b696",
+            "type": "app-edge",
+            "sourceNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "targetNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "startPoint": {
+                "x": 1000,
+                "y": 3210
+            },
+            "endPoint": {
+                "x": 1200,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1000,
+                    "y": 3210
+                },
+                {
+                    "x": 1110,
+                    "y": 3210
+                },
+                {
+                    "x": 1090,
+                    "y": 3210
+                },
+                {
+                    "x": 1200,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_right",
+            "targetAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_left"
+        },
+        {
+            "id": "e8f6cfe6-7e48-41cd-abd3-abfb5304d0d8",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "startPoint": {
+                "x": 1780,
+                "y": 3073.775
+            },
+            "endPoint": {
+                "x": 2010,
+                "y": 2480
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1890,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1900,
+                    "y": 2480
+                },
+                {
+                    "x": 2010,
+                    "y": 2480
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_1009_right",
+            "targetAnchorId": "4ffe1086-25df-4c85-b168-979b5bbf0a26_left"
+        },
+        {
+            "id": "994ff325-6f7a-4ebc-b61b-10e15519d6d2",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "startPoint": {
+                "x": 1780,
+                "y": 3203
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3200
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3200
+                },
+                {
+                    "x": 2000,
+                    "y": 3200
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_4908_right",
+            "targetAnchorId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb_left"
+        },
+        {
+            "id": "19270caf-bb9f-4ba7-9bf8-200aa70fecd5",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "startPoint": {
+                "x": 1780,
+                "y": 3293.6124999999997
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3970
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3970
+                },
+                {
+                    "x": 2000,
+                    "y": 3970
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_161_right",
+            "targetAnchorId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7_left"
+        }
+    ]
+}

+ 451 - 0
apps/application/flow/default_workflow_en.json

@@ -0,0 +1,451 @@
+{
+    "nodes": [
+        {
+            "id": "base-node",
+            "type": "base-node",
+            "x": 360,
+            "y": 2810,
+            "properties": {
+                "config": {
+
+                },
+                "height": 825.6,
+                "stepName": "Base",
+                "node_data": {
+                    "desc": "",
+                    "name": "maxkbapplication",
+                    "prologue": "Hello, I am the MaxKB assistant. You can ask me about MaxKB usage issues.\n-What are the main functions of MaxKB?\n-What major language models does MaxKB support?\n-What document types does MaxKB support?"
+                },
+                "input_field_list": [
+
+                ]
+            }
+        },
+        {
+            "id": "start-node",
+            "type": "start-node",
+            "x": 430,
+            "y": 3660,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "User Question",
+                            "value": "question"
+                        }
+                    ],
+                    "globalFields": [
+                        {
+                            "label": "Current Time",
+                            "value": "time"
+                        }
+                    ]
+                },
+                "fields": [
+                    {
+                        "label": "User Question",
+                        "value": "question"
+                    }
+                ],
+                "height": 276,
+                "stepName": "Start",
+                "globalFields": [
+                    {
+                        "label": "Current Time",
+                        "value": "time"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "type": "search-dataset-node",
+            "x": 840,
+            "y": 3210,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "List of Retrieved Paragraphs",
+                            "value": "paragraph_list"
+                        },
+                        {
+                            "label": "List of Paragraphs Satisfying Direct Answer",
+                            "value": "is_hit_handling_method_list"
+                        },
+                        {
+                            "label": "Search Results",
+                            "value": "data"
+                        },
+                        {
+                            "label": "Content of Paragraphs Satisfying Direct Answer",
+                            "value": "directly_return"
+                        }
+                    ]
+                },
+                "height": 794,
+                "stepName": "Knowledge Search",
+                "node_data": {
+                    "dataset_id_list": [
+
+                    ],
+                    "dataset_setting": {
+                        "top_n": 3,
+                        "similarity": 0.6,
+                        "search_mode": "embedding",
+                        "max_paragraph_char_number": 5000
+                    },
+                    "question_reference_address": [
+                        "start-node",
+                        "question"
+                    ],
+                    "source_dataset_id_list": [
+
+                    ]
+                }
+            }
+        },
+        {
+            "id": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "type": "condition-node",
+            "x": 1490,
+            "y": 3210,
+            "properties": {
+                "width": 600,
+                "config": {
+                    "fields": [
+                        {
+                            "label": "Branch Name",
+                            "value": "branch_name"
+                        }
+                    ]
+                },
+                "height": 543.675,
+                "stepName": "Conditional Branch",
+                "node_data": {
+                    "branch": [
+                        {
+                            "id": "1009",
+                            "type": "IF",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "is_hit_handling_method_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "4908",
+                            "type": "ELSE IF 1",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "paragraph_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "161",
+                            "type": "ELSE",
+                            "condition": "and",
+                            "conditions": [
+
+                            ]
+                        }
+                    ]
+                },
+                "branch_condition_list": [
+                    {
+                        "index": 0,
+                        "height": 121.225,
+                        "id": "1009"
+                    },
+                    {
+                        "index": 1,
+                        "height": 121.225,
+                        "id": "4908"
+                    },
+                    {
+                        "index": 2,
+                        "height": 44,
+                        "id": "161"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "type": "reply-node",
+            "x": 2170,
+            "y": 2480,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "Content",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 378,
+                "stepName": "Specified Reply",
+                "node_data": {
+                    "fields": [
+                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                        "directly_return"
+                    ],
+                    "content": "",
+                    "reply_type": "referencing",
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3200,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI Answer Content",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI Chat",
+                "node_data": {
+                    "prompt": "Known information:\n{{Knowledge Search.data}}\nQuestion:\n{{Start.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3970,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI Answer Content",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI Chat1",
+                "node_data": {
+                    "prompt": "{{Start.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        }
+    ],
+    "edges": [
+        {
+            "id": "7d0f166f-c472-41b2-b9a2-c294f4c83d73",
+            "type": "app-edge",
+            "sourceNodeId": "start-node",
+            "targetNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "startPoint": {
+                "x": 590,
+                "y": 3660
+            },
+            "endPoint": {
+                "x": 680,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 590,
+                    "y": 3660
+                },
+                {
+                    "x": 700,
+                    "y": 3660
+                },
+                {
+                    "x": 570,
+                    "y": 3210
+                },
+                {
+                    "x": 680,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "start-node_right",
+            "targetAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_left"
+        },
+        {
+            "id": "35cb86dd-f328-429e-a973-12fd7218b696",
+            "type": "app-edge",
+            "sourceNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "targetNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "startPoint": {
+                "x": 1000,
+                "y": 3210
+            },
+            "endPoint": {
+                "x": 1200,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1000,
+                    "y": 3210
+                },
+                {
+                    "x": 1110,
+                    "y": 3210
+                },
+                {
+                    "x": 1090,
+                    "y": 3210
+                },
+                {
+                    "x": 1200,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_right",
+            "targetAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_left"
+        },
+        {
+            "id": "e8f6cfe6-7e48-41cd-abd3-abfb5304d0d8",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "startPoint": {
+                "x": 1780,
+                "y": 3073.775
+            },
+            "endPoint": {
+                "x": 2010,
+                "y": 2480
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1890,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1900,
+                    "y": 2480
+                },
+                {
+                    "x": 2010,
+                    "y": 2480
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_1009_right",
+            "targetAnchorId": "4ffe1086-25df-4c85-b168-979b5bbf0a26_left"
+        },
+        {
+            "id": "994ff325-6f7a-4ebc-b61b-10e15519d6d2",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "startPoint": {
+                "x": 1780,
+                "y": 3203
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3200
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3200
+                },
+                {
+                    "x": 2000,
+                    "y": 3200
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_4908_right",
+            "targetAnchorId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb_left"
+        },
+        {
+            "id": "19270caf-bb9f-4ba7-9bf8-200aa70fecd5",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "startPoint": {
+                "x": 1780,
+                "y": 3293.6124999999997
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3970
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3970
+                },
+                {
+                    "x": 2000,
+                    "y": 3970
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_161_right",
+            "targetAnchorId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7_left"
+        }
+    ]
+}

+ 451 - 0
apps/application/flow/default_workflow_zh.json

@@ -0,0 +1,451 @@
+{
+    "nodes": [
+        {
+            "id": "base-node",
+            "type": "base-node",
+            "x": 360,
+            "y": 2810,
+            "properties": {
+                "config": {
+
+                },
+                "height": 825.6,
+                "stepName": "基本信息",
+                "node_data": {
+                    "desc": "",
+                    "name": "maxkbapplication",
+                    "prologue": "您好,我是 MaxKB 小助手,您可以向我提出 MaxKB 使用问题。\n- MaxKB 主要功能有什么?\n- MaxKB 支持哪些大语言模型?\n- MaxKB 支持哪些文档类型?"
+                },
+                "input_field_list": [
+
+                ]
+            }
+        },
+        {
+            "id": "start-node",
+            "type": "start-node",
+            "x": 430,
+            "y": 3660,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "用户问题",
+                            "value": "question"
+                        }
+                    ],
+                    "globalFields": [
+                        {
+                            "label": "当前时间",
+                            "value": "time"
+                        }
+                    ]
+                },
+                "fields": [
+                    {
+                        "label": "用户问题",
+                        "value": "question"
+                    }
+                ],
+                "height": 276,
+                "stepName": "开始",
+                "globalFields": [
+                    {
+                        "label": "当前时间",
+                        "value": "time"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "type": "search-dataset-node",
+            "x": 840,
+            "y": 3210,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "检索结果的分段列表",
+                            "value": "paragraph_list"
+                        },
+                        {
+                            "label": "满足直接回答的分段列表",
+                            "value": "is_hit_handling_method_list"
+                        },
+                        {
+                            "label": "检索结果",
+                            "value": "data"
+                        },
+                        {
+                            "label": "满足直接回答的分段内容",
+                            "value": "directly_return"
+                        }
+                    ]
+                },
+                "height": 794,
+                "stepName": "知识库检索",
+                "node_data": {
+                    "dataset_id_list": [
+
+                    ],
+                    "dataset_setting": {
+                        "top_n": 3,
+                        "similarity": 0.6,
+                        "search_mode": "embedding",
+                        "max_paragraph_char_number": 5000
+                    },
+                    "question_reference_address": [
+                        "start-node",
+                        "question"
+                    ],
+                    "source_dataset_id_list": [
+
+                    ]
+                }
+            }
+        },
+        {
+            "id": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "type": "condition-node",
+            "x": 1490,
+            "y": 3210,
+            "properties": {
+                "width": 600,
+                "config": {
+                    "fields": [
+                        {
+                            "label": "分支名称",
+                            "value": "branch_name"
+                        }
+                    ]
+                },
+                "height": 543.675,
+                "stepName": "判断器",
+                "node_data": {
+                    "branch": [
+                        {
+                            "id": "1009",
+                            "type": "IF",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "is_hit_handling_method_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "4908",
+                            "type": "ELSE IF 1",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "paragraph_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "161",
+                            "type": "ELSE",
+                            "condition": "and",
+                            "conditions": [
+
+                            ]
+                        }
+                    ]
+                },
+                "branch_condition_list": [
+                    {
+                        "index": 0,
+                        "height": 121.225,
+                        "id": "1009"
+                    },
+                    {
+                        "index": 1,
+                        "height": 121.225,
+                        "id": "4908"
+                    },
+                    {
+                        "index": 2,
+                        "height": 44,
+                        "id": "161"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "type": "reply-node",
+            "x": 2170,
+            "y": 2480,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 378,
+                "stepName": "指定回复",
+                "node_data": {
+                    "fields": [
+                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                        "directly_return"
+                    ],
+                    "content": "",
+                    "reply_type": "referencing",
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3200,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 对话",
+                "node_data": {
+                    "prompt": "已知信息:\n{{知识库检索.data}}\n问题:\n{{开始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3970,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答内容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 对话1",
+                "node_data": {
+                    "prompt": "{{开始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        }
+    ],
+    "edges": [
+        {
+            "id": "7d0f166f-c472-41b2-b9a2-c294f4c83d73",
+            "type": "app-edge",
+            "sourceNodeId": "start-node",
+            "targetNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "startPoint": {
+                "x": 590,
+                "y": 3660
+            },
+            "endPoint": {
+                "x": 680,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 590,
+                    "y": 3660
+                },
+                {
+                    "x": 700,
+                    "y": 3660
+                },
+                {
+                    "x": 570,
+                    "y": 3210
+                },
+                {
+                    "x": 680,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "start-node_right",
+            "targetAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_left"
+        },
+        {
+            "id": "35cb86dd-f328-429e-a973-12fd7218b696",
+            "type": "app-edge",
+            "sourceNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "targetNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "startPoint": {
+                "x": 1000,
+                "y": 3210
+            },
+            "endPoint": {
+                "x": 1200,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1000,
+                    "y": 3210
+                },
+                {
+                    "x": 1110,
+                    "y": 3210
+                },
+                {
+                    "x": 1090,
+                    "y": 3210
+                },
+                {
+                    "x": 1200,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_right",
+            "targetAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_left"
+        },
+        {
+            "id": "e8f6cfe6-7e48-41cd-abd3-abfb5304d0d8",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "startPoint": {
+                "x": 1780,
+                "y": 3073.775
+            },
+            "endPoint": {
+                "x": 2010,
+                "y": 2480
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1890,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1900,
+                    "y": 2480
+                },
+                {
+                    "x": 2010,
+                    "y": 2480
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_1009_right",
+            "targetAnchorId": "4ffe1086-25df-4c85-b168-979b5bbf0a26_left"
+        },
+        {
+            "id": "994ff325-6f7a-4ebc-b61b-10e15519d6d2",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "startPoint": {
+                "x": 1780,
+                "y": 3203
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3200
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3200
+                },
+                {
+                    "x": 2000,
+                    "y": 3200
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_4908_right",
+            "targetAnchorId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb_left"
+        },
+        {
+            "id": "19270caf-bb9f-4ba7-9bf8-200aa70fecd5",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "startPoint": {
+                "x": 1780,
+                "y": 3293.6124999999997
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3970
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3970
+                },
+                {
+                    "x": 2000,
+                    "y": 3970
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_161_right",
+            "targetAnchorId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7_left"
+        }
+    ]
+}

+ 451 - 0
apps/application/flow/default_workflow_zh_Hant.json

@@ -0,0 +1,451 @@
+{
+    "nodes": [
+        {
+            "id": "base-node",
+            "type": "base-node",
+            "x": 360,
+            "y": 2810,
+            "properties": {
+                "config": {
+
+                },
+                "height": 825.6,
+                "stepName": "基本資訊",
+                "node_data": {
+                    "desc": "",
+                    "name": "maxkbapplication",
+                    "prologue": "您好,我是 MaxKB 小助手,您可以向我提出 MaxKB 使用問題。\n- MaxKB 主要功能有哪些?\n- MaxKB 支援哪些大型語言模型?\n- MaxKB 支援哪些文件類型?"
+                },
+                "input_field_list": [
+
+                ]
+            }
+        },
+        {
+            "id": "start-node",
+            "type": "start-node",
+            "x": 430,
+            "y": 3660,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "用戶問題",
+                            "value": "question"
+                        }
+                    ],
+                    "globalFields": [
+                        {
+                            "label": "當前時間",
+                            "value": "time"
+                        }
+                    ]
+                },
+                "fields": [
+                    {
+                        "label": "用戶問題",
+                        "value": "question"
+                    }
+                ],
+                "height": 276,
+                "stepName": "開始",
+                "globalFields": [
+                    {
+                        "label": "當前時間",
+                        "value": "time"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "type": "search-dataset-node",
+            "x": 840,
+            "y": 3210,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "檢索結果的分段列表",
+                            "value": "paragraph_list"
+                        },
+                        {
+                            "label": "滿足直接回答的分段列表",
+                            "value": "is_hit_handling_method_list"
+                        },
+                        {
+                            "label": "檢索結果",
+                            "value": "data"
+                        },
+                        {
+                            "label": "滿足直接回答的分段內容",
+                            "value": "directly_return"
+                        }
+                    ]
+                },
+                "height": 794,
+                "stepName": "知識庫檢索",
+                "node_data": {
+                    "dataset_id_list": [
+
+                    ],
+                    "dataset_setting": {
+                        "top_n": 3,
+                        "similarity": 0.6,
+                        "search_mode": "embedding",
+                        "max_paragraph_char_number": 5000
+                    },
+                    "question_reference_address": [
+                        "start-node",
+                        "question"
+                    ],
+                    "source_dataset_id_list": [
+
+                    ]
+                }
+            }
+        },
+        {
+            "id": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "type": "condition-node",
+            "x": 1490,
+            "y": 3210,
+            "properties": {
+                "width": 600,
+                "config": {
+                    "fields": [
+                        {
+                            "label": "分支名稱",
+                            "value": "branch_name"
+                        }
+                    ]
+                },
+                "height": 543.675,
+                "stepName": "判斷器",
+                "node_data": {
+                    "branch": [
+                        {
+                            "id": "1009",
+                            "type": "IF",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "is_hit_handling_method_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "4908",
+                            "type": "ELSE IF 1",
+                            "condition": "and",
+                            "conditions": [
+                                {
+                                    "field": [
+                                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                                        "paragraph_list"
+                                    ],
+                                    "value": "1",
+                                    "compare": "len_ge"
+                                }
+                            ]
+                        },
+                        {
+                            "id": "161",
+                            "type": "ELSE",
+                            "condition": "and",
+                            "conditions": [
+
+                            ]
+                        }
+                    ]
+                },
+                "branch_condition_list": [
+                    {
+                        "index": 0,
+                        "height": 121.225,
+                        "id": "1009"
+                    },
+                    {
+                        "index": 1,
+                        "height": 121.225,
+                        "id": "4908"
+                    },
+                    {
+                        "index": 2,
+                        "height": 44,
+                        "id": "161"
+                    }
+                ]
+            }
+        },
+        {
+            "id": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "type": "reply-node",
+            "x": 2170,
+            "y": 2480,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "內容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 378,
+                "stepName": "指定回覆",
+                "node_data": {
+                    "fields": [
+                        "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+                        "directly_return"
+                    ],
+                    "content": "",
+                    "reply_type": "referencing",
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3200,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答內容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 對話",
+                "node_data": {
+                    "prompt": "已知資訊:\n{{知識庫檢索.data}}\n問題:\n{{開始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        },
+        {
+            "id": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "type": "ai-chat-node",
+            "x": 2160,
+            "y": 3970,
+            "properties": {
+                "config": {
+                    "fields": [
+                        {
+                            "label": "AI 回答內容",
+                            "value": "answer"
+                        }
+                    ]
+                },
+                "height": 763,
+                "stepName": "AI 對話1",
+                "node_data": {
+                    "prompt": "{{開始.question}}",
+                    "system": "",
+                    "model_id": "",
+                    "dialogue_number": 0,
+                    "is_result": true
+                }
+            }
+        }
+    ],
+    "edges": [
+        {
+            "id": "7d0f166f-c472-41b2-b9a2-c294f4c83d73",
+            "type": "app-edge",
+            "sourceNodeId": "start-node",
+            "targetNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "startPoint": {
+                "x": 590,
+                "y": 3660
+            },
+            "endPoint": {
+                "x": 680,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 590,
+                    "y": 3660
+                },
+                {
+                    "x": 700,
+                    "y": 3660
+                },
+                {
+                    "x": 570,
+                    "y": 3210
+                },
+                {
+                    "x": 680,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "start-node_right",
+            "targetAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_left"
+        },
+        {
+            "id": "35cb86dd-f328-429e-a973-12fd7218b696",
+            "type": "app-edge",
+            "sourceNodeId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5",
+            "targetNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "startPoint": {
+                "x": 1000,
+                "y": 3210
+            },
+            "endPoint": {
+                "x": 1200,
+                "y": 3210
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1000,
+                    "y": 3210
+                },
+                {
+                    "x": 1110,
+                    "y": 3210
+                },
+                {
+                    "x": 1090,
+                    "y": 3210
+                },
+                {
+                    "x": 1200,
+                    "y": 3210
+                }
+            ],
+            "sourceAnchorId": "b931efe5-5b66-46e0-ae3b-0160cb18eeb5_right",
+            "targetAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_left"
+        },
+        {
+            "id": "e8f6cfe6-7e48-41cd-abd3-abfb5304d0d8",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "4ffe1086-25df-4c85-b168-979b5bbf0a26",
+            "startPoint": {
+                "x": 1780,
+                "y": 3073.775
+            },
+            "endPoint": {
+                "x": 2010,
+                "y": 2480
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1890,
+                    "y": 3073.775
+                },
+                {
+                    "x": 1900,
+                    "y": 2480
+                },
+                {
+                    "x": 2010,
+                    "y": 2480
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_1009_right",
+            "targetAnchorId": "4ffe1086-25df-4c85-b168-979b5bbf0a26_left"
+        },
+        {
+            "id": "994ff325-6f7a-4ebc-b61b-10e15519d6d2",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb",
+            "startPoint": {
+                "x": 1780,
+                "y": 3203
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3200
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3203
+                },
+                {
+                    "x": 1890,
+                    "y": 3200
+                },
+                {
+                    "x": 2000,
+                    "y": 3200
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_4908_right",
+            "targetAnchorId": "f1f1ee18-5a02-46f6-b4e6-226253cdffbb_left"
+        },
+        {
+            "id": "19270caf-bb9f-4ba7-9bf8-200aa70fecd5",
+            "type": "app-edge",
+            "sourceNodeId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b",
+            "targetNodeId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7",
+            "startPoint": {
+                "x": 1780,
+                "y": 3293.6124999999997
+            },
+            "endPoint": {
+                "x": 2000,
+                "y": 3970
+            },
+            "properties": {
+
+            },
+            "pointsList": [
+                {
+                    "x": 1780,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3293.6124999999997
+                },
+                {
+                    "x": 1890,
+                    "y": 3970
+                },
+                {
+                    "x": 2000,
+                    "y": 3970
+                }
+            ],
+            "sourceAnchorId": "fc60863a-dec2-4854-9e5a-7a44b7187a2b_161_right",
+            "targetAnchorId": "309d0eef-c597-46b5-8d51-b9a28aaef4c7_left"
+        }
+    ]
+}

+ 369 - 0
apps/application/flow/i_step_node.py

@@ -0,0 +1,369 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_step_node.py
+    @date:2024/6/3 14:57
+    @desc:
+"""
+import time
+import uuid
+from abc import abstractmethod
+from hashlib import sha1
+from typing import Type, Dict, List
+
+from django.core import cache
+from django.db.models import QuerySet
+from rest_framework import serializers
+from rest_framework.exceptions import ValidationError, ErrorDetail
+
+from application.flow.common import Answer, NodeChunk
+from application.models import ApplicationChatUserStats
+from application.models import ChatRecord, ChatUserType
+from common.field.common import InstanceField
+from knowledge.models.knowledge_action import KnowledgeAction, State
+from tools.models import ToolRecord
+
+chat_cache = cache
+
+
+def write_context(step_variable: Dict, global_variable: Dict, node, workflow):
+    if step_variable is not None:
+        for key in step_variable:
+            node.context[key] = step_variable[key]
+        if workflow.is_result(node, NodeResult(step_variable, global_variable)) and 'answer' in step_variable:
+            answer = step_variable['answer']
+            yield answer
+            node.answer_text = answer
+    if global_variable is not None:
+        for key in global_variable:
+            workflow.context[key] = global_variable[key]
+    node.context['run_time'] = time.time() - node.context['start_time']
+
+
+def is_interrupt(node, step_variable: Dict, global_variable: Dict):
+    return node.type == 'form-node' and not node.context.get('is_submit', False)
+
+
+class WorkFlowPostHandler:
+    def __init__(self, chat_info):
+        self.chat_info = chat_info
+
+    def handler(self, workflow):
+        workflow_body = workflow.get_body()
+        question = workflow_body.get('question')
+        chat_record_id = workflow_body.get('chat_record_id')
+        chat_id = workflow_body.get('chat_id')
+        details = workflow.get_runtime_details()
+        message_tokens = sum([row.get('message_tokens') for row in details.values() if
+                              'message_tokens' in row and row.get('message_tokens') is not None])
+        answer_tokens = sum([row.get('answer_tokens') for row in details.values() if
+                             'answer_tokens' in row and row.get('answer_tokens') is not None])
+        answer_text_list = workflow.get_answer_text_list()
+        answer_text = '\n\n'.join(
+            '\n\n'.join([a.get('content') for a in answer]) for answer in
+            answer_text_list)
+        if workflow.chat_record is not None:
+            chat_record = workflow.chat_record
+            chat_record.problem_text = question
+            chat_record.answer_text = answer_text
+            chat_record.details = details
+            chat_record.message_tokens = message_tokens
+            chat_record.answer_tokens = answer_tokens
+            chat_record.answer_text_list = answer_text_list
+            chat_record.run_time = time.time() - workflow.context['start_time']
+        else:
+            chat_record = ChatRecord(id=chat_record_id,
+                                     chat_id=chat_id,
+                                     problem_text=question,
+                                     answer_text=answer_text,
+                                     details=details,
+                                     message_tokens=message_tokens,
+                                     answer_tokens=answer_tokens,
+                                     answer_text_list=answer_text_list,
+                                     run_time=time.time() - workflow.context.get('start_time') if workflow.context.get(
+                                         'start_time') is not None else 0,
+                                     index=0,
+                                     ip_address=self.chat_info.ip_address,
+                                     source=self.chat_info.source)
+
+        self.chat_info.append_chat_record(chat_record)
+        self.chat_info.set_cache()
+
+        if not self.chat_info.debug and [ChatUserType.ANONYMOUS_USER.value, ChatUserType.CHAT_USER.value].__contains__(
+                workflow_body.get('chat_user_type')):
+            application_public_access_client = (QuerySet(ApplicationChatUserStats)
+                                                .filter(chat_user_id=workflow_body.get('chat_user_id'),
+                                                        chat_user_type=workflow_body.get('chat_user_type'),
+                                                        application_id=self.chat_info.application_id).first())
+            if application_public_access_client is not None:
+                application_public_access_client.access_num = application_public_access_client.access_num + 1
+                application_public_access_client.intraday_access_num = application_public_access_client.intraday_access_num + 1
+                application_public_access_client.save()
+        self.chat_info = None
+
+
+class KnowledgeWorkflowPostHandler(WorkFlowPostHandler):
+    def __init__(self, chat_info, knowledge_action_id):
+        super().__init__(chat_info)
+        self.knowledge_action_id = knowledge_action_id
+
+    def handler(self, workflow):
+        state = get_workflow_state(workflow)
+        QuerySet(KnowledgeAction).filter(id=self.knowledge_action_id).update(
+            state=state,
+            run_time=time.time() - workflow.context.get('start_time') if workflow.context.get(
+                'start_time') is not None else 0)
+
+
+def get_tool_workflow_state(workflow):
+    if workflow.is_the_task_interrupted():
+        return State.REVOKED
+    details = workflow.get_runtime_details()
+    node_list = details.values()
+    all_node = [*node_list, *get_loop_workflow_node(node_list)]
+    err = any([True for value in all_node if value.get('status') == 500 and not value.get('enableException')])
+    if err:
+        return State.FAILURE
+    return State.SUCCESS
+
+
+class ToolWorkflowCallPostHandler(WorkFlowPostHandler):
+    def __init__(self, chat_info, tool_id):
+        super().__init__(chat_info)
+        self.tool_id = tool_id
+
+    def handler(self, workflow):
+        self.chat_info = None
+        self.tool_id = None
+
+
+class ToolWorkflowPostHandler(WorkFlowPostHandler):
+    def __init__(self, chat_info, tool_id):
+        super().__init__(chat_info)
+        self.tool_id = tool_id
+
+    def handler(self, workflow):
+        state = get_tool_workflow_state(workflow)
+        record = ToolRecord(id=self.chat_info.tool_record_id, tool_id=self.tool_id,
+                            workspace_id=self.chat_info.workspace_id,
+                            source_type=self.chat_info.source_type,
+                            source_id=self.chat_info.source_id,
+                            state=state,
+                            run_time=time.time() - workflow.context.get('start_time') if workflow.context.get(
+                                'start_time') is not None else 0,
+                            meta={
+                                'input_field_list': workflow.get_input_field_list(),
+                                'output_field_list': workflow.get_output_field_list(),
+                                'input': workflow.get_input(),
+                                'output': workflow.out_context,
+                                'details': workflow.get_runtime_details(),
+                                'answer_text_list': workflow.get_answer_text_list()
+                            })
+        self.chat_info.set_record(record)
+        self.chat_info = None
+        self.tool_id = None
+
+
+def get_loop_workflow_node(node_list):
+    result = []
+    for item in node_list:
+        if item.get('type') == 'loop-node':
+            for loop_item in item.get('loop_node_data') or []:
+                for inner_item in loop_item.values():
+                    result.append(inner_item)
+    return result
+
+
+def get_workflow_state(workflow):
+    if workflow.is_the_task_interrupted():
+        return State.REVOKED
+    details = workflow.get_runtime_details()
+    node_list = details.values()
+    all_node = [*node_list, *get_loop_workflow_node(node_list)]
+    err = any([True for value in all_node if value.get('status') == 500 and not value.get('enableException')])
+    if err:
+        return State.FAILURE
+    write_is_exist = any([True for value in all_node if value.get('type') == 'knowledge-write-node'])
+    if not write_is_exist:
+        return State.FAILURE
+    return State.SUCCESS
+
+
+class NodeResult:
+    def __init__(self, node_variable: Dict, workflow_variable: Dict,
+                 _write_context=write_context, _is_interrupt=is_interrupt):
+        self._write_context = _write_context
+        self.node_variable = node_variable
+        self.workflow_variable = workflow_variable
+        self._is_interrupt = _is_interrupt
+
+    def write_context(self, node, workflow):
+        return self._write_context(self.node_variable, self.workflow_variable, node, workflow)
+
+    def is_assertion_result(self):
+        return 'branch_id' in self.node_variable
+
+    def is_interrupt_exec(self, current_node):
+        """
+        是否中断执行
+        @param current_node:
+        @return:
+        """
+        return self._is_interrupt(current_node, self.node_variable, self.workflow_variable)
+
+
+class ReferenceAddressSerializer(serializers.Serializer):
+    node_id = serializers.CharField(required=True, label="节点id")
+    fields = serializers.ListField(
+        child=serializers.CharField(required=True, label="节点字段"), required=True,
+        label="节点字段数组")
+
+
+class FlowParamsSerializer(serializers.Serializer):
+    # 历史对答
+    history_chat_record = serializers.ListField(child=InstanceField(model_type=ChatRecord, required=True),
+                                                label="历史对答")
+
+    question = serializers.CharField(required=True, label="用户问题")
+
+    chat_id = serializers.CharField(required=True, label="对话id")
+
+    chat_record_id = serializers.CharField(required=True, label="对话记录id")
+
+    stream = serializers.BooleanField(required=True, label="流式输出")
+
+    chat_user_id = serializers.CharField(required=False, label="对话用户id")
+
+    chat_user_type = serializers.CharField(required=False, label="对话用户类型")
+
+    workspace_id = serializers.CharField(required=True, label="工作空间id")
+
+    application_id = serializers.CharField(required=True, label="应用id")
+
+    re_chat = serializers.BooleanField(required=True, label="换个答案")
+
+    debug = serializers.BooleanField(required=True, label="是否debug")
+
+
+class KnowledgeFlowParamsSerializer(serializers.Serializer):
+    knowledge_id = serializers.UUIDField(required=True, label="知识库id")
+    workspace_id = serializers.CharField(required=True, label="工作空间id")
+    knowledge_action_id = serializers.UUIDField(required=True, label="知识库任务执行器id")
+    data_source = serializers.DictField(required=True, label="数据源")
+    knowledge_base = serializers.DictField(required=False, label="知识库设置")
+
+
+class ToolFlowParamsSerializer(serializers.Serializer):
+    tool_id = serializers.UUIDField(required=True, label="工具id")
+    workspace_id = serializers.CharField(required=True, label="工作空间id")
+
+
+class INode:
+    view_type = 'many_view'
+
+    @abstractmethod
+    def save_context(self, details, workflow_manage):
+        pass
+
+    def get_answer_list(self) -> List[Answer] | None:
+        if self.answer_text is None:
+            return None
+        reasoning_content_enable = self.context.get('model_setting', {}).get('reasoning_content_enable', False)
+        return [
+            Answer(self.answer_text, self.view_type, self.runtime_node_id, self.workflow_params.get('chat_record_id'),
+                   {},
+                   self.runtime_node_id, self.context.get('reasoning_content', '') if reasoning_content_enable else '')]
+
+    def __init__(self, node, workflow_params, workflow_manage, up_node_id_list=None,
+                 get_node_params=lambda node: node.properties.get('node_data'), salt=None):
+        # 当前步骤上下文,用于存储当前步骤信息
+        self.status = 200
+        self.err_message = ''
+        self.node = node
+        self.node_params = get_node_params(node)
+        self.workflow_params = workflow_params
+        self.workflow_manage = workflow_manage
+        self.node_params_serializer = None
+        self.flow_params_serializer = None
+        self.context = {}
+        self.answer_text = None
+        self.id = node.id
+        if up_node_id_list is None:
+            up_node_id_list = []
+        self.up_node_id_list = up_node_id_list
+        self.node_chunk = NodeChunk()
+        self.runtime_node_id = sha1(uuid.NAMESPACE_DNS.bytes + bytes(str(uuid.uuid5(uuid.NAMESPACE_DNS,
+                                                                                    "".join([*sorted(up_node_id_list),
+                                                                                             node.id]))),
+                                                                     "utf-8")).hexdigest() + (
+                                   "__" + str(salt) if salt is not None else '')
+        self.extra = {}
+
+    def valid_args(self, node_params, flow_params):
+        flow_params_serializer_class = self.get_flow_params_serializer_class()
+        node_params_serializer_class = self.get_node_params_serializer_class()
+        if flow_params_serializer_class is not None and flow_params is not None:
+            self.flow_params_serializer = flow_params_serializer_class(data=flow_params)
+            self.flow_params_serializer.is_valid(raise_exception=True)
+        if node_params_serializer_class is not None:
+            self.node_params_serializer = node_params_serializer_class(data=node_params)
+            self.node_params_serializer.is_valid(raise_exception=True)
+        if self.node.properties.get('status', 200) != 200:
+            raise ValidationError(ErrorDetail(f'节点{self.node.properties.get("stepName")} 不可用'))
+
+    def get_reference_field(self, fields: List[str]):
+        return self.get_field(self.context, fields)
+
+    @staticmethod
+    def get_field(obj, fields: List[str]):
+        for field in fields:
+            value = obj.get(field)
+            if value is None:
+                return None
+            else:
+                obj = value
+        return obj
+
+    @abstractmethod
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        pass
+
+    def get_flow_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return self.workflow_manage.get_params_serializer_class()
+
+    def get_write_error_context(self, e):
+        self.status = 500
+        self.answer_text = str(e)
+        self.err_message = str(e)
+        current_time = time.time()
+        self.context['run_time'] = current_time - (self.context.get('start_time') or current_time)
+
+        def write_error_context(answer, status=200):
+            pass
+
+        return write_error_context
+
+    def run(self) -> NodeResult:
+        """
+        :return: 执行结果
+        """
+        start_time = time.time()
+        self.context['start_time'] = start_time
+        result = self._run()
+        self.context['run_time'] = time.time() - start_time
+        return result
+
+    def _run(self):
+        result = self.execute()
+        return result
+
+    def execute(self, **kwargs) -> NodeResult:
+        pass
+
+    def get_details(self, index: int, **kwargs):
+        """
+        运行详情
+        :return: 步骤详情
+        """
+        return {}

+ 21 - 0
apps/application/flow/knowledge_loop_workflow_manage.py

@@ -0,0 +1,21 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: workflow_manage.py
+    @date:2024/1/9 17:40
+    @desc:
+"""
+from application.flow.i_step_node import KnowledgeFlowParamsSerializer
+from application.flow.loop_workflow_manage import LoopWorkflowManage
+
+
+class KnowledgeLoopWorkflowManage(LoopWorkflowManage):
+    def get_params_serializer_class(self):
+        return KnowledgeFlowParamsSerializer
+
+    def get_source_type(self):
+        return "KNOWLEDGE"
+
+    def get_source_id(self):
+        return self.params.get('knowledge_id')

+ 130 - 0
apps/application/flow/knowledge_workflow_manage.py

@@ -0,0 +1,130 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: Knowledge_workflow_manage.py
+    @date:2025/11/13 19:02
+    @desc:
+"""
+import time
+import traceback
+from concurrent.futures import ThreadPoolExecutor
+
+from django.db.models import QuerySet
+from django.utils.translation import get_language
+
+from application.flow.common import Workflow
+from application.flow.i_step_node import WorkFlowPostHandler, KnowledgeFlowParamsSerializer, NodeResult
+from application.flow.workflow_manage import WorkflowManage
+from common.handle.base_to_response import BaseToResponse
+from common.handle.impl.response.system_to_response import SystemToResponse
+from knowledge.models.knowledge_action import KnowledgeAction, State
+
+executor = ThreadPoolExecutor(max_workers=200)
+
+
+class KnowledgeWorkflowManage(WorkflowManage):
+
+    def __init__(self, flow: Workflow,
+                 params,
+                 work_flow_post_handler: WorkFlowPostHandler,
+                 base_to_response: BaseToResponse = SystemToResponse(),
+                 start_node_id=None,
+                 start_node_data=None, chat_record=None, child_node=None, is_the_task_interrupted=lambda: False):
+        super().__init__(flow, params, work_flow_post_handler, base_to_response, None, None, None,
+                         None,
+                         None, None, start_node_id, start_node_data, chat_record, child_node, is_the_task_interrupted)
+
+    def get_params_serializer_class(self):
+        return KnowledgeFlowParamsSerializer
+
+    def get_start_node(self):
+        start_node_list = [node for node in self.flow.nodes if
+                           self.params.get('data_source', {}).get('node_id') == node.id]
+        return start_node_list[0]
+
+    def run(self):
+        self.context['start_time'] = time.time()
+        executor.submit(self._run)
+
+    def _run(self):
+        QuerySet(KnowledgeAction).filter(id=self.params.get('knowledge_action_id')).update(
+            state=State.STARTED)
+        language = get_language()
+        self.run_chain_async(self.start_node, None, language)
+        while self.is_run():
+            pass
+        self.work_flow_post_handler.handler(self)
+
+    @staticmethod
+    def get_node_details(current_node, node, index):
+        if current_node == node:
+            return {
+                'name': node.node.properties.get('stepName'),
+                "index": index,
+                'run_time': 0,
+                'type': node.type,
+                'status': 202,
+                'err_message': ""
+            }
+
+        return node.get_details(index)
+
+    def run_chain(self, current_node, node_result_future=None):
+        QuerySet(KnowledgeAction).filter(id=self.params.get('knowledge_action_id')).update(
+            details=self.get_runtime_details(lambda node, index: self.get_node_details(current_node, node, index)))
+        if node_result_future is None:
+            node_result_future = self.run_node_future(current_node)
+        try:
+            result = self.hand_node_result(current_node, node_result_future)
+            return result
+        except Exception as e:
+            traceback.print_exc()
+        return None
+
+    def hand_node_result(self, current_node, node_result_future):
+        try:
+            current_result = node_result_future.result()
+            result = current_result.write_context(current_node, self)
+            if result is not None:
+                # 阻塞获取结果
+                list(result)
+            if current_node.status == 500:
+                enableException = current_node.node.properties.get('enableException')
+                if not enableException:
+                    return None
+                current_node.context['exception_message'] = current_node.err_message
+                current_node.context['branch_id'] = 'exception'
+                r = NodeResult({'branch_id': 'exception', 'exception': current_node.err_message}, {},
+                               _is_interrupt=lambda node, step_variable, global_variable: False)
+                r.write_context(current_node, self)
+                return r
+            if self.is_the_task_interrupted():
+                current_node.status = 201
+                return None
+            return current_result
+        except Exception as e:
+            traceback.print_exc()
+            self.status = 500
+            current_node.get_write_error_context(e)
+            self.answer += str(e)
+            if self.is_the_task_interrupted():
+                current_node.status = 201
+                return None
+            enableException = current_node.node.properties.get('enableException')
+            if enableException:
+                current_node.context['exception_message'] = current_node.err_message
+                current_node.context['branch_id'] = 'exception'
+                return NodeResult({'branch_id': 'exception', 'exception': current_node.err_message}, {},
+                                  _is_interrupt=lambda node, step_variable, global_variable: False)
+            QuerySet(KnowledgeAction).filter(id=self.params.get('knowledge_action_id')).update(state=State.FAILURE)
+        finally:
+            current_node.node_chunk.end()
+            QuerySet(KnowledgeAction).filter(id=self.params.get('knowledge_action_id')).update(
+                details=self.get_runtime_details())
+
+    def get_source_type(self):
+        return "KNOWLEDGE"
+
+    def get_source_id(self):
+        return self.params.get('knowledge_id')

+ 199 - 0
apps/application/flow/loop_workflow_manage.py

@@ -0,0 +1,199 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: workflow_manage.py
+    @date:2024/1/9 17:40
+    @desc:
+"""
+from concurrent.futures import ThreadPoolExecutor
+from typing import List
+
+from django.db import close_old_connections
+from django.utils.translation import get_language
+from langchain_core.prompts import PromptTemplate
+
+from application.flow.common import Workflow
+from application.flow.i_step_node import WorkFlowPostHandler, INode
+from application.flow.step_node import get_node
+from application.flow.workflow_manage import WorkflowManage
+from common.handle.base_to_response import BaseToResponse
+from common.handle.impl.response.system_to_response import SystemToResponse
+
+executor = ThreadPoolExecutor(max_workers=200)
+
+
+class NodeResultFuture:
+    def __init__(self, r, e, status=200):
+        self.r = r
+        self.e = e
+        self.status = status
+
+    def result(self):
+        if self.status == 200:
+            return self.r
+        else:
+            raise self.e
+
+
+def await_result(result, timeout=1):
+    try:
+        result.result(timeout)
+        return False
+    except Exception as e:
+        return True
+
+
+class NodeChunkManage:
+
+    def __init__(self, work_flow):
+        self.node_chunk_list = []
+        self.current_node_chunk = None
+        self.work_flow = work_flow
+
+    def add_node_chunk(self, node_chunk):
+        self.node_chunk_list.append(node_chunk)
+
+    def contains(self, node_chunk):
+        return self.node_chunk_list.__contains__(node_chunk)
+
+    def pop(self):
+        if self.current_node_chunk is None:
+            try:
+                current_node_chunk = self.node_chunk_list.pop(0)
+                self.current_node_chunk = current_node_chunk
+            except IndexError as e:
+                pass
+        if self.current_node_chunk is not None:
+            try:
+                chunk = self.current_node_chunk.chunk_list.pop(0)
+                return chunk
+            except IndexError as e:
+                if self.current_node_chunk.is_end():
+                    self.current_node_chunk = None
+                    if self.work_flow.answer_is_not_empty():
+                        chunk = self.work_flow.base_to_response.to_stream_chunk_response(
+                            self.work_flow.params['chat_id'],
+                            self.work_flow.params['chat_record_id'],
+                            '\n\n', False, 0, 0)
+                        self.work_flow.append_answer('\n\n')
+                        return chunk
+                    return self.pop()
+        return None
+
+
+class LoopWorkflowManage(WorkflowManage):
+
+    def __init__(self, flow: Workflow,
+                 params,
+                 work_flow_post_handler: WorkFlowPostHandler,
+                 parentWorkflowManage,
+                 loop_params,
+                 get_loop_context,
+                 base_to_response: BaseToResponse = SystemToResponse(),
+                 start_node_id=None,
+                 start_node_data=None, chat_record=None, child_node=None, is_the_task_interrupted=lambda: False):
+        self.parentWorkflowManage = parentWorkflowManage
+        self.loop_params = loop_params
+        self.get_loop_context = get_loop_context
+        self.loop_field_list = []
+        super().__init__(flow, params, work_flow_post_handler, base_to_response, None, None, None,
+                         None,
+                         None, None, start_node_id, start_node_data, chat_record, child_node, is_the_task_interrupted)
+
+    def get_node_cls_by_id(self, node_id, up_node_id_list=None,
+                           get_node_params=lambda node: node.properties.get('node_data')):
+        for node in self.flow.nodes:
+            if node.id == node_id:
+                node_instance = get_node(node.type, self.flow.workflow_mode)(node,
+                                                                             self.params, self, up_node_id_list,
+                                                                             get_node_params,
+                                                                             salt=self.get_index())
+                return node_instance
+        return None
+
+    def stream(self):
+        close_old_connections()
+        language = get_language()
+        self.run_chain_async(self.start_node, None, language)
+        return self.await_result(is_cleanup=False)
+
+    def get_index(self):
+        return self.loop_params.get('index')
+
+    def get_start_node(self):
+        start_node_list = [node for node in self.flow.nodes if
+                           ['loop-start-node'].__contains__(node.type)]
+        return start_node_list[0]
+
+    def get_reference_field(self, node_id: str, fields: List[str]):
+        """
+        @param node_id: 节点id
+        @param fields:  字段
+        @return:
+        """
+        if node_id == 'global':
+            return self.parentWorkflowManage.get_reference_field(node_id, fields)
+        elif node_id == 'chat':
+            return self.parentWorkflowManage.get_reference_field(node_id, fields)
+        elif node_id == 'loop':
+            loop_context = self.get_loop_context()
+            return INode.get_field(loop_context, fields)
+        else:
+            node = self.get_node_by_id(node_id)
+            if node:
+                return node.get_reference_field(fields)
+            return self.parentWorkflowManage.get_reference_field(node_id, fields)
+
+    def get_workflow_content(self):
+        context = {
+            'global': self.context,
+            'chat': self.chat_context,
+            'loop': self.get_loop_context(),
+        }
+
+        for node in self.node_context:
+            context[node.id] = node.context
+        return context
+
+    def init_fields(self):
+        super().init_fields()
+        loop_field_list = []
+        loop_start_node = self.flow.get_node('loop-start-node')
+        loop_input_field_list = loop_start_node.properties.get('loop_input_field_list')
+        node_name = loop_start_node.properties.get('stepName')
+        node_id = loop_start_node.id
+        if loop_input_field_list is not None:
+            for f in loop_input_field_list:
+                loop_field_list.append(
+                    {'label': f.get('label'), 'value': f.get('field'), 'node_id': node_id, 'node_name': node_name})
+        self.loop_field_list = loop_field_list
+
+    def reset_prompt(self, prompt: str):
+        prompt = super().reset_prompt(prompt)
+        for field in self.loop_field_list:
+            chatLabel = f"loop.{field.get('value')}"
+            chatValue = f"context.get('loop').get('{field.get('value', '')}','')"
+            prompt = prompt.replace(chatLabel, chatValue)
+
+        prompt = self.parentWorkflowManage.reset_prompt(prompt)
+        return prompt
+
+    def generate_prompt(self, prompt: str):
+        """
+        格式化生成提示词
+        @param prompt: 提示词信息
+        @return: 格式化后的提示词
+        """
+
+        context = {**self.get_workflow_content(), **self.parentWorkflowManage.get_workflow_content()}
+        prompt = self.reset_prompt(prompt)
+        prompt_template = PromptTemplate.from_template(prompt, template_format='jinja2')
+        value = prompt_template.format(context=context)
+        return value
+
+    def get_source_type(self):
+        return "APPLICATION"
+
+    def get_source_id(self):
+        return self.params.get('application_id')

+ 63 - 0
apps/application/flow/step_node/__init__.py

@@ -0,0 +1,63 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/6/7 14:43
+    @desc:
+"""
+from .ai_chat_step_node import *
+from .application_node import BaseApplicationNode
+from .condition_node import *
+from .data_source_local_node.impl.base_data_source_local_node import BaseDataSourceLocalNode
+from .data_source_web_node.impl.base_data_source_web_node import BaseDataSourceWebNode
+from .direct_reply_node import *
+from .document_extract_node import *
+from .form_node import *
+from .image_generate_step_node import *
+from .image_to_video_step_node import BaseImageToVideoNode
+from .image_understand_step_node import *
+from .intent_node import *
+from .knowledge_write_node.impl.base_knowledge_write_node import BaseKnowledgeWriteNode
+from .loop_break_node import BaseLoopBreakNode
+from .loop_continue_node import BaseLoopContinueNode
+from .loop_node import *
+from .loop_start_node import *
+from .mcp_node import BaseMcpNode
+from .parameter_extraction_node import BaseParameterExtractionNode
+from .question_node import *
+from .reranker_node import *
+from .search_document_node import BaseSearchDocumentNode
+from .search_knowledge_node import *
+from .speech_to_text_step_node import BaseSpeechToTextNode
+from .start_node import *
+from .text_to_speech_step_node.impl.base_text_to_speech_node import BaseTextToSpeechNode
+from .text_to_video_step_node.impl.base_text_to_video_node import BaseTextToVideoNode
+from .tool_lib_node import *
+from .tool_node import *
+from .tool_workflow_lib_node import BaseToolWorkflowLibNodeNode
+from .variable_aggregation_node.impl.base_variable_aggregation_node import BaseVariableAggregationNode
+from .variable_assign_node import BaseVariableAssignNode
+from .variable_splitting_node import BaseVariableSplittingNode
+from .video_understand_step_node import BaseVideoUnderstandNode
+from .document_split_node import BaseDocumentSplitNode
+from .tool_start_node import BaseToolStartStepNode
+
+node_list = [BaseStartStepNode, BaseChatNode, BaseSearchKnowledgeNode, BaseSearchDocumentNode, BaseQuestionNode,
+             BaseConditionNode, BaseReplyNode,
+             BaseToolNodeNode, BaseToolLibNodeNode, BaseRerankerNode, BaseApplicationNode,
+             BaseDocumentExtractNode,
+             BaseImageUnderstandNode, BaseFormNode, BaseSpeechToTextNode, BaseTextToSpeechNode,
+             BaseImageGenerateNode, BaseVariableAssignNode, BaseMcpNode, BaseTextToVideoNode, BaseImageToVideoNode,
+             BaseVideoUnderstandNode,
+             BaseIntentNode, BaseLoopNode, BaseLoopStartStepNode,
+             BaseLoopContinueNode,
+             BaseLoopBreakNode, BaseVariableSplittingNode, BaseParameterExtractionNode, BaseVariableAggregationNode,
+             BaseDataSourceLocalNode, BaseDataSourceWebNode, BaseKnowledgeWriteNode, BaseDocumentSplitNode,
+             BaseToolStartStepNode, BaseToolWorkflowLibNodeNode]
+
+node_map = {n.type: {w: n for w in n.support} for n in node_list}
+
+
+def get_node(node_type, workflow_model):
+    return node_map.get(node_type).get(workflow_model)

+ 9 - 0
apps/application/flow/step_node/ai_chat_step_node/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py
+    @date:2024/6/11 15:29
+    @desc:
+"""
+from .impl import *

+ 86 - 0
apps/application/flow/step_node/ai_chat_step_node/i_chat_node.py

@@ -0,0 +1,86 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_chat_node.py
+    @date:2024/6/4 13:58
+    @desc:
+"""
+from typing import Type
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+
+class ChatNodeSerializer(serializers.Serializer):
+    model_id = serializers.CharField(required=False, allow_blank=True, allow_null=True, label=_("Model id"))
+    model_id_type = serializers.CharField(required=False, default='custom', label=_("Model id type"))
+    model_id_reference = serializers.ListField(required=False, child=serializers.CharField(), allow_empty=True,
+                                               label=_("Reference Field"))
+    system = serializers.CharField(required=False, allow_blank=True, allow_null=True,
+                                   label=_("Role Setting"))
+    prompt = serializers.CharField(required=True, label=_("Prompt word"))
+    # 多轮对话数量
+    dialogue_number = serializers.IntegerField(required=True, label=_("Number of multi-round conversations"))
+
+    is_result = serializers.BooleanField(required=False,
+                                         label=_('Whether to return content'))
+
+    model_params_setting = serializers.DictField(required=False,
+                                                 label=_("Model parameter settings"))
+    model_setting = serializers.DictField(required=False,
+                                          label='Model settings')
+    dialogue_type = serializers.CharField(required=False, allow_blank=True, allow_null=True,
+                                          label=_("Context Type"))
+    mcp_servers = serializers.JSONField(required=False, label=_("MCP Server"))
+    mcp_tool_id = serializers.CharField(required=False, allow_blank=True, allow_null=True, label=_("MCP Tool ID"))
+    mcp_tool_ids = serializers.ListField(child=serializers.UUIDField(), required=False, allow_empty=True,
+                                         label=_("MCP Tool IDs"), )
+    mcp_source = serializers.CharField(required=False, allow_blank=True, allow_null=True, label=_("MCP Source"))
+
+    tool_ids = serializers.ListField(child=serializers.UUIDField(), required=False, allow_empty=True,
+                                     label=_("Tool IDs"), )
+    application_ids = serializers.ListField(child=serializers.UUIDField(), required=False, allow_empty=True,
+                                            label=_("App IDs"), )
+    skill_tool_ids = serializers.ListField(child=serializers.UUIDField(), required=False, allow_empty=True,
+                                           label=_("Skill IDs"), )
+    mcp_output_enable = serializers.BooleanField(required=False, default=True, label=_("Whether to enable MCP output"))
+
+
+class IChatNode(INode):
+    type = 'ai-chat-node'
+    support = [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.KNOWLEDGE_LOOP,
+               WorkflowMode.KNOWLEDGE, WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP]
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return ChatNodeSerializer
+
+    def _run(self):
+        if [WorkflowMode.KNOWLEDGE, WorkflowMode.KNOWLEDGE_LOOP, WorkflowMode.TOOL,
+            WorkflowMode.TOOL_LOOP].__contains__(
+            self.workflow_manage.flow.workflow_mode):
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data,
+                                **{'history_chat_record': [], 'stream': True, 'chat_id': None, 'chat_record_id': None})
+        else:
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data)
+
+    def execute(self, model_id, system, prompt, dialogue_number, history_chat_record, stream, chat_id,
+                chat_record_id,
+                model_params_setting=None,
+                model_id_type=None,
+                model_id_reference=None,
+                dialogue_type=None,
+                model_setting=None,
+                mcp_servers=None,
+                mcp_tool_id=None,
+                mcp_tool_ids=None,
+                mcp_source=None,
+                tool_ids=None,
+                application_ids=None,
+                skill_tool_ids=None,
+                mcp_output_enable=True,
+                **kwargs) -> NodeResult:
+        pass

+ 9 - 0
apps/application/flow/step_node/ai_chat_step_node/impl/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py
+    @date:2024/6/11 15:34
+    @desc:
+"""
+from .base_chat_node import BaseChatNode

+ 423 - 0
apps/application/flow/step_node/ai_chat_step_node/impl/base_chat_node.py

@@ -0,0 +1,423 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_question_node.py
+    @date:2024/6/4 14:30
+    @desc:
+"""
+import json
+import re
+import time
+from functools import reduce
+from typing import List, Dict
+
+from django.db.models import QuerySet
+from django.utils.translation import gettext as _
+from langchain_core.messages import BaseMessage, AIMessage, HumanMessage, SystemMessage
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import NodeResult, INode
+from application.flow.step_node.ai_chat_step_node.i_chat_node import IChatNode
+from application.flow.tools import Reasoning, mcp_response_generator, get_tools
+from application.models import Application, ApplicationApiKey, ApplicationAccessToken
+from common.exception.app_exception import AppApiException
+from common.utils.rsa_util import rsa_long_decrypt
+from common.utils.shared_resource_auth import filter_authorized_ids
+from common.utils.tool_code import ToolExecutor
+from models_provider.models import Model
+from models_provider.tools import get_model_credential, get_model_instance_by_model_workspace_id
+from tools.models import Tool, ToolType
+
+
+def _write_context(node_variable: Dict, workflow_variable: Dict, node: INode, workflow, answer: str,
+                   reasoning_content: str):
+    chat_model = node_variable.get('chat_model')
+    message_tokens = chat_model.get_num_tokens_from_messages(node_variable.get('message_list'))
+    answer_tokens = chat_model.get_num_tokens(answer)
+    node.context['message_tokens'] = message_tokens
+    node.context['answer_tokens'] = answer_tokens
+    node.context['answer'] = answer
+    node.context['question'] = node_variable['question']
+    node.context['run_time'] = time.time() - node.context['start_time']
+    node.context['reasoning_content'] = reasoning_content
+    if workflow.is_result(node, NodeResult(node_variable, workflow_variable)):
+        node.answer_text = answer
+
+
+def write_context_stream(node_variable: Dict, workflow_variable: Dict, node: INode, workflow):
+    """
+    写入上下文数据 (流式)
+    @param node_variable:      节点数据
+    @param workflow_variable:  全局数据
+    @param node:               节点
+    @param workflow:           工作流管理器
+    """
+    response = node_variable.get('result')
+    answer = ''
+    reasoning_content = ''
+    model_setting = node.context.get('model_setting',
+                                     {'reasoning_content_enable': False, 'reasoning_content_end': '</think>',
+                                      'reasoning_content_start': '<think>'})
+    reasoning = Reasoning(model_setting.get('reasoning_content_start', '<think>'),
+                          model_setting.get('reasoning_content_end', '</think>'))
+    response_reasoning_content = False
+
+    for chunk in response:
+        if workflow.is_the_task_interrupted():
+            break
+        reasoning_chunk = reasoning.get_reasoning_content(chunk)
+        content_chunk = reasoning_chunk.get('content')
+        if 'reasoning_content' in chunk.additional_kwargs:
+            response_reasoning_content = True
+            reasoning_content_chunk = chunk.additional_kwargs.get('reasoning_content', '')
+        else:
+            reasoning_content_chunk = reasoning_chunk.get('reasoning_content')
+        answer += content_chunk
+        if reasoning_content_chunk is None:
+            reasoning_content_chunk = ''
+        reasoning_content += reasoning_content_chunk
+        yield {'content': content_chunk,
+               'reasoning_content': reasoning_content_chunk if model_setting.get('reasoning_content_enable',
+                                                                                 False) else ''}
+
+    reasoning_chunk = reasoning.get_end_reasoning_content()
+    answer += reasoning_chunk.get('content')
+    reasoning_content_chunk = ""
+    if not response_reasoning_content:
+        reasoning_content_chunk = reasoning_chunk.get(
+            'reasoning_content')
+    yield {'content': reasoning_chunk.get('content'),
+           'reasoning_content': reasoning_content_chunk if model_setting.get('reasoning_content_enable',
+                                                                             False) else ''}
+    _write_context(node_variable, workflow_variable, node, workflow, answer, reasoning_content)
+
+
+def write_context(node_variable: Dict, workflow_variable: Dict, node: INode, workflow):
+    """
+    写入上下文数据
+    @param node_variable:      节点数据
+    @param workflow_variable:  全局数据
+    @param node:               节点实例对象
+    @param workflow:           工作流管理器
+    """
+    response = node_variable.get('result')
+    model_setting = node.context.get('model_setting',
+                                     {'reasoning_content_enable': False, 'reasoning_content_end': '</think>',
+                                      'reasoning_content_start': '<think>'})
+    reasoning = Reasoning(model_setting.get('reasoning_content_start'), model_setting.get('reasoning_content_end'))
+    reasoning_result = reasoning.get_reasoning_content(response)
+    reasoning_result_end = reasoning.get_end_reasoning_content()
+    content = reasoning_result.get('content') + reasoning_result_end.get('content')
+    meta = {**response.response_metadata, **response.additional_kwargs}
+    if 'reasoning_content' in meta:
+        reasoning_content = (meta.get('reasoning_content', '') or '')
+    else:
+        reasoning_content = (reasoning_result.get('reasoning_content') or '') + (
+                reasoning_result_end.get('reasoning_content') or '')
+    _write_context(node_variable, workflow_variable, node, workflow, content, reasoning_content)
+
+
+def get_default_model_params_setting(model_id):
+    model = QuerySet(Model).filter(id=model_id).first()
+    credential = get_model_credential(model.provider, model.model_type, model.model_name)
+    model_params_setting = credential.get_model_params_setting_form(
+        model.model_name).get_default_form_data()
+    return model_params_setting
+
+
+def get_node_message(chat_record, runtime_node_id):
+    node_details = chat_record.get_node_details_runtime_node_id(runtime_node_id)
+    if node_details is None:
+        return []
+    return [HumanMessage(node_details.get('question')), AIMessage(node_details.get('answer'))]
+
+
+def get_workflow_message(chat_record):
+    return [chat_record.get_human_message(), chat_record.get_ai_message()]
+
+
+def get_message(chat_record, dialogue_type, runtime_node_id):
+    return get_node_message(chat_record, runtime_node_id) if dialogue_type == 'NODE' else get_workflow_message(
+        chat_record)
+
+
+class BaseChatNode(IChatNode):
+    def save_context(self, details, workflow_manage):
+        self.context['answer'] = details.get('answer')
+        self.context['question'] = details.get('question')
+        self.context['reasoning_content'] = details.get('reasoning_content')
+        self.context['exception_message'] = details.get('err_message')
+        if self.node_params.get('is_result', False):
+            self.answer_text = details.get('answer')
+
+    def execute(self, model_id, system, prompt, dialogue_number, history_chat_record, stream, chat_id, chat_record_id,
+                model_params_setting=None,
+                model_id_type=None,
+                model_id_reference=None,
+                dialogue_type=None,
+                model_setting=None,
+                mcp_servers=None,
+                mcp_tool_id=None,
+                mcp_tool_ids=None,
+                mcp_source=None,
+                tool_ids=None,
+                application_ids=None,
+                skill_tool_ids=None,
+                mcp_output_enable=True,
+                **kwargs) -> NodeResult:
+        if dialogue_type is None:
+            dialogue_type = 'WORKFLOW'
+
+        if model_id_type == 'reference' and model_id_reference:
+
+            reference_data = self.workflow_manage.get_reference_field(
+                model_id_reference[0],
+                model_id_reference[1:],
+            )
+
+            if reference_data and isinstance(reference_data, dict):
+                model_id = reference_data.get('model_id', model_id)
+                model_params_setting = reference_data.get('model_params_setting')
+        if model_id is None or model_id == '':
+            raise Exception(_('Model is not allowed to be empty'))
+
+        if model_params_setting is None and model_id:
+            model_params_setting = get_default_model_params_setting(model_id)
+
+        if model_setting is None:
+            model_setting = {'reasoning_content_enable': False, 'reasoning_content_end': '</think>',
+                             'reasoning_content_start': '<think>'}
+        self.context['model_setting'] = model_setting
+        workspace_id = self.workflow_manage.get_body().get('workspace_id')
+        chat_model = get_model_instance_by_model_workspace_id(model_id, workspace_id,
+                                                              **(model_params_setting or {}))
+        history_message = self.get_history_message(history_chat_record, dialogue_number, dialogue_type,
+                                                   self.runtime_node_id)
+        self.context['history_message'] = [{'content': message.content, 'role': message.type} for message in
+                                           (history_message if history_message is not None else [])]
+        question = self.generate_prompt_question(prompt)
+        self.context['question'] = question.content
+        system = self.workflow_manage.generate_prompt(system)
+        self.context['system'] = system
+        message_list = self.generate_message_list(system, prompt, history_message)
+        self.context['message_list'] = message_list
+
+        # 过滤tool_id
+        all_tool_ids = list(set(
+            (mcp_tool_ids or []) +
+            (tool_ids or []) +
+            (skill_tool_ids or []) +
+            ([mcp_tool_id] if mcp_tool_id else [])
+        ))
+        authorized_set = set(filter_authorized_ids('tool', all_tool_ids, workspace_id))
+
+        mcp_tool_ids = [i for i in (mcp_tool_ids or []) if i in authorized_set]
+        tool_ids = [i for i in (tool_ids or []) if i in authorized_set]
+        skill_tool_ids = [i for i in (skill_tool_ids or []) if i in authorized_set]
+        mcp_tool_id = mcp_tool_id if (mcp_tool_id and mcp_tool_id in authorized_set) else None
+        # 处理 MCP 请求
+        mcp_result = self._handle_mcp_request(
+            mcp_source, mcp_servers, mcp_tool_id, mcp_tool_ids, tool_ids,
+            application_ids, skill_tool_ids, mcp_output_enable,
+            chat_model, message_list, history_message, question, chat_id, workspace_id
+        )
+        if mcp_result:
+            return mcp_result
+
+        if stream:
+            r = chat_model.stream(message_list)
+            return NodeResult({'result': r, 'chat_model': chat_model, 'message_list': message_list,
+                               'question': question.content}, {},
+                              _write_context=write_context_stream)
+        else:
+            r = chat_model.invoke(message_list)
+            return NodeResult({'result': r, 'chat_model': chat_model, 'message_list': message_list,
+                               'history_message': [{'content': message.content, 'role': message.type} for message in
+                                                   (history_message if history_message is not None else [])],
+                               'question': question.content}, {},
+                              _write_context=write_context)
+
+    def _handle_mcp_request(self, mcp_source, mcp_servers, mcp_tool_id, mcp_tool_ids, tool_ids,
+                            application_ids, skill_tool_ids,
+                            mcp_output_enable, chat_model, message_list, history_message, question, chat_id,
+                            workspace_id):
+
+        mcp_servers_config = {}
+
+        # 迁移过来mcp_source是None
+        if mcp_source is None:
+            mcp_source = 'custom'
+        # 兼容老数据
+        if not mcp_tool_ids:
+            mcp_tool_ids = []
+        if mcp_tool_id:
+            mcp_tool_ids = list(set(mcp_tool_ids + [mcp_tool_id]))
+        if mcp_source == 'custom' and mcp_servers:
+            ToolExecutor().validate_mcp_transport(mcp_servers)
+            mcp_servers_config = json.loads(mcp_servers)
+            mcp_servers_config = self.handle_variables(mcp_servers_config)
+        elif mcp_tool_ids:
+            mcp_tools = QuerySet(Tool).filter(id__in=mcp_tool_ids).values()
+            for mcp_tool in mcp_tools:
+                if mcp_tool and mcp_tool['is_active']:
+                    mcp_servers_config = {**mcp_servers_config, **json.loads(mcp_tool['code'])}
+                    mcp_servers_config = self.handle_variables(mcp_servers_config)
+        tool_init_params = {}
+        tools = get_tools(self.workflow_manage.get_source_type(), self.workflow_manage.get_source_id(), tool_ids,
+                          workspace_id)
+        if tool_ids and len(tool_ids) > 0:  # 如果有工具ID,则将其转换为MCP
+            self.context['tool_ids'] = tool_ids
+            for tool_id in tool_ids:
+                tool = QuerySet(Tool).filter(id=tool_id, tool_type=ToolType.CUSTOM).first()
+                if tool is None or not tool.is_active:
+                    continue
+                executor = ToolExecutor()
+                if tool.init_params is not None:
+                    params = json.loads(rsa_long_decrypt(tool.init_params))
+                    tool_init_params = json.loads(rsa_long_decrypt(tool.init_params))
+                else:
+                    params = {}
+                tool_config = executor.get_tool_mcp_config(tool, params)
+
+                mcp_servers_config[str(tool.id)] = tool_config
+
+        if application_ids and len(application_ids) > 0:
+            self.context['application_ids'] = application_ids
+            for application_id in application_ids:
+                app = QuerySet(Application).filter(id=application_id, is_publish=True).first()
+                if app is None:
+                    continue
+                app_key = QuerySet(ApplicationApiKey).filter(application_id=application_id, is_active=True).first()
+                if app_key is not None:
+                    api_key = app_key.secret_key
+                    application_access_token = QuerySet(ApplicationAccessToken).filter(
+                        application_id=app_key.application_id
+                    ).first()
+                    if application_access_token is not None and application_access_token.authentication:
+                        raise AppApiException(
+                            500,
+                            _('Agent 【{name}】 access token authentication is not supported for agent tool').format(
+                                name=app.name)
+                        )
+                else:
+                    raise AppApiException(
+                        500,
+                        _('Agent Key is required for agent tool 【{name}】').format(name=app.name)
+                    )
+                executor = ToolExecutor()
+                app_config = executor.get_app_mcp_config(api_key)
+                mcp_servers_config[app.name] = app_config
+
+        if skill_tool_ids and len(skill_tool_ids) > 0:
+            self.context['skill_tool_ids'] = skill_tool_ids
+            skill_file_items = []
+
+            for tool_id in skill_tool_ids:
+                tool = QuerySet(Tool).filter(id=tool_id, is_active=True).first()
+                if tool is None or tool.is_active is False:
+                    continue
+                init_params_default_value = {i["field"]: i.get('default_value') for i in tool.init_field_list}
+                if tool.init_params is not None:
+                    params = init_params_default_value | json.loads(rsa_long_decrypt(tool.init_params))
+                else:
+                    params = init_params_default_value
+
+                skill_file_items.append({
+                    'tool_id': str(tool.id),
+                    'file_id': tool.code,
+                    'params': params
+                })
+            mcp_servers_config['skills'] = skill_file_items
+
+        if len(mcp_servers_config) > 0 or len(tools) > 0:
+            # 安全获取 application
+            application_id = None
+            tool_id = None
+            knowledge_id = None
+            if [WorkflowMode.KNOWLEDGE, WorkflowMode.KNOWLEDGE_LOOP].__contains__(
+                    self.workflow_manage.flow.workflow_mode):
+                knowledge_id = self.workflow_params.get('knowledge_id')
+            elif [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP].__contains__(
+                    self.workflow_manage.flow.workflow_mode):
+                application_id = self.workflow_manage.work_flow_post_handler.chat_info.application.id
+            elif [WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP].__contains__(self.workflow_manage.flow.workflow_mode):
+                tool_id = self.workflow_params.get('tool_id')
+
+            source_id = application_id or knowledge_id or tool_id
+            source_type = 'APPLICATION' if application_id else 'KNOWLEDGE' if knowledge_id else 'TOOL'
+            r = mcp_response_generator(chat_model, message_list, json.dumps(mcp_servers_config), mcp_output_enable,
+                                       tool_init_params, source_id, source_type, chat_id, tools)
+            return NodeResult(
+                {'result': r, 'chat_model': chat_model, 'message_list': message_list,
+                 'history_message': [{'content': message.content, 'role': message.type} for message in
+                                     (history_message if history_message is not None else [])],
+                 'question': question.content}, {},
+                _write_context=write_context_stream)
+
+        return None
+
+    def handle_variables(self, tool_params):
+        # 处理参数中的变量
+        for k, v in tool_params.items():
+            if type(v) == str:
+                tool_params[k] = self.workflow_manage.generate_prompt(tool_params[k])
+            elif type(v) == dict:
+                self.handle_variables(v)
+            elif (type(v) == list) and len(v) > 0 and type(v[0]) == str:
+                tool_params[k] = self.get_reference_content(v)
+        return tool_params
+
+    def get_reference_content(self, fields: List[str]):
+        return str(self.workflow_manage.get_reference_field(
+            fields[0],
+            fields[1:]))
+
+    @staticmethod
+    def get_history_message(history_chat_record, dialogue_number, dialogue_type, runtime_node_id):
+        start_index = len(history_chat_record) - dialogue_number
+        history_message = reduce(lambda x, y: [*x, *y], [
+            get_message(history_chat_record[index], dialogue_type, runtime_node_id)
+            for index in
+            range(start_index if start_index > 0 else 0, len(history_chat_record))], [])
+        for message in history_message:
+            if isinstance(message.content, str):
+                message.content = re.sub('<form_rander>[\d\D]*?<\/form_rander>', '', message.content)
+        return history_message
+
+    def generate_prompt_question(self, prompt):
+        return HumanMessage(self.workflow_manage.generate_prompt(prompt))
+
+    def generate_message_list(self, system: str, prompt: str, history_message):
+        if system is not None and len(system) > 0:
+            return [SystemMessage(self.workflow_manage.generate_prompt(system)), *history_message,
+                    HumanMessage(self.workflow_manage.generate_prompt(prompt))]
+        else:
+            return [*history_message, HumanMessage(self.workflow_manage.generate_prompt(prompt))]
+
+    @staticmethod
+    def reset_message_list(message_list: List[BaseMessage], answer_text):
+        result = [{'role': 'user' if isinstance(message, HumanMessage) else 'ai', 'content': message.content} for
+                  message
+                  in
+                  message_list]
+        result.append({'role': 'ai', 'content': answer_text})
+        return result
+
+    def get_details(self, index: int, **kwargs):
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'system': self.context.get('system'),
+            'history_message': self.context.get('history_message'),
+            'question': self.context.get('question'),
+            'answer': self.context.get('answer'),
+            'reasoning_content': self.context.get('reasoning_content'),
+            'enableException': self.node.properties.get('enableException'),
+            'type': self.node.type,
+            'message_tokens': self.context.get('message_tokens'),
+            'answer_tokens': self.context.get('answer_tokens'),
+            'status': self.status,
+            'err_message': self.err_message
+        }

+ 2 - 0
apps/application/flow/step_node/application_node/__init__.py

@@ -0,0 +1,2 @@
+# coding=utf-8
+from .impl import *

+ 106 - 0
apps/application/flow/step_node/application_node/i_application_node.py

@@ -0,0 +1,106 @@
+# coding=utf-8
+from typing import Type
+
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+from django.utils.translation import gettext_lazy as _
+
+from application.models import ChatSourceChoices
+
+
+class ApplicationNodeSerializer(serializers.Serializer):
+    application_id = serializers.CharField(required=True, label=_("Application ID"))
+    question_reference_address = serializers.ListField(required=True,
+                                                       label=_("User Questions"))
+    api_input_field_list = serializers.ListField(required=False, label=_("API Input Fields"))
+    user_input_field_list = serializers.ListField(required=False,
+                                                  label=_("User Input Fields"))
+    image_list = serializers.ListField(required=False, label=_("picture"))
+    document_list = serializers.ListField(required=False, label=_("document"))
+    audio_list = serializers.ListField(required=False, label=_("Audio"))
+    video_list = serializers.ListField(required=False, label=_("Video"))
+    child_node = serializers.DictField(required=False, allow_null=True,
+                                       label=_("Child Nodes"))
+    node_data = serializers.DictField(required=False, allow_null=True, label=_("Form Data"))
+
+
+class IApplicationNode(INode):
+    type = 'application-node'
+    support = [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP]
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return ApplicationNodeSerializer
+
+    def _run(self):
+        question = self.workflow_manage.get_reference_field(
+            self.node_params_serializer.data.get('question_reference_address')[0],
+            self.node_params_serializer.data.get('question_reference_address')[1:])
+        kwargs = {}
+        for api_input_field in self.node_params_serializer.data.get('api_input_field_list', []):
+            value = api_input_field.get('value', [''])[0] if api_input_field.get('value') else ''
+            kwargs[api_input_field['variable']] = self.workflow_manage.get_reference_field(value,
+                                                                                           api_input_field['value'][
+                                                                                           1:]) if value != '' else ''
+
+        for user_input_field in self.node_params_serializer.data.get('user_input_field_list', []):
+            value = user_input_field.get('value', [''])[0] if user_input_field.get('value') else ''
+            kwargs[user_input_field['field']] = self.workflow_manage.get_reference_field(value,
+                                                                                         user_input_field['value'][
+                                                                                         1:]) if value != '' else ''
+        # 判断是否包含这个属性
+        app_document_list = self.node_params_serializer.data.get('document_list', [])
+        if app_document_list and len(app_document_list) > 0:
+            app_document_list = self.workflow_manage.get_reference_field(
+                app_document_list[0],
+                app_document_list[1:])
+            for document in app_document_list:
+                if 'file_id' not in document:
+                    raise ValueError(
+                        _("Parameter value error: The uploaded document lacks file_id, and the document upload fails"))
+        app_image_list = self.node_params_serializer.data.get('image_list', [])
+        if app_image_list and len(app_image_list) > 0:
+            app_image_list = self.workflow_manage.get_reference_field(
+                app_image_list[0],
+                app_image_list[1:])
+            for image in app_image_list:
+                if 'file_id' not in image:
+                    raise ValueError(
+                        _("Parameter value error: The uploaded image lacks file_id, and the image upload fails"))
+
+        app_audio_list = self.node_params_serializer.data.get('audio_list', [])
+        if app_audio_list and len(app_audio_list) > 0:
+            app_audio_list = self.workflow_manage.get_reference_field(
+                app_audio_list[0],
+                app_audio_list[1:])
+            for audio in app_audio_list:
+                if 'file_id' not in audio:
+                    raise ValueError(
+                        _("Parameter value error: The uploaded audio lacks file_id, and the audio upload fails."))
+        app_video_list = self.node_params_serializer.data.get('video_list', [])
+        if app_video_list and len(app_video_list) > 0:
+            app_video_list = self.workflow_manage.get_reference_field(
+                app_video_list[0],
+                app_video_list[1:]
+            )
+            for video in app_video_list:
+                if 'file_id' not in video:
+                    raise ValueError(
+                        _("Parameter value error: The uploaded video lacks file_id, and the video upload fails."))
+        return self.execute(**{**self.flow_params_serializer.data, **self.node_params_serializer.data},
+                            app_document_list=app_document_list, app_image_list=app_image_list,
+                            app_audio_list=app_audio_list,
+                            app_video_list=app_video_list,
+                            ip_address=self.workflow_params.get('ip_address') or '-',
+                            source=self.workflow_params.get('source') or {"type": ChatSourceChoices.ONLINE.value},
+                            message=str(question), **kwargs)
+
+    def execute(self, application_id, message, chat_id, chat_record_id, stream, re_chat, client_id, client_type,
+                app_document_list=None, app_image_list=None, app_audio_list=None, app_video_list=None, child_node=None,
+                node_data=None,
+                ip_address=None,
+                source=None,
+                **kwargs) -> NodeResult:
+        pass

+ 2 - 0
apps/application/flow/step_node/application_node/impl/__init__.py

@@ -0,0 +1,2 @@
+# coding=utf-8
+from .base_application_node import BaseApplicationNode

+ 298 - 0
apps/application/flow/step_node/application_node/impl/base_application_node.py

@@ -0,0 +1,298 @@
+# coding=utf-8
+import json
+import re
+import time
+import uuid
+from typing import Dict, List
+from django.utils.translation import gettext as _
+from application.flow.common import Answer
+from application.flow.i_step_node import NodeResult, INode
+from application.flow.step_node.application_node.i_application_node import IApplicationNode
+from application.models import Chat, ChatSourceChoices
+
+
+def string_to_uuid(input_str):
+    return str(uuid.uuid5(uuid.NAMESPACE_DNS, input_str))
+
+
+def _is_interrupt_exec(node, node_variable: Dict, workflow_variable: Dict):
+    return node_variable.get('is_interrupt_exec', False)
+
+
+def _write_context(node_variable: Dict, workflow_variable: Dict, node: INode, workflow, answer: str,
+                   reasoning_content: str):
+    result = node_variable.get('result')
+    node.context['application_node_dict'] = node_variable.get('application_node_dict')
+    node.context['node_dict'] = node_variable.get('node_dict', {})
+    node.context['is_interrupt_exec'] = node_variable.get('is_interrupt_exec')
+    node.context['message_tokens'] = result.get('usage', {}).get('prompt_tokens', 0)
+    node.context['answer_tokens'] = result.get('usage', {}).get('completion_tokens', 0)
+    node.context['answer'] = answer
+    node.context['result'] = answer
+    node.context['reasoning_content'] = reasoning_content
+    node.context['question'] = node_variable['question']
+    node.context['run_time'] = time.time() - node.context['start_time']
+    if workflow.is_result(node, NodeResult(node_variable, workflow_variable)):
+        node.answer_text = answer
+
+
+def write_context_stream(node_variable: Dict, workflow_variable: Dict, node: INode, workflow):
+    """
+    写入上下文数据 (流式)
+    @param node_variable:      节点数据
+    @param workflow_variable:  全局数据
+    @param node:               节点
+    @param workflow:           工作流管理器
+    """
+    response = node_variable.get('result')
+    answer = ''
+    reasoning_content = ''
+    usage = {}
+    node_child_node = {}
+    application_node_dict = node.context.get('application_node_dict', {})
+    is_interrupt_exec = False
+    for chunk in response:
+        # 先把流转成字符串
+        response_content = chunk.decode('utf-8')[6:]
+        response_content = json.loads(response_content)
+        content = (response_content.get('content', '') or '')
+        runtime_node_id = response_content.get('runtime_node_id', '')
+        chat_record_id = response_content.get('chat_record_id', '')
+        child_node = response_content.get('child_node')
+        view_type = response_content.get('view_type')
+        node_type = response_content.get('node_type')
+        real_node_id = response_content.get('real_node_id')
+        node_is_end = response_content.get('node_is_end', False)
+        _reasoning_content = (response_content.get('reasoning_content', '') or '')
+        if node_type == 'form-node':
+            is_interrupt_exec = True
+        answer += content
+        reasoning_content += _reasoning_content
+        node_child_node = {'runtime_node_id': runtime_node_id, 'chat_record_id': chat_record_id,
+                           'child_node': child_node}
+
+        if real_node_id is not None:
+            application_node = application_node_dict.get(real_node_id, None)
+            if application_node is None:
+
+                application_node_dict[real_node_id] = {'content': content,
+                                                       'runtime_node_id': runtime_node_id,
+                                                       'chat_record_id': chat_record_id,
+                                                       'child_node': child_node,
+                                                       'index': len(application_node_dict),
+                                                       'view_type': view_type,
+                                                       'reasoning_content': _reasoning_content}
+            else:
+                application_node['content'] += content
+                application_node['reasoning_content'] += _reasoning_content
+
+        yield {'content': content,
+               'node_type': node_type,
+               'runtime_node_id': runtime_node_id, 'chat_record_id': chat_record_id,
+               'reasoning_content': _reasoning_content,
+               'child_node': child_node,
+               'real_node_id': real_node_id,
+               'node_is_end': node_is_end,
+               'view_type': view_type}
+        usage = response_content.get('usage', {})
+    node_variable['result'] = {'usage': usage}
+    node_variable['is_interrupt_exec'] = is_interrupt_exec
+    node_variable['child_node'] = node_child_node
+    node_variable['application_node_dict'] = application_node_dict
+    _write_context(node_variable, workflow_variable, node, workflow, answer, reasoning_content)
+
+
+def write_context(node_variable: Dict, workflow_variable: Dict, node: INode, workflow):
+    """
+    写入上下文数据
+    @param node_variable:      节点数据
+    @param workflow_variable:  全局数据
+    @param node:               节点实例对象
+    @param workflow:           工作流管理器
+    """
+    response = node_variable.get('result', {}).get('data', {})
+    node_variable['result'] = {'usage': {'completion_tokens': response.get('completion_tokens'),
+                                         'prompt_tokens': response.get('prompt_tokens')}}
+    answer = response.get('content', '') or "抱歉,没有查找到相关内容,请重新描述您的问题或提供更多信息。"
+    reasoning_content = response.get('reasoning_content', '')
+    answer_list = response.get('answer_list', [])
+    node_variable['application_node_dict'] = {answer.get('real_node_id'): {**answer, 'index': index} for answer, index
+                                              in
+                                              zip(answer_list, range(len(answer_list)))}
+    _write_context(node_variable, workflow_variable, node, workflow, answer, reasoning_content)
+
+
+def reset_application_node_dict(application_node_dict, runtime_node_id, node_data):
+    try:
+        if application_node_dict is None:
+            return
+        for key in application_node_dict:
+            application_node = application_node_dict[key]
+            if application_node.get('runtime_node_id') == runtime_node_id:
+                content: str = application_node.get('content')
+                match = re.search('<form_rander>.*?</form_rander>', content)
+                if match:
+                    form_setting_str = match.group().replace('<form_rander>', '').replace('</form_rander>', '')
+                    form_setting = json.loads(form_setting_str)
+                    form_setting['is_submit'] = True
+                    form_setting['form_data'] = node_data
+                    value = f'<form_rander>{json.dumps(form_setting)}</form_rander>'
+                    res = re.sub('<form_rander>.*?</form_rander>',
+                                 '${value}', content)
+                    application_node['content'] = res.replace('${value}', value)
+    except Exception as e:
+        pass
+
+
+class BaseApplicationNode(IApplicationNode):
+    def get_answer_list(self) -> List[Answer] | None:
+        if self.answer_text is None:
+            return None
+        application_node_dict = self.context.get('application_node_dict')
+        if application_node_dict is None or len(application_node_dict) == 0:
+            return [
+                Answer(self.answer_text, self.view_type, self.runtime_node_id, self.workflow_params['chat_record_id'],
+                       self.context.get('child_node'), self.runtime_node_id, '')]
+        else:
+            return [Answer(n.get('content'), n.get('view_type'), self.runtime_node_id,
+                           self.workflow_params['chat_record_id'], {'runtime_node_id': n.get('runtime_node_id'),
+                                                                    'chat_record_id': n.get('chat_record_id')
+                               , 'child_node': n.get('child_node')}, n.get('real_node_id'),
+                           n.get('reasoning_content', ''))
+                    for n in
+                    sorted(application_node_dict.values(), key=lambda item: item.get('index'))]
+
+    def save_context(self, details, workflow_manage):
+        self.context['answer'] = details.get('answer')
+        self.context['result'] = details.get('answer')
+        self.context['question'] = details.get('question')
+        self.context['type'] = details.get('type')
+        self.context['reasoning_content'] = details.get('reasoning_content')
+        self.context['exception_message'] = details.get('err_message')
+        if self.node_params.get('is_result', False):
+            self.answer_text = details.get('answer')
+
+    def get_chat_asker(self, kwargs):
+        asker = kwargs.get('asker')
+        if asker:
+            if isinstance(asker, dict):
+                return asker
+            return {'username': asker}
+        return self.workflow_manage.work_flow_post_handler.chat_info.get_chat_user()
+
+    def execute(self, application_id, message, chat_id, chat_record_id, stream, re_chat,
+                chat_user_id,
+                chat_user_type,
+                app_document_list=None, app_image_list=None, app_audio_list=None, app_video_list=None, child_node=None,
+                node_data=None,
+                ip_address=None,
+                source=None,
+                **kwargs) -> NodeResult:
+        from chat.serializers.chat import ChatSerializers
+        if application_id == self.workflow_manage.get_body().get('application_id'):
+            raise Exception(_("The sub application cannot use the current node"))
+        # 生成嵌入应用的chat_id
+        current_chat_id = string_to_uuid(chat_id + application_id)
+        Chat.objects.get_or_create(id=current_chat_id, defaults={
+            'application_id': application_id,
+            'abstract': message[0:1024],
+            'chat_user_id': chat_user_id,
+            'chat_user_type': chat_user_type,
+            'ip_address': ip_address,
+            'source': source,
+            'asker': self.get_chat_asker(kwargs)
+        })
+        if app_document_list is None:
+            app_document_list = []
+        if app_image_list is None:
+            app_image_list = []
+        if app_audio_list is None:
+            app_audio_list = []
+        if app_video_list is None:
+            app_video_list = []
+        runtime_node_id = None
+        record_id = None
+        child_node_value = None
+        if child_node is not None:
+            runtime_node_id = child_node.get('runtime_node_id')
+            record_id = child_node.get('chat_record_id')
+            child_node_value = child_node.get('child_node')
+            application_node_dict = self.context.get('application_node_dict')
+            reset_application_node_dict(application_node_dict, runtime_node_id, node_data)
+        response = ChatSerializers(data={
+            "chat_id": current_chat_id,
+            "chat_user_id": chat_user_id,
+            'chat_user_type': chat_user_type,
+            'application_id': application_id,
+            'ip_address': ip_address,
+            'source': source,
+            'debug': False
+        }).chat(instance=
+                {'message': message,
+                 're_chat': re_chat,
+                 'stream': stream,
+                 'document_list': [*app_document_list],
+                 'image_list': [*app_image_list],
+                 'audio_list': [*app_audio_list],
+                 'video_list': [*app_video_list],
+                 'runtime_node_id': runtime_node_id,
+                 'chat_record_id': record_id,
+                 'child_node': child_node_value,
+                 'node_data': node_data,
+                 'form_data': kwargs}
+                )
+
+        if response.status_code == 200:
+            if stream:
+                content_generator = response.streaming_content
+                return NodeResult({'result': content_generator, 'question': message}, {},
+                                  _write_context=write_context_stream, _is_interrupt=_is_interrupt_exec)
+            else:
+                data = json.loads(response.content)
+                return NodeResult({'result': data, 'question': message}, {},
+                                  _write_context=write_context, _is_interrupt=_is_interrupt_exec)
+
+    def get_details(self, index: int, **kwargs):
+        global_fields = []
+        for api_input_field in self.node_params_serializer.data.get('api_input_field_list', []):
+            value = api_input_field.get('value', [''])[0] if api_input_field.get('value') else ''
+            global_fields.append({
+                'label': api_input_field['variable'],
+                'key': api_input_field['variable'],
+                'value': self.workflow_manage.get_reference_field(
+                    value,
+                    api_input_field['value'][1:]
+                ) if value != '' else ''
+            })
+
+        for user_input_field in self.node_params_serializer.data.get('user_input_field_list', []):
+            value = user_input_field.get('value', [''])[0] if user_input_field.get('value') else ''
+            global_fields.append({
+                'label': user_input_field['label'],
+                'key': user_input_field['field'],
+                'value': self.workflow_manage.get_reference_field(
+                    value,
+                    user_input_field['value'][1:]
+                ) if value != '' else ''
+            })
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            "info": self.node.properties.get('node_data'),
+            'run_time': self.context.get('run_time'),
+            'question': self.context.get('question'),
+            'answer': self.context.get('answer'),
+            'reasoning_content': self.context.get('reasoning_content'),
+            'type': self.node.type,
+            'message_tokens': self.context.get('message_tokens'),
+            'answer_tokens': self.context.get('answer_tokens'),
+            'status': self.status,
+            'err_message': self.err_message,
+            'global_fields': global_fields,
+            'document_list': self.workflow_manage.document_list,
+            'image_list': self.workflow_manage.image_list,
+            'audio_list': self.workflow_manage.audio_list,
+            'video_list': self.workflow_manage.video_list,
+            'application_node_dict': self.context.get('application_node_dict'),
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 9 - 0
apps/application/flow/step_node/condition_node/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py.py
+    @date:2024/6/7 14:43
+    @desc:
+"""
+from .impl import *

+ 42 - 0
apps/application/flow/step_node/condition_node/i_condition_node.py

@@ -0,0 +1,42 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_condition_node.py
+    @date:2024/6/7 9:54
+    @desc:
+"""
+from typing import Type
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode
+
+
+class ConditionSerializer(serializers.Serializer):
+    compare = serializers.CharField(required=True, label=_("Comparator"))
+    value = serializers.CharField(required=True, label=_("value"))
+    field = serializers.ListField(required=True, label=_("Fields"))
+
+
+class ConditionBranchSerializer(serializers.Serializer):
+    id = serializers.CharField(required=True, label=_("Branch id"))
+    type = serializers.CharField(required=True, label=_("Branch Type"))
+    condition = serializers.CharField(required=True, label=_("Condition or|and"))
+    conditions = ConditionSerializer(many=True)
+
+
+class ConditionNodeParamsSerializer(serializers.Serializer):
+    branch = ConditionBranchSerializer(many=True)
+
+
+class IConditionNode(INode):
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return ConditionNodeParamsSerializer
+
+    type = 'condition-node'
+
+    support = [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.KNOWLEDGE,
+               WorkflowMode.KNOWLEDGE_LOOP, WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP]

+ 9 - 0
apps/application/flow/step_node/condition_node/impl/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py
+    @date:2024/6/11 15:35
+    @desc:
+"""
+from .base_condition_node import BaseConditionNode

+ 64 - 0
apps/application/flow/step_node/condition_node/impl/base_condition_node.py

@@ -0,0 +1,64 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_condition_node.py
+    @date:2024/6/7 11:29
+    @desc:
+"""
+from typing import List
+
+from application.flow.i_step_node import NodeResult
+from application.flow.compare import compare_handle_list
+from application.flow.step_node.condition_node.i_condition_node import IConditionNode
+
+
+class BaseConditionNode(IConditionNode):
+    def save_context(self, details, workflow_manage):
+        self.context['branch_id'] = details.get('branch_id')
+        self.context['branch_name'] = details.get('branch_name')
+        self.context['exception_message'] = details.get('err_message')
+
+    def execute(self, **kwargs) -> NodeResult:
+        branch_list = self.node_params_serializer.data['branch']
+        branch = self._execute(branch_list)
+        r = NodeResult({'branch_id': branch.get('id'), 'branch_name': branch.get('type')}, {})
+        return r
+
+    def _execute(self, branch_list: List):
+        for branch in branch_list:
+            if self.branch_assertion(branch):
+                return branch
+
+    def branch_assertion(self, branch):
+        condition_list = [self.assertion(row.get('field'), row.get('compare'), row.get('value')) for row in
+                          branch.get('conditions')]
+        condition = branch.get('condition')
+        return all(condition_list) if condition == 'and' else any(condition_list)
+
+    def assertion(self, field_list: List[str], compare: str, value):
+        try:
+            value = self.workflow_manage.generate_prompt(value)
+        except Exception as e:
+            pass
+        field_value = None
+        try:
+            field_value = self.workflow_manage.get_reference_field(field_list[0], field_list[1:])
+        except  Exception as e:
+            pass
+        for compare_handler in compare_handle_list:
+            if compare_handler.support(field_list[0], field_list[1:], field_value, compare, value):
+                return compare_handler.compare(field_value, compare, value)
+
+    def get_details(self, index: int, **kwargs):
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'branch_id': self.context.get('branch_id'),
+            'branch_name': self.context.get('branch_name'),
+            'type': self.node.type,
+            'status': self.status,
+            'err_message': self.err_message,
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 8 - 0
apps/application/flow/step_node/data_source_local_node/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: __init__.py.py
+    @date:2025/11/11 10:06
+    @desc:
+"""

+ 42 - 0
apps/application/flow/step_node/data_source_local_node/i_data_source_local_node.py

@@ -0,0 +1,42 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: i_data_source_local_node.py
+    @date:2025/11/11 10:06
+    @desc:
+"""
+from abc import abstractmethod
+from typing import Type
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+
+class DataSourceLocalNodeParamsSerializer(serializers.Serializer):
+    file_type_list = serializers.ListField(child=serializers.CharField(label=('')), label='')
+    file_size_limit = serializers.IntegerField(required=True, label=_("Number of uploaded files"))
+    file_count_limit = serializers.IntegerField(required=True, label=_("Upload file size"))
+
+
+class IDataSourceLocalNode(INode):
+    type = 'data-source-local-node'
+
+    @staticmethod
+    @abstractmethod
+    def get_form_list(node):
+        pass
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return DataSourceLocalNodeParamsSerializer
+
+    def _run(self):
+        return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data)
+
+    def execute(self, file_type_list, file_size_limit, file_count_limit, **kwargs) -> NodeResult:
+        pass
+
+    support = [WorkflowMode.KNOWLEDGE]

+ 8 - 0
apps/application/flow/step_node/data_source_local_node/impl/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: __init__.py.py
+    @date:2025/11/11 10:08
+    @desc:
+"""

+ 52 - 0
apps/application/flow/step_node/data_source_local_node/impl/base_data_source_local_node.py

@@ -0,0 +1,52 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:虎虎
+    @file: base_data_source_local_node.py
+    @date:2025/11/11 10:30
+    @desc:
+"""
+from application.flow.i_step_node import NodeResult
+from application.flow.step_node.data_source_local_node.i_data_source_local_node import IDataSourceLocalNode
+from common import forms
+from common.forms import BaseForm
+
+
+class BaseDataSourceLocalNodeForm(BaseForm):
+    api_key = forms.PasswordInputField('API Key', required=True)
+
+
+class BaseDataSourceLocalNode(IDataSourceLocalNode):
+    def save_context(self, details, workflow_manage):
+        self.context['exception_message'] = details.get('err_message')
+
+    @staticmethod
+    def get_form_list(node):
+        node_data = node.get('properties').get('node_data')
+        return [{
+            'field': 'file_list',
+            'input_type': 'LocalFileUpload',
+            'attrs': {
+                'file_count_limit': node_data.get('file_count_limit') or 10,
+                'file_size_limit': node_data.get('file_size_limit') or 100,
+                'file_type_list': node_data.get('file_type_list'),
+            },
+            'label': '',
+        }]
+
+    def execute(self, file_type_list, file_size_limit, file_count_limit, **kwargs) -> NodeResult:
+        return NodeResult({'file_list': self.workflow_manage.params.get('data_source', {}).get('file_list')},
+                          self.workflow_manage.params.get('knowledge_base') or {})
+
+    def get_details(self, index: int, **kwargs):
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'type': self.node.type,
+            'file_list': self.context.get('file_list'),
+            'knowledge_base': self.workflow_params.get('knowledge_base'),
+            'status': self.status,
+            'err_message': self.err_message,
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 8 - 0
apps/application/flow/step_node/data_source_web_node/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:niu
+    @file: __init__.py.py
+    @date:2025/11/12 13:43
+    @desc:
+"""

+ 28 - 0
apps/application/flow/step_node/data_source_web_node/i_data_source_web_node.py

@@ -0,0 +1,28 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:niu
+    @file: i_data_source_web_node.py
+    @date:2025/11/12 13:47
+    @desc:
+"""
+from abc import abstractmethod
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+
+class IDataSourceWebNode(INode):
+    type = 'data-source-web-node'
+    support = [WorkflowMode.KNOWLEDGE]
+
+    @staticmethod
+    @abstractmethod
+    def get_form_list(node):
+        pass
+
+    def _run(self):
+        return self.execute(**self.flow_params_serializer.data)
+
+    def execute(self, **kwargs) -> NodeResult:
+        pass

+ 8 - 0
apps/application/flow/step_node/data_source_web_node/impl/__init__.py

@@ -0,0 +1,8 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:niu
+    @file: __init__.py
+    @date:2025/11/12 13:44
+    @desc:
+"""

+ 98 - 0
apps/application/flow/step_node/data_source_web_node/impl/base_data_source_web_node.py

@@ -0,0 +1,98 @@
+# coding=utf-8
+"""
+    @project: MaxKB
+    @Author:niu
+    @file: base_data_source_web_node.py
+    @date:2025/11/12 13:47
+    @desc:
+"""
+import traceback
+
+from django.utils.translation import gettext_lazy as _
+
+from application.flow.i_step_node import NodeResult
+from application.flow.step_node.data_source_web_node.i_data_source_web_node import IDataSourceWebNode
+from common import forms
+from common.forms import BaseForm
+from common.utils.fork import ForkManage, Fork, ChildLink
+from common.utils.logger import maxkb_logger
+
+
+class BaseDataSourceWebNodeForm(BaseForm):
+    source_url = forms.TextInputField(_('Web source url'), required=True, attrs={
+        'placeholder': _('Please enter the Web root address')})
+    selector = forms.TextInputField(_('Web knowledge selector'), required=False, attrs={
+        'placeholder': _('The default is body, you can enter .classname/#idname/tagname')})
+
+
+class InterruptedTaskException(Exception):
+    def __init__(self, *args, **kwargs):  # real signature unknown
+        pass
+
+
+def get_collect_handler(workflow_manage):
+    results = []
+
+    def handler(child_link: ChildLink, response: Fork.Response):
+        if response.status == 200:
+            try:
+                document_name = child_link.tag.text if child_link.tag is not None and len(
+                    child_link.tag.text.strip()) > 0 else child_link.url
+                results.append({
+                    "name": document_name.strip(),
+                    "content": response.content,
+                })
+
+            except Exception as e:
+                maxkb_logger.error(f'{str(e)}:{traceback.format_exc()}')
+        if workflow_manage.is_the_task_interrupted():
+            raise InterruptedTaskException('Task interrupted')
+
+    return handler, results
+
+
+class BaseDataSourceWebNode(IDataSourceWebNode):
+    def save_context(self, details, workflow_manage):
+        self.context['exception_message'] = details.get('err_message')
+
+    @staticmethod
+    def get_form_list(node):
+        return BaseDataSourceWebNodeForm().to_form_list()
+
+    def execute(self, **kwargs) -> NodeResult:
+        BaseDataSourceWebNodeForm().valid_form(self.workflow_params.get("data_source"))
+
+        data_source = self.workflow_params.get("data_source")
+
+        node_id = data_source.get("node_id")
+        source_url = data_source.get("source_url")
+        selector = data_source.get("selector") or "body"
+
+        collect_handler, document_list = get_collect_handler(self.workflow_manage)
+
+        try:
+            ForkManage(source_url, selector.split(" ") if selector is not None else []).fork(3, set(), collect_handler)
+
+            return NodeResult({'document_list': document_list, 'source_url': source_url, 'selector': selector},
+                              self.workflow_manage.params.get('knowledge_base') or {})
+
+        except Exception as e:
+            if isinstance(e, InterruptedTaskException):
+                return NodeResult({'document_list': document_list, 'source_url': source_url, 'selector': selector},
+                                  self.workflow_manage.params.get('knowledge_base') or {})
+            maxkb_logger.error(_('data source web node:{node_id} error{error}{traceback}').format(
+                node_id=node_id, error=str(e), traceback=traceback.format_exc()))
+
+    def get_details(self, index: int, **kwargs):
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'type': self.node.type,
+            'input_params': {"source_url": self.context.get("source_url"), "selector": self.context.get('selector')},
+            'output_params': self.context.get('document_list'),
+            'knowledge_base': self.workflow_params.get('knowledge_base'),
+            'status': self.status,
+            'err_message': self.err_message,
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 9 - 0
apps/application/flow/step_node/direct_reply_node/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py
+    @date:2024/6/11 17:50
+    @desc:
+"""
+from .impl import *

+ 58 - 0
apps/application/flow/step_node/direct_reply_node/i_reply_node.py

@@ -0,0 +1,58 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: i_reply_node.py
+    @date:2024/6/11 16:25
+    @desc:
+"""
+from typing import Type
+
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+from common.exception.app_exception import AppApiException
+
+from django.utils.translation import gettext_lazy as _
+
+
+class ReplyNodeParamsSerializer(serializers.Serializer):
+    reply_type = serializers.CharField(required=True, label=_("Response Type"))
+    fields = serializers.ListField(required=False, label=_("Reference Field"))
+    content = serializers.CharField(required=False, allow_blank=True, allow_null=True,
+                                    label=_("Direct answer content"))
+    is_result = serializers.BooleanField(required=False,
+                                         label=_('Whether to return content'))
+
+    def is_valid(self, *, raise_exception=False):
+        super().is_valid(raise_exception=True)
+        if self.data.get('reply_type') == 'referencing':
+            if 'fields' not in self.data:
+                raise AppApiException(500, _("Reference field cannot be empty"))
+            if len(self.data.get('fields')) < 2:
+                raise AppApiException(500, _("Reference field error"))
+        else:
+            if 'content' not in self.data or self.data.get('content') is None:
+                raise AppApiException(500, _("Content cannot be empty"))
+
+
+class IReplyNode(INode):
+    type = 'reply-node'
+    support = [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.KNOWLEDGE_LOOP,
+               WorkflowMode.KNOWLEDGE, WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP]
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return ReplyNodeParamsSerializer
+
+    def _run(self):
+        if [WorkflowMode.KNOWLEDGE, WorkflowMode.KNOWLEDGE_LOOP, WorkflowMode.TOOL,
+            WorkflowMode.TOOL_LOOP].__contains__(
+            self.workflow_manage.flow.workflow_mode):
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data,
+                                **{'stream': True})
+        else:
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data)
+
+    def execute(self, reply_type, stream, fields=None, content=None, **kwargs) -> NodeResult:
+        pass

+ 9 - 0
apps/application/flow/step_node/direct_reply_node/impl/__init__.py

@@ -0,0 +1,9 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: __init__.py
+    @date:2024/6/11 17:49
+    @desc:
+"""
+from .base_reply_node import *

+ 47 - 0
apps/application/flow/step_node/direct_reply_node/impl/base_reply_node.py

@@ -0,0 +1,47 @@
+# coding=utf-8
+"""
+    @project: maxkb
+    @Author:虎
+    @file: base_reply_node.py
+    @date:2024/6/11 17:25
+    @desc:
+"""
+from typing import List
+
+from application.flow.i_step_node import NodeResult
+from application.flow.step_node.direct_reply_node.i_reply_node import IReplyNode
+
+
+class BaseReplyNode(IReplyNode):
+    def save_context(self, details, workflow_manage):
+        self.context['answer'] = details.get('answer')
+        self.context['exception_message'] = details.get('err_message')
+        if self.node_params.get('is_result', False):
+            self.answer_text = details.get('answer')
+
+    def execute(self, reply_type, stream, fields=None, content=None, **kwargs) -> NodeResult:
+        if reply_type == 'referencing':
+            result = self.get_reference_content(fields)
+        else:
+            result = self.generate_reply_content(content)
+        return NodeResult({'answer': result}, {})
+
+    def generate_reply_content(self, prompt):
+        return self.workflow_manage.generate_prompt(prompt)
+
+    def get_reference_content(self, fields: List[str]):
+        return str(self.workflow_manage.get_reference_field(
+            fields[0],
+            fields[1:]))
+
+    def get_details(self, index: int, **kwargs):
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'type': self.node.type,
+            'answer': self.context.get('answer'),
+            'status': self.status,
+            'err_message': self.err_message,
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 1 - 0
apps/application/flow/step_node/document_extract_node/__init__.py

@@ -0,0 +1 @@
+from .impl import *

+ 30 - 0
apps/application/flow/step_node/document_extract_node/i_document_extract_node.py

@@ -0,0 +1,30 @@
+# coding=utf-8
+
+from typing import Type
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+
+class DocumentExtractNodeSerializer(serializers.Serializer):
+    document_list = serializers.ListField(required=False, label=_("document"))
+
+
+class IDocumentExtractNode(INode):
+    type = 'document-extract-node'
+    support = [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.KNOWLEDGE_LOOP,
+               WorkflowMode.KNOWLEDGE, WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP]
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return DocumentExtractNodeSerializer
+
+    def _run(self):
+        res = self.workflow_manage.get_reference_field(self.node_params_serializer.data.get('document_list')[0],
+                                                       self.node_params_serializer.data.get('document_list')[1:])
+        return self.execute(document=res, **self.flow_params_serializer.data)
+
+    def execute(self, document, chat_id=None, **kwargs) -> NodeResult:
+        pass

+ 1 - 0
apps/application/flow/step_node/document_extract_node/impl/__init__.py

@@ -0,0 +1 @@
+from .base_document_extract_node import BaseDocumentExtractNode

+ 95 - 0
apps/application/flow/step_node/document_extract_node/impl/base_document_extract_node.py

@@ -0,0 +1,95 @@
+# coding=utf-8
+import ast
+import io
+
+import uuid_utils.compat as uuid
+from django.db.models import QuerySet
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import NodeResult
+from application.flow.step_node.document_extract_node.i_document_extract_node import IDocumentExtractNode
+from knowledge.models import File, FileSourceType
+from knowledge.serializers.document import split_handles, parse_table_handle_list, FileBufferHandle
+
+splitter = '\n`-----------------------------------`\n'
+
+
+class BaseDocumentExtractNode(IDocumentExtractNode):
+    def save_context(self, details, workflow_manage):
+        self.context['content'] = details.get('content')
+        self.context['exception_message'] = details.get('err_message')
+
+    def execute(self, document, chat_id=None, **kwargs):
+        get_buffer = FileBufferHandle().get_buffer
+
+        self.context['document_list'] = document
+        content = []
+        if document is None or not isinstance(document, list):
+            return NodeResult({'content': '', 'document_list': []}, {})
+
+        # 安全获取 application
+        application_id = None
+        tool_id = None
+        knowledge_id = None
+        if [WorkflowMode.KNOWLEDGE, WorkflowMode.KNOWLEDGE_LOOP].__contains__(self.workflow_manage.flow.workflow_mode):
+            knowledge_id = self.workflow_params.get('knowledge_id')
+        elif [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP].__contains__(
+                self.workflow_manage.flow.workflow_mode):
+            application_id = self.workflow_manage.work_flow_post_handler.chat_info.application.id
+        elif [WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP].__contains__(self.workflow_manage.flow.workflow_mode):
+            tool_id = self.workflow_params.get('tool_id')
+
+        # doc文件中的图片保存
+        def save_image(image_list):
+            for image in image_list:
+                meta = {
+                    'debug': False if (application_id or knowledge_id or tool_id) else True,
+                    'chat_id': chat_id,
+                    'application_id': str(application_id) if application_id else None,
+                    'knowledge_id': str(knowledge_id) if knowledge_id else None,
+                    'tool_id': str(tool_id) if tool_id else None,
+                    'file_id': str(image.id)
+                }
+                file_bytes = image.meta.pop('content')
+                new_file = File(
+                    id=meta['file_id'],
+                    file_name=image.file_name,
+                    file_size=len(file_bytes),
+                    source_type=FileSourceType.APPLICATION.value if application_id else FileSourceType.KNOWLEDGE.value if knowledge_id else FileSourceType.APPLICATION.value,
+                    source_id=application_id or tool_id or knowledge_id,
+                    meta=meta
+                )
+                if not QuerySet(File).filter(id=new_file.id).exists():
+                    new_file.save(file_bytes)
+
+        document_list = []
+        for doc in document:
+            file = QuerySet(File).filter(id=doc['file_id']).first()
+            buffer = io.BytesIO(file.get_bytes())
+            buffer.name = doc['name']  # this is the important line
+
+            for split_handle in (parse_table_handle_list + split_handles):
+                if split_handle.support(buffer, get_buffer):
+                    # 回到文件头
+                    buffer.seek(0)
+                    file_content = split_handle.get_content(buffer, save_image)
+                    content.append('### ' + doc['name'] + '\n' + file_content)
+                    document_list.append({'id': str(file.id), 'name': doc['name'], 'content': file_content})
+                    break
+
+        return NodeResult({'content': splitter.join(content), 'document_list': document_list}, {})
+
+    def get_details(self, index: int, **kwargs):
+        content = self.context.get('content', '').split(splitter)
+        # 不保存content全部内容,因为content内容可能会很大
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'type': self.node.type,
+            'content': [file_content[:500] for file_content in content],
+            'status': self.status,
+            'err_message': self.err_message,
+            'document_list': self.context.get('document_list'),
+            'enableException': self.node.properties.get('enableException'),
+        }

+ 1 - 0
apps/application/flow/step_node/document_split_node/__init__.py

@@ -0,0 +1 @@
+from .impl import *

+ 97 - 0
apps/application/flow/step_node/document_split_node/i_document_split_node.py

@@ -0,0 +1,97 @@
+# coding=utf-8
+
+from typing import Type
+
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+
+from application.flow.common import WorkflowMode
+from application.flow.i_step_node import INode, NodeResult
+
+
+class DocumentSplitNodeSerializer(serializers.Serializer):
+    document_list = serializers.ListField(required=False, label=_("document list"))
+    split_strategy = serializers.ChoiceField(
+        choices=['auto', 'custom', 'qa'], required=False, label=_("split strategy"), default='auto'
+    )
+    paragraph_title_relate_problem_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("paragraph title relate problem type"),
+        default='custom'
+    )
+    paragraph_title_relate_problem = serializers.BooleanField(
+        required=False, label=_("paragraph title relate problem"), default=False
+    )
+    paragraph_title_relate_problem_reference = serializers.ListField(
+        required=False, label=_("paragraph title relate problem reference"), child=serializers.CharField(), default=[]
+    )
+    document_name_relate_problem_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("document name relate problem type"),
+        default='custom'
+    )
+    document_name_relate_problem = serializers.BooleanField(
+        required=False, label=_("document name relate problem"), default=False
+    )
+    document_name_relate_problem_reference = serializers.ListField(
+        required=False, label=_("document name relate problem reference"), child=serializers.CharField(), default=[]
+    )
+    limit = serializers.IntegerField(required=False, label=_("limit"), default=4096)
+    limit_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("document name relate problem type"),
+        default='custom'
+    )
+    limit_reference = serializers.ListField(
+        required=False, label=_("limit reference"), child=serializers.CharField(), default=[]
+    )
+    chunk_size = serializers.IntegerField(required=False, label=_("chunk size"), default=256)
+    chunk_size_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("chunk size type"), default='custom'
+    )
+    chunk_size_reference = serializers.ListField(
+        required=False, label=_("chunk size reference"), child=serializers.CharField(), default=[]
+    )
+    patterns = serializers.ListField(
+        required=False, label=_("patterns"), child=serializers.CharField(), default=[]
+    )
+    patterns_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("patterns type"), default='custom'
+    )
+    patterns_reference = serializers.ListField(
+        required=False, label=_("patterns reference"), child=serializers.CharField(), default=[]
+    )
+    with_filter = serializers.BooleanField(
+        required=False, label=_("with filter"), default=False
+    )
+    with_filter_type = serializers.ChoiceField(
+        choices=['custom', 'referencing'], required=False, label=_("with filter type"), default='custom'
+    )
+    with_filter_reference = serializers.ListField(
+        required=False, label=_("with filter reference"), child=serializers.CharField(), default=[]
+    )
+
+
+class IDocumentSplitNode(INode):
+    type = 'document-split-node'
+    support = [
+        WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.KNOWLEDGE_LOOP, WorkflowMode.KNOWLEDGE,
+        WorkflowMode.TOOL, WorkflowMode.TOOL_LOOP
+    ]
+
+    def get_node_params_serializer_class(self) -> Type[serializers.Serializer]:
+        return DocumentSplitNodeSerializer
+
+    def _run(self):
+        if [WorkflowMode.APPLICATION, WorkflowMode.APPLICATION_LOOP, WorkflowMode.TOOL,
+            WorkflowMode.TOOL_LOOP].__contains__(
+            self.workflow_manage.flow.workflow_mode):
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data,
+                                **{'knowledge_id': None})
+        else:
+            return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data)
+
+    def execute(self, document_list, knowledge_id, split_strategy, paragraph_title_relate_problem_type,
+                paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+                document_name_relate_problem_type, document_name_relate_problem,
+                document_name_relate_problem_reference, limit, limit_type, limit_reference, chunk_size, chunk_size_type,
+                chunk_size_reference, patterns, patterns_type, patterns_reference, with_filter, with_filter_type,
+                with_filter_reference, **kwargs) -> NodeResult:
+        pass

+ 1 - 0
apps/application/flow/step_node/document_split_node/impl/__init__.py

@@ -0,0 +1 @@
+from .base_document_split_node import BaseDocumentSplitNode

+ 192 - 0
apps/application/flow/step_node/document_split_node/impl/base_document_split_node.py

@@ -0,0 +1,192 @@
+# coding=utf-8
+import io
+import mimetypes
+from typing import List
+
+from django.core.files.uploadedfile import InMemoryUploadedFile
+
+from application.flow.i_step_node import NodeResult
+from application.flow.step_node.document_split_node.i_document_split_node import IDocumentSplitNode
+from common.chunk import text_to_chunk
+from knowledge.serializers.document import default_split_handle, FileBufferHandle, md_qa_split_handle
+
+
+def bytes_to_uploaded_file(file_bytes, file_name="file.txt"):
+    if file_name.startswith("http"):
+        file_name = "file.txt"
+    content_type, _ = mimetypes.guess_type(file_name)
+    if content_type is None:
+        # 如果未能识别,设置为默认的二进制文件类型
+        content_type = "application/octet-stream"
+    # 创建一个内存中的字节流对象
+    file_stream = io.BytesIO(file_bytes)
+
+    # 获取文件大小
+    file_size = len(file_bytes)
+
+    # 创建 InMemoryUploadedFile 对象
+    uploaded_file = InMemoryUploadedFile(
+        file=file_stream,
+        field_name=None,
+        name=file_name,
+        content_type=content_type,
+        size=file_size,
+        charset=None,
+    )
+    return uploaded_file
+
+
+class BaseDocumentSplitNode(IDocumentSplitNode):
+    def save_context(self, details, workflow_manage):
+        self.context['content'] = details.get('content')
+        self.context['exception_message'] = details.get('err_message')
+
+    def get_reference_content(self, fields: List[str]):
+        return self.workflow_manage.get_reference_field(fields[0], fields[1:])
+
+    def execute(self, document_list, knowledge_id, split_strategy, paragraph_title_relate_problem_type,
+                paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+                document_name_relate_problem_type, document_name_relate_problem,
+                document_name_relate_problem_reference, limit, limit_type, limit_reference, chunk_size, chunk_size_type,
+                chunk_size_reference, patterns, patterns_type, patterns_reference, with_filter, with_filter_type,
+                with_filter_reference, **kwargs) -> NodeResult:
+        self.context['knowledge_id'] = knowledge_id
+        file_list = self.get_reference_content(document_list)
+
+        # 处理引用类型的参数
+        if patterns_type == 'referencing':
+            patterns = self.get_reference_content(patterns_reference)
+        if limit_type == 'referencing':
+            limit = self.get_reference_content(limit_reference)
+        if chunk_size_type == 'referencing':
+            chunk_size = self.get_reference_content(chunk_size_reference)
+        if with_filter_type == 'referencing':
+            with_filter = self.get_reference_content(with_filter_reference)
+
+        paragraph_list = []
+        for doc in file_list:
+            get_buffer = FileBufferHandle().get_buffer
+
+            file_mem = bytes_to_uploaded_file(doc['content'].encode('utf-8'), doc['name'])
+            if split_strategy == 'qa':
+                result = md_qa_split_handle.handle(file_mem, get_buffer, self._save_image)
+            else:
+                result = default_split_handle.handle(file_mem, patterns, with_filter, limit, get_buffer,
+                                                     self._save_image)
+            # 统一处理结果为列表
+            results = result if isinstance(result, list) else [result]
+
+            for item in results:
+                self._process_split_result(
+                    item, knowledge_id, doc.get('id'), doc.get('name'),
+                    split_strategy, paragraph_title_relate_problem_type,
+                    paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+                    document_name_relate_problem_type, document_name_relate_problem,
+                    document_name_relate_problem_reference, chunk_size
+                )
+
+            paragraph_list += results
+
+        self.context['paragraph_list'] = paragraph_list
+        self.context['document_list'] = file_list
+        self.context['limit'] = limit
+        self.context['chunk_size'] = chunk_size
+        self.context['with_filter'] = with_filter
+        self.context['patterns'] = patterns
+        self.context['split_strategy'] = split_strategy
+
+        return NodeResult({'paragraph_list': paragraph_list}, {})
+
+    def _save_image(self, image_list):
+        pass
+
+    def _process_split_result(
+            self, item, knowledge_id, source_file_id, file_name,
+            split_strategy, paragraph_title_relate_problem_type,
+            paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+            document_name_relate_problem_type, document_name_relate_problem,
+            document_name_relate_problem_reference, chunk_size
+    ):
+        """处理文档分割结果"""
+        item['meta'] = {
+            'knowledge_id': knowledge_id,
+            'source_file_id': source_file_id,
+            'source_url': file_name,
+        }
+        if item.get('name', 'file.txt') == 'file.txt':
+            item['name'] = file_name
+        item['source_file_id'] = source_file_id
+        item['paragraphs'] = item.pop('content', item.get('paragraphs', []))
+
+        for paragraph in item['paragraphs']:
+            paragraph['problem_list'] = self._generate_problem_list(
+                paragraph, file_name,
+                split_strategy, paragraph_title_relate_problem_type,
+                paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+                document_name_relate_problem_type, document_name_relate_problem,
+                document_name_relate_problem_reference
+            )
+            paragraph['is_active'] = True
+            paragraph['chunks'] = text_to_chunk(paragraph['content'], chunk_size)
+
+    def _generate_problem_list(
+            self, paragraph, document_name, split_strategy, paragraph_title_relate_problem_type,
+            paragraph_title_relate_problem, paragraph_title_relate_problem_reference,
+            document_name_relate_problem_type, document_name_relate_problem,
+            document_name_relate_problem_reference
+    ):
+        if paragraph_title_relate_problem_type == 'referencing':
+            paragraph_title_relate_problem = self.get_reference_content(paragraph_title_relate_problem_reference)
+        if document_name_relate_problem_type == 'referencing':
+            document_name_relate_problem = self.get_reference_content(document_name_relate_problem_reference)
+
+        problem_list = [
+            item for p in paragraph.get('problem_list', []) for item in p.get('content', '').split('<br>')
+            if item.strip()
+        ]
+
+        if split_strategy == 'auto':
+            if paragraph_title_relate_problem and paragraph.get('title'):
+                problem_list.append(paragraph.get('title'))
+            if document_name_relate_problem and document_name:
+                problem_list.append(document_name)
+        elif split_strategy == 'custom':
+            if paragraph_title_relate_problem and paragraph.get('title'):
+                problem_list.append(paragraph.get('title'))
+            if document_name_relate_problem and document_name:
+                problem_list.append(document_name)
+        elif split_strategy == 'qa':
+            if document_name_relate_problem and document_name:
+                problem_list.append(document_name)
+
+        return list(set(problem_list))
+
+    def get_details(self, index: int, **kwargs):
+        paragraph_list = self.context.get('paragraph_list', [])
+        # 每个文档保留前5个分段
+        limited_paragraph_list = []
+        for doc in paragraph_list:
+            if doc.get('paragraphs'):
+                doc_copy = doc.copy()
+                doc_copy['paragraphs'] = doc['paragraphs'][:5]
+                limited_paragraph_list.append(doc_copy)
+            else:
+                limited_paragraph_list.append(doc)
+        paragraph_list = limited_paragraph_list
+
+        return {
+            'name': self.node.properties.get('stepName'),
+            "index": index,
+            'run_time': self.context.get('run_time'),
+            'type': self.node.type,
+            'status': self.status,
+            'err_message': self.err_message,
+            'paragraph_list': paragraph_list,
+            'limit': self.context.get('limit'),
+            'chunk_size': self.context.get('chunk_size'),
+            'with_filter': self.context.get('with_filter'),
+            'patterns': self.context.get('patterns'),
+            'split_strategy': self.context.get('split_strategy'),
+            'enableException': self.node.properties.get('enableException'),
+            # 'document_list': self.context.get('document_list', []),
+        }

Някои файлове не бяха показани, защото твърде много файлове са промени