Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

Initial commit

John Wangdb896255d625
diff --git a/.github/workflows/build-api-image.sh b/.github/workflows/build-api-image.sh
new file mode 100644
index 00000000000..b7c92525fbe
--- /dev/null
+++ b/.github/workflows/build-api-image.sh
@@ -0,0 +1,61 @@
+#!/usr/bin/env bash
+
+set -eo pipefail
+
+SHA=$(git rev-parse HEAD)
+REPO_NAME=langgenius/dify
+API_REPO_NAME="${REPO_NAME}-api"
+
+if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
+ REFSPEC=$(echo "${GITHUB_HEAD_REF}" | sed 's/[^a-zA-Z0-9]/-/g' | head -c 40)
+ PR_NUM=$(echo "${GITHUB_REF}" | sed 's:refs/pull/::' | sed 's:/merge::')
+ LATEST_TAG="pr-${PR_NUM}"
+ CACHE_FROM_TAG="latest"
+elif [[ "${GITHUB_EVENT_NAME}" == "release" ]]; then
+ REFSPEC=$(echo "${GITHUB_REF}" | sed 's:refs/tags/::' | head -c 40)
+ LATEST_TAG="${REFSPEC}"
+ CACHE_FROM_TAG="latest"
+else
+ REFSPEC=$(echo "${GITHUB_REF}" | sed 's:refs/heads/::' | sed 's/[^a-zA-Z0-9]/-/g' | head -c 40)
+ LATEST_TAG="${REFSPEC}"
+ CACHE_FROM_TAG="${REFSPEC}"
+fi
+
+if [[ "${REFSPEC}" == "main" ]]; then
+ LATEST_TAG="latest"
+ CACHE_FROM_TAG="latest"
+fi
+
+echo "Pulling cache image ${API_REPO_NAME}:${CACHE_FROM_TAG}"
+if docker pull "${API_REPO_NAME}:${CACHE_FROM_TAG}"; then
+ API_CACHE_FROM_SCRIPT="--cache-from ${API_REPO_NAME}:${CACHE_FROM_TAG}"
+else
+ echo "WARNING: Failed to pull ${API_REPO_NAME}:${CACHE_FROM_TAG}, disable build image cache."
+ API_CACHE_FROM_SCRIPT=""
+fi
+
+
+cat<<EOF
+ Rolling with tags:
+ - ${API_REPO_NAME}:${SHA}
+ - ${API_REPO_NAME}:${REFSPEC}
+ - ${API_REPO_NAME}:${LATEST_TAG}
+EOF
+
+#
+# Build image
+#
+cd api
+docker build \
+ ${API_CACHE_FROM_SCRIPT} \
+ --build-arg COMMIT_SHA=${SHA} \
+ -t "${API_REPO_NAME}:${SHA}" \
+ -t "${API_REPO_NAME}:${REFSPEC}" \
+ -t "${API_REPO_NAME}:${LATEST_TAG}" \
+ --label "sha=${SHA}" \
+ --label "built_at=$(date)" \
+ --label "build_actor=${GITHUB_ACTOR}" \
+ .
+
+# push
+docker push --all-tags "${API_REPO_NAME}"
diff --git a/.github/workflows/build-api-image.yml b/.github/workflows/build-api-image.yml
new file mode 100644
index 00000000000..006a8d98abd
--- /dev/null
+++ b/.github/workflows/build-api-image.yml
@@ -0,0 +1,43 @@
+name: Build and Push API Image
+
+on:
+ push:
+ branches:
+ - 'main'
+ - 'deploy/dev'
+ pull_request:
+ types: [synchronize, opened, reopened, ready_for_review]
+
+jobs:
+ build-and-push:
+ runs-on: ubuntu-latest
+ if: github.event.pull_request.draft == false
+ steps:
+ - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
+ uses: actions/checkout@v2
+ with:
+ persist-credentials: false
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v2
+ with:
+ username: ${{ secrets.DOCKERHUB_USER }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ - name: Build and push Docker image
+ shell: bash
+ env:
+ DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }}
+ DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+ run: |
+ /bin/bash .github/workflows/build-api-image.sh
+
+ - name: Deploy to server
+ if: github.ref == 'refs/heads/deploy/dev'
+ uses: appleboy/[email protected]
+ with:
+ host: ${{ secrets.SSH_HOST }}
+ username: ${{ secrets.SSH_USER }}
+ key: ${{ secrets.SSH_PRIVATE_KEY }}
+ script: |
+ ${{ secrets.SSH_SCRIPT }}
diff --git a/.github/workflows/build-web-image.sh b/.github/workflows/build-web-image.sh
new file mode 100644
index 00000000000..8c67c156e65
--- /dev/null
+++ b/.github/workflows/build-web-image.sh
@@ -0,0 +1,60 @@
+#!/usr/bin/env bash
+
+set -eo pipefail
+
+SHA=$(git rev-parse HEAD)
+REPO_NAME=langgenius/dify
+WEB_REPO_NAME="${REPO_NAME}-web"
+
+if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
+ REFSPEC=$(echo "${GITHUB_HEAD_REF}" | sed 's/[^a-zA-Z0-9]/-/g' | head -c 40)
+ PR_NUM=$(echo "${GITHUB_REF}" | sed 's:refs/pull/::' | sed 's:/merge::')
+ LATEST_TAG="pr-${PR_NUM}"
+ CACHE_FROM_TAG="latest"
+elif [[ "${GITHUB_EVENT_NAME}" == "release" ]]; then
+ REFSPEC=$(echo "${GITHUB_REF}" | sed 's:refs/tags/::' | head -c 40)
+ LATEST_TAG="${REFSPEC}"
+ CACHE_FROM_TAG="latest"
+else
+ REFSPEC=$(echo "${GITHUB_REF}" | sed 's:refs/heads/::' | sed 's/[^a-zA-Z0-9]/-/g' | head -c 40)
+ LATEST_TAG="${REFSPEC}"
+ CACHE_FROM_TAG="${REFSPEC}"
+fi
+
+if [[ "${REFSPEC}" == "main" ]]; then
+ LATEST_TAG="latest"
+ CACHE_FROM_TAG="latest"
+fi
+
+echo "Pulling cache image ${WEB_REPO_NAME}:${CACHE_FROM_TAG}"
+if docker pull "${WEB_REPO_NAME}:${CACHE_FROM_TAG}"; then
+ WEB_CACHE_FROM_SCRIPT="--cache-from ${WEB_REPO_NAME}:${CACHE_FROM_TAG}"
+else
+ echo "WARNING: Failed to pull ${WEB_REPO_NAME}:${CACHE_FROM_TAG}, disable build image cache."
+ WEB_CACHE_FROM_SCRIPT=""
+fi
+
+
+cat<<EOF
+ Rolling with tags:
+ - ${WEB_REPO_NAME}:${SHA}
+ - ${WEB_REPO_NAME}:${REFSPEC}
+ - ${WEB_REPO_NAME}:${LATEST_TAG}
+EOF
+
+#
+# Build image
+#
+cd web
+docker build \
+ ${WEB_CACHE_FROM_SCRIPT} \
+ --build-arg COMMIT_SHA=${SHA} \
+ -t "${WEB_REPO_NAME}:${SHA}" \
+ -t "${WEB_REPO_NAME}:${REFSPEC}" \
+ -t "${WEB_REPO_NAME}:${LATEST_TAG}" \
+ --label "sha=${SHA}" \
+ --label "built_at=$(date)" \
+ --label "build_actor=${GITHUB_ACTOR}" \
+ .
+
+docker push --all-tags "${WEB_REPO_NAME}"
\ No newline at end of file
diff --git a/.github/workflows/build-web-image.yml b/.github/workflows/build-web-image.yml
new file mode 100644
index 00000000000..69a44f97de7
--- /dev/null
+++ b/.github/workflows/build-web-image.yml
@@ -0,0 +1,43 @@
+name: Build and Push WEB Image
+
+on:
+ push:
+ branches:
+ - 'main'
+ - 'deploy/dev'
+ pull_request:
+ types: [synchronize, opened, reopened, ready_for_review]
+
+jobs:
+ build-and-push:
+ runs-on: ubuntu-latest
+ if: github.event.pull_request.draft == false
+ steps:
+ - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
+ uses: actions/checkout@v2
+ with:
+ persist-credentials: false
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v2
+ with:
+ username: ${{ secrets.DOCKERHUB_USER }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ - name: Build and push Docker image
+ shell: bash
+ env:
+ DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }}
+ DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+ run: |
+ /bin/bash .github/workflows/build-web-image.sh
+
+ - name: Deploy to server
+ if: github.ref == 'refs/heads/deploy/dev'
+ uses: appleboy/[email protected]
+ with:
+ host: ${{ secrets.SSH_HOST }}
+ username: ${{ secrets.SSH_USER }}
+ key: ${{ secrets.SSH_PRIVATE_KEY }}
+ script: |
+ ${{ secrets.SSH_SCRIPT }}
diff --git a/.github/workflows/check_no_chinese_comments.py b/.github/workflows/check_no_chinese_comments.py
new file mode 100644
index 00000000000..41e53ebfcbc
--- /dev/null
+++ b/.github/workflows/check_no_chinese_comments.py
@@ -0,0 +1,35 @@
+import os
+import re
+from zhon.hanzi import punctuation
+
+def has_chinese_characters(text):
+ for char in text:
+ if '\u4e00' <= char <= '\u9fff' or char in punctuation:
+ return True
+ return False
+
+def check_file_for_chinese_comments(file_path):
+ with open(file_path, 'r', encoding='utf-8') as file:
+ for line_number, line in enumerate(file, start=1):
+ if has_chinese_characters(line):
+ print(f"Found Chinese characters in {file_path} on line {line_number}:")
+ print(line.strip())
+ return True
+ return False
+
+def main():
+ has_chinese = False
+ excluded_files = ["model_template.py", 'stopwords.py', 'commands.py', 'indexing_runner.py']
+
+ for root, _, files in os.walk("."):
+ for file in files:
+ if file.endswith(".py") and file not in excluded_files:
+ file_path = os.path.join(root, file)
+ if check_file_for_chinese_comments(file_path):
+ has_chinese = True
+
+ if has_chinese:
+ raise Exception("Found Chinese characters in Python files. Please remove them.")
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/workflows/check_no_chinese_comments.yml b/.github/workflows/check_no_chinese_comments.yml
new file mode 100644
index 00000000000..ff3882acacd
--- /dev/null
+++ b/.github/workflows/check_no_chinese_comments.yml
@@ -0,0 +1,31 @@
+name: Check for Chinese comments
+
+on:
+ push:
+ branches:
+ - 'main'
+ pull_request:
+ branches:
+ - main
+
+jobs:
+ check-chinese-comments:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v2
+
+ - name: Set up Python
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.9
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install zhon
+
+ - name: Run script to check for Chinese comments
+ run: |
+ python .github/workflows/check_no_chinese_comments.py
diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml
new file mode 100644
index 00000000000..308e837dc7e
--- /dev/null
+++ b/.github/workflows/flake8.yml
@@ -0,0 +1,19 @@
+name: PEP8 Check
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+jobs:
+ pep8:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Python 3.10
+ uses: actions/setup-python@v4
+ with:
+ python-version: '3.10'
+ - name: Install flake8
+ run: pip install flake8
+ - name: Run flake8
+ run: flake8 --ignore=E501 .
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000000..a3e3d66fed9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,149 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from 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/
+
+# 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
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.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
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__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/
+.idea/'
+
+.DS_Store
+.vscode
+
+# Intellij IDEA Files
+.idea/
+.ideaDataSources/
+
+api/.env
+api/storage/*
+
+docker/volumes/app/storage/privkeys/*
+docker/volumes/db/data/*
+docker/volumes/redis/data/*
+docker/volumes/weaviate/*
+
+sdks/python-client/build
+sdks/python-client/dist
+sdks/python-client/dify_client.egg-info
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 00000000000..9590606d92e
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,6 @@
+nite-knite
+goocarlos
+crazywoola
+iamjoel
+idsong
+takatost
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000000..e96a51072fa
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,56 @@
+# Contributing
+
+Thanks for your interest in [Dify](https://dify.ai) and for wanting to contribute! Before you begin, read the
+[code of conduct](https://github.com/langgenius/.github/blob/main/CODE_OF_CONDUCT.md) and check out the
+[existing issues](https://github.com/langgenius/langgenius-gateway/issues).
+This document describes how to set up your development environment to build and test [Dify](https://dify.ai).
+
+### Install dependencies
+
+You need to install and configure the following dependencies on your machine to build [Dify](https://dify.ai):
+
+- [Git](http://git-scm.com/)
+- [Docker](https://www.docker.com/)
+- [Docker Compose](https://docs.docker.com/compose/install/)
+- [Node.js v18.x (LTS)](http://nodejs.org)
+- [npm](https://www.npmjs.com/) version 8.x.x or [Yarn](https://yarnpkg.com/)
+- [Python](https://www.python.org/) version 3.10.x
+
+## Local development
+
+To set up a working development environment, just fork the project git repository and install the backend and frontend dependencies using the proper package manager and create run the docker-compose stack.
+
+### Fork the repository
+
+you need to fork the [repository](https://github.com/langgenius/langgenius-gateway).
+
+### Clone the repo
+
+Clone your GitHub forked repository:
+
+```
+git clone [email protected]:<github_username>/langgenius-gateway.git
+```
+
+### Install backend
+
+To learn how to install the backend application, please refer to the [Backend README](api/README.md).
+
+### Install frontend
+
+To learn how to install the frontend application, please refer to the [Frontend README](web/README.md).
+
+### Visit dify in your browser
+
+Finally, you can now visit [http://localhost:3000](http://localhost:3000) to view the [Dify](https://dify.ai) in local environment.
+
+
+## Create a pull request
+
+After making your changes, open a pull request (PR). Once you submit your pull request, others from the Dify team/community will review it with you.
+
+Did you have an issue, like a merge conflict, or don't know how to open a pull request? Check out [GitHub's pull request tutorial](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests) on how to resolve merge conflicts and other issues. Once your PR has been merged, you will be proudly listed as a contributor in the [contributor chart](https://github.com/langgenius/langgenius-gateway/graphs/contributors).
+
+## Community channels
+
+Stuck somewhere? Have any questions? Join the [Discord Community Server](https://discord.gg/AhzKf7dNgk). We are here to help!
diff --git a/CONTRIBUTING_CN.md b/CONTRIBUTING_CN.md
new file mode 100644
index 00000000000..51327d24b7a
--- /dev/null
+++ b/CONTRIBUTING_CN.md
@@ -0,0 +1,53 @@
+# 贡献
+
+感谢您对 [Dify](https://dify.ai) 的兴趣,并希望您能够做出贡献!在开始之前,请先阅读[行为准则](https://github.com/langgenius/.github/blob/main/CODE_OF_CONDUCT.md)并查看[现有问题](https://github.com/langgenius/dify/issues)。
+本文档介绍了如何设置开发环境以构建和测试 [Dify](https://dify.ai)。
+
+### 安装依赖项
+
+您需要在计算机上安装和配置以下依赖项才能构建 [Dify](https://dify.ai):
+
+- [Git](http://git-scm.com/)
+- [Docker](https://www.docker.com/)
+- [Docker Compose](https://docs.docker.com/compose/install/)
+- [Node.js v18.x (LTS)](http://nodejs.org)
+- [npm](https://www.npmjs.com/) 版本 8.x.x 或 [Yarn](https://yarnpkg.com/)
+- [Python](https://www.python.org/) 版本 3.10.x
+
+## 本地开发
+
+要设置一个可工作的开发环境,只需 fork 项目的 git 存储库,并使用适当的软件包管理器安装后端和前端依赖项,然后创建并运行 docker-compose 堆栈。
+
+### Fork存储库
+
+您需要 fork [存储库](https://github.com/langgenius/dify)。
+
+### 克隆存储库
+
+克隆您在 GitHub 上 fork 的存储库:
+
+```
+git clone [email protected]:<github_username>/dify.git
+```
+
+### 安装后端
+
+要了解如何安装后端应用程序,请参阅[后端 README](api/README.md)。
+
+### 安装前端
+
+要了解如何安装前端应用程序,请参阅[前端 README](web/README.md)。
+
+### 在浏览器中访问 Dify
+
+最后,您现在可以访问 [http://localhost:3000](http://localhost:3000) 在本地环境中查看 [Dify](https://dify.ai)。
+
+## 创建拉取请求
+
+在进行更改后,打开一个拉取请求(PR)。提交拉取请求后,Dify 团队/社区的其他人将与您一起审查它。
+
+如果遇到问题,比如合并冲突或不知道如何打开拉取请求,请查看 GitHub 的[拉取请求教程](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests),了解如何解决合并冲突和其他问题。一旦您的 PR 被合并,您将自豪地被列为[贡献者表](https://github.com/langgenius/dify/graphs/contributors)中的一员。
+
+## 社区渠道
+
+遇到困难了吗?有任何问题吗? 加入 [Discord Community Server](https://discord.gg/AhzKf7dNgk),我们将为您提供帮助。
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000000..d5d166643fe
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,46 @@
+# Dify Open Source License
+
+The Dify project uses a combination of the Apache License 2.0, MIT License, and an additional agreement to protect against direct competition with Dify Cloud services.
+
+As a contributor, you should agree that your contributed code:
+a. Might be subject to a more permissive open source license in the future.
+b. Can be used for commercial purposes, such as Dify's cloud business.
+
+The following components are open source under the MIT license, allowing you to build and develop applications based on them:
+- WebApp elements, e.g., web/app/components/share
+- Derived WebApp Template projects
+
+The remaining parts of the project are open source under the Apache License 2.0.
+
+With the Apache License 2.0, MIT License, and this supplementary agreement, anyone can freely use, modify, and distribute Dify, provided that:
+
+- If you use Dify solely as a backend service for other applications, no authorization is needed for commercial or closed source purposes.
+- If you wish to use Dify for commercial and closed source SaaS services similar to Dify Cloud, please contact us for authorization.
+
+The interactive design of this product is protected by appearance patent.
+
+© 2023 LangGenius, Inc.
+
+----------
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+----------
+The MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 00000000000..169618b79f1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,115 @@
+![](./images/describe-en.png)
+<p align="center">
+ <a href="./README.md">English</a> |
+ <a href="./README_CN.md">简体中文</a>
+</p>
+
+[Website](http://dify.ai) • [Docs](https://docs.dify.ai) • [Twitter](https://twitter.com/dify_ai)
+
+**Dify** is an easy-to-use LLMOps platform designed to empower more people to create sustainable, AI-native applications. With visual orchestration for various application types, Dify offers out-of-the-box, ready-to-use applications that can also serve as Backend-as-a-Service APIs. Unify your development process with one API for plugins and datasets integration, and streamline your operations using a single interface for prompt engineering, visual analytics, and continuous improvement.
+
+Applications created with Dify include:
+
+Out-of-the-box web sites supporting form mode and chat conversation mode
+A single API encompassing plugin capabilities, context enhancement, and more, saving you backend coding effort
+Visual data analysis, log review, and annotation for applications
+Dify is compatible with Langchain, meaning we'll gradually support multiple LLMs, currently supported:
+
+- GPT 3 (text-davinci-003)
+- GPT 3.5 Turbo(ChatGPT)
+- GPT-4
+
+## Use Cloud Services
+
+Visit [Dify.ai](http://dify.ai)
+
+## Install the Community Edition
+
+### System Requirements
+
+Before installing Dify, make sure your machine meets the following minimum system requirements:
+
+- CPU >= 1 Core
+- RAM >= 4GB
+
+### Quick Start
+
+The easiest way to start the Dify server is to run our [docker-compose.yml](docker/docker-compose.yaml) file. Before running the installation command, make sure that [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) are installed on your machine:
+
+```bash
+cd docker
+docker-compose up -d
+```
+
+After running, you can access the Dify console in your browser at [http://localhost](http://localhost) and start the initialization operation.
+
+### Configuration
+
+If you need to customize the configuration, please refer to the comments in our [docker-compose.yml](docker/docker-compose.yaml) file and manually set the environment configuration. After making the changes, please run 'docker-compose up -d' again.
+
+## Roadmap
+
+Features under development:
+
+- **Datasets**, supporting more datasets, e.g. syncing content from Notion or webpages
+We will support more datasets, including text, webpages, and even Notion content. Users can build AI applications based on their own data sources.
+- **Plugins**, introducing ChatGPT Plugin-standard plugins for applications, or using Dify-produced plugins
+We will release plugins complying with ChatGPT standard, or Dify's own plugins to enable more capabilities in applications.
+- **Open-source models**, e.g. adopting Llama as a model provider or for further fine-tuning
+We will work with excellent open-source models like Llama, by providing them as model options in our platform, or using them for further fine-tuning.
+
+
+## Q&A
+
+**Q: What can I do with Dify?**
+
+A: Dify is a simple yet powerful LLM development and operations tool. You can use it to build commercial-grade applications, personal assistants. If you want to develop your own applications, LangDifyGenius can save you backend work in integrating with OpenAI and offer visual operations capabilities, allowing you to continuously improve and train your GPT model.
+
+**Q: How do I use Dify to "train" my own model?**
+
+A: A valuable application consists of Prompt Engineering, context enhancement, and Fine-tuning. We've created a hybrid programming approach combining Prompts with programming languages (similar to a template engine), making it easy to accomplish long-text embedding or capturing subtitles from a user-input Youtube video - all of which will be submitted as context for LLMs to process. We place great emphasis on application operability, with data generated by users during App usage available for analysis, annotation, and continuous training. Without the right tools, these steps can be time-consuming.
+
+**Q: What do I need to prepare if I want to create my own application?**
+
+A: We assume you already have an OpenAI API Key; if not, please register for one. If you already have some content that can serve as training context, that's great!
+
+**Q: What interface languages are available?**
+
+A: English and Chinese are currently supported, and you can contribute language packs to us.
+
+## Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
+
+## Contact Us
+
+If you have any questions, suggestions, or partnership inquiries, feel free to contact us through the following channels:
+
+- Submit an Issue or PR on our GitHub Repo
+- Join the discussion in our [Discord](https://discord.gg/AhzKf7dNgk) Community
+- Send an email to [email protected]
+
+We're eager to assist you and together create more fun and useful AI applications!
+
+## Contributing
+
+To ensure proper review, all code contributions - including those from contributors with direct commit access - must be submitted via pull requests and approved by the core development team prior to being merged.
+
+We welcome all pull requests! If you'd like to help, check out the [Contribution Guide](CONTRIBUTING.md) for more information on how to get started.
+
+## Security
+
+To protect your privacy, please avoid posting security issues on GitHub. Instead, send your questions to [email protected] and we will provide you with a more detailed answer.
+
+## Citation
+
+This software uses the following open-source software:
+
+- Chase, H. (2022). LangChain [Computer software]. https://github.com/hwchase17/langchain
+- Liu, J. (2022). LlamaIndex [Computer software]. doi: 10.5281/zenodo.1234.
+
+For more information, please refer to the official website or license text of the respective software.
+
+## License
+
+This repository is available under the [Dify Open Source License](LICENSE).
diff --git a/README_CN.md b/README_CN.md
new file mode 100644
index 00000000000..3788c857fcc
--- /dev/null
+++ b/README_CN.md
@@ -0,0 +1,114 @@
+![](./images/describe-cn.jpg)
+<p align="center">
+ <a href="./README.md">English</a> |
+ <a href="./README_CN.md">简体中文</a>
+</p>
+
+
+[官方网站](http://dify.ai) • [文档](https://docs.dify.ai/v/zh-hans) • [Twitter](https://twitter.com/dify_ai)
+
+**Dify** 是一个易用的 LLMOps 平台,旨在让更多人可以创建可持续运营的原生 AI 应用。Dify 提供多种类型应用的可视化编排,应用可开箱即用,也能以“后端即服务”的 API 提供服务。
+
+通过 Dify 创建的应用包含了:
+
+- 开箱即用的的 Web 站点,支持表单模式和聊天对话模式
+- 一套 API 即可包含插件、上下文增强等能力,替你省下了后端代码的编写工作
+- 可视化的对应用进行数据分析,查阅日志或进行标注
+
+Dify 兼容 Langchain,这意味着我们将逐步支持多种 LLMs ,目前已支持:
+
+- GPT 3 (text-davinci-003)
+- GPT 3.5 Turbo(ChatGPT)
+- GPT-4
+
+## 使用云服务
+
+访问 [Dify.ai](http://cloud.dify.ai)
+
+## 安装社区版
+
+### 系统要求
+
+在安装 Dify 之前,请确保您的机器满足以下最低系统要求:
+
+- CPU >= 1 Core
+- RAM >= 4GB
+
+### 快速启动
+
+启动 Dify 服务器的最简单方法是运行我们的 [docker-compose.yml](docker/docker-compose.yaml) 文件。在运行安装命令之前,请确保您的机器上安装了 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://docs.docker.com/compose/install/):
+
+```bash
+cd docker
+docker-compose up -d
+```
+
+运行后,可以在浏览器上访问 [http://localhost](http://localhost) 进入 Dify 控制台,并开始初始化操作。
+
+### 配置
+
+需要自定义配置,请参考我们的 [docker-compose.yml](docker/docker-compose.yaml) 文件中的注释,并手动设置环境配置,修改完毕后,请再次执行 `docker-compose up -d`。
+
+## Roadmap
+
+我们正在开发中的功能:
+
+- **数据集**,支持更多的数据集,例如同步 Notion 或网页的内容
+我们将支持更多的数据集,包括文本、网页,甚至 Notion 内容。用户可以根据自己的数据源构建 AI 应用程序。
+- **插件**,推出符合 ChatGPT 标准的插件,或使用 Dify 产生的插件
+我们将发布符合 ChatGPT 标准的插件,或者 Dify 自己的插件,以在应用程序中启用更多功能。
+- **开源模型**,例如采用 Llama 作为模型提供者,或进行进一步的微调
+我们将与优秀的开源模型如 Llama 合作,通过在我们的平台中提供它们作为模型选项,或使用它们进行进一步的微调。
+
+## Q&A
+
+**Q: 我能用 Dify 做什么?**
+
+A: Dify 是一个简单且能力丰富的 LLM 开发和运营工具。你可以用它搭建商用级应用,个人助理。如果你想自己开发应用,Dify 也能为你省下接入 OpenAI 的后端工作,使用我们逐步提供的可视化运营能力,你可以持续的改进和训练你的 GPT 模型。
+
+**Q: 如何使用 Dify “训练”自己的模型?**
+
+A: 一个有价值的应用由 Prompt Engineering、上下文增强和 Fine-tune 三个环节组成。我们创造了一种 Prompt 结合编程语言的 Hybrid 编程方式(类似一个模版引擎),你可以轻松的完成长文本嵌入,或抓取用户输入的一个 Youtube 视频的字幕——这些都将作为上下文提交给 LLMs 进行计算。我们十分注重应用的可运营性,你的用户在使用 App 期间产生的数据,可进行分析、标记和持续训练。以上环节如果没有好的工具支持,可能会消耗你大量的时间。
+
+**Q: 如果要创建一个自己的应用,我需要准备什么?**
+
+A: 我们假定你已经有了 OpenAI API Key,如果没有请去注册一个。如果你已经有了一些内容可以作为训练上下文,就太好了。
+
+**Q: 提供哪些界面语言?**
+
+A: 现已支持英文与中文,你可以为我们贡献语言包。
+
+## Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
+
+## 联系我们
+
+如果您有任何问题、建议或合作意向,欢迎通过以下方式联系我们:
+
+- 在我们的 [GitHub Repo](https://github.com/langgenius/dify) 上提交 Issue 或 PR
+- 在我们的 [Discord 社区](https://discord.gg/AhzKf7dNgk) 上加入讨论
+- 发送邮件至 [email protected]
+
+## 贡献代码
+
+为了确保正确审查,所有代码贡献 - 包括来自具有直接提交更改权限的贡献者 - 都必须提交 PR 请求并在合并分支之前得到核心开发人员的批准。
+
+我们欢迎所有人提交 PR!如果您愿意提供帮助,可以在 [贡献指南](CONTRIBUTING_CN.md) 中了解有关如何为项目做出贡献的更多信息。
+
+## 安全
+
+为了保护您的隐私,请避免在 GitHub 上发布安全问题。发送问题至 [email protected],我们将为您做更细致的解答。
+
+## Citation
+
+本软件使用了以下开源软件:
+
+- Chase, H. (2022). LangChain [Computer software]. https://github.com/hwchase17/langchain
+- Liu, J. (2022). LlamaIndex [Computer software]. doi: 10.5281/zenodo.1234.
+
+更多信息,请参考相应软件的官方网站或许可证文本。
+
+## License
+
+本仓库遵循 [Dify Open Source License](LICENSE) 开源协议。
diff --git a/api/.dockerignore b/api/.dockerignore
new file mode 100644
index 00000000000..9b5050396df
--- /dev/null
+++ b/api/.dockerignore
@@ -0,0 +1,2 @@
+.env
+storage/privkeys/*
\ No newline at end of file
diff --git a/api/.env.example b/api/.env.example
new file mode 100644
index 00000000000..5f307dc106d
--- /dev/null
+++ b/api/.env.example
@@ -0,0 +1,85 @@
+# Server Edition
+EDITION=SELF_HOSTED
+
+# Your App secret key will be used for securely signing the session cookie
+# Make sure you are changing this key for your deployment with a strong key.
+# You can generate a strong key using `openssl rand -base64 42`.
+# Alternatively you can set it with `SECRET_KEY` environment variable.
+SECRET_KEY=
+
+# Console API base URL
+CONSOLE_URL=http://127.0.0.1:5001
+
+# Service API base URL
+API_URL=http://127.0.0.1:5001
+
+# Web APP base URL
+APP_URL=http://127.0.0.1:5001
+
+# celery configuration
+CELERY_BROKER_URL=redis://:difyai123456@localhost:6379/1
+
+# redis configuration
+REDIS_HOST=localhost
+REDIS_PORT=6379
+REDIS_PASSWORD=difyai123456
+REDIS_DB=0
+
+# PostgreSQL database configuration
+DB_USERNAME=postgres
+DB_PASSWORD=difyai123456
+DB_HOST=localhost
+DB_PORT=5432
+DB_DATABASE=dify
+
+# Storage configuration
+# use for store upload files, private keys...
+# storage type: local, s3
+STORAGE_TYPE=local
+STORAGE_LOCAL_PATH=storage
+S3_ENDPOINT=https://your-bucket-name.storage.s3.clooudflare.com
+S3_BUCKET_NAME=your-bucket-name
+S3_ACCESS_KEY=your-access-key
+S3_SECRET_KEY=your-secret-key
+S3_REGION=your-region
+
+# CORS configuration
+WEB_API_CORS_ALLOW_ORIGINS=http://127.0.0.1:3000,*
+CONSOLE_CORS_ALLOW_ORIGINS=http://127.0.0.1:3000,*
+
+# Cookie configuration
+COOKIE_HTTPONLY=true
+COOKIE_SAMESITE=None
+COOKIE_SECURE=true
+
+# Session configuration
+SESSION_PERMANENT=true
+SESSION_USE_SIGNER=true
+
+## support redis, sqlalchemy
+SESSION_TYPE=redis
+
+# session redis configuration
+SESSION_REDIS_HOST=localhost
+SESSION_REDIS_PORT=6379
+SESSION_REDIS_PASSWORD=difyai123456
+SESSION_REDIS_DB=2
+
+# Vector database configuration, support: weaviate, qdrant
+VECTOR_STORE=weaviate
+
+# Weaviate configuration
+WEAVIATE_ENDPOINT=http://localhost:8080
+WEAVIATE_API_KEY=WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih
+WEAVIATE_GRPC_ENABLED=false
+
+# Qdrant configuration, use `path:` prefix for local mode or `https://your-qdrant-cluster-url.qdrant.io` for remote mode
+QDRANT_URL=path:storage/qdrant
+QDRANT_API_KEY=your-qdrant-api-key
+
+# Sentry configuration
+SENTRY_DSN=
+
+# DEBUG
+DEBUG=false
+SQLALCHEMY_ECHO=false
diff --git a/api/Dockerfile b/api/Dockerfile
new file mode 100644
index 00000000000..fb451129d1e
--- /dev/null
+++ b/api/Dockerfile
@@ -0,0 +1,28 @@
+FROM langgenius/base:1.0.0-bullseye-slim as langgenius-api
+
+LABEL maintainer="[email protected]"
+
+ENV FLASK_APP app.py
+ENV EDITION SELF_HOSTED
+ENV DEPLOY_ENV PRODUCTION
+ENV CONSOLE_URL http://127.0.0.1:5001
+ENV API_URL http://127.0.0.1:5001
+ENV APP_URL http://127.0.0.1:5001
+
+EXPOSE 5001
+
+WORKDIR /app/api
+
+COPY requirements.txt /app/api/requirements.txt
+
+RUN pip install -r requirements.txt
+
+COPY . /app/api/
+
+COPY docker/entrypoint.sh /entrypoint.sh
+RUN chmod +x /entrypoint.sh
+
+ARG COMMIT_SHA
+ENV COMMIT_SHA ${COMMIT_SHA}
+
+ENTRYPOINT ["/entrypoint.sh"]
\ No newline at end of file
diff --git a/api/README.md b/api/README.md
new file mode 100644
index 00000000000..97f09fc700c
--- /dev/null
+++ b/api/README.md
@@ -0,0 +1,35 @@
+# Dify Backend API
+
+## Usage
+
+1. Start the docker-compose stack
+
+ The backend require some middleware, including PostgreSQL, Redis, and Weaviate, which can be started together using `docker-compose`.
+
+ ```bash
+ cd ../docker
+ docker-compose -f docker-compose.middleware.yaml up -d
+ cd ../api
+ ```
+2. Copy `.env.example` to `.env`
+3. Generate a `SECRET_KEY` in the `.env` file.
+
+ ```bash
+ openssl rand -base64 42
+ ```
+4. Install dependencies
+ ```bash
+ pip install -r requirements.txt
+ ```
+5. Run migrate
+
+ Before the first launch, migrate the database to the latest version.
+
+ ```bash
+ flask db upgrade
+ ```
+6. Start backend:
+ ```bash
+ flask run --host 0.0.0.0 --port=5001 --debug
+ ```
+7. Setup your application by visiting http://localhost:5001/console/api/setup or other apis...
diff --git a/api/app.py b/api/app.py
new file mode 100644
index 00000000000..b3fcbc220ad
--- /dev/null
+++ b/api/app.py
@@ -0,0 +1,222 @@
+# -*- coding:utf-8 -*-
+import os
+if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
+ from gevent import monkey
+ monkey.patch_all()
+
+import logging
+import json
+import threading
+
+from flask import Flask, request, Response, session
+import flask_login
+from flask_cors import CORS
+
+from extensions import ext_session, ext_celery, ext_sentry, ext_redis, ext_login, ext_vector_store, ext_migrate, \
+ ext_database, ext_storage
+from extensions.ext_database import db
+from extensions.ext_login import login_manager
+
+# DO NOT REMOVE BELOW
+from models import model, account, dataset, web, task
+from events import event_handlers
+# DO NOT REMOVE ABOVE
+
+import core
+from config import Config, CloudEditionConfig
+from commands import register_commands
+from models.account import TenantAccountJoin
+from models.model import Account, EndUser, App
+
+import warnings
+warnings.simplefilter("ignore", ResourceWarning)
+
+
+class DifyApp(Flask):
+ pass
+
+# -------------
+# Configuration
+# -------------
+
+
+config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
+
+# ----------------------------
+# Application Factory Function
+# ----------------------------
+
+
+def create_app(test_config=None) -> Flask:
+ app = DifyApp(__name__)
+
+ if test_config:
+ app.config.from_object(test_config)
+ else:
+ if config_type == "CLOUD":
+ app.config.from_object(CloudEditionConfig())
+ else:
+ app.config.from_object(Config())
+
+ app.secret_key = app.config['SECRET_KEY']
+
+ logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
+
+ initialize_extensions(app)
+ register_blueprints(app)
+ register_commands(app)
+
+ core.init_app(app)
+
+ return app
+
+
+def initialize_extensions(app):
+ # Since the application instance is now created, pass it to each Flask
+ # extension instance to bind it to the Flask application instance (app)
+ ext_database.init_app(app)
+ ext_migrate.init(app, db)
+ ext_redis.init_app(app)
+ ext_vector_store.init_app(app)
+ ext_storage.init_app(app)
+ ext_celery.init_app(app)
+ ext_session.init_app(app)
+ ext_login.init_app(app)
+ ext_sentry.init_app(app)
+
+
+# Flask-Login configuration
+@login_manager.user_loader
+def load_user(user_id):
+ """Load user based on the user_id."""
+ if request.blueprint == 'console':
+ # Check if the user_id contains a dot, indicating the old format
+ if '.' in user_id:
+ tenant_id, account_id = user_id.split('.')
+ else:
+ account_id = user_id
+
+ account = db.session.query(Account).filter(Account.id == account_id).first()
+
+ if account:
+ workspace_id = session.get('workspace_id')
+ if workspace_id:
+ tenant_account_join = db.session.query(TenantAccountJoin).filter(
+ TenantAccountJoin.account_id == account.id,
+ TenantAccountJoin.tenant_id == workspace_id
+ ).first()
+
+ if not tenant_account_join:
+ tenant_account_join = db.session.query(TenantAccountJoin).filter(
+ TenantAccountJoin.account_id == account.id).first()
+
+ if tenant_account_join:
+ account.current_tenant_id = tenant_account_join.tenant_id
+ session['workspace_id'] = account.current_tenant_id
+ else:
+ account.current_tenant_id = workspace_id
+ else:
+ tenant_account_join = db.session.query(TenantAccountJoin).filter(
+ TenantAccountJoin.account_id == account.id).first()
+ if tenant_account_join:
+ account.current_tenant_id = tenant_account_join.tenant_id
+ session['workspace_id'] = account.current_tenant_id
+
+ # Log in the user with the updated user_id
+ flask_login.login_user(account, remember=True)
+
+ return account
+ else:
+ return None
+
+
+@login_manager.unauthorized_handler
+def unauthorized_handler():
+ """Handle unauthorized requests."""
+ return Response(json.dumps({
+ 'code': 'unauthorized',
+ 'message': "Unauthorized."
+ }), status=401, content_type="application/json")
+
+
+# register blueprint routers
+def register_blueprints(app):
+ from controllers.service_api import bp as service_api_bp
+ from controllers.web import bp as web_bp
+ from controllers.console import bp as console_app_bp
+
+ app.register_blueprint(service_api_bp)
+
+ CORS(web_bp,
+ resources={
+ r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
+ supports_credentials=True,
+ allow_headers=['Content-Type', 'Authorization'],
+ methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
+ expose_headers=['X-Version', 'X-Env']
+ )
+
+ app.register_blueprint(web_bp)
+
+ CORS(console_app_bp,
+ resources={
+ r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
+ supports_credentials=True,
+ allow_headers=['Content-Type', 'Authorization'],
+ methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
+ expose_headers=['X-Version', 'X-Env']
+ )
+
+ app.register_blueprint(console_app_bp)
+
+
+# create app
+app = create_app()
+celery = app.extensions["celery"]
+
+
+if app.config['TESTING']:
+ print("App is running in TESTING mode")
+
+
+def after_request(response):
+ """Add Version headers to the response."""
+ response.headers.add('X-Version', app.config['CURRENT_VERSION'])
+ response.headers.add('X-Env', app.config['DEPLOY_ENV'])
+ return response
+
+
+def health():
+ return Response(json.dumps({
+ 'status': 'ok',
+ 'version': app.config['CURRENT_VERSION']
+ }), status=200, content_type="application/json")
+
+
[email protected]('/threads')
+def threads():
+ num_threads = threading.active_count()
+ threads = threading.enumerate()
+
+ thread_list = []
+ for thread in threads:
+ thread_name = thread.name
+ thread_id = thread.ident
+ is_alive = thread.is_alive()
+
+ thread_list.append({
+ 'name': thread_name,
+ 'id': thread_id,
+ 'is_alive': is_alive
+ })
+
+ return {
+ 'thread_num': num_threads,
+ 'threads': thread_list
+ }
+
+
+if __name__ == '__main__':
+ app.run(host='0.0.0.0', port=5001)
diff --git a/api/commands.py b/api/commands.py
new file mode 100644
index 00000000000..b67b4f86765
--- /dev/null
+++ b/api/commands.py
@@ -0,0 +1,160 @@
+import datetime
+import json
+import random
+import string
+
+import click
+
+from libs.password import password_pattern, valid_password, hash_password
+from libs.helper import email as email_validate
+from extensions.ext_database import db
+from models.account import InvitationCode
+from models.model import Account, AppModelConfig, ApiToken, Site, App, RecommendedApp
+import secrets
+import base64
+
+
[email protected]('reset-password', help='Reset the account password.')
[email protected]('--email', prompt=True, help='The email address of the account whose password you need to reset')
[email protected]('--new-password', prompt=True, help='the new password.')
[email protected]('--password-confirm', prompt=True, help='the new password confirm.')
+def reset_password(email, new_password, password_confirm):
+ if str(new_password).strip() != str(password_confirm).strip():
+ click.echo(click.style('sorry. The two passwords do not match.', fg='red'))
+ return
+ account = db.session.query(Account). \
+ filter(Account.email == email). \
+ one_or_none()
+ if not account:
+ click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
+ return
+ try:
+ valid_password(new_password)
+ except:
+ click.echo(
+ click.style('sorry. The passwords must match {} '.format(password_pattern), fg='red'))
+ return
+
+ # generate password salt
+ salt = secrets.token_bytes(16)
+ base64_salt = base64.b64encode(salt).decode()
+
+ # encrypt password with salt
+ password_hashed = hash_password(new_password, salt)
+ base64_password_hashed = base64.b64encode(password_hashed).decode()
+ account.password = base64_password_hashed
+ account.password_salt = base64_salt
+ db.session.commit()
+ click.echo(click.style('Congratulations!, password has been reset.', fg='green'))
+
+
[email protected]('reset-email', help='Reset the account email.')
[email protected]('--email', prompt=True, help='The old email address of the account whose email you need to reset')
[email protected]('--new-email', prompt=True, help='the new email.')
[email protected]('--email-confirm', prompt=True, help='the new email confirm.')
+def reset_email(email, new_email, email_confirm):
+ if str(new_email).strip() != str(email_confirm).strip():
+ click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red'))
+ return
+ account = db.session.query(Account). \
+ filter(Account.email == email). \
+ one_or_none()
+ if not account:
+ click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
+ return
+ try:
+ email_validate(new_email)
+ except:
+ click.echo(
+ click.style('sorry. {} is not a valid email. '.format(email), fg='red'))
+ return
+
+ account.email = new_email
+ db.session.commit()
+ click.echo(click.style('Congratulations!, email has been reset.', fg='green'))
+
+
[email protected]('generate-invitation-codes', help='Generate invitation codes.')
[email protected]('--batch', help='The batch of invitation codes.')
[email protected]('--count', prompt=True, help='Invitation codes count.')
+def generate_invitation_codes(batch, count):
+ if not batch:
+ now = datetime.datetime.now()
+ batch = now.strftime('%Y%m%d%H%M%S')
+
+ if not count or int(count) <= 0:
+ click.echo(click.style('sorry. the count must be greater than 0.', fg='red'))
+ return
+
+ count = int(count)
+
+ click.echo('Start generate {} invitation codes for batch {}.'.format(count, batch))
+
+ codes = ''
+ for i in range(count):
+ code = generate_invitation_code()
+ invitation_code = InvitationCode(
+ code=code,
+ batch=batch
+ )
+ db.session.add(invitation_code)
+ click.echo(code)
+
+ codes += code + "\n"
+ db.session.commit()
+
+ filename = 'storage/invitation-codes-{}.txt'.format(batch)
+
+ with open(filename, 'w') as f:
+ f.write(codes)
+
+ click.echo(click.style(
+ 'Congratulations! Generated {} invitation codes for batch {} and saved to the file \'{}\''.format(count, batch,
+ filename),
+ fg='green'))
+
+
+def generate_invitation_code():
+ code = generate_upper_string()
+ while db.session.query(InvitationCode).filter(InvitationCode.code == code).count() > 0:
+ code = generate_upper_string()
+
+ return code
+
+
+def generate_upper_string():
+ letters_digits = string.ascii_uppercase + string.digits
+ result = ""
+ for i in range(8):
+ result += random.choice(letters_digits)
+
+ return result
+
+
[email protected]('gen-recommended-apps', help='Number of records to generate')
+def generate_recommended_apps():
+ print('Generating recommended app data...')
+ apps = App.query.all()
+ for app in apps:
+ recommended_app = RecommendedApp(
+ app_id=app.id,
+ description={
+ 'en': 'Description for ' + app.name,
+ 'zh': '描述 ' + app.name
+ },
+ copyright='Copyright ' + str(random.randint(1990, 2020)),
+ privacy_policy='https://privacypolicy.example.com',
+ category=random.choice(['Games', 'News', 'Music', 'Sports']),
+ position=random.randint(1, 100),
+ install_count=random.randint(100, 100000)
+ )
+ db.session.add(recommended_app)
+ db.session.commit()
+ print('Done!')
+
+
+def register_commands(app):
+ app.cli.add_command(reset_password)
+ app.cli.add_command(reset_email)
+ app.cli.add_command(generate_invitation_codes)
+ app.cli.add_command(generate_recommended_apps)
diff --git a/api/config.py b/api/config.py
new file mode 100644
index 00000000000..04c44f24479
--- /dev/null
+++ b/api/config.py
@@ -0,0 +1,200 @@
+# -*- coding:utf-8 -*-
+import os
+from datetime import timedelta
+
+import dotenv
+
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+
+dotenv.load_dotenv()
+
+DEFAULTS = {
+ 'COOKIE_HTTPONLY': 'True',
+ 'COOKIE_SECURE': 'True',
+ 'COOKIE_SAMESITE': 'None',
+ 'DB_USERNAME': 'postgres',
+ 'DB_PASSWORD': '',
+ 'DB_HOST': 'localhost',
+ 'DB_PORT': '5432',
+ 'DB_DATABASE': 'dify',
+ 'REDIS_HOST': 'localhost',
+ 'REDIS_PORT': '6379',
+ 'REDIS_DB': '0',
+ 'SESSION_REDIS_HOST': 'localhost',
+ 'SESSION_REDIS_PORT': '6379',
+ 'SESSION_REDIS_DB': '2',
+ 'OAUTH_REDIRECT_PATH': '/console/api/oauth/authorize',
+ 'OAUTH_REDIRECT_INDEX_PATH': '/',
+ 'CONSOLE_URL': 'https://cloud.dify.ai',
+ 'API_URL': 'https://api.dify.ai',
+ 'APP_URL': 'https://udify.app',
+ 'STORAGE_TYPE': 'local',
+ 'STORAGE_LOCAL_PATH': 'storage',
+ 'CHECK_UPDATE_URL': 'https://updates.dify.ai',
+ 'SESSION_TYPE': 'sqlalchemy',
+ 'SESSION_PERMANENT': 'True',
+ 'SESSION_USE_SIGNER': 'True',
+ 'DEPLOY_ENV': 'PRODUCTION',
+ 'SQLALCHEMY_POOL_SIZE': 30,
+ 'SQLALCHEMY_ECHO': 'False',
+ 'SENTRY_TRACES_SAMPLE_RATE': 1.0,
+ 'SENTRY_PROFILES_SAMPLE_RATE': 1.0,
+ 'WEAVIATE_GRPC_ENABLED': 'True',
+ 'CELERY_BACKEND': 'database',
+ 'PDF_PREVIEW': 'True',
+ 'LOG_LEVEL': 'INFO',
+}
+
+
+def get_env(key):
+ return os.environ.get(key, DEFAULTS.get(key))
+
+
+def get_bool_env(key):
+ return get_env(key).lower() == 'true'
+
+
+def get_cors_allow_origins(env, default):
+ cors_allow_origins = []
+ if get_env(env):
+ for origin in get_env(env).split(','):
+ cors_allow_origins.append(origin)
+ else:
+ cors_allow_origins = [default]
+
+ return cors_allow_origins
+
+
+class Config:
+ """Application configuration class."""
+
+ def __init__(self):
+ # app settings
+ self.CONSOLE_URL = get_env('CONSOLE_URL')
+ self.API_URL = get_env('API_URL')
+ self.APP_URL = get_env('APP_URL')
+ self.CURRENT_VERSION = "0.2.0"
+ self.COMMIT_SHA = get_env('COMMIT_SHA')
+ self.EDITION = "SELF_HOSTED"
+ self.DEPLOY_ENV = get_env('DEPLOY_ENV')
+ self.TESTING = False
+ self.LOG_LEVEL = get_env('LOG_LEVEL')
+ self.PDF_PREVIEW = get_bool_env('PDF_PREVIEW')
+
+ # Your App secret key will be used for securely signing the session cookie
+ # Make sure you are changing this key for your deployment with a strong key.
+ # You can generate a strong key using `openssl rand -base64 42`.
+ # Alternatively you can set it with `SECRET_KEY` environment variable.
+ self.SECRET_KEY = get_env('SECRET_KEY')
+
+ # cookie settings
+ self.REMEMBER_COOKIE_HTTPONLY = get_bool_env('COOKIE_HTTPONLY')
+ self.SESSION_COOKIE_HTTPONLY = get_bool_env('COOKIE_HTTPONLY')
+ self.REMEMBER_COOKIE_SAMESITE = get_env('COOKIE_SAMESITE')
+ self.SESSION_COOKIE_SAMESITE = get_env('COOKIE_SAMESITE')
+ self.REMEMBER_COOKIE_SECURE = get_bool_env('COOKIE_SECURE')
+ self.SESSION_COOKIE_SECURE = get_bool_env('COOKIE_SECURE')
+ self.PERMANENT_SESSION_LIFETIME = timedelta(days=7)
+
+ # session settings, only support sqlalchemy, redis
+ self.SESSION_TYPE = get_env('SESSION_TYPE')
+ self.SESSION_PERMANENT = get_bool_env('SESSION_PERMANENT')
+ self.SESSION_USE_SIGNER = get_bool_env('SESSION_USE_SIGNER')
+
+ # redis settings
+ self.REDIS_HOST = get_env('REDIS_HOST')
+ self.REDIS_PORT = get_env('REDIS_PORT')
+ self.REDIS_PASSWORD = get_env('REDIS_PASSWORD')
+ self.REDIS_DB = get_env('REDIS_DB')
+
+ # session redis settings
+ self.SESSION_REDIS_HOST = get_env('SESSION_REDIS_HOST')
+ self.SESSION_REDIS_PORT = get_env('SESSION_REDIS_PORT')
+ self.SESSION_REDIS_PASSWORD = get_env('SESSION_REDIS_PASSWORD')
+ self.SESSION_REDIS_DB = get_env('SESSION_REDIS_DB')
+
+ # storage settings
+ self.STORAGE_TYPE = get_env('STORAGE_TYPE')
+ self.STORAGE_LOCAL_PATH = get_env('STORAGE_LOCAL_PATH')
+ self.S3_ENDPOINT = get_env('S3_ENDPOINT')
+ self.S3_BUCKET_NAME = get_env('S3_BUCKET_NAME')
+ self.S3_ACCESS_KEY = get_env('S3_ACCESS_KEY')
+ self.S3_SECRET_KEY = get_env('S3_SECRET_KEY')
+ self.S3_REGION = get_env('S3_REGION')
+
+ # vector store settings, only support weaviate, qdrant
+ self.VECTOR_STORE = get_env('VECTOR_STORE')
+
+ # weaviate settings
+ self.WEAVIATE_ENDPOINT = get_env('WEAVIATE_ENDPOINT')
+ self.WEAVIATE_API_KEY = get_env('WEAVIATE_API_KEY')
+ self.WEAVIATE_GRPC_ENABLED = get_bool_env('WEAVIATE_GRPC_ENABLED')
+
+ # qdrant settings
+ self.QDRANT_URL = get_env('QDRANT_URL')
+ self.QDRANT_API_KEY = get_env('QDRANT_API_KEY')
+
+ # cors settings
+ self.CONSOLE_CORS_ALLOW_ORIGINS = get_cors_allow_origins(
+ 'CONSOLE_CORS_ALLOW_ORIGINS', self.CONSOLE_URL)
+ self.WEB_API_CORS_ALLOW_ORIGINS = get_cors_allow_origins(
+ 'WEB_API_CORS_ALLOW_ORIGINS', '*')
+
+ # sentry settings
+ self.SENTRY_DSN = get_env('SENTRY_DSN')
+ self.SENTRY_TRACES_SAMPLE_RATE = float(get_env('SENTRY_TRACES_SAMPLE_RATE'))
+ self.SENTRY_PROFILES_SAMPLE_RATE = float(get_env('SENTRY_PROFILES_SAMPLE_RATE'))
+
+ # check update url
+ self.CHECK_UPDATE_URL = get_env('CHECK_UPDATE_URL')
+
+ # database settings
+ db_credentials = {
+ key: get_env(key) for key in
+ ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE']
+ }
+
+ self.SQLALCHEMY_DATABASE_URI = f"postgresql://{db_credentials['DB_USERNAME']}:{db_credentials['DB_PASSWORD']}@{db_credentials['DB_HOST']}:{db_credentials['DB_PORT']}/{db_credentials['DB_DATABASE']}"
+ self.SQLALCHEMY_ENGINE_OPTIONS = {'pool_size': int(get_env('SQLALCHEMY_POOL_SIZE'))}
+
+ self.SQLALCHEMY_ECHO = get_bool_env('SQLALCHEMY_ECHO')
+
+ # celery settings
+ self.CELERY_BROKER_URL = get_env('CELERY_BROKER_URL')
+ self.CELERY_BACKEND = get_env('CELERY_BACKEND')
+ self.CELERY_RESULT_BACKEND = 'db+{}'.format(self.SQLALCHEMY_DATABASE_URI) \
+ if self.CELERY_BACKEND == 'database' else self.CELERY_BROKER_URL
+
+ # hosted provider credentials
+ self.OPENAI_API_KEY = get_env('OPENAI_API_KEY')
+
+
+class CloudEditionConfig(Config):
+
+ def __init__(self):
+ super().__init__()
+
+ self.EDITION = "CLOUD"
+
+ self.GITHUB_CLIENT_ID = get_env('GITHUB_CLIENT_ID')
+ self.GITHUB_CLIENT_SECRET = get_env('GITHUB_CLIENT_SECRET')
+ self.GOOGLE_CLIENT_ID = get_env('GOOGLE_CLIENT_ID')
+ self.GOOGLE_CLIENT_SECRET = get_env('GOOGLE_CLIENT_SECRET')
+ self.OAUTH_REDIRECT_PATH = get_env('OAUTH_REDIRECT_PATH')
+
+
+class TestConfig(Config):
+
+ def __init__(self):
+ super().__init__()
+
+ self.EDITION = "SELF_HOSTED"
+ self.TESTING = True
+
+ db_credentials = {
+ key: get_env(key) for key in ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT']
+ }
+
+ # use a different database for testing: dify_test
+ self.SQLALCHEMY_DATABASE_URI = f"postgresql://{db_credentials['DB_USERNAME']}:{db_credentials['DB_PASSWORD']}@{db_credentials['DB_HOST']}:{db_credentials['DB_PORT']}/dify_test"
diff --git a/api/constants/__init__.py b/api/constants/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/constants/model_template.py b/api/constants/model_template.py
new file mode 100644
index 00000000000..f8d7e0b74ae
--- /dev/null
+++ b/api/constants/model_template.py
@@ -0,0 +1,322 @@
+import json
+
+from models.model import AppModelConfig, App
+
+model_templates = {
+ # completion default mode
+ 'completion_default': {
+ 'app': {
+ 'mode': 'completion',
+ 'enable_site': True,
+ 'enable_api': True,
+ 'is_demo': False,
+ 'api_rpm': 0,
+ 'api_rph': 0,
+ 'status': 'normal'
+ },
+ 'model_config': {
+ 'provider': 'openai',
+ 'model_id': 'text-davinci-003',
+ 'configs': {
+ 'prompt_template': '',
+ 'prompt_variables': [],
+ 'completion_params': {
+ 'max_token': 512,
+ 'temperature': 1,
+ 'top_p': 1,
+ 'presence_penalty': 0,
+ 'frequency_penalty': 0,
+ }
+ },
+ 'model': json.dumps({
+ "provider": "openai",
+ "name": "text-davinci-003",
+ "completion_params": {
+ "max_tokens": 512,
+ "temperature": 1,
+ "top_p": 1,
+ "presence_penalty": 0,
+ "frequency_penalty": 0
+ }
+ })
+ }
+ },
+
+ # chat default mode
+ 'chat_default': {
+ 'app': {
+ 'mode': 'chat',
+ 'enable_site': True,
+ 'enable_api': True,
+ 'is_demo': False,
+ 'api_rpm': 0,
+ 'api_rph': 0,
+ 'status': 'normal'
+ },
+ 'model_config': {
+ 'provider': 'openai',
+ 'model_id': 'gpt-3.5-turbo',
+ 'configs': {
+ 'prompt_template': '',
+ 'prompt_variables': [],
+ 'completion_params': {
+ 'max_token': 512,
+ 'temperature': 1,
+ 'top_p': 1,
+ 'presence_penalty': 0,
+ 'frequency_penalty': 0,
+ }
+ },
+ 'model': json.dumps({
+ "provider": "openai",
+ "name": "gpt-3.5-turbo",
+ "completion_params": {
+ "max_tokens": 512,
+ "temperature": 1,
+ "top_p": 1,
+ "presence_penalty": 0,
+ "frequency_penalty": 0
+ }
+ })
+ }
+ },
+}
+
+
+demo_model_templates = {
+ 'en-US': [
+ {
+ 'name': 'Translation Assistant',
+ 'icon': '',
+ 'icon_background': '',
+ 'description': 'A multilingual translator that provides translation capabilities in multiple languages, translating user input into the language they need.',
+ 'mode': 'completion',
+ 'model_config': AppModelConfig(
+ provider='openai',
+ model_id='text-davinci-003',
+ configs={
+ 'prompt_template': "Please translate the following text into {{target_language}}:\n",
+ 'prompt_variables': [
+ {
+ "key": "target_language",
+ "name": "Target Language",
+ "description": "The language you want to translate into.",
+ "type": "select",
+ "default": "Chinese",
+ 'options': [
+ 'Chinese',
+ 'English',
+ 'Japanese',
+ 'French',
+ 'Russian',
+ 'German',
+ 'Spanish',
+ 'Korean',
+ 'Italian',
+ ]
+ }
+ ],
+ 'completion_params': {
+ 'max_token': 1000,
+ 'temperature': 0,
+ 'top_p': 0,
+ 'presence_penalty': 0.1,
+ 'frequency_penalty': 0.1,
+ }
+ },
+ opening_statement='',
+ suggested_questions=None,
+ pre_prompt="Please translate the following text into {{target_language}}:\n",
+ model=json.dumps({
+ "provider": "openai",
+ "name": "text-davinci-003",
+ "completion_params": {
+ "max_tokens": 1000,
+ "temperature": 0,
+ "top_p": 0,
+ "presence_penalty": 0.1,
+ "frequency_penalty": 0.1
+ }
+ }),
+ user_input_form=json.dumps([
+ {
+ "select": {
+ "label": "Target Language",
+ "variable": "target_language",
+ "description": "The language you want to translate into.",
+ "default": "Chinese",
+ "required": True,
+ 'options': [
+ 'Chinese',
+ 'English',
+ 'Japanese',
+ 'French',
+ 'Russian',
+ 'German',
+ 'Spanish',
+ 'Korean',
+ 'Italian',
+ ]
+ }
+ }
+ ])
+ )
+ },
+ {
+ 'name': 'AI Front-end Interviewer',
+ 'icon': '',
+ 'icon_background': '',
+ 'description': 'A simulated front-end interviewer that tests the skill level of front-end development through questioning.',
+ 'mode': 'chat',
+ 'model_config': AppModelConfig(
+ provider='openai',
+ model_id='gpt-3.5-turbo',
+ configs={
+ 'introduction': 'Hi, welcome to our interview. I am the interviewer for this technology company, and I will test your web front-end development skills. Next, I will ask you some technical questions. Please answer them as thoroughly as possible. ',
+ 'prompt_template': "You will play the role of an interviewer for a technology company, examining the user's web front-end development skills and posing 5-10 sharp technical questions.\n\nPlease note:\n- Only ask one question at a time.\n- After the user answers a question, ask the next question directly, without trying to correct any mistakes made by the candidate.\n- If you think the user has not answered correctly for several consecutive questions, ask fewer questions.\n- After asking the last question, you can ask this question: Why did you leave your last job? After the user answers this question, please express your understanding and support.\n",
+ 'prompt_variables': [],
+ 'completion_params': {
+ 'max_token': 300,
+ 'temperature': 0.8,
+ 'top_p': 0.9,
+ 'presence_penalty': 0.1,
+ 'frequency_penalty': 0.1,
+ }
+ },
+ opening_statement='Hi, welcome to our interview. I am the interviewer for this technology company, and I will test your web front-end development skills. Next, I will ask you some technical questions. Please answer them as thoroughly as possible. ',
+ suggested_questions=None,
+ pre_prompt="You will play the role of an interviewer for a technology company, examining the user's web front-end development skills and posing 5-10 sharp technical questions.\n\nPlease note:\n- Only ask one question at a time.\n- After the user answers a question, ask the next question directly, without trying to correct any mistakes made by the candidate.\n- If you think the user has not answered correctly for several consecutive questions, ask fewer questions.\n- After asking the last question, you can ask this question: Why did you leave your last job? After the user answers this question, please express your understanding and support.\n",
+ model=json.dumps({
+ "provider": "openai",
+ "name": "gpt-3.5-turbo",
+ "completion_params": {
+ "max_tokens": 300,
+ "temperature": 0.8,
+ "top_p": 0.9,
+ "presence_penalty": 0.1,
+ "frequency_penalty": 0.1
+ }
+ }),
+ user_input_form=None
+ )
+ }
+ ],
+
+ 'zh-Hans': [
+ {
+ 'name': '翻译助手',
+ 'icon': '',
+ 'icon_background': '',
+ 'description': '一个多语言翻译器,提供多种语言翻译能力,将用户输入的文本翻译成他们需要的语言。',
+ 'mode': 'completion',
+ 'model_config': AppModelConfig(
+ provider='openai',
+ model_id='text-davinci-003',
+ configs={
+ 'prompt_template': "请将以下文本翻译为{{target_language}}:\n",
+ 'prompt_variables': [
+ {
+ "key": "target_language",
+ "name": "目标语言",
+ "description": "翻译的目标语言",
+ "type": "select",
+ "default": "中文",
+ "options": [
+ "中文",
+ "英文",
+ "日语",
+ "法语",
+ "俄语",
+ "德语",
+ "西班牙语",
+ "韩语",
+ "意大利语",
+ ]
+ }
+ ],
+ 'completion_params': {
+ 'max_token': 1000,
+ 'temperature': 0,
+ 'top_p': 0,
+ 'presence_penalty': 0.1,
+ 'frequency_penalty': 0.1,
+ }
+ },
+ opening_statement='',
+ suggested_questions=None,
+ pre_prompt="请将以下文本翻译为{{target_language}}:\n",
+ model=json.dumps({
+ "provider": "openai",
+ "name": "text-davinci-003",
+ "completion_params": {
+ "max_tokens": 1000,
+ "temperature": 0,
+ "top_p": 0,
+ "presence_penalty": 0.1,
+ "frequency_penalty": 0.1
+ }
+ }),
+ user_input_form=json.dumps([
+ {
+ "select": {
+ "label": "目标语言",
+ "variable": "target_language",
+ "description": "翻译的目标语言",
+ "default": "中文",
+ "required": True,
+ 'options': [
+ "中文",
+ "英文",
+ "日语",
+ "法语",
+ "俄语",
+ "德语",
+ "西班牙语",
+ "韩语",
+ "意大利语",
+ ]
+ }
+ }
+ ])
+ )
+ },
+ {
+ 'name': 'AI 前端面试官',
+ 'icon': '',
+ 'icon_background': '',
+ 'description': '一个模拟的前端面试官,通过提问的方式对前端开发的技能水平进行检验。',
+ 'mode': 'chat',
+ 'model_config': AppModelConfig(
+ provider='openai',
+ model_id='gpt-3.5-turbo',
+ configs={
+ 'introduction': '你好,欢迎来参加我们的面试,我是这家科技公司的面试官,我将考察你的 Web 前端开发技能。接下来我会向您提出一些技术问题,请您尽可能详尽地回答。',
+ 'prompt_template': "你将扮演一个科技公司的面试官,考察用户作为候选人的 Web 前端开发水平,提出 5-10 个犀利的技术问题。\n\n请注意:\n- 每次只问一个问题\n- 用户回答问题后请直接问下一个问题,而不要试图纠正候选人的错误;\n- 如果你认为用户连续几次回答的都不对,就少问一点;\n- 问完最后一个问题后,你可以问这样一个问题:上一份工作为什么离职?用户回答该问题后,请表示理解与支持。\n",
+ 'prompt_variables': [],
+ 'completion_params': {
+ 'max_token': 300,
+ 'temperature': 0.8,
+ 'top_p': 0.9,
+ 'presence_penalty': 0.1,
+ 'frequency_penalty': 0.1,
+ }
+ },
+ opening_statement='你好,欢迎来参加我们的面试,我是这家科技公司的面试官,我将考察你的 Web 前端开发技能。接下来我会向您提出一些技术问题,请您尽可能详尽地回答。',
+ suggested_questions=None,
+ pre_prompt="你将扮演一个科技公司的面试官,考察用户作为候选人的 Web 前端开发水平,提出 5-10 个犀利的技术问题。\n\n请注意:\n- 每次只问一个问题\n- 用户回答问题后请直接问下一个问题,而不要试图纠正候选人的错误;\n- 如果你认为用户连续几次回答的都不对,就少问一点;\n- 问完最后一个问题后,你可以问这样一个问题:上一份工作为什么离职?用户回答该问题后,请表示理解与支持。\n",
+ model=json.dumps({
+ "provider": "openai",
+ "name": "gpt-3.5-turbo",
+ "completion_params": {
+ "max_tokens": 300,
+ "temperature": 0.8,
+ "top_p": 0.9,
+ "presence_penalty": 0.1,
+ "frequency_penalty": 0.1
+ }
+ }),
+ user_input_form=None
+ )
+ }
+ ],
+}
diff --git a/api/controllers/__init__.py b/api/controllers/__init__.py
new file mode 100644
index 00000000000..2c0485b18d6
--- /dev/null
+++ b/api/controllers/__init__.py
@@ -0,0 +1,4 @@
+# -*- coding:utf-8 -*-
+
+
+
diff --git a/api/controllers/console/__init__.py b/api/controllers/console/__init__.py
new file mode 100644
index 00000000000..971e4899713
--- /dev/null
+++ b/api/controllers/console/__init__.py
@@ -0,0 +1,20 @@
+from flask import Blueprint
+
+from libs.external_api import ExternalApi
+
+bp = Blueprint('console', __name__, url_prefix='/console/api')
+api = ExternalApi(bp)
+
+# Import app controllers
+from .app import app, site, explore, completion, model_config, statistic, conversation, message
+
+# Import auth controllers
+from .auth import login, oauth
+
+# Import datasets controllers
+from .datasets import datasets, datasets_document, datasets_segments, file, hit_testing
+
+# Import other controllers
+from . import setup, version, apikey
+
+from .workspace import workspace, members, providers, account
diff --git a/api/controllers/console/apikey.py b/api/controllers/console/apikey.py
new file mode 100644
index 00000000000..e576a4d8480
--- /dev/null
+++ b/api/controllers/console/apikey.py
@@ -0,0 +1,175 @@
+from flask_login import login_required, current_user
+import flask_restful
+from flask_restful import Resource, fields, marshal_with
+from werkzeug.exceptions import Forbidden
+
+from extensions.ext_database import db
+from models.model import App, ApiToken
+from models.dataset import Dataset
+
+from . import api
+from .setup import setup_required
+from .wraps import account_initialization_required
+from libs.helper import TimestampField
+
+api_key_fields = {
+ 'id': fields.String,
+ 'type': fields.String,
+ 'token': fields.String,
+ 'last_used_at': TimestampField,
+ 'created_at': TimestampField
+}
+
+api_key_list = {
+ 'data': fields.List(fields.Nested(api_key_fields), attribute="items")
+}
+
+
+def _get_resource(resource_id, tenant_id, resource_model):
+ resource = resource_model.query.filter_by(
+ id=resource_id, tenant_id=tenant_id
+ ).first()
+
+ if resource is None:
+ flask_restful.abort(
+ 404, message=f"{resource_model.__name__} not found.")
+
+ return resource
+
+
+class BaseApiKeyListResource(Resource):
+ method_decorators = [account_initialization_required, login_required, setup_required]
+
+ resource_type = None
+ resource_model = None
+ resource_id_field = None
+ token_prefix = None
+ max_keys = 10
+
+ @marshal_with(api_key_list)
+ def get(self, resource_id):
+ resource_id = str(resource_id)
+ _get_resource(resource_id, current_user.current_tenant_id,
+ self.resource_model)
+ keys = db.session.query(ApiToken). \
+ filter(ApiToken.type == self.resource_type, getattr(ApiToken, self.resource_id_field) == resource_id). \
+ all()
+ return {"items": keys}
+
+ @marshal_with(api_key_fields)
+ def post(self, resource_id):
+ resource_id = str(resource_id)
+ _get_resource(resource_id, current_user.current_tenant_id,
+ self.resource_model)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ current_key_count = db.session.query(ApiToken). \
+ filter(ApiToken.type == self.resource_type, getattr(ApiToken, self.resource_id_field) == resource_id). \
+ count()
+
+ if current_key_count >= self.max_keys:
+ flask_restful.abort(
+ 400,
+ message=f"Cannot create more than {self.max_keys} API keys for this resource type.",
+ code='max_keys_exceeded'
+ )
+
+ key = ApiToken.generate_api_key(self.token_prefix, 24)
+ api_token = ApiToken()
+ setattr(api_token, self.resource_id_field, resource_id)
+ api_token.token = key
+ api_token.type = self.resource_type
+ db.session.add(api_token)
+ db.session.commit()
+ return api_token, 201
+
+
+class BaseApiKeyResource(Resource):
+ method_decorators = [account_initialization_required, login_required, setup_required]
+
+ resource_type = None
+ resource_model = None
+ resource_id_field = None
+
+ def delete(self, resource_id, api_key_id):
+ resource_id = str(resource_id)
+ api_key_id = str(api_key_id)
+ _get_resource(resource_id, current_user.current_tenant_id,
+ self.resource_model)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ key = db.session.query(ApiToken). \
+ filter(getattr(ApiToken, self.resource_id_field) == resource_id, ApiToken.type == self.resource_type, ApiToken.id == api_key_id). \
+ first()
+
+ if key is None:
+ flask_restful.abort(404, message='API key not found')
+
+ db.session.query(ApiToken).filter(ApiToken.id == api_key_id).delete()
+ db.session.commit()
+
+ return {'result': 'success'}, 204
+
+
+class AppApiKeyListResource(BaseApiKeyListResource):
+
+ def after_request(self, resp):
+ resp.headers['Access-Control-Allow-Origin'] = '*'
+ resp.headers['Access-Control-Allow-Credentials'] = 'true'
+ return resp
+
+ resource_type = 'app'
+ resource_model = App
+ resource_id_field = 'app_id'
+ token_prefix = 'app-'
+
+
+class AppApiKeyResource(BaseApiKeyResource):
+
+ def after_request(self, resp):
+ resp.headers['Access-Control-Allow-Origin'] = '*'
+ resp.headers['Access-Control-Allow-Credentials'] = 'true'
+ return resp
+
+ resource_type = 'app'
+ resource_model = App
+ resource_id_field = 'app_id'
+
+
+class DatasetApiKeyListResource(BaseApiKeyListResource):
+
+ def after_request(self, resp):
+ resp.headers['Access-Control-Allow-Origin'] = '*'
+ resp.headers['Access-Control-Allow-Credentials'] = 'true'
+ return resp
+
+ resource_type = 'dataset'
+ resource_model = Dataset
+ resource_id_field = 'dataset_id'
+ token_prefix = 'ds-'
+
+
+class DatasetApiKeyResource(BaseApiKeyResource):
+
+ def after_request(self, resp):
+ resp.headers['Access-Control-Allow-Origin'] = '*'
+ resp.headers['Access-Control-Allow-Credentials'] = 'true'
+ return resp
+ resource_type = 'dataset'
+ resource_model = Dataset
+ resource_id_field = 'dataset_id'
+
+
+api.add_resource(AppApiKeyListResource, '/apps/<uuid:resource_id>/api-keys')
+api.add_resource(AppApiKeyResource,
+ '/apps/<uuid:resource_id>/api-keys/<uuid:api_key_id>')
+api.add_resource(DatasetApiKeyListResource,
+ '/datasets/<uuid:resource_id>/api-keys')
+api.add_resource(DatasetApiKeyResource,
+ '/datasets/<uuid:resource_id>/api-keys/<uuid:api_key_id>')
diff --git a/api/controllers/console/app/__init__.py b/api/controllers/console/app/__init__.py
new file mode 100644
index 00000000000..1f22ab30c65
--- /dev/null
+++ b/api/controllers/console/app/__init__.py
@@ -0,0 +1,22 @@
+from flask_login import current_user
+from werkzeug.exceptions import NotFound
+
+from controllers.console.app.error import AppUnavailableError
+from extensions.ext_database import db
+from models.model import App
+
+
+def _get_app(app_id, mode=None):
+ app = db.session.query(App).filter(
+ App.id == app_id,
+ App.tenant_id == current_user.current_tenant_id,
+ App.status == 'normal'
+ ).first()
+
+ if not app:
+ raise NotFound("App not found")
+
+ if mode and app.mode != mode:
+ raise AppUnavailableError()
+
+ return app
diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.py
new file mode 100644
index 00000000000..fbb28fb4aec
--- /dev/null
+++ b/api/controllers/console/app/app.py
@@ -0,0 +1,518 @@
+# -*- coding:utf-8 -*-
+import json
+from datetime import datetime
+
+import flask
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal_with, abort, inputs
+from werkzeug.exceptions import Unauthorized, Forbidden
+
+from constants.model_template import model_templates, demo_model_templates
+from controllers.console import api
+from controllers.console.app.error import AppNotFoundError, ProviderNotInitializeError, ProviderQuotaExceededError, \
+ CompletionRequestError, ProviderModelCurrentlyNotSupportError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.generator.llm_generator import LLMGenerator
+from core.llm.error import ProviderTokenNotInitError, QuotaExceededError, LLMBadRequestError, LLMAPIConnectionError, \
+ LLMAPIUnavailableError, LLMRateLimitError, LLMAuthorizationError, ModelCurrentlyNotSupportError
+from events.app_event import app_was_created, app_was_deleted
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.model import App, AppModelConfig, Site, InstalledApp
+from services.account_service import TenantService
+from services.app_model_config_service import AppModelConfigService
+
+model_config_fields = {
+ 'opening_statement': fields.String,
+ 'suggested_questions': fields.Raw(attribute='suggested_questions_list'),
+ 'suggested_questions_after_answer': fields.Raw(attribute='suggested_questions_after_answer_dict'),
+ 'more_like_this': fields.Raw(attribute='more_like_this_dict'),
+ 'model': fields.Raw(attribute='model_dict'),
+ 'user_input_form': fields.Raw(attribute='user_input_form_list'),
+ 'pre_prompt': fields.String,
+ 'agent_mode': fields.Raw(attribute='agent_mode_dict'),
+}
+
+app_detail_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'mode': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'enable_site': fields.Boolean,
+ 'enable_api': fields.Boolean,
+ 'api_rpm': fields.Integer,
+ 'api_rph': fields.Integer,
+ 'is_demo': fields.Boolean,
+ 'model_config': fields.Nested(model_config_fields, attribute='app_model_config'),
+ 'created_at': TimestampField
+}
+
+
+def _get_app(app_id, tenant_id):
+ app = db.session.query(App).filter(App.id == app_id, App.tenant_id == tenant_id).first()
+ if not app:
+ raise AppNotFoundError
+ return app
+
+
+class AppListApi(Resource):
+ prompt_config_fields = {
+ 'prompt_template': fields.String,
+ }
+
+ model_config_partial_fields = {
+ 'model': fields.Raw(attribute='model_dict'),
+ 'pre_prompt': fields.String,
+ }
+
+ app_partial_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'mode': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'enable_site': fields.Boolean,
+ 'enable_api': fields.Boolean,
+ 'is_demo': fields.Boolean,
+ 'model_config': fields.Nested(model_config_partial_fields, attribute='app_model_config'),
+ 'created_at': TimestampField
+ }
+
+ app_pagination_fields = {
+ 'page': fields.Integer,
+ 'limit': fields.Integer(attribute='per_page'),
+ 'total': fields.Integer,
+ 'has_more': fields.Boolean(attribute='has_next'),
+ 'data': fields.List(fields.Nested(app_partial_fields), attribute='items')
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_pagination_fields)
+ def get(self):
+ """Get app list"""
+ parser = reqparse.RequestParser()
+ parser.add_argument('page', type=inputs.int_range(1, 99999), required=False, default=1, location='args')
+ parser.add_argument('limit', type=inputs.int_range(1, 100), required=False, default=20, location='args')
+ args = parser.parse_args()
+
+ app_models = db.paginate(
+ db.select(App).where(App.tenant_id == current_user.current_tenant_id).order_by(App.created_at.desc()),
+ page=args['page'],
+ per_page=args['limit'],
+ error_out=False)
+
+ return app_models
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self):
+ """Create app"""
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, location='json')
+ parser.add_argument('mode', type=str, choices=['completion', 'chat'], location='json')
+ parser.add_argument('icon', type=str, location='json')
+ parser.add_argument('icon_background', type=str, location='json')
+ parser.add_argument('model_config', type=dict, location='json')
+ args = parser.parse_args()
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ if args['model_config'] is not None:
+ # validate config
+ model_configuration = AppModelConfigService.validate_configuration(
+ account=current_user,
+ config=args['model_config'],
+ mode=args['mode']
+ )
+
+ app = App(
+ enable_site=True,
+ enable_api=True,
+ is_demo=False,
+ api_rpm=0,
+ api_rph=0,
+ status='normal'
+ )
+
+ app_model_config = AppModelConfig(
+ provider="",
+ model_id="",
+ configs={},
+ opening_statement=model_configuration['opening_statement'],
+ suggested_questions=json.dumps(model_configuration['suggested_questions']),
+ suggested_questions_after_answer=json.dumps(model_configuration['suggested_questions_after_answer']),
+ more_like_this=json.dumps(model_configuration['more_like_this']),
+ model=json.dumps(model_configuration['model']),
+ user_input_form=json.dumps(model_configuration['user_input_form']),
+ pre_prompt=model_configuration['pre_prompt'],
+ agent_mode=json.dumps(model_configuration['agent_mode']),
+ )
+ else:
+ if 'mode' not in args or args['mode'] is None:
+ abort(400, message="mode is required")
+
+ model_config_template = model_templates[args['mode'] + '_default']
+
+ app = App(**model_config_template['app'])
+ app_model_config = AppModelConfig(**model_config_template['model_config'])
+
+ app.name = args['name']
+ app.mode = args['mode']
+ app.icon = args['icon']
+ app.icon_background = args['icon_background']
+ app.tenant_id = current_user.current_tenant_id
+
+ db.session.add(app)
+ db.session.flush()
+
+ app_model_config.app_id = app.id
+ db.session.add(app_model_config)
+ db.session.flush()
+
+ app.app_model_config_id = app_model_config.id
+
+ account = current_user
+
+ site = Site(
+ app_id=app.id,
+ title=app.name,
+ default_language=account.interface_language,
+ customize_token_strategy='not_allow',
+ code=Site.generate_code(16)
+ )
+
+ db.session.add(site)
+ db.session.commit()
+
+ app_was_created.send(app)
+
+ return app, 201
+
+
+class AppTemplateApi(Resource):
+ template_fields = {
+ 'name': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'description': fields.String,
+ 'mode': fields.String,
+ 'model_config': fields.Nested(model_config_fields),
+ }
+
+ template_list_fields = {
+ 'data': fields.List(fields.Nested(template_fields)),
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(template_list_fields)
+ def get(self):
+ """Get app demo templates"""
+ account = current_user
+ interface_language = account.interface_language
+
+ return {'data': demo_model_templates.get(interface_language)}
+
+
+class AppApi(Resource):
+ site_fields = {
+ 'access_token': fields.String(attribute='code'),
+ 'code': fields.String,
+ 'title': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'description': fields.String,
+ 'default_language': fields.String,
+ 'customize_domain': fields.String,
+ 'copyright': fields.String,
+ 'privacy_policy': fields.String,
+ 'customize_token_strategy': fields.String,
+ 'prompt_public': fields.Boolean,
+ 'app_base_url': fields.String,
+ }
+
+ app_detail_fields_with_site = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'mode': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'enable_site': fields.Boolean,
+ 'enable_api': fields.Boolean,
+ 'api_rpm': fields.Integer,
+ 'api_rph': fields.Integer,
+ 'is_demo': fields.Boolean,
+ 'model_config': fields.Nested(model_config_fields, attribute='app_model_config'),
+ 'site': fields.Nested(site_fields),
+ 'api_base_url': fields.String,
+ 'created_at': TimestampField
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields_with_site)
+ def get(self, app_id):
+ """Get app detail"""
+ app_id = str(app_id)
+ app = _get_app(app_id, current_user.current_tenant_id)
+
+ return app
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def delete(self, app_id):
+ """Delete app"""
+ app_id = str(app_id)
+ app = _get_app(app_id, current_user.current_tenant_id)
+
+ db.session.delete(app)
+ db.session.commit()
+
+ # todo delete related data??
+ # model_config, site, api_token, conversation, message, message_feedback, message_annotation
+
+ app_was_deleted.send(app)
+
+ return {'result': 'success'}, 204
+
+
+class AppNameApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ app = db.get_or_404(App, str(app_id))
+ if app.tenant_id != flask.session.get('tenant_id'):
+ raise Unauthorized()
+
+ app.name = args.get('name')
+ app.updated_at = datetime.utcnow()
+ db.session.commit()
+ return app
+
+
+class AppIconApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('icon', type=str, location='json')
+ parser.add_argument('icon_background', type=str, location='json')
+ args = parser.parse_args()
+
+ app = db.get_or_404(App, str(app_id))
+ if app.tenant_id != flask.session.get('tenant_id'):
+ raise Unauthorized()
+
+ app.icon = args.get('icon')
+ app.icon_background = args.get('icon_background')
+ app.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ return app
+
+
+class AppSiteStatus(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+ parser = reqparse.RequestParser()
+ parser.add_argument('enable_site', type=bool, required=True, location='json')
+ args = parser.parse_args()
+ app_id = str(app_id)
+ app = db.session.query(App).filter(App.id == app_id, App.tenant_id == current_user.current_tenant_id).first()
+ if not app:
+ raise AppNotFoundError
+
+ if args.get('enable_site') == app.enable_site:
+ return app
+
+ app.enable_site = args.get('enable_site')
+ app.updated_at = datetime.utcnow()
+ db.session.commit()
+ return app
+
+
+class AppApiStatus(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+ parser = reqparse.RequestParser()
+ parser.add_argument('enable_api', type=bool, required=True, location='json')
+ args = parser.parse_args()
+
+ app_id = str(app_id)
+ app = _get_app(app_id, current_user.current_tenant_id)
+
+ if args.get('enable_api') == app.enable_api:
+ return app
+
+ app.enable_api = args.get('enable_api')
+ app.updated_at = datetime.utcnow()
+ db.session.commit()
+ return app
+
+
+class AppRateLimit(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+ parser = reqparse.RequestParser()
+ parser.add_argument('api_rpm', type=inputs.natural, required=False, location='json')
+ parser.add_argument('api_rph', type=inputs.natural, required=False, location='json')
+ args = parser.parse_args()
+
+ app_id = str(app_id)
+ app = _get_app(app_id, current_user.current_tenant_id)
+
+ if args.get('api_rpm'):
+ app.api_rpm = args.get('api_rpm')
+ if args.get('api_rph'):
+ app.api_rph = args.get('api_rph')
+ app.updated_at = datetime.utcnow()
+ db.session.commit()
+ return app
+
+
+class AppCopy(Resource):
+ @staticmethod
+ def create_app_copy(app):
+ copy_app = App(
+ name=app.name + ' copy',
+ icon=app.icon,
+ icon_background=app.icon_background,
+ tenant_id=app.tenant_id,
+ mode=app.mode,
+ app_model_config_id=app.app_model_config_id,
+ enable_site=app.enable_site,
+ enable_api=app.enable_api,
+ api_rpm=app.api_rpm,
+ api_rph=app.api_rph
+ )
+ return copy_app
+
+ @staticmethod
+ def create_app_model_config_copy(app_config, copy_app_id):
+ copy_app_model_config = AppModelConfig(
+ app_id=copy_app_id,
+ provider=app_config.provider,
+ model_id=app_config.model_id,
+ configs=app_config.configs,
+ opening_statement=app_config.opening_statement,
+ suggested_questions=app_config.suggested_questions,
+ suggested_questions_after_answer=app_config.suggested_questions_after_answer,
+ more_like_this=app_config.more_like_this,
+ model=app_config.model,
+ user_input_form=app_config.user_input_form,
+ pre_prompt=app_config.pre_prompt,
+ agent_mode=app_config.agent_mode
+ )
+ return copy_app_model_config
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_detail_fields)
+ def post(self, app_id):
+ app_id = str(app_id)
+ app = _get_app(app_id, current_user.current_tenant_id)
+
+ copy_app = self.create_app_copy(app)
+ db.session.add(copy_app)
+
+ app_config = db.session.query(AppModelConfig). \
+ filter(AppModelConfig.app_id == app_id). \
+ one_or_none()
+
+ if app_config:
+ copy_app_model_config = self.create_app_model_config_copy(app_config, copy_app.id)
+ db.session.add(copy_app_model_config)
+ db.session.commit()
+ copy_app.app_model_config_id = copy_app_model_config.id
+ db.session.commit()
+
+ return copy_app, 201
+
+
+class AppExport(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ # todo
+ pass
+
+
+class IntroductionGenerateApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('prompt_template', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ account = current_user
+
+ try:
+ answer = LLMGenerator.generate_introduction(
+ account.current_tenant_id,
+ args['prompt_template']
+ )
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+
+ return {'introduction': answer}
+
+
+api.add_resource(AppListApi, '/apps')
+api.add_resource(AppTemplateApi, '/app-templates')
+api.add_resource(AppApi, '/apps/<uuid:app_id>')
+api.add_resource(AppCopy, '/apps/<uuid:app_id>/copy')
+api.add_resource(AppNameApi, '/apps/<uuid:app_id>/name')
+api.add_resource(AppSiteStatus, '/apps/<uuid:app_id>/site-enable')
+api.add_resource(AppApiStatus, '/apps/<uuid:app_id>/api-enable')
+api.add_resource(AppRateLimit, '/apps/<uuid:app_id>/rate-limit')
+api.add_resource(IntroductionGenerateApi, '/introduction-generate')
diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.py
new file mode 100644
index 00000000000..552271a9ecb
--- /dev/null
+++ b/api/controllers/console/app/completion.py
@@ -0,0 +1,206 @@
+# -*- coding:utf-8 -*-
+import json
+import logging
+from typing import Generator, Union
+
+import flask_login
+from flask import Response, stream_with_context
+from flask_login import login_required
+from werkzeug.exceptions import InternalServerError, NotFound
+
+import services
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.app.error import ConversationCompletedError, AppUnavailableError, \
+ ProviderNotInitializeError, CompletionRequestError, ProviderQuotaExceededError, \
+ ProviderModelCurrentlyNotSupportError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.conversation_message_task import PubHandler
+from core.llm.error import LLMBadRequestError, LLMAPIUnavailableError, LLMAuthorizationError, LLMAPIConnectionError, \
+ LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError, ModelCurrentlyNotSupportError
+from libs.helper import uuid_value
+from flask_restful import Resource, reqparse
+
+from services.completion_service import CompletionService
+
+
+# define completion message api for user
+class CompletionMessageApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app_model = _get_app(app_id, 'completion')
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, location='json')
+ parser.add_argument('model_config', type=dict, required=True, location='json')
+ args = parser.parse_args()
+
+ account = flask_login.current_user
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=account,
+ args=args,
+ from_source='console',
+ streaming=True,
+ is_model_config_override=True
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+class CompletionMessageStopApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id, task_id):
+ app_id = str(app_id)
+
+ # get app info
+ _get_app(app_id, 'completion')
+
+ account = flask_login.current_user
+
+ PubHandler.stop(account, task_id)
+
+ return {'result': 'success'}, 200
+
+
+class ChatMessageApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app_model = _get_app(app_id, 'chat')
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, required=True, location='json')
+ parser.add_argument('model_config', type=dict, required=True, location='json')
+ parser.add_argument('conversation_id', type=uuid_value, location='json')
+ args = parser.parse_args()
+
+ account = flask_login.current_user
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=account,
+ args=args,
+ from_source='console',
+ streaming=True,
+ is_model_config_override=True
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+def compact_response(response: Union[dict | Generator]) -> Response:
+ if isinstance(response, dict):
+ return Response(response=json.dumps(response), status=200, mimetype='application/json')
+ else:
+ def generate() -> Generator:
+ try:
+ for chunk in response:
+ yield chunk
+ except services.errors.conversation.ConversationNotExistsError:
+ yield "data: " + json.dumps(api.handle_error(NotFound("Conversation Not Exists.")).get_json()) + "\n\n"
+ except services.errors.conversation.ConversationCompletedError:
+ yield "data: " + json.dumps(api.handle_error(ConversationCompletedError()).get_json()) + "\n\n"
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ yield "data: " + json.dumps(api.handle_error(AppUnavailableError()).get_json()) + "\n\n"
+ except ProviderTokenNotInitError:
+ yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError()).get_json()) + "\n\n"
+ except QuotaExceededError:
+ yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
+ except ModelCurrentlyNotSupportError:
+ yield "data: " + json.dumps(api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
+ except ValueError as e:
+ yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
+ except Exception:
+ logging.exception("internal server error.")
+ yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
+
+ return Response(stream_with_context(generate()), status=200,
+ mimetype='text/event-stream')
+
+
+class ChatMessageStopApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id, task_id):
+ app_id = str(app_id)
+
+ # get app info
+ _get_app(app_id, 'chat')
+
+ account = flask_login.current_user
+
+ PubHandler.stop(account, task_id)
+
+ return {'result': 'success'}, 200
+
+
+api.add_resource(CompletionMessageApi, '/apps/<uuid:app_id>/completion-messages')
+api.add_resource(CompletionMessageStopApi, '/apps/<uuid:app_id>/completion-messages/<string:task_id>/stop')
+api.add_resource(ChatMessageApi, '/apps/<uuid:app_id>/chat-messages')
+api.add_resource(ChatMessageStopApi, '/apps/<uuid:app_id>/chat-messages/<string:task_id>/stop')
diff --git a/api/controllers/console/app/conversation.py b/api/controllers/console/app/conversation.py
new file mode 100644
index 00000000000..62752deaacb
--- /dev/null
+++ b/api/controllers/console/app/conversation.py
@@ -0,0 +1,384 @@
+from datetime import datetime
+
+import pytz
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal_with
+from flask_restful.inputs import int_range
+from sqlalchemy import or_, func
+from sqlalchemy.orm import joinedload
+from werkzeug.exceptions import NotFound
+
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from libs.helper import TimestampField, datetime_string, uuid_value
+from extensions.ext_database import db
+from models.model import Message, MessageAnnotation, Conversation
+
+account_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'email': fields.String
+}
+
+feedback_fields = {
+ 'rating': fields.String,
+ 'content': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account': fields.Nested(account_fields, allow_null=True),
+}
+
+annotation_fields = {
+ 'content': fields.String,
+ 'account': fields.Nested(account_fields, allow_null=True),
+ 'created_at': TimestampField
+}
+
+message_detail_fields = {
+ 'id': fields.String,
+ 'conversation_id': fields.String,
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'message': fields.Raw,
+ 'message_tokens': fields.Integer,
+ 'answer': fields.String,
+ 'answer_tokens': fields.Integer,
+ 'provider_response_latency': fields.Integer,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'feedbacks': fields.List(fields.Nested(feedback_fields)),
+ 'annotation': fields.Nested(annotation_fields, allow_null=True),
+ 'created_at': TimestampField
+}
+
+feedback_stat_fields = {
+ 'like': fields.Integer,
+ 'dislike': fields.Integer
+}
+
+model_config_fields = {
+ 'opening_statement': fields.String,
+ 'suggested_questions': fields.Raw,
+ 'model': fields.Raw,
+ 'user_input_form': fields.Raw,
+ 'pre_prompt': fields.String,
+ 'agent_mode': fields.Raw,
+}
+
+
+class CompletionConversationApi(Resource):
+ class MessageTextField(fields.Raw):
+ def format(self, value):
+ return value[0]['text'] if value else ''
+
+ simple_configs_fields = {
+ 'prompt_template': fields.String,
+ }
+
+ simple_model_config_fields = {
+ 'model': fields.Raw(attribute='model_dict'),
+ 'pre_prompt': fields.String,
+ }
+
+ simple_message_detail_fields = {
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'message': MessageTextField,
+ 'answer': fields.String,
+ }
+
+ conversation_fields = {
+ 'id': fields.String,
+ 'status': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'read_at': TimestampField,
+ 'created_at': TimestampField,
+ 'annotation': fields.Nested(annotation_fields, allow_null=True),
+ 'model_config': fields.Nested(simple_model_config_fields),
+ 'user_feedback_stats': fields.Nested(feedback_stat_fields),
+ 'admin_feedback_stats': fields.Nested(feedback_stat_fields),
+ 'message': fields.Nested(simple_message_detail_fields, attribute='first_message')
+ }
+
+ conversation_pagination_fields = {
+ 'page': fields.Integer,
+ 'limit': fields.Integer(attribute='per_page'),
+ 'total': fields.Integer,
+ 'has_more': fields.Boolean(attribute='has_next'),
+ 'data': fields.List(fields.Nested(conversation_fields), attribute='items')
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(conversation_pagination_fields)
+ def get(self, app_id):
+ app_id = str(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('keyword', type=str, location='args')
+ parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('annotation_status', type=str,
+ choices=['annotated', 'not_annotated', 'all'], default='all', location='args')
+ parser.add_argument('page', type=int_range(1, 99999), default=1, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), default=20, location='args')
+ args = parser.parse_args()
+
+ # get app info
+ app = _get_app(app_id, 'completion')
+
+ query = db.select(Conversation).where(Conversation.app_id == app.id, Conversation.mode == 'completion')
+
+ if args['keyword']:
+ query = query.join(
+ Message, Message.conversation_id == Conversation.id
+ ).filter(
+ or_(
+ Message.query.ilike('%{}%'.format(args['keyword'])),
+ Message.answer.ilike('%{}%'.format(args['keyword']))
+ )
+ )
+
+ account = current_user
+ timezone = pytz.timezone(account.timezone)
+ utc_timezone = pytz.utc
+
+ if args['start']:
+ start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
+ start_datetime = start_datetime.replace(second=0)
+
+ start_datetime_timezone = timezone.localize(start_datetime)
+ start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
+
+ query = query.where(Conversation.created_at >= start_datetime_utc)
+
+ if args['end']:
+ end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
+ end_datetime = end_datetime.replace(second=0)
+
+ end_datetime_timezone = timezone.localize(end_datetime)
+ end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
+
+ query = query.where(Conversation.created_at < end_datetime_utc)
+
+ if args['annotation_status'] == "annotated":
+ query = query.options(joinedload(Conversation.message_annotations)).join(
+ MessageAnnotation, MessageAnnotation.conversation_id == Conversation.id
+ )
+ elif args['annotation_status'] == "not_annotated":
+ query = query.outerjoin(
+ MessageAnnotation, MessageAnnotation.conversation_id == Conversation.id
+ ).group_by(Conversation.id).having(func.count(MessageAnnotation.id) == 0)
+
+ query = query.order_by(Conversation.created_at.desc())
+
+ conversations = db.paginate(
+ query,
+ page=args['page'],
+ per_page=args['limit'],
+ error_out=False
+ )
+
+ return conversations
+
+
+class CompletionConversationDetailApi(Resource):
+ conversation_detail_fields = {
+ 'id': fields.String,
+ 'status': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'created_at': TimestampField,
+ 'model_config': fields.Nested(model_config_fields),
+ 'message': fields.Nested(message_detail_fields, attribute='first_message'),
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(conversation_detail_fields)
+ def get(self, app_id, conversation_id):
+ app_id = str(app_id)
+ conversation_id = str(conversation_id)
+
+ return _get_conversation(app_id, conversation_id, 'completion')
+
+
+class ChatConversationApi(Resource):
+ simple_configs_fields = {
+ 'prompt_template': fields.String,
+ }
+
+ simple_model_config_fields = {
+ 'model': fields.Raw(attribute='model_dict'),
+ 'pre_prompt': fields.String,
+ }
+
+ conversation_fields = {
+ 'id': fields.String,
+ 'status': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'summary': fields.String(attribute='summary_or_query'),
+ 'read_at': TimestampField,
+ 'created_at': TimestampField,
+ 'annotated': fields.Boolean,
+ 'model_config': fields.Nested(simple_model_config_fields),
+ 'message_count': fields.Integer,
+ 'user_feedback_stats': fields.Nested(feedback_stat_fields),
+ 'admin_feedback_stats': fields.Nested(feedback_stat_fields)
+ }
+
+ conversation_pagination_fields = {
+ 'page': fields.Integer,
+ 'limit': fields.Integer(attribute='per_page'),
+ 'total': fields.Integer,
+ 'has_more': fields.Boolean(attribute='has_next'),
+ 'data': fields.List(fields.Nested(conversation_fields), attribute='items')
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(conversation_pagination_fields)
+ def get(self, app_id):
+ app_id = str(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('keyword', type=str, location='args')
+ parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('annotation_status', type=str,
+ choices=['annotated', 'not_annotated', 'all'], default='all', location='args')
+ parser.add_argument('message_count_gte', type=int_range(1, 99999), required=False, location='args')
+ parser.add_argument('page', type=int_range(1, 99999), required=False, default=1, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ args = parser.parse_args()
+
+ # get app info
+ app = _get_app(app_id, 'chat')
+
+ query = db.select(Conversation).where(Conversation.app_id == app.id, Conversation.mode == 'chat')
+
+ if args['keyword']:
+ query = query.join(
+ Message, Message.conversation_id == Conversation.id
+ ).filter(
+ or_(
+ Message.query.ilike('%{}%'.format(args['keyword'])),
+ Message.answer.ilike('%{}%'.format(args['keyword'])),
+ Conversation.name.ilike('%{}%'.format(args['keyword'])),
+ Conversation.introduction.ilike('%{}%'.format(args['keyword'])),
+ ),
+
+ )
+
+ account = current_user
+ timezone = pytz.timezone(account.timezone)
+ utc_timezone = pytz.utc
+
+ if args['start']:
+ start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
+ start_datetime = start_datetime.replace(second=0)
+
+ start_datetime_timezone = timezone.localize(start_datetime)
+ start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
+
+ query = query.where(Conversation.created_at >= start_datetime_utc)
+
+ if args['end']:
+ end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
+ end_datetime = end_datetime.replace(second=0)
+
+ end_datetime_timezone = timezone.localize(end_datetime)
+ end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
+
+ query = query.where(Conversation.created_at < end_datetime_utc)
+
+ if args['annotation_status'] == "annotated":
+ query = query.options(joinedload(Conversation.message_annotations)).join(
+ MessageAnnotation, MessageAnnotation.conversation_id == Conversation.id
+ )
+ elif args['annotation_status'] == "not_annotated":
+ query = query.outerjoin(
+ MessageAnnotation, MessageAnnotation.conversation_id == Conversation.id
+ ).group_by(Conversation.id).having(func.count(MessageAnnotation.id) == 0)
+
+ if args['message_count_gte'] and args['message_count_gte'] >= 1:
+ query = (
+ query.options(joinedload(Conversation.messages))
+ .join(Message, Message.conversation_id == Conversation.id)
+ .group_by(Conversation.id)
+ .having(func.count(Message.id) >= args['message_count_gte'])
+ )
+
+ query = query.order_by(Conversation.created_at.desc())
+
+ conversations = db.paginate(
+ query,
+ page=args['page'],
+ per_page=args['limit'],
+ error_out=False
+ )
+
+ return conversations
+
+
+class ChatConversationDetailApi(Resource):
+ conversation_detail_fields = {
+ 'id': fields.String,
+ 'status': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'created_at': TimestampField,
+ 'annotated': fields.Boolean,
+ 'model_config': fields.Nested(model_config_fields),
+ 'message_count': fields.Integer,
+ 'user_feedback_stats': fields.Nested(feedback_stat_fields),
+ 'admin_feedback_stats': fields.Nested(feedback_stat_fields)
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(conversation_detail_fields)
+ def get(self, app_id, conversation_id):
+ app_id = str(app_id)
+ conversation_id = str(conversation_id)
+
+ return _get_conversation(app_id, conversation_id, 'chat')
+
+
+
+
+api.add_resource(CompletionConversationApi, '/apps/<uuid:app_id>/completion-conversations')
+api.add_resource(CompletionConversationDetailApi, '/apps/<uuid:app_id>/completion-conversations/<uuid:conversation_id>')
+api.add_resource(ChatConversationApi, '/apps/<uuid:app_id>/chat-conversations')
+api.add_resource(ChatConversationDetailApi, '/apps/<uuid:app_id>/chat-conversations/<uuid:conversation_id>')
+
+
+def _get_conversation(app_id, conversation_id, mode):
+ # get app info
+ app = _get_app(app_id, mode)
+
+ conversation = db.session.query(Conversation) \
+ .filter(Conversation.id == conversation_id, Conversation.app_id == app.id).first()
+
+ if not conversation:
+ raise NotFound("Conversation Not Exists.")
+
+ if not conversation.read_at:
+ conversation.read_at = datetime.utcnow()
+ conversation.read_account_id = current_user.id
+ db.session.commit()
+
+ return conversation
diff --git a/api/controllers/console/app/error.py b/api/controllers/console/app/error.py
new file mode 100644
index 00000000000..c19f054be41
--- /dev/null
+++ b/api/controllers/console/app/error.py
@@ -0,0 +1,49 @@
+from libs.exception import BaseHTTPException
+
+
+class AppNotFoundError(BaseHTTPException):
+ error_code = 'app_not_found'
+ description = "App not found."
+ code = 404
+
+
+class ProviderNotInitializeError(BaseHTTPException):
+ error_code = 'provider_not_initialize'
+ description = "Provider Token not initialize."
+ code = 400
+
+
+class ProviderQuotaExceededError(BaseHTTPException):
+ error_code = 'provider_quota_exceeded'
+ description = "Provider quota exceeded."
+ code = 400
+
+
+class ProviderModelCurrentlyNotSupportError(BaseHTTPException):
+ error_code = 'model_currently_not_support'
+ description = "GPT-4 currently not support."
+ code = 400
+
+
+class ConversationCompletedError(BaseHTTPException):
+ error_code = 'conversation_completed'
+ description = "Conversation was completed."
+ code = 400
+
+
+class AppUnavailableError(BaseHTTPException):
+ error_code = 'app_unavailable'
+ description = "App unavailable."
+ code = 400
+
+
+class CompletionRequestError(BaseHTTPException):
+ error_code = 'completion_request_error'
+ description = "Completion request failed."
+ code = 400
+
+
+class AppMoreLikeThisDisabledError(BaseHTTPException):
+ error_code = 'app_more_like_this_disabled'
+ description = "More like this disabled."
+ code = 403
diff --git a/api/controllers/console/app/explore.py b/api/controllers/console/app/explore.py
new file mode 100644
index 00000000000..eeec2ddc241
--- /dev/null
+++ b/api/controllers/console/app/explore.py
@@ -0,0 +1,209 @@
+# -*- coding:utf-8 -*-
+from datetime import datetime
+
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal_with, abort, inputs
+from sqlalchemy import and_
+
+from controllers.console import api
+from extensions.ext_database import db
+from models.model import Tenant, App, InstalledApp, RecommendedApp
+from services.account_service import TenantService
+
+app_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'mode': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String
+}
+
+installed_app_fields = {
+ 'id': fields.String,
+ 'app': fields.Nested(app_fields, attribute='app'),
+ 'app_owner_tenant_id': fields.String,
+ 'is_pinned': fields.Boolean,
+ 'last_used_at': fields.DateTime,
+ 'editable': fields.Boolean
+}
+
+installed_app_list_fields = {
+ 'installed_apps': fields.List(fields.Nested(installed_app_fields))
+}
+
+recommended_app_fields = {
+ 'app': fields.Nested(app_fields, attribute='app'),
+ 'app_id': fields.String,
+ 'description': fields.String(attribute='description'),
+ 'copyright': fields.String,
+ 'privacy_policy': fields.String,
+ 'category': fields.String,
+ 'position': fields.Integer,
+ 'is_listed': fields.Boolean,
+ 'install_count': fields.Integer,
+ 'installed': fields.Boolean,
+ 'editable': fields.Boolean
+}
+
+recommended_app_list_fields = {
+ 'recommended_apps': fields.List(fields.Nested(recommended_app_fields)),
+ 'categories': fields.List(fields.String)
+}
+
+
+class InstalledAppsListResource(Resource):
+ @login_required
+ @marshal_with(installed_app_list_fields)
+ def get(self):
+ current_tenant_id = Tenant.query.first().id
+ installed_apps = db.session.query(InstalledApp).filter(
+ InstalledApp.tenant_id == current_tenant_id
+ ).all()
+
+ current_user.role = TenantService.get_user_role(current_user, current_user.current_tenant)
+ installed_apps = [
+ {
+ **installed_app,
+ "editable": current_user.role in ["owner", "admin"],
+ }
+ for installed_app in installed_apps
+ ]
+ installed_apps.sort(key=lambda app: (-app.is_pinned, app.last_used_at))
+
+ return {'installed_apps': installed_apps}
+
+ @login_required
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('app_id', type=str, required=True, help='Invalid app_id')
+ args = parser.parse_args()
+
+ current_tenant_id = Tenant.query.first().id
+ app = App.query.get(args['app_id'])
+ if app is None:
+ abort(404, message='App not found')
+ recommended_app = RecommendedApp.query.filter(RecommendedApp.app_id == args['app_id']).first()
+ if recommended_app is None:
+ abort(404, message='App not found')
+ if not app.is_public:
+ abort(403, message="You can't install a non-public app")
+
+ installed_app = InstalledApp.query.filter(and_(
+ InstalledApp.app_id == args['app_id'],
+ InstalledApp.tenant_id == current_tenant_id
+ )).first()
+
+ if installed_app is None:
+ # todo: position
+ recommended_app.install_count += 1
+
+ new_installed_app = InstalledApp(
+ app_id=args['app_id'],
+ tenant_id=current_tenant_id,
+ is_pinned=False,
+ last_used_at=datetime.utcnow()
+ )
+ db.session.add(new_installed_app)
+ db.session.commit()
+
+ return {'message': 'App installed successfully'}
+
+
+class InstalledAppResource(Resource):
+
+ @login_required
+ def delete(self, installed_app_id):
+
+ installed_app = InstalledApp.query.filter(and_(
+ InstalledApp.id == str(installed_app_id),
+ InstalledApp.tenant_id == current_user.current_tenant_id
+ )).first()
+
+ if installed_app is None:
+ abort(404, message='App not found')
+
+ if installed_app.app_owner_tenant_id == current_user.current_tenant_id:
+ abort(400, message="You can't uninstall an app owned by the current tenant")
+
+ db.session.delete(installed_app)
+ db.session.commit()
+
+ return {'result': 'success', 'message': 'App uninstalled successfully'}
+
+ @login_required
+ def patch(self, installed_app_id):
+ parser = reqparse.RequestParser()
+ parser.add_argument('is_pinned', type=inputs.boolean)
+ args = parser.parse_args()
+
+ current_tenant_id = Tenant.query.first().id
+ installed_app = InstalledApp.query.filter(and_(
+ InstalledApp.id == str(installed_app_id),
+ InstalledApp.tenant_id == current_tenant_id
+ )).first()
+
+ if installed_app is None:
+ abort(404, message='Installed app not found')
+
+ commit_args = False
+ if 'is_pinned' in args:
+ installed_app.is_pinned = args['is_pinned']
+ commit_args = True
+
+ if commit_args:
+ db.session.commit()
+
+ return {'result': 'success', 'message': 'App info updated successfully'}
+
+
+class RecommendedAppsResource(Resource):
+ @login_required
+ @marshal_with(recommended_app_list_fields)
+ def get(self):
+ recommended_apps = db.session.query(RecommendedApp).filter(
+ RecommendedApp.is_listed == True
+ ).all()
+
+ categories = set()
+ current_user.role = TenantService.get_user_role(current_user, current_user.current_tenant)
+ recommended_apps_result = []
+ for recommended_app in recommended_apps:
+ installed = db.session.query(InstalledApp).filter(
+ and_(
+ InstalledApp.app_id == recommended_app.app_id,
+ InstalledApp.tenant_id == current_user.current_tenant_id
+ )
+ ).first() is not None
+
+ language_prefix = current_user.interface_language.split('-')[0]
+ desc = None
+ if recommended_app.description:
+ if language_prefix in recommended_app.description:
+ desc = recommended_app.description[language_prefix]
+ elif 'en' in recommended_app.description:
+ desc = recommended_app.description['en']
+
+ recommended_app_result = {
+ 'id': recommended_app.id,
+ 'app': recommended_app.app,
+ 'app_id': recommended_app.app_id,
+ 'description': desc,
+ 'copyright': recommended_app.copyright,
+ 'privacy_policy': recommended_app.privacy_policy,
+ 'category': recommended_app.category,
+ 'position': recommended_app.position,
+ 'is_listed': recommended_app.is_listed,
+ 'install_count': recommended_app.install_count,
+ 'installed': installed,
+ 'editable': current_user.role in ['owner', 'admin'],
+ }
+ recommended_apps_result.append(recommended_app_result)
+
+ categories.add(recommended_app.category) # add category to categories
+
+ return {'recommended_apps': recommended_apps_result, 'categories': list(categories)}
+
+
+api.add_resource(InstalledAppsListResource, '/installed-apps')
+api.add_resource(InstalledAppResource, '/installed-apps/<uuid:installed_app_id>')
+api.add_resource(RecommendedAppsResource, '/explore/apps')
diff --git a/api/controllers/console/app/message.py b/api/controllers/console/app/message.py
new file mode 100644
index 00000000000..27698d965c0
--- /dev/null
+++ b/api/controllers/console/app/message.py
@@ -0,0 +1,361 @@
+import json
+import logging
+from typing import Union, Generator
+
+from flask import Response, stream_with_context
+from flask_login import current_user, login_required
+from flask_restful import Resource, reqparse, marshal_with, fields
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import InternalServerError, NotFound
+
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.app.error import CompletionRequestError, ProviderNotInitializeError, \
+ AppMoreLikeThisDisabledError, ProviderQuotaExceededError, ProviderModelCurrentlyNotSupportError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.llm.error import LLMRateLimitError, LLMBadRequestError, LLMAuthorizationError, LLMAPIConnectionError, \
+ ProviderTokenNotInitError, LLMAPIUnavailableError, QuotaExceededError, ModelCurrentlyNotSupportError
+from libs.helper import uuid_value, TimestampField
+from libs.infinite_scroll_pagination import InfiniteScrollPagination
+from extensions.ext_database import db
+from models.model import MessageAnnotation, Conversation, Message, MessageFeedback
+from services.completion_service import CompletionService
+from services.errors.app import MoreLikeThisDisabledError
+from services.errors.conversation import ConversationNotExistsError
+from services.errors.message import MessageNotExistsError
+from services.message_service import MessageService
+
+
+class ChatMessageApi(Resource):
+ account_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'email': fields.String
+ }
+
+ feedback_fields = {
+ 'rating': fields.String,
+ 'content': fields.String,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account': fields.Nested(account_fields, allow_null=True),
+ }
+
+ annotation_fields = {
+ 'content': fields.String,
+ 'account': fields.Nested(account_fields, allow_null=True),
+ 'created_at': TimestampField
+ }
+
+ message_detail_fields = {
+ 'id': fields.String,
+ 'conversation_id': fields.String,
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'message': fields.Raw,
+ 'message_tokens': fields.Integer,
+ 'answer': fields.String,
+ 'answer_tokens': fields.Integer,
+ 'provider_response_latency': fields.Integer,
+ 'from_source': fields.String,
+ 'from_end_user_id': fields.String,
+ 'from_account_id': fields.String,
+ 'feedbacks': fields.List(fields.Nested(feedback_fields)),
+ 'annotation': fields.Nested(annotation_fields, allow_null=True),
+ 'created_at': TimestampField
+ }
+
+ message_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(message_detail_fields))
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(message_infinite_scroll_pagination_fields)
+ def get(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app = _get_app(app_id, 'chat')
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('conversation_id', required=True, type=uuid_value, location='args')
+ parser.add_argument('first_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ args = parser.parse_args()
+
+ conversation = db.session.query(Conversation).filter(
+ Conversation.id == args['conversation_id'],
+ Conversation.app_id == app.id
+ ).first()
+
+ if not conversation:
+ raise NotFound("Conversation Not Exists.")
+
+ if args['first_id']:
+ first_message = db.session.query(Message) \
+ .filter(Message.conversation_id == conversation.id, Message.id == args['first_id']).first()
+
+ if not first_message:
+ raise NotFound("First message not found")
+
+ history_messages = db.session.query(Message).filter(
+ Message.conversation_id == conversation.id,
+ Message.created_at < first_message.created_at,
+ Message.id != first_message.id
+ ) \
+ .order_by(Message.created_at.desc()).limit(args['limit']).all()
+ else:
+ history_messages = db.session.query(Message).filter(Message.conversation_id == conversation.id) \
+ .order_by(Message.created_at.desc()).limit(args['limit']).all()
+
+ has_more = False
+ if len(history_messages) == args['limit']:
+ current_page_first_message = history_messages[-1]
+ rest_count = db.session.query(Message).filter(
+ Message.conversation_id == conversation.id,
+ Message.created_at < current_page_first_message.created_at,
+ Message.id != current_page_first_message.id
+ ).count()
+
+ if rest_count > 0:
+ has_more = True
+
+ history_messages = list(reversed(history_messages))
+
+ return InfiniteScrollPagination(
+ data=history_messages,
+ limit=args['limit'],
+ has_more=has_more
+ )
+
+
+class MessageFeedbackApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app = _get_app(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('message_id', required=True, type=uuid_value, location='json')
+ parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
+ args = parser.parse_args()
+
+ message_id = str(args['message_id'])
+
+ message = db.session.query(Message).filter(
+ Message.id == message_id,
+ Message.app_id == app.id
+ ).first()
+
+ if not message:
+ raise NotFound("Message Not Exists.")
+
+ feedback = message.admin_feedback
+
+ if not args['rating'] and feedback:
+ db.session.delete(feedback)
+ elif args['rating'] and feedback:
+ feedback.rating = args['rating']
+ elif not args['rating'] and not feedback:
+ raise ValueError('rating cannot be None when feedback not exists')
+ else:
+ feedback = MessageFeedback(
+ app_id=app.id,
+ conversation_id=message.conversation_id,
+ message_id=message.id,
+ rating=args['rating'],
+ from_source='admin',
+ from_account_id=current_user.id
+ )
+ db.session.add(feedback)
+
+ db.session.commit()
+
+ return {'result': 'success'}
+
+
+class MessageAnnotationApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app = _get_app(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('message_id', required=True, type=uuid_value, location='json')
+ parser.add_argument('content', type=str, location='json')
+ args = parser.parse_args()
+
+ message_id = str(args['message_id'])
+
+ message = db.session.query(Message).filter(
+ Message.id == message_id,
+ Message.app_id == app.id
+ ).first()
+
+ if not message:
+ raise NotFound("Message Not Exists.")
+
+ annotation = message.annotation
+
+ if annotation:
+ annotation.content = args['content']
+ else:
+ annotation = MessageAnnotation(
+ app_id=app.id,
+ conversation_id=message.conversation_id,
+ message_id=message.id,
+ content=args['content'],
+ account_id=current_user.id
+ )
+ db.session.add(annotation)
+
+ db.session.commit()
+
+ return {'result': 'success'}
+
+
+class MessageAnnotationCountApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id):
+ app_id = str(app_id)
+
+ # get app info
+ app = _get_app(app_id)
+
+ count = db.session.query(MessageAnnotation).filter(
+ MessageAnnotation.app_id == app.id
+ ).count()
+
+ return {'count': count}
+
+
+class MessageMoreLikeThisApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id, message_id):
+ app_id = str(app_id)
+ message_id = str(message_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('response_mode', type=str, required=True, choices=['blocking', 'streaming'], location='args')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ # get app info
+ app_model = _get_app(app_id, 'completion')
+
+ try:
+ response = CompletionService.generate_more_like_this(app_model, current_user, message_id, streaming)
+ return compact_response(response)
+ except MessageNotExistsError:
+ raise NotFound("Message Not Exists.")
+ except MoreLikeThisDisabledError:
+ raise AppMoreLikeThisDisabledError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+def compact_response(response: Union[dict | Generator]) -> Response:
+ if isinstance(response, dict):
+ return Response(response=json.dumps(response), status=200, mimetype='application/json')
+ else:
+ def generate() -> Generator:
+ try:
+ for chunk in response:
+ yield chunk
+ except MessageNotExistsError:
+ yield "data: " + json.dumps(api.handle_error(NotFound("Message Not Exists.")).get_json()) + "\n\n"
+ except MoreLikeThisDisabledError:
+ yield "data: " + json.dumps(api.handle_error(AppMoreLikeThisDisabledError()).get_json()) + "\n\n"
+ except ProviderTokenNotInitError:
+ yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError()).get_json()) + "\n\n"
+ except QuotaExceededError:
+ yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
+ except ModelCurrentlyNotSupportError:
+ yield "data: " + json.dumps(api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
+ except ValueError as e:
+ yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
+ except Exception:
+ logging.exception("internal server error.")
+ yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
+
+ return Response(stream_with_context(generate()), status=200,
+ mimetype='text/event-stream')
+
+
+class MessageSuggestedQuestionApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id, message_id):
+ app_id = str(app_id)
+ message_id = str(message_id)
+
+ # get app info
+ app_model = _get_app(app_id, 'chat')
+
+ try:
+ questions = MessageService.get_suggested_questions_after_answer(
+ app_model=app_model,
+ user=current_user,
+ message_id=message_id,
+ check_enabled=False
+ )
+ except MessageNotExistsError:
+ raise NotFound("Message not found")
+ except ConversationNotExistsError:
+ raise NotFound("Conversation not found")
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except Exception:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+ return {'data': questions}
+
+
+api.add_resource(MessageMoreLikeThisApi, '/apps/<uuid:app_id>/completion-messages/<uuid:message_id>/more-like-this')
+api.add_resource(MessageSuggestedQuestionApi, '/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions')
+api.add_resource(ChatMessageApi, '/apps/<uuid:app_id>/chat-messages', endpoint='chat_messages')
+api.add_resource(MessageFeedbackApi, '/apps/<uuid:app_id>/feedbacks')
+api.add_resource(MessageAnnotationApi, '/apps/<uuid:app_id>/annotations')
+api.add_resource(MessageAnnotationCountApi, '/apps/<uuid:app_id>/annotations/count')
diff --git a/api/controllers/console/app/model_config.py b/api/controllers/console/app/model_config.py
new file mode 100644
index 00000000000..adc10d6609e
--- /dev/null
+++ b/api/controllers/console/app/model_config.py
@@ -0,0 +1,65 @@
+# -*- coding:utf-8 -*-
+import json
+
+from flask import request
+from flask_restful import Resource
+from flask_login import login_required, current_user
+
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from events.app_event import app_model_config_was_updated
+from extensions.ext_database import db
+from models.model import AppModelConfig
+from services.app_model_config_service import AppModelConfigService
+
+
+class ModelConfigResource(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, app_id):
+ """Modify app model config"""
+ app_id = str(app_id)
+
+ app_model = _get_app(app_id)
+
+ # validate config
+ model_configuration = AppModelConfigService.validate_configuration(
+ account=current_user,
+ config=request.json,
+ mode=app_model.mode
+ )
+
+ new_app_model_config = AppModelConfig(
+ app_id=app_model.id,
+ provider="",
+ model_id="",
+ configs={},
+ opening_statement=model_configuration['opening_statement'],
+ suggested_questions=json.dumps(model_configuration['suggested_questions']),
+ suggested_questions_after_answer=json.dumps(model_configuration['suggested_questions_after_answer']),
+ more_like_this=json.dumps(model_configuration['more_like_this']),
+ model=json.dumps(model_configuration['model']),
+ user_input_form=json.dumps(model_configuration['user_input_form']),
+ pre_prompt=model_configuration['pre_prompt'],
+ agent_mode=json.dumps(model_configuration['agent_mode']),
+ )
+
+ db.session.add(new_app_model_config)
+ db.session.flush()
+
+ app_model.app_model_config_id = new_app_model_config.id
+ db.session.commit()
+
+ app_model_config_was_updated.send(
+ app_model,
+ app_model_config=new_app_model_config
+ )
+
+ return {'result': 'success'}
+
+
+api.add_resource(ModelConfigResource, '/apps/<uuid:app_id>/model-config')
diff --git a/api/controllers/console/app/site.py b/api/controllers/console/app/site.py
new file mode 100644
index 00000000000..2e0e00a8817
--- /dev/null
+++ b/api/controllers/console/app/site.py
@@ -0,0 +1,114 @@
+# -*- coding:utf-8 -*-
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal_with
+from werkzeug.exceptions import NotFound, Forbidden
+
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from libs.helper import supported_language
+from extensions.ext_database import db
+from models.model import Site
+
+app_site_fields = {
+ 'app_id': fields.String,
+ 'access_token': fields.String(attribute='code'),
+ 'code': fields.String,
+ 'title': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'description': fields.String,
+ 'default_language': fields.String,
+ 'customize_domain': fields.String,
+ 'copyright': fields.String,
+ 'privacy_policy': fields.String,
+ 'customize_token_strategy': fields.String,
+ 'prompt_public': fields.Boolean
+}
+
+
+def parse_app_site_args():
+ parser = reqparse.RequestParser()
+ parser.add_argument('title', type=str, required=False, location='json')
+ parser.add_argument('icon', type=str, required=False, location='json')
+ parser.add_argument('icon_background', type=str, required=False, location='json')
+ parser.add_argument('description', type=str, required=False, location='json')
+ parser.add_argument('default_language', type=supported_language, required=False, location='json')
+ parser.add_argument('customize_domain', type=str, required=False, location='json')
+ parser.add_argument('copyright', type=str, required=False, location='json')
+ parser.add_argument('privacy_policy', type=str, required=False, location='json')
+ parser.add_argument('customize_token_strategy', type=str, choices=['must', 'allow', 'not_allow'],
+ required=False,
+ location='json')
+ parser.add_argument('prompt_public', type=bool, required=False, location='json')
+ return parser.parse_args()
+
+
+class AppSite(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_site_fields)
+ def post(self, app_id):
+ args = parse_app_site_args()
+
+ app_id = str(app_id)
+ app_model = _get_app(app_id)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ site = db.session.query(Site). \
+ filter(Site.app_id == app_model.id). \
+ one_or_404()
+
+ for attr_name in [
+ 'title',
+ 'icon',
+ 'icon_background',
+ 'description',
+ 'default_language',
+ 'customize_domain',
+ 'copyright',
+ 'privacy_policy',
+ 'customize_token_strategy',
+ 'prompt_public'
+ ]:
+ value = args.get(attr_name)
+ if value is not None:
+ setattr(site, attr_name, value)
+
+ db.session.commit()
+
+ return site
+
+
+class AppSiteAccessTokenReset(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(app_site_fields)
+ def post(self, app_id):
+ app_id = str(app_id)
+ app_model = _get_app(app_id)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ site = db.session.query(Site).filter(Site.app_id == app_model.id).first()
+
+ if not site:
+ raise NotFound
+
+ site.code = Site.generate_code(16)
+ db.session.commit()
+
+ return site
+
+
+api.add_resource(AppSite, '/apps/<uuid:app_id>/site')
+api.add_resource(AppSiteAccessTokenReset, '/apps/<uuid:app_id>/site/access-token-reset')
diff --git a/api/controllers/console/app/statistic.py b/api/controllers/console/app/statistic.py
new file mode 100644
index 00000000000..37c35004487
--- /dev/null
+++ b/api/controllers/console/app/statistic.py
@@ -0,0 +1,202 @@
+# -*- coding:utf-8 -*-
+from datetime import datetime
+
+import pytz
+from flask import jsonify
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse
+
+from controllers.console import api
+from controllers.console.app import _get_app
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from libs.helper import datetime_string
+from extensions.ext_database import db
+
+
+class DailyConversationStatistic(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id):
+ account = current_user
+ app_id = str(app_id)
+ app_model = _get_app(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ args = parser.parse_args()
+
+ sql_query = '''
+ SELECT date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date, count(distinct messages.conversation_id) AS conversation_count
+ FROM messages where app_id = :app_id
+ '''
+ arg_dict = {'tz': account.timezone, 'app_id': app_model.id}
+
+ timezone = pytz.timezone(account.timezone)
+ utc_timezone = pytz.utc
+
+ if args['start']:
+ start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
+ start_datetime = start_datetime.replace(second=0)
+
+ start_datetime_timezone = timezone.localize(start_datetime)
+ start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at >= :start'
+ arg_dict['start'] = start_datetime_utc
+
+ if args['end']:
+ end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
+ end_datetime = end_datetime.replace(second=0)
+
+ end_datetime_timezone = timezone.localize(end_datetime)
+ end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at < :end'
+ arg_dict['end'] = end_datetime_utc
+
+ sql_query += ' GROUP BY date order by date'
+ rs = db.session.execute(sql_query, arg_dict)
+
+ response_date = []
+
+ for i in rs:
+ response_date.append({
+ 'date': str(i.date),
+ 'conversation_count': i.conversation_count
+ })
+
+ return jsonify({
+ 'data': response_date
+ })
+
+
+class DailyTerminalsStatistic(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id):
+ account = current_user
+ app_id = str(app_id)
+ app_model = _get_app(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ args = parser.parse_args()
+
+ sql_query = '''
+ SELECT date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date, count(distinct messages.from_end_user_id) AS terminal_count
+ FROM messages where app_id = :app_id
+ '''
+ arg_dict = {'tz': account.timezone, 'app_id': app_model.id}
+
+ timezone = pytz.timezone(account.timezone)
+ utc_timezone = pytz.utc
+
+ if args['start']:
+ start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
+ start_datetime = start_datetime.replace(second=0)
+
+ start_datetime_timezone = timezone.localize(start_datetime)
+ start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at >= :start'
+ arg_dict['start'] = start_datetime_utc
+
+ if args['end']:
+ end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
+ end_datetime = end_datetime.replace(second=0)
+
+ end_datetime_timezone = timezone.localize(end_datetime)
+ end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at < :end'
+ arg_dict['end'] = end_datetime_utc
+
+ sql_query += ' GROUP BY date order by date'
+ rs = db.session.execute(sql_query, arg_dict)
+
+ response_date = []
+
+ for i in rs:
+ response_date.append({
+ 'date': str(i.date),
+ 'terminal_count': i.terminal_count
+ })
+
+ return jsonify({
+ 'data': response_date
+ })
+
+
+class DailyTokenCostStatistic(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, app_id):
+ account = current_user
+ app_id = str(app_id)
+ app_model = _get_app(app_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
+ args = parser.parse_args()
+
+ sql_query = '''
+ SELECT date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date,
+ (sum(messages.message_tokens) + sum(messages.answer_tokens)) as token_count,
+ sum(total_price) as total_price
+ FROM messages where app_id = :app_id
+ '''
+ arg_dict = {'tz': account.timezone, 'app_id': app_model.id}
+
+ timezone = pytz.timezone(account.timezone)
+ utc_timezone = pytz.utc
+
+ if args['start']:
+ start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
+ start_datetime = start_datetime.replace(second=0)
+
+ start_datetime_timezone = timezone.localize(start_datetime)
+ start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at >= :start'
+ arg_dict['start'] = start_datetime_utc
+
+ if args['end']:
+ end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
+ end_datetime = end_datetime.replace(second=0)
+
+ end_datetime_timezone = timezone.localize(end_datetime)
+ end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
+
+ sql_query += ' and created_at < :end'
+ arg_dict['end'] = end_datetime_utc
+
+ sql_query += ' GROUP BY date order by date'
+ rs = db.session.execute(sql_query, arg_dict)
+
+ response_date = []
+
+ for i in rs:
+ response_date.append({
+ 'date': str(i.date),
+ 'token_count': i.token_count,
+ 'total_price': i.total_price,
+ 'currency': 'USD'
+ })
+
+ return jsonify({
+ 'data': response_date
+ })
+
+
+api.add_resource(DailyConversationStatistic, '/apps/<uuid:app_id>/statistics/daily-conversations')
+api.add_resource(DailyTerminalsStatistic, '/apps/<uuid:app_id>/statistics/daily-end-users')
+api.add_resource(DailyTokenCostStatistic, '/apps/<uuid:app_id>/statistics/token-costs')
diff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.py
new file mode 100644
index 00000000000..89f5d917892
--- /dev/null
+++ b/api/controllers/console/auth/login.py
@@ -0,0 +1,109 @@
+# -*- coding:utf-8 -*-
+import flask
+import flask_login
+from flask import request, current_app
+from flask_restful import Resource, reqparse
+
+import services
+from controllers.console import api
+from controllers.console.error import AccountNotLinkTenantError
+from controllers.console.setup import setup_required
+from libs.helper import email
+from libs.password import valid_password
+from services.account_service import AccountService, TenantService
+
+
+class LoginApi(Resource):
+ """Resource for user login."""
+
+ @setup_required
+ def post(self):
+ """Authenticate user and login."""
+ parser = reqparse.RequestParser()
+ parser.add_argument('email', type=email, required=True, location='json')
+ parser.add_argument('password', type=valid_password, required=True, location='json')
+ parser.add_argument('remember_me', type=bool, required=False, default=False, location='json')
+ args = parser.parse_args()
+
+ # todo: Verify the recaptcha
+
+ try:
+ account = AccountService.authenticate(args['email'], args['password'])
+ except services.errors.account.AccountLoginError:
+ return {'code': 'unauthorized', 'message': 'Invalid email or password'}, 401
+
+ try:
+ TenantService.switch_tenant(account)
+ except Exception:
+ raise AccountNotLinkTenantError("Account not link tenant")
+
+ flask_login.login_user(account, remember=args['remember_me'])
+ AccountService.update_last_login(account, request)
+
+ # todo: return the user info
+
+ return {'result': 'success'}
+
+
+class LogoutApi(Resource):
+
+ @setup_required
+ def get(self):
+ flask.session.pop('workspace_id', None)
+ flask_login.logout_user()
+ return {'result': 'success'}
+
+
+class ResetPasswordApi(Resource):
+ @setup_required
+ def get(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('email', type=email, required=True, location='json')
+ args = parser.parse_args()
+
+ # import mailchimp_transactional as MailchimpTransactional
+ # from mailchimp_transactional.api_client import ApiClientError
+
+ account = {'email': args['email']}
+ # account = AccountService.get_by_email(args['email'])
+ # if account is None:
+ # raise ValueError('Email not found')
+ # new_password = AccountService.generate_password()
+ # AccountService.update_password(account, new_password)
+
+ # todo: Send email
+ MAILCHIMP_API_KEY = current_app.config['MAILCHIMP_TRANSACTIONAL_API_KEY']
+ # mailchimp = MailchimpTransactional(MAILCHIMP_API_KEY)
+
+ message = {
+ 'from_email': '[email protected]',
+ 'to': [{'email': account.email}],
+ 'subject': 'Reset your Dify password',
+ 'html': """
+ <p>Dear User,</p>
+ <p>The Dify team has generated a new password for you, details as follows:</p>
+ <p><strong>{new_password}</strong></p>
+ <p>Please change your password to log in as soon as possible.</p>
+ <p>Regards,</p>
+ <p>The Dify Team</p>
+ """
+ }
+
+ # response = mailchimp.messages.send({
+ # 'message': message,
+ # # required for transactional email
+ # ' settings': {
+ # 'sandbox_mode': current_app.config['MAILCHIMP_SANDBOX_MODE'],
+ # },
+ # })
+
+ # Check if MSG was sent
+ # if response.status_code != 200:
+ # # handle error
+ # pass
+
+ return {'result': 'success'}
+
+
+api.add_resource(LoginApi, '/login')
+api.add_resource(LogoutApi, '/logout')
diff --git a/api/controllers/console/auth/oauth.py b/api/controllers/console/auth/oauth.py
new file mode 100644
index 00000000000..ababc30de9b
--- /dev/null
+++ b/api/controllers/console/auth/oauth.py
@@ -0,0 +1,126 @@
+import logging
+from datetime import datetime
+from typing import Optional
+
+import flask_login
+import requests
+from flask import request, redirect, current_app, session
+from flask_restful import Resource
+
+from libs.oauth import OAuthUserInfo, GitHubOAuth, GoogleOAuth
+from extensions.ext_database import db
+from models.account import Account, AccountStatus
+from services.account_service import AccountService, RegisterService
+from .. import api
+
+
+def get_oauth_providers():
+ with current_app.app_context():
+ github_oauth = GitHubOAuth(client_id=current_app.config.get('GITHUB_CLIENT_ID'),
+ client_secret=current_app.config.get(
+ 'GITHUB_CLIENT_SECRET'),
+ redirect_uri=current_app.config.get(
+ 'CONSOLE_URL') + '/console/api/oauth/authorize/github')
+
+ google_oauth = GoogleOAuth(client_id=current_app.config.get('GOOGLE_CLIENT_ID'),
+ client_secret=current_app.config.get(
+ 'GOOGLE_CLIENT_SECRET'),
+ redirect_uri=current_app.config.get(
+ 'CONSOLE_URL') + '/console/api/oauth/authorize/google')
+
+ OAUTH_PROVIDERS = {
+ 'github': github_oauth,
+ 'google': google_oauth
+ }
+ return OAUTH_PROVIDERS
+
+
+class OAuthLogin(Resource):
+ def get(self, provider: str):
+ OAUTH_PROVIDERS = get_oauth_providers()
+ with current_app.app_context():
+ oauth_provider = OAUTH_PROVIDERS.get(provider)
+ print(vars(oauth_provider))
+ if not oauth_provider:
+ return {'error': 'Invalid provider'}, 400
+
+ auth_url = oauth_provider.get_authorization_url()
+ return redirect(auth_url)
+
+
+class OAuthCallback(Resource):
+ def get(self, provider: str):
+ OAUTH_PROVIDERS = get_oauth_providers()
+ with current_app.app_context():
+ oauth_provider = OAUTH_PROVIDERS.get(provider)
+ if not oauth_provider:
+ return {'error': 'Invalid provider'}, 400
+
+ code = request.args.get('code')
+ try:
+ token = oauth_provider.get_access_token(code)
+ user_info = oauth_provider.get_user_info(token)
+ except requests.exceptions.HTTPError as e:
+ logging.exception(
+ f"An error occurred during the OAuth process with {provider}: {e.response.text}")
+ return {'error': 'OAuth process failed'}, 400
+
+ account = _generate_account(provider, user_info)
+ # Check account status
+ if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
+ return {'error': 'Account is banned or closed.'}, 403
+
+ if account.status == AccountStatus.PENDING.value:
+ account.status = AccountStatus.ACTIVE.value
+ account.initialized_at = datetime.utcnow()
+ db.session.commit()
+
+ # login user
+ session.clear()
+ flask_login.login_user(account, remember=True)
+ AccountService.update_last_login(account, request)
+
+ return redirect(f'{current_app.config.get("CONSOLE_URL")}?oauth_login=success')
+
+
+def _get_account_by_openid_or_email(provider: str, user_info: OAuthUserInfo) -> Optional[Account]:
+ account = Account.get_by_openid(provider, user_info.id)
+
+ if not account:
+ account = Account.query.filter_by(email=user_info.email).first()
+
+ return account
+
+
+def _generate_account(provider: str, user_info: OAuthUserInfo):
+ # Get account by openid or email.
+ account = _get_account_by_openid_or_email(provider, user_info)
+
+ if not account:
+ # Create account
+ account_name = user_info.name if user_info.name else 'Dify'
+ account = RegisterService.register(
+ email=user_info.email,
+ name=account_name,
+ password=None,
+ open_id=user_info.id,
+ provider=provider
+ )
+
+ # Set interface language
+ preferred_lang = request.accept_languages.best_match(['zh', 'en'])
+ if preferred_lang == 'zh':
+ interface_language = 'zh-Hans'
+ else:
+ interface_language = 'en-US'
+ account.interface_language = interface_language
+ db.session.commit()
+
+ # Link account
+ AccountService.link_account_integrate(provider, user_info.id, account)
+
+ return account
+
+
+api.add_resource(OAuthLogin, '/oauth/login/<provider>')
+api.add_resource(OAuthCallback, '/oauth/authorize/<provider>')
diff --git a/api/controllers/console/datasets/datasets.py b/api/controllers/console/datasets/datasets.py
new file mode 100644
index 00000000000..04a4a44840c
--- /dev/null
+++ b/api/controllers/console/datasets/datasets.py
@@ -0,0 +1,281 @@
+# -*- coding:utf-8 -*-
+from flask import request
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal, marshal_with
+from werkzeug.exceptions import NotFound, Forbidden
+
+import services
+from controllers.console import api
+from controllers.console.datasets.error import DatasetNameDuplicateError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.indexing_runner import IndexingRunner
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.model import UploadFile
+from services.dataset_service import DatasetService
+
+dataset_detail_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'description': fields.String,
+ 'provider': fields.String,
+ 'permission': fields.String,
+ 'data_source_type': fields.String,
+ 'indexing_technique': fields.String,
+ 'app_count': fields.Integer,
+ 'document_count': fields.Integer,
+ 'word_count': fields.Integer,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+ 'updated_by': fields.String,
+ 'updated_at': TimestampField,
+}
+
+dataset_query_detail_fields = {
+ "id": fields.String,
+ "content": fields.String,
+ "source": fields.String,
+ "source_app_id": fields.String,
+ "created_by_role": fields.String,
+ "created_by": fields.String,
+ "created_at": TimestampField
+}
+
+
+def _validate_name(name):
+ if not name or len(name) < 1 or len(name) > 40:
+ raise ValueError('Name must be between 1 to 40 characters.')
+ return name
+
+
+def _validate_description_length(description):
+ if len(description) > 200:
+ raise ValueError('Description cannot exceed 200 characters.')
+ return description
+
+
+class DatasetListApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self):
+ page = request.args.get('page', default=1, type=int)
+ limit = request.args.get('limit', default=20, type=int)
+ ids = request.args.getlist('ids')
+ provider = request.args.get('provider', default="vendor")
+ if ids:
+ datasets, total = DatasetService.get_datasets_by_ids(ids, current_user.current_tenant_id)
+ else:
+ datasets, total = DatasetService.get_datasets(page, limit, provider,
+ current_user.current_tenant_id, current_user)
+
+ response = {
+ 'data': marshal(datasets, dataset_detail_fields),
+ 'has_more': len(datasets) == limit,
+ 'limit': limit,
+ 'total': total,
+ 'page': page
+ }
+ return response, 200
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', nullable=False, required=True,
+ help='type is required. Name must be between 1 to 40 characters.',
+ type=_validate_name)
+ parser.add_argument('indexing_technique', type=str, location='json',
+ choices=('high_quality', 'economy'),
+ help='Invalid indexing technique.')
+ args = parser.parse_args()
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ try:
+ dataset = DatasetService.create_empty_dataset(
+ tenant_id=current_user.current_tenant_id,
+ name=args['name'],
+ indexing_technique=args['indexing_technique'],
+ account=current_user
+ )
+ except services.errors.dataset.DatasetNameDuplicateError:
+ raise DatasetNameDuplicateError()
+
+ return marshal(dataset, dataset_detail_fields), 201
+
+
+class DatasetApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+ dataset = DatasetService.get_dataset(dataset_id_str)
+ if dataset is None:
+ raise NotFound("Dataset not found.")
+
+ try:
+ DatasetService.check_dataset_permission(
+ dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ return marshal(dataset, dataset_detail_fields), 200
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def patch(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', nullable=False,
+ help='type is required. Name must be between 1 to 40 characters.',
+ type=_validate_name)
+ parser.add_argument('description',
+ location='json', store_missing=False,
+ type=_validate_description_length)
+ parser.add_argument('indexing_technique', type=str, location='json',
+ choices=('high_quality', 'economy'),
+ help='Invalid indexing technique.')
+ parser.add_argument('permission', type=str, location='json', choices=(
+ 'only_me', 'all_team_members'), help='Invalid permission.')
+ args = parser.parse_args()
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ dataset = DatasetService.update_dataset(
+ dataset_id_str, args, current_user)
+
+ if dataset is None:
+ raise NotFound("Dataset not found.")
+
+ return marshal(dataset, dataset_detail_fields), 200
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def delete(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ if DatasetService.delete_dataset(dataset_id_str, current_user):
+ return {'result': 'success'}, 204
+ else:
+ raise NotFound("Dataset not found.")
+
+
+class DatasetQueryApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+ dataset = DatasetService.get_dataset(dataset_id_str)
+ if dataset is None:
+ raise NotFound("Dataset not found.")
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ page = request.args.get('page', default=1, type=int)
+ limit = request.args.get('limit', default=20, type=int)
+
+ dataset_queries, total = DatasetService.get_dataset_queries(
+ dataset_id=dataset.id,
+ page=page,
+ per_page=limit
+ )
+
+ response = {
+ 'data': marshal(dataset_queries, dataset_query_detail_fields),
+ 'has_more': len(dataset_queries) == limit,
+ 'limit': limit,
+ 'total': total,
+ 'page': page
+ }
+ return response, 200
+
+
+class DatasetIndexingEstimateApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self):
+ segment_rule = request.get_json()
+ file_detail = db.session.query(UploadFile).filter(
+ UploadFile.tenant_id == current_user.current_tenant_id,
+ UploadFile.id == segment_rule["file_id"]
+ ).first()
+
+ if file_detail is None:
+ raise NotFound("File not found.")
+
+ indexing_runner = IndexingRunner()
+ response = indexing_runner.indexing_estimate(file_detail, segment_rule['process_rule'])
+ return response, 200
+
+
+class DatasetRelatedAppListApi(Resource):
+ app_detail_kernel_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'mode': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ }
+
+ related_app_list = {
+ 'data': fields.List(fields.Nested(app_detail_kernel_fields)),
+ 'total': fields.Integer,
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(related_app_list)
+ def get(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+ dataset = DatasetService.get_dataset(dataset_id_str)
+ if dataset is None:
+ raise NotFound("Dataset not found.")
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ app_dataset_joins = DatasetService.get_related_apps(dataset.id)
+
+ related_apps = []
+ for app_dataset_join in app_dataset_joins:
+ app_model = app_dataset_join.app
+ if app_model:
+ related_apps.append(app_model)
+
+ return {
+ 'data': related_apps,
+ 'total': len(related_apps)
+ }, 200
+
+
+api.add_resource(DatasetListApi, '/datasets')
+api.add_resource(DatasetApi, '/datasets/<uuid:dataset_id>')
+api.add_resource(DatasetQueryApi, '/datasets/<uuid:dataset_id>/queries')
+api.add_resource(DatasetIndexingEstimateApi, '/datasets/file-indexing-estimate')
+api.add_resource(DatasetRelatedAppListApi, '/datasets/<uuid:dataset_id>/related-apps')
diff --git a/api/controllers/console/datasets/datasets_document.py b/api/controllers/console/datasets/datasets_document.py
new file mode 100644
index 00000000000..79e52d565be
--- /dev/null
+++ b/api/controllers/console/datasets/datasets_document.py
@@ -0,0 +1,682 @@
+# -*- coding:utf-8 -*-
+import random
+from datetime import datetime
+
+from flask import request
+from flask_login import login_required, current_user
+from flask_restful import Resource, fields, marshal, marshal_with, reqparse
+from sqlalchemy import desc, asc
+from werkzeug.exceptions import NotFound, Forbidden
+
+import services
+from controllers.console import api
+from controllers.console.app.error import ProviderNotInitializeError
+from controllers.console.datasets.error import DocumentAlreadyFinishedError, InvalidActionError, DocumentIndexingError, \
+ InvalidMetadataError, ArchivedDocumentImmutableError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.indexing_runner import IndexingRunner
+from core.llm.error import ProviderTokenNotInitError
+from extensions.ext_redis import redis_client
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.dataset import DatasetProcessRule, Dataset
+from models.dataset import Document, DocumentSegment
+from models.model import UploadFile
+from services.dataset_service import DocumentService, DatasetService
+from tasks.add_document_to_index_task import add_document_to_index_task
+from tasks.remove_document_from_index_task import remove_document_from_index_task
+
+dataset_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'description': fields.String,
+ 'permission': fields.String,
+ 'data_source_type': fields.String,
+ 'indexing_technique': fields.String,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+}
+
+document_fields = {
+ 'id': fields.String,
+ 'position': fields.Integer,
+ 'data_source_type': fields.String,
+ 'data_source_info': fields.Raw(attribute='data_source_info_dict'),
+ 'dataset_process_rule_id': fields.String,
+ 'name': fields.String,
+ 'created_from': fields.String,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+ 'tokens': fields.Integer,
+ 'indexing_status': fields.String,
+ 'error': fields.String,
+ 'enabled': fields.Boolean,
+ 'disabled_at': TimestampField,
+ 'disabled_by': fields.String,
+ 'archived': fields.Boolean,
+ 'display_status': fields.String,
+ 'word_count': fields.Integer,
+ 'hit_count': fields.Integer,
+}
+
+
+class DocumentResource(Resource):
+ def get_document(self, dataset_id: str, document_id: str) -> Document:
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ document = DocumentService.get_document(dataset_id, document_id)
+
+ if not document:
+ raise NotFound('Document not found.')
+
+ if document.tenant_id != current_user.current_tenant_id:
+ raise Forbidden('No permission.')
+
+ return document
+
+
+class GetProcessRuleApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self):
+ req_data = request.args
+
+ document_id = req_data.get('document_id')
+ if document_id:
+ # get the latest process rule
+ document = Document.query.get_or_404(document_id)
+
+ dataset = DatasetService.get_dataset(document.dataset_id)
+
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ # get the latest process rule
+ dataset_process_rule = db.session.query(DatasetProcessRule). \
+ filter(DatasetProcessRule.dataset_id == document.dataset_id). \
+ order_by(DatasetProcessRule.created_at.desc()). \
+ limit(1). \
+ one_or_none()
+ mode = dataset_process_rule.mode
+ rules = dataset_process_rule.rules_dict
+ else:
+ mode = DocumentService.DEFAULT_RULES['mode']
+ rules = DocumentService.DEFAULT_RULES['rules']
+
+ return {
+ 'mode': mode,
+ 'rules': rules
+ }
+
+
+class DatasetDocumentListApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id):
+ dataset_id = str(dataset_id)
+ page = request.args.get('page', default=1, type=int)
+ limit = request.args.get('limit', default=20, type=int)
+ search = request.args.get('search', default=None, type=str)
+ sort = request.args.get('sort', default='-created_at', type=str)
+
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ query = Document.query.filter_by(
+ dataset_id=str(dataset_id), tenant_id=current_user.current_tenant_id)
+
+ if search:
+ search = f'%{search}%'
+ query = query.filter(Document.name.like(search))
+
+ if sort.startswith('-'):
+ sort_logic = desc
+ sort = sort[1:]
+ else:
+ sort_logic = asc
+
+ if sort == 'hit_count':
+ sub_query = db.select(DocumentSegment.document_id,
+ db.func.sum(DocumentSegment.hit_count).label("total_hit_count")) \
+ .group_by(DocumentSegment.document_id) \
+ .subquery()
+
+ query = query.outerjoin(sub_query, sub_query.c.document_id == Document.id) \
+ .order_by(sort_logic(db.func.coalesce(sub_query.c.total_hit_count, 0)))
+ elif sort == 'created_at':
+ query = query.order_by(sort_logic(Document.created_at))
+ else:
+ query = query.order_by(desc(Document.created_at))
+
+ paginated_documents = query.paginate(
+ page=page, per_page=limit, max_per_page=100, error_out=False)
+ documents = paginated_documents.items
+
+ response = {
+ 'data': marshal(documents, document_fields),
+ 'has_more': len(documents) == limit,
+ 'limit': limit,
+ 'total': paginated_documents.total,
+ 'page': page
+ }
+
+ return response
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(document_fields)
+ def post(self, dataset_id):
+ dataset_id = str(dataset_id)
+
+ dataset = DatasetService.get_dataset(dataset_id)
+
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('indexing_technique', type=str, choices=Dataset.INDEXING_TECHNIQUE_LIST, nullable=False,
+ location='json')
+ parser.add_argument('data_source', type=dict, required=True, nullable=True, location='json')
+ parser.add_argument('process_rule', type=dict, required=True, nullable=True, location='json')
+ parser.add_argument('duplicate', type=bool, nullable=False, location='json')
+ args = parser.parse_args()
+
+ if not dataset.indexing_technique and not args['indexing_technique']:
+ raise ValueError('indexing_technique is required.')
+
+ # validate args
+ DocumentService.document_create_args_validate(args)
+
+ try:
+ document = DocumentService.save_document_with_dataset_id(dataset, args, current_user)
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+
+ return document
+
+
+class DatasetInitApi(Resource):
+ dataset_and_document_fields = {
+ 'dataset': fields.Nested(dataset_fields),
+ 'document': fields.Nested(document_fields)
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(dataset_and_document_fields)
+ def post(self):
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('indexing_technique', type=str, choices=Dataset.INDEXING_TECHNIQUE_LIST, required=True,
+ nullable=False, location='json')
+ parser.add_argument('data_source', type=dict, required=True, nullable=True, location='json')
+ parser.add_argument('process_rule', type=dict, required=True, nullable=True, location='json')
+ args = parser.parse_args()
+
+ # validate args
+ DocumentService.document_create_args_validate(args)
+
+ try:
+ dataset, document = DocumentService.save_document_without_dataset_id(
+ tenant_id=current_user.current_tenant_id,
+ document_data=args,
+ account=current_user
+ )
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+
+ response = {
+ 'dataset': dataset,
+ 'document': document
+ }
+
+ return response
+
+
+class DocumentIndexingEstimateApi(DocumentResource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ if document.indexing_status in ['completed', 'error']:
+ raise DocumentAlreadyFinishedError()
+
+ data_process_rule = document.dataset_process_rule
+ data_process_rule_dict = data_process_rule.to_dict()
+
+ response = {
+ "tokens": 0,
+ "total_price": 0,
+ "currency": "USD",
+ "total_segments": 0,
+ "preview": []
+ }
+
+ if document.data_source_type == 'upload_file':
+ data_source_info = document.data_source_info_dict
+ if data_source_info and 'upload_file_id' in data_source_info:
+ file_id = data_source_info['upload_file_id']
+
+ file = db.session.query(UploadFile).filter(
+ UploadFile.tenant_id == document.tenant_id,
+ UploadFile.id == file_id
+ ).first()
+
+ # raise error if file not found
+ if not file:
+ raise NotFound('File not found.')
+
+ indexing_runner = IndexingRunner()
+ response = indexing_runner.indexing_estimate(file, data_process_rule_dict)
+
+ return response
+
+
+class DocumentIndexingStatusApi(DocumentResource):
+ document_status_fields = {
+ 'id': fields.String,
+ 'indexing_status': fields.String,
+ 'processing_started_at': TimestampField,
+ 'parsing_completed_at': TimestampField,
+ 'cleaning_completed_at': TimestampField,
+ 'splitting_completed_at': TimestampField,
+ 'completed_at': TimestampField,
+ 'paused_at': TimestampField,
+ 'error': fields.String,
+ 'stopped_at': TimestampField,
+ 'completed_segments': fields.Integer,
+ 'total_segments': fields.Integer,
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ completed_segments = DocumentSegment.query \
+ .filter(DocumentSegment.completed_at.isnot(None),
+ DocumentSegment.document_id == str(document_id)) \
+ .count()
+ total_segments = DocumentSegment.query \
+ .filter_by(document_id=str(document_id)) \
+ .count()
+
+ document.completed_segments = completed_segments
+ document.total_segments = total_segments
+
+ return marshal(document, self.document_status_fields)
+
+
+class DocumentDetailApi(DocumentResource):
+ METADATA_CHOICES = {'all', 'only', 'without'}
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ metadata = request.args.get('metadata', 'all')
+ if metadata not in self.METADATA_CHOICES:
+ raise InvalidMetadataError(f'Invalid metadata value: {metadata}')
+
+ if metadata == 'only':
+ response = {
+ 'id': document.id,
+ 'doc_type': document.doc_type,
+ 'doc_metadata': document.doc_metadata
+ }
+ elif metadata == 'without':
+ process_rules = DatasetService.get_process_rules(dataset_id)
+ data_source_info = document.data_source_detail_dict
+ response = {
+ 'id': document.id,
+ 'position': document.position,
+ 'data_source_type': document.data_source_type,
+ 'data_source_info': data_source_info,
+ 'dataset_process_rule_id': document.dataset_process_rule_id,
+ 'dataset_process_rule': process_rules,
+ 'name': document.name,
+ 'created_from': document.created_from,
+ 'created_by': document.created_by,
+ 'created_at': document.created_at.timestamp(),
+ 'tokens': document.tokens,
+ 'indexing_status': document.indexing_status,
+ 'completed_at': int(document.completed_at.timestamp()) if document.completed_at else None,
+ 'updated_at': int(document.updated_at.timestamp()) if document.updated_at else None,
+ 'indexing_latency': document.indexing_latency,
+ 'error': document.error,
+ 'enabled': document.enabled,
+ 'disabled_at': int(document.disabled_at.timestamp()) if document.disabled_at else None,
+ 'disabled_by': document.disabled_by,
+ 'archived': document.archived,
+ 'segment_count': document.segment_count,
+ 'average_segment_length': document.average_segment_length,
+ 'hit_count': document.hit_count,
+ 'display_status': document.display_status
+ }
+ else:
+ process_rules = DatasetService.get_process_rules(dataset_id)
+ data_source_info = document.data_source_detail_dict_()
+ response = {
+ 'id': document.id,
+ 'position': document.position,
+ 'data_source_type': document.data_source_type,
+ 'data_source_info': data_source_info,
+ 'dataset_process_rule_id': document.dataset_process_rule_id,
+ 'dataset_process_rule': process_rules,
+ 'name': document.name,
+ 'created_from': document.created_from,
+ 'created_by': document.created_by,
+ 'created_at': document.created_at.timestamp(),
+ 'tokens': document.tokens,
+ 'indexing_status': document.indexing_status,
+ 'completed_at': int(document.completed_at.timestamp())if document.completed_at else None,
+ 'updated_at': int(document.updated_at.timestamp()) if document.updated_at else None,
+ 'indexing_latency': document.indexing_latency,
+ 'error': document.error,
+ 'enabled': document.enabled,
+ 'disabled_at': int(document.disabled_at.timestamp()) if document.disabled_at else None,
+ 'disabled_by': document.disabled_by,
+ 'archived': document.archived,
+ 'doc_type': document.doc_type,
+ 'doc_metadata': document.doc_metadata,
+ 'segment_count': document.segment_count,
+ 'average_segment_length': document.average_segment_length,
+ 'hit_count': document.hit_count,
+ 'display_status': document.display_status
+ }
+
+ return response, 200
+
+
+class DocumentProcessingApi(DocumentResource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def patch(self, dataset_id, document_id, action):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ if action == "pause":
+ if document.indexing_status != "indexing":
+ raise InvalidActionError('Document not in indexing state.')
+
+ document.paused_by = current_user.id
+ document.paused_at = datetime.utcnow()
+ document.is_paused = True
+ db.session.commit()
+
+ elif action == "resume":
+ if document.indexing_status not in ["paused", "error"]:
+ raise InvalidActionError('Document not in paused or error state.')
+
+ document.paused_by = None
+ document.paused_at = None
+ document.is_paused = False
+ db.session.commit()
+ else:
+ raise InvalidActionError()
+
+ return {'result': 'success'}, 200
+
+
+class DocumentDeleteApi(DocumentResource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def delete(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ try:
+ DocumentService.delete_document(document)
+ except services.errors.document.DocumentIndexingError:
+ raise DocumentIndexingError('Cannot delete document during indexing.')
+
+ return {'result': 'success'}, 204
+
+
+class DocumentMetadataApi(DocumentResource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def put(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ req_data = request.get_json()
+
+ doc_type = req_data.get('doc_type')
+ doc_metadata = req_data.get('doc_metadata')
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ if doc_type is None or doc_metadata is None:
+ raise ValueError('Both doc_type and doc_metadata must be provided.')
+
+ if doc_type not in DocumentService.DOCUMENT_METADATA_SCHEMA:
+ raise ValueError('Invalid doc_type.')
+
+ if not isinstance(doc_metadata, dict):
+ raise ValueError('doc_metadata must be a dictionary.')
+
+ metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[doc_type]
+
+ document.doc_metadata = {}
+
+ for key, value_type in metadata_schema.items():
+ value = doc_metadata.get(key)
+ if value is not None and isinstance(value, value_type):
+ document.doc_metadata[key] = value
+
+ document.doc_type = doc_type
+ document.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ return {'result': 'success', 'message': 'Document metadata updated.'}, 200
+
+
+class DocumentStatusApi(DocumentResource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def patch(self, dataset_id, document_id, action):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ document = self.get_document(dataset_id, document_id)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ indexing_cache_key = 'document_{}_indexing'.format(document.id)
+ cache_result = redis_client.get(indexing_cache_key)
+ if cache_result is not None:
+ raise InvalidActionError("Document is being indexed, please try again later")
+
+ if action == "enable":
+ if document.enabled:
+ raise InvalidActionError('Document already enabled.')
+
+ document.enabled = True
+ document.disabled_at = None
+ document.disabled_by = None
+ document.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ # Set cache to prevent indexing the same document multiple times
+ redis_client.setex(indexing_cache_key, 600, 1)
+
+ add_document_to_index_task.delay(document_id)
+
+ return {'result': 'success'}, 200
+
+ elif action == "disable":
+ if not document.enabled:
+ raise InvalidActionError('Document already disabled.')
+
+ document.enabled = False
+ document.disabled_at = datetime.utcnow()
+ document.disabled_by = current_user.id
+ document.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ # Set cache to prevent indexing the same document multiple times
+ redis_client.setex(indexing_cache_key, 600, 1)
+
+ remove_document_from_index_task.delay(document_id)
+
+ return {'result': 'success'}, 200
+
+ elif action == "archive":
+ if document.archived:
+ raise InvalidActionError('Document already archived.')
+
+ document.archived = True
+ document.archived_at = datetime.utcnow()
+ document.archived_by = current_user.id
+ document.updated_at = datetime.utcnow()
+ db.session.commit()
+
+ if document.enabled:
+ # Set cache to prevent indexing the same document multiple times
+ redis_client.setex(indexing_cache_key, 600, 1)
+
+ remove_document_from_index_task.delay(document_id)
+
+ return {'result': 'success'}, 200
+ else:
+ raise InvalidActionError()
+
+
+class DocumentPauseApi(DocumentResource):
+ def patch(self, dataset_id, document_id):
+ """pause document."""
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ document = DocumentService.get_document(dataset.id, document_id)
+
+ # 404 if document not found
+ if document is None:
+ raise NotFound("Document Not Exists.")
+
+ # 403 if document is archived
+ if DocumentService.check_archived(document):
+ raise ArchivedDocumentImmutableError()
+
+ try:
+ # pause document
+ DocumentService.pause_document(document)
+ except services.errors.document.DocumentIndexingError:
+ raise DocumentIndexingError('Cannot pause completed document.')
+
+ return {'result': 'success'}, 204
+
+
+class DocumentRecoverApi(DocumentResource):
+ def patch(self, dataset_id, document_id):
+ """recover document."""
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+ document = DocumentService.get_document(dataset.id, document_id)
+
+ # 404 if document not found
+ if document is None:
+ raise NotFound("Document Not Exists.")
+
+ # 403 if document is archived
+ if DocumentService.check_archived(document):
+ raise ArchivedDocumentImmutableError()
+ try:
+ # pause document
+ DocumentService.recover_document(document)
+ except services.errors.document.DocumentIndexingError:
+ raise DocumentIndexingError('Document is not in paused status.')
+
+ return {'result': 'success'}, 204
+
+
+api.add_resource(GetProcessRuleApi, '/datasets/process-rule')
+api.add_resource(DatasetDocumentListApi,
+ '/datasets/<uuid:dataset_id>/documents')
+api.add_resource(DatasetInitApi,
+ '/datasets/init')
+api.add_resource(DocumentIndexingEstimateApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/indexing-estimate')
+api.add_resource(DocumentIndexingStatusApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/indexing-status')
+api.add_resource(DocumentDetailApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>')
+api.add_resource(DocumentProcessingApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/processing/<string:action>')
+api.add_resource(DocumentDeleteApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>')
+api.add_resource(DocumentMetadataApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/metadata')
+api.add_resource(DocumentStatusApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/status/<string:action>')
+api.add_resource(DocumentPauseApi, '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/processing/pause')
+api.add_resource(DocumentRecoverApi, '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/processing/resume')
diff --git a/api/controllers/console/datasets/datasets_segments.py b/api/controllers/console/datasets/datasets_segments.py
new file mode 100644
index 00000000000..2c77a44c97c
--- /dev/null
+++ b/api/controllers/console/datasets/datasets_segments.py
@@ -0,0 +1,203 @@
+# -*- coding:utf-8 -*-
+from datetime import datetime
+
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal
+from werkzeug.exceptions import NotFound, Forbidden
+
+import services
+from controllers.console import api
+from controllers.console.datasets.error import InvalidActionError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DocumentSegment
+
+from libs.helper import TimestampField
+from services.dataset_service import DatasetService, DocumentService
+from tasks.add_segment_to_index_task import add_segment_to_index_task
+from tasks.remove_segment_from_index_task import remove_segment_from_index_task
+
+segment_fields = {
+ 'id': fields.String,
+ 'position': fields.Integer,
+ 'document_id': fields.String,
+ 'content': fields.String,
+ 'word_count': fields.Integer,
+ 'tokens': fields.Integer,
+ 'keywords': fields.List(fields.String),
+ 'index_node_id': fields.String,
+ 'index_node_hash': fields.String,
+ 'hit_count': fields.Integer,
+ 'enabled': fields.Boolean,
+ 'disabled_at': TimestampField,
+ 'disabled_by': fields.String,
+ 'status': fields.String,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+ 'indexing_at': TimestampField,
+ 'completed_at': TimestampField,
+ 'error': fields.String,
+ 'stopped_at': TimestampField
+}
+
+segment_list_response = {
+ 'data': fields.List(fields.Nested(segment_fields)),
+ 'has_more': fields.Boolean,
+ 'limit': fields.Integer
+}
+
+
+class DatasetDocumentSegmentListApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, dataset_id, document_id):
+ dataset_id = str(dataset_id)
+ document_id = str(document_id)
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ document = DocumentService.get_document(dataset_id, document_id)
+
+ if not document:
+ raise NotFound('Document not found.')
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('last_id', type=str, default=None, location='args')
+ parser.add_argument('limit', type=int, default=20, location='args')
+ parser.add_argument('status', type=str,
+ action='append', default=[], location='args')
+ parser.add_argument('hit_count_gte', type=int,
+ default=None, location='args')
+ parser.add_argument('enabled', type=str, default='all', location='args')
+ args = parser.parse_args()
+
+ last_id = args['last_id']
+ limit = min(args['limit'], 100)
+ status_list = args['status']
+ hit_count_gte = args['hit_count_gte']
+
+ query = DocumentSegment.query.filter(
+ DocumentSegment.document_id == str(document_id),
+ DocumentSegment.tenant_id == current_user.current_tenant_id
+ )
+
+ if last_id is not None:
+ last_segment = DocumentSegment.query.get(str(last_id))
+ if last_segment:
+ query = query.filter(
+ DocumentSegment.position > last_segment.position)
+ else:
+ return {'data': [], 'has_more': False, 'limit': limit}, 200
+
+ if status_list:
+ query = query.filter(DocumentSegment.status.in_(status_list))
+
+ if hit_count_gte is not None:
+ query = query.filter(DocumentSegment.hit_count >= hit_count_gte)
+
+ if args['enabled'].lower() != 'all':
+ if args['enabled'].lower() == 'true':
+ query = query.filter(DocumentSegment.enabled == True)
+ elif args['enabled'].lower() == 'false':
+ query = query.filter(DocumentSegment.enabled == False)
+
+ total = query.count()
+ segments = query.order_by(DocumentSegment.position).limit(limit + 1).all()
+
+ has_more = False
+ if len(segments) > limit:
+ has_more = True
+ segments = segments[:-1]
+
+ return {
+ 'data': marshal(segments, segment_fields),
+ 'has_more': has_more,
+ 'limit': limit,
+ 'total': total
+ }, 200
+
+
+class DatasetDocumentSegmentApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def patch(self, dataset_id, segment_id, action):
+ dataset_id = str(dataset_id)
+ dataset = DatasetService.get_dataset(dataset_id)
+ if not dataset:
+ raise NotFound('Dataset not found.')
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ segment = DocumentSegment.query.filter(
+ DocumentSegment.id == str(segment_id),
+ DocumentSegment.tenant_id == current_user.current_tenant_id
+ ).first()
+
+ if not segment:
+ raise NotFound('Segment not found.')
+
+ document_indexing_cache_key = 'document_{}_indexing'.format(segment.document_id)
+ cache_result = redis_client.get(document_indexing_cache_key)
+ if cache_result is not None:
+ raise InvalidActionError("Document is being indexed, please try again later")
+
+ indexing_cache_key = 'segment_{}_indexing'.format(segment.id)
+ cache_result = redis_client.get(indexing_cache_key)
+ if cache_result is not None:
+ raise InvalidActionError("Segment is being indexed, please try again later")
+
+ if action == "enable":
+ if segment.enabled:
+ raise InvalidActionError("Segment is already enabled.")
+
+ segment.enabled = True
+ segment.disabled_at = None
+ segment.disabled_by = None
+ db.session.commit()
+
+ # Set cache to prevent indexing the same segment multiple times
+ redis_client.setex(indexing_cache_key, 600, 1)
+
+ add_segment_to_index_task.delay(segment.id)
+
+ return {'result': 'success'}, 200
+ elif action == "disable":
+ if not segment.enabled:
+ raise InvalidActionError("Segment is already disabled.")
+
+ segment.enabled = False
+ segment.disabled_at = datetime.utcnow()
+ segment.disabled_by = current_user.id
+ db.session.commit()
+
+ # Set cache to prevent indexing the same segment multiple times
+ redis_client.setex(indexing_cache_key, 600, 1)
+
+ remove_segment_from_index_task.delay(segment.id)
+
+ return {'result': 'success'}, 200
+ else:
+ raise InvalidActionError()
+
+
+api.add_resource(DatasetDocumentSegmentListApi,
+ '/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments')
+api.add_resource(DatasetDocumentSegmentApi,
+ '/datasets/<uuid:dataset_id>/segments/<uuid:segment_id>/<string:action>')
diff --git a/api/controllers/console/datasets/error.py b/api/controllers/console/datasets/error.py
new file mode 100644
index 00000000000..014822d5659
--- /dev/null
+++ b/api/controllers/console/datasets/error.py
@@ -0,0 +1,73 @@
+from libs.exception import BaseHTTPException
+
+
+class NoFileUploadedError(BaseHTTPException):
+ error_code = 'no_file_uploaded'
+ description = "No file uploaded."
+ code = 400
+
+
+class TooManyFilesError(BaseHTTPException):
+ error_code = 'too_many_files'
+ description = "Only one file is allowed."
+ code = 400
+
+
+class FileTooLargeError(BaseHTTPException):
+ error_code = 'file_too_large'
+ description = "File size exceeded. {message}"
+ code = 413
+
+
+class UnsupportedFileTypeError(BaseHTTPException):
+ error_code = 'unsupported_file_type'
+ description = "File type not allowed."
+ code = 415
+
+
+class HighQualityDatasetOnlyError(BaseHTTPException):
+ error_code = 'high_quality_dataset_only'
+ description = "High quality dataset only."
+ code = 400
+
+
+class DatasetNotInitializedError(BaseHTTPException):
+ error_code = 'dataset_not_initialized'
+ description = "Dataset not initialized."
+ code = 400
+
+
+class ArchivedDocumentImmutableError(BaseHTTPException):
+ error_code = 'archived_document_immutable'
+ description = "Cannot process an archived document."
+ code = 403
+
+
+class DatasetNameDuplicateError(BaseHTTPException):
+ error_code = 'dataset_name_duplicate'
+ description = "Dataset name already exists."
+ code = 409
+
+
+class InvalidActionError(BaseHTTPException):
+ error_code = 'invalid_action'
+ description = "Invalid action."
+ code = 400
+
+
+class DocumentAlreadyFinishedError(BaseHTTPException):
+ error_code = 'document_already_finished'
+ description = "Document already finished."
+ code = 400
+
+
+class DocumentIndexingError(BaseHTTPException):
+ error_code = 'document_indexing'
+ description = "Document indexing."
+ code = 400
+
+
+class InvalidMetadataError(BaseHTTPException):
+ error_code = 'invalid_metadata'
+ description = "Invalid metadata."
+ code = 400
diff --git a/api/controllers/console/datasets/file.py b/api/controllers/console/datasets/file.py
new file mode 100644
index 00000000000..75aba5e9eb9
--- /dev/null
+++ b/api/controllers/console/datasets/file.py
@@ -0,0 +1,147 @@
+import datetime
+import hashlib
+import tempfile
+import time
+import uuid
+from pathlib import Path
+
+from cachetools import TTLCache
+from flask import request, current_app
+from flask_login import login_required, current_user
+from flask_restful import Resource, marshal_with, fields
+from werkzeug.exceptions import NotFound
+
+from controllers.console import api
+from controllers.console.datasets.error import NoFileUploadedError, TooManyFilesError, FileTooLargeError, \
+ UnsupportedFileTypeError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.index.readers.html_parser import HTMLParser
+from core.index.readers.pdf_parser import PDFParser
+from extensions.ext_storage import storage
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.model import UploadFile
+
+cache = TTLCache(maxsize=None, ttl=30)
+
+FILE_SIZE_LIMIT = 15 * 1024 * 1024 # 15MB
+ALLOWED_EXTENSIONS = ['txt', 'markdown', 'md', 'pdf', 'html', 'htm']
+PREVIEW_WORDS_LIMIT = 3000
+
+
+class FileApi(Resource):
+ file_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'size': fields.Integer,
+ 'extension': fields.String,
+ 'mime_type': fields.String,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(file_fields)
+ def post(self):
+
+ # get file from request
+ file = request.files['file']
+
+ # check file
+ if 'file' not in request.files:
+ raise NoFileUploadedError()
+
+ if len(request.files) > 1:
+ raise TooManyFilesError()
+
+ file_content = file.read()
+ file_size = len(file_content)
+
+ if file_size > FILE_SIZE_LIMIT:
+ message = "({file_size} > {FILE_SIZE_LIMIT})"
+ raise FileTooLargeError(message)
+
+ extension = file.filename.split('.')[-1]
+ if extension not in ALLOWED_EXTENSIONS:
+ raise UnsupportedFileTypeError()
+
+ # user uuid as file name
+ file_uuid = str(uuid.uuid4())
+ file_key = 'upload_files/' + current_user.current_tenant_id + '/' + file_uuid + '.' + extension
+
+ # save file to storage
+ storage.save(file_key, file_content)
+
+ # save file to db
+ config = current_app.config
+ upload_file = UploadFile(
+ tenant_id=current_user.current_tenant_id,
+ storage_type=config['STORAGE_TYPE'],
+ key=file_key,
+ name=file.filename,
+ size=file_size,
+ extension=extension,
+ mime_type=file.mimetype,
+ created_by=current_user.id,
+ created_at=datetime.datetime.utcnow(),
+ used=False,
+ hash=hashlib.sha3_256(file_content).hexdigest()
+ )
+
+ db.session.add(upload_file)
+ db.session.commit()
+
+ return upload_file, 201
+
+
+class FilePreviewApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, file_id):
+ file_id = str(file_id)
+
+ key = file_id + request.path
+ cached_response = cache.get(key)
+ if cached_response and time.time() - cached_response['timestamp'] < cache.ttl:
+ return cached_response['response']
+
+ upload_file = db.session.query(UploadFile) \
+ .filter(UploadFile.id == file_id) \
+ .first()
+
+ if not upload_file:
+ raise NotFound("File not found")
+
+ # extract text from file
+ extension = upload_file.extension
+ if extension not in ALLOWED_EXTENSIONS:
+ raise UnsupportedFileTypeError()
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ suffix = Path(upload_file.key).suffix
+ filepath = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}"
+ storage.download(upload_file.key, filepath)
+
+ if extension == 'pdf':
+ parser = PDFParser({'upload_file': upload_file})
+ text = parser.parse_file(Path(filepath))
+ elif extension in ['html', 'htm']:
+ # Use BeautifulSoup to extract text
+ parser = HTMLParser()
+ text = parser.parse_file(Path(filepath))
+ else:
+ # ['txt', 'markdown', 'md']
+ with open(filepath, "rb") as fp:
+ data = fp.read()
+ text = data.decode(encoding='utf-8').strip() if data else ''
+
+ text = text[0:PREVIEW_WORDS_LIMIT] if text else ''
+ return {'content': text}
+
+
+api.add_resource(FileApi, '/files/upload')
+api.add_resource(FilePreviewApi, '/files/<uuid:file_id>/preview')
diff --git a/api/controllers/console/datasets/hit_testing.py b/api/controllers/console/datasets/hit_testing.py
new file mode 100644
index 00000000000..16bb571df38
--- /dev/null
+++ b/api/controllers/console/datasets/hit_testing.py
@@ -0,0 +1,100 @@
+import logging
+
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, marshal, fields
+from werkzeug.exceptions import InternalServerError, NotFound, Forbidden
+
+import services
+from controllers.console import api
+from controllers.console.datasets.error import HighQualityDatasetOnlyError, DatasetNotInitializedError
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from libs.helper import TimestampField
+from services.dataset_service import DatasetService
+from services.hit_testing_service import HitTestingService
+
+document_fields = {
+ 'id': fields.String,
+ 'data_source_type': fields.String,
+ 'name': fields.String,
+ 'doc_type': fields.String,
+}
+
+segment_fields = {
+ 'id': fields.String,
+ 'position': fields.Integer,
+ 'document_id': fields.String,
+ 'content': fields.String,
+ 'word_count': fields.Integer,
+ 'tokens': fields.Integer,
+ 'keywords': fields.List(fields.String),
+ 'index_node_id': fields.String,
+ 'index_node_hash': fields.String,
+ 'hit_count': fields.Integer,
+ 'enabled': fields.Boolean,
+ 'disabled_at': TimestampField,
+ 'disabled_by': fields.String,
+ 'status': fields.String,
+ 'created_by': fields.String,
+ 'created_at': TimestampField,
+ 'indexing_at': TimestampField,
+ 'completed_at': TimestampField,
+ 'error': fields.String,
+ 'stopped_at': TimestampField,
+ 'document': fields.Nested(document_fields),
+}
+
+hit_testing_record_fields = {
+ 'segment': fields.Nested(segment_fields),
+ 'score': fields.Float,
+ 'tsne_position': fields.Raw
+}
+
+
+class HitTestingApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, dataset_id):
+ dataset_id_str = str(dataset_id)
+
+ dataset = DatasetService.get_dataset(dataset_id_str)
+ if dataset is None:
+ raise NotFound("Dataset not found.")
+
+ try:
+ DatasetService.check_dataset_permission(dataset, current_user)
+ except services.errors.account.NoPermissionError as e:
+ raise Forbidden(str(e))
+
+ # only high quality dataset can be used for hit testing
+ if dataset.indexing_technique != 'high_quality':
+ raise HighQualityDatasetOnlyError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('query', type=str, location='json')
+ args = parser.parse_args()
+
+ query = args['query']
+
+ if not query or len(query) > 250:
+ raise ValueError('Query is required and cannot exceed 250 characters')
+
+ try:
+ response = HitTestingService.retrieve(
+ dataset=dataset,
+ query=query,
+ account=current_user,
+ limit=10,
+ )
+
+ return {"query": response['query'], 'records': marshal(response['records'], hit_testing_record_fields)}
+ except services.errors.index.IndexNotInitializedError:
+ raise DatasetNotInitializedError()
+ except Exception as e:
+ logging.exception("Hit testing failed.")
+ raise InternalServerError(str(e))
+
+
+api.add_resource(HitTestingApi, '/datasets/<uuid:dataset_id>/hit-testing')
diff --git a/api/controllers/console/error.py b/api/controllers/console/error.py
new file mode 100644
index 00000000000..3040423d71f
--- /dev/null
+++ b/api/controllers/console/error.py
@@ -0,0 +1,19 @@
+from libs.exception import BaseHTTPException
+
+
+class AlreadySetupError(BaseHTTPException):
+ error_code = 'already_setup'
+ description = "Application already setup."
+ code = 403
+
+
+class NotSetupError(BaseHTTPException):
+ error_code = 'not_setup'
+ description = "Application not setup."
+ code = 401
+
+
+class AccountNotLinkTenantError(BaseHTTPException):
+ error_code = 'account_not_link_tenant'
+ description = "Account not link tenant."
+ code = 403
diff --git a/api/controllers/console/setup.py b/api/controllers/console/setup.py
new file mode 100644
index 00000000000..4677a2075ba
--- /dev/null
+++ b/api/controllers/console/setup.py
@@ -0,0 +1,93 @@
+# -*- coding:utf-8 -*-
+from functools import wraps
+
+import flask_login
+from flask import request, current_app
+from flask_restful import Resource, reqparse
+
+from extensions.ext_database import db
+from models.model import DifySetup
+from services.account_service import AccountService, TenantService, RegisterService
+
+from libs.helper import email, str_len
+from libs.password import valid_password
+
+from . import api
+from .error import AlreadySetupError, NotSetupError
+from .wraps import only_edition_self_hosted
+
+
+class SetupApi(Resource):
+
+ @only_edition_self_hosted
+ def get(self):
+ setup_status = get_setup_status()
+ if setup_status:
+ return {
+ 'step': 'finished',
+ 'setup_at': setup_status.setup_at.isoformat()
+ }
+ return {'step': 'not_start'}
+
+ @only_edition_self_hosted
+ def post(self):
+ # is set up
+ if get_setup_status():
+ raise AlreadySetupError()
+
+ # is tenant created
+ tenant_count = TenantService.get_tenant_count()
+ if tenant_count > 0:
+ raise AlreadySetupError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('email', type=email,
+ required=True, location='json')
+ parser.add_argument('name', type=str_len(
+ 30), required=True, location='json')
+ parser.add_argument('password', type=valid_password,
+ required=True, location='json')
+ args = parser.parse_args()
+
+ # Register
+ account = RegisterService.register(
+ email=args['email'],
+ name=args['name'],
+ password=args['password']
+ )
+
+ setup()
+
+ # Login
+ flask_login.login_user(account)
+ AccountService.update_last_login(account, request)
+
+ return {'result': 'success'}, 201
+
+
+def setup():
+ dify_setup = DifySetup(
+ version=current_app.config['CURRENT_VERSION']
+ )
+ db.session.add(dify_setup)
+
+
+def setup_required(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ # check setup
+ if not get_setup_status():
+ raise NotSetupError()
+
+ return view(*args, **kwargs)
+
+ return decorated
+
+
+def get_setup_status():
+ if current_app.config['EDITION'] == 'SELF_HOSTED':
+ return DifySetup.query.first()
+ else:
+ return True
+
+api.add_resource(SetupApi, '/setup')
diff --git a/api/controllers/console/version.py b/api/controllers/console/version.py
new file mode 100644
index 00000000000..0e6e75c3614
--- /dev/null
+++ b/api/controllers/console/version.py
@@ -0,0 +1,39 @@
+# -*- coding:utf-8 -*-
+
+import json
+import logging
+
+import requests
+from flask import current_app
+from flask_restful import reqparse, Resource
+from werkzeug.exceptions import InternalServerError
+
+from . import api
+
+
+class VersionApi(Resource):
+
+ def get(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('current_version', type=str, required=True, location='args')
+ args = parser.parse_args()
+ check_update_url = current_app.config['CHECK_UPDATE_URL']
+
+ try:
+ response = requests.get(check_update_url, {
+ 'current_version': args.get('current_version')
+ })
+ except Exception as error:
+ logging.exception("Check update error.")
+ raise InternalServerError()
+
+ content = json.loads(response.content)
+ return {
+ 'version': content['version'],
+ 'release_date': content['releaseDate'],
+ 'release_notes': content['releaseNotes'],
+ 'can_auto_update': content['canAutoUpdate']
+ }
+
+
+api.add_resource(VersionApi, '/version')
diff --git a/api/controllers/console/workspace/__init__.py b/api/controllers/console/workspace/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.py
new file mode 100644
index 00000000000..0890cd04685
--- /dev/null
+++ b/api/controllers/console/workspace/account.py
@@ -0,0 +1,263 @@
+# -*- coding:utf-8 -*-
+from datetime import datetime
+
+import pytz
+from flask import current_app, request
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, fields, marshal_with
+
+from controllers.console import api
+from controllers.console.setup import setup_required
+from controllers.console.workspace.error import AccountAlreadyInitedError, InvalidInvitationCodeError, \
+ RepeatPasswordNotMatchError
+from controllers.console.wraps import account_initialization_required
+from libs.helper import TimestampField, supported_language, timezone
+from extensions.ext_database import db
+from models.account import InvitationCode, AccountIntegrate
+from services.account_service import AccountService
+
+
+account_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'avatar': fields.String,
+ 'email': fields.String,
+ 'interface_language': fields.String,
+ 'interface_theme': fields.String,
+ 'timezone': fields.String,
+ 'last_login_at': TimestampField,
+ 'last_login_ip': fields.String,
+ 'created_at': TimestampField
+}
+
+
+class AccountInitApi(Resource):
+
+ @setup_required
+ @login_required
+ def post(self):
+ account = current_user
+
+ if account.status == 'active':
+ raise AccountAlreadyInitedError()
+
+ parser = reqparse.RequestParser()
+
+ if current_app.config['EDITION'] == 'CLOUD':
+ parser.add_argument('invitation_code', type=str, location='json')
+
+ parser.add_argument(
+ 'interface_language', type=supported_language, required=True, location='json')
+ parser.add_argument('timezone', type=timezone,
+ required=True, location='json')
+ args = parser.parse_args()
+
+ if current_app.config['EDITION'] == 'CLOUD':
+ if not args['invitation_code']:
+ raise ValueError('invitation_code is required')
+
+ # check invitation code
+ invitation_code = db.session.query(InvitationCode).filter(
+ InvitationCode.code == args['invitation_code'],
+ InvitationCode.status == 'unused',
+ ).first()
+
+ if not invitation_code:
+ raise InvalidInvitationCodeError()
+
+ invitation_code.status = 'used'
+ invitation_code.used_at = datetime.utcnow()
+ invitation_code.used_by_tenant_id = account.current_tenant_id
+ invitation_code.used_by_account_id = account.id
+
+ account.interface_language = args['interface_language']
+ account.timezone = args['timezone']
+ account.interface_theme = 'light'
+ account.status = 'active'
+ account.initialized_at = datetime.utcnow()
+ db.session.commit()
+
+ return {'result': 'success'}
+
+
+class AccountProfileApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def get(self):
+ return current_user
+
+
+class AccountNameApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ # Validate account name length
+ if len(args['name']) < 3 or len(args['name']) > 30:
+ raise ValueError(
+ "Account name must be between 3 and 30 characters.")
+
+ updated_account = AccountService.update_account(current_user, name=args['name'])
+
+ return updated_account
+
+
+class AccountAvatarApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('avatar', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ updated_account = AccountService.update_account(current_user, avatar=args['avatar'])
+
+ return updated_account
+
+
+class AccountInterfaceLanguageApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument(
+ 'interface_language', type=supported_language, required=True, location='json')
+ args = parser.parse_args()
+
+ updated_account = AccountService.update_account(current_user, interface_language=args['interface_language'])
+
+ return updated_account
+
+
+class AccountInterfaceThemeApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('interface_theme', type=str, choices=[
+ 'light', 'dark'], required=True, location='json')
+ args = parser.parse_args()
+
+ updated_account = AccountService.update_account(current_user, interface_theme=args['interface_theme'])
+
+ return updated_account
+
+
+class AccountTimezoneApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('timezone', type=str,
+ required=True, location='json')
+ args = parser.parse_args()
+
+ # Validate timezone string, e.g. America/New_York, Asia/Shanghai
+ if args['timezone'] not in pytz.all_timezones:
+ raise ValueError("Invalid timezone string.")
+
+ updated_account = AccountService.update_account(current_user, timezone=args['timezone'])
+
+ return updated_account
+
+
+class AccountPasswordApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_fields)
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('password', type=str,
+ required=False, location='json')
+ parser.add_argument('new_password', type=str,
+ required=True, location='json')
+ parser.add_argument('repeat_new_password', type=str,
+ required=True, location='json')
+ args = parser.parse_args()
+
+ if args['new_password'] != args['repeat_new_password']:
+ raise RepeatPasswordNotMatchError()
+
+ AccountService.update_account_password(
+ current_user, args['password'], args['new_password'])
+
+ return {"result": "success"}
+
+
+class AccountIntegrateApi(Resource):
+ integrate_fields = {
+ 'provider': fields.String,
+ 'created_at': TimestampField,
+ 'is_bound': fields.Boolean,
+ 'link': fields.String
+ }
+
+ integrate_list_fields = {
+ 'data': fields.List(fields.Nested(integrate_fields)),
+ }
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(integrate_list_fields)
+ def get(self):
+ account = current_user
+
+ account_integrates = db.session.query(AccountIntegrate).filter(
+ AccountIntegrate.account_id == account.id).all()
+
+ base_url = request.url_root.rstrip('/')
+ oauth_base_path = "/console/api/oauth/login"
+ providers = ["github", "google"]
+
+ integrate_data = []
+ for provider in providers:
+ existing_integrate = next((ai for ai in account_integrates if ai.provider == provider), None)
+ if existing_integrate:
+ integrate_data.append({
+ 'id': existing_integrate.id,
+ 'provider': provider,
+ 'created_at': existing_integrate.created_at,
+ 'is_bound': True,
+ 'link': None
+ })
+ else:
+ integrate_data.append({
+ 'id': None,
+ 'provider': provider,
+ 'created_at': None,
+ 'is_bound': False,
+ 'link': f'{base_url}{oauth_base_path}/{provider}'
+ })
+
+ return {'data': integrate_data}
+
+
+# Register API resources
+api.add_resource(AccountInitApi, '/account/init')
+api.add_resource(AccountProfileApi, '/account/profile')
+api.add_resource(AccountNameApi, '/account/name')
+api.add_resource(AccountAvatarApi, '/account/avatar')
+api.add_resource(AccountInterfaceLanguageApi, '/account/interface-language')
+api.add_resource(AccountInterfaceThemeApi, '/account/interface-theme')
+api.add_resource(AccountTimezoneApi, '/account/timezone')
+api.add_resource(AccountPasswordApi, '/account/password')
+api.add_resource(AccountIntegrateApi, '/account/integrates')
+# api.add_resource(AccountEmailApi, '/account/email')
+# api.add_resource(AccountEmailVerifyApi, '/account/email-verify')
diff --git a/api/controllers/console/workspace/error.py b/api/controllers/console/workspace/error.py
new file mode 100644
index 00000000000..c5e3a3fb6ae
--- /dev/null
+++ b/api/controllers/console/workspace/error.py
@@ -0,0 +1,31 @@
+from libs.exception import BaseHTTPException
+
+
+class RepeatPasswordNotMatchError(BaseHTTPException):
+ error_code = 'repeat_password_not_match'
+ description = "New password and repeat password does not match."
+ code = 400
+
+
+class ProviderRequestFailedError(BaseHTTPException):
+ error_code = 'provider_request_failed'
+ description = None
+ code = 400
+
+
+class InvalidInvitationCodeError(BaseHTTPException):
+ error_code = 'invalid_invitation_code'
+ description = "Invalid invitation code."
+ code = 400
+
+
+class AccountAlreadyInitedError(BaseHTTPException):
+ error_code = 'account_already_inited'
+ description = "Account already inited."
+ code = 400
+
+
+class AccountNotInitializedError(BaseHTTPException):
+ error_code = 'account_not_initialized'
+ description = "Account not initialized."
+ code = 400
diff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.py
new file mode 100644
index 00000000000..e0fc2bc19f0
--- /dev/null
+++ b/api/controllers/console/workspace/members.py
@@ -0,0 +1,141 @@
+# -*- coding:utf-8 -*-
+
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, marshal_with, abort, fields, marshal
+
+import services
+from controllers.console import api
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.account import Account, TenantAccountJoin
+from services.account_service import TenantService, RegisterService
+
+account_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'avatar': fields.String,
+ 'email': fields.String,
+ 'last_login_at': TimestampField,
+ 'created_at': TimestampField,
+ 'role': fields.String,
+ 'status': fields.String,
+}
+
+account_list_fields = {
+ 'accounts': fields.List(fields.Nested(account_fields))
+}
+
+
+class MemberListApi(Resource):
+ """List all members of current tenant."""
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(account_list_fields)
+ def get(self):
+ members = TenantService.get_tenant_members(current_user.current_tenant)
+ return {'result': 'success', 'accounts': members}, 200
+
+
+class MemberInviteEmailApi(Resource):
+ """Invite a new member by email."""
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('email', type=str, required=True, location='json')
+ parser.add_argument('role', type=str, required=True, default='admin', location='json')
+ args = parser.parse_args()
+
+ invitee_email = args['email']
+ invitee_role = args['role']
+ if invitee_role not in ['admin', 'normal']:
+ return {'code': 'invalid-role', 'message': 'Invalid role'}, 400
+
+ inviter = current_user
+
+ try:
+ RegisterService.invite_new_member(inviter.current_tenant, invitee_email, role=invitee_role, inviter=inviter)
+ account = db.session.query(Account, TenantAccountJoin.role).join(
+ TenantAccountJoin, Account.id == TenantAccountJoin.account_id
+ ).filter(Account.email == args['email']).first()
+ account, role = account
+ account = marshal(account, account_fields)
+ account['role'] = role
+ except services.errors.account.CannotOperateSelfError as e:
+ return {'code': 'cannot-operate-self', 'message': str(e)}, 400
+ except services.errors.account.NoPermissionError as e:
+ return {'code': 'forbidden', 'message': str(e)}, 403
+ except services.errors.account.AccountAlreadyInTenantError as e:
+ return {'code': 'email-taken', 'message': str(e)}, 409
+ except Exception as e:
+ return {'code': 'unexpected-error', 'message': str(e)}, 500
+
+ # todo:413
+
+ return {'result': 'success', 'account': account}, 201
+
+
+class MemberCancelInviteApi(Resource):
+ """Cancel an invitation by member id."""
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def delete(self, member_id):
+ member = Account.query.get(str(member_id))
+ if not member:
+ abort(404)
+
+ try:
+ TenantService.remove_member_from_tenant(current_user.current_tenant, member, current_user)
+ except services.errors.account.CannotOperateSelfError as e:
+ return {'code': 'cannot-operate-self', 'message': str(e)}, 400
+ except services.errors.account.NoPermissionError as e:
+ return {'code': 'forbidden', 'message': str(e)}, 403
+ except services.errors.account.MemberNotInTenantError as e:
+ return {'code': 'member-not-found', 'message': str(e)}, 404
+ except Exception as e:
+ raise ValueError(str(e))
+
+ return {'result': 'success'}, 204
+
+
+class MemberUpdateRoleApi(Resource):
+ """Update member role."""
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def put(self, member_id):
+ parser = reqparse.RequestParser()
+ parser.add_argument('role', type=str, required=True, location='json')
+ args = parser.parse_args()
+ new_role = args['role']
+
+ if new_role not in ['admin', 'normal', 'owner']:
+ return {'code': 'invalid-role', 'message': 'Invalid role'}, 400
+
+ member = Account.query.get(str(member_id))
+ if not member:
+ abort(404)
+
+ try:
+ TenantService.update_member_role(current_user.current_tenant, member, new_role, current_user)
+ except Exception as e:
+ raise ValueError(str(e))
+
+ # todo: 403
+
+ return {'result': 'success'}
+
+
+api.add_resource(MemberListApi, '/workspaces/current/members')
+api.add_resource(MemberInviteEmailApi, '/workspaces/current/members/invite-email')
+api.add_resource(MemberCancelInviteApi, '/workspaces/current/members/<uuid:member_id>')
+api.add_resource(MemberUpdateRoleApi, '/workspaces/current/members/<uuid:member_id>/update-role')
diff --git a/api/controllers/console/workspace/providers.py b/api/controllers/console/workspace/providers.py
new file mode 100644
index 00000000000..bc6b8320afb
--- /dev/null
+++ b/api/controllers/console/workspace/providers.py
@@ -0,0 +1,246 @@
+# -*- coding:utf-8 -*-
+import base64
+import json
+import logging
+
+from flask_login import login_required, current_user
+from flask_restful import Resource, reqparse, abort
+from werkzeug.exceptions import Forbidden
+
+from controllers.console import api
+from controllers.console.setup import setup_required
+from controllers.console.wraps import account_initialization_required
+from core.llm.provider.errors import ValidateFailedError
+from extensions.ext_database import db
+from libs import rsa
+from models.provider import Provider, ProviderType, ProviderName
+from services.provider_service import ProviderService
+
+
+class ProviderListApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self):
+ tenant_id = current_user.current_tenant_id
+
+ """
+ If the type is AZURE_OPENAI, decode and return the four fields of azure_api_type, azure_api_version:,
+ azure_api_base, azure_api_key as an object, where azure_api_key displays the first 6 bits in plaintext, and the
+ rest is replaced by * and the last two bits are displayed in plaintext
+
+ If the type is other, decode and return the Token field directly, the field displays the first 6 bits in
+ plaintext, the rest is replaced by * and the last two bits are displayed in plaintext
+ """
+
+ ProviderService.init_supported_provider(current_user.current_tenant, "cloud")
+ providers = Provider.query.filter_by(tenant_id=tenant_id).all()
+
+ provider_list = [
+ {
+ 'provider_name': p.provider_name,
+ 'provider_type': p.provider_type,
+ 'is_valid': p.is_valid,
+ 'last_used': p.last_used,
+ 'is_enabled': p.is_enabled,
+ **({
+ 'quota_type': p.quota_type,
+ 'quota_limit': p.quota_limit,
+ 'quota_used': p.quota_used
+ } if p.provider_type == ProviderType.SYSTEM.value else {}),
+ 'token': ProviderService.get_obfuscated_api_key(current_user.current_tenant,
+ ProviderName(p.provider_name))
+ }
+ for p in providers
+ ]
+
+ return provider_list
+
+
+class ProviderTokenApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, provider):
+ if provider not in [p.value for p in ProviderName]:
+ abort(404)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ logging.log(logging.ERROR,
+ f'User {current_user.id} is not authorized to update provider token, current_role is {current_user.current_tenant.current_role}')
+ raise Forbidden()
+
+ parser = reqparse.RequestParser()
+
+ parser.add_argument('token', type=ProviderService.get_token_type(
+ tenant=current_user.current_tenant,
+ provider_name=ProviderName(provider)
+ ), required=True, nullable=False, location='json')
+
+ args = parser.parse_args()
+
+ if not args['token']:
+ raise ValueError('Token is empty')
+
+ try:
+ ProviderService.validate_provider_configs(
+ tenant=current_user.current_tenant,
+ provider_name=ProviderName(provider),
+ configs=args['token']
+ )
+ token_is_valid = True
+ except ValidateFailedError:
+ token_is_valid = False
+
+ tenant = current_user.current_tenant
+
+ base64_encrypted_token = ProviderService.get_encrypted_token(
+ tenant=current_user.current_tenant,
+ provider_name=ProviderName(provider),
+ configs=args['token']
+ )
+
+ provider_model = Provider.query.filter_by(tenant_id=tenant.id, provider_name=provider,
+ provider_type=ProviderType.CUSTOM.value).first()
+
+ # Only allow updating token for CUSTOM provider type
+ if provider_model:
+ provider_model.encrypted_config = base64_encrypted_token
+ provider_model.is_valid = token_is_valid
+ else:
+ provider_model = Provider(tenant_id=tenant.id, provider_name=provider,
+ provider_type=ProviderType.CUSTOM.value,
+ encrypted_config=base64_encrypted_token,
+ is_valid=token_is_valid)
+ db.session.add(provider_model)
+
+ db.session.commit()
+
+ if provider in [ProviderName.ANTHROPIC.value, ProviderName.AZURE_OPENAI.value, ProviderName.COHERE.value,
+ ProviderName.HUGGINGFACEHUB.value]:
+ return {'result': 'success', 'warning': 'MOCK: This provider is not supported yet.'}, 201
+
+ return {'result': 'success'}, 201
+
+
+class ProviderTokenValidateApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self, provider):
+ if provider not in [p.value for p in ProviderName]:
+ abort(404)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('token', type=ProviderService.get_token_type(
+ tenant=current_user.current_tenant,
+ provider_name=ProviderName(provider)
+ ), required=True, nullable=False, location='json')
+ args = parser.parse_args()
+
+ # todo: remove this when the provider is supported
+ if provider in [ProviderName.ANTHROPIC.value, ProviderName.AZURE_OPENAI.value, ProviderName.COHERE.value,
+ ProviderName.HUGGINGFACEHUB.value]:
+ return {'result': 'success', 'warning': 'MOCK: This provider is not supported yet.'}
+
+ result = True
+ error = None
+
+ try:
+ ProviderService.validate_provider_configs(
+ tenant=current_user.current_tenant,
+ provider_name=ProviderName(provider),
+ configs=args['token']
+ )
+ except ValidateFailedError as e:
+ result = False
+ error = str(e)
+
+ response = {'result': 'success' if result else 'error'}
+
+ if not result:
+ response['error'] = error
+
+ return response
+
+
+class ProviderSystemApi(Resource):
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def put(self, provider):
+ if provider not in [p.value for p in ProviderName]:
+ abort(404)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('is_enabled', type=bool, required=True, location='json')
+ args = parser.parse_args()
+
+ tenant = current_user.current_tenant_id
+
+ provider_model = Provider.query.filter_by(tenant_id=tenant.id, provider_name=provider).first()
+
+ if provider_model and provider_model.provider_type == ProviderType.SYSTEM.value:
+ provider_model.is_valid = args['is_enabled']
+ db.session.commit()
+ elif not provider_model:
+ ProviderService.create_system_provider(tenant, provider, args['is_enabled'])
+ else:
+ abort(403)
+
+ return {'result': 'success'}
+
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self, provider):
+ if provider not in [p.value for p in ProviderName]:
+ abort(404)
+
+ # The role of the current user in the ta table must be admin or owner
+ if current_user.current_tenant.current_role not in ['admin', 'owner']:
+ raise Forbidden()
+
+ provider_model = db.session.query(Provider).filter(Provider.tenant_id == current_user.current_tenant_id,
+ Provider.provider_name == provider,
+ Provider.provider_type == ProviderType.SYSTEM.value).first()
+
+ system_model = None
+ if provider_model:
+ system_model = {
+ 'result': 'success',
+ 'provider': {
+ 'provider_name': provider_model.provider_name,
+ 'provider_type': provider_model.provider_type,
+ 'is_valid': provider_model.is_valid,
+ 'last_used': provider_model.last_used,
+ 'is_enabled': provider_model.is_enabled,
+ 'quota_type': provider_model.quota_type,
+ 'quota_limit': provider_model.quota_limit,
+ 'quota_used': provider_model.quota_used
+ }
+ }
+ else:
+ abort(404)
+
+ return system_model
+
+
+api.add_resource(ProviderTokenApi, '/providers/<provider>/token',
+ endpoint='current_providers_token') # Deprecated
+api.add_resource(ProviderTokenValidateApi, '/providers/<provider>/token-validate',
+ endpoint='current_providers_token_validate') # Deprecated
+
+api.add_resource(ProviderTokenApi, '/workspaces/current/providers/<provider>/token',
+ endpoint='workspaces_current_providers_token') # PUT for updating provider token
+api.add_resource(ProviderTokenValidateApi, '/workspaces/current/providers/<provider>/token-validate',
+ endpoint='workspaces_current_providers_token_validate') # POST for validating provider token
+
+api.add_resource(ProviderListApi, '/workspaces/current/providers') # GET for getting providers list
+api.add_resource(ProviderSystemApi, '/workspaces/current/providers/<provider>/system',
+ endpoint='workspaces_current_providers_system') # GET for getting provider quota, PUT for updating provider status
diff --git a/api/controllers/console/workspace/workspace.py b/api/controllers/console/workspace/workspace.py
new file mode 100644
index 00000000000..2ad457c79b2
--- /dev/null
+++ b/api/controllers/console/workspace/workspace.py
@@ -0,0 +1,97 @@
+# -*- coding:utf-8 -*-
+import logging
+
+from flask import request
+from flask_login import login_required, current_user
+from flask_restful import Resource, fields, marshal_with, reqparse, marshal
+
+from controllers.console import api
+from controllers.console.setup import setup_required
+from controllers.console.error import AccountNotLinkTenantError
+from controllers.console.wraps import account_initialization_required
+from libs.helper import TimestampField
+from extensions.ext_database import db
+from models.account import Tenant
+from services.account_service import TenantService
+from services.workspace_service import WorkspaceService
+
+provider_fields = {
+ 'provider_name': fields.String,
+ 'provider_type': fields.String,
+ 'is_valid': fields.Boolean,
+ 'token_is_set': fields.Boolean,
+}
+
+tenant_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'plan': fields.String,
+ 'status': fields.String,
+ 'created_at': TimestampField,
+ 'role': fields.String,
+ 'providers': fields.List(fields.Nested(provider_fields)),
+ 'in_trail': fields.Boolean,
+ 'trial_end_reason': fields.String,
+}
+
+tenants_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'plan': fields.String,
+ 'status': fields.String,
+ 'created_at': TimestampField,
+ 'current': fields.Boolean
+}
+
+
+class TenantListApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def get(self):
+ tenants = TenantService.get_join_tenants(current_user)
+
+ for tenant in tenants:
+ if tenant.id == current_user.current_tenant_id:
+ tenant.current = True # Set current=True for current tenant
+ return {'workspaces': marshal(tenants, tenants_fields)}, 200
+
+
+class TenantApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @marshal_with(tenant_fields)
+ def get(self):
+ if request.path == '/info':
+ logging.warning('Deprecated URL /info was used.')
+
+ tenant = current_user.current_tenant
+
+ return WorkspaceService.get_tenant_info(tenant), 200
+
+
+class SwitchWorkspaceApi(Resource):
+ @setup_required
+ @login_required
+ @account_initialization_required
+ def post(self):
+ parser = reqparse.RequestParser()
+ parser.add_argument('tenant_id', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ # check if tenant_id is valid, 403 if not
+ try:
+ TenantService.switch_tenant(current_user, args['tenant_id'])
+ except Exception:
+ raise AccountNotLinkTenantError("Account not link tenant")
+
+ new_tenant = db.session.query(Tenant).get(args['tenant_id']) # Get new tenant
+
+ return {'result': 'success', 'new_tenant': marshal(WorkspaceService.get_tenant_info(new_tenant), tenant_fields)}
+
+
+api.add_resource(TenantListApi, '/workspaces') # GET for getting all tenants
+api.add_resource(TenantApi, '/workspaces/current', endpoint='workspaces_current') # GET for getting current tenant info
+api.add_resource(TenantApi, '/info', endpoint='info') # Deprecated
+api.add_resource(SwitchWorkspaceApi, '/workspaces/switch') # POST for switching tenant
diff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.py
new file mode 100644
index 00000000000..41ce4f200bd
--- /dev/null
+++ b/api/controllers/console/wraps.py
@@ -0,0 +1,43 @@
+# -*- coding:utf-8 -*-
+from functools import wraps
+
+from flask import current_app, abort
+from flask_login import current_user
+
+from controllers.console.workspace.error import AccountNotInitializedError
+
+
+def account_initialization_required(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ # check account initialization
+ account = current_user
+
+ if account.status == 'uninitialized':
+ raise AccountNotInitializedError()
+
+ return view(*args, **kwargs)
+
+ return decorated
+
+
+def only_edition_cloud(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ if current_app.config['EDITION'] != 'CLOUD':
+ abort(404)
+
+ return view(*args, **kwargs)
+
+ return decorated
+
+
+def only_edition_self_hosted(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ if current_app.config['EDITION'] != 'SELF_HOSTED':
+ abort(404)
+
+ return view(*args, **kwargs)
+
+ return decorated
diff --git a/api/controllers/service_api/__init__.py b/api/controllers/service_api/__init__.py
new file mode 100644
index 00000000000..05318a20763
--- /dev/null
+++ b/api/controllers/service_api/__init__.py
@@ -0,0 +1,12 @@
+# -*- coding:utf-8 -*-
+from flask import Blueprint
+
+from libs.external_api import ExternalApi
+
+bp = Blueprint('service_api', __name__, url_prefix='/v1')
+api = ExternalApi(bp)
+
+
+from .app import completion, app, conversation, message
+
+from .dataset import document
diff --git a/api/controllers/service_api/app/__init__.py b/api/controllers/service_api/app/__init__.py
new file mode 100644
index 00000000000..d8018ee3857
--- /dev/null
+++ b/api/controllers/service_api/app/__init__.py
@@ -0,0 +1,27 @@
+from extensions.ext_database import db
+from models.model import EndUser
+
+
+def create_or_update_end_user_for_user_id(app_model, user_id):
+ """
+ Create or update session terminal based on user ID.
+ """
+ end_user = db.session.query(EndUser) \
+ .filter(
+ EndUser.tenant_id == app_model.tenant_id,
+ EndUser.session_id == user_id,
+ EndUser.type == 'service_api'
+ ).first()
+
+ if end_user is None:
+ end_user = EndUser(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ type='service_api',
+ is_anonymous=True,
+ session_id=user_id
+ )
+ db.session.add(end_user)
+ db.session.commit()
+
+ return end_user
diff --git a/api/controllers/service_api/app/app.py b/api/controllers/service_api/app/app.py
new file mode 100644
index 00000000000..08532441c83
--- /dev/null
+++ b/api/controllers/service_api/app/app.py
@@ -0,0 +1,43 @@
+# -*- coding:utf-8 -*-
+from flask_restful import fields, marshal_with
+
+from controllers.service_api import api
+from controllers.service_api.wraps import AppApiResource
+
+
+class AppParameterApi(AppApiResource):
+ """Resource for app variables."""
+
+ variable_fields = {
+ 'key': fields.String,
+ 'name': fields.String,
+ 'description': fields.String,
+ 'type': fields.String,
+ 'default': fields.String,
+ 'max_length': fields.Integer,
+ 'options': fields.List(fields.String)
+ }
+
+ parameters_fields = {
+ 'opening_statement': fields.String,
+ 'suggested_questions': fields.Raw,
+ 'suggested_questions_after_answer': fields.Raw,
+ 'more_like_this': fields.Raw,
+ 'user_input_form': fields.Raw,
+ }
+
+ @marshal_with(parameters_fields)
+ def get(self, app_model, end_user):
+ """Retrieve app parameters."""
+ app_model_config = app_model.app_model_config
+
+ return {
+ 'opening_statement': app_model_config.opening_statement,
+ 'suggested_questions': app_model_config.suggested_questions_list,
+ 'suggested_questions_after_answer': app_model_config.suggested_questions_after_answer_dict,
+ 'more_like_this': app_model_config.more_like_this_dict,
+ 'user_input_form': app_model_config.user_input_form_list
+ }
+
+
+api.add_resource(AppParameterApi, '/parameters')
diff --git a/api/controllers/service_api/app/completion.py b/api/controllers/service_api/app/completion.py
new file mode 100644
index 00000000000..e5eb4153aa8
--- /dev/null
+++ b/api/controllers/service_api/app/completion.py
@@ -0,0 +1,182 @@
+import json
+import logging
+from typing import Union, Generator
+
+from flask import stream_with_context, Response
+from flask_restful import reqparse
+from werkzeug.exceptions import NotFound, InternalServerError
+
+import services
+from controllers.service_api import api
+from controllers.service_api.app import create_or_update_end_user_for_user_id
+from controllers.service_api.app.error import AppUnavailableError, ProviderNotInitializeError, NotChatAppError, \
+ ConversationCompletedError, CompletionRequestError, ProviderQuotaExceededError, \
+ ProviderModelCurrentlyNotSupportError
+from controllers.service_api.wraps import AppApiResource
+from core.conversation_message_task import PubHandler
+from core.llm.error import LLMBadRequestError, LLMAuthorizationError, LLMAPIUnavailableError, LLMAPIConnectionError, \
+ LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError, ModelCurrentlyNotSupportError
+from libs.helper import uuid_value
+from services.completion_service import CompletionService
+
+
+class CompletionApi(AppApiResource):
+ def post(self, app_model, end_user):
+ if app_model.mode != 'completion':
+ raise AppUnavailableError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, location='json')
+ parser.add_argument('response_mode', type=str, choices=['blocking', 'streaming'], location='json')
+ parser.add_argument('user', type=str, location='json')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=end_user,
+ args=args,
+ from_source='api',
+ streaming=streaming
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+class CompletionStopApi(AppApiResource):
+ def post(self, app_model, end_user, task_id):
+ if app_model.mode != 'completion':
+ raise AppUnavailableError()
+
+ PubHandler.stop(end_user, task_id)
+
+ return {'result': 'success'}, 200
+
+
+class ChatApi(AppApiResource):
+ def post(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, required=True, location='json')
+ parser.add_argument('response_mode', type=str, choices=['blocking', 'streaming'], location='json')
+ parser.add_argument('conversation_id', type=uuid_value, location='json')
+ parser.add_argument('user', type=str, location='json')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=end_user,
+ args=args,
+ from_source='api',
+ streaming=streaming
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+class ChatStopApi(AppApiResource):
+ def post(self, app_model, end_user, task_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ PubHandler.stop(end_user, task_id)
+
+ return {'result': 'success'}, 200
+
+
+def compact_response(response: Union[dict | Generator]) -> Response:
+ if isinstance(response, dict):
+ return Response(response=json.dumps(response), status=200, mimetype='application/json')
+ else:
+ def generate() -> Generator:
+ try:
+ for chunk in response:
+ yield chunk
+ except services.errors.conversation.ConversationNotExistsError:
+ yield "data: " + json.dumps(api.handle_error(NotFound("Conversation Not Exists.")).get_json()) + "\n\n"
+ except services.errors.conversation.ConversationCompletedError:
+ yield "data: " + json.dumps(api.handle_error(ConversationCompletedError()).get_json()) + "\n\n"
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ yield "data: " + json.dumps(api.handle_error(AppUnavailableError()).get_json()) + "\n\n"
+ except ProviderTokenNotInitError:
+ yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError()).get_json()) + "\n\n"
+ except QuotaExceededError:
+ yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
+ except ModelCurrentlyNotSupportError:
+ yield "data: " + json.dumps(api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
+ except ValueError as e:
+ yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
+ except Exception:
+ logging.exception("internal server error.")
+ yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
+
+ return Response(stream_with_context(generate()), status=200,
+ mimetype='text/event-stream')
+
+
+api.add_resource(CompletionApi, '/completion-messages')
+api.add_resource(CompletionStopApi, '/completion-messages/<string:task_id>/stop')
+api.add_resource(ChatApi, '/chat-messages')
+api.add_resource(ChatStopApi, '/chat-messages/<string:task_id>/stop')
+
diff --git a/api/controllers/service_api/app/conversation.py b/api/controllers/service_api/app/conversation.py
new file mode 100644
index 00000000000..602ac8d7850
--- /dev/null
+++ b/api/controllers/service_api/app/conversation.py
@@ -0,0 +1,76 @@
+# -*- coding:utf-8 -*-
+from flask_restful import fields, marshal_with, reqparse
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import NotFound
+
+from controllers.service_api import api
+from controllers.service_api.app import create_or_update_end_user_for_user_id
+from controllers.service_api.app.error import NotChatAppError
+from controllers.service_api.wraps import AppApiResource
+from libs.helper import TimestampField, uuid_value
+import services
+from services.conversation_service import ConversationService
+
+conversation_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'inputs': fields.Raw,
+ 'status': fields.String,
+ 'introduction': fields.String,
+ 'created_at': TimestampField
+}
+
+conversation_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(conversation_fields))
+}
+
+
+class ConversationApi(AppApiResource):
+
+ @marshal_with(conversation_infinite_scroll_pagination_fields)
+ def get(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('last_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ parser.add_argument('user', type=str, location='args')
+ args = parser.parse_args()
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ return ConversationService.pagination_by_last_id(app_model, end_user, args['last_id'], args['limit'])
+ except services.errors.conversation.LastConversationNotExistsError:
+ raise NotFound("Last Conversation Not Exists.")
+
+
+class ConversationRenameApi(AppApiResource):
+
+ @marshal_with(conversation_fields)
+ def post(self, app_model, end_user, c_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ conversation_id = str(c_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, location='json')
+ parser.add_argument('user', type=str, location='json')
+ args = parser.parse_args()
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ return ConversationService.rename(app_model, conversation_id, end_user, args['name'])
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+
+
+api.add_resource(ConversationRenameApi, '/conversations/<uuid:c_id>/name', endpoint='conversation_name')
+api.add_resource(ConversationApi, '/conversations')
diff --git a/api/controllers/service_api/app/error.py b/api/controllers/service_api/app/error.py
new file mode 100644
index 00000000000..c59f570efd0
--- /dev/null
+++ b/api/controllers/service_api/app/error.py
@@ -0,0 +1,51 @@
+# -*- coding:utf-8 -*-
+from libs.exception import BaseHTTPException
+
+
+class AppUnavailableError(BaseHTTPException):
+ error_code = 'app_unavailable'
+ description = "App unavailable."
+ code = 400
+
+
+class NotCompletionAppError(BaseHTTPException):
+ error_code = 'not_completion_app'
+ description = "Not Completion App"
+ code = 400
+
+
+class NotChatAppError(BaseHTTPException):
+ error_code = 'not_chat_app'
+ description = "Not Chat App"
+ code = 400
+
+
+class ConversationCompletedError(BaseHTTPException):
+ error_code = 'conversation_completed'
+ description = "Conversation Completed."
+ code = 400
+
+
+class ProviderNotInitializeError(BaseHTTPException):
+ error_code = 'provider_not_initialize'
+ description = "Provider Token not initialize."
+ code = 400
+
+
+class ProviderQuotaExceededError(BaseHTTPException):
+ error_code = 'provider_quota_exceeded'
+ description = "Provider quota exceeded."
+ code = 400
+
+
+class ProviderModelCurrentlyNotSupportError(BaseHTTPException):
+ error_code = 'model_currently_not_support'
+ description = "GPT-4 currently not support."
+ code = 400
+
+
+class CompletionRequestError(BaseHTTPException):
+ error_code = 'completion_request_error'
+ description = "Completion request failed."
+ code = 400
+
diff --git a/api/controllers/service_api/app/message.py b/api/controllers/service_api/app/message.py
new file mode 100644
index 00000000000..ef020891ff0
--- /dev/null
+++ b/api/controllers/service_api/app/message.py
@@ -0,0 +1,81 @@
+# -*- coding:utf-8 -*-
+from flask_restful import fields, marshal_with, reqparse
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import NotFound
+
+import services
+from controllers.service_api import api
+from controllers.service_api.app import create_or_update_end_user_for_user_id
+from controllers.service_api.app.error import NotChatAppError
+from controllers.service_api.wraps import AppApiResource
+from libs.helper import TimestampField, uuid_value
+from services.message_service import MessageService
+
+
+class MessageListApi(AppApiResource):
+ feedback_fields = {
+ 'rating': fields.String
+ }
+
+ message_fields = {
+ 'id': fields.String,
+ 'conversation_id': fields.String,
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'answer': fields.String,
+ 'feedback': fields.Nested(feedback_fields, attribute='user_feedback', allow_null=True),
+ 'created_at': TimestampField
+ }
+
+ message_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(message_fields))
+ }
+
+ @marshal_with(message_infinite_scroll_pagination_fields)
+ def get(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('conversation_id', required=True, type=uuid_value, location='args')
+ parser.add_argument('first_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ parser.add_argument('user', type=str, location='args')
+ args = parser.parse_args()
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ return MessageService.pagination_by_first_id(app_model, end_user,
+ args['conversation_id'], args['first_id'], args['limit'])
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.message.FirstMessageNotExistsError:
+ raise NotFound("First Message Not Exists.")
+
+
+class MessageFeedbackApi(AppApiResource):
+ def post(self, app_model, end_user, message_id):
+ message_id = str(message_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
+ parser.add_argument('user', type=str, location='json')
+ args = parser.parse_args()
+
+ if end_user is None and args['user'] is not None:
+ end_user = create_or_update_end_user_for_user_id(app_model, args['user'])
+
+ try:
+ MessageService.create_feedback(app_model, message_id, end_user, args['rating'])
+ except services.errors.message.MessageNotExistsError:
+ raise NotFound("Message Not Exists.")
+
+ return {'result': 'success'}
+
+
+api.add_resource(MessageListApi, '/messages')
+api.add_resource(MessageFeedbackApi, '/messages/<uuid:message_id>/feedbacks')
diff --git a/api/controllers/service_api/dataset/__init__.py b/api/controllers/service_api/dataset/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/controllers/service_api/dataset/document.py b/api/controllers/service_api/dataset/document.py
new file mode 100644
index 00000000000..47a90756db0
--- /dev/null
+++ b/api/controllers/service_api/dataset/document.py
@@ -0,0 +1,129 @@
+import datetime
+import uuid
+
+from flask import current_app
+from flask_restful import reqparse
+from werkzeug.exceptions import NotFound
+
+import services.dataset_service
+from controllers.service_api import api
+from controllers.service_api.app.error import ProviderNotInitializeError
+from controllers.service_api.dataset.error import ArchivedDocumentImmutableError, DocumentIndexingError, \
+ DatasetNotInitedError
+from controllers.service_api.wraps import DatasetApiResource
+from core.llm.error import ProviderTokenNotInitError
+from extensions.ext_database import db
+from extensions.ext_storage import storage
+from models.model import UploadFile
+from services.dataset_service import DocumentService
+
+
+class DocumentListApi(DatasetApiResource):
+ """Resource for documents."""
+
+ def post(self, dataset):
+ """Create document."""
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, nullable=False, location='json')
+ parser.add_argument('text', type=str, required=True, nullable=False, location='json')
+ parser.add_argument('doc_type', type=str, location='json')
+ parser.add_argument('doc_metadata', type=dict, location='json')
+ args = parser.parse_args()
+
+ if not dataset.indexing_technique:
+ raise DatasetNotInitedError("Dataset indexing technique must be set.")
+
+ doc_type = args.get('doc_type')
+ doc_metadata = args.get('doc_metadata')
+
+ if doc_type and doc_type not in DocumentService.DOCUMENT_METADATA_SCHEMA:
+ raise ValueError('Invalid doc_type.')
+
+ # user uuid as file name
+ file_uuid = str(uuid.uuid4())
+ file_key = 'upload_files/' + dataset.tenant_id + '/' + file_uuid + '.txt'
+
+ # save file to storage
+ storage.save(file_key, args.get('text'))
+
+ # save file to db
+ config = current_app.config
+ upload_file = UploadFile(
+ tenant_id=dataset.tenant_id,
+ storage_type=config['STORAGE_TYPE'],
+ key=file_key,
+ name=args.get('name') + '.txt',
+ size=len(args.get('text')),
+ extension='txt',
+ mime_type='text/plain',
+ created_by=dataset.created_by,
+ created_at=datetime.datetime.utcnow(),
+ used=True,
+ used_by=dataset.created_by,
+ used_at=datetime.datetime.utcnow()
+ )
+
+ db.session.add(upload_file)
+ db.session.commit()
+
+ document_data = {
+ 'data_source': {
+ 'type': 'upload_file',
+ 'info': upload_file.id
+ }
+ }
+
+ try:
+ document = DocumentService.save_document_with_dataset_id(
+ dataset=dataset,
+ document_data=document_data,
+ account=dataset.created_by_account,
+ dataset_process_rule=dataset.latest_process_rule,
+ created_from='api'
+ )
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+
+ if doc_type and doc_metadata:
+ metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[doc_type]
+
+ document.doc_metadata = {}
+
+ for key, value_type in metadata_schema.items():
+ value = doc_metadata.get(key)
+ if value is not None and isinstance(value, value_type):
+ document.doc_metadata[key] = value
+
+ document.doc_type = doc_type
+ document.updated_at = datetime.datetime.utcnow()
+ db.session.commit()
+
+ return {'id': document.id}
+
+
+class DocumentApi(DatasetApiResource):
+ def delete(self, dataset, document_id):
+ """Delete document."""
+ document_id = str(document_id)
+
+ document = DocumentService.get_document(dataset.id, document_id)
+
+ # 404 if document not found
+ if document is None:
+ raise NotFound("Document Not Exists.")
+
+ # 403 if document is archived
+ if DocumentService.check_archived(document):
+ raise ArchivedDocumentImmutableError()
+
+ try:
+ # delete document
+ DocumentService.delete_document(document)
+ except services.errors.document.DocumentIndexingError:
+ raise DocumentIndexingError('Cannot delete document during indexing.')
+
+ return {'result': 'success'}, 204
+
+
+api.add_resource(DocumentListApi, '/documents')
+api.add_resource(DocumentApi, '/documents/<uuid:document_id>')
diff --git a/api/controllers/service_api/dataset/error.py b/api/controllers/service_api/dataset/error.py
new file mode 100644
index 00000000000..d231e0b40a1
--- /dev/null
+++ b/api/controllers/service_api/dataset/error.py
@@ -0,0 +1,20 @@
+# -*- coding:utf-8 -*-
+from libs.exception import BaseHTTPException
+
+
+class ArchivedDocumentImmutableError(BaseHTTPException):
+ error_code = 'archived_document_immutable'
+ description = "Cannot operate when document was archived."
+ code = 403
+
+
+class DocumentIndexingError(BaseHTTPException):
+ error_code = 'document_indexing'
+ description = "Cannot operate document during indexing."
+ code = 403
+
+
+class DatasetNotInitedError(BaseHTTPException):
+ error_code = 'dataset_not_inited'
+ description = "Dataset not inited."
+ code = 403
diff --git a/api/controllers/service_api/wraps.py b/api/controllers/service_api/wraps.py
new file mode 100644
index 00000000000..cb64a3b1584
--- /dev/null
+++ b/api/controllers/service_api/wraps.py
@@ -0,0 +1,95 @@
+# -*- coding:utf-8 -*-
+from datetime import datetime
+from functools import wraps
+
+from flask import request
+from flask_restful import Resource
+from werkzeug.exceptions import NotFound, Unauthorized
+
+from extensions.ext_database import db
+from models.dataset import Dataset
+from models.model import ApiToken, App
+
+
+def validate_app_token(view=None):
+ def decorator(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ api_token = validate_and_get_api_token('app')
+
+ app_model = db.session.query(App).get(api_token.app_id)
+ if not app_model:
+ raise NotFound()
+
+ if app_model.status != 'normal':
+ raise NotFound()
+
+ if not app_model.enable_api:
+ raise NotFound()
+
+ return view(app_model, None, *args, **kwargs)
+ return decorated
+
+ if view:
+ return decorator(view)
+
+ # if view is None, it means that the decorator is used without parentheses
+ # use the decorator as a function for method_decorators
+ return decorator
+
+
+def validate_dataset_token(view=None):
+ def decorator(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ api_token = validate_and_get_api_token('dataset')
+
+ dataset = db.session.query(Dataset).get(api_token.dataset_id)
+ if not dataset:
+ raise NotFound()
+
+ return view(dataset, *args, **kwargs)
+ return decorated
+
+ if view:
+ return decorator(view)
+
+ # if view is None, it means that the decorator is used without parentheses
+ # use the decorator as a function for method_decorators
+ return decorator
+
+
+def validate_and_get_api_token(scope=None):
+ """
+ Validate and get API token.
+ """
+ auth_header = request.headers.get('Authorization')
+ if auth_header is None:
+ raise Unauthorized()
+
+ auth_scheme, auth_token = auth_header.split(None, 1)
+ auth_scheme = auth_scheme.lower()
+
+ if auth_scheme != 'bearer':
+ raise Unauthorized()
+
+ api_token = db.session.query(ApiToken).filter(
+ ApiToken.token == auth_token,
+ ApiToken.type == scope,
+ ).first()
+
+ if not api_token:
+ raise Unauthorized()
+
+ api_token.last_used_at = datetime.utcnow()
+ db.session.commit()
+
+ return api_token
+
+
+class AppApiResource(Resource):
+ method_decorators = [validate_app_token]
+
+
+class DatasetApiResource(Resource):
+ method_decorators = [validate_dataset_token]
diff --git a/api/controllers/web/__init__.py b/api/controllers/web/__init__.py
new file mode 100644
index 00000000000..b793f110145
--- /dev/null
+++ b/api/controllers/web/__init__.py
@@ -0,0 +1,10 @@
+# -*- coding:utf-8 -*-
+from flask import Blueprint
+
+from libs.external_api import ExternalApi
+
+bp = Blueprint('web', __name__, url_prefix='/api')
+api = ExternalApi(bp)
+
+
+from . import completion, app, conversation, message, site, saved_message
diff --git a/api/controllers/web/app.py b/api/controllers/web/app.py
new file mode 100644
index 00000000000..1396531111b
--- /dev/null
+++ b/api/controllers/web/app.py
@@ -0,0 +1,42 @@
+# -*- coding:utf-8 -*-
+from flask_restful import marshal_with, fields
+
+from controllers.web import api
+from controllers.web.wraps import WebApiResource
+
+
+class AppParameterApi(WebApiResource):
+ """Resource for app variables."""
+ variable_fields = {
+ 'key': fields.String,
+ 'name': fields.String,
+ 'description': fields.String,
+ 'type': fields.String,
+ 'default': fields.String,
+ 'max_length': fields.Integer,
+ 'options': fields.List(fields.String)
+ }
+
+ parameters_fields = {
+ 'opening_statement': fields.String,
+ 'suggested_questions': fields.Raw,
+ 'suggested_questions_after_answer': fields.Raw,
+ 'more_like_this': fields.Raw,
+ 'user_input_form': fields.Raw,
+ }
+
+ @marshal_with(parameters_fields)
+ def get(self, app_model, end_user):
+ """Retrieve app parameters."""
+ app_model_config = app_model.app_model_config
+
+ return {
+ 'opening_statement': app_model_config.opening_statement,
+ 'suggested_questions': app_model_config.suggested_questions_list,
+ 'suggested_questions_after_answer': app_model_config.suggested_questions_after_answer_dict,
+ 'more_like_this': app_model_config.more_like_this_dict,
+ 'user_input_form': app_model_config.user_input_form_list
+ }
+
+
+api.add_resource(AppParameterApi, '/parameters')
diff --git a/api/controllers/web/completion.py b/api/controllers/web/completion.py
new file mode 100644
index 00000000000..532bcfaa8d7
--- /dev/null
+++ b/api/controllers/web/completion.py
@@ -0,0 +1,175 @@
+# -*- coding:utf-8 -*-
+import json
+import logging
+from typing import Generator, Union
+
+from flask import Response, stream_with_context
+from flask_restful import reqparse
+from werkzeug.exceptions import InternalServerError, NotFound
+
+import services
+from controllers.web import api
+from controllers.web.error import AppUnavailableError, ConversationCompletedError, \
+ ProviderNotInitializeError, NotChatAppError, NotCompletionAppError, CompletionRequestError, \
+ ProviderQuotaExceededError, ProviderModelCurrentlyNotSupportError
+from controllers.web.wraps import WebApiResource
+from core.conversation_message_task import PubHandler
+from core.llm.error import LLMBadRequestError, LLMAPIUnavailableError, LLMAuthorizationError, LLMAPIConnectionError, \
+ LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError, ModelCurrentlyNotSupportError
+from libs.helper import uuid_value
+from services.completion_service import CompletionService
+
+
+# define completion api for user
+class CompletionApi(WebApiResource):
+
+ def post(self, app_model, end_user):
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, location='json')
+ parser.add_argument('response_mode', type=str, choices=['blocking', 'streaming'], location='json')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=end_user,
+ args=args,
+ from_source='api',
+ streaming=streaming
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+class CompletionStopApi(WebApiResource):
+ def post(self, app_model, end_user, task_id):
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ PubHandler.stop(end_user, task_id)
+
+ return {'result': 'success'}, 200
+
+
+class ChatApi(WebApiResource):
+ def post(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('inputs', type=dict, required=True, location='json')
+ parser.add_argument('query', type=str, required=True, location='json')
+ parser.add_argument('response_mode', type=str, choices=['blocking', 'streaming'], location='json')
+ parser.add_argument('conversation_id', type=uuid_value, location='json')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ try:
+ response = CompletionService.completion(
+ app_model=app_model,
+ user=end_user,
+ args=args,
+ from_source='api',
+ streaming=streaming
+ )
+
+ return compact_response(response)
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.conversation.ConversationCompletedError:
+ raise ConversationCompletedError()
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ raise AppUnavailableError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception as e:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+class ChatStopApi(WebApiResource):
+ def post(self, app_model, end_user, task_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ PubHandler.stop(end_user, task_id)
+
+ return {'result': 'success'}, 200
+
+
+def compact_response(response: Union[dict | Generator]) -> Response:
+ if isinstance(response, dict):
+ return Response(response=json.dumps(response), status=200, mimetype='application/json')
+ else:
+ def generate() -> Generator:
+ try:
+ for chunk in response:
+ yield chunk
+ except services.errors.conversation.ConversationNotExistsError:
+ yield "data: " + json.dumps(api.handle_error(NotFound("Conversation Not Exists.")).get_json()) + "\n\n"
+ except services.errors.conversation.ConversationCompletedError:
+ yield "data: " + json.dumps(api.handle_error(ConversationCompletedError()).get_json()) + "\n\n"
+ except services.errors.app_model_config.AppModelConfigBrokenError:
+ logging.exception("App model config broken.")
+ yield "data: " + json.dumps(api.handle_error(AppUnavailableError()).get_json()) + "\n\n"
+ except ProviderTokenNotInitError:
+ yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError()).get_json()) + "\n\n"
+ except QuotaExceededError:
+ yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
+ except ModelCurrentlyNotSupportError:
+ yield "data: " + json.dumps(api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
+ except ValueError as e:
+ yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
+ except Exception:
+ logging.exception("internal server error.")
+ yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
+
+ return Response(stream_with_context(generate()), status=200,
+ mimetype='text/event-stream')
+
+
+api.add_resource(CompletionApi, '/completion-messages')
+api.add_resource(CompletionStopApi, '/completion-messages/<string:task_id>/stop')
+api.add_resource(ChatApi, '/chat-messages')
+api.add_resource(ChatStopApi, '/chat-messages/<string:task_id>/stop')
diff --git a/api/controllers/web/conversation.py b/api/controllers/web/conversation.py
new file mode 100644
index 00000000000..53ba3820515
--- /dev/null
+++ b/api/controllers/web/conversation.py
@@ -0,0 +1,121 @@
+# -*- coding:utf-8 -*-
+from flask_restful import fields, reqparse, marshal_with
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import NotFound
+
+from controllers.web import api
+from controllers.web.error import NotChatAppError
+from controllers.web.wraps import WebApiResource
+from libs.helper import TimestampField, uuid_value
+from services.conversation_service import ConversationService
+from services.errors.conversation import LastConversationNotExistsError, ConversationNotExistsError
+from services.web_conversation_service import WebConversationService
+
+conversation_fields = {
+ 'id': fields.String,
+ 'name': fields.String,
+ 'inputs': fields.Raw,
+ 'status': fields.String,
+ 'introduction': fields.String,
+ 'created_at': TimestampField
+}
+
+conversation_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(conversation_fields))
+}
+
+
+class ConversationListApi(WebApiResource):
+
+ @marshal_with(conversation_infinite_scroll_pagination_fields)
+ def get(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('last_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ parser.add_argument('pinned', type=str, choices=['true', 'false', None], location='args')
+ args = parser.parse_args()
+
+ pinned = None
+ if 'pinned' in args and args['pinned'] is not None:
+ pinned = True if args['pinned'] == 'true' else False
+
+ try:
+ return WebConversationService.pagination_by_last_id(
+ app_model=app_model,
+ end_user=end_user,
+ last_id=args['last_id'],
+ limit=args['limit'],
+ pinned=pinned
+ )
+ except LastConversationNotExistsError:
+ raise NotFound("Last Conversation Not Exists.")
+
+
+class ConversationApi(WebApiResource):
+ def delete(self, app_model, end_user, c_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ conversation_id = str(c_id)
+ ConversationService.delete(app_model, conversation_id, end_user)
+ WebConversationService.unpin(app_model, conversation_id, end_user)
+
+ return {"result": "success"}, 204
+
+
+class ConversationRenameApi(WebApiResource):
+
+ @marshal_with(conversation_fields)
+ def post(self, app_model, end_user, c_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ conversation_id = str(c_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('name', type=str, required=True, location='json')
+ args = parser.parse_args()
+
+ try:
+ return ConversationService.rename(app_model, conversation_id, end_user, args['name'])
+ except ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+
+
+class ConversationPinApi(WebApiResource):
+
+ def patch(self, app_model, end_user, c_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ conversation_id = str(c_id)
+
+ try:
+ WebConversationService.pin(app_model, conversation_id, end_user)
+ except ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+
+ return {"result": "success"}
+
+
+class ConversationUnPinApi(WebApiResource):
+ def patch(self, app_model, end_user, c_id):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ conversation_id = str(c_id)
+ WebConversationService.unpin(app_model, conversation_id, end_user)
+
+ return {"result": "success"}
+
+
+api.add_resource(ConversationRenameApi, '/conversations/<uuid:c_id>/name', endpoint='web_conversation_name')
+api.add_resource(ConversationListApi, '/conversations')
+api.add_resource(ConversationApi, '/conversations/<uuid:c_id>')
+api.add_resource(ConversationPinApi, '/conversations/<uuid:c_id>/pin')
+api.add_resource(ConversationUnPinApi, '/conversations/<uuid:c_id>/unpin')
diff --git a/api/controllers/web/error.py b/api/controllers/web/error.py
new file mode 100644
index 00000000000..ea72422a1bc
--- /dev/null
+++ b/api/controllers/web/error.py
@@ -0,0 +1,62 @@
+# -*- coding:utf-8 -*-
+from libs.exception import BaseHTTPException
+
+
+class AppUnavailableError(BaseHTTPException):
+ error_code = 'app_unavailable'
+ description = "App unavailable."
+ code = 400
+
+
+class NotCompletionAppError(BaseHTTPException):
+ error_code = 'not_completion_app'
+ description = "Not Completion App"
+ code = 400
+
+
+class NotChatAppError(BaseHTTPException):
+ error_code = 'not_chat_app'
+ description = "Not Chat App"
+ code = 400
+
+
+class ConversationCompletedError(BaseHTTPException):
+ error_code = 'conversation_completed'
+ description = "Conversation Completed."
+ code = 400
+
+
+class ProviderNotInitializeError(BaseHTTPException):
+ error_code = 'provider_not_initialize'
+ description = "Provider Token not initialize."
+ code = 400
+
+
+class ProviderQuotaExceededError(BaseHTTPException):
+ error_code = 'provider_quota_exceeded'
+ description = "Provider quota exceeded."
+ code = 400
+
+
+class ProviderModelCurrentlyNotSupportError(BaseHTTPException):
+ error_code = 'model_currently_not_support'
+ description = "GPT-4 currently not support."
+ code = 400
+
+
+class CompletionRequestError(BaseHTTPException):
+ error_code = 'completion_request_error'
+ description = "Completion request failed."
+ code = 400
+
+
+class AppMoreLikeThisDisabledError(BaseHTTPException):
+ error_code = 'app_more_like_this_disabled'
+ description = "More like this disabled."
+ code = 403
+
+
+class AppSuggestedQuestionsAfterAnswerDisabledError(BaseHTTPException):
+ error_code = 'app_suggested_questions_after_answer_disabled'
+ description = "Function Suggested questions after answer disabled."
+ code = 403
diff --git a/api/controllers/web/message.py b/api/controllers/web/message.py
new file mode 100644
index 00000000000..0d519eac067
--- /dev/null
+++ b/api/controllers/web/message.py
@@ -0,0 +1,189 @@
+# -*- coding:utf-8 -*-
+import json
+import logging
+from typing import Generator, Union
+
+from flask import stream_with_context, Response
+from flask_restful import reqparse, fields, marshal_with
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import NotFound, InternalServerError
+
+import services
+from controllers.web import api
+from controllers.web.error import NotChatAppError, CompletionRequestError, ProviderNotInitializeError, \
+ AppMoreLikeThisDisabledError, NotCompletionAppError, AppSuggestedQuestionsAfterAnswerDisabledError, \
+ ProviderQuotaExceededError, ProviderModelCurrentlyNotSupportError
+from controllers.web.wraps import WebApiResource
+from core.llm.error import LLMRateLimitError, LLMBadRequestError, LLMAuthorizationError, LLMAPIConnectionError, \
+ ProviderTokenNotInitError, LLMAPIUnavailableError, QuotaExceededError, ModelCurrentlyNotSupportError
+from libs.helper import uuid_value, TimestampField
+from services.completion_service import CompletionService
+from services.errors.app import MoreLikeThisDisabledError
+from services.errors.conversation import ConversationNotExistsError
+from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
+from services.message_service import MessageService
+
+
+class MessageListApi(WebApiResource):
+ feedback_fields = {
+ 'rating': fields.String
+ }
+
+ message_fields = {
+ 'id': fields.String,
+ 'conversation_id': fields.String,
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'answer': fields.String,
+ 'feedback': fields.Nested(feedback_fields, attribute='user_feedback', allow_null=True),
+ 'created_at': TimestampField
+ }
+
+ message_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(message_fields))
+ }
+
+ @marshal_with(message_infinite_scroll_pagination_fields)
+ def get(self, app_model, end_user):
+ if app_model.mode != 'chat':
+ raise NotChatAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('conversation_id', required=True, type=uuid_value, location='args')
+ parser.add_argument('first_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ args = parser.parse_args()
+
+ try:
+ return MessageService.pagination_by_first_id(app_model, end_user,
+ args['conversation_id'], args['first_id'], args['limit'])
+ except services.errors.conversation.ConversationNotExistsError:
+ raise NotFound("Conversation Not Exists.")
+ except services.errors.message.FirstMessageNotExistsError:
+ raise NotFound("First Message Not Exists.")
+
+
+class MessageFeedbackApi(WebApiResource):
+ def post(self, app_model, end_user, message_id):
+ message_id = str(message_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
+ args = parser.parse_args()
+
+ try:
+ MessageService.create_feedback(app_model, message_id, end_user, args['rating'])
+ except services.errors.message.MessageNotExistsError:
+ raise NotFound("Message Not Exists.")
+
+ return {'result': 'success'}
+
+
+class MessageMoreLikeThisApi(WebApiResource):
+ def get(self, app_model, end_user, message_id):
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ message_id = str(message_id)
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('response_mode', type=str, required=True, choices=['blocking', 'streaming'], location='args')
+ args = parser.parse_args()
+
+ streaming = args['response_mode'] == 'streaming'
+
+ try:
+ response = CompletionService.generate_more_like_this(app_model, end_user, message_id, streaming)
+ return compact_response(response)
+ except MessageNotExistsError:
+ raise NotFound("Message Not Exists.")
+ except MoreLikeThisDisabledError:
+ raise AppMoreLikeThisDisabledError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except ValueError as e:
+ raise e
+ except Exception:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+
+def compact_response(response: Union[dict | Generator]) -> Response:
+ if isinstance(response, dict):
+ return Response(response=json.dumps(response), status=200, mimetype='application/json')
+ else:
+ def generate() -> Generator:
+ try:
+ for chunk in response:
+ yield chunk
+ except MessageNotExistsError:
+ yield "data: " + json.dumps(api.handle_error(NotFound("Message Not Exists.")).get_json()) + "\n\n"
+ except MoreLikeThisDisabledError:
+ yield "data: " + json.dumps(api.handle_error(AppMoreLikeThisDisabledError()).get_json()) + "\n\n"
+ except ProviderTokenNotInitError:
+ yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError()).get_json()) + "\n\n"
+ except QuotaExceededError:
+ yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
+ except ModelCurrentlyNotSupportError:
+ yield "data: " + json.dumps(api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
+ except ValueError as e:
+ yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
+ except Exception:
+ logging.exception("internal server error.")
+ yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
+
+ return Response(stream_with_context(generate()), status=200,
+ mimetype='text/event-stream')
+
+
+class MessageSuggestedQuestionApi(WebApiResource):
+ def get(self, app_model, end_user, message_id):
+ if app_model.mode != 'chat':
+ raise NotCompletionAppError()
+
+ message_id = str(message_id)
+
+ try:
+ questions = MessageService.get_suggested_questions_after_answer(
+ app_model=app_model,
+ user=end_user,
+ message_id=message_id
+ )
+ except MessageNotExistsError:
+ raise NotFound("Message not found")
+ except ConversationNotExistsError:
+ raise NotFound("Conversation not found")
+ except SuggestedQuestionsAfterAnswerDisabledError:
+ raise AppSuggestedQuestionsAfterAnswerDisabledError()
+ except ProviderTokenNotInitError:
+ raise ProviderNotInitializeError()
+ except QuotaExceededError:
+ raise ProviderQuotaExceededError()
+ except ModelCurrentlyNotSupportError:
+ raise ProviderModelCurrentlyNotSupportError()
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, LLMAuthorizationError) as e:
+ raise CompletionRequestError(str(e))
+ except Exception:
+ logging.exception("internal server error.")
+ raise InternalServerError()
+
+ return {'data': questions}
+
+
+api.add_resource(MessageListApi, '/messages')
+api.add_resource(MessageFeedbackApi, '/messages/<uuid:message_id>/feedbacks')
+api.add_resource(MessageMoreLikeThisApi, '/messages/<uuid:message_id>/more-like-this')
+api.add_resource(MessageSuggestedQuestionApi, '/messages/<uuid:message_id>/suggested-questions')
diff --git a/api/controllers/web/saved_message.py b/api/controllers/web/saved_message.py
new file mode 100644
index 00000000000..7f6f4249c96
--- /dev/null
+++ b/api/controllers/web/saved_message.py
@@ -0,0 +1,74 @@
+from flask_restful import reqparse, marshal_with, fields
+from flask_restful.inputs import int_range
+from werkzeug.exceptions import NotFound
+
+from controllers.web import api
+from controllers.web.error import NotCompletionAppError
+from controllers.web.wraps import WebApiResource
+from libs.helper import uuid_value, TimestampField
+from services.errors.message import MessageNotExistsError
+from services.saved_message_service import SavedMessageService
+
+feedback_fields = {
+ 'rating': fields.String
+}
+
+message_fields = {
+ 'id': fields.String,
+ 'inputs': fields.Raw,
+ 'query': fields.String,
+ 'answer': fields.String,
+ 'feedback': fields.Nested(feedback_fields, attribute='user_feedback', allow_null=True),
+ 'created_at': TimestampField
+}
+
+
+class SavedMessageListApi(WebApiResource):
+ saved_message_infinite_scroll_pagination_fields = {
+ 'limit': fields.Integer,
+ 'has_more': fields.Boolean,
+ 'data': fields.List(fields.Nested(message_fields))
+ }
+
+ @marshal_with(saved_message_infinite_scroll_pagination_fields)
+ def get(self, app_model, end_user):
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('last_id', type=uuid_value, location='args')
+ parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
+ args = parser.parse_args()
+
+ return SavedMessageService.pagination_by_last_id(app_model, end_user, args['last_id'], args['limit'])
+
+ def post(self, app_model, end_user):
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ parser = reqparse.RequestParser()
+ parser.add_argument('message_id', type=uuid_value, required=True, location='json')
+ args = parser.parse_args()
+
+ try:
+ SavedMessageService.save(app_model, end_user, args['message_id'])
+ except MessageNotExistsError:
+ raise NotFound("Message Not Exists.")
+
+ return {'result': 'success'}
+
+
+class SavedMessageApi(WebApiResource):
+ def delete(self, app_model, end_user, message_id):
+ message_id = str(message_id)
+
+ if app_model.mode != 'completion':
+ raise NotCompletionAppError()
+
+ SavedMessageService.delete(app_model, end_user, message_id)
+
+ return {'result': 'success'}
+
+
+api.add_resource(SavedMessageListApi, '/saved-messages')
+api.add_resource(SavedMessageApi, '/saved-messages/<uuid:message_id>')
diff --git a/api/controllers/web/site.py b/api/controllers/web/site.py
new file mode 100644
index 00000000000..de7a38b6df3
--- /dev/null
+++ b/api/controllers/web/site.py
@@ -0,0 +1,73 @@
+# -*- coding:utf-8 -*-
+from flask_restful import fields, marshal_with
+from werkzeug.exceptions import Forbidden
+
+from controllers.web import api
+from controllers.web.wraps import WebApiResource
+from extensions.ext_database import db
+from models.model import Site
+
+
+class AppSiteApi(WebApiResource):
+ """Resource for app sites."""
+
+ model_config_fields = {
+ 'opening_statement': fields.String,
+ 'suggested_questions': fields.Raw(attribute='suggested_questions_list'),
+ 'suggested_questions_after_answer': fields.Raw(attribute='suggested_questions_after_answer_dict'),
+ 'more_like_this': fields.Raw(attribute='more_like_this_dict'),
+ 'model': fields.Raw(attribute='model_dict'),
+ 'user_input_form': fields.Raw(attribute='user_input_form_list'),
+ 'pre_prompt': fields.String,
+ }
+
+ site_fields = {
+ 'title': fields.String,
+ 'icon': fields.String,
+ 'icon_background': fields.String,
+ 'description': fields.String,
+ 'copyright': fields.String,
+ 'privacy_policy': fields.String,
+ 'default_language': fields.String,
+ 'prompt_public': fields.Boolean
+ }
+
+ app_fields = {
+ 'app_id': fields.String,
+ 'end_user_id': fields.String,
+ 'enable_site': fields.Boolean,
+ 'site': fields.Nested(site_fields),
+ 'model_config': fields.Nested(model_config_fields, allow_null=True),
+ 'plan': fields.String,
+ }
+
+ @marshal_with(app_fields)
+ def get(self, app_model, end_user):
+ """Retrieve app site info."""
+ # get site
+ site = db.session.query(Site).filter(Site.app_id == app_model.id).first()
+
+ if not site:
+ raise Forbidden()
+
+ return AppSiteInfo(app_model.tenant, app_model, site, end_user.id)
+
+
+api.add_resource(AppSiteApi, '/site')
+
+
+class AppSiteInfo:
+ """Class to store site information."""
+
+ def __init__(self, tenant, app, site, end_user):
+ """Initialize AppSiteInfo instance."""
+ self.app_id = app.id
+ self.end_user_id = end_user
+ self.enable_site = app.enable_site
+ self.site = site
+ self.model_config = None
+ self.plan = tenant.plan
+
+ if app.enable_site and site.prompt_public:
+ app_model_config = app.app_model_config
+ self.model_config = app_model_config
diff --git a/api/controllers/web/wraps.py b/api/controllers/web/wraps.py
new file mode 100644
index 00000000000..d227a9659ea
--- /dev/null
+++ b/api/controllers/web/wraps.py
@@ -0,0 +1,107 @@
+# -*- coding:utf-8 -*-
+import uuid
+from functools import wraps
+
+from flask import request, session
+from flask_restful import Resource
+from werkzeug.exceptions import NotFound, Unauthorized
+
+from extensions.ext_database import db
+from models.model import App, Site, EndUser
+
+
+def validate_token(view=None):
+ def decorator(view):
+ @wraps(view)
+ def decorated(*args, **kwargs):
+ site = validate_and_get_site()
+
+ app_model = db.session.query(App).get(site.app_id)
+ if not app_model:
+ raise NotFound()
+
+ if app_model.status != 'normal':
+ raise NotFound()
+
+ if not app_model.enable_site:
+ raise NotFound()
+
+ end_user = create_or_update_end_user_for_session(app_model)
+
+ return view(app_model, end_user, *args, **kwargs)
+ return decorated
+
+ if view:
+ return decorator(view)
+ return decorator
+
+
+def validate_and_get_site():
+ """
+ Validate and get API token.
+ """
+ auth_header = request.headers.get('Authorization')
+ if auth_header is None:
+ raise Unauthorized()
+
+ auth_scheme, auth_token = auth_header.split(None, 1)
+ auth_scheme = auth_scheme.lower()
+
+ if auth_scheme != 'bearer':
+ raise Unauthorized()
+
+ site = db.session.query(Site).filter(
+ Site.code == auth_token,
+ Site.status == 'normal'
+ ).first()
+
+ if not site:
+ raise NotFound()
+
+ return site
+
+
+def create_or_update_end_user_for_session(app_model):
+ """
+ Create or update session terminal based on session ID.
+ """
+ if 'session_id' not in session:
+ session['session_id'] = generate_session_id()
+
+ session_id = session.get('session_id')
+ end_user = db.session.query(EndUser) \
+ .filter(
+ EndUser.session_id == session_id,
+ EndUser.type == 'browser'
+ ).first()
+
+ if end_user is None:
+ end_user = EndUser(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ type='browser',
+ is_anonymous=True,
+ session_id=session_id
+ )
+ db.session.add(end_user)
+ db.session.commit()
+
+ return end_user
+
+
+def generate_session_id():
+ """
+ Generate a unique session ID.
+ """
+ count = 1
+ session_id = ''
+ while count != 0:
+ session_id = str(uuid.uuid4())
+ count = db.session.query(EndUser) \
+ .filter(EndUser.session_id == session_id).count()
+
+ return session_id
+
+
+class WebApiResource(Resource):
+ method_decorators = [validate_token]
diff --git a/api/core/__init__.py b/api/core/__init__.py
new file mode 100644
index 00000000000..f6257d8b369
--- /dev/null
+++ b/api/core/__init__.py
@@ -0,0 +1,52 @@
+import os
+from typing import Optional
+
+import langchain
+from flask import Flask
+from jieba.analyse import default_tfidf
+from langchain import set_handler
+from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING
+from llama_index import IndexStructType, QueryMode
+from llama_index.indices.registry import INDEX_STRUT_TYPE_TO_QUERY_MAP
+from pydantic import BaseModel
+
+from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
+from core.index.keyword_table.jieba_keyword_table import GPTJIEBAKeywordTableIndex
+from core.index.keyword_table.stopwords import STOPWORDS
+from core.prompt.prompt_template import OneLineFormatter
+from core.vector_store.vector_store import VectorStore
+from core.vector_store.vector_store_index_query import EnhanceGPTVectorStoreIndexQuery
+
+
+class HostedOpenAICredential(BaseModel):
+ api_key: str
+
+
+class HostedLLMCredentials(BaseModel):
+ openai: Optional[HostedOpenAICredential] = None
+
+
+hosted_llm_credentials = HostedLLMCredentials()
+
+
+def init_app(app: Flask):
+ formatter = OneLineFormatter()
+ DEFAULT_FORMATTER_MAPPING['f-string'] = formatter.format
+ INDEX_STRUT_TYPE_TO_QUERY_MAP[IndexStructType.KEYWORD_TABLE] = GPTJIEBAKeywordTableIndex.get_query_map()
+ INDEX_STRUT_TYPE_TO_QUERY_MAP[IndexStructType.WEAVIATE] = {
+ QueryMode.DEFAULT: EnhanceGPTVectorStoreIndexQuery,
+ QueryMode.EMBEDDING: EnhanceGPTVectorStoreIndexQuery,
+ }
+ INDEX_STRUT_TYPE_TO_QUERY_MAP[IndexStructType.QDRANT] = {
+ QueryMode.DEFAULT: EnhanceGPTVectorStoreIndexQuery,
+ QueryMode.EMBEDDING: EnhanceGPTVectorStoreIndexQuery,
+ }
+
+ default_tfidf.stop_words = STOPWORDS
+
+ if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
+ langchain.verbose = True
+ set_handler(DifyStdOutCallbackHandler())
+
+ if app.config.get("OPENAI_API_KEY"):
+ hosted_llm_credentials.openai = HostedOpenAICredential(api_key=app.config.get("OPENAI_API_KEY"))
diff --git a/api/core/agent/agent_builder.py b/api/core/agent/agent_builder.py
new file mode 100644
index 00000000000..b1d6948467e
--- /dev/null
+++ b/api/core/agent/agent_builder.py
@@ -0,0 +1,89 @@
+from typing import Optional
+
+from langchain import LLMChain
+from langchain.agents import ZeroShotAgent, AgentExecutor, ConversationalAgent
+from langchain.callbacks import CallbackManager
+from langchain.memory.chat_memory import BaseChatMemory
+
+from core.callback_handler.agent_loop_gather_callback_handler import AgentLoopGatherCallbackHandler
+from core.callback_handler.dataset_tool_callback_handler import DatasetToolCallbackHandler
+from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
+from core.llm.llm_builder import LLMBuilder
+
+
+class AgentBuilder:
+ @classmethod
+ def to_agent_chain(cls, tenant_id: str, tools, memory: Optional[BaseChatMemory],
+ dataset_tool_callback_handler: DatasetToolCallbackHandler,
+ agent_loop_gather_callback_handler: AgentLoopGatherCallbackHandler):
+ llm_callback_manager = CallbackManager([agent_loop_gather_callback_handler, DifyStdOutCallbackHandler()])
+ llm = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name=agent_loop_gather_callback_handler.model_name,
+ temperature=0,
+ max_tokens=1024,
+ callback_manager=llm_callback_manager
+ )
+
+ tool_callback_manager = CallbackManager([
+ agent_loop_gather_callback_handler,
+ dataset_tool_callback_handler,
+ DifyStdOutCallbackHandler()
+ ])
+
+ for tool in tools:
+ tool.callback_manager = tool_callback_manager
+
+ prompt = cls.build_agent_prompt_template(
+ tools=tools,
+ memory=memory,
+ )
+
+ agent_llm_chain = LLMChain(
+ llm=llm,
+ prompt=prompt,
+ )
+
+ agent = cls.build_agent(agent_llm_chain=agent_llm_chain, memory=memory)
+
+ agent_callback_manager = CallbackManager(
+ [agent_loop_gather_callback_handler, DifyStdOutCallbackHandler()]
+ )
+
+ agent_chain = AgentExecutor.from_agent_and_tools(
+ tools=tools,
+ agent=agent,
+ memory=memory,
+ callback_manager=agent_callback_manager,
+ max_iterations=6,
+ early_stopping_method="generate",
+ # `generate` will continue to complete the last inference after reaching the iteration limit or request time limit
+ )
+
+ return agent_chain
+
+ @classmethod
+ def build_agent_prompt_template(cls, tools, memory: Optional[BaseChatMemory]):
+ if memory:
+ prompt = ConversationalAgent.create_prompt(
+ tools=tools,
+ )
+ else:
+ prompt = ZeroShotAgent.create_prompt(
+ tools=tools,
+ )
+
+ return prompt
+
+ @classmethod
+ def build_agent(cls, agent_llm_chain: LLMChain, memory: Optional[BaseChatMemory]):
+ if memory:
+ agent = ConversationalAgent(
+ llm_chain=agent_llm_chain
+ )
+ else:
+ agent = ZeroShotAgent(
+ llm_chain=agent_llm_chain
+ )
+
+ return agent
diff --git a/api/core/callback_handler/agent_loop_gather_callback_handler.py b/api/core/callback_handler/agent_loop_gather_callback_handler.py
new file mode 100644
index 00000000000..f37411cacc6
--- /dev/null
+++ b/api/core/callback_handler/agent_loop_gather_callback_handler.py
@@ -0,0 +1,178 @@
+import logging
+import time
+
+from typing import Any, Dict, List, Union, Optional
+
+from langchain.callbacks.base import BaseCallbackHandler
+from langchain.schema import AgentAction, AgentFinish, LLMResult
+
+from core.callback_handler.entity.agent_loop import AgentLoop
+from core.conversation_message_task import ConversationMessageTask
+
+
+class AgentLoopGatherCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that prints to std out."""
+
+ def __init__(self, model_name, conversation_message_task: ConversationMessageTask) -> None:
+ """Initialize callback handler."""
+ self.model_name = model_name
+ self.conversation_message_task = conversation_message_task
+ self._agent_loops = []
+ self._current_loop = None
+ self.current_chain = None
+
+ @property
+ def agent_loops(self) -> List[AgentLoop]:
+ return self._agent_loops
+
+ def clear_agent_loops(self) -> None:
+ self._agent_loops = []
+ self._current_loop = None
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return True
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Print out the prompts."""
+ # serialized={'name': 'OpenAI'}
+ # prompts=['Answer the following questions...\nThought:']
+ # kwargs={}
+ if not self._current_loop:
+ # Agent start with a LLM query
+ self._current_loop = AgentLoop(
+ position=len(self._agent_loops) + 1,
+ prompt=prompts[0],
+ status='llm_started',
+ started_at=time.perf_counter()
+ )
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Do nothing."""
+ # kwargs={}
+ if self._current_loop and self._current_loop.status == 'llm_started':
+ self._current_loop.status = 'llm_end'
+ self._current_loop.prompt_tokens = response.llm_output['token_usage']['prompt_tokens']
+ self._current_loop.completion = response.generations[0][0].text
+ self._current_loop.completion_tokens = response.llm_output['token_usage']['completion_tokens']
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_llm_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ logging.error(error)
+ self._agent_loops = []
+ self._current_loop = None
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print out that we are entering a chain."""
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Print out that we finished a chain."""
+ pass
+
+ def on_chain_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ logging.error(error)
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing."""
+ # kwargs={'color': 'green', 'llm_prefix': 'Thought:', 'observation_prefix': 'Observation: '}
+ # input_str='action-input'
+ # serialized={'description': 'A search engine. Useful for when you need to answer questions about current events. Input should be a search query.', 'name': 'Search'}
+ pass
+
+ def on_agent_action(
+ self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
+ ) -> Any:
+ """Run on agent action."""
+ tool = action.tool
+ tool_input = action.tool_input
+ action_name_position = action.log.index("\nAction:") + 1 if action.log else -1
+ thought = action.log[:action_name_position].strip() if action.log else ''
+
+ if self._current_loop and self._current_loop.status == 'llm_end':
+ self._current_loop.status = 'agent_action'
+ self._current_loop.thought = thought
+ self._current_loop.tool_name = tool
+ self._current_loop.tool_input = tool_input
+
+ def on_tool_end(
+ self,
+ output: str,
+ color: Optional[str] = None,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """If not the final action, print out observation."""
+ # kwargs={'name': 'Search'}
+ # llm_prefix='Thought:'
+ # observation_prefix='Observation: '
+ # output='53 years'
+
+ if self._current_loop and self._current_loop.status == 'agent_action' and output and output != 'None':
+ self._current_loop.status = 'tool_end'
+ self._current_loop.tool_output = output
+ self._current_loop.completed = True
+ self._current_loop.completed_at = time.perf_counter()
+ self._current_loop.latency = self._current_loop.completed_at - self._current_loop.started_at
+
+ self.conversation_message_task.on_agent_end(self.current_chain, self.model_name, self._current_loop)
+
+ self._agent_loops.append(self._current_loop)
+ self._current_loop = None
+
+ def on_tool_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ logging.error(error)
+ self._agent_loops = []
+ self._current_loop = None
+
+ def on_text(
+ self,
+ text: str,
+ color: Optional[str] = None,
+ end: str = "",
+ **kwargs: Optional[str],
+ ) -> None:
+ """Run on additional input from chains and agents."""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:
+ """Run on agent end."""
+ # Final Answer
+ if self._current_loop and (self._current_loop.status == 'llm_end' or self._current_loop.status == 'agent_action'):
+ self._current_loop.status = 'agent_finish'
+ self._current_loop.completed = True
+ self._current_loop.completed_at = time.perf_counter()
+ self._current_loop.latency = self._current_loop.completed_at - self._current_loop.started_at
+
+ self.conversation_message_task.on_agent_end(self.current_chain, self.model_name, self._current_loop)
+
+ self._agent_loops.append(self._current_loop)
+ self._current_loop = None
+ elif not self._current_loop and self._agent_loops:
+ self._agent_loops[-1].status = 'agent_finish'
diff --git a/api/core/callback_handler/dataset_tool_callback_handler.py b/api/core/callback_handler/dataset_tool_callback_handler.py
new file mode 100644
index 00000000000..e3fce665118
--- /dev/null
+++ b/api/core/callback_handler/dataset_tool_callback_handler.py
@@ -0,0 +1,117 @@
+import logging
+
+from typing import Any, Dict, List, Union, Optional
+
+from langchain.callbacks.base import BaseCallbackHandler
+from langchain.schema import AgentAction, AgentFinish, LLMResult
+
+from core.callback_handler.entity.dataset_query import DatasetQueryObj
+from core.conversation_message_task import ConversationMessageTask
+
+
+class DatasetToolCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that prints to std out."""
+
+ def __init__(self, conversation_message_task: ConversationMessageTask) -> None:
+ """Initialize callback handler."""
+ self.queries = []
+ self.conversation_message_task = conversation_message_task
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return True
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return True
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return False
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ tool_name = serialized.get('name')
+ dataset_id = tool_name[len("dataset-"):]
+ self.conversation_message_task.on_dataset_query_end(DatasetQueryObj(dataset_id=dataset_id, query=input_str))
+
+ def on_tool_end(
+ self,
+ output: str,
+ color: Optional[str] = None,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ # kwargs={'name': 'Search'}
+ # llm_prefix='Thought:'
+ # observation_prefix='Observation: '
+ # output='53 years'
+ pass
+
+ def on_tool_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ logging.error(error)
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ pass
+
+ def on_chain_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ pass
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_llm_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ logging.error(error)
+
+ def on_agent_action(
+ self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
+ ) -> Any:
+ pass
+
+ def on_text(
+ self,
+ text: str,
+ color: Optional[str] = None,
+ end: str = "",
+ **kwargs: Optional[str],
+ ) -> None:
+ """Run on additional input from chains and agents."""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:
+ """Run on agent end."""
+ pass
diff --git a/api/core/callback_handler/entity/agent_loop.py b/api/core/callback_handler/entity/agent_loop.py
new file mode 100644
index 00000000000..13ed4caa7f7
--- /dev/null
+++ b/api/core/callback_handler/entity/agent_loop.py
@@ -0,0 +1,23 @@
+from pydantic import BaseModel
+
+
+class AgentLoop(BaseModel):
+ position: int = 1
+
+ thought: str = None
+ tool_name: str = None
+ tool_input: str = None
+ tool_output: str = None
+
+ prompt: str = None
+ prompt_tokens: int = None
+ completion: str = None
+ completion_tokens: int = None
+
+ latency: float = None
+
+ status: str = 'llm_started'
+ completed: bool = False
+
+ started_at: float = None
+ completed_at: float = None
\ No newline at end of file
diff --git a/api/core/callback_handler/entity/chain_result.py b/api/core/callback_handler/entity/chain_result.py
new file mode 100644
index 00000000000..596486cdb07
--- /dev/null
+++ b/api/core/callback_handler/entity/chain_result.py
@@ -0,0 +1,16 @@
+from pydantic import BaseModel
+
+
+class ChainResult(BaseModel):
+ type: str = None
+ prompt: dict = None
+ completion: dict = None
+
+ status: str = 'chain_started'
+ completed: bool = False
+
+ started_at: float = None
+ completed_at: float = None
+
+ agent_result: dict = None
+ """only when type is 'AgentExecutor'"""
diff --git a/api/core/callback_handler/entity/dataset_query.py b/api/core/callback_handler/entity/dataset_query.py
new file mode 100644
index 00000000000..23705e55ac2
--- /dev/null
+++ b/api/core/callback_handler/entity/dataset_query.py
@@ -0,0 +1,6 @@
+from pydantic import BaseModel
+
+
+class DatasetQueryObj(BaseModel):
+ dataset_id: str = None
+ query: str = None
diff --git a/api/core/callback_handler/entity/llm_message.py b/api/core/callback_handler/entity/llm_message.py
new file mode 100644
index 00000000000..0f53295ae93
--- /dev/null
+++ b/api/core/callback_handler/entity/llm_message.py
@@ -0,0 +1,9 @@
+from pydantic import BaseModel
+
+
+class LLMMessage(BaseModel):
+ prompt: str = ''
+ prompt_tokens: int = 0
+ completion: str = ''
+ completion_tokens: int = 0
+ latency: float = 0.0
diff --git a/api/core/callback_handler/index_tool_callback_handler.py b/api/core/callback_handler/index_tool_callback_handler.py
new file mode 100644
index 00000000000..f0c93794136
--- /dev/null
+++ b/api/core/callback_handler/index_tool_callback_handler.py
@@ -0,0 +1,38 @@
+from llama_index import Response
+
+from extensions.ext_database import db
+from models.dataset import DocumentSegment
+
+
+class IndexToolCallbackHandler:
+
+ def __init__(self) -> None:
+ self._response = None
+
+ @property
+ def response(self) -> Response:
+ return self._response
+
+ def on_tool_end(self, response: Response) -> None:
+ """Handle tool end."""
+ self._response = response
+
+
+class DatasetIndexToolCallbackHandler(IndexToolCallbackHandler):
+ """Callback handler for dataset tool."""
+
+ def __init__(self, dataset_id: str) -> None:
+ super().__init__()
+ self.dataset_id = dataset_id
+
+ def on_tool_end(self, response: Response) -> None:
+ """Handle tool end."""
+ for node in response.source_nodes:
+ index_node_id = node.node.doc_id
+
+ # add hit count to document segment
+ db.session.query(DocumentSegment).filter(
+ DocumentSegment.dataset_id == self.dataset_id,
+ DocumentSegment.index_node_id == index_node_id
+ ).update({DocumentSegment.hit_count: DocumentSegment.hit_count + 1}, synchronize_session=False)
+
diff --git a/api/core/callback_handler/llm_callback_handler.py b/api/core/callback_handler/llm_callback_handler.py
new file mode 100644
index 00000000000..b6f7ef2f549
--- /dev/null
+++ b/api/core/callback_handler/llm_callback_handler.py
@@ -0,0 +1,147 @@
+import logging
+import time
+from typing import Any, Dict, List, Union, Optional
+
+from langchain.callbacks.base import BaseCallbackHandler
+from langchain.schema import AgentAction, AgentFinish, LLMResult, HumanMessage, AIMessage, SystemMessage
+
+from core.callback_handler.entity.llm_message import LLMMessage
+from core.conversation_message_task import ConversationMessageTask, ConversationTaskStoppedException
+from core.llm.streamable_chat_open_ai import StreamableChatOpenAI
+from core.llm.streamable_open_ai import StreamableOpenAI
+
+
+class LLMCallbackHandler(BaseCallbackHandler):
+
+ def __init__(self, llm: Union[StreamableOpenAI, StreamableChatOpenAI],
+ conversation_message_task: ConversationMessageTask):
+ self.llm = llm
+ self.llm_message = LLMMessage()
+ self.start_at = None
+ self.conversation_message_task = conversation_message_task
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ self.start_at = time.perf_counter()
+
+ if 'Chat' in serialized['name']:
+ real_prompts = []
+ messages = []
+ for prompt in prompts:
+ role, content = prompt.split(': ', maxsplit=1)
+ if role == 'human':
+ role = 'user'
+ message = HumanMessage(content=content)
+ elif role == 'ai':
+ role = 'assistant'
+ message = AIMessage(content=content)
+ else:
+ message = SystemMessage(content=content)
+
+ real_prompt = {
+ "role": role,
+ "text": content
+ }
+ real_prompts.append(real_prompt)
+ messages.append(message)
+
+ self.llm_message.prompt = real_prompts
+ self.llm_message.prompt_tokens = self.llm.get_messages_tokens(messages)
+ else:
+ self.llm_message.prompt = [{
+ "role": 'user',
+ "text": prompts[0]
+ }]
+
+ self.llm_message.prompt_tokens = self.llm.get_num_tokens(prompts[0])
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ end_at = time.perf_counter()
+ self.llm_message.latency = end_at - self.start_at
+
+ if not self.conversation_message_task.streaming:
+ self.conversation_message_task.append_message_text(response.generations[0][0].text)
+ self.llm_message.completion = response.generations[0][0].text
+ self.llm_message.completion_tokens = response.llm_output['token_usage']['completion_tokens']
+ else:
+ self.llm_message.completion_tokens = self.llm.get_num_tokens(self.llm_message.completion)
+
+ self.conversation_message_task.save_message(self.llm_message)
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ self.conversation_message_task.append_message_text(token)
+ self.llm_message.completion += token
+
+ def on_llm_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ if isinstance(error, ConversationTaskStoppedException):
+ if self.conversation_message_task.streaming:
+ end_at = time.perf_counter()
+ self.llm_message.latency = end_at - self.start_at
+ self.llm_message.completion_tokens = self.llm.get_num_tokens(self.llm_message.completion)
+ self.conversation_message_task.save_message(llm_message=self.llm_message, by_stopped=True)
+ else:
+ logging.error(error)
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ pass
+
+ def on_chain_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_agent_action(
+ self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
+ ) -> Any:
+ pass
+
+ def on_tool_end(
+ self,
+ output: str,
+ color: Optional[str] = None,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_tool_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_text(
+ self,
+ text: str,
+ color: Optional[str] = None,
+ end: str = "",
+ **kwargs: Optional[str],
+ ) -> None:
+ pass
+
+ def on_agent_finish(
+ self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
+ ) -> None:
+ pass
diff --git a/api/core/callback_handler/main_chain_gather_callback_handler.py b/api/core/callback_handler/main_chain_gather_callback_handler.py
new file mode 100644
index 00000000000..1bd41edd6c2
--- /dev/null
+++ b/api/core/callback_handler/main_chain_gather_callback_handler.py
@@ -0,0 +1,137 @@
+import logging
+import time
+
+from typing import Any, Dict, List, Union, Optional
+
+from langchain.callbacks.base import BaseCallbackHandler
+from langchain.schema import AgentAction, AgentFinish, LLMResult
+
+from core.callback_handler.agent_loop_gather_callback_handler import AgentLoopGatherCallbackHandler
+from core.callback_handler.entity.chain_result import ChainResult
+from core.constant import llm_constant
+from core.conversation_message_task import ConversationMessageTask
+
+
+class MainChainGatherCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that prints to std out."""
+
+ def __init__(self, conversation_message_task: ConversationMessageTask) -> None:
+ """Initialize callback handler."""
+ self._current_chain_result = None
+ self._current_chain_message = None
+ self.conversation_message_task = conversation_message_task
+ self.agent_loop_gather_callback_handler = AgentLoopGatherCallbackHandler(
+ llm_constant.agent_model_name,
+ conversation_message_task
+ )
+
+ def clear_chain_results(self) -> None:
+ self._current_chain_result = None
+ self._current_chain_message = None
+ self.agent_loop_gather_callback_handler.current_chain = None
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return True
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return True
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print out that we are entering a chain."""
+ if not self._current_chain_result:
+ self._current_chain_result = ChainResult(
+ type=serialized['name'],
+ prompt=inputs,
+ started_at=time.perf_counter()
+ )
+ self._current_chain_message = self.conversation_message_task.init_chain(self._current_chain_result)
+ self.agent_loop_gather_callback_handler.current_chain = self._current_chain_message
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Print out that we finished a chain."""
+ if self._current_chain_result and self._current_chain_result.status == 'chain_started':
+ self._current_chain_result.status = 'chain_ended'
+ self._current_chain_result.completion = outputs
+ self._current_chain_result.completed = True
+ self._current_chain_result.completed_at = time.perf_counter()
+
+ self.conversation_message_task.on_chain_end(self._current_chain_message, self._current_chain_result)
+
+ self.clear_chain_results()
+
+ def on_chain_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ logging.error(error)
+ self.clear_chain_results()
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ pass
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_llm_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ logging.error(error)
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_agent_action(
+ self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
+ ) -> Any:
+ pass
+
+ def on_tool_end(
+ self,
+ output: str,
+ color: Optional[str] = None,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_tool_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ logging.error(error)
+
+ def on_text(
+ self,
+ text: str,
+ color: Optional[str] = None,
+ end: str = "",
+ **kwargs: Optional[str],
+ ) -> None:
+ """Run on additional input from chains and agents."""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any:
+ """Run on agent end."""
+ pass
diff --git a/api/core/callback_handler/std_out_callback_handler.py b/api/core/callback_handler/std_out_callback_handler.py
new file mode 100644
index 00000000000..352e6cb4d8d
--- /dev/null
+++ b/api/core/callback_handler/std_out_callback_handler.py
@@ -0,0 +1,127 @@
+import sys
+from typing import Any, Dict, List, Optional, Union
+
+from langchain.callbacks.base import BaseCallbackHandler
+from langchain.input import print_text
+from langchain.schema import AgentAction, AgentFinish, LLMResult
+
+
+class DifyStdOutCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that prints to std out."""
+
+ def __init__(self, color: Optional[str] = None) -> None:
+ """Initialize callback handler."""
+ self.color = color
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Print out the prompts."""
+ print_text("\n[on_llm_start]\n", color='blue')
+
+ if 'Chat' in serialized['name']:
+ for prompt in prompts:
+ print_text(prompt + "\n", color='blue')
+ else:
+ print_text(prompts[0] + "\n", color='blue')
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Do nothing."""
+ print_text("\n[on_llm_end]\nOutput: " + str(response.generations[0][0].text) + "\nllm_output: " + str(
+ response.llm_output) + "\n", color='blue')
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_llm_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ print_text("\n[on_llm_error]\nError: " + str(error) + "\n", color='blue')
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print out that we are entering a chain."""
+ class_name = serialized["name"]
+ print_text("\n[on_chain_start]\nChain: " + class_name + "\nInputs: " + str(inputs) + "\n", color='pink')
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Print out that we finished a chain."""
+ print_text("\n[on_chain_end]\nOutputs: " + str(outputs) + "\n", color='pink')
+
+ def on_chain_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ print_text("\n[on_chain_error]\nError: " + str(error) + "\n", color='pink')
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing."""
+ print_text("\n[on_tool_start] " + str(serialized), color='yellow')
+
+ def on_agent_action(
+ self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
+ ) -> Any:
+ """Run on agent action."""
+ tool = action.tool
+ tool_input = action.tool_input
+ action_name_position = action.log.index("\nAction:") + 1 if action.log else -1
+ thought = action.log[:action_name_position].strip() if action.log else ''
+
+ log = f"Thought: {thought}\nTool: {tool}\nTool Input: {tool_input}"
+ print_text("\n[on_agent_action]\n" + log + "\n", color='green')
+
+ def on_tool_end(
+ self,
+ output: str,
+ color: Optional[str] = None,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """If not the final action, print out observation."""
+ print_text("\n[on_tool_end]\n", color='yellow')
+ if observation_prefix:
+ print_text(f"\n{observation_prefix}")
+ print_text(output, color='yellow')
+ if llm_prefix:
+ print_text(f"\n{llm_prefix}")
+ print_text("\n")
+
+ def on_tool_error(
+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
+ ) -> None:
+ """Do nothing."""
+ print_text("\n[on_tool_error] Error: " + str(error) + "\n", color='yellow')
+
+ def on_text(
+ self,
+ text: str,
+ color: Optional[str] = None,
+ end: str = "",
+ **kwargs: Optional[str],
+ ) -> None:
+ """Run when agent ends."""
+ print_text("\n[on_text] " + text + "\n", color=color if color else self.color, end=end)
+
+ def on_agent_finish(
+ self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
+ ) -> None:
+ """Run on agent end."""
+ print_text("[on_agent_finish] " + finish.return_values['output'] + "\n", color='green', end="\n")
+
+
+class DifyStreamingStdOutCallbackHandler(DifyStdOutCallbackHandler):
+ """Callback handler for streaming. Only works with LLMs that support streaming."""
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run on new LLM token. Only available when streaming is enabled."""
+ sys.stdout.write(token)
+ sys.stdout.flush()
diff --git a/api/core/chain/chain_builder.py b/api/core/chain/chain_builder.py
new file mode 100644
index 00000000000..b7583ed890a
--- /dev/null
+++ b/api/core/chain/chain_builder.py
@@ -0,0 +1,34 @@
+from typing import Optional
+
+from langchain.callbacks import CallbackManager
+
+from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
+from core.chain.sensitive_word_avoidance_chain import SensitiveWordAvoidanceChain
+from core.chain.tool_chain import ToolChain
+
+
+class ChainBuilder:
+ @classmethod
+ def to_tool_chain(cls, tool, **kwargs) -> ToolChain:
+ return ToolChain(
+ tool=tool,
+ input_key=kwargs.get('input_key', 'input'),
+ output_key=kwargs.get('output_key', 'tool_output'),
+ callback_manager=CallbackManager([DifyStdOutCallbackHandler()])
+ )
+
+ @classmethod
+ def to_sensitive_word_avoidance_chain(cls, tool_config: dict, **kwargs) -> Optional[
+ SensitiveWordAvoidanceChain]:
+ sensitive_words = tool_config.get("words", "")
+ if tool_config.get("enabled", False) \
+ and sensitive_words:
+ return SensitiveWordAvoidanceChain(
+ sensitive_words=sensitive_words.split(","),
+ canned_response=tool_config.get("canned_response", ''),
+ output_key="sensitive_word_avoidance_output",
+ callback_manager=CallbackManager([DifyStdOutCallbackHandler()]),
+ **kwargs
+ )
+
+ return None
diff --git a/api/core/chain/main_chain_builder.py b/api/core/chain/main_chain_builder.py
new file mode 100644
index 00000000000..5a4ab2214d7
--- /dev/null
+++ b/api/core/chain/main_chain_builder.py
@@ -0,0 +1,116 @@
+from typing import Optional, List
+
+from langchain.callbacks import SharedCallbackManager
+from langchain.chains import SequentialChain
+from langchain.chains.base import Chain
+from langchain.memory.chat_memory import BaseChatMemory
+
+from core.agent.agent_builder import AgentBuilder
+from core.callback_handler.agent_loop_gather_callback_handler import AgentLoopGatherCallbackHandler
+from core.callback_handler.dataset_tool_callback_handler import DatasetToolCallbackHandler
+from core.callback_handler.main_chain_gather_callback_handler import MainChainGatherCallbackHandler
+from core.chain.chain_builder import ChainBuilder
+from core.constant import llm_constant
+from core.conversation_message_task import ConversationMessageTask
+from core.tool.dataset_tool_builder import DatasetToolBuilder
+
+
+class MainChainBuilder:
+ @classmethod
+ def to_langchain_components(cls, tenant_id: str, agent_mode: dict, memory: Optional[BaseChatMemory],
+ conversation_message_task: ConversationMessageTask):
+ first_input_key = "input"
+ final_output_key = "output"
+
+ chains = []
+
+ chain_callback_handler = MainChainGatherCallbackHandler(conversation_message_task)
+
+ # agent mode
+ tool_chains, chains_output_key = cls.get_agent_chains(
+ tenant_id=tenant_id,
+ agent_mode=agent_mode,
+ memory=memory,
+ dataset_tool_callback_handler=DatasetToolCallbackHandler(conversation_message_task),
+ agent_loop_gather_callback_handler=chain_callback_handler.agent_loop_gather_callback_handler
+ )
+ chains += tool_chains
+
+ if chains_output_key:
+ final_output_key = chains_output_key
+
+ if len(chains) == 0:
+ return None
+
+ for chain in chains:
+ # do not add handler into singleton callback manager
+ if not isinstance(chain.callback_manager, SharedCallbackManager):
+ chain.callback_manager.add_handler(chain_callback_handler)
+
+ # build main chain
+ overall_chain = SequentialChain(
+ chains=chains,
+ input_variables=[first_input_key],
+ output_variables=[final_output_key],
+ memory=memory, # only for use the memory prompt input key
+ )
+
+ return overall_chain
+
+ @classmethod
+ def get_agent_chains(cls, tenant_id: str, agent_mode: dict, memory: Optional[BaseChatMemory],
+ dataset_tool_callback_handler: DatasetToolCallbackHandler,
+ agent_loop_gather_callback_handler: AgentLoopGatherCallbackHandler):
+ # agent mode
+ chains = []
+ if agent_mode and agent_mode.get('enabled'):
+ tools = agent_mode.get('tools', [])
+
+ pre_fixed_chains = []
+ agent_tools = []
+ for tool in tools:
+ tool_type = list(tool.keys())[0]
+ tool_config = list(tool.values())[0]
+ if tool_type == 'sensitive-word-avoidance':
+ chain = ChainBuilder.to_sensitive_word_avoidance_chain(tool_config)
+ if chain:
+ pre_fixed_chains.append(chain)
+ elif tool_type == "dataset":
+ dataset_tool = DatasetToolBuilder.build_dataset_tool(
+ tenant_id=tenant_id,
+ dataset_id=tool_config.get("id"),
+ response_mode='no_synthesizer', # "compact"
+ callback_handler=dataset_tool_callback_handler
+ )
+
+ if dataset_tool:
+ agent_tools.append(dataset_tool)
+
+ # add pre-fixed chains
+ chains += pre_fixed_chains
+
+ if len(agent_tools) == 1:
+ # tool to chain
+ tool_chain = ChainBuilder.to_tool_chain(tool=agent_tools[0], output_key='tool_output')
+ chains.append(tool_chain)
+ elif len(agent_tools) > 1:
+ # build agent config
+ agent_chain = AgentBuilder.to_agent_chain(
+ tenant_id=tenant_id,
+ tools=agent_tools,
+ memory=memory,
+ dataset_tool_callback_handler=dataset_tool_callback_handler,
+ agent_loop_gather_callback_handler=agent_loop_gather_callback_handler
+ )
+
+ chains.append(agent_chain)
+
+ final_output_key = cls.get_chains_output_key(chains)
+
+ return chains, final_output_key
+
+ @classmethod
+ def get_chains_output_key(cls, chains: List[Chain]):
+ if len(chains) > 0:
+ return chains[-1].output_keys[0]
+ return None
diff --git a/api/core/chain/sensitive_word_avoidance_chain.py b/api/core/chain/sensitive_word_avoidance_chain.py
new file mode 100644
index 00000000000..a552551c0fe
--- /dev/null
+++ b/api/core/chain/sensitive_word_avoidance_chain.py
@@ -0,0 +1,42 @@
+from typing import List, Dict
+
+from langchain.chains.base import Chain
+
+
+class SensitiveWordAvoidanceChain(Chain):
+ input_key: str = "input" #: :meta private:
+ output_key: str = "output" #: :meta private:
+
+ sensitive_words: List[str] = []
+ canned_response: str = None
+
+ @property
+ def _chain_type(self) -> str:
+ return "sensitive_word_avoidance_chain"
+
+ @property
+ def input_keys(self) -> List[str]:
+ """Expect input key.
+
+ :meta private:
+ """
+ return [self.input_key]
+
+ @property
+ def output_keys(self) -> List[str]:
+ """Return output key.
+
+ :meta private:
+ """
+ return [self.output_key]
+
+ def _check_sensitive_word(self, text: str) -> str:
+ for word in self.sensitive_words:
+ if word in text:
+ return self.canned_response
+ return text
+
+ def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
+ text = inputs[self.input_key]
+ output = self._check_sensitive_word(text)
+ return {self.output_key: output}
diff --git a/api/core/chain/tool_chain.py b/api/core/chain/tool_chain.py
new file mode 100644
index 00000000000..458a35eb827
--- /dev/null
+++ b/api/core/chain/tool_chain.py
@@ -0,0 +1,42 @@
+from typing import List, Dict
+
+from langchain.chains.base import Chain
+from langchain.tools import BaseTool
+
+
+class ToolChain(Chain):
+ input_key: str = "input" #: :meta private:
+ output_key: str = "output" #: :meta private:
+
+ tool: BaseTool
+
+ @property
+ def _chain_type(self) -> str:
+ return "tool_chain"
+
+ @property
+ def input_keys(self) -> List[str]:
+ """Expect input key.
+
+ :meta private:
+ """
+ return [self.input_key]
+
+ @property
+ def output_keys(self) -> List[str]:
+ """Return output key.
+
+ :meta private:
+ """
+ return [self.output_key]
+
+ def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
+ input = inputs[self.input_key]
+ output = self.tool.run(input, self.verbose)
+ return {self.output_key: output}
+
+ async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]:
+ """Run the logic of this chain and return the output."""
+ input = inputs[self.input_key]
+ output = await self.tool.arun(input, self.verbose)
+ return {self.output_key: output}
diff --git a/api/core/completion.py b/api/core/completion.py
new file mode 100644
index 00000000000..f215bd0ee55
--- /dev/null
+++ b/api/core/completion.py
@@ -0,0 +1,326 @@
+from typing import Optional, List, Union
+
+from langchain.callbacks import CallbackManager
+from langchain.chat_models.base import BaseChatModel
+from langchain.llms import BaseLLM
+from langchain.schema import BaseMessage, BaseLanguageModel, HumanMessage
+from core.constant import llm_constant
+from core.callback_handler.llm_callback_handler import LLMCallbackHandler
+from core.callback_handler.std_out_callback_handler import DifyStreamingStdOutCallbackHandler, \
+ DifyStdOutCallbackHandler
+from core.conversation_message_task import ConversationMessageTask, ConversationTaskStoppedException
+from core.llm.error import LLMBadRequestError
+from core.llm.llm_builder import LLMBuilder
+from core.chain.main_chain_builder import MainChainBuilder
+from core.llm.streamable_chat_open_ai import StreamableChatOpenAI
+from core.llm.streamable_open_ai import StreamableOpenAI
+from core.memory.read_only_conversation_token_db_buffer_shared_memory import \
+ ReadOnlyConversationTokenDBBufferSharedMemory
+from core.memory.read_only_conversation_token_db_string_buffer_shared_memory import \
+ ReadOnlyConversationTokenDBStringBufferSharedMemory
+from core.prompt.prompt_builder import PromptBuilder
+from core.prompt.prompt_template import OutLinePromptTemplate
+from core.prompt.prompts import MORE_LIKE_THIS_GENERATE_PROMPT
+from models.model import App, AppModelConfig, Account, Conversation, Message
+
+
+class Completion:
+ @classmethod
+ def generate(cls, task_id: str, app: App, app_model_config: AppModelConfig, query: str, inputs: dict,
+ user: Account, conversation: Optional[Conversation], streaming: bool, is_override: bool = False):
+ """
+ errors: ProviderTokenNotInitError
+ """
+ cls.validate_query_tokens(app.tenant_id, app_model_config, query)
+
+ memory = None
+ if conversation:
+ # get memory of conversation (read-only)
+ memory = cls.get_memory_from_conversation(
+ tenant_id=app.tenant_id,
+ app_model_config=app_model_config,
+ conversation=conversation
+ )
+
+ inputs = conversation.inputs
+
+ conversation_message_task = ConversationMessageTask(
+ task_id=task_id,
+ app=app,
+ app_model_config=app_model_config,
+ user=user,
+ conversation=conversation,
+ is_override=is_override,
+ inputs=inputs,
+ query=query,
+ streaming=streaming
+ )
+
+ # build main chain include agent
+ main_chain = MainChainBuilder.to_langchain_components(
+ tenant_id=app.tenant_id,
+ agent_mode=app_model_config.agent_mode_dict,
+ memory=ReadOnlyConversationTokenDBStringBufferSharedMemory(memory=memory) if memory else None,
+ conversation_message_task=conversation_message_task
+ )
+
+ chain_output = ''
+ if main_chain:
+ chain_output = main_chain.run(query)
+
+ # run the final llm
+ try:
+ cls.run_final_llm(
+ tenant_id=app.tenant_id,
+ mode=app.mode,
+ app_model_config=app_model_config,
+ query=query,
+ inputs=inputs,
+ chain_output=chain_output,
+ conversation_message_task=conversation_message_task,
+ memory=memory,
+ streaming=streaming
+ )
+ except ConversationTaskStoppedException:
+ return
+
+ @classmethod
+ def run_final_llm(cls, tenant_id: str, mode: str, app_model_config: AppModelConfig, query: str, inputs: dict,
+ chain_output: str,
+ conversation_message_task: ConversationMessageTask,
+ memory: Optional[ReadOnlyConversationTokenDBBufferSharedMemory], streaming: bool):
+ final_llm = LLMBuilder.to_llm_from_model(
+ tenant_id=tenant_id,
+ model=app_model_config.model_dict,
+ streaming=streaming
+ )
+
+ # get llm prompt
+ prompt = cls.get_main_llm_prompt(
+ mode=mode,
+ llm=final_llm,
+ pre_prompt=app_model_config.pre_prompt,
+ query=query,
+ inputs=inputs,
+ chain_output=chain_output,
+ memory=memory
+ )
+
+ final_llm.callback_manager = cls.get_llm_callback_manager(final_llm, streaming, conversation_message_task)
+
+ cls.recale_llm_max_tokens(
+ final_llm=final_llm,
+ prompt=prompt,
+ mode=mode
+ )
+
+ response = final_llm.generate([prompt])
+
+ return response
+
+ @classmethod
+ def get_main_llm_prompt(cls, mode: str, llm: BaseLanguageModel, pre_prompt: str, query: str, inputs: dict, chain_output: Optional[str],
+ memory: Optional[ReadOnlyConversationTokenDBBufferSharedMemory]) -> \
+ Union[str | List[BaseMessage]]:
+ pre_prompt = PromptBuilder.process_template(pre_prompt) if pre_prompt else pre_prompt
+ if mode == 'completion':
+ prompt_template = OutLinePromptTemplate.from_template(
+ template=("Use the following pieces of [CONTEXT] to answer the question at the end. "
+ "If you don't know the answer, "
+ "just say that you don't know, don't try to make up an answer. \n"
+ "```\n"
+ "[CONTEXT]\n"
+ "{context}\n"
+ "```\n" if chain_output else "")
+ + (pre_prompt + "\n" if pre_prompt else "")
+ + "{query}\n"
+ )
+
+ if chain_output:
+ inputs['context'] = chain_output
+
+ prompt_inputs = {k: inputs[k] for k in prompt_template.input_variables if k in inputs}
+ prompt_content = prompt_template.format(
+ query=query,
+ **prompt_inputs
+ )
+
+ if isinstance(llm, BaseChatModel):
+ # use chat llm as completion model
+ return [HumanMessage(content=prompt_content)]
+ else:
+ return prompt_content
+ else:
+ messages: List[BaseMessage] = []
+
+ system_message = None
+ if pre_prompt:
+ # append pre prompt as system message
+ system_message = PromptBuilder.to_system_message(pre_prompt, inputs)
+
+ if chain_output:
+ # append context as system message, currently only use simple stuff prompt
+ context_message = PromptBuilder.to_system_message(
+ """Use the following pieces of [CONTEXT] to answer the users question.
+If you don't know the answer, just say that you don't know, don't try to make up an answer.
+```
+[CONTEXT]
+{context}
+```""",
+ {'context': chain_output}
+ )
+
+ if not system_message:
+ system_message = context_message
+ else:
+ system_message.content = context_message.content + "\n\n" + system_message.content
+
+ if system_message:
+ messages.append(system_message)
+
+ human_inputs = {
+ "query": query
+ }
+
+ # construct main prompt
+ human_message = PromptBuilder.to_human_message(
+ prompt_content="{query}",
+ inputs=human_inputs
+ )
+
+ if memory:
+ # append chat histories
+ tmp_messages = messages.copy() + [human_message]
+ curr_message_tokens = memory.llm.get_messages_tokens(tmp_messages)
+ rest_tokens = llm_constant.max_context_token_length[
+ memory.llm.model_name] - memory.llm.max_tokens - curr_message_tokens
+ rest_tokens = max(rest_tokens, 0)
+ history_messages = cls.get_history_messages_from_memory(memory, rest_tokens)
+ messages += history_messages
+
+ messages.append(human_message)
+
+ return messages
+
+ @classmethod
+ def get_llm_callback_manager(cls, llm: Union[StreamableOpenAI, StreamableChatOpenAI],
+ streaming: bool, conversation_message_task: ConversationMessageTask) -> CallbackManager:
+ llm_callback_handler = LLMCallbackHandler(llm, conversation_message_task)
+ if streaming:
+ callback_handlers = [llm_callback_handler, DifyStreamingStdOutCallbackHandler()]
+ else:
+ callback_handlers = [llm_callback_handler, DifyStdOutCallbackHandler()]
+
+ return CallbackManager(callback_handlers)
+
+ @classmethod
+ def get_history_messages_from_memory(cls, memory: ReadOnlyConversationTokenDBBufferSharedMemory,
+ max_token_limit: int) -> \
+ List[BaseMessage]:
+ """Get memory messages."""
+ memory.max_token_limit = max_token_limit
+ memory_key = memory.memory_variables[0]
+ external_context = memory.load_memory_variables({})
+ return external_context[memory_key]
+
+ @classmethod
+ def get_memory_from_conversation(cls, tenant_id: str, app_model_config: AppModelConfig,
+ conversation: Conversation,
+ **kwargs) -> ReadOnlyConversationTokenDBBufferSharedMemory:
+ # only for calc token in memory
+ memory_llm = LLMBuilder.to_llm_from_model(
+ tenant_id=tenant_id,
+ model=app_model_config.model_dict
+ )
+
+ # use llm config from conversation
+ memory = ReadOnlyConversationTokenDBBufferSharedMemory(
+ conversation=conversation,
+ llm=memory_llm,
+ max_token_limit=kwargs.get("max_token_limit", 2048),
+ memory_key=kwargs.get("memory_key", "chat_history"),
+ return_messages=kwargs.get("return_messages", True),
+ input_key=kwargs.get("input_key", "input"),
+ output_key=kwargs.get("output_key", "output"),
+ message_limit=kwargs.get("message_limit", 10),
+ )
+
+ return memory
+
+ @classmethod
+ def validate_query_tokens(cls, tenant_id: str, app_model_config: AppModelConfig, query: str):
+ llm = LLMBuilder.to_llm_from_model(
+ tenant_id=tenant_id,
+ model=app_model_config.model_dict
+ )
+
+ model_limited_tokens = llm_constant.max_context_token_length[llm.model_name]
+ max_tokens = llm.max_tokens
+
+ if model_limited_tokens - max_tokens - llm.get_num_tokens(query) < 0:
+ raise LLMBadRequestError("Query is too long")
+
+ @classmethod
+ def recale_llm_max_tokens(cls, final_llm: Union[StreamableOpenAI, StreamableChatOpenAI],
+ prompt: Union[str, List[BaseMessage]], mode: str):
+ # recalc max_tokens if sum(prompt_token + max_tokens) over model token limit
+ model_limited_tokens = llm_constant.max_context_token_length[final_llm.model_name]
+ max_tokens = final_llm.max_tokens
+
+ if mode == 'completion' and isinstance(final_llm, BaseLLM):
+ prompt_tokens = final_llm.get_num_tokens(prompt)
+ else:
+ prompt_tokens = final_llm.get_messages_tokens(prompt)
+
+ if prompt_tokens + max_tokens > model_limited_tokens:
+ max_tokens = max(model_limited_tokens - prompt_tokens, 16)
+ final_llm.max_tokens = max_tokens
+
+ @classmethod
+ def generate_more_like_this(cls, task_id: str, app: App, message: Message, pre_prompt: str,
+ app_model_config: AppModelConfig, user: Account, streaming: bool):
+ llm: StreamableOpenAI = LLMBuilder.to_llm(
+ tenant_id=app.tenant_id,
+ model_name='gpt-3.5-turbo',
+ streaming=streaming
+ )
+
+ # get llm prompt
+ original_prompt = cls.get_main_llm_prompt(
+ mode="completion",
+ llm=llm,
+ pre_prompt=pre_prompt,
+ query=message.query,
+ inputs=message.inputs,
+ chain_output=None,
+ memory=None
+ )
+
+ original_completion = message.answer.strip()
+
+ prompt = MORE_LIKE_THIS_GENERATE_PROMPT
+ prompt = prompt.format(prompt=original_prompt, original_completion=original_completion)
+
+ if isinstance(llm, BaseChatModel):
+ prompt = [HumanMessage(content=prompt)]
+
+ conversation_message_task = ConversationMessageTask(
+ task_id=task_id,
+ app=app,
+ app_model_config=app_model_config,
+ user=user,
+ inputs=message.inputs,
+ query=message.query,
+ is_override=True if message.override_model_configs else False,
+ streaming=streaming
+ )
+
+ llm.callback_manager = cls.get_llm_callback_manager(llm, streaming, conversation_message_task)
+
+ cls.recale_llm_max_tokens(
+ final_llm=llm,
+ prompt=prompt,
+ mode='completion'
+ )
+
+ llm.generate([prompt])
diff --git a/api/core/constant/llm_constant.py b/api/core/constant/llm_constant.py
new file mode 100644
index 00000000000..6879ec5b06f
--- /dev/null
+++ b/api/core/constant/llm_constant.py
@@ -0,0 +1,84 @@
+from _decimal import Decimal
+
+models = {
+ 'gpt-4': 'openai', # 8,192 tokens
+ 'gpt-4-32k': 'openai', # 32,768 tokens
+ 'gpt-3.5-turbo': 'openai', # 4,096 tokens
+ 'text-davinci-003': 'openai', # 4,097 tokens
+ 'text-davinci-002': 'openai', # 4,097 tokens
+ 'text-curie-001': 'openai', # 2,049 tokens
+ 'text-babbage-001': 'openai', # 2,049 tokens
+ 'text-ada-001': 'openai', # 2,049 tokens
+ 'text-embedding-ada-002': 'openai' # 8191 tokens, 1536 dimensions
+}
+
+max_context_token_length = {
+ 'gpt-4': 8192,
+ 'gpt-4-32k': 32768,
+ 'gpt-3.5-turbo': 4096,
+ 'text-davinci-003': 4097,
+ 'text-davinci-002': 4097,
+ 'text-curie-001': 2049,
+ 'text-babbage-001': 2049,
+ 'text-ada-001': 2049,
+ 'text-embedding-ada-002': 8191
+}
+
+models_by_mode = {
+ 'chat': [
+ 'gpt-4', # 8,192 tokens
+ 'gpt-4-32k', # 32,768 tokens
+ 'gpt-3.5-turbo', # 4,096 tokens
+ ],
+ 'completion': [
+ 'gpt-4', # 8,192 tokens
+ 'gpt-4-32k', # 32,768 tokens
+ 'gpt-3.5-turbo', # 4,096 tokens
+ 'text-davinci-003', # 4,097 tokens
+ 'text-davinci-002' # 4,097 tokens
+ 'text-curie-001', # 2,049 tokens
+ 'text-babbage-001', # 2,049 tokens
+ 'text-ada-001' # 2,049 tokens
+ ],
+ 'embedding': [
+ 'text-embedding-ada-002' # 8191 tokens, 1536 dimensions
+ ]
+}
+
+model_currency = 'USD'
+
+model_prices = {
+ 'gpt-4': {
+ 'prompt': Decimal('0.03'),
+ 'completion': Decimal('0.06'),
+ },
+ 'gpt-4-32k': {
+ 'prompt': Decimal('0.06'),
+ 'completion': Decimal('0.12')
+ },
+ 'gpt-3.5-turbo': {
+ 'prompt': Decimal('0.002'),
+ 'completion': Decimal('0.002')
+ },
+ 'text-davinci-003': {
+ 'prompt': Decimal('0.02'),
+ 'completion': Decimal('0.02')
+ },
+ 'text-curie-001': {
+ 'prompt': Decimal('0.002'),
+ 'completion': Decimal('0.002')
+ },
+ 'text-babbage-001': {
+ 'prompt': Decimal('0.0005'),
+ 'completion': Decimal('0.0005')
+ },
+ 'text-ada-001': {
+ 'prompt': Decimal('0.0004'),
+ 'completion': Decimal('0.0004')
+ },
+ 'text-embedding-ada-002': {
+ 'usage': Decimal('0.0004'),
+ }
+}
+
+agent_model_name = 'text-davinci-003'
diff --git a/api/core/conversation_message_task.py b/api/core/conversation_message_task.py
new file mode 100644
index 00000000000..0df26637a34
--- /dev/null
+++ b/api/core/conversation_message_task.py
@@ -0,0 +1,388 @@
+import decimal
+import json
+from typing import Optional, Union
+
+from gunicorn.config import User
+
+from core.callback_handler.entity.agent_loop import AgentLoop
+from core.callback_handler.entity.dataset_query import DatasetQueryObj
+from core.callback_handler.entity.llm_message import LLMMessage
+from core.callback_handler.entity.chain_result import ChainResult
+from core.constant import llm_constant
+from core.llm.llm_builder import LLMBuilder
+from core.llm.provider.llm_provider_service import LLMProviderService
+from core.prompt.prompt_builder import PromptBuilder
+from core.prompt.prompt_template import OutLinePromptTemplate
+from events.message_event import message_was_created
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DatasetQuery
+from models.model import AppModelConfig, Conversation, Account, Message, EndUser, App, MessageAgentThought, MessageChain
+from models.provider import ProviderType, Provider
+
+
+class ConversationMessageTask:
+ def __init__(self, task_id: str, app: App, app_model_config: AppModelConfig, user: Account,
+ inputs: dict, query: str, streaming: bool,
+ conversation: Optional[Conversation] = None, is_override: bool = False):
+ self.task_id = task_id
+
+ self.app = app
+ self.tenant_id = app.tenant_id
+ self.app_model_config = app_model_config
+ self.is_override = is_override
+
+ self.user = user
+ self.inputs = inputs
+ self.query = query
+ self.streaming = streaming
+
+ self.conversation = conversation
+ self.is_new_conversation = False
+
+ self.message = None
+
+ self.model_dict = self.app_model_config.model_dict
+ self.model_name = self.model_dict.get('name')
+ self.mode = app.mode
+
+ self.init()
+
+ self._pub_handler = PubHandler(
+ user=self.user,
+ task_id=self.task_id,
+ message=self.message,
+ conversation=self.conversation,
+ chain_pub=False, # disabled currently
+ agent_thought_pub=False # disabled currently
+ )
+
+ def init(self):
+ override_model_configs = None
+ if self.is_override:
+ override_model_configs = {
+ "model": self.app_model_config.model_dict,
+ "pre_prompt": self.app_model_config.pre_prompt,
+ "agent_mode": self.app_model_config.agent_mode_dict,
+ "opening_statement": self.app_model_config.opening_statement,
+ "suggested_questions": self.app_model_config.suggested_questions_list,
+ "suggested_questions_after_answer": self.app_model_config.suggested_questions_after_answer_dict,
+ "more_like_this": self.app_model_config.more_like_this_dict,
+ "user_input_form": self.app_model_config.user_input_form_list,
+ }
+
+ introduction = ''
+ system_instruction = ''
+ system_instruction_tokens = 0
+ if self.mode == 'chat':
+ introduction = self.app_model_config.opening_statement
+ if introduction:
+ prompt_template = OutLinePromptTemplate.from_template(template=PromptBuilder.process_template(introduction))
+ prompt_inputs = {k: self.inputs[k] for k in prompt_template.input_variables if k in self.inputs}
+ introduction = prompt_template.format(**prompt_inputs)
+
+ if self.app_model_config.pre_prompt:
+ pre_prompt = PromptBuilder.process_template(self.app_model_config.pre_prompt)
+ system_message = PromptBuilder.to_system_message(pre_prompt, self.inputs)
+ system_instruction = system_message.content
+ llm = LLMBuilder.to_llm(self.tenant_id, self.model_name)
+ system_instruction_tokens = llm.get_messages_tokens([system_message])
+
+ if not self.conversation:
+ self.is_new_conversation = True
+ self.conversation = Conversation(
+ app_id=self.app_model_config.app_id,
+ app_model_config_id=self.app_model_config.id,
+ model_provider=self.model_dict.get('provider'),
+ model_id=self.model_name,
+ override_model_configs=json.dumps(override_model_configs) if override_model_configs else None,
+ mode=self.mode,
+ name='',
+ inputs=self.inputs,
+ introduction=introduction,
+ system_instruction=system_instruction,
+ system_instruction_tokens=system_instruction_tokens,
+ status='normal',
+ from_source=('console' if isinstance(self.user, Account) else 'api'),
+ from_end_user_id=(self.user.id if isinstance(self.user, EndUser) else None),
+ from_account_id=(self.user.id if isinstance(self.user, Account) else None),
+ )
+
+ db.session.add(self.conversation)
+ db.session.flush()
+
+ self.message = Message(
+ app_id=self.app_model_config.app_id,
+ model_provider=self.model_dict.get('provider'),
+ model_id=self.model_name,
+ override_model_configs=json.dumps(override_model_configs) if override_model_configs else None,
+ conversation_id=self.conversation.id,
+ inputs=self.inputs,
+ query=self.query,
+ message="",
+ message_tokens=0,
+ message_unit_price=0,
+ answer="",
+ answer_tokens=0,
+ answer_unit_price=0,
+ provider_response_latency=0,
+ total_price=0,
+ currency=llm_constant.model_currency,
+ from_source=('console' if isinstance(self.user, Account) else 'api'),
+ from_end_user_id=(self.user.id if isinstance(self.user, EndUser) else None),
+ from_account_id=(self.user.id if isinstance(self.user, Account) else None),
+ agent_based=self.app_model_config.agent_mode_dict.get('enabled'),
+ )
+
+ db.session.add(self.message)
+ db.session.flush()
+
+ def append_message_text(self, text: str):
+ self._pub_handler.pub_text(text)
+
+ def save_message(self, llm_message: LLMMessage, by_stopped: bool = False):
+ model_name = self.app_model_config.model_dict.get('name')
+
+ message_tokens = llm_message.prompt_tokens
+ answer_tokens = llm_message.completion_tokens
+ message_unit_price = llm_constant.model_prices[model_name]['prompt']
+ answer_unit_price = llm_constant.model_prices[model_name]['completion']
+
+ total_price = self.calc_total_price(message_tokens, message_unit_price, answer_tokens, answer_unit_price)
+
+ self.message.message = llm_message.prompt
+ self.message.message_tokens = message_tokens
+ self.message.message_unit_price = message_unit_price
+ self.message.answer = llm_message.completion.strip() if llm_message.completion else ''
+ self.message.answer_tokens = answer_tokens
+ self.message.answer_unit_price = answer_unit_price
+ self.message.provider_response_latency = llm_message.latency
+ self.message.total_price = total_price
+
+ self.update_provider_quota()
+
+ db.session.commit()
+
+ message_was_created.send(
+ self.message,
+ conversation=self.conversation,
+ is_first_message=self.is_new_conversation
+ )
+
+ if not by_stopped:
+ self._pub_handler.pub_end()
+
+ def update_provider_quota(self):
+ llm_provider_service = LLMProviderService(
+ tenant_id=self.app.tenant_id,
+ provider_name=self.message.model_provider,
+ )
+
+ provider = llm_provider_service.get_provider_db_record()
+ if provider and provider.provider_type == ProviderType.SYSTEM.value:
+ db.session.query(Provider).filter(
+ Provider.tenant_id == self.app.tenant_id,
+ Provider.quota_limit > Provider.quota_used
+ ).update({'quota_used': Provider.quota_used + 1})
+
+ def init_chain(self, chain_result: ChainResult):
+ message_chain = MessageChain(
+ message_id=self.message.id,
+ type=chain_result.type,
+ input=json.dumps(chain_result.prompt),
+ output=''
+ )
+
+ db.session.add(message_chain)
+ db.session.flush()
+
+ return message_chain
+
+ def on_chain_end(self, message_chain: MessageChain, chain_result: ChainResult):
+ message_chain.output = json.dumps(chain_result.completion)
+
+ self._pub_handler.pub_chain(message_chain)
+
+ def on_agent_end(self, message_chain: MessageChain, agent_model_name: str,
+ agent_loop: AgentLoop):
+ agent_message_unit_price = llm_constant.model_prices[agent_model_name]['prompt']
+ agent_answer_unit_price = llm_constant.model_prices[agent_model_name]['completion']
+
+ loop_message_tokens = agent_loop.prompt_tokens
+ loop_answer_tokens = agent_loop.completion_tokens
+
+ loop_total_price = self.calc_total_price(
+ loop_message_tokens,
+ agent_message_unit_price,
+ loop_answer_tokens,
+ agent_answer_unit_price
+ )
+
+ message_agent_loop = MessageAgentThought(
+ message_id=self.message.id,
+ message_chain_id=message_chain.id,
+ position=agent_loop.position,
+ thought=agent_loop.thought,
+ tool=agent_loop.tool_name,
+ tool_input=agent_loop.tool_input,
+ observation=agent_loop.tool_output,
+ tool_process_data='', # currently not support
+ message=agent_loop.prompt,
+ message_token=loop_message_tokens,
+ message_unit_price=agent_message_unit_price,
+ answer=agent_loop.completion,
+ answer_token=loop_answer_tokens,
+ answer_unit_price=agent_answer_unit_price,
+ latency=agent_loop.latency,
+ tokens=agent_loop.prompt_tokens + agent_loop.completion_tokens,
+ total_price=loop_total_price,
+ currency=llm_constant.model_currency,
+ created_by_role=('account' if isinstance(self.user, Account) else 'end_user'),
+ created_by=self.user.id
+ )
+
+ db.session.add(message_agent_loop)
+ db.session.flush()
+
+ self._pub_handler.pub_agent_thought(message_agent_loop)
+
+ def on_dataset_query_end(self, dataset_query_obj: DatasetQueryObj):
+ dataset_query = DatasetQuery(
+ dataset_id=dataset_query_obj.dataset_id,
+ content=dataset_query_obj.query,
+ source='app',
+ source_app_id=self.app.id,
+ created_by_role=('account' if isinstance(self.user, Account) else 'end_user'),
+ created_by=self.user.id
+ )
+
+ db.session.add(dataset_query)
+
+ def calc_total_price(self, message_tokens, message_unit_price, answer_tokens, answer_unit_price):
+ message_tokens_per_1k = (decimal.Decimal(message_tokens) / 1000).quantize(decimal.Decimal('0.001'),
+ rounding=decimal.ROUND_HALF_UP)
+ answer_tokens_per_1k = (decimal.Decimal(answer_tokens) / 1000).quantize(decimal.Decimal('0.001'),
+ rounding=decimal.ROUND_HALF_UP)
+
+ total_price = message_tokens_per_1k * message_unit_price + answer_tokens_per_1k * answer_unit_price
+ return total_price.quantize(decimal.Decimal('0.0000001'), rounding=decimal.ROUND_HALF_UP)
+
+
+class PubHandler:
+ def __init__(self, user: Union[Account | User], task_id: str,
+ message: Message, conversation: Conversation,
+ chain_pub: bool = False, agent_thought_pub: bool = False):
+ self._channel = PubHandler.generate_channel_name(user, task_id)
+ self._stopped_cache_key = PubHandler.generate_stopped_cache_key(user, task_id)
+
+ self._task_id = task_id
+ self._message = message
+ self._conversation = conversation
+ self._chain_pub = chain_pub
+ self._agent_thought_pub = agent_thought_pub
+
+ @classmethod
+ def generate_channel_name(cls, user: Union[Account | User], task_id: str):
+ user_str = 'account-' + user.id if isinstance(user, Account) else 'end-user-' + user.id
+ return "generate_result:{}-{}".format(user_str, task_id)
+
+ @classmethod
+ def generate_stopped_cache_key(cls, user: Union[Account | User], task_id: str):
+ user_str = 'account-' + user.id if isinstance(user, Account) else 'end-user-' + user.id
+ return "generate_result_stopped:{}-{}".format(user_str, task_id)
+
+ def pub_text(self, text: str):
+ content = {
+ 'event': 'message',
+ 'data': {
+ 'task_id': self._task_id,
+ 'message_id': self._message.id,
+ 'text': text,
+ 'mode': self._conversation.mode,
+ 'conversation_id': self._conversation.id
+ }
+ }
+
+ redis_client.publish(self._channel, json.dumps(content))
+
+ if self._is_stopped():
+ self.pub_end()
+ raise ConversationTaskStoppedException()
+
+ def pub_chain(self, message_chain: MessageChain):
+ if self._chain_pub:
+ content = {
+ 'event': 'chain',
+ 'data': {
+ 'task_id': self._task_id,
+ 'message_id': self._message.id,
+ 'chain_id': message_chain.id,
+ 'type': message_chain.type,
+ 'input': json.loads(message_chain.input),
+ 'output': json.loads(message_chain.output),
+ 'mode': self._conversation.mode,
+ 'conversation_id': self._conversation.id
+ }
+ }
+
+ redis_client.publish(self._channel, json.dumps(content))
+
+ if self._is_stopped():
+ self.pub_end()
+ raise ConversationTaskStoppedException()
+
+ def pub_agent_thought(self, message_agent_thought: MessageAgentThought):
+ if self._agent_thought_pub:
+ content = {
+ 'event': 'agent_thought',
+ 'data': {
+ 'task_id': self._task_id,
+ 'message_id': self._message.id,
+ 'chain_id': message_agent_thought.message_chain_id,
+ 'agent_thought_id': message_agent_thought.id,
+ 'position': message_agent_thought.position,
+ 'thought': message_agent_thought.thought,
+ 'tool': message_agent_thought.tool,
+ 'tool_input': message_agent_thought.tool_input,
+ 'observation': message_agent_thought.observation,
+ 'answer': message_agent_thought.answer,
+ 'mode': self._conversation.mode,
+ 'conversation_id': self._conversation.id
+ }
+ }
+
+ redis_client.publish(self._channel, json.dumps(content))
+
+ if self._is_stopped():
+ self.pub_end()
+ raise ConversationTaskStoppedException()
+
+
+ def pub_end(self):
+ content = {
+ 'event': 'end',
+ }
+
+ redis_client.publish(self._channel, json.dumps(content))
+
+ @classmethod
+ def pub_error(cls, user: Union[Account | User], task_id: str, e):
+ content = {
+ 'error': type(e).__name__,
+ 'description': e.description if getattr(e, 'description', None) is not None else str(e)
+ }
+
+ channel = cls.generate_channel_name(user, task_id)
+ redis_client.publish(channel, json.dumps(content))
+
+ def _is_stopped(self):
+ return redis_client.get(self._stopped_cache_key) is not None
+
+ @classmethod
+ def stop(cls, user: Union[Account | User], task_id: str):
+ stopped_cache_key = cls.generate_stopped_cache_key(user, task_id)
+ redis_client.setex(stopped_cache_key, 600, 1)
+
+
+class ConversationTaskStoppedException(Exception):
+ pass
diff --git a/api/core/docstore/dataset_docstore.py b/api/core/docstore/dataset_docstore.py
new file mode 100644
index 00000000000..b3b968532cc
--- /dev/null
+++ b/api/core/docstore/dataset_docstore.py
@@ -0,0 +1,190 @@
+from typing import Any, Dict, Optional, Sequence
+
+import tiktoken
+from llama_index.data_structs import Node
+from llama_index.docstore.types import BaseDocumentStore
+from llama_index.docstore.utils import json_to_doc
+from llama_index.schema import BaseDocument
+from sqlalchemy import func
+
+from core.llm.token_calculator import TokenCalculator
+from extensions.ext_database import db
+from models.dataset import Dataset, DocumentSegment
+
+
+class DatesetDocumentStore(BaseDocumentStore):
+ def __init__(
+ self,
+ dataset: Dataset,
+ user_id: str,
+ embedding_model_name: str,
+ document_id: Optional[str] = None,
+ ):
+ self._dataset = dataset
+ self._user_id = user_id
+ self._embedding_model_name = embedding_model_name
+ self._document_id = document_id
+
+ @classmethod
+ def from_dict(cls, config_dict: Dict[str, Any]) -> "DatesetDocumentStore":
+ return cls(**config_dict)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Serialize to dict."""
+ return {
+ "dataset_id": self._dataset.id,
+ }
+
+ @property
+ def dateset_id(self) -> Any:
+ return self._dataset.id
+
+ @property
+ def user_id(self) -> Any:
+ return self._user_id
+
+ @property
+ def embedding_model_name(self) -> Any:
+ return self._embedding_model_name
+
+ @property
+ def docs(self) -> Dict[str, BaseDocument]:
+ document_segments = db.session.query(DocumentSegment).filter(
+ DocumentSegment.dataset_id == self._dataset.id
+ ).all()
+
+ output = {}
+ for document_segment in document_segments:
+ doc_id = document_segment.index_node_id
+ result = self.segment_to_dict(document_segment)
+ output[doc_id] = json_to_doc(result)
+
+ return output
+
+ def add_documents(
+ self, docs: Sequence[BaseDocument], allow_update: bool = True
+ ) -> None:
+ max_position = db.session.query(func.max(DocumentSegment.position)).filter(
+ DocumentSegment.document == self._document_id
+ ).scalar()
+
+ if max_position is None:
+ max_position = 0
+
+ for doc in docs:
+ if doc.is_doc_id_none:
+ raise ValueError("doc_id not set")
+
+ if not isinstance(doc, Node):
+ raise ValueError("doc must be a Node")
+
+ segment_document = self.get_document(doc_id=doc.get_doc_id(), raise_error=False)
+
+ # NOTE: doc could already exist in the store, but we overwrite it
+ if not allow_update and segment_document:
+ raise ValueError(
+ f"doc_id {doc.get_doc_id()} already exists. "
+ "Set allow_update to True to overwrite."
+ )
+
+ # calc embedding use tokens
+ tokens = TokenCalculator.get_num_tokens(self._embedding_model_name, doc.get_text())
+
+ if not segment_document:
+ max_position += 1
+
+ segment_document = DocumentSegment(
+ tenant_id=self._dataset.tenant_id,
+ dataset_id=self._dataset.id,
+ document_id=self._document_id,
+ index_node_id=doc.get_doc_id(),
+ index_node_hash=doc.get_doc_hash(),
+ position=max_position,
+ content=doc.get_text(),
+ word_count=len(doc.get_text()),
+ tokens=tokens,
+ created_by=self._user_id,
+ )
+ db.session.add(segment_document)
+ else:
+ segment_document.content = doc.get_text()
+ segment_document.index_node_hash = doc.get_doc_hash()
+ segment_document.word_count = len(doc.get_text())
+ segment_document.tokens = tokens
+
+ db.session.commit()
+
+ def document_exists(self, doc_id: str) -> bool:
+ """Check if document exists."""
+ result = self.get_document_segment(doc_id)
+ return result is not None
+
+ def get_document(
+ self, doc_id: str, raise_error: bool = True
+ ) -> Optional[BaseDocument]:
+ document_segment = self.get_document_segment(doc_id)
+
+ if document_segment is None:
+ if raise_error:
+ raise ValueError(f"doc_id {doc_id} not found.")
+ else:
+ return None
+
+ result = self.segment_to_dict(document_segment)
+ return json_to_doc(result)
+
+ def delete_document(self, doc_id: str, raise_error: bool = True) -> None:
+ document_segment = self.get_document_segment(doc_id)
+
+ if document_segment is None:
+ if raise_error:
+ raise ValueError(f"doc_id {doc_id} not found.")
+ else:
+ return None
+
+ db.session.delete(document_segment)
+ db.session.commit()
+
+ def set_document_hash(self, doc_id: str, doc_hash: str) -> None:
+ """Set the hash for a given doc_id."""
+ document_segment = self.get_document_segment(doc_id)
+
+ if document_segment is None:
+ return None
+
+ document_segment.index_node_hash = doc_hash
+ db.session.commit()
+
+ def get_document_hash(self, doc_id: str) -> Optional[str]:
+ """Get the stored hash for a document, if it exists."""
+ document_segment = self.get_document_segment(doc_id)
+
+ if document_segment is None:
+ return None
+
+ return document_segment.index_node_hash
+
+ def update_docstore(self, other: "BaseDocumentStore") -> None:
+ """Update docstore.
+
+ Args:
+ other (BaseDocumentStore): docstore to update from
+
+ """
+ self.add_documents(list(other.docs.values()))
+
+ def get_document_segment(self, doc_id: str) -> DocumentSegment:
+ document_segment = db.session.query(DocumentSegment).filter(
+ DocumentSegment.dataset_id == self._dataset.id,
+ DocumentSegment.index_node_id == doc_id
+ ).first()
+
+ return document_segment
+
+ def segment_to_dict(self, segment: DocumentSegment) -> Dict[str, Any]:
+ return {
+ "doc_id": segment.index_node_id,
+ "doc_hash": segment.index_node_hash,
+ "text": segment.content,
+ "__type__": Node.get_type()
+ }
diff --git a/api/core/docstore/empty_docstore.py b/api/core/docstore/empty_docstore.py
new file mode 100644
index 00000000000..e19f1824cbb
--- /dev/null
+++ b/api/core/docstore/empty_docstore.py
@@ -0,0 +1,51 @@
+from typing import Any, Dict, Optional, Sequence
+from llama_index.docstore.types import BaseDocumentStore
+from llama_index.schema import BaseDocument
+
+
+class EmptyDocumentStore(BaseDocumentStore):
+ @classmethod
+ def from_dict(cls, config_dict: Dict[str, Any]) -> "EmptyDocumentStore":
+ return cls()
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Serialize to dict."""
+ return {}
+
+ @property
+ def docs(self) -> Dict[str, BaseDocument]:
+ return {}
+
+ def add_documents(
+ self, docs: Sequence[BaseDocument], allow_update: bool = True
+ ) -> None:
+ pass
+
+ def document_exists(self, doc_id: str) -> bool:
+ """Check if document exists."""
+ return False
+
+ def get_document(
+ self, doc_id: str, raise_error: bool = True
+ ) -> Optional[BaseDocument]:
+ return None
+
+ def delete_document(self, doc_id: str, raise_error: bool = True) -> None:
+ pass
+
+ def set_document_hash(self, doc_id: str, doc_hash: str) -> None:
+ """Set the hash for a given doc_id."""
+ pass
+
+ def get_document_hash(self, doc_id: str) -> Optional[str]:
+ """Get the stored hash for a document, if it exists."""
+ return None
+
+ def update_docstore(self, other: "BaseDocumentStore") -> None:
+ """Update docstore.
+
+ Args:
+ other (BaseDocumentStore): docstore to update from
+
+ """
+ self.add_documents(list(other.docs.values()))
diff --git a/api/core/embedding/openai_embedding.py b/api/core/embedding/openai_embedding.py
new file mode 100644
index 00000000000..09383974232
--- /dev/null
+++ b/api/core/embedding/openai_embedding.py
@@ -0,0 +1,176 @@
+from typing import Optional, Any, List
+
+import openai
+from llama_index.embeddings.base import BaseEmbedding
+from llama_index.embeddings.openai import OpenAIEmbeddingMode, OpenAIEmbeddingModelType, _QUERY_MODE_MODEL_DICT, \
+ _TEXT_MODE_MODEL_DICT
+from tenacity import wait_random_exponential, retry, stop_after_attempt
+
+from core.llm.error_handle_wraps import handle_llm_exceptions, handle_llm_exceptions_async
+
+
+@retry(reraise=True, wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6))
+def get_embedding(
+ text: str,
+ engine: Optional[str] = None,
+ openai_api_key: Optional[str] = None,
+) -> List[float]:
+ """Get embedding.
+
+ NOTE: Copied from OpenAI's embedding utils:
+ https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py
+
+ Copied here to avoid importing unnecessary dependencies
+ like matplotlib, plotly, scipy, sklearn.
+
+ """
+ text = text.replace("\n", " ")
+ return openai.Embedding.create(input=[text], engine=engine, api_key=openai_api_key)["data"][0]["embedding"]
+
+
+@retry(reraise=True, wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6))
+async def aget_embedding(text: str, engine: Optional[str] = None, openai_api_key: Optional[str] = None) -> List[float]:
+ """Asynchronously get embedding.
+
+ NOTE: Copied from OpenAI's embedding utils:
+ https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py
+
+ Copied here to avoid importing unnecessary dependencies
+ like matplotlib, plotly, scipy, sklearn.
+
+ """
+ # replace newlines, which can negatively affect performance.
+ text = text.replace("\n", " ")
+
+ return (await openai.Embedding.acreate(input=[text], engine=engine, api_key=openai_api_key))["data"][0][
+ "embedding"
+ ]
+
+
+@retry(reraise=True, wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6))
+def get_embeddings(
+ list_of_text: List[str],
+ engine: Optional[str] = None,
+ openai_api_key: Optional[str] = None
+) -> List[List[float]]:
+ """Get embeddings.
+
+ NOTE: Copied from OpenAI's embedding utils:
+ https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py
+
+ Copied here to avoid importing unnecessary dependencies
+ like matplotlib, plotly, scipy, sklearn.
+
+ """
+ assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048."
+
+ # replace newlines, which can negatively affect performance.
+ list_of_text = [text.replace("\n", " ") for text in list_of_text]
+
+ data = openai.Embedding.create(input=list_of_text, engine=engine, api_key=openai_api_key).data
+ data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input.
+ return [d["embedding"] for d in data]
+
+
+@retry(reraise=True, wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6))
+async def aget_embeddings(
+ list_of_text: List[str], engine: Optional[str] = None, openai_api_key: Optional[str] = None
+) -> List[List[float]]:
+ """Asynchronously get embeddings.
+
+ NOTE: Copied from OpenAI's embedding utils:
+ https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py
+
+ Copied here to avoid importing unnecessary dependencies
+ like matplotlib, plotly, scipy, sklearn.
+
+ """
+ assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048."
+
+ # replace newlines, which can negatively affect performance.
+ list_of_text = [text.replace("\n", " ") for text in list_of_text]
+
+ data = (await openai.Embedding.acreate(input=list_of_text, engine=engine, api_key=openai_api_key)).data
+ data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input.
+ return [d["embedding"] for d in data]
+
+
+class OpenAIEmbedding(BaseEmbedding):
+
+ def __init__(
+ self,
+ mode: str = OpenAIEmbeddingMode.TEXT_SEARCH_MODE,
+ model: str = OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002,
+ deployment_name: Optional[str] = None,
+ openai_api_key: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Init params."""
+ super().__init__(**kwargs)
+ self.mode = OpenAIEmbeddingMode(mode)
+ self.model = OpenAIEmbeddingModelType(model)
+ self.deployment_name = deployment_name
+ self.openai_api_key = openai_api_key
+
+ @handle_llm_exceptions
+ def _get_query_embedding(self, query: str) -> List[float]:
+ """Get query embedding."""
+ if self.deployment_name is not None:
+ engine = self.deployment_name
+ else:
+ key = (self.mode, self.model)
+ if key not in _QUERY_MODE_MODEL_DICT:
+ raise ValueError(f"Invalid mode, model combination: {key}")
+ engine = _QUERY_MODE_MODEL_DICT[key]
+ return get_embedding(query, engine=engine, openai_api_key=self.openai_api_key)
+
+ def _get_text_embedding(self, text: str) -> List[float]:
+ """Get text embedding."""
+ if self.deployment_name is not None:
+ engine = self.deployment_name
+ else:
+ key = (self.mode, self.model)
+ if key not in _TEXT_MODE_MODEL_DICT:
+ raise ValueError(f"Invalid mode, model combination: {key}")
+ engine = _TEXT_MODE_MODEL_DICT[key]
+ return get_embedding(text, engine=engine, openai_api_key=self.openai_api_key)
+
+ async def _aget_text_embedding(self, text: str) -> List[float]:
+ """Asynchronously get text embedding."""
+ if self.deployment_name is not None:
+ engine = self.deployment_name
+ else:
+ key = (self.mode, self.model)
+ if key not in _TEXT_MODE_MODEL_DICT:
+ raise ValueError(f"Invalid mode, model combination: {key}")
+ engine = _TEXT_MODE_MODEL_DICT[key]
+ return await aget_embedding(text, engine=engine, openai_api_key=self.openai_api_key)
+
+ def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Get text embeddings.
+
+ By default, this is a wrapper around _get_text_embedding.
+ Can be overriden for batch queries.
+
+ """
+ if self.deployment_name is not None:
+ engine = self.deployment_name
+ else:
+ key = (self.mode, self.model)
+ if key not in _TEXT_MODE_MODEL_DICT:
+ raise ValueError(f"Invalid mode, model combination: {key}")
+ engine = _TEXT_MODE_MODEL_DICT[key]
+ embeddings = get_embeddings(texts, engine=engine, openai_api_key=self.openai_api_key)
+ return embeddings
+
+ async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Asynchronously get text embeddings."""
+ if self.deployment_name is not None:
+ engine = self.deployment_name
+ else:
+ key = (self.mode, self.model)
+ if key not in _TEXT_MODE_MODEL_DICT:
+ raise ValueError(f"Invalid mode, model combination: {key}")
+ engine = _TEXT_MODE_MODEL_DICT[key]
+ embeddings = await aget_embeddings(texts, engine=engine, openai_api_key=self.openai_api_key)
+ return embeddings
diff --git a/api/core/generator/llm_generator.py b/api/core/generator/llm_generator.py
new file mode 100644
index 00000000000..67e5753007f
--- /dev/null
+++ b/api/core/generator/llm_generator.py
@@ -0,0 +1,120 @@
+import logging
+
+from langchain.chat_models.base import BaseChatModel
+from langchain.schema import HumanMessage
+
+from core.constant import llm_constant
+from core.llm.llm_builder import LLMBuilder
+from core.llm.streamable_open_ai import StreamableOpenAI
+from core.llm.token_calculator import TokenCalculator
+
+from core.prompt.output_parser.suggested_questions_after_answer import SuggestedQuestionsAfterAnswerOutputParser
+from core.prompt.prompt_template import OutLinePromptTemplate
+from core.prompt.prompts import CONVERSATION_TITLE_PROMPT, CONVERSATION_SUMMARY_PROMPT, INTRODUCTION_GENERATE_PROMPT
+
+
+# gpt-3.5-turbo works not well
+generate_base_model = 'text-davinci-003'
+
+
+class LLMGenerator:
+ @classmethod
+ def generate_conversation_name(cls, tenant_id: str, query, answer):
+ prompt = CONVERSATION_TITLE_PROMPT
+ prompt = prompt.format(query=query, answer=answer)
+ llm: StreamableOpenAI = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name=generate_base_model,
+ max_tokens=50
+ )
+
+ if isinstance(llm, BaseChatModel):
+ prompt = [HumanMessage(content=prompt)]
+
+ response = llm.generate([prompt])
+ answer = response.generations[0][0].text
+ return answer.strip()
+
+ @classmethod
+ def generate_conversation_summary(cls, tenant_id: str, messages):
+ max_tokens = 200
+
+ prompt = CONVERSATION_SUMMARY_PROMPT
+ prompt_with_empty_context = prompt.format(context='')
+ prompt_tokens = TokenCalculator.get_num_tokens(generate_base_model, prompt_with_empty_context)
+ rest_tokens = llm_constant.max_context_token_length[generate_base_model] - prompt_tokens - max_tokens
+
+ context = ''
+ for message in messages:
+ if not message.answer:
+ continue
+
+ message_qa_text = "Human:" + message.query + "\nAI:" + message.answer + "\n"
+ if rest_tokens - TokenCalculator.get_num_tokens(generate_base_model, context + message_qa_text) > 0:
+ context += message_qa_text
+
+ prompt = prompt.format(context=context)
+
+ llm: StreamableOpenAI = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name=generate_base_model,
+ max_tokens=max_tokens
+ )
+
+ if isinstance(llm, BaseChatModel):
+ prompt = [HumanMessage(content=prompt)]
+
+ response = llm.generate([prompt])
+ answer = response.generations[0][0].text
+ return answer.strip()
+
+ @classmethod
+ def generate_introduction(cls, tenant_id: str, pre_prompt: str):
+ prompt = INTRODUCTION_GENERATE_PROMPT
+ prompt = prompt.format(prompt=pre_prompt)
+
+ llm: StreamableOpenAI = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name=generate_base_model,
+ )
+
+ if isinstance(llm, BaseChatModel):
+ prompt = [HumanMessage(content=prompt)]
+
+ response = llm.generate([prompt])
+ answer = response.generations[0][0].text
+ return answer.strip()
+
+ @classmethod
+ def generate_suggested_questions_after_answer(cls, tenant_id: str, histories: str):
+ output_parser = SuggestedQuestionsAfterAnswerOutputParser()
+ format_instructions = output_parser.get_format_instructions()
+
+ prompt = OutLinePromptTemplate(
+ template="{histories}\n{format_instructions}\nquestions:\n",
+ input_variables=["histories"],
+ partial_variables={"format_instructions": format_instructions}
+ )
+
+ _input = prompt.format_prompt(histories=histories)
+
+ llm: StreamableOpenAI = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name=generate_base_model,
+ temperature=0,
+ max_tokens=256
+ )
+
+ if isinstance(llm, BaseChatModel):
+ query = [HumanMessage(content=_input.to_string())]
+ else:
+ query = _input.to_string()
+
+ try:
+ output = llm(query)
+ questions = output_parser.parse(output)
+ except Exception:
+ logging.exception("Error generating suggested questions after answer")
+ questions = []
+
+ return questions
diff --git a/api/core/index/index_builder.py b/api/core/index/index_builder.py
new file mode 100644
index 00000000000..baf16b0f3aa
--- /dev/null
+++ b/api/core/index/index_builder.py
@@ -0,0 +1,45 @@
+from langchain.callbacks import CallbackManager
+from llama_index import ServiceContext, PromptHelper, LLMPredictor
+from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
+from core.embedding.openai_embedding import OpenAIEmbedding
+from core.llm.llm_builder import LLMBuilder
+
+
+class IndexBuilder:
+ @classmethod
+ def get_default_service_context(cls, tenant_id: str) -> ServiceContext:
+ # set number of output tokens
+ num_output = 512
+
+ # only for verbose
+ callback_manager = CallbackManager([DifyStdOutCallbackHandler()])
+
+ llm = LLMBuilder.to_llm(
+ tenant_id=tenant_id,
+ model_name='text-davinci-003',
+ temperature=0,
+ max_tokens=num_output,
+ callback_manager=callback_manager,
+ )
+
+ llm_predictor = LLMPredictor(llm=llm)
+
+ # These parameters here will affect the logic of segmenting the final synthesized response.
+ # The number of refinement iterations in the synthesis process depends
+ # on whether the length of the segmented output exceeds the max_input_size.
+ prompt_helper = PromptHelper(
+ max_input_size=3500,
+ num_output=num_output,
+ max_chunk_overlap=20
+ )
+
+ model_credentials = LLMBuilder.get_model_credentials(
+ tenant_id=tenant_id,
+ model_name='text-embedding-ada-002'
+ )
+
+ return ServiceContext.from_defaults(
+ llm_predictor=llm_predictor,
+ prompt_helper=prompt_helper,
+ embed_model=OpenAIEmbedding(**model_credentials),
+ )
diff --git a/api/core/index/keyword_table/jieba_keyword_table.py b/api/core/index/keyword_table/jieba_keyword_table.py
new file mode 100644
index 00000000000..89dcca5802d
--- /dev/null
+++ b/api/core/index/keyword_table/jieba_keyword_table.py
@@ -0,0 +1,159 @@
+import re
+from typing import (
+ Any,
+ Dict,
+ List,
+ Set,
+ Optional
+)
+
+import jieba.analyse
+
+from core.index.keyword_table.stopwords import STOPWORDS
+from llama_index.indices.query.base import IS
+from llama_index import QueryMode
+from llama_index.indices.base import QueryMap
+from llama_index.indices.keyword_table.base import BaseGPTKeywordTableIndex
+from llama_index.indices.keyword_table.query import BaseGPTKeywordTableQuery
+from llama_index.docstore import BaseDocumentStore
+from llama_index.indices.postprocessor.node import (
+ BaseNodePostprocessor,
+)
+from llama_index.indices.response.response_builder import ResponseMode
+from llama_index.indices.service_context import ServiceContext
+from llama_index.optimization.optimizer import BaseTokenUsageOptimizer
+from llama_index.prompts.prompts import (
+ QuestionAnswerPrompt,
+ RefinePrompt,
+ SimpleInputPrompt,
+)
+
+from core.index.query.synthesizer import EnhanceResponseSynthesizer
+
+
+def jieba_extract_keywords(
+ text_chunk: str,
+ max_keywords: Optional[int] = None,
+ expand_with_subtokens: bool = True,
+) -> Set[str]:
+ """Extract keywords with JIEBA tfidf."""
+ keywords = jieba.analyse.extract_tags(
+ sentence=text_chunk,
+ topK=max_keywords,
+ )
+
+ if expand_with_subtokens:
+ return set(expand_tokens_with_subtokens(keywords))
+ else:
+ return set(keywords)
+
+
+def expand_tokens_with_subtokens(tokens: Set[str]) -> Set[str]:
+ """Get subtokens from a list of tokens., filtering for stopwords."""
+ results = set()
+ for token in tokens:
+ results.add(token)
+ sub_tokens = re.findall(r"\w+", token)
+ if len(sub_tokens) > 1:
+ results.update({w for w in sub_tokens if w not in list(STOPWORDS)})
+
+ return results
+
+
+class GPTJIEBAKeywordTableIndex(BaseGPTKeywordTableIndex):
+ """GPT JIEBA Keyword Table Index.
+
+ This index uses a JIEBA keyword extractor to extract keywords from the text.
+
+ """
+
+ def _extract_keywords(self, text: str) -> Set[str]:
+ """Extract keywords from text."""
+ return jieba_extract_keywords(text, max_keywords=self.max_keywords_per_chunk)
+
+ @classmethod
+ def get_query_map(self) -> QueryMap:
+ """Get query map."""
+ super_map = super().get_query_map()
+ super_map[QueryMode.DEFAULT] = GPTKeywordTableJIEBAQuery
+ return super_map
+
+ def _delete(self, doc_id: str, **delete_kwargs: Any) -> None:
+ """Delete a document."""
+ # get set of ids that correspond to node
+ node_idxs_to_delete = {doc_id}
+
+ # delete node_idxs from keyword to node idxs mapping
+ keywords_to_delete = set()
+ for keyword, node_idxs in self._index_struct.table.items():
+ if node_idxs_to_delete.intersection(node_idxs):
+ self._index_struct.table[keyword] = node_idxs.difference(
+ node_idxs_to_delete
+ )
+ if not self._index_struct.table[keyword]:
+ keywords_to_delete.add(keyword)
+
+ for keyword in keywords_to_delete:
+ del self._index_struct.table[keyword]
+
+
+class GPTKeywordTableJIEBAQuery(BaseGPTKeywordTableQuery):
+ """GPT Keyword Table Index JIEBA Query.
+
+ Extracts keywords using JIEBA keyword extractor.
+ Set when `mode="jieba"` in `query` method of `GPTKeywordTableIndex`.
+
+ .. code-block:: python
+
+ response = index.query("<query_str>", mode="jieba")
+
+ See BaseGPTKeywordTableQuery for arguments.
+
+ """
+
+ @classmethod
+ def from_args(
+ cls,
+ index_struct: IS,
+ service_context: ServiceContext,
+ docstore: Optional[BaseDocumentStore] = None,
+ node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
+ verbose: bool = False,
+ # response synthesizer args
+ response_mode: ResponseMode = ResponseMode.DEFAULT,
+ text_qa_template: Optional[QuestionAnswerPrompt] = None,
+ refine_template: Optional[RefinePrompt] = None,
+ simple_template: Optional[SimpleInputPrompt] = None,
+ response_kwargs: Optional[Dict] = None,
+ use_async: bool = False,
+ streaming: bool = False,
+ optimizer: Optional[BaseTokenUsageOptimizer] = None,
+ # class-specific args
+ **kwargs: Any,
+ ) -> "BaseGPTIndexQuery":
+ response_synthesizer = EnhanceResponseSynthesizer.from_args(
+ service_context=service_context,
+ text_qa_template=text_qa_template,
+ refine_template=refine_template,
+ simple_template=simple_template,
+ response_mode=response_mode,
+ response_kwargs=response_kwargs,
+ use_async=use_async,
+ streaming=streaming,
+ optimizer=optimizer,
+ )
+ return cls(
+ index_struct=index_struct,
+ service_context=service_context,
+ response_synthesizer=response_synthesizer,
+ docstore=docstore,
+ node_postprocessors=node_postprocessors,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _get_keywords(self, query_str: str) -> List[str]:
+ """Extract keywords."""
+ return list(
+ jieba_extract_keywords(query_str, max_keywords=self.max_keywords_per_query)
+ )
diff --git a/api/core/index/keyword_table/stopwords.py b/api/core/index/keyword_table/stopwords.py
new file mode 100644
index 00000000000..c616a15cf0c
--- /dev/null
+++ b/api/core/index/keyword_table/stopwords.py
@@ -0,0 +1,90 @@
+STOPWORDS = {
+ "during", "when", "but", "then", "further", "isn", "mustn't", "until", "own", "i", "couldn", "y", "only", "you've",
+ "ours", "who", "where", "ourselves", "has", "to", "was", "didn't", "themselves", "if", "against", "through", "her",
+ "an", "your", "can", "those", "didn", "about", "aren't", "shan't", "be", "not", "these", "again", "so", "t",
+ "theirs", "weren", "won't", "won", "itself", "just", "same", "while", "why", "doesn", "aren", "him", "haven",
+ "for", "you'll", "that", "we", "am", "d", "by", "having", "wasn't", "than", "weren't", "out", "from", "now",
+ "their", "too", "hadn", "o", "needn", "most", "it", "under", "needn't", "any", "some", "few", "ll", "hers", "which",
+ "m", "you're", "off", "other", "had", "she", "you'd", "do", "you", "does", "s", "will", "each", "wouldn't", "hasn't",
+ "such", "more", "whom", "she's", "my", "yours", "yourself", "of", "on", "very", "hadn't", "with", "yourselves",
+ "been", "ma", "them", "mightn't", "shan", "mustn", "they", "what", "both", "that'll", "how", "is", "he", "because",
+ "down", "haven't", "are", "no", "it's", "our", "being", "the", "or", "above", "myself", "once", "don't", "doesn't",
+ "as", "nor", "here", "herself", "hasn", "mightn", "have", "its", "all", "were", "ain", "this", "at", "after",
+ "over", "shouldn't", "into", "before", "don", "wouldn", "re", "couldn't", "wasn", "in", "should", "there",
+ "himself", "isn't", "should've", "doing", "ve", "shouldn", "a", "did", "and", "his", "between", "me", "up", "below",
+ "人民", "末##末", "啊", "阿", "哎", "哎呀", "哎哟", "唉", "俺", "俺们", "按", "按照", "吧", "吧哒", "把", "罢了", "被", "本",
+ "本着", "比", "比方", "比如", "鄙人", "彼", "彼此", "边", "别", "别的", "别说", "并", "并且", "不比", "不成", "不单", "不但",
+ "不独", "不管", "不光", "不过", "不仅", "不拘", "不论", "不怕", "不然", "不如", "不特", "不惟", "不问", "不只", "朝", "朝着",
+ "趁", "趁着", "乘", "冲", "除", "除此之外", "除非", "除了", "此", "此间", "此外", "从", "从而", "打", "待", "但", "但是", "当",
+ "当着", "到", "得", "的", "的话", "等", "等等", "地", "第", "叮咚", "对", "对于", "多", "多少", "而", "而况", "而且", "而是",
+ "而外", "而言", "而已", "尔后", "反过来", "反过来说", "反之", "非但", "非徒", "否则", "嘎", "嘎登", "该", "赶", "个", "各",
+ "各个", "各位", "各种", "各自", "给", "根据", "跟", "故", "故此", "固然", "关于", "管", "归", "果然", "果真", "过", "哈",
+ "哈哈", "呵", "和", "何", "何处", "何况", "何时", "嘿", "哼", "哼唷", "呼哧", "乎", "哗", "还是", "还有", "换句话说", "换言之",
+ "或", "或是", "或者", "极了", "及", "及其", "及至", "即", "即便", "即或", "即令", "即若", "即使", "几", "几时", "己", "既",
+ "既然", "既是", "继而", "加之", "假如", "假若", "假使", "鉴于", "将", "较", "较之", "叫", "接着", "结果", "借", "紧接着",
+ "进而", "尽", "尽管", "经", "经过", "就", "就是", "就是说", "据", "具体地说", "具体说来", "开始", "开外", "靠", "咳", "可",
+ "可见", "可是", "可以", "况且", "啦", "来", "来着", "离", "例如", "哩", "连", "连同", "两者", "了", "临", "另", "另外",
+ "另一方面", "论", "嘛", "吗", "慢说", "漫说", "冒", "么", "每", "每当", "们", "莫若", "某", "某个", "某些", "拿", "哪",
+ "哪边", "哪儿", "哪个", "哪里", "哪年", "哪怕", "哪天", "哪些", "哪样", "那", "那边", "那儿", "那个", "那会儿", "那里", "那么",
+ "那么些", "那么样", "那时", "那些", "那样", "乃", "乃至", "呢", "能", "你", "你们", "您", "宁", "宁可", "宁肯", "宁愿", "哦",
+ "呕", "啪达", "旁人", "呸", "凭", "凭借", "其", "其次", "其二", "其他", "其它", "其一", "其余", "其中", "起", "起见", "岂但",
+ "恰恰相反", "前后", "前者", "且", "然而", "然后", "然则", "让", "人家", "任", "任何", "任凭", "如", "如此", "如果", "如何",
+ "如其", "如若", "如上所述", "若", "若非", "若是", "啥", "上下", "尚且", "设若", "设使", "甚而", "甚么", "甚至", "省得", "时候",
+ "什么", "什么样", "使得", "是", "是的", "首先", "谁", "谁知", "顺", "顺着", "似的", "虽", "虽然", "虽说", "虽则", "随", "随着",
+ "所", "所以", "他", "他们", "他人", "它", "它们", "她", "她们", "倘", "倘或", "倘然", "倘若", "倘使", "腾", "替", "通过", "同",
+ "同时", "哇", "万一", "往", "望", "为", "为何", "为了", "为什么", "为着", "喂", "嗡嗡", "我", "我们", "呜", "呜呼", "乌乎",
+ "无论", "无宁", "毋宁", "嘻", "吓", "相对而言", "像", "向", "向着", "嘘", "呀", "焉", "沿", "沿着", "要", "要不", "要不然",
+ "要不是", "要么", "要是", "也", "也罢", "也好", "一", "一般", "一旦", "一方面", "一来", "一切", "一样", "一则", "依", "依照",
+ "矣", "以", "以便", "以及", "以免", "以至", "以至于", "以致", "抑或", "因", "因此", "因而", "因为", "哟", "用", "由",
+ "由此可见", "由于", "有", "有的", "有关", "有些", "又", "于", "于是", "于是乎", "与", "与此同时", "与否", "与其", "越是",
+ "云云", "哉", "再说", "再者", "在", "在下", "咱", "咱们", "则", "怎", "怎么", "怎么办", "怎么样", "怎样", "咋", "照", "照着",
+ "者", "这", "这边", "这儿", "这个", "这会儿", "这就是说", "这里", "这么", "这么点儿", "这么些", "这么样", "这时", "这些", "这样",
+ "正如", "吱", "之", "之类", "之所以", "之一", "只是", "只限", "只要", "只有", "至", "至于", "诸位", "着", "着呢", "自", "自从",
+ "自个儿", "自各儿", "自己", "自家", "自身", "综上所述", "总的来看", "总的来说", "总的说来", "总而言之", "总之", "纵", "纵令",
+ "纵然", "纵使", "遵照", "作为", "兮", "呃", "呗", "咚", "咦", "喏", "啐", "喔唷", "嗬", "嗯", "嗳", "~", "!", ".", ":",
+ "\"", "'", "(", ")", "*", "A", "白", "社会主义", "--", "..", ">>", " [", " ]", "", "<", ">", "/", "\\", "|", "-", "_",
+ "+", "=", "&", "^", "%", "#", "@", "`", ";", "$", "(", ")", "——", "—", "¥", "·", "...", "‘", "’", "〉", "〈", "…",
+ " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "二",
+ "三", "四", "五", "六", "七", "八", "九", "零", ">", "<", "@", "#", "$", "%", "︿", "&", "*", "+", "~", "|", "[",
+ "]", "{", "}", "啊哈", "啊呀", "啊哟", "挨次", "挨个", "挨家挨户", "挨门挨户", "挨门逐户", "挨着", "按理", "按期", "按时",
+ "按说", "暗地里", "暗中", "暗自", "昂然", "八成", "白白", "半", "梆", "保管", "保险", "饱", "背地里", "背靠背", "倍感", "倍加",
+ "本人", "本身", "甭", "比起", "比如说", "比照", "毕竟", "必", "必定", "必将", "必须", "便", "别人", "并非", "并肩", "并没",
+ "并没有", "并排", "并无", "勃然", "不", "不必", "不常", "不大", "不但...而且", "不得", "不得不", "不得了", "不得已", "不迭",
+ "不定", "不对", "不妨", "不管怎样", "不会", "不仅...而且", "不仅仅", "不仅仅是", "不经意", "不可开交", "不可抗拒", "不力", "不了",
+ "不料", "不满", "不免", "不能不", "不起", "不巧", "不然的话", "不日", "不少", "不胜", "不时", "不是", "不同", "不能", "不要",
+ "不外", "不外乎", "不下", "不限", "不消", "不已", "不亦乐乎", "不由得", "不再", "不择手段", "不怎么", "不曾", "不知不觉", "不止",
+ "不止一次", "不至于", "才", "才能", "策略地", "差不多", "差一点", "常", "常常", "常言道", "常言说", "常言说得好", "长此下去",
+ "长话短说", "长期以来", "长线", "敞开儿", "彻夜", "陈年", "趁便", "趁机", "趁热", "趁势", "趁早", "成年", "成年累月", "成心",
+ "乘机", "乘胜", "乘势", "乘隙", "乘虚", "诚然", "迟早", "充分", "充其极", "充其量", "抽冷子", "臭", "初", "出", "出来", "出去",
+ "除此", "除此而外", "除此以外", "除开", "除去", "除却", "除外", "处处", "川流不息", "传", "传说", "传闻", "串行", "纯", "纯粹",
+ "此后", "此中", "次第", "匆匆", "从不", "从此", "从此以后", "从古到今", "从古至今", "从今以后", "从宽", "从来", "从轻", "从速",
+ "从头", "从未", "从无到有", "从小", "从新", "从严", "从优", "从早到晚", "从中", "从重", "凑巧", "粗", "存心", "达旦", "打从",
+ "打开天窗说亮话", "大", "大不了", "大大", "大抵", "大都", "大多", "大凡", "大概", "大家", "大举", "大略", "大面儿上", "大事",
+ "大体", "大体上", "大约", "大张旗鼓", "大致", "呆呆地", "带", "殆", "待到", "单", "单纯", "单单", "但愿", "弹指之间", "当场",
+ "当儿", "当即", "当口儿", "当然", "当庭", "当头", "当下", "当真", "当中", "倒不如", "倒不如说", "倒是", "到处", "到底", "到了儿",
+ "到目前为止", "到头", "到头来", "得起", "得天独厚", "的确", "等到", "叮当", "顶多", "定", "动不动", "动辄", "陡然", "都", "独",
+ "独自", "断然", "顿时", "多次", "多多", "多多少少", "多多益善", "多亏", "多年来", "多年前", "而后", "而论", "而又", "尔等",
+ "二话不说", "二话没说", "反倒", "反倒是", "反而", "反手", "反之亦然", "反之则", "方", "方才", "方能", "放量", "非常", "非得",
+ "分期", "分期分批", "分头", "奋勇", "愤然", "风雨无阻", "逢", "弗", "甫", "嘎嘎", "该当", "概", "赶快", "赶早不赶晚", "敢",
+ "敢情", "敢于", "刚", "刚才", "刚好", "刚巧", "高低", "格外", "隔日", "隔夜", "个人", "各式", "更", "更加", "更进一步", "更为",
+ "公然", "共", "共总", "够瞧的", "姑且", "古来", "故而", "故意", "固", "怪", "怪不得", "惯常", "光", "光是", "归根到底",
+ "归根结底", "过于", "毫不", "毫无", "毫无保留地", "毫无例外", "好在", "何必", "何尝", "何妨", "何苦", "何乐而不为", "何须",
+ "何止", "很", "很多", "很少", "轰然", "后来", "呼啦", "忽地", "忽然", "互", "互相", "哗啦", "话说", "还", "恍然", "会", "豁然",
+ "活", "伙同", "或多或少", "或许", "基本", "基本上", "基于", "极", "极大", "极度", "极端", "极力", "极其", "极为", "急匆匆",
+ "即将", "即刻", "即是说", "几度", "几番", "几乎", "几经", "既...又", "继之", "加上", "加以", "间或", "简而言之", "简言之",
+ "简直", "见", "将才", "将近", "将要", "交口", "较比", "较为", "接连不断", "接下来", "皆可", "截然", "截至", "藉以", "借此",
+ "借以", "届时", "仅", "仅仅", "谨", "进来", "进去", "近", "近几年来", "近来", "近年来", "尽管如此", "尽可能", "尽快", "尽量",
+ "尽然", "尽如人意", "尽心竭力", "尽心尽力", "尽早", "精光", "经常", "竟", "竟然", "究竟", "就此", "就地", "就算", "居然", "局外",
+ "举凡", "据称", "据此", "据实", "据说", "据我所知", "据悉", "具体来说", "决不", "决非", "绝", "绝不", "绝顶", "绝对", "绝非",
+ "均", "喀", "看", "看来", "看起来", "看上去", "看样子", "可好", "可能", "恐怕", "快", "快要", "来不及", "来得及", "来讲",
+ "来看", "拦腰", "牢牢", "老", "老大", "老老实实", "老是", "累次", "累年", "理当", "理该", "理应", "历", "立", "立地", "立刻",
+ "立马", "立时", "联袂", "连连", "连日", "连日来", "连声", "连袂", "临到", "另方面", "另行", "另一个", "路经", "屡", "屡次",
+ "屡次三番", "屡屡", "缕缕", "率尔", "率然", "略", "略加", "略微", "略为", "论说", "马上", "蛮", "满", "没", "没有", "每逢",
+ "每每", "每时每刻", "猛然", "猛然间", "莫", "莫不", "莫非", "莫如", "默默地", "默然", "呐", "那末", "奈", "难道", "难得", "难怪",
+ "难说", "内", "年复一年", "凝神", "偶而", "偶尔", "怕", "砰", "碰巧", "譬如", "偏偏", "乒", "平素", "颇", "迫于", "扑通",
+ "其后", "其实", "奇", "齐", "起初", "起来", "起首", "起头", "起先", "岂", "岂非", "岂止", "迄", "恰逢", "恰好", "恰恰", "恰巧",
+ "恰如", "恰似", "千", "千万", "千万千万", "切", "切不可", "切莫", "切切", "切勿", "窃", "亲口", "亲身", "亲手", "亲眼", "亲自",
+ "顷", "顷刻", "顷刻间", "顷刻之间", "请勿", "穷年累月", "取道", "去", "权时", "全都", "全力", "全年", "全然", "全身心", "然",
+ "人人", "仍", "仍旧", "仍然", "日复一日", "日见", "日渐", "日益", "日臻", "如常", "如此等等", "如次", "如今", "如期", "如前所述",
+ "如上", "如下", "汝", "三番两次", "三番五次", "三天两头", "瑟瑟", "沙沙", "上", "上来", "上去", "一个", "月", "日", "\n"
+}
diff --git a/api/core/index/keyword_table_index.py b/api/core/index/keyword_table_index.py
new file mode 100644
index 00000000000..f0b39055572
--- /dev/null
+++ b/api/core/index/keyword_table_index.py
@@ -0,0 +1,135 @@
+import json
+from typing import List, Optional
+
+from llama_index import ServiceContext, LLMPredictor, OpenAIEmbedding
+from llama_index.data_structs import KeywordTable, Node
+from llama_index.indices.keyword_table.base import BaseGPTKeywordTableIndex
+from llama_index.indices.registry import load_index_struct_from_dict
+
+from core.docstore.dataset_docstore import DatesetDocumentStore
+from core.docstore.empty_docstore import EmptyDocumentStore
+from core.index.index_builder import IndexBuilder
+from core.index.keyword_table.jieba_keyword_table import GPTJIEBAKeywordTableIndex
+from core.llm.llm_builder import LLMBuilder
+from extensions.ext_database import db
+from models.dataset import Dataset, DatasetKeywordTable, DocumentSegment
+
+
+class KeywordTableIndex:
+
+ def __init__(self, dataset: Dataset):
+ self._dataset = dataset
+
+ def add_nodes(self, nodes: List[Node]):
+ llm = LLMBuilder.to_llm(
+ tenant_id=self._dataset.tenant_id,
+ model_name='fake'
+ )
+
+ service_context = ServiceContext.from_defaults(
+ llm_predictor=LLMPredictor(llm=llm),
+ embed_model=OpenAIEmbedding()
+ )
+
+ dataset_keyword_table = self.get_keyword_table()
+ if not dataset_keyword_table or not dataset_keyword_table.keyword_table_dict:
+ index_struct = KeywordTable()
+ else:
+ index_struct_dict = dataset_keyword_table.keyword_table_dict
+ index_struct: KeywordTable = load_index_struct_from_dict(index_struct_dict)
+
+ # create index
+ index = GPTJIEBAKeywordTableIndex(
+ index_struct=index_struct,
+ docstore=EmptyDocumentStore(),
+ service_context=service_context
+ )
+
+ for node in nodes:
+ keywords = index._extract_keywords(node.get_text())
+ self.update_segment_keywords(node.doc_id, list(keywords))
+ index._index_struct.add_node(list(keywords), node)
+
+ index_struct_dict = index.index_struct.to_dict()
+
+ if not dataset_keyword_table:
+ dataset_keyword_table = DatasetKeywordTable(
+ dataset_id=self._dataset.id,
+ keyword_table=json.dumps(index_struct_dict)
+ )
+ db.session.add(dataset_keyword_table)
+ else:
+ dataset_keyword_table.keyword_table = json.dumps(index_struct_dict)
+
+ db.session.commit()
+
+ def del_nodes(self, node_ids: List[str]):
+ llm = LLMBuilder.to_llm(
+ tenant_id=self._dataset.tenant_id,
+ model_name='fake'
+ )
+
+ service_context = ServiceContext.from_defaults(
+ llm_predictor=LLMPredictor(llm=llm),
+ embed_model=OpenAIEmbedding()
+ )
+
+ dataset_keyword_table = self.get_keyword_table()
+ if not dataset_keyword_table or not dataset_keyword_table.keyword_table_dict:
+ return
+ else:
+ index_struct_dict = dataset_keyword_table.keyword_table_dict
+ index_struct: KeywordTable = load_index_struct_from_dict(index_struct_dict)
+
+ # create index
+ index = GPTJIEBAKeywordTableIndex(
+ index_struct=index_struct,
+ docstore=EmptyDocumentStore(),
+ service_context=service_context
+ )
+
+ for node_id in node_ids:
+ index.delete(node_id)
+
+ index_struct_dict = index.index_struct.to_dict()
+
+ if not dataset_keyword_table:
+ dataset_keyword_table = DatasetKeywordTable(
+ dataset_id=self._dataset.id,
+ keyword_table=json.dumps(index_struct_dict)
+ )
+ db.session.add(dataset_keyword_table)
+ else:
+ dataset_keyword_table.keyword_table = json.dumps(index_struct_dict)
+
+ db.session.commit()
+
+ @property
+ def query_index(self) -> Optional[BaseGPTKeywordTableIndex]:
+ docstore = DatesetDocumentStore(
+ dataset=self._dataset,
+ user_id=self._dataset.created_by,
+ embedding_model_name="text-embedding-ada-002"
+ )
+
+ service_context = IndexBuilder.get_default_service_context(tenant_id=self._dataset.tenant_id)
+
+ dataset_keyword_table = self.get_keyword_table()
+ if not dataset_keyword_table or not dataset_keyword_table.keyword_table_dict:
+ return None
+
+ index_struct: KeywordTable = load_index_struct_from_dict(dataset_keyword_table.keyword_table_dict)
+
+ return GPTJIEBAKeywordTableIndex(index_struct=index_struct, docstore=docstore, service_context=service_context)
+
+ def get_keyword_table(self):
+ dataset_keyword_table = self._dataset.dataset_keyword_table
+ if dataset_keyword_table:
+ return dataset_keyword_table
+ return None
+
+ def update_segment_keywords(self, node_id: str, keywords: List[str]):
+ document_segment = db.session.query(DocumentSegment).filter(DocumentSegment.index_node_id == node_id).first()
+ if document_segment:
+ document_segment.keywords = keywords
+ db.session.commit()
diff --git a/api/core/index/query/synthesizer.py b/api/core/index/query/synthesizer.py
new file mode 100644
index 00000000000..7ab8b4a8cac
--- /dev/null
+++ b/api/core/index/query/synthesizer.py
@@ -0,0 +1,79 @@
+from typing import (
+ Any,
+ Dict,
+ Optional, Sequence,
+)
+
+from llama_index.indices.response.response_synthesis import ResponseSynthesizer
+from llama_index.indices.response.response_builder import ResponseMode, BaseResponseBuilder, get_response_builder
+from llama_index.indices.service_context import ServiceContext
+from llama_index.optimization.optimizer import BaseTokenUsageOptimizer
+from llama_index.prompts.prompts import (
+ QuestionAnswerPrompt,
+ RefinePrompt,
+ SimpleInputPrompt,
+)
+from llama_index.types import RESPONSE_TEXT_TYPE
+
+
+class EnhanceResponseSynthesizer(ResponseSynthesizer):
+ @classmethod
+ def from_args(
+ cls,
+ service_context: ServiceContext,
+ streaming: bool = False,
+ use_async: bool = False,
+ text_qa_template: Optional[QuestionAnswerPrompt] = None,
+ refine_template: Optional[RefinePrompt] = None,
+ simple_template: Optional[SimpleInputPrompt] = None,
+ response_mode: ResponseMode = ResponseMode.DEFAULT,
+ response_kwargs: Optional[Dict] = None,
+ optimizer: Optional[BaseTokenUsageOptimizer] = None,
+ ) -> "ResponseSynthesizer":
+ response_builder: Optional[BaseResponseBuilder] = None
+ if response_mode != ResponseMode.NO_TEXT:
+ if response_mode == 'no_synthesizer':
+ response_builder = NoSynthesizer(
+ service_context=service_context,
+ simple_template=simple_template,
+ streaming=streaming,
+ )
+ else:
+ response_builder = get_response_builder(
+ service_context,
+ text_qa_template,
+ refine_template,
+ simple_template,
+ response_mode,
+ use_async=use_async,
+ streaming=streaming,
+ )
+ return cls(response_builder, response_mode, response_kwargs, optimizer)
+
+
+class NoSynthesizer(BaseResponseBuilder):
+ def __init__(
+ self,
+ service_context: ServiceContext,
+ simple_template: Optional[SimpleInputPrompt] = None,
+ streaming: bool = False,
+ ) -> None:
+ super().__init__(service_context, streaming)
+
+ async def aget_response(
+ self,
+ query_str: str,
+ text_chunks: Sequence[str],
+ prev_response: Optional[str] = None,
+ **response_kwargs: Any,
+ ) -> RESPONSE_TEXT_TYPE:
+ return "\n".join(text_chunks)
+
+ def get_response(
+ self,
+ query_str: str,
+ text_chunks: Sequence[str],
+ prev_response: Optional[str] = None,
+ **response_kwargs: Any,
+ ) -> RESPONSE_TEXT_TYPE:
+ return "\n".join(text_chunks)
\ No newline at end of file
diff --git a/api/core/index/readers/html_parser.py b/api/core/index/readers/html_parser.py
new file mode 100644
index 00000000000..2afadb284c4
--- /dev/null
+++ b/api/core/index/readers/html_parser.py
@@ -0,0 +1,22 @@
+from pathlib import Path
+from typing import Dict
+
+from bs4 import BeautifulSoup
+from llama_index.readers.file.base_parser import BaseParser
+
+
+class HTMLParser(BaseParser):
+ """HTML parser."""
+
+ def _init_parser(self) -> Dict:
+ """Init parser."""
+ return {}
+
+ def parse_file(self, file: Path, errors: str = "ignore") -> str:
+ """Parse file."""
+ with open(file, "rb") as fp:
+ soup = BeautifulSoup(fp, 'html.parser')
+ text = soup.get_text()
+ text = text.strip() if text else ''
+
+ return text
diff --git a/api/core/index/readers/pdf_parser.py b/api/core/index/readers/pdf_parser.py
new file mode 100644
index 00000000000..81c4840c600
--- /dev/null
+++ b/api/core/index/readers/pdf_parser.py
@@ -0,0 +1,56 @@
+from pathlib import Path
+from typing import Dict
+
+from flask import current_app
+from llama_index.readers.file.base_parser import BaseParser
+from pypdf import PdfReader
+
+from extensions.ext_storage import storage
+from models.model import UploadFile
+
+
+class PDFParser(BaseParser):
+ """PDF parser."""
+
+ def _init_parser(self) -> Dict:
+ """Init parser."""
+ return {}
+
+ def parse_file(self, file: Path, errors: str = "ignore") -> str:
+ """Parse file."""
+ if not current_app.config.get('PDF_PREVIEW', True):
+ return ''
+
+ plaintext_file_key = ''
+ plaintext_file_exists = False
+ if self._parser_config and 'upload_file' in self._parser_config and self._parser_config['upload_file']:
+ upload_file: UploadFile = self._parser_config['upload_file']
+ if upload_file.hash:
+ plaintext_file_key = 'upload_files/' + upload_file.tenant_id + '/' + upload_file.hash + '.plaintext'
+ try:
+ text = storage.load(plaintext_file_key).decode('utf-8')
+ plaintext_file_exists = True
+ return text
+ except FileNotFoundError:
+ pass
+
+ text_list = []
+ with open(file, "rb") as fp:
+ # Create a PDF object
+ pdf = PdfReader(fp)
+
+ # Get the number of pages in the PDF document
+ num_pages = len(pdf.pages)
+
+ # Iterate over every page
+ for page in range(num_pages):
+ # Extract the text from the page
+ page_text = pdf.pages[page].extract_text()
+ text_list.append(page_text)
+ text = "\n".join(text_list)
+
+ # save plaintext file for caching
+ if not plaintext_file_exists and plaintext_file_key:
+ storage.save(plaintext_file_key, text.encode('utf-8'))
+
+ return text
diff --git a/api/core/index/vector_index.py b/api/core/index/vector_index.py
new file mode 100644
index 00000000000..f9d8542a8ca
--- /dev/null
+++ b/api/core/index/vector_index.py
@@ -0,0 +1,136 @@
+import json
+import logging
+from typing import List, Optional
+
+from llama_index.data_structs import Node
+from requests import ReadTimeout
+from sqlalchemy.exc import IntegrityError
+from tenacity import retry, stop_after_attempt, retry_if_exception_type
+
+from core.index.index_builder import IndexBuilder
+from core.vector_store.base import BaseGPTVectorStoreIndex
+from extensions.ext_vector_store import vector_store
+from extensions.ext_database import db
+from models.dataset import Dataset, Embedding
+
+
+class VectorIndex:
+
+ def __init__(self, dataset: Dataset):
+ self._dataset = dataset
+
+ def add_nodes(self, nodes: List[Node], duplicate_check: bool = False):
+ if not self._dataset.index_struct_dict:
+ index_id = "Vector_index_" + self._dataset.id.replace("-", "_")
+ self._dataset.index_struct = json.dumps(vector_store.to_index_struct(index_id))
+ db.session.commit()
+
+ service_context = IndexBuilder.get_default_service_context(tenant_id=self._dataset.tenant_id)
+
+ index = vector_store.get_index(
+ service_context=service_context,
+ index_struct=self._dataset.index_struct_dict
+ )
+
+ if duplicate_check:
+ nodes = self._filter_duplicate_nodes(index, nodes)
+
+ embedding_queue_nodes = []
+ embedded_nodes = []
+ for node in nodes:
+ node_hash = node.doc_hash
+
+ # if node hash in cached embedding tables, use cached embedding
+ embedding = db.session.query(Embedding).filter_by(hash=node_hash).first()
+ if embedding:
+ node.embedding = embedding.get_embedding()
+ embedded_nodes.append(node)
+ else:
+ embedding_queue_nodes.append(node)
+
+ if embedding_queue_nodes:
+ embedding_results = index._get_node_embedding_results(
+ embedding_queue_nodes,
+ set(),
+ )
+
+ # pre embed nodes for cached embedding
+ for embedding_result in embedding_results:
+ node = embedding_result.node
+ node.embedding = embedding_result.embedding
+
+ try:
+ embedding = Embedding(hash=node.doc_hash)
+ embedding.set_embedding(node.embedding)
+ db.session.add(embedding)
+ db.session.commit()
+ except IntegrityError:
+ db.session.rollback()
+ continue
+ except:
+ logging.exception('Failed to add embedding to db')
+ continue
+
+ embedded_nodes.append(node)
+
+ self.index_insert_nodes(index, embedded_nodes)
+
+ @retry(reraise=True, retry=retry_if_exception_type(ReadTimeout), stop=stop_after_attempt(3))
+ def index_insert_nodes(self, index: BaseGPTVectorStoreIndex, nodes: List[Node]):
+ index.insert_nodes(nodes)
+
+ def del_nodes(self, node_ids: List[str]):
+ if not self._dataset.index_struct_dict:
+ return
+
+ service_context = IndexBuilder.get_default_service_context(tenant_id=self._dataset.tenant_id)
+
+ index = vector_store.get_index(
+ service_context=service_context,
+ index_struct=self._dataset.index_struct_dict
+ )
+
+ for node_id in node_ids:
+ self.index_delete_node(index, node_id)
+
+ @retry(reraise=True, retry=retry_if_exception_type(ReadTimeout), stop=stop_after_attempt(3))
+ def index_delete_node(self, index: BaseGPTVectorStoreIndex, node_id: str):
+ index.delete_node(node_id)
+
+ def del_doc(self, doc_id: str):
+ if not self._dataset.index_struct_dict:
+ return
+
+ service_context = IndexBuilder.get_default_service_context(tenant_id=self._dataset.tenant_id)
+
+ index = vector_store.get_index(
+ service_context=service_context,
+ index_struct=self._dataset.index_struct_dict
+ )
+
+ self.index_delete_doc(index, doc_id)
+
+ @retry(reraise=True, retry=retry_if_exception_type(ReadTimeout), stop=stop_after_attempt(3))
+ def index_delete_doc(self, index: BaseGPTVectorStoreIndex, doc_id: str):
+ index.delete(doc_id)
+
+ @property
+ def query_index(self) -> Optional[BaseGPTVectorStoreIndex]:
+ if not self._dataset.index_struct_dict:
+ return None
+
+ service_context = IndexBuilder.get_default_service_context(tenant_id=self._dataset.tenant_id)
+
+ return vector_store.get_index(
+ service_context=service_context,
+ index_struct=self._dataset.index_struct_dict
+ )
+
+ def _filter_duplicate_nodes(self, index: BaseGPTVectorStoreIndex, nodes: List[Node]) -> List[Node]:
+ for node in nodes:
+ node_id = node.doc_id
+ exists_duplicate_node = index.exists_by_node_id(node_id)
+ if exists_duplicate_node:
+ nodes.remove(node)
+
+ return nodes
diff --git a/api/core/indexing_runner.py b/api/core/indexing_runner.py
new file mode 100644
index 00000000000..fd9e4301166
--- /dev/null
+++ b/api/core/indexing_runner.py
@@ -0,0 +1,467 @@
+import datetime
+import json
+import re
+import tempfile
+import time
+from pathlib import Path
+from typing import Optional, List
+from langchain.text_splitter import RecursiveCharacterTextSplitter
+
+from llama_index import SimpleDirectoryReader
+from llama_index.data_structs import Node
+from llama_index.data_structs.node_v2 import DocumentRelationship
+from llama_index.node_parser import SimpleNodeParser, NodeParser
+from llama_index.readers.file.base import DEFAULT_FILE_EXTRACTOR
+from llama_index.readers.file.markdown_parser import MarkdownParser
+
+from core.docstore.dataset_docstore import DatesetDocumentStore
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.readers.html_parser import HTMLParser
+from core.index.readers.pdf_parser import PDFParser
+from core.index.vector_index import VectorIndex
+from core.llm.token_calculator import TokenCalculator
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from extensions.ext_storage import storage
+from models.dataset import Document, Dataset, DocumentSegment, DatasetProcessRule
+from models.model import UploadFile
+
+
+class IndexingRunner:
+
+ def __init__(self, embedding_model_name: str = "text-embedding-ada-002"):
+ self.storage = storage
+ self.embedding_model_name = embedding_model_name
+
+ def run(self, document: Document):
+ """Run the indexing process."""
+ # get dataset
+ dataset = Dataset.query.filter_by(
+ id=document.dataset_id
+ ).first()
+
+ if not dataset:
+ raise ValueError("no dataset found")
+
+ # load file
+ text_docs = self._load_data(document)
+
+ # get the process rule
+ processing_rule = db.session.query(DatasetProcessRule). \
+ filter(DatasetProcessRule.id == document.dataset_process_rule_id). \
+ first()
+
+ # get node parser for splitting
+ node_parser = self._get_node_parser(processing_rule)
+
+ # split to nodes
+ nodes = self._step_split(
+ text_docs=text_docs,
+ node_parser=node_parser,
+ dataset=dataset,
+ document=document,
+ processing_rule=processing_rule
+ )
+
+ # build index
+ self._build_index(
+ dataset=dataset,
+ document=document,
+ nodes=nodes
+ )
+
+ def run_in_splitting_status(self, document: Document):
+ """Run the indexing process when the index_status is splitting."""
+ # get dataset
+ dataset = Dataset.query.filter_by(
+ id=document.dataset_id
+ ).first()
+
+ if not dataset:
+ raise ValueError("no dataset found")
+
+ # get exist document_segment list and delete
+ document_segments = DocumentSegment.query.filter_by(
+ dataset_id=dataset.id,
+ document_id=document.id
+ ).all()
+ db.session.delete(document_segments)
+ db.session.commit()
+ # load file
+ text_docs = self._load_data(document)
+
+ # get the process rule
+ processing_rule = db.session.query(DatasetProcessRule). \
+ filter(DatasetProcessRule.id == document.dataset_process_rule_id). \
+ first()
+
+ # get node parser for splitting
+ node_parser = self._get_node_parser(processing_rule)
+
+ # split to nodes
+ nodes = self._step_split(
+ text_docs=text_docs,
+ node_parser=node_parser,
+ dataset=dataset,
+ document=document,
+ processing_rule=processing_rule
+ )
+
+ # build index
+ self._build_index(
+ dataset=dataset,
+ document=document,
+ nodes=nodes
+ )
+
+ def run_in_indexing_status(self, document: Document):
+ """Run the indexing process when the index_status is indexing."""
+ # get dataset
+ dataset = Dataset.query.filter_by(
+ id=document.dataset_id
+ ).first()
+
+ if not dataset:
+ raise ValueError("no dataset found")
+
+ # get exist document_segment list and delete
+ document_segments = DocumentSegment.query.filter_by(
+ dataset_id=dataset.id,
+ document_id=document.id
+ ).all()
+ nodes = []
+ if document_segments:
+ for document_segment in document_segments:
+ # transform segment to node
+ if document_segment.status != "completed":
+ relationships = {
+ DocumentRelationship.SOURCE: document_segment.document_id,
+ }
+
+ previous_segment = document_segment.previous_segment
+ if previous_segment:
+ relationships[DocumentRelationship.PREVIOUS] = previous_segment.index_node_id
+
+ next_segment = document_segment.next_segment
+ if next_segment:
+ relationships[DocumentRelationship.NEXT] = next_segment.index_node_id
+ node = Node(
+ doc_id=document_segment.index_node_id,
+ doc_hash=document_segment.index_node_hash,
+ text=document_segment.content,
+ extra_info=None,
+ node_info=None,
+ relationships=relationships
+ )
+ nodes.append(node)
+
+ # build index
+ self._build_index(
+ dataset=dataset,
+ document=document,
+ nodes=nodes
+ )
+
+ def indexing_estimate(self, file_detail: UploadFile, tmp_processing_rule: dict) -> dict:
+ """
+ Estimate the indexing for the document.
+ """
+ # load data from file
+ text_docs = self._load_data_from_file(file_detail)
+
+ processing_rule = DatasetProcessRule(
+ mode=tmp_processing_rule["mode"],
+ rules=json.dumps(tmp_processing_rule["rules"])
+ )
+
+ # get node parser for splitting
+ node_parser = self._get_node_parser(processing_rule)
+
+ # split to nodes
+ nodes = self._split_to_nodes(
+ text_docs=text_docs,
+ node_parser=node_parser,
+ processing_rule=processing_rule
+ )
+
+ tokens = 0
+ preview_texts = []
+ for node in nodes:
+ if len(preview_texts) < 5:
+ preview_texts.append(node.get_text())
+
+ tokens += TokenCalculator.get_num_tokens(self.embedding_model_name, node.get_text())
+
+ return {
+ "total_segments": len(nodes),
+ "tokens": tokens,
+ "total_price": '{:f}'.format(TokenCalculator.get_token_price(self.embedding_model_name, tokens)),
+ "currency": TokenCalculator.get_currency(self.embedding_model_name),
+ "preview": preview_texts
+ }
+
+ def _load_data(self, document: Document) -> List[Document]:
+ # load file
+ if document.data_source_type != "upload_file":
+ return []
+
+ data_source_info = document.data_source_info_dict
+ if not data_source_info or 'upload_file_id' not in data_source_info:
+ raise ValueError("no upload file found")
+
+ file_detail = db.session.query(UploadFile). \
+ filter(UploadFile.id == data_source_info['upload_file_id']). \
+ one_or_none()
+
+ text_docs = self._load_data_from_file(file_detail)
+
+ # update document status to splitting
+ self._update_document_index_status(
+ document_id=document.id,
+ after_indexing_status="splitting",
+ extra_update_params={
+ Document.file_id: file_detail.id,
+ Document.word_count: sum([len(text_doc.text) for text_doc in text_docs]),
+ Document.parsing_completed_at: datetime.datetime.utcnow()
+ }
+ )
+
+ # replace doc id to document model id
+ for text_doc in text_docs:
+ # remove invalid symbol
+ text_doc.text = self.filter_string(text_doc.get_text())
+ text_doc.doc_id = document.id
+
+ return text_docs
+
+ def filter_string(self, text):
+ pattern = re.compile('[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x80-\xFF]')
+ return pattern.sub('', text)
+
+ def _load_data_from_file(self, upload_file: UploadFile) -> List[Document]:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ suffix = Path(upload_file.key).suffix
+ filepath = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}"
+ self.storage.download(upload_file.key, filepath)
+
+ file_extractor = DEFAULT_FILE_EXTRACTOR.copy()
+ file_extractor[".markdown"] = MarkdownParser()
+ file_extractor[".html"] = HTMLParser()
+ file_extractor[".htm"] = HTMLParser()
+ file_extractor[".pdf"] = PDFParser({'upload_file': upload_file})
+
+ loader = SimpleDirectoryReader(input_files=[filepath], file_extractor=file_extractor)
+ text_docs = loader.load_data()
+
+ return text_docs
+
+ def _get_node_parser(self, processing_rule: DatasetProcessRule) -> NodeParser:
+ """
+ Get the NodeParser object according to the processing rule.
+ """
+ if processing_rule.mode == "custom":
+ # The user-defined segmentation rule
+ rules = json.loads(processing_rule.rules)
+ segmentation = rules["segmentation"]
+ if segmentation["max_tokens"] < 50 or segmentation["max_tokens"] > 1000:
+ raise ValueError("Custom segment length should be between 50 and 1000.")
+
+ separator = segmentation["separator"]
+ if not separator:
+ separators = ["\n\n", "。", ".", " ", ""]
+ else:
+ separator = separator.replace('\\n', '\n')
+ separators = [separator, ""]
+
+ character_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
+ chunk_size=segmentation["max_tokens"],
+ chunk_overlap=0,
+ separators=separators
+ )
+ else:
+ # Automatic segmentation
+ character_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
+ chunk_size=DatasetProcessRule.AUTOMATIC_RULES['segmentation']['max_tokens'],
+ chunk_overlap=0,
+ separators=["\n\n", "。", ".", " ", ""]
+ )
+
+ return SimpleNodeParser(text_splitter=character_splitter, include_extra_info=True)
+
+ def _step_split(self, text_docs: List[Document], node_parser: NodeParser,
+ dataset: Dataset, document: Document, processing_rule: DatasetProcessRule) -> List[Node]:
+ """
+ Split the text documents into nodes and save them to the document segment.
+ """
+ nodes = self._split_to_nodes(
+ text_docs=text_docs,
+ node_parser=node_parser,
+ processing_rule=processing_rule
+ )
+
+ # save node to document segment
+ doc_store = DatesetDocumentStore(
+ dataset=dataset,
+ user_id=document.created_by,
+ embedding_model_name=self.embedding_model_name,
+ document_id=document.id
+ )
+
+ doc_store.add_documents(nodes)
+
+ # update document status to indexing
+ cur_time = datetime.datetime.utcnow()
+ self._update_document_index_status(
+ document_id=document.id,
+ after_indexing_status="indexing",
+ extra_update_params={
+ Document.cleaning_completed_at: cur_time,
+ Document.splitting_completed_at: cur_time,
+ }
+ )
+
+ # update segment status to indexing
+ self._update_segments_by_document(
+ document_id=document.id,
+ update_params={
+ DocumentSegment.status: "indexing",
+ DocumentSegment.indexing_at: datetime.datetime.utcnow()
+ }
+ )
+
+ return nodes
+
+ def _split_to_nodes(self, text_docs: List[Document], node_parser: NodeParser,
+ processing_rule: DatasetProcessRule) -> List[Node]:
+ """
+ Split the text documents into nodes.
+ """
+ all_nodes = []
+ for text_doc in text_docs:
+ # document clean
+ document_text = self._document_clean(text_doc.get_text(), processing_rule)
+ text_doc.text = document_text
+
+ # parse document to nodes
+ nodes = node_parser.get_nodes_from_documents([text_doc])
+
+ all_nodes.extend(nodes)
+
+ return all_nodes
+
+ def _document_clean(self, text: str, processing_rule: DatasetProcessRule) -> str:
+ """
+ Clean the document text according to the processing rules.
+ """
+ if processing_rule.mode == "automatic":
+ rules = DatasetProcessRule.AUTOMATIC_RULES
+ else:
+ rules = json.loads(processing_rule.rules) if processing_rule.rules else {}
+
+ if 'pre_processing_rules' in rules:
+ pre_processing_rules = rules["pre_processing_rules"]
+ for pre_processing_rule in pre_processing_rules:
+ if pre_processing_rule["id"] == "remove_extra_spaces" and pre_processing_rule["enabled"] is True:
+ # Remove extra spaces
+ pattern = r'\n{3,}'
+ text = re.sub(pattern, '\n\n', text)
+ pattern = r'[\t\f\r\x20\u00a0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]{2,}'
+ text = re.sub(pattern, ' ', text)
+ elif pre_processing_rule["id"] == "remove_urls_emails" and pre_processing_rule["enabled"] is True:
+ # Remove email
+ pattern = r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)'
+ text = re.sub(pattern, '', text)
+
+ # Remove URL
+ pattern = r'https?://[^\s]+'
+ text = re.sub(pattern, '', text)
+
+ return text
+
+ def _build_index(self, dataset: Dataset, document: Document, nodes: List[Node]) -> None:
+ """
+ Build the index for the document.
+ """
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ # chunk nodes by chunk size
+ indexing_start_at = time.perf_counter()
+ tokens = 0
+ chunk_size = 100
+ for i in range(0, len(nodes), chunk_size):
+ # check document is paused
+ self._check_document_paused_status(document.id)
+ chunk_nodes = nodes[i:i + chunk_size]
+
+ tokens += sum(
+ TokenCalculator.get_num_tokens(self.embedding_model_name, node.get_text()) for node in chunk_nodes
+ )
+
+ # save vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.add_nodes(chunk_nodes)
+
+ # save keyword index
+ keyword_table_index.add_nodes(chunk_nodes)
+
+ node_ids = [node.doc_id for node in chunk_nodes]
+ db.session.query(DocumentSegment).filter(
+ DocumentSegment.document_id == document.id,
+ DocumentSegment.index_node_id.in_(node_ids),
+ DocumentSegment.status == "indexing"
+ ).update({
+ DocumentSegment.status: "completed",
+ DocumentSegment.completed_at: datetime.datetime.utcnow()
+ })
+
+ db.session.commit()
+
+ indexing_end_at = time.perf_counter()
+
+ # update document status to completed
+ self._update_document_index_status(
+ document_id=document.id,
+ after_indexing_status="completed",
+ extra_update_params={
+ Document.tokens: tokens,
+ Document.completed_at: datetime.datetime.utcnow(),
+ Document.indexing_latency: indexing_end_at - indexing_start_at,
+ }
+ )
+
+ def _check_document_paused_status(self, document_id: str):
+ indexing_cache_key = 'document_{}_is_paused'.format(document_id)
+ result = redis_client.get(indexing_cache_key)
+ if result:
+ raise DocumentIsPausedException()
+
+ def _update_document_index_status(self, document_id: str, after_indexing_status: str,
+ extra_update_params: Optional[dict] = None) -> None:
+ """
+ Update the document indexing status.
+ """
+ count = Document.query.filter_by(id=document_id, is_paused=True).count()
+ if count > 0:
+ raise DocumentIsPausedException()
+
+ update_params = {
+ Document.indexing_status: after_indexing_status
+ }
+
+ if extra_update_params:
+ update_params.update(extra_update_params)
+
+ Document.query.filter_by(id=document_id).update(update_params)
+ db.session.commit()
+
+ def _update_segments_by_document(self, document_id: str, update_params: dict) -> None:
+ """
+ Update the document segment by document id.
+ """
+ DocumentSegment.query.filter_by(document_id=document_id).update(update_params)
+ db.session.commit()
+
+
+class DocumentIsPausedException(Exception):
+ pass
diff --git a/api/core/llm/error.py b/api/core/llm/error.py
new file mode 100644
index 00000000000..883d282e8a4
--- /dev/null
+++ b/api/core/llm/error.py
@@ -0,0 +1,55 @@
+from typing import Optional
+
+
+class LLMError(Exception):
+ """Base class for all LLM exceptions."""
+ description: Optional[str] = None
+
+ def __init__(self, description: Optional[str] = None) -> None:
+ self.description = description
+
+
+class LLMBadRequestError(LLMError):
+ """Raised when the LLM returns bad request."""
+ description = "Bad Request"
+
+
+class LLMAPIConnectionError(LLMError):
+ """Raised when the LLM returns API connection error."""
+ description = "API Connection Error"
+
+
+class LLMAPIUnavailableError(LLMError):
+ """Raised when the LLM returns API unavailable error."""
+ description = "API Unavailable Error"
+
+
+class LLMRateLimitError(LLMError):
+ """Raised when the LLM returns rate limit error."""
+ description = "Rate Limit Error"
+
+
+class LLMAuthorizationError(LLMError):
+ """Raised when the LLM returns authorization error."""
+ description = "Authorization Error"
+
+
+class ProviderTokenNotInitError(Exception):
+ """
+ Custom exception raised when the provider token is not initialized.
+ """
+ description = "Provider Token Not Init"
+
+
+class QuotaExceededError(Exception):
+ """
+ Custom exception raised when the quota for a provider has been exceeded.
+ """
+ description = "Quota Exceeded"
+
+
+class ModelCurrentlyNotSupportError(Exception):
+ """
+ Custom exception raised when the model not support
+ """
+ description = "Model Currently Not Support"
diff --git a/api/core/llm/error_handle_wraps.py b/api/core/llm/error_handle_wraps.py
new file mode 100644
index 00000000000..ae9a0278bb8
--- /dev/null
+++ b/api/core/llm/error_handle_wraps.py
@@ -0,0 +1,51 @@
+import logging
+from functools import wraps
+
+import openai
+
+from core.llm.error import LLMAPIConnectionError, LLMAPIUnavailableError, LLMRateLimitError, LLMAuthorizationError, \
+ LLMBadRequestError
+
+
+def handle_llm_exceptions(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except openai.error.InvalidRequestError as e:
+ logging.exception("Invalid request to OpenAI API.")
+ raise LLMBadRequestError(str(e))
+ except openai.error.APIConnectionError as e:
+ logging.exception("Failed to connect to OpenAI API.")
+ raise LLMAPIConnectionError(str(e))
+ except (openai.error.APIError, openai.error.ServiceUnavailableError, openai.error.Timeout) as e:
+ logging.exception("OpenAI service unavailable.")
+ raise LLMAPIUnavailableError(str(e))
+ except openai.error.RateLimitError as e:
+ raise LLMRateLimitError(str(e))
+ except openai.error.AuthenticationError as e:
+ raise LLMAuthorizationError(str(e))
+
+ return wrapper
+
+
+def handle_llm_exceptions_async(func):
+ @wraps(func)
+ async def wrapper(*args, **kwargs):
+ try:
+ return await func(*args, **kwargs)
+ except openai.error.InvalidRequestError as e:
+ logging.exception("Invalid request to OpenAI API.")
+ raise LLMBadRequestError(str(e))
+ except openai.error.APIConnectionError as e:
+ logging.exception("Failed to connect to OpenAI API.")
+ raise LLMAPIConnectionError(str(e))
+ except (openai.error.APIError, openai.error.ServiceUnavailableError, openai.error.Timeout) as e:
+ logging.exception("OpenAI service unavailable.")
+ raise LLMAPIUnavailableError(str(e))
+ except openai.error.RateLimitError as e:
+ raise LLMRateLimitError(str(e))
+ except openai.error.AuthenticationError as e:
+ raise LLMAuthorizationError(str(e))
+
+ return wrapper
diff --git a/api/core/llm/llm_builder.py b/api/core/llm/llm_builder.py
new file mode 100644
index 00000000000..4355593c5d0
--- /dev/null
+++ b/api/core/llm/llm_builder.py
@@ -0,0 +1,103 @@
+from typing import Union, Optional
+
+from langchain.callbacks import CallbackManager
+from langchain.llms.fake import FakeListLLM
+
+from core.constant import llm_constant
+from core.llm.provider.llm_provider_service import LLMProviderService
+from core.llm.streamable_chat_open_ai import StreamableChatOpenAI
+from core.llm.streamable_open_ai import StreamableOpenAI
+
+
+class LLMBuilder:
+ """
+ This class handles the following logic:
+ 1. For providers with the name 'OpenAI', the OPENAI_API_KEY value is stored directly in encrypted_config.
+ 2. For providers with the name 'Azure OpenAI', encrypted_config stores the serialized values of four fields, as shown below:
+ OPENAI_API_TYPE=azure
+ OPENAI_API_VERSION=2022-12-01
+ OPENAI_API_BASE=https://your-resource-name.openai.azure.com
+ OPENAI_API_KEY=<your Azure OpenAI API key>
+ 3. For providers with the name 'Anthropic', the ANTHROPIC_API_KEY value is stored directly in encrypted_config.
+ 4. For providers with the name 'Cohere', the COHERE_API_KEY value is stored directly in encrypted_config.
+ 5. For providers with the name 'HUGGINGFACEHUB', the HUGGINGFACEHUB_API_KEY value is stored directly in encrypted_config.
+ 6. Providers with the provider_type 'CUSTOM' can be created through the admin interface, while 'System' providers cannot be created through the admin interface.
+ 7. If both CUSTOM and System providers exist in the records, the CUSTOM provider is preferred by default, but this preference can be changed via an input parameter.
+ 8. For providers with the provider_type 'System', the quota_used must not exceed quota_limit. If the quota is exceeded, the provider cannot be used. Currently, only the TRIAL quota_type is supported, which is permanently non-resetting.
+ """
+
+ @classmethod
+ def to_llm(cls, tenant_id: str, model_name: str, **kwargs) -> Union[StreamableOpenAI, StreamableChatOpenAI, FakeListLLM]:
+ if model_name == 'fake':
+ return FakeListLLM(responses=[])
+
+ mode = cls.get_mode_by_model(model_name)
+ if mode == 'chat':
+ # llm_cls = StreamableAzureChatOpenAI
+ llm_cls = StreamableChatOpenAI
+ elif mode == 'completion':
+ llm_cls = StreamableOpenAI
+ else:
+ raise ValueError(f"model name {model_name} is not supported.")
+
+ model_credentials = cls.get_model_credentials(tenant_id, model_name)
+
+ return llm_cls(
+ model_name=model_name,
+ temperature=kwargs.get('temperature', 0),
+ max_tokens=kwargs.get('max_tokens', 256),
+ top_p=kwargs.get('top_p', 1),
+ frequency_penalty=kwargs.get('frequency_penalty', 0),
+ presence_penalty=kwargs.get('presence_penalty', 0),
+ callback_manager=kwargs.get('callback_manager', None),
+ streaming=kwargs.get('streaming', False),
+ # request_timeout=None
+ **model_credentials
+ )
+
+ @classmethod
+ def to_llm_from_model(cls, tenant_id: str, model: dict, streaming: bool = False,
+ callback_manager: Optional[CallbackManager] = None) -> Union[StreamableOpenAI, StreamableChatOpenAI]:
+ model_name = model.get("name")
+ completion_params = model.get("completion_params", {})
+
+ return cls.to_llm(
+ tenant_id=tenant_id,
+ model_name=model_name,
+ temperature=completion_params.get('temperature', 0),
+ max_tokens=completion_params.get('max_tokens', 256),
+ top_p=completion_params.get('top_p', 0),
+ frequency_penalty=completion_params.get('frequency_penalty', 0.1),
+ presence_penalty=completion_params.get('presence_penalty', 0.1),
+ streaming=streaming,
+ callback_manager=callback_manager
+ )
+
+ @classmethod
+ def get_mode_by_model(cls, model_name: str) -> str:
+ if not model_name:
+ raise ValueError(f"empty model name is not supported.")
+
+ if model_name in llm_constant.models_by_mode['chat']:
+ return "chat"
+ elif model_name in llm_constant.models_by_mode['completion']:
+ return "completion"
+ else:
+ raise ValueError(f"model name {model_name} is not supported.")
+
+ @classmethod
+ def get_model_credentials(cls, tenant_id: str, model_name: str) -> dict:
+ """
+ Returns the API credentials for the given tenant_id and model_name, based on the model's provider.
+ Raises an exception if the model_name is not found or if the provider is not found.
+ """
+ if not model_name:
+ raise Exception('model name not found')
+
+ if model_name not in llm_constant.models:
+ raise Exception('model {} not found'.format(model_name))
+
+ model_provider = llm_constant.models[model_name]
+
+ provider_service = LLMProviderService(tenant_id=tenant_id, provider_name=model_provider)
+ return provider_service.get_credentials(model_name)
diff --git a/api/core/llm/moderation.py b/api/core/llm/moderation.py
new file mode 100644
index 00000000000..d18d6fc5c27
--- /dev/null
+++ b/api/core/llm/moderation.py
@@ -0,0 +1,15 @@
+import openai
+from models.provider import ProviderName
+
+
+class Moderation:
+
+ def __init__(self, provider: str, api_key: str):
+ self.provider = provider
+ self.api_key = api_key
+
+ if self.provider == ProviderName.OPENAI.value:
+ self.client = openai.Moderation
+
+ def moderate(self, text):
+ return self.client.create(input=text, api_key=self.api_key)
diff --git a/api/core/llm/provider/anthropic_provider.py b/api/core/llm/provider/anthropic_provider.py
new file mode 100644
index 00000000000..4c7756305e3
--- /dev/null
+++ b/api/core/llm/provider/anthropic_provider.py
@@ -0,0 +1,23 @@
+from typing import Optional
+
+from core.llm.provider.base import BaseProvider
+from models.provider import ProviderName
+
+
+class AnthropicProvider(BaseProvider):
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ credentials = self.get_credentials(model_id)
+ # todo
+ return []
+
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ """
+ Returns the API credentials for Azure OpenAI as a dictionary, for the given tenant_id.
+ The dictionary contains keys: azure_api_type, azure_api_version, azure_api_base, and azure_api_key.
+ """
+ return {
+ 'anthropic_api_key': self.get_provider_api_key(model_id=model_id)
+ }
+
+ def get_provider_name(self):
+ return ProviderName.ANTHROPIC
\ No newline at end of file
diff --git a/api/core/llm/provider/azure_provider.py b/api/core/llm/provider/azure_provider.py
new file mode 100644
index 00000000000..e0ba0d07344
--- /dev/null
+++ b/api/core/llm/provider/azure_provider.py
@@ -0,0 +1,105 @@
+import json
+from typing import Optional, Union
+
+import requests
+
+from core.llm.provider.base import BaseProvider
+from models.provider import ProviderName
+
+
+class AzureProvider(BaseProvider):
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ credentials = self.get_credentials(model_id)
+ url = "{}/openai/deployments?api-version={}".format(
+ credentials.get('openai_api_base'),
+ credentials.get('openai_api_version')
+ )
+
+ headers = {
+ "api-key": credentials.get('openai_api_key'),
+ "content-type": "application/json; charset=utf-8"
+ }
+
+ response = requests.get(url, headers=headers)
+
+ if response.status_code == 200:
+ result = response.json()
+ return [{
+ 'id': deployment['id'],
+ 'name': '{} ({})'.format(deployment['id'], deployment['model'])
+ } for deployment in result['data'] if deployment['status'] == 'succeeded']
+ else:
+ # TODO: optimize in future
+ raise Exception('Failed to get deployments from Azure OpenAI. Status code: {}'.format(response.status_code))
+
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ """
+ Returns the API credentials for Azure OpenAI as a dictionary.
+ """
+ encrypted_config = self.get_provider_api_key(model_id=model_id)
+ config = json.loads(encrypted_config)
+ config['openai_api_type'] = 'azure'
+ config['deployment_name'] = model_id
+ return config
+
+ def get_provider_name(self):
+ return ProviderName.AZURE_OPENAI
+
+ def get_provider_configs(self, obfuscated: bool = False) -> Union[str | dict]:
+ """
+ Returns the provider configs.
+ """
+ try:
+ config = self.get_provider_api_key()
+ config = json.loads(config)
+ except:
+ config = {
+ 'openai_api_type': 'azure',
+ 'openai_api_version': '2023-03-15-preview',
+ 'openai_api_base': 'https://foo.microsoft.com/bar',
+ 'openai_api_key': ''
+ }
+
+ if obfuscated:
+ if not config.get('openai_api_key'):
+ config = {
+ 'openai_api_type': 'azure',
+ 'openai_api_version': '2023-03-15-preview',
+ 'openai_api_base': 'https://foo.microsoft.com/bar',
+ 'openai_api_key': ''
+ }
+
+ config['openai_api_key'] = self.obfuscated_token(config.get('openai_api_key'))
+ return config
+
+ return config
+
+ def get_token_type(self):
+ # TODO: change to dict when implemented
+ return lambda value: value
+
+ def config_validate(self, config: Union[dict | str]):
+ """
+ Validates the given config.
+ """
+ # TODO: implement
+ pass
+
+ def get_encrypted_token(self, config: Union[dict | str]):
+ """
+ Returns the encrypted token.
+ """
+ return json.dumps({
+ 'openai_api_type': 'azure',
+ 'openai_api_version': '2023-03-15-preview',
+ 'openai_api_base': config['openai_api_base'],
+ 'openai_api_key': self.encrypt_token(config['openai_api_key'])
+ })
+
+ def get_decrypted_token(self, token: str):
+ """
+ Returns the decrypted token.
+ """
+ config = json.loads(token)
+ config['openai_api_key'] = self.decrypt_token(config['openai_api_key'])
+ return config
diff --git a/api/core/llm/provider/base.py b/api/core/llm/provider/base.py
new file mode 100644
index 00000000000..89343ff62a4
--- /dev/null
+++ b/api/core/llm/provider/base.py
@@ -0,0 +1,124 @@
+import base64
+from abc import ABC, abstractmethod
+from typing import Optional, Union
+
+from core import hosted_llm_credentials
+from core.llm.error import QuotaExceededError, ModelCurrentlyNotSupportError, ProviderTokenNotInitError
+from extensions.ext_database import db
+from libs import rsa
+from models.account import Tenant
+from models.provider import Provider, ProviderType, ProviderName
+
+
+class BaseProvider(ABC):
+ def __init__(self, tenant_id: str):
+ self.tenant_id = tenant_id
+
+ def get_provider_api_key(self, model_id: Optional[str] = None, prefer_custom: bool = True) -> str:
+ """
+ Returns the decrypted API key for the given tenant_id and provider_name.
+ If the provider is of type SYSTEM and the quota is exceeded, raises a QuotaExceededError.
+ If the provider is not found or not valid, raises a ProviderTokenNotInitError.
+ """
+ provider = self.get_provider(prefer_custom)
+ if not provider:
+ raise ProviderTokenNotInitError()
+
+ if provider.provider_type == ProviderType.SYSTEM.value:
+ quota_used = provider.quota_used if provider.quota_used is not None else 0
+ quota_limit = provider.quota_limit if provider.quota_limit is not None else 0
+
+ if model_id and model_id == 'gpt-4':
+ raise ModelCurrentlyNotSupportError()
+
+ if quota_used >= quota_limit:
+ raise QuotaExceededError()
+
+ return self.get_hosted_credentials()
+ else:
+ return self.get_decrypted_token(provider.encrypted_config)
+
+ def get_provider(self, prefer_custom: bool) -> Optional[Provider]:
+ """
+ Returns the Provider instance for the given tenant_id and provider_name.
+ If both CUSTOM and System providers exist, the preferred provider will be returned based on the prefer_custom flag.
+ """
+ providers = db.session.query(Provider).filter(
+ Provider.tenant_id == self.tenant_id,
+ Provider.provider_name == self.get_provider_name().value
+ ).order_by(Provider.provider_type.desc() if prefer_custom else Provider.provider_type).all()
+
+ custom_provider = None
+ system_provider = None
+
+ for provider in providers:
+ if provider.provider_type == ProviderType.CUSTOM.value:
+ custom_provider = provider
+ elif provider.provider_type == ProviderType.SYSTEM.value:
+ system_provider = provider
+
+ if custom_provider and custom_provider.is_valid and custom_provider.encrypted_config:
+ return custom_provider
+ elif system_provider and system_provider.is_valid:
+ return system_provider
+ else:
+ return None
+
+ def get_hosted_credentials(self) -> str:
+ if self.get_provider_name() != ProviderName.OPENAI:
+ raise ProviderTokenNotInitError()
+
+ if not hosted_llm_credentials.openai or not hosted_llm_credentials.openai.api_key:
+ raise ProviderTokenNotInitError()
+
+ return hosted_llm_credentials.openai.api_key
+
+ def get_provider_configs(self, obfuscated: bool = False) -> Union[str | dict]:
+ """
+ Returns the provider configs.
+ """
+ try:
+ config = self.get_provider_api_key()
+ except:
+ config = 'THIS-IS-A-MOCK-TOKEN'
+
+ if obfuscated:
+ return self.obfuscated_token(config)
+
+ return config
+
+ def obfuscated_token(self, token: str):
+ return token[:6] + '*' * (len(token) - 8) + token[-2:]
+
+ def get_token_type(self):
+ return str
+
+ def get_encrypted_token(self, config: Union[dict | str]):
+ return self.encrypt_token(config)
+
+ def get_decrypted_token(self, token: str):
+ return self.decrypt_token(token)
+
+ def encrypt_token(self, token):
+ tenant = db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
+ encrypted_token = rsa.encrypt(token, tenant.encrypt_public_key)
+ return base64.b64encode(encrypted_token).decode()
+
+ def decrypt_token(self, token):
+ return rsa.decrypt(base64.b64decode(token), self.tenant_id)
+
+ @abstractmethod
+ def get_provider_name(self):
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ raise NotImplementedError
+
+ @abstractmethod
+ def config_validate(self, config: str):
+ raise NotImplementedError
diff --git a/api/core/llm/provider/errors.py b/api/core/llm/provider/errors.py
new file mode 100644
index 00000000000..407b7f7906d
--- /dev/null
+++ b/api/core/llm/provider/errors.py
@@ -0,0 +1,2 @@
+class ValidateFailedError(Exception):
+ description = "Provider Validate failed"
diff --git a/api/core/llm/provider/huggingface_provider.py b/api/core/llm/provider/huggingface_provider.py
new file mode 100644
index 00000000000..b3dd3ed5730
--- /dev/null
+++ b/api/core/llm/provider/huggingface_provider.py
@@ -0,0 +1,22 @@
+from typing import Optional
+
+from core.llm.provider.base import BaseProvider
+from models.provider import ProviderName
+
+
+class HuggingfaceProvider(BaseProvider):
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ credentials = self.get_credentials(model_id)
+ # todo
+ return []
+
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ """
+ Returns the API credentials for Huggingface as a dictionary, for the given tenant_id.
+ """
+ return {
+ 'huggingface_api_key': self.get_provider_api_key(model_id=model_id)
+ }
+
+ def get_provider_name(self):
+ return ProviderName.HUGGINGFACEHUB
\ No newline at end of file
diff --git a/api/core/llm/provider/llm_provider_service.py b/api/core/llm/provider/llm_provider_service.py
new file mode 100644
index 00000000000..ca4f8bec6d5
--- /dev/null
+++ b/api/core/llm/provider/llm_provider_service.py
@@ -0,0 +1,53 @@
+from typing import Optional, Union
+
+from core.llm.provider.anthropic_provider import AnthropicProvider
+from core.llm.provider.azure_provider import AzureProvider
+from core.llm.provider.base import BaseProvider
+from core.llm.provider.huggingface_provider import HuggingfaceProvider
+from core.llm.provider.openai_provider import OpenAIProvider
+from models.provider import Provider
+
+
+class LLMProviderService:
+
+ def __init__(self, tenant_id: str, provider_name: str):
+ self.provider = self.init_provider(tenant_id, provider_name)
+
+ def init_provider(self, tenant_id: str, provider_name: str) -> BaseProvider:
+ if provider_name == 'openai':
+ return OpenAIProvider(tenant_id)
+ elif provider_name == 'azure_openai':
+ return AzureProvider(tenant_id)
+ elif provider_name == 'anthropic':
+ return AnthropicProvider(tenant_id)
+ elif provider_name == 'huggingface':
+ return HuggingfaceProvider(tenant_id)
+ else:
+ raise Exception('provider {} not found'.format(provider_name))
+
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ return self.provider.get_models(model_id)
+
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ return self.provider.get_credentials(model_id)
+
+ def get_provider_configs(self, obfuscated: bool = False) -> Union[str | dict]:
+ return self.provider.get_provider_configs(obfuscated)
+
+ def get_provider_db_record(self, prefer_custom: bool = False) -> Optional[Provider]:
+ return self.provider.get_provider(prefer_custom)
+
+ def config_validate(self, config: Union[dict | str]):
+ """
+ Validates the given config.
+
+ :param config:
+ :raises: ValidateFailedError
+ """
+ return self.provider.config_validate(config)
+
+ def get_token_type(self):
+ return self.provider.get_token_type()
+
+ def get_encrypted_token(self, config: Union[dict | str]):
+ return self.provider.get_encrypted_token(config)
diff --git a/api/core/llm/provider/openai_provider.py b/api/core/llm/provider/openai_provider.py
new file mode 100644
index 00000000000..8257ad3aabb
--- /dev/null
+++ b/api/core/llm/provider/openai_provider.py
@@ -0,0 +1,44 @@
+import logging
+from typing import Optional, Union
+
+import openai
+from openai.error import AuthenticationError, OpenAIError
+
+from core.llm.moderation import Moderation
+from core.llm.provider.base import BaseProvider
+from core.llm.provider.errors import ValidateFailedError
+from models.provider import ProviderName
+
+
+class OpenAIProvider(BaseProvider):
+ def get_models(self, model_id: Optional[str] = None) -> list[dict]:
+ credentials = self.get_credentials(model_id)
+ response = openai.Model.list(**credentials)
+
+ return [{
+ 'id': model['id'],
+ 'name': model['id'],
+ } for model in response['data']]
+
+ def get_credentials(self, model_id: Optional[str] = None) -> dict:
+ """
+ Returns the credentials for the given tenant_id and provider_name.
+ """
+ return {
+ 'openai_api_key': self.get_provider_api_key(model_id=model_id)
+ }
+
+ def get_provider_name(self):
+ return ProviderName.OPENAI
+
+ def config_validate(self, config: Union[dict | str]):
+ """
+ Validates the given config.
+ """
+ try:
+ Moderation(self.get_provider_name().value, config).moderate('test')
+ except (AuthenticationError, OpenAIError) as ex:
+ raise ValidateFailedError(str(ex))
+ except Exception as ex:
+ logging.exception('OpenAI config validation failed')
+ raise ex
diff --git a/api/core/llm/streamable_azure_chat_open_ai.py b/api/core/llm/streamable_azure_chat_open_ai.py
new file mode 100644
index 00000000000..539ce92774b
--- /dev/null
+++ b/api/core/llm/streamable_azure_chat_open_ai.py
@@ -0,0 +1,89 @@
+import requests
+from langchain.schema import BaseMessage, ChatResult, LLMResult
+from langchain.chat_models import AzureChatOpenAI
+from typing import Optional, List
+
+from core.llm.error_handle_wraps import handle_llm_exceptions, handle_llm_exceptions_async
+
+
+class StreamableAzureChatOpenAI(AzureChatOpenAI):
+ def get_messages_tokens(self, messages: List[BaseMessage]) -> int:
+ """Get the number of tokens in a list of messages.
+
+ Args:
+ messages: The messages to count the tokens of.
+
+ Returns:
+ The number of tokens in the messages.
+ """
+ tokens_per_message = 5
+ tokens_per_request = 3
+
+ message_tokens = tokens_per_request
+ message_strs = ''
+ for message in messages:
+ message_strs += message.content
+ message_tokens += tokens_per_message
+
+ # calc once
+ message_tokens += self.get_num_tokens(message_strs)
+
+ return message_tokens
+
+ def _generate(
+ self, messages: List[BaseMessage], stop: Optional[List[str]] = None
+ ) -> ChatResult:
+ self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages],
+ verbose=self.verbose
+ )
+
+ chat_result = super()._generate(messages, stop)
+
+ result = LLMResult(
+ generations=[chat_result.generations],
+ llm_output=chat_result.llm_output
+ )
+ self.callback_manager.on_llm_end(result, verbose=self.verbose)
+
+ return chat_result
+
+ async def _agenerate(
+ self, messages: List[BaseMessage], stop: Optional[List[str]] = None
+ ) -> ChatResult:
+ if self.callback_manager.is_async:
+ await self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages],
+ verbose=self.verbose
+ )
+ else:
+ self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages],
+ verbose=self.verbose
+ )
+
+ chat_result = super()._generate(messages, stop)
+
+ result = LLMResult(
+ generations=[chat_result.generations],
+ llm_output=chat_result.llm_output
+ )
+
+ if self.callback_manager.is_async:
+ await self.callback_manager.on_llm_end(result, verbose=self.verbose)
+ else:
+ self.callback_manager.on_llm_end(result, verbose=self.verbose)
+
+ return chat_result
+
+ @handle_llm_exceptions
+ def generate(
+ self, messages: List[List[BaseMessage]], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return super().generate(messages, stop)
+
+ @handle_llm_exceptions_async
+ async def agenerate(
+ self, messages: List[List[BaseMessage]], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return await super().agenerate(messages, stop)
diff --git a/api/core/llm/streamable_chat_open_ai.py b/api/core/llm/streamable_chat_open_ai.py
new file mode 100644
index 00000000000..59391e4ce03
--- /dev/null
+++ b/api/core/llm/streamable_chat_open_ai.py
@@ -0,0 +1,86 @@
+from langchain.schema import BaseMessage, ChatResult, LLMResult
+from langchain.chat_models import ChatOpenAI
+from typing import Optional, List
+
+from core.llm.error_handle_wraps import handle_llm_exceptions, handle_llm_exceptions_async
+
+
+class StreamableChatOpenAI(ChatOpenAI):
+
+ def get_messages_tokens(self, messages: List[BaseMessage]) -> int:
+ """Get the number of tokens in a list of messages.
+
+ Args:
+ messages: The messages to count the tokens of.
+
+ Returns:
+ The number of tokens in the messages.
+ """
+ tokens_per_message = 5
+ tokens_per_request = 3
+
+ message_tokens = tokens_per_request
+ message_strs = ''
+ for message in messages:
+ message_strs += message.content
+ message_tokens += tokens_per_message
+
+ # calc once
+ message_tokens += self.get_num_tokens(message_strs)
+
+ return message_tokens
+
+ def _generate(
+ self, messages: List[BaseMessage], stop: Optional[List[str]] = None
+ ) -> ChatResult:
+ self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages], verbose=self.verbose
+ )
+
+ chat_result = super()._generate(messages, stop)
+
+ result = LLMResult(
+ generations=[chat_result.generations],
+ llm_output=chat_result.llm_output
+ )
+ self.callback_manager.on_llm_end(result, verbose=self.verbose)
+
+ return chat_result
+
+ async def _agenerate(
+ self, messages: List[BaseMessage], stop: Optional[List[str]] = None
+ ) -> ChatResult:
+ if self.callback_manager.is_async:
+ await self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages], verbose=self.verbose
+ )
+ else:
+ self.callback_manager.on_llm_start(
+ {"name": self.__class__.__name__}, [(message.type + ": " + message.content) for message in messages], verbose=self.verbose
+ )
+
+ chat_result = super()._generate(messages, stop)
+
+ result = LLMResult(
+ generations=[chat_result.generations],
+ llm_output=chat_result.llm_output
+ )
+
+ if self.callback_manager.is_async:
+ await self.callback_manager.on_llm_end(result, verbose=self.verbose)
+ else:
+ self.callback_manager.on_llm_end(result, verbose=self.verbose)
+
+ return chat_result
+
+ @handle_llm_exceptions
+ def generate(
+ self, messages: List[List[BaseMessage]], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return super().generate(messages, stop)
+
+ @handle_llm_exceptions_async
+ async def agenerate(
+ self, messages: List[List[BaseMessage]], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return await super().agenerate(messages, stop)
diff --git a/api/core/llm/streamable_open_ai.py b/api/core/llm/streamable_open_ai.py
new file mode 100644
index 00000000000..94754af30e0
--- /dev/null
+++ b/api/core/llm/streamable_open_ai.py
@@ -0,0 +1,20 @@
+from langchain.schema import LLMResult
+from typing import Optional, List
+from langchain import OpenAI
+
+from core.llm.error_handle_wraps import handle_llm_exceptions, handle_llm_exceptions_async
+
+
+class StreamableOpenAI(OpenAI):
+
+ @handle_llm_exceptions
+ def generate(
+ self, prompts: List[str], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return super().generate(prompts, stop)
+
+ @handle_llm_exceptions_async
+ async def agenerate(
+ self, prompts: List[str], stop: Optional[List[str]] = None
+ ) -> LLMResult:
+ return await super().agenerate(prompts, stop)
diff --git a/api/core/llm/token_calculator.py b/api/core/llm/token_calculator.py
new file mode 100644
index 00000000000..e45f2b4d625
--- /dev/null
+++ b/api/core/llm/token_calculator.py
@@ -0,0 +1,41 @@
+import decimal
+from typing import Optional
+
+import tiktoken
+
+from core.constant import llm_constant
+
+
+class TokenCalculator:
+ @classmethod
+ def get_num_tokens(cls, model_name: str, text: str):
+ if len(text) == 0:
+ return 0
+
+ enc = tiktoken.encoding_for_model(model_name)
+
+ tokenized_text = enc.encode(text)
+
+ # calculate the number of tokens in the encoded text
+ return len(tokenized_text)
+
+ @classmethod
+ def get_token_price(cls, model_name: str, tokens: int, text_type: Optional[str] = None) -> decimal.Decimal:
+ if model_name in llm_constant.models_by_mode['embedding']:
+ unit_price = llm_constant.model_prices[model_name]['usage']
+ elif text_type == 'prompt':
+ unit_price = llm_constant.model_prices[model_name]['prompt']
+ elif text_type == 'completion':
+ unit_price = llm_constant.model_prices[model_name]['completion']
+ else:
+ raise Exception('Invalid text type')
+
+ tokens_per_1k = (decimal.Decimal(tokens) / 1000).quantize(decimal.Decimal('0.001'),
+ rounding=decimal.ROUND_HALF_UP)
+
+ total_price = tokens_per_1k * unit_price
+ return total_price.quantize(decimal.Decimal('0.0000001'), rounding=decimal.ROUND_HALF_UP)
+
+ @classmethod
+ def get_currency(cls, model_name: str):
+ return llm_constant.model_currency
diff --git a/api/core/memory/read_only_conversation_token_db_buffer_shared_memory.py b/api/core/memory/read_only_conversation_token_db_buffer_shared_memory.py
new file mode 100644
index 00000000000..16f982c5927
--- /dev/null
+++ b/api/core/memory/read_only_conversation_token_db_buffer_shared_memory.py
@@ -0,0 +1,77 @@
+from typing import Any, List, Dict, Union
+
+from langchain.memory.chat_memory import BaseChatMemory
+from langchain.schema import get_buffer_string, BaseMessage, HumanMessage, AIMessage
+
+from core.llm.streamable_chat_open_ai import StreamableChatOpenAI
+from core.llm.streamable_open_ai import StreamableOpenAI
+from extensions.ext_database import db
+from models.model import Conversation, Message
+
+
+class ReadOnlyConversationTokenDBBufferSharedMemory(BaseChatMemory):
+ conversation: Conversation
+ human_prefix: str = "Human"
+ ai_prefix: str = "AI"
+ llm: Union[StreamableChatOpenAI | StreamableOpenAI]
+ memory_key: str = "chat_history"
+ max_token_limit: int = 2000
+ message_limit: int = 10
+
+ @property
+ def buffer(self) -> List[BaseMessage]:
+ """String buffer of memory."""
+ # fetch limited messages desc, and return reversed
+ messages = db.session.query(Message).filter(
+ Message.conversation_id == self.conversation.id,
+ Message.answer_tokens > 0
+ ).order_by(Message.created_at.desc()).limit(self.message_limit).all()
+
+ messages = list(reversed(messages))
+
+ chat_messages: List[BaseMessage] = []
+ for message in messages:
+ chat_messages.append(HumanMessage(content=message.query))
+ chat_messages.append(AIMessage(content=message.answer))
+
+ if not chat_messages:
+ return chat_messages
+
+ # prune the chat message if it exceeds the max token limit
+ curr_buffer_length = self.llm.get_messages_tokens(chat_messages)
+ if curr_buffer_length > self.max_token_limit:
+ pruned_memory = []
+ while curr_buffer_length > self.max_token_limit and chat_messages:
+ pruned_memory.append(chat_messages.pop(0))
+ curr_buffer_length = self.llm.get_messages_tokens(chat_messages)
+
+ return chat_messages
+
+ @property
+ def memory_variables(self) -> List[str]:
+ """Will always return list of memory variables.
+
+ :meta private:
+ """
+ return [self.memory_key]
+
+ def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
+ """Return history buffer."""
+ buffer: Any = self.buffer
+ if self.return_messages:
+ final_buffer: Any = buffer
+ else:
+ final_buffer = get_buffer_string(
+ buffer,
+ human_prefix=self.human_prefix,
+ ai_prefix=self.ai_prefix,
+ )
+ return {self.memory_key: final_buffer}
+
+ def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
+ """Nothing should be saved or changed"""
+ pass
+
+ def clear(self) -> None:
+ """Nothing to clear, got a memory like a vault."""
+ pass
diff --git a/api/core/memory/read_only_conversation_token_db_string_buffer_shared_memory.py b/api/core/memory/read_only_conversation_token_db_string_buffer_shared_memory.py
new file mode 100644
index 00000000000..e5933931a23
--- /dev/null
+++ b/api/core/memory/read_only_conversation_token_db_string_buffer_shared_memory.py
@@ -0,0 +1,36 @@
+from typing import Any, List, Dict
+
+from langchain.memory.chat_memory import BaseChatMemory
+from langchain.schema import get_buffer_string, BaseMessage, BaseLanguageModel
+
+from core.memory.read_only_conversation_token_db_buffer_shared_memory import \
+ ReadOnlyConversationTokenDBBufferSharedMemory
+
+
+class ReadOnlyConversationTokenDBStringBufferSharedMemory(BaseChatMemory):
+ memory: ReadOnlyConversationTokenDBBufferSharedMemory
+
+ @property
+ def memory_variables(self) -> List[str]:
+ """Return memory variables."""
+ return self.memory.memory_variables
+
+ def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
+ """Load memory variables from memory."""
+ buffer: Any = self.memory.buffer
+
+ final_buffer = get_buffer_string(
+ buffer,
+ human_prefix=self.memory.human_prefix,
+ ai_prefix=self.memory.ai_prefix,
+ )
+
+ return {self.memory.memory_key: final_buffer}
+
+ def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
+ """Nothing should be saved or changed"""
+ pass
+
+ def clear(self) -> None:
+ """Nothing to clear, got a memory like a vault."""
+ pass
\ No newline at end of file
diff --git a/api/core/prompt/output_parser/suggested_questions_after_answer.py b/api/core/prompt/output_parser/suggested_questions_after_answer.py
new file mode 100644
index 00000000000..7898d082628
--- /dev/null
+++ b/api/core/prompt/output_parser/suggested_questions_after_answer.py
@@ -0,0 +1,16 @@
+import json
+from typing import Any
+
+from langchain.schema import BaseOutputParser
+from core.prompt.prompts import SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT
+
+
+class SuggestedQuestionsAfterAnswerOutputParser(BaseOutputParser):
+
+ def get_format_instructions(self) -> str:
+ return SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT
+
+ def parse(self, text: str) -> Any:
+ json_string = text.strip()
+ json_obj = json.loads(json_string)
+ return json_obj
diff --git a/api/core/prompt/prompt_builder.py b/api/core/prompt/prompt_builder.py
new file mode 100644
index 00000000000..cbe41576f1c
--- /dev/null
+++ b/api/core/prompt/prompt_builder.py
@@ -0,0 +1,37 @@
+import re
+
+from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate
+from langchain.schema import BaseMessage
+
+from core.prompt.prompt_template import OutLinePromptTemplate
+
+
+class PromptBuilder:
+ @classmethod
+ def to_system_message(cls, prompt_content: str, inputs: dict) -> BaseMessage:
+ prompt_template = OutLinePromptTemplate.from_template(prompt_content)
+ system_prompt_template = SystemMessagePromptTemplate(prompt=prompt_template)
+ prompt_inputs = {k: inputs[k] for k in system_prompt_template.input_variables if k in inputs}
+ system_message = system_prompt_template.format(**prompt_inputs)
+ return system_message
+
+ @classmethod
+ def to_ai_message(cls, prompt_content: str, inputs: dict) -> BaseMessage:
+ prompt_template = OutLinePromptTemplate.from_template(prompt_content)
+ ai_prompt_template = AIMessagePromptTemplate(prompt=prompt_template)
+ prompt_inputs = {k: inputs[k] for k in ai_prompt_template.input_variables if k in inputs}
+ ai_message = ai_prompt_template.format(**prompt_inputs)
+ return ai_message
+
+ @classmethod
+ def to_human_message(cls, prompt_content: str, inputs: dict) -> BaseMessage:
+ prompt_template = OutLinePromptTemplate.from_template(prompt_content)
+ human_prompt_template = HumanMessagePromptTemplate(prompt=prompt_template)
+ human_message = human_prompt_template.format(**inputs)
+ return human_message
+
+ @classmethod
+ def process_template(cls, template: str):
+ processed_template = re.sub(r'\{(.+?)\}', r'\1', template)
+ processed_template = re.sub(r'\{\{(.+?)\}\}', r'{\1}', processed_template)
+ return processed_template
diff --git a/api/core/prompt/prompt_template.py b/api/core/prompt/prompt_template.py
new file mode 100644
index 00000000000..6799c5a733b
--- /dev/null
+++ b/api/core/prompt/prompt_template.py
@@ -0,0 +1,37 @@
+import re
+from typing import Any
+
+from langchain import PromptTemplate
+from langchain.formatting import StrictFormatter
+
+
+class OutLinePromptTemplate(PromptTemplate):
+ @classmethod
+ def from_template(cls, template: str, **kwargs: Any) -> PromptTemplate:
+ """Load a prompt template from a template."""
+ input_variables = {
+ v for _, v, _, _ in OneLineFormatter().parse(template) if v is not None
+ }
+ return cls(
+ input_variables=list(sorted(input_variables)), template=template, **kwargs
+ )
+
+
+class OneLineFormatter(StrictFormatter):
+ def parse(self, format_string):
+ last_end = 0
+ results = []
+ for match in re.finditer(r"{([a-zA-Z_]\w*)}", format_string):
+ field_name = match.group(1)
+ start, end = match.span()
+
+ literal_text = format_string[last_end:start]
+ last_end = end
+
+ results.append((literal_text, field_name, '', None))
+
+ remaining_literal_text = format_string[last_end:]
+ if remaining_literal_text:
+ results.append((remaining_literal_text, None, None, None))
+
+ return results
diff --git a/api/core/prompt/prompts.py b/api/core/prompt/prompts.py
new file mode 100644
index 00000000000..1d9c00990cb
--- /dev/null
+++ b/api/core/prompt/prompts.py
@@ -0,0 +1,63 @@
+from llama_index import QueryKeywordExtractPrompt
+
+CONVERSATION_TITLE_PROMPT = (
+ "Human:{query}\n-----\n"
+ "Help me summarize the intent of what the human said and provide a title, the title should not exceed 20 words.\n"
+ "If the human said is conducted in Chinese, you should return a Chinese title.\n"
+ "If the human said is conducted in English, you should return an English title.\n"
+ "title:"
+)
+
+CONVERSATION_SUMMARY_PROMPT = (
+ "Please generate a short summary of the following conversation.\n"
+ "If the conversation communicating in Chinese, you should return a Chinese summary.\n"
+ "If the conversation communicating in English, you should return an English summary.\n"
+ "[Conversation Start]\n"
+ "{context}\n"
+ "[Conversation End]\n\n"
+ "summary:"
+)
+
+INTRODUCTION_GENERATE_PROMPT = (
+ "I am designing a product for users to interact with an AI through dialogue. "
+ "The Prompt given to the AI before the conversation is:\n\n"
+ "```\n{prompt}\n```\n\n"
+ "Please generate a brief introduction of no more than 50 words that greets the user, based on this Prompt. "
+ "Do not reveal the developer's motivation or deep logic behind the Prompt, "
+ "but focus on building a relationship with the user:\n"
+)
+
+MORE_LIKE_THIS_GENERATE_PROMPT = (
+ "-----\n"
+ "{original_completion}\n"
+ "-----\n\n"
+ "Please use the above content as a sample for generating the result, "
+ "and include key information points related to the original sample in the result. "
+ "Try to rephrase this information in different ways and predict according to the rules below.\n\n"
+ "-----\n"
+ "{prompt}\n"
+)
+
+SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT = (
+ "Please help me predict the three most likely questions that human would ask, "
+ "and keeping each question under 20 characters.\n"
+ "The output must be in JSON format following the specified schema:\n"
+ "[\"question1\",\"question2\",\"question3\"]\n"
+)
+
+QUERY_KEYWORD_EXTRACT_TEMPLATE_TMPL = (
+ "A question is provided below. Given the question, extract up to {max_keywords} "
+ "keywords from the text. Focus on extracting the keywords that we can use "
+ "to best lookup answers to the question. Avoid stopwords."
+ "I am not sure which language the following question is in. "
+ "If the user asked the question in Chinese, please return the keywords in Chinese. "
+ "If the user asked the question in English, please return the keywords in English.\n"
+ "---------------------\n"
+ "{question}\n"
+ "---------------------\n"
+ "Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'\n"
+)
+
+QUERY_KEYWORD_EXTRACT_TEMPLATE = QueryKeywordExtractPrompt(
+ QUERY_KEYWORD_EXTRACT_TEMPLATE_TMPL
+)
diff --git a/api/core/tool/dataset_tool_builder.py b/api/core/tool/dataset_tool_builder.py
new file mode 100644
index 00000000000..b31b15511a5
--- /dev/null
+++ b/api/core/tool/dataset_tool_builder.py
@@ -0,0 +1,83 @@
+from typing import Optional
+
+from langchain.callbacks import CallbackManager
+from llama_index.langchain_helpers.agents import IndexToolConfig
+
+from core.callback_handler.dataset_tool_callback_handler import DatasetToolCallbackHandler
+from core.callback_handler.index_tool_callback_handler import DatasetIndexToolCallbackHandler
+from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from core.prompt.prompts import QUERY_KEYWORD_EXTRACT_TEMPLATE
+from core.tool.llama_index_tool import EnhanceLlamaIndexTool
+from extensions.ext_database import db
+from models.dataset import Dataset
+
+
+class DatasetToolBuilder:
+ @classmethod
+ def build_dataset_tool(cls, tenant_id: str, dataset_id: str,
+ response_mode: str = "no_synthesizer",
+ callback_handler: Optional[DatasetToolCallbackHandler] = None):
+ # get dataset from dataset id
+ dataset = db.session.query(Dataset).filter(
+ Dataset.tenant_id == tenant_id,
+ Dataset.id == dataset_id
+ ).first()
+
+ if not dataset:
+ return None
+
+ if dataset.indexing_technique == "economy":
+ # use keyword table query
+ index = KeywordTableIndex(dataset=dataset).query_index
+
+ if not index:
+ return None
+
+ query_kwargs = {
+ "mode": "default",
+ "response_mode": response_mode,
+ "query_keyword_extract_template": QUERY_KEYWORD_EXTRACT_TEMPLATE,
+ "max_keywords_per_query": 5,
+ # If num_chunks_per_query is too large,
+ # it will slow down the synthesis process due to multiple iterations of refinement.
+ "num_chunks_per_query": 2
+ }
+ else:
+ index = VectorIndex(dataset=dataset).query_index
+
+ if not index:
+ return None
+
+ query_kwargs = {
+ "mode": "default",
+ "response_mode": response_mode,
+ # If top_k is too large,
+ # it will slow down the synthesis process due to multiple iterations of refinement.
+ "similarity_top_k": 2
+ }
+
+ # fulfill description when it is empty
+ description = dataset.description
+ if not description:
+ description = 'useful for when you want to answer queries about the ' + dataset.name
+
+ index_tool_config = IndexToolConfig(
+ index=index,
+ name=f"dataset-{dataset_id}",
+ description=description,
+ index_query_kwargs=query_kwargs,
+ tool_kwargs={
+ "callback_manager": CallbackManager([callback_handler, DifyStdOutCallbackHandler()])
+ },
+ # tool_kwargs={"return_direct": True},
+ # return_direct: Whether to return LLM results directly or process the output data with an Output Parser
+ )
+
+ index_callback_handler = DatasetIndexToolCallbackHandler(dataset_id=dataset_id)
+
+ return EnhanceLlamaIndexTool.from_tool_config(
+ tool_config=index_tool_config,
+ callback_handler=index_callback_handler
+ )
diff --git a/api/core/tool/llama_index_tool.py b/api/core/tool/llama_index_tool.py
new file mode 100644
index 00000000000..ffb216771bb
--- /dev/null
+++ b/api/core/tool/llama_index_tool.py
@@ -0,0 +1,43 @@
+from typing import Dict
+
+from langchain.tools import BaseTool
+from llama_index.indices.base import BaseGPTIndex
+from llama_index.langchain_helpers.agents import IndexToolConfig
+from pydantic import Field
+
+from core.callback_handler.index_tool_callback_handler import IndexToolCallbackHandler
+
+
+class EnhanceLlamaIndexTool(BaseTool):
+ """Tool for querying a LlamaIndex."""
+
+ # NOTE: name/description still needs to be set
+ index: BaseGPTIndex
+ query_kwargs: Dict = Field(default_factory=dict)
+ return_sources: bool = False
+ callback_handler: IndexToolCallbackHandler
+
+ @classmethod
+ def from_tool_config(cls, tool_config: IndexToolConfig,
+ callback_handler: IndexToolCallbackHandler) -> "EnhanceLlamaIndexTool":
+ """Create a tool from a tool config."""
+ return_sources = tool_config.tool_kwargs.pop("return_sources", False)
+ return cls(
+ index=tool_config.index,
+ callback_handler=callback_handler,
+ name=tool_config.name,
+ description=tool_config.description,
+ return_sources=return_sources,
+ query_kwargs=tool_config.index_query_kwargs,
+ **tool_config.tool_kwargs,
+ )
+
+ def _run(self, tool_input: str) -> str:
+ response = self.index.query(tool_input, **self.query_kwargs)
+ self.callback_handler.on_tool_end(response)
+ return str(response)
+
+ async def _arun(self, tool_input: str) -> str:
+ response = await self.index.aquery(tool_input, **self.query_kwargs)
+ self.callback_handler.on_tool_end(response)
+ return str(response)
diff --git a/api/core/vector_store/base.py b/api/core/vector_store/base.py
new file mode 100644
index 00000000000..526f83831de
--- /dev/null
+++ b/api/core/vector_store/base.py
@@ -0,0 +1,34 @@
+from abc import ABC, abstractmethod
+from typing import Optional
+
+from llama_index import ServiceContext, GPTVectorStoreIndex
+from llama_index.data_structs import Node
+from llama_index.vector_stores.types import VectorStore
+
+
+class BaseVectorStoreClient(ABC):
+ @abstractmethod
+ def get_index(self, service_context: ServiceContext, config: dict) -> GPTVectorStoreIndex:
+ raise NotImplementedError
+
+ @abstractmethod
+ def to_index_config(self, index_id: str) -> dict:
+ raise NotImplementedError
+
+
+class BaseGPTVectorStoreIndex(GPTVectorStoreIndex):
+ def delete_node(self, node_id: str):
+ self._vector_store.delete_node(node_id)
+
+ def exists_by_node_id(self, node_id: str) -> bool:
+ return self._vector_store.exists_by_node_id(node_id)
+
+
+class EnhanceVectorStore(ABC):
+ @abstractmethod
+ def delete_node(self, node_id: str):
+ pass
+
+ @abstractmethod
+ def exists_by_node_id(self, node_id: str) -> bool:
+ pass
diff --git a/api/core/vector_store/qdrant_vector_store_client.py b/api/core/vector_store/qdrant_vector_store_client.py
new file mode 100644
index 00000000000..1188c121e34
--- /dev/null
+++ b/api/core/vector_store/qdrant_vector_store_client.py
@@ -0,0 +1,147 @@
+import os
+from typing import cast, List
+
+from llama_index.data_structs import Node
+from llama_index.data_structs.node_v2 import DocumentRelationship
+from llama_index.vector_stores.types import VectorStoreQuery, VectorStoreQueryResult
+from qdrant_client.http.models import Payload, Filter
+
+import qdrant_client
+from llama_index import ServiceContext, GPTVectorStoreIndex, GPTQdrantIndex
+from llama_index.data_structs.data_structs_v2 import QdrantIndexDict
+from llama_index.vector_stores import QdrantVectorStore
+from qdrant_client.local.qdrant_local import QdrantLocal
+
+from core.vector_store.base import BaseVectorStoreClient, BaseGPTVectorStoreIndex, EnhanceVectorStore
+
+
+class QdrantVectorStoreClient(BaseVectorStoreClient):
+
+ def __init__(self, url: str, api_key: str, root_path: str):
+ self._client = self.init_from_config(url, api_key, root_path)
+
+ @classmethod
+ def init_from_config(cls, url: str, api_key: str, root_path: str):
+ if url and url.startswith('path:'):
+ path = url.replace('path:', '')
+ if not os.path.isabs(path):
+ path = os.path.join(root_path, path)
+
+ return qdrant_client.QdrantClient(
+ path=path
+ )
+ else:
+ return qdrant_client.QdrantClient(
+ url=url,
+ api_key=api_key,
+ )
+
+ def get_index(self, service_context: ServiceContext, config: dict) -> GPTVectorStoreIndex:
+ index_struct = QdrantIndexDict()
+
+ if self._client is None:
+ raise Exception("Vector client is not initialized.")
+
+ # {"collection_name": "Gpt_index_xxx"}
+ collection_name = config.get('collection_name')
+ if not collection_name:
+ raise Exception("collection_name cannot be None.")
+
+ return GPTQdrantEnhanceIndex(
+ service_context=service_context,
+ index_struct=index_struct,
+ vector_store=QdrantEnhanceVectorStore(
+ client=self._client,
+ collection_name=collection_name
+ )
+ )
+
+ def to_index_config(self, index_id: str) -> dict:
+ return {"collection_name": index_id}
+
+
+class GPTQdrantEnhanceIndex(GPTQdrantIndex, BaseGPTVectorStoreIndex):
+ pass
+
+
+class QdrantEnhanceVectorStore(QdrantVectorStore, EnhanceVectorStore):
+ def delete_node(self, node_id: str):
+ """
+ Delete node from the index.
+
+ :param node_id: node id
+ """
+ from qdrant_client.http import models as rest
+
+ self._reload_if_needed()
+
+ self._client.delete(
+ collection_name=self._collection_name,
+ points_selector=rest.Filter(
+ must=[
+ rest.FieldCondition(
+ key="id", match=rest.MatchValue(value=node_id)
+ )
+ ]
+ ),
+ )
+
+ def exists_by_node_id(self, node_id: str) -> bool:
+ """
+ Get node from the index by node id.
+
+ :param node_id: node id
+ """
+ self._reload_if_needed()
+
+ response = self._client.retrieve(
+ collection_name=self._collection_name,
+ ids=[node_id]
+ )
+
+ return len(response) > 0
+
+ def query(
+ self,
+ query: VectorStoreQuery,
+ ) -> VectorStoreQueryResult:
+ """Query index for top k most similar nodes.
+
+ Args:
+ query (VectorStoreQuery): query
+ """
+ query_embedding = cast(List[float], query.query_embedding)
+
+ self._reload_if_needed()
+
+ response = self._client.search(
+ collection_name=self._collection_name,
+ query_vector=query_embedding,
+ limit=cast(int, query.similarity_top_k),
+ query_filter=cast(Filter, self._build_query_filter(query)),
+ with_vectors=True
+ )
+
+ nodes = []
+ similarities = []
+ ids = []
+ for point in response:
+ payload = cast(Payload, point.payload)
+ node = Node(
+ doc_id=str(point.id),
+ text=payload.get("text"),
+ embedding=point.vector,
+ extra_info=payload.get("extra_info"),
+ relationships={
+ DocumentRelationship.SOURCE: payload.get("doc_id", "None"),
+ },
+ )
+ nodes.append(node)
+ similarities.append(point.score)
+ ids.append(str(point.id))
+
+ return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)
+
+ def _reload_if_needed(self):
+ if isinstance(self._client._client, QdrantLocal):
+ self._client._client._load()
diff --git a/api/core/vector_store/vector_store.py b/api/core/vector_store/vector_store.py
new file mode 100644
index 00000000000..56b5fd0f975
--- /dev/null
+++ b/api/core/vector_store/vector_store.py
@@ -0,0 +1,61 @@
+from flask import Flask
+from llama_index import ServiceContext, GPTVectorStoreIndex
+from requests import ReadTimeout
+from tenacity import retry, retry_if_exception_type, stop_after_attempt
+
+from core.vector_store.qdrant_vector_store_client import QdrantVectorStoreClient
+from core.vector_store.weaviate_vector_store_client import WeaviateVectorStoreClient
+
+SUPPORTED_VECTOR_STORES = ['weaviate', 'qdrant']
+
+
+class VectorStore:
+
+ def __init__(self):
+ self._vector_store = None
+ self._client = None
+
+ def init_app(self, app: Flask):
+ if not app.config['VECTOR_STORE']:
+ return
+
+ self._vector_store = app.config['VECTOR_STORE']
+ if self._vector_store not in SUPPORTED_VECTOR_STORES:
+ raise ValueError(f"Vector store {self._vector_store} is not supported.")
+
+ if self._vector_store == 'weaviate':
+ self._client = WeaviateVectorStoreClient(
+ endpoint=app.config['WEAVIATE_ENDPOINT'],
+ api_key=app.config['WEAVIATE_API_KEY'],
+ grpc_enabled=app.config['WEAVIATE_GRPC_ENABLED']
+ )
+ elif self._vector_store == 'qdrant':
+ self._client = QdrantVectorStoreClient(
+ url=app.config['QDRANT_URL'],
+ api_key=app.config['QDRANT_API_KEY'],
+ root_path=app.root_path
+ )
+
+ app.extensions['vector_store'] = self
+
+ @retry(reraise=True, retry=retry_if_exception_type(ReadTimeout), stop=stop_after_attempt(3))
+ def get_index(self, service_context: ServiceContext, index_struct: dict) -> GPTVectorStoreIndex:
+ vector_store_config: dict = index_struct.get('vector_store')
+ index = self.get_client().get_index(
+ service_context=service_context,
+ config=vector_store_config
+ )
+
+ return index
+
+ def to_index_struct(self, index_id: str) -> dict:
+ return {
+ "type": self._vector_store,
+ "vector_store": self.get_client().to_index_config(index_id)
+ }
+
+ def get_client(self):
+ if not self._client:
+ raise Exception("Vector store client is not initialized.")
+
+ return self._client
diff --git a/api/core/vector_store/vector_store_index_query.py b/api/core/vector_store/vector_store_index_query.py
new file mode 100644
index 00000000000..f29de83f9e1
--- /dev/null
+++ b/api/core/vector_store/vector_store_index_query.py
@@ -0,0 +1,66 @@
+from llama_index.indices.query.base import IS
+from typing import (
+ Any,
+ Dict,
+ List,
+ Optional
+)
+
+from llama_index.docstore import BaseDocumentStore
+from llama_index.indices.postprocessor.node import (
+ BaseNodePostprocessor,
+)
+from llama_index.indices.vector_store import GPTVectorStoreIndexQuery
+from llama_index.indices.response.response_builder import ResponseMode
+from llama_index.indices.service_context import ServiceContext
+from llama_index.optimization.optimizer import BaseTokenUsageOptimizer
+from llama_index.prompts.prompts import (
+ QuestionAnswerPrompt,
+ RefinePrompt,
+ SimpleInputPrompt,
+)
+
+from core.index.query.synthesizer import EnhanceResponseSynthesizer
+
+
+class EnhanceGPTVectorStoreIndexQuery(GPTVectorStoreIndexQuery):
+ @classmethod
+ def from_args(
+ cls,
+ index_struct: IS,
+ service_context: ServiceContext,
+ docstore: Optional[BaseDocumentStore] = None,
+ node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
+ verbose: bool = False,
+ # response synthesizer args
+ response_mode: ResponseMode = ResponseMode.DEFAULT,
+ text_qa_template: Optional[QuestionAnswerPrompt] = None,
+ refine_template: Optional[RefinePrompt] = None,
+ simple_template: Optional[SimpleInputPrompt] = None,
+ response_kwargs: Optional[Dict] = None,
+ use_async: bool = False,
+ streaming: bool = False,
+ optimizer: Optional[BaseTokenUsageOptimizer] = None,
+ # class-specific args
+ **kwargs: Any,
+ ) -> "BaseGPTIndexQuery":
+ response_synthesizer = EnhanceResponseSynthesizer.from_args(
+ service_context=service_context,
+ text_qa_template=text_qa_template,
+ refine_template=refine_template,
+ simple_template=simple_template,
+ response_mode=response_mode,
+ response_kwargs=response_kwargs,
+ use_async=use_async,
+ streaming=streaming,
+ optimizer=optimizer,
+ )
+ return cls(
+ index_struct=index_struct,
+ service_context=service_context,
+ response_synthesizer=response_synthesizer,
+ docstore=docstore,
+ node_postprocessors=node_postprocessors,
+ verbose=verbose,
+ **kwargs,
+ )
diff --git a/api/core/vector_store/weaviate_vector_store_client.py b/api/core/vector_store/weaviate_vector_store_client.py
new file mode 100644
index 00000000000..2310278cf96
--- /dev/null
+++ b/api/core/vector_store/weaviate_vector_store_client.py
@@ -0,0 +1,258 @@
+import json
+import weaviate
+from dataclasses import field
+from typing import List, Any, Dict, Optional
+
+from core.vector_store.base import BaseVectorStoreClient, BaseGPTVectorStoreIndex, EnhanceVectorStore
+from llama_index import ServiceContext, GPTWeaviateIndex, GPTVectorStoreIndex
+from llama_index.data_structs.data_structs_v2 import WeaviateIndexDict, Node
+from llama_index.data_structs.node_v2 import DocumentRelationship
+from llama_index.readers.weaviate.client import _class_name, NODE_SCHEMA, _logger
+from llama_index.vector_stores import WeaviateVectorStore
+from llama_index.vector_stores.types import VectorStoreQuery, VectorStoreQueryResult, VectorStoreQueryMode
+from llama_index.readers.weaviate.utils import (
+ parse_get_response,
+ validate_client,
+)
+
+
+class WeaviateVectorStoreClient(BaseVectorStoreClient):
+
+ def __init__(self, endpoint: str, api_key: str, grpc_enabled: bool):
+ self._client = self.init_from_config(endpoint, api_key, grpc_enabled)
+
+ def init_from_config(self, endpoint: str, api_key: str, grpc_enabled: bool):
+ auth_config = weaviate.auth.AuthApiKey(api_key=api_key)
+
+ weaviate.connect.connection.has_grpc = grpc_enabled
+
+ return weaviate.Client(
+ url=endpoint,
+ auth_client_secret=auth_config,
+ timeout_config=(5, 15),
+ startup_period=None
+ )
+
+ def get_index(self, service_context: ServiceContext, config: dict) -> GPTVectorStoreIndex:
+ index_struct = WeaviateIndexDict()
+
+ if self._client is None:
+ raise Exception("Vector client is not initialized.")
+
+ # {"class_prefix": "Gpt_index_xxx"}
+ class_prefix = config.get('class_prefix')
+ if not class_prefix:
+ raise Exception("class_prefix cannot be None.")
+
+ return GPTWeaviateEnhanceIndex(
+ service_context=service_context,
+ index_struct=index_struct,
+ vector_store=WeaviateWithSimilaritiesVectorStore(
+ weaviate_client=self._client,
+ class_prefix=class_prefix
+ )
+ )
+
+ def to_index_config(self, index_id: str) -> dict:
+ return {"class_prefix": index_id}
+
+
+class WeaviateWithSimilaritiesVectorStore(WeaviateVectorStore, EnhanceVectorStore):
+ def query(self, query: VectorStoreQuery) -> VectorStoreQueryResult:
+ """Query index for top k most similar nodes."""
+ nodes = self.weaviate_query(
+ self._client,
+ self._class_prefix,
+ query,
+ )
+ nodes = nodes[: query.similarity_top_k]
+ node_idxs = [str(i) for i in range(len(nodes))]
+
+ similarities = []
+ for node in nodes:
+ similarities.append(node.extra_info['similarity'])
+ del node.extra_info['similarity']
+
+ return VectorStoreQueryResult(nodes=nodes, ids=node_idxs, similarities=similarities)
+
+ def weaviate_query(
+ self,
+ client: Any,
+ class_prefix: str,
+ query_spec: VectorStoreQuery,
+ ) -> List[Node]:
+ """Convert to LlamaIndex list."""
+ validate_client(client)
+
+ class_name = _class_name(class_prefix)
+ prop_names = [p["name"] for p in NODE_SCHEMA]
+ vector = query_spec.query_embedding
+
+ # build query
+ query = client.query.get(class_name, prop_names).with_additional(["id", "vector", "certainty"])
+ if query_spec.mode == VectorStoreQueryMode.DEFAULT:
+ _logger.debug("Using vector search")
+ if vector is not None:
+ query = query.with_near_vector(
+ {
+ "vector": vector,
+ }
+ )
+ elif query_spec.mode == VectorStoreQueryMode.HYBRID:
+ _logger.debug(f"Using hybrid search with alpha {query_spec.alpha}")
+ query = query.with_hybrid(
+ query=query_spec.query_str,
+ alpha=query_spec.alpha,
+ vector=vector,
+ )
+ query = query.with_limit(query_spec.similarity_top_k)
+ _logger.debug(f"Using limit of {query_spec.similarity_top_k}")
+
+ # execute query
+ query_result = query.do()
+
+ # parse results
+ parsed_result = parse_get_response(query_result)
+ entries = parsed_result[class_name]
+ results = [self._to_node(entry) for entry in entries]
+ return results
+
+ def _to_node(self, entry: Dict) -> Node:
+ """Convert to Node."""
+ extra_info_str = entry["extra_info"]
+ if extra_info_str == "":
+ extra_info = None
+ else:
+ extra_info = json.loads(extra_info_str)
+
+ if 'certainty' in entry['_additional']:
+ if extra_info:
+ extra_info['similarity'] = entry['_additional']['certainty']
+ else:
+ extra_info = {'similarity': entry['_additional']['certainty']}
+
+ node_info_str = entry["node_info"]
+ if node_info_str == "":
+ node_info = None
+ else:
+ node_info = json.loads(node_info_str)
+
+ relationships_str = entry["relationships"]
+ relationships: Dict[DocumentRelationship, str]
+ if relationships_str == "":
+ relationships = field(default_factory=dict)
+ else:
+ relationships = {
+ DocumentRelationship(k): v for k, v in json.loads(relationships_str).items()
+ }
+
+ return Node(
+ text=entry["text"],
+ doc_id=entry["doc_id"],
+ embedding=entry["_additional"]["vector"],
+ extra_info=extra_info,
+ node_info=node_info,
+ relationships=relationships,
+ )
+
+ def delete(self, doc_id: str, **delete_kwargs: Any) -> None:
+ """Delete a document.
+
+ Args:
+ doc_id (str): document id
+
+ """
+ delete_document(self._client, doc_id, self._class_prefix)
+
+ def delete_node(self, node_id: str):
+ """
+ Delete node from the index.
+
+ :param node_id: node id
+ """
+ delete_node(self._client, node_id, self._class_prefix)
+
+ def exists_by_node_id(self, node_id: str) -> bool:
+ """
+ Get node from the index by node id.
+
+ :param node_id: node id
+ """
+ entry = get_by_node_id(self._client, node_id, self._class_prefix)
+ return True if entry else False
+
+
+class GPTWeaviateEnhanceIndex(GPTWeaviateIndex, BaseGPTVectorStoreIndex):
+ pass
+
+
+def delete_document(client: Any, ref_doc_id: str, class_prefix: str) -> None:
+ """Delete entry."""
+ validate_client(client)
+ # make sure that each entry
+ class_name = _class_name(class_prefix)
+ where_filter = {
+ "path": ["ref_doc_id"],
+ "operator": "Equal",
+ "valueString": ref_doc_id,
+ }
+ query = (
+ client.query.get(class_name).with_additional(["id"]).with_where(where_filter)
+ )
+
+ query_result = query.do()
+ parsed_result = parse_get_response(query_result)
+ entries = parsed_result[class_name]
+ for entry in entries:
+ client.data_object.delete(entry["_additional"]["id"], class_name)
+
+ while len(entries) > 0:
+ query_result = query.do()
+ parsed_result = parse_get_response(query_result)
+ entries = parsed_result[class_name]
+ for entry in entries:
+ client.data_object.delete(entry["_additional"]["id"], class_name)
+
+
+def delete_node(client: Any, node_id: str, class_prefix: str) -> None:
+ """Delete entry."""
+ validate_client(client)
+ # make sure that each entry
+ class_name = _class_name(class_prefix)
+ where_filter = {
+ "path": ["doc_id"],
+ "operator": "Equal",
+ "valueString": node_id,
+ }
+ query = (
+ client.query.get(class_name).with_additional(["id"]).with_where(where_filter)
+ )
+
+ query_result = query.do()
+ parsed_result = parse_get_response(query_result)
+ entries = parsed_result[class_name]
+ for entry in entries:
+ client.data_object.delete(entry["_additional"]["id"], class_name)
+
+
+def get_by_node_id(client: Any, node_id: str, class_prefix: str) -> Optional[Dict]:
+ """Delete entry."""
+ validate_client(client)
+ # make sure that each entry
+ class_name = _class_name(class_prefix)
+ where_filter = {
+ "path": ["doc_id"],
+ "operator": "Equal",
+ "valueString": node_id,
+ }
+ query = (
+ client.query.get(class_name).with_additional(["id"]).with_where(where_filter)
+ )
+
+ query_result = query.do()
+ parsed_result = parse_get_response(query_result)
+ entries = parsed_result[class_name]
+ if len(entries) == 0:
+ return None
+
+ return entries[0]
diff --git a/api/docker/entrypoint.sh b/api/docker/entrypoint.sh
new file mode 100644
index 00000000000..50b8cbd86a3
--- /dev/null
+++ b/api/docker/entrypoint.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+set -e
+
+if [[ "${MIGRATION_ENABLED}" == "true" ]]; then
+ echo "Running migrations"
+ flask db upgrade
+fi
+
+if [[ "${MODE}" == "worker" ]]; then
+ celery -A app.celery worker -P ${CELERY_WORKER_CLASS:-gevent} -c ${CELERY_WORKER_AMOUNT:-1} --loglevel INFO
+else
+ if [[ "${DEBUG}" == "true" ]]; then
+ flask run --host=${DIFY_BIND_ADDRESS:-0.0.0.0} --port=${DIFY_PORT:-5001} --debug
+ else
+ gunicorn \
+ --bind "${DIFY_BIND_ADDRESS:-0.0.0.0}:${DIFY_PORT:-5001}" \
+ --workers ${SERVER_WORKER_AMOUNT:-1} \
+ --worker-class ${SERVER_WORKER_CLASS:-gevent} \
+ --timeout ${GUNICORN_TIMEOUT:-200} \
+ --preload \
+ app:app
+ fi
+fi
\ No newline at end of file
diff --git a/api/events/app_event.py b/api/events/app_event.py
new file mode 100644
index 00000000000..938478d3b71
--- /dev/null
+++ b/api/events/app_event.py
@@ -0,0 +1,10 @@
+from blinker import signal
+
+# sender: app
+app_was_created = signal('app-was-created')
+
+# sender: app
+app_was_deleted = signal('app-was-deleted')
+
+# sender: app, kwargs: old_app_model_config, new_app_model_config
+app_model_config_was_updated = signal('app-model-config-was-updated')
diff --git a/api/events/dataset_event.py b/api/events/dataset_event.py
new file mode 100644
index 00000000000..d4a2b6f313c
--- /dev/null
+++ b/api/events/dataset_event.py
@@ -0,0 +1,4 @@
+from blinker import signal
+
+# sender: dataset
+dataset_was_deleted = signal('dataset-was-deleted')
diff --git a/api/events/document_event.py b/api/events/document_event.py
new file mode 100644
index 00000000000..f95326630b2
--- /dev/null
+++ b/api/events/document_event.py
@@ -0,0 +1,4 @@
+from blinker import signal
+
+# sender: document
+document_was_deleted = signal('document-was-deleted')
diff --git a/api/events/event_handlers/__init__.py b/api/events/event_handlers/__init__.py
new file mode 100644
index 00000000000..c858ac08800
--- /dev/null
+++ b/api/events/event_handlers/__init__.py
@@ -0,0 +1,9 @@
+from .create_installed_app_when_app_created import handle
+from .delete_installed_app_when_app_deleted import handle
+from .create_provider_when_tenant_created import handle
+from .create_provider_when_tenant_updated import handle
+from .clean_when_document_deleted import handle
+from .clean_when_dataset_deleted import handle
+from .update_app_dataset_join_when_app_model_config_updated import handle
+from .generate_conversation_name_when_first_message_created import handle
+from .generate_conversation_summary_when_few_message_created import handle
diff --git a/api/events/event_handlers/clean_when_dataset_deleted.py b/api/events/event_handlers/clean_when_dataset_deleted.py
new file mode 100644
index 00000000000..e9975c92bc4
--- /dev/null
+++ b/api/events/event_handlers/clean_when_dataset_deleted.py
@@ -0,0 +1,8 @@
+from events.dataset_event import dataset_was_deleted
+from tasks.clean_dataset_task import clean_dataset_task
+
+
+@dataset_was_deleted.connect
+def handle(sender, **kwargs):
+ dataset = sender
+ clean_dataset_task.delay(dataset.id, dataset.tenant_id, dataset.indexing_technique, dataset.index_struct)
diff --git a/api/events/event_handlers/clean_when_document_deleted.py b/api/events/event_handlers/clean_when_document_deleted.py
new file mode 100644
index 00000000000..d6553b385e0
--- /dev/null
+++ b/api/events/event_handlers/clean_when_document_deleted.py
@@ -0,0 +1,9 @@
+from events.document_event import document_was_deleted
+from tasks.clean_document_task import clean_document_task
+
+
+@document_was_deleted.connect
+def handle(sender, **kwargs):
+ document_id = sender
+ dataset_id = kwargs.get('dataset_id')
+ clean_document_task.delay(document_id, dataset_id)
diff --git a/api/events/event_handlers/create_installed_app_when_app_created.py b/api/events/event_handlers/create_installed_app_when_app_created.py
new file mode 100644
index 00000000000..31084ce0fe8
--- /dev/null
+++ b/api/events/event_handlers/create_installed_app_when_app_created.py
@@ -0,0 +1,16 @@
+from events.app_event import app_was_created
+from extensions.ext_database import db
+from models.model import InstalledApp
+
+
+@app_was_created.connect
+def handle(sender, **kwargs):
+ """Create an installed app when an app is created."""
+ app = sender
+ installed_app = InstalledApp(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ app_owner_tenant_id=app.tenant_id
+ )
+ db.session.add(installed_app)
+ db.session.commit()
diff --git a/api/events/event_handlers/create_provider_when_tenant_created.py b/api/events/event_handlers/create_provider_when_tenant_created.py
new file mode 100644
index 00000000000..e967a5d071c
--- /dev/null
+++ b/api/events/event_handlers/create_provider_when_tenant_created.py
@@ -0,0 +1,9 @@
+from events.tenant_event import tenant_was_updated
+from services.provider_service import ProviderService
+
+
+@tenant_was_updated.connect
+def handle(sender, **kwargs):
+ tenant = sender
+ if tenant.status == 'normal':
+ ProviderService.create_system_provider(tenant)
diff --git a/api/events/event_handlers/create_provider_when_tenant_updated.py b/api/events/event_handlers/create_provider_when_tenant_updated.py
new file mode 100644
index 00000000000..81a7d40ff66
--- /dev/null
+++ b/api/events/event_handlers/create_provider_when_tenant_updated.py
@@ -0,0 +1,9 @@
+from events.tenant_event import tenant_was_created
+from services.provider_service import ProviderService
+
+
+@tenant_was_created.connect
+def handle(sender, **kwargs):
+ tenant = sender
+ if tenant.status == 'normal':
+ ProviderService.create_system_provider(tenant)
diff --git a/api/events/event_handlers/delete_installed_app_when_app_deleted.py b/api/events/event_handlers/delete_installed_app_when_app_deleted.py
new file mode 100644
index 00000000000..1d6271a4665
--- /dev/null
+++ b/api/events/event_handlers/delete_installed_app_when_app_deleted.py
@@ -0,0 +1,12 @@
+from events.app_event import app_was_deleted
+from extensions.ext_database import db
+from models.model import InstalledApp
+
+
+@app_was_deleted.connect
+def handle(sender, **kwargs):
+ app = sender
+ installed_apps = db.session.query(InstalledApp).filter(InstalledApp.app_id == app.id).all()
+ for installed_app in installed_apps:
+ db.session.delete(installed_app)
+ db.session.commit()
diff --git a/api/events/event_handlers/generate_conversation_name_when_first_message_created.py b/api/events/event_handlers/generate_conversation_name_when_first_message_created.py
new file mode 100644
index 00000000000..4c1bbee53e9
--- /dev/null
+++ b/api/events/event_handlers/generate_conversation_name_when_first_message_created.py
@@ -0,0 +1,29 @@
+import logging
+
+from core.generator.llm_generator import LLMGenerator
+from events.message_event import message_was_created
+from extensions.ext_database import db
+
+
+@message_was_created.connect
+def handle(sender, **kwargs):
+ message = sender
+ conversation = kwargs.get('conversation')
+ is_first_message = kwargs.get('is_first_message')
+
+ if is_first_message:
+ if conversation.mode == 'chat':
+ app_model = conversation.app
+ if not app_model:
+ return
+
+ # generate conversation name
+ try:
+ name = LLMGenerator.generate_conversation_name(app_model.tenant_id, message.query, message.answer)
+ conversation.name = name
+ except:
+ conversation.name = 'New Chat'
+ logging.exception('generate_conversation_name failed')
+
+ db.session.add(conversation)
+ db.session.commit()
diff --git a/api/events/event_handlers/generate_conversation_summary_when_few_message_created.py b/api/events/event_handlers/generate_conversation_summary_when_few_message_created.py
new file mode 100644
index 00000000000..df62a90b8e2
--- /dev/null
+++ b/api/events/event_handlers/generate_conversation_summary_when_few_message_created.py
@@ -0,0 +1,14 @@
+from events.message_event import message_was_created
+from tasks.generate_conversation_summary_task import generate_conversation_summary_task
+
+
+@message_was_created.connect
+def handle(sender, **kwargs):
+ message = sender
+ conversation = kwargs.get('conversation')
+ is_first_message = kwargs.get('is_first_message')
+
+ if not is_first_message and conversation.mode == 'chat' and not conversation.summary:
+ history_message_count = conversation.message_count
+ if history_message_count >= 5:
+ generate_conversation_summary_task.delay(conversation.id)
diff --git a/api/events/event_handlers/update_app_dataset_join_when_app_model_config_updated.py b/api/events/event_handlers/update_app_dataset_join_when_app_model_config_updated.py
new file mode 100644
index 00000000000..d165b014d61
--- /dev/null
+++ b/api/events/event_handlers/update_app_dataset_join_when_app_model_config_updated.py
@@ -0,0 +1,66 @@
+from events.app_event import app_model_config_was_updated
+from extensions.ext_database import db
+from models.dataset import AppDatasetJoin
+from models.model import AppModelConfig
+
+
+@app_model_config_was_updated.connect
+def handle(sender, **kwargs):
+ app_model = sender
+ app_model_config = kwargs.get('app_model_config')
+
+ dataset_ids = get_dataset_ids_from_model_config(app_model_config)
+
+ app_dataset_joins = db.session.query(AppDatasetJoin).filter(
+ AppDatasetJoin.app_id == app_model.id
+ ).all()
+
+ removed_dataset_ids = []
+ if not app_dataset_joins:
+ added_dataset_ids = dataset_ids
+ else:
+ old_dataset_ids = set()
+ for app_dataset_join in app_dataset_joins:
+ old_dataset_ids.add(app_dataset_join.dataset_id)
+
+ added_dataset_ids = dataset_ids - old_dataset_ids
+ removed_dataset_ids = old_dataset_ids - dataset_ids
+
+ if removed_dataset_ids:
+ for dataset_id in removed_dataset_ids:
+ db.session.query(AppDatasetJoin).filter(
+ AppDatasetJoin.app_id == app_model.id,
+ AppDatasetJoin.dataset_id == dataset_id
+ ).delete()
+
+ if added_dataset_ids:
+ for dataset_id in added_dataset_ids:
+ app_dataset_join = AppDatasetJoin(
+ app_id=app_model.id,
+ dataset_id=dataset_id
+ )
+ db.session.add(app_dataset_join)
+
+ db.session.commit()
+
+
+def get_dataset_ids_from_model_config(app_model_config: AppModelConfig) -> set:
+ dataset_ids = set()
+ if not app_model_config:
+ return dataset_ids
+
+ agent_mode = app_model_config.agent_mode_dict
+ if agent_mode.get('enabled') is False:
+ return dataset_ids
+
+ if not agent_mode.get('tools'):
+ return dataset_ids
+
+ tools = agent_mode.get('tools')
+ for tool in tools:
+ tool_type = list(tool.keys())[0]
+ tool_config = list(tool.values())[0]
+ if tool_type == "dataset":
+ dataset_ids.add(tool_config.get("id"))
+
+ return dataset_ids
diff --git a/api/events/message_event.py b/api/events/message_event.py
new file mode 100644
index 00000000000..21da83f2496
--- /dev/null
+++ b/api/events/message_event.py
@@ -0,0 +1,4 @@
+from blinker import signal
+
+# sender: message, kwargs: conversation
+message_was_created = signal('message-was-created')
diff --git a/api/events/tenant_event.py b/api/events/tenant_event.py
new file mode 100644
index 00000000000..942f709917b
--- /dev/null
+++ b/api/events/tenant_event.py
@@ -0,0 +1,7 @@
+from blinker import signal
+
+# sender: tenant
+tenant_was_created = signal('tenant-was-created')
+
+# sender: tenant
+tenant_was_updated = signal('tenant-was-updated')
diff --git a/api/extensions/ext_celery.py b/api/extensions/ext_celery.py
new file mode 100644
index 00000000000..f738b984d9d
--- /dev/null
+++ b/api/extensions/ext_celery.py
@@ -0,0 +1,23 @@
+from celery import Task, Celery
+from flask import Flask
+
+
+def init_app(app: Flask) -> Celery:
+ class FlaskTask(Task):
+ def __call__(self, *args: object, **kwargs: object) -> object:
+ with app.app_context():
+ return self.run(*args, **kwargs)
+
+ celery_app = Celery(
+ app.name,
+ task_cls=FlaskTask,
+ broker=app.config["CELERY_BROKER_URL"],
+ backend=app.config["CELERY_BACKEND"],
+ task_ignore_result=True,
+ )
+ celery_app.conf.update(
+ result_backend=app.config["CELERY_RESULT_BACKEND"],
+ )
+ celery_app.set_default()
+ app.extensions["celery"] = celery_app
+ return celery_app
diff --git a/api/extensions/ext_database.py b/api/extensions/ext_database.py
new file mode 100644
index 00000000000..9121c6ead98
--- /dev/null
+++ b/api/extensions/ext_database.py
@@ -0,0 +1,7 @@
+from flask_sqlalchemy import SQLAlchemy
+
+db = SQLAlchemy()
+
+
+def init_app(app):
+ db.init_app(app)
diff --git a/api/extensions/ext_login.py b/api/extensions/ext_login.py
new file mode 100644
index 00000000000..f7d5cffddad
--- /dev/null
+++ b/api/extensions/ext_login.py
@@ -0,0 +1,7 @@
+import flask_login
+
+login_manager = flask_login.LoginManager()
+
+
+def init_app(app):
+ login_manager.init_app(app)
diff --git a/api/extensions/ext_migrate.py b/api/extensions/ext_migrate.py
new file mode 100644
index 00000000000..e7b278fc382
--- /dev/null
+++ b/api/extensions/ext_migrate.py
@@ -0,0 +1,5 @@
+import flask_migrate
+
+
+def init(app, db):
+ flask_migrate.Migrate(app, db)
diff --git a/api/extensions/ext_redis.py b/api/extensions/ext_redis.py
new file mode 100644
index 00000000000..c3e021e7988
--- /dev/null
+++ b/api/extensions/ext_redis.py
@@ -0,0 +1,18 @@
+import redis
+
+
+redis_client = redis.Redis()
+
+
+def init_app(app):
+ redis_client.connection_pool = redis.ConnectionPool(**{
+ 'host': app.config.get('REDIS_HOST', 'localhost'),
+ 'port': app.config.get('REDIS_PORT', 6379),
+ 'password': app.config.get('REDIS_PASSWORD', None),
+ 'db': app.config.get('REDIS_DB', 0),
+ 'encoding': 'utf-8',
+ 'encoding_errors': 'strict',
+ 'decode_responses': False
+ })
+
+ app.extensions['redis'] = redis_client
diff --git a/api/extensions/ext_sentry.py b/api/extensions/ext_sentry.py
new file mode 100644
index 00000000000..f05c10bc089
--- /dev/null
+++ b/api/extensions/ext_sentry.py
@@ -0,0 +1,20 @@
+import sentry_sdk
+from sentry_sdk.integrations.celery import CeleryIntegration
+from sentry_sdk.integrations.flask import FlaskIntegration
+from werkzeug.exceptions import HTTPException
+
+
+def init_app(app):
+ if app.config.get('SENTRY_DSN'):
+ sentry_sdk.init(
+ dsn=app.config.get('SENTRY_DSN'),
+ integrations=[
+ FlaskIntegration(),
+ CeleryIntegration()
+ ],
+ ignore_errors=[HTTPException, ValueError],
+ traces_sample_rate=app.config.get('SENTRY_TRACES_SAMPLE_RATE', 1.0),
+ profiles_sample_rate=app.config.get('SENTRY_PROFILES_SAMPLE_RATE', 1.0),
+ environment=app.config.get('DEPLOY_ENV'),
+ release=f"dify-{app.config.get('CURRENT_VERSION')}-{app.config.get('COMMIT_SHA')}"
+ )
diff --git a/api/extensions/ext_session.py b/api/extensions/ext_session.py
new file mode 100644
index 00000000000..5b454d469ea
--- /dev/null
+++ b/api/extensions/ext_session.py
@@ -0,0 +1,168 @@
+import redis
+from flask import request
+from flask_session import Session, SqlAlchemySessionInterface, RedisSessionInterface
+from flask_session.sessions import total_seconds
+from itsdangerous import want_bytes
+
+from extensions.ext_database import db
+
+sess = Session()
+
+
+def init_app(app):
+ sqlalchemy_session_interface = CustomSqlAlchemySessionInterface(
+ app,
+ db,
+ app.config.get('SESSION_SQLALCHEMY_TABLE', 'sessions'),
+ app.config.get('SESSION_KEY_PREFIX', 'session:'),
+ app.config.get('SESSION_USE_SIGNER', False),
+ app.config.get('SESSION_PERMANENT', True)
+ )
+
+ session_type = app.config.get('SESSION_TYPE')
+ if session_type == 'sqlalchemy':
+ app.session_interface = sqlalchemy_session_interface
+ elif session_type == 'redis':
+ sess_redis_client = redis.Redis()
+ sess_redis_client.connection_pool = redis.ConnectionPool(**{
+ 'host': app.config.get('SESSION_REDIS_HOST', 'localhost'),
+ 'port': app.config.get('SESSION_REDIS_PORT', 6379),
+ 'password': app.config.get('SESSION_REDIS_PASSWORD', None),
+ 'db': app.config.get('SESSION_REDIS_DB', 2),
+ 'encoding': 'utf-8',
+ 'encoding_errors': 'strict',
+ 'decode_responses': False
+ })
+
+ app.extensions['session_redis'] = sess_redis_client
+
+ app.session_interface = CustomRedisSessionInterface(
+ sess_redis_client,
+ app.config.get('SESSION_KEY_PREFIX', 'session:'),
+ app.config.get('SESSION_USE_SIGNER', False),
+ app.config.get('SESSION_PERMANENT', True)
+ )
+
+
+class CustomSqlAlchemySessionInterface(SqlAlchemySessionInterface):
+
+ def __init__(
+ self,
+ app,
+ db,
+ table,
+ key_prefix,
+ use_signer=False,
+ permanent=True,
+ sequence=None,
+ autodelete=False,
+ ):
+ if db is None:
+ from flask_sqlalchemy import SQLAlchemy
+
+ db = SQLAlchemy(app)
+ self.db = db
+ self.key_prefix = key_prefix
+ self.use_signer = use_signer
+ self.permanent = permanent
+ self.autodelete = autodelete
+ self.sequence = sequence
+ self.has_same_site_capability = hasattr(self, "get_cookie_samesite")
+
+ class Session(self.db.Model):
+ __tablename__ = table
+
+ if sequence:
+ id = self.db.Column( # noqa: A003, VNE003, A001
+ self.db.Integer, self.db.Sequence(sequence), primary_key=True
+ )
+ else:
+ id = self.db.Column( # noqa: A003, VNE003, A001
+ self.db.Integer, primary_key=True
+ )
+
+ session_id = self.db.Column(self.db.String(255), unique=True)
+ data = self.db.Column(self.db.LargeBinary)
+ expiry = self.db.Column(self.db.DateTime)
+
+ def __init__(self, session_id, data, expiry):
+ self.session_id = session_id
+ self.data = data
+ self.expiry = expiry
+
+ def __repr__(self):
+ return f"<Session data {self.data}>"
+
+ self.sql_session_model = Session
+
+ def save_session(self, *args, **kwargs):
+ if request.blueprint == 'service_api':
+ return
+ elif request.method == 'OPTIONS':
+ return
+ elif request.endpoint and request.endpoint == 'health':
+ return
+ return super().save_session(*args, **kwargs)
+
+
+class CustomRedisSessionInterface(RedisSessionInterface):
+
+ def save_session(self, app, session, response):
+ if request.blueprint == 'service_api':
+ return
+ elif request.method == 'OPTIONS':
+ return
+ elif request.endpoint and request.endpoint == 'health':
+ return
+
+ if not self.should_set_cookie(app, session):
+ return
+ domain = self.get_cookie_domain(app)
+ path = self.get_cookie_path(app)
+ if not session:
+ if session.modified:
+ self.redis.delete(self.key_prefix + session.sid)
+ response.delete_cookie(
+ app.config["SESSION_COOKIE_NAME"], domain=domain, path=path
+ )
+ return
+
+ # Modification case. There are upsides and downsides to
+ # emitting a set-cookie header each request. The behavior
+ # is controlled by the :meth:`should_set_cookie` method
+ # which performs a quick check to figure out if the cookie
+ # should be set or not. This is controlled by the
+ # SESSION_REFRESH_EACH_REQUEST config flag as well as
+ # the permanent flag on the session itself.
+ # if not self.should_set_cookie(app, session):
+ # return
+ conditional_cookie_kwargs = {}
+ httponly = self.get_cookie_httponly(app)
+ secure = self.get_cookie_secure(app)
+ if self.has_same_site_capability:
+ conditional_cookie_kwargs["samesite"] = self.get_cookie_samesite(app)
+ expires = self.get_expiration_time(app, session)
+
+ if session.permanent:
+ value = self.serializer.dumps(dict(session))
+ if value is not None:
+ self.redis.setex(
+ name=self.key_prefix + session.sid,
+ value=value,
+ time=total_seconds(app.permanent_session_lifetime),
+ )
+
+ if self.use_signer:
+ session_id = self._get_signer(app).sign(want_bytes(session.sid)).decode("utf-8")
+ else:
+ session_id = session.sid
+ response.set_cookie(
+ app.config["SESSION_COOKIE_NAME"],
+ session_id,
+ expires=expires,
+ httponly=httponly,
+ domain=domain,
+ path=path,
+ secure=secure,
+ **conditional_cookie_kwargs,
+ )
diff --git a/api/extensions/ext_storage.py b/api/extensions/ext_storage.py
new file mode 100644
index 00000000000..dc44892024f
--- /dev/null
+++ b/api/extensions/ext_storage.py
@@ -0,0 +1,108 @@
+import os
+import shutil
+from contextlib import closing
+
+import boto3
+from botocore.exceptions import ClientError
+from flask import Flask
+
+
+class Storage:
+ def __init__(self):
+ self.storage_type = None
+ self.bucket_name = None
+ self.client = None
+ self.folder = None
+
+ def init_app(self, app: Flask):
+ self.storage_type = app.config.get('STORAGE_TYPE')
+ if self.storage_type == 's3':
+ self.bucket_name = app.config.get('S3_BUCKET_NAME')
+ self.client = boto3.client(
+ 's3',
+ aws_secret_access_key=app.config.get('S3_SECRET_KEY'),
+ aws_access_key_id=app.config.get('S3_ACCESS_KEY'),
+ endpoint_url=app.config.get('S3_ENDPOINT'),
+ region_name=app.config.get('S3_REGION')
+ )
+ else:
+ self.folder = app.config.get('STORAGE_LOCAL_PATH')
+ if not os.path.isabs(self.folder):
+ self.folder = os.path.join(app.root_path, self.folder)
+
+ def save(self, filename, data):
+ if self.storage_type == 's3':
+ self.client.put_object(Bucket=self.bucket_name, Key=filename, Body=data)
+ else:
+ if not self.folder or self.folder.endswith('/'):
+ filename = self.folder + filename
+ else:
+ filename = self.folder + '/' + filename
+
+ folder = os.path.dirname(filename)
+ os.makedirs(folder, exist_ok=True)
+
+ with open(os.path.join(os.getcwd(), filename), "wb") as f:
+ f.write(data)
+
+ def load(self, filename):
+ if self.storage_type == 's3':
+ try:
+ with closing(self.client) as client:
+ data = client.get_object(Bucket=self.bucket_name, Key=filename)['Body'].read()
+ except ClientError as ex:
+ if ex.response['Error']['Code'] == 'NoSuchKey':
+ raise FileNotFoundError("File not found")
+ else:
+ raise
+ else:
+ if not self.folder or self.folder.endswith('/'):
+ filename = self.folder + filename
+ else:
+ filename = self.folder + '/' + filename
+
+ if not os.path.exists(filename):
+ raise FileNotFoundError("File not found")
+
+ with open(filename, "rb") as f:
+ data = f.read()
+
+ return data
+
+ def download(self, filename, target_filepath):
+ if self.storage_type == 's3':
+ with closing(self.client) as client:
+ client.download_file(self.bucket_name, filename, target_filepath)
+ else:
+ if not self.folder or self.folder.endswith('/'):
+ filename = self.folder + filename
+ else:
+ filename = self.folder + '/' + filename
+
+ if not os.path.exists(filename):
+ raise FileNotFoundError("File not found")
+
+ shutil.copyfile(filename, target_filepath)
+
+ def exists(self, filename):
+ if self.storage_type == 's3':
+ with closing(self.client) as client:
+ try:
+ client.head_object(Bucket=self.bucket_name, Key=filename)
+ return True
+ except:
+ return False
+ else:
+ if not self.folder or self.folder.endswith('/'):
+ filename = self.folder + filename
+ else:
+ filename = self.folder + '/' + filename
+
+ return os.path.exists(filename)
+
+
+storage = Storage()
+
+
+def init_app(app: Flask):
+ storage.init_app(app)
diff --git a/api/extensions/ext_vector_store.py b/api/extensions/ext_vector_store.py
new file mode 100644
index 00000000000..4ed7a93422d
--- /dev/null
+++ b/api/extensions/ext_vector_store.py
@@ -0,0 +1,7 @@
+from core.vector_store.vector_store import VectorStore
+
+vector_store = VectorStore()
+
+
+def init_app(app):
+ vector_store.init_app(app)
diff --git a/api/libs/__init__.py b/api/libs/__init__.py
new file mode 100644
index 00000000000..380474e035b
--- /dev/null
+++ b/api/libs/__init__.py
@@ -0,0 +1 @@
+# -*- coding:utf-8 -*-
diff --git a/api/libs/ecc_aes.py b/api/libs/ecc_aes.py
new file mode 100644
index 00000000000..aef32145357
--- /dev/null
+++ b/api/libs/ecc_aes.py
@@ -0,0 +1,82 @@
+from Crypto.Cipher import AES
+from Crypto.Hash import SHA256
+from Crypto.PublicKey import ECC
+from Crypto.Util.Padding import pad, unpad
+
+
+class ECC_AES:
+ def __init__(self, curve='P-256'):
+ self.curve = curve
+ self._aes_key = None
+ self._private_key = None
+
+ def _derive_aes_key(self, ecc_key, nonce):
+ if not self._aes_key:
+ hasher = SHA256.new()
+ hasher.update(ecc_key.export_key(format='DER') + nonce.encode())
+ self._aes_key = hasher.digest()[:32]
+ return self._aes_key
+
+ def generate_key_pair(self):
+ private_key = ECC.generate(curve=self.curve)
+ public_key = private_key.public_key()
+
+ pem_private = private_key.export_key(format='PEM')
+ pem_public = public_key.export_key(format='PEM')
+
+ return pem_private, pem_public
+
+ def load_private_key(self, private_key_pem):
+ self._private_key = ECC.import_key(private_key_pem)
+ self._aes_key = None
+
+ def encrypt(self, text, nonce):
+ if not self._private_key:
+ raise ValueError("Private key not loaded")
+
+ # Generate AES key using ECC private key and nonce
+ aes_key = self._derive_aes_key(self._private_key, nonce)
+
+ # Encrypt data using AES key
+ cipher = AES.new(aes_key, AES.MODE_ECB)
+ padded_text = pad(text.encode(), AES.block_size)
+ ciphertext = cipher.encrypt(padded_text)
+
+ return ciphertext
+
+ def decrypt(self, ciphertext, nonce):
+ if not self._private_key:
+ raise ValueError("Private key not loaded")
+
+ # Generate AES key using ECC private key and nonce
+ aes_key = self._derive_aes_key(self._private_key, nonce)
+
+ # Decrypt data using AES key
+ cipher = AES.new(aes_key, AES.MODE_ECB)
+ padded_plaintext = cipher.decrypt(ciphertext)
+ plaintext = unpad(padded_plaintext, AES.block_size)
+
+ return plaintext.decode()
+
+
+if __name__ == '__main__':
+ ecc_aes = ECC_AES()
+
+ # Generate key pairs for the user
+ private_key, public_key = ecc_aes.generate_key_pair()
+ ecc_aes.load_private_key(private_key)
+ nonce = "THIS-IS-USER-ID"
+
+ print(private_key)
+
+ # Encrypt a message
+ message = "Hello, this is a secret message!"
+ encrypted_message = ecc_aes.encrypt(message, nonce)
+ print(f"Encrypted message: {encrypted_message.hex()}")
+
+ # Decrypt the message
+ decrypted_message = ecc_aes.decrypt(encrypted_message, nonce)
+ print(f"Decrypted message: {decrypted_message}")
+
+ # Check if the original message and decrypted message are the same
+ assert message == decrypted_message, "Original message and decrypted message do not match"
diff --git a/api/libs/exception.py b/api/libs/exception.py
new file mode 100644
index 00000000000..567062f064f
--- /dev/null
+++ b/api/libs/exception.py
@@ -0,0 +1,17 @@
+from typing import Optional
+
+from werkzeug.exceptions import HTTPException
+
+
+class BaseHTTPException(HTTPException):
+ error_code: str = 'unknown'
+ data: Optional[dict] = None
+
+ def __init__(self, description=None, response=None):
+ super().__init__(description, response)
+
+ self.data = {
+ "code": self.error_code,
+ "message": self.description,
+ "status": self.code,
+ }
\ No newline at end of file
diff --git a/api/libs/external_api.py b/api/libs/external_api.py
new file mode 100644
index 00000000000..b5cc8fb9c51
--- /dev/null
+++ b/api/libs/external_api.py
@@ -0,0 +1,115 @@
+import re
+import sys
+
+from flask import got_request_exception, current_app
+from flask_restful import Api, http_status_message
+from werkzeug.datastructures import Headers
+from werkzeug.exceptions import HTTPException
+
+
+class ExternalApi(Api):
+
+ def handle_error(self, e):
+ """Error handler for the API transforms a raised exception into a Flask
+ response, with the appropriate HTTP status code and body.
+
+ :param e: the raised Exception object
+ :type e: Exception
+
+ """
+ got_request_exception.send(current_app, exception=e)
+
+ headers = Headers()
+ if isinstance(e, HTTPException):
+ if e.response is not None:
+ resp = e.get_response()
+ return resp
+
+ status_code = e.code
+ default_data = {
+ 'code': re.sub(r'(?<!^)(?=[A-Z])', '_', type(e).__name__).lower(),
+ 'message': getattr(e, 'description', http_status_message(status_code)),
+ 'status': status_code
+ }
+ headers = e.get_response().headers
+ elif isinstance(e, ValueError):
+ status_code = 400
+ default_data = {
+ 'code': 'invalid_param',
+ 'message': str(e),
+ 'status': status_code
+ }
+ else:
+ status_code = 500
+ default_data = {
+ 'message': http_status_message(status_code),
+ }
+
+ # Werkzeug exceptions generate a content-length header which is added
+ # to the response in addition to the actual content-length header
+ # https://github.com/flask-restful/flask-restful/issues/534
+ remove_headers = ('Content-Length',)
+
+ for header in remove_headers:
+ headers.pop(header, None)
+
+ data = getattr(e, 'data', default_data)
+
+ error_cls_name = type(e).__name__
+ if error_cls_name in self.errors:
+ custom_data = self.errors.get(error_cls_name, {})
+ custom_data = custom_data.copy()
+ status_code = custom_data.get('status', 500)
+
+ if 'message' in custom_data:
+ custom_data['message'] = custom_data['message'].format(
+ message=str(e.description if hasattr(e, 'description') else e)
+ )
+ data.update(custom_data)
+
+ # record the exception in the logs when we have a server error of status code: 500
+ if status_code and status_code >= 500:
+ exc_info = sys.exc_info()
+ if exc_info[1] is None:
+ exc_info = None
+ current_app.log_exception(exc_info)
+
+ if status_code == 406 and self.default_mediatype is None:
+ # if we are handling NotAcceptable (406), make sure that
+ # make_response uses a representation we support as the
+ # default mediatype (so that make_response doesn't throw
+ # another NotAcceptable error).
+ supported_mediatypes = list(self.representations.keys()) # only supported application/json
+ fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"
+ data = {
+ 'code': 'not_acceptable',
+ 'message': data.get('message')
+ }
+ resp = self.make_response(
+ data,
+ status_code,
+ headers,
+ fallback_mediatype = fallback_mediatype
+ )
+ elif status_code == 400:
+ if isinstance(data.get('message'), dict):
+ param_key, param_value = list(data.get('message').items())[0]
+ data = {
+ 'code': 'invalid_param',
+ 'message': param_value,
+ 'params': param_key
+ }
+ else:
+ if 'code' not in data:
+ data['code'] = 'unknown'
+
+ resp = self.make_response(data, status_code, headers)
+ else:
+ if 'code' not in data:
+ data['code'] = 'unknown'
+
+ resp = self.make_response(data, status_code, headers)
+
+ if status_code == 401:
+ resp = self.unauthorized(resp)
+ return resp
diff --git a/api/libs/helper.py b/api/libs/helper.py
new file mode 100644
index 00000000000..bbf01cbad76
--- /dev/null
+++ b/api/libs/helper.py
@@ -0,0 +1,149 @@
+# -*- coding:utf-8 -*-
+import re
+import subprocess
+import uuid
+from datetime import datetime
+from zoneinfo import available_timezones
+import random
+import string
+
+from flask_restful import fields
+
+
+def run(script):
+ return subprocess.getstatusoutput('source /root/.bashrc && ' + script)
+
+
+class TimestampField(fields.Raw):
+ def format(self, value):
+ return int(value.timestamp())
+
+
+def email(email):
+ # Define a regex pattern for email addresses
+ pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
+ # Check if the email matches the pattern
+ if re.match(pattern, email) is not None:
+ return email
+
+ error = ('{email} is not a valid email.'
+ .format(email=email))
+ raise ValueError(error)
+
+
+def uuid_value(value):
+ if value == '':
+ return str(value)
+
+ try:
+ uuid_obj = uuid.UUID(value)
+ return str(uuid_obj)
+ except ValueError:
+ error = ('{value} is not a valid uuid.'
+ .format(value=value))
+ raise ValueError(error)
+
+
+def timestamp_value(timestamp):
+ try:
+ int_timestamp = int(timestamp)
+ if int_timestamp < 0:
+ raise ValueError
+ return int_timestamp
+ except ValueError:
+ error = ('{timestamp} is not a valid timestamp.'
+ .format(timestamp=timestamp))
+ raise ValueError(error)
+
+
+class str_len(object):
+ """ Restrict input to an integer in a range (inclusive) """
+
+ def __init__(self, max_length, argument='argument'):
+ self.max_length = max_length
+ self.argument = argument
+
+ def __call__(self, value):
+ length = len(value)
+ if length > self.max_length:
+ error = ('Invalid {arg}: {val}. {arg} cannot exceed length {length}'
+ .format(arg=self.argument, val=value, length=self.max_length))
+ raise ValueError(error)
+
+ return value
+
+
+class float_range(object):
+ """ Restrict input to an float in a range (inclusive) """
+ def __init__(self, low, high, argument='argument'):
+ self.low = low
+ self.high = high
+ self.argument = argument
+
+ def __call__(self, value):
+ value = _get_float(value)
+ if value < self.low or value > self.high:
+ error = ('Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}'
+ .format(arg=self.argument, val=value, lo=self.low, hi=self.high))
+ raise ValueError(error)
+
+ return value
+
+
+class datetime_string(object):
+ def __init__(self, format, argument='argument'):
+ self.format = format
+ self.argument = argument
+
+ def __call__(self, value):
+ try:
+ datetime.strptime(value, self.format)
+ except ValueError:
+ error = ('Invalid {arg}: {val}. {arg} must be conform to the format {format}'
+ .format(arg=self.argument, val=value, lo=self.format))
+ raise ValueError(error)
+
+ return value
+
+
+def _get_float(value):
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ raise ValueError('{0} is not a valid float'.format(value))
+
+
+def supported_language(lang):
+ if lang in ['en-US', 'zh-Hans']:
+ return lang
+
+ error = ('{lang} is not a valid language.'
+ .format(lang=lang))
+ raise ValueError(error)
+
+
+def timezone(timezone_string):
+ if timezone_string and timezone_string in available_timezones():
+ return timezone_string
+
+ error = ('{timezone_string} is not a valid timezone.'
+ .format(timezone_string=timezone_string))
+ raise ValueError(error)
+
+
+def generate_string(n):
+ letters_digits = string.ascii_letters + string.digits
+ result = ""
+ for i in range(n):
+ result += random.choice(letters_digits)
+
+ return result
+
+
+def get_remote_ip(request):
+ if request.headers.get('CF-Connecting-IP'):
+ return request.headers.get('Cf-Connecting-Ip')
+ elif request.headers.getlist("X-Forwarded-For"):
+ return request.headers.getlist("X-Forwarded-For")[0]
+ else:
+ return request.remote_addr
diff --git a/api/libs/infinite_scroll_pagination.py b/api/libs/infinite_scroll_pagination.py
new file mode 100644
index 00000000000..076cb383b8e
--- /dev/null
+++ b/api/libs/infinite_scroll_pagination.py
@@ -0,0 +1,7 @@
+# -*- coding:utf-8 -*-
+
+class InfiniteScrollPagination:
+ def __init__(self, data, limit, has_more):
+ self.data = data
+ self.limit = limit
+ self.has_more = has_more
diff --git a/api/libs/oauth.py b/api/libs/oauth.py
new file mode 100644
index 00000000000..ce41f0c22cf
--- /dev/null
+++ b/api/libs/oauth.py
@@ -0,0 +1,136 @@
+import urllib.parse
+from dataclasses import dataclass
+
+import requests
+
+
+@dataclass
+class OAuthUserInfo:
+ id: str
+ name: str
+ email: str
+
+
+class OAuth:
+ def __init__(self, client_id: str, client_secret: str, redirect_uri: str):
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.redirect_uri = redirect_uri
+
+ def get_authorization_url(self):
+ raise NotImplementedError()
+
+ def get_access_token(self, code: str):
+ raise NotImplementedError()
+
+ def get_raw_user_info(self, token: str):
+ raise NotImplementedError()
+
+ def get_user_info(self, token: str) -> OAuthUserInfo:
+ raw_info = self.get_raw_user_info(token)
+ return self._transform_user_info(raw_info)
+
+ def _transform_user_info(self, raw_info: dict) -> OAuthUserInfo:
+ raise NotImplementedError()
+
+
+class GitHubOAuth(OAuth):
+ _AUTH_URL = 'https://github.com/login/oauth/authorize'
+ _TOKEN_URL = 'https://github.com/login/oauth/access_token'
+ _USER_INFO_URL = 'https://api.github.com/user'
+ _EMAIL_INFO_URL = 'https://api.github.com/user/emails'
+
+ def get_authorization_url(self):
+ params = {
+ 'client_id': self.client_id,
+ 'redirect_uri': self.redirect_uri,
+ 'scope': 'user:email' # Request only basic user information
+ }
+ return f"{self._AUTH_URL}?{urllib.parse.urlencode(params)}"
+
+ def get_access_token(self, code: str):
+ data = {
+ 'client_id': self.client_id,
+ 'client_secret': self.client_secret,
+ 'code': code,
+ 'redirect_uri': self.redirect_uri
+ }
+ headers = {'Accept': 'application/json'}
+ response = requests.post(self._TOKEN_URL, data=data, headers=headers)
+
+ response_json = response.json()
+ access_token = response_json.get('access_token')
+
+ if not access_token:
+ raise ValueError(f"Error in GitHub OAuth: {response_json}")
+
+ return access_token
+
+ def get_raw_user_info(self, token: str):
+ headers = {'Authorization': f"token {token}"}
+ response = requests.get(self._USER_INFO_URL, headers=headers)
+ response.raise_for_status()
+ user_info = response.json()
+
+ email_response = requests.get(self._EMAIL_INFO_URL, headers=headers)
+ email_info = email_response.json()
+ primary_email = next((email for email in email_info if email['primary'] == True), None)
+
+ return {**user_info, 'email': primary_email['email']}
+
+ def _transform_user_info(self, raw_info: dict) -> OAuthUserInfo:
+ email = raw_info.get('email')
+ if not email:
+ email = f"{raw_info['id']}+{raw_info['login']}@users.noreply.github.com"
+ return OAuthUserInfo(
+ id=str(raw_info['id']),
+ name=raw_info['name'],
+ email=email
+ )
+
+
+class GoogleOAuth(OAuth):
+ _AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'
+ _TOKEN_URL = 'https://oauth2.googleapis.com/token'
+ _USER_INFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo'
+
+ def get_authorization_url(self):
+ params = {
+ 'client_id': self.client_id,
+ 'response_type': 'code',
+ 'redirect_uri': self.redirect_uri,
+ 'scope': 'openid email'
+ }
+ return f"{self._AUTH_URL}?{urllib.parse.urlencode(params)}"
+
+ def get_access_token(self, code: str):
+ data = {
+ 'client_id': self.client_id,
+ 'client_secret': self.client_secret,
+ 'code': code,
+ 'grant_type': 'authorization_code',
+ 'redirect_uri': self.redirect_uri
+ }
+ headers = {'Accept': 'application/json'}
+ response = requests.post(self._TOKEN_URL, data=data, headers=headers)
+
+ response_json = response.json()
+ access_token = response_json.get('access_token')
+
+ if not access_token:
+ raise ValueError(f"Error in Google OAuth: {response_json}")
+
+ return access_token
+
+ def get_raw_user_info(self, token: str):
+ headers = {'Authorization': f"Bearer {token}"}
+ response = requests.get(self._USER_INFO_URL, headers=headers)
+ response.raise_for_status()
+ return response.json()
+
+ def _transform_user_info(self, raw_info: dict) -> OAuthUserInfo:
+ return OAuthUserInfo(
+ id=str(raw_info['sub']),
+ name=None,
+ email=raw_info['email']
+ )
diff --git a/api/libs/password.py b/api/libs/password.py
new file mode 100644
index 00000000000..dde77c10468
--- /dev/null
+++ b/api/libs/password.py
@@ -0,0 +1,26 @@
+# -*- coding:utf-8 -*-
+import base64
+import binascii
+import hashlib
+import re
+
+password_pattern = r"^(?=.*[a-zA-Z])(?=.*\d).{8,}$"
+
+def valid_password(password):
+ # Define a regex pattern for password rules
+ pattern = password_pattern
+ # Check if the password matches the pattern
+ if re.match(pattern, password) is not None:
+ return password
+
+ raise ValueError('Not a valid password.')
+
+
+def hash_password(password_str, salt_byte):
+ dk = hashlib.pbkdf2_hmac('sha256', password_str.encode('utf-8'), salt_byte, 10000)
+ return binascii.hexlify(dk)
+
+
+def compare_password(password_str, password_hashed_base64, salt_base64):
+ # compare password for login
+ return hash_password(password_str, base64.b64decode(salt_base64)) == base64.b64decode(password_hashed_base64)
diff --git a/api/libs/rsa.py b/api/libs/rsa.py
new file mode 100644
index 00000000000..8741989a9a7
--- /dev/null
+++ b/api/libs/rsa.py
@@ -0,0 +1,58 @@
+# -*- coding:utf-8 -*-
+import hashlib
+
+from Crypto.Cipher import PKCS1_OAEP
+from Crypto.PublicKey import RSA
+
+from extensions.ext_redis import redis_client
+from extensions.ext_storage import storage
+
+
+# TODO: PKCS1_OAEP is no longer recommended for new systems and protocols. It is recommended to migrate to PKCS1_PSS.
+
+
+def generate_key_pair(tenant_id):
+ private_key = RSA.generate(2048)
+ public_key = private_key.publickey()
+
+ pem_private = private_key.export_key()
+ pem_public = public_key.export_key()
+
+ filepath = "privkeys/{tenant_id}".format(tenant_id=tenant_id) + "/private.pem"
+
+ storage.save(filepath, pem_private)
+
+ return pem_public.decode()
+
+
+def encrypt(text, public_key):
+ if isinstance(public_key, str):
+ public_key = public_key.encode()
+
+ rsa_key = RSA.import_key(public_key)
+ cipher = PKCS1_OAEP.new(rsa_key)
+ encrypted_text = cipher.encrypt(text.encode())
+ return encrypted_text
+
+
+def decrypt(encrypted_text, tenant_id):
+ filepath = "privkeys/{tenant_id}".format(tenant_id=tenant_id) + "/private.pem"
+
+ cache_key = 'tenant_privkey:{hash}'.format(hash=hashlib.sha3_256(filepath.encode()).hexdigest())
+ private_key = redis_client.get(cache_key)
+ if not private_key:
+ try:
+ private_key = storage.load(filepath)
+ except FileNotFoundError:
+ raise PrivkeyNotFoundError("Private key not found, tenant_id: {tenant_id}".format(tenant_id=tenant_id))
+
+ redis_client.setex(cache_key, 120, private_key)
+
+ rsa_key = RSA.import_key(private_key)
+ cipher = PKCS1_OAEP.new(rsa_key)
+ decrypted_text = cipher.decrypt(encrypted_text)
+ return decrypted_text.decode()
+
+
+class PrivkeyNotFoundError(Exception):
+ pass
diff --git a/api/migrations/README b/api/migrations/README
new file mode 100644
index 00000000000..0e048441597
--- /dev/null
+++ b/api/migrations/README
@@ -0,0 +1 @@
+Single-database configuration for Flask.
diff --git a/api/migrations/alembic.ini b/api/migrations/alembic.ini
new file mode 100644
index 00000000000..ec9d45c26a6
--- /dev/null
+++ b/api/migrations/alembic.ini
@@ -0,0 +1,50 @@
+# A generic, single database configuration.
+
+[alembic]
+# template used to generate migration files
+# file_template = %%(rev)s_%%(slug)s
+
+# set to 'true' to run the environment during
+# the 'revision' command, regardless of autogenerate
+# revision_environment = false
+
+
+# Logging configuration
+[loggers]
+keys = root,sqlalchemy,alembic,flask_migrate
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = WARN
+handlers = console
+qualname =
+
+[logger_sqlalchemy]
+level = WARN
+handlers =
+qualname = sqlalchemy.engine
+
+[logger_alembic]
+level = INFO
+handlers =
+qualname = alembic
+
+[logger_flask_migrate]
+level = INFO
+handlers =
+qualname = flask_migrate
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S
diff --git a/api/migrations/env.py b/api/migrations/env.py
new file mode 100644
index 00000000000..0ac25ee989a
--- /dev/null
+++ b/api/migrations/env.py
@@ -0,0 +1,113 @@
+import logging
+from logging.config import fileConfig
+
+from flask import current_app
+
+from alembic import context
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+fileConfig(config.config_file_name)
+logger = logging.getLogger('alembic.env')
+
+
+def get_engine():
+ return current_app.extensions['migrate'].db.engine
+
+
+def get_engine_url():
+ try:
+ return get_engine().url.render_as_string(hide_password=False).replace(
+ '%', '%%')
+ except AttributeError:
+ return str(get_engine().url).replace('%', '%%')
+
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# target_metadata = mymodel.Base.metadata
+config.set_main_option('sqlalchemy.url', get_engine_url())
+target_db = current_app.extensions['migrate'].db
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def get_metadata():
+ if hasattr(target_db, 'metadatas'):
+ return target_db.metadatas[None]
+ return target_db.metadata
+
+
+def include_object(object, name, type_, reflected, compare_to):
+ if type_ == "foreign_key_constraint":
+ return False
+ else:
+ return True
+
+
+def run_migrations_offline():
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
+ Calls to context.execute() here emit the given string to the
+ script output.
+
+ """
+ url = config.get_main_option("sqlalchemy.url")
+ context.configure(
+ url=url, target_metadata=get_metadata(), literal_binds=True
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+def run_migrations_online():
+ """Run migrations in 'online' mode.
+
+ In this scenario we need to create an Engine
+ and associate a connection with the context.
+
+ """
+
+ # this callback is used to prevent an auto-migration from being generated
+ # when there are no changes to the schema
+ # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
+ def process_revision_directives(context, revision, directives):
+ if getattr(config.cmd_opts, 'autogenerate', False):
+ script = directives[0]
+ if script.upgrade_ops.is_empty():
+ directives[:] = []
+ logger.info('No changes in schema detected.')
+
+ connectable = get_engine()
+
+ with connectable.connect() as connection:
+ context.configure(
+ connection=connection,
+ target_metadata=get_metadata(),
+ process_revision_directives=process_revision_directives,
+ include_object=include_object,
+ **current_app.extensions['migrate'].configure_args
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()
diff --git a/api/migrations/script.py.mako b/api/migrations/script.py.mako
new file mode 100644
index 00000000000..2c0156303a8
--- /dev/null
+++ b/api/migrations/script.py.mako
@@ -0,0 +1,24 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+# revision identifiers, used by Alembic.
+revision = ${repr(up_revision)}
+down_revision = ${repr(down_revision)}
+branch_labels = ${repr(branch_labels)}
+depends_on = ${repr(depends_on)}
+
+
+def upgrade():
+ ${upgrades if upgrades else "pass"}
+
+
+def downgrade():
+ ${downgrades if downgrades else "pass"}
diff --git a/api/migrations/versions/64b051264f32_init.py b/api/migrations/versions/64b051264f32_init.py
new file mode 100644
index 00000000000..84e1f2af17a
--- /dev/null
+++ b/api/migrations/versions/64b051264f32_init.py
@@ -0,0 +1,793 @@
+"""init
+
+Revision ID: 64b051264f32
+Revises:
+Create Date: 2023-05-13 14:26:59.085018
+
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+# revision identifiers, used by Alembic.
+revision = '64b051264f32'
+down_revision = None
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('account_integrates',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('account_id', postgresql.UUID(), nullable=False),
+ sa.Column('provider', sa.String(length=16), nullable=False),
+ sa.Column('open_id', sa.String(length=255), nullable=False),
+ sa.Column('encrypted_token', sa.String(length=255), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='account_integrate_pkey'),
+ sa.UniqueConstraint('account_id', 'provider', name='unique_account_provider'),
+ sa.UniqueConstraint('provider', 'open_id', name='unique_provider_open_id')
+ )
+ op.create_table('accounts',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('email', sa.String(length=255), nullable=False),
+ sa.Column('password', sa.String(length=255), nullable=True),
+ sa.Column('password_salt', sa.String(length=255), nullable=True),
+ sa.Column('avatar', sa.String(length=255), nullable=True),
+ sa.Column('interface_language', sa.String(length=255), nullable=True),
+ sa.Column('interface_theme', sa.String(length=255), nullable=True),
+ sa.Column('timezone', sa.String(length=255), nullable=True),
+ sa.Column('last_login_at', sa.DateTime(), nullable=True),
+ sa.Column('last_login_ip', sa.String(length=255), nullable=True),
+ sa.Column('status', sa.String(length=16), server_default=sa.text("'active'::character varying"), nullable=False),
+ sa.Column('initialized_at', sa.DateTime(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='account_pkey')
+ )
+ with op.batch_alter_table('accounts', schema=None) as batch_op:
+ batch_op.create_index('account_email_idx', ['email'], unique=False)
+
+ op.create_table('api_requests',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('api_token_id', postgresql.UUID(), nullable=False),
+ sa.Column('path', sa.String(length=255), nullable=False),
+ sa.Column('request', sa.Text(), nullable=True),
+ sa.Column('response', sa.Text(), nullable=True),
+ sa.Column('ip', sa.String(length=255), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='api_request_pkey')
+ )
+ with op.batch_alter_table('api_requests', schema=None) as batch_op:
+ batch_op.create_index('api_request_token_idx', ['tenant_id', 'api_token_id'], unique=False)
+
+ op.create_table('api_tokens',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=True),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=True),
+ sa.Column('type', sa.String(length=16), nullable=False),
+ sa.Column('token', sa.String(length=255), nullable=False),
+ sa.Column('last_used_at', sa.DateTime(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='api_token_pkey')
+ )
+ with op.batch_alter_table('api_tokens', schema=None) as batch_op:
+ batch_op.create_index('api_token_app_id_type_idx', ['app_id', 'type'], unique=False)
+ batch_op.create_index('api_token_token_idx', ['token', 'type'], unique=False)
+
+ op.create_table('app_dataset_joins',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='app_dataset_join_pkey')
+ )
+ with op.batch_alter_table('app_dataset_joins', schema=None) as batch_op:
+ batch_op.create_index('app_dataset_join_app_dataset_idx', ['dataset_id', 'app_id'], unique=False)
+
+ op.create_table('app_model_configs',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('provider', sa.String(length=255), nullable=False),
+ sa.Column('model_id', sa.String(length=255), nullable=False),
+ sa.Column('configs', sa.JSON(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('opening_statement', sa.Text(), nullable=True),
+ sa.Column('suggested_questions', sa.Text(), nullable=True),
+ sa.Column('suggested_questions_after_answer', sa.Text(), nullable=True),
+ sa.Column('more_like_this', sa.Text(), nullable=True),
+ sa.Column('model', sa.Text(), nullable=True),
+ sa.Column('user_input_form', sa.Text(), nullable=True),
+ sa.Column('pre_prompt', sa.Text(), nullable=True),
+ sa.Column('agent_mode', sa.Text(), nullable=True),
+ sa.PrimaryKeyConstraint('id', name='app_model_config_pkey')
+ )
+ with op.batch_alter_table('app_model_configs', schema=None) as batch_op:
+ batch_op.create_index('app_app_id_idx', ['app_id'], unique=False)
+
+ op.create_table('apps',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('mode', sa.String(length=255), nullable=False),
+ sa.Column('icon', sa.String(length=255), nullable=True),
+ sa.Column('icon_background', sa.String(length=255), nullable=True),
+ sa.Column('app_model_config_id', postgresql.UUID(), nullable=True),
+ sa.Column('status', sa.String(length=255), server_default=sa.text("'normal'::character varying"), nullable=False),
+ sa.Column('enable_site', sa.Boolean(), nullable=False),
+ sa.Column('enable_api', sa.Boolean(), nullable=False),
+ sa.Column('api_rpm', sa.Integer(), nullable=False),
+ sa.Column('api_rph', sa.Integer(), nullable=False),
+ sa.Column('is_demo', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('is_public', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='app_pkey')
+ )
+ with op.batch_alter_table('apps', schema=None) as batch_op:
+ batch_op.create_index('app_tenant_id_idx', ['tenant_id'], unique=False)
+
+ op.execute('CREATE SEQUENCE task_id_sequence;')
+ op.execute('CREATE SEQUENCE taskset_id_sequence;')
+
+ op.create_table('celery_taskmeta',
+ sa.Column('id', sa.Integer(), nullable=False,
+ server_default=sa.text('nextval(\'task_id_sequence\')')),
+ sa.Column('task_id', sa.String(length=155), nullable=True),
+ sa.Column('status', sa.String(length=50), nullable=True),
+ sa.Column('result', sa.PickleType(), nullable=True),
+ sa.Column('date_done', sa.DateTime(), nullable=True),
+ sa.Column('traceback', sa.Text(), nullable=True),
+ sa.Column('name', sa.String(length=155), nullable=True),
+ sa.Column('args', sa.LargeBinary(), nullable=True),
+ sa.Column('kwargs', sa.LargeBinary(), nullable=True),
+ sa.Column('worker', sa.String(length=155), nullable=True),
+ sa.Column('retries', sa.Integer(), nullable=True),
+ sa.Column('queue', sa.String(length=155), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('task_id')
+ )
+ op.create_table('celery_tasksetmeta',
+ sa.Column('id', sa.Integer(), nullable=False,
+ server_default=sa.text('nextval(\'taskset_id_sequence\')')),
+ sa.Column('taskset_id', sa.String(length=155), nullable=True),
+ sa.Column('result', sa.PickleType(), nullable=True),
+ sa.Column('date_done', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('taskset_id')
+ )
+ op.create_table('conversations',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('app_model_config_id', postgresql.UUID(), nullable=False),
+ sa.Column('model_provider', sa.String(length=255), nullable=False),
+ sa.Column('override_model_configs', sa.Text(), nullable=True),
+ sa.Column('model_id', sa.String(length=255), nullable=False),
+ sa.Column('mode', sa.String(length=255), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('summary', sa.Text(), nullable=True),
+ sa.Column('inputs', sa.JSON(), nullable=True),
+ sa.Column('introduction', sa.Text(), nullable=True),
+ sa.Column('system_instruction', sa.Text(), nullable=True),
+ sa.Column('system_instruction_tokens', sa.Integer(), server_default=sa.text('0'), nullable=False),
+ sa.Column('status', sa.String(length=255), nullable=False),
+ sa.Column('from_source', sa.String(length=255), nullable=False),
+ sa.Column('from_end_user_id', postgresql.UUID(), nullable=True),
+ sa.Column('from_account_id', postgresql.UUID(), nullable=True),
+ sa.Column('read_at', sa.DateTime(), nullable=True),
+ sa.Column('read_account_id', postgresql.UUID(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='conversation_pkey')
+ )
+ with op.batch_alter_table('conversations', schema=None) as batch_op:
+ batch_op.create_index('conversation_app_from_user_idx', ['app_id', 'from_source', 'from_end_user_id'], unique=False)
+
+ op.create_table('dataset_keyword_tables',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('keyword_table', sa.Text(), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='dataset_keyword_table_pkey'),
+ sa.UniqueConstraint('dataset_id')
+ )
+ with op.batch_alter_table('dataset_keyword_tables', schema=None) as batch_op:
+ batch_op.create_index('dataset_keyword_table_dataset_id_idx', ['dataset_id'], unique=False)
+
+ op.create_table('dataset_process_rules',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('mode', sa.String(length=255), server_default=sa.text("'automatic'::character varying"), nullable=False),
+ sa.Column('rules', sa.Text(), nullable=True),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='dataset_process_rule_pkey')
+ )
+ with op.batch_alter_table('dataset_process_rules', schema=None) as batch_op:
+ batch_op.create_index('dataset_process_rule_dataset_id_idx', ['dataset_id'], unique=False)
+
+ op.create_table('dataset_queries',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('content', sa.Text(), nullable=False),
+ sa.Column('source', sa.String(length=255), nullable=False),
+ sa.Column('source_app_id', postgresql.UUID(), nullable=True),
+ sa.Column('created_by_role', sa.String(), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='dataset_query_pkey')
+ )
+ with op.batch_alter_table('dataset_queries', schema=None) as batch_op:
+ batch_op.create_index('dataset_query_dataset_id_idx', ['dataset_id'], unique=False)
+
+ op.create_table('datasets',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('description', sa.Text(), nullable=True),
+ sa.Column('provider', sa.String(length=255), server_default=sa.text("'vendor'::character varying"), nullable=False),
+ sa.Column('permission', sa.String(length=255), server_default=sa.text("'only_me'::character varying"), nullable=False),
+ sa.Column('data_source_type', sa.String(length=255), nullable=True),
+ sa.Column('indexing_technique', sa.String(length=255), nullable=True),
+ sa.Column('index_struct', sa.Text(), nullable=True),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_by', postgresql.UUID(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='dataset_pkey')
+ )
+ with op.batch_alter_table('datasets', schema=None) as batch_op:
+ batch_op.create_index('dataset_tenant_idx', ['tenant_id'], unique=False)
+
+ op.create_table('dify_setups',
+ sa.Column('version', sa.String(length=255), nullable=False),
+ sa.Column('setup_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('version', name='dify_setup_pkey')
+ )
+ op.create_table('document_segments',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('document_id', postgresql.UUID(), nullable=False),
+ sa.Column('position', sa.Integer(), nullable=False),
+ sa.Column('content', sa.Text(), nullable=False),
+ sa.Column('word_count', sa.Integer(), nullable=False),
+ sa.Column('tokens', sa.Integer(), nullable=False),
+ sa.Column('keywords', sa.JSON(), nullable=True),
+ sa.Column('index_node_id', sa.String(length=255), nullable=True),
+ sa.Column('index_node_hash', sa.String(length=255), nullable=True),
+ sa.Column('hit_count', sa.Integer(), nullable=False),
+ sa.Column('enabled', sa.Boolean(), server_default=sa.text('true'), nullable=False),
+ sa.Column('disabled_at', sa.DateTime(), nullable=True),
+ sa.Column('disabled_by', postgresql.UUID(), nullable=True),
+ sa.Column('status', sa.String(length=255), server_default=sa.text("'waiting'::character varying"), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('indexing_at', sa.DateTime(), nullable=True),
+ sa.Column('completed_at', sa.DateTime(), nullable=True),
+ sa.Column('error', sa.Text(), nullable=True),
+ sa.Column('stopped_at', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id', name='document_segment_pkey')
+ )
+ with op.batch_alter_table('document_segments', schema=None) as batch_op:
+ batch_op.create_index('document_segment_dataset_id_idx', ['dataset_id'], unique=False)
+ batch_op.create_index('document_segment_dataset_node_idx', ['dataset_id', 'index_node_id'], unique=False)
+ batch_op.create_index('document_segment_document_id_idx', ['document_id'], unique=False)
+ batch_op.create_index('document_segment_tenant_dataset_idx', ['dataset_id', 'tenant_id'], unique=False)
+ batch_op.create_index('document_segment_tenant_document_idx', ['document_id', 'tenant_id'], unique=False)
+
+ op.create_table('documents',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('dataset_id', postgresql.UUID(), nullable=False),
+ sa.Column('position', sa.Integer(), nullable=False),
+ sa.Column('data_source_type', sa.String(length=255), nullable=False),
+ sa.Column('data_source_info', sa.Text(), nullable=True),
+ sa.Column('dataset_process_rule_id', postgresql.UUID(), nullable=True),
+ sa.Column('batch', sa.String(length=255), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('created_from', sa.String(length=255), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_api_request_id', postgresql.UUID(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('processing_started_at', sa.DateTime(), nullable=True),
+ sa.Column('file_id', sa.Text(), nullable=True),
+ sa.Column('word_count', sa.Integer(), nullable=True),
+ sa.Column('parsing_completed_at', sa.DateTime(), nullable=True),
+ sa.Column('cleaning_completed_at', sa.DateTime(), nullable=True),
+ sa.Column('splitting_completed_at', sa.DateTime(), nullable=True),
+ sa.Column('tokens', sa.Integer(), nullable=True),
+ sa.Column('indexing_latency', sa.Float(), nullable=True),
+ sa.Column('completed_at', sa.DateTime(), nullable=True),
+ sa.Column('is_paused', sa.Boolean(), server_default=sa.text('false'), nullable=True),
+ sa.Column('paused_by', postgresql.UUID(), nullable=True),
+ sa.Column('paused_at', sa.DateTime(), nullable=True),
+ sa.Column('error', sa.Text(), nullable=True),
+ sa.Column('stopped_at', sa.DateTime(), nullable=True),
+ sa.Column('indexing_status', sa.String(length=255), server_default=sa.text("'waiting'::character varying"), nullable=False),
+ sa.Column('enabled', sa.Boolean(), server_default=sa.text('true'), nullable=False),
+ sa.Column('disabled_at', sa.DateTime(), nullable=True),
+ sa.Column('disabled_by', postgresql.UUID(), nullable=True),
+ sa.Column('archived', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('archived_reason', sa.String(length=255), nullable=True),
+ sa.Column('archived_by', postgresql.UUID(), nullable=True),
+ sa.Column('archived_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('doc_type', sa.String(length=40), nullable=True),
+ sa.Column('doc_metadata', sa.JSON(), nullable=True),
+ sa.PrimaryKeyConstraint('id', name='document_pkey')
+ )
+ with op.batch_alter_table('documents', schema=None) as batch_op:
+ batch_op.create_index('document_dataset_id_idx', ['dataset_id'], unique=False)
+ batch_op.create_index('document_is_paused_idx', ['is_paused'], unique=False)
+
+ op.create_table('embeddings',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('hash', sa.String(length=64), nullable=False),
+ sa.Column('embedding', sa.LargeBinary(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='embedding_pkey'),
+ sa.UniqueConstraint('hash', name='embedding_hash_idx')
+ )
+ op.create_table('end_users',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=True),
+ sa.Column('type', sa.String(length=255), nullable=False),
+ sa.Column('external_user_id', sa.String(length=255), nullable=True),
+ sa.Column('name', sa.String(length=255), nullable=True),
+ sa.Column('is_anonymous', sa.Boolean(), server_default=sa.text('true'), nullable=False),
+ sa.Column('session_id', sa.String(length=255), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='end_user_pkey')
+ )
+ with op.batch_alter_table('end_users', schema=None) as batch_op:
+ batch_op.create_index('end_user_session_id_idx', ['session_id', 'type'], unique=False)
+ batch_op.create_index('end_user_tenant_session_id_idx', ['tenant_id', 'session_id', 'type'], unique=False)
+
+ op.create_table('installed_apps',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('app_owner_tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('position', sa.Integer(), nullable=False),
+ sa.Column('is_pinned', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('last_used_at', sa.DateTime(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='installed_app_pkey'),
+ sa.UniqueConstraint('tenant_id', 'app_id', name='unique_tenant_app')
+ )
+ with op.batch_alter_table('installed_apps', schema=None) as batch_op:
+ batch_op.create_index('installed_app_app_id_idx', ['app_id'], unique=False)
+ batch_op.create_index('installed_app_tenant_id_idx', ['tenant_id'], unique=False)
+
+ op.create_table('invitation_codes',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('batch', sa.String(length=255), nullable=False),
+ sa.Column('code', sa.String(length=32), nullable=False),
+ sa.Column('status', sa.String(length=16), server_default=sa.text("'unused'::character varying"), nullable=False),
+ sa.Column('used_at', sa.DateTime(), nullable=True),
+ sa.Column('used_by_tenant_id', postgresql.UUID(), nullable=True),
+ sa.Column('used_by_account_id', postgresql.UUID(), nullable=True),
+ sa.Column('deprecated_at', sa.DateTime(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='invitation_code_pkey')
+ )
+ with op.batch_alter_table('invitation_codes', schema=None) as batch_op:
+ batch_op.create_index('invitation_codes_batch_idx', ['batch'], unique=False)
+ batch_op.create_index('invitation_codes_code_idx', ['code', 'status'], unique=False)
+
+ op.create_table('message_agent_thoughts',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('message_id', postgresql.UUID(), nullable=False),
+ sa.Column('message_chain_id', postgresql.UUID(), nullable=False),
+ sa.Column('position', sa.Integer(), nullable=False),
+ sa.Column('thought', sa.Text(), nullable=True),
+ sa.Column('tool', sa.Text(), nullable=True),
+ sa.Column('tool_input', sa.Text(), nullable=True),
+ sa.Column('observation', sa.Text(), nullable=True),
+ sa.Column('tool_process_data', sa.Text(), nullable=True),
+ sa.Column('message', sa.Text(), nullable=True),
+ sa.Column('message_token', sa.Integer(), nullable=True),
+ sa.Column('message_unit_price', sa.Numeric(), nullable=True),
+ sa.Column('answer', sa.Text(), nullable=True),
+ sa.Column('answer_token', sa.Integer(), nullable=True),
+ sa.Column('answer_unit_price', sa.Numeric(), nullable=True),
+ sa.Column('tokens', sa.Integer(), nullable=True),
+ sa.Column('total_price', sa.Numeric(), nullable=True),
+ sa.Column('currency', sa.String(), nullable=True),
+ sa.Column('latency', sa.Float(), nullable=True),
+ sa.Column('created_by_role', sa.String(), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='message_agent_thought_pkey')
+ )
+ with op.batch_alter_table('message_agent_thoughts', schema=None) as batch_op:
+ batch_op.create_index('message_agent_thought_message_chain_id_idx', ['message_chain_id'], unique=False)
+ batch_op.create_index('message_agent_thought_message_id_idx', ['message_id'], unique=False)
+
+ op.create_table('message_chains',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('message_id', postgresql.UUID(), nullable=False),
+ sa.Column('type', sa.String(length=255), nullable=False),
+ sa.Column('input', sa.Text(), nullable=True),
+ sa.Column('output', sa.Text(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='message_chain_pkey')
+ )
+ with op.batch_alter_table('message_chains', schema=None) as batch_op:
+ batch_op.create_index('message_chain_message_id_idx', ['message_id'], unique=False)
+
+ op.create_table('message_feedbacks',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('conversation_id', postgresql.UUID(), nullable=False),
+ sa.Column('message_id', postgresql.UUID(), nullable=False),
+ sa.Column('rating', sa.String(length=255), nullable=False),
+ sa.Column('content', sa.Text(), nullable=True),
+ sa.Column('from_source', sa.String(length=255), nullable=False),
+ sa.Column('from_end_user_id', postgresql.UUID(), nullable=True),
+ sa.Column('from_account_id', postgresql.UUID(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='message_feedback_pkey')
+ )
+ with op.batch_alter_table('message_feedbacks', schema=None) as batch_op:
+ batch_op.create_index('message_feedback_app_idx', ['app_id'], unique=False)
+ batch_op.create_index('message_feedback_conversation_idx', ['conversation_id', 'from_source', 'rating'], unique=False)
+ batch_op.create_index('message_feedback_message_idx', ['message_id', 'from_source'], unique=False)
+
+ op.create_table('operation_logs',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('account_id', postgresql.UUID(), nullable=False),
+ sa.Column('action', sa.String(length=255), nullable=False),
+ sa.Column('content', sa.JSON(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('created_ip', sa.String(length=255), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='operation_log_pkey')
+ )
+ with op.batch_alter_table('operation_logs', schema=None) as batch_op:
+ batch_op.create_index('operation_log_account_action_idx', ['tenant_id', 'account_id', 'action'], unique=False)
+
+ op.create_table('pinned_conversations',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('conversation_id', postgresql.UUID(), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='pinned_conversation_pkey')
+ )
+ with op.batch_alter_table('pinned_conversations', schema=None) as batch_op:
+ batch_op.create_index('pinned_conversation_conversation_idx', ['app_id', 'conversation_id', 'created_by'], unique=False)
+
+ op.create_table('providers',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('provider_name', sa.String(length=40), nullable=False),
+ sa.Column('provider_type', sa.String(length=40), nullable=False, server_default=sa.text("'custom'::character varying")),
+ sa.Column('encrypted_config', sa.Text(), nullable=True),
+ sa.Column('is_valid', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('last_used', sa.DateTime(), nullable=True),
+ sa.Column('quota_type', sa.String(length=40), nullable=True, server_default=sa.text("''::character varying")),
+ sa.Column('quota_limit', sa.Integer(), nullable=True),
+ sa.Column('quota_used', sa.Integer(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='provider_pkey'),
+ sa.UniqueConstraint('tenant_id', 'provider_name', 'provider_type', 'quota_type', name='unique_provider_name_type_quota')
+ )
+ with op.batch_alter_table('providers', schema=None) as batch_op:
+ batch_op.create_index('provider_tenant_id_provider_idx', ['tenant_id', 'provider_name'], unique=False)
+
+ op.create_table('recommended_apps',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('description', sa.JSON(), nullable=False),
+ sa.Column('copyright', sa.String(length=255), nullable=False),
+ sa.Column('privacy_policy', sa.String(length=255), nullable=False),
+ sa.Column('category', sa.String(length=255), nullable=False),
+ sa.Column('position', sa.Integer(), nullable=False),
+ sa.Column('is_listed', sa.Boolean(), nullable=False),
+ sa.Column('install_count', sa.Integer(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='recommended_app_pkey')
+ )
+ with op.batch_alter_table('recommended_apps', schema=None) as batch_op:
+ batch_op.create_index('recommended_app_app_id_idx', ['app_id'], unique=False)
+ batch_op.create_index('recommended_app_is_listed_idx', ['is_listed'], unique=False)
+
+ op.create_table('saved_messages',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('message_id', postgresql.UUID(), nullable=False),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='saved_message_pkey')
+ )
+ with op.batch_alter_table('saved_messages', schema=None) as batch_op:
+ batch_op.create_index('saved_message_message_idx', ['app_id', 'message_id', 'created_by'], unique=False)
+
+ op.create_table('sessions',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('session_id', sa.String(length=255), nullable=True),
+ sa.Column('data', sa.LargeBinary(), nullable=True),
+ sa.Column('expiry', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('session_id')
+ )
+ op.create_table('sites',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('title', sa.String(length=255), nullable=False),
+ sa.Column('icon', sa.String(length=255), nullable=True),
+ sa.Column('icon_background', sa.String(length=255), nullable=True),
+ sa.Column('description', sa.String(length=255), nullable=True),
+ sa.Column('default_language', sa.String(length=255), nullable=False),
+ sa.Column('copyright', sa.String(length=255), nullable=True),
+ sa.Column('privacy_policy', sa.String(length=255), nullable=True),
+ sa.Column('customize_domain', sa.String(length=255), nullable=True),
+ sa.Column('customize_token_strategy', sa.String(length=255), nullable=False),
+ sa.Column('prompt_public', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('status', sa.String(length=255), server_default=sa.text("'normal'::character varying"), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('code', sa.String(length=255), nullable=True),
+ sa.PrimaryKeyConstraint('id', name='site_pkey')
+ )
+ with op.batch_alter_table('sites', schema=None) as batch_op:
+ batch_op.create_index('site_app_id_idx', ['app_id'], unique=False)
+ batch_op.create_index('site_code_idx', ['code', 'status'], unique=False)
+
+ op.create_table('tenant_account_joins',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('account_id', postgresql.UUID(), nullable=False),
+ sa.Column('role', sa.String(length=16), server_default='normal', nullable=False),
+ sa.Column('invited_by', postgresql.UUID(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='tenant_account_join_pkey'),
+ sa.UniqueConstraint('tenant_id', 'account_id', name='unique_tenant_account_join')
+ )
+ with op.batch_alter_table('tenant_account_joins', schema=None) as batch_op:
+ batch_op.create_index('tenant_account_join_account_id_idx', ['account_id'], unique=False)
+ batch_op.create_index('tenant_account_join_tenant_id_idx', ['tenant_id'], unique=False)
+
+ op.create_table('tenants',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('encrypt_public_key', sa.Text(), nullable=True),
+ sa.Column('plan', sa.String(length=255), server_default=sa.text("'basic'::character varying"), nullable=False),
+ sa.Column('status', sa.String(length=255), server_default=sa.text("'normal'::character varying"), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='tenant_pkey')
+ )
+ op.create_table('upload_files',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('tenant_id', postgresql.UUID(), nullable=False),
+ sa.Column('storage_type', sa.String(length=255), nullable=False),
+ sa.Column('key', sa.String(length=255), nullable=False),
+ sa.Column('name', sa.String(length=255), nullable=False),
+ sa.Column('size', sa.Integer(), nullable=False),
+ sa.Column('extension', sa.String(length=255), nullable=False),
+ sa.Column('mime_type', sa.String(length=255), nullable=True),
+ sa.Column('created_by', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('used', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.Column('used_by', postgresql.UUID(), nullable=True),
+ sa.Column('used_at', sa.DateTime(), nullable=True),
+ sa.Column('hash', sa.String(length=255), nullable=True),
+ sa.PrimaryKeyConstraint('id', name='upload_file_pkey')
+ )
+ with op.batch_alter_table('upload_files', schema=None) as batch_op:
+ batch_op.create_index('upload_file_tenant_idx', ['tenant_id'], unique=False)
+
+ op.create_table('message_annotations',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('conversation_id', postgresql.UUID(), nullable=False),
+ sa.Column('message_id', postgresql.UUID(), nullable=False),
+ sa.Column('content', sa.Text(), nullable=False),
+ sa.Column('account_id', postgresql.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='message_annotation_pkey')
+ )
+ with op.batch_alter_table('message_annotations', schema=None) as batch_op:
+ batch_op.create_index('message_annotation_app_idx', ['app_id'], unique=False)
+ batch_op.create_index('message_annotation_conversation_idx', ['conversation_id'], unique=False)
+ batch_op.create_index('message_annotation_message_idx', ['message_id'], unique=False)
+
+ op.create_table('messages',
+ sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
+ sa.Column('app_id', postgresql.UUID(), nullable=False),
+ sa.Column('model_provider', sa.String(length=255), nullable=False),
+ sa.Column('model_id', sa.String(length=255), nullable=False),
+ sa.Column('override_model_configs', sa.Text(), nullable=True),
+ sa.Column('conversation_id', postgresql.UUID(), nullable=False),
+ sa.Column('inputs', sa.JSON(), nullable=True),
+ sa.Column('query', sa.Text(), nullable=False),
+ sa.Column('message', sa.JSON(), nullable=False),
+ sa.Column('message_tokens', sa.Integer(), server_default=sa.text('0'), nullable=False),
+ sa.Column('message_unit_price', sa.Numeric(precision=10, scale=4), nullable=False),
+ sa.Column('answer', sa.Text(), nullable=False),
+ sa.Column('answer_tokens', sa.Integer(), server_default=sa.text('0'), nullable=False),
+ sa.Column('answer_unit_price', sa.Numeric(precision=10, scale=4), nullable=False),
+ sa.Column('provider_response_latency', sa.Float(), server_default=sa.text('0'), nullable=False),
+ sa.Column('total_price', sa.Numeric(precision=10, scale=7), nullable=True),
+ sa.Column('currency', sa.String(length=255), nullable=False),
+ sa.Column('from_source', sa.String(length=255), nullable=False),
+ sa.Column('from_end_user_id', postgresql.UUID(), nullable=True),
+ sa.Column('from_account_id', postgresql.UUID(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
+ sa.Column('agent_based', sa.Boolean(), server_default=sa.text('false'), nullable=False),
+ sa.PrimaryKeyConstraint('id', name='message_pkey')
+ )
+ with op.batch_alter_table('messages', schema=None) as batch_op:
+ batch_op.create_index('message_account_idx', ['app_id', 'from_source', 'from_account_id'], unique=False)
+ batch_op.create_index('message_app_id_idx', ['app_id', 'created_at'], unique=False)
+ batch_op.create_index('message_conversation_id_idx', ['conversation_id'], unique=False)
+ batch_op.create_index('message_end_user_idx', ['app_id', 'from_source', 'from_end_user_id'], unique=False)
+
+ # ### end Alembic commands ###
+
+
+def downgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ with op.batch_alter_table('messages', schema=None) as batch_op:
+ batch_op.drop_index('message_end_user_idx')
+ batch_op.drop_index('message_conversation_id_idx')
+ batch_op.drop_index('message_app_id_idx')
+ batch_op.drop_index('message_account_idx')
+
+ op.drop_table('messages')
+ with op.batch_alter_table('message_annotations', schema=None) as batch_op:
+ batch_op.drop_index('message_annotation_message_idx')
+ batch_op.drop_index('message_annotation_conversation_idx')
+ batch_op.drop_index('message_annotation_app_idx')
+
+ op.drop_table('message_annotations')
+ with op.batch_alter_table('upload_files', schema=None) as batch_op:
+ batch_op.drop_index('upload_file_tenant_idx')
+
+ op.drop_table('upload_files')
+ op.drop_table('tenants')
+ with op.batch_alter_table('tenant_account_joins', schema=None) as batch_op:
+ batch_op.drop_index('tenant_account_join_tenant_id_idx')
+ batch_op.drop_index('tenant_account_join_account_id_idx')
+
+ op.drop_table('tenant_account_joins')
+ with op.batch_alter_table('sites', schema=None) as batch_op:
+ batch_op.drop_index('site_code_idx')
+ batch_op.drop_index('site_app_id_idx')
+
+ op.drop_table('sites')
+ op.drop_table('sessions')
+ with op.batch_alter_table('saved_messages', schema=None) as batch_op:
+ batch_op.drop_index('saved_message_message_idx')
+
+ op.drop_table('saved_messages')
+ with op.batch_alter_table('recommended_apps', schema=None) as batch_op:
+ batch_op.drop_index('recommended_app_is_listed_idx')
+ batch_op.drop_index('recommended_app_app_id_idx')
+
+ op.drop_table('recommended_apps')
+ with op.batch_alter_table('providers', schema=None) as batch_op:
+ batch_op.drop_index('provider_tenant_id_provider_idx')
+
+ op.drop_table('providers')
+ with op.batch_alter_table('pinned_conversations', schema=None) as batch_op:
+ batch_op.drop_index('pinned_conversation_conversation_idx')
+
+ op.drop_table('pinned_conversations')
+ with op.batch_alter_table('operation_logs', schema=None) as batch_op:
+ batch_op.drop_index('operation_log_account_action_idx')
+
+ op.drop_table('operation_logs')
+ with op.batch_alter_table('message_feedbacks', schema=None) as batch_op:
+ batch_op.drop_index('message_feedback_message_idx')
+ batch_op.drop_index('message_feedback_conversation_idx')
+ batch_op.drop_index('message_feedback_app_idx')
+
+ op.drop_table('message_feedbacks')
+ with op.batch_alter_table('message_chains', schema=None) as batch_op:
+ batch_op.drop_index('message_chain_message_id_idx')
+
+ op.drop_table('message_chains')
+ with op.batch_alter_table('message_agent_thoughts', schema=None) as batch_op:
+ batch_op.drop_index('message_agent_thought_message_id_idx')
+ batch_op.drop_index('message_agent_thought_message_chain_id_idx')
+
+ op.drop_table('message_agent_thoughts')
+ with op.batch_alter_table('invitation_codes', schema=None) as batch_op:
+ batch_op.drop_index('invitation_codes_code_idx')
+ batch_op.drop_index('invitation_codes_batch_idx')
+
+ op.drop_table('invitation_codes')
+ with op.batch_alter_table('installed_apps', schema=None) as batch_op:
+ batch_op.drop_index('installed_app_tenant_id_idx')
+ batch_op.drop_index('installed_app_app_id_idx')
+
+ op.drop_table('installed_apps')
+ with op.batch_alter_table('end_users', schema=None) as batch_op:
+ batch_op.drop_index('end_user_tenant_session_id_idx')
+ batch_op.drop_index('end_user_session_id_idx')
+
+ op.drop_table('end_users')
+ op.drop_table('embeddings')
+ with op.batch_alter_table('documents', schema=None) as batch_op:
+ batch_op.drop_index('document_is_paused_idx')
+ batch_op.drop_index('document_dataset_id_idx')
+
+ op.drop_table('documents')
+ with op.batch_alter_table('document_segments', schema=None) as batch_op:
+ batch_op.drop_index('document_segment_tenant_document_idx')
+ batch_op.drop_index('document_segment_tenant_dataset_idx')
+ batch_op.drop_index('document_segment_document_id_idx')
+ batch_op.drop_index('document_segment_dataset_node_idx')
+ batch_op.drop_index('document_segment_dataset_id_idx')
+
+ op.drop_table('document_segments')
+ op.drop_table('dify_setups')
+ with op.batch_alter_table('datasets', schema=None) as batch_op:
+ batch_op.drop_index('dataset_tenant_idx')
+
+ op.drop_table('datasets')
+ with op.batch_alter_table('dataset_queries', schema=None) as batch_op:
+ batch_op.drop_index('dataset_query_dataset_id_idx')
+
+ op.drop_table('dataset_queries')
+ with op.batch_alter_table('dataset_process_rules', schema=None) as batch_op:
+ batch_op.drop_index('dataset_process_rule_dataset_id_idx')
+
+ op.drop_table('dataset_process_rules')
+ with op.batch_alter_table('dataset_keyword_tables', schema=None) as batch_op:
+ batch_op.drop_index('dataset_keyword_table_dataset_id_idx')
+
+ op.drop_table('dataset_keyword_tables')
+ with op.batch_alter_table('conversations', schema=None) as batch_op:
+ batch_op.drop_index('conversation_app_from_user_idx')
+
+ op.drop_table('conversations')
+ op.drop_table('celery_tasksetmeta')
+ op.drop_table('celery_taskmeta')
+
+ op.execute('DROP SEQUENCE taskset_id_sequence;')
+ op.execute('DROP SEQUENCE task_id_sequence;')
+ with op.batch_alter_table('apps', schema=None) as batch_op:
+ batch_op.drop_index('app_tenant_id_idx')
+
+ op.drop_table('apps')
+ with op.batch_alter_table('app_model_configs', schema=None) as batch_op:
+ batch_op.drop_index('app_app_id_idx')
+
+ op.drop_table('app_model_configs')
+ with op.batch_alter_table('app_dataset_joins', schema=None) as batch_op:
+ batch_op.drop_index('app_dataset_join_app_dataset_idx')
+
+ op.drop_table('app_dataset_joins')
+ with op.batch_alter_table('api_tokens', schema=None) as batch_op:
+ batch_op.drop_index('api_token_token_idx')
+ batch_op.drop_index('api_token_app_id_type_idx')
+
+ op.drop_table('api_tokens')
+ with op.batch_alter_table('api_requests', schema=None) as batch_op:
+ batch_op.drop_index('api_request_token_idx')
+
+ op.drop_table('api_requests')
+ with op.batch_alter_table('accounts', schema=None) as batch_op:
+ batch_op.drop_index('account_email_idx')
+
+ op.drop_table('accounts')
+ op.drop_table('account_integrates')
+ # ### end Alembic commands ###
diff --git a/api/models/__init__.py b/api/models/__init__.py
new file mode 100644
index 00000000000..44d37d3052e
--- /dev/null
+++ b/api/models/__init__.py
@@ -0,0 +1 @@
+# -*- coding:utf-8 -*-
\ No newline at end of file
diff --git a/api/models/account.py b/api/models/account.py
new file mode 100644
index 00000000000..de2d3bd71fe
--- /dev/null
+++ b/api/models/account.py
@@ -0,0 +1,180 @@
+import enum
+from typing import List
+
+from flask_login import UserMixin
+from extensions.ext_database import db
+from sqlalchemy.dialects.postgresql import UUID
+
+
+class AccountStatus(str, enum.Enum):
+ PENDING = 'pending'
+ UNINITIALIZED = 'uninitialized'
+ ACTIVE = 'active'
+ BANNED = 'banned'
+ CLOSED = 'closed'
+
+
+class Account(UserMixin, db.Model):
+ __tablename__ = 'accounts'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='account_pkey'),
+ db.Index('account_email_idx', 'email')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ name = db.Column(db.String(255), nullable=False)
+ email = db.Column(db.String(255), nullable=False)
+ password = db.Column(db.String(255), nullable=True)
+ password_salt = db.Column(db.String(255), nullable=True)
+ avatar = db.Column(db.String(255))
+ interface_language = db.Column(db.String(255))
+ interface_theme = db.Column(db.String(255))
+ timezone = db.Column(db.String(255))
+ last_login_at = db.Column(db.DateTime)
+ last_login_ip = db.Column(db.String(255))
+ status = db.Column(db.String(16), nullable=False, server_default=db.text("'active'::character varying"))
+ initialized_at = db.Column(db.DateTime)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ _current_tenant: db.Model = None
+
+ @property
+ def current_tenant(self):
+ return self._current_tenant
+
+ @current_tenant.setter
+ def current_tenant(self, value):
+ tenant = value
+ ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=self.id).first()
+ if ta:
+ tenant.current_role = ta.role
+ else:
+ tenant = None
+ self._current_tenant = tenant
+
+ @property
+ def current_tenant_id(self):
+ return self._current_tenant.id
+
+ @current_tenant_id.setter
+ def current_tenant_id(self, value):
+ try:
+ tenant_account_join = db.session.query(Tenant, TenantAccountJoin) \
+ .filter(Tenant.id == value) \
+ .filter(TenantAccountJoin.tenant_id == Tenant.id) \
+ .filter(TenantAccountJoin.account_id == self.id) \
+ .one_or_none()
+
+ if tenant_account_join:
+ tenant, ta = tenant_account_join
+ tenant.current_role = ta.role
+ else:
+ tenant = None
+ except:
+ tenant = None
+
+ self._current_tenant = tenant
+
+ def get_status(self) -> AccountStatus:
+ status_str = self.status
+ return AccountStatus(status_str)
+
+ @classmethod
+ def get_by_openid(cls, provider: str, open_id: str) -> db.Model:
+ account_integrate = db.session.query(AccountIntegrate). \
+ filter(AccountIntegrate.provider == provider, AccountIntegrate.open_id == open_id). \
+ one_or_none()
+ if account_integrate:
+ return db.session.query(Account). \
+ filter(Account.id == account_integrate.account_id). \
+ one_or_none()
+ return None
+
+ def get_integrates(self) -> List[db.Model]:
+ ai = db.Model
+ return db.session.query(ai).filter(
+ ai.account_id == self.id
+ ).all()
+
+
+class Tenant(db.Model):
+ __tablename__ = 'tenants'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='tenant_pkey'),
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ name = db.Column(db.String(255), nullable=False)
+ encrypt_public_key = db.Column(db.Text)
+ plan = db.Column(db.String(255), nullable=False, server_default=db.text("'basic'::character varying"))
+ status = db.Column(db.String(255), nullable=False, server_default=db.text("'normal'::character varying"))
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ def get_accounts(self) -> List[db.Model]:
+ Account = db.Model
+ return db.session.query(Account).filter(
+ Account.id == TenantAccountJoin.account_id,
+ TenantAccountJoin.tenant_id == self.id
+ ).all()
+
+
+class TenantAccountJoinRole(enum.Enum):
+ OWNER = 'owner'
+ ADMIN = 'admin'
+ NORMAL = 'normal'
+
+
+class TenantAccountJoin(db.Model):
+ __tablename__ = 'tenant_account_joins'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='tenant_account_join_pkey'),
+ db.Index('tenant_account_join_account_id_idx', 'account_id'),
+ db.Index('tenant_account_join_tenant_id_idx', 'tenant_id'),
+ db.UniqueConstraint('tenant_id', 'account_id', name='unique_tenant_account_join')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ account_id = db.Column(UUID, nullable=False)
+ role = db.Column(db.String(16), nullable=False, server_default='normal')
+ invited_by = db.Column(UUID, nullable=True)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class AccountIntegrate(db.Model):
+ __tablename__ = 'account_integrates'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='account_integrate_pkey'),
+ db.UniqueConstraint('account_id', 'provider', name='unique_account_provider'),
+ db.UniqueConstraint('provider', 'open_id', name='unique_provider_open_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ account_id = db.Column(UUID, nullable=False)
+ provider = db.Column(db.String(16), nullable=False)
+ open_id = db.Column(db.String(255), nullable=False)
+ encrypted_token = db.Column(db.String(255), nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class InvitationCode(db.Model):
+ __tablename__ = 'invitation_codes'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='invitation_code_pkey'),
+ db.Index('invitation_codes_batch_idx', 'batch'),
+ db.Index('invitation_codes_code_idx', 'code', 'status')
+ )
+
+ id = db.Column(db.Integer, nullable=False)
+ batch = db.Column(db.String(255), nullable=False)
+ code = db.Column(db.String(32), nullable=False)
+ status = db.Column(db.String(16), nullable=False, server_default=db.text("'unused'::character varying"))
+ used_at = db.Column(db.DateTime)
+ used_by_tenant_id = db.Column(UUID)
+ used_by_account_id = db.Column(UUID)
+ deprecated_at = db.Column(db.DateTime)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
diff --git a/api/models/dataset.py b/api/models/dataset.py
new file mode 100644
index 00000000000..29588c1f387
--- /dev/null
+++ b/api/models/dataset.py
@@ -0,0 +1,415 @@
+import json
+import pickle
+from json import JSONDecodeError
+
+from sqlalchemy import func
+from sqlalchemy.dialects.postgresql import UUID
+
+from extensions.ext_database import db
+from models.account import Account
+from models.model import App, UploadFile
+
+class Dataset(db.Model):
+ __tablename__ = 'datasets'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='dataset_pkey'),
+ db.Index('dataset_tenant_idx', 'tenant_id'),
+ )
+
+ INDEXING_TECHNIQUE_LIST = ['high_quality', 'economy']
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ name = db.Column(db.String(255), nullable=False)
+ description = db.Column(db.Text, nullable=True)
+ provider = db.Column(db.String(255), nullable=False,
+ server_default=db.text("'vendor'::character varying"))
+ permission = db.Column(db.String(255), nullable=False,
+ server_default=db.text("'only_me'::character varying"))
+ data_source_type = db.Column(db.String(255))
+ indexing_technique = db.Column(db.String(255), nullable=True)
+ index_struct = db.Column(db.Text, nullable=True)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_by = db.Column(UUID, nullable=True)
+ updated_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def dataset_keyword_table(self):
+ dataset_keyword_table = db.session.query(DatasetKeywordTable).filter(
+ DatasetKeywordTable.dataset_id == self.id).first()
+ if dataset_keyword_table:
+ return dataset_keyword_table
+
+ return None
+
+ @property
+ def index_struct_dict(self):
+ return json.loads(self.index_struct) if self.index_struct else None
+
+ @property
+ def created_by_account(self):
+ return Account.query.get(self.created_by)
+
+ @property
+ def latest_process_rule(self):
+ return DatasetProcessRule.query.filter(DatasetProcessRule.dataset_id == self.id) \
+ .order_by(DatasetProcessRule.created_at.desc()).first()
+
+ @property
+ def app_count(self):
+ return db.session.query(func.count(AppDatasetJoin.id)).filter(AppDatasetJoin.dataset_id == self.id).scalar()
+
+ @property
+ def document_count(self):
+ return db.session.query(func.count(Document.id)).filter(Document.dataset_id == self.id).scalar()
+
+ @property
+ def word_count(self):
+ return Document.query.with_entities(func.coalesce(func.sum(Document.word_count))) \
+ .filter(Document.dataset_id == self.id).scalar()
+
+
+class DatasetProcessRule(db.Model):
+ __tablename__ = 'dataset_process_rules'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='dataset_process_rule_pkey'),
+ db.Index('dataset_process_rule_dataset_id_idx', 'dataset_id'),
+ )
+
+ id = db.Column(UUID, nullable=False,
+ server_default=db.text('uuid_generate_v4()'))
+ dataset_id = db.Column(UUID, nullable=False)
+ mode = db.Column(db.String(255), nullable=False,
+ server_default=db.text("'automatic'::character varying"))
+ rules = db.Column(db.Text, nullable=True)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ MODES = ['automatic', 'custom']
+ PRE_PROCESSING_RULES = ['remove_stopwords', 'remove_extra_spaces', 'remove_urls_emails']
+ AUTOMATIC_RULES = {
+ 'pre_processing_rules': [
+ {'id': 'remove_extra_spaces', 'enabled': True},
+ {'id': 'remove_urls_emails', 'enabled': False}
+ ],
+ 'segmentation': {
+ 'delimiter': '\n',
+ 'max_tokens': 1000
+ }
+ }
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'dataset_id': self.dataset_id,
+ 'mode': self.mode,
+ 'rules': self.rules_dict,
+ 'created_by': self.created_by,
+ 'created_at': self.created_at,
+ }
+
+ @property
+ def rules_dict(self):
+ try:
+ return json.loads(self.rules) if self.rules else None
+ except JSONDecodeError:
+ return None
+
+
+class Document(db.Model):
+ __tablename__ = 'documents'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='document_pkey'),
+ db.Index('document_dataset_id_idx', 'dataset_id'),
+ db.Index('document_is_paused_idx', 'is_paused'),
+ )
+
+ # initial fields
+ id = db.Column(UUID, nullable=False,
+ server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ dataset_id = db.Column(UUID, nullable=False)
+ position = db.Column(db.Integer, nullable=False)
+ data_source_type = db.Column(db.String(255), nullable=False)
+ data_source_info = db.Column(db.Text, nullable=True)
+ dataset_process_rule_id = db.Column(UUID, nullable=True)
+ batch = db.Column(db.String(255), nullable=False)
+ name = db.Column(db.String(255), nullable=False)
+ created_from = db.Column(db.String(255), nullable=False)
+ created_by = db.Column(UUID, nullable=False)
+ created_api_request_id = db.Column(UUID, nullable=True)
+ created_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ # start processing
+ processing_started_at = db.Column(db.DateTime, nullable=True)
+
+ # parsing
+ file_id = db.Column(db.Text, nullable=True)
+ word_count = db.Column(db.Integer, nullable=True)
+ parsing_completed_at = db.Column(db.DateTime, nullable=True)
+
+ # cleaning
+ cleaning_completed_at = db.Column(db.DateTime, nullable=True)
+
+ # split
+ splitting_completed_at = db.Column(db.DateTime, nullable=True)
+
+ # indexing
+ tokens = db.Column(db.Integer, nullable=True)
+ indexing_latency = db.Column(db.Float, nullable=True)
+ completed_at = db.Column(db.DateTime, nullable=True)
+
+ # pause
+ is_paused = db.Column(db.Boolean, nullable=True, server_default=db.text('false'))
+ paused_by = db.Column(UUID, nullable=True)
+ paused_at = db.Column(db.DateTime, nullable=True)
+
+ # error
+ error = db.Column(db.Text, nullable=True)
+ stopped_at = db.Column(db.DateTime, nullable=True)
+
+ # basic fields
+ indexing_status = db.Column(db.String(
+ 255), nullable=False, server_default=db.text("'waiting'::character varying"))
+ enabled = db.Column(db.Boolean, nullable=False,
+ server_default=db.text('true'))
+ disabled_at = db.Column(db.DateTime, nullable=True)
+ disabled_by = db.Column(UUID, nullable=True)
+ archived = db.Column(db.Boolean, nullable=False,
+ server_default=db.text('false'))
+ archived_reason = db.Column(db.String(255), nullable=True)
+ archived_by = db.Column(UUID, nullable=True)
+ archived_at = db.Column(db.DateTime, nullable=True)
+ updated_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ doc_type = db.Column(db.String(40), nullable=True)
+ doc_metadata = db.Column(db.JSON, nullable=True)
+
+ DATA_SOURCES = ['upload_file']
+
+ @property
+ def display_status(self):
+ status = None
+ if self.indexing_status == 'waiting':
+ status = 'queuing'
+ elif self.indexing_status not in ['completed', 'error', 'waiting'] and self.is_paused:
+ status = 'paused'
+ elif self.indexing_status in ['parsing', 'cleaning', 'splitting', 'indexing']:
+ status = 'indexing'
+ elif self.indexing_status == 'error':
+ status = 'error'
+ elif self.indexing_status == 'completed' and not self.archived and self.enabled:
+ status = 'available'
+ elif self.indexing_status == 'completed' and not self.archived and not self.enabled:
+ status = 'disabled'
+ elif self.indexing_status == 'completed' and self.archived:
+ status = 'archived'
+ return status
+
+ @property
+ def data_source_info_dict(self):
+ if self.data_source_info:
+ try:
+ data_source_info_dict = json.loads(self.data_source_info)
+ except JSONDecodeError:
+ data_source_info_dict = {}
+
+ return data_source_info_dict
+ return None
+
+ @property
+ def data_source_detail_dict(self):
+ if self.data_source_info:
+ if self.data_source_type == 'upload_file':
+ data_source_info_dict = json.loads(self.data_source_info)
+ file_detail = db.session.query(UploadFile). \
+ filter(UploadFile.id == data_source_info_dict['upload_file_id']). \
+ one_or_none()
+ if file_detail:
+ return {
+ 'upload_file': {
+ 'id': file_detail.id,
+ 'name': file_detail.name,
+ 'size': file_detail.size,
+ 'extension': file_detail.extension,
+ 'mime_type': file_detail.mime_type,
+ 'created_by': file_detail.created_by,
+ 'created_at': file_detail.created_at.timestamp()
+ }
+ }
+ return {}
+
+ @property
+ def average_segment_length(self):
+ if self.word_count and self.word_count != 0 and self.segment_count and self.segment_count != 0:
+ return self.word_count//self.segment_count
+ return 0
+
+ @property
+ def dataset_process_rule(self):
+ if self.dataset_process_rule_id:
+ return DatasetProcessRule.query.get(self.dataset_process_rule_id)
+ return None
+
+ @property
+ def dataset(self):
+ return Dataset.query.get(self.dataset_id)
+
+ @property
+ def segment_count(self):
+ return DocumentSegment.query.filter(DocumentSegment.document_id == self.id).count()
+
+ @property
+ def hit_count(self):
+ return DocumentSegment.query.with_entities(func.coalesce(func.sum(DocumentSegment.hit_count))) \
+ .filter(DocumentSegment.document_id == self.id).scalar()
+
+
+class DocumentSegment(db.Model):
+ __tablename__ = 'document_segments'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='document_segment_pkey'),
+ db.Index('document_segment_dataset_id_idx', 'dataset_id'),
+ db.Index('document_segment_document_id_idx', 'document_id'),
+ db.Index('document_segment_tenant_dataset_idx', 'dataset_id', 'tenant_id'),
+ db.Index('document_segment_tenant_document_idx', 'document_id', 'tenant_id'),
+ db.Index('document_segment_dataset_node_idx', 'dataset_id', 'index_node_id'),
+ )
+
+ # initial fields
+ id = db.Column(UUID, nullable=False,
+ server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ dataset_id = db.Column(UUID, nullable=False)
+ document_id = db.Column(UUID, nullable=False)
+ position = db.Column(db.Integer, nullable=False)
+ content = db.Column(db.Text, nullable=False)
+ word_count = db.Column(db.Integer, nullable=False)
+ tokens = db.Column(db.Integer, nullable=False)
+
+ # indexing fields
+ keywords = db.Column(db.JSON, nullable=True)
+ index_node_id = db.Column(db.String(255), nullable=True)
+ index_node_hash = db.Column(db.String(255), nullable=True)
+
+ # basic fields
+ hit_count = db.Column(db.Integer, nullable=False, default=0)
+ enabled = db.Column(db.Boolean, nullable=False,
+ server_default=db.text('true'))
+ disabled_at = db.Column(db.DateTime, nullable=True)
+ disabled_by = db.Column(UUID, nullable=True)
+ status = db.Column(db.String(255), nullable=False,
+ server_default=db.text("'waiting'::character varying"))
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False,
+ server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ indexing_at = db.Column(db.DateTime, nullable=True)
+ completed_at = db.Column(db.DateTime, nullable=True)
+ error = db.Column(db.Text, nullable=True)
+ stopped_at = db.Column(db.DateTime, nullable=True)
+
+ @property
+ def dataset(self):
+ return db.session.query(Dataset).filter(Dataset.id == self.dataset_id).first()
+
+ @property
+ def document(self):
+ return db.session.query(Document).filter(Document.id == self.document_id).first()
+
+ @property
+ def embedding(self):
+ embedding = db.session.query(Embedding).filter(Embedding.hash == self.index_node_hash).first() \
+ if self.index_node_hash else None
+
+ if embedding:
+ return embedding.embedding
+
+ return None
+
+ @property
+ def previous_segment(self):
+ return db.session.query(DocumentSegment).filter(
+ DocumentSegment.document_id == self.document_id,
+ DocumentSegment.position == self.position - 1
+ ).first()
+
+ @property
+ def next_segment(self):
+ return db.session.query(DocumentSegment).filter(
+ DocumentSegment.document_id == self.document_id,
+ DocumentSegment.position == self.position + 1
+ ).first()
+
+
+class AppDatasetJoin(db.Model):
+ __tablename__ = 'app_dataset_joins'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='app_dataset_join_pkey'),
+ db.Index('app_dataset_join_app_dataset_idx', 'dataset_id', 'app_id'),
+ )
+
+ id = db.Column(UUID, primary_key=True, nullable=False, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ dataset_id = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
+
+ @property
+ def app(self):
+ return App.query.get(self.app_id)
+
+
+class DatasetQuery(db.Model):
+ __tablename__ = 'dataset_queries'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='dataset_query_pkey'),
+ db.Index('dataset_query_dataset_id_idx', 'dataset_id'),
+ )
+
+ id = db.Column(UUID, primary_key=True, nullable=False, server_default=db.text('uuid_generate_v4()'))
+ dataset_id = db.Column(UUID, nullable=False)
+ content = db.Column(db.Text, nullable=False)
+ source = db.Column(db.String(255), nullable=False)
+ source_app_id = db.Column(UUID, nullable=True)
+ created_by_role = db.Column(db.String, nullable=False)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
+
+
+class DatasetKeywordTable(db.Model):
+ __tablename__ = 'dataset_keyword_tables'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='dataset_keyword_table_pkey'),
+ db.Index('dataset_keyword_table_dataset_id_idx', 'dataset_id'),
+ )
+
+ id = db.Column(UUID, primary_key=True, server_default=db.text('uuid_generate_v4()'))
+ dataset_id = db.Column(UUID, nullable=False, unique=True)
+ keyword_table = db.Column(db.Text, nullable=False)
+
+ @property
+ def keyword_table_dict(self):
+ return json.loads(self.keyword_table) if self.keyword_table else None
+
+
+class Embedding(db.Model):
+ __tablename__ = 'embeddings'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='embedding_pkey'),
+ db.UniqueConstraint('hash', name='embedding_hash_idx')
+ )
+
+ id = db.Column(UUID, primary_key=True, server_default=db.text('uuid_generate_v4()'))
+ hash = db.Column(db.String(64), nullable=False)
+ embedding = db.Column(db.LargeBinary, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ def set_embedding(self, embedding_data: list[float]):
+ self.embedding = pickle.dumps(embedding_data, protocol=pickle.HIGHEST_PROTOCOL)
+
+ def get_embedding(self) -> list[float]:
+ return pickle.loads(self.embedding)
diff --git a/api/models/model.py b/api/models/model.py
new file mode 100644
index 00000000000..9b4e2a38bca
--- /dev/null
+++ b/api/models/model.py
@@ -0,0 +1,622 @@
+import json
+
+from flask import current_app
+from flask_login import UserMixin
+from sqlalchemy.dialects.postgresql import UUID
+
+from libs.helper import generate_string
+from extensions.ext_database import db
+from .account import Account, Tenant
+
+
+class DifySetup(db.Model):
+ __tablename__ = 'dify_setups'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('version', name='dify_setup_pkey'),
+ )
+
+ version = db.Column(db.String(255), nullable=False)
+ setup_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class App(db.Model):
+ __tablename__ = 'apps'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='app_pkey'),
+ db.Index('app_tenant_id_idx', 'tenant_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ name = db.Column(db.String(255), nullable=False)
+ mode = db.Column(db.String(255), nullable=False)
+ icon = db.Column(db.String(255))
+ icon_background = db.Column(db.String(255))
+ app_model_config_id = db.Column(UUID, nullable=True)
+ status = db.Column(db.String(255), nullable=False, server_default=db.text("'normal'::character varying"))
+ enable_site = db.Column(db.Boolean, nullable=False)
+ enable_api = db.Column(db.Boolean, nullable=False)
+ api_rpm = db.Column(db.Integer, nullable=False)
+ api_rph = db.Column(db.Integer, nullable=False)
+ is_demo = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ is_public = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def site(self):
+ site = db.session.query(Site).filter(Site.app_id == self.id).first()
+ return site
+
+ @property
+ def app_model_config(self):
+ app_model_config = db.session.query(AppModelConfig).filter(
+ AppModelConfig.id == self.app_model_config_id).first()
+ return app_model_config
+
+ @property
+ def api_base_url(self):
+ return current_app.config['API_URL'] + '/v1'
+
+ @property
+ def tenant(self):
+ tenant = db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
+ return tenant
+
+
+class AppModelConfig(db.Model):
+ __tablename__ = 'app_model_configs'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='app_model_config_pkey'),
+ db.Index('app_app_id_idx', 'app_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ provider = db.Column(db.String(255), nullable=False)
+ model_id = db.Column(db.String(255), nullable=False)
+ configs = db.Column(db.JSON, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ opening_statement = db.Column(db.Text)
+ suggested_questions = db.Column(db.Text)
+ suggested_questions_after_answer = db.Column(db.Text)
+ more_like_this = db.Column(db.Text)
+ model = db.Column(db.Text)
+ user_input_form = db.Column(db.Text)
+ pre_prompt = db.Column(db.Text)
+ agent_mode = db.Column(db.Text)
+
+ @property
+ def app(self):
+ app = db.session.query(App).filter(App.id == self.app_id).first()
+ return app
+
+ @property
+ def model_dict(self) -> dict:
+ return json.loads(self.model) if self.model else None
+
+ @property
+ def suggested_questions_list(self) -> list:
+ return json.loads(self.suggested_questions) if self.suggested_questions else []
+
+ @property
+ def suggested_questions_after_answer_dict(self) -> dict:
+ return json.loads(self.suggested_questions_after_answer) if self.suggested_questions_after_answer \
+ else {"enabled": False}
+
+ @property
+ def more_like_this_dict(self) -> dict:
+ return json.loads(self.more_like_this) if self.more_like_this else {"enabled": False}
+
+ @property
+ def user_input_form_list(self) -> dict:
+ return json.loads(self.user_input_form) if self.user_input_form else []
+
+ @property
+ def agent_mode_dict(self) -> dict:
+ return json.loads(self.agent_mode) if self.agent_mode else {"enabled": False, "tools": []}
+
+
+class RecommendedApp(db.Model):
+ __tablename__ = 'recommended_apps'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='recommended_app_pkey'),
+ db.Index('recommended_app_app_id_idx', 'app_id'),
+ db.Index('recommended_app_is_listed_idx', 'is_listed')
+ )
+
+ id = db.Column(UUID, primary_key=True, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ description = db.Column(db.JSON, nullable=False)
+ copyright = db.Column(db.String(255), nullable=False)
+ privacy_policy = db.Column(db.String(255), nullable=False)
+ category = db.Column(db.String(255), nullable=False)
+ position = db.Column(db.Integer, nullable=False, default=0)
+ is_listed = db.Column(db.Boolean, nullable=False, default=True)
+ install_count = db.Column(db.Integer, nullable=False, default=0)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def app(self):
+ app = db.session.query(App).filter(App.id == self.app_id).first()
+ return app
+
+ # def set_description(self, lang, desc):
+ # if self.description is None:
+ # self.description = {}
+ # self.description[lang] = desc
+
+ def get_description(self, lang):
+ if self.description and lang in self.description:
+ return self.description[lang]
+ else:
+ return self.description.get('en')
+
+
+class InstalledApp(db.Model):
+ __tablename__ = 'installed_apps'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='installed_app_pkey'),
+ db.Index('installed_app_tenant_id_idx', 'tenant_id'),
+ db.Index('installed_app_app_id_idx', 'app_id'),
+ db.UniqueConstraint('tenant_id', 'app_id', name='unique_tenant_app')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ app_id = db.Column(UUID, nullable=False)
+ app_owner_tenant_id = db.Column(UUID, nullable=False)
+ position = db.Column(db.Integer, nullable=False, default=0)
+ is_pinned = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ last_used_at = db.Column(db.DateTime, nullable=True)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def app(self):
+ app = db.session.query(App).filter(App.id == self.app_id).first()
+ return app
+
+ @property
+ def tenant(self):
+ tenant = db.session.query(Tenant).filter(Tenant.id == self.tenant_id).first()
+ return tenant
+
+
+class Conversation(db.Model):
+ __tablename__ = 'conversations'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='conversation_pkey'),
+ db.Index('conversation_app_from_user_idx', 'app_id', 'from_source', 'from_end_user_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ app_model_config_id = db.Column(UUID, nullable=False)
+ model_provider = db.Column(db.String(255), nullable=False)
+ override_model_configs = db.Column(db.Text)
+ model_id = db.Column(db.String(255), nullable=False)
+ mode = db.Column(db.String(255), nullable=False)
+ name = db.Column(db.String(255), nullable=False)
+ summary = db.Column(db.Text)
+ inputs = db.Column(db.JSON)
+ introduction = db.Column(db.Text)
+ system_instruction = db.Column(db.Text)
+ system_instruction_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
+ status = db.Column(db.String(255), nullable=False)
+ from_source = db.Column(db.String(255), nullable=False)
+ from_end_user_id = db.Column(UUID)
+ from_account_id = db.Column(UUID)
+ read_at = db.Column(db.DateTime)
+ read_account_id = db.Column(UUID)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ messages = db.relationship("Message", backref="conversation", lazy='select', passive_deletes="all")
+ message_annotations = db.relationship("MessageAnnotation", backref="conversation", lazy='select', passive_deletes="all")
+
+ @property
+ def model_config(self):
+ model_config = {}
+ if self.override_model_configs:
+ override_model_configs = json.loads(self.override_model_configs)
+
+ if 'model' in override_model_configs:
+ model_config['model'] = override_model_configs['model']
+ model_config['pre_prompt'] = override_model_configs['pre_prompt']
+ model_config['agent_mode'] = override_model_configs['agent_mode']
+ model_config['opening_statement'] = override_model_configs['opening_statement']
+ model_config['suggested_questions'] = override_model_configs['suggested_questions']
+ model_config['suggested_questions_after_answer'] = override_model_configs[
+ 'suggested_questions_after_answer'] \
+ if 'suggested_questions_after_answer' in override_model_configs else {"enabled": False}
+ model_config['more_like_this'] = override_model_configs['more_like_this'] \
+ if 'more_like_this' in override_model_configs else {"enabled": False}
+ model_config['user_input_form'] = override_model_configs['user_input_form']
+ else:
+ model_config['configs'] = override_model_configs
+ else:
+ app_model_config = db.session.query(AppModelConfig).filter(
+ AppModelConfig.id == self.app_model_config_id).first()
+
+ model_config['configs'] = app_model_config.configs
+ model_config['model'] = app_model_config.model_dict
+ model_config['pre_prompt'] = app_model_config.pre_prompt
+ model_config['agent_mode'] = app_model_config.agent_mode_dict
+ model_config['opening_statement'] = app_model_config.opening_statement
+ model_config['suggested_questions'] = app_model_config.suggested_questions_list
+ model_config['suggested_questions_after_answer'] = app_model_config.suggested_questions_after_answer_dict
+ model_config['more_like_this'] = app_model_config.more_like_this_dict
+ model_config['user_input_form'] = app_model_config.user_input_form_list
+
+ model_config['model_id'] = self.model_id
+ model_config['provider'] = self.model_provider
+
+ return model_config
+
+ @property
+ def summary_or_query(self):
+ if self.summary:
+ return self.summary
+ else:
+ first_message = self.first_message
+ if first_message:
+ return first_message.query
+ else:
+ return ''
+
+ @property
+ def annotated(self):
+ return db.session.query(MessageAnnotation).filter(MessageAnnotation.conversation_id == self.id).count() > 0
+
+ @property
+ def annotation(self):
+ return db.session.query(MessageAnnotation).filter(MessageAnnotation.conversation_id == self.id).first()
+
+ @property
+ def message_count(self):
+ return db.session.query(Message).filter(Message.conversation_id == self.id).count()
+
+ @property
+ def user_feedback_stats(self):
+ like = db.session.query(MessageFeedback) \
+ .filter(MessageFeedback.conversation_id == self.id,
+ MessageFeedback.from_source == 'user',
+ MessageFeedback.rating == 'like').count()
+
+ dislike = db.session.query(MessageFeedback) \
+ .filter(MessageFeedback.conversation_id == self.id,
+ MessageFeedback.from_source == 'user',
+ MessageFeedback.rating == 'dislike').count()
+
+ return {'like': like, 'dislike': dislike}
+
+ @property
+ def admin_feedback_stats(self):
+ like = db.session.query(MessageFeedback) \
+ .filter(MessageFeedback.conversation_id == self.id,
+ MessageFeedback.from_source == 'admin',
+ MessageFeedback.rating == 'like').count()
+
+ dislike = db.session.query(MessageFeedback) \
+ .filter(MessageFeedback.conversation_id == self.id,
+ MessageFeedback.from_source == 'admin',
+ MessageFeedback.rating == 'dislike').count()
+
+ return {'like': like, 'dislike': dislike}
+
+ @property
+ def first_message(self):
+ return db.session.query(Message).filter(Message.conversation_id == self.id).first()
+
+ @property
+ def app(self):
+ return db.session.query(App).filter(App.id == self.app_id).first()
+
+
+class Message(db.Model):
+ __tablename__ = 'messages'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='message_pkey'),
+ db.Index('message_app_id_idx', 'app_id', 'created_at'),
+ db.Index('message_conversation_id_idx', 'conversation_id'),
+ db.Index('message_end_user_idx', 'app_id', 'from_source', 'from_end_user_id'),
+ db.Index('message_account_idx', 'app_id', 'from_source', 'from_account_id'),
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ model_provider = db.Column(db.String(255), nullable=False)
+ model_id = db.Column(db.String(255), nullable=False)
+ override_model_configs = db.Column(db.Text)
+ conversation_id = db.Column(UUID, db.ForeignKey('conversations.id'), nullable=False)
+ inputs = db.Column(db.JSON)
+ query = db.Column(db.Text, nullable=False)
+ message = db.Column(db.JSON, nullable=False)
+ message_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
+ message_unit_price = db.Column(db.Numeric(10, 4), nullable=False)
+ answer = db.Column(db.Text, nullable=False)
+ answer_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
+ answer_unit_price = db.Column(db.Numeric(10, 4), nullable=False)
+ provider_response_latency = db.Column(db.Float, nullable=False, server_default=db.text('0'))
+ total_price = db.Column(db.Numeric(10, 7))
+ currency = db.Column(db.String(255), nullable=False)
+ from_source = db.Column(db.String(255), nullable=False)
+ from_end_user_id = db.Column(UUID)
+ from_account_id = db.Column(UUID)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ agent_based = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+
+ @property
+ def user_feedback(self):
+ feedback = db.session.query(MessageFeedback).filter(MessageFeedback.message_id == self.id,
+ MessageFeedback.from_source == 'user').first()
+ return feedback
+
+ @property
+ def admin_feedback(self):
+ feedback = db.session.query(MessageFeedback).filter(MessageFeedback.message_id == self.id,
+ MessageFeedback.from_source == 'admin').first()
+ return feedback
+
+ @property
+ def feedbacks(self):
+ feedbacks = db.session.query(MessageFeedback).filter(MessageFeedback.message_id == self.id).all()
+ return feedbacks
+
+ @property
+ def annotation(self):
+ annotation = db.session.query(MessageAnnotation).filter(MessageAnnotation.message_id == self.id).first()
+ return annotation
+
+ @property
+ def app_model_config(self):
+ conversation = db.session.query(Conversation).filter(Conversation.id == self.conversation_id).first()
+ if conversation:
+ return db.session.query(AppModelConfig).filter(
+ AppModelConfig.id == conversation.app_model_config_id).first()
+
+ return None
+
+
+class MessageFeedback(db.Model):
+ __tablename__ = 'message_feedbacks'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='message_feedback_pkey'),
+ db.Index('message_feedback_app_idx', 'app_id'),
+ db.Index('message_feedback_message_idx', 'message_id', 'from_source'),
+ db.Index('message_feedback_conversation_idx', 'conversation_id', 'from_source', 'rating')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ conversation_id = db.Column(UUID, nullable=False)
+ message_id = db.Column(UUID, nullable=False)
+ rating = db.Column(db.String(255), nullable=False)
+ content = db.Column(db.Text)
+ from_source = db.Column(db.String(255), nullable=False)
+ from_end_user_id = db.Column(UUID)
+ from_account_id = db.Column(UUID)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def from_account(self):
+ account = db.session.query(Account).filter(Account.id == self.from_account_id).first()
+ return account
+
+
+class MessageAnnotation(db.Model):
+ __tablename__ = 'message_annotations'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='message_annotation_pkey'),
+ db.Index('message_annotation_app_idx', 'app_id'),
+ db.Index('message_annotation_conversation_idx', 'conversation_id'),
+ db.Index('message_annotation_message_idx', 'message_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ conversation_id = db.Column(UUID, db.ForeignKey('conversations.id'), nullable=False)
+ message_id = db.Column(UUID, nullable=False)
+ content = db.Column(db.Text, nullable=False)
+ account_id = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def account(self):
+ account = db.session.query(Account).filter(Account.id == self.account_id).first()
+ return account
+
+
+class OperationLog(db.Model):
+ __tablename__ = 'operation_logs'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='operation_log_pkey'),
+ db.Index('operation_log_account_action_idx', 'tenant_id', 'account_id', 'action')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ account_id = db.Column(UUID, nullable=False)
+ action = db.Column(db.String(255), nullable=False)
+ content = db.Column(db.JSON)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ created_ip = db.Column(db.String(255), nullable=False)
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class EndUser(UserMixin, db.Model):
+ __tablename__ = 'end_users'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='end_user_pkey'),
+ db.Index('end_user_session_id_idx', 'session_id', 'type'),
+ db.Index('end_user_tenant_session_id_idx', 'tenant_id', 'session_id', 'type'),
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ app_id = db.Column(UUID, nullable=True)
+ type = db.Column(db.String(255), nullable=False)
+ external_user_id = db.Column(db.String(255), nullable=True)
+ name = db.Column(db.String(255))
+ is_anonymous = db.Column(db.Boolean, nullable=False, server_default=db.text('true'))
+ session_id = db.Column(db.String(255), nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class Site(db.Model):
+ __tablename__ = 'sites'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='site_pkey'),
+ db.Index('site_app_id_idx', 'app_id'),
+ db.Index('site_code_idx', 'code', 'status')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ title = db.Column(db.String(255), nullable=False)
+ icon = db.Column(db.String(255))
+ icon_background = db.Column(db.String(255))
+ description = db.Column(db.String(255))
+ default_language = db.Column(db.String(255), nullable=False)
+ copyright = db.Column(db.String(255))
+ privacy_policy = db.Column(db.String(255))
+ customize_domain = db.Column(db.String(255))
+ customize_token_strategy = db.Column(db.String(255), nullable=False)
+ prompt_public = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ status = db.Column(db.String(255), nullable=False, server_default=db.text("'normal'::character varying"))
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ code = db.Column(db.String(255))
+
+ @staticmethod
+ def generate_code(n):
+ while True:
+ result = generate_string(n)
+ while db.session.query(Site).filter(Site.code == result).count() > 0:
+ result = generate_string(n)
+
+ return result
+
+ @property
+ def app_base_url(self):
+ return current_app.config['APP_URL']
+
+
+class ApiToken(db.Model):
+ __tablename__ = 'api_tokens'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='api_token_pkey'),
+ db.Index('api_token_app_id_type_idx', 'app_id', 'type'),
+ db.Index('api_token_token_idx', 'token', 'type')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=True)
+ dataset_id = db.Column(UUID, nullable=True)
+ type = db.Column(db.String(16), nullable=False)
+ token = db.Column(db.String(255), nullable=False)
+ last_used_at = db.Column(db.DateTime, nullable=True)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @staticmethod
+ def generate_api_key(prefix, n):
+ while True:
+ result = prefix + generate_string(n)
+ while db.session.query(ApiToken).filter(ApiToken.token == result).count() > 0:
+ result = prefix + generate_string(n)
+
+ return result
+
+
+class UploadFile(db.Model):
+ __tablename__ = 'upload_files'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='upload_file_pkey'),
+ db.Index('upload_file_tenant_idx', 'tenant_id')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ storage_type = db.Column(db.String(255), nullable=False)
+ key = db.Column(db.String(255), nullable=False)
+ name = db.Column(db.String(255), nullable=False)
+ size = db.Column(db.Integer, nullable=False)
+ extension = db.Column(db.String(255), nullable=False)
+ mime_type = db.Column(db.String(255), nullable=True)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ used = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ used_by = db.Column(UUID, nullable=True)
+ used_at = db.Column(db.DateTime, nullable=True)
+ hash = db.Column(db.String(255), nullable=True)
+
+
+class ApiRequest(db.Model):
+ __tablename__ = 'api_requests'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='api_request_pkey'),
+ db.Index('api_request_token_idx', 'tenant_id', 'api_token_id')
+ )
+
+ id = db.Column(UUID, nullable=False, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ api_token_id = db.Column(UUID, nullable=False)
+ path = db.Column(db.String(255), nullable=False)
+ request = db.Column(db.Text, nullable=True)
+ response = db.Column(db.Text, nullable=True)
+ ip = db.Column(db.String(255), nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+
+class MessageChain(db.Model):
+ __tablename__ = 'message_chains'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='message_chain_pkey'),
+ db.Index('message_chain_message_id_idx', 'message_id')
+ )
+
+ id = db.Column(UUID, nullable=False, server_default=db.text('uuid_generate_v4()'))
+ message_id = db.Column(UUID, nullable=False)
+ type = db.Column(db.String(255), nullable=False)
+ input = db.Column(db.Text, nullable=True)
+ output = db.Column(db.Text, nullable=True)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
+
+
+class MessageAgentThought(db.Model):
+ __tablename__ = 'message_agent_thoughts'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='message_agent_thought_pkey'),
+ db.Index('message_agent_thought_message_id_idx', 'message_id'),
+ db.Index('message_agent_thought_message_chain_id_idx', 'message_chain_id'),
+ )
+
+ id = db.Column(UUID, nullable=False, server_default=db.text('uuid_generate_v4()'))
+ message_id = db.Column(UUID, nullable=False)
+ message_chain_id = db.Column(UUID, nullable=False)
+ position = db.Column(db.Integer, nullable=False)
+ thought = db.Column(db.Text, nullable=True)
+ tool = db.Column(db.Text, nullable=True)
+ tool_input = db.Column(db.Text, nullable=True)
+ observation = db.Column(db.Text, nullable=True)
+ # plugin_id = db.Column(UUID, nullable=True) ## for future design
+ tool_process_data = db.Column(db.Text, nullable=True)
+ message = db.Column(db.Text, nullable=True)
+ message_token = db.Column(db.Integer, nullable=True)
+ message_unit_price = db.Column(db.Numeric, nullable=True)
+ answer = db.Column(db.Text, nullable=True)
+ answer_token = db.Column(db.Integer, nullable=True)
+ answer_unit_price = db.Column(db.Numeric, nullable=True)
+ tokens = db.Column(db.Integer, nullable=True)
+ total_price = db.Column(db.Numeric, nullable=True)
+ currency = db.Column(db.String, nullable=True)
+ latency = db.Column(db.Float, nullable=True)
+ created_by_role = db.Column(db.String, nullable=False)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
diff --git a/api/models/provider.py b/api/models/provider.py
new file mode 100644
index 00000000000..e4ecfa1241e
--- /dev/null
+++ b/api/models/provider.py
@@ -0,0 +1,77 @@
+from enum import Enum
+
+from sqlalchemy.dialects.postgresql import UUID
+
+from extensions.ext_database import db
+
+
+class ProviderType(Enum):
+ CUSTOM = 'custom'
+ SYSTEM = 'system'
+
+
+class ProviderName(Enum):
+ OPENAI = 'openai'
+ AZURE_OPENAI = 'azure_openai'
+ ANTHROPIC = 'anthropic'
+ COHERE = 'cohere'
+ HUGGINGFACEHUB = 'huggingfacehub'
+
+ @staticmethod
+ def value_of(value):
+ for member in ProviderName:
+ if member.value == value:
+ return member
+ raise ValueError(f"No matching enum found for value '{value}'")
+
+
+class ProviderQuotaType(Enum):
+ MONTHLY = 'monthly'
+ TRIAL = 'trial'
+
+
+class Provider(db.Model):
+ """
+ Provider model representing the API providers and their configurations.
+ """
+ __tablename__ = 'providers'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='provider_pkey'),
+ db.Index('provider_tenant_id_provider_idx', 'tenant_id', 'provider_name'),
+ db.UniqueConstraint('tenant_id', 'provider_name', 'provider_type', 'quota_type', name='unique_provider_name_type_quota')
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ tenant_id = db.Column(UUID, nullable=False)
+ provider_name = db.Column(db.String(40), nullable=False)
+ provider_type = db.Column(db.String(40), nullable=False, server_default=db.text("'custom'::character varying"))
+ encrypted_config = db.Column(db.Text, nullable=True)
+ is_valid = db.Column(db.Boolean, nullable=False, server_default=db.text('false'))
+ last_used = db.Column(db.DateTime, nullable=True)
+
+ quota_type = db.Column(db.String(40), nullable=True, server_default=db.text("''::character varying"))
+ quota_limit = db.Column(db.Integer, nullable=True)
+ quota_used = db.Column(db.Integer, default=0)
+
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+ updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ def __repr__(self):
+ return f"<Provider(id={self.id}, tenant_id={self.tenant_id}, provider_name='{self.provider_name}', provider_type='{self.provider_type}')>"
+
+ @property
+ def token_is_set(self):
+ """
+ Returns True if the encrypted_config is not None, indicating that the token is set.
+ """
+ return self.encrypted_config is not None
+
+ @property
+ def is_enabled(self):
+ """
+ Returns True if the provider is enabled.
+ """
+ if self.provider_type == ProviderType.SYSTEM.value:
+ return self.is_valid
+ else:
+ return self.is_valid and self.token_is_set
diff --git a/api/models/task.py b/api/models/task.py
new file mode 100644
index 00000000000..d85cf16d7c5
--- /dev/null
+++ b/api/models/task.py
@@ -0,0 +1,37 @@
+from extensions.ext_database import db
+from celery import states
+from datetime import datetime
+
+
+class CeleryTask(db.Model):
+ """Task result/status."""
+
+ __tablename__ = 'celery_taskmeta'
+
+ id = db.Column(db.Integer, db.Sequence('task_id_sequence'),
+ primary_key=True, autoincrement=True)
+ task_id = db.Column(db.String(155), unique=True)
+ status = db.Column(db.String(50), default=states.PENDING)
+ result = db.Column(db.PickleType, nullable=True)
+ date_done = db.Column(db.DateTime, default=datetime.utcnow,
+ onupdate=datetime.utcnow, nullable=True)
+ traceback = db.Column(db.Text, nullable=True)
+ name = db.Column(db.String(155), nullable=True)
+ args = db.Column(db.LargeBinary, nullable=True)
+ kwargs = db.Column(db.LargeBinary, nullable=True)
+ worker = db.Column(db.String(155), nullable=True)
+ retries = db.Column(db.Integer, nullable=True)
+ queue = db.Column(db.String(155), nullable=True)
+
+
+class CeleryTaskSet(db.Model):
+ """TaskSet result."""
+
+ __tablename__ = 'celery_tasksetmeta'
+
+ id = db.Column(db.Integer, db.Sequence('taskset_id_sequence'),
+ autoincrement=True, primary_key=True)
+ taskset_id = db.Column(db.String(155), unique=True)
+ result = db.Column(db.PickleType, nullable=True)
+ date_done = db.Column(db.DateTime, default=datetime.utcnow,
+ nullable=True)
diff --git a/api/models/web.py b/api/models/web.py
new file mode 100644
index 00000000000..1580ce74c95
--- /dev/null
+++ b/api/models/web.py
@@ -0,0 +1,36 @@
+from sqlalchemy.dialects.postgresql import UUID
+
+from extensions.ext_database import db
+from models.model import Message
+
+
+class SavedMessage(db.Model):
+ __tablename__ = 'saved_messages'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='saved_message_pkey'),
+ db.Index('saved_message_message_idx', 'app_id', 'message_id', 'created_by'),
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ message_id = db.Column(UUID, nullable=False)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
+
+ @property
+ def message(self):
+ return db.session.query(Message).filter(Message.id == self.message_id).first()
+
+
+class PinnedConversation(db.Model):
+ __tablename__ = 'pinned_conversations'
+ __table_args__ = (
+ db.PrimaryKeyConstraint('id', name='pinned_conversation_pkey'),
+ db.Index('pinned_conversation_conversation_idx', 'app_id', 'conversation_id', 'created_by'),
+ )
+
+ id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
+ app_id = db.Column(UUID, nullable=False)
+ conversation_id = db.Column(UUID, nullable=False)
+ created_by = db.Column(UUID, nullable=False)
+ created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
diff --git a/api/requirements.txt b/api/requirements.txt
new file mode 100644
index 00000000000..511625ccfd8
--- /dev/null
+++ b/api/requirements.txt
@@ -0,0 +1,32 @@
+coverage~=7.2.4
+beautifulsoup4==4.12.2
+flask~=2.3.2
+Flask-SQLAlchemy~=3.0.3
+flask-login==0.6.2
+flask-migrate~=4.0.4
+flask-restful==0.3.9
+flask-session2==1.3.1
+flask-cors==3.0.10
+gunicorn~=20.1.0
+gevent~=22.10.2
+langchain==0.0.142
+llama-index==0.5.27
+openai~=0.27.5
+psycopg2-binary~=2.9.6
+pycryptodome==3.17
+python-dotenv==1.0.0
+pytest~=7.3.1
+tiktoken==0.3.3
+Authlib==1.2.0
+boto3~=1.26.123
+tenacity==8.2.2
+cachetools~=5.3.0
+weaviate-client~=3.16.2
+qdrant_client~=1.1.6
+mailchimp-transactional~=1.0.50
+scikit-learn==1.2.2
+sentry-sdk[flask]~=1.21.1
+jieba==0.42.1
+celery==5.2.7
+redis~=4.5.4
+pypdf==3.8.1
\ No newline at end of file
diff --git a/api/services/__init__.py b/api/services/__init__.py
new file mode 100644
index 00000000000..36a7704385a
--- /dev/null
+++ b/api/services/__init__.py
@@ -0,0 +1,2 @@
+# -*- coding:utf-8 -*-
+import services.errors
diff --git a/api/services/account_service.py b/api/services/account_service.py
new file mode 100644
index 00000000000..8442e0eab85
--- /dev/null
+++ b/api/services/account_service.py
@@ -0,0 +1,382 @@
+# -*- coding:utf-8 -*-
+import base64
+import logging
+import secrets
+from datetime import datetime
+from typing import Optional
+
+from flask import session
+from sqlalchemy import func
+
+from events.tenant_event import tenant_was_created
+from services.errors.account import AccountLoginError, CurrentPasswordIncorrectError, LinkAccountIntegrateError, \
+ TenantNotFound, AccountNotLinkTenantError, InvalidActionError, CannotOperateSelfError, MemberNotInTenantError, \
+ RoleAlreadyAssignedError, NoPermissionError, AccountRegisterError, AccountAlreadyInTenantError
+from libs.helper import get_remote_ip
+from libs.password import compare_password, hash_password
+from libs.rsa import generate_key_pair
+from models.account import *
+
+
+class AccountService:
+
+ @staticmethod
+ def load_user(account_id: int) -> Account:
+ # todo: used by flask_login
+ pass
+
+ @staticmethod
+ def authenticate(email: str, password: str) -> Account:
+ """authenticate account with email and password"""
+
+ account = Account.query.filter_by(email=email).first()
+ if not account:
+ raise AccountLoginError('Invalid email or password.')
+
+ if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
+ raise AccountLoginError('Account is banned or closed.')
+
+ if account.status == AccountStatus.PENDING.value:
+ account.status = AccountStatus.ACTIVE.value
+ account.initialized_at = datetime.utcnow()
+ db.session.commit()
+
+ if account.password is None or not compare_password(password, account.password, account.password_salt):
+ raise AccountLoginError('Invalid email or password.')
+ return account
+
+ @staticmethod
+ def update_account_password(account, password, new_password):
+ """update account password"""
+ # todo: split validation and update
+ if account.password and not compare_password(password, account.password, account.password_salt):
+ raise CurrentPasswordIncorrectError("Current password is incorrect.")
+ password_hashed = hash_password(new_password, account.password_salt)
+ base64_password_hashed = base64.b64encode(password_hashed).decode()
+ account.password = base64_password_hashed
+ db.session.commit()
+ return account
+
+ @staticmethod
+ def create_account(email: str, name: str, password: str = None,
+ interface_language: str = 'en-US', interface_theme: str = 'light',
+ timezone: str = 'America/New_York', ) -> Account:
+ """create account"""
+ account = Account()
+ account.email = email
+ account.name = name
+
+ if password:
+ # generate password salt
+ salt = secrets.token_bytes(16)
+ base64_salt = base64.b64encode(salt).decode()
+
+ # encrypt password with salt
+ password_hashed = hash_password(password, salt)
+ base64_password_hashed = base64.b64encode(password_hashed).decode()
+
+ account.password = base64_password_hashed
+ account.password_salt = base64_salt
+
+ account.interface_language = interface_language
+ account.interface_theme = interface_theme
+
+ if interface_language == 'zh-Hans':
+ account.timezone = 'Asia/Shanghai'
+ else:
+ account.timezone = timezone
+
+ db.session.add(account)
+ db.session.commit()
+ return account
+
+ @staticmethod
+ def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
+ """Link account integrate"""
+ try:
+ # Query whether there is an existing binding record for the same provider
+ account_integrate: Optional[AccountIntegrate] = AccountIntegrate.query.filter_by(account_id=account.id,
+ provider=provider).first()
+
+ if account_integrate:
+ # If it exists, update the record
+ account_integrate.open_id = open_id
+ account_integrate.encrypted_token = "" # todo
+ account_integrate.updated_at = datetime.utcnow()
+ else:
+ # If it does not exist, create a new record
+ account_integrate = AccountIntegrate(account_id=account.id, provider=provider, open_id=open_id,
+ encrypted_token="")
+ db.session.add(account_integrate)
+
+ db.session.commit()
+ logging.info(f'Account {account.id} linked {provider} account {open_id}.')
+ except Exception as e:
+ logging.exception(f'Failed to link {provider} account {open_id} to Account {account.id}')
+ raise LinkAccountIntegrateError('Failed to link account.') from e
+
+ @staticmethod
+ def close_account(account: Account) -> None:
+ """todo: Close account"""
+ account.status = AccountStatus.CLOSED.value
+ db.session.commit()
+
+ @staticmethod
+ def update_account(account, **kwargs):
+ """Update account fields"""
+ for field, value in kwargs.items():
+ if hasattr(account, field):
+ setattr(account, field, value)
+ else:
+ raise AttributeError(f"Invalid field: {field}")
+
+ db.session.commit()
+ return account
+
+ @staticmethod
+ def update_last_login(account: Account, request) -> None:
+ """Update last login time and ip"""
+ account.last_login_at = datetime.utcnow()
+ account.last_login_ip = get_remote_ip(request)
+ db.session.add(account)
+ db.session.commit()
+ logging.info(f'Account {account.id} logged in successfully.')
+
+
+class TenantService:
+
+ @staticmethod
+ def create_tenant(name: str) -> Tenant:
+ """Create tenant"""
+ tenant = Tenant(name=name)
+
+ db.session.add(tenant)
+ db.session.commit()
+
+ tenant.encrypt_public_key = generate_key_pair(tenant.id)
+ db.session.commit()
+ return tenant
+
+ @staticmethod
+ def create_tenant_member(tenant: Tenant, account: Account, role: str = 'normal') -> TenantAccountJoin:
+ """Create tenant member"""
+ if role == TenantAccountJoinRole.OWNER.value:
+ if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
+ logging.error(f'Tenant {tenant.id} has already an owner.')
+ raise Exception('Tenant already has an owner.')
+
+ ta = TenantAccountJoin(
+ tenant_id=tenant.id,
+ account_id=account.id,
+ role=role
+ )
+ db.session.add(ta)
+ db.session.commit()
+ return ta
+
+ @staticmethod
+ def get_join_tenants(account: Account) -> List[Tenant]:
+ """Get account join tenants"""
+ return db.session.query(Tenant).join(
+ TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id
+ ).filter(TenantAccountJoin.account_id == account.id).all()
+
+ @staticmethod
+ def get_current_tenant_by_account(account: Account):
+ """Get tenant by account and add the role"""
+ tenant = account.current_tenant
+ if not tenant:
+ raise TenantNotFound("Tenant not found.")
+
+ ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
+ if ta:
+ tenant.role = ta.role
+ else:
+ raise TenantNotFound("Tenant not found for the account.")
+ return tenant
+
+ @staticmethod
+ def switch_tenant(account: Account, tenant_id: int = None) -> None:
+ """Switch the current workspace for the account"""
+ if not tenant_id:
+ tenant_account_join = TenantAccountJoin.query.filter_by(account_id=account.id).first()
+ else:
+ tenant_account_join = TenantAccountJoin.query.filter_by(account_id=account.id, tenant_id=tenant_id).first()
+
+ # Check if the tenant exists and the account is a member of the tenant
+ if not tenant_account_join:
+ raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
+
+ # Set the current tenant for the account
+ account.current_tenant_id = tenant_account_join.tenant_id
+ session['workspace_id'] = account.current_tenant.id
+
+ @staticmethod
+ def get_tenant_members(tenant: Tenant) -> List[Account]:
+ """Get tenant members"""
+ query = (
+ db.session.query(Account, TenantAccountJoin.role)
+ .select_from(Account)
+ .join(
+ TenantAccountJoin, Account.id == TenantAccountJoin.account_id
+ )
+ .filter(TenantAccountJoin.tenant_id == tenant.id)
+ )
+
+ # Initialize an empty list to store the updated accounts
+ updated_accounts = []
+
+ for account, role in query:
+ account.role = role
+ updated_accounts.append(account)
+
+ return updated_accounts
+
+ @staticmethod
+ def has_roles(tenant: Tenant, roles: List[TenantAccountJoinRole]) -> bool:
+ """Check if user has any of the given roles for a tenant"""
+ if not all(isinstance(role, TenantAccountJoinRole) for role in roles):
+ raise ValueError('all roles must be TenantAccountJoinRole')
+
+ return db.session.query(TenantAccountJoin).filter(
+ TenantAccountJoin.tenant_id == tenant.id,
+ TenantAccountJoin.role.in_([role.value for role in roles])
+ ).first() is not None
+
+ @staticmethod
+ def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountJoinRole]:
+ """Get the role of the current account for a given tenant"""
+ join = db.session.query(TenantAccountJoin).filter(
+ TenantAccountJoin.tenant_id == tenant.id,
+ TenantAccountJoin.account_id == account.id
+ ).first()
+ return join.role if join else None
+
+ @staticmethod
+ def get_tenant_count() -> int:
+ """Get tenant count"""
+ return db.session.query(func.count(Tenant.id)).scalar()
+
+ @staticmethod
+ def check_member_permission(tenant: Tenant, operator: Account, member: Account, action: str) -> None:
+ """Check member permission"""
+ perms = {
+ 'add': ['owner', 'admin'],
+ 'remove': ['owner'],
+ 'update': ['owner']
+ }
+ if action not in ['add', 'remove', 'update']:
+ raise InvalidActionError("Invalid action.")
+
+ if operator.id == member.id:
+ raise CannotOperateSelfError("Cannot operate self.")
+
+ ta_operator = TenantAccountJoin.query.filter_by(
+ tenant_id=tenant.id,
+ account_id=operator.id
+ ).first()
+
+ if not ta_operator or ta_operator.role not in perms[action]:
+ raise NoPermissionError(f'No permission to {action} member.')
+
+ @staticmethod
+ def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
+ """Remove member from tenant"""
+ # todo: check permission
+
+ if operator.id == account.id and TenantService.check_member_permission(tenant, operator, account, 'remove'):
+ raise CannotOperateSelfError("Cannot operate self.")
+
+ ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
+ if not ta:
+ raise MemberNotInTenantError("Member not in tenant.")
+
+ db.session.delete(ta)
+ db.session.commit()
+
+ @staticmethod
+ def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
+ """Update member role"""
+ TenantService.check_member_permission(tenant, operator, member, 'update')
+
+ target_member_join = TenantAccountJoin.query.filter_by(
+ tenant_id=tenant.id,
+ account_id=member.id
+ ).first()
+
+ if target_member_join.role == new_role:
+ raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
+
+ if new_role == 'owner':
+ # Find the current owner and change their role to 'admin'
+ current_owner_join = TenantAccountJoin.query.filter_by(
+ tenant_id=tenant.id,
+ role='owner'
+ ).first()
+ current_owner_join.role = 'admin'
+
+ # Update the role of the target member
+ target_member_join.role = new_role
+ db.session.commit()
+
+ @staticmethod
+ def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
+ """Dissolve tenant"""
+ if not TenantService.check_member_permission(tenant, operator, operator, 'remove'):
+ raise NoPermissionError('No permission to dissolve tenant.')
+ db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
+ db.session.delete(tenant)
+ db.session.commit()
+
+
+class RegisterService:
+
+ @staticmethod
+ def register(email, name, password: str = None, open_id: str = None, provider: str = None) -> Account:
+ db.session.begin_nested()
+ """Register account"""
+ try:
+ account = AccountService.create_account(email, name, password)
+ account.status = AccountStatus.ACTIVE.value
+ account.initialized_at = datetime.utcnow()
+
+ if open_id is not None or provider is not None:
+ AccountService.link_account_integrate(provider, open_id, account)
+
+ tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
+
+ TenantService.create_tenant_member(tenant, account, role='owner')
+ account.current_tenant = tenant
+
+ db.session.commit()
+ except Exception as e:
+ db.session.rollback() # todo: do not work
+ logging.error(f'Register failed: {e}')
+ raise AccountRegisterError(f'Registration failed: {e}') from e
+
+ tenant_was_created.send(tenant)
+
+ return account
+
+ @staticmethod
+ def invite_new_member(tenant: Tenant, email: str, role: str = 'normal',
+ inviter: Account = None) -> TenantAccountJoin:
+ """Invite new member"""
+ account = Account.query.filter_by(email=email).first()
+
+ if not account:
+ name = email.split('@')[0]
+ account = AccountService.create_account(email, name)
+ account.status = AccountStatus.PENDING.value
+ db.session.commit()
+ else:
+ TenantService.check_member_permission(tenant, inviter, account, 'add')
+ ta = TenantAccountJoin.query.filter_by(
+ tenant_id=tenant.id,
+ account_id=account.id
+ ).first()
+ if ta:
+ raise AccountAlreadyInTenantError("Account already in tenant.")
+
+ ta = TenantService.create_tenant_member(tenant, account, role)
+ return ta
diff --git a/api/services/app_model_config_service.py b/api/services/app_model_config_service.py
new file mode 100644
index 00000000000..70b63fbe19d
--- /dev/null
+++ b/api/services/app_model_config_service.py
@@ -0,0 +1,292 @@
+import re
+import uuid
+
+from core.constant import llm_constant
+from models.account import Account
+from services.dataset_service import DatasetService
+from services.errors.account import NoPermissionError
+
+
+class AppModelConfigService:
+ @staticmethod
+ def is_dataset_exists(account: Account, dataset_id: str) -> bool:
+ # verify if the dataset ID exists
+ dataset = DatasetService.get_dataset(dataset_id)
+
+ if not dataset:
+ return False
+
+ if dataset.tenant_id != account.current_tenant_id:
+ return False
+
+ return True
+
+ @staticmethod
+ def validate_model_completion_params(cp: dict, model_name: str) -> dict:
+ # 6. model.completion_params
+ if not isinstance(cp, dict):
+ raise ValueError("model.completion_params must be of object type")
+
+ # max_tokens
+ if 'max_tokens' not in cp:
+ cp["max_tokens"] = 512
+
+ if not isinstance(cp["max_tokens"], int) or cp["max_tokens"] <= 0 or cp["max_tokens"] > \
+ llm_constant.max_context_token_length[model_name]:
+ raise ValueError(
+ "max_tokens must be an integer greater than 0 and not exceeding the maximum value of the corresponding model")
+
+ # temperature
+ if 'temperature' not in cp:
+ cp["temperature"] = 1
+
+ if not isinstance(cp["temperature"], (float, int)) or cp["temperature"] < 0 or cp["temperature"] > 2:
+ raise ValueError("temperature must be a float between 0 and 2")
+
+ # top_p
+ if 'top_p' not in cp:
+ cp["top_p"] = 1
+
+ if not isinstance(cp["top_p"], (float, int)) or cp["top_p"] < 0 or cp["top_p"] > 2:
+ raise ValueError("top_p must be a float between 0 and 2")
+
+ # presence_penalty
+ if 'presence_penalty' not in cp:
+ cp["presence_penalty"] = 0
+
+ if not isinstance(cp["presence_penalty"], (float, int)) or cp["presence_penalty"] < -2 or cp["presence_penalty"] > 2:
+ raise ValueError("presence_penalty must be a float between -2 and 2")
+
+ # presence_penalty
+ if 'frequency_penalty' not in cp:
+ cp["frequency_penalty"] = 0
+
+ if not isinstance(cp["frequency_penalty"], (float, int)) or cp["frequency_penalty"] < -2 or cp["frequency_penalty"] > 2:
+ raise ValueError("frequency_penalty must be a float between -2 and 2")
+
+ # Filter out extra parameters
+ filtered_cp = {
+ "max_tokens": cp["max_tokens"],
+ "temperature": cp["temperature"],
+ "top_p": cp["top_p"],
+ "presence_penalty": cp["presence_penalty"],
+ "frequency_penalty": cp["frequency_penalty"]
+ }
+
+ return filtered_cp
+
+ @staticmethod
+ def validate_configuration(account: Account, config: dict, mode: str) -> dict:
+ # opening_statement
+ if 'opening_statement' not in config or not config["opening_statement"]:
+ config["opening_statement"] = ""
+
+ if not isinstance(config["opening_statement"], str):
+ raise ValueError("opening_statement must be of string type")
+
+ # suggested_questions
+ if 'suggested_questions' not in config or not config["suggested_questions"]:
+ config["suggested_questions"] = []
+
+ if not isinstance(config["suggested_questions"], list):
+ raise ValueError("suggested_questions must be of list type")
+
+ for question in config["suggested_questions"]:
+ if not isinstance(question, str):
+ raise ValueError("Elements in suggested_questions list must be of string type")
+
+ # suggested_questions_after_answer
+ if 'suggested_questions_after_answer' not in config or not config["suggested_questions_after_answer"]:
+ config["suggested_questions_after_answer"] = {
+ "enabled": False
+ }
+
+ if not isinstance(config["suggested_questions_after_answer"], dict):
+ raise ValueError("suggested_questions_after_answer must be of dict type")
+
+ if "enabled" not in config["suggested_questions_after_answer"] or not config["suggested_questions_after_answer"]["enabled"]:
+ config["suggested_questions_after_answer"]["enabled"] = False
+
+ if not isinstance(config["suggested_questions_after_answer"]["enabled"], bool):
+ raise ValueError("enabled in suggested_questions_after_answer must be of boolean type")
+
+ # more_like_this
+ if 'more_like_this' not in config or not config["more_like_this"]:
+ config["more_like_this"] = {
+ "enabled": False
+ }
+
+ if not isinstance(config["more_like_this"], dict):
+ raise ValueError("more_like_this must be of dict type")
+
+ if "enabled" not in config["more_like_this"] or not config["more_like_this"]["enabled"]:
+ config["more_like_this"]["enabled"] = False
+
+ if not isinstance(config["more_like_this"]["enabled"], bool):
+ raise ValueError("enabled in more_like_this must be of boolean type")
+
+ # model
+ if 'model' not in config:
+ raise ValueError("model is required")
+
+ if not isinstance(config["model"], dict):
+ raise ValueError("model must be of object type")
+
+ # model.provider
+ if 'provider' not in config["model"] or config["model"]["provider"] != "openai":
+ raise ValueError("model.provider must be 'openai'")
+
+ # model.name
+ if 'name' not in config["model"]:
+ raise ValueError("model.name is required")
+
+ if config["model"]["name"] not in llm_constant.models_by_mode[mode]:
+ raise ValueError("model.name must be in the specified model list")
+
+ # model.completion_params
+ if 'completion_params' not in config["model"]:
+ raise ValueError("model.completion_params is required")
+
+ config["model"]["completion_params"] = AppModelConfigService.validate_model_completion_params(
+ config["model"]["completion_params"],
+ config["model"]["name"]
+ )
+
+ # user_input_form
+ if "user_input_form" not in config or not config["user_input_form"]:
+ config["user_input_form"] = []
+
+ if not isinstance(config["user_input_form"], list):
+ raise ValueError("user_input_form must be a list of objects")
+
+ variables = []
+ for item in config["user_input_form"]:
+ key = list(item.keys())[0]
+ if key not in ["text-input", "select"]:
+ raise ValueError("Keys in user_input_form list can only be 'text-input' or 'select'")
+
+ form_item = item[key]
+ if 'label' not in form_item:
+ raise ValueError("label is required in user_input_form")
+
+ if not isinstance(form_item["label"], str):
+ raise ValueError("label in user_input_form must be of string type")
+
+ if 'variable' not in form_item:
+ raise ValueError("variable is required in user_input_form")
+
+ if not isinstance(form_item["variable"], str):
+ raise ValueError("variable in user_input_form must be of string type")
+
+ pattern = re.compile(r"^(?!\d)[\u4e00-\u9fa5A-Za-z0-9_\U0001F300-\U0001F64F\U0001F680-\U0001F6FF]{1,100}$")
+ if pattern.match(form_item["variable"]) is None:
+ raise ValueError("variable in user_input_form must be a string, "
+ "and cannot start with a number")
+
+ variables.append(form_item["variable"])
+
+ if 'required' not in form_item or not form_item["required"]:
+ form_item["required"] = False
+
+ if not isinstance(form_item["required"], bool):
+ raise ValueError("required in user_input_form must be of boolean type")
+
+ if key == "select":
+ if 'options' not in form_item or not form_item["options"]:
+ form_item["options"] = []
+
+ if not isinstance(form_item["options"], list):
+ raise ValueError("options in user_input_form must be a list of strings")
+
+ if "default" in form_item and form_item['default'] \
+ and form_item["default"] not in form_item["options"]:
+ raise ValueError("default value in user_input_form must be in the options list")
+
+ # pre_prompt
+ if "pre_prompt" not in config or not config["pre_prompt"]:
+ config["pre_prompt"] = ""
+
+ if not isinstance(config["pre_prompt"], str):
+ raise ValueError("pre_prompt must be of string type")
+
+ template_vars = re.findall(r"\{\{(\w+)\}\}", config["pre_prompt"])
+ for var in template_vars:
+ if var not in variables:
+ raise ValueError("Template variables in pre_prompt must be defined in user_input_form")
+
+ # agent_mode
+ if "agent_mode" not in config or not config["agent_mode"]:
+ config["agent_mode"] = {
+ "enabled": False,
+ "tools": []
+ }
+
+ if not isinstance(config["agent_mode"], dict):
+ raise ValueError("agent_mode must be of object type")
+
+ if "enabled" not in config["agent_mode"] or not config["agent_mode"]["enabled"]:
+ config["agent_mode"]["enabled"] = False
+
+ if not isinstance(config["agent_mode"]["enabled"], bool):
+ raise ValueError("enabled in agent_mode must be of boolean type")
+
+ if "tools" not in config["agent_mode"] or not config["agent_mode"]["tools"]:
+ config["agent_mode"]["tools"] = []
+
+ if not isinstance(config["agent_mode"]["tools"], list):
+ raise ValueError("tools in agent_mode must be a list of objects")
+
+ for tool in config["agent_mode"]["tools"]:
+ key = list(tool.keys())[0]
+ if key not in ["sensitive-word-avoidance", "dataset"]:
+ raise ValueError("Keys in agent_mode.tools list can only be 'sensitive-word-avoidance' or 'dataset'")
+
+ tool_item = tool[key]
+
+ if "enabled" not in tool_item or not tool_item["enabled"]:
+ tool_item["enabled"] = False
+
+ if not isinstance(tool_item["enabled"], bool):
+ raise ValueError("enabled in agent_mode.tools must be of boolean type")
+
+ if key == "sensitive-word-avoidance":
+ if "words" not in tool_item or not tool_item["words"]:
+ tool_item["words"] = ""
+
+ if not isinstance(tool_item["words"], str):
+ raise ValueError("words in sensitive-word-avoidance must be of string type")
+
+ if "canned_response" not in tool_item or not tool_item["canned_response"]:
+ tool_item["canned_response"] = ""
+
+ if not isinstance(tool_item["canned_response"], str):
+ raise ValueError("canned_response in sensitive-word-avoidance must be of string type")
+ elif key == "dataset":
+ if 'id' not in tool_item:
+ raise ValueError("id is required in dataset")
+
+ try:
+ uuid.UUID(tool_item["id"])
+ except ValueError:
+ raise ValueError("id in dataset must be of UUID type")
+
+ if not AppModelConfigService.is_dataset_exists(account, tool_item["id"]):
+ raise ValueError("Dataset ID does not exist, please check your permission.")
+
+ # Filter out extra parameters
+ filtered_config = {
+ "opening_statement": config["opening_statement"],
+ "suggested_questions": config["suggested_questions"],
+ "suggested_questions_after_answer": config["suggested_questions_after_answer"],
+ "more_like_this": config["more_like_this"],
+ "model": {
+ "provider": config["model"]["provider"],
+ "name": config["model"]["name"],
+ "completion_params": config["model"]["completion_params"]
+ },
+ "user_input_form": config["user_input_form"],
+ "pre_prompt": config["pre_prompt"],
+ "agent_mode": config["agent_mode"]
+ }
+
+ return filtered_config
diff --git a/api/services/completion_service.py b/api/services/completion_service.py
new file mode 100644
index 00000000000..f94cd23d3e1
--- /dev/null
+++ b/api/services/completion_service.py
@@ -0,0 +1,506 @@
+import json
+import logging
+import threading
+import time
+import uuid
+from typing import Generator, Union, Any
+
+from flask import current_app, Flask
+from redis.client import PubSub
+from sqlalchemy import and_
+
+from core.completion import Completion
+from core.conversation_message_task import PubHandler, ConversationTaskStoppedException
+from core.llm.error import LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError, LLMRateLimitError, \
+ LLMAuthorizationError, ProviderTokenNotInitError, QuotaExceededError, ModelCurrentlyNotSupportError
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.model import Conversation, AppModelConfig, App, Account, EndUser, Message
+from services.app_model_config_service import AppModelConfigService
+from services.errors.app import MoreLikeThisDisabledError
+from services.errors.app_model_config import AppModelConfigBrokenError
+from services.errors.completion import CompletionStoppedError
+from services.errors.conversation import ConversationNotExistsError, ConversationCompletedError
+from services.errors.message import MessageNotExistsError
+
+
+class CompletionService:
+
+ @classmethod
+ def completion(cls, app_model: App, user: Union[Account | EndUser], args: Any,
+ from_source: str, streaming: bool = True,
+ is_model_config_override: bool = False) -> Union[dict | Generator]:
+ # is streaming mode
+ inputs = args['inputs']
+ query = args['query']
+ conversation_id = args['conversation_id'] if 'conversation_id' in args else None
+
+ conversation = None
+ if conversation_id:
+ conversation_filter = [
+ Conversation.id == args['conversation_id'],
+ Conversation.app_id == app_model.id,
+ Conversation.status == 'normal'
+ ]
+
+ if from_source == 'console':
+ conversation_filter.append(Conversation.from_account_id == user.id)
+ else:
+ conversation_filter.append(Conversation.from_end_user_id == user.id if user else None)
+
+ conversation = db.session.query(Conversation).filter(and_(*conversation_filter)).first()
+
+ if not conversation:
+ raise ConversationNotExistsError()
+
+ if conversation.status != 'normal':
+ raise ConversationCompletedError()
+
+ if not conversation.override_model_configs:
+ app_model_config = db.session.query(AppModelConfig).get(conversation.app_model_config_id)
+
+ if not app_model_config:
+ raise AppModelConfigBrokenError()
+ else:
+ conversation_override_model_configs = json.loads(conversation.override_model_configs)
+ app_model_config = AppModelConfig(
+ id=conversation.app_model_config_id,
+ app_id=app_model.id,
+ provider="",
+ model_id="",
+ configs="",
+ opening_statement=conversation_override_model_configs['opening_statement'],
+ suggested_questions=json.dumps(conversation_override_model_configs['suggested_questions']),
+ model=json.dumps(conversation_override_model_configs['model']),
+ user_input_form=json.dumps(conversation_override_model_configs['user_input_form']),
+ pre_prompt=conversation_override_model_configs['pre_prompt'],
+ agent_mode=json.dumps(conversation_override_model_configs['agent_mode']),
+ )
+
+ if is_model_config_override:
+ # build new app model config
+ if 'model' not in args['model_config']:
+ raise ValueError('model_config.model is required')
+
+ if 'completion_params' not in args['model_config']['model']:
+ raise ValueError('model_config.model.completion_params is required')
+
+ completion_params = AppModelConfigService.validate_model_completion_params(
+ cp=args['model_config']['model']['completion_params'],
+ model_name=app_model_config.model_dict["name"]
+ )
+
+ app_model_config_model = app_model_config.model_dict
+ app_model_config_model['completion_params'] = completion_params
+
+ app_model_config = AppModelConfig(
+ id=app_model_config.id,
+ app_id=app_model.id,
+ provider="",
+ model_id="",
+ configs="",
+ opening_statement=app_model_config.opening_statement,
+ suggested_questions=app_model_config.suggested_questions,
+ model=json.dumps(app_model_config_model),
+ user_input_form=app_model_config.user_input_form,
+ pre_prompt=app_model_config.pre_prompt,
+ agent_mode=app_model_config.agent_mode,
+ )
+ else:
+ if app_model.app_model_config_id is None:
+ raise AppModelConfigBrokenError()
+
+ app_model_config = app_model.app_model_config
+
+ if not app_model_config:
+ raise AppModelConfigBrokenError()
+
+ if is_model_config_override:
+ if not isinstance(user, Account):
+ raise Exception("Only account can override model config")
+
+ # validate config
+ model_config = AppModelConfigService.validate_configuration(
+ account=user,
+ config=args['model_config'],
+ mode=app_model.mode
+ )
+
+ app_model_config = AppModelConfig(
+ id=app_model_config.id,
+ app_id=app_model.id,
+ provider="",
+ model_id="",
+ configs="",
+ opening_statement=model_config['opening_statement'],
+ suggested_questions=json.dumps(model_config['suggested_questions']),
+ suggested_questions_after_answer=json.dumps(model_config['suggested_questions_after_answer']),
+ more_like_this=json.dumps(model_config['more_like_this']),
+ model=json.dumps(model_config['model']),
+ user_input_form=json.dumps(model_config['user_input_form']),
+ pre_prompt=model_config['pre_prompt'],
+ agent_mode=json.dumps(model_config['agent_mode']),
+ )
+
+ # clean input by app_model_config form rules
+ inputs = cls.get_cleaned_inputs(inputs, app_model_config)
+
+ generate_task_id = str(uuid.uuid4())
+
+ pubsub = redis_client.pubsub()
+ pubsub.subscribe(PubHandler.generate_channel_name(user, generate_task_id))
+
+ user = cls.get_real_user_instead_of_proxy_obj(user)
+
+ generate_worker_thread = threading.Thread(target=cls.generate_worker, kwargs={
+ 'flask_app': current_app._get_current_object(),
+ 'generate_task_id': generate_task_id,
+ 'app_model': app_model,
+ 'app_model_config': app_model_config,
+ 'query': query,
+ 'inputs': inputs,
+ 'user': user,
+ 'conversation': conversation,
+ 'streaming': streaming,
+ 'is_model_config_override': is_model_config_override
+ })
+
+ generate_worker_thread.start()
+
+ # wait for 5 minutes to close the thread
+ cls.countdown_and_close(generate_worker_thread, pubsub, user, generate_task_id)
+
+ return cls.compact_response(pubsub, streaming)
+
+ @classmethod
+ def get_real_user_instead_of_proxy_obj(cls, user: Union[Account, EndUser]):
+ if isinstance(user, Account):
+ user = db.session.query(Account).get(user.id)
+ elif isinstance(user, EndUser):
+ user = db.session.query(EndUser).get(user.id)
+ else:
+ raise Exception("Unknown user type")
+
+ return user
+
+ @classmethod
+ def generate_worker(cls, flask_app: Flask, generate_task_id: str, app_model: App, app_model_config: AppModelConfig,
+ query: str, inputs: dict, user: Union[Account, EndUser],
+ conversation: Conversation, streaming: bool, is_model_config_override: bool):
+ with flask_app.app_context():
+ try:
+ if conversation:
+ # fixed the state of the conversation object when it detached from the original session
+ conversation = db.session.query(Conversation).filter_by(id=conversation.id).first()
+
+ # run
+ Completion.generate(
+ task_id=generate_task_id,
+ app=app_model,
+ app_model_config=app_model_config,
+ query=query,
+ inputs=inputs,
+ user=user,
+ conversation=conversation,
+ streaming=streaming,
+ is_override=is_model_config_override,
+ )
+ except ConversationTaskStoppedException:
+ pass
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError,
+ ModelCurrentlyNotSupportError) as e:
+ db.session.rollback()
+ PubHandler.pub_error(user, generate_task_id, e)
+ except LLMAuthorizationError:
+ db.session.rollback()
+ PubHandler.pub_error(user, generate_task_id, LLMAuthorizationError('Incorrect API key provided'))
+ except Exception as e:
+ db.session.rollback()
+ logging.exception("Unknown Error in completion")
+ PubHandler.pub_error(user, generate_task_id, e)
+
+ @classmethod
+ def countdown_and_close(cls, worker_thread, pubsub, user, generate_task_id) -> threading.Thread:
+ # wait for 5 minutes to close the thread
+ timeout = 300
+
+ def close_pubsub():
+ sleep_iterations = 0
+ while sleep_iterations < timeout and worker_thread.is_alive():
+ time.sleep(1)
+ sleep_iterations += 1
+
+ if worker_thread.is_alive():
+ PubHandler.stop(user, generate_task_id)
+ try:
+ pubsub.close()
+ except:
+ pass
+
+ countdown_thread = threading.Thread(target=close_pubsub)
+ countdown_thread.start()
+
+ return countdown_thread
+
+ @classmethod
+ def generate_more_like_this(cls, app_model: App, user: Union[Account | EndUser],
+ message_id: str, streaming: bool = True) -> Union[dict | Generator]:
+ if not user:
+ raise ValueError('user cannot be None')
+
+ message = db.session.query(Message).filter(
+ Message.id == message_id,
+ Message.app_id == app_model.id,
+ Message.from_source == ('api' if isinstance(user, EndUser) else 'console'),
+ Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
+ Message.from_account_id == (user.id if isinstance(user, Account) else None),
+ ).first()
+
+ if not message:
+ raise MessageNotExistsError()
+
+ current_app_model_config = app_model.app_model_config
+ more_like_this = current_app_model_config.more_like_this_dict
+
+ if not current_app_model_config.more_like_this or more_like_this.get("enabled", False) is False:
+ raise MoreLikeThisDisabledError()
+
+ app_model_config = message.app_model_config
+
+ if message.override_model_configs:
+ override_model_configs = json.loads(message.override_model_configs)
+ pre_prompt = override_model_configs.get("pre_prompt", '')
+ elif app_model_config:
+ pre_prompt = app_model_config.pre_prompt
+ else:
+ raise AppModelConfigBrokenError()
+
+ generate_task_id = str(uuid.uuid4())
+
+ pubsub = redis_client.pubsub()
+ pubsub.subscribe(PubHandler.generate_channel_name(user, generate_task_id))
+
+ user = cls.get_real_user_instead_of_proxy_obj(user)
+
+ generate_worker_thread = threading.Thread(target=cls.generate_more_like_this_worker, kwargs={
+ 'flask_app': current_app._get_current_object(),
+ 'generate_task_id': generate_task_id,
+ 'app_model': app_model,
+ 'app_model_config': app_model_config,
+ 'message': message,
+ 'pre_prompt': pre_prompt,
+ 'user': user,
+ 'streaming': streaming
+ })
+
+ generate_worker_thread.start()
+
+ cls.countdown_and_close(generate_worker_thread, pubsub, user, generate_task_id)
+
+ return cls.compact_response(pubsub, streaming)
+
+ @classmethod
+ def generate_more_like_this_worker(cls, flask_app: Flask, generate_task_id: str, app_model: App,
+ app_model_config: AppModelConfig, message: Message, pre_prompt: str,
+ user: Union[Account, EndUser], streaming: bool):
+ with flask_app.app_context():
+ try:
+ # run
+ Completion.generate_more_like_this(
+ task_id=generate_task_id,
+ app=app_model,
+ user=user,
+ message=message,
+ pre_prompt=pre_prompt,
+ app_model_config=app_model_config,
+ streaming=streaming
+ )
+ except ConversationTaskStoppedException:
+ pass
+ except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
+ LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError,
+ ModelCurrentlyNotSupportError) as e:
+ db.session.rollback()
+ PubHandler.pub_error(user, generate_task_id, e)
+ except LLMAuthorizationError:
+ db.session.rollback()
+ PubHandler.pub_error(user, generate_task_id, LLMAuthorizationError('Incorrect API key provided'))
+ except Exception as e:
+ db.session.rollback()
+ logging.exception("Unknown Error in completion")
+ PubHandler.pub_error(user, generate_task_id, e)
+
+ @classmethod
+ def get_cleaned_inputs(cls, user_inputs: dict, app_model_config: AppModelConfig):
+ if user_inputs is None:
+ user_inputs = {}
+
+ filtered_inputs = {}
+
+ # Filter input variables from form configuration, handle required fields, default values, and option values
+ input_form_config = app_model_config.user_input_form_list
+ for config in input_form_config:
+ input_config = list(config.values())[0]
+ variable = input_config["variable"]
+
+ input_type = list(config.keys())[0]
+
+ if variable not in user_inputs or not user_inputs[variable]:
+ if "required" in input_config and input_config["required"]:
+ raise ValueError(f"{variable} is required in input form")
+ else:
+ filtered_inputs[variable] = input_config["default"] if "default" in input_config else ""
+ continue
+
+ value = user_inputs[variable]
+
+ if input_type == "select":
+ options = input_config["options"] if "options" in input_config else []
+ if value not in options:
+ raise ValueError(f"{variable} in input form must be one of the following: {options}")
+ else:
+ if 'max_length' in variable:
+ max_length = variable['max_length']
+ if len(value) > max_length:
+ raise ValueError(f'{variable} in input form must be less than {max_length} characters')
+
+ filtered_inputs[variable] = value
+
+ return filtered_inputs
+
+ @classmethod
+ def compact_response(cls, pubsub: PubSub, streaming: bool = False) -> Union[dict | Generator]:
+ generate_channel = list(pubsub.channels.keys())[0].decode('utf-8')
+ if not streaming:
+ try:
+ for message in pubsub.listen():
+ if message["type"] == "message":
+ result = message["data"].decode('utf-8')
+ result = json.loads(result)
+ if result.get('error'):
+ cls.handle_error(result)
+
+ return cls.get_message_response_data(result.get('data'))
+ except ValueError as e:
+ if e.args[0] != "I/O operation on closed file.": # ignore this error
+ raise CompletionStoppedError()
+ else:
+ logging.exception(e)
+ raise
+ finally:
+ try:
+ pubsub.unsubscribe(generate_channel)
+ except ConnectionError:
+ pass
+ else:
+ def generate() -> Generator:
+ try:
+ for message in pubsub.listen():
+ if message["type"] == "message":
+ result = message["data"].decode('utf-8')
+ result = json.loads(result)
+ if result.get('error'):
+ cls.handle_error(result)
+
+ event = result.get('event')
+ if event == "end":
+ logging.debug("{} finished".format(generate_channel))
+ break
+
+ if event == 'message':
+ yield "data: " + json.dumps(cls.get_message_response_data(result.get('data'))) + "\n\n"
+ elif event == 'chain':
+ yield "data: " + json.dumps(cls.get_chain_response_data(result.get('data'))) + "\n\n"
+ elif event == 'agent_thought':
+ yield "data: " + json.dumps(cls.get_agent_thought_response_data(result.get('data'))) + "\n\n"
+ except ValueError as e:
+ if e.args[0] != "I/O operation on closed file.": # ignore this error
+ logging.exception(e)
+ raise
+ finally:
+ try:
+ pubsub.unsubscribe(generate_channel)
+ except ConnectionError:
+ pass
+
+ return generate()
+
+ @classmethod
+ def get_message_response_data(cls, data: dict):
+ response_data = {
+ 'event': 'message',
+ 'task_id': data.get('task_id'),
+ 'id': data.get('message_id'),
+ 'answer': data.get('text'),
+ 'created_at': int(time.time())
+ }
+
+ if data.get('mode') == 'chat':
+ response_data['conversation_id'] = data.get('conversation_id')
+
+ return response_data
+
+ @classmethod
+ def get_chain_response_data(cls, data: dict):
+ response_data = {
+ 'event': 'chain',
+ 'id': data.get('chain_id'),
+ 'task_id': data.get('task_id'),
+ 'message_id': data.get('message_id'),
+ 'type': data.get('type'),
+ 'input': data.get('input'),
+ 'output': data.get('output'),
+ 'created_at': int(time.time())
+ }
+
+ if data.get('mode') == 'chat':
+ response_data['conversation_id'] = data.get('conversation_id')
+
+ return response_data
+
+ @classmethod
+ def get_agent_thought_response_data(cls, data: dict):
+ response_data = {
+ 'event': 'agent_thought',
+ 'id': data.get('agent_thought_id'),
+ 'chain_id': data.get('chain_id'),
+ 'task_id': data.get('task_id'),
+ 'message_id': data.get('message_id'),
+ 'position': data.get('position'),
+ 'thought': data.get('thought'),
+ 'tool': data.get('tool'), # todo use real dataset obj replace it
+ 'tool_input': data.get('tool_input'),
+ 'observation': data.get('observation'),
+ 'answer': data.get('answer') if not data.get('thought') else '',
+ 'created_at': int(time.time())
+ }
+
+ if data.get('mode') == 'chat':
+ response_data['conversation_id'] = data.get('conversation_id')
+
+ return response_data
+
+ @classmethod
+ def handle_error(cls, result: dict):
+ logging.debug("error: %s", result)
+ error = result.get('error')
+ description = result.get('description')
+
+ # handle errors
+ llm_errors = {
+ 'LLMBadRequestError': LLMBadRequestError,
+ 'LLMAPIConnectionError': LLMAPIConnectionError,
+ 'LLMAPIUnavailableError': LLMAPIUnavailableError,
+ 'LLMRateLimitError': LLMRateLimitError,
+ 'ProviderTokenNotInitError': ProviderTokenNotInitError,
+ 'QuotaExceededError': QuotaExceededError,
+ 'ModelCurrentlyNotSupportError': ModelCurrentlyNotSupportError
+ }
+
+ if error in llm_errors:
+ raise llm_errors[error](description)
+ elif error == 'LLMAuthorizationError':
+ raise LLMAuthorizationError('Incorrect API key provided')
+ else:
+ raise Exception(description)
diff --git a/api/services/conversation_service.py b/api/services/conversation_service.py
new file mode 100644
index 00000000000..968209c71ee
--- /dev/null
+++ b/api/services/conversation_service.py
@@ -0,0 +1,94 @@
+from typing import Union, Optional
+
+from libs.infinite_scroll_pagination import InfiniteScrollPagination
+from extensions.ext_database import db
+from models.account import Account
+from models.model import Conversation, App, EndUser
+from services.errors.conversation import ConversationNotExistsError, LastConversationNotExistsError
+
+
+class ConversationService:
+ @classmethod
+ def pagination_by_last_id(cls, app_model: App, user: Optional[Union[Account | EndUser]],
+ last_id: Optional[str], limit: int,
+ include_ids: Optional[list] = None, exclude_ids: Optional[list] = None) -> InfiniteScrollPagination:
+ if not user:
+ return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
+
+ base_query = db.session.query(Conversation).filter(
+ Conversation.app_id == app_model.id,
+ Conversation.from_source == ('api' if isinstance(user, EndUser) else 'console'),
+ Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
+ Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
+ )
+
+ if include_ids is not None:
+ base_query = base_query.filter(Conversation.id.in_(include_ids))
+
+ if exclude_ids is not None:
+ base_query = base_query.filter(~Conversation.id.in_(exclude_ids))
+
+ if last_id:
+ last_conversation = base_query.filter(
+ Conversation.id == last_id,
+ ).first()
+
+ if not last_conversation:
+ raise LastConversationNotExistsError()
+
+ conversations = base_query.filter(
+ Conversation.created_at < last_conversation.created_at,
+ Conversation.id != last_conversation.id
+ ).order_by(Conversation.created_at.desc()).limit(limit).all()
+ else:
+ conversations = base_query.order_by(Conversation.created_at.desc()).limit(limit).all()
+
+ has_more = False
+ if len(conversations) == limit:
+ current_page_first_conversation = conversations[-1]
+ rest_count = base_query.filter(
+ Conversation.created_at < current_page_first_conversation.created_at,
+ Conversation.id != current_page_first_conversation.id
+ ).count()
+
+ if rest_count > 0:
+ has_more = True
+
+ return InfiniteScrollPagination(
+ data=conversations,
+ limit=limit,
+ has_more=has_more
+ )
+
+ @classmethod
+ def rename(cls, app_model: App, conversation_id: str,
+ user: Optional[Union[Account | EndUser]], name: str):
+ conversation = cls.get_conversation(app_model, conversation_id, user)
+
+ conversation.name = name
+ db.session.commit()
+
+ return conversation
+
+ @classmethod
+ def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account | EndUser]]):
+ conversation = db.session.query(Conversation) \
+ .filter(
+ Conversation.id == conversation_id,
+ Conversation.app_id == app_model.id,
+ Conversation.from_source == ('api' if isinstance(user, EndUser) else 'console'),
+ Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
+ Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
+ ).first()
+
+ if not conversation:
+ raise ConversationNotExistsError()
+
+ return conversation
+
+ @classmethod
+ def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account | EndUser]]):
+ conversation = cls.get_conversation(app_model, conversation_id, user)
+
+ db.session.delete(conversation)
+ db.session.commit()
diff --git a/api/services/dataset_service.py b/api/services/dataset_service.py
new file mode 100644
index 00000000000..39004c34375
--- /dev/null
+++ b/api/services/dataset_service.py
@@ -0,0 +1,521 @@
+import json
+import logging
+import datetime
+import time
+import random
+from typing import Optional
+from extensions.ext_redis import redis_client
+from flask_login import current_user
+
+from core.index.index_builder import IndexBuilder
+from events.dataset_event import dataset_was_deleted
+from events.document_event import document_was_deleted
+from extensions.ext_database import db
+from models.account import Account
+from models.dataset import Dataset, Document, DatasetQuery, DatasetProcessRule, AppDatasetJoin
+from models.model import UploadFile
+from services.errors.account import NoPermissionError
+from services.errors.dataset import DatasetNameDuplicateError
+from services.errors.document import DocumentIndexingError
+from services.errors.file import FileNotExistsError
+from tasks.document_indexing_task import document_indexing_task
+
+
+class DatasetService:
+
+ @staticmethod
+ def get_datasets(page, per_page, provider="vendor", tenant_id=None, user=None):
+ if user:
+ permission_filter = db.or_(Dataset.created_by == user.id,
+ Dataset.permission == 'all_team_members')
+ else:
+ permission_filter = Dataset.permission == 'all_team_members'
+ datasets = Dataset.query.filter(
+ db.and_(Dataset.provider == provider, Dataset.tenant_id == tenant_id, permission_filter)) \
+ .paginate(
+ page=page,
+ per_page=per_page,
+ max_per_page=100,
+ error_out=False
+ )
+
+ return datasets.items, datasets.total
+
+ @staticmethod
+ def get_process_rules(dataset_id):
+ # get the latest process rule
+ dataset_process_rule = db.session.query(DatasetProcessRule). \
+ filter(DatasetProcessRule.dataset_id == dataset_id). \
+ order_by(DatasetProcessRule.created_at.desc()). \
+ limit(1). \
+ one_or_none()
+ if dataset_process_rule:
+ mode = dataset_process_rule.mode
+ rules = dataset_process_rule.rules_dict
+ else:
+ mode = DocumentService.DEFAULT_RULES['mode']
+ rules = DocumentService.DEFAULT_RULES['rules']
+ return {
+ 'mode': mode,
+ 'rules': rules
+ }
+
+ @staticmethod
+ def get_datasets_by_ids(ids, tenant_id):
+ datasets = Dataset.query.filter(Dataset.id.in_(ids),
+ Dataset.tenant_id == tenant_id).paginate(
+ page=1, per_page=len(ids), max_per_page=len(ids), error_out=False)
+ return datasets.items, datasets.total
+
+ @staticmethod
+ def create_empty_dataset(tenant_id: str, name: str, indexing_technique: Optional[str], account: Account):
+ # check if dataset name already exists
+ if Dataset.query.filter_by(name=name, tenant_id=tenant_id).first():
+ raise DatasetNameDuplicateError(
+ f'Dataset with name {name} already exists.')
+
+ dataset = Dataset(name=name, indexing_technique=indexing_technique, data_source_type='upload_file')
+ # dataset = Dataset(name=name, provider=provider, config=config)
+ dataset.created_by = account.id
+ dataset.updated_by = account.id
+ dataset.tenant_id = tenant_id
+ db.session.add(dataset)
+ db.session.commit()
+ return dataset
+
+ @staticmethod
+ def get_dataset(dataset_id):
+ dataset = Dataset.query.filter_by(
+ id=dataset_id
+ ).first()
+ if dataset is None:
+ return None
+ else:
+ return dataset
+
+ @staticmethod
+ def update_dataset(dataset_id, data, user):
+ dataset = DatasetService.get_dataset(dataset_id)
+ DatasetService.check_dataset_permission(dataset, user)
+
+ filtered_data = {k: v for k, v in data.items() if v is not None or k == 'description'}
+
+ filtered_data['updated_by'] = user.id
+ filtered_data['updated_at'] = datetime.datetime.now()
+
+ dataset.query.filter_by(id=dataset_id).update(filtered_data)
+
+ db.session.commit()
+
+ return dataset
+
+ @staticmethod
+ def delete_dataset(dataset_id, user):
+ # todo: cannot delete dataset if it is being processed
+
+ dataset = DatasetService.get_dataset(dataset_id)
+
+ if dataset is None:
+ return False
+
+ DatasetService.check_dataset_permission(dataset, user)
+
+ dataset_was_deleted.send(dataset)
+
+ db.session.delete(dataset)
+ db.session.commit()
+ return True
+
+ @staticmethod
+ def check_dataset_permission(dataset, user):
+ if dataset.tenant_id != user.current_tenant_id:
+ logging.debug(
+ f'User {user.id} does not have permission to access dataset {dataset.id}')
+ raise NoPermissionError(
+ 'You do not have permission to access this dataset.')
+ if dataset.permission == 'only_me' and dataset.created_by != user.id:
+ logging.debug(
+ f'User {user.id} does not have permission to access dataset {dataset.id}')
+ raise NoPermissionError(
+ 'You do not have permission to access this dataset.')
+
+ @staticmethod
+ def get_dataset_queries(dataset_id: str, page: int, per_page: int):
+ dataset_queries = DatasetQuery.query.filter_by(dataset_id=dataset_id) \
+ .order_by(db.desc(DatasetQuery.created_at)) \
+ .paginate(
+ page=page, per_page=per_page, max_per_page=100, error_out=False
+ )
+ return dataset_queries.items, dataset_queries.total
+
+ @staticmethod
+ def get_related_apps(dataset_id: str):
+ return AppDatasetJoin.query.filter(AppDatasetJoin.dataset_id == dataset_id) \
+ .order_by(db.desc(AppDatasetJoin.created_at)).all()
+
+
+class DocumentService:
+ DEFAULT_RULES = {
+ 'mode': 'custom',
+ 'rules': {
+ 'pre_processing_rules': [
+ {'id': 'remove_extra_spaces', 'enabled': True},
+ {'id': 'remove_urls_emails', 'enabled': False}
+ ],
+ 'segmentation': {
+ 'delimiter': '\n',
+ 'max_tokens': 500
+ }
+ }
+ }
+
+ DOCUMENT_METADATA_SCHEMA = {
+ "book": {
+ "title": str,
+ "language": str,
+ "author": str,
+ "publisher": str,
+ "publication_date": str,
+ "isbn": str,
+ "category": str,
+ },
+ "web_page": {
+ "title": str,
+ "url": str,
+ "language": str,
+ "publish_date": str,
+ "author/publisher": str,
+ "topic/keywords": str,
+ "description": str,
+ },
+ "paper": {
+ "title": str,
+ "language": str,
+ "author": str,
+ "publish_date": str,
+ "journal/conference_name": str,
+ "volume/issue/page_numbers": str,
+ "doi": str,
+ "topic/keywords": str,
+ "abstract": str,
+ },
+ "social_media_post": {
+ "platform": str,
+ "author/username": str,
+ "publish_date": str,
+ "post_url": str,
+ "topic/tags": str,
+ },
+ "wikipedia_entry": {
+ "title": str,
+ "language": str,
+ "web_page_url": str,
+ "last_edit_date": str,
+ "editor/contributor": str,
+ "summary/introduction": str,
+ },
+ "personal_document": {
+ "title": str,
+ "author": str,
+ "creation_date": str,
+ "last_modified_date": str,
+ "document_type": str,
+ "tags/category": str,
+ },
+ "business_document": {
+ "title": str,
+ "author": str,
+ "creation_date": str,
+ "last_modified_date": str,
+ "document_type": str,
+ "department/team": str,
+ },
+ "im_chat_log": {
+ "chat_platform": str,
+ "chat_participants/group_name": str,
+ "start_date": str,
+ "end_date": str,
+ "summary": str,
+ },
+ "synced_from_notion": {
+ "title": str,
+ "language": str,
+ "author/creator": str,
+ "creation_date": str,
+ "last_modified_date": str,
+ "notion_page_link": str,
+ "category/tags": str,
+ "description": str,
+ },
+ "synced_from_github": {
+ "repository_name": str,
+ "repository_description": str,
+ "repository_owner/organization": str,
+ "code_filename": str,
+ "code_file_path": str,
+ "programming_language": str,
+ "github_link": str,
+ "open_source_license": str,
+ "commit_date": str,
+ "commit_author": str
+ }
+ }
+
+ @staticmethod
+ def get_document(dataset_id: str, document_id: str) -> Optional[Document]:
+ document = db.session.query(Document).filter(
+ Document.id == document_id,
+ Document.dataset_id == dataset_id
+ ).first()
+
+ return document
+
+ @staticmethod
+ def get_document_file_detail(file_id: str):
+ file_detail = db.session.query(UploadFile). \
+ filter(UploadFile.id == file_id). \
+ one_or_none()
+ return file_detail
+
+ @staticmethod
+ def check_archived(document):
+ if document.archived:
+ return True
+ else:
+ return False
+
+ @staticmethod
+ def delete_document(document):
+ if document.indexing_status in ["parsing", "cleaning", "splitting", "indexing"]:
+ raise DocumentIndexingError()
+
+ # trigger document_was_deleted signal
+ document_was_deleted.send(document.id, dataset_id=document.dataset_id)
+
+ db.session.delete(document)
+ db.session.commit()
+
+ @staticmethod
+ def pause_document(document):
+ if document.indexing_status not in ["waiting", "parsing", "cleaning", "splitting", "indexing"]:
+ raise DocumentIndexingError()
+ # update document to be paused
+ document.is_paused = True
+ document.paused_by = current_user.id
+ document.paused_at = datetime.datetime.utcnow()
+
+ db.session.add(document)
+ db.session.commit()
+ # set document paused flag
+ indexing_cache_key = 'document_{}_is_paused'.format(document.id)
+ redis_client.setnx(indexing_cache_key, "True")
+
+ @staticmethod
+ def recover_document(document):
+ if not document.is_paused:
+ raise DocumentIndexingError()
+ # update document to be recover
+ document.is_paused = False
+ document.paused_by = current_user.id
+ document.paused_at = time.time()
+
+ db.session.add(document)
+ db.session.commit()
+ # delete paused flag
+ indexing_cache_key = 'document_{}_is_paused'.format(document.id)
+ redis_client.delete(indexing_cache_key)
+ # trigger async task
+ document_indexing_task.delay(document.dataset_id, document.id)
+
+ @staticmethod
+ def get_documents_position(dataset_id):
+ documents = Document.query.filter_by(dataset_id=dataset_id).all()
+ if documents:
+ return len(documents) + 1
+ else:
+ return 1
+
+ @staticmethod
+ def save_document_with_dataset_id(dataset: Dataset, document_data: dict,
+ account: Account, dataset_process_rule: Optional[DatasetProcessRule] = None,
+ created_from: str = 'web'):
+ if not dataset.indexing_technique:
+ if 'indexing_technique' not in document_data \
+ or document_data['indexing_technique'] not in Dataset.INDEXING_TECHNIQUE_LIST:
+ raise ValueError("Indexing technique is required")
+
+ dataset.indexing_technique = document_data["indexing_technique"]
+
+ if dataset.indexing_technique == 'high_quality':
+ IndexBuilder.get_default_service_context(dataset.tenant_id)
+
+ # save process rule
+ if not dataset_process_rule:
+ process_rule = document_data["process_rule"]
+ if process_rule["mode"] == "custom":
+ dataset_process_rule = DatasetProcessRule(
+ dataset_id=dataset.id,
+ mode=process_rule["mode"],
+ rules=json.dumps(process_rule["rules"]),
+ created_by=account.id
+ )
+ elif process_rule["mode"] == "automatic":
+ dataset_process_rule = DatasetProcessRule(
+ dataset_id=dataset.id,
+ mode=process_rule["mode"],
+ rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
+ created_by=account.id
+ )
+ db.session.add(dataset_process_rule)
+ db.session.commit()
+
+ file_name = ''
+ data_source_info = {}
+ if document_data["data_source"]["type"] == "upload_file":
+ file_id = document_data["data_source"]["info"]
+ file = db.session.query(UploadFile).filter(
+ UploadFile.tenant_id == dataset.tenant_id,
+ UploadFile.id == file_id
+ ).first()
+
+ # raise error if file not found
+ if not file:
+ raise FileNotExistsError()
+
+ file_name = file.name
+ data_source_info = {
+ "upload_file_id": file_id,
+ }
+
+ # save document
+ position = DocumentService.get_documents_position(dataset.id)
+ document = Document(
+ tenant_id=dataset.tenant_id,
+ dataset_id=dataset.id,
+ position=position,
+ data_source_type=document_data["data_source"]["type"],
+ data_source_info=json.dumps(data_source_info),
+ dataset_process_rule_id=dataset_process_rule.id,
+ batch=time.strftime('%Y%m%d%H%M%S') + str(random.randint(100000, 999999)),
+ name=file_name,
+ created_from=created_from,
+ created_by=account.id,
+ # created_api_request_id = db.Column(UUID, nullable=True)
+ )
+
+ db.session.add(document)
+ db.session.commit()
+
+ # trigger async task
+ document_indexing_task.delay(document.dataset_id, document.id)
+
+ return document
+
+ @staticmethod
+ def save_document_without_dataset_id(tenant_id: str, document_data: dict, account: Account):
+ # save dataset
+ dataset = Dataset(
+ tenant_id=tenant_id,
+ name='',
+ data_source_type=document_data["data_source"]["type"],
+ indexing_technique=document_data["indexing_technique"],
+ created_by=account.id
+ )
+
+ db.session.add(dataset)
+ db.session.flush()
+
+ document = DocumentService.save_document_with_dataset_id(dataset, document_data, account)
+
+ cut_length = 18
+ cut_name = document.name[:cut_length]
+ dataset.name = cut_name + '...' if len(document.name) > cut_length else cut_name
+ dataset.description = 'useful for when you want to answer queries about the ' + document.name
+ db.session.commit()
+
+ return dataset, document
+
+ @classmethod
+ def document_create_args_validate(cls, args: dict):
+ if 'data_source' not in args or not args['data_source']:
+ raise ValueError("Data source is required")
+
+ if not isinstance(args['data_source'], dict):
+ raise ValueError("Data source is invalid")
+
+ if 'type' not in args['data_source'] or not args['data_source']['type']:
+ raise ValueError("Data source type is required")
+
+ if args['data_source']['type'] not in Document.DATA_SOURCES:
+ raise ValueError("Data source type is invalid")
+
+ if args['data_source']['type'] == 'upload_file':
+ if 'info' not in args['data_source'] or not args['data_source']['info']:
+ raise ValueError("Data source info is required")
+
+ if 'process_rule' not in args or not args['process_rule']:
+ raise ValueError("Process rule is required")
+
+ if not isinstance(args['process_rule'], dict):
+ raise ValueError("Process rule is invalid")
+
+ if 'mode' not in args['process_rule'] or not args['process_rule']['mode']:
+ raise ValueError("Process rule mode is required")
+
+ if args['process_rule']['mode'] not in DatasetProcessRule.MODES:
+ raise ValueError("Process rule mode is invalid")
+
+ if args['process_rule']['mode'] == 'automatic':
+ args['process_rule']['rules'] = {}
+ else:
+ if 'rules' not in args['process_rule'] or not args['process_rule']['rules']:
+ raise ValueError("Process rule rules is required")
+
+ if not isinstance(args['process_rule']['rules'], dict):
+ raise ValueError("Process rule rules is invalid")
+
+ if 'pre_processing_rules' not in args['process_rule']['rules'] \
+ or args['process_rule']['rules']['pre_processing_rules'] is None:
+ raise ValueError("Process rule pre_processing_rules is required")
+
+ if not isinstance(args['process_rule']['rules']['pre_processing_rules'], list):
+ raise ValueError("Process rule pre_processing_rules is invalid")
+
+ unique_pre_processing_rule_dicts = {}
+ for pre_processing_rule in args['process_rule']['rules']['pre_processing_rules']:
+ if 'id' not in pre_processing_rule or not pre_processing_rule['id']:
+ raise ValueError("Process rule pre_processing_rules id is required")
+
+ if pre_processing_rule['id'] not in DatasetProcessRule.PRE_PROCESSING_RULES:
+ raise ValueError("Process rule pre_processing_rules id is invalid")
+
+ if 'enabled' not in pre_processing_rule or pre_processing_rule['enabled'] is None:
+ raise ValueError("Process rule pre_processing_rules enabled is required")
+
+ if not isinstance(pre_processing_rule['enabled'], bool):
+ raise ValueError("Process rule pre_processing_rules enabled is invalid")
+
+ unique_pre_processing_rule_dicts[pre_processing_rule['id']] = pre_processing_rule
+
+ args['process_rule']['rules']['pre_processing_rules'] = list(unique_pre_processing_rule_dicts.values())
+
+ if 'segmentation' not in args['process_rule']['rules'] \
+ or args['process_rule']['rules']['segmentation'] is None:
+ raise ValueError("Process rule segmentation is required")
+
+ if not isinstance(args['process_rule']['rules']['segmentation'], dict):
+ raise ValueError("Process rule segmentation is invalid")
+
+ if 'separator' not in args['process_rule']['rules']['segmentation'] \
+ or not args['process_rule']['rules']['segmentation']['separator']:
+ raise ValueError("Process rule segmentation separator is required")
+
+ if not isinstance(args['process_rule']['rules']['segmentation']['separator'], str):
+ raise ValueError("Process rule segmentation separator is invalid")
+
+ if 'max_tokens' not in args['process_rule']['rules']['segmentation'] \
+ or not args['process_rule']['rules']['segmentation']['max_tokens']:
+ raise ValueError("Process rule segmentation max_tokens is required")
+
+ if not isinstance(args['process_rule']['rules']['segmentation']['max_tokens'], int):
+ raise ValueError("Process rule segmentation max_tokens is invalid")
diff --git a/api/services/errors/__init__.py b/api/services/errors/__init__.py
new file mode 100644
index 00000000000..fe77ca86b69
--- /dev/null
+++ b/api/services/errors/__init__.py
@@ -0,0 +1,7 @@
+# -*- coding:utf-8 -*-
+__all__ = [
+ 'base', 'conversation', 'message', 'index', 'app_model_config', 'account', 'document', 'dataset',
+ 'app', 'completion'
+]
+
+from . import *
diff --git a/api/services/errors/account.py b/api/services/errors/account.py
new file mode 100644
index 00000000000..14612eed757
--- /dev/null
+++ b/api/services/errors/account.py
@@ -0,0 +1,53 @@
+from services.errors.base import BaseServiceError
+
+
+class AccountNotFound(BaseServiceError):
+ pass
+
+
+class AccountRegisterError(BaseServiceError):
+ pass
+
+
+class AccountLoginError(BaseServiceError):
+ pass
+
+
+class AccountNotLinkTenantError(BaseServiceError):
+ pass
+
+
+class CurrentPasswordIncorrectError(BaseServiceError):
+ pass
+
+
+class LinkAccountIntegrateError(BaseServiceError):
+ pass
+
+
+class TenantNotFound(BaseServiceError):
+ pass
+
+
+class AccountAlreadyInTenantError(BaseServiceError):
+ pass
+
+
+class InvalidActionError(BaseServiceError):
+ pass
+
+
+class CannotOperateSelfError(BaseServiceError):
+ pass
+
+
+class NoPermissionError(BaseServiceError):
+ pass
+
+
+class MemberNotInTenantError(BaseServiceError):
+ pass
+
+
+class RoleAlreadyAssignedError(BaseServiceError):
+ pass
diff --git a/api/services/errors/app.py b/api/services/errors/app.py
new file mode 100644
index 00000000000..7c4ca99c2ae
--- /dev/null
+++ b/api/services/errors/app.py
@@ -0,0 +1,2 @@
+class MoreLikeThisDisabledError(Exception):
+ pass
diff --git a/api/services/errors/app_model_config.py b/api/services/errors/app_model_config.py
new file mode 100644
index 00000000000..c0669ed231a
--- /dev/null
+++ b/api/services/errors/app_model_config.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class AppModelConfigBrokenError(BaseServiceError):
+ pass
diff --git a/api/services/errors/base.py b/api/services/errors/base.py
new file mode 100644
index 00000000000..f5d41e17f11
--- /dev/null
+++ b/api/services/errors/base.py
@@ -0,0 +1,3 @@
+class BaseServiceError(Exception):
+ def __init__(self, description: str = None):
+ self.description = description
\ No newline at end of file
diff --git a/api/services/errors/completion.py b/api/services/errors/completion.py
new file mode 100644
index 00000000000..7fc50a588e6
--- /dev/null
+++ b/api/services/errors/completion.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class CompletionStoppedError(BaseServiceError):
+ pass
diff --git a/api/services/errors/conversation.py b/api/services/errors/conversation.py
new file mode 100644
index 00000000000..139dd9a70ae
--- /dev/null
+++ b/api/services/errors/conversation.py
@@ -0,0 +1,13 @@
+from services.errors.base import BaseServiceError
+
+
+class LastConversationNotExistsError(BaseServiceError):
+ pass
+
+
+class ConversationNotExistsError(BaseServiceError):
+ pass
+
+
+class ConversationCompletedError(Exception):
+ pass
diff --git a/api/services/errors/dataset.py b/api/services/errors/dataset.py
new file mode 100644
index 00000000000..254a70ffe31
--- /dev/null
+++ b/api/services/errors/dataset.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class DatasetNameDuplicateError(BaseServiceError):
+ pass
diff --git a/api/services/errors/document.py b/api/services/errors/document.py
new file mode 100644
index 00000000000..7327b9d032b
--- /dev/null
+++ b/api/services/errors/document.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class DocumentIndexingError(BaseServiceError):
+ pass
diff --git a/api/services/errors/file.py b/api/services/errors/file.py
new file mode 100644
index 00000000000..3674eca3e7a
--- /dev/null
+++ b/api/services/errors/file.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class FileNotExistsError(BaseServiceError):
+ pass
diff --git a/api/services/errors/index.py b/api/services/errors/index.py
new file mode 100644
index 00000000000..8513b6a55d1
--- /dev/null
+++ b/api/services/errors/index.py
@@ -0,0 +1,5 @@
+from services.errors.base import BaseServiceError
+
+
+class IndexNotInitializedError(BaseServiceError):
+ pass
diff --git a/api/services/errors/message.py b/api/services/errors/message.py
new file mode 100644
index 00000000000..969447df9f1
--- /dev/null
+++ b/api/services/errors/message.py
@@ -0,0 +1,17 @@
+from services.errors.base import BaseServiceError
+
+
+class FirstMessageNotExistsError(BaseServiceError):
+ pass
+
+
+class LastMessageNotExistsError(BaseServiceError):
+ pass
+
+
+class MessageNotExistsError(BaseServiceError):
+ pass
+
+
+class SuggestedQuestionsAfterAnswerDisabledError(BaseServiceError):
+ pass
diff --git a/api/services/hit_testing_service.py b/api/services/hit_testing_service.py
new file mode 100644
index 00000000000..619df1b8730
--- /dev/null
+++ b/api/services/hit_testing_service.py
@@ -0,0 +1,130 @@
+import logging
+import time
+from typing import List
+
+import numpy as np
+from llama_index.data_structs.node_v2 import NodeWithScore
+from llama_index.indices.query.schema import QueryBundle
+from llama_index.indices.vector_store import GPTVectorStoreIndexQuery
+from sklearn.manifold import TSNE
+
+from core.docstore.empty_docstore import EmptyDocumentStore
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from models.account import Account
+from models.dataset import Dataset, DocumentSegment, DatasetQuery
+from services.errors.index import IndexNotInitializedError
+
+
+class HitTestingService:
+ @classmethod
+ def retrieve(cls, dataset: Dataset, query: str, account: Account, limit: int = 10) -> dict:
+ index = VectorIndex(dataset=dataset).query_index
+
+ if not index:
+ raise IndexNotInitializedError()
+
+ index_query = GPTVectorStoreIndexQuery(
+ index_struct=index.index_struct,
+ service_context=index.service_context,
+ vector_store=index.query_context.get('vector_store'),
+ docstore=EmptyDocumentStore(),
+ response_synthesizer=None,
+ similarity_top_k=limit
+ )
+
+ query_bundle = QueryBundle(
+ query_str=query,
+ custom_embedding_strs=[query],
+ )
+
+ query_bundle.embedding = index.service_context.embed_model.get_agg_embedding_from_queries(
+ query_bundle.embedding_strs
+ )
+
+ start = time.perf_counter()
+ nodes = index_query.retrieve(query_bundle=query_bundle)
+ end = time.perf_counter()
+ logging.debug(f"Hit testing retrieve in {end - start:0.4f} seconds")
+
+ dataset_query = DatasetQuery(
+ dataset_id=dataset.id,
+ content=query,
+ source='hit_testing',
+ created_by_role='account',
+ created_by=account.id
+ )
+
+ db.session.add(dataset_query)
+ db.session.commit()
+
+ return cls.compact_retrieve_response(dataset, query_bundle, nodes)
+
+ @classmethod
+ def compact_retrieve_response(cls, dataset: Dataset, query_bundle: QueryBundle, nodes: List[NodeWithScore]):
+ embeddings = [
+ query_bundle.embedding
+ ]
+
+ for node in nodes:
+ embeddings.append(node.node.embedding)
+
+ tsne_position_data = cls.get_tsne_positions_from_embeddings(embeddings)
+
+ query_position = tsne_position_data.pop(0)
+
+ i = 0
+ records = []
+ for node in nodes:
+ index_node_id = node.node.doc_id
+
+ segment = db.session.query(DocumentSegment).filter(
+ DocumentSegment.dataset_id == dataset.id,
+ DocumentSegment.enabled == True,
+ DocumentSegment.status == 'completed',
+ DocumentSegment.index_node_id == index_node_id
+ ).first()
+
+ if not segment:
+ i += 1
+ continue
+
+ record = {
+ "segment": segment,
+ "score": node.score,
+ "tsne_position": tsne_position_data[i]
+ }
+
+ records.append(record)
+
+ i += 1
+
+ return {
+ "query": {
+ "content": query_bundle.query_str,
+ "tsne_position": query_position,
+ },
+ "records": records
+ }
+
+ @classmethod
+ def get_tsne_positions_from_embeddings(cls, embeddings: list):
+ embedding_length = len(embeddings)
+ if embedding_length <= 1:
+ return [{'x': 0, 'y': 0}]
+
+ concatenate_data = np.array(embeddings).reshape(embedding_length, -1)
+ # concatenate_data = np.concatenate(embeddings)
+
+ perplexity = embedding_length / 2 + 1
+ if perplexity >= embedding_length:
+ perplexity = max(embedding_length - 1, 1)
+
+ tsne = TSNE(n_components=2, perplexity=perplexity, early_exaggeration=12.0)
+ data_tsne = tsne.fit_transform(concatenate_data)
+
+ tsne_position_data = []
+ for i in range(len(data_tsne)):
+ tsne_position_data.append({'x': float(data_tsne[i][0]), 'y': float(data_tsne[i][1])})
+
+ return tsne_position_data
diff --git a/api/services/message_service.py b/api/services/message_service.py
new file mode 100644
index 00000000000..b59fb0f10cf
--- /dev/null
+++ b/api/services/message_service.py
@@ -0,0 +1,212 @@
+from typing import Optional, Union, List
+
+from core.completion import Completion
+from core.generator.llm_generator import LLMGenerator
+from libs.infinite_scroll_pagination import InfiniteScrollPagination
+from extensions.ext_database import db
+from models.account import Account
+from models.model import App, EndUser, Message, MessageFeedback
+from services.conversation_service import ConversationService
+from services.errors.message import FirstMessageNotExistsError, MessageNotExistsError, LastMessageNotExistsError, \
+ SuggestedQuestionsAfterAnswerDisabledError
+
+
+class MessageService:
+ @classmethod
+ def pagination_by_first_id(cls, app_model: App, user: Optional[Union[Account | EndUser]],
+ conversation_id: str, first_id: Optional[str], limit: int) -> InfiniteScrollPagination:
+ if not user:
+ return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
+
+ if not conversation_id:
+ return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
+
+ conversation = ConversationService.get_conversation(
+ app_model=app_model,
+ user=user,
+ conversation_id=conversation_id
+ )
+
+ if first_id:
+ first_message = db.session.query(Message) \
+ .filter(Message.conversation_id == conversation.id, Message.id == first_id).first()
+
+ if not first_message:
+ raise FirstMessageNotExistsError()
+
+ history_messages = db.session.query(Message).filter(
+ Message.conversation_id == conversation.id,
+ Message.created_at < first_message.created_at,
+ Message.id != first_message.id
+ ) \
+ .order_by(Message.created_at.desc()).limit(limit).all()
+ else:
+ history_messages = db.session.query(Message).filter(Message.conversation_id == conversation.id) \
+ .order_by(Message.created_at.desc()).limit(limit).all()
+
+ has_more = False
+ if len(history_messages) == limit:
+ current_page_first_message = history_messages[-1]
+ rest_count = db.session.query(Message).filter(
+ Message.conversation_id == conversation.id,
+ Message.created_at < current_page_first_message.created_at,
+ Message.id != current_page_first_message.id
+ ).count()
+
+ if rest_count > 0:
+ has_more = True
+
+ history_messages = list(reversed(history_messages))
+
+ return InfiniteScrollPagination(
+ data=history_messages,
+ limit=limit,
+ has_more=has_more
+ )
+
+ @classmethod
+ def pagination_by_last_id(cls, app_model: App, user: Optional[Union[Account | EndUser]],
+ last_id: Optional[str], limit: int, conversation_id: Optional[str] = None,
+ include_ids: Optional[list] = None) -> InfiniteScrollPagination:
+ if not user:
+ return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
+
+ base_query = db.session.query(Message)
+
+ if conversation_id is not None:
+ conversation = ConversationService.get_conversation(
+ app_model=app_model,
+ user=user,
+ conversation_id=conversation_id
+ )
+
+ base_query = base_query.filter(Message.conversation_id == conversation.id)
+
+ if include_ids is not None:
+ base_query = base_query.filter(Message.id.in_(include_ids))
+
+ if last_id:
+ last_message = base_query.filter(Message.id == last_id).first()
+
+ if not last_message:
+ raise LastMessageNotExistsError()
+
+ history_messages = base_query.filter(
+ Message.created_at < last_message.created_at,
+ Message.id != last_message.id
+ ).order_by(Message.created_at.desc()).limit(limit).all()
+ else:
+ history_messages = base_query.order_by(Message.created_at.desc()).limit(limit).all()
+
+ has_more = False
+ if len(history_messages) == limit:
+ current_page_first_message = history_messages[-1]
+ rest_count = base_query.filter(
+ Message.created_at < current_page_first_message.created_at,
+ Message.id != current_page_first_message.id
+ ).count()
+
+ if rest_count > 0:
+ has_more = True
+
+ return InfiniteScrollPagination(
+ data=history_messages,
+ limit=limit,
+ has_more=has_more
+ )
+
+ @classmethod
+ def create_feedback(cls, app_model: App, message_id: str, user: Optional[Union[Account | EndUser]],
+ rating: Optional[str]) -> MessageFeedback:
+ if not user:
+ raise ValueError('user cannot be None')
+
+ message = cls.get_message(
+ app_model=app_model,
+ user=user,
+ message_id=message_id
+ )
+
+ feedback = message.user_feedback
+
+ if not rating and feedback:
+ db.session.delete(feedback)
+ elif rating and feedback:
+ feedback.rating = rating
+ elif not rating and not feedback:
+ raise ValueError('rating cannot be None when feedback not exists')
+ else:
+ feedback = MessageFeedback(
+ app_id=app_model.id,
+ conversation_id=message.conversation_id,
+ message_id=message.id,
+ rating=rating,
+ from_source=('user' if isinstance(user, EndUser) else 'admin'),
+ from_end_user_id=(user.id if isinstance(user, EndUser) else None),
+ from_account_id=(user.id if isinstance(user, Account) else None),
+ )
+ db.session.add(feedback)
+
+ db.session.commit()
+
+ return feedback
+
+ @classmethod
+ def get_message(cls, app_model: App, user: Optional[Union[Account | EndUser]], message_id: str):
+ message = db.session.query(Message).filter(
+ Message.id == message_id,
+ Message.app_id == app_model.id,
+ Message.from_source == ('api' if isinstance(user, EndUser) else 'console'),
+ Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
+ Message.from_account_id == (user.id if isinstance(user, Account) else None),
+ ).first()
+
+ if not message:
+ raise MessageNotExistsError()
+
+ return message
+
+ @classmethod
+ def get_suggested_questions_after_answer(cls, app_model: App, user: Optional[Union[Account | EndUser]],
+ message_id: str, check_enabled: bool = True) -> List[Message]:
+ if not user:
+ raise ValueError('user cannot be None')
+
+ app_model_config = app_model.app_model_config
+ suggested_questions_after_answer = app_model_config.suggested_questions_after_answer_dict
+
+ if check_enabled and suggested_questions_after_answer.get("enabled", False) is False:
+ raise SuggestedQuestionsAfterAnswerDisabledError()
+
+ message = cls.get_message(
+ app_model=app_model,
+ user=user,
+ message_id=message_id
+ )
+
+ conversation = ConversationService.get_conversation(
+ app_model=app_model,
+ conversation_id=message.conversation_id,
+ user=user
+ )
+
+ # get memory of conversation (read-only)
+ memory = Completion.get_memory_from_conversation(
+ tenant_id=app_model.tenant_id,
+ app_model_config=app_model.app_model_config,
+ conversation=conversation,
+ max_token_limit=3000,
+ message_limit=3,
+ return_messages=False,
+ memory_key="histories"
+ )
+
+ external_context = memory.load_memory_variables({})
+
+ questions = LLMGenerator.generate_suggested_questions_after_answer(
+ tenant_id=app_model.tenant_id,
+ **external_context
+ )
+
+ return questions
+
diff --git a/api/services/provider_service.py b/api/services/provider_service.py
new file mode 100644
index 00000000000..7f6c7c93030
--- /dev/null
+++ b/api/services/provider_service.py
@@ -0,0 +1,96 @@
+from typing import Union
+
+from flask import current_app
+
+from core.llm.provider.llm_provider_service import LLMProviderService
+from models.account import Tenant
+from models.provider import *
+
+
+class ProviderService:
+
+ @staticmethod
+ def init_supported_provider(tenant, edition):
+ """Initialize the model provider, check whether the supported provider has a record"""
+
+ providers = Provider.query.filter_by(tenant_id=tenant.id).all()
+
+ openai_provider_exists = False
+ azure_openai_provider_exists = False
+
+ # TODO: The cloud version needs to construct the data of the SYSTEM type
+
+ for provider in providers:
+ if provider.provider_name == ProviderName.OPENAI.value and provider.provider_type == ProviderType.CUSTOM.value:
+ openai_provider_exists = True
+ if provider.provider_name == ProviderName.AZURE_OPENAI.value and provider.provider_type == ProviderType.CUSTOM.value:
+ azure_openai_provider_exists = True
+
+ # Initialize the model provider, check whether the supported provider has a record
+
+ # Create default providers if they don't exist
+ if not openai_provider_exists:
+ openai_provider = Provider(
+ tenant_id=tenant.id,
+ provider_name=ProviderName.OPENAI.value,
+ provider_type=ProviderType.CUSTOM.value,
+ is_valid=False
+ )
+ db.session.add(openai_provider)
+
+ if not azure_openai_provider_exists:
+ azure_openai_provider = Provider(
+ tenant_id=tenant.id,
+ provider_name=ProviderName.AZURE_OPENAI.value,
+ provider_type=ProviderType.CUSTOM.value,
+ is_valid=False
+ )
+ db.session.add(azure_openai_provider)
+
+ if not openai_provider_exists or not azure_openai_provider_exists:
+ db.session.commit()
+
+ @staticmethod
+ def get_obfuscated_api_key(tenant, provider_name: ProviderName):
+ llm_provider_service = LLMProviderService(tenant.id, provider_name.value)
+ return llm_provider_service.get_provider_configs(obfuscated=True)
+
+ @staticmethod
+ def get_token_type(tenant, provider_name: ProviderName):
+ llm_provider_service = LLMProviderService(tenant.id, provider_name.value)
+ return llm_provider_service.get_token_type()
+
+ @staticmethod
+ def validate_provider_configs(tenant, provider_name: ProviderName, configs: Union[dict | str]):
+ llm_provider_service = LLMProviderService(tenant.id, provider_name.value)
+ return llm_provider_service.config_validate(configs)
+
+ @staticmethod
+ def get_encrypted_token(tenant, provider_name: ProviderName, configs: Union[dict | str]):
+ llm_provider_service = LLMProviderService(tenant.id, provider_name.value)
+ return llm_provider_service.get_encrypted_token(configs)
+
+ @staticmethod
+ def create_system_provider(tenant: Tenant, provider_name: str = ProviderName.OPENAI.value,
+ is_valid: bool = True):
+ if current_app.config['EDITION'] != 'CLOUD':
+ return
+
+ provider = db.session.query(Provider).filter(
+ Provider.tenant_id == tenant.id,
+ Provider.provider_name == provider_name,
+ Provider.provider_type == ProviderType.SYSTEM.value
+ ).one_or_none()
+
+ if not provider:
+ provider = Provider(
+ tenant_id=tenant.id,
+ provider_name=provider_name,
+ provider_type=ProviderType.SYSTEM.value,
+ quota_type=ProviderQuotaType.TRIAL.value,
+ quota_limit=200,
+ encrypted_config='',
+ is_valid=is_valid,
+ )
+ db.session.add(provider)
+ db.session.commit()
diff --git a/api/services/saved_message_service.py b/api/services/saved_message_service.py
new file mode 100644
index 00000000000..1a68a1ba349
--- /dev/null
+++ b/api/services/saved_message_service.py
@@ -0,0 +1,66 @@
+from typing import Optional
+
+from libs.infinite_scroll_pagination import InfiniteScrollPagination
+from extensions.ext_database import db
+from models.model import App, EndUser
+from models.web import SavedMessage
+from services.message_service import MessageService
+
+
+class SavedMessageService:
+ @classmethod
+ def pagination_by_last_id(cls, app_model: App, end_user: Optional[EndUser],
+ last_id: Optional[str], limit: int) -> InfiniteScrollPagination:
+ saved_messages = db.session.query(SavedMessage).filter(
+ SavedMessage.app_id == app_model.id,
+ SavedMessage.created_by == end_user.id
+ ).order_by(SavedMessage.created_at.desc()).all()
+ message_ids = [sm.message_id for sm in saved_messages]
+
+ return MessageService.pagination_by_last_id(
+ app_model=app_model,
+ user=end_user,
+ last_id=last_id,
+ limit=limit,
+ include_ids=message_ids
+ )
+
+ @classmethod
+ def save(cls, app_model: App, user: Optional[EndUser], message_id: str):
+ saved_message = db.session.query(SavedMessage).filter(
+ SavedMessage.app_id == app_model.id,
+ SavedMessage.message_id == message_id,
+ SavedMessage.created_by == user.id
+ ).first()
+
+ if saved_message:
+ return
+
+ message = MessageService.get_message(
+ app_model=app_model,
+ user=user,
+ message_id=message_id
+ )
+
+ saved_message = SavedMessage(
+ app_id=app_model.id,
+ message_id=message.id,
+ created_by=user.id
+ )
+
+ db.session.add(saved_message)
+ db.session.commit()
+
+ @classmethod
+ def delete(cls, app_model: App, user: Optional[EndUser], message_id: str):
+ saved_message = db.session.query(SavedMessage).filter(
+ SavedMessage.app_id == app_model.id,
+ SavedMessage.message_id == message_id,
+ SavedMessage.created_by == user.id
+ ).first()
+
+ if not saved_message:
+ return
+
+ db.session.delete(saved_message)
+ db.session.commit()
diff --git a/api/services/web_conversation_service.py b/api/services/web_conversation_service.py
new file mode 100644
index 00000000000..5cfab25006c
--- /dev/null
+++ b/api/services/web_conversation_service.py
@@ -0,0 +1,74 @@
+from typing import Optional, Union
+
+from libs.infinite_scroll_pagination import InfiniteScrollPagination
+from extensions.ext_database import db
+from models.model import App, EndUser
+from models.web import PinnedConversation
+from services.conversation_service import ConversationService
+
+
+class WebConversationService:
+ @classmethod
+ def pagination_by_last_id(cls, app_model: App, end_user: Optional[EndUser],
+ last_id: Optional[str], limit: int, pinned: Optional[bool] = None) -> InfiniteScrollPagination:
+ include_ids = None
+ exclude_ids = None
+ if pinned is not None:
+ pinned_conversations = db.session.query(PinnedConversation).filter(
+ PinnedConversation.app_id == app_model.id,
+ PinnedConversation.created_by == end_user.id
+ ).order_by(PinnedConversation.created_at.desc()).all()
+ pinned_conversation_ids = [pc.conversation_id for pc in pinned_conversations]
+ if pinned:
+ include_ids = pinned_conversation_ids
+ else:
+ exclude_ids = pinned_conversation_ids
+
+ return ConversationService.pagination_by_last_id(
+ app_model=app_model,
+ user=end_user,
+ last_id=last_id,
+ limit=limit,
+ include_ids=include_ids,
+ exclude_ids=exclude_ids
+ )
+
+ @classmethod
+ def pin(cls, app_model: App, conversation_id: str, user: Optional[EndUser]):
+ pinned_conversation = db.session.query(PinnedConversation).filter(
+ PinnedConversation.app_id == app_model.id,
+ PinnedConversation.conversation_id == conversation_id,
+ PinnedConversation.created_by == user.id
+ ).first()
+
+ if pinned_conversation:
+ return
+
+ conversation = ConversationService.get_conversation(
+ app_model=app_model,
+ conversation_id=conversation_id,
+ user=user
+ )
+
+ pinned_conversation = PinnedConversation(
+ app_id=app_model.id,
+ conversation_id=conversation.id,
+ created_by=user.id
+ )
+
+ db.session.add(pinned_conversation)
+ db.session.commit()
+
+ @classmethod
+ def unpin(cls, app_model: App, conversation_id: str, user: Optional[EndUser]):
+ pinned_conversation = db.session.query(PinnedConversation).filter(
+ PinnedConversation.app_id == app_model.id,
+ PinnedConversation.conversation_id == conversation_id,
+ PinnedConversation.created_by == user.id
+ ).first()
+
+ if not pinned_conversation:
+ return
+
+ db.session.delete(pinned_conversation)
+ db.session.commit()
diff --git a/api/services/workspace_service.py b/api/services/workspace_service.py
new file mode 100644
index 00000000000..92227ffa7a8
--- /dev/null
+++ b/api/services/workspace_service.py
@@ -0,0 +1,49 @@
+from extensions.ext_database import db
+from models.account import Tenant
+from models.provider import Provider, ProviderType
+
+
+class WorkspaceService:
+ @classmethod
+ def get_tenant_info(cls, tenant: Tenant):
+ tenant_info = {
+ 'id': tenant.id,
+ 'name': tenant.name,
+ 'plan': tenant.plan,
+ 'status': tenant.status,
+ 'created_at': tenant.created_at,
+ 'providers': [],
+ 'in_trail': False,
+ 'trial_end_reason': 'using_custom'
+ }
+
+ # Get providers
+ providers = db.session.query(Provider).filter(
+ Provider.tenant_id == tenant.id
+ ).all()
+
+ # Add providers to the tenant info
+ tenant_info['providers'] = providers
+
+ custom_provider = None
+ system_provider = None
+
+ for provider in providers:
+ if provider.provider_type == ProviderType.CUSTOM.value:
+ if provider.is_valid and provider.encrypted_config:
+ custom_provider = provider
+ elif provider.provider_type == ProviderType.SYSTEM.value:
+ if provider.is_valid:
+ system_provider = provider
+
+ if system_provider and not custom_provider:
+ quota_used = system_provider.quota_used if system_provider.quota_used is not None else 0
+ quota_limit = system_provider.quota_limit if system_provider.quota_limit is not None else 0
+
+ if quota_used >= quota_limit:
+ tenant_info['trial_end_reason'] = 'trial_exceeded'
+ else:
+ tenant_info['in_trail'] = True
+ tenant_info['trial_end_reason'] = None
+
+ return tenant_info
diff --git a/api/tasks/add_document_to_index_task.py b/api/tasks/add_document_to_index_task.py
new file mode 100644
index 00000000000..9ea259227ea
--- /dev/null
+++ b/api/tasks/add_document_to_index_task.py
@@ -0,0 +1,99 @@
+import datetime
+import logging
+import time
+
+import click
+from celery import shared_task
+from llama_index.data_structs import Node
+from llama_index.data_structs.node_v2 import DocumentRelationship
+from werkzeug.exceptions import NotFound
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DocumentSegment, Document
+
+
+@shared_task
+def add_document_to_index_task(document_id: str):
+ """
+ Async Add document to index
+ :param document_id:
+
+ Usage: add_document_to_index.delay(document_id)
+ """
+ logging.info(click.style('Start add document to index: {}'.format(document_id), fg='green'))
+ start_at = time.perf_counter()
+
+ document = db.session.query(Document).filter(Document.id == document_id).first()
+ if not document:
+ raise NotFound('Document not found')
+
+ if document.indexing_status != 'completed':
+ return
+
+ indexing_cache_key = 'document_{}_indexing'.format(document.id)
+
+ try:
+ segments = db.session.query(DocumentSegment).filter(
+ DocumentSegment.document_id == document.id,
+ DocumentSegment.enabled == True
+ ) \
+ .order_by(DocumentSegment.position.asc()).all()
+
+ nodes = []
+ previous_node = None
+ for segment in segments:
+ relationships = {
+ DocumentRelationship.SOURCE: document.id
+ }
+
+ if previous_node:
+ relationships[DocumentRelationship.PREVIOUS] = previous_node.doc_id
+
+ previous_node.relationships[DocumentRelationship.NEXT] = segment.index_node_id
+
+ node = Node(
+ doc_id=segment.index_node_id,
+ doc_hash=segment.index_node_hash,
+ text=segment.content,
+ extra_info=None,
+ node_info=None,
+ relationships=relationships
+ )
+
+ previous_node = node
+
+ nodes.append(node)
+
+ dataset = document.dataset
+
+ if not dataset:
+ raise Exception('Document has no dataset')
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ # save vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.add_nodes(
+ nodes=nodes,
+ duplicate_check=True
+ )
+
+ # save keyword index
+ keyword_table_index.add_nodes(nodes)
+
+ end_at = time.perf_counter()
+ logging.info(
+ click.style('Document added to index: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
+ except Exception as e:
+ logging.exception("add document to index failed")
+ document.enabled = False
+ document.disabled_at = datetime.datetime.utcnow()
+ document.status = 'error'
+ document.error = str(e)
+ db.session.commit()
+ finally:
+ redis_client.delete(indexing_cache_key)
diff --git a/api/tasks/add_segment_to_index_task.py b/api/tasks/add_segment_to_index_task.py
new file mode 100644
index 00000000000..bd3cadfd3cd
--- /dev/null
+++ b/api/tasks/add_segment_to_index_task.py
@@ -0,0 +1,88 @@
+import datetime
+import logging
+import time
+
+import click
+from celery import shared_task
+from llama_index.data_structs import Node
+from llama_index.data_structs.node_v2 import DocumentRelationship
+from werkzeug.exceptions import NotFound
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DocumentSegment
+
+
+@shared_task
+def add_segment_to_index_task(segment_id: str):
+ """
+ Async Add segment to index
+ :param segment_id:
+
+ Usage: add_segment_to_index.delay(segment_id)
+ """
+ logging.info(click.style('Start add segment to index: {}'.format(segment_id), fg='green'))
+ start_at = time.perf_counter()
+
+ segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_id).first()
+ if not segment:
+ raise NotFound('Segment not found')
+
+ if segment.status != 'completed':
+ return
+
+ indexing_cache_key = 'segment_{}_indexing'.format(segment.id)
+
+ try:
+ relationships = {
+ DocumentRelationship.SOURCE: segment.document_id,
+ }
+
+ previous_segment = segment.previous_segment
+ if previous_segment:
+ relationships[DocumentRelationship.PREVIOUS] = previous_segment.index_node_id
+
+ next_segment = segment.next_segment
+ if next_segment:
+ relationships[DocumentRelationship.NEXT] = next_segment.index_node_id
+
+ node = Node(
+ doc_id=segment.index_node_id,
+ doc_hash=segment.index_node_hash,
+ text=segment.content,
+ extra_info=None,
+ node_info=None,
+ relationships=relationships
+ )
+
+ dataset = segment.dataset
+
+ if not dataset:
+ raise Exception('Segment has no dataset')
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ # save vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.add_nodes(
+ nodes=[node],
+ duplicate_check=True
+ )
+
+ # save keyword index
+ keyword_table_index.add_nodes([node])
+
+ end_at = time.perf_counter()
+ logging.info(click.style('Segment added to index: {} latency: {}'.format(segment.id, end_at - start_at), fg='green'))
+ except Exception as e:
+ logging.exception("add segment to index failed")
+ segment.enabled = False
+ segment.disabled_at = datetime.datetime.utcnow()
+ segment.status = 'error'
+ segment.error = str(e)
+ db.session.commit()
+ finally:
+ redis_client.delete(indexing_cache_key)
diff --git a/api/tasks/clean_dataset_task.py b/api/tasks/clean_dataset_task.py
new file mode 100644
index 00000000000..3c5ea8eb957
--- /dev/null
+++ b/api/tasks/clean_dataset_task.py
@@ -0,0 +1,77 @@
+import logging
+import time
+
+import click
+from celery import shared_task
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from models.dataset import DocumentSegment, Dataset, DatasetKeywordTable, DatasetQuery, DatasetProcessRule, \
+ AppDatasetJoin
+
+
+@shared_task
+def clean_dataset_task(dataset_id: str, tenant_id: str, indexing_technique: str, index_struct: str):
+ """
+ Clean dataset when dataset deleted.
+ :param dataset_id: dataset id
+ :param tenant_id: tenant id
+ :param indexing_technique: indexing technique
+ :param index_struct: index struct dict
+
+ Usage: clean_dataset_task.delay(dataset_id, tenant_id, indexing_technique, index_struct)
+ """
+ logging.info(click.style('Start clean dataset when dataset deleted: {}'.format(dataset_id), fg='green'))
+ start_at = time.perf_counter()
+
+ try:
+ dataset = Dataset(
+ id=dataset_id,
+ tenant_id=tenant_id,
+ indexing_technique=indexing_technique,
+ index_struct=index_struct
+ )
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ documents = db.session.query(DocumentSegment).filter(DocumentSegment.dataset_id == dataset_id).all()
+ index_doc_ids = [document.id for document in documents]
+ segments = db.session.query(DocumentSegment).filter(DocumentSegment.dataset_id == dataset_id).all()
+ index_node_ids = [segment.index_node_id for segment in segments]
+
+ # delete from vector index
+ if dataset.indexing_technique == "high_quality":
+ for index_doc_id in index_doc_ids:
+ try:
+ vector_index.del_doc(index_doc_id)
+ except Exception:
+ logging.exception("Delete doc index failed when dataset deleted.")
+ continue
+
+ # delete from keyword index
+ if index_node_ids:
+ try:
+ keyword_table_index.del_nodes(index_node_ids)
+ except Exception:
+ logging.exception("Delete nodes index failed when dataset deleted.")
+
+ for document in documents:
+ db.session.delete(document)
+
+ for segment in segments:
+ db.session.delete(segment)
+
+ db.session.query(DatasetKeywordTable).filter(DatasetKeywordTable.dataset_id == dataset_id).delete()
+ db.session.query(DatasetProcessRule).filter(DatasetProcessRule.dataset_id == dataset_id).delete()
+ db.session.query(DatasetQuery).filter(DatasetQuery.dataset_id == dataset_id).delete()
+ db.session.query(AppDatasetJoin).filter(AppDatasetJoin.dataset_id == dataset_id).delete()
+
+ db.session.commit()
+
+ end_at = time.perf_counter()
+ logging.info(
+ click.style('Cleaned dataset when dataset deleted: {} latency: {}'.format(dataset_id, end_at - start_at), fg='green'))
+ except Exception:
+ logging.exception("Cleaned dataset when dataset deleted failed")
diff --git a/api/tasks/clean_document_task.py b/api/tasks/clean_document_task.py
new file mode 100644
index 00000000000..5ca7f2d5c29
--- /dev/null
+++ b/api/tasks/clean_document_task.py
@@ -0,0 +1,52 @@
+import logging
+import time
+
+import click
+from celery import shared_task
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from models.dataset import DocumentSegment, Dataset
+
+
+@shared_task
+def clean_document_task(document_id: str, dataset_id: str):
+ """
+ Clean document when document deleted.
+ :param document_id: document id
+ :param dataset_id: dataset id
+
+ Usage: clean_document_task.delay(document_id, dataset_id)
+ """
+ logging.info(click.style('Start clean document when document deleted: {}'.format(document_id), fg='green'))
+ start_at = time.perf_counter()
+
+ try:
+ dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
+
+ if not dataset:
+ raise Exception('Document has no dataset')
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ segments = db.session.query(DocumentSegment).filter(DocumentSegment.document_id == document_id).all()
+ index_node_ids = [segment.index_node_id for segment in segments]
+
+ # delete from vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.del_nodes(index_node_ids)
+
+ # delete from keyword index
+ if index_node_ids:
+ keyword_table_index.del_nodes(index_node_ids)
+
+ for segment in segments:
+ db.session.delete(segment)
+
+ end_at = time.perf_counter()
+ logging.info(
+ click.style('Cleaned document when document deleted: {} latency: {}'.format(document_id, end_at - start_at), fg='green'))
+ except Exception:
+ logging.exception("Cleaned document when document deleted failed")
diff --git a/api/tasks/document_indexing_task.py b/api/tasks/document_indexing_task.py
new file mode 100644
index 00000000000..59bbd4dc987
--- /dev/null
+++ b/api/tasks/document_indexing_task.py
@@ -0,0 +1,56 @@
+import datetime
+import logging
+import time
+
+import click
+from celery import shared_task
+from werkzeug.exceptions import NotFound
+
+from core.indexing_runner import IndexingRunner, DocumentIsPausedException
+from core.llm.error import ProviderTokenNotInitError
+from extensions.ext_database import db
+from models.dataset import Document
+
+
+@shared_task
+def document_indexing_task(dataset_id: str, document_id: str):
+ """
+ Async process document
+ :param dataset_id:
+ :param document_id:
+
+ Usage: document_indexing_task.delay(dataset_id, document_id)
+ """
+ logging.info(click.style('Start process document: {}'.format(document_id), fg='green'))
+ start_at = time.perf_counter()
+
+ document = db.session.query(Document).filter(
+ Document.id == document_id,
+ Document.dataset_id == dataset_id
+ ).first()
+
+ if not document:
+ raise NotFound('Document not found')
+
+ document.indexing_status = 'parsing'
+ document.processing_started_at = datetime.datetime.utcnow()
+ db.session.commit()
+
+ try:
+ indexing_runner = IndexingRunner()
+ indexing_runner.run(document)
+ end_at = time.perf_counter()
+ logging.info(click.style('Processed document: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
+ except DocumentIsPausedException:
+ logging.info(click.style('Document paused, document id: {}'.format(document.id), fg='yellow'))
+ except ProviderTokenNotInitError as e:
+ document.indexing_status = 'error'
+ document.error = str(e.description)
+ document.stopped_at = datetime.datetime.utcnow()
+ db.session.commit()
+ except Exception as e:
+ logging.exception("consume document failed")
+ document.indexing_status = 'error'
+ document.error = str(e)
+ document.stopped_at = datetime.datetime.utcnow()
+ db.session.commit()
diff --git a/api/tasks/generate_conversation_summary_task.py b/api/tasks/generate_conversation_summary_task.py
new file mode 100644
index 00000000000..b19576f6fc6
--- /dev/null
+++ b/api/tasks/generate_conversation_summary_task.py
@@ -0,0 +1,46 @@
+import logging
+import time
+
+import click
+from celery import shared_task
+from werkzeug.exceptions import NotFound
+
+from core.generator.llm_generator import LLMGenerator
+from extensions.ext_database import db
+from models.model import Conversation, Message
+
+
+@shared_task
+def generate_conversation_summary_task(conversation_id: str):
+ """
+ Async Generate conversation summary
+ :param conversation_id:
+
+ Usage: generate_conversation_summary_task.delay(conversation_id)
+ """
+ logging.info(click.style('Start generate conversation summary: {}'.format(conversation_id), fg='green'))
+ start_at = time.perf_counter()
+
+ conversation = db.session.query(Conversation).filter(Conversation.id == conversation_id).first()
+ if not conversation:
+ raise NotFound('Conversation not found')
+
+ try:
+ # get conversation messages count
+ history_message_count = conversation.message_count
+ if history_message_count >= 5:
+ app_model = conversation.app
+ if not app_model:
+ return
+
+ history_messages = db.session.query(Message).filter(Message.conversation_id == conversation.id) \
+ .order_by(Message.created_at.asc()).all()
+
+ conversation.summary = LLMGenerator.generate_conversation_summary(app_model.tenant_id, history_messages)
+ db.session.add(conversation)
+ db.session.commit()
+
+ end_at = time.perf_counter()
+ logging.info(click.style('Conversation summary generated: {} latency: {}'.format(conversation_id, end_at - start_at), fg='green'))
+ except Exception:
+ logging.exception("generate conversation summary failed")
diff --git a/api/tasks/recover_document_indexing_task.py b/api/tasks/recover_document_indexing_task.py
new file mode 100644
index 00000000000..c1a5d4336c7
--- /dev/null
+++ b/api/tasks/recover_document_indexing_task.py
@@ -0,0 +1,51 @@
+import datetime
+import logging
+import time
+
+import click
+from celery import shared_task
+from werkzeug.exceptions import NotFound
+
+from core.indexing_runner import IndexingRunner, DocumentIsPausedException
+from extensions.ext_database import db
+from models.dataset import Document
+
+
+@shared_task
+def recover_document_indexing_task(dataset_id: str, document_id: str):
+ """
+ Async recover document
+ :param dataset_id:
+ :param document_id:
+
+ Usage: recover_document_indexing_task.delay(dataset_id, document_id)
+ """
+ logging.info(click.style('Recover document: {}'.format(document_id), fg='green'))
+ start_at = time.perf_counter()
+
+ document = db.session.query(Document).filter(
+ Document.id == document_id,
+ Document.dataset_id == dataset_id
+ ).first()
+
+ if not document:
+ raise NotFound('Document not found')
+
+ try:
+ indexing_runner = IndexingRunner()
+ if document.indexing_status in ["waiting", "parsing", "cleaning"]:
+ indexing_runner.run(document)
+ elif document.indexing_status == "splitting":
+ indexing_runner.run_in_splitting_status(document)
+ elif document.indexing_status == "indexing":
+ indexing_runner.run_in_indexing_status(document)
+ end_at = time.perf_counter()
+ logging.info(click.style('Processed document: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
+ except DocumentIsPausedException:
+ logging.info(click.style('Document paused, document id: {}'.format(document.id), fg='yellow'))
+ except Exception as e:
+ logging.exception("consume document failed")
+ document.indexing_status = 'error'
+ document.error = str(e)
+ document.stopped_at = datetime.datetime.utcnow()
+ db.session.commit()
diff --git a/api/tasks/remove_document_from_index_task.py b/api/tasks/remove_document_from_index_task.py
new file mode 100644
index 00000000000..3dc6f9cd77f
--- /dev/null
+++ b/api/tasks/remove_document_from_index_task.py
@@ -0,0 +1,63 @@
+import logging
+import time
+
+import click
+from celery import shared_task
+from werkzeug.exceptions import NotFound
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DocumentSegment, Document
+
+
+@shared_task
+def remove_document_from_index_task(document_id: str):
+ """
+ Async Remove document from index
+ :param document_id: document id
+
+ Usage: remove_document_from_index.delay(document_id)
+ """
+ logging.info(click.style('Start remove document segments from index: {}'.format(document_id), fg='green'))
+ start_at = time.perf_counter()
+
+ document = db.session.query(Document).filter(Document.id == document_id).first()
+ if not document:
+ raise NotFound('Document not found')
+
+ if document.indexing_status != 'completed':
+ return
+
+ indexing_cache_key = 'document_{}_indexing'.format(document.id)
+
+ try:
+ dataset = document.dataset
+
+ if not dataset:
+ raise Exception('Document has no dataset')
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ # delete from vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.del_doc(document.id)
+
+ # delete from keyword index
+ segments = db.session.query(DocumentSegment).filter(DocumentSegment.document_id == document.id).all()
+ index_node_ids = [segment.index_node_id for segment in segments]
+ if index_node_ids:
+ keyword_table_index.del_nodes(index_node_ids)
+
+ end_at = time.perf_counter()
+ logging.info(
+ click.style('Document removed from index: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
+ except Exception:
+ logging.exception("remove document from index failed")
+ if not document.archived:
+ document.enabled = True
+ db.session.commit()
+ finally:
+ redis_client.delete(indexing_cache_key)
diff --git a/api/tasks/remove_segment_from_index_task.py b/api/tasks/remove_segment_from_index_task.py
new file mode 100644
index 00000000000..48cebfc4d12
--- /dev/null
+++ b/api/tasks/remove_segment_from_index_task.py
@@ -0,0 +1,58 @@
+import logging
+import time
+
+import click
+from celery import shared_task
+from werkzeug.exceptions import NotFound
+
+from core.index.keyword_table_index import KeywordTableIndex
+from core.index.vector_index import VectorIndex
+from extensions.ext_database import db
+from extensions.ext_redis import redis_client
+from models.dataset import DocumentSegment
+
+
+@shared_task
+def remove_segment_from_index_task(segment_id: str):
+ """
+ Async Remove segment from index
+ :param segment_id:
+
+ Usage: remove_segment_from_index.delay(segment_id)
+ """
+ logging.info(click.style('Start remove segment from index: {}'.format(segment_id), fg='green'))
+ start_at = time.perf_counter()
+
+ segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_id).first()
+ if not segment:
+ raise NotFound('Segment not found')
+
+ if segment.status != 'completed':
+ return
+
+ indexing_cache_key = 'segment_{}_indexing'.format(segment.id)
+
+ try:
+ dataset = segment.dataset
+
+ if not dataset:
+ raise Exception('Segment has no dataset')
+
+ vector_index = VectorIndex(dataset=dataset)
+ keyword_table_index = KeywordTableIndex(dataset=dataset)
+
+ # delete from vector index
+ if dataset.indexing_technique == "high_quality":
+ vector_index.del_nodes([segment.index_node_id])
+
+ # delete from keyword index
+ keyword_table_index.del_nodes([segment.index_node_id])
+
+ end_at = time.perf_counter()
+ logging.info(click.style('Segment removed from index: {} latency: {}'.format(segment.id, end_at - start_at), fg='green'))
+ except Exception:
+ logging.exception("remove segment from index failed")
+ segment.enabled = True
+ db.session.commit()
+ finally:
+ redis_client.delete(indexing_cache_key)
diff --git a/api/tests/__init__.py b/api/tests/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/conftest.py b/api/tests/conftest.py
new file mode 100644
index 00000000000..48de037846d
--- /dev/null
+++ b/api/tests/conftest.py
@@ -0,0 +1,50 @@
+# -*- coding:utf-8 -*-
+
+import pytest
+import flask_migrate
+
+from app import create_app
+from extensions.ext_database import db
+
+
[email protected](scope='module')
+def test_client():
+ # Create a Flask app configured for testing
+ from config import TestConfig
+ flask_app = create_app(TestConfig())
+ flask_app.config.from_object('config.TestingConfig')
+
+ # Create a test client using the Flask application configured for testing
+ with flask_app.test_client() as testing_client:
+ # Establish an application context
+ with flask_app.app_context():
+ yield testing_client # this is where the testing happens!
+
+
[email protected](scope='module')
+def init_database(test_client):
+ # Initialize the database
+ with test_client.application.app_context():
+ flask_migrate.upgrade()
+
+ yield # this is where the testing happens!
+
+ # Clean up the database
+ with test_client.application.app_context():
+ flask_migrate.downgrade()
+
+
[email protected](scope='module')
+def db_session(test_client):
+ with test_client.application.app_context():
+ yield db.session
+
+
[email protected](scope='function')
+def login_default_user(test_client):
+
+ # todo
+
+ yield # this is where the testing happens!
+
+ test_client.get('/logout', follow_redirects=True)
\ No newline at end of file
diff --git a/api/tests/test_controllers/__init__.py b/api/tests/test_controllers/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/test_controllers/test_account_api.py.bak b/api/tests/test_controllers/test_account_api.py.bak
new file mode 100644
index 00000000000..a73c796b789
--- /dev/null
+++ b/api/tests/test_controllers/test_account_api.py.bak
@@ -0,0 +1,75 @@
+import json
+import pytest
+from flask import url_for
+
+from models.model import Account
+
+# Sample user data for testing
+sample_user_data = {
+ 'name': 'Test User',
+ 'email': '[email protected]',
+ 'interface_language': 'en-US',
+ 'interface_theme': 'light',
+ 'timezone': 'America/New_York',
+ 'password': 'testpassword',
+ 'new_password': 'newtestpassword',
+ 'repeat_new_password': 'newtestpassword'
+}
+
+# Create a test user and log them in
[email protected](scope='function')
+def logged_in_user(client, session):
+ # Create test user and add them to the database
+ # Replace this with your actual User model and any required fields
+
+ # todo refer to api.controllers.setup.SetupApi.post() to create a user
+ db_user_data = sample_user_data.copy()
+ db_user_data['password_salt'] = 'testpasswordsalt'
+ del db_user_data['new_password']
+ del db_user_data['repeat_new_password']
+ test_user = Account(**db_user_data)
+ session.add(test_user)
+ session.commit()
+
+ # Log in the test user
+ client.post(url_for('console.loginapi'), data={'email': sample_user_data['email'], 'password': sample_user_data['password']})
+
+ return test_user
+
+def test_account_profile(logged_in_user, client):
+ response = client.get(url_for('console.accountprofileapi'))
+ assert response.status_code == 200
+ assert json.loads(response.data)['name'] == sample_user_data['name']
+
+def test_account_name(logged_in_user, client):
+ new_name = 'New Test User'
+ response = client.post(url_for('console.accountnameapi'), json={'name': new_name})
+ assert response.status_code == 200
+ assert json.loads(response.data)['name'] == new_name
+
+def test_account_interface_language(logged_in_user, client):
+ new_language = 'zh-CN'
+ response = client.post(url_for('console.accountinterfacelanguageapi'), json={'interface_language': new_language})
+ assert response.status_code == 200
+ assert json.loads(response.data)['interface_language'] == new_language
+
+def test_account_interface_theme(logged_in_user, client):
+ new_theme = 'dark'
+ response = client.post(url_for('console.accountinterfacethemeapi'), json={'interface_theme': new_theme})
+ assert response.status_code == 200
+ assert json.loads(response.data)['interface_theme'] == new_theme
+
+def test_account_timezone(logged_in_user, client):
+ new_timezone = 'Asia/Shanghai'
+ response = client.post(url_for('console.accounttimezoneapi'), json={'timezone': new_timezone})
+ assert response.status_code == 200
+ assert json.loads(response.data)['timezone'] == new_timezone
+
+def test_account_password(logged_in_user, client):
+ response = client.post(url_for('console.accountpasswordapi'), json={
+ 'password': sample_user_data['password'],
+ 'new_password': sample_user_data['new_password'],
+ 'repeat_new_password': sample_user_data['repeat_new_password']
+ })
+ assert response.status_code == 200
+ assert json.loads(response.data)['result'] == 'success'
diff --git a/api/tests/test_controllers/test_login.py b/api/tests/test_controllers/test_login.py
new file mode 100644
index 00000000000..559e2f809ec
--- /dev/null
+++ b/api/tests/test_controllers/test_login.py
@@ -0,0 +1,108 @@
+import pytest
+from app import create_app, db
+from flask_login import current_user
+from models.model import Account, TenantAccountJoin, Tenant
+
+
+def client(test_client, db_session):
+ app = create_app()
+ app.config["TESTING"] = True
+ with app.app_context():
+ db.create_all()
+ yield test_client
+ db.drop_all()
+
+
+def test_login_api_post(client, db_session):
+ # create a tenant, account, and tenant account join
+ tenant = Tenant(name="Test Tenant", status="normal")
+ account = Account(email="[email protected]", name="Test User")
+ account.password_salt = "uQ7K0/0wUJ7VPhf3qBzwNQ=="
+ account.password = "A9YpfzjK7c/tOwzamrvpJg=="
+ db.session.add_all([tenant, account])
+ db.session.flush()
+ tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
+ db.session.add(tenant_account_join)
+ db.session.commit()
+
+ # login with correct credentials
+ response = client.post("/login", json={
+ "email": "[email protected]",
+ "password": "Abc123456",
+ "remember_me": True
+ })
+ assert response.status_code == 200
+ assert response.json == {"result": "success"}
+ assert current_user == account
+ assert 'tenant_id' in client.session
+ assert client.session['tenant_id'] == tenant.id
+
+ # login with incorrect password
+ response = client.post("/login", json={
+ "email": "[email protected]",
+ "password": "wrong_password",
+ "remember_me": True
+ })
+ assert response.status_code == 401
+
+ # login with non-existent account
+ response = client.post("/login", json={
+ "email": "[email protected]",
+ "password": "Abc123456",
+ "remember_me": True
+ })
+ assert response.status_code == 401
+
+
+def test_logout_api_get(client, db_session):
+ # create a tenant, account, and tenant account join
+ tenant = Tenant(name="Test Tenant", status="normal")
+ account = Account(email="[email protected]", name="Test User")
+ db.session.add_all([tenant, account])
+ db.session.flush()
+ tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
+ db.session.add(tenant_account_join)
+ db.session.commit()
+
+ # login and check if session variable and current_user are set
+ with client.session_transaction() as session:
+ session['tenant_id'] = tenant.id
+ client.post("/login", json={
+ "email": "[email protected]",
+ "password": "Abc123456",
+ "remember_me": True
+ })
+ assert current_user == account
+ assert 'tenant_id' in client.session
+ assert client.session['tenant_id'] == tenant.id
+
+ # logout and check if session variable and current_user are unset
+ response = client.get("/logout")
+ assert response.status_code == 200
+ assert current_user.is_authenticated is False
+ assert 'tenant_id' not in client.session
+
+
+def test_reset_password_api_get(client, db_session):
+ # create a tenant, account, and tenant account join
+ tenant = Tenant(name="Test Tenant", status="normal")
+ account = Account(email="[email protected]", name="Test User")
+ db.session.add_all([tenant, account])
+ db.session.flush()
+ tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
+ db.session.add(tenant_account_join)
+ db.session.commit()
+
+ # reset password in cloud edition
+ app = client.application
+ app.config["CLOUD_EDITION"] = True
+ response = client.get("/reset_password")
+ assert response.status_code == 200
+ assert response.json == {"result": "success"}
+
+ # reset password in non-cloud edition
+ app.config["CLOUD_EDITION"] = False
+ response = client.get("/reset_password")
+ assert response.status_code == 200
+ assert response.json == {"result": "success"}
diff --git a/api/tests/test_controllers/test_setup.py b/api/tests/test_controllers/test_setup.py
new file mode 100644
index 00000000000..96a9b0911ef
--- /dev/null
+++ b/api/tests/test_controllers/test_setup.py
@@ -0,0 +1,80 @@
+import os
+import pytest
+from models.model import Account, Tenant, TenantAccountJoin
+
+
+def test_setup_api_get(test_client,db_session):
+ response = test_client.get("/setup")
+ assert response.status_code == 200
+ assert response.json == {"step": "not_start"}
+
+ # create a tenant and check again
+ tenant = Tenant(name="Test Tenant", status="normal")
+ db_session.add(tenant)
+ db_session.commit()
+ response = test_client.get("/setup")
+ assert response.status_code == 200
+ assert response.json == {"step": "step2"}
+
+ # create setup file and check again
+ response = test_client.get("/setup")
+ assert response.status_code == 200
+ assert response.json == {"step": "finished"}
+
+
+def test_setup_api_post(test_client):
+ response = test_client.post("/setup", json={
+ "email": "[email protected]",
+ "name": "Test User",
+ "password": "Abc123456"
+ })
+ assert response.status_code == 200
+ assert response.json == {"result": "success", "next_step": "step2"}
+
+ # check if the tenant, account, and tenant account join records were created
+ tenant = Tenant.query.first()
+ assert tenant.name == "Test User's LLM Factory"
+ assert tenant.status == "normal"
+ assert tenant.encrypt_public_key
+
+ account = Account.query.first()
+ assert account.email == "[email protected]"
+ assert account.name == "Test User"
+ assert account.password_salt
+ assert account.password
+ assert TenantAccountJoin.query.filter_by(account_id=account.id, is_tenant_owner=True).count() == 1
+
+ # check if password is encrypted correctly
+ salt = account.password_salt.encode()
+ password_hashed = account.password.encode()
+ assert account.password == base64.b64encode(hash_password("Abc123456", salt)).decode()
+
+
+def test_setup_step2_api_post(test_client,db_session):
+ # create a tenant, account, and setup file
+ tenant = Tenant(name="Test Tenant", status="normal")
+ account = Account(email="[email protected]", name="Test User")
+ db_session.add_all([tenant, account])
+ db_session.commit()
+
+ # try to set up with incorrect language
+ response = test_client.post("/setup/step2", json={
+ "interface_language": "invalid_language",
+ "timezone": "Asia/Shanghai"
+ })
+ assert response.status_code == 400
+
+ # set up successfully
+ response = test_client.post("/setup/step2", json={
+ "interface_language": "en",
+ "timezone": "Asia/Shanghai"
+ })
+ assert response.status_code == 200
+ assert response.json == {"result": "success", "next_step": "finished"}
+
+ # check if account was updated correctly
+ account = Account.query.first()
+ assert account.interface_language == "en"
+ assert account.timezone == "Asia/Shanghai"
+ assert account.interface_theme == "light"
+ assert account.last_login_ip == "127.0.0.1"
diff --git a/api/tests/test_factory.py b/api/tests/test_factory.py
new file mode 100644
index 00000000000..0d73168b437
--- /dev/null
+++ b/api/tests/test_factory.py
@@ -0,0 +1,22 @@
+# -*- coding:utf-8 -*-
+
+import pytest
+
+from app import create_app
+
+def test_create_app():
+
+ # Test Default(CE) Config
+ app = create_app()
+
+ assert app.config['SECRET_KEY'] is not None
+ assert app.config['SQLALCHEMY_DATABASE_URI'] is not None
+ assert app.config['EDITION'] == "SELF_HOSTED"
+
+ # Test TestConfig
+ from config import TestConfig
+ test_app = create_app(TestConfig())
+
+ assert test_app.config['SECRET_KEY'] is not None
+ assert test_app.config['SQLALCHEMY_DATABASE_URI'] is not None
+ assert test_app.config['TESTING'] is True
\ No newline at end of file
diff --git a/api/tests/test_helpers/__init__.py b/api/tests/test_helpers/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/test_libs/__init__.py b/api/tests/test_libs/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/test_models/__init__.py b/api/tests/test_models/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/test_services/__init__.py b/api/tests/test_services/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base
new file mode 100644
index 00000000000..ec0e930f17b
--- /dev/null
+++ b/docker/Dockerfile.base
@@ -0,0 +1,256 @@
+FROM nginx:1.22
+
+# ensure local python is preferred over distribution python
+ENV PATH /usr/local/bin:$PATH
+
+# http://bugs.python.org/issue19846
+# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
+ENV LANG C.UTF-8
+
+# runtime dependencies
+RUN set -eux; \
+ apt-get update; \
+ apt-get install -y --no-install-recommends \
+ ca-certificates \
+ netbase \
+ tzdata \
+ ; \
+ rm -rf /var/lib/apt/lists/*
+
+ENV GPG_KEY A035C8C19219BA821ECEA86B64E628F8D684696D
+ENV PYTHON_VERSION 3.10.10
+
+RUN set -eux; \
+ \
+ savedAptMark="$(apt-mark showmanual)"; \
+ apt-get update; \
+ apt-get install -y --no-install-recommends \
+ dpkg-dev \
+ gcc \
+ gnupg dirmngr \
+ libbluetooth-dev \
+ libbz2-dev \
+ libc6-dev \
+ libdb-dev \
+ libexpat1-dev \
+ libffi-dev \
+ libgdbm-dev \
+ liblzma-dev \
+ libncursesw5-dev \
+ libreadline-dev \
+ libsqlite3-dev \
+ libssl-dev \
+ make \
+ tk-dev \
+ uuid-dev \
+ wget \
+ xz-utils \
+ zlib1g-dev \
+ ; \
+ \
+ wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz"; \
+ wget -O python.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc"; \
+ GNUPGHOME="$(mktemp -d)"; export GNUPGHOME; \
+ gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys "$GPG_KEY"; \
+ gpg --batch --verify python.tar.xz.asc python.tar.xz; \
+ command -v gpgconf > /dev/null && gpgconf --kill all || :; \
+ rm -rf "$GNUPGHOME" python.tar.xz.asc; \
+ mkdir -p /usr/src/python; \
+ tar --extract --directory /usr/src/python --strip-components=1 --file python.tar.xz; \
+ rm python.tar.xz; \
+ \
+ cd /usr/src/python; \
+ gnuArch="$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)"; \
+ ./configure \
+ --build="$gnuArch" \
+ --enable-loadable-sqlite-extensions \
+ --enable-optimizations \
+ --enable-option-checking=fatal \
+ --enable-shared \
+ --with-lto \
+ --with-system-expat \
+ --without-ensurepip \
+ ; \
+ nproc="$(nproc)"; \
+ EXTRA_CFLAGS="$(dpkg-buildflags --get CFLAGS)"; \
+ LDFLAGS="$(dpkg-buildflags --get LDFLAGS)"; \
+ LDFLAGS="${LDFLAGS:--Wl},--strip-all"; \
+ make -j "$nproc" \
+ "EXTRA_CFLAGS=${EXTRA_CFLAGS:-}" \
+ "LDFLAGS=${LDFLAGS:-}" \
+ "PROFILE_TASK=${PROFILE_TASK:-}" \
+ ; \
+# https://github.com/docker-library/python/issues/784
+# prevent accidental usage of a system installed libpython of the same version
+ rm python; \
+ make -j "$nproc" \
+ "EXTRA_CFLAGS=${EXTRA_CFLAGS:-}" \
+ "LDFLAGS=${LDFLAGS:--Wl},-rpath='\$\$ORIGIN/../lib'" \
+ "PROFILE_TASK=${PROFILE_TASK:-}" \
+ python \
+ ; \
+ make install; \
+ \
+ cd /; \
+ rm -rf /usr/src/python; \
+ \
+ find /usr/local -depth \
+ \( \
+ \( -type d -a \( -name test -o -name tests -o -name idle_test \) \) \
+ -o \( -type f -a \( -name '*.pyc' -o -name '*.pyo' -o -name 'libpython*.a' \) \) \
+ \) -exec rm -rf '{}' + \
+ ; \
+ \
+ ldconfig; \
+ \
+ apt-mark auto '.*' > /dev/null; \
+ apt-mark manual $savedAptMark; \
+ find /usr/local -type f -executable -not \( -name '*tkinter*' \) -exec ldd '{}' ';' \
+ | awk '/=>/ { print $(NF-1) }' \
+ | sort -u \
+ | xargs -r dpkg-query --search \
+ | cut -d: -f1 \
+ | sort -u \
+ | xargs -r apt-mark manual \
+ ; \
+ rm -rf /var/lib/apt/lists/*; \
+ \
+ python3 --version
+
+# make some useful symlinks that are expected to exist ("/usr/local/bin/python" and friends)
+RUN set -eux; \
+ for src in idle3 pydoc3 python3 python3-config; do \
+ dst="$(echo "$src" | tr -d 3)"; \
+ [ -s "/usr/local/bin/$src" ]; \
+ [ ! -e "/usr/local/bin/$dst" ]; \
+ ln -svT "$src" "/usr/local/bin/$dst"; \
+ done
+
+# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
+ENV PYTHON_PIP_VERSION 22.3.1
+# https://github.com/docker-library/python/issues/365
+ENV PYTHON_SETUPTOOLS_VERSION 65.5.1
+# https://github.com/pypa/get-pip
+ENV PYTHON_GET_PIP_URL https://github.com/pypa/get-pip/raw/d5cb0afaf23b8520f1bbcfed521017b4a95f5c01/public/get-pip.py
+ENV PYTHON_GET_PIP_SHA256 394be00f13fa1b9aaa47e911bdb59a09c3b2986472130f30aa0bfaf7f3980637
+
+RUN set -eux; \
+ \
+ savedAptMark="$(apt-mark showmanual)"; \
+ apt-get update; \
+ apt-get install -y --no-install-recommends wget; \
+ \
+ wget -O get-pip.py "$PYTHON_GET_PIP_URL"; \
+ echo "$PYTHON_GET_PIP_SHA256 *get-pip.py" | sha256sum -c -; \
+ \
+ apt-mark auto '.*' > /dev/null; \
+ [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
+ rm -rf /var/lib/apt/lists/*; \
+ \
+ export PYTHONDONTWRITEBYTECODE=1; \
+ \
+ python get-pip.py \
+ --disable-pip-version-check \
+ --no-cache-dir \
+ --no-compile \
+ "pip==$PYTHON_PIP_VERSION" \
+ "setuptools==$PYTHON_SETUPTOOLS_VERSION" \
+ ; \
+ rm -f get-pip.py; \
+ \
+ pip --version
+
+RUN groupadd --gid 1000 node \
+ && useradd --uid 1000 --gid node --shell /bin/bash --create-home node
+
+ENV NODE_VERSION 18.15.0
+
+RUN ARCH= && dpkgArch="$(dpkg --print-architecture)" \
+ && case "${dpkgArch##*-}" in \
+ amd64) ARCH='x64';; \
+ ppc64el) ARCH='ppc64le';; \
+ s390x) ARCH='s390x';; \
+ arm64) ARCH='arm64';; \
+ armhf) ARCH='armv7l';; \
+ i386) ARCH='x86';; \
+ *) echo "unsupported architecture"; exit 1 ;; \
+ esac \
+ && set -ex \
+ # libatomic1 for arm
+ && apt-get update && apt-get install -y ca-certificates curl wget gnupg dirmngr xz-utils libatomic1 --no-install-recommends \
+ && rm -rf /var/lib/apt/lists/* \
+ && for key in \
+ 4ED778F539E3634C779C87C6D7062848A1AB005C \
+ 141F07595B7B3FFE74309A937405533BE57C7D57 \
+ 74F12602B6F1C4E913FAA37AD3A89613643B6201 \
+ DD792F5973C6DE52C432CBDAC77ABFA00DDBF2B7 \
+ 61FC681DFB92A079F1685E77973F295594EC4689 \
+ 8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 \
+ C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
+ 890C08DB8579162FEE0DF9DB8BEAB4DFCF555EF4 \
+ C82FA3AE1CBEDC6BE46B9360C43CEC45C17AB93C \
+ 108F52B48DB57BB0CC439B2997B01419BD92F80A \
+ ; do \
+ gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys "$key" || \
+ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
+ done \
+ && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-$ARCH.tar.xz" \
+ && curl -fsSLO --compressed "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
+ && gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
+ && grep " node-v$NODE_VERSION-linux-$ARCH.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
+ && tar -xJf "node-v$NODE_VERSION-linux-$ARCH.tar.xz" -C /usr/local --strip-components=1 --no-same-owner \
+ && rm "node-v$NODE_VERSION-linux-$ARCH.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
+ && apt-mark auto '.*' > /dev/null \
+ && find /usr/local -type f -executable -exec ldd '{}' ';' \
+ | awk '/=>/ { print $(NF-1) }' \
+ | sort -u \
+ | xargs -r dpkg-query --search \
+ | cut -d: -f1 \
+ | sort -u \
+ | xargs -r apt-mark manual \
+ && ln -s /usr/local/bin/node /usr/local/bin/nodejs \
+ # smoke tests
+ && node --version \
+ && npm --version
+
+ENV YARN_VERSION 1.22.19
+
+RUN set -ex \
+ && savedAptMark="$(apt-mark showmanual)" \
+ && apt-get update && apt-get install -y ca-certificates curl wget gnupg dirmngr --no-install-recommends \
+ && rm -rf /var/lib/apt/lists/* \
+ && for key in \
+ 6A010C5166006599AA17F08146C2130DFD2497F5 \
+ ; do \
+ gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys "$key" || \
+ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
+ done \
+ && curl -fsSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
+ && curl -fsSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
+ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
+ && mkdir -p /opt \
+ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/ \
+ && ln -s /opt/yarn-v$YARN_VERSION/bin/yarn /usr/local/bin/yarn \
+ && ln -s /opt/yarn-v$YARN_VERSION/bin/yarnpkg /usr/local/bin/yarnpkg \
+ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
+ && apt-mark auto '.*' > /dev/null \
+ && { [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; } \
+ && find /usr/local -type f -executable -exec ldd '{}' ';' \
+ | awk '/=>/ { print $(NF-1) }' \
+ | sort -u \
+ | xargs -r dpkg-query --search \
+ | cut -d: -f1 \
+ | sort -u \
+ | xargs -r apt-mark manual \
+ # smoke test
+ && yarn --version
+
+
+
+RUN apt-get update && \
+ apt-get install -y bash curl wget vim gcc g++ python3-dev libc-dev libffi-dev
+
+RUN pip3 install gunicorn
+RUN npm install pm2 -g
+
+ENTRYPOINT ["/usr/local/bin/pm2-runtime", "start"]
\ No newline at end of file
diff --git a/docker/docker-compose.middleware.yaml b/docker/docker-compose.middleware.yaml
new file mode 100644
index 00000000000..09372ca2a39
--- /dev/null
+++ b/docker/docker-compose.middleware.yaml
@@ -0,0 +1,53 @@
+version: '3.1'
+services:
+ # The postgres database.
+ db:
+ image: postgres:15-alpine
+ restart: always
+ environment:
+ # The password for the default postgres user.
+ POSTGRES_PASSWORD: difyai123456
+ # The name of the default postgres database.
+ POSTGRES_DB: dify
+ # postgres data directory
+ PGDATA: /var/lib/postgresql/data/pgdata
+ volumes:
+ - ./volumes/db/data:/var/lib/postgresql/data
+ - ./volumes/db/scripts:/docker-entrypoint-initdb.d/
+ ports:
+ - "5432:5432"
+
+ # The redis cache.
+ redis:
+ image: redis:6-alpine
+ restart: always
+ volumes:
+ # Mount the redis data directory to the container.
+ - ./volumes/redis/data:/data
+ # Set the redis password when startup redis server.
+ command: redis-server --requirepass difyai123456
+ ports:
+ - "6379:6379"
+
+ # The Weaviate vector store.
+ weaviate:
+ image: semitechnologies/weaviate:1.18.4
+ restart: always
+ volumes:
+ # Mount the Weaviate data directory to the container.
+ - ./volumes/weaviate:/var/lib/weaviate
+ environment:
+ # The Weaviate configurations
+ # You can refer to the [Weaviate](https://weaviate.io/developers/weaviate/config-refs/env-vars) documentation for more information.
+ QUERY_DEFAULTS_LIMIT: 25
+ AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'false'
+ PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
+ DEFAULT_VECTORIZER_MODULE: 'none'
+ CLUSTER_HOSTNAME: 'node1'
+ AUTHENTICATION_APIKEY_ENABLED: 'true'
+ AUTHENTICATION_APIKEY_ALLOWED_KEYS: 'WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih'
+ AUTHENTICATION_APIKEY_USERS: '[email protected]'
+ AUTHORIZATION_ADMINLIST_ENABLED: 'true'
+ AUTHORIZATION_ADMINLIST_USERS: '[email protected]'
+ ports:
+ - "8080:8080"
\ No newline at end of file
diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml
new file mode 100644
index 00000000000..7d1542fbca1
--- /dev/null
+++ b/docker/docker-compose.yaml
@@ -0,0 +1,213 @@
+version: '3.1'
+services:
+ # API service
+ api:
+ image: langgenius/dify-api:latest
+ restart: always
+ environment:
+ # Startup mode, 'api' starts the API server.
+ MODE: api
+ # The log level for the application. Supported values are `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`
+ LOG_LEVEL: INFO
+ # A secret key that is used for securely signing the session cookie and encrypting sensitive information on the database. You can generate a strong key using `openssl rand -base64 42`.
+ SECRET_KEY: sk-9f73s3ljTXVcMT3Blb3ljTqtsKiGHXVcMT3BlbkFJLK7U
+ # The base URL of console application, refers to the Console base URL of WEB service.
+ CONSOLE_URL: http://localhost
+ # The URL for Service API endpoints,refers to the base URL of the current API service.
+ API_URL: http://localhost
+ # The URL for Web APP, refers to the Web App base URL of WEB service.
+ APP_URL: http://localhost
+ # When enabled, migrations will be executed prior to application startup and the application will start after the migrations have completed.
+ MIGRATION_ENABLED: 'true'
+ # The configurations of postgres database connection.
+ # It is consistent with the configuration in the 'db' service below.
+ DB_USERNAME: postgres
+ DB_PASSWORD: difyai123456
+ DB_HOST: db
+ DB_PORT: 5432
+ DB_DATABASE: dify
+ # The configurations of redis connection.
+ # It is consistent with the configuration in the 'redis' service below.
+ REDIS_HOST: redis
+ REDIS_PORT: 6379
+ REDIS_PASSWORD: difyai123456
+ # use redis db 0 for redis cache
+ REDIS_DB: 0
+ # The configurations of session, Supported values are `sqlalchemy`. `redis`
+ SESSION_TYPE: redis
+ SESSION_REDIS_HOST: redis
+ SESSION_REDIS_PORT: 6379
+ SESSION_REDIS_PASSWORD: difyai123456
+ # use redis db 2 for session store
+ SESSION_REDIS_DB: 2
+ # The configurations of celery broker.
+ # Use redis as the broker, and redis db 1 for celery broker.
+ CELERY_BROKER_URL: redis://:difyai123456@redis:6379/1
+ # Specifies the allowed origins for cross-origin requests to the Web API
+ WEB_API_CORS_ALLOW_ORIGINS: http://localhost,*
+ # Specifies the allowed origins for cross-origin requests to the console API
+ CONSOLE_CORS_ALLOW_ORIGINS: http://localhost,*
+ # CSRF Cookie settings
+ # Controls whether a cookie is sent with cross-site requests,
+ # providing some protection against cross-site request forgery attacks
+ COOKIE_HTTPONLY: 'true'
+ COOKIE_SAMESITE: 'None'
+ COOKIE_SECURE: 'true'
+ # The type of storage to use for storing user files. Supported values are `local` and `s3`, Default: `local`
+ STORAGE_TYPE: local
+ # The path to the local storage directory, the directory relative the root path of API service codes or absolute path. Default: `storage` or `/home/john/storage`.
+ # only available when STORAGE_TYPE is `local`.
+ STORAGE_LOCAL_PATH: storage
+ # The S3 storage configurations, only available when STORAGE_TYPE is `s3`.
+ S3_ENDPOINT: 'https://xxx.r2.cloudflarestorage.com'
+ S3_BUCKET_NAME: 'difyai'
+ S3_ACCESS_KEY: 'ak-difyai'
+ S3_SECRET_KEY: 'sk-difyai'
+ S3_REGION: 'us-east-1'
+ # The type of vector store to use. Supported values are `weaviate`, `qdrant`.
+ VECTOR_STORE: weaviate
+ # The Weaviate endpoint URL. Only available when VECTOR_STORE is `weaviate`.
+ WEAVIATE_ENDPOINT: http://weaviate:8080
+ # The Weaviate API key.
+ WEAVIATE_API_KEY: WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih
+ # The Qdrant endpoint URL. Only available when VECTOR_STORE is `qdrant`.
+ QDRANT_URL: 'https://your-qdrant-cluster-url.qdrant.tech/'
+ # The Qdrant API key.
+ QDRANT_API_KEY: 'ak-difyai'
+ # The DSN for Sentry error reporting. If not set, Sentry error reporting will be disabled.
+ SENTRY_DSN: ''
+ # The sample rate for Sentry events. Default: `1.0`
+ SENTRY_TRACES_SAMPLE_RATE: 1.0
+ # The sample rate for Sentry profiles. Default: `1.0`
+ SENTRY_PROFILES_SAMPLE_RATE: 1.0
+ depends_on:
+ - db
+ - redis
+ - weaviate
+ volumes:
+ # Mount the storage directory to the container, for storing user files.
+ - ./volumes/app/storage:/app/storage
+
+ # worker service
+ # The Celery worker for processing the queue.
+ worker:
+ image: langgenius/dify-api:latest
+ restart: always
+ environment:
+ # Startup mode, 'worker' starts the Celery worker for processing the queue.
+ MODE: worker
+
+ # --- All the configurations below are the same as those in the 'api' service. ---
+
+ # The log level for the application. Supported values are `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`
+ LOG_LEVEL: INFO
+ # A secret key that is used for securely signing the session cookie and encrypting sensitive information on the database. You can generate a strong key using `openssl rand -base64 42`.
+ # same as the API service
+ SECRET_KEY: sk-9f73s3ljTXVcMT3Blb3ljTqtsKiGHXVcMT3BlbkFJLK7U
+ # The base URL of console application, refers to the Console base URL of WEB service.
+ CONSOLE_URL: http://localhost
+ # The URL for Service API endpoints,refers to the base URL of the current API service.
+ API_URL: http://localhost
+ # The URL for Web APP, refers to the Web App base URL of WEB service.
+ APP_URL: http://localhost
+ # The configurations of postgres database connection.
+ # It is consistent with the configuration in the 'db' service below.
+ DB_USERNAME: postgres
+ DB_PASSWORD: difyai123456
+ DB_HOST: db
+ DB_PORT: 5432
+ DB_DATABASE: dify
+ # The configurations of redis cache connection.
+ REDIS_HOST: redis
+ REDIS_PORT: 6379
+ REDIS_PASSWORD: difyai123456
+ REDIS_DB: 0
+ # The configurations of celery broker.
+ CELERY_BROKER_URL: redis://:difyai123456@redis:6379/1
+ # The type of storage to use for storing user files. Supported values are `local` and `s3`, Default: `local`
+ STORAGE_TYPE: local
+ STORAGE_LOCAL_PATH: storage
+ # The Vector store configurations.
+ VECTOR_STORE: weaviate
+ WEAVIATE_ENDPOINT: http://weaviate:8080
+ WEAVIATE_API_KEY: WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih
+ depends_on:
+ - db
+ - redis
+ - weaviate
+ volumes:
+ # Mount the storage directory to the container, for storing user files.
+ - ./volumes/app/storage:/app/storage
+
+ # Frontend web application.
+ web:
+ image: langgenius/dify-web:latest
+ restart: always
+ environment:
+ EDITION: SELF_HOSTED
+ # The base URL of console application, refers to the Console base URL of WEB service.
+ CONSOLE_URL: http://localhost
+ # The URL for Web APP, refers to the Web App base URL of WEB service.
+ APP_URL: http://localhost
+
+ # The postgres database.
+ db:
+ image: postgres:15-alpine
+ restart: always
+ environment:
+ # The password for the default postgres user.
+ POSTGRES_PASSWORD: difyai123456
+ # The name of the default postgres database.
+ POSTGRES_DB: dify
+ # postgres data directory
+ PGDATA: /var/lib/postgresql/data/pgdata
+ volumes:
+ - ./volumes/db/data:/var/lib/postgresql/data
+ - ./volumes/db/scripts:/docker-entrypoint-initdb.d/
+ ports:
+ - "5432:5432"
+
+ # The redis cache.
+ redis:
+ image: redis:6-alpine
+ restart: always
+ volumes:
+ # Mount the redis data directory to the container.
+ - ./volumes/redis/data:/data
+ # Set the redis password when startup redis server.
+ command: redis-server --requirepass difyai123456
+
+ # The Weaviate vector store.
+ weaviate:
+ image: semitechnologies/weaviate:1.18.4
+ restart: always
+ volumes:
+ # Mount the Weaviate data directory to the container.
+ - ./volumes/weaviate:/var/lib/weaviate
+ environment:
+ # The Weaviate configurations
+ # You can refer to the [Weaviate](https://weaviate.io/developers/weaviate/config-refs/env-vars) documentation for more information.
+ QUERY_DEFAULTS_LIMIT: 25
+ AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'false'
+ PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
+ DEFAULT_VECTORIZER_MODULE: 'none'
+ CLUSTER_HOSTNAME: 'node1'
+ AUTHENTICATION_APIKEY_ENABLED: 'true'
+ AUTHENTICATION_APIKEY_ALLOWED_KEYS: 'WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih'
+ AUTHENTICATION_APIKEY_USERS: '[email protected]'
+ AUTHORIZATION_ADMINLIST_ENABLED: 'true'
+ AUTHORIZATION_ADMINLIST_USERS: '[email protected]'
+
+ # The nginx reverse proxy.
+ # used for reverse proxying the API service and Web service.
+ nginx:
+ image: nginx:latest
+ volumes:
+ - ./nginx/nginx.conf:/etc/nginx/nginx.conf
+ - ./nginx/proxy.conf:/etc/nginx/proxy.conf
+ - ./nginx/conf.d:/etc/nginx/conf.d
+ depends_on:
+ - api
+ - web
+ ports:
+ - "80:80"
\ No newline at end of file
diff --git a/docker/nginx/conf.d/default.conf b/docker/nginx/conf.d/default.conf
new file mode 100644
index 00000000000..3b153f40b03
--- /dev/null
+++ b/docker/nginx/conf.d/default.conf
@@ -0,0 +1,24 @@
+server {
+ listen 80;
+ server_name localhost;
+
+ location /console/api {
+ proxy_pass http://api:5001;
+ include proxy.conf;
+ }
+
+ location /api {
+ proxy_pass http://api:5001;
+ include proxy.conf;
+ }
+
+ location /v1 {
+ proxy_pass http://api:5001;
+ include proxy.conf;
+ }
+
+ location / {
+ proxy_pass http://web:3000;
+ include proxy.conf;
+ }
+}
\ No newline at end of file
diff --git a/docker/nginx/nginx.conf b/docker/nginx/nginx.conf
new file mode 100644
index 00000000000..d2b52963e84
--- /dev/null
+++ b/docker/nginx/nginx.conf
@@ -0,0 +1,32 @@
+user nginx;
+worker_processes auto;
+
+error_log /var/log/nginx/error.log notice;
+pid /var/run/nginx.pid;
+
+
+events {
+ worker_connections 1024;
+}
+
+
+http {
+ include /etc/nginx/mime.types;
+ default_type application/octet-stream;
+
+ log_format main '$remote_addr - $remote_user [$time_local] "$request" '
+ '$status $body_bytes_sent "$http_referer" '
+ '"$http_user_agent" "$http_x_forwarded_for"';
+
+ access_log /var/log/nginx/access.log main;
+
+ sendfile on;
+ #tcp_nopush on;
+
+ keepalive_timeout 65;
+
+ #gzip on;
+ client_max_body_size 15M;
+
+ include /etc/nginx/conf.d/*.conf;
+}
\ No newline at end of file
diff --git a/docker/nginx/proxy.conf b/docker/nginx/proxy.conf
new file mode 100644
index 00000000000..254f6259612
--- /dev/null
+++ b/docker/nginx/proxy.conf
@@ -0,0 +1,8 @@
+proxy_set_header Host $host;
+proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+proxy_set_header X-Forwarded-Proto $scheme;
+proxy_http_version 1.1;
+proxy_set_header Connection "";
+proxy_buffering off;
+proxy_read_timeout 3600s;
+proxy_send_timeout 3600s;
\ No newline at end of file
diff --git a/docker/volumes/db/scripts/init_extension.sh b/docker/volumes/db/scripts/init_extension.sh
new file mode 100644
index 00000000000..abad1e51821
--- /dev/null
+++ b/docker/volumes/db/scripts/init_extension.sh
@@ -0,0 +1 @@
+psql -U postgres -d dify -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";'
\ No newline at end of file
diff --git a/images/describe-cn.jpg b/images/describe-cn.jpg
new file mode 100644
index 00000000000..10bdc286579
Binary files /dev/null and b/images/describe-cn.jpg differ
diff --git a/images/describe-en.png b/images/describe-en.png
new file mode 100644
index 00000000000..bf2bd226757
Binary files /dev/null and b/images/describe-en.png differ
diff --git a/mock-server/.gitignore b/mock-server/.gitignore
new file mode 100644
index 00000000000..02651453d88
--- /dev/null
+++ b/mock-server/.gitignore
@@ -0,0 +1,117 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+*.lcov
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+jspm_packages/
+
+# TypeScript v1 declaration files
+typings/
+
+# TypeScript cache
+*.tsbuildinfo
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Microbundle cache
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# Yarn Integrity file
+.yarn-integrity
+
+# dotenv environment variables file
+.env
+.env.test
+
+# parcel-bundler cache (https://parceljs.org/)
+.cache
+
+# Next.js build output
+.next
+
+# Nuxt.js build / generate output
+.nuxt
+dist
+
+# Gatsby files
+.cache/
+# Comment in the public line in if your project uses Gatsby and *not* Next.js
+# https://nextjs.org/blog/next-9-1#public-directory-support
+# public
+
+# vuepress build output
+.vuepress/dist
+
+# Serverless directories
+.serverless/
+
+# FuseBox cache
+.fusebox/
+
+# DynamoDB Local files
+.dynamodb/
+
+# TernJS port file
+.tern-port
+
+# npm
+package-lock.json
+
+# yarn
+.pnp.cjs
+.pnp.loader.mjs
+.yarn/
+yarn.lock
+.yarnrc.yml
+
+# pmpm
+pnpm-lock.yaml
\ No newline at end of file
diff --git a/mock-server/README.md b/mock-server/README.md
new file mode 100644
index 00000000000..7b0a621e847
--- /dev/null
+++ b/mock-server/README.md
@@ -0,0 +1 @@
+# Mock Server
diff --git a/mock-server/api/apps.js b/mock-server/api/apps.js
new file mode 100644
index 00000000000..d704387376a
--- /dev/null
+++ b/mock-server/api/apps.js
@@ -0,0 +1,551 @@
+const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
+
+function randomString (length) {
+ let result = ''
+ for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]
+ return result
+}
+
+// https://www.notion.so/55773516a0194781ae211792a44a3663?pvs=4
+const VirtualData = new Array(10).fill().map((_, index) => {
+ const date = new Date(Date.now() - index * 24 * 60 * 60 * 1000)
+ return {
+ date: `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`,
+ conversation_count: Math.floor(Math.random() * 10) + index,
+ terminal_count: Math.floor(Math.random() * 10) + index,
+ token_count: Math.floor(Math.random() * 10) + index,
+ total_price: Math.floor(Math.random() * 10) + index,
+ }
+})
+
+const registerAPI = function (app) {
+ const apps = [{
+ id: '1',
+ name: 'chat app',
+ mode: 'chat',
+ description: 'description01',
+ enable_site: true,
+ enable_api: true,
+ api_rpm: 60,
+ api_rph: 3600,
+ is_demo: false,
+ model_config: {
+ provider: 'OPENAI',
+ model_id: 'gpt-3.5-turbo',
+ configs: {
+ prompt_template: '你是我的解梦小助手,请参考 {{book}} 回答我有关梦境的问题。在回答前请称呼我为 {{myName}}。',
+ prompt_variables: [
+ {
+ key: 'book',
+ name: '书',
+ value: '《梦境解析》',
+ type: 'string',
+ description: '请具体说下书名'
+ },
+ {
+ key: 'myName',
+ name: 'your name',
+ value: 'Book',
+ type: 'string',
+ description: 'please tell me your name'
+ }
+ ],
+ completion_params: {
+ max_token: 16,
+ temperature: 1, // 0-2
+ top_p: 1,
+ presence_penalty: 1, // -2-2
+ frequency_penalty: 1, // -2-2
+ }
+ }
+ },
+ site: {
+ access_token: '1000',
+ title: 'site 01',
+ author: 'John',
+ default_language: 'zh-Hans-CN',
+ customize_domain: 'http://customize_domain',
+ theme: 'theme',
+ customize_token_strategy: 'must',
+ prompt_public: true
+ }
+ },
+ {
+ id: '2',
+ name: 'completion app',
+ mode: 'completion', // genertation text
+ description: 'description 02', // genertation text
+ enable_site: false,
+ enable_api: false,
+ api_rpm: 60,
+ api_rph: 3600,
+ is_demo: false,
+ model_config: {
+ provider: 'OPENAI',
+ model_id: 'text-davinci-003',
+ configs: {
+ prompt_template: '你是我的翻译小助手,请把以下内容 {{langA}} 翻译成 {{langB}},以下的内容:',
+ prompt_variables: [
+ {
+ key: 'langA',
+ name: '原始语音',
+ value: '中文',
+ type: 'string',
+ description: '这是中文格式的原始语音'
+ },
+ {
+ key: 'langB',
+ name: '目标语言',
+ value: '英语',
+ type: 'string',
+ description: '这是英语格式的目标语言'
+ }
+ ],
+ completion_params: {
+ max_token: 16,
+ temperature: 1, // 0-2
+ top_p: 1,
+ presence_penalty: 1, // -2-2
+ frequency_penalty: 1, // -2-2
+ }
+ }
+ },
+ site: {
+ access_token: '2000',
+ title: 'site 02',
+ author: 'Mark',
+ default_language: 'en-US',
+ customize_domain: 'http://customize_domain',
+ theme: 'theme',
+ customize_token_strategy: 'must',
+ prompt_public: false
+ }
+ },
+ ]
+
+ const apikeys = [{
+ id: '111121312313132',
+ token: 'sk-DEFGHJKMNPQRSTWXYZabcdefhijk1234',
+ last_used_at: '1679212138000',
+ created_at: '1673316000000'
+ }, {
+ id: '43441242131223123',
+ token: 'sk-EEFGHJKMNPQRSTWXYZabcdefhijk5678',
+ last_used_at: '1679212721000',
+ created_at: '1679212731000'
+ }]
+
+ // create app
+ app.post('/apps', async (req, res) => {
+ apps.push({
+ id: apps.length + 1 + '',
+ ...req.body,
+
+ })
+ res.send({
+ result: 'success'
+ })
+ })
+
+ // app list
+ app.get('/apps', async (req, res) => {
+ res.send({
+ data: apps
+ })
+ })
+
+ // app detail
+ app.get('/apps/:id', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id) || apps[0]
+ res.send(item)
+ })
+
+ // update app name
+ app.post('/apps/:id/name', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ item.name = req.body.name
+ res.send(item || null)
+ })
+
+ // update app site-enable status
+ app.post('/apps/:id/site-enable', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.enable_site = req.body.enable_site
+ res.send(item || null)
+ })
+
+ // update app api-enable status
+ app.post('/apps/:id/api-enable', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.enable_api = req.body.enable_api
+ res.send(item || null)
+ })
+
+ // update app rate-limit
+ app.post('/apps/:id/rate-limit', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.api_rpm = req.body.api_rpm
+ item.api_rph = req.body.api_rph
+ res.send(item || null)
+ })
+
+ // update app url including code
+ app.post('/apps/:id/site/access-token-reset', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.site.access_token = randomString(12)
+ res.send(item || null)
+ })
+
+ // update app config
+ app.post('/apps/:id/site', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.name = req.body.title
+ item.description = req.body.description
+ item.prompt_public = req.body.prompt_public
+ item.default_language = req.body.default_language
+ res.send(item || null)
+ })
+
+ // get statistics daily-conversations
+ app.get('/apps/:id/statistics/daily-conversations', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ if (item) {
+ res.send({
+ data: VirtualData
+ })
+ } else {
+ res.send({
+ data: []
+ })
+ }
+ })
+
+ // get statistics daily-end-users
+ app.get('/apps/:id/statistics/daily-end-users', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ if (item) {
+ res.send({
+ data: VirtualData
+ })
+ } else {
+ res.send({
+ data: []
+ })
+ }
+ })
+
+ // get statistics token-costs
+ app.get('/apps/:id/statistics/token-costs', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ if (item) {
+ res.send({
+ data: VirtualData
+ })
+ } else {
+ res.send({
+ data: []
+ })
+ }
+ })
+
+ // update app model config
+ app.post('/apps/:id/model-config', async (req, res) => {
+ const item = apps.find(item => item.id === req.params.id)
+ console.log(item)
+ item.model_config = req.body
+ res.send(item || null)
+ })
+
+
+ // get api keys list
+ app.get('/apps/:id/api-keys', async (req, res) => {
+ res.send({
+ data: apikeys
+ })
+ })
+
+ // del api key
+ app.delete('/apps/:id/api-keys/:api_key_id', async (req, res) => {
+ res.send({
+ result: 'success'
+ })
+ })
+
+ // create api key
+ app.post('/apps/:id/api-keys', async (req, res) => {
+ res.send({
+ id: 'e2424241313131',
+ token: 'sk-GEFGHJKMNPQRSTWXYZabcdefhijk0124',
+ created_at: '1679216688962'
+ })
+ })
+
+ // get completion-conversations
+ app.get('/apps/:id/completion-conversations', async (req, res) => {
+ const data = {
+ data: [{
+ id: 1,
+ from_end_user_id: 'user 1',
+ summary: 'summary1',
+ created_at: '2023-10-11',
+ annotated: true,
+ message_count: 100,
+ user_feedback_stats: {
+ like: 4, dislike: 5
+ },
+ admin_feedback_stats: {
+ like: 1, dislike: 2
+ },
+ message: {
+ message: 'message1',
+ query: 'question1',
+ answer: 'answer1'
+ }
+ }, {
+ id: 12,
+ from_end_user_id: 'user 2',
+ summary: 'summary2',
+ created_at: '2023-10-01',
+ annotated: false,
+ message_count: 10,
+ user_feedback_stats: {
+ like: 2, dislike: 20
+ },
+ admin_feedback_stats: {
+ like: 12, dislike: 21
+ },
+ message: {
+ message: 'message2',
+ query: 'question2',
+ answer: 'answer2'
+ }
+ }, {
+ id: 13,
+ from_end_user_id: 'user 3',
+ summary: 'summary3',
+ created_at: '2023-10-11',
+ annotated: false,
+ message_count: 20,
+ user_feedback_stats: {
+ like: 2, dislike: 0
+ },
+ admin_feedback_stats: {
+ like: 0, dislike: 21
+ },
+ message: {
+ message: 'message3',
+ query: 'question3',
+ answer: 'answer3'
+ }
+ }],
+ total: 200
+ }
+ res.send(data)
+ })
+
+ // get chat-conversations
+ app.get('/apps/:id/chat-conversations', async (req, res) => {
+ const data = {
+ data: [{
+ id: 1,
+ from_end_user_id: 'user 1',
+ summary: 'summary1',
+ created_at: '2023-10-11',
+ read_at: '2023-10-12',
+ annotated: true,
+ message_count: 100,
+ user_feedback_stats: {
+ like: 4, dislike: 5
+ },
+ admin_feedback_stats: {
+ like: 1, dislike: 2
+ },
+ message: {
+ message: 'message1',
+ query: 'question1',
+ answer: 'answer1'
+ }
+ }, {
+ id: 12,
+ from_end_user_id: 'user 2',
+ summary: 'summary2',
+ created_at: '2023-10-01',
+ annotated: false,
+ message_count: 10,
+ user_feedback_stats: {
+ like: 2, dislike: 20
+ },
+ admin_feedback_stats: {
+ like: 12, dislike: 21
+ },
+ message: {
+ message: 'message2',
+ query: 'question2',
+ answer: 'answer2'
+ }
+ }, {
+ id: 13,
+ from_end_user_id: 'user 3',
+ summary: 'summary3',
+ created_at: '2023-10-11',
+ annotated: false,
+ message_count: 20,
+ user_feedback_stats: {
+ like: 2, dislike: 0
+ },
+ admin_feedback_stats: {
+ like: 0, dislike: 21
+ },
+ message: {
+ message: 'message3',
+ query: 'question3',
+ answer: 'answer3'
+ }
+ }],
+ total: 200
+ }
+ res.send(data)
+ })
+
+ // get completion-conversation detail
+ app.get('/apps/:id/completion-conversations/:cid', async (req, res) => {
+ const data =
+ {
+ id: 1,
+ from_end_user_id: 'user 1',
+ summary: 'summary1',
+ created_at: '2023-10-11',
+ annotated: true,
+ message: {
+ message: 'question1',
+ // query: 'question1',
+ answer: 'answer1',
+ annotation: {
+ content: '这是一段纠正的内容'
+ }
+ },
+ model_config: {
+ provider: 'openai',
+ model_id: 'model_id',
+ configs: {
+ prompt_template: '你是我的翻译小助手,请把以下内容 {{langA}} 翻译成 {{langB}},以下的内容:{{content}}'
+ }
+ }
+ }
+ res.send(data)
+ })
+
+ // get chat-conversation detail
+ app.get('/apps/:id/chat-conversations/:cid', async (req, res) => {
+ const data =
+ {
+ id: 1,
+ from_end_user_id: 'user 1',
+ summary: 'summary1',
+ created_at: '2023-10-11',
+ annotated: true,
+ message: {
+ message: 'question1',
+ // query: 'question1',
+ answer: 'answer1',
+ created_at: '2023-08-09 13:00',
+ provider_response_latency: 130,
+ message_tokens: 230
+ },
+ model_config: {
+ provider: 'openai',
+ model_id: 'model_id',
+ configs: {
+ prompt_template: '你是我的翻译小助手,请把以下内容 {{langA}} 翻译成 {{langB}},以下的内容:{{content}}'
+ }
+ }
+ }
+ res.send(data)
+ })
+
+ // get chat-conversation message list
+ app.get('/apps/:id/chat-messages', async (req, res) => {
+ const data = {
+ data: [{
+ id: 1,
+ created_at: '2023-10-11 07:09',
+ message: '请说说人为什么会做梦?' + req.query.conversation_id,
+ answer: '梦境通常是个人内心深处的反映,很难确定每个人梦境的确切含义,因为它们可能会受到梦境者的文化背景、生活经验和情感状态等多种因素的影响。',
+ provider_response_latency: 450,
+ answer_tokens: 200,
+ annotation: {
+ content: 'string',
+ account: {
+ id: 'string',
+ name: 'string',
+ email: 'string'
+ }
+ },
+ feedbacks: {
+ rating: 'like',
+ content: 'string',
+ from_source: 'log'
+ }
+ }, {
+ id: 2,
+ created_at: '2023-10-11 8:23',
+ message: '夜里经常做梦会影响次日的精神状态吗?',
+ answer: '总之,这个梦境可能与梦境者的个人经历和情感状态有关,但在一般情况下,它可能表示一种强烈的情感反应,包括愤怒、不满和对于正义和自由的渴望。',
+ provider_response_latency: 400,
+ answer_tokens: 250,
+ annotation: {
+ content: 'string',
+ account: {
+ id: 'string',
+ name: 'string',
+ email: 'string'
+ }
+ },
+ // feedbacks: {
+ // rating: 'like',
+ // content: 'string',
+ // from_source: 'log'
+ // }
+ }, {
+ id: 3,
+ created_at: '2023-10-11 10:20',
+ message: '梦见在山上手撕鬼子,大师解解梦',
+ answer: '但是,一般来说,“手撕鬼子”这个场景可能是梦境者对于过去历史上的战争、侵略以及对于自己国家和族群的保护与维护的情感反应。在梦中,你可能会感到自己充满力量和勇气,去对抗那些看似强大的侵略者。',
+ provider_response_latency: 288,
+ answer_tokens: 100,
+ annotation: {
+ content: 'string',
+ account: {
+ id: 'string',
+ name: 'string',
+ email: 'string'
+ }
+ },
+ feedbacks: {
+ rating: 'dislike',
+ content: 'string',
+ from_source: 'log'
+ }
+ }],
+ limit: 20,
+ has_more: true
+ }
+ res.send(data)
+ })
+
+ app.post('/apps/:id/annotations', async (req, res) => {
+ res.send({ result: 'success' })
+ })
+
+ app.post('/apps/:id/feedbacks', async (req, res) => {
+ res.send({ result: 'success' })
+ })
+
+}
+
+module.exports = registerAPI
\ No newline at end of file
diff --git a/mock-server/api/common.js b/mock-server/api/common.js
new file mode 100644
index 00000000000..3e43ad524a0
--- /dev/null
+++ b/mock-server/api/common.js
@@ -0,0 +1,38 @@
+
+const registerAPI = function (app) {
+ app.post('/login', async (req, res) => {
+ res.send({
+ result: 'success'
+ })
+ })
+
+ // get user info
+ app.get('/account/profile', async (req, res) => {
+ res.send({
+ id: '11122222',
+ name: 'Joel',
+ })
+ })
+
+ // logout
+ app.get('/logout', async (req, res) => {
+ res.send({
+ result: 'success'
+ })
+ })
+
+ // Langgenius version
+ app.get('/version', async (req, res) => {
+ res.send({
+ current_version: 'v1.0.0',
+ latest_version: 'v1.0.0',
+ upgradeable: true,
+ compatible_upgrade: true
+ })
+ })
+
+}
+
+module.exports = registerAPI
+
diff --git a/mock-server/api/datasets.js b/mock-server/api/datasets.js
new file mode 100644
index 00000000000..0821b3786b9
--- /dev/null
+++ b/mock-server/api/datasets.js
@@ -0,0 +1,249 @@
+const registerAPI = function (app) {
+ app.get("/datasets/:id/documents", async (req, res) => {
+ if (req.params.id === "0") res.send({ data: [] });
+ else {
+ res.send({
+ data: [
+ {
+ id: 1,
+ name: "Steve Jobs' life",
+ words: "70k",
+ word_count: 100,
+ updated_at: 1681801029,
+ indexing_status: "completed",
+ archived: true,
+ enabled: false,
+ data_source_info: {
+ upload_file: {
+ // id: string
+ // name: string
+ // size: number
+ // mime_type: string
+ // created_at: number
+ // created_by: string
+ extension: "pdf",
+ },
+ },
+ },
+ {
+ id: 2,
+ name: "Steve Jobs' life",
+ word_count: "10k",
+ hit_count: 10,
+ updated_at: 1681801029,
+ indexing_status: "waiting",
+ archived: true,
+ enabled: false,
+ data_source_info: {
+ upload_file: {
+ extension: "json",
+ },
+ },
+ },
+ {
+ id: 3,
+ name: "Steve Jobs' life xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ word_count: "100k",
+ hit_count: 0,
+ updated_at: 1681801029,
+ indexing_status: "indexing",
+ archived: false,
+ enabled: true,
+ data_source_info: {
+ upload_file: {
+ extension: "txt",
+ },
+ },
+ },
+ {
+ id: 4,
+ name: "Steve Jobs' life xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ word_count: "100k",
+ hit_count: 0,
+ updated_at: 1681801029,
+ indexing_status: "splitting",
+ archived: false,
+ enabled: true,
+ data_source_info: {
+ upload_file: {
+ extension: "md",
+ },
+ },
+ },
+ {
+ id: 5,
+ name: "Steve Jobs' life",
+ word_count: "100k",
+ hit_count: 0,
+ updated_at: 1681801029,
+ indexing_status: "error",
+ archived: false,
+ enabled: false,
+ data_source_info: {
+ upload_file: {
+ extension: "html",
+ },
+ },
+ },
+ ],
+ total: 100,
+ id: req.params.id,
+ });
+ }
+ });
+
+ app.get("/datasets/:id/documents/:did/segments", async (req, res) => {
+ if (req.params.id === "0") res.send({ data: [] });
+ else {
+ res.send({
+ data: new Array(100).fill({
+ id: 1234,
+ content: `他的坚持让我很为难。众所周知他非常注意保护自己的隐私,而我想他应该从来没有看过我写的书。也许将来的某个时候吧,我还是这么说。但是,到了2009年,他的妻子劳伦·鲍威尔(Laurene Powell)直言不讳地对我说:“如果你真的打算写一本关于史蒂夫的书,最好现在就开始。”他当时刚刚第二次因病休假。我向劳伦坦承,当乔布斯第一次提出这个想法时,我并不知道他病了。几乎没有人知道,她说。他是在接受癌症手术之前给我打的电话,直到今天他还将此事作为一个秘密,她这么解释道。\n
+ 他的坚持让我很为难。众所周知他非常注意保护自己的隐私,而我想他应该从来没有看过我写的书。也许将来的某个时候吧,我还是这么说。但是,到了2009年,他的妻子劳伦·鲍威尔(Laurene Powell)直言不讳地对我说:“如果你真的打算写一本关于史蒂夫的书,最好现在就开始。”他当时刚刚第二次因病休假。我向劳伦坦承,当乔布斯第一次提出这个想法时,我并不知道他病了。几乎没有人知道,她说。他是在接受癌症手术之前给我打的电话,直到今天他还将此事作为一个秘密,她这么解释道。`,
+ enabled: true,
+ keyWords: [
+ "劳伦·鲍威尔",
+ "劳伦·鲍威尔",
+ "手术",
+ "秘密",
+ "癌症",
+ "乔布斯",
+ "史蒂夫",
+ "书",
+ "休假",
+ "坚持",
+ "隐私",
+ ],
+ word_count: 120,
+ hit_count: 100,
+ status: "ok",
+ index_node_hash: "index_node_hash value",
+ }),
+ limit: 100,
+ has_more: true,
+ });
+ }
+ });
+
+ // get doc detail
+ app.get("/datasets/:id/documents/:did", async (req, res) => {
+ const fixedParams = {
+ // originInfo: {
+ originalFilename: "Original filename",
+ originalFileSize: "16mb",
+ uploadDate: "2023-01-01",
+ lastUpdateDate: "2023-01-05",
+ source: "Source",
+ // },
+ // technicalParameters: {
+ segmentSpecification: "909090",
+ segmentLength: 100,
+ avgParagraphLength: 130,
+ };
+ const bookData = {
+ doc_type: "book",
+ doc_metadata: {
+ title: "机器学习实战",
+ language: "zh",
+ author: "Peter Harrington",
+ publisher: "人民邮电出版社",
+ publicationDate: "2013-01-01",
+ ISBN: "9787115335500",
+ category: "技术",
+ },
+ };
+ const webData = {
+ doc_type: "webPage",
+ doc_metadata: {
+ title: "深度学习入门教程",
+ url: "https://www.example.com/deep-learning-tutorial",
+ language: "zh",
+ publishDate: "2020-05-01",
+ authorPublisher: "张三",
+ topicsKeywords: "深度学习, 人工智能, 教程",
+ description:
+ "这是一篇详细的深度学习入门教程,适用于对人工智能和深度学习感兴趣的初学者。",
+ },
+ };
+ const postData = {
+ doc_type: "socialMediaPost",
+ doc_metadata: {
+ platform: "Twitter",
+ authorUsername: "example_user",
+ publishDate: "2021-08-15",
+ postURL: "https://twitter.com/example_user/status/1234567890",
+ topicsTags:
+ "AI, DeepLearning, Tutorial, Example, Example2, Example3, AI, DeepLearning, Tutorial, Example, Example2, Example3, AI, DeepLearning, Tutorial, Example, Example2, Example3,",
+ },
+ };
+ res.send({
+ id: "550e8400-e29b-41d4-a716-446655440000",
+ position: 1,
+ dataset_id: "550e8400-e29b-41d4-a716-446655440002",
+ data_source_type: "upload_file",
+ data_source_info: {
+ upload_file: {
+ extension: "html",
+ id: "550e8400-e29b-41d4-a716-446655440003",
+ },
+ },
+ dataset_process_rule_id: "550e8400-e29b-41d4-a716-446655440004",
+ batch: "20230410123456123456",
+ name: "example_document",
+ created_from: "web",
+ created_by: "550e8400-e29b-41d4-a716-446655440005",
+ created_api_request_id: "550e8400-e29b-41d4-a716-446655440006",
+ created_at: 1671269696,
+ processing_started_at: 1671269700,
+ word_count: 11,
+ parsing_completed_at: 1671269710,
+ cleaning_completed_at: 1671269720,
+ splitting_completed_at: 1671269730,
+ tokens: 10,
+ indexing_latency: 5.0,
+ completed_at: 1671269740,
+ paused_by: null,
+ paused_at: null,
+ error: null,
+ stopped_at: null,
+ indexing_status: "completed",
+ enabled: true,
+ disabled_at: null,
+ disabled_by: null,
+ archived: false,
+ archived_reason: null,
+ archived_by: null,
+ archived_at: null,
+ updated_at: 1671269740,
+ ...(req.params.did === "book"
+ ? bookData
+ : req.params.did === "web"
+ ? webData
+ : req.params.did === "post"
+ ? postData
+ : {}),
+ segment_count: 10,
+ hit_count: 9,
+ status: "ok",
+ });
+ });
+
+ // // logout
+ // app.get("/logout", async (req, res) => {
+ // res.send({
+ // result: "success",
+ // });
+ // });
+
+ // // Langgenius version
+ // app.get("/version", async (req, res) => {
+ // res.send({
+ // current_version: "v1.0.0",
+ // latest_version: "v1.0.0",
+ // upgradeable: true,
+ // compatible_upgrade: true,
+ // });
+ // });
+};
+
+module.exports = registerAPI;
diff --git a/mock-server/api/debug.js b/mock-server/api/debug.js
new file mode 100644
index 00000000000..2e6f3ca0a74
--- /dev/null
+++ b/mock-server/api/debug.js
@@ -0,0 +1,119 @@
+const registerAPI = function (app) {
+ const coversationList = [
+ {
+ id: '1',
+ name: '梦的解析',
+ inputs: {
+ book: '《梦的解析》',
+ callMe: '大师',
+ },
+ chats: []
+ },
+ {
+ id: '2',
+ name: '生命的起源',
+ inputs: {
+ book: '《x x x》',
+ }
+ },
+ ]
+ // site info
+ app.get('/apps/site/info', async (req, res) => {
+ // const id = req.params.id
+ res.send({
+ enable_site: true,
+ appId: '1',
+ site: {
+ title: 'Story Bot',
+ description: '这是一款解梦聊天机器人,你可以选择你喜欢的解梦人进行解梦,这句话是客户端应用说明',
+ },
+ prompt_public: true, //id === '1',
+ prompt_template: '你是我的解梦小助手,请参考 {{book}} 回答我有关梦境的问题。在回答前请称呼我为 {{myName}}。',
+ })
+ })
+
+ app.post('/apps/:id/chat-messages', async (req, res) => {
+ const conversationId = req.body.conversation_id ? req.body.conversation_id : Date.now() + ''
+ res.send({
+ id: Date.now() + '',
+ conversation_id: Date.now() + '',
+ answer: 'balabababab'
+ })
+ })
+
+ app.post('/apps/:id/completion-messages', async (req, res) => {
+ res.send({
+ id: Date.now() + '',
+ answer: `做为一个AI助手,我可以为你提供随机生成的段落,这些段落可以用于测试、占位符、或者其他目的。以下是一个随机生成的段落:
+
+ “随着科技的不断发展,越来越多的人开始意识到人工智能的重要性。人工智能已经成为我们生活中不可或缺的一部分,它可以帮助我们完成很多繁琐的工作,也可以为我们提供更智能、更便捷的服务。虽然人工智能带来了很多好处,但它也面临着很多挑战。例如,人工智能的算法可能会出现偏见,导致对某些人群不公平。此外,人工智能的发展也可能会导致一些工作的失业。因此,我们需要不断地研究人工智能的发展,以确保它能够为人类带来更多的好处。”`
+ })
+ })
+
+ // share api
+ // chat list
+ app.get('/apps/:id/coversations', async (req, res) => {
+ res.send({
+ data: coversationList
+ })
+ })
+
+
+
+ app.get('/apps/:id/variables', async (req, res) => {
+ res.send({
+ variables: [
+ {
+ key: 'book',
+ name: '书',
+ value: '《梦境解析》',
+ type: 'string'
+ },
+ {
+ key: 'myName',
+ name: '称呼',
+ value: '',
+ type: 'string'
+ }
+ ],
+ })
+ })
+
+}
+
+module.exports = registerAPI
+
+// const chatList = [
+// {
+// id: 1,
+// content: 'AI 开场白',
+// isAnswer: true,
+// },
+// {
+// id: 2,
+// content: '梦见在山上手撕鬼子,大师解解梦',
+// more: { time: '5.6 秒' },
+// },
+// {
+// id: 3,
+// content: '梦境通常是个人内心深处的反映,很难确定每个人梦境的确切含义,因为它们可能会受到梦境者的文化背景、生活经验和情感状态等多种因素的影响。',
+// isAnswer: true,
+// more: { time: '99 秒' },
+
+// },
+// {
+// id: 4,
+// content: '梦见在山上手撕鬼子,大师解解梦',
+// more: { time: '5.6 秒' },
+// },
+// {
+// id: 5,
+// content: '梦见在山上手撕鬼子,大师解解梦',
+// more: { time: '5.6 秒' },
+// },
+// {
+// id: 6,
+// content: '梦见在山上手撕鬼子,大师解解梦',
+// more: { time: '5.6 秒' },
+// },
+// ]
\ No newline at end of file
diff --git a/mock-server/api/demo.js b/mock-server/api/demo.js
new file mode 100644
index 00000000000..8f8a35079b6
--- /dev/null
+++ b/mock-server/api/demo.js
@@ -0,0 +1,15 @@
+const registerAPI = function (app) {
+ app.get('/demo', async (req, res) => {
+ res.send({
+ des: 'get res'
+ })
+ })
+
+ app.post('/demo', async (req, res) => {
+ res.send({
+ des: 'post res'
+ })
+ })
+}
+
+module.exports = registerAPI
\ No newline at end of file
diff --git a/mock-server/app.js b/mock-server/app.js
new file mode 100644
index 00000000000..96eec0ab2ae
--- /dev/null
+++ b/mock-server/app.js
@@ -0,0 +1,42 @@
+const express = require('express')
+const app = express()
+const bodyParser = require('body-parser')
+var cors = require('cors')
+
+const commonAPI = require('./api/common')
+const demoAPI = require('./api/demo')
+const appsApi = require('./api/apps')
+const debugAPI = require('./api/debug')
+const datasetsAPI = require('./api/datasets')
+
+const port = 3001
+
+app.use(bodyParser.json()) // for parsing application/json
+app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
+
+const corsOptions = {
+ origin: true,
+ credentials: true,
+}
+app.use(cors(corsOptions)) // for cross origin
+app.options('*', cors(corsOptions)) // include before other routes
+
+
+demoAPI(app)
+commonAPI(app)
+appsApi(app)
+debugAPI(app)
+datasetsAPI(app)
+
+
+app.get('/', (req, res) => {
+ res.send('rootpath')
+})
+
+app.listen(port, () => {
+ console.log(`Mock run on port ${port}`)
+})
+
+const sleep = (ms) => {
+ return new Promise(resolve => setTimeout(resolve, ms))
+}
diff --git a/mock-server/package.json b/mock-server/package.json
new file mode 100644
index 00000000000..11a68d61e79
--- /dev/null
+++ b/mock-server/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "server",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "dev": "nodemon node app.js",
+ "start": "node app.js",
+ "tcp": "node tcp.js"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.0.0"
+ },
+ "dependencies": {
+ "body-parser": "^1.20.2",
+ "cors": "^2.8.5",
+ "express": "4.18.2",
+ "express-jwt": "8.4.1"
+ },
+ "devDependencies": {
+ "nodemon": "2.0.21"
+ }
+}
diff --git a/sdks/nodejs-client/.gitignore b/sdks/nodejs-client/.gitignore
new file mode 100644
index 00000000000..2c013281550
--- /dev/null
+++ b/sdks/nodejs-client/.gitignore
@@ -0,0 +1,49 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+.pnpm-debug.log*
+
+# local env files
+.env*.local
+
+# vercel
+.vercel
+
+# typescript
+*.tsbuildinfo
+next-env.d.ts
+
+# npm
+package-lock.json
+
+# yarn
+.pnp.cjs
+.pnp.loader.mjs
+.yarn/
+yarn.lock
+.yarnrc.yml
+
+# pmpm
+pnpm-lock.yaml
\ No newline at end of file
diff --git a/sdks/nodejs-client/README.md b/sdks/nodejs-client/README.md
new file mode 100644
index 00000000000..1bfd5f5e006
--- /dev/null
+++ b/sdks/nodejs-client/README.md
@@ -0,0 +1,46 @@
+# Dify Node.js SDK
+This is the Node.js SDK for the Dify API, which allows you to easily integrate Dify into your Node.js applications.
+
+## Install
+```bash
+npm install dify-client
+```
+
+## Usage
+After installing the SDK, you can use it in your project like this:
+
+```js
+import { DifyClient, ChatClient, CompletionClient } from 'dify-client'
+
+const API_KEY = 'your-api-key-here';
+const user = `random-user-id`:
+
+// Create a completion client
+const completionClient = new CompletionClient(API_KEY)
+// Create a completion message
+completionClient.createCompletionMessage(inputs, query, responseMode, user)
+
+// Create a chat client
+const chatClient = new ChatClient(API_KEY)
+// Create a chat message
+chatClient.createChatMessage(inputs, query, responseMode, user, conversationId)
+// Fetch conversations
+chatClient.getConversations(user)
+// Fetch conversation messages
+chatClient.getConversationMessages(conversationId, user)
+// Rename conversation
+chatClient.renameConversation(conversationId, name, user)
+
+
+const client = new DifyClient(API_KEY)
+// Fetch application parameters
+client.getApplicationParameters(user)
+// Provide feedback for a message
+client.messageFeedback(messageId, rating, user)
+
+```
+
+Replace 'your-api-key-here' with your actual Dify API key.Replace 'your-app-id-here' with your actual Dify APP ID.
+
+## License
+This SDK is released under the MIT License.
diff --git a/sdks/nodejs-client/index.js b/sdks/nodejs-client/index.js
new file mode 100644
index 00000000000..902ecbd880d
--- /dev/null
+++ b/sdks/nodejs-client/index.js
@@ -0,0 +1,140 @@
+import axios from 'axios'
+
+const BASE_URL = 'https://api.dify.ai/v1'
+
+const routes = {
+ application: {
+ method: 'GET',
+ url: () => `/parameters`
+ },
+ feedback: {
+ method: 'POST',
+ url: (messageId) => `/messages/${messageId}/feedbacks`,
+ },
+ createCompletionMessage: {
+ method: 'POST',
+ url: () => `/completion-messages`,
+ },
+ createChatMessage: {
+ method: 'POST',
+ url: () => `/chat-message`,
+ },
+ getConversationMessages: {
+ method: 'GET',
+ url: () => '/messages',
+ },
+ getConversations: {
+ method: 'GET',
+ url: () => '/conversations',
+ },
+ renameConversation: {
+ method: 'PATCH',
+ url: (conversationId) => `/conversations/${conversationId}`,
+ }
+
+}
+
+export class DifyClient {
+ constructor(apiKey, baseUrl = BASE_URL) {
+ this.apiKey = apiKey
+ this.baseUrl = baseUrl
+ }
+
+ updateApiKey(apiKey) {
+ this.apiKey = apiKey
+ }
+
+ async sendRequest(method, endpoint, data = null, params = null, stream = false) {
+ const headers = {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ }
+
+ const url = `${this.baseUrl}${endpoint}`
+ let response
+ if (!stream) {
+ response = await axios({
+ method,
+ url,
+ data,
+ params,
+ headers,
+ responseType: stream ? 'stream' : 'json',
+ })
+ } else {
+ response = await fetch(url, {
+ headers,
+ method,
+ body: JSON.stringify(data),
+ })
+ }
+
+ return response
+ }
+
+ messageFeedback(messageId, rating, user) {
+ const data = {
+ rating,
+ user,
+ }
+ return this.sendRequest(routes.feedback.method, routes.feedback.url(messageId), data)
+ }
+
+ getApplicationParameters(user) {
+ const params = { user }
+ return this.sendRequest(routes.application.method, routes.application.url(), null, params)
+ }
+}
+
+export class CompletionClient extends DifyClient {
+ createCompletionMessage(inputs, query, user, responseMode) {
+ const data = {
+ inputs,
+ query,
+ responseMode,
+ user,
+ }
+ return this.sendRequest(routes.createCompletionMessage.method, routes.createCompletionMessage.url(), data, null, responseMode === 'streaming')
+ }
+}
+
+export class ChatClient extends DifyClient {
+ createChatMessage(inputs, query, user, responseMode = 'blocking', conversationId = null) {
+ const data = {
+ inputs,
+ query,
+ user,
+ responseMode,
+ }
+ if (conversationId)
+ data.conversation_id = conversationId
+
+ return this.sendRequest(routes.createChatMessage.method, routes.createChatMessage.url(), data, null, responseMode === 'streaming')
+ }
+
+ getConversationMessages(user, conversationId = '', firstId = null, limit = null) {
+ const params = { user }
+
+ if (conversationId)
+ params.conversation_id = conversationId
+
+ if (firstId)
+ params.first_id = firstId
+
+ if (limit)
+ params.limit = limit
+
+ return this.sendRequest(routes.getConversationMessages.method, routes.getConversationMessages.url(), null, params)
+ }
+
+ getConversations(user, firstId = null, limit = null, pinned = null) {
+ const params = { user, first_id: firstId, limit, pinned }
+ return this.sendRequest(routes.getConversations.method, routes.getConversations.url(), null, params)
+ }
+
+ renameConversation(conversationId, name, user) {
+ const data = { name, user }
+ return this.sendRequest(routes.renameConversation.method, routes.renameConversation.url(conversationId), data)
+ }
+}
+
diff --git a/sdks/nodejs-client/package.json b/sdks/nodejs-client/package.json
new file mode 100644
index 00000000000..350cfc97328
--- /dev/null
+++ b/sdks/nodejs-client/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "dify-client",
+ "version": "1.0.2",
+ "description": "This is the Node.js SDK for the Dify.AI API, which allows you to easily integrate Dify.AI into your Node.js applications.",
+ "main": "index.js",
+ "type": "module",
+ "keywords": [
+ "Dify",
+ "Dify.AI",
+ "LLM"
+ ],
+ "author": "Joel",
+ "contributors": [
+ "<crazywoola> <<[email protected]>> (https://github.com/crazywoola)"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "axios": "^1.3.5"
+ }
+}
\ No newline at end of file
diff --git a/sdks/php-client/README.md b/sdks/php-client/README.md
new file mode 100644
index 00000000000..a44abc0f806
--- /dev/null
+++ b/sdks/php-client/README.md
@@ -0,0 +1,51 @@
+# Dify PHP SDK
+
+This is the PHP SDK for the Dify API, which allows you to easily integrate Dify into your PHP applications.
+
+## Requirements
+
+- PHP 7.2 or later
+- Guzzle HTTP client library
+
+## Usage
+
+After installing the SDK, you can use it in your project like this:
+
+```
+<?php
+
+require 'vendor/autoload.php';
+
+use YourVendorName\DifyPHP\DifyClient;
+use YourVendorName\DifyPHP\CompletionClient;
+use YourVendorName\DifyPHP\ChatClient;
+
+$apiKey = 'your-api-key-here';
+
+$difyClient = new DifyClient($apiKey);
+
+// Create a completion client
+$completionClient = new CompletionClient($apiKey);
+$response = $completionClient->create_completion_message($inputs, $query, $response_mode, $user);
+
+// Create a chat client
+$chatClient = new ChatClient($apiKey);
+$response = $chatClient->create_chat_message($inputs, $query, $user, $response_mode, $conversation_id);
+
+// Fetch application parameters
+$response = $difyClient->get_application_parameters($user);
+
+// Provide feedback for a message
+$response = $difyClient->message_feedback($message_id, $rating, $user);
+
+// Other available methods:
+// - get_conversation_messages()
+// - get_conversations()
+// - rename_conversation()
+```
+
+Replace 'your-api-key-here' with your actual Dify API key.
+
+## License
+
+This SDK is released under the MIT License.
\ No newline at end of file
diff --git a/sdks/php-client/dify-client.php b/sdks/php-client/dify-client.php
new file mode 100644
index 00000000000..7a5d9b60cfd
--- /dev/null
+++ b/sdks/php-client/dify-client.php
@@ -0,0 +1,109 @@
+<?php
+
+require 'vendor/autoload.php';
+
+use GuzzleHttp\Client;
+
+class DifyClient {
+ protected $api_key;
+ protected $base_url;
+ protected $client;
+
+ public function __construct($api_key) {
+ $this->api_key = $api_key;
+ $this->base_url = "https://api.dify.ai/v1";
+ $this->client = new Client([
+ 'base_uri' => $this->base_url,
+ 'headers' => [
+ 'Authorization' => 'Bearer ' . $this->api_key,
+ 'Content-Type' => 'application/json',
+ ],
+ ]);
+ }
+
+ protected function send_request($method, $endpoint, $data = null, $params = null, $stream = false) {
+ $options = [
+ 'json' => $data,
+ 'query' => $params,
+ 'stream' => $stream,
+ ];
+
+ $response = $this->client->request($method, $endpoint, $options);
+ return $response;
+ }
+
+ public function message_feedback($message_id, $rating, $user) {
+ $data = [
+ 'rating' => $rating,
+ 'user' => $user,
+ ];
+ return $this->send_request('POST', "/messages/{$message_id}/feedbacks", $data);
+ }
+
+ public function get_application_parameters($user) {
+ $params = ['user' => $user];
+ return $this->send_request('GET', '/parameters', null, $params);
+ }
+}
+
+class CompletionClient extends DifyClient {
+ public function create_completion_message($inputs, $query, $response_mode, $user) {
+ $data = [
+ 'inputs' => $inputs,
+ 'query' => $query,
+ 'response_mode' => $response_mode,
+ 'user' => $user,
+ ];
+ return $this->send_request('POST', '/completion-messages', $data, null, $response_mode === 'streaming');
+ }
+}
+
+class ChatClient extends DifyClient {
+ public function create_chat_message($inputs, $query, $user, $response_mode = 'blocking', $conversation_id = null) {
+ $data = [
+ 'inputs' => $inputs,
+ 'query' => $query,
+ 'user' => $user,
+ 'response_mode' => $response_mode,
+ ];
+ if ($conversation_id) {
+ $data['conversation_id'] = $conversation_id;
+ }
+
+ return $this->send_request('POST', '/chat-messages', $data, null, $response_mode === 'streaming');
+ }
+
+ public function get_conversation_messages($user, $conversation_id = null, $first_id = null, $limit = null) {
+ $params = ['user' => $user];
+
+ if ($conversation_id) {
+ $params['conversation_id'] = $conversation_id;
+ }
+ if ($first_id) {
+ $params['first_id'] = $first_id;
+ }
+ if ($limit) {
+ $params['limit'] = $limit;
+ }
+
+ return $this->send_request('GET', '/messages', null, $params);
+ }
+
+ public function get_conversations($user, $first_id = null, $limit = null, $pinned = null) {
+ $params = [
+ 'user' => $user,
+ 'first_id' => $first_id,
+ 'limit' => $limit,
+ 'pinned'=> $pinned,
+ ];
+ return $this->send_request('GET', '/conversations', null, $params);
+ }
+
+ public function rename_conversation($conversation_id, $name, $user) {
+ $data = [
+ 'name' => $name,
+ 'user' => $user,
+ ];
+ return $this->send_request('PATCH', "/conversations/{$conversation_id}", $data);
+ }
+}
diff --git a/sdks/python-client/LICENSE b/sdks/python-client/LICENSE
new file mode 100644
index 00000000000..873e44b4bc4
--- /dev/null
+++ b/sdks/python-client/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 LangGenius
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/sdks/python-client/MANIFEST.in b/sdks/python-client/MANIFEST.in
new file mode 100644
index 00000000000..da331d5e5ca
--- /dev/null
+++ b/sdks/python-client/MANIFEST.in
@@ -0,0 +1 @@
+recursive-include dify_client *.py
\ No newline at end of file
diff --git a/sdks/python-client/README.md b/sdks/python-client/README.md
new file mode 100644
index 00000000000..0997d326328
--- /dev/null
+++ b/sdks/python-client/README.md
@@ -0,0 +1,100 @@
+# dify-client
+
+A Dify App Service-API Client, using for build a webapp by request Service-API
+
+## Usage
+
+First, install `dify-client` python sdk package:
+
+```
+pip install dify-client
+```
+
+Write your code with sdk:
+
+- completion generate with `blocking` response_mode
+
+```
+import json
+from dify_client import CompletionClient
+
+api_key = "your_api_key"
+
+# Initialize CompletionClient
+completion_client = CompletionClient(api_key)
+
+# Create Completion Message using CompletionClient
+completion_response = completion_client.create_completion_message(inputs={}, query="Hello", response_mode="blocking", user="user_id")
+completion_response.raise_for_status()
+
+result = completion_response.text
+result = json.loads(result)
+
+print(result.get('answer'))
+```
+
+- chat generate with `streaming` response_mode
+
+```
+import json
+from dify_client import ChatClient
+
+api_key = "your_api_key"
+
+# Initialize ChatClient
+chat_client = ChatClient(api_key)
+
+# Create Chat Message using ChatClient
+chat_response = chat_client.create_chat_message(inputs={}, query="Hello", user="user_id", response_mode="streaming")
+chat_response.raise_for_status()
+
+for line in chat_response.iter_lines(decode_unicode=True):
+ line = line.split('data:', 1)[-1]
+ if line.strip():
+ line = json.loads(line.strip())
+ print(line.get('answer'))
+```
+
+- Others
+
+```
+import json
+from dify_client import ChatClient
+
+api_key = "your_api_key"
+
+# Initialize Client
+client = ChatClient(api_key)
+
+# Get App parameters
+parameters = client.get_application_parameters(user="user_id")
+parameters.raise_for_status()
+parameters = json.loads(parameters.text)
+
+print('[parameters]')
+print(parameters)
+
+# Get Conversation List (only for chat)
+conversations = client.get_conversations(user="user_id")
+conversations.raise_for_status()
+conversations = json.loads(conversations.text)
+
+print('[conversations]')
+print(conversations)
+
+# Get Message List (only for chat)
+messages = client.get_conversation_messages(user="user_id", conversation_id="conversation_id")
+messages.raise_for_status()
+messages = json.loads(messages.text)
+
+print('[messages]')
+print(messages)
+
+# Rename Conversation (only for chat)
+rename_conversation_response = client.rename_conversation(conversation_id="conversation_id", name="new_name", user="user_id")
+rename_conversation_response.raise_for_status()
+rename_conversation_result = json.loads(rename_conversation_response.text)
+
+print('[rename result]')
+print(rename_conversation_result)
+```
diff --git a/sdks/python-client/build.sh b/sdks/python-client/build.sh
new file mode 100755
index 00000000000..ca1a762c996
--- /dev/null
+++ b/sdks/python-client/build.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+set -e
+
+rm -rf build dist *.egg-info
+
+pip install setuptools wheel twine
+python setup.py sdist bdist_wheel
+twine upload dist/*
\ No newline at end of file
diff --git a/sdks/python-client/dify_client/__init__.py b/sdks/python-client/dify_client/__init__.py
new file mode 100644
index 00000000000..471b8d19903
--- /dev/null
+++ b/sdks/python-client/dify_client/__init__.py
@@ -0,0 +1 @@
+from dify_client.client import ChatClient, CompletionClient
\ No newline at end of file
diff --git a/sdks/python-client/dify_client/client.py b/sdks/python-client/dify_client/client.py
new file mode 100644
index 00000000000..1a8bc3602ed
--- /dev/null
+++ b/sdks/python-client/dify_client/client.py
@@ -0,0 +1,74 @@
+import requests
+
+
+class DifyClient:
+ def __init__(self, api_key):
+ self.api_key = api_key
+ self.base_url = "https://api.dify.ai/v1"
+
+ def _send_request(self, method, endpoint, data=None, params=None, stream=False):
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json"
+ }
+
+ url = f"{self.base_url}{endpoint}"
+ response = requests.request(method, url, json=data, params=params, headers=headers, stream=stream)
+
+ return response
+
+ def message_feedback(self, message_id, rating, user):
+ data = {
+ "rating": rating,
+ "user": user
+ }
+ return self._send_request("POST", f"/messages/{message_id}/feedbacks", data)
+
+ def get_application_parameters(self, user):
+ params = {"user": user}
+ return self._send_request("GET", "/parameters", params=params)
+
+
+class CompletionClient(DifyClient):
+ def create_completion_message(self, inputs, query, response_mode, user):
+ data = {
+ "inputs": inputs,
+ "query": query,
+ "response_mode": response_mode,
+ "user": user
+ }
+ return self._send_request("POST", "/completion-messages", data, stream=True if response_mode == "streaming" else False)
+
+
+class ChatClient(DifyClient):
+ def create_chat_message(self, inputs, query, user, response_mode="blocking", conversation_id=None):
+ data = {
+ "inputs": inputs,
+ "query": query,
+ "user": user,
+ "response_mode": response_mode
+ }
+ if conversation_id:
+ data["conversation_id"] = conversation_id
+
+ return self._send_request("POST", "/chat-messages", data, stream=True if response_mode == "streaming" else False)
+
+ def get_conversation_messages(self, user, conversation_id=None, first_id=None, limit=None):
+ params = {"user": user}
+
+ if conversation_id:
+ params["conversation_id"] = conversation_id
+ if first_id:
+ params["first_id"] = first_id
+ if limit:
+ params["limit"] = limit
+
+ return self._send_request("GET", "/messages", params=params)
+
+ def get_conversations(self, user, first_id=None, limit=None, pinned=None):
+ params = {"user": user, "first_id": first_id, "limit": limit, "pinned": pinned}
+ return self._send_request("GET", "/conversations", params=params)
+
+ def rename_conversation(self, conversation_id, name, user):
+ data = {"name": name, "user": user}
+ return self._send_request("POST", f"/conversations/{conversation_id}/name", data)
diff --git a/sdks/python-client/setup.py b/sdks/python-client/setup.py
new file mode 100644
index 00000000000..17ba87fde28
--- /dev/null
+++ b/sdks/python-client/setup.py
@@ -0,0 +1,28 @@
+from setuptools import setup
+
+with open("README.md", "r", encoding="utf-8") as fh:
+ long_description = fh.read()
+
+setup(
+ name="dify-client",
+ version="0.1.7",
+ author="Dify",
+ author_email="[email protected]",
+ description="A package for interacting with the Dify Service-API",
+ long_description=long_description,
+ long_description_content_type="text/markdown",
+ url="https://github.com/langgenius/dify",
+ license='MIT',
+ packages=['dify_client'],
+ classifiers=[
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: OS Independent",
+ ],
+ python_requires=">=3.6",
+ install_requires=[
+ "requests"
+ ],
+ keywords='dify nlp ai language-processing',
+ include_package_data=True,
+)
diff --git a/sdks/python-client/tests/__init__.py b/sdks/python-client/tests/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/sdks/python-client/tests/test_client.py b/sdks/python-client/tests/test_client.py
new file mode 100644
index 00000000000..f123c1882b2
--- /dev/null
+++ b/sdks/python-client/tests/test_client.py
@@ -0,0 +1,49 @@
+import os
+import unittest
+from dify_client.client import ChatClient, CompletionClient, DifyClient
+
+API_KEY = os.environ.get("API_KEY")
+APP_ID = os.environ.get("APP_ID")
+
+
+class TestChatClient(unittest.TestCase):
+ def setUp(self):
+ self.chat_client = ChatClient(API_KEY)
+
+ def test_create_chat_message(self):
+ response = self.chat_client.create_chat_message({}, "Hello, World!", "test_user")
+ self.assertIn("message_id", response)
+
+ def test_get_conversation_messages(self):
+ response = self.chat_client.get_conversation_messages("test_user")
+ self.assertIsInstance(response, list)
+
+ def test_get_conversations(self):
+ response = self.chat_client.get_conversations("test_user")
+ self.assertIsInstance(response, list)
+
+
+class TestCompletionClient(unittest.TestCase):
+ def setUp(self):
+ self.completion_client = CompletionClient(API_KEY)
+
+ def test_create_completion_message(self):
+ response = self.completion_client.create_completion_message({}, "What's the weather like today?", "blocking", "test_user")
+ self.assertIn("message_id", response)
+
+
+class TestDifyClient(unittest.TestCase):
+ def setUp(self):
+ self.dify_client = DifyClient(API_KEY)
+
+ def test_message_feedback(self):
+ response = self.dify_client.message_feedback("test_message_id", 5, "test_user")
+ self.assertIn("success", response)
+
+ def test_get_application_parameters(self):
+ response = self.dify_client.get_application_parameters("test_user")
+ self.assertIsInstance(response, dict)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/web/.editorconfig b/web/.editorconfig
new file mode 100644
index 00000000000..e1d3f0b9928
--- /dev/null
+++ b/web/.editorconfig
@@ -0,0 +1,22 @@
+# EditorConfig is awesome: https://EditorConfig.org
+
+# top-most EditorConfig file
+root = true
+
+# Unix-style newlines with a newline ending every file
+[*]
+end_of_line = lf
+insert_final_newline = true
+
+# Matches multiple files with brace expansion notation
+# Set default charset
+[*.{js,tsx}]
+charset = utf-8
+indent_style = space
+indent_size = 2
+
+
+# Matches the exact files either package.json or .travis.yml
+[{package.json,.travis.yml}]
+indent_style = space
+indent_size = 2
diff --git a/web/.eslintrc.json b/web/.eslintrc.json
new file mode 100644
index 00000000000..db813b0b253
--- /dev/null
+++ b/web/.eslintrc.json
@@ -0,0 +1,28 @@
+{
+ "extends": [
+ "@antfu",
+ "plugin:react-hooks/recommended"
+ ],
+ "rules": {
+ "@typescript-eslint/consistent-type-definitions": [
+ "error",
+ "type"
+ ],
+ "no-console": "off",
+ "indent": "off",
+ "@typescript-eslint/indent": [
+ "error",
+ 2,
+ {
+ "SwitchCase": 1,
+ "flatTernaryExpressions": false,
+ "ignoredNodes": [
+ "PropertyDefinition[decorators]",
+ "TSUnionType",
+ "FunctionExpression[params]:has(Identifier[decorators])"
+ ]
+ }
+ ],
+ "react-hooks/exhaustive-deps": "warning"
+ }
+}
diff --git a/web/.gitignore b/web/.gitignore
new file mode 100644
index 00000000000..2c013281550
--- /dev/null
+++ b/web/.gitignore
@@ -0,0 +1,49 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+.pnpm-debug.log*
+
+# local env files
+.env*.local
+
+# vercel
+.vercel
+
+# typescript
+*.tsbuildinfo
+next-env.d.ts
+
+# npm
+package-lock.json
+
+# yarn
+.pnp.cjs
+.pnp.loader.mjs
+.yarn/
+yarn.lock
+.yarnrc.yml
+
+# pmpm
+pnpm-lock.yaml
\ No newline at end of file
diff --git a/web/Dockerfile b/web/Dockerfile
new file mode 100644
index 00000000000..315a13e896c
--- /dev/null
+++ b/web/Dockerfile
@@ -0,0 +1,29 @@
+FROM langgenius/base:1.0.0-bullseye-slim
+
+LABEL maintainer="[email protected]"
+
+ENV EDITION SELF_HOSTED
+ENV DEPLOY_ENV PRODUCTION
+ENV CONSOLE_URL http://127.0.0.1:5001
+ENV APP_URL http://127.0.0.1:5001
+
+EXPOSE 3000
+
+WORKDIR /app/web
+
+COPY package.json /app/web/package.json
+
+RUN npm install
+
+COPY . /app/web/
+
+RUN npm run build
+
+COPY docker/pm2.json /app/web/pm2.json
+COPY docker/entrypoint.sh /entrypoint.sh
+RUN chmod +x /entrypoint.sh
+
+ARG COMMIT_SHA
+ENV COMMIT_SHA ${COMMIT_SHA}
+
+ENTRYPOINT ["/entrypoint.sh"]
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 00000000000..710e8062d10
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,39 @@
+# Dify Frontend
+This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
+
+## Getting Started
+
+First, run the development server:
+
+```bash
+npm run dev
+# or
+yarn dev
+# or
+pnpm dev
+```
+
+Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
+
+You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
+
+[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.
+
+The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
+
+This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
+
+## Learn More
+
+To learn more about Next.js, take a look at the following resources:
+
+- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
+- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
+
+You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
+
+## Deploy on Vercel
+
+The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
+
+Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
diff --git a/web/app/(commonLayout)/_layout-client.tsx b/web/app/(commonLayout)/_layout-client.tsx
new file mode 100644
index 00000000000..8624091de29
--- /dev/null
+++ b/web/app/(commonLayout)/_layout-client.tsx
@@ -0,0 +1,85 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useState } from 'react'
+import { usePathname, useRouter, useSelectedLayoutSegments } from 'next/navigation'
+import useSWR, { SWRConfig } from 'swr'
+import Header from '../components/header'
+import { fetchAppList } from '@/service/apps'
+import { fetchDatasets } from '@/service/datasets'
+import { fetchLanggeniusVersion, fetchUserProfile, logout } from '@/service/common'
+import Loading from '@/app/components/base/loading'
+import AppContext from '@/context/app-context'
+import DatasetsContext from '@/context/datasets-context'
+import type { LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
+
+export type ICommonLayoutProps = {
+ children: React.ReactNode
+}
+
+const CommonLayout: FC<ICommonLayoutProps> = ({ children }) => {
+ const router = useRouter()
+ const pathname = usePathname()
+ const segments = useSelectedLayoutSegments()
+ const pattern = pathname.replace(/.*\/app\//, '')
+ const [idOrMethod] = pattern.split('/')
+ const isNotDetailPage = idOrMethod === 'list'
+
+ const appId = isNotDetailPage ? '' : idOrMethod
+
+ const { data: appList, mutate: mutateApps } = useSWR({ url: '/apps', params: { page: 1 } }, fetchAppList)
+ const { data: datasetList, mutate: mutateDatasets } = useSWR(segments[0] === 'datasets' ? { url: '/datasets', params: { page: 1 } } : null, fetchDatasets)
+ const { data: userProfileResponse, mutate: mutateUserProfile } = useSWR({ url: '/account/profile', params: {} }, fetchUserProfile)
+
+ const [userProfile, setUserProfile] = useState<UserProfileResponse>()
+ const [langeniusVersionInfo, setLangeniusVersionInfo] = useState<LangGeniusVersionResponse>()
+ const updateUserProfileAndVersion = async () => {
+ if (userProfileResponse && !userProfileResponse.bodyUsed) {
+ const result = await userProfileResponse.json()
+ setUserProfile(result)
+ const current_version = userProfileResponse.headers.get('x-version')
+ const current_env = userProfileResponse.headers.get('x-env')
+ const versionData = await fetchLanggeniusVersion({ url: '/version', params: { current_version } })
+ setLangeniusVersionInfo({ ...versionData, current_version, latest_version: versionData.version, current_env })
+ }
+ }
+ useEffect(() => {
+ updateUserProfileAndVersion()
+ }, [userProfileResponse])
+
+ if (!appList || !userProfile || !langeniusVersionInfo)
+ return <Loading type='app' />
+
+ const curApp = appList?.data.find(opt => opt.id === appId)
+ const currentDatasetId = segments[0] === 'datasets' && segments[2]
+ const currentDataset = datasetList?.data?.find(opt => opt.id === currentDatasetId)
+
+ // if (!isNotDetailPage && !curApp) {
+ // alert('app not found') // TODO: use toast. Now can not get toast context here.
+ // // notify({ type: 'error', message: 'App not found' })
+ // router.push('/apps')
+ // }
+
+ const onLogout = async () => {
+ await logout({
+ url: '/logout',
+ params: {},
+ })
+ router.push('/signin')
+ }
+
+ return (
+ <SWRConfig value={{
+ shouldRetryOnError: false
+ }}>
+ <AppContext.Provider value={{ apps: appList.data, mutateApps, userProfile, mutateUserProfile }}>
+ <DatasetsContext.Provider value={{ datasets: datasetList?.data || [], mutateDatasets, currentDataset }}>
+ <div className='relative flex flex-col h-full overflow-scroll bg-gray-100'>
+ <Header isBordered={['/apps', '/datasets'].includes(pathname)} curApp={curApp as any} appItems={appList.data} userProfile={userProfile} onLogout={onLogout} langeniusVersionInfo={langeniusVersionInfo} />
+ {children}
+ </div>
+ </DatasetsContext.Provider>
+ </AppContext.Provider>
+ </SWRConfig>
+ )
+}
+export default React.memo(CommonLayout)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/configuration/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/configuration/page.tsx
new file mode 100644
index 00000000000..41143b979a1
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/configuration/page.tsx
@@ -0,0 +1,10 @@
+import React from 'react'
+import Configuration from '@/app/components/app/configuration'
+
+const IConfiguration = async () => {
+ return (
+ <Configuration />
+ )
+}
+
+export default IConfiguration
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/develop/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/develop/page.tsx
new file mode 100644
index 00000000000..d544059a846
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/develop/page.tsx
@@ -0,0 +1,18 @@
+import React from 'react'
+import { getDictionary } from '@/i18n/server'
+import { type Locale } from '@/i18n'
+import DevelopMain from '@/app/components/develop'
+
+export type IDevelopProps = {
+ params: { locale: Locale; appId: string }
+}
+
+const Develop = async ({
+ params: { locale, appId },
+}: IDevelopProps) => {
+ const dictionary = await getDictionary(locale)
+
+ return <DevelopMain appId={appId} dictionary={dictionary} />
+}
+
+export default Develop
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout.tsx
new file mode 100644
index 00000000000..049d908dde5
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout.tsx
@@ -0,0 +1,57 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect } from 'react'
+import cn from 'classnames'
+import useSWR from 'swr'
+import { useTranslation } from 'react-i18next'
+import {
+ ChartBarSquareIcon,
+ Cog8ToothIcon,
+ CommandLineIcon,
+ DocumentTextIcon,
+} from '@heroicons/react/24/outline'
+import {
+ ChartBarSquareIcon as ChartBarSquareSolidIcon,
+ Cog8ToothIcon as Cog8ToothSolidIcon,
+ CommandLineIcon as CommandLineSolidIcon,
+ DocumentTextIcon as DocumentTextSolidIcon,
+} from '@heroicons/react/24/solid'
+import s from './style.module.css'
+import AppSideBar from '@/app/components/app-sidebar'
+import { fetchAppDetail } from '@/service/apps'
+
+export type IAppDetailLayoutProps = {
+ children: React.ReactNode
+ params: { appId: string }
+}
+
+const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
+ const {
+ children,
+ params: { appId }, // get appId in path
+ } = props
+ const { t } = useTranslation()
+ const detailParams = { url: '/apps', id: appId }
+ const { data: response } = useSWR(detailParams, fetchAppDetail)
+
+ const navigation = [
+ { name: t('common.appMenus.overview'), href: `/app/${appId}/overview`, icon: ChartBarSquareIcon, selectedIcon: ChartBarSquareSolidIcon },
+ { name: t('common.appMenus.promptEng'), href: `/app/${appId}/configuration`, icon: Cog8ToothIcon, selectedIcon: Cog8ToothSolidIcon },
+ { name: t('common.appMenus.apiAccess'), href: `/app/${appId}/develop`, icon: CommandLineIcon, selectedIcon: CommandLineSolidIcon },
+ { name: t('common.appMenus.logAndAnn'), href: `/app/${appId}/logs`, icon: DocumentTextIcon, selectedIcon: DocumentTextSolidIcon },
+ ]
+ const appModeName = response?.mode?.toUpperCase() === 'COMPLETION' ? t('common.appModes.completionApp') : t('common.appModes.chatApp')
+ useEffect(() => {
+ if (response?.name)
+ document.title = `${(response.name || 'App')} - Dify`
+ }, [response])
+ if (!response)
+ return null
+ return (
+ <div className={cn(s.app, 'flex', 'overflow-hidden')}>
+ <AppSideBar title={response.name} desc={appModeName} navigation={navigation} />
+ <div className="bg-white grow">{children}</div>
+ </div>
+ )
+}
+export default React.memo(AppDetailLayout)
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx
new file mode 100644
index 00000000000..6c17986ce6b
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import Main from '@/app/components/app/log'
+
+export type IProps = {
+ params: { appId: string }
+}
+
+const Logs = async ({
+ params: { appId },
+}: IProps) => {
+ return (
+ <Main appId={appId} />
+ )
+}
+
+export default Logs
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/cardView.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/cardView.tsx
new file mode 100644
index 00000000000..ff9388e1472
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/cardView.tsx
@@ -0,0 +1,86 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import useSWR, { useSWRConfig } from 'swr'
+import AppCard from '@/app/components/app/overview/appCard'
+import Loading from '@/app/components/base/loading'
+import { ToastContext } from '@/app/components/base/toast'
+import { fetchAppDetail, updateAppApiStatus, updateAppSiteAccessToken, updateAppSiteConfig, updateAppSiteStatus } from '@/service/apps'
+import type { IToastProps } from '@/app/components/base/toast'
+import type { App } from '@/types/app'
+
+export type ICardViewProps = {
+ appId: string
+}
+
+type IParams = {
+ url: string
+ body?: Record<string, any>
+}
+
+export async function asyncRunSafe<T>(func: (val: IParams) => Promise<T>, params: IParams, callback: (props: IToastProps) => void, dict?: any): Promise<[string?, T?]> {
+ try {
+ const res = await func(params)
+ callback && callback({ type: 'success', message: dict('common.actionMsg.modifiedSuccessfully') })
+ return [undefined, res]
+ }
+ catch (err) {
+ callback && callback({ type: 'error', message: dict('common.actionMsg.modificationFailed') })
+ return [(err as Error).message, undefined]
+ }
+}
+
+const CardView: FC<ICardViewProps> = ({ appId }) => {
+ const detailParams = { url: '/apps', id: appId }
+ const { data: response } = useSWR(detailParams, fetchAppDetail)
+ const { mutate } = useSWRConfig()
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+
+ if (!response)
+ return <Loading />
+
+ const onChangeSiteStatus = async (value: boolean) => {
+ const [err] = await asyncRunSafe<App>(updateAppSiteStatus as any, { url: `/apps/${appId}/site-enable`, body: { enable_site: value } }, notify, t)
+ if (!err)
+ mutate(detailParams)
+ }
+
+ const onChangeApiStatus = async (value: boolean) => {
+ const [err] = await asyncRunSafe<App>(updateAppApiStatus as any, { url: `/apps/${appId}/api-enable`, body: { enable_api: value } }, notify, t)
+ if (!err)
+ mutate(detailParams)
+ }
+
+ const onSaveSiteConfig = async (params: any) => {
+ const [err] = await asyncRunSafe<App>(updateAppSiteConfig as any, { url: `/apps/${appId}/site`, body: params }, notify, t)
+ if (!err)
+ mutate(detailParams)
+ }
+
+ const onGenerateCode = async () => {
+ const [err] = await asyncRunSafe<App>(updateAppSiteAccessToken as any, { url: `/apps/${appId}/site/access-token-reset` }, notify, t)
+ if (!err)
+ mutate(detailParams)
+ }
+
+ return (
+ <div className='flex flex-row justify-between w-full mb-6'>
+ <AppCard
+ className='mr-3 flex-1'
+ appInfo={response}
+ onChangeStatus={onChangeSiteStatus}
+ onGenerateCode={onGenerateCode}
+ onSaveSiteConfig={onSaveSiteConfig} />
+ <AppCard
+ className='ml-3 flex-1'
+ cardType='api'
+ appInfo={response}
+ onChangeStatus={onChangeApiStatus} />
+ </div>
+ )
+}
+
+export default CardView
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chartView.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chartView.tsx
new file mode 100644
index 00000000000..251c29ad1ac
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chartView.tsx
@@ -0,0 +1,52 @@
+'use client'
+import React, { useState } from 'react'
+import dayjs from 'dayjs'
+import quarterOfYear from 'dayjs/plugin/quarterOfYear'
+import { useTranslation } from 'react-i18next'
+import type { PeriodParams } from '@/app/components/app/overview/appChart'
+import { ConversationsChart, CostChart, EndUsersChart } from '@/app/components/app/overview/appChart'
+import type { Item } from '@/app/components/base/select'
+import { SimpleSelect } from '@/app/components/base/select'
+import { TIME_PERIOD_LIST } from '@/app/components/app/log/filter'
+
+dayjs.extend(quarterOfYear)
+
+const today = dayjs()
+
+const queryDateFormat = 'YYYY-MM-DD HH:mm'
+
+export type IChartViewProps = {
+ appId: string
+}
+
+export default function ChartView({ appId }: IChartViewProps) {
+ const { t } = useTranslation()
+ const [period, setPeriod] = useState<PeriodParams>({ name: t('appLog.filter.period.last7days'), query: { start: today.subtract(7, 'day').format(queryDateFormat), end: today.format(queryDateFormat) } })
+
+ const onSelect = (item: Item) => {
+ setPeriod({ name: item.name, query: { start: today.subtract(item.value as number, 'day').format(queryDateFormat), end: today.format(queryDateFormat) } })
+ }
+
+ return (
+ <div>
+ <div className='flex flex-row items-center mt-8 mb-4 text-gray-900 text-base'>
+ <span className='mr-3'>{t('appOverview.analysis.title')}</span>
+ <SimpleSelect
+ items={TIME_PERIOD_LIST.map(item => ({ value: item.value, name: t(`appLog.filter.period.${item.name}`) }))}
+ className='mt-0 !w-40'
+ onSelect={onSelect}
+ defaultValue={7}
+ />
+ </div>
+ <div className='flex flex-row w-full mb-6'>
+ <div className='flex-1 mr-3'>
+ <ConversationsChart period={period} id={appId} />
+ </div>
+ <div className='flex-1 ml-3'>
+ <EndUsersChart period={period} id={appId} />
+ </div>
+ </div>
+ <CostChart period={period} id={appId} />
+ </div>
+ )
+}
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx
new file mode 100644
index 00000000000..1b80c0a0c7b
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/page.tsx
@@ -0,0 +1,30 @@
+import React from 'react'
+import WelcomeBanner, { EditKeyPopover } from './welcome-banner'
+import ChartView from './chartView'
+import CardView from './cardView'
+import { getLocaleOnServer } from '@/i18n/server'
+import { useTranslation } from '@/i18n/i18next-serverside-config'
+
+export type IDevelopProps = {
+ params: { appId: string }
+}
+
+const Overview = async ({
+ params: { appId },
+}: IDevelopProps) => {
+ const locale = getLocaleOnServer()
+ const { t } = await useTranslation(locale, 'app-overview')
+ return (
+ <div className="h-full px-16 py-6 overflow-scroll">
+ <WelcomeBanner />
+ <div className='flex flex-row items-center justify-between mb-4 text-xl text-gray-900'>
+ {t('overview.title')}
+ <EditKeyPopover />
+ </div>
+ <CardView appId={appId} />
+ <ChartView appId={appId} />
+ </div>
+ )
+}
+
+export default Overview
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/welcome-banner.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/welcome-banner.tsx
new file mode 100644
index 00000000000..9b323eaa4bc
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/welcome-banner.tsx
@@ -0,0 +1,200 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import { useContext } from 'use-context-selector'
+import { useTranslation } from 'react-i18next'
+import Link from 'next/link'
+import useSWR, { useSWRConfig } from 'swr'
+import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
+import { ExclamationCircleIcon } from '@heroicons/react/24/solid'
+import { debounce } from 'lodash-es'
+import Popover from '@/app/components/base/popover'
+import Button from '@/app/components/base/button'
+import Tag from '@/app/components/base/tag'
+import { ToastContext } from '@/app/components/base/toast'
+import { updateOpenAIKey, validateOpenAIKey } from '@/service/apps'
+import { fetchTenantInfo } from '@/service/common'
+import I18n from '@/context/i18n'
+
+type IStatusType = 'normal' | 'verified' | 'error' | 'error-api-key-exceed-bill'
+
+const STATUS_COLOR_MAP = {
+ normal: { color: '', bgColor: 'bg-primary-50', borderColor: 'border-primary-100' },
+ error: { color: 'text-red-600', bgColor: 'bg-red-50', borderColor: 'border-red-100' },
+ verified: { color: '', bgColor: 'bg-green-50', borderColor: 'border-green-100' },
+ 'error-api-key-exceed-bill': { color: 'text-red-600', bgColor: 'bg-red-50', borderColor: 'border-red-100' },
+}
+
+const CheckCircleIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <rect width="20" height="20" rx="10" fill="#DEF7EC" />
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M14.6947 6.70495C14.8259 6.83622 14.8996 7.01424 14.8996 7.19985C14.8996 7.38547 14.8259 7.56348 14.6947 7.69475L9.0947 13.2948C8.96343 13.426 8.78541 13.4997 8.5998 13.4997C8.41418 13.4997 8.23617 13.426 8.1049 13.2948L5.3049 10.4948C5.17739 10.3627 5.10683 10.1859 5.10842 10.0024C5.11002 9.81883 5.18364 9.64326 5.31342 9.51348C5.44321 9.38369 5.61878 9.31007 5.80232 9.30848C5.98585 9.30688 6.16268 9.37744 6.2947 9.50495L8.5998 11.8101L13.7049 6.70495C13.8362 6.57372 14.0142 6.5 14.1998 6.5C14.3854 6.5 14.5634 6.57372 14.6947 6.70495Z" fill="#046C4E" />
+ </svg>
+}
+
+type IEditKeyDiv = {
+ className?: string
+ showInPopover?: boolean
+ onClose?: () => void
+ getTenantInfo?: () => void
+}
+
+const EditKeyDiv: FC<IEditKeyDiv> = ({ className = '', showInPopover = false, onClose, getTenantInfo }) => {
+ const [inputValue, setInputValue] = useState<string | undefined>()
+ const [editStatus, setEditStatus] = useState<IStatusType>('normal')
+ const [loading, setLoading] = useState(false)
+ const [validating, setValidating] = useState(false)
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+ const { locale } = useContext(I18n)
+
+ // Hide the pop-up window and need to get the latest key again
+ // If the key is valid, the edit button will be hidden later
+ const onClosePanel = () => {
+ getTenantInfo && getTenantInfo()
+ onClose && onClose()
+ }
+
+ const onSaveKey = async () => {
+ if (editStatus === 'verified') {
+ setLoading(true)
+ try {
+ await updateOpenAIKey({ url: '/providers/openai/token', body: { token: inputValue ?? '' } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ onClosePanel()
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ }
+ finally {
+ setLoading(false)
+ }
+ }
+ }
+
+ const validateKey = async (value: string) => {
+ try {
+ setValidating(true)
+ const res = await validateOpenAIKey({ url: '/providers/openai/token-validate', body: { token: value ?? '' } })
+ setEditStatus(res.result === 'success' ? 'verified' : 'error')
+ }
+ catch (err: any) {
+ if (err.status === 400) {
+ err.json().then(({ code }: any) => {
+ if (code === 'provider_request_failed') {
+ setEditStatus('error-api-key-exceed-bill')
+ }
+ })
+ } else {
+ setEditStatus('error')
+ }
+ }
+ finally {
+ setValidating(false)
+ }
+ }
+ const renderErrorMessage = () => {
+ if (validating) {
+ return (
+ <div className={`text-primary-600 mt-2 text-xs`}>
+ {t('common.provider.validating')}
+ </div>
+ )
+ }
+ if (editStatus === 'error-api-key-exceed-bill') {
+ return (
+ <div className={`text-[#D92D20] mt-2 text-xs`}>
+ {t('common.provider.apiKeyExceedBill')}
+ {locale === 'en' ? ' ' : ''}
+ <Link
+ className='underline'
+ href="https://platform.openai.com/account/api-keys"
+ target={'_blank'}>
+ {locale === 'en' ? 'this link' : '这篇文档'}
+ </Link>
+ </div>
+ )
+ }
+ if (editStatus === 'error') {
+ return (
+ <div className={`text-[#D92D20] mt-2 text-xs`}>
+ {t('common.provider.invalidKey')}
+ </div>
+ )
+ }
+ return null
+ }
+
+ return (
+ <div className={`flex flex-col w-full rounded-lg px-8 py-6 border-solid border-[0.5px] ${className} ${Object.values(STATUS_COLOR_MAP[editStatus]).join(' ')}`}>
+ {!showInPopover && <p className='text-xl font-medium text-gray-800'>{t('appOverview.welcome.firstStepTip')}</p>}
+ <p className={`${showInPopover ? 'text-sm' : 'text-xl'} font-medium text-gray-800`}>{t('appOverview.welcome.enterKeyTip')} {showInPopover ? '' : '👇'}</p>
+ <div className='relative mt-2'>
+ <input type="text"
+ className={`h-9 w-96 max-w-full py-2 pl-2 text-gray-900 rounded-lg bg-white sm:text-xs focus:ring-blue-500 focus:border-blue-500 shadow-sm ${editStatus === 'normal' ? 'pr-2' : 'pr-8'}`}
+ placeholder={t('appOverview.welcome.placeholder') || ''}
+ onChange={debounce((e) => {
+ setInputValue(e.target.value)
+ if (!e.target.value) {
+ setEditStatus('normal')
+ return
+ }
+ validateKey(e.target.value)
+ }, 300)}
+ />
+ {editStatus === 'verified' && <div className="absolute inset-y-0 right-0 flex flex-row-reverse items-center pr-6 pointer-events-none">
+ <CheckCircleIcon className="rounded-lg" />
+ </div>}
+ {(editStatus === 'error' || editStatus === 'error-api-key-exceed-bill') && <div className="absolute inset-y-0 right-0 flex flex-row-reverse items-center pr-6 pointer-events-none">
+ <ExclamationCircleIcon className="w-5 h-5 text-red-800" />
+ </div>}
+ {showInPopover ? null : <Button type='primary' onClick={onSaveKey} className='!h-9 !inline-block ml-2' loading={loading} disabled={editStatus !== 'verified'}>{t('common.operation.save')}</Button>}
+ </div>
+ {renderErrorMessage()}
+ <Link className="inline-flex items-center mt-2 text-xs font-normal cursor-pointer text-primary-600 w-fit" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
+ {t('appOverview.welcome.getKeyTip')}
+ <ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
+ </Link>
+ {showInPopover && <div className='flex justify-end mt-6'>
+ <Button className='flex-shrink-0 mr-2' onClick={onClosePanel}>{t('common.operation.cancel')}</Button>
+ <Button type='primary' className='flex-shrink-0' onClick={onSaveKey} loading={loading} disabled={editStatus !== 'verified'}>{t('common.operation.save')}</Button>
+ </div>}
+ </div>
+ )
+}
+
+const WelcomeBanner: FC = () => {
+ const { data: userInfo } = useSWR({ url: '/info' }, fetchTenantInfo)
+ if (!userInfo)
+ return null
+ return userInfo?.providers?.find(({ token_is_set }) => token_is_set) ? null : <EditKeyDiv className='mb-8' />
+}
+
+export const EditKeyPopover: FC = () => {
+ const { data: userInfo } = useSWR({ url: '/info' }, fetchTenantInfo)
+ const { mutate } = useSWRConfig()
+ if (!userInfo)
+ return null
+
+ const getTenantInfo = () => {
+ mutate({ url: '/info' })
+ }
+ // In this case, the edit button is displayed
+ const targetProvider = userInfo?.providers?.some(({ token_is_set, is_valid }) => token_is_set && is_valid)
+ return (
+ !targetProvider
+ ? <div className='flex items-center'>
+ <Tag className='mr-2 h-fit' color='red'><ExclamationCircleIcon className='h-3.5 w-3.5 mr-2' />OpenAI API key invalid</Tag>
+ <Popover
+ htmlContent={<EditKeyDiv className='!border-0' showInPopover={true} getTenantInfo={getTenantInfo} />}
+ trigger='click'
+ position='br'
+ btnElement='Edit'
+ btnClassName='text-primary-600 !text-xs px-3 py-1.5'
+ className='!p-0 !w-[464px] h-[200px]'
+ />
+ </div>
+ : null)
+}
+
+export default WelcomeBanner
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/style.module.css b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/style.module.css
new file mode 100644
index 00000000000..2d6b3bd15c3
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/style.module.css
@@ -0,0 +1,5 @@
+.app {
+ height: calc(100vh - 56px);
+ border-radius: 16px 16px 0px 0px;
+ box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.05), 0px 0px 2px -1px rgba(0, 0, 0, 0.03);
+}
\ No newline at end of file
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/layout.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/layout.tsx
new file mode 100644
index 00000000000..b70959ea79a
--- /dev/null
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/layout.tsx
@@ -0,0 +1,16 @@
+import type { FC } from 'react'
+import React from 'react'
+
+export type IAppDetail = {
+ children: React.ReactNode
+}
+
+const AppDetail: FC<IAppDetail> = ({ children }) => {
+ return (
+ <>
+ {children}
+ </>
+ )
+}
+
+export default React.memo(AppDetail)
diff --git a/web/app/(commonLayout)/apps/AppCard.tsx b/web/app/(commonLayout)/apps/AppCard.tsx
new file mode 100644
index 00000000000..eb62cd88993
--- /dev/null
+++ b/web/app/(commonLayout)/apps/AppCard.tsx
@@ -0,0 +1,76 @@
+'use client'
+
+import { useContext, useContextSelector } from 'use-context-selector'
+import Link from 'next/link'
+import type { MouseEventHandler } from 'react'
+import { useCallback, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import style from '../list.module.css'
+import AppModeLabel from './AppModeLabel'
+import type { App } from '@/types/app'
+import Confirm from '@/app/components/base/confirm'
+import { ToastContext } from '@/app/components/base/toast'
+import { deleteApp } from '@/service/apps'
+import AppIcon from '@/app/components/base/app-icon'
+import AppsContext from '@/context/app-context'
+
+export type AppCardProps = {
+ app: App
+}
+
+const AppCard = ({
+ app,
+}: AppCardProps) => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+
+ const mutateApps = useContextSelector(AppsContext, state => state.mutateApps)
+
+ const [showConfirmDelete, setShowConfirmDelete] = useState(false)
+ const onDeleteClick: MouseEventHandler = useCallback((e) => {
+ e.preventDefault()
+ setShowConfirmDelete(true)
+ }, [])
+ const onConfirmDelete = useCallback(async () => {
+ try {
+ await deleteApp(app.id)
+ notify({ type: 'success', message: t('app.appDeleted') })
+ mutateApps()
+ }
+ catch (e: any) {
+ notify({ type: 'error', message: `${t('app.appDeleteFailed')}${'message' in e ? `: ${e.message}` : ''}` })
+ }
+ setShowConfirmDelete(false)
+ }, [app.id])
+
+ return (
+ <>
+ <Link href={`/app/${app.id}/overview`} className={style.listItem}>
+ <div className={style.listItemTitle}>
+ <AppIcon size='small' />
+ <div className={style.listItemHeading}>
+ <div className={style.listItemHeadingContent}>{app.name}</div>
+ </div>
+ <span className={style.deleteAppIcon} onClick={onDeleteClick} />
+ </div>
+ <div className={style.listItemDescription}>{app.model_config?.pre_prompt}</div>
+ <div className={style.listItemFooter}>
+ <AppModeLabel mode={app.mode} />
+ </div>
+
+ {showConfirmDelete && (
+ <Confirm
+ title={t('app.deleteAppConfirmTitle')}
+ content={t('app.deleteAppConfirmContent')}
+ isShow={showConfirmDelete}
+ onClose={() => setShowConfirmDelete(false)}
+ onConfirm={onConfirmDelete}
+ onCancel={() => setShowConfirmDelete(false)}
+ />
+ )}
+ </Link>
+ </>
+ )
+}
+
+export default AppCard
diff --git a/web/app/(commonLayout)/apps/AppModeLabel.tsx b/web/app/(commonLayout)/apps/AppModeLabel.tsx
new file mode 100644
index 00000000000..f223c019819
--- /dev/null
+++ b/web/app/(commonLayout)/apps/AppModeLabel.tsx
@@ -0,0 +1,26 @@
+'use client'
+
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+import { type AppMode } from '@/types/app'
+import style from '../list.module.css'
+
+export type AppModeLabelProps = {
+ mode: AppMode
+ className?: string
+}
+
+const AppModeLabel = ({
+ mode,
+ className,
+}: AppModeLabelProps) => {
+ const { t } = useTranslation()
+ return (
+ <span className={classNames('flex items-center w-fit h-6 gap-1 px-2 text-gray-500 text-xs border border-gray-100 rounded', className)}>
+ <span className={classNames(style.listItemFooterIcon, mode === 'chat' && style.solidChatIcon, mode === 'completion' && style.solidCompletionIcon)} />
+ {t(`app.modes.${mode}`)}
+ </span>
+ )
+}
+
+export default AppModeLabel
diff --git a/web/app/(commonLayout)/apps/Apps.tsx b/web/app/(commonLayout)/apps/Apps.tsx
new file mode 100644
index 00000000000..b11b0da6a03
--- /dev/null
+++ b/web/app/(commonLayout)/apps/Apps.tsx
@@ -0,0 +1,23 @@
+'use client'
+
+import { useEffect } from 'react'
+import AppCard from './AppCard'
+import NewAppCard from './NewAppCard'
+import { useAppContext } from '@/context/app-context'
+
+const Apps = () => {
+ const { apps, mutateApps } = useAppContext()
+
+ useEffect(() => {
+ mutateApps()
+ }, [])
+
+ return (
+ <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-8 sm:grid-cols-2 lg:grid-cols-4 grow shrink-0'>
+ {apps.map(app => (<AppCard key={app.id} app={app} />))}
+ <NewAppCard />
+ </nav>
+ )
+}
+
+export default Apps
diff --git a/web/app/(commonLayout)/apps/NewAppCard.tsx b/web/app/(commonLayout)/apps/NewAppCard.tsx
new file mode 100644
index 00000000000..7fee93534e1
--- /dev/null
+++ b/web/app/(commonLayout)/apps/NewAppCard.tsx
@@ -0,0 +1,29 @@
+'use client'
+
+import { useState } from 'react'
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+import style from '../list.module.css'
+import NewAppDialog from './NewAppDialog'
+
+const CreateAppCard = () => {
+ const { t } = useTranslation()
+ const [showNewAppDialog, setShowNewAppDialog] = useState(false)
+
+ return (
+ <a className={classNames(style.listItem, style.newItemCard)} onClick={() => setShowNewAppDialog(true)}>
+ <div className={style.listItemTitle}>
+ <span className={style.newItemIcon}>
+ <span className={classNames(style.newItemIconImage, style.newItemIconAdd)} />
+ </span>
+ <div className={classNames(style.listItemHeading, style.newItemCardHeading)}>
+ {t('app.createApp')}
+ </div>
+ </div>
+ {/* <div className='text-xs text-gray-500'>{t('app.createFromConfigFile')}</div> */}
+ <NewAppDialog show={showNewAppDialog} onClose={() => setShowNewAppDialog(false)} />
+ </a>
+ )
+}
+
+export default CreateAppCard
diff --git a/web/app/(commonLayout)/apps/NewAppDialog.tsx b/web/app/(commonLayout)/apps/NewAppDialog.tsx
new file mode 100644
index 00000000000..3b434fa3b20
--- /dev/null
+++ b/web/app/(commonLayout)/apps/NewAppDialog.tsx
@@ -0,0 +1,193 @@
+'use client'
+
+import type { MouseEventHandler } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import useSWR from 'swr'
+import classNames from 'classnames'
+import { useRouter } from 'next/navigation'
+import { useContext, useContextSelector } from 'use-context-selector'
+import { useTranslation } from 'react-i18next'
+import style from '../list.module.css'
+import AppModeLabel from './AppModeLabel'
+import Button from '@/app/components/base/button'
+import Dialog from '@/app/components/base/dialog'
+import type { AppMode } from '@/types/app'
+import { ToastContext } from '@/app/components/base/toast'
+import { createApp, fetchAppTemplates } from '@/service/apps'
+import AppIcon from '@/app/components/base/app-icon'
+import AppsContext from '@/context/app-context'
+
+type NewAppDialogProps = {
+ show: boolean
+ onClose?: () => void
+}
+
+const NewAppDialog = ({ show, onClose }: NewAppDialogProps) => {
+ const router = useRouter()
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+
+ const nameInputRef = useRef<HTMLInputElement>(null)
+ const [newAppMode, setNewAppMode] = useState<AppMode>()
+ const [isWithTemplate, setIsWithTemplate] = useState(false)
+ const [selectedTemplateIndex, setSelectedTemplateIndex] = useState<number>(-1)
+ const mutateApps = useContextSelector(AppsContext, state => state.mutateApps)
+
+ const { data: templates, mutate } = useSWR({ url: '/app-templates' }, fetchAppTemplates)
+ const mutateTemplates = useCallback(
+ () => mutate(),
+ [],
+ )
+
+ useEffect(() => {
+ if (show) {
+ mutateTemplates()
+ setIsWithTemplate(false)
+ }
+ }, [show])
+
+ const isCreatingRef = useRef(false)
+ const onCreate: MouseEventHandler = useCallback(async () => {
+ const name = nameInputRef.current?.value
+ if (!name) {
+ notify({ type: 'error', message: t('app.newApp.nameNotEmpty') })
+ return
+ }
+ if (!templates || (isWithTemplate && !(selectedTemplateIndex > -1))) {
+ notify({ type: 'error', message: t('app.newApp.appTemplateNotSelected') })
+ return
+ }
+ if (!isWithTemplate && !newAppMode) {
+ notify({ type: 'error', message: t('app.newApp.appTypeRequired') })
+ return
+ }
+ if (isCreatingRef.current)
+ return
+ isCreatingRef.current = true
+ try {
+ const app = await createApp({
+ name,
+ mode: isWithTemplate ? templates.data[selectedTemplateIndex].mode : newAppMode!,
+ config: isWithTemplate ? templates.data[selectedTemplateIndex].model_config : undefined,
+ })
+ if (onClose)
+ onClose()
+ notify({ type: 'success', message: t('app.newApp.appCreated') })
+ mutateApps()
+ router.push(`/app/${app.id}/overview`)
+ }
+ catch (e) {
+ notify({ type: 'error', message: t('app.newApp.appCreateFailed') })
+ }
+ isCreatingRef.current = false
+ }, [isWithTemplate, newAppMode, notify, router, templates, selectedTemplateIndex])
+
+ return (
+ <Dialog
+ show={show}
+ title={t('app.newApp.startToCreate')}
+ footer={
+ <>
+ <Button onClick={onClose}>{t('app.newApp.Cancel')}</Button>
+ <Button type="primary" onClick={onCreate}>{t('app.newApp.Create')}</Button>
+ </>
+ }
+ >
+ <h3 className={style.newItemCaption}>{t('app.newApp.captionName')}</h3>
+
+ <div className='flex items-center justify-between gap-3 mb-8'>
+ <AppIcon size='large' />
+ <input ref={nameInputRef} className='h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg grow' />
+ </div>
+
+ <div className='h-[247px]'>
+ <div className={style.newItemCaption}>
+ <h3 className='inline'>{t('app.newApp.captionAppType')}</h3>
+ {isWithTemplate && (
+ <>
+ <span className='block ml-[9px] mr-[9px] w-[1px] h-[13px] bg-gray-200' />
+ <span
+ className='inline-flex items-center gap-1 text-xs font-medium cursor-pointer text-primary-600'
+ onClick={() => setIsWithTemplate(false)}
+ >
+ {t('app.newApp.hideTemplates')}
+ </span>
+ </>
+ )}
+ </div>
+ {isWithTemplate
+ ? (
+ <ul className='grid grid-cols-2 gap-4'>
+ {templates?.data?.map((template, index) => (
+ <li
+ key={index}
+ className={classNames(style.listItem, style.selectable, selectedTemplateIndex === index && style.selected)}
+ onClick={() => setSelectedTemplateIndex(index)}
+ >
+ <div className={style.listItemTitle}>
+ <AppIcon size='small' />
+ <div className={style.listItemHeading}>
+ <div className={style.listItemHeadingContent}>{template.name}</div>
+ </div>
+ </div>
+ <div className={style.listItemDescription}>{template.model_config?.pre_prompt}</div>
+ <AppModeLabel mode={template.mode} className='mt-2' />
+ {/* <AppModeLabel mode='chat' className='mt-2' /> */}
+ </li>
+ ))}
+ </ul>
+ )
+ : (
+ <>
+ <ul className='grid grid-cols-2 gap-4'>
+ <li
+ className={classNames(style.listItem, style.selectable, newAppMode === 'chat' && style.selected)}
+ onClick={() => setNewAppMode('chat')}
+ >
+ <div className={style.listItemTitle}>
+ <span className={style.newItemIcon}>
+ <span className={classNames(style.newItemIconImage, style.newItemIconChat)} />
+ </span>
+ <div className={style.listItemHeading}>
+ <div className={style.listItemHeadingContent}>{t('app.newApp.chatApp')}</div>
+ </div>
+ </div>
+ <div className={style.listItemDescription}>{t('app.newApp.chatAppIntro')}</div>
+ <div className={classNames(style.listItemFooter, 'justify-end')}>
+ <a className={style.listItemLink} href='https://udify.app/chat/7CQBa5yyvYLSkZtx' target='_blank'>{t('app.newApp.previewDemo')}<span className={classNames(style.linkIcon, style.grayLinkIcon)} /></a>
+ </div>
+ </li>
+ <li
+ className={classNames(style.listItem, style.selectable, newAppMode === 'completion' && style.selected)}
+ onClick={() => setNewAppMode('completion')}
+ >
+ <div className={style.listItemTitle}>
+ <span className={style.newItemIcon}>
+ <span className={classNames(style.newItemIconImage, style.newItemIconComplete)} />
+ </span>
+ <div className={style.listItemHeading}>
+ <div className={style.listItemHeadingContent}>{t('app.newApp.completeApp')}</div>
+ </div>
+ </div>
+ <div className={style.listItemDescription}>{t('app.newApp.completeAppIntro')}</div>
+ <div className={classNames(style.listItemFooter, 'justify-end')}>
+ <a className={style.listItemLink} href='https://udify.app/completion/aeFTj0VCb3Ok3TUE' target='_blank'>{t('app.newApp.previewDemo')}<span className={classNames(style.linkIcon, style.grayLinkIcon)} /></a>
+ </div>
+ </li>
+ </ul>
+ <div className='flex items-center h-[34px] mt-2'>
+ <span
+ className='inline-flex items-center gap-1 text-xs font-medium cursor-pointer text-primary-600'
+ onClick={() => setIsWithTemplate(true)}
+ >
+ {t('app.newApp.showTemplates')}<span className={style.rightIcon} />
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+ </Dialog>
+ )
+}
+
+export default NewAppDialog
diff --git a/web/app/(commonLayout)/apps/assets/add.svg b/web/app/(commonLayout)/apps/assets/add.svg
new file mode 100644
index 00000000000..9958e855aaf
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/add.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M8 4V8M8 8V12M8 8H12M8 8H4" stroke="#6B7280" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/chat-solid.svg b/web/app/(commonLayout)/apps/assets/chat-solid.svg
new file mode 100644
index 00000000000..a793e982c0f
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/chat-solid.svg
@@ -0,0 +1,4 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M0.631586 8.25C0.631586 6.46656 2.04586 5 3.8158 5C5.58573 5 7.00001 6.46656 7.00001 8.25C7.00001 10.0334 5.58573 11.5 3.8158 11.5C3.45197 11.5 3.10149 11.4375 2.77474 11.3222C2.72073 11.3031 2.68723 11.2913 2.66266 11.2832C2.65821 11.2817 2.65456 11.2806 2.65164 11.2796L2.64892 11.2799C2.63177 11.2818 2.60839 11.285 2.56507 11.2909L1.06766 11.4954C0.905637 11.5175 0.743029 11.459 0.632239 11.3387C0.521449 11.2185 0.476481 11.0516 0.511825 10.8919L0.817497 9.51109C0.828118 9.46311 0.833802 9.43722 0.837453 9.41817C0.83766 9.4171 0.838022 9.41517 0.838022 9.41517C0.837114 9.412 0.835963 9.40808 0.834525 9.40332C0.826292 9.37605 0.814183 9.33888 0.794499 9.27863C0.688657 8.95463 0.631586 8.60857 0.631586 8.25Z" fill="#98A2B3"/>
+<path d="M2.57377 4.1863C2.96256 4.06535 3.37698 4 3.80894 4C6.16566 4 8.00006 5.94534 8.00006 8.24999C8.00006 8.65682 7.9429 9.05245 7.8358 9.42816C8.10681 9.37948 8.36964 9.30678 8.6219 9.21229C8.65748 9.19897 8.69298 9.18534 8.72893 9.17304C8.75795 9.17641 8.78684 9.18093 8.81574 9.18517L10.4222 9.42065C10.498 9.43179 10.5841 9.44444 10.6591 9.4487C10.7422 9.45343 10.8713 9.45292 11.0081 9.39408C11.1789 9.32061 11.3164 9.18628 11.3938 9.01716C11.4558 8.88174 11.4593 8.75269 11.4564 8.66955C11.4539 8.59442 11.4433 8.5081 11.4339 8.43202L11.2309 6.78307C11.2256 6.7402 11.2229 6.71768 11.2213 6.70118C11.23 6.66505 11.2466 6.6301 11.2598 6.59546C11.4492 6.09896 11.5526 5.56093 11.5526 5C11.5526 2.51163 9.52304 0.5 7.02632 0.5C4.80843 0.5 2.95915 2.08742 2.57377 4.1863Z" fill="#98A2B3"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/chat.svg b/web/app/(commonLayout)/apps/assets/chat.svg
new file mode 100644
index 00000000000..0971349a53c
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/chat.svg
@@ -0,0 +1,3 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M14.1667 6.66634H15.8333C16.2754 6.66634 16.6993 6.84194 17.0118 7.1545C17.3244 7.46706 17.5 7.89098 17.5 8.33301V13.333C17.5 13.775 17.3244 14.199 17.0118 14.5115C16.6993 14.8241 16.2754 14.9997 15.8333 14.9997H14.1667V18.333L10.8333 14.9997H7.5C7.28111 14.9999 7.06433 14.9569 6.86211 14.8731C6.6599 14.7893 6.47623 14.6663 6.32167 14.5113M6.32167 14.5113L9.16667 11.6663H12.5C12.942 11.6663 13.366 11.4907 13.6785 11.1782C13.9911 10.8656 14.1667 10.4417 14.1667 9.99967V4.99967C14.1667 4.55765 13.9911 4.13372 13.6785 3.82116C13.366 3.5086 12.942 3.33301 12.5 3.33301H4.16667C3.72464 3.33301 3.30072 3.5086 2.98816 3.82116C2.67559 4.13372 2.5 4.55765 2.5 4.99967V9.99967C2.5 10.4417 2.67559 10.8656 2.98816 11.1782C3.30072 11.4907 3.72464 11.6663 4.16667 11.6663H5.83333V14.9997L6.32167 14.5113Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/completion-solid.svg b/web/app/(commonLayout)/apps/assets/completion-solid.svg
new file mode 100644
index 00000000000..a9dc7e3dc13
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/completion-solid.svg
@@ -0,0 +1,4 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M6.5 1.00779C6.5 0.994638 6.5 0.988062 6.49943 0.976137C6.48764 0.729248 6.27052 0.51224 6.02363 0.50056C6.01171 0.499996 6.0078 0.499998 6.00001 0.5H4.37933C3.97686 0.499995 3.64468 0.49999 3.37409 0.522098C3.09304 0.545061 2.83469 0.594343 2.59202 0.717989C2.2157 0.909735 1.90973 1.2157 1.71799 1.59202C1.59434 1.83469 1.54506 2.09304 1.5221 2.37409C1.49999 2.64468 1.49999 2.97686 1.5 3.37934V8.62066C1.49999 9.02313 1.49999 9.35532 1.5221 9.62591C1.54506 9.90696 1.59434 10.1653 1.71799 10.408C1.90973 10.7843 2.2157 11.0903 2.59202 11.282C2.83469 11.4057 3.09304 11.4549 3.37409 11.4779C3.64468 11.5 3.97686 11.5 4.37934 11.5H7.62066C8.02314 11.5 8.35532 11.5 8.62591 11.4779C8.90696 11.4549 9.16531 11.4057 9.40798 11.282C9.78431 11.0903 10.0903 10.7843 10.282 10.408C10.4057 10.1653 10.4549 9.90696 10.4779 9.62591C10.5 9.35532 10.5 9.02314 10.5 8.62066V4.99997C10.5 4.9922 10.5 4.98832 10.4994 4.97641C10.4878 4.72949 10.2707 4.51236 10.0238 4.50057C10.0119 4.50001 10.0054 4.50001 9.99225 4.50001L7.78404 4.50001C7.65786 4.50002 7.53496 4.50004 7.43089 4.49153C7.31659 4.48219 7.18172 4.46016 7.04601 4.39101C6.85785 4.29514 6.70487 4.14216 6.609 3.954C6.53985 3.81828 6.51781 3.68342 6.50848 3.56912C6.49997 3.46504 6.49999 3.34215 6.5 3.21596L6.5 1.00779ZM4 6.5C3.72386 6.5 3.5 6.72386 3.5 7C3.5 7.27614 3.72386 7.5 4 7.5H8C8.27614 7.5 8.5 7.27614 8.5 7C8.5 6.72386 8.27614 6.5 8 6.5H4ZM4 8.5C3.72386 8.5 3.5 8.72386 3.5 9C3.5 9.27614 3.72386 9.5 4 9.5H7C7.27614 9.5 7.5 9.27614 7.5 9C7.5 8.72386 7.27614 8.5 7 8.5H4Z" fill="#98A2B3"/>
+<path d="M9.45398 3.5C9.60079 3.5 9.67419 3.5 9.73432 3.46314C9.81925 3.41107 9.87002 3.28842 9.84674 3.19157C9.83025 3.12299 9.78238 3.07516 9.68665 2.97952L8.02049 1.31336C7.92484 1.21762 7.87701 1.16975 7.80843 1.15326C7.71158 1.12998 7.58893 1.18075 7.53687 1.26567C7.5 1.3258 7.5 1.39921 7.5 1.54602L7.5 3.09998C7.5 3.23999 7.5 3.30999 7.52725 3.36347C7.55122 3.41051 7.58946 3.44876 7.6365 3.47272C7.68998 3.49997 7.75998 3.49997 7.9 3.49998L9.45398 3.5Z" fill="#98A2B3"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/completion.svg b/web/app/(commonLayout)/apps/assets/completion.svg
new file mode 100644
index 00000000000..34af4417fe8
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/completion.svg
@@ -0,0 +1,3 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M16.25 11.875V9.6875C16.25 8.1342 14.9908 6.875 13.4375 6.875H12.1875C11.6697 6.875 11.25 6.45527 11.25 5.9375V4.6875C11.25 3.1342 9.9908 1.875 8.4375 1.875H6.875M6.875 12.5H13.125M6.875 15H10M8.75 1.875H4.6875C4.16973 1.875 3.75 2.29473 3.75 2.8125V17.1875C3.75 17.7053 4.16973 18.125 4.6875 18.125H15.3125C15.8303 18.125 16.25 17.7053 16.25 17.1875V9.375C16.25 5.23286 12.8921 1.875 8.75 1.875Z" stroke="#1F2A37" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/delete.svg b/web/app/(commonLayout)/apps/assets/delete.svg
new file mode 100644
index 00000000000..fcd60cf7ddf
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/delete.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.6665 7.33333V11.3333M9.33317 7.33333V11.3333M2.6665 4.66667H13.3332M12.6665 4.66667L12.0885 12.7613C12.0646 13.0977 11.914 13.4125 11.6672 13.6424C11.4205 13.8722 11.0957 14 10.7585 14H5.24117C4.90393 14 4.57922 13.8722 4.33243 13.6424C4.08564 13.4125 3.93511 13.0977 3.91117 12.7613L3.33317 4.66667H12.6665ZM9.99984 4.66667V2.66667C9.99984 2.48986 9.9296 2.32029 9.80457 2.19526C9.67955 2.07024 9.50998 2 9.33317 2H6.6665C6.48969 2 6.32012 2.07024 6.1951 2.19526C6.07008 2.32029 5.99984 2.48986 5.99984 2.66667V4.66667H9.99984Z" stroke="#1F2A37" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/discord.svg b/web/app/(commonLayout)/apps/assets/discord.svg
new file mode 100644
index 00000000000..9f22a1ab59c
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/discord.svg
@@ -0,0 +1,3 @@
+<svg width="26" height="26" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M22.0101 4.50191C20.3529 3.74154 18.5759 3.18133 16.7179 2.86048C16.6841 2.85428 16.6503 2.86976 16.6328 2.90071C16.4043 3.30719 16.1511 3.83748 15.9738 4.25429C13.9754 3.95511 11.9873 3.95511 10.0298 4.25429C9.85253 3.82822 9.59019 3.30719 9.36062 2.90071C9.34319 2.87079 9.30939 2.85532 9.27555 2.86048C7.41857 3.18031 5.64152 3.74051 3.98335 4.50191C3.96899 4.5081 3.95669 4.51843 3.94852 4.53183C0.577841 9.56755 -0.345529 14.4795 0.107445 19.3306C0.109495 19.3543 0.122817 19.377 0.141265 19.3914C2.36514 21.0246 4.51935 22.0161 6.63355 22.6732C6.66739 22.6836 6.70324 22.6712 6.72477 22.6433C7.22489 21.9604 7.6707 21.2402 8.05293 20.4829C8.07549 20.4386 8.05396 20.386 8.00785 20.3684C7.30073 20.1002 6.6274 19.7731 5.97971 19.4017C5.92848 19.3718 5.92437 19.2985 5.9715 19.2635C6.1078 19.1613 6.24414 19.0551 6.37428 18.9478C6.39783 18.9282 6.43064 18.924 6.45833 18.9364C10.7134 20.8791 15.32 20.8791 19.5249 18.9364C19.5525 18.923 19.5854 18.9272 19.6099 18.9467C19.7401 19.054 19.8764 19.1613 20.0137 19.2635C20.0609 19.2985 20.0578 19.3718 20.0066 19.4017C19.3589 19.7804 18.6855 20.1002 17.9774 20.3674C17.9313 20.3849 17.9108 20.4386 17.9333 20.4829C18.3238 21.2392 18.7696 21.9593 19.2605 22.6423C19.281 22.6712 19.3179 22.6836 19.3517 22.6732C21.4761 22.0161 23.6303 21.0246 25.8542 19.3914C25.8737 19.377 25.886 19.3553 25.8881 19.3316C26.4302 13.7232 24.98 8.85156 22.0439 4.53286C22.0367 4.51843 22.0245 4.5081 22.0101 4.50191ZM8.68836 16.3768C7.40729 16.3768 6.35173 15.2007 6.35173 13.7563C6.35173 12.3119 7.38682 11.1358 8.68836 11.1358C10.0001 11.1358 11.0455 12.3222 11.025 13.7563C11.025 15.2007 9.98986 16.3768 8.68836 16.3768ZM17.3276 16.3768C16.0466 16.3768 14.991 15.2007 14.991 13.7563C14.991 12.3119 16.0261 11.1358 17.3276 11.1358C18.6394 11.1358 19.6847 12.3222 19.6643 13.7563C19.6643 15.2007 18.6394 16.3768 17.3276 16.3768Z" fill="#5865F2"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/github.svg b/web/app/(commonLayout)/apps/assets/github.svg
new file mode 100644
index 00000000000..f03798b5e1d
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/github.svg
@@ -0,0 +1,17 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_131_1011)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0003 0.5C9.15149 0.501478 6.39613 1.51046 4.22687 3.34652C2.05761 5.18259 0.615903 7.72601 0.159545 10.522C-0.296814 13.318 0.261927 16.1842 1.73587 18.6082C3.20981 21.0321 5.50284 22.8558 8.20493 23.753C8.80105 23.8636 9.0256 23.4941 9.0256 23.18C9.0256 22.8658 9.01367 21.955 9.0097 20.9592C5.6714 21.6804 4.96599 19.5505 4.96599 19.5505C4.42152 18.1674 3.63464 17.8039 3.63464 17.8039C2.54571 17.065 3.71611 17.0788 3.71611 17.0788C4.92227 17.1637 5.55616 18.3097 5.55616 18.3097C6.62521 20.1333 8.36389 19.6058 9.04745 19.2976C9.15475 18.5251 9.46673 17.9995 9.8105 17.7012C7.14383 17.4008 4.34204 16.3774 4.34204 11.8054C4.32551 10.6197 4.76802 9.47305 5.57801 8.60268C5.45481 8.30236 5.04348 7.08923 5.69524 5.44143C5.69524 5.44143 6.7027 5.12135 8.9958 6.66444C10.9627 6.12962 13.0379 6.12962 15.0047 6.66444C17.2958 5.12135 18.3013 5.44143 18.3013 5.44143C18.9551 7.08528 18.5437 8.29841 18.4205 8.60268C19.2331 9.47319 19.6765 10.6218 19.6585 11.8094C19.6585 16.3912 16.8507 17.4008 14.1801 17.6952C14.6093 18.0667 14.9928 18.7918 14.9928 19.9061C14.9928 21.5026 14.9789 22.7868 14.9789 23.18C14.9789 23.4981 15.1955 23.8695 15.8035 23.753C18.5059 22.8557 20.7992 21.0317 22.2731 18.6073C23.747 16.183 24.3055 13.3163 23.8486 10.5201C23.3917 7.7238 21.9493 5.18035 19.7793 3.34461C17.6093 1.50886 14.8533 0.500541 12.0042 0.5H12.0003Z" fill="#191717"/>
+<path d="M4.54444 17.6321C4.5186 17.6914 4.42322 17.7092 4.34573 17.6677C4.26823 17.6262 4.21061 17.5491 4.23843 17.4879C4.26625 17.4266 4.35964 17.4108 4.43714 17.4523C4.51463 17.4938 4.57424 17.5729 4.54444 17.6321Z" fill="#191717"/>
+<path d="M5.03123 18.1714C4.99008 18.192 4.943 18.1978 4.89805 18.1877C4.8531 18.1776 4.81308 18.1523 4.78483 18.1161C4.70734 18.0331 4.69143 17.9185 4.75104 17.8671C4.81066 17.8157 4.91797 17.8395 4.99546 17.9224C5.07296 18.0054 5.09084 18.12 5.03123 18.1714Z" fill="#191717"/>
+<path d="M5.50425 18.857C5.43072 18.9084 5.30553 18.857 5.23598 18.7543C5.21675 18.7359 5.20146 18.7138 5.19101 18.6893C5.18056 18.6649 5.17517 18.6386 5.17517 18.612C5.17517 18.5855 5.18056 18.5592 5.19101 18.5347C5.20146 18.5103 5.21675 18.4882 5.23598 18.4698C5.3095 18.4204 5.4347 18.4698 5.50425 18.5705C5.57379 18.6713 5.57578 18.8057 5.50425 18.857V18.857Z" fill="#191717"/>
+<path d="M6.14612 19.5207C6.08054 19.5939 5.94741 19.5741 5.83812 19.4753C5.72883 19.3765 5.70299 19.2422 5.76857 19.171C5.83414 19.0999 5.96727 19.1197 6.08054 19.2165C6.1938 19.3133 6.21566 19.4496 6.14612 19.5207V19.5207Z" fill="#191717"/>
+<path d="M7.04617 19.9081C7.01637 20.001 6.88124 20.0425 6.74612 20.003C6.611 19.9635 6.52158 19.8528 6.54741 19.758C6.57325 19.6631 6.71036 19.6197 6.84747 19.6631C6.98457 19.7066 7.07201 19.8113 7.04617 19.9081Z" fill="#191717"/>
+<path d="M8.02783 19.9752C8.02783 20.072 7.91656 20.155 7.77349 20.1569C7.63042 20.1589 7.51318 20.0799 7.51318 19.9831C7.51318 19.8863 7.62445 19.8033 7.76752 19.8013C7.91059 19.7993 8.02783 19.8764 8.02783 19.9752Z" fill="#191717"/>
+<path d="M8.9419 19.8232C8.95978 19.92 8.86042 20.0207 8.71735 20.0445C8.57428 20.0682 8.4491 20.0109 8.43121 19.916C8.41333 19.8212 8.51666 19.7185 8.65576 19.6928C8.79485 19.6671 8.92401 19.7264 8.9419 19.8232Z" fill="#191717"/>
+</g>
+<defs>
+<clipPath id="clip0_131_1011">
+<rect width="24" height="24" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/link-gray.svg b/web/app/(commonLayout)/apps/assets/link-gray.svg
new file mode 100644
index 00000000000..a293cfcf533
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/link-gray.svg
@@ -0,0 +1,3 @@
+<svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.41663 3.75033H3.24996C2.96264 3.75033 2.68709 3.86446 2.48393 4.06763C2.28076 4.27079 2.16663 4.54634 2.16663 4.83366V10.2503C2.16663 10.5376 2.28076 10.8132 2.48393 11.0164C2.68709 11.2195 2.96264 11.3337 3.24996 11.3337H8.66663C8.95394 11.3337 9.22949 11.2195 9.43266 11.0164C9.63582 10.8132 9.74996 10.5376 9.74996 10.2503V8.08366M7.58329 2.66699H10.8333M10.8333 2.66699V5.91699M10.8333 2.66699L5.41663 8.08366" stroke="#9CA3AF" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/link.svg b/web/app/(commonLayout)/apps/assets/link.svg
new file mode 100644
index 00000000000..2926c28b16f
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/link.svg
@@ -0,0 +1,3 @@
+<svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.41663 3.75008H3.24996C2.96264 3.75008 2.68709 3.86422 2.48393 4.06738C2.28076 4.27055 2.16663 4.5461 2.16663 4.83341V10.2501C2.16663 10.5374 2.28076 10.8129 2.48393 11.0161C2.68709 11.2193 2.96264 11.3334 3.24996 11.3334H8.66663C8.95394 11.3334 9.22949 11.2193 9.43266 11.0161C9.63582 10.8129 9.74996 10.5374 9.74996 10.2501V8.08341M7.58329 2.66675H10.8333M10.8333 2.66675V5.91675M10.8333 2.66675L5.41663 8.08341" stroke="#1C64F2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/assets/right-arrow.svg b/web/app/(commonLayout)/apps/assets/right-arrow.svg
new file mode 100644
index 00000000000..a2c1cedf950
--- /dev/null
+++ b/web/app/(commonLayout)/apps/assets/right-arrow.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M7 2.5L10.5 6M10.5 6L7 9.5M10.5 6H1.5" stroke="#1C64F2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/apps/page.tsx b/web/app/(commonLayout)/apps/page.tsx
new file mode 100644
index 00000000000..bc5a0b583fe
--- /dev/null
+++ b/web/app/(commonLayout)/apps/page.tsx
@@ -0,0 +1,36 @@
+import classNames from 'classnames'
+import style from '../list.module.css'
+import Apps from './Apps'
+import { getLocaleOnServer } from '@/i18n/server'
+import { useTranslation } from '@/i18n/i18next-serverside-config'
+
+const AppList = async () => {
+ const locale = getLocaleOnServer()
+ const { t } = await useTranslation(locale, 'app')
+
+ return (
+ <div className='flex flex-col overflow-auto bg-gray-100 shrink-0 grow'>
+ <Apps />
+ <footer className='px-12 py-6 grow-0 shrink-0'>
+ <h3 className='text-xl font-semibold leading-tight text-gradient'>{t('join')}</h3>
+ <p className='mt-1 text-sm font-normal leading-tight text-gray-700'>{t('communityIntro')}</p>
+ {/*<p className='mt-3 text-sm'>*/}
+ {/* <a className='inline-flex items-center gap-1 link' target='_blank' href={`https://docs.dify.ai${locale === 'en' ? '' : '/v/zh-hans'}/community/product-roadmap`}>*/}
+ {/* {t('roadmap')}*/}
+ {/* <span className={style.linkIcon} />*/}
+ {/* </a>*/}
+ {/*</p>*/}
+ <div className='flex items-center gap-2 mt-3'>
+ <a className={style.socialMediaLink} target='_blank' href='https://github.com/langgenius'><span className={classNames(style.socialMediaIcon, style.githubIcon)} /></a>
+ <a className={style.socialMediaLink} target='_blank' href='https://discord.gg/AhzKf7dNgk'><span className={classNames(style.socialMediaIcon, style.discordIcon)} /></a>
+ </div>
+ </footer>
+ </div >
+ )
+}
+
+export const metadata = {
+ title: 'Apps - Dify',
+}
+
+export default AppList
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/api/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/api/page.tsx
new file mode 100644
index 00000000000..f1b20dd8d84
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/api/page.tsx
@@ -0,0 +1,11 @@
+import React from 'react'
+
+type Props = {}
+
+const page = (props: Props) => {
+ return (
+ <div>dataset detail api</div>
+ )
+}
+
+export default page
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/[documentId]/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/[documentId]/page.tsx
new file mode 100644
index 00000000000..2bd2a356cc2
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/[documentId]/page.tsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import MainDetail from '@/app/components/datasets/documents/detail'
+
+export type IDocumentDetailProps = {
+ params: { datasetId: string; documentId: string }
+}
+
+const DocumentDetail = async ({
+ params: { datasetId, documentId },
+}: IDocumentDetailProps) => {
+ return (
+ <MainDetail datasetId={datasetId} documentId={documentId} />
+ )
+}
+
+export default DocumentDetail
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/create/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/create/page.tsx
new file mode 100644
index 00000000000..e249632bfa3
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/create/page.tsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import DatasetUpdateForm from '@/app/components/datasets/create'
+
+export type IProps = {
+ params: { datasetId: string }
+}
+
+const Create = async ({
+ params: { datasetId },
+}: IProps) => {
+ return (
+ <DatasetUpdateForm datasetId={datasetId} />
+ )
+}
+
+export default Create
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/page.tsx
new file mode 100644
index 00000000000..545e9ed3780
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/page.tsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import Main from '@/app/components/datasets/documents'
+
+export type IProps = {
+ params: { datasetId: string }
+}
+
+const Documents = async ({
+ params: { datasetId },
+}: IProps) => {
+ return (
+ <Main datasetId={datasetId} />
+ )
+}
+
+export default Documents
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/style.module.css b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/style.module.css
new file mode 100644
index 00000000000..67a9fe3bf5d
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/documents/style.module.css
@@ -0,0 +1,9 @@
+.logTable td {
+ padding: 7px 8px;
+ box-sizing: border-box;
+ max-width: 200px;
+}
+
+.pagination li {
+ list-style: none;
+}
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/hitTesting/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/hitTesting/page.tsx
new file mode 100644
index 00000000000..bec07e41b96
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/hitTesting/page.tsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import Main from '@/app/components/datasets/hit-testing'
+
+type Props = {
+ params: { datasetId: string }
+}
+
+const HitTesting = ({
+ params: { datasetId },
+}: Props) => {
+ return (
+ <Main datasetId={datasetId} />
+ )
+}
+
+export default HitTesting
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout.tsx
new file mode 100644
index 00000000000..1dc65789776
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout.tsx
@@ -0,0 +1,169 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect } from 'react'
+import { usePathname, useSelectedLayoutSegments } from 'next/navigation'
+import useSWR from 'swr'
+import { useTranslation } from 'react-i18next'
+import { getLocaleOnClient } from '@/i18n/client'
+import {
+ Cog8ToothIcon,
+ // CommandLineIcon,
+ Squares2X2Icon,
+ PuzzlePieceIcon,
+ DocumentTextIcon,
+} from '@heroicons/react/24/outline'
+import {
+ Cog8ToothIcon as Cog8ToothSolidIcon,
+ // CommandLineIcon as CommandLineSolidIcon,
+ DocumentTextIcon as DocumentTextSolidIcon,
+} from '@heroicons/react/24/solid'
+import Link from 'next/link'
+import { fetchDataDetail, fetchDatasetRelatedApps } from '@/service/datasets'
+import type { RelatedApp } from '@/models/datasets'
+import s from './style.module.css'
+import AppSideBar from '@/app/components/app-sidebar'
+import Divider from '@/app/components/base/divider'
+import Indicator from '@/app/components/header/indicator'
+import AppIcon from '@/app/components/base/app-icon'
+import Loading from '@/app/components/base/loading'
+import DatasetDetailContext from '@/context/dataset-detail'
+
+// import { fetchDatasetDetail } from '@/service/datasets'
+
+export type IAppDetailLayoutProps = {
+ children: React.ReactNode
+ params: { datasetId: string }
+}
+
+const LikedItem: FC<{ type?: 'plugin' | 'app'; appStatus?: boolean; detail: RelatedApp }> = ({
+ type = 'app',
+ appStatus = true,
+ detail
+}) => {
+ return (
+ <Link prefetch className={s.itemWrapper} href={`/app/${detail?.id}/overview`}>
+ <div className={s.iconWrapper}>
+ <AppIcon size='tiny' />
+ {type === 'app' && (
+ <div className={s.statusPoint}>
+ <Indicator color={appStatus ? 'green' : 'gray'} />
+ </div>
+ )}
+ </div>
+ <div className={s.appInfo}>{detail?.name || '--'}</div>
+ </Link>
+ )
+}
+
+const TargetIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <g clip-path="url(#clip0_4610_6951)">
+ <path d="M10.6666 5.33325V3.33325L12.6666 1.33325L13.3332 2.66659L14.6666 3.33325L12.6666 5.33325H10.6666ZM10.6666 5.33325L7.9999 7.99988M14.6666 7.99992C14.6666 11.6818 11.6818 14.6666 7.99992 14.6666C4.31802 14.6666 1.33325 11.6818 1.33325 7.99992C1.33325 4.31802 4.31802 1.33325 7.99992 1.33325M11.3333 7.99992C11.3333 9.84087 9.84087 11.3333 7.99992 11.3333C6.15897 11.3333 4.66659 9.84087 4.66659 7.99992C4.66659 6.15897 6.15897 4.66659 7.99992 4.66659" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" />
+ </g>
+ <defs>
+ <clipPath id="clip0_4610_6951">
+ <rect width="16" height="16" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+}
+
+const TargetSolidIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M12.7733 0.67512C12.9848 0.709447 13.1669 0.843364 13.2627 1.03504L13.83 2.16961L14.9646 2.73689C15.1563 2.83273 15.2902 3.01486 15.3245 3.22639C15.3588 3.43792 15.2894 3.65305 15.1379 3.80458L13.1379 5.80458C13.0128 5.92961 12.8433 5.99985 12.6665 5.99985H10.9426L8.47124 8.47124C8.21089 8.73159 7.78878 8.73159 7.52843 8.47124C7.26808 8.21089 7.26808 7.78878 7.52843 7.52843L9.9998 5.05707V3.33318C9.9998 3.15637 10.07 2.9868 10.1951 2.86177L12.1951 0.861774C12.3466 0.710244 12.5617 0.640794 12.7733 0.67512Z" fill="#155EEF" />
+ <path d="M1.99984 7.99984C1.99984 4.68613 4.68613 1.99984 7.99984 1.99984C8.36803 1.99984 8.6665 1.70136 8.6665 1.33317C8.6665 0.964981 8.36803 0.666504 7.99984 0.666504C3.94975 0.666504 0.666504 3.94975 0.666504 7.99984C0.666504 12.0499 3.94975 15.3332 7.99984 15.3332C12.0499 15.3332 15.3332 12.0499 15.3332 7.99984C15.3332 7.63165 15.0347 7.33317 14.6665 7.33317C14.2983 7.33317 13.9998 7.63165 13.9998 7.99984C13.9998 11.3135 11.3135 13.9998 7.99984 13.9998C4.68613 13.9998 1.99984 11.3135 1.99984 7.99984Z" fill="#155EEF" />
+ <path d="M5.33317 7.99984C5.33317 6.52708 6.52708 5.33317 7.99984 5.33317C8.36803 5.33317 8.6665 5.03469 8.6665 4.6665C8.6665 4.29831 8.36803 3.99984 7.99984 3.99984C5.7907 3.99984 3.99984 5.7907 3.99984 7.99984C3.99984 10.209 5.7907 11.9998 7.99984 11.9998C10.209 11.9998 11.9998 10.209 11.9998 7.99984C11.9998 7.63165 11.7014 7.33317 11.3332 7.33317C10.965 7.33317 10.6665 7.63165 10.6665 7.99984C10.6665 9.4726 9.4726 10.6665 7.99984 10.6665C6.52708 10.6665 5.33317 9.4726 5.33317 7.99984Z" fill="#155EEF" />
+ </svg>
+}
+
+const BookOpenIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path opacity="0.12" d="M1 3.1C1 2.53995 1 2.25992 1.10899 2.04601C1.20487 1.85785 1.35785 1.70487 1.54601 1.60899C1.75992 1.5 2.03995 1.5 2.6 1.5H2.8C3.9201 1.5 4.48016 1.5 4.90798 1.71799C5.28431 1.90973 5.59027 2.21569 5.78201 2.59202C6 3.01984 6 3.5799 6 4.7V10.5L5.94997 10.425C5.60265 9.90398 5.42899 9.64349 5.19955 9.45491C4.99643 9.28796 4.76238 9.1627 4.5108 9.0863C4.22663 9 3.91355 9 3.28741 9H2.6C2.03995 9 1.75992 9 1.54601 8.89101C1.35785 8.79513 1.20487 8.64215 1.10899 8.45399C1 8.24008 1 7.96005 1 7.4V3.1Z" fill="#155EEF" />
+ <path d="M6 10.5L5.94997 10.425C5.60265 9.90398 5.42899 9.64349 5.19955 9.45491C4.99643 9.28796 4.76238 9.1627 4.5108 9.0863C4.22663 9 3.91355 9 3.28741 9H2.6C2.03995 9 1.75992 9 1.54601 8.89101C1.35785 8.79513 1.20487 8.64215 1.10899 8.45399C1 8.24008 1 7.96005 1 7.4V3.1C1 2.53995 1 2.25992 1.10899 2.04601C1.20487 1.85785 1.35785 1.70487 1.54601 1.60899C1.75992 1.5 2.03995 1.5 2.6 1.5H2.8C3.9201 1.5 4.48016 1.5 4.90798 1.71799C5.28431 1.90973 5.59027 2.21569 5.78201 2.59202C6 3.01984 6 3.5799 6 4.7M6 10.5V4.7M6 10.5L6.05003 10.425C6.39735 9.90398 6.57101 9.64349 6.80045 9.45491C7.00357 9.28796 7.23762 9.1627 7.4892 9.0863C7.77337 9 8.08645 9 8.71259 9H9.4C9.96005 9 10.2401 9 10.454 8.89101C10.6422 8.79513 10.7951 8.64215 10.891 8.45399C11 8.24008 11 7.96005 11 7.4V3.1C11 2.53995 11 2.25992 10.891 2.04601C10.7951 1.85785 10.6422 1.70487 10.454 1.60899C10.2401 1.5 9.96005 1.5 9.4 1.5H9.2C8.07989 1.5 7.51984 1.5 7.09202 1.71799C6.71569 1.90973 6.40973 2.21569 6.21799 2.59202C6 3.01984 6 3.5799 6 4.7" stroke="#155EEF" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
+ const {
+ children,
+ params: { datasetId },
+ } = props
+ const pathname = usePathname()
+ const hideSideBar = /documents\/create$/.test(pathname)
+ const { t } = useTranslation()
+ const { data: datasetRes, error } = useSWR({
+ action: 'fetchDataDetail',
+ datasetId,
+ }, apiParams => fetchDataDetail(apiParams.datasetId))
+
+ const { data: relatedApps } = useSWR({
+ action: 'fetchDatasetRelatedApps',
+ datasetId,
+ }, apiParams => fetchDatasetRelatedApps(apiParams.datasetId))
+
+ const navigation = [
+ { name: t('common.datasetMenus.documents'), href: `/datasets/${datasetId}/documents`, icon: DocumentTextIcon, selectedIcon: DocumentTextSolidIcon },
+ { name: t('common.datasetMenus.hitTesting'), href: `/datasets/${datasetId}/hitTesting`, icon: TargetIcon, selectedIcon: TargetSolidIcon },
+ // { name: 'api & webhook', href: `/datasets/${datasetId}/api`, icon: CommandLineIcon, selectedIcon: CommandLineSolidIcon },
+ { name: t('common.datasetMenus.settings'), href: `/datasets/${datasetId}/settings`, icon: Cog8ToothIcon, selectedIcon: Cog8ToothSolidIcon },
+ ]
+
+ useEffect(() => {
+ if (datasetRes) {
+ document.title = `${datasetRes.name || 'Dataset'} - Dify`
+ }
+ }, [datasetRes])
+
+ const ExtraInfo: FC = () => {
+ const locale = getLocaleOnClient()
+
+ return <div className='w-full'>
+ <Divider className='mt-5' />
+ {relatedApps?.data?.length ? (
+ <>
+ <div className={s.subTitle}>{relatedApps?.total || '--'} {t('common.datasetMenus.relatedApp')}</div>
+ {relatedApps?.data?.map((item) => (<LikedItem detail={item} />))}
+ </>
+ ) : (
+ <div className='mt-5 p-3'>
+ <div className='flex items-center justify-start gap-2'>
+ <div className={s.emptyIconDiv}>
+ <Squares2X2Icon className='w-3 h-3 text-gray-500' />
+ </div>
+ <div className={s.emptyIconDiv}>
+ <PuzzlePieceIcon className='w-3 h-3 text-gray-500' />
+ </div>
+ </div>
+ <div className='text-xs text-gray-500 mt-2'>{t('common.datasetMenus.emptyTip')}</div>
+ <a
+ className='inline-flex items-center text-xs text-primary-600 mt-2 cursor-pointer'
+ href={`https://docs.dify.ai/${locale === 'en' ? '' : 'v/zh-hans'}/application/prompt-engineering`}
+ target='_blank'
+ >
+ <BookOpenIcon className='mr-1' />
+ {t('common.datasetMenus.viewDoc')}
+ </a>
+ </div>
+ )}
+ </div>
+ }
+
+ if (!datasetRes && !error)
+ return <Loading />
+
+ return (
+ <div className='flex' style={{ height: 'calc(100vh - 56px)' }}>
+ {!hideSideBar && <AppSideBar
+ title={datasetRes?.name || '--'}
+ desc={datasetRes?.description || '--'}
+ navigation={navigation}
+ extraInfo={<ExtraInfo />}
+ iconType='dataset'
+ />}
+ <DatasetDetailContext.Provider value={{ indexingTechnique: datasetRes?.indexing_technique }}>
+ <div className="bg-white grow">{children}</div>
+ </DatasetDetailContext.Provider>
+ </div>
+ )
+}
+export default React.memo(DatasetDetailLayout)
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/settings/page.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/settings/page.tsx
new file mode 100644
index 00000000000..23863881c3b
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/settings/page.tsx
@@ -0,0 +1,23 @@
+import React from 'react'
+import { getLocaleOnServer } from '@/i18n/server'
+import { useTranslation } from '@/i18n/i18next-serverside-config'
+import Form from '@/app/components/datasets/settings/form'
+
+const Settings = async () => {
+ const locale = getLocaleOnServer()
+ const { t } = await useTranslation(locale, 'dataset-settings')
+
+ return (
+ <div className='bg-white h-full'>
+ <div className='px-6 py-3'>
+ <div className='mb-1 text-lg font-semibold text-gray-900'>{t('title')}</div>
+ <div className='text-sm text-gray-500'>{t('desc')}</div>
+ </div>
+ <div>
+ <Form />
+ </div>
+ </div>
+ )
+}
+
+export default Settings
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/style.module.css b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/style.module.css
new file mode 100644
index 00000000000..786726703f6
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/style.module.css
@@ -0,0 +1,18 @@
+.itemWrapper {
+ @apply flex items-center w-full h-10 px-3 rounded-lg hover:bg-gray-50 cursor-pointer;
+}
+.appInfo {
+ @apply truncate text-gray-700 text-sm font-normal;
+}
+.iconWrapper {
+ @apply relative w-6 h-6 mr-2 bg-[#D5F5F6] rounded-md;
+}
+.statusPoint {
+ @apply flex justify-center items-center absolute -right-0.5 -bottom-0.5 w-2.5 h-2.5 bg-white rounded;
+}
+.subTitle {
+ @apply uppercase text-xs text-gray-500 font-medium px-3 pb-2 pt-4;
+}
+.emptyIconDiv {
+ @apply h-7 w-7 bg-gray-50 border border-[#EAECF5] inline-flex justify-center items-center rounded-lg;
+}
diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/layout.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/layout.tsx
new file mode 100644
index 00000000000..ccbc58f5e5c
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/layout.tsx
@@ -0,0 +1,16 @@
+import type { FC } from 'react'
+import React from 'react'
+
+export type IDatasetDetail = {
+ children: React.ReactNode
+}
+
+const AppDetail: FC<IDatasetDetail> = ({ children }) => {
+ return (
+ <>
+ {children}
+ </>
+ )
+}
+
+export default React.memo(AppDetail)
diff --git a/web/app/(commonLayout)/datasets/DatasetCard.tsx b/web/app/(commonLayout)/datasets/DatasetCard.tsx
new file mode 100644
index 00000000000..b6786d05196
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/DatasetCard.tsx
@@ -0,0 +1,89 @@
+'use client'
+
+import { useContext, useContextSelector } from 'use-context-selector'
+import Link from 'next/link'
+import useSWR from 'swr'
+import type { MouseEventHandler } from 'react'
+import { useCallback, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import style from '../list.module.css'
+import type { App } from '@/types/app'
+import Confirm from '@/app/components/base/confirm'
+import { ToastContext } from '@/app/components/base/toast'
+import { deleteDataset, fetchDatasets } from '@/service/datasets'
+import AppIcon from '@/app/components/base/app-icon'
+import AppsContext from '@/context/app-context'
+import { DataSet } from '@/models/datasets'
+import classNames from 'classnames'
+
+export type DatasetCardProps = {
+ dataset: DataSet
+}
+
+const DatasetCard = ({
+ dataset,
+}: DatasetCardProps) => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+
+ const { mutate: mutateDatasets } = useSWR({ url: '/datasets', params: { page: 1 } }, fetchDatasets)
+
+ const [showConfirmDelete, setShowConfirmDelete] = useState(false)
+ const onDeleteClick: MouseEventHandler = useCallback((e) => {
+ e.preventDefault()
+ setShowConfirmDelete(true)
+ }, [])
+ const onConfirmDelete = useCallback(async () => {
+ try {
+ await deleteDataset(dataset.id)
+ notify({ type: 'success', message: t('dataset.datasetDeleted') })
+ mutateDatasets()
+ }
+ catch (e: any) {
+ notify({ type: 'error', message: `${t('dataset.datasetDeleteFailed')}${'message' in e ? `: ${e.message}` : ''}` })
+ }
+ setShowConfirmDelete(false)
+ }, [dataset.id])
+
+ return (
+ <>
+ <Link href={`/datasets/${dataset.id}/documents`} className={style.listItem}>
+ <div className={style.listItemTitle}>
+ <AppIcon size='small' />
+ <div className={style.listItemHeading}>
+ <div className={style.listItemHeadingContent}>{dataset.name}</div>
+ </div>
+ <span className={style.deleteAppIcon} onClick={onDeleteClick} />
+ </div>
+ <div className={style.listItemDescription}>{dataset.description}</div>
+ <div className={classNames(style.listItemFooter, style.datasetCardFooter)}>
+ <span className={style.listItemStats}>
+ <span className={classNames(style.listItemFooterIcon, style.docIcon)} />
+ {dataset.document_count}{t('dataset.documentCount')}
+ </span>
+ <span className={style.listItemStats}>
+ <span className={classNames(style.listItemFooterIcon, style.textIcon)} />
+ {Math.round(dataset.word_count / 1000)}{t('dataset.wordCount')}
+ </span>
+ <span className={style.listItemStats}>
+ <span className={classNames(style.listItemFooterIcon, style.applicationIcon)} />
+ {dataset.app_count}{t('dataset.appCount')}
+ </span>
+ </div>
+
+ {showConfirmDelete && (
+ <Confirm
+ title={t('dataset.deleteDatasetConfirmTitle')}
+ content={t('dataset.deleteDatasetConfirmContent')}
+ isShow={showConfirmDelete}
+ onClose={() => setShowConfirmDelete(false)}
+ onConfirm={onConfirmDelete}
+ onCancel={() => setShowConfirmDelete(false)}
+ />
+ )}
+ </Link>
+ </>
+ )
+}
+
+export default DatasetCard
diff --git a/web/app/(commonLayout)/datasets/DatasetFooter.tsx b/web/app/(commonLayout)/datasets/DatasetFooter.tsx
new file mode 100644
index 00000000000..020bfceffe1
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/DatasetFooter.tsx
@@ -0,0 +1,19 @@
+'use client'
+
+import { useTranslation } from "react-i18next"
+
+const DatasetFooter = () => {
+ const { t } = useTranslation()
+
+ return (
+ <footer className='px-12 py-6 grow-0 shrink-0'>
+ <h3 className='text-xl font-semibold leading-tight text-gradient'>{t('dataset.didYouKnow')}</h3>
+ <p className='mt-1 text-sm font-normal leading-tight text-gray-700'>
+ {t('dataset.intro1')}<a className='inline-flex items-center gap-1 link' target='_blank' href='/'>{t('dataset.intro2')}</a>{t('dataset.intro3')}<br />
+ {t('dataset.intro4')}<a className='inline-flex items-center gap-1 link' target='_blank' href='/'>{t('dataset.intro5')}</a>{t('dataset.intro6')}
+ </p>
+ </footer>
+ )
+}
+
+export default DatasetFooter
diff --git a/web/app/(commonLayout)/datasets/Datasets.tsx b/web/app/(commonLayout)/datasets/Datasets.tsx
new file mode 100644
index 00000000000..b044547748e
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/Datasets.tsx
@@ -0,0 +1,27 @@
+'use client'
+
+import { useEffect } from 'react'
+import useSWR from 'swr'
+import { DataSet } from '@/models/datasets';
+import NewDatasetCard from './NewDatasetCard'
+import DatasetCard from './DatasetCard';
+import { fetchDatasets } from '@/service/datasets';
+
+const Datasets = () => {
+ // const { datasets, mutateDatasets } = useAppContext()
+ const { data: datasetList, mutate: mutateDatasets } = useSWR({ url: '/datasets', params: { page: 1 } }, fetchDatasets)
+
+ useEffect(() => {
+ mutateDatasets()
+ }, [])
+
+ return (
+ <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-8 sm:grid-cols-2 lg:grid-cols-4 grow shrink-0'>
+ {datasetList?.data.map(dataset => (<DatasetCard key={dataset.id} dataset={dataset} />))}
+ <NewDatasetCard />
+ </nav>
+ )
+}
+
+export default Datasets
+
diff --git a/web/app/(commonLayout)/datasets/NewDatasetCard.tsx b/web/app/(commonLayout)/datasets/NewDatasetCard.tsx
new file mode 100644
index 00000000000..a3f6282c972
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/NewDatasetCard.tsx
@@ -0,0 +1,28 @@
+'use client'
+
+import { useState } from 'react'
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+import style from '../list.module.css'
+
+const CreateAppCard = () => {
+ const { t } = useTranslation()
+ const [showNewAppDialog, setShowNewAppDialog] = useState(false)
+
+ return (
+ <a className={classNames(style.listItem, style.newItemCard)} href='/datasets/create'>
+ <div className={style.listItemTitle}>
+ <span className={style.newItemIcon}>
+ <span className={classNames(style.newItemIconImage, style.newItemIconAdd)} />
+ </span>
+ <div className={classNames(style.listItemHeading, style.newItemCardHeading)}>
+ {t('dataset.createDataset')}
+ </div>
+ </div>
+ <div className={style.listItemDescription}>{t('dataset.createDatasetIntro')}</div>
+ {/* <div className='text-xs text-gray-500'>{t('app.createFromConfigFile')}</div> */}
+ </a>
+ )
+}
+
+export default CreateAppCard
diff --git a/web/app/(commonLayout)/datasets/assets/application.svg b/web/app/(commonLayout)/datasets/assets/application.svg
new file mode 100644
index 00000000000..0384961f825
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/assets/application.svg
@@ -0,0 +1,6 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M4.2 1.5H2.3C2.01997 1.5 1.87996 1.5 1.773 1.5545C1.67892 1.60243 1.60243 1.67892 1.5545 1.773C1.5 1.87996 1.5 2.01997 1.5 2.3V4.2C1.5 4.48003 1.5 4.62004 1.5545 4.727C1.60243 4.82108 1.67892 4.89757 1.773 4.9455C1.87996 5 2.01997 5 2.3 5H4.2C4.48003 5 4.62004 5 4.727 4.9455C4.82108 4.89757 4.89757 4.82108 4.9455 4.727C5 4.62004 5 4.48003 5 4.2V2.3C5 2.01997 5 1.87996 4.9455 1.773C4.89757 1.67892 4.82108 1.60243 4.727 1.5545C4.62004 1.5 4.48003 1.5 4.2 1.5Z" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M9.7 1.5H7.8C7.51997 1.5 7.37996 1.5 7.273 1.5545C7.17892 1.60243 7.10243 1.67892 7.0545 1.773C7 1.87996 7 2.01997 7 2.3V4.2C7 4.48003 7 4.62004 7.0545 4.727C7.10243 4.82108 7.17892 4.89757 7.273 4.9455C7.37996 5 7.51997 5 7.8 5H9.7C9.98003 5 10.12 5 10.227 4.9455C10.3211 4.89757 10.3976 4.82108 10.4455 4.727C10.5 4.62004 10.5 4.48003 10.5 4.2V2.3C10.5 2.01997 10.5 1.87996 10.4455 1.773C10.3976 1.67892 10.3211 1.60243 10.227 1.5545C10.12 1.5 9.98003 1.5 9.7 1.5Z" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M9.7 7H7.8C7.51997 7 7.37996 7 7.273 7.0545C7.17892 7.10243 7.10243 7.17892 7.0545 7.273C7 7.37996 7 7.51997 7 7.8V9.7C7 9.98003 7 10.12 7.0545 10.227C7.10243 10.3211 7.17892 10.3976 7.273 10.4455C7.37996 10.5 7.51997 10.5 7.8 10.5H9.7C9.98003 10.5 10.12 10.5 10.227 10.4455C10.3211 10.3976 10.3976 10.3211 10.4455 10.227C10.5 10.12 10.5 9.98003 10.5 9.7V7.8C10.5 7.51997 10.5 7.37996 10.4455 7.273C10.3976 7.17892 10.3211 7.10243 10.227 7.0545C10.12 7 9.98003 7 9.7 7Z" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M4.2 7H2.3C2.01997 7 1.87996 7 1.773 7.0545C1.67892 7.10243 1.60243 7.17892 1.5545 7.273C1.5 7.37996 1.5 7.51997 1.5 7.8V9.7C1.5 9.98003 1.5 10.12 1.5545 10.227C1.60243 10.3211 1.67892 10.3976 1.773 10.4455C1.87996 10.5 2.01997 10.5 2.3 10.5H4.2C4.48003 10.5 4.62004 10.5 4.727 10.4455C4.82108 10.3976 4.89757 10.3211 4.9455 10.227C5 10.12 5 9.98003 5 9.7V7.8C5 7.51997 5 7.37996 4.9455 7.273C4.89757 7.17892 4.82108 7.10243 4.727 7.0545C4.62004 7 4.48003 7 4.2 7Z" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/datasets/assets/doc.svg b/web/app/(commonLayout)/datasets/assets/doc.svg
new file mode 100644
index 00000000000..6bb150cfd62
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/assets/doc.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M7 1H3C2.73478 1 2.48043 1.10536 2.29289 1.29289C2.10536 1.48043 2 1.73478 2 2V10C2 10.2652 2.10536 10.5196 2.29289 10.7071C2.48043 10.8946 2.73478 11 3 11H9C9.26522 11 9.51957 10.8946 9.70711 10.7071C9.89464 10.5196 10 10.2652 10 10V4M7 1L10 4M7 1V4H10M8 6.5H4M8 8.5H4M5 4.5H4" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/datasets/assets/text.svg b/web/app/(commonLayout)/datasets/assets/text.svg
new file mode 100644
index 00000000000..6bb150cfd62
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/assets/text.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M7 1H3C2.73478 1 2.48043 1.10536 2.29289 1.29289C2.10536 1.48043 2 1.73478 2 2V10C2 10.2652 2.10536 10.5196 2.29289 10.7071C2.48043 10.8946 2.73478 11 3 11H9C9.26522 11 9.51957 10.8946 9.70711 10.7071C9.89464 10.5196 10 10.2652 10 10V4M7 1L10 4M7 1V4H10M8 6.5H4M8 8.5H4M5 4.5H4" stroke="#98A2B3" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/(commonLayout)/datasets/create/page.tsx b/web/app/(commonLayout)/datasets/create/page.tsx
new file mode 100644
index 00000000000..663a830665a
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/create/page.tsx
@@ -0,0 +1,12 @@
+import React from 'react'
+import DatasetUpdateForm from '@/app/components/datasets/create'
+
+type Props = {}
+
+const DatasetCreation = async (props: Props) => {
+ return (
+ <DatasetUpdateForm />
+ )
+}
+
+export default DatasetCreation
diff --git a/web/app/(commonLayout)/datasets/page.tsx b/web/app/(commonLayout)/datasets/page.tsx
new file mode 100644
index 00000000000..909c46a4359
--- /dev/null
+++ b/web/app/(commonLayout)/datasets/page.tsx
@@ -0,0 +1,23 @@
+import classNames from 'classnames'
+import { getLocaleOnServer } from '@/i18n/server'
+import { useTranslation } from '@/i18n/i18next-serverside-config'
+import Datasets from './Datasets'
+import DatasetFooter from './DatasetFooter'
+
+const AppList = async () => {
+ const locale = getLocaleOnServer()
+ const { t } = await useTranslation(locale, 'dataset')
+
+ return (
+ <div className='flex flex-col overflow-auto bg-gray-100 shrink-0 grow'>
+ <Datasets />
+ <DatasetFooter />
+ </div >
+ )
+}
+
+export const metadata = {
+ title: 'Datasets - Dify',
+}
+
+export default AppList
diff --git a/web/app/(commonLayout)/layout.tsx b/web/app/(commonLayout)/layout.tsx
new file mode 100644
index 00000000000..901fd95eae9
--- /dev/null
+++ b/web/app/(commonLayout)/layout.tsx
@@ -0,0 +1,19 @@
+import React from "react";
+import type { FC } from 'react'
+import LayoutClient, { ICommonLayoutProps } from "./_layout-client";
+import GA, { GaType } from '@/app/components/base/ga'
+
+const Layout: FC<ICommonLayoutProps> = ({ children }) => {
+ return (
+ <>
+ <GA gaType={GaType.admin} />
+ <LayoutClient children={children}></LayoutClient>
+ </>
+ )
+}
+
+export const metadata = {
+ title: 'Dify',
+}
+
+export default Layout
\ No newline at end of file
diff --git a/web/app/(commonLayout)/list.module.css b/web/app/(commonLayout)/list.module.css
new file mode 100644
index 00000000000..14351d40eb6
--- /dev/null
+++ b/web/app/(commonLayout)/list.module.css
@@ -0,0 +1,183 @@
+.listItem {
+ @apply col-span-1 bg-white border-2 border-solid border-transparent rounded-lg shadow-sm min-h-[160px] flex flex-col transition-all duration-200 ease-in-out cursor-pointer hover:shadow-lg;
+}
+
+.listItem.newItemCard {
+ @apply outline outline-1 outline-gray-200 -outline-offset-1 hover:shadow-sm hover:bg-white;
+ background-color: rgba(229, 231, 235, 0.5);
+}
+
+.listItem.selectable {
+ @apply relative bg-gray-50 outline outline-1 outline-gray-200 -outline-offset-1 shadow-none hover:bg-none hover:shadow-none hover:outline-primary-200 transition-colors;
+}
+.listItem.selectable * {
+ @apply relative;
+}
+.listItem.selectable::before {
+ content: '';
+ @apply absolute top-0 left-0 block w-full h-full rounded-lg pointer-events-none opacity-0 transition-opacity duration-200 ease-in-out hover:opacity-100;
+ background: linear-gradient(0deg, rgba(235, 245, 255, 0.5), rgba(235, 245, 255, 0.5)), #FFFFFF;
+}
+.listItem.selectable:hover::before {
+ @apply opacity-100;
+}
+
+.listItem.selected {
+ @apply border-primary-600 hover:border-primary-600 border-2;
+}
+.listItem.selected::before {
+ @apply opacity-100;
+}
+
+.appIcon {
+ @apply flex items-center justify-center w-8 h-8 bg-pink-100 rounded-lg grow-0 shrink-0;
+}
+.appIcon.medium {
+ @apply w-9 h-9;
+}
+.appIcon.large {
+ @apply w-10 h-10;
+}
+
+.newItemIcon {
+ @apply flex items-center justify-center w-8 h-8 transition-colors duration-200 ease-in-out border border-gray-200 rounded-lg hover:bg-white grow-0 shrink-0;
+}
+.listItem:hover .newItemIcon {
+ @apply bg-gray-50 border-primary-100;
+}
+.newItemCard .newItemIcon {
+ @apply bg-gray-100;
+}
+.newItemCard:hover .newItemIcon {
+ @apply bg-white;
+}
+.selectable .newItemIcon {
+ @apply bg-gray-50;
+}
+.selectable:hover .newItemIcon {
+ @apply bg-primary-50;
+}
+.newItemIconImage {
+ @apply grow-0 shrink-0 block w-4 h-4 bg-center bg-contain transition-colors duration-200 ease-in-out;
+ color: #1f2a37;
+}
+.listItem:hover .newIconImage {
+ @apply text-primary-600;
+}
+.newItemIconAdd {
+ background-image: url('./apps/assets/add.svg');
+}
+.newItemIconChat {
+ background-image: url('./apps/assets/chat.svg');
+}
+.newItemIconComplete {
+ background-image: url('./apps/assets/completion.svg');
+}
+
+.listItemTitle {
+ @apply flex pt-[14px] px-[14px] pb-3 h-[66px] items-center gap-3 grow-0 shrink-0;
+}
+
+.listItemHeading {
+ @apply relative h-8 text-sm font-medium leading-8 grow;
+}
+
+.listItemHeadingContent {
+ @apply absolute top-0 left-0 w-full h-full overflow-hidden text-ellipsis whitespace-nowrap;
+}
+
+.deleteAppIcon {
+ @apply hidden grow-0 shrink-0 basis-8 w-8 h-8 rounded-lg transition-colors duration-200 ease-in-out bg-white border border-gray-200 hover:bg-gray-100 bg-center bg-no-repeat;
+ background-size: 16px;
+ background-image: url('./apps/assets/delete.svg');
+}
+.listItem:hover .deleteAppIcon {
+ @apply block;
+}
+
+.listItemDescription {
+ @apply mb-3 px-[14px] h-9 text-xs leading-normal text-gray-500 line-clamp-2;
+}
+
+.listItemFooter {
+ @apply flex items-center flex-wrap min-h-[42px] px-[14px] pt-2 pb-[10px];
+}
+.listItemFooter.datasetCardFooter {
+ @apply flex items-center gap-4 text-xs text-gray-500;
+}
+
+.listItemStats {
+ @apply flex items-center gap-1;
+}
+
+.listItemFooterIcon {
+ @apply block w-3 h-3 bg-center bg-contain;
+}
+.solidChatIcon {
+ background-image: url('./apps/assets/chat-solid.svg');
+}
+.solidCompletionIcon {
+ background-image: url('./apps/assets/completion-solid.svg');
+}
+.docIcon {
+ background-image: url('./datasets/assets/doc.svg');
+}
+.textIcon {
+ background-image: url('./datasets/assets/text.svg');
+}
+.applicationIcon {
+ background-image: url('./datasets/assets/application.svg');
+}
+
+.newItemCardHeading {
+ @apply transition-colors duration-200 ease-in-out;
+}
+.listItem:hover .newItemCardHeading {
+ @apply text-primary-600;
+}
+
+.listItemLink {
+ @apply inline-flex items-center gap-1 text-xs text-gray-400 transition-colors duration-200 ease-in-out;
+}
+.listItem:hover .listItemLink {
+ @apply text-primary-600
+}
+
+.linkIcon {
+ @apply block w-[13px] h-[13px] bg-center bg-contain;
+ background-image: url('./apps/assets/link.svg');
+}
+
+.linkIcon.grayLinkIcon {
+ background-image: url('./apps/assets/link-gray.svg');
+}
+.listItem:hover .grayLinkIcon {
+ background-image: url('./apps/assets/link.svg');
+}
+
+.rightIcon {
+ @apply block w-[13px] h-[13px] bg-center bg-contain;
+ background-image: url('./apps/assets/right-arrow.svg');
+}
+
+.socialMediaLink {
+ @apply flex items-center justify-center w-8 h-8 cursor-pointer hover:opacity-80 transition-opacity duration-200 ease-in-out;
+}
+
+.socialMediaIcon {
+ @apply block w-6 h-6 bg-center bg-contain;
+}
+
+.githubIcon {
+ background-image: url('./apps/assets/github.svg');
+}
+
+.discordIcon {
+ background-image: url('./apps/assets/discord.svg');
+}
+
+/* #region new app dialog */
+.newItemCaption {
+ @apply inline-flex items-center mb-2 text-sm font-medium;
+}
+/* #endregion new app dialog */
diff --git a/web/app/(commonLayout)/plugins-coming-soon/assets/coming-soon.png b/web/app/(commonLayout)/plugins-coming-soon/assets/coming-soon.png
new file mode 100644
index 00000000000..a1c48b508df
Binary files /dev/null and b/web/app/(commonLayout)/plugins-coming-soon/assets/coming-soon.png differ
diff --git a/web/app/(commonLayout)/plugins-coming-soon/assets/plugins-bg.png b/web/app/(commonLayout)/plugins-coming-soon/assets/plugins-bg.png
new file mode 100644
index 00000000000..9be76acc520
Binary files /dev/null and b/web/app/(commonLayout)/plugins-coming-soon/assets/plugins-bg.png differ
diff --git a/web/app/(commonLayout)/plugins-coming-soon/page.module.css b/web/app/(commonLayout)/plugins-coming-soon/page.module.css
new file mode 100644
index 00000000000..73aab949c98
--- /dev/null
+++ b/web/app/(commonLayout)/plugins-coming-soon/page.module.css
@@ -0,0 +1,32 @@
+.bg {
+ position: relative;
+ width: 750px;
+ height: 450px;
+ background: #fff url(./assets/plugins-bg.png) center center no-repeat;
+ background-size: contain;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+ border-radius: 16px;
+}
+
+.text {
+ position: absolute;
+ top: 40px;
+ left: 48px;
+ width: 526px;
+ background: linear-gradient(91.92deg, #104AE1 -1.74%, #0098EE 75.74%);
+ background-clip: text;
+ color: transparent;
+ font-size: 24px;
+ font-weight: 700;
+ line-height: 32px;
+}
+
+.tag {
+ position: absolute;
+ width: 116.74px;
+ height: 69.3px;
+ left: -18.37px;
+ top: -11.48px;
+ background: url(./assets/coming-soon.png) center center no-repeat;
+ background-size: contain;
+}
\ No newline at end of file
diff --git a/web/app/(commonLayout)/plugins-coming-soon/page.tsx b/web/app/(commonLayout)/plugins-coming-soon/page.tsx
new file mode 100644
index 00000000000..285b0189a33
--- /dev/null
+++ b/web/app/(commonLayout)/plugins-coming-soon/page.tsx
@@ -0,0 +1,19 @@
+import s from './page.module.css'
+import { getLocaleOnServer } from '@/i18n/server'
+import { useTranslation } from '@/i18n/i18next-serverside-config'
+
+const PluginsComingSoon = async () => {
+ const locale = getLocaleOnServer()
+ const { t } = await useTranslation(locale, 'common')
+
+ return (
+ <div className='flex justify-center items-center w-full h-full bg-gray-100'>
+ <div className={s.bg}>
+ <div className={s.tag} />
+ <div className={s.text}>{t('menus.pluginsTips')}</div>
+ </div>
+ </div >
+ )
+}
+
+export default PluginsComingSoon
diff --git a/web/app/(shareLayout)/chat/[token]/page.tsx b/web/app/(shareLayout)/chat/[token]/page.tsx
new file mode 100644
index 00000000000..472bc360910
--- /dev/null
+++ b/web/app/(shareLayout)/chat/[token]/page.tsx
@@ -0,0 +1,16 @@
+import type { FC } from 'react'
+import React from 'react'
+
+import type { IMainProps } from '@/app/components/share/chat'
+import Main from '@/app/components/share/chat'
+
+const Chat: FC<IMainProps> = ({
+ params,
+}: any) => {
+
+ return (
+ <Main params={params} />
+ )
+}
+
+export default React.memo(Chat)
diff --git a/web/app/(shareLayout)/completion/[token]/page.tsx b/web/app/(shareLayout)/completion/[token]/page.tsx
new file mode 100644
index 00000000000..0c3992dc726
--- /dev/null
+++ b/web/app/(shareLayout)/completion/[token]/page.tsx
@@ -0,0 +1,13 @@
+import type { FC } from 'react'
+import React from 'react'
+
+import type { IMainProps } from '@/app/components/share/chat'
+import Main from '@/app/components/share/text-generation'
+
+const TextGeneration: FC<IMainProps> = () => {
+ return (
+ <Main />
+ )
+}
+
+export default React.memo(TextGeneration)
\ No newline at end of file
diff --git a/web/app/(shareLayout)/layout.tsx b/web/app/(shareLayout)/layout.tsx
new file mode 100644
index 00000000000..f629943f864
--- /dev/null
+++ b/web/app/(shareLayout)/layout.tsx
@@ -0,0 +1,18 @@
+import React from "react";
+import type { FC } from 'react'
+import GA, { GaType } from '@/app/components/base/ga'
+
+const Layout: FC<{
+ children: React.ReactNode
+}> = ({ children }) => {
+ return (
+ <div className="overflow-x-auto">
+ <div className="w-screen h-screen min-w-[300px]">
+ <GA gaType={GaType.webapp} />
+ {children}
+ </div>
+ </div>
+ )
+}
+
+export default Layout
\ No newline at end of file
diff --git a/web/app/api/hello/route.ts b/web/app/api/hello/route.ts
new file mode 100644
index 00000000000..d3a7036df17
--- /dev/null
+++ b/web/app/api/hello/route.ts
@@ -0,0 +1,3 @@
+export async function GET(_request: Request) {
+ return new Response('Hello, Next.js!')
+}
diff --git a/web/app/components/app-sidebar/basic.tsx b/web/app/components/app-sidebar/basic.tsx
new file mode 100644
index 00000000000..4cefafa0c15
--- /dev/null
+++ b/web/app/components/app-sidebar/basic.tsx
@@ -0,0 +1,65 @@
+import React from 'react'
+import {
+ InformationCircleIcon,
+} from '@heroicons/react/24/outline'
+import Tooltip from '../base/tooltip'
+import AppIcon from '../base/app-icon'
+
+const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
+
+export function randomString(length: number) {
+ let result = ''
+ for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]
+ return result
+}
+
+export type IAppBasicProps = {
+ iconType?: 'app' | 'api' | 'dataset'
+ iconUrl?: string
+ name: string
+ type: string | React.ReactNode
+ hoverTip?: string
+ textStyle?: { main?: string; extra?: string }
+}
+
+const AlgorithmSvg = <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.5 3.5C8.5 4.60457 9.39543 5.5 10.5 5.5C11.6046 5.5 12.5 4.60457 12.5 3.5C12.5 2.39543 11.6046 1.5 10.5 1.5C9.39543 1.5 8.5 2.39543 8.5 3.5Z" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M12.5 9C12.5 10.1046 13.3954 11 14.5 11C15.6046 11 16.5 10.1046 16.5 9C16.5 7.89543 15.6046 7 14.5 7C13.3954 7 12.5 7.89543 12.5 9Z" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M8.5 3.5H5.5L3.5 6.5" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M8.5 14.5C8.5 15.6046 9.39543 16.5 10.5 16.5C11.6046 16.5 12.5 15.6046 12.5 14.5C12.5 13.3954 11.6046 12.5 10.5 12.5C9.39543 12.5 8.5 13.3954 8.5 14.5Z" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M8.5 14.5H5.5L3.5 11.5" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ <path d="M12.5 9H1.5" stroke="#5850EC" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+</svg>
+
+const DatasetSvg = <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M0.833497 5.13481C0.833483 4.69553 0.83347 4.31654 0.858973 4.0044C0.88589 3.67495 0.94532 3.34727 1.10598 3.03195C1.34567 2.56155 1.72812 2.17909 2.19852 1.93941C2.51384 1.77875 2.84152 1.71932 3.17097 1.6924C3.48312 1.6669 3.86209 1.66691 4.30137 1.66693L7.62238 1.66684C8.11701 1.66618 8.55199 1.66561 8.95195 1.80356C9.30227 1.92439 9.62134 2.12159 9.88607 2.38088C10.1883 2.67692 10.3823 3.06624 10.603 3.50894L11.3484 5.00008H14.3679C15.0387 5.00007 15.5924 5.00006 16.0434 5.03691C16.5118 5.07518 16.9424 5.15732 17.3468 5.36339C17.974 5.68297 18.4839 6.19291 18.8035 6.82011C19.0096 7.22456 19.0917 7.65515 19.13 8.12356C19.1668 8.57455 19.1668 9.12818 19.1668 9.79898V13.5345C19.1668 14.2053 19.1668 14.7589 19.13 15.2099C19.0917 15.6784 19.0096 16.1089 18.8035 16.5134C18.4839 17.1406 17.974 17.6505 17.3468 17.9701C16.9424 18.1762 16.5118 18.2583 16.0434 18.2966C15.5924 18.3334 15.0387 18.3334 14.3679 18.3334H5.63243C4.96163 18.3334 4.40797 18.3334 3.95698 18.2966C3.48856 18.2583 3.05798 18.1762 2.65353 17.9701C2.02632 17.6505 1.51639 17.1406 1.19681 16.5134C0.990734 16.1089 0.908597 15.6784 0.870326 15.2099C0.833478 14.7589 0.833487 14.2053 0.833497 13.5345V5.13481ZM7.51874 3.33359C8.17742 3.33359 8.30798 3.34447 8.4085 3.37914C8.52527 3.41942 8.63163 3.48515 8.71987 3.57158C8.79584 3.64598 8.86396 3.7579 9.15852 4.34704L9.48505 5.00008L2.50023 5.00008C2.50059 4.61259 2.50314 4.34771 2.5201 4.14012C2.5386 3.91374 2.57 3.82981 2.59099 3.7886C2.67089 3.6318 2.79837 3.50432 2.95517 3.42442C2.99638 3.40343 3.08031 3.37203 3.30669 3.35353C3.54281 3.33424 3.85304 3.33359 4.3335 3.33359H7.51874Z" fill="#444CE7" />
+</svg>
+
+const ICON_MAP = {
+ 'app': <AppIcon className='border !border-[rgba(0,0,0,0.05)]' />,
+ 'api': <AppIcon innerIcon={AlgorithmSvg} className='border !bg-purple-50 !border-purple-200' />,
+ 'dataset': <AppIcon innerIcon={DatasetSvg} className='!border-[0.5px] !border-indigo-100 !bg-indigo-25' />
+}
+
+export default function AppBasic({ iconUrl, name, type, hoverTip, textStyle, iconType = 'app' }: IAppBasicProps) {
+ return (
+ <div className="flex items-start">
+ {iconUrl && (
+ <div className='flex-shrink-0 mr-3'>
+ {/* <img className="inline-block rounded-lg h-9 w-9" src={iconUrl} alt={name} /> */}
+ {ICON_MAP[iconType]}
+ </div>
+ )}
+ <div className="group">
+ <div className={`flex flex-row items-center text-sm font-semibold text-gray-700 group-hover:text-gray-900 ${textStyle?.main}`}>
+ {name}
+ {hoverTip
+ && <Tooltip content={hoverTip} selector={`a${randomString(16)}`}>
+ <InformationCircleIcon className='w-4 h-4 ml-1 text-gray-400' />
+ </Tooltip>}
+ </div>
+ <div className={`text-xs font-normal text-gray-500 group-hover:text-gray-700 ${textStyle?.extra}`}>{type}</div>
+ </div>
+ </div>
+ )
+}
diff --git a/web/app/components/app-sidebar/index.tsx b/web/app/components/app-sidebar/index.tsx
new file mode 100644
index 00000000000..cdafcce78e3
--- /dev/null
+++ b/web/app/components/app-sidebar/index.tsx
@@ -0,0 +1,39 @@
+import React from 'react'
+import type { FC } from 'react'
+import NavLink from './navLink'
+import AppBasic from './basic'
+
+export type IAppDetailNavProps = {
+ iconType?: 'app' | 'dataset'
+ title: string
+ desc: string
+ navigation: Array<{
+ name: string
+ href: string
+ icon: any
+ selectedIcon: any
+ }>
+ extraInfo?: React.ReactNode
+}
+
+const sampleAppIconUrl = 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80'
+
+const AppDetailNav: FC<IAppDetailNavProps> = ({ title, desc, navigation, extraInfo, iconType = 'app' }) => {
+ return (
+ <div className="flex flex-col w-56 overflow-y-auto bg-white border-r border-gray-200 shrink-0">
+ <div className="flex flex-shrink-0 p-4">
+ <AppBasic iconType={iconType} iconUrl={sampleAppIconUrl} name={title} type={desc} />
+ </div>
+ <nav className="flex-1 p-4 space-y-1 bg-white">
+ {navigation.map((item, index) => {
+ return (
+ <NavLink key={index} iconMap={{ selected: item.selectedIcon, normal: item.icon }} name={item.name} href={item.href} />
+ )
+ })}
+ {extraInfo ?? null}
+ </nav>
+ </div>
+ )
+}
+
+export default React.memo(AppDetailNav)
diff --git a/web/app/components/app-sidebar/navLink.tsx b/web/app/components/app-sidebar/navLink.tsx
new file mode 100644
index 00000000000..20aa2241bdf
--- /dev/null
+++ b/web/app/components/app-sidebar/navLink.tsx
@@ -0,0 +1,39 @@
+'use client'
+import { useSelectedLayoutSegment } from 'next/navigation'
+import classNames from 'classnames'
+import Link from 'next/link'
+
+export default function NavLink({
+ name,
+ href,
+ iconMap,
+}: {
+ name: string
+ href: string
+ iconMap: { selected: any; normal: any }
+}) {
+ const segment = useSelectedLayoutSegment()
+ const isActive = href.toLowerCase().split('/')?.pop() === segment?.toLowerCase()
+ const NavIcon = isActive ? iconMap.selected : iconMap.normal
+
+ return (
+ <Link
+ prefetch
+ key={name}
+ href={href}
+ className={classNames(
+ isActive ? 'bg-primary-50 text-primary-600 font-semibold' : 'text-gray-700 hover:bg-gray-100 hover:text-gray-700',
+ 'group flex items-center rounded-md px-2 py-2 text-sm font-normal',
+ )}
+ >
+ <NavIcon
+ className={classNames(
+ 'mr-2 h-4 w-4 flex-shrink-0',
+ isActive ? 'text-primary-600' : 'text-gray-700',
+ )}
+ aria-hidden="true"
+ />
+ {name}
+ </Link>
+ )
+}
diff --git a/web/app/components/app-sidebar/style.module.css b/web/app/components/app-sidebar/style.module.css
new file mode 100644
index 00000000000..77570ef376b
--- /dev/null
+++ b/web/app/components/app-sidebar/style.module.css
@@ -0,0 +1,3 @@
+.sidebar {
+ border-right: 1px solid #F3F4F6;
+}
\ No newline at end of file
diff --git a/web/app/components/app/chat/icons/answer.svg b/web/app/components/app/chat/icons/answer.svg
new file mode 100644
index 00000000000..e9830393061
--- /dev/null
+++ b/web/app/components/app/chat/icons/answer.svg
@@ -0,0 +1,3 @@
+<svg width="8" height="12" viewBox="0 0 8 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M1.03647 1.5547C0.59343 0.890144 1.06982 0 1.86852 0H8V12L1.03647 1.5547Z" fill="#F3F4F6"/>
+</svg>
diff --git a/web/app/components/app/chat/icons/default-avatar.jpg b/web/app/components/app/chat/icons/default-avatar.jpg
new file mode 100644
index 00000000000..396d5dd291b
Binary files /dev/null and b/web/app/components/app/chat/icons/default-avatar.jpg differ
diff --git a/web/app/components/app/chat/icons/edit.svg b/web/app/components/app/chat/icons/edit.svg
new file mode 100644
index 00000000000..a922970b6ce
--- /dev/null
+++ b/web/app/components/app/chat/icons/edit.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M14 11.9998L13.3332 12.7292C12.9796 13.1159 12.5001 13.3332 12.0001 13.3332C11.5001 13.3332 11.0205 13.1159 10.6669 12.7292C10.3128 12.3432 9.83332 12.1265 9.33345 12.1265C8.83359 12.1265 8.35409 12.3432 7.99998 12.7292M2 13.3332H3.11636C3.44248 13.3332 3.60554 13.3332 3.75899 13.2963C3.89504 13.2637 4.0251 13.2098 4.1444 13.1367C4.27895 13.0542 4.39425 12.9389 4.62486 12.7083L13 4.33316C13.5523 3.78087 13.5523 2.88544 13 2.33316C12.4477 1.78087 11.5523 1.78087 11 2.33316L2.62484 10.7083C2.39424 10.9389 2.27894 11.0542 2.19648 11.1888C2.12338 11.3081 2.0695 11.4381 2.03684 11.5742C2 11.7276 2 11.8907 2 12.2168V13.3332Z" stroke="#6B7280" strokeLinecap="round" strokeLinejoin="round" />
+</svg>
\ No newline at end of file
diff --git a/web/app/components/app/chat/icons/question.svg b/web/app/components/app/chat/icons/question.svg
new file mode 100644
index 00000000000..39904f52a50
--- /dev/null
+++ b/web/app/components/app/chat/icons/question.svg
@@ -0,0 +1,3 @@
+<svg width="8" height="12" viewBox="0 0 8 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.96353 1.5547C7.40657 0.890144 6.93018 0 6.13148 0H0V12L6.96353 1.5547Z" fill="#E1EFFE"/>
+</svg>
diff --git a/web/app/components/app/chat/icons/robot.svg b/web/app/components/app/chat/icons/robot.svg
new file mode 100644
index 00000000000..a50c8886d1d
--- /dev/null
+++ b/web/app/components/app/chat/icons/robot.svg
@@ -0,0 +1,10 @@
+<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+<rect width="40" height="40" rx="20" fill="#D5F5F6"/>
+<path d="M11 28.76H29V10.76H11V28.76Z" fill="url(#pattern0)"/>
+<defs>
+<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
+<use xlink:href="#image0_135_973" transform="scale(0.00625)"/>
+</pattern>
+<image id="image0_135_973" width="160" height="160" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAYAAACLz2ctAABqnElEQVR4nO39d7xkx3nfCX+rTujcN6fJg8EAGAwIEJEACRJiDqKYJYqUlSjZsiR7bVm2LMm7tvfVem0v9ZHXkkxJq8gokRQlkWIQM0iARAaIHAZhcrh3bux8zqmq9486qfveO9MDDgmSwjOfntt9YoVfPameekoYY3ienqfniuRzXYDn6R83ucNe+M/f+7vn/HCl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0TvSfL0bXJ88Z0CSD5LEUBRChRAFAFIKz5WhEKJTdJ3lQKnGSKm4pIRYrNVrx7TmsUqtcsCFp1q9cPGCvXvaTz19kCiKiKIIpRRmw71Pv7v0PQHAPBlj4jRqRgtYLBQLi5FS95aEoF6tTumgV19qtkdEx6lMjI9PVgr++OGl1enW0pIpSMl1l+0rHFltjJ9YXvG1ihJ/XKpJ2Zesty3MwI/+RXE53TDv2Rm8N40kESmg+q7JqXTCZIuGUubYt3rNZI+UDvVyKXzR3t3LTx853n344BFDrSZ3bJlpSGPmXc89feLEqcbM3HQjDMLVibmZ06cXVwK/WMRVirVOjyiK0PGeH99LNPRMyPP0PH0n6PzEVT9Pz9OzpOcB+Dw9p/Q8AJ+n55SeB+Dz9JzS8wB8np5Teh6Az9NzSs8D8Hl6Tul5AD5Pzyn9/wEFaPppgwjxcAAAAABJRU5ErkJggg=="/>
+</defs>
+</svg>
diff --git a/web/app/components/app/chat/icons/send-active.svg b/web/app/components/app/chat/icons/send-active.svg
new file mode 100644
index 00000000000..03d4734bc6a
--- /dev/null
+++ b/web/app/components/app/chat/icons/send-active.svg
@@ -0,0 +1,3 @@
+<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M23.447 16.8939C23.6128 16.8108 23.7523 16.6832 23.8498 16.5253C23.9473 16.3674 23.9989 16.1855 23.9989 15.9999C23.9989 15.8144 23.9473 15.6325 23.8498 15.4746C23.7523 15.3167 23.6128 15.1891 23.447 15.1059L9.44697 8.10595C9.27338 8.01909 9.07827 7.98463 8.88543 8.00677C8.69259 8.02891 8.51036 8.1067 8.36098 8.23064C8.2116 8.35458 8.10151 8.51931 8.04415 8.70475C7.9868 8.89019 7.98465 9.08831 8.03797 9.27495L9.46697 14.2749C9.52674 14.4839 9.65297 14.6677 9.82655 14.7985C10.0001 14.9294 10.2116 15.0001 10.429 14.9999H15C15.2652 14.9999 15.5195 15.1053 15.7071 15.2928C15.8946 15.4804 16 15.7347 16 15.9999C16 16.2652 15.8946 16.5195 15.7071 16.7071C15.5195 16.8946 15.2652 16.9999 15 16.9999H10.429C10.2116 16.9998 10.0001 17.0705 9.82655 17.2013C9.65297 17.3322 9.52674 17.516 9.46697 17.7249L8.03897 22.7249C7.98554 22.9115 7.98756 23.1096 8.04478 23.2951C8.10201 23.4805 8.21195 23.6453 8.36122 23.7693C8.51049 23.8934 8.69263 23.9713 8.88542 23.9936C9.07821 24.0159 9.27332 23.9816 9.44697 23.8949L23.447 16.8949V16.8939Z" fill="#1C64F2"/>
+</svg>
diff --git a/web/app/components/app/chat/icons/send.svg b/web/app/components/app/chat/icons/send.svg
new file mode 100644
index 00000000000..e977ef95bb0
--- /dev/null
+++ b/web/app/components/app/chat/icons/send.svg
@@ -0,0 +1,3 @@
+<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M23.447 16.8939C23.6128 16.8108 23.7523 16.6832 23.8498 16.5253C23.9473 16.3674 23.9989 16.1855 23.9989 15.9999C23.9989 15.8144 23.9473 15.6325 23.8498 15.4746C23.7523 15.3167 23.6128 15.1891 23.447 15.1059L9.44697 8.10595C9.27338 8.01909 9.07827 7.98463 8.88543 8.00677C8.69259 8.02891 8.51036 8.1067 8.36098 8.23064C8.2116 8.35458 8.10151 8.51931 8.04415 8.70475C7.9868 8.89019 7.98465 9.08831 8.03797 9.27495L9.46697 14.2749C9.52674 14.4839 9.65297 14.6677 9.82655 14.7985C10.0001 14.9294 10.2116 15.0001 10.429 14.9999H15C15.2652 14.9999 15.5195 15.1053 15.7071 15.2928C15.8946 15.4804 16 15.7347 16 15.9999C16 16.2652 15.8946 16.5195 15.7071 16.7071C15.5195 16.8946 15.2652 16.9999 15 16.9999H10.429C10.2116 16.9998 10.0001 17.0705 9.82655 17.2013C9.65297 17.3322 9.52674 17.516 9.46697 17.7249L8.03897 22.7249C7.98554 22.9115 7.98756 23.1096 8.04478 23.2951C8.10201 23.4805 8.21195 23.6453 8.36122 23.7693C8.51049 23.8934 8.69263 23.9713 8.88542 23.9936C9.07821 24.0159 9.27332 23.9816 9.44697 23.8949L23.447 16.8949V16.8939Z" fill="#D1D5DB"/>
+</svg>
diff --git a/web/app/components/app/chat/icons/typing.svg b/web/app/components/app/chat/icons/typing.svg
new file mode 100644
index 00000000000..7b28f0ef78f
--- /dev/null
+++ b/web/app/components/app/chat/icons/typing.svg
@@ -0,0 +1,19 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_2358_1380)">
+<rect x="2" y="1" width="16" height="16" rx="8" fill="white"/>
+<path opacity="0.7" d="M13.5 9H13.505M14 9C14 9.13261 13.9473 9.25979 13.8536 9.35355C13.7598 9.44732 13.6326 9.5 13.5 9.5C13.3674 9.5 13.2402 9.44732 13.1464 9.35355C13.0527 9.25979 13 9.13261 13 9C13 8.86739 13.0527 8.74021 13.1464 8.64645C13.2402 8.55268 13.3674 8.5 13.5 8.5C13.6326 8.5 13.7598 8.55268 13.8536 8.64645C13.9473 8.74021 14 8.86739 14 9Z" stroke="#155EEF" stroke-linecap="round" stroke-linejoin="round"/>
+<path opacity="0.6" d="M10 9H10.005M10.5 9C10.5 9.13261 10.4473 9.25979 10.3536 9.35355C10.2598 9.44732 10.1326 9.5 10 9.5C9.86739 9.5 9.74021 9.44732 9.64645 9.35355C9.55268 9.25979 9.5 9.13261 9.5 9C9.5 8.86739 9.55268 8.74021 9.64645 8.64645C9.74021 8.55268 9.86739 8.5 10 8.5C10.1326 8.5 10.2598 8.55268 10.3536 8.64645C10.4473 8.74021 10.5 8.86739 10.5 9Z" stroke="#155EEF" stroke-linecap="round" stroke-linejoin="round"/>
+<path opacity="0.3" d="M6.5 9H6.505M7 9C7 9.13261 6.94732 9.25979 6.85355 9.35355C6.75979 9.44732 6.63261 9.5 6.5 9.5C6.36739 9.5 6.24021 9.44732 6.14645 9.35355C6.05268 9.25979 6 9.13261 6 9C6 8.86739 6.05268 8.74021 6.14645 8.64645C6.24021 8.55268 6.36739 8.5 6.5 8.5C6.63261 8.5 6.75979 8.55268 6.85355 8.64645C6.94732 8.74021 7 8.86739 7 9Z" stroke="#155EEF" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<filter id="filter0_d_2358_1380" x="0" y="0" width="20" height="20" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_2358_1380"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_2358_1380" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/app/chat/icons/user.svg b/web/app/components/app/chat/icons/user.svg
new file mode 100644
index 00000000000..556aaf7bfb3
--- /dev/null
+++ b/web/app/components/app/chat/icons/user.svg
@@ -0,0 +1,10 @@
+<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+<rect width="40" height="40" rx="20" fill="white"/>
+<rect width="40" height="40" rx="20" fill="url(#pattern0)"/>
+<defs>
+<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
+<use xlink:href="#image0_84_1144" transform="scale(0.00238095)"/>
+</pattern>
+<image id="image0_84_1144" width="420" height="420" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaQAAAGkCAIAAADxLsZiAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNv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ZLWnO+H6Ee/0ub177n/oqssvCTeQr9fY7h78GbT8kQQysyhjtuGkOlM3W+YMTfC+oKDvl1w3LDGlGzyCPE5HqebUGilv077n9DF+mSSsYz0zm9Ou3vKYdWwLWKY93vgAGBOXMdbmyF07YeruStxWHQgHmEEiA7QM7ZsCqyg7wod2o4HZREmmsW3vNcZ08Sv2DzwYUtjznGL7nKpSmcqKsh1xS9ZlAspFXLa72MDudTfdstYU7Fx/d+ICDdm2pEH00Jd2wp18/OhGc9PM51nOqGLL13TP6CnFMgXhVBVDidTuqKoRkRF3qFe5xI83QSFPtLYbNxySPtSy+lMYE+SFXbGlbHLIJQchG7FcCpwvfK50yO2ryolfEhUdGP5Zf1FtwYs/Is/Je1J0HB1aFltL+b3g9ye8pUEruC9+zx/KBmmdzaPWXs52t7XwDk4ITnnXo9zezz97lwza60ZdYRltFpePPHL2zvse7gawi9ZEJ3Mi73HPLdvY96picBdyo2+8+okD2H1FPPzIdVNiRnfCasU6C/Jq7+976Oy58wdPuPzoKLYRU3AXfybtm9dMU/veYpMOfNJiS2XBvkpccsbj+VMBdoX5NBbXKmcOaWiLe7MkpNFBEkG6uCx/Cnjj5lCXGKr0eJmkgOg4iNOu9A75MGpuK+uJOsbE5bKOyFIJNy/H35dMwLWTpAqpWJOwlXQFgSkSQ83muKvZRJKq+joMl29rZrjx4jPJrtmD6/ny7vsffuTsfk/3VZbtPKB3KwoQ+XfxslTv+MBt3/jyixPs/l8BBgA1CUB+vqceNQAAAABJRU5ErkJggg=="/>
+</defs>
+</svg>
diff --git a/web/app/components/app/chat/index.tsx b/web/app/components/app/chat/index.tsx
new file mode 100644
index 00000000000..7b512c57d43
--- /dev/null
+++ b/web/app/components/app/chat/index.tsx
@@ -0,0 +1,559 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useRef, useState } from 'react'
+import { useContext } from 'use-context-selector'
+import cn from 'classnames'
+import { HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
+import { UserCircleIcon } from '@heroicons/react/24/solid'
+import { useTranslation } from 'react-i18next'
+import { randomString } from '../../app-sidebar/basic'
+import s from './style.module.css'
+import Tooltip from '@/app/components/base/tooltip'
+import { ToastContext } from '@/app/components/base/toast'
+import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
+import Button from '@/app/components/base/button'
+import type { Annotation, MessageRating } from '@/models/log'
+import AppContext from '@/context/app-context'
+import { Markdown } from '@/app/components/base/markdown'
+import LoadingAnim from './loading-anim'
+
+const stopIcon = (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M7.00004 0.583313C3.45621 0.583313 0.583374 3.45615 0.583374 6.99998C0.583374 10.5438 3.45621 13.4166 7.00004 13.4166C10.5439 13.4166 13.4167 10.5438 13.4167 6.99998C13.4167 3.45615 10.5439 0.583313 7.00004 0.583313ZM4.73029 4.98515C4.66671 5.10993 4.66671 5.27328 4.66671 5.59998V8.39998C4.66671 8.72668 4.66671 8.89003 4.73029 9.01481C4.78621 9.12457 4.87545 9.21381 4.98521 9.26973C5.10999 9.33331 5.27334 9.33331 5.60004 9.33331H8.40004C8.72674 9.33331 8.89009 9.33331 9.01487 9.26973C9.12463 9.21381 9.21387 9.12457 9.2698 9.01481C9.33337 8.89003 9.33337 8.72668 9.33337 8.39998V5.59998C9.33337 5.27328 9.33337 5.10993 9.2698 4.98515C9.21387 4.87539 9.12463 4.78615 9.01487 4.73023C8.89009 4.66665 8.72674 4.66665 8.40004 4.66665H5.60004C5.27334 4.66665 5.10999 4.66665 4.98521 4.73023C4.87545 4.78615 4.78621 4.87539 4.73029 4.98515Z" fill="#667085" />
+ </svg>
+)
+export type Feedbacktype = {
+ rating: MessageRating
+ content?: string | null
+}
+
+export type FeedbackFunc = (messageId: string, feedback: Feedbacktype) => Promise<any>
+export type SubmitAnnotationFunc = (messageId: string, content: string) => Promise<any>
+
+export type DisplayScene = 'web' | 'console'
+
+export type IChatProps = {
+ chatList: IChatItem[]
+ /**
+ * Whether to display the editing area and rating status
+ */
+ feedbackDisabled?: boolean
+ /**
+ * Whether to display the input area
+ */
+ isHideFeedbackEdit?: boolean
+ isHideSendInput?: boolean
+ onFeedback?: FeedbackFunc
+ onSubmitAnnotation?: SubmitAnnotationFunc
+ checkCanSend?: () => boolean
+ onSend?: (message: string) => void
+ displayScene?: DisplayScene
+ useCurrentUserAvatar?: boolean
+ isResponsing?: boolean
+ abortResponsing?: () => void
+ controlClearQuery?: number
+ controlFocus?: number
+ isShowSuggestion?: boolean
+ suggestionList?: string[]
+}
+
+export type MessageMore = {
+ time: string
+ tokens: number
+ latency: number | string
+}
+
+export type IChatItem = {
+ id: string
+ content: string
+ /**
+ * Specific message type
+ */
+ isAnswer: boolean
+ /**
+ * The user feedback result of this message
+ */
+ feedback?: Feedbacktype
+ /**
+ * The admin feedback result of this message
+ */
+ adminFeedback?: Feedbacktype
+ /**
+ * Whether to hide the feedback area
+ */
+ feedbackDisabled?: boolean
+ /**
+ * More information about this message
+ */
+ more?: MessageMore
+ annotation?: Annotation
+ useCurrentUserAvatar?: boolean
+ isOpeningStatement?: boolean
+}
+
+const OperationBtn = ({ innerContent, onClick, className }: { innerContent: React.ReactNode; onClick?: () => void; className?: string }) => (
+ <div
+ className={`relative box-border flex items-center justify-center h-7 w-7 p-0.5 rounded-lg bg-white cursor-pointer text-gray-500 hover:text-gray-800 ${className ?? ''}`}
+ style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
+ onClick={onClick && onClick}
+ >
+ {innerContent}
+ </div>
+)
+
+const MoreInfo: FC<{ more: MessageMore; isQuestion: boolean }> = ({ more, isQuestion }) => {
+ const { t } = useTranslation()
+ return (<div className={`mt-1 space-x-2 text-xs text-gray-400 ${isQuestion ? 'mr-2 text-right ' : 'ml-2 text-left float-right'}`}>
+ <span>{`${t('appLog.detail.timeConsuming')} ${more.latency}${t('appLog.detail.second')}`}</span>
+ <span>{`${t('appLog.detail.tokenCost')} ${more.tokens}`}</span>
+ <span>· </span>
+ <span>{more.time} </span>
+ </div>)
+}
+
+const OpeningStatementIcon: FC<{ className?: string }> = ({ className }) => (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M6.25002 1C3.62667 1 1.50002 3.12665 1.50002 5.75C1.50002 6.28 1.58702 6.79071 1.7479 7.26801C1.7762 7.35196 1.79285 7.40164 1.80368 7.43828L1.80722 7.45061L1.80535 7.45452C1.79249 7.48102 1.77339 7.51661 1.73766 7.58274L0.911727 9.11152C0.860537 9.20622 0.807123 9.30503 0.770392 9.39095C0.733879 9.47635 0.674738 9.63304 0.703838 9.81878C0.737949 10.0365 0.866092 10.2282 1.05423 10.343C1.21474 10.4409 1.38213 10.4461 1.475 10.4451C1.56844 10.444 1.68015 10.4324 1.78723 10.4213L4.36472 10.1549C4.406 10.1506 4.42758 10.1484 4.44339 10.1472L4.44542 10.147L4.45161 10.1492C4.47103 10.1562 4.49738 10.1663 4.54285 10.1838C5.07332 10.3882 5.64921 10.5 6.25002 10.5C8.87338 10.5 11 8.37335 11 5.75C11 3.12665 8.87338 1 6.25002 1ZM4.48481 4.29111C5.04844 3.81548 5.7986 3.9552 6.24846 4.47463C6.69831 3.9552 7.43879 3.82048 8.01211 4.29111C8.58544 4.76175 8.6551 5.562 8.21247 6.12453C7.93825 6.47305 7.24997 7.10957 6.76594 7.54348C6.58814 7.70286 6.49924 7.78255 6.39255 7.81466C6.30103 7.84221 6.19589 7.84221 6.10436 7.81466C5.99767 7.78255 5.90878 7.70286 5.73098 7.54348C5.24694 7.10957 4.55867 6.47305 4.28444 6.12453C3.84182 5.562 3.92117 4.76675 4.48481 4.29111Z" fill="#667085" />
+ </svg>
+)
+
+const RatingIcon: FC<{ isLike: boolean }> = ({ isLike }) => {
+ return isLike ? <HandThumbUpIcon className='w-4 h-4' /> : <HandThumbDownIcon className='w-4 h-4' />
+}
+
+const EditIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
+ <path d="M14 11.9998L13.3332 12.7292C12.9796 13.1159 12.5001 13.3332 12.0001 13.3332C11.5001 13.3332 11.0205 13.1159 10.6669 12.7292C10.3128 12.3432 9.83332 12.1265 9.33345 12.1265C8.83359 12.1265 8.35409 12.3432 7.99998 12.7292M2 13.3332H3.11636C3.44248 13.3332 3.60554 13.3332 3.75899 13.2963C3.89504 13.2637 4.0251 13.2098 4.1444 13.1367C4.27895 13.0542 4.39425 12.9389 4.62486 12.7083L13 4.33316C13.5523 3.78087 13.5523 2.88544 13 2.33316C12.4477 1.78087 11.5523 1.78087 11 2.33316L2.62484 10.7083C2.39424 10.9389 2.27894 11.0542 2.19648 11.1888C2.12338 11.3081 2.0695 11.4381 2.03684 11.5742C2 11.7276 2 11.8907 2 12.2168V13.3332Z" stroke="#6B7280" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+}
+
+export const EditIconSolid: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
+ <path fill-rule="evenodd" clipRule="evenodd" d="M10.8374 8.63108C11.0412 8.81739 11.0554 9.13366 10.8691 9.33747L10.369 9.88449C10.0142 10.2725 9.52293 10.5001 9.00011 10.5001C8.47746 10.5001 7.98634 10.2727 7.63157 9.8849C7.45561 9.69325 7.22747 9.59515 7.00014 9.59515C6.77271 9.59515 6.54446 9.69335 6.36846 9.88517C6.18177 10.0886 5.86548 10.1023 5.66201 9.91556C5.45853 9.72888 5.44493 9.41259 5.63161 9.20911C5.98678 8.82201 6.47777 8.59515 7.00014 8.59515C7.52251 8.59515 8.0135 8.82201 8.36867 9.20911L8.36924 9.20974C8.54486 9.4018 8.77291 9.50012 9.00011 9.50012C9.2273 9.50012 9.45533 9.40182 9.63095 9.20979L10.131 8.66276C10.3173 8.45895 10.6336 8.44476 10.8374 8.63108Z" fill="#6B7280" />
+ <path fill-rule="evenodd" clipRule="evenodd" d="M7.89651 1.39656C8.50599 0.787085 9.49414 0.787084 10.1036 1.39656C10.7131 2.00604 10.7131 2.99419 10.1036 3.60367L3.82225 9.88504C3.81235 9.89494 3.80254 9.90476 3.79281 9.91451C3.64909 10.0585 3.52237 10.1855 3.3696 10.2791C3.23539 10.3613 3.08907 10.4219 2.93602 10.4587C2.7618 10.5005 2.58242 10.5003 2.37897 10.5001C2.3652 10.5001 2.35132 10.5001 2.33732 10.5001H1.50005C1.22391 10.5001 1.00005 10.2763 1.00005 10.0001V9.16286C1.00005 9.14886 1.00004 9.13497 1.00003 9.1212C0.999836 8.91776 0.999669 8.73838 1.0415 8.56416C1.07824 8.4111 1.13885 8.26479 1.22109 8.13058C1.31471 7.97781 1.44166 7.85109 1.58566 7.70736C1.5954 7.69764 1.60523 7.68783 1.61513 7.67793L7.89651 1.39656Z" fill="#6B7280" />
+ </svg>
+}
+
+const TryToAskIcon = (
+ <svg width="11" height="10" viewBox="0 0 11 10" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5.88889 0.683718C5.827 0.522805 5.67241 0.416626 5.5 0.416626C5.3276 0.416626 5.173 0.522805 5.11111 0.683718L4.27279 2.86334C4.14762 3.18877 4.10829 3.28255 4.05449 3.35821C4.00051 3.43413 3.93418 3.50047 3.85826 3.55445C3.78259 3.60825 3.68881 3.64758 3.36338 3.77275L1.18376 4.61106C1.02285 4.67295 0.916668 4.82755 0.916668 4.99996C0.916668 5.17236 1.02285 5.32696 1.18376 5.38885L3.36338 6.22717C3.68881 6.35234 3.78259 6.39167 3.85826 6.44547C3.93418 6.49945 4.00051 6.56578 4.05449 6.6417C4.10829 6.71737 4.14762 6.81115 4.27279 7.13658L5.11111 9.3162C5.173 9.47711 5.3276 9.58329 5.5 9.58329C5.67241 9.58329 5.82701 9.47711 5.8889 9.3162L6.72721 7.13658C6.85238 6.81115 6.89171 6.71737 6.94551 6.6417C6.99949 6.56578 7.06583 6.49945 7.14175 6.44547C7.21741 6.39167 7.31119 6.35234 7.63662 6.22717L9.81624 5.38885C9.97715 5.32696 10.0833 5.17236 10.0833 4.99996C10.0833 4.82755 9.97715 4.67295 9.81624 4.61106L7.63662 3.77275C7.31119 3.64758 7.21741 3.60825 7.14175 3.55445C7.06583 3.50047 6.99949 3.43413 6.94551 3.35821C6.89171 3.28255 6.85238 3.18877 6.72721 2.86334L5.88889 0.683718Z" fill="#667085" />
+ </svg>
+)
+
+const Divider: FC<{ name: string }> = ({ name }) => {
+ const { t } = useTranslation()
+ return <div className='flex items-center my-2'>
+ <span className='text-xs text-gray-500 inline-flex items-center mr-2'>
+ <EditIconSolid className='mr-1' />{t('appLog.detail.annotationTip', { user: name })}
+ </span>
+ <div className='h-[1px] bg-gray-200 flex-1'></div>
+ </div>
+}
+
+const IconWrapper: FC<{ children: React.ReactNode | string }> = ({ children }) => {
+ return <div className={'rounded-lg h-6 w-6 flex items-center justify-center hover:bg-gray-100'}>
+ {children}
+ </div>
+}
+
+type IAnswerProps = {
+ item: IChatItem
+ feedbackDisabled: boolean
+ isHideFeedbackEdit: boolean
+ onFeedback?: FeedbackFunc
+ onSubmitAnnotation?: SubmitAnnotationFunc
+ displayScene: DisplayScene
+ isResponsing?: boolean
+}
+
+// The component needs to maintain its own state to control whether to display input component
+const Answer: FC<IAnswerProps> = ({ item, feedbackDisabled = false, isHideFeedbackEdit = false, onFeedback, onSubmitAnnotation, displayScene = 'web', isResponsing }) => {
+ const { id, content, more, feedback, adminFeedback, annotation: initAnnotation } = item
+ const [showEdit, setShowEdit] = useState(false)
+ const [loading, setLoading] = useState(false)
+ const [annotation, setAnnotation] = useState<Annotation | undefined | null>(initAnnotation)
+ const [inputValue, setInputValue] = useState<string>(initAnnotation?.content ?? '')
+ const [localAdminFeedback, setLocalAdminFeedback] = useState<Feedbacktype | undefined | null>(adminFeedback)
+ const { userProfile } = useContext(AppContext)
+ const { t } = useTranslation()
+
+ /**
+ * Render feedback results (distinguish between users and administrators)
+ * User reviews cannot be cancelled in Console
+ * @param rating feedback result
+ * @param isUserFeedback Whether it is user's feedback
+ * @param isWebScene Whether it is web scene
+ * @returns comp
+ */
+ const renderFeedbackRating = (rating: MessageRating | undefined, isUserFeedback = true, isWebScene = true) => {
+ if (!rating)
+ return null
+
+ const isLike = rating === 'like'
+ const ratingIconClassname = isLike ? 'text-primary-600 bg-primary-100 hover:bg-primary-200' : 'text-red-600 bg-red-100 hover:bg-red-200'
+ const UserSymbol = <UserCircleIcon className='absolute top-[-2px] left-[18px] w-3 h-3 rounded-lg text-gray-400 bg-white' />
+ // The tooltip is always displayed, but the content is different for different scenarios.
+ return (
+ <Tooltip
+ selector={`user-feedback-${randomString(16)}`}
+ content={(isWebScene || (!isUserFeedback && !isWebScene)) ? isLike ? '取消赞同' : '取消反对' : (!isWebScene && isUserFeedback) ? `用户表示${isLike ? '赞同' : '反对'}` : ''}
+ >
+ <div
+ className={`relative box-border flex items-center justify-center h-7 w-7 p-0.5 rounded-lg bg-white cursor-pointer text-gray-500 hover:text-gray-800 ${(!isWebScene && isUserFeedback) ? '!cursor-default' : ''}`}
+ style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
+ {...((isWebScene || (!isUserFeedback && !isWebScene))
+ ? {
+ onClick: async () => {
+ const res = await onFeedback?.(id, { rating: null })
+ if (res && !isWebScene)
+ setLocalAdminFeedback({ rating: null })
+ },
+ }
+ : {})}
+ >
+ <div className={`${ratingIconClassname} rounded-lg h-6 w-6 flex items-center justify-center`}>
+ <RatingIcon isLike={isLike} />
+ </div>
+ {!isWebScene && isUserFeedback && UserSymbol}
+ </div>
+ </Tooltip>
+ )
+ }
+
+ /**
+ * Different scenarios have different operation items.
+ * @param isWebScene Whether it is web scene
+ * @returns comp
+ */
+ const renderItemOperation = (isWebScene = true) => {
+ const userOperation = () => {
+ return feedback?.rating
+ ? null
+ : <div className='flex gap-1'>
+ <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
+ {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'like' }) })}
+ </Tooltip>
+ <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
+ {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'dislike' }) })}
+ </Tooltip>
+ </div>
+ }
+
+ const adminOperation = () => {
+ return <div className='flex gap-1'>
+ <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.addAnnotation') as string}>
+ {OperationBtn({
+ innerContent: <IconWrapper><EditIcon className='hover:text-gray-800' /></IconWrapper>,
+ onClick: () => setShowEdit(true),
+ })}
+ </Tooltip>
+ {!localAdminFeedback?.rating && <>
+ <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
+ {OperationBtn({
+ innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>,
+ onClick: async () => {
+ const res = await onFeedback?.(id, { rating: 'like' })
+ if (res)
+ setLocalAdminFeedback({ rating: 'like' })
+ },
+ })}
+ </Tooltip>
+ <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
+ {OperationBtn({
+ innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>,
+ onClick: async () => {
+ const res = await onFeedback?.(id, { rating: 'dislike' })
+ if (res)
+ setLocalAdminFeedback({ rating: 'dislike' })
+ },
+ })}
+ </Tooltip>
+ </>}
+ </div>
+ }
+
+ return (
+ <div className={`${s.itemOperation} flex gap-2`}>
+ {isWebScene ? userOperation() : adminOperation()}
+ </div>
+ )
+ }
+
+ return (
+ <div key={id}>
+ <div className='flex items-start'>
+ <div className={`${s.answerIcon} w-10 h-10 shrink-0`}>
+ {isResponsing &&
+ <div className={s.typeingIcon}>
+ <LoadingAnim type='avatar' />
+ </div>
+ }
+ </div>
+ <div className={`${s.answerWrap} ${showEdit ? 'w-full' : ''}`}>
+ <div className={`${s.answer} relative text-sm text-gray-900`}>
+ <div className={'ml-2 py-3 px-4 bg-gray-100 rounded-tr-2xl rounded-b-2xl'}>
+ {item.isOpeningStatement && (
+ <div className='flex items-center mb-1 gap-1'>
+ <OpeningStatementIcon />
+ <div className='text-xs text-gray-500'>{t('appDebug.openingStatement.title')}</div>
+ </div>
+ )}
+ {(isResponsing && !content) ? (
+ <div className='flex items-center justify-center w-6 h-5'>
+ <LoadingAnim type='text' />
+ </div>
+ ) : (
+ <Markdown content={content} />
+ )}
+ {!showEdit
+ ? (annotation?.content
+ && <>
+ <Divider name={annotation?.account?.name || userProfile?.name} />
+ {annotation.content}
+ </>)
+ : <>
+ <Divider name={annotation?.account?.name || userProfile?.name} />
+ <AutoHeightTextarea
+ placeholder={t('appLog.detail.operation.annotationPlaceholder') as string}
+ value={inputValue}
+ onChange={e => setInputValue(e.target.value)}
+ minHeight={58}
+ className={`${cn(s.textArea)} !py-2 resize-none block w-full !px-3 bg-gray-50 border border-gray-200 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm text-gray-700 tracking-[0.2px]`}
+ />
+ <div className="mt-2 flex flex-row">
+ <Button
+ type='primary'
+ className='mr-2'
+ loading={loading}
+ onClick={async () => {
+ if (!inputValue)
+ return
+ setLoading(true)
+ const res = await onSubmitAnnotation?.(id, inputValue)
+ if (res)
+ setAnnotation({ ...annotation, content: inputValue } as any)
+ setLoading(false)
+ setShowEdit(false)
+ }}>{t('common.operation.confirm')}</Button>
+ <Button
+ onClick={() => {
+ setInputValue(annotation?.content ?? '')
+ setShowEdit(false)
+ }}>{t('common.operation.cancel')}</Button>
+ </div>
+ </>
+ }
+ </div>
+ <div className='absolute top-[-14px] right-[-14px] flex flex-row justify-end gap-1'>
+ {!feedbackDisabled && !item.feedbackDisabled && renderItemOperation(displayScene !== 'console')}
+ {/* Admin feedback is displayed only in the background. */}
+ {!feedbackDisabled && renderFeedbackRating(localAdminFeedback?.rating, false, false)}
+ {/* User feedback must be displayed */}
+ {!feedbackDisabled && renderFeedbackRating(feedback?.rating, !isHideFeedbackEdit, displayScene !== 'console')}
+ </div>
+ </div>
+ {more && <MoreInfo more={more} isQuestion={false} />}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+type IQuestionProps = Pick<IChatItem, 'id' | 'content' | 'more' | 'useCurrentUserAvatar'>
+
+const Question: FC<IQuestionProps> = ({ id, content, more, useCurrentUserAvatar }) => {
+ const { userProfile } = useContext(AppContext)
+ const userName = userProfile?.name
+ return (
+ <div className='flex items-start justify-end' key={id}>
+ <div>
+ <div className={`${s.question} relative text-sm text-gray-900`}>
+ <div
+ className={'mr-2 py-3 px-4 bg-blue-500 rounded-tl-2xl rounded-b-2xl'}
+ >
+ <Markdown content={content} />
+ </div>
+ </div>
+ {more && <MoreInfo more={more} isQuestion={true} />}
+ </div>
+ {useCurrentUserAvatar ? (
+ <div className='w-10 h-10 shrink-0 leading-10 text-center mr-2 rounded-full bg-primary-600 text-white'>
+ {userName?.[0].toLocaleUpperCase()}
+ </div>
+ ) : (
+ <div className={`${s.questionIcon} w-10 h-10 shrink-0 `}></div>
+ )}
+ </div>
+ )
+}
+
+const Chat: FC<IChatProps> = ({
+ chatList,
+ feedbackDisabled = false,
+ isHideFeedbackEdit = false,
+ isHideSendInput = false,
+ onFeedback,
+ onSubmitAnnotation,
+ checkCanSend,
+ onSend = () => { },
+ displayScene,
+ useCurrentUserAvatar,
+ isResponsing,
+ abortResponsing,
+ controlClearQuery,
+ controlFocus,
+ isShowSuggestion,
+ suggestionList
+}) => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+ const isUseInputMethod = useRef(false)
+
+ const [query, setQuery] = React.useState('')
+ const handleContentChange = (e: any) => {
+ const value = e.target.value
+ setQuery(value)
+ }
+
+ const logError = (message: string) => {
+ notify({ type: 'error', message, duration: 3000 })
+ }
+
+ const valid = () => {
+ if (!query || query.trim() === '') {
+ logError('Message cannot be empty')
+ return false
+ }
+ return true
+ }
+
+ useEffect(() => {
+ if (controlClearQuery) {
+ setQuery('')
+ }
+ }, [controlClearQuery])
+
+ const handleSend = () => {
+ if (!valid() || (checkCanSend && !checkCanSend()))
+ return
+ onSend(query)
+ if (!isResponsing) {
+ setQuery('')
+ }
+ }
+
+ const handleKeyUp = (e: any) => {
+ if (e.code === 'Enter') {
+ e.preventDefault()
+ // prevent send message when using input method enter
+ if (!e.shiftKey && !isUseInputMethod.current) {
+ handleSend()
+ }
+ }
+ }
+
+ const haneleKeyDown = (e: any) => {
+ isUseInputMethod.current = e.nativeEvent.isComposing
+ if (e.code === 'Enter' && !e.shiftKey) {
+ setQuery(query.replace(/\n$/, ''))
+ e.preventDefault()
+ }
+ }
+
+ return (
+ <div className={cn(!feedbackDisabled && 'px-3.5', 'h-full')}>
+ {/* Chat List */}
+ <div className="h-full space-y-[30px]">
+ {chatList.map((item) => {
+ if (item.isAnswer) {
+ const isLast = item.id === chatList[chatList.length - 1].id
+ return <Answer
+ key={item.id}
+ item={item}
+ feedbackDisabled={feedbackDisabled}
+ isHideFeedbackEdit={isHideFeedbackEdit}
+ onFeedback={onFeedback}
+ onSubmitAnnotation={onSubmitAnnotation}
+ displayScene={displayScene ?? 'web'}
+ isResponsing={isResponsing && isLast}
+ />
+ }
+ return <Question key={item.id} id={item.id} content={item.content} more={item.more} useCurrentUserAvatar={useCurrentUserAvatar} />
+ })}
+ </div>
+ {
+ !isHideSendInput && (
+ <div className={cn(!feedbackDisabled && '!left-3.5 !right-3.5', 'absolute z-10 bottom-0 left-0 right-0')}>
+ {isResponsing && (
+ <div className='flex justify-center mb-4'>
+ <Button className='flex items-center space-x-1 bg-white' onClick={() => abortResponsing?.()}>
+ {stopIcon}
+ <span className='text-xs text-gray-500 font-normal'>{t('appDebug.operation.stopResponding')}</span>
+ </Button>
+ </div>
+ )}
+ {
+ isShowSuggestion && (
+ <div className='pt-2 mb-2 '>
+ <div className='flex items-center justify-center mb-2.5'>
+ <div className='grow h-[1px]'
+ style={{
+ background: 'linear-gradient(270deg, #F3F4F6 0%, rgba(243, 244, 246, 0) 100%)'
+ }}></div>
+ <div className='shrink-0 flex items-center px-3 space-x-1'>
+ {TryToAskIcon}
+ <span className='text-xs text-gray-500 font-medium'>{t('appDebug.feature.suggestedQuestionsAfterAnswer.tryToAsk')}</span>
+ </div>
+ <div className='grow h-[1px]'
+ style={{
+ background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, #F3F4F6 100%)'
+ }}></div>
+ </div>
+ <div className='flex justify-center overflow-x-scroll pb-2'>
+ {suggestionList?.map((item, index) => (
+ <div className='shrink-0 flex justify-center mr-2'>
+ <Button
+ key={index}
+ onClick={() => setQuery(item)}
+ >
+ <span className='text-primary-600 text-xs font-medium'>{item}</span>
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>)
+ }
+ <div className="relative">
+ <AutoHeightTextarea
+ value={query}
+ onChange={handleContentChange}
+ onKeyUp={handleKeyUp}
+ onKeyDown={haneleKeyDown}
+ minHeight={48}
+ autoFocus
+ controlFocus={controlFocus}
+ className={`${cn(s.textArea)} resize-none block w-full pl-3 bg-gray-50 border border-gray-200 rounded-md focus:outline-none sm:text-sm text-gray-700`}
+ />
+ <div className="absolute top-0 right-2 flex items-center h-[48px]">
+ <div className={`${s.count} mr-4 h-5 leading-5 text-sm bg-gray-50 text-gray-500`}>{query.trim().length}</div>
+ <Tooltip
+ selector='send-tip'
+ htmlContent={
+ <div>
+ <div>{t('common.operation.send')} Enter</div>
+ <div>{t('common.operation.lineBreak')} Shift Enter</div>
+ </div>
+ }
+ >
+ <div className={`${s.sendBtn} w-8 h-8 cursor-pointer rounded-md`} onClick={handleSend}></div>
+ </Tooltip>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ </div>
+ )
+}
+export default React.memo(Chat)
diff --git a/web/app/components/app/chat/loading-anim/index.tsx b/web/app/components/app/chat/loading-anim/index.tsx
new file mode 100644
index 00000000000..0cd4111b39a
--- /dev/null
+++ b/web/app/components/app/chat/loading-anim/index.tsx
@@ -0,0 +1,16 @@
+'use client'
+import React, { FC } from 'react'
+import s from './style.module.css'
+
+export interface ILoaidingAnimProps {
+ type: 'text' | 'avatar'
+}
+
+const LoaidingAnim: FC<ILoaidingAnimProps> = ({
+ type
+}) => {
+ return (
+ <div className={`${s['dot-flashing']} ${s[type]}`}></div>
+ )
+}
+export default React.memo(LoaidingAnim)
diff --git a/web/app/components/app/chat/loading-anim/style.module.css b/web/app/components/app/chat/loading-anim/style.module.css
new file mode 100644
index 00000000000..5a764db13c0
--- /dev/null
+++ b/web/app/components/app/chat/loading-anim/style.module.css
@@ -0,0 +1,82 @@
+.dot-flashing {
+ position: relative;
+ animation: 1s infinite linear alternate;
+ animation-delay: 0.5s;
+}
+
+.dot-flashing::before,
+.dot-flashing::after {
+ content: "";
+ display: inline-block;
+ position: absolute;
+ top: 0;
+ animation: 1s infinite linear alternate;
+}
+
+.dot-flashing::before {
+ animation-delay: 0s;
+}
+
+.dot-flashing::after {
+ animation-delay: 1s;
+}
+
+@keyframes dot-flashing {
+ 0% {
+ background-color: #667085;
+ }
+
+ 50%,
+ 100% {
+ background-color: rgba(102, 112, 133, 0.3);
+ }
+}
+
+@keyframes dot-flashing-avatar {
+ 0% {
+ background-color: #155EEF;
+ }
+
+ 50%,
+ 100% {
+ background-color: rgba(21, 94, 239, 0.3);
+ }
+}
+
+.text,
+.text::before,
+.text::after {
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background-color: #667085;
+ color: #667085;
+ animation-name: dot-flashing;
+}
+
+.text::before {
+ left: -7px;
+}
+
+.text::after {
+ left: 7px;
+}
+
+.avatar,
+.avatar::before,
+.avatar::after {
+ width: 2px;
+ height: 2px;
+ border-radius: 50%;
+ background-color: #155EEF;
+ color: #155EEF;
+ animation-name: dot-flashing-avatar;
+}
+
+.avatar::before {
+ left: -5px;
+}
+
+.avatar::after {
+ left: 5px;
+}
\ No newline at end of file
diff --git a/web/app/components/app/chat/style.module.css b/web/app/components/app/chat/style.module.css
new file mode 100644
index 00000000000..0744311c6d8
--- /dev/null
+++ b/web/app/components/app/chat/style.module.css
@@ -0,0 +1,91 @@
+.answerIcon {
+ position: relative;
+ background: url(./icons/robot.svg);
+}
+
+.typeingIcon {
+ position: absolute;
+ top: 0px;
+ left: 0px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 16px;
+ height: 16px;
+ background: #FFFFFF;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ border-radius: 16px;
+}
+
+
+.questionIcon {
+ background: url(./icons/default-avatar.jpg);
+ background-size: contain;
+ border-radius: 50%;
+}
+
+.answer::before,
+.question::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ width: 8px;
+ height: 12px;
+}
+
+.answer::before {
+ left: 0;
+ background: url(./icons/answer.svg) no-repeat;
+}
+
+.answerWrap .itemOperation {
+ display: none;
+}
+
+.answerWrap:hover .itemOperation {
+ display: flex;
+}
+
+.question::before {
+ right: 0;
+ background: url(./icons/question.svg) no-repeat;
+}
+
+.textArea {
+ padding-top: 13px;
+ padding-bottom: 13px;
+ padding-right: 90px;
+ border-radius: 12px;
+ line-height: 20px;
+ background-color: #fff;
+}
+
+.textArea:hover {
+ background-color: #fff;
+}
+
+/* .textArea:focus {
+ box-shadow: 0px 3px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px rgba(0, 0, 0, 0.05);
+} */
+
+.count {
+ /* display: none; */
+ padding: 0 2px;
+}
+
+.sendBtn {
+ background: url(./icons/send.svg) center center no-repeat;
+}
+
+.sendBtn:hover {
+ background-image: url(./icons/send-active.svg);
+ background-color: #EBF5FF;
+}
+
+.textArea:focus+div .count {
+ display: block;
+}
+
+.textArea:focus+div .sendBtn {
+ background-image: url(./icons/send-active.svg);
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/base/feature-panel/index.tsx b/web/app/components/app/configuration/base/feature-panel/index.tsx
new file mode 100644
index 00000000000..0bb2f88ba1a
--- /dev/null
+++ b/web/app/components/app/configuration/base/feature-panel/index.tsx
@@ -0,0 +1,54 @@
+'use client'
+import React, { FC, ReactNode } from 'react'
+import cn from 'classnames'
+
+export interface IFeaturePanelProps {
+ className?: string
+ headerIcon: ReactNode
+ title: ReactNode
+ headerRight: ReactNode
+ hasHeaderBottomBorder?: boolean
+ isFocus?: boolean
+ noBodySpacing?: boolean
+ children?: ReactNode
+}
+
+const FeaturePanel: FC<IFeaturePanelProps> = ({
+ className,
+ headerIcon,
+ title,
+ headerRight,
+ hasHeaderBottomBorder,
+ isFocus,
+ noBodySpacing,
+ children,
+}) => {
+ return (
+ <div
+ className={cn(className, isFocus && 'border border-[#2D0DEE]', 'rounded-xl bg-gray-50 pt-2 pb-3', noBodySpacing && '!pb-0')}
+ style={isFocus ? {
+ boxShadow: '0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06)',
+ } : {}}
+ >
+ {/* Header */}
+ <div className={cn('pb-2 px-3', hasHeaderBottomBorder && 'border-b border-gray-100')}>
+ <div className='flex justify-between items-center h-8'>
+ <div className='flex items-center space-x-1 shrink-0'>
+ <div className='flex items-center justify-center w-4 h-4'>{headerIcon}</div>
+ <div className='text-sm font-semibold text-gray-800'>{title}</div>
+ </div>
+ <div>
+ {headerRight}
+ </div>
+ </div>
+ </div>
+ {/* Body */}
+ {children && (
+ <div className={cn(!noBodySpacing && 'mt-1 px-3')}>
+ {children}
+ </div>
+ )}
+ </div>
+ )
+}
+export default React.memo(FeaturePanel)
diff --git a/web/app/components/app/configuration/base/group-name/index.tsx b/web/app/components/app/configuration/base/group-name/index.tsx
new file mode 100644
index 00000000000..68c87d6d923
--- /dev/null
+++ b/web/app/components/app/configuration/base/group-name/index.tsx
@@ -0,0 +1,23 @@
+'use client'
+import React, { FC } from 'react'
+
+export interface IGroupNameProps {
+ name: string
+}
+
+const GroupName: FC<IGroupNameProps> = ({
+ name
+}) => {
+ return (
+ <div className='flex items-center mb-1'>
+ <div className='mr-3 leading-[18px] text-xs font-semibold text-gray-500 uppercase'>{name}</div>
+ <div className='grow h-[1px]'
+ style={{
+ background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, #F3F4F6 100%)',
+
+ }}
+ ></div>
+ </div>
+ )
+}
+export default React.memo(GroupName)
diff --git a/web/app/components/app/configuration/base/icons/more-like-this-icon.tsx b/web/app/components/app/configuration/base/icons/more-like-this-icon.tsx
new file mode 100644
index 00000000000..8aa79fb400f
--- /dev/null
+++ b/web/app/components/app/configuration/base/icons/more-like-this-icon.tsx
@@ -0,0 +1,13 @@
+'use client'
+import React, { FC } from 'react'
+
+const MoreLikeThisIcon: FC = ({ }) => {
+ return (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M5.83914 0.666748H10.1609C10.6975 0.666741 11.1404 0.666734 11.5012 0.696212C11.8759 0.726829 12.2204 0.792538 12.544 0.957399C13.0457 1.21306 13.4537 1.62101 13.7093 2.12277C13.8742 2.44633 13.9399 2.7908 13.9705 3.16553C14 3.52633 14 3.96923 14 4.50587V7.41171C14 7.62908 14 7.73776 13.9652 7.80784C13.9303 7.87806 13.8939 7.91566 13.8249 7.95288C13.756 7.99003 13.6262 7.99438 13.3665 8.00307C12.8879 8.01909 12.4204 8.14633 11.997 8.36429C10.9478 7.82388 9.62021 7.82912 8.53296 8.73228C7.15064 9.88056 6.92784 11.8645 8.0466 13.2641C8.36602 13.6637 8.91519 14.1949 9.40533 14.6492C9.49781 14.7349 9.54405 14.7777 9.5632 14.8041C9.70784 15.003 9.5994 15.2795 9.35808 15.3271C9.32614 15.3334 9.26453 15.3334 9.14129 15.3334H5.83912C5.30248 15.3334 4.85958 15.3334 4.49878 15.304C4.12405 15.2733 3.77958 15.2076 3.45603 15.0428C2.95426 14.7871 2.54631 14.3792 2.29065 13.8774C2.12579 13.5538 2.06008 13.2094 2.02946 12.8346C1.99999 12.4738 1.99999 12.0309 2 11.4943V4.50587C1.99999 3.96924 1.99999 3.52632 2.02946 3.16553C2.06008 2.7908 2.12579 2.44633 2.29065 2.12277C2.54631 1.62101 2.95426 1.21306 3.45603 0.957399C3.77958 0.792538 4.12405 0.726829 4.49878 0.696212C4.85957 0.666734 5.3025 0.666741 5.83914 0.666748ZM4.66667 5.33342C4.29848 5.33342 4 5.63189 4 6.00008C4 6.36827 4.29848 6.66675 4.66667 6.66675H8.66667C9.03486 6.66675 9.33333 6.36827 9.33333 6.00008C9.33333 5.63189 9.03486 5.33342 8.66667 5.33342H4.66667ZM4 8.66675C4 8.29856 4.29848 8.00008 4.66667 8.00008H6C6.36819 8.00008 6.66667 8.29856 6.66667 8.66675C6.66667 9.03494 6.36819 9.33342 6 9.33342H4.66667C4.29848 9.33342 4 9.03494 4 8.66675ZM4.66667 2.66675C4.29848 2.66675 4 2.96523 4 3.33342C4 3.7016 4.29848 4.00008 4.66667 4.00008H10.6667C11.0349 4.00008 11.3333 3.7016 11.3333 3.33342C11.3333 2.96523 11.0349 2.66675 10.6667 2.66675H4.66667Z" fill="#DD2590" />
+ <path d="M11.9977 10.0256C11.3313 9.26808 10.2199 9.06432 9.3849 9.75796C8.54988 10.4516 8.43232 11.6113 9.08807 12.4317C9.58479 13.0531 10.9986 14.3025 11.655 14.8719C11.7744 14.9754 11.8341 15.0272 11.9037 15.0477C11.9642 15.0654 12.0312 15.0654 12.0917 15.0477C12.1613 15.0272 12.221 14.9754 12.3404 14.8719C12.9968 14.3025 14.4106 13.0531 14.9074 12.4317C15.5631 11.6113 15.4599 10.4443 14.6105 9.75796C13.7612 9.07161 12.6642 9.26808 11.9977 10.0256Z" fill="#DD2590" />
+ </svg>
+
+ )
+}
+export default React.memo(MoreLikeThisIcon)
diff --git a/web/app/components/app/configuration/base/icons/remove-icon/index.tsx b/web/app/components/app/configuration/base/icons/remove-icon/index.tsx
new file mode 100644
index 00000000000..497d5b68c25
--- /dev/null
+++ b/web/app/components/app/configuration/base/icons/remove-icon/index.tsx
@@ -0,0 +1,31 @@
+'use client'
+import React, { FC, useState } from 'react'
+import cn from 'classnames'
+
+export interface IRemoveIconProps {
+ className?: string
+ isHoverStatus?: boolean
+ onClick: () => void
+}
+
+const RemoveIcon: FC<IRemoveIconProps> = ({
+ className,
+ isHoverStatus,
+ onClick
+}) => {
+ const [isHovered, setIsHovered] = useState(false)
+ const computedIsHovered = isHoverStatus || isHovered
+ return (
+ <div
+ className={cn(className, computedIsHovered && 'bg-[#FEE4E2]', 'flex w-6 h-6 items-center justify-center rounded-md cursor-pointer hover:bg-[#FEE4E2]')}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ onClick={onClick}
+ >
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10 6H14M6 8H18M16.6667 8L16.1991 15.0129C16.129 16.065 16.0939 16.5911 15.8667 16.99C15.6666 17.3412 15.3648 17.6235 15.0011 17.7998C14.588 18 14.0607 18 13.0062 18H10.9938C9.93927 18 9.41202 18 8.99889 17.7998C8.63517 17.6235 8.33339 17.3412 8.13332 16.99C7.90607 16.5911 7.871 16.065 7.80086 15.0129L7.33333 8M10.6667 11V14.3333M13.3333 11V14.3333" stroke={computedIsHovered ? "#D92D20" : "#667085"} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </div>
+ )
+}
+export default React.memo(RemoveIcon)
diff --git a/web/app/components/app/configuration/base/icons/remove-icon/style.module.css b/web/app/components/app/configuration/base/icons/remove-icon/style.module.css
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/web/app/components/app/configuration/base/icons/suggested-questions-after-answer-icon.tsx b/web/app/components/app/configuration/base/icons/suggested-questions-after-answer-icon.tsx
new file mode 100644
index 00000000000..178d27609f7
--- /dev/null
+++ b/web/app/components/app/configuration/base/icons/suggested-questions-after-answer-icon.tsx
@@ -0,0 +1,11 @@
+'use client'
+import React, { FC } from 'react'
+
+const SuggestedQuestionsAfterAnswerIcon: FC = () => {
+ return (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M10.8275 1.33325H5.17245C4.63581 1.33324 4.19289 1.33324 3.8321 1.36272C3.45737 1.39333 3.1129 1.45904 2.78934 1.6239C2.28758 1.87956 1.87963 2.28751 1.62397 2.78928C1.45911 3.11284 1.3934 3.4573 1.36278 3.83204C1.3333 4.19283 1.33331 4.63574 1.33332 5.17239L1.33328 9.42497C1.333 9.95523 1.33278 10.349 1.42418 10.6901C1.67076 11.6103 2.38955 12.3291 3.3098 12.5757C3.51478 12.6306 3.73878 12.6525 3.99998 12.6611L3.99998 13.5806C3.99995 13.7374 3.99992 13.8973 4.01182 14.0283C4.0232 14.1536 4.05333 14.3901 4.21844 14.5969C4.40843 14.8349 4.69652 14.9734 5.00106 14.973C5.26572 14.9728 5.46921 14.8486 5.57416 14.7792C5.6839 14.7066 5.80872 14.6067 5.93117 14.5087L7.53992 13.2217C7.88564 12.9451 7.98829 12.8671 8.09494 12.8126C8.20192 12.7579 8.3158 12.718 8.43349 12.6938C8.55081 12.6697 8.67974 12.6666 9.12248 12.6666H10.8275C11.3642 12.6666 11.8071 12.6666 12.1679 12.6371C12.5426 12.6065 12.8871 12.5408 13.2106 12.3759C13.7124 12.1203 14.1203 11.7123 14.376 11.2106C14.5409 10.887 14.6066 10.5425 14.6372 10.1678C14.6667 9.80701 14.6667 9.36411 14.6667 8.82747V5.17237C14.6667 4.63573 14.6667 4.19283 14.6372 3.83204C14.6066 3.4573 14.5409 3.11284 14.376 2.78928C14.1203 2.28751 13.7124 1.87956 13.2106 1.6239C12.8871 1.45904 12.5426 1.39333 12.1679 1.36272C11.8071 1.33324 11.3642 1.33324 10.8275 1.33325ZM8.99504 4.99992C8.99504 4.44763 9.44275 3.99992 9.99504 3.99992C10.5473 3.99992 10.995 4.44763 10.995 4.99992C10.995 5.5522 10.5473 5.99992 9.99504 5.99992C9.44275 5.99992 8.99504 5.5522 8.99504 4.99992ZM4.92837 7.79996C5.222 7.57974 5.63816 7.63837 5.85961 7.93051C5.90071 7.98295 5.94593 8.03229 5.99199 8.08035C6.09019 8.18282 6.23775 8.32184 6.42882 8.4608C6.81353 8.74059 7.3454 8.99996 7.99504 8.99996C8.64469 8.99996 9.17655 8.74059 9.56126 8.4608C9.75233 8.32184 9.89989 8.18282 9.99809 8.08035C10.0441 8.0323 10.0894 7.98294 10.1305 7.93051C10.3519 7.63837 10.7681 7.57974 11.0617 7.79996C11.3563 8.02087 11.416 8.43874 11.195 8.73329C11.1967 8.73112 11.1928 8.7361 11.186 8.74466C11.1697 8.7651 11.1372 8.80597 11.1261 8.81916C11.087 8.86575 11.0317 8.92884 10.9607 9.00289C10.8194 9.15043 10.6128 9.34474 10.3455 9.53912C9.81353 9.92599 9.01206 10.3333 7.99504 10.3333C6.97802 10.3333 6.17655 9.92599 5.64459 9.53912C5.37733 9.34474 5.17072 9.15043 5.02934 9.00289C4.95837 8.92884 4.90305 8.86575 4.86395 8.81916C4.84438 8.79585 4.82881 8.77659 4.81731 8.76207C4.58702 8.46455 4.61798 8.03275 4.92837 7.79996ZM5.99504 3.99992C5.44275 3.99992 4.99504 4.44763 4.99504 4.99992C4.99504 5.5522 5.44275 5.99992 5.99504 5.99992C6.54732 5.99992 6.99504 5.5522 6.99504 4.99992C6.99504 4.44763 6.54732 3.99992 5.99504 3.99992Z" fill="#06AED4" />
+ </svg>
+ )
+}
+export default React.memo(SuggestedQuestionsAfterAnswerIcon)
diff --git a/web/app/components/app/configuration/base/icons/var-icon.tsx b/web/app/components/app/configuration/base/icons/var-icon.tsx
new file mode 100644
index 00000000000..e991e5bb388
--- /dev/null
+++ b/web/app/components/app/configuration/base/icons/var-icon.tsx
@@ -0,0 +1,11 @@
+'use client'
+import React, { FC } from 'react'
+
+const VarIcon: FC = () => {
+ return (
+ <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M3.71922 2.96714C3.91321 3.05239 4.06546 3.21112 4.14255 3.4085C4.21964 3.60588 4.21528 3.82578 4.13042 4.01994C3.51419 5.43299 3.1974 6.95838 3.20002 8.49994C3.20002 10.0943 3.53282 11.6087 4.13122 12.9799C4.20853 13.173 4.20766 13.3885 4.1288 13.5809C4.04993 13.7732 3.89927 13.9274 3.70873 14.0106C3.51819 14.0938 3.30274 14.0995 3.10802 14.0266C2.91331 13.9537 2.75464 13.8078 2.66562 13.6199C1.96073 12.0052 1.59791 10.2619 1.60002 8.49994C1.60002 6.68074 1.98002 4.94794 2.66562 3.37994C2.70767 3.28364 2.76829 3.19658 2.84401 3.12371C2.91973 3.05085 3.00906 2.99361 3.1069 2.95528C3.20474 2.91694 3.30917 2.89826 3.41424 2.9003C3.5193 2.90233 3.62293 2.92505 3.71922 2.96714ZM10.368 6.09994C10.0082 6.10002 9.65293 6.18102 9.32862 6.33695C9.0043 6.49288 8.7192 6.71974 8.49441 7.00074L8.23201 7.32874L8.14321 7.10554C8.02447 6.80879 7.81958 6.55441 7.55494 6.37518C7.2903 6.19594 6.97804 6.10008 6.65841 6.09994H6.40001C6.18784 6.09994 5.98436 6.18423 5.83433 6.33426C5.6843 6.48429 5.60002 6.68777 5.60002 6.89994C5.60002 7.11212 5.6843 7.3156 5.83433 7.46563C5.98436 7.61566 6.18784 7.69994 6.40001 7.69994H6.65841L7.08401 8.76394L6.25602 9.79994C6.18103 9.8936 6.08594 9.96919 5.97779 10.0211C5.86964 10.073 5.75119 10.1 5.63122 10.0999H5.60002C5.38784 10.0999 5.18436 10.1842 5.03433 10.3343C4.8843 10.4843 4.80001 10.6878 4.80001 10.8999C4.80001 11.1121 4.8843 11.3156 5.03433 11.4656C5.18436 11.6157 5.38784 11.6999 5.60002 11.6999H5.63122C5.99107 11.6999 6.34629 11.6189 6.67061 11.4629C6.99493 11.307 7.28003 11.0801 7.50481 10.7991L7.76721 10.4711L7.85601 10.6943C7.97481 10.9912 8.17982 11.2457 8.44462 11.4249C8.70942 11.6042 9.02185 11.7 9.34161 11.6999H9.60001C9.81219 11.6999 10.0157 11.6157 10.1657 11.4656C10.3157 11.3156 10.4 11.1121 10.4 10.8999C10.4 10.6878 10.3157 10.4843 10.1657 10.3343C10.0157 10.1842 9.81219 10.0999 9.60001 10.0999H9.34161L8.91602 9.03594L9.74401 7.99994C9.819 7.90629 9.91409 7.8307 10.0222 7.77877C10.1304 7.72684 10.2488 7.6999 10.3688 7.69994H10.4C10.6122 7.69994 10.8157 7.61566 10.9657 7.46563C11.1157 7.3156 11.2 7.11212 11.2 6.89994C11.2 6.68777 11.1157 6.48429 10.9657 6.33426C10.8157 6.18423 10.6122 6.09994 10.4 6.09994H10.3688H10.368ZM11.8672 4.01994C11.7837 3.82571 11.7804 3.6063 11.8581 3.40966C11.9359 3.21303 12.0883 3.05517 12.2821 2.97059C12.4759 2.88602 12.6953 2.8816 12.8923 2.9583C13.0894 3.03501 13.248 3.1866 13.3336 3.37994C14.0388 4.99468 14.4019 6.73795 14.4 8.49994C14.4 10.3191 14.02 12.0519 13.3344 13.6199C13.2946 13.7194 13.2352 13.8098 13.1597 13.8859C13.0843 13.9619 12.9943 14.0221 12.8952 14.0627C12.7961 14.1033 12.6898 14.1236 12.5827 14.1224C12.4756 14.1212 12.3698 14.0985 12.2716 14.0556C12.1735 14.0127 12.0849 13.9506 12.0112 13.8728C11.9375 13.7951 11.8802 13.7033 11.8426 13.603C11.805 13.5027 11.788 13.3959 11.7925 13.2888C11.797 13.1818 11.8229 13.0768 11.8688 12.9799C12.4853 11.567 12.8024 10.0416 12.8 8.49994C12.8 6.90554 12.4672 5.39114 11.868 4.01994H11.8672Z" fill="#FF8A4C" />
+ </svg>
+ )
+}
+export default React.memo(VarIcon)
diff --git a/web/app/components/app/configuration/base/operation-btn/index.tsx b/web/app/components/app/configuration/base/operation-btn/index.tsx
new file mode 100644
index 00000000000..1756464f7eb
--- /dev/null
+++ b/web/app/components/app/configuration/base/operation-btn/index.tsx
@@ -0,0 +1,39 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import { PlusIcon } from '@heroicons/react/20/solid'
+
+export interface IOperationBtnProps {
+ type: 'add' | 'edit'
+ actionName?: string
+ onClick: () => void
+}
+
+const iconMap = {
+ add: <PlusIcon className='w-3.5 h-3.5' />,
+ edit: (<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M6.99998 11.6666H12.25M1.75 11.6666H2.72682C3.01217 11.6666 3.15485 11.6666 3.28912 11.6344C3.40816 11.6058 3.52196 11.5587 3.62635 11.4947C3.74408 11.4226 3.84497 11.3217 4.04675 11.1199L11.375 3.79164C11.8583 3.30839 11.8583 2.52488 11.375 2.04164C10.8918 1.55839 10.1083 1.55839 9.62501 2.04164L2.29674 9.3699C2.09496 9.57168 1.99407 9.67257 1.92192 9.7903C1.85795 9.89469 1.81081 10.0085 1.78224 10.1275C1.75 10.2618 1.75 10.4045 1.75 10.6898V11.6666Z" stroke="#344054" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ )
+}
+
+const OperationBtn: FC<IOperationBtnProps> = ({
+ type,
+ actionName,
+ onClick
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div
+ className='flex items-center rounded-md h-7 px-3 space-x-1 text-gray-700 cursor-pointer hover:bg-gray-200'
+ onClick={onClick}>
+ <div>
+ {iconMap[type]}
+ </div>
+ <div className='text-xs font-medium'>
+ {actionName || t(`common.operation.${type}`)}
+ </div>
+ </div>
+ )
+}
+export default React.memo(OperationBtn)
diff --git a/web/app/components/app/configuration/base/var-highlight/index.tsx b/web/app/components/app/configuration/base/var-highlight/index.tsx
new file mode 100644
index 00000000000..8d7e09573f4
--- /dev/null
+++ b/web/app/components/app/configuration/base/var-highlight/index.tsx
@@ -0,0 +1,36 @@
+'use client'
+import React, { FC } from 'react'
+
+import s from './style.module.css'
+
+export interface IVarHighlightProps {
+ name: string
+}
+
+const VarHighlight: FC<IVarHighlightProps> = ({
+ name,
+}) => {
+ return (
+ <div
+ key={name}
+ className={`${s.item} flex mb-2 items-center justify-center rounded-md px-1 h-5 text-xs font-medium text-primary-600`}
+ >
+ <span className='opacity-60'>{'{{'}</span>
+ <span>{name}</span>
+ <span className='opacity-60'>{'}}'}</span>
+ </div>
+ )
+}
+
+export const varHighlightHTML = ({ name }: IVarHighlightProps) => {
+ const html = `<div class="${s.item} inline-flex mb-2 items-center justify-center px-1 rounded-md h-5 text-xs font-medium text-primary-600">
+ <span class='opacity-60'>{{</span>
+ <span>${name}</span>
+ <span class='opacity-60'>}}</span>
+</div>`
+ return html
+}
+
+
+
+export default React.memo(VarHighlight)
diff --git a/web/app/components/app/configuration/base/var-highlight/style.module.css b/web/app/components/app/configuration/base/var-highlight/style.module.css
new file mode 100644
index 00000000000..cd5c8f8d775
--- /dev/null
+++ b/web/app/components/app/configuration/base/var-highlight/style.module.css
@@ -0,0 +1,3 @@
+.item {
+ background-color: rgba(21, 94, 239, 0.05);
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/base/warning-mask/formatting-changed.tsx b/web/app/components/app/configuration/base/warning-mask/formatting-changed.tsx
new file mode 100644
index 00000000000..61787a4d0f5
--- /dev/null
+++ b/web/app/components/app/configuration/base/warning-mask/formatting-changed.tsx
@@ -0,0 +1,40 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import WarningMask from '.'
+import Button from '@/app/components/base/button'
+
+export interface IFormattingChangedProps {
+ onConfirm: () => void
+ onCancel: () => void
+}
+
+const icon = (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M1.33337 6.66667C1.33337 6.66667 2.67003 4.84548 3.75593 3.75883C4.84183 2.67218 6.34244 2 8.00004 2C11.3137 2 14 4.68629 14 8C14 11.3137 11.3137 14 8.00004 14C5.26465 14 2.95678 12.1695 2.23455 9.66667M1.33337 6.66667V2.66667M1.33337 6.66667H5.33337" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const FormattingChanged: FC<IFormattingChangedProps> = ({
+ onConfirm,
+ onCancel
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <WarningMask
+ title={t('appDebug.formattingChangedTitle')}
+ description={t('appDebug.formattingChangedText')}
+ footer={
+ <div className='flex space-x-2'>
+ <Button type='primary' className='flex items-center space-x-2' onClick={onConfirm}>
+ {icon}
+ <span>{t('common.operation.refresh')}</span>
+ </Button>
+ <Button onClick={onCancel}>{t('common.operation.cancel') as string}</Button>
+ </div>
+ }
+ />
+ )
+}
+export default React.memo(FormattingChanged)
diff --git a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx
new file mode 100644
index 00000000000..af39b700386
--- /dev/null
+++ b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx
@@ -0,0 +1,37 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import WarningMask from '.'
+import Button from '@/app/components/base/button'
+
+export interface IHasNotSetAPIProps {
+ isTrailFinished: boolean
+ onSetting: () => void
+}
+
+const icon = (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M14 6.00001L14 2.00001M14 2.00001H9.99999M14 2.00001L8 8M6.66667 2H5.2C4.0799 2 3.51984 2 3.09202 2.21799C2.71569 2.40973 2.40973 2.71569 2.21799 3.09202C2 3.51984 2 4.07989 2 5.2V10.8C2 11.9201 2 12.4802 2.21799 12.908C2.40973 13.2843 2.71569 13.5903 3.09202 13.782C3.51984 14 4.07989 14 5.2 14H10.8C11.9201 14 12.4802 14 12.908 13.782C13.2843 13.5903 13.5903 13.2843 13.782 12.908C14 12.4802 14 11.9201 14 10.8V9.33333" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+
+)
+
+const HasNotSetAPI: FC<IHasNotSetAPIProps> = ({
+ isTrailFinished,
+ onSetting
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <WarningMask
+ title={isTrailFinished ? t('appDebug.notSetAPIKey.trailFinished') : t('appDebug.notSetAPIKey.title')}
+ description={t('appDebug.notSetAPIKey.description')}
+ footer={
+ <Button type='primary' className='flex items-center space-x-2' onClick={onSetting}>
+ <span>{t('appDebug.notSetAPIKey.settingBtn')}</span>
+ {icon}
+ </Button>}
+ />
+ )
+}
+export default React.memo(HasNotSetAPI)
diff --git a/web/app/components/app/configuration/base/warning-mask/index.tsx b/web/app/components/app/configuration/base/warning-mask/index.tsx
new file mode 100644
index 00000000000..d7e45e360fc
--- /dev/null
+++ b/web/app/components/app/configuration/base/warning-mask/index.tsx
@@ -0,0 +1,42 @@
+'use client'
+import React, { FC } from 'react'
+
+import s from './style.module.css'
+
+export interface IWarningMaskProps {
+ title: string
+ description: string
+ footer: React.ReactNode
+}
+
+const warningIcon = (
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M9.99996 13.3334V10.0001M9.99996 6.66675H10.0083M18.3333 10.0001C18.3333 14.6025 14.6023 18.3334 9.99996 18.3334C5.39759 18.3334 1.66663 14.6025 1.66663 10.0001C1.66663 5.39771 5.39759 1.66675 9.99996 1.66675C14.6023 1.66675 18.3333 5.39771 18.3333 10.0001Z" stroke="#F79009" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const WarningMask: FC<IWarningMaskProps> = ({
+ title,
+ description,
+ footer,
+}) => {
+ return (
+ <div className={`${s.mask} absolute z-10 inset-0 pt-16`}
+ >
+ <div className='mx-auto w-[535px]'>
+ <div className={`${s.icon} flex items-center justify-center w-11 h-11 rounded-xl bg-white`}>{warningIcon}</div>
+ <div className='mt-4 text-[24px] leading-normal font-semibold text-gray-800'>
+ {title}
+ </div>
+ <div className='mt-3 text-base text-gray-500'>
+ {description}
+ </div>
+ <div className='mt-6'>
+ {footer}
+ </div>
+ </div>
+
+ </div>
+ )
+}
+export default React.memo(WarningMask)
diff --git a/web/app/components/app/configuration/base/warning-mask/style.module.css b/web/app/components/app/configuration/base/warning-mask/style.module.css
new file mode 100644
index 00000000000..e1d6f10de9e
--- /dev/null
+++ b/web/app/components/app/configuration/base/warning-mask/style.module.css
@@ -0,0 +1,8 @@
+.mask {
+ background-color: rgba(239, 244, 255, 0.9);
+ backdrop-filter: blur(2px);
+}
+
+.icon {
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config-model/index.tsx b/web/app/components/app/configuration/config-model/index.tsx
new file mode 100644
index 00000000000..999e9896826
--- /dev/null
+++ b/web/app/components/app/configuration/config-model/index.tsx
@@ -0,0 +1,243 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useState } from 'react'
+import cn from 'classnames'
+import { useTranslation } from 'react-i18next'
+import { useBoolean, useClickAway } from 'ahooks'
+import ParamItem from './param-item'
+import Radio from '@/app/components/base/radio'
+import Panel from '@/app/components/base/panel'
+import type { CompletionParams } from '@/models/debug'
+import { Cog8ToothIcon, InformationCircleIcon, ChevronDownIcon } from '@heroicons/react/24/outline'
+import { AppType } from '@/types/app'
+import { TONE_LIST } from '@/config'
+
+export type IConifgModelProps = {
+ mode: string
+ modelId: string
+ setModelId: (id: string) => void
+ completionParams: CompletionParams
+ onCompletionParamsChange: (newParams: CompletionParams) => void
+ disabled: boolean
+ canUseGPT4: boolean
+ onShowUseGPT4Confirm: () => void
+}
+
+const options = [
+ { id: 'gpt-3.5-turbo', name: 'gpt-3.5-turbo', type: AppType.chat },
+ { id: 'gpt-4', name: 'gpt-4', type: AppType.chat }, // 8k version
+ { id: 'gpt-3.5-turbo', name: 'gpt-3.5-turbo', type: AppType.completion },
+ { id: 'text-davinci-003', name: 'text-davinci-003', type: AppType.completion },
+]
+
+const ModelIcon = ({ className }: { className?: string }) => (
+ <svg className={`w-4 h-4 ${className}`} width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="20" height="20" rx="6" fill="black" />
+ <path d="M16.5963 9.65729C16.748 9.99569 16.8443 10.3574 16.8836 10.7265C16.9216 11.0955 16.9026 11.4689 16.8238 11.8321C16.7465 12.1953 16.6123 12.5439 16.4256 12.8648C16.3031 13.0793 16.1587 13.2805 15.9924 13.4658C15.8276 13.6496 15.6438 13.8159 15.444 13.9617C15.2427 14.1076 15.0283 14.2301 14.8007 14.3308C14.5746 14.4299 14.3383 14.5058 14.0962 14.5554C13.9824 14.9084 13.8132 15.2424 13.5944 15.5429C13.3771 15.8434 13.1131 16.1074 12.8126 16.3247C12.5121 16.5435 12.1795 16.7127 11.8266 16.8265C11.4736 16.9417 11.1045 16.9986 10.7326 16.9986C10.4861 17.0001 10.2381 16.9738 9.99596 16.9242C9.75529 16.8732 9.51899 16.7959 9.2929 16.6952C9.06681 16.5946 8.85239 16.4691 8.65256 16.3233C8.45418 16.1774 8.2704 16.0097 8.10703 15.8244C7.74237 15.9032 7.36896 15.9221 6.99992 15.8842C6.63089 15.8448 6.26914 15.7486 5.92928 15.5969C5.59088 15.4466 5.27727 15.2424 5.00159 14.993C4.72591 14.7436 4.49107 14.4518 4.30582 14.1309C4.18184 13.9165 4.07973 13.6904 4.00242 13.4556C3.92511 13.2207 3.87406 12.9786 3.84781 12.7321C3.82155 12.487 3.82301 12.2391 3.84927 11.9926C3.87552 11.7475 3.92949 11.5054 4.0068 11.2705C3.75883 10.9949 3.55462 10.6813 3.40292 10.3428C3.25268 10.003 3.15495 9.6427 3.11703 9.27367C3.07765 8.90463 3.09807 8.53122 3.17538 8.16802C3.25268 7.80482 3.38688 7.4562 3.57358 7.1353C3.69611 6.92088 3.84051 6.71813 4.00534 6.53434C4.17017 6.35056 4.35541 6.18427 4.55525 6.03841C4.75508 5.89254 4.97096 5.76856 5.19705 5.66937C5.42459 5.56873 5.66089 5.49434 5.90303 5.44474C6.0168 5.09029 6.186 4.75772 6.40334 4.45725C6.62213 4.15677 6.88615 3.89275 7.18663 3.67396C7.48711 3.45662 7.81968 3.28742 8.17267 3.17219C8.52566 3.05841 8.89469 3.00007 9.26664 3.00153C9.51315 3.00007 9.76112 3.02486 10.0033 3.07592C10.2454 3.12697 10.4817 3.20282 10.7078 3.30346C10.9339 3.40557 11.1483 3.52955 11.3481 3.67542C11.548 3.82274 11.7317 3.98902 11.8951 4.17427C12.2583 4.09696 12.6317 4.078 13.0008 4.11592C13.3698 4.15385 13.7301 4.25158 14.0699 4.40182C14.4083 4.55352 14.7219 4.75627 14.9976 5.00569C15.2733 5.25366 15.5082 5.54393 15.6934 5.86629C15.8174 6.07925 15.9195 6.30534 15.9968 6.54164C16.0741 6.77648 16.1266 7.01861 16.1514 7.26512C16.1777 7.51163 16.1777 7.7596 16.15 8.00611C16.1237 8.25262 16.0697 8.49475 15.9924 8.72959C16.2418 9.00528 16.4446 9.31742 16.5963 9.65729ZM11.7361 15.8842C12.0541 15.7529 12.3429 15.5589 12.5865 15.3153C12.8301 15.0717 13.0241 14.7829 13.1554 14.4635C13.2866 14.1455 13.3552 13.8042 13.3552 13.46V10.2072C13.3542 10.2043 13.3533 10.2009 13.3523 10.197C13.3513 10.1941 13.3499 10.1911 13.3479 10.1882C13.346 10.1853 13.3435 10.1829 13.3406 10.1809C13.3377 10.178 13.3348 10.1761 13.3319 10.1751L12.1547 9.49538V13.4249C12.1547 13.4643 12.1489 13.5052 12.1387 13.5431C12.1285 13.5825 12.1139 13.6189 12.0935 13.654C12.0731 13.689 12.0497 13.7211 12.0206 13.7488C11.9922 13.777 11.9603 13.8015 11.9257 13.8217L9.13828 15.4306C9.11495 15.4452 9.07556 15.4656 9.05514 15.4772C9.17037 15.575 9.29582 15.661 9.42709 15.7369C9.55983 15.8127 9.69694 15.8769 9.83989 15.9294C9.98284 15.9805 10.1302 16.0199 10.2789 16.0461C10.4292 16.0724 10.5809 16.0855 10.7326 16.0855C11.0768 16.0855 11.4181 16.0169 11.7361 15.8842ZM5.09786 13.6758C5.27144 13.9749 5.50044 14.2345 5.77321 14.4445C6.04743 14.6546 6.35812 14.8077 6.69069 14.8967C7.02326 14.9857 7.37042 15.009 7.71174 14.9638C8.05306 14.9186 8.38125 14.8077 8.68027 14.6356L11.4984 13.0092L11.5057 13.0019C11.5076 13 11.5091 12.9971 11.51 12.9932C11.512 12.9903 11.5134 12.9874 11.5144 12.9844V11.6133L8.11286 13.581C8.07786 13.6014 8.04139 13.616 8.00346 13.6277C7.96408 13.6379 7.9247 13.6423 7.88386 13.6423C7.84447 13.6423 7.80509 13.6379 7.76571 13.6277C7.72778 13.616 7.68986 13.6014 7.65485 13.581L4.86739 11.9707C4.8426 11.9561 4.80613 11.9342 4.78571 11.9211C4.75946 12.0713 4.74633 12.223 4.74633 12.3747C4.74633 12.5264 4.76091 12.6781 4.78717 12.8284C4.81342 12.9771 4.85427 13.1245 4.90532 13.2674C4.95783 13.4104 5.02201 13.5475 5.09786 13.6788V13.6758ZM4.36562 7.59332C4.1935 7.89234 4.08265 8.22199 4.03743 8.56331C3.99221 8.90463 4.01555 9.25033 4.10453 9.58436C4.1935 9.91692 4.34666 10.2276 4.5567 10.5018C4.76675 10.7746 5.02784 11.0036 5.32541 11.1757L8.14204 12.8036C8.14495 12.8045 8.14836 12.8055 8.15225 12.8065H8.16246C8.16635 12.8065 8.16975 12.8055 8.17267 12.8036C8.17558 12.8026 8.1785 12.8011 8.18142 12.7992L9.36291 12.1165L5.96137 10.1532C5.92782 10.1328 5.89573 10.108 5.86656 10.0803C5.8383 10.0519 5.81379 10.0201 5.79363 9.98548C5.77467 9.95047 5.75862 9.91401 5.74841 9.87462C5.7382 9.8367 5.73237 9.79732 5.73383 9.75647V6.44391C5.59088 6.49642 5.45231 6.5606 5.32103 6.63645C5.18975 6.71376 5.06577 6.80128 4.94908 6.899C4.83385 6.99673 4.72591 7.10467 4.62818 7.22136C4.53045 7.3366 4.44439 7.46204 4.36854 7.59332H4.36562ZM14.0408 9.84545C14.0758 9.86587 14.1079 9.88921 14.137 9.91838C14.1647 9.9461 14.1895 9.97819 14.21 10.0132C14.2289 10.0482 14.245 10.0861 14.2552 10.1241C14.2639 10.1634 14.2698 10.2028 14.2683 10.2437V13.5562C14.7365 13.3841 15.145 13.0822 15.4469 12.6854C15.7503 12.2887 15.9326 11.8146 15.9749 11.3187C16.0172 10.8227 15.918 10.3239 15.6876 9.88192C15.4571 9.43995 15.1056 9.07237 14.6738 8.82441L11.8572 7.19657C11.8543 7.19559 11.8509 7.19462 11.847 7.19365H11.8368C11.8338 7.19462 11.8304 7.19559 11.8266 7.19657C11.8236 7.19754 11.8207 7.199 11.8178 7.20094L10.6421 7.88067L14.0437 9.84545H14.0408ZM15.215 8.0805H15.2135V8.08196L15.215 8.0805ZM15.2135 8.07904C15.2981 7.58894 15.2412 7.08425 15.0487 6.62478C14.8576 6.16531 14.5382 5.77002 14.1297 5.48413C13.7213 5.19969 13.24 5.03632 12.7426 5.01445C12.2437 4.99402 11.7507 5.11509 11.3189 5.36306L8.50232 6.98944C8.4994 6.99138 8.49697 6.99382 8.49503 6.99673L8.48919 7.00549C8.48822 7.0084 8.48725 7.01181 8.48627 7.0157C8.4853 7.01861 8.48482 7.02202 8.48482 7.02591V8.38536L11.8864 6.42057C11.9214 6.40015 11.9593 6.38556 11.9972 6.37389C12.0366 6.36368 12.076 6.35931 12.1154 6.35931C12.1562 6.35931 12.1956 6.36368 12.235 6.37389C12.2729 6.38556 12.3094 6.40015 12.3444 6.42057L15.1318 8.03091C15.1566 8.04549 15.1931 8.06591 15.2135 8.07904ZM7.84301 6.57373C7.84301 6.53434 7.84885 6.49496 7.85906 6.45558C7.86927 6.41765 7.88386 6.37973 7.90428 6.34472C7.9247 6.31117 7.94804 6.27908 7.97721 6.24991C8.00492 6.2222 8.03701 6.1974 8.07202 6.17844L10.8595 4.56956C10.8857 4.55352 10.9222 4.53309 10.9426 4.52288C10.5605 4.20344 10.0937 3.99923 9.59921 3.93651C9.10474 3.87233 8.60296 3.9511 8.15225 4.1626C7.70007 4.3741 7.3179 4.71105 7.05097 5.13114C6.78404 5.55268 6.64256 6.03987 6.64256 6.53872V9.79148C6.64353 9.79537 6.6445 9.79878 6.64547 9.80169C6.64645 9.80461 6.6479 9.80753 6.64985 9.81044C6.65179 9.81336 6.65422 9.81628 6.65714 9.8192C6.65909 9.82114 6.662 9.82309 6.66589 9.82503L7.84301 10.5048V6.57373ZM8.4819 10.8723L9.99742 11.7475L11.5129 10.8723V9.12343L9.99888 8.24824L8.48336 9.12343L8.4819 10.8723Z" fill="white" />
+ </svg>
+)
+
+const ConifgModel: FC<IConifgModelProps> = ({
+ mode,
+ modelId,
+ setModelId,
+ completionParams,
+ onCompletionParamsChange,
+ disabled,
+ canUseGPT4,
+ onShowUseGPT4Confirm,
+}) => {
+ const { t } = useTranslation()
+ const isChatApp = mode === AppType.chat
+ const availableModels = options.filter((item) => item.type === mode)
+ const [isShowConfig, { setFalse: hideConfig, toggle: toogleShowConfig }] = useBoolean(false)
+ const configContentRef = React.useRef(null)
+ useClickAway(() => {
+ hideConfig()
+ }, configContentRef)
+
+ const params = [
+ {
+ id: 1,
+ name: t('common.model.params.temperature'),
+ key: 'temperature',
+ tip: t('common.model.params.temperatureTip'),
+ max: 2,
+ },
+ {
+ id: 2,
+ name: t('common.model.params.topP'),
+ key: 'top_p',
+ tip: t('common.model.params.topPTip'),
+ max: 1,
+ },
+ {
+ id: 3,
+ name: t('common.model.params.presencePenalty'),
+ key: 'presence_penalty',
+ tip: t('common.model.params.presencePenaltyTip'),
+ min: -2,
+ max: 2,
+ },
+ {
+ id: 4,
+ name: t('common.model.params.frequencyPenalty'),
+ key: 'frequency_penalty',
+ tip: t('common.model.params.frequencyPenaltyTip'),
+ min: -2,
+ max: 2,
+ },
+ {
+ id: 5,
+ name: t('common.model.params.maxToken'),
+ key: 'max_tokens',
+ tip: t('common.model.params.maxTokenTip'),
+ step: 100,
+ max: 4000,
+ },
+ ]
+
+ const selectModelDisabled = false // chat gpt-3.5-turbo, gpt-4; text generation text-davinci-003, gpt-3.5-turbo
+
+ const selectedModel = { name: modelId } // options.find(option => option.id === modelId)
+ const [isShowOption, { setFalse: hideOption, toggle: toogleOption }] = useBoolean(false)
+ const triggerRef = React.useRef(null)
+ useClickAway(() => {
+ hideOption()
+ }, triggerRef)
+
+ const handleSelectModel = (id: string) => {
+ return () => {
+ if (id === 'gpt-4' && !canUseGPT4) {
+ hideConfig()
+ hideOption()
+ onShowUseGPT4Confirm()
+ return
+ }
+ setModelId(id)
+ }
+ }
+
+ function matchToneId(completionParams: CompletionParams): number {
+ const remvoedCustomeTone = TONE_LIST.slice(0, -1)
+ const CUSTOM_TONE_ID = 4
+ const tone = remvoedCustomeTone.find((tone) => {
+ return tone.config?.temperature === completionParams.temperature
+ && tone.config?.top_p === completionParams.top_p
+ && tone.config?.presence_penalty === completionParams.presence_penalty
+ && tone.config?.frequency_penalty === completionParams.frequency_penalty
+ })
+ return tone ? tone.id : CUSTOM_TONE_ID
+ }
+
+ // tone is a preset of completionParams.
+ const [toneId, setToneId] = React.useState(matchToneId(completionParams)) // default is Balanced
+ // set completionParams by toneId
+ const handleToneChange = (id: number) => {
+ if (id === 4)
+ return // custom tone
+ const tone = TONE_LIST.find(tone => tone.id === id)
+ if (tone) {
+ setToneId(id)
+ onCompletionParamsChange({
+ ...tone.config,
+ max_tokens: completionParams.max_tokens
+ } as CompletionParams)
+ }
+ }
+
+ useEffect(() => {
+ setToneId(matchToneId(completionParams))
+ }, [completionParams])
+
+ const handleParamChange = (id: number, value: number) => {
+ const key = params.find(item => item.id === id)?.key
+
+ if (key) {
+ onCompletionParamsChange({
+ ...completionParams,
+ [key]: value,
+ })
+ }
+ }
+ const ableStyle = 'bg-indigo-25 border-[#2A87F5] cursor-pointer'
+ const diabledStyle = 'bg-[#FFFCF5] border-[#F79009]'
+
+ return (
+ <div className='relative' ref={configContentRef}>
+ <div
+ className={cn(`flex items-center border h-8 px-2.5 space-x-2 rounded-lg`, disabled ? diabledStyle : ableStyle)}
+ onClick={() => !disabled && toogleShowConfig()}
+ >
+ <ModelIcon />
+ <div className='text-[13px] text-gray-900 font-medium'>{selectedModel.name}</div>
+ {disabled ? <InformationCircleIcon className='w-3.5 h-3.5 text-[#F79009]' /> : <Cog8ToothIcon className='w-3.5 h-3.5 text-gray-500' />}
+ </div>
+ {isShowConfig && (
+ <Panel
+ className='absolute z-20 top-8 right-0 !w-[496px] bg-white'
+ keepUnFold
+ headerIcon={
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.26865 0.790031C8.09143 0.753584 7.90866 0.753584 7.73144 0.790031C7.52659 0.832162 7.3435 0.934713 7.19794 1.01624L7.15826 1.03841L6.17628 1.58395C5.85443 1.76276 5.73846 2.16863 5.91727 2.49049C6.09608 2.81234 6.50195 2.9283 6.82381 2.74949L7.80579 2.20395C7.90681 2.14782 7.95839 2.11946 7.99686 2.10091L8.00004 2.09938L8.00323 2.10091C8.0417 2.11946 8.09327 2.14782 8.1943 2.20395L9.17628 2.74949C9.49814 2.9283 9.90401 2.81234 10.0828 2.49048C10.2616 2.16863 10.1457 1.76276 9.82381 1.58395L8.84183 1.03841L8.80215 1.01624C8.65659 0.934713 8.4735 0.832162 8.26865 0.790031Z" fill="#1C64F2" />
+ <path d="M12.8238 3.25062C12.5019 3.07181 12.0961 3.18777 11.9173 3.50963C11.7385 3.83148 11.8544 4.23735 12.1763 4.41616L12.6272 4.66668L12.1763 4.91719C11.8545 5.096 11.7385 5.50186 11.9173 5.82372C12.0961 6.14558 12.502 6.26154 12.8238 6.08273L13.3334 5.79966V6.33339C13.3334 6.70158 13.6319 7.00006 14 7.00006C14.3682 7.00006 14.6667 6.70158 14.6667 6.33339V5.29435L14.6668 5.24627C14.6673 5.12441 14.6678 4.98084 14.6452 4.83482C14.6869 4.67472 14.6696 4.49892 14.5829 4.34286C14.4904 4.1764 14.3371 4.06501 14.1662 4.02099C14.0496 3.93038 13.9239 3.86116 13.8173 3.8024L13.7752 3.77915L12.8238 3.25062Z" fill="#1C64F2" />
+ <path d="M3.8238 4.41616C4.14566 4.23735 4.26162 3.83148 4.08281 3.50963C3.90401 3.18777 3.49814 3.07181 3.17628 3.25062L2.22493 3.77915L2.18284 3.8024C2.07615 3.86116 1.95045 3.9304 1.83382 4.02102C1.66295 4.06506 1.50977 4.17643 1.41731 4.34286C1.33065 4.49886 1.31323 4.67459 1.35493 4.83464C1.33229 4.98072 1.33281 5.12436 1.33326 5.24627L1.33338 5.29435V6.33339C1.33338 6.70158 1.63185 7.00006 2.00004 7.00006C2.36823 7.00006 2.66671 6.70158 2.66671 6.33339V5.79961L3.17632 6.08273C3.49817 6.26154 3.90404 6.14558 4.08285 5.82372C4.26166 5.50186 4.1457 5.096 3.82384 4.91719L3.3729 4.66666L3.8238 4.41616Z" fill="#1C64F2" />
+ <path d="M2.66671 9.66672C2.66671 9.29853 2.36823 9.00006 2.00004 9.00006C1.63185 9.00006 1.33338 9.29853 1.33338 9.66672V10.7058L1.33326 10.7538C1.33262 10.9298 1.33181 11.1509 1.40069 11.3594C1.46024 11.5397 1.55759 11.7051 1.68622 11.8447C1.835 12.0061 2.02873 12.1128 2.18281 12.1977L2.22493 12.221L3.17628 12.7495C3.49814 12.9283 3.90401 12.8123 4.08281 12.4905C4.26162 12.1686 4.14566 11.7628 3.8238 11.584L2.87245 11.0554C2.76582 10.9962 2.71137 10.9656 2.67318 10.9413L2.66995 10.9392L2.66971 10.9354C2.66699 10.8902 2.66671 10.8277 2.66671 10.7058V9.66672Z" fill="#1C64F2" />
+ <path d="M14.6667 9.66672C14.6667 9.29853 14.3682 9.00006 14 9.00006C13.6319 9.00006 13.3334 9.29853 13.3334 9.66672V10.7058C13.3334 10.8277 13.3331 10.8902 13.3304 10.9354L13.3301 10.9392L13.3269 10.9413C13.2887 10.9656 13.2343 10.9962 13.1276 11.0554L12.1763 11.584C11.8544 11.7628 11.7385 12.1686 11.9173 12.4905C12.0961 12.8123 12.5019 12.9283 12.8238 12.7495L13.7752 12.221L13.8172 12.1977C13.9713 12.1128 14.1651 12.0061 14.3139 11.8447C14.4425 11.7051 14.5398 11.5397 14.5994 11.3594C14.6683 11.1509 14.6675 10.9298 14.6668 10.7538L14.6667 10.7058V9.66672Z" fill="#1C64F2" />
+ <path d="M6.82381 13.2506C6.50195 13.0718 6.09608 13.1878 5.91727 13.5096C5.73846 13.8315 5.85443 14.2374 6.17628 14.4162L7.15826 14.9617L7.19793 14.9839C7.29819 15.04 7.41625 15.1061 7.54696 15.1556C7.66589 15.2659 7.82512 15.3333 8.00008 15.3333C8.17507 15.3333 8.33431 15.2659 8.45324 15.1556C8.58391 15.1061 8.70193 15.04 8.80215 14.9839L8.84183 14.9617L9.82381 14.4162C10.1457 14.2374 10.2616 13.8315 10.0828 13.5096C9.90401 13.1878 9.49814 13.0718 9.17628 13.2506L8.66675 13.5337V13C8.66675 12.6318 8.36827 12.3333 8.00008 12.3333C7.63189 12.3333 7.33341 12.6318 7.33341 13V13.5337L6.82381 13.2506Z" fill="#1C64F2" />
+ <path d="M6.82384 6.58385C6.50199 6.40505 6.09612 6.52101 5.91731 6.84286C5.7385 7.16472 5.85446 7.57059 6.17632 7.7494L7.33341 8.39223V9.66663C7.33341 10.0348 7.63189 10.3333 8.00008 10.3333C8.36827 10.3333 8.66675 10.0348 8.66675 9.66663V8.39223L9.82384 7.7494C10.1457 7.57059 10.2617 7.16472 10.0829 6.84286C9.90404 6.52101 9.49817 6.40505 9.17632 6.58385L8.00008 7.23732L6.82384 6.58385Z" fill="#1C64F2" />
+ </svg>
+ }
+ title={t('appDebug.modelConfig.title')}
+ >
+ <div className='py-3 pl-10 pr-6 text-sm'>
+ <div className="flex items-center justify-between my-5 h-9">
+ <div>{t('appDebug.modelConfig.model')}</div>
+ {/* model selector */}
+ <div className="relative">
+ <div ref={triggerRef} onClick={() => !selectModelDisabled && toogleOption()} className={cn(selectModelDisabled ? 'cursor-not-allowed' : 'cursor-pointer', "flex items-center h-9 px-3 space-x-2 rounded-lg bg-gray-50 ")}>
+ <ModelIcon />
+ <div className="text-sm gray-900">{selectedModel?.name}</div>
+ {!selectModelDisabled && <ChevronDownIcon className={cn(isShowOption && 'rotate-180', 'w-[14px] h-[14px] text-gray-500')} />}
+ </div>
+ {isShowOption && (
+ <div className={cn(isChatApp ? 'w-[159px]' : 'w-[179px]', "absolute right-0 bg-gray-50 rounded-lg")}>
+ {availableModels.map(item => (
+ <div key={item.id} onClick={handleSelectModel(item.id)} className="flex items-center h-9 px-3 rounded-lg cursor-pointer hover:bg-gray-100">
+ <ModelIcon className='mr-2' />
+ <div className="text-sm gray-900">{item.name}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="border-b border-gray-100"></div>
+
+ {/* Response type */}
+ <div className="mt-5 mb-4">
+ <div className="mb-4 text-sm text-gray-900">{t('appDebug.modelConfig.setTone')}</div>
+ <Radio.Group value={toneId} onChange={handleToneChange}>
+ <>
+ {TONE_LIST.slice(0, 3).map(tone => (
+ <Radio key={tone.id} value={tone.id} className="grow !px-0 !justify-center">{t(`common.model.tone.${tone.name}`) as string}</Radio>
+ ))}
+ </>
+ <div className="ml-[2px] mr-[3px] h-5 border-r border-gray-200"></div>
+ <Radio value={TONE_LIST[3].id}>{t(`common.model.tone.${TONE_LIST[3].name}`) as string}</Radio>
+ </Radio.Group>
+ </div>
+
+ {/* Params */}
+ <div className="mt-4 space-y-4">
+ {params.map(({ key, ...param }) => (<ParamItem key={key} {...param} value={(completionParams as any)[key] as any} onChange={handleParamChange} />))}
+ </div>
+ </div>
+ </Panel>
+ )}
+ </div>
+
+ )
+}
+
+export default React.memo(ConifgModel)
diff --git a/web/app/components/app/configuration/config-model/param-item.tsx b/web/app/components/app/configuration/config-model/param-item.tsx
new file mode 100644
index 00000000000..3ac19594342
--- /dev/null
+++ b/web/app/components/app/configuration/config-model/param-item.tsx
@@ -0,0 +1,45 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import Tooltip from '@/app/components/base/tooltip'
+import Slider from '@/app/components/base/slider'
+
+export type IParamIteProps = {
+ id: number
+ name: string
+ tip: string
+ value: number
+ step?: number
+ min?: number
+ max: number
+ onChange: (id: number, value: number) => void
+}
+
+const ParamIte: FC<IParamIteProps> = ({ id, name, tip, step = 0.1, min = 0, max, value, onChange }) => {
+ return (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center">
+ <span className="mr-[6px]">{name}</span>
+ {/* Give tooltip different tip to avoiding hide bug */}
+ <Tooltip htmlContent={<div className="w-[200px]">{tip}</div>} position='top' selector={`param-name-tooltip-${id}`}>
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.66667 10.6667H8V8H7.33333M8 5.33333H8.00667M14 8C14 8.78793 13.8448 9.56815 13.5433 10.2961C13.2417 11.0241 12.7998 11.6855 12.2426 12.2426C11.6855 12.7998 11.0241 13.2417 10.2961 13.5433C9.56815 13.8448 8.78793 14 8 14C7.21207 14 6.43185 13.8448 5.7039 13.5433C4.97595 13.2417 4.31451 12.7998 3.75736 12.2426C3.20021 11.6855 2.75825 11.0241 2.45672 10.2961C2.15519 9.56815 2 8.78793 2 8C2 6.4087 2.63214 4.88258 3.75736 3.75736C4.88258 2.63214 6.4087 2 8 2C9.5913 2 11.1174 2.63214 12.2426 3.75736C13.3679 4.88258 14 6.4087 14 8Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </Tooltip>
+ </div>
+ <div className="flex items-center">
+ <div className="mr-4 w-[120px]">
+ <Slider value={max < 5 ? value * 10 : value} min={min < 0 ? min * 10 : min} max={max < 5 ? max * 10 : max} onChange={value => onChange(id, value / (max < 5 ? 10 : 1))} />
+ </div>
+ <input type="number" min={min} max={max} step={step} className="block w-[64px] h-9 leading-9 rounded-lg border-0 pl-1 pl py-1.5 bg-gray-50 text-gray-900 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-primary-600" value={value} onChange={(e) => {
+ const value = parseFloat(e.target.value)
+ if (value < 0 || value > max)
+ return
+
+ onChange(id, value)
+ }} />
+ </div>
+ </div>
+ )
+}
+export default React.memo(ParamIte)
diff --git a/web/app/components/app/configuration/config-prompt/confirm-add-var/index.tsx b/web/app/components/app/configuration/config-prompt/confirm-add-var/index.tsx
new file mode 100644
index 00000000000..972f097be2d
--- /dev/null
+++ b/web/app/components/app/configuration/config-prompt/confirm-add-var/index.tsx
@@ -0,0 +1,72 @@
+'use client'
+import React, { FC, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import { useClickAway } from 'ahooks'
+import VarHighlight from '../../base/var-highlight'
+
+export interface IConfirmAddVarProps {
+ varNameArr: string[]
+ onConfrim: () => void
+ onCancel: () => void
+ onHide: () => void
+}
+
+const VarIcon = (
+ <svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M13.8683 0.704745C13.7051 0.374685 13.3053 0.239393 12.9752 0.402563C12.6452 0.565732 12.5099 0.965573 12.673 1.29563C13.5221 3.01316 13.9999 4.94957 13.9999 7.00019C13.9999 9.05081 13.5221 10.9872 12.673 12.7047C12.5099 13.0348 12.6452 13.4346 12.9752 13.5978C13.3053 13.761 13.7051 13.6257 13.8683 13.2956C14.8063 11.3983 15.3333 9.26009 15.3333 7.00019C15.3333 4.74029 14.8063 2.60209 13.8683 0.704745Z" fill="#FD853A" />
+ <path d="M3.32687 1.29563C3.49004 0.965573 3.35475 0.565732 3.02469 0.402563C2.69463 0.239393 2.29479 0.374685 2.13162 0.704745C1.19364 2.60209 0.666626 4.74029 0.666626 7.00019C0.666626 9.26009 1.19364 11.3983 2.13162 13.2956C2.29479 13.6257 2.69463 13.761 3.02469 13.5978C3.35475 13.4346 3.49004 13.0348 3.32687 12.7047C2.47779 10.9872 1.99996 9.05081 1.99996 7.00019C1.99996 4.94957 2.47779 3.01316 3.32687 1.29563Z" fill="#FD853A" />
+ <path d="M9.33238 4.8413C9.74208 4.36081 10.3411 4.08337 10.9726 4.08337H11.0324C11.4006 4.08337 11.6991 4.38185 11.6991 4.75004C11.6991 5.11823 11.4006 5.41671 11.0324 5.41671H10.9726C10.7329 5.41671 10.5042 5.52196 10.347 5.7064L8.78693 7.536L9.28085 9.27382C9.29145 9.31112 9.32388 9.33337 9.35696 9.33337H10.2864C10.6545 9.33337 10.953 9.63185 10.953 10C10.953 10.3682 10.6545 10.6667 10.2864 10.6667H9.35696C8.72382 10.6667 8.17074 10.245 7.99832 9.63834L7.74732 8.75524L6.76373 9.90878C6.35403 10.3893 5.75501 10.6667 5.1235 10.6667H5.06372C4.69553 10.6667 4.39705 10.3682 4.39705 10C4.39705 9.63185 4.69553 9.33337 5.06372 9.33337H5.1235C5.3632 9.33337 5.59189 9.22812 5.74915 9.04368L7.30926 7.21399L6.81536 5.47626C6.80476 5.43897 6.77233 5.41671 6.73925 5.41671H5.80986C5.44167 5.41671 5.14319 5.11823 5.14319 4.75004C5.14319 4.38185 5.44167 4.08337 5.80986 4.08337H6.73925C7.37239 4.08337 7.92547 4.50508 8.0979 5.11174L8.34887 5.99475L9.33238 4.8413Z" fill="#FD853A" />
+ </svg>
+)
+
+const ConfirmAddVar: FC<IConfirmAddVarProps> = ({
+ varNameArr,
+ onConfrim,
+ onCancel,
+ onHide,
+}) => {
+ const { t } = useTranslation()
+ const mainContentRef = useRef<HTMLDivElement>(null)
+ useClickAway(() => {
+ onHide()
+ }, mainContentRef)
+ return (
+ <div className='absolute inset-0 flex items-center justify-center rounded-xl'
+ style={{
+ backgroundColor: 'rgba(35, 56, 118, 0.2)'
+ }}>
+ <div
+ ref={mainContentRef}
+ className='w-[420px] rounded-xl bg-gray-50 p-6'
+ style={{
+ boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)'
+ }}
+ >
+ <div className='flex items-start space-x-3'>
+ <div
+ className='shrink-0 flex items-center justify-center h-10 w-10 rounded-xl border border-gray-100'
+ style={{
+ backgroundColor: 'rgba(255, 255, 255, 0.9)',
+ boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)'
+ }}
+ >{VarIcon}</div>
+ <div className='grow-1'>
+ <div className='text-sm font-medium text-gray-900'>{t('appDebug.autoAddVar')}</div>
+ <div className='flex flex-wrap mt-[15px] max-h-[66px] overflow-y-auto px-1 space-x-1'>
+ {varNameArr.map((name) => (
+ <VarHighlight key={name} name={name} />
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className='mt-7 flex justify-end space-x-2'>
+ <Button className='w-20 h-8 !text-[13px]' onClick={onCancel}>{t('common.operation.cancel')}</Button>
+ <Button className='w-20 h-8 !text-[13px]' type='primary' onClick={onConfrim}>{t('common.operation.add')}</Button>
+ </div>
+ </div>
+
+ </div>
+ )
+}
+export default React.memo(ConfirmAddVar)
diff --git a/web/app/components/app/configuration/config-prompt/index.tsx b/web/app/components/app/configuration/config-prompt/index.tsx
new file mode 100644
index 00000000000..b18d148c4cb
--- /dev/null
+++ b/web/app/components/app/configuration/config-prompt/index.tsx
@@ -0,0 +1,95 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import BlockInput from '@/app/components/base/block-input'
+import type { PromptVariable } from '@/models/debug'
+import Tooltip from '@/app/components/base/tooltip'
+import { AppType } from '@/types/app'
+import { getNewVar } from '@/utils/var'
+import { useTranslation } from 'react-i18next'
+import { useBoolean } from 'ahooks'
+import ConfirmAddVar from './confirm-add-var'
+
+export type IPromptProps = {
+ mode: AppType
+ promptTemplate: string
+ promptVariables: PromptVariable[]
+ onChange: (promp: string, promptVariables: PromptVariable[]) => void
+}
+
+const Prompt: FC<IPromptProps> = ({
+ mode,
+ promptTemplate,
+ promptVariables,
+ onChange,
+}) => {
+ const { t } = useTranslation()
+ const promptVariablesObj = (() => {
+ const obj: Record<string, boolean> = {}
+ promptVariables.forEach((item) => {
+ obj[item.key] = true
+ })
+ return obj
+ })()
+
+ const [newPromptVariables, setNewPromptVariables] = React.useState<PromptVariable[]>(promptVariables)
+ const [newTemplates, setNewTemplates] = React.useState('')
+ const [isShowConfirmAddVar, { setTrue: showConfirmAddVar, setFalse: hideConfirmAddVar }] = useBoolean(false)
+
+ const handleChange = (newTemplates: string, keys: string[]) => {
+ // const hasRemovedKeysInput = promptVariables.filter(input => keys.includes(input.key))
+ const newPromptVariables = keys.filter(key => !(key in promptVariablesObj)).map(key => getNewVar(key))
+ if (newPromptVariables.length > 0) {
+ setNewPromptVariables(newPromptVariables)
+ setNewTemplates(newTemplates)
+ showConfirmAddVar()
+ return
+ }
+ onChange(newTemplates, [])
+ }
+
+ const handleAutoAdd = (isAdd: boolean) => {
+ return () => {
+ onChange(newTemplates, isAdd ? newPromptVariables : [])
+ hideConfirmAddVar()
+ }
+ }
+
+ return (
+ <div className='relative rounded-xl border border-[#2D0DEE] bg-gray-25'>
+ <div className="flex items-center h-11 pl-3 gap-1">
+ <svg width="14" height="13" viewBox="0 0 14 13" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M3.00001 0.100098C3.21218 0.100098 3.41566 0.184383 3.56569 0.334412C3.71572 0.484441 3.80001 0.687924 3.80001 0.900098V1.7001H4.60001C4.81218 1.7001 5.01566 1.78438 5.16569 1.93441C5.31572 2.08444 5.40001 2.28792 5.40001 2.5001C5.40001 2.71227 5.31572 2.91575 5.16569 3.06578C5.01566 3.21581 4.81218 3.3001 4.60001 3.3001H3.80001V4.1001C3.80001 4.31227 3.71572 4.51575 3.56569 4.66578C3.41566 4.81581 3.21218 4.9001 3.00001 4.9001C2.78783 4.9001 2.58435 4.81581 2.43432 4.66578C2.28429 4.51575 2.20001 4.31227 2.20001 4.1001V3.3001H1.40001C1.18783 3.3001 0.98435 3.21581 0.834321 3.06578C0.684292 2.91575 0.600006 2.71227 0.600006 2.5001C0.600006 2.28792 0.684292 2.08444 0.834321 1.93441C0.98435 1.78438 1.18783 1.7001 1.40001 1.7001H2.20001V0.900098C2.20001 0.687924 2.28429 0.484441 2.43432 0.334412C2.58435 0.184383 2.78783 0.100098 3.00001 0.100098ZM3.00001 8.1001C3.21218 8.1001 3.41566 8.18438 3.56569 8.33441C3.71572 8.48444 3.80001 8.68792 3.80001 8.9001V9.7001H4.60001C4.81218 9.7001 5.01566 9.78438 5.16569 9.93441C5.31572 10.0844 5.40001 10.2879 5.40001 10.5001C5.40001 10.7123 5.31572 10.9158 5.16569 11.0658C5.01566 11.2158 4.81218 11.3001 4.60001 11.3001H3.80001V12.1001C3.80001 12.3123 3.71572 12.5158 3.56569 12.6658C3.41566 12.8158 3.21218 12.9001 3.00001 12.9001C2.78783 12.9001 2.58435 12.8158 2.43432 12.6658C2.28429 12.5158 2.20001 12.3123 2.20001 12.1001V11.3001H1.40001C1.18783 11.3001 0.98435 11.2158 0.834321 11.0658C0.684292 10.9158 0.600006 10.7123 0.600006 10.5001C0.600006 10.2879 0.684292 10.0844 0.834321 9.93441C0.98435 9.78438 1.18783 9.7001 1.40001 9.7001H2.20001V8.9001C2.20001 8.68792 2.28429 8.48444 2.43432 8.33441C2.58435 8.18438 2.78783 8.1001 3.00001 8.1001ZM8.60001 0.100098C8.77656 0.100041 8.94817 0.158388 9.0881 0.266047C9.22802 0.373706 9.32841 0.52463 9.37361 0.695298L10.3168 4.2601L13 5.8073C13.1216 5.87751 13.2226 5.9785 13.2928 6.10011C13.363 6.22173 13.4 6.35967 13.4 6.5001C13.4 6.64052 13.363 6.77847 13.2928 6.90008C13.2226 7.02169 13.1216 7.12268 13 7.1929L10.3168 8.7409L9.37281 12.3049C9.32753 12.4754 9.22716 12.6262 9.08732 12.7337C8.94748 12.8413 8.77602 12.8996 8.59961 12.8996C8.42319 12.8996 8.25173 12.8413 8.11189 12.7337C7.97205 12.6262 7.87169 12.4754 7.82641 12.3049L6.88321 8.7401L4.20001 7.1929C4.0784 7.12268 3.97742 7.02169 3.90721 6.90008C3.837 6.77847 3.80004 6.64052 3.80004 6.5001C3.80004 6.35967 3.837 6.22173 3.90721 6.10011C3.97742 5.9785 4.0784 5.87751 4.20001 5.8073L6.88321 4.2593L7.82721 0.695298C7.87237 0.524762 7.97263 0.373937 8.1124 0.266291C8.25216 0.158646 8.42359 0.100217 8.60001 0.100098Z" fill="#5850EC" />
+ </svg>
+ <div className="h2">{mode === AppType.chat ? t('appDebug.chatSubTitle') : t('appDebug.completionSubTitle')}</div>
+ <Tooltip
+ htmlContent={<div className='w-[180px]'>
+ {t('appDebug.promptTip')}
+ </div>}
+ selector='config-prompt-tooltip'>
+ <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.66667 11.1667H8V8.5H7.33333M8 5.83333H8.00667M14 8.5C14 9.28793 13.8448 10.0681 13.5433 10.7961C13.2417 11.5241 12.7998 12.1855 12.2426 12.7426C11.6855 13.2998 11.0241 13.7417 10.2961 14.0433C9.56815 14.3448 8.78793 14.5 8 14.5C7.21207 14.5 6.43185 14.3448 5.7039 14.0433C4.97595 13.7417 4.31451 13.2998 3.75736 12.7426C3.20021 12.1855 2.75825 11.5241 2.45672 10.7961C2.15519 10.0681 2 9.28793 2 8.5C2 6.9087 2.63214 5.38258 3.75736 4.25736C4.88258 3.13214 6.4087 2.5 8 2.5C9.5913 2.5 11.1174 3.13214 12.2426 4.25736C13.3679 5.38258 14 6.9087 14 8.5Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </Tooltip>
+ </div>
+
+ <BlockInput
+ value={promptTemplate}
+ onConfirm={(value: string, vars: string[]) => {
+ handleChange(value, vars)
+ }}
+ />
+
+ {isShowConfirmAddVar && (
+ <ConfirmAddVar
+ varNameArr={newPromptVariables.map((v) => v.name)}
+ onConfrim={handleAutoAdd(true)}
+ onCancel={handleAutoAdd(false)}
+ onHide={hideConfirmAddVar}
+ />
+ )}
+ </div>
+ )
+}
+
+export default React.memo(Prompt)
diff --git a/web/app/components/app/configuration/config-var/config-model/index.tsx b/web/app/components/app/configuration/config-var/config-model/index.tsx
new file mode 100644
index 00000000000..8d701489922
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-model/index.tsx
@@ -0,0 +1,115 @@
+'use client'
+import React, { FC, useState, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import ModalFoot from '../modal-foot'
+import ConfigSelect, { Options } from '../config-select'
+import ConfigString from '../config-string'
+import Toast from '@/app/components/base/toast'
+import type { PromptVariable } from '@/models/debug'
+import SelectTypeItem from '../select-type-item'
+import { getNewVar } from '@/utils/var'
+
+import s from './style.module.css'
+
+export interface IConfigModalProps {
+ payload: PromptVariable
+ type?: string
+ isShow: boolean
+ onClose: () => void
+ onConfirm: (newValue: { type: string, value: any }) => void
+}
+
+const ConfigModal: FC<IConfigModalProps> = ({
+ payload,
+ isShow,
+ onClose,
+ onConfirm
+}) => {
+ const { t } = useTranslation()
+ const { type, name, key, options, max_length } = payload || getNewVar('')
+
+ const [tempType, setTempType] = useState(type)
+ useEffect(() => {
+ setTempType(type)
+ }, [type])
+ const handleTypeChange = (type: string) => {
+ return () => {
+ setTempType(type)
+ }
+ }
+
+ const isStringInput = tempType === 'string'
+ const title = isStringInput ? t('appDebug.variableConig.maxLength') : t('appDebug.variableConig.options')
+
+ // string type
+ const [tempMaxLength, setTempMaxValue] = useState(max_length)
+ useEffect(() => {
+ setTempMaxValue(max_length)
+ }, [max_length])
+
+ // select type
+ const [tempOptions, setTempOptions] = useState<Options>(options || [])
+ useEffect(() => {
+ setTempOptions(options || [])
+ }, [options])
+
+ const handleConfirm = () => {
+ if (isStringInput) {
+ onConfirm({ type: tempType, value: tempMaxLength })
+ } else {
+ if (tempOptions.length === 0) {
+ Toast.notify({ type: 'error', message: 'At least one option requied' })
+ return
+ }
+ const obj: Record<string, boolean> = {}
+ let hasRepeatedItem = false
+ tempOptions.forEach(o => {
+ if (obj[o]) {
+ hasRepeatedItem = true
+ return
+ }
+ obj[o] = true
+ })
+ if (hasRepeatedItem) {
+ Toast.notify({ type: 'error', message: 'Has repeat items' })
+ return
+ }
+ onConfirm({ type: tempType, value: tempOptions })
+ }
+ }
+
+ return (
+ <Modal
+ title={t('appDebug.variableConig.modalTitle')}
+ isShow={isShow}
+ onClose={onClose}
+ >
+ <div className='mb-8'>
+ <div className='mt-2 mb-8 text-sm text-gray-500'>{t('appDebug.variableConig.description', { varName: `{{${name || key}}}` })}</div>
+ <div className='mb-2'>
+ <div className={s.title}>{t('appDebug.variableConig.fieldType')}</div>
+ <div className='flex space-x-2'>
+ <SelectTypeItem type='string' selected={isStringInput} onClick={handleTypeChange('string')} />
+ <SelectTypeItem type='select' selected={!isStringInput} onClick={handleTypeChange('select')} />
+ </div>
+ </div>
+
+ <div className='mt-6'>
+ <div className={s.title}>{title}</div>
+ {isStringInput ? (
+ <ConfigString value={tempMaxLength} onChange={setTempMaxValue} />
+ ) : (
+ <ConfigSelect options={tempOptions} onChange={setTempOptions} />
+ )}
+ </div>
+
+ </div>
+ <ModalFoot
+ onConfirm={handleConfirm}
+ onCancel={onClose}
+ />
+ </Modal>
+ )
+}
+export default React.memo(ConfigModal)
diff --git a/web/app/components/app/configuration/config-var/config-model/style.module.css b/web/app/components/app/configuration/config-var/config-model/style.module.css
new file mode 100644
index 00000000000..71476af2354
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-model/style.module.css
@@ -0,0 +1,8 @@
+.title {
+ margin-bottom: 8px;
+ font-size: 13px;
+ line-height: 18px;
+ font-weight: 500;
+ color: #101828;
+ text-transform: capitalize;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config-var/config-select/index.tsx b/web/app/components/app/configuration/config-var/config-select/index.tsx
new file mode 100644
index 00000000000..37d3812e118
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-select/index.tsx
@@ -0,0 +1,64 @@
+'use client'
+import React, { FC, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { PlusIcon } from '@heroicons/react/24/outline'
+import RemoveIcon from '../../base/icons/remove-icon'
+
+import s from './style.module.css'
+
+export type Options = string[]
+export interface IConfigSelectProps {
+ options: Options
+ onChange: (options: Options) => void
+}
+
+
+const ConfigSelect: FC<IConfigSelectProps> = ({
+ options,
+ onChange
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div>
+ {options.length > 0 && (
+ <div className='mb-1 space-y-1 '>
+ {options.map((o, index) => (
+ <div className={`${s.inputWrap} relative`}>
+ <input
+ key={index}
+ type="input"
+ value={o || ''}
+ onChange={e => {
+ let value = e.target.value
+ onChange(options.map((item, i) => {
+ if (index === i) {
+ return value
+ }
+ return item
+ }))
+ }}
+ className={`${s.input} w-full px-3 text-sm leading-9 text-gray-900 border-0 grow h-9 bg-transparent focus:outline-none cursor-pointer`}
+ />
+ <RemoveIcon
+ className={`${s.deleteBtn} absolute top-1/2 translate-y-[-50%] right-1.5 items-center justify-center w-6 h-6 rounded-md cursor-pointer hover:bg-[#FEE4E2]`}
+ onClick={() => {
+ onChange(options.filter((_, i) => index !== i))
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div
+ onClick={() => { onChange([...options, '']) }}
+ className='flex items-center h-9 px-3 gap-2 rounded-lg cursor-pointer text-gray-400 bg-gray-100'>
+ <PlusIcon width={16} height={16}></PlusIcon>
+ <div className='text-gray-500 text-[13px]'>{t('appDebug.variableConig.addOption')}</div>
+ </div>
+ </div>
+ )
+}
+
+export default React.memo(ConfigSelect)
diff --git a/web/app/components/app/configuration/config-var/config-select/style.module.css b/web/app/components/app/configuration/config-var/config-select/style.module.css
new file mode 100644
index 00000000000..5d558d89f2e
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-select/style.module.css
@@ -0,0 +1,20 @@
+.inputWrap {
+ border-radius: 8px;
+ border: 1px solid #EAECF0;
+ cursor: pointer;
+}
+
+.deleteBtn {
+ display: none;
+ display: flex;
+}
+
+.inputWrap:hover {
+ border-color: #FEE4E2;
+ background-color: #FFFBFA;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+}
+
+.inputWrap:hover .deleteBtn {
+ display: flex;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config-var/config-string/index.tsx b/web/app/components/app/configuration/config-var/config-string/index.tsx
new file mode 100644
index 00000000000..41ebf651539
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-string/index.tsx
@@ -0,0 +1,38 @@
+'use client'
+import React, { FC, } from 'react'
+
+export interface IConfigStringProps {
+ value: number | undefined
+ onChange: (value: number | undefined) => void
+}
+
+const MAX_LENGTH = 64
+
+const ConfigString: FC<IConfigStringProps> = ({
+ value,
+ onChange,
+}) => {
+
+ return (
+ <div>
+ <input
+ type="number"
+ max={MAX_LENGTH}
+ min={1}
+ value={value || ''}
+ onChange={e => {
+ let value = parseInt(e.target.value, 10)
+ if (value > MAX_LENGTH) {
+ value = MAX_LENGTH
+ } else if (value < 1) {
+ value = 1
+ }
+ onChange(value)
+ }}
+ className="w-full px-3 text-sm leading-9 text-gray-900 border-0 rounded-lg grow h-9 bg-gray-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
+ />
+ </div>
+ )
+}
+
+export default React.memo(ConfigString)
diff --git a/web/app/components/app/configuration/config-var/index.tsx b/web/app/components/app/configuration/config-var/index.tsx
new file mode 100644
index 00000000000..45411cc8a56
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/index.tsx
@@ -0,0 +1,228 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Panel from '../base/feature-panel'
+import Tooltip from '@/app/components/base/tooltip'
+import type { PromptVariable } from '@/models/debug'
+import { Cog8ToothIcon, TrashIcon } from '@heroicons/react/24/outline'
+import { useBoolean } from 'ahooks'
+import EditModel from './config-model'
+import { DEFAULT_VALUE_MAX_LEN, getMaxVarNameLength } from '@/config'
+import { getNewVar } from '@/utils/var'
+import OperationBtn from '../base/operation-btn'
+import Switch from '@/app/components/base/switch'
+import IconTypeIcon from './input-type-icon'
+import { checkKeys } from '@/utils/var'
+import Toast from '@/app/components/base/toast'
+
+import s from './style.module.css'
+import VarIcon from '../base/icons/var-icon'
+
+export type IConfigVarProps = {
+ promptVariables: PromptVariable[]
+ onPromptVariablesChange: (promptVariables: PromptVariable[]) => void
+}
+
+const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, onPromptVariablesChange }) => {
+ const { t } = useTranslation()
+ const hasVar = promptVariables.length > 0
+ const promptVariableObj = (() => {
+ const obj: Record<string, boolean> = {}
+ promptVariables.forEach((item) => {
+ obj[item.key] = true
+ })
+ return obj
+ })()
+
+ const updatePromptVariable = (key: string, updateKey: string, newValue: any) => {
+ if (!(key in promptVariableObj))
+ return
+ const newPromptVariables = promptVariables.map((item) => {
+ if (item.key === key)
+ return {
+ ...item,
+ [updateKey]: newValue
+ }
+
+ return item
+ })
+
+ onPromptVariablesChange(newPromptVariables)
+ }
+
+ const batchUpdatePromptVariable = (key: string, updateKeys: string[], newValues: any[]) => {
+ if (!(key in promptVariableObj))
+ return
+ const newPromptVariables = promptVariables.map((item) => {
+ if (item.key === key) {
+ const newItem: any = { ...item }
+ updateKeys.forEach((updateKey, i) => {
+ newItem[updateKey] = newValues[i]
+ })
+ return newItem
+ }
+
+ return item
+ })
+
+ onPromptVariablesChange(newPromptVariables)
+ }
+
+
+ const updatePromptKey = (index: number, newKey: string) => {
+ const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
+ if (!isValid) {
+ Toast.notify({
+ type: 'error',
+ message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey })
+ })
+ return
+ }
+ const newPromptVariables = promptVariables.map((item, i) => {
+ if (i === index)
+ return {
+ ...item,
+ key: newKey,
+ }
+
+ return item
+ })
+
+ onPromptVariablesChange(newPromptVariables)
+ }
+
+ const updatePromptNameIfNameEmpty = (index: number, newKey: string) => {
+ if (!newKey) return
+ const newPromptVariables = promptVariables.map((item, i) => {
+ if (i === index && !item.name)
+ return {
+ ...item,
+ name: newKey,
+ }
+ return item
+ })
+
+ onPromptVariablesChange(newPromptVariables)
+ }
+
+ const handleAddVar = () => {
+ const newVar = getNewVar('')
+ onPromptVariablesChange([...promptVariables, newVar])
+ }
+
+ const handleRemoveVar = (index: number) => {
+ onPromptVariablesChange(promptVariables.filter((_, i) => i !== index))
+ }
+
+ const [currKey, setCurrKey] = useState<string | null>(null)
+ const currItem = currKey ? promptVariables.find(item => item.key === currKey) : null
+ const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)
+ const handleConfig = (key: string) => {
+ setCurrKey(key)
+ showEditModal()
+ }
+
+ return (
+ <Panel
+ className="mt-4"
+ headerIcon={
+ <VarIcon />
+ }
+ title={
+ <div className='flex items-center gap-2'>
+ <div>{t('appDebug.variableTitle')}</div>
+ <Tooltip htmlContent={<div className='w-[180px]'>
+ {t('appDebug.variableTip')}
+ </div>} selector='config-var-tooltip'>
+ <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.66667 11.1667H8V8.5H7.33333M8 5.83333H8.00667M14 8.5C14 9.28793 13.8448 10.0681 13.5433 10.7961C13.2417 11.5241 12.7998 12.1855 12.2426 12.7426C11.6855 13.2998 11.0241 13.7417 10.2961 14.0433C9.56815 14.3448 8.78793 14.5 8 14.5C7.21207 14.5 6.43185 14.3448 5.7039 14.0433C4.97595 13.7417 4.31451 13.2998 3.75736 12.7426C3.20021 12.1855 2.75825 11.5241 2.45672 10.7961C2.15519 10.0681 2 9.28793 2 8.5C2 6.9087 2.63214 5.38258 3.75736 4.25736C4.88258 3.13214 6.4087 2.5 8 2.5C9.5913 2.5 11.1174 3.13214 12.2426 4.25736C13.3679 5.38258 14 6.9087 14 8.5Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </Tooltip>
+ </div>
+ }
+ headerRight={<OperationBtn type="add" onClick={handleAddVar} />}
+ >
+ {!hasVar && (
+ <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.notSetVar')}</div>
+ )}
+ {hasVar && (
+ <div className='rounded-lg border border-gray-200 bg-white'>
+ <table className={`${s.table} w-full border-collapse border-0 rounded-lg text-sm`}>
+ <thead className="border-b border-gray-200 text-gray-500 text-xs font-medium">
+ <tr className='uppercase'>
+ <td>{t('appDebug.variableTable.key')}</td>
+ <td>{t('appDebug.variableTable.name')}</td>
+ <td>{t('appDebug.variableTable.optional')}</td>
+ <td>{t('appDebug.variableTable.action')}</td>
+ </tr>
+ </thead>
+ <tbody className="text-gray-700">
+ {promptVariables.map(({ key, name, type, required }, index) => (
+ <tr key={index} className="h-9 leading-9">
+ <td className="w-[160px] border-b border-gray-100 pl-3">
+ <div className='flex items-center space-x-1'>
+ <IconTypeIcon type={type} />
+ <input
+ type="text"
+ placeholder="key"
+ value={key}
+ onChange={e => updatePromptKey(index, e.target.value)}
+ onBlur={e => updatePromptNameIfNameEmpty(index, e.target.value)}
+ maxLength={getMaxVarNameLength(name)}
+ className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
+ />
+ </div>
+ </td>
+ <td className="py-1 border-b border-gray-100">
+ <input
+ type="text"
+ placeholder={key}
+ value={name}
+ onChange={e => updatePromptVariable(key, 'name', e.target.value)}
+ maxLength={getMaxVarNameLength(name)}
+ className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
+ />
+ </td>
+ <td className='w-[84px] border-b border-gray-100'>
+ <div className='flex items-center h-full'>
+ <Switch defaultValue={!required} size='md' onChange={(value) => updatePromptVariable(key, 'required', !value)} />
+ </div>
+ </td>
+ <td className='w-20 border-b border-gray-100'>
+ <div className='flex h-full items-center space-x-1'>
+ <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleConfig(key)}>
+ <Cog8ToothIcon width={16} height={16} />
+ </div>
+ <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleRemoveVar(index)} >
+ <TrashIcon width={16} height={16} />
+ </div>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {isShowEditModal && (
+ <EditModel
+ payload={currItem as PromptVariable}
+ isShow={isShowEditModal}
+ onClose={hideEditModal}
+ onConfirm={({ type, value }) => {
+ if (type === 'string') {
+ batchUpdatePromptVariable(currKey as string, ['type', 'max_length'], [type, value || DEFAULT_VALUE_MAX_LEN])
+ } else {
+ batchUpdatePromptVariable(currKey as string, ['type', 'options'], [type, value || []])
+ }
+ hideEditModal()
+ }}
+ />
+ )}
+
+ </Panel>
+ )
+}
+export default React.memo(ConfigVar)
diff --git a/web/app/components/app/configuration/config-var/input-type-icon.tsx b/web/app/components/app/configuration/config-var/input-type-icon.tsx
new file mode 100644
index 00000000000..ff59a48bda2
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/input-type-icon.tsx
@@ -0,0 +1,34 @@
+'use client'
+import React, { FC, ReactNode } from 'react'
+import { ReactElement } from 'react-markdown/lib/react-markdown'
+
+export interface IInputTypeIconProps {
+ type: string
+}
+
+const IconMap = (type: string) => {
+ const icons: Record<string, ReactNode> = {
+ 'string': (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M3.52593 0.166672H8.47411C8.94367 0.166665 9.33123 0.166659 9.64692 0.192452C9.97481 0.219242 10.2762 0.276738 10.5593 0.420991C10.9984 0.644695 11.3553 1.00165 11.579 1.44069C11.7233 1.72381 11.7808 2.02522 11.8076 2.35311C11.8334 2.6688 11.8334 3.05634 11.8334 3.5259V8.47411C11.8334 8.94367 11.8334 9.33121 11.8076 9.6469C11.7808 9.97479 11.7233 10.2762 11.579 10.5593C11.3553 10.9984 10.9984 11.3553 10.5593 11.579C10.2762 11.7233 9.97481 11.7808 9.64692 11.8076C9.33123 11.8334 8.94369 11.8333 8.47413 11.8333H3.52592C3.05636 11.8333 2.66882 11.8334 2.35312 11.8076C2.02523 11.7808 1.72382 11.7233 1.44071 11.579C1.00167 11.3553 0.644711 10.9984 0.421006 10.5593C0.276753 10.2762 0.219257 9.97479 0.192468 9.6469C0.166674 9.33121 0.16668 8.94366 0.166687 8.4741V3.52591C0.16668 3.05635 0.166674 2.6688 0.192468 2.35311C0.219257 2.02522 0.276753 1.72381 0.421006 1.44069C0.644711 1.00165 1.00167 0.644695 1.44071 0.420991C1.72382 0.276738 2.02523 0.219242 2.35312 0.192452C2.66882 0.166659 3.05637 0.166665 3.52593 0.166672ZM3.08335 3.08334C3.08335 2.76117 3.34452 2.50001 3.66669 2.50001H8.33335C8.65552 2.50001 8.91669 2.76117 8.91669 3.08334C8.91669 3.4055 8.65552 3.66667 8.33335 3.66667H6.58335V8.91667C6.58335 9.23884 6.32219 9.5 6.00002 9.5C5.67785 9.5 5.41669 9.23884 5.41669 8.91667V3.66667H3.66669C3.34452 3.66667 3.08335 3.4055 3.08335 3.08334Z" fill="#98A2B3" />
+ </svg>
+ ),
+ 'select': (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M7.48913 4.08334H3.01083C2.70334 4.08333 2.43804 4.08333 2.21955 4.10118C1.98893 4.12002 1.75955 4.16162 1.53883 4.27408C1.20955 4.44186 0.941831 4.70958 0.774053 5.03886C0.66159 5.25958 0.619989 5.48896 0.601147 5.71958C0.583295 5.93807 0.583304 6.20334 0.583313 6.51084V10.9892C0.583304 11.2967 0.583295 11.5619 0.601147 11.7804C0.619989 12.0111 0.66159 12.2404 0.774053 12.4612C0.941831 12.7904 1.20955 13.0582 1.53883 13.2259C1.75955 13.3384 1.98893 13.38 2.21955 13.3988C2.43803 13.4167 2.70329 13.4167 3.01077 13.4167H7.48912C7.7966 13.4167 8.06193 13.4167 8.28041 13.3988C8.51103 13.38 8.74041 13.3384 8.96113 13.2259C9.29041 13.0582 9.55813 12.7904 9.72591 12.4612C9.83837 12.2404 9.87997 12.0111 9.89882 11.7804C9.91667 11.5619 9.91666 11.2967 9.91665 10.9892V6.51087C9.91666 6.20336 9.91667 5.93808 9.89882 5.71958C9.87997 5.48896 9.83837 5.25958 9.72591 5.03886C9.55813 4.70958 9.29041 4.44186 8.96113 4.27408C8.74041 4.16162 8.51103 4.12002 8.28041 4.10118C8.06192 4.08333 7.79663 4.08333 7.48913 4.08334ZM7.70413 7.70416C7.93193 7.47635 7.93193 7.107 7.70413 6.8792C7.47632 6.65139 7.10697 6.65139 6.87917 6.8792L4.66665 9.09172L3.91246 8.33753C3.68465 8.10973 3.31531 8.10973 3.0875 8.33753C2.8597 8.56534 2.8597 8.93468 3.0875 9.16249L4.25417 10.3292C4.48197 10.557 4.85132 10.557 5.07913 10.3292L7.70413 7.70416Z" fill="#98A2B3" />
+ <path d="M10.9891 0.583344H6.51083C6.20334 0.583334 5.93804 0.583326 5.71955 0.601177C5.48893 0.620019 5.25955 0.66162 5.03883 0.774084C4.70955 0.941862 4.44183 1.20958 4.27405 1.53886C4.16159 1.75958 4.11999 1.98896 4.10115 2.21958C4.08514 2.41545 4.08349 2.64892 4.08333 2.91669L7.51382 2.91668C7.79886 2.91662 8.10791 2.91654 8.37541 2.9384C8.67818 2.96314 9.07818 3.02436 9.49078 3.23459C10.0396 3.51422 10.4858 3.96041 10.7654 4.50922C10.9756 4.92182 11.0369 5.32182 11.0616 5.62459C11.0835 5.8921 11.0834 6.20115 11.0833 6.48619L11.0833 9.91666C11.3511 9.9165 11.5845 9.91485 11.7804 9.89885C12.011 9.88 12.2404 9.8384 12.4611 9.72594C12.7904 9.55816 13.0581 9.29045 13.2259 8.96116C13.3384 8.74044 13.38 8.51106 13.3988 8.28044C13.4167 8.06196 13.4167 7.7967 13.4166 7.48922V3.01087C13.4167 2.70339 13.4167 2.43807 13.3988 2.21958C13.38 1.98896 13.3384 1.75958 13.2259 1.53886C13.0581 1.20958 12.7904 0.941862 12.4611 0.774084C12.2404 0.66162 12.011 0.620019 11.7804 0.601177C11.5619 0.583326 11.2966 0.583334 10.9891 0.583344Z" fill="#98A2B3" />
+ </svg>
+ ),
+ }
+
+ return icons[type] as any
+}
+
+const InputTypeIcon: FC<IInputTypeIconProps> = ({
+ type
+}) => {
+ const Icon = IconMap(type)
+ return Icon
+}
+
+export default React.memo(InputTypeIcon)
diff --git a/web/app/components/app/configuration/config-var/modal-foot.tsx b/web/app/components/app/configuration/config-var/modal-foot.tsx
new file mode 100644
index 00000000000..acd8d9b51df
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/modal-foot.tsx
@@ -0,0 +1,23 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+
+export interface IModalFootProps {
+ onConfirm: () => void
+ onCancel: () => void
+}
+
+const ModalFoot: FC<IModalFootProps> = ({
+ onConfirm,
+ onCancel
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div className='flex justify-end gap-2'>
+ <Button onClick={onCancel}>{t('common.operation.cancel')}</Button>
+ <Button type='primary' onClick={onConfirm}>{t('common.operation.save')}</Button>
+ </div>
+ )
+}
+export default React.memo(ModalFoot)
diff --git a/web/app/components/app/configuration/config-var/select-type-item/index.tsx b/web/app/components/app/configuration/config-var/select-type-item/index.tsx
new file mode 100644
index 00000000000..632a3301aae
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/select-type-item/index.tsx
@@ -0,0 +1,61 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import cn from 'classnames'
+
+import s from './style.module.css'
+
+export interface ISelectTypeItemProps {
+ type: string
+ selected: boolean
+ onClick: () => void
+}
+
+const Icon = ({ type, selected }: Partial<ISelectTypeItemProps>) => {
+ switch (type) {
+ case 'select':
+ return selected ? (
+ <svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M8.89233 4.66669H3.77428C3.42285 4.66668 3.11966 4.66667 2.86995 4.68707C2.60639 4.7086 2.34424 4.75615 2.09199 4.88468C1.71567 5.07642 1.4097 5.38238 1.21796 5.75871C1.08943 6.01096 1.04188 6.27311 1.02035 6.53667C0.999949 6.78638 0.999959 7.08954 0.99997 7.44096V12.5591C0.999959 12.9105 0.999949 13.2137 1.02035 13.4634C1.04188 13.7269 1.08943 13.9891 1.21796 14.2413C1.4097 14.6177 1.71567 14.9236 2.09199 15.1154C2.34424 15.2439 2.60639 15.2914 2.86995 15.313C3.11965 15.3334 3.4228 15.3334 3.77421 15.3334H8.89232C9.24372 15.3334 9.54696 15.3334 9.79666 15.313C10.0602 15.2914 10.3224 15.2439 10.5746 15.1154C10.9509 14.9236 11.2569 14.6177 11.4487 14.2413C11.5772 13.9891 11.6247 13.7269 11.6463 13.4634C11.6667 13.2137 11.6667 12.9105 11.6666 12.559V7.44101C11.6667 7.08957 11.6667 6.78639 11.6463 6.53667C11.6247 6.27311 11.5772 6.01096 11.4487 5.75871C11.2569 5.38238 10.9509 5.07642 10.5746 4.88468C10.3224 4.75615 10.0602 4.7086 9.79666 4.68707C9.54695 4.66667 9.24376 4.66668 8.89233 4.66669ZM9.13804 8.80476C9.39839 8.54441 9.39839 8.1223 9.13804 7.86195C8.87769 7.6016 8.45558 7.6016 8.19523 7.86195L5.66664 10.3905L4.80471 9.52862C4.54436 9.26827 4.12225 9.26827 3.8619 9.52862C3.60155 9.78897 3.60155 10.2111 3.8619 10.4714L5.19523 11.8048C5.45558 12.0651 5.87769 12.0651 6.13804 11.8048L9.13804 8.80476Z" fill="#155EEF" />
+ <path d="M12.8923 0.666688H7.77427C7.42285 0.666676 7.11966 0.666666 6.86995 0.687068C6.60639 0.708602 6.34424 0.756146 6.09199 0.884676C5.71567 1.07642 5.40971 1.38238 5.21796 1.75871C5.08943 2.01096 5.04188 2.27311 5.02035 2.53667C5.00206 2.76053 5.00018 3.02734 4.99999 3.33337L8.92055 3.33336C9.2463 3.33329 9.59951 3.3332 9.90523 3.35818C10.2512 3.38645 10.7084 3.45642 11.1799 3.69668C11.8071 4.01626 12.3171 4.5262 12.6367 5.1534C12.8769 5.62495 12.9469 6.08209 12.9752 6.42811C13.0001 6.73384 13.0001 7.08704 13 7.4128L13 11.3333C13.306 11.3332 13.5728 11.3313 13.7967 11.313C14.0602 11.2914 14.3224 11.2439 14.5746 11.1154C14.9509 10.9236 15.2569 10.6177 15.4487 10.2413C15.5772 9.98908 15.6247 9.72694 15.6463 9.46338C15.6667 9.21368 15.6666 8.91052 15.6666 8.55912V3.44101C15.6666 3.0896 15.6667 2.78637 15.6463 2.53667C15.6247 2.27311 15.5772 2.01096 15.4487 1.75871C15.2569 1.38238 14.9509 1.07642 14.5746 0.884676C14.3224 0.756146 14.0602 0.708602 13.7967 0.687068C13.5469 0.666666 13.2438 0.666676 12.8923 0.666688Z" fill="#155EEF" />
+ </svg>
+
+ ) : (
+ <svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M8.89233 4.66667H3.77428C3.42285 4.66666 3.11966 4.66665 2.86995 4.68705C2.60639 4.70859 2.34424 4.75613 2.09199 4.88466C1.71567 5.07641 1.4097 5.38237 1.21796 5.75869C1.08943 6.01095 1.04188 6.27309 1.02035 6.53665C0.999949 6.78636 0.999959 7.08953 0.99997 7.44095V12.559C0.999959 12.9105 0.999949 13.2137 1.02035 13.4634C1.04188 13.7269 1.08943 13.9891 1.21796 14.2413C1.4097 14.6176 1.71567 14.9236 2.09199 15.1154C2.34424 15.2439 2.60639 15.2914 2.86995 15.313C3.11965 15.3334 3.4228 15.3334 3.77421 15.3333H8.89232C9.24372 15.3334 9.54696 15.3334 9.79666 15.313C10.0602 15.2914 10.3224 15.2439 10.5746 15.1154C10.9509 14.9236 11.2569 14.6176 11.4487 14.2413C11.5772 13.9891 11.6247 13.7269 11.6463 13.4634C11.6667 13.2136 11.6667 12.9105 11.6666 12.559V7.44099C11.6667 7.08955 11.6667 6.78637 11.6463 6.53665C11.6247 6.27309 11.5772 6.01095 11.4487 5.75869C11.2569 5.38237 10.9509 5.07641 10.5746 4.88466C10.3224 4.75613 10.0602 4.70859 9.79666 4.68705C9.54695 4.66665 9.24376 4.66666 8.89233 4.66667ZM9.13804 8.80474C9.39839 8.54439 9.39839 8.12228 9.13804 7.86193C8.87769 7.60159 8.45558 7.60159 8.19523 7.86193L5.66664 10.3905L4.80471 9.5286C4.54436 9.26825 4.12225 9.26825 3.8619 9.5286C3.60155 9.78895 3.60155 10.2111 3.8619 10.4714L5.19523 11.8047C5.45558 12.0651 5.87769 12.0651 6.13804 11.8047L9.13804 8.80474Z" fill="#667085" />
+ <path d="M12.8923 0.666672H7.77427C7.42285 0.666661 7.11966 0.666651 6.86995 0.687053C6.60639 0.708587 6.34424 0.756131 6.09199 0.884661C5.71567 1.07641 5.40971 1.38237 5.21796 1.75869C5.08943 2.01095 5.04188 2.27309 5.02035 2.53665C5.00206 2.76051 5.00018 3.02733 4.99999 3.33336L8.92055 3.33335C9.2463 3.33327 9.59951 3.33319 9.90523 3.35816C10.2512 3.38644 10.7084 3.4564 11.1799 3.69667C11.8071 4.01625 12.3171 4.52618 12.6367 5.15339C12.8769 5.62493 12.9469 6.08208 12.9752 6.42809C13.0001 6.73382 13.0001 7.08702 13 7.41279L13 11.3333C13.306 11.3331 13.5728 11.3313 13.7967 11.313C14.0602 11.2914 14.3224 11.2439 14.5746 11.1154C14.9509 10.9236 15.2569 10.6176 15.4487 10.2413C15.5772 9.98907 15.6247 9.72692 15.6463 9.46336C15.6667 9.21366 15.6666 8.91051 15.6666 8.5591V3.44099C15.6666 3.08959 15.6667 2.78635 15.6463 2.53665C15.6247 2.27309 15.5772 2.01095 15.4487 1.75869C15.2569 1.38237 14.9509 1.07641 14.5746 0.884661C14.3224 0.756131 14.0602 0.708587 13.7967 0.687053C13.5469 0.666651 13.2438 0.666661 12.8923 0.666672Z" fill="#667085" />
+ </svg>
+
+ )
+ case 'string':
+ default:
+ return selected ? (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M5.17246 1.33333H10.8275C11.3642 1.33332 11.8071 1.33331 12.1679 1.36279C12.5426 1.39341 12.8871 1.45912 13.2106 1.62398C13.7124 1.87964 14.1203 2.28759 14.376 2.78935C14.5409 3.11291 14.6066 3.45738 14.6372 3.83211C14.6667 4.19291 14.6667 4.63581 14.6667 5.17245V10.8275C14.6667 11.3642 14.6667 11.8071 14.6372 12.1679C14.6066 12.5426 14.5409 12.8871 14.376 13.2106C14.1203 13.7124 13.7124 14.1203 13.2106 14.376C12.8871 14.5409 12.5426 14.6066 12.1679 14.6372C11.8071 14.6667 11.3642 14.6667 10.8275 14.6667H5.17245C4.63581 14.6667 4.1929 14.6667 3.83211 14.6372C3.45738 14.6066 3.11291 14.5409 2.78935 14.376C2.28759 14.1203 1.87964 13.7124 1.62398 13.2106C1.45912 12.8871 1.39341 12.5426 1.36279 12.1679C1.33331 11.8071 1.33332 11.3642 1.33333 10.8275V5.17245C1.33332 4.63581 1.33331 4.1929 1.36279 3.83211C1.39341 3.45738 1.45912 3.11291 1.62398 2.78935C1.87964 2.28759 2.28759 1.87964 2.78935 1.62398C3.11291 1.45912 3.45738 1.39341 3.83211 1.36279C4.1929 1.33331 4.63583 1.33332 5.17246 1.33333ZM4.66666 4.66666C4.66666 4.29847 4.96514 3.99999 5.33333 3.99999H10.6667C11.0349 3.99999 11.3333 4.29847 11.3333 4.66666C11.3333 5.03485 11.0349 5.33333 10.6667 5.33333H8.66666V11.3333C8.66666 11.7015 8.36818 12 7.99999 12C7.6318 12 7.33333 11.7015 7.33333 11.3333V5.33333H5.33333C4.96514 5.33333 4.66666 5.03485 4.66666 4.66666Z" fill="#155EEF" />
+ </svg>
+
+ ) : (<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M5.17246 1.33331H10.8275C11.3642 1.33331 11.8071 1.3333 12.1679 1.36278C12.5426 1.39339 12.8871 1.4591 13.2106 1.62396C13.7124 1.87963 14.1203 2.28757 14.376 2.78934C14.5409 3.1129 14.6066 3.45737 14.6372 3.8321C14.6667 4.19289 14.6667 4.63579 14.6667 5.17243V10.8275C14.6667 11.3642 14.6667 11.8071 14.6372 12.1679C14.6066 12.5426 14.5409 12.8871 14.376 13.2106C14.1203 13.7124 13.7124 14.1203 13.2106 14.376C12.8871 14.5409 12.5426 14.6066 12.1679 14.6372C11.8071 14.6667 11.3642 14.6667 10.8275 14.6666H5.17245C4.63581 14.6667 4.1929 14.6667 3.83211 14.6372C3.45738 14.6066 3.11291 14.5409 2.78935 14.376C2.28759 14.1203 1.87964 13.7124 1.62398 13.2106C1.45912 12.8871 1.39341 12.5426 1.36279 12.1679C1.33331 11.8071 1.33332 11.3642 1.33333 10.8275V5.17244C1.33332 4.6358 1.33331 4.19289 1.36279 3.8321C1.39341 3.45737 1.45912 3.1129 1.62398 2.78934C1.87964 2.28757 2.28759 1.87963 2.78935 1.62396C3.11291 1.4591 3.45738 1.39339 3.83211 1.36278C4.1929 1.3333 4.63583 1.33331 5.17246 1.33331ZM4.66666 4.66665C4.66666 4.29846 4.96514 3.99998 5.33333 3.99998H10.6667C11.0349 3.99998 11.3333 4.29846 11.3333 4.66665C11.3333 5.03484 11.0349 5.33331 10.6667 5.33331H8.66666V11.3333C8.66666 11.7015 8.36818 12 7.99999 12C7.6318 12 7.33333 11.7015 7.33333 11.3333V5.33331H5.33333C4.96514 5.33331 4.66666 5.03484 4.66666 4.66665Z" fill="#667085" />
+ </svg>)
+ }
+}
+
+const SelectTypeItem: FC<ISelectTypeItemProps> = ({
+ type,
+ selected,
+ onClick
+}) => {
+ const { t } = useTranslation()
+ const typeName = t(`appDebug.variableConig.${type}`)
+
+ return (
+ <div
+ className={cn(s.item, selected && s.selected, 'space-x-2')}
+ onClick={onClick}
+ >
+ <Icon type={type} selected={selected} />
+ <span className={cn(s.text)}>{typeName}</span>
+ </div>
+ )
+}
+export default React.memo(SelectTypeItem)
diff --git a/web/app/components/app/configuration/config-var/select-type-item/style.module.css b/web/app/components/app/configuration/config-var/select-type-item/style.module.css
new file mode 100644
index 00000000000..9f3dc278d22
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/select-type-item/style.module.css
@@ -0,0 +1,38 @@
+.item {
+ display: flex;
+ align-items: center;
+ height: 32px;
+ width: 133px;
+ padding-left: 12px;
+ border-radius: 8px;
+ border: 1px solid #EAECF0;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ background-color: #fff;
+ cursor: pointer;
+}
+
+.item:not(.selected):hover {
+ border-color: #B2CCFF;
+ background-color: #F5F8FF;
+ box-shadow: 0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06);
+}
+
+.item.selected {
+ border-color: #528BFF;
+ background-color: #F5F8FF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+.text {
+ font-size: 13px;
+ color: #667085;
+ font-weight: 500;
+}
+
+.item.selected.text {
+ color: #155EEF;
+}
+
+.item:not(.selected):hover {
+ color: #344054;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config-var/style.module.css b/web/app/components/app/configuration/config-var/style.module.css
new file mode 100644
index 00000000000..733755d0c85
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/style.module.css
@@ -0,0 +1,12 @@
+.table td {
+ padding-left: 12px;
+}
+
+.table thead td {
+ height: 33px;
+ line-height: 33px;
+}
+
+.table tbody tr:last-child td {
+ border-bottom: none;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config/feature/add-feature-btn/index.tsx b/web/app/components/app/configuration/config/feature/add-feature-btn/index.tsx
new file mode 100644
index 00000000000..90c9fd9153d
--- /dev/null
+++ b/web/app/components/app/configuration/config/feature/add-feature-btn/index.tsx
@@ -0,0 +1,31 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import { PlusIcon } from '@heroicons/react/24/solid'
+
+export interface IAddFeatureBtnProps {
+ onClick: () => void
+}
+
+const AddFeatureBtn: FC<IAddFeatureBtnProps> = ({
+ onClick
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div
+ className='
+ flex items-center h-8 space-x-2 px-3
+ border border-primary-100 rounded-lg bg-primary-25 hover:bg-primary-50 cursor-pointer
+ text-xs font-semibold text-primary-600 uppercase
+ '
+ style={{
+ boxShadow: '0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06)',
+ }}
+ onClick={onClick}
+ >
+ <PlusIcon className='w-4 h-4 font-semibold' />
+ <div>{t('appDebug.operation.addFeature')}</div>
+ </div>
+ )
+}
+export default React.memo(AddFeatureBtn)
diff --git a/web/app/components/app/configuration/config/feature/choose-feature/feature-item/index.tsx b/web/app/components/app/configuration/config/feature/choose-feature/feature-item/index.tsx
new file mode 100644
index 00000000000..cfb3159e1af
--- /dev/null
+++ b/web/app/components/app/configuration/config/feature/choose-feature/feature-item/index.tsx
@@ -0,0 +1,42 @@
+'use client'
+import React, { FC } from 'react'
+import Switch from '@/app/components/base/switch'
+
+export interface IFeatureItemProps {
+ icon: React.ReactNode
+ title: string
+ description: string
+ value: boolean
+ onChange: (value: boolean) => void
+}
+
+const FeatureItem: FC<IFeatureItemProps> = ({
+ icon,
+ title,
+ description,
+ value,
+ onChange
+}) => {
+ return (
+ <div className='flex justify-between p-3 rounded-xl border border-transparent bg-gray-50 hover:border-gray-200 cursor-pointer'>
+ <div className='flex space-x-3 mr-2'>
+ {/* icon */}
+ <div
+ className='shrink-0 flex items-center justify-center w-8 h-8 rounded-lg border border-gray-200 bg-white'
+ style={{
+ boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.05)',
+ }}
+ >
+ {icon}
+ </div>
+ <div>
+ <div className='text-sm font-semibold text-gray-800'>{title}</div>
+ <div className='text-xs font-normal text-gray-500'>{description}</div>
+ </div>
+ </div>
+
+ <Switch onChange={onChange} defaultValue={value} />
+ </div>
+ )
+}
+export default React.memo(FeatureItem)
diff --git a/web/app/components/app/configuration/config/feature/choose-feature/index.tsx b/web/app/components/app/configuration/config/feature/choose-feature/index.tsx
new file mode 100644
index 00000000000..174104663d5
--- /dev/null
+++ b/web/app/components/app/configuration/config/feature/choose-feature/index.tsx
@@ -0,0 +1,92 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import FeatureItem from './feature-item'
+import FeatureGroup from '../feature-group'
+import MoreLikeThisIcon from '../../../base/icons/more-like-this-icon'
+import SuggestedQuestionsAfterAnswerIcon from '@/app/components/app/configuration/base/icons/suggested-questions-after-answer-icon'
+
+interface IConfig {
+ openingStatement: boolean
+ moreLikeThis: boolean
+ suggestedQuestionsAfterAnswer: boolean
+}
+
+export interface IChooseFeatureProps {
+ isShow: boolean
+ onClose: () => void
+ config: IConfig
+ isChatApp: boolean
+ onChange: (key: string, value: boolean) => void
+}
+
+const OpeningStatementIcon = (
+ <svg width="15" height="13" viewBox="0 0 15 13" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M8.33328 0.333252C4.83548 0.333252 1.99995 3.16878 1.99995 6.66659C1.99995 7.37325 2.11594 8.05419 2.33045 8.6906C2.36818 8.80254 2.39039 8.86877 2.40482 8.91762L2.40955 8.93407L2.40705 8.93928C2.38991 8.97462 2.36444 9.02207 2.31681 9.11025L1.21555 11.1486C1.1473 11.2749 1.07608 11.4066 1.02711 11.5212C0.978424 11.6351 0.899569 11.844 0.938369 12.0916C0.98385 12.3819 1.15471 12.6375 1.40556 12.7905C1.61957 12.9211 1.84276 12.9281 1.96659 12.9267C2.09117 12.9252 2.24012 12.9098 2.3829 12.895L5.81954 12.5397C5.87458 12.534 5.90335 12.5311 5.92443 12.5295L5.92715 12.5293L5.93539 12.5322C5.96129 12.5415 5.99642 12.555 6.05705 12.5784C6.76435 12.8509 7.53219 12.9999 8.33328 12.9999C11.8311 12.9999 14.6666 10.1644 14.6666 6.66659C14.6666 3.16878 11.8311 0.333252 8.33328 0.333252ZM5.97966 4.7214C6.73118 4.08722 7.73139 4.27352 8.3312 4.96609C8.931 4.27352 9.9183 4.09389 10.6827 4.7214C11.4472 5.34892 11.5401 6.41591 10.9499 7.16596C10.5843 7.63065 9.66655 8.47935 9.02117 9.05789C8.78411 9.2704 8.66558 9.37666 8.52332 9.41947C8.40129 9.4562 8.2611 9.4562 8.13907 9.41947C7.99682 9.37666 7.87829 9.2704 7.64122 9.05789C6.99584 8.47935 6.07814 7.63065 5.71251 7.16596C5.12234 6.41591 5.22815 5.35559 5.97966 4.7214Z" fill="#DD2590" />
+ </svg>
+)
+
+const ChooseFeature: FC<IChooseFeatureProps> = ({
+ isShow,
+ onClose,
+ isChatApp,
+ config,
+ onChange
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={onClose}
+ className='w-[400px]'
+ title={t('appDebug.operation.addFeature')}
+ closable
+ >
+ <div className='pt-5 pb-10'>
+ {/* Chat Feature */}
+ {isChatApp && (
+ <FeatureGroup
+ title={t('appDebug.feature.groupChat.title')}
+ description={t('appDebug.feature.groupChat.description') as string}
+ >
+ <>
+ <FeatureItem
+ icon={OpeningStatementIcon}
+ title={t('appDebug.feature.conversationOpener.title')}
+ description={t('appDebug.feature.conversationOpener.description')}
+ value={config.openingStatement}
+ onChange={(value) => onChange('openingStatement', value)}
+ />
+ <FeatureItem
+ icon={<SuggestedQuestionsAfterAnswerIcon />}
+ title={t('appDebug.feature.suggestedQuestionsAfterAnswer.title')}
+ description={t('appDebug.feature.suggestedQuestionsAfterAnswer.description')}
+ value={config.suggestedQuestionsAfterAnswer}
+ onChange={(value) => onChange('suggestedQuestionsAfterAnswer', value)}
+ />
+ </>
+ </FeatureGroup>
+ )}
+
+ {/* Text Generation Feature */}
+ {!isChatApp && (
+ <FeatureGroup title={t('appDebug.feature.groupExperience.title')}>
+ <>
+ <FeatureItem
+ icon={<MoreLikeThisIcon />}
+ title={t('appDebug.feature.moreLikeThis.title')}
+ description={t('appDebug.feature.moreLikeThis.description')}
+ value={config.moreLikeThis}
+ onChange={(value) => onChange('moreLikeThis', value)}
+ />
+ </>
+ </FeatureGroup>
+ )}
+ </div>
+
+ </Modal>
+ )
+}
+export default React.memo(ChooseFeature)
diff --git a/web/app/components/app/configuration/config/feature/feature-group/index.tsx b/web/app/components/app/configuration/config/feature/feature-group/index.tsx
new file mode 100644
index 00000000000..6bbe8511342
--- /dev/null
+++ b/web/app/components/app/configuration/config/feature/feature-group/index.tsx
@@ -0,0 +1,30 @@
+'use client'
+import React, { FC } from 'react'
+import GroupName from '@/app/components/app/configuration/base/group-name'
+
+export interface IFeatureGroupProps {
+ title: string
+ description?: string
+ children: React.ReactNode
+}
+
+const FeatureGroup: FC<IFeatureGroupProps> = ({
+ title,
+ description,
+ children
+}) => {
+ return (
+ <div className='mb-6'>
+ <div className='mb-2'>
+ <GroupName name={title} />
+ {description && (
+ <div className='text-xs font-normal text-gray-500'>{description}</div>
+ )}
+ </div>
+ <div className='space-y-2'>
+ {children}
+ </div>
+ </div>
+ )
+}
+export default React.memo(FeatureGroup)
diff --git a/web/app/components/app/configuration/config/feature/use-feature.tsx b/web/app/components/app/configuration/config/feature/use-feature.tsx
new file mode 100644
index 00000000000..c88f7c8fe57
--- /dev/null
+++ b/web/app/components/app/configuration/config/feature/use-feature.tsx
@@ -0,0 +1,58 @@
+import React, { useEffect } from 'react'
+
+function useFeature({
+ introduction,
+ setIntroduction,
+ moreLikeThis,
+ setMoreLikeThis,
+ suggestedQuestionsAfterAnswer,
+ setSuggestedQuestionsAfterAnswer,
+}: {
+ introduction: string
+ setIntroduction: (introduction: string) => void
+ moreLikeThis: boolean
+ setMoreLikeThis: (moreLikeThis: boolean) => void
+ suggestedQuestionsAfterAnswer: boolean
+ setSuggestedQuestionsAfterAnswer: (suggestedQuestionsAfterAnswer: boolean) => void
+}) {
+ const [tempshowOpeningStatement, setTempShowOpeningStatement] = React.useState(!!introduction)
+ useEffect(() => {
+ // wait to api data back
+ if (!!introduction) {
+ setTempShowOpeningStatement(true)
+ }
+ }, [introduction])
+
+ // const [tempMoreLikeThis, setTempMoreLikeThis] = React.useState(moreLikeThis)
+ // useEffect(() => {
+ // setTempMoreLikeThis(moreLikeThis)
+ // }, [moreLikeThis])
+
+ const featureConfig = {
+ openingStatement: tempshowOpeningStatement,
+ moreLikeThis: moreLikeThis,
+ suggestedQuestionsAfterAnswer: suggestedQuestionsAfterAnswer
+ }
+ const handleFeatureChange = (key: string, value: boolean) => {
+ switch (key) {
+ case 'openingStatement':
+ if (!value) {
+ setIntroduction('')
+ }
+ setTempShowOpeningStatement(value)
+ break
+ case 'moreLikeThis':
+ setMoreLikeThis(value)
+ break
+ case 'suggestedQuestionsAfterAnswer':
+ setSuggestedQuestionsAfterAnswer(value)
+ break
+ }
+ }
+ return {
+ featureConfig,
+ handleFeatureChange
+ }
+}
+
+export default useFeature
\ No newline at end of file
diff --git a/web/app/components/app/configuration/config/index.tsx b/web/app/components/app/configuration/config/index.tsx
new file mode 100644
index 00000000000..4f9e3bcd4c8
--- /dev/null
+++ b/web/app/components/app/configuration/config/index.tsx
@@ -0,0 +1,153 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useContext } from 'use-context-selector'
+import produce from 'immer'
+import AddFeatureBtn from './feature/add-feature-btn'
+import ChooseFeature from './feature/choose-feature'
+import useFeature from './feature/use-feature'
+import ConfigContext from '@/context/debug-configuration'
+import DatasetConfig from '../dataset-config'
+import ChatGroup from '../features/chat-group'
+import ExperienceEnchanceGroup from '../features/experience-enchance-group'
+import Toolbox from '../toolbox'
+import ConfigPrompt from '@/app/components/app/configuration/config-prompt'
+import ConfigVar from '@/app/components/app/configuration/config-var'
+import type { PromptVariable } from '@/models/debug'
+import { AppType } from '@/types/app'
+import { useBoolean } from 'ahooks'
+
+const Config: FC = () => {
+ const {
+ mode,
+ introduction,
+ setIntroduction,
+ modelConfig,
+ setModelConfig,
+ setPrevPromptConfig,
+ setFormattingChanged,
+ moreLikeThisConifg,
+ setMoreLikeThisConifg,
+ suggestedQuestionsAfterAnswerConfig,
+ setSuggestedQuestionsAfterAnswerConfig
+ } = useContext(ConfigContext)
+ const isChatApp = mode === AppType.chat
+
+ const promptTemplate = modelConfig.configs.prompt_template
+ const promptVariables = modelConfig.configs.prompt_variables
+ const handlePromptChange = (newTemplate: string, newVariables: PromptVariable[]) => {
+ const newModelConfig = produce(modelConfig, (draft) => {
+ draft.configs.prompt_template = newTemplate
+ draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...newVariables]
+ })
+
+ if (modelConfig.configs.prompt_template !== newTemplate) {
+ setFormattingChanged(true)
+ }
+
+ setPrevPromptConfig(modelConfig.configs)
+ setModelConfig(newModelConfig)
+ }
+
+ const handlePromptVariablesNameChange = (newVariables: PromptVariable[]) => {
+ setPrevPromptConfig(modelConfig.configs)
+ const newModelConfig = produce(modelConfig, (draft) => {
+ draft.configs.prompt_variables = newVariables
+ })
+ setModelConfig(newModelConfig)
+ }
+
+ const [showChooseFeature, {
+ setTrue: showChooseFeatureTrue,
+ setFalse: showChooseFeatureFalse
+ }] = useBoolean(false)
+ const { featureConfig, handleFeatureChange } = useFeature({
+ introduction,
+ setIntroduction,
+ moreLikeThis: moreLikeThisConifg.enabled,
+ setMoreLikeThis: (value) => {
+ setMoreLikeThisConifg(produce(moreLikeThisConifg, (draft) => {
+ draft.enabled = value
+ }))
+ },
+ suggestedQuestionsAfterAnswer: suggestedQuestionsAfterAnswerConfig.enabled,
+ setSuggestedQuestionsAfterAnswer: (value) => {
+ setSuggestedQuestionsAfterAnswerConfig(produce(suggestedQuestionsAfterAnswerConfig, (draft) => {
+ draft.enabled = value
+ }))
+ },
+ })
+
+ const hasChatConfig = isChatApp && (featureConfig.openingStatement || featureConfig.suggestedQuestionsAfterAnswer)
+ const hasToolbox = false
+
+ return (
+ <>
+ <div className="pb-[20px]">
+ <div className='flex justify-between items-center mb-4'>
+ <AddFeatureBtn onClick={showChooseFeatureTrue} />
+ <div>
+ {/* AutoMatic */}
+ </div>
+ </div>
+
+ {showChooseFeature && (
+ <ChooseFeature
+ isShow={showChooseFeature}
+ onClose={showChooseFeatureFalse}
+ isChatApp={isChatApp}
+ config={featureConfig}
+ onChange={handleFeatureChange}
+ />
+ )}
+ {/* Template */}
+ <ConfigPrompt
+ mode={mode as AppType}
+ promptTemplate={promptTemplate}
+ promptVariables={promptVariables}
+ onChange={handlePromptChange}
+ />
+
+ {/* Variables */}
+ <ConfigVar
+ promptVariables={promptVariables}
+ onPromptVariablesChange={handlePromptVariablesNameChange}
+ />
+
+ {/* Dataset */}
+ <DatasetConfig />
+
+ {/* ChatConifig */}
+ {
+ hasChatConfig && (
+ <ChatGroup
+ isShowOpeningStatement={featureConfig.openingStatement}
+ openingStatementConfig={
+ {
+ promptTemplate,
+ value: introduction,
+ onChange: setIntroduction
+ }
+ }
+ isShowSuggestedQuestionsAfterAnswer={featureConfig.suggestedQuestionsAfterAnswer}
+ />
+ )
+ }
+
+ {/* TextnGeneration config */}
+ {moreLikeThisConifg.enabled && (
+ <ExperienceEnchanceGroup />
+ )}
+
+
+ {/* Toolbox */}
+ {
+ hasToolbox && (
+ <Toolbox searchToolConfig={false} sensitiveWordAvoidanceConifg={false} />
+ )
+ }
+ </div>
+ </>
+ )
+}
+export default React.memo(Config)
diff --git a/web/app/components/app/configuration/ctrl-btn-group/index.tsx b/web/app/components/app/configuration/ctrl-btn-group/index.tsx
new file mode 100644
index 00000000000..d7b5d49b0e7
--- /dev/null
+++ b/web/app/components/app/configuration/ctrl-btn-group/index.tsx
@@ -0,0 +1,24 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import s from './style.module.css'
+import Button from '@/app/components/base/button'
+
+export type IContrlBtnGroupProps = {
+ onSave: () => void
+ onReset: () => void
+}
+
+const ContrlBtnGroup: FC<IContrlBtnGroupProps> = ({ onSave, onReset }) => {
+ const { t } = useTranslation()
+ return (
+ <div className="fixed left-[224px] bottom-0 w-[519px] h-[64px]">
+ <div className={`${s.ctrlBtn} flex items-center h-full pl-4 gap-2 bg-white`}>
+ <Button type='primary' onClick={onSave}>{t('appDebug.operation.applyConfig')}</Button>
+ <Button type='default' onClick={onReset}>{t('appDebug.operation.resetConfig')}</Button>
+ </div>
+ </div>
+ )
+}
+export default React.memo(ContrlBtnGroup)
diff --git a/web/app/components/app/configuration/ctrl-btn-group/style.module.css b/web/app/components/app/configuration/ctrl-btn-group/style.module.css
new file mode 100644
index 00000000000..c7250b8f96f
--- /dev/null
+++ b/web/app/components/app/configuration/ctrl-btn-group/style.module.css
@@ -0,0 +1,6 @@
+.ctrlBtn {
+ left: -16px;
+ right: -16px;
+ bottom: -16px;
+ border-top: 1px solid #F3F4F6;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/dataset-config/card-item/index.tsx b/web/app/components/app/configuration/dataset-config/card-item/index.tsx
new file mode 100644
index 00000000000..88d3716ce63
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/card-item/index.tsx
@@ -0,0 +1,51 @@
+'use client'
+import React, { FC } from 'react'
+import cn from 'classnames'
+import TypeIcon from '../type-icon'
+import { useTranslation } from 'react-i18next'
+import { formatNumber } from '@/utils/format'
+import RemoveIcon from '../../base/icons/remove-icon'
+import s from './style.module.css'
+
+export interface ICardItemProps {
+ className?: string
+ config: any
+ onRemove: (id: string) => void
+}
+
+
+
+// const RemoveIcon = ({ className, onClick }: { className: string, onClick: () => void }) => (
+// <svg className={className} onClick={onClick} width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+// <path d="M10 6H14M6 8H18M16.6667 8L16.1991 15.0129C16.129 16.065 16.0939 16.5911 15.8667 16.99C15.6666 17.3412 15.3648 17.6235 15.0011 17.7998C14.588 18 14.0607 18 13.0062 18H10.9938C9.93927 18 9.41202 18 8.99889 17.7998C8.63517 17.6235 8.33339 17.3412 8.13332 16.99C7.90607 16.5911 7.871 16.065 7.80086 15.0129L7.33333 8M10.6667 11V14.3333M13.3333 11V14.3333" stroke="#667085" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+// </svg>
+// )
+
+const CardItem: FC<ICardItemProps> = ({
+ className,
+ config,
+ onRemove
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div
+ className={
+ cn(className, s.card,
+ 'flex items-center justify-between rounded-xl px-3 py-2.5 bg-white border border-gray-200 cursor-pointer')
+ }>
+ <div className='shrink-0 flex items-center space-x-2'>
+ <TypeIcon type="upload_file" />
+ <div>
+ <div className='w-[160px] text-[13px] leading-[18px] font-medium text-gray-800 overflow-hidden text-ellipsis whitespace-nowrap'>{config.name}</div>
+ <div className='flex text-xs text-gray-500'>
+ {formatNumber(config.word_count)} {t('appDebug.feature.dataSet.words')} · {formatNumber(config.document_count)} {t('appDebug.feature.dataSet.textBlocks')}
+ </div>
+ </div>
+ </div>
+
+ <RemoveIcon className={`${s.deleteBtn} shrink-0`} onClick={() => onRemove(config.id)} />
+ </div>
+ )
+}
+export default React.memo(CardItem)
diff --git a/web/app/components/app/configuration/dataset-config/card-item/style.module.css b/web/app/components/app/configuration/dataset-config/card-item/style.module.css
new file mode 100644
index 00000000000..def8bf8d66f
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/card-item/style.module.css
@@ -0,0 +1,16 @@
+.card {
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ width: calc(50% - 4px);
+}
+
+.card:hover {
+ box-shadow: 0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06);
+}
+
+.deleteBtn {
+ display: none;
+}
+
+.card:hover .deleteBtn {
+ display: block;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/dataset-config/index.tsx b/web/app/components/app/configuration/dataset-config/index.tsx
new file mode 100644
index 00000000000..46207ca3964
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/index.tsx
@@ -0,0 +1,79 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import ConfigContext from '@/context/debug-configuration'
+import FeaturePanel from '../base/feature-panel'
+import OperationBtn from '../base/operation-btn'
+import CardItem from './card-item'
+import { useBoolean } from 'ahooks'
+import SelectDataSet from './select-dataset'
+import { DataSet } from '@/models/datasets'
+import { isEqual } from 'lodash-es'
+
+const Icon = (
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M12.6667 5.34368C12.6667 5.32614 12.6667 5.31738 12.6659 5.30147C12.6502 4.97229 12.3607 4.68295 12.0315 4.66737C12.0156 4.66662 12.0104 4.66662 12 4.66663H9.8391C9.30248 4.66662 8.85957 4.66661 8.49878 4.69609C8.12405 4.72671 7.77958 4.79242 7.45603 4.95728C6.95426 5.21294 6.54631 5.62089 6.29065 6.12265C6.12579 6.44621 6.06008 6.79068 6.02946 7.16541C5.99999 7.5262 5.99999 7.96911 6 8.50574V15.4942C5.99999 16.0308 5.99999 16.4737 6.02946 16.8345C6.06008 17.2092 6.12579 17.5537 6.29065 17.8773C6.54631 18.379 6.95426 18.787 7.45603 19.0426C7.77958 19.2075 8.12405 19.2732 8.49878 19.3038C8.85958 19.3333 9.30248 19.3333 9.83912 19.3333H14.1609C14.6975 19.3333 15.1404 19.3333 15.5012 19.3038C15.8759 19.2732 16.2204 19.2075 16.544 19.0426C17.0457 18.787 17.4537 18.379 17.7093 17.8773C17.8742 17.5537 17.9399 17.2092 17.9705 16.8345C18 16.4737 18 16.0308 18 15.4942V10.6666C18 10.6562 18 10.6511 17.9993 10.6352C17.9837 10.306 17.6943 10.0164 17.3651 10.0007C17.3492 9.99997 17.3405 9.99997 17.323 9.99997L14.3787 9.99997C14.2105 9.99999 14.0466 10 13.9078 9.98867C13.7555 9.97622 13.5756 9.94684 13.3947 9.85464C13.1438 9.72681 12.9398 9.52284 12.812 9.27195C12.7198 9.09101 12.6904 8.91118 12.678 8.75879C12.6666 8.62001 12.6666 8.45615 12.6667 8.2879L12.6667 5.34368ZM9.33333 12.6666C8.96514 12.6666 8.66667 12.9651 8.66667 13.3333C8.66667 13.7015 8.96514 14 9.33333 14H14.6667C15.0349 14 15.3333 13.7015 15.3333 13.3333C15.3333 12.9651 15.0349 12.6666 14.6667 12.6666H9.33333ZM9.33333 15.3333C8.96514 15.3333 8.66667 15.6318 8.66667 16C8.66667 16.3681 8.96514 16.6666 9.33333 16.6666H13.3333C13.7015 16.6666 14 16.3681 14 16C14 15.6318 13.7015 15.3333 13.3333 15.3333H9.33333Z" fill="#6938EF" />
+ <path d="M16.6053 8.66662C16.8011 8.66662 16.8989 8.66663 16.9791 8.61747C17.0923 8.54806 17.16 8.38452 17.129 8.25538C17.107 8.16394 17.0432 8.10018 16.9155 7.97265L14.694 5.75111C14.5664 5.62345 14.5027 5.55962 14.4112 5.53764C14.2821 5.5066 14.1186 5.57429 14.0492 5.68752C14 5.7677 14 5.86557 14 6.06132L14 8.13327C14 8.31994 14 8.41328 14.0363 8.48459C14.0683 8.54731 14.1193 8.5983 14.182 8.63026C14.2533 8.66659 14.3466 8.66659 14.5333 8.66659L16.6053 8.66662Z" fill="#6938EF" />
+ </svg>
+)
+
+const DatasetConfig: FC = () => {
+ const { t } = useTranslation()
+ const {
+ dataSets: dataSet,
+ setDataSets: setDataSet,
+ setFormattingChanged
+ } = useContext(ConfigContext)
+ const selectedIds = dataSet.map((item) => item.id)
+
+ const hasData = dataSet.length > 0
+ const [isShowSelectDataSet, { setTrue: showSelectDataSet, setFalse: hideSelectDataSet }] = useBoolean(false)
+ const handleSelect = (data: DataSet[]) => {
+ if (isEqual(data, dataSet)) {
+ hideSelectDataSet()
+ }
+ setFormattingChanged(true)
+ setDataSet(data)
+ hideSelectDataSet()
+ }
+ const onRemove = (id: string) => {
+ setDataSet(dataSet.filter((item) => item.id !== id))
+ }
+
+
+ return (
+ <FeaturePanel
+ className='mt-3'
+ headerIcon={Icon}
+ title={t('appDebug.feature.dataSet.title')}
+ headerRight={<OperationBtn type="add" onClick={showSelectDataSet} />}
+ hasHeaderBottomBorder={!hasData}
+ >
+ {hasData ? (
+ <div className='flex flex-wrap justify-between'>
+ {dataSet.map((item) => (
+ <CardItem
+ className="mb-2"
+ key={item.id}
+ config={item}
+ onRemove={onRemove}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.feature.dataSet.noData')}</div>
+ )}
+
+ {isShowSelectDataSet && (
+ <SelectDataSet
+ isShow={isShowSelectDataSet}
+ onClose={hideSelectDataSet}
+ selectedIds={selectedIds}
+ onSelect={handleSelect}
+ />
+ )}
+ </FeaturePanel>
+ )
+}
+export default React.memo(DatasetConfig)
diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx
new file mode 100644
index 00000000000..78c219bfc53
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx
@@ -0,0 +1,130 @@
+'use client'
+import React, { FC, useEffect } from 'react'
+import cn from 'classnames'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import { DataSet } from '@/models/datasets'
+import TypeIcon from '../type-icon'
+import Button from '@/app/components/base/button'
+import { fetchDatasets } from '@/service/datasets'
+import Loading from '@/app/components/base/loading'
+import { formatNumber } from '@/utils/format'
+import Link from 'next/link'
+
+import s from './style.module.css'
+import Toast from '@/app/components/base/toast'
+
+export interface ISelectDataSetProps {
+ isShow: boolean
+ onClose: () => void
+ selectedIds: string[]
+ onSelect: (dataSet: DataSet[]) => void
+}
+
+const SelectDataSet: FC<ISelectDataSetProps> = ({
+ isShow,
+ onClose,
+ selectedIds,
+ onSelect,
+}) => {
+ const { t } = useTranslation()
+ const [selected, setSelected] = React.useState<DataSet[]>([])
+ const [loaded, setLoaded] = React.useState(false)
+ const [datasets, setDataSets] = React.useState<DataSet[] | null>(null)
+ const hasNoData = !datasets || datasets?.length === 0
+ // Only one dataset can be selected. Historical data retains data and supports multiple selections, but when saving, only one can be selected. This is based on considerations of performance and accuracy.
+ const canSelectMulti = selectedIds.length > 1
+ useEffect(() => {
+ (async () => {
+ const { data } = await fetchDatasets({ url: '/datasets', params: { page: 1 } })
+ setDataSets(data)
+ setLoaded(true)
+ setSelected(data.filter((item) => selectedIds.includes(item.id)))
+ })()
+ }, [])
+ const toggleSelect = (dataSet: DataSet) => {
+ const isSelected = selected.some((item) => item.id === dataSet.id)
+ if (isSelected) {
+ setSelected(selected.filter((item) => item.id !== dataSet.id))
+ }
+ else {
+ if (canSelectMulti) {
+ setSelected([...selected, dataSet])
+ } else {
+ setSelected([dataSet])
+ }
+ }
+ }
+
+ const handleSelect = () => {
+ if (selected.length > 1) {
+ Toast.notify({
+ type: 'error',
+ message: t('appDebug.feature.dataSet.notSupportSelectMulti')
+ })
+ return
+ }
+ onSelect(selected)
+ }
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={onClose}
+ className='w-[400px]'
+ title={t('appDebug.feature.dataSet.selectTitle')}
+ >
+ {!loaded && (
+ <div className='flex h-[200px]'>
+ <Loading type='area' />
+ </div>
+ )}
+
+ {(loaded && hasNoData) && (
+ <div className='flex items-center justify-center mt-6 rounded-lg space-x-1 h-[128px] text-[13px] border'
+ style={{
+ background: 'rgba(0, 0, 0, 0.02)',
+ borderColor: 'rgba(0, 0, 0, 0.02'
+ }}
+ >
+ <span className='text-gray-500'>{t('appDebug.feature.dataSet.noDataSet')}</span>
+ <Link href="/datasets/create" className='font-normal text-[#155EEF]'>{t('appDebug.feature.dataSet.toCreate')}</Link>
+ </div>
+ )}
+
+ {datasets && datasets?.length > 0 && (
+ <>
+ <div className='mt-7 space-y-1 max-h-[286px] overflow-y-auto'>
+ {datasets.map((item) => (
+ <div
+ key={item.id}
+ className={cn(s.item, selected.some(i => i.id === item.id) && s.selected, 'flex justify-between items-center h-10 px-2 rounded-lg bg-white border border-gray-200 cursor-pointer')}
+ onClick={() => toggleSelect(item)}
+ >
+ <div className='flex items-center space-x-2'>
+ <TypeIcon type="upload_file" size='md' />
+ <div className='max-w-[200px] text-[13px] font-medium text-gray-800 overflow-hidden text-ellipsis whitespace-nowrap'>{item.name}</div>
+ </div>
+
+ <div className='max-w-[140px] flex text-xs text-gray-500 overflow-hidden text-ellipsis whitespace-nowrap'>
+ {formatNumber(item.word_count)} {t('appDebug.feature.dataSet.words')} · {formatNumber(item.document_count)} {t('appDebug.feature.dataSet.textBlocks')}
+ </div>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ {loaded && (
+ <div className='flex justify-between items-center mt-8'>
+ <div className='text-sm font-medium text-gray-700'>
+ {selected.length > 0 && `${selected.length} ${t('appDebug.feature.dataSet.selected')}`}
+ </div>
+ <div className='flex space-x-2'>
+ <Button className='!w-24 !h-9' onClick={onClose}>{t('common.operation.cancel')}</Button>
+ <Button className='!w-24 !h-9' type='primary' onClick={handleSelect} disabled={hasNoData}>{t('common.operation.add')}</Button>
+ </div>
+ </div>
+ )}
+ </Modal>
+ )
+}
+export default React.memo(SelectDataSet)
diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/style.module.css b/web/app/components/app/configuration/dataset-config/select-dataset/style.module.css
new file mode 100644
index 00000000000..9c73b882981
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/select-dataset/style.module.css
@@ -0,0 +1,9 @@
+.item {
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+}
+
+.item:hover,
+.item.selected {
+ background: #F5F8FF;
+ border-color: #528BFF;
+}
\ No newline at end of file
diff --git a/web/app/components/app/configuration/dataset-config/type-icon/index.tsx b/web/app/components/app/configuration/dataset-config/type-icon/index.tsx
new file mode 100644
index 00000000000..9bebea6127f
--- /dev/null
+++ b/web/app/components/app/configuration/dataset-config/type-icon/index.tsx
@@ -0,0 +1,33 @@
+'use client'
+import React, { FC } from 'react'
+
+export interface ITypeIconProps {
+ type: 'upload_file'
+ size?: 'md' | 'lg'
+}
+
+// data_source_type: current only support upload_file
+const Icon = ({ type, size = "lg" }: ITypeIconProps) => {
+ const len = size === "lg" ? 32 : 24
+ const iconMap = {
+ upload_file: (
+ <svg width={len} height={len} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="0.25" y="0.25" width="31.5" height="31.5" rx="7.75" fill="#F5F8FF" />
+ <path fillRule="evenodd" clipRule="evenodd" d="M8.66669 12.1078C8.66668 11.7564 8.66667 11.4532 8.68707 11.2035C8.7086 10.9399 8.75615 10.6778 8.88468 10.4255C9.07642 10.0492 9.38238 9.74322 9.75871 9.55147C10.011 9.42294 10.2731 9.3754 10.5367 9.35387C10.7864 9.33346 11.0896 9.33347 11.441 9.33349L14.0978 9.33341C14.4935 9.33289 14.8415 9.33243 15.1615 9.4428C15.4417 9.53946 15.697 9.69722 15.9087 9.90465C16.1506 10.1415 16.3058 10.4529 16.4823 10.8071L17.0786 12H19.4942C20.0309 12 20.4738 12 20.8346 12.0295C21.2093 12.0601 21.5538 12.1258 21.8773 12.2907C22.3791 12.5463 22.787 12.9543 23.0427 13.456C23.2076 13.7796 23.2733 14.1241 23.3039 14.4988C23.3334 14.8596 23.3334 15.3025 23.3334 15.8391V18.8276C23.3334 19.3642 23.3334 19.8071 23.3039 20.1679C23.2733 20.5426 23.2076 20.8871 23.0427 21.2107C22.787 21.7124 22.3791 22.1204 21.8773 22.376C21.5538 22.5409 21.2093 22.6066 20.8346 22.6372C20.4738 22.6667 20.0309 22.6667 19.4942 22.6667H12.5058C11.9692 22.6667 11.5263 22.6667 11.1655 22.6372C10.7907 22.6066 10.4463 22.5409 10.1227 22.376C9.62095 22.1204 9.213 21.7124 8.95734 21.2107C8.79248 20.8871 8.72677 20.5426 8.69615 20.1679C8.66667 19.8071 8.66668 19.3642 8.66669 18.8276V12.1078ZM14.0149 10.6668C14.5418 10.6668 14.6463 10.6755 14.7267 10.7033C14.8201 10.7355 14.9052 10.7881 14.9758 10.8572C15.0366 10.9167 15.0911 11.0063 15.3267 11.4776L15.5879 12L10.0001 12C10.0004 11.69 10.0024 11.4781 10.016 11.312C10.0308 11.1309 10.0559 11.0638 10.0727 11.0308C10.1366 10.9054 10.2386 10.8034 10.364 10.7395C10.397 10.7227 10.4641 10.6976 10.6452 10.6828C10.8341 10.6673 11.0823 10.6668 11.4667 10.6668H14.0149Z" fill="#444CE7" />
+ <rect x="0.25" y="0.25" width="31.5" height="31.5" rx="7.75" stroke="#E0EAFF" strokeWidth="0.5" />
+ </svg>
+ )
+ }
+ return iconMap[type]
+
+}
+
+const TypeIcon: FC<ITypeIconProps> = ({
+ type,
+ size = 'lg',
+}) => {
+ return (
+ <Icon type={type} size={size} ></Icon>
+ )
+}
+export default React.memo(TypeIcon)
diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsx
new file mode 100644
index 00000000000..c7ac2738866
--- /dev/null
+++ b/web/app/components/app/configuration/debug/index.tsx
@@ -0,0 +1,417 @@
+'use client'
+import type { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import React, { useEffect, useState, useRef } from 'react'
+import cn from 'classnames'
+import produce from 'immer'
+import { useBoolean, useGetState } from 'ahooks'
+import { useContext } from 'use-context-selector'
+import { AppType } from '@/types/app'
+import PromptValuePanel, { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
+import type { IChatItem } from '@/app/components/app/chat'
+import Chat from '@/app/components/app/chat'
+import ConfigContext from '@/context/debug-configuration'
+import { ToastContext } from '@/app/components/base/toast'
+import { sendChatMessage, sendCompletionMessage, fetchSuggestedQuestions, fetchConvesationMessages } from '@/service/debug'
+import Button from '@/app/components/base/button'
+import type { ModelConfig as BackendModelConfig } from '@/types/app'
+import { promptVariablesToUserInputsForm } from '@/utils/model-config'
+import HasNotSetAPIKEY from '../base/warning-mask/has-not-set-api'
+import FormattingChanged from '../base/warning-mask/formatting-changed'
+import TextGeneration from '@/app/components/app/text-generate/item'
+import GroupName from '../base/group-name'
+import dayjs from 'dayjs'
+import { IS_CE_EDITION } from '@/config'
+
+interface IDebug {
+ hasSetAPIKEY: boolean
+ onSetting: () => void
+}
+
+const Debug: FC<IDebug> = ({
+ hasSetAPIKEY = true,
+ onSetting
+}) => {
+ const { t } = useTranslation()
+ const {
+ appId,
+ mode,
+ introduction,
+ suggestedQuestionsAfterAnswerConfig,
+ moreLikeThisConifg,
+ inputs,
+ // setInputs,
+ formattingChanged,
+ setFormattingChanged,
+ conversationId,
+ setConversationId,
+ controlClearChatMessage,
+ dataSets,
+ modelConfig,
+ completionParams,
+ } = useContext(ConfigContext)
+
+
+ const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
+ const chatListDomRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ // scroll to bottom
+ if (chatListDomRef.current) {
+ chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
+ }
+ }, [chatList])
+
+ const getIntroduction = () => replaceStringWithValues(introduction, modelConfig.configs.prompt_variables, inputs)
+ useEffect(() => {
+ if (introduction && !chatList.some(item => !item.isAnswer)) {
+ setChatList([{
+ id: `${Date.now()}`,
+ content: getIntroduction(),
+ isAnswer: true,
+ isOpeningStatement: true
+ }])
+ }
+ }, [introduction, modelConfig.configs.prompt_variables, inputs])
+
+ const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
+ const [abortController, setAbortController] = useState<AbortController | null>(null)
+ const [isShowFormattingChangeConfirm, setIsShowFormattingChangeConfirm] = useState(false)
+
+ useEffect(() => {
+ if (formattingChanged && chatList.some(item => !item.isAnswer)) {
+ setIsShowFormattingChangeConfirm(true)
+ }
+ setFormattingChanged(false)
+ }, [formattingChanged])
+
+ const clearConversation = () => {
+ setConversationId(null)
+ abortController?.abort()
+ setResponsingFalse()
+ setChatList(introduction ? [{
+ id: `${Date.now()}`,
+ content: getIntroduction(),
+ isAnswer: true,
+ isOpeningStatement: true
+ }] : [])
+ setIsShowSuggestion(false)
+ }
+
+ const handleConfirm = () => {
+ clearConversation()
+ setIsShowFormattingChangeConfirm(false)
+ }
+
+ const handleCancel = () => {
+ setIsShowFormattingChangeConfirm(false)
+ }
+
+ const { notify } = useContext(ToastContext)
+ const logError = (message: string) => {
+ notify({ type: 'error', message })
+ }
+
+ const checkCanSend = () => {
+ let hasEmptyInput = false
+ const requiredVars = modelConfig.configs.prompt_variables.filter(({ key, name, required }) => {
+ const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
+ return res
+ }) // compatible with old version
+ // debugger
+ requiredVars.forEach(({ key }) => {
+ if (hasEmptyInput) {
+ return
+ }
+ if (!inputs[key]) {
+ hasEmptyInput = true
+ }
+ })
+
+ if (hasEmptyInput) {
+ logError(t('appDebug.errorMessage.valueOfVarRequired'))
+ return false
+ }
+ return !hasEmptyInput
+ }
+
+ const [isShowSuggestion, setIsShowSuggestion] = useState(false)
+ const doShowSuggestion = isShowSuggestion && !isResponsing
+ const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
+ const onSend = async (message: string) => {
+ if (isResponsing) {
+ notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
+ return false
+ }
+
+ const postDatasets = dataSets.map(({ id }) => ({
+ dataset: {
+ enabled: true,
+ id,
+ }
+ }))
+
+ const postModelConfig: BackendModelConfig = {
+ pre_prompt: modelConfig.configs.prompt_template,
+ user_input_form: promptVariablesToUserInputsForm(modelConfig.configs.prompt_variables),
+ opening_statement: introduction,
+ more_like_this: {
+ enabled: false
+ },
+ suggested_questions_after_answer: suggestedQuestionsAfterAnswerConfig,
+ agent_mode: {
+ enabled: true,
+ tools: [...postDatasets]
+ },
+ model: {
+ provider: modelConfig.provider,
+ name: modelConfig.model_id,
+ completion_params: completionParams as any
+ },
+ }
+
+ const data = {
+ conversation_id: conversationId,
+ inputs,
+ query: message,
+ model_config: postModelConfig,
+ }
+
+ // qustion
+ const questionId = `question-${Date.now()}`
+ const questionItem = {
+ id: questionId,
+ content: message,
+ isAnswer: false,
+ }
+
+ const placeholderAnswerId = `answer-placeholder-${Date.now()}`
+ const placeholderAnswerItem = {
+ id: placeholderAnswerId,
+ content: '',
+ isAnswer: true,
+ }
+
+ const newList = [...getChatList(), questionItem, placeholderAnswerItem]
+ setChatList(newList)
+
+ // answer
+ const responseItem = {
+ id: `${Date.now()}`,
+ content: '',
+ isAnswer: true,
+ }
+
+ let _newConversationId: null | string = null
+
+ setResponsingTrue()
+ setIsShowSuggestion(false)
+ sendChatMessage(appId, data, {
+ getAbortController: (abortController) => {
+ setAbortController(abortController)
+ },
+ onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId }: any) => {
+ responseItem.content = responseItem.content + message
+ if (isFirstMessage && newConversationId) {
+ setConversationId(newConversationId)
+ _newConversationId = newConversationId
+ }
+ if (messageId) {
+ responseItem.id = messageId
+ }
+ // closesure new list is outdated.
+ const newListWithAnswer = produce(
+ getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
+ (draft) => {
+ if (!draft.find(item => item.id === questionId)) {
+ draft.push({ ...questionItem })
+ }
+ draft.push({ ...responseItem })
+ })
+ setChatList(newListWithAnswer)
+ },
+ async onCompleted(hasError?: boolean) {
+ setResponsingFalse()
+ if (hasError) {
+ return
+ }
+ if (_newConversationId) {
+ const { data }: any = await fetchConvesationMessages(appId, _newConversationId as string)
+ const newResponseItem = data.find((item: any) => item.id === responseItem.id)
+ if (!newResponseItem) {
+ return
+ }
+ setChatList(produce(getChatList(), draft => {
+ const index = draft.findIndex(item => item.id === responseItem.id)
+ if (index !== -1) {
+ draft[index] = {
+ ...draft[index],
+ more: {
+ time: dayjs.unix(newResponseItem.created_at).format('hh:mm A'),
+ tokens: newResponseItem.answer_tokens,
+ latency: (newResponseItem.provider_response_latency / 1000).toFixed(2),
+ }
+ }
+ }
+ }))
+ }
+ if (suggestedQuestionsAfterAnswerConfig.enabled) {
+ const { data }: any = await fetchSuggestedQuestions(appId, responseItem.id)
+ setSuggestQuestions(data)
+ setIsShowSuggestion(true)
+ }
+ },
+ onError() {
+ setResponsingFalse()
+ // role back placeholder answer
+ setChatList(produce(getChatList(), draft => {
+ draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
+ }))
+ }
+ })
+ return true
+ }
+
+ useEffect(() => {
+ if (controlClearChatMessage)
+ setChatList([])
+ }, [controlClearChatMessage])
+
+ const [completionQuery, setCompletionQuery] = useState('')
+ const [completionRes, setCompletionRes] = useState(``)
+
+ const sendTextCompletion = async () => {
+ if (isResponsing) {
+ notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
+ return false
+ }
+
+ if (!checkCanSend())
+ return
+
+ if (!completionQuery) {
+ logError(t('appDebug.errorMessage.queryRequired'))
+ return false
+ }
+
+ const postDatasets = dataSets.map(({ id }) => ({
+ dataset: {
+ enabled: true,
+ id,
+ }
+ }))
+
+ const postModelConfig: BackendModelConfig = {
+ pre_prompt: modelConfig.configs.prompt_template,
+ user_input_form: promptVariablesToUserInputsForm(modelConfig.configs.prompt_variables),
+ opening_statement: introduction,
+ suggested_questions_after_answer: suggestedQuestionsAfterAnswerConfig,
+ more_like_this: moreLikeThisConifg,
+ agent_mode: {
+ enabled: true,
+ tools: [...postDatasets]
+ },
+ model: {
+ provider: modelConfig.provider,
+ name: modelConfig.model_id,
+ completion_params: completionParams as any
+ },
+ }
+
+
+ const data = {
+ inputs,
+ query: completionQuery,
+ model_config: postModelConfig,
+ }
+
+ setCompletionRes('')
+ const res: string[] = []
+
+ setResponsingTrue()
+ sendCompletionMessage(appId, data, {
+ onData: (data: string) => {
+ res.push(data)
+ setCompletionRes(res.join(''))
+ },
+ onCompleted() {
+ setResponsingFalse()
+ },
+ onError() {
+ setResponsingFalse()
+ }
+ })
+ }
+
+
+ return (
+ <>
+ <div className="shrink-0">
+ <div className='flex items-center justify-between mb-2'>
+ <div className='h2 '>{t('appDebug.inputs.title')}</div>
+ {mode === 'chat' && (
+ <Button className='flex items-center gap-1 !h-8 !bg-white' onClick={clearConversation}>
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M2.66663 2.66629V5.99963H3.05463M3.05463 5.99963C3.49719 4.90505 4.29041 3.98823 5.30998 3.39287C6.32954 2.7975 7.51783 2.55724 8.68861 2.70972C9.85938 2.8622 10.9465 3.39882 11.7795 4.23548C12.6126 5.07213 13.1445 6.16154 13.292 7.33296M3.05463 5.99963H5.99996M13.3333 13.333V9.99963H12.946M12.946 9.99963C12.5028 11.0936 11.7093 12.0097 10.6898 12.6045C9.67038 13.1993 8.48245 13.4393 7.31203 13.2869C6.1416 13.1344 5.05476 12.5982 4.22165 11.7621C3.38854 10.926 2.8562 9.83726 2.70796 8.66629M12.946 9.99963H9.99996" stroke="#1C64F2" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ <span className='text-primary-600 text-[13px] font-semibold'>{t('common.operation.refresh')}</span>
+ </Button>
+ )}
+ </div>
+ <PromptValuePanel
+ appType={mode as AppType}
+ value={completionQuery}
+ onChange={setCompletionQuery}
+ onSend={sendTextCompletion}
+ />
+ </div>
+ <div className="flex flex-col grow">
+ {/* Chat */}
+ {mode === AppType.chat && (
+ <div className="mt-[34px] h-full flex flex-col">
+ <div className={cn(doShowSuggestion ? 'pb-[140px]' : 'pb-[66px]', "relative mt-1.5 grow h-[200px] overflow-hidden")}>
+ <div className="h-full overflow-y-auto" ref={chatListDomRef}>
+ {/* {JSON.stringify(chatList)} */}
+ <Chat
+ chatList={chatList}
+ onSend={onSend}
+ checkCanSend={checkCanSend}
+ feedbackDisabled
+ useCurrentUserAvatar
+ isResponsing={isResponsing}
+ abortResponsing={() => {
+ abortController?.abort()
+ setResponsingFalse()
+ }}
+ isShowSuggestion={doShowSuggestion}
+ suggestionList={suggestQuestions}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ {/* Text Generation */}
+ {mode === AppType.completion && (
+ <div className="mt-6">
+ <GroupName name={t('appDebug.result')} />
+ {(completionRes || isResponsing) && (
+ <TextGeneration
+ className="mt-2"
+ content={completionRes}
+ isLoading={!completionRes && isResponsing}
+ />
+ )}
+ </div>
+ )}
+ {isShowFormattingChangeConfirm && (
+ <FormattingChanged
+ onConfirm={handleConfirm}
+ onCancel={handleCancel}
+ />
+ )}
+ </div>
+
+ {!hasSetAPIKEY && (<HasNotSetAPIKEY isTrailFinished={!IS_CE_EDITION} onSetting={onSetting} />)}
+ </>
+ )
+}
+export default React.memo(Debug)
diff --git a/web/app/components/app/configuration/features/chat-group/index.tsx b/web/app/components/app/configuration/features/chat-group/index.tsx
new file mode 100644
index 00000000000..774137edb18
--- /dev/null
+++ b/web/app/components/app/configuration/features/chat-group/index.tsx
@@ -0,0 +1,40 @@
+'use client'
+import React, { FC } from 'react'
+import GroupName from '../../base/group-name'
+import OpeningStatement, { IOpeningStatementProps } from './opening-statement'
+import SuggestedQuestionsAfterAnswer from './suggested-questions-after-answer'
+import { useTranslation } from 'react-i18next'
+
+/*
+* Include
+* 1. Conversation Opener
+* 2. Opening Suggestion
+* 3. Next question suggestion
+*/
+interface ChatGroupProps {
+ isShowOpeningStatement: boolean
+ openingStatementConfig: IOpeningStatementProps
+ isShowSuggestedQuestionsAfterAnswer: boolean
+}
+const ChatGroup: FC<ChatGroupProps> = ({
+ isShowOpeningStatement,
+ openingStatementConfig,
+ isShowSuggestedQuestionsAfterAnswer
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className='mt-7'>
+ <GroupName name={t('appDebug.feature.groupChat.title')} />
+ <div className='space-y-3'>
+ {isShowOpeningStatement && (
+ <OpeningStatement {...openingStatementConfig} />
+ )}
+ {isShowSuggestedQuestionsAfterAnswer && (
+ <SuggestedQuestionsAfterAnswer />
+ )}
+ </div>
+ </div>
+ )
+}
+export default React.memo(ChatGroup)
diff --git a/web/app/components/app/configuration/features/chat-group/opening-statement/index.tsx b/web/app/components/app/configuration/features/chat-group/opening-statement/index.tsx
new file mode 100644
index 00000000000..3feacd22abf
--- /dev/null
+++ b/web/app/components/app/configuration/features/chat-group/opening-statement/index.tsx
@@ -0,0 +1,177 @@
+'use client'
+import React, { FC, useEffect, useRef, useState } from 'react'
+import cn from 'classnames'
+import { useContext } from 'use-context-selector'
+import ConfigContext from '@/context/debug-configuration'
+import produce from 'immer'
+import { useTranslation } from 'react-i18next'
+import { useBoolean } from 'ahooks'
+import Panel from '@/app/components/app/configuration/base/feature-panel'
+import Button from '@/app/components/base/button'
+import OperationBtn from '@/app/components/app/configuration/base/operation-btn'
+import { getInputKeys } from '@/app/components/base/block-input'
+import ConfirmAddVar from '@/app/components/app/configuration/config-prompt/confirm-add-var'
+import { getNewVar } from '@/utils/var'
+import { varHighlightHTML } from '@/app/components/app/configuration/base/var-highlight'
+
+export interface IOpeningStatementProps {
+ promptTemplate: string
+ value: string
+ onChange: (value: string) => void
+}
+
+// regex to match the {{}} and replace it with a span
+const regex = /\{\{([^}]+)\}\}/g
+
+const OpeningStatement: FC<IOpeningStatementProps> = ({
+ value = '',
+ onChange
+}) => {
+ const { t } = useTranslation()
+ const {
+ modelConfig,
+ setModelConfig,
+ } = useContext(ConfigContext)
+ const promptVariables = modelConfig.configs.prompt_variables
+ const [notIncludeKeys, setNotIncludeKeys] = useState<string[]>([])
+
+ const hasValue = !!(value || '').trim()
+ const inputRef = useRef<HTMLTextAreaElement>(null)
+
+ const [isFocus, { setTrue: didSetFocus, setFalse: setBlur }] = useBoolean(false)
+ const setFocus = () => {
+ didSetFocus()
+ setTimeout(() => {
+ const input = inputRef.current
+ if (input) {
+ input.focus()
+ input.setSelectionRange(input.value.length, input.value.length)
+ }
+ }, 0)
+ }
+
+ const [tempValue, setTempValue] = useState(value)
+ useEffect(() => {
+ setTempValue(value || '')
+ }, [value])
+
+ const coloredContent = (tempValue || '')
+ .replace(regex, varHighlightHTML({ name: '$1' })) // `<span class="${highLightClassName}">{{$1}}</span>`
+ .replace(/\n/g, '<br />')
+
+
+ const handleEdit = () => {
+ setFocus()
+ }
+
+ const [isShowConfirmAddVar, { setTrue: showConfirmAddVar, setFalse: hideConfirmAddVar }] = useBoolean(false)
+
+ const handleCancel = () => {
+ setBlur()
+ setTempValue(value)
+ }
+
+ const handleConfirm = () => {
+ const keys = getInputKeys(tempValue)
+ const promptKeys = promptVariables.map((item) => item.key)
+ let notIncludeKeys: string[] = []
+
+ if (promptKeys.length === 0) {
+ if (keys.length > 0) {
+ notIncludeKeys = keys
+ }
+ } else {
+ notIncludeKeys = keys.filter((key) => !promptKeys.includes(key))
+ }
+
+ if (notIncludeKeys.length > 0) {
+ setNotIncludeKeys(notIncludeKeys)
+ showConfirmAddVar()
+ return
+ }
+ setBlur()
+ onChange(tempValue)
+ }
+
+ const cancelAutoAddVar = () => {
+ onChange(tempValue)
+ hideConfirmAddVar()
+ setBlur()
+ }
+
+ const autoAddVar = () => {
+ const newModelConfig = produce(modelConfig, (draft) => {
+ draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...notIncludeKeys.map((key) => getNewVar(key))]
+ })
+ onChange(tempValue)
+ setModelConfig(newModelConfig)
+ hideConfirmAddVar()
+ setBlur()
+ }
+
+ const headerRight = (
+ <OperationBtn type='edit' actionName={hasValue ? '' : t('appDebug.openingStatement.writeOpner') as string} onClick={handleEdit} />
+ )
+
+ return (
+ <Panel
+ className={cn(isShowConfirmAddVar && 'h-[220px]', 'relative mt-4')}
+ title={t('appDebug.openingStatement.title')}
+ headerIcon={
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M8.33353 1.33301C4.83572 1.33301 2.00019 4.16854 2.00019 7.66634C2.00019 8.37301 2.11619 9.05395 2.3307 9.69036C2.36843 9.80229 2.39063 9.86853 2.40507 9.91738L2.40979 9.93383L2.40729 9.93903C2.39015 9.97437 2.36469 10.0218 2.31705 10.11L1.2158 12.1484C1.14755 12.2746 1.07633 12.4064 1.02735 12.5209C0.978668 12.6348 0.899813 12.8437 0.938613 13.0914C0.984094 13.3817 1.15495 13.6373 1.40581 13.7903C1.61981 13.9208 1.843 13.9279 1.96683 13.9264C2.09141 13.925 2.24036 13.9095 2.38314 13.8947L5.81978 13.5395C5.87482 13.5338 5.9036 13.5309 5.92468 13.5292L5.92739 13.529L5.93564 13.532C5.96154 13.5413 5.99666 13.5548 6.0573 13.5781C6.76459 13.8506 7.53244 13.9997 8.33353 13.9997C11.8313 13.9997 14.6669 11.1641 14.6669 7.66634C14.6669 4.16854 11.8313 1.33301 8.33353 1.33301ZM5.9799 5.72116C6.73142 5.08698 7.73164 5.27327 8.33144 5.96584C8.93125 5.27327 9.91854 5.09365 10.683 5.72116C11.4474 6.34867 11.5403 7.41567 10.9501 8.16572C10.5845 8.6304 9.6668 9.47911 9.02142 10.0576C8.78435 10.2702 8.66582 10.3764 8.52357 10.4192C8.40154 10.456 8.26134 10.456 8.13931 10.4192C7.99706 10.3764 7.87853 10.2702 7.64147 10.0576C6.99609 9.47911 6.07839 8.6304 5.71276 8.16572C5.12259 7.41567 5.22839 6.35534 5.9799 5.72116Z" fill="#E74694" />
+ </svg>
+ }
+ headerRight={headerRight}
+ hasHeaderBottomBorder={!hasValue}
+ isFocus={isFocus}
+ >
+ <div className='text-gray-700 text-sm'>
+ {(hasValue || (!hasValue && isFocus)) ? (
+ <>
+ {isFocus ? (
+ <textarea
+ ref={inputRef}
+ value={tempValue}
+ rows={3}
+ onChange={e => setTempValue(e.target.value)}
+ className="w-full px-0 text-sm border-0 bg-transparent focus:outline-none "
+ placeholder={t('appDebug.openingStatement.placeholder') as string}
+ >
+ </textarea>
+ ) : (
+ <div dangerouslySetInnerHTML={{
+ __html: coloredContent
+ }}></div>
+ )}
+
+ {/* Operation Bar */}
+ {isFocus && (
+ <div className='mt-2 flex items-center justify-between'>
+ <div className='text-xs text-gray-500'>{t('appDebug.openingStatement.varTip')}</div>
+
+ <div className='flex gap-2'>
+ <Button className='!h-8 text-sm' onClick={handleCancel}>{t('common.operation.cancel')}</Button>
+ <Button className='!h-8 text-sm' onClick={handleConfirm} type="primary">{t('common.operation.save')}</Button>
+ </div>
+ </div>
+ )}
+
+ </>) : (
+ <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.openingStatement.noDataPlaceHolder')}</div>
+ )}
+
+ {isShowConfirmAddVar && (
+ <ConfirmAddVar
+ varNameArr={notIncludeKeys}
+ onConfrim={autoAddVar}
+ onCancel={cancelAutoAddVar}
+ onHide={hideConfirmAddVar}
+ />
+ )}
+
+ </div>
+ </Panel>
+ )
+}
+export default React.memo(OpeningStatement)
diff --git a/web/app/components/app/configuration/features/chat-group/suggested-questions-after-answer/index.tsx b/web/app/components/app/configuration/features/chat-group/suggested-questions-after-answer/index.tsx
new file mode 100644
index 00000000000..0c5b8cf4db1
--- /dev/null
+++ b/web/app/components/app/configuration/features/chat-group/suggested-questions-after-answer/index.tsx
@@ -0,0 +1,33 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import Panel from '@/app/components/app/configuration/base/feature-panel'
+import SuggestedQuestionsAfterAnswerIcon from '@/app/components/app/configuration/base/icons/suggested-questions-after-answer-icon'
+import Tooltip from '@/app/components/base/tooltip'
+
+const SuggestedQuestionsAfterAnswer: FC = () => {
+ const { t } = useTranslation()
+
+ return (
+ <Panel
+ title={
+ <div className='flex items-center gap-2'>
+ <div>{t('appDebug.feature.suggestedQuestionsAfterAnswer.title')}</div>
+ <Tooltip htmlContent={<div className='w-[180px]'>
+ {t('appDebug.feature.suggestedQuestionsAfterAnswer.description')}
+ </div>} selector='suggestion-question-tooltip'>
+ <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M8.66667 11.1667H8V8.5H7.33333M8 5.83333H8.00667M14 8.5C14 9.28793 13.8448 10.0681 13.5433 10.7961C13.2417 11.5241 12.7998 12.1855 12.2426 12.7426C11.6855 13.2998 11.0241 13.7417 10.2961 14.0433C9.56815 14.3448 8.78793 14.5 8 14.5C7.21207 14.5 6.43185 14.3448 5.7039 14.0433C4.97595 13.7417 4.31451 13.2998 3.75736 12.7426C3.20021 12.1855 2.75825 11.5241 2.45672 10.7961C2.15519 10.0681 2 9.28793 2 8.5C2 6.9087 2.63214 5.38258 3.75736 4.25736C4.88258 3.13214 6.4087 2.5 8 2.5C9.5913 2.5 11.1174 3.13214 12.2426 4.25736C13.3679 5.38258 14 6.9087 14 8.5Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </Tooltip>
+ </div>
+ }
+ headerIcon={<SuggestedQuestionsAfterAnswerIcon />}
+ headerRight={
+ <div className='text-xs text-gray-500'>{t('appDebug.feature.suggestedQuestionsAfterAnswer.resDes')}</div>
+ }
+ noBodySpacing
+ />
+ )
+}
+export default React.memo(SuggestedQuestionsAfterAnswer)
diff --git a/web/app/components/app/configuration/features/experience-enchance-group/index.tsx b/web/app/components/app/configuration/features/experience-enchance-group/index.tsx
new file mode 100644
index 00000000000..0c898cbee4e
--- /dev/null
+++ b/web/app/components/app/configuration/features/experience-enchance-group/index.tsx
@@ -0,0 +1,21 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import GroupName from '../../base/group-name'
+import MoreLikeThis from './more-like-this'
+
+/*
+* Include
+* 1. More like this
+*/
+const ExperienceEnchanceGroup: FC = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className='mt-7'>
+ <GroupName name={t('appDebug.feature.groupExperience.title')} />
+ <MoreLikeThis />
+ </div>
+ )
+}
+export default React.memo(ExperienceEnchanceGroup)
diff --git a/web/app/components/app/configuration/features/experience-enchance-group/more-like-this/index.tsx b/web/app/components/app/configuration/features/experience-enchance-group/more-like-this/index.tsx
new file mode 100644
index 00000000000..91d77fee141
--- /dev/null
+++ b/web/app/components/app/configuration/features/experience-enchance-group/more-like-this/index.tsx
@@ -0,0 +1,50 @@
+'use client'
+import React, { FC } from 'react'
+import Panel from '@/app/components/app/configuration/base/feature-panel'
+import { useTranslation } from 'react-i18next'
+import MoreLikeThisIcon from '../../../base/icons/more-like-this-icon'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+import { useLocalStorageState } from 'ahooks'
+
+const GENERATE_NUM = 1
+
+const warningIcon = (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M6.40616 0.834307C6.14751 0.719294 5.85222 0.719294 5.59356 0.834307C5.3938 0.923133 5.26403 1.07959 5.17373 1.20708C5.08495 1.33242 4.9899 1.49664 4.88536 1.67723L0.751783 8.81705C0.646828 8.9983 0.551451 9.16302 0.486781 9.3028C0.421056 9.44487 0.349754 9.63584 0.372478 9.85381C0.401884 10.1359 0.549654 10.3922 0.779012 10.5589C0.956259 10.6878 1.15726 10.7218 1.31314 10.7361C1.46651 10.7501 1.65684 10.7501 1.86628 10.7501H10.1334C10.3429 10.7501 10.5332 10.7501 10.6866 10.7361C10.8425 10.7218 11.0435 10.6878 11.2207 10.5589C11.4501 10.3922 11.5978 10.1359 11.6272 9.85381C11.65 9.63584 11.5787 9.44487 11.5129 9.3028C11.4483 9.16303 11.3529 8.99833 11.248 8.81709L7.11436 1.67722C7.00983 1.49663 6.91477 1.33242 6.82599 1.20708C6.73569 1.07959 6.60593 0.923133 6.40616 0.834307ZM6.49988 4.50012C6.49988 4.22398 6.27602 4.00012 5.99988 4.00012C5.72374 4.00012 5.49988 4.22398 5.49988 4.50012V6.50012C5.49988 6.77626 5.72374 7.00012 5.99988 7.00012C6.27602 7.00012 6.49988 6.77626 6.49988 6.50012V4.50012ZM5.99988 8.00012C5.72374 8.00012 5.49988 8.22398 5.49988 8.50012C5.49988 8.77626 5.72374 9.00012 5.99988 9.00012H6.00488C6.28102 9.00012 6.50488 8.77626 6.50488 8.50012C6.50488 8.22398 6.28102 8.00012 6.00488 8.00012H5.99988Z" fill="#F79009" />
+ </svg>
+
+)
+const MoreLikeThis: FC = () => {
+ const { t } = useTranslation()
+
+ const [isHideTip, setIsHideTip] = useLocalStorageState('isHideMoreLikeThisTip', {
+ defaultValue: false,
+ })
+
+ const headerRight = (
+ <div className='text-xs text-gray-500'>{t('appDebug.feature.moreLikeThis.generateNumTip')} {GENERATE_NUM}</div>
+ )
+ return (
+ <Panel
+ className='mt-4'
+ title={t('appDebug.feature.moreLikeThis.title')}
+ headerIcon={<MoreLikeThisIcon />}
+ headerRight={headerRight}
+ noBodySpacing
+ >
+ {!isHideTip && (
+ <div className='flex justify-between items-center h-9 px-3 rounded-b-xl bg-[#FFFAEB] text-xs text-gray-700'>
+ <div className='flex items-center space-x-2'>
+ <div>{warningIcon}</div>
+ <div>{t('appDebug.feature.moreLikeThis.tip')}</div>
+ </div>
+ <div className='flex items-center justify-center w-4 h-4 cursor-pointer' onClick={() => setIsHideTip(true)}>
+ <XMarkIcon className="w-3 h-3" />
+ </div>
+ </div>
+ )}
+
+ </Panel>
+ )
+}
+export default React.memo(MoreLikeThis)
diff --git a/web/app/components/app/configuration/index.tsx b/web/app/components/app/configuration/index.tsx
new file mode 100644
index 00000000000..03bea3f3168
--- /dev/null
+++ b/web/app/components/app/configuration/index.tsx
@@ -0,0 +1,317 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import { usePathname } from 'next/navigation'
+import produce from 'immer'
+import type { CompletionParams, Inputs, ModelConfig, PromptConfig, PromptVariable, MoreLikeThisConfig } from '@/models/debug'
+import type { DataSet } from '@/models/datasets'
+import type { ModelConfig as BackendModelConfig } from '@/types/app'
+import ConfigContext from '@/context/debug-configuration'
+import ConfigModel from '@/app/components/app/configuration/config-model'
+import Config from '@/app/components/app/configuration/config'
+import Debug from '@/app/components/app/configuration/debug'
+import Confirm from '@/app/components/base/confirm'
+import type { AppDetailResponse } from '@/models/app'
+import { ToastContext } from '@/app/components/base/toast'
+import { fetchTenantInfo } from '@/service/common'
+import { fetchAppDetail, updateAppModelConfig } from '@/service/apps'
+import { userInputsFormToPromptVariables, promptVariablesToUserInputsForm } from '@/utils/model-config'
+import { fetchDatasets } from '@/service/datasets'
+import AccountSetting from '@/app/components/header/account-setting'
+import { useBoolean } from 'ahooks'
+import Button from '../../base/button'
+import Loading from '../../base/loading'
+
+const Configuration: FC = () => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+
+ const [hasFetchedDetail, setHasFetchedDetail] = useState(false)
+ const [hasFetchedKey, setHasFetchedKey] = useState(false)
+ const isLoading = !hasFetchedDetail || !hasFetchedKey
+ const pathname = usePathname()
+ const matched = pathname.match(/\/app\/([^/]+)/)
+ const appId = (matched?.length && matched[1]) ? matched[1] : ''
+ const [mode, setMode] = useState('')
+ const [pusblisedConfig, setPusblisedConfig] = useState<{
+ modelConfig: ModelConfig,
+ completionParams: CompletionParams
+ } | null>(null)
+
+ const [conversationId, setConversationId] = useState<string | null>('')
+ const [introduction, setIntroduction] = useState<string>('')
+ const [controlClearChatMessage, setControlClearChatMessage] = useState(0)
+ const [prevPromptConfig, setPrevPromptConfig] = useState<PromptConfig>({
+ prompt_template: '',
+ prompt_variables: [],
+ })
+ const [moreLikeThisConifg, setMoreLikeThisConifg] = useState<MoreLikeThisConfig>({
+ enabled: false,
+ })
+ const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<MoreLikeThisConfig>({
+ enabled: false,
+ })
+ const [formattingChanged, setFormattingChanged] = useState(false)
+ const [inputs, setInputs] = useState<Inputs>({})
+ const [query, setQuery] = useState('')
+ const [completionParams, setCompletionParams] = useState<CompletionParams>({
+ max_tokens: 16,
+ temperature: 1, // 0-2
+ top_p: 1,
+ presence_penalty: 1, // -2-2
+ frequency_penalty: 1, // -2-2
+ })
+ const [modelConfig, doSetModelConfig] = useState<ModelConfig>({
+ provider: 'openai',
+ model_id: 'gpt-3.5-turbo',
+ configs: {
+ prompt_template: '',
+ prompt_variables: [] as PromptVariable[],
+ },
+ })
+
+ const setModelConfig = (newModelConfig: ModelConfig) => {
+ doSetModelConfig(newModelConfig)
+ }
+
+ const setModelId = (modelId: string) => {
+ const newModelConfig = produce(modelConfig, (draft) => {
+ draft.model_id = modelId
+ })
+ setModelConfig(newModelConfig)
+ }
+
+ const syncToPublishedConfig = (_pusblisedConfig: any) => {
+ setModelConfig(_pusblisedConfig.modelConfig)
+ setCompletionParams(_pusblisedConfig.completionParams)
+ }
+
+ const [dataSets, setDataSets] = useState<DataSet[]>([])
+
+ const [hasSetCustomAPIKEY, setHasSetCustomerAPIKEY] = useState(true)
+ const [isTrailFinished, setIsTrailFinished] = useState(false)
+ const hasSetAPIKEY = hasSetCustomAPIKEY || !isTrailFinished
+
+ const [isShowSetAPIKey, { setTrue: showSetAPIKey, setFalse: hideSetAPIkey }] = useBoolean()
+
+ const checkAPIKey = async () => {
+ const { in_trail, trial_end_reason } = await fetchTenantInfo({ url: '/info' })
+ const isTrailFinished = in_trail && trial_end_reason === 'trial_exceeded'
+ const hasSetCustomAPIKEY = trial_end_reason === 'using_custom'
+ setHasSetCustomerAPIKEY(hasSetCustomAPIKEY)
+ setIsTrailFinished(isTrailFinished)
+ setHasFetchedKey(true)
+ }
+
+ useEffect(() => {
+ checkAPIKey()
+ }, [])
+
+ useEffect(() => {
+ (fetchAppDetail({ url: '/apps', id: appId }) as any).then(async (res: AppDetailResponse) => {
+ setMode(res.mode)
+ const modelConfig = res.model_config
+ const model = res.model_config.model
+
+ let datasets: any = null
+ if (modelConfig.agent_mode?.enabled) {
+ datasets = modelConfig.agent_mode?.tools.filter(({ dataset }: any) => dataset?.enabled)
+ }
+
+ if (dataSets && datasets?.length && datasets?.length > 0) {
+ const { data: dataSetsWithDetail } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: datasets.map(({ dataset }: any) => dataset.id) } })
+ datasets = dataSetsWithDetail
+ setDataSets(datasets)
+ }
+ const config = {
+ modelConfig: {
+ provider: model.provider,
+ model_id: model.name,
+ configs: {
+ prompt_template: modelConfig.pre_prompt,
+ prompt_variables: userInputsFormToPromptVariables(modelConfig.user_input_form)
+ },
+ },
+ completionParams: model.completion_params,
+ }
+ syncToPublishedConfig(config)
+ setPusblisedConfig(config)
+ setIntroduction(modelConfig.opening_statement)
+ if (modelConfig.more_like_this) {
+ setMoreLikeThisConifg(modelConfig.more_like_this)
+ }
+ if (modelConfig.suggested_questions_after_answer) {
+ setSuggestedQuestionsAfterAnswerConfig(modelConfig.suggested_questions_after_answer)
+ }
+ setHasFetchedDetail(true)
+ })
+ }, [appId])
+
+ const saveAppConfig = async () => {
+ const modelId = modelConfig.model_id
+ const promptTemplate = modelConfig.configs.prompt_template
+ const promptVariables = modelConfig.configs.prompt_variables
+
+ // not save empty key adn name
+ // const missingNameItem = promptVariables.find(item => item.name.trim() === '')
+ // if (missingNameItem) {
+ // notify({ type: 'error', message: t('appDebug.errorMessage.nameOfKeyRequired', { key: missingNameItem.key }) })
+ // return
+ // }
+
+ const postDatasets = dataSets.map(({ id }) => ({
+ dataset: {
+ enabled: true,
+ id,
+ }
+ }))
+
+ // new model config data struct
+ const data: BackendModelConfig = {
+ pre_prompt: promptTemplate,
+ user_input_form: promptVariablesToUserInputsForm(promptVariables),
+ opening_statement: introduction || '',
+ more_like_this: moreLikeThisConifg,
+ suggested_questions_after_answer: suggestedQuestionsAfterAnswerConfig,
+ agent_mode: {
+ enabled: true,
+ tools: [...postDatasets]
+ },
+ model: {
+ provider: modelConfig.provider,
+ name: modelId,
+ completion_params: completionParams as any,
+ },
+ }
+
+ await updateAppModelConfig({ url: `/apps/${appId}/model-config`, body: data })
+ setPusblisedConfig({
+ modelConfig,
+ completionParams,
+ })
+ notify({ type: 'success', message: t('common.api.success'), duration: 3000 })
+ }
+
+ const [showConfirm, setShowConfirm] = useState(false)
+ const resetAppConfig = () => {
+ // debugger
+ syncToPublishedConfig(pusblisedConfig)
+ setShowConfirm(false)
+ }
+
+ const [showUseGPT4Confirm, setShowUseGPT4Confirm] = useState(false)
+ const [showSetAPIKeyModal, setShowSetAPIKeyModal] = useState(false)
+
+ if (isLoading) {
+ return <div className='flex h-full items-center justify-center'>
+ <Loading type='area' />
+ </div>
+ }
+
+ return (
+ <ConfigContext.Provider value={{
+ appId,
+ hasSetAPIKEY,
+ isTrailFinished,
+ mode,
+ conversationId,
+ introduction,
+ setIntroduction,
+ setConversationId,
+ controlClearChatMessage,
+ setControlClearChatMessage,
+ prevPromptConfig,
+ setPrevPromptConfig,
+ moreLikeThisConifg,
+ setMoreLikeThisConifg,
+ suggestedQuestionsAfterAnswerConfig,
+ setSuggestedQuestionsAfterAnswerConfig,
+ formattingChanged,
+ setFormattingChanged,
+ inputs,
+ setInputs,
+ query,
+ setQuery,
+ completionParams,
+ setCompletionParams,
+ modelConfig,
+ setModelConfig,
+ dataSets,
+ setDataSets
+ }}
+ >
+ <>
+ <div className="flex flex-col h-full">
+ <div className='flex items-center justify-between px-6 border-b shrink-0 h-14 boder-gray-100'>
+ <div className='text-xl text-gray-900'>{t('appDebug.pageTitle')}</div>
+ <div className='flex items-center'>
+ {/* Model and Parameters */}
+ <ConfigModel
+ mode={mode}
+ completionParams={completionParams}
+ modelId={modelConfig.model_id}
+ setModelId={setModelId}
+ onCompletionParamsChange={(newParams: CompletionParams) => {
+ setCompletionParams(newParams)
+ }}
+ disabled={!hasSetAPIKEY}
+ canUseGPT4={hasSetCustomAPIKEY}
+ onShowUseGPT4Confirm={() => {
+ setShowUseGPT4Confirm(true)
+ }}
+ />
+ <div className='mx-3 w-[1px] h-[14px] bg-gray-200'></div>
+ <Button onClick={() => setShowConfirm(true)} className='shrink-0 mr-2 w-[70px] !h-8 !text-[13px] font-medium'>{t('appDebug.operation.resetConfig')}</Button>
+ <Button type='primary' onClick={saveAppConfig} className='shrink-0 w-[70px] !h-8 !text-[13px] font-medium'>{t('appDebug.operation.applyConfig')}</Button>
+ </div>
+ </div>
+ <div className='flex grow h-[200px]'>
+ <div className="w-[574px] shrink-0 h-full overflow-y-auto border-r border-gray-100 py-4 px-6">
+ <Config />
+ </div>
+ <div className="relative grow h-full overflow-y-auto py-4 px-6 bg-gray-50 flex flex-col">
+ <Debug hasSetAPIKEY={hasSetAPIKEY} onSetting={showSetAPIKey} />
+ </div>
+ </div>
+ </div>
+ {showConfirm && (
+ <Confirm
+ title={t('appDebug.resetConfig.title')}
+ content={t('appDebug.resetConfig.message')}
+ isShow={showConfirm}
+ onClose={() => setShowConfirm(false)}
+ onConfirm={resetAppConfig}
+ onCancel={() => setShowConfirm(false)}
+ />
+ )}
+ {showUseGPT4Confirm && (
+ <Confirm
+ title={t('appDebug.trailUseGPT4Info.title')}
+ content={t('appDebug.trailUseGPT4Info.description')}
+ isShow={showUseGPT4Confirm}
+ onClose={() => setShowUseGPT4Confirm(false)}
+ onConfirm={() => {
+ setShowSetAPIKeyModal(true)
+ setShowUseGPT4Confirm(false)
+ }}
+ onCancel={() => setShowUseGPT4Confirm(false)}
+ />
+ )}
+ {
+ showSetAPIKeyModal && (
+ <AccountSetting activeTab="provider" onCancel={async () => {
+ setShowSetAPIKeyModal(false)
+ }} />
+ )
+ }
+ {isShowSetAPIKey && <AccountSetting activeTab="provider" onCancel={async () => {
+ await checkAPIKey()
+ hideSetAPIkey()
+ }} />}
+ </>
+ </ConfigContext.Provider>
+ )
+}
+export default React.memo(Configuration)
diff --git a/web/app/components/app/configuration/prompt-value-panel/index.tsx b/web/app/components/app/configuration/prompt-value-panel/index.tsx
new file mode 100644
index 00000000000..b86094556ce
--- /dev/null
+++ b/web/app/components/app/configuration/prompt-value-panel/index.tsx
@@ -0,0 +1,210 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import {
+ PlayIcon,
+} from '@heroicons/react/24/solid'
+import ConfigContext from '@/context/debug-configuration'
+import type { PromptVariable } from '@/models/debug'
+import { AppType } from '@/types/app'
+import Select from '@/app/components/base/select'
+import { DEFAULT_VALUE_MAX_LEN } from '@/config'
+import VarIcon from '../base/icons/var-icon'
+import Button from '@/app/components/base/button'
+
+export type IPromptValuePanelProps = {
+ appType: AppType
+ value?: string
+ onChange?: (value: string) => void
+ onSend?: () => void
+}
+
+const starIcon = (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M2.75 1C2.75 0.723858 2.52614 0.5 2.25 0.5C1.97386 0.5 1.75 0.723858 1.75 1V1.75H1C0.723858 1.75 0.5 1.97386 0.5 2.25C0.5 2.52614 0.723858 2.75 1 2.75H1.75V3.5C1.75 3.77614 1.97386 4 2.25 4C2.52614 4 2.75 3.77614 2.75 3.5V2.75H3.5C3.77614 2.75 4 2.52614 4 2.25C4 1.97386 3.77614 1.75 3.5 1.75H2.75V1Z" fill="#444CE7" />
+ <path d="M2.75 8.5C2.75 8.22386 2.52614 8 2.25 8C1.97386 8 1.75 8.22386 1.75 8.5V9.25H1C0.723858 9.25 0.5 9.47386 0.5 9.75C0.5 10.0261 0.723858 10.25 1 10.25H1.75V11C1.75 11.2761 1.97386 11.5 2.25 11.5C2.52614 11.5 2.75 11.2761 2.75 11V10.25H3.5C3.77614 10.25 4 10.0261 4 9.75C4 9.47386 3.77614 9.25 3.5 9.25H2.75V8.5Z" fill="#444CE7" />
+ <path d="M6.96667 1.32051C6.8924 1.12741 6.70689 1 6.5 1C6.29311 1 6.10759 1.12741 6.03333 1.32051L5.16624 3.57494C5.01604 3.96546 4.96884 4.078 4.90428 4.1688C4.8395 4.2599 4.7599 4.3395 4.6688 4.40428C4.578 4.46884 4.46546 4.51604 4.07494 4.66624L1.82051 5.53333C1.62741 5.60759 1.5 5.79311 1.5 6C1.5 6.20689 1.62741 6.39241 1.82051 6.46667L4.07494 7.33376C4.46546 7.48396 4.578 7.53116 4.6688 7.59572C4.7599 7.6605 4.8395 7.7401 4.90428 7.8312C4.96884 7.922 5.01604 8.03454 5.16624 8.42506L6.03333 10.6795C6.1076 10.8726 6.29311 11 6.5 11C6.70689 11 6.89241 10.8726 6.96667 10.6795L7.83376 8.42506C7.98396 8.03454 8.03116 7.922 8.09572 7.8312C8.1605 7.7401 8.2401 7.6605 8.3312 7.59572C8.422 7.53116 8.53454 7.48396 8.92506 7.33376L11.1795 6.46667C11.3726 6.39241 11.5 6.20689 11.5 6C11.5 5.79311 11.3726 5.60759 11.1795 5.53333L8.92506 4.66624C8.53454 4.51604 8.422 4.46884 8.3312 4.40428C8.2401 4.3395 8.1605 4.2599 8.09572 4.1688C8.03116 4.078 7.98396 3.96546 7.83376 3.57494L6.96667 1.32051Z" fill="#444CE7" />
+ </svg>
+)
+
+const PromptValuePanel: FC<IPromptValuePanelProps> = ({
+ appType,
+ value,
+ onChange,
+ onSend,
+}) => {
+ const { t } = useTranslation()
+ const { modelConfig, inputs, setInputs } = useContext(ConfigContext)
+ const promptTemplate = modelConfig.configs.prompt_template
+ const promptVariables = modelConfig.configs.prompt_variables.filter(({ key, name }) => {
+ return key && key?.trim() && name && name?.trim()
+ })
+
+ const promptVariableObj = (() => {
+ const obj: Record<string, boolean> = {}
+ promptVariables.forEach((input) => {
+ obj[input.key] = true
+ })
+ return obj
+ })()
+
+ const handleInputValueChange = (key: string, value: string) => {
+ if (!(key in promptVariableObj))
+ return
+
+ const newInputs = { ...inputs }
+ promptVariables.forEach((input) => {
+ if (input.key === key)
+ newInputs[key] = value
+ })
+ setInputs(newInputs)
+ }
+
+ const promptPreview = (
+ <div className='pt-3 pb-4 rounded-t-xl bg-indigo-25'>
+ <div className="px-4">
+ <div className="flex items-center space-x-1">
+ {starIcon}
+ <div className="text-xs font-medium text-indigo-600 uppercase">{t('appDebug.inputs.previewTitle')}</div>
+ </div>
+ <div className='mt-2 leading-normal'>
+ {
+ (promptTemplate && promptTemplate?.trim()) ? (
+ <div
+ className="max-h-48 overflow-y-auto text-sm text-gray-700"
+ dangerouslySetInnerHTML={{
+ __html: format(replaceStringWithValuesWithFormat(promptTemplate, promptVariables, inputs)),
+ }}
+ >
+ </div>
+ ) : (
+ <div className='text-xs text-gray-500'>{t('appDebug.inputs.noPrompt')}</div>
+ )
+ }
+ </div>
+ </div>
+ </div>
+ )
+
+ return (
+ <div className="pb-5 border border-gray-200 bg-white rounded-xl" style={{
+ boxShadow: '0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06)',
+ }}>
+ {promptPreview}
+
+ <div className="mt-5 px-4">
+ <div className='mb-4 '>
+ <div className='flex items-center space-x-1'>
+ <div className='flex items-center justify-center w-4 h-4'><VarIcon /></div>
+ <div className='text-sm font-semibold text-gray-800'>{t('appDebug.inputs.userInputField')}</div>
+ </div>
+ {appType === AppType.completion && promptVariables.length > 0 && (
+ <div className="mt-1 text-xs leading-normal text-gray-500">{t('appDebug.inputs.completionVarTip')}</div>
+ )}
+ </div>
+ {
+ promptVariables.length > 0 ? (
+ <div className="space-y-3 ">
+ {promptVariables.map(({ key, name, type, options, max_length, required }) => (
+ <div key={key} className="flex items-center justify-between">
+ <div className="mr-1 shrink-0 w-[120px] text-sm text-gray-900">{name || key}</div>
+ {type === 'select' ? (
+ <Select
+ className='w-full'
+ defaultValue={inputs[key] as string}
+ onSelect={(i) => { handleInputValueChange(key, i.value as string) }}
+ items={(options || []).map(i => ({ name: i, value: i }))}
+ allowSearch={false}
+ bgClassName='bg-gray-50'
+ />
+ ) : (
+ <input
+ className="w-full px-3 text-sm leading-9 text-gray-900 border-0 rounded-lg grow h-9 bg-gray-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
+ placeholder={`${name}${!required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
+ type="text"
+ value={inputs[key] ? `${inputs[key]}` : ''}
+ onChange={(e) => { handleInputValueChange(key, e.target.value) }}
+ maxLength={max_length || DEFAULT_VALUE_MAX_LEN}
+ />
+ )}
+
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className='text-xs text-gray-500'>{t('appDebug.inputs.noVar')}</div>
+ )
+ }
+ </div>
+
+ {
+ appType === AppType.completion && (
+ <div className='px-4'>
+ <div className="mt-5 border-b border-gray-100"></div>
+ <div className="mt-4">
+ <div>
+ <div className="text-[13px] text-gray-900 font-medium">{t('appDebug.inputs.queryTitle')}</div>
+ <div className="mt-2 mb-4 overflow-hidden border border-gray-200 rounded-lg grow bg-gray-50 ">
+ <div className="px-4 py-2 rounded-t-lg bg-gray-50">
+ <textarea
+ rows={4}
+ className="w-full px-0 text-sm text-gray-900 border-0 bg-gray-50 focus:outline-none placeholder:bg-gray-50"
+ placeholder={t('appDebug.inputs.queryPlaceholder') as string}
+ value={value}
+ onChange={e => onChange && onChange(e.target.value)}
+ ></textarea>
+ </div>
+ <div className="flex items-center justify-between px-3 py-2 bg-gray-50">
+ <div className="flex pl-0 space-x-1 sm:pl-2">
+ <span className="bg-gray-100 text-gray-500 text-xs font-medium mr-2 px-2.5 py-0.5 rounded cursor-pointer">{value?.length}</span>
+ </div>
+ <Button
+ type="primary"
+ onClick={() => onSend && onSend()}
+ className="w-[80px] !h-8">
+ <PlayIcon className="shrink-0 w-4 h-4 mr-1" aria-hidden="true" />
+ <span className='uppercase text-[13px]'>{t('appDebug.inputs.run')}</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+ </div>
+ )
+}
+
+export default React.memo(PromptValuePanel)
+
+function replaceStringWithValuesWithFormat(str: string, promptVariables: PromptVariable[], inputs: Record<string, any>) {
+ return str.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
+ const name = inputs[key]
+ if (name) { // has set value
+ return `<div class='inline-block px-1 rounded-md text-gray-900' style='background: rgba(16, 24, 40, 0.1)'>${name}</div>`
+ }
+
+ const valueObj: PromptVariable | undefined = promptVariables.find(v => v.key === key)
+ return `<div class='inline-block px-1 rounded-md text-gray-500' style='background: rgba(16, 24, 40, 0.05)'>${valueObj ? valueObj.name : match}</div>`
+ })
+}
+
+export function replaceStringWithValues(str: string, promptVariables: PromptVariable[], inputs: Record<string, any>) {
+ return str.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
+ const name = inputs[key]
+ if (name) { // has set value
+ return name
+ }
+
+ const valueObj: PromptVariable | undefined = promptVariables.find(v => v.key === key)
+ return valueObj ? `{{${valueObj.name}}}` : match
+ })
+}
+
+// \n -> br
+function format(str: string) {
+ return str.replaceAll('\n', '<br>')
+}
diff --git a/web/app/components/app/configuration/toolbox/index.tsx b/web/app/components/app/configuration/toolbox/index.tsx
new file mode 100644
index 00000000000..0304b3f32e2
--- /dev/null
+++ b/web/app/components/app/configuration/toolbox/index.tsx
@@ -0,0 +1,26 @@
+'use client'
+import React, { FC } from 'react'
+import GroupName from '../base/group-name'
+
+export interface IToolboxProps {
+ searchToolConfig: any
+ sensitiveWordAvoidanceConifg: any
+}
+
+/*
+* Include
+* 1. Search Tool
+* 2. Sensitive word avoidance
+*/
+const Toolbox: FC<IToolboxProps> = ({ searchToolConfig, sensitiveWordAvoidanceConifg }) => {
+ return (
+ <div>
+ <GroupName name='Toolbox' />
+ <div>
+ {searchToolConfig?.enabled && <div>Search Tool</div>}
+ {sensitiveWordAvoidanceConifg?.enabled && <div>Sensitive word avoidance</div>}
+ </div>
+ </div>
+ )
+}
+export default React.memo(Toolbox)
diff --git a/web/app/components/app/log/filter.tsx b/web/app/components/app/log/filter.tsx
new file mode 100644
index 00000000000..45c70b5c4d5
--- /dev/null
+++ b/web/app/components/app/log/filter.tsx
@@ -0,0 +1,83 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ MagnifyingGlassIcon,
+} from '@heroicons/react/24/solid'
+import useSWR from 'swr'
+import dayjs from 'dayjs'
+import quarterOfYear from 'dayjs/plugin/quarterOfYear'
+import type { QueryParam } from './index'
+import { SimpleSelect } from '@/app/components/base/select'
+import { fetchAnnotationsCount } from '@/service/log'
+dayjs.extend(quarterOfYear)
+
+const today = dayjs()
+
+export const TIME_PERIOD_LIST = [
+ { value: 0, name: 'today' },
+ { value: 7, name: 'last7days' },
+ { value: 28, name: 'last4weeks' },
+ { value: today.diff(today.subtract(3, 'month'), 'day'), name: 'last3months' },
+ { value: today.diff(today.subtract(12, 'month'), 'day'), name: 'last12months' },
+ { value: today.diff(today.startOf('month'), 'day'), name: 'monthToDate' },
+ { value: today.diff(today.startOf('quarter'), 'day'), name: 'quarterToDate' },
+ { value: today.diff(today.startOf('year'), 'day'), name: 'yearToDate' },
+ { value: 'all', name: 'allTime' },
+]
+
+type IFilterProps = {
+ appId: string
+ queryParams: QueryParam
+ setQueryParams: (v: QueryParam) => void
+}
+
+const Filter: FC<IFilterProps> = ({ appId, queryParams, setQueryParams }: IFilterProps) => {
+ const { data } = useSWR({ url: `/apps/${appId}/annotations/count` }, fetchAnnotationsCount)
+ const { t } = useTranslation()
+ if (!data)
+ return null
+ return (
+ <div className='flex flex-row items-center mb-4 text-gray-900 text-base'>
+ <SimpleSelect
+ items={TIME_PERIOD_LIST.map(item => ({ value: item.value, name: t(`appLog.filter.period.${item.name}`) }))}
+ className='mt-0 !w-40'
+ onSelect={(item) => {
+ setQueryParams({ ...queryParams, period: item.value })
+ }}
+ defaultValue={queryParams.period} />
+ <div className="relative ml-4 rounded-md mr-4">
+ <SimpleSelect
+ defaultValue={'all'}
+ className='!w-[300px]'
+ onSelect={
+ (item) => {
+ setQueryParams({ ...queryParams, annotation_status: item.value as string })
+ }
+ }
+ items={[{ value: 'all', name: t('appLog.filter.annotation.all') },
+ { value: 'annotated', name: t('appLog.filter.annotation.annotated', { count: data?.count }) },
+ { value: 'not_annotated', name: t('appLog.filter.annotation.not_annotated') }]}
+ />
+ </div>
+ <div className="relative">
+ <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
+ <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
+ </div>
+ <input
+ type="text"
+ name="query"
+ className="block w-[240px] bg-gray-100 shadow-sm rounded-md border-0 py-1.5 pl-10 text-gray-900 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-gray-200 focus-visible:outline-none sm:text-sm sm:leading-6"
+ placeholder={t('common.operation.search')}
+ value={queryParams.keyword}
+ onChange={(e) => {
+ setQueryParams({ ...queryParams, keyword: e.target.value })
+ }}
+ />
+ </div>
+ </div>
+ )
+}
+
+export default Filter
diff --git a/web/app/components/app/log/index.tsx b/web/app/components/app/log/index.tsx
new file mode 100644
index 00000000000..eb4dbdd636a
--- /dev/null
+++ b/web/app/components/app/log/index.tsx
@@ -0,0 +1,146 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import useSWR from 'swr'
+import { usePathname } from 'next/navigation'
+import { Pagination } from 'react-headless-pagination'
+import { omit } from 'lodash-es'
+import dayjs from 'dayjs'
+import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline'
+import { Trans, useTranslation } from 'react-i18next'
+import Link from 'next/link'
+import List from './list'
+import Filter from './filter'
+import s from './style.module.css'
+import Loading from '@/app/components/base/loading'
+import { fetchChatConversations, fetchCompletionConversations } from '@/service/log'
+import { fetchAppDetail } from '@/service/apps'
+
+export type ILogsProps = {
+ appId: string
+}
+
+export type QueryParam = {
+ period?: number | string
+ annotation_status?: string
+ keyword?: string
+}
+
+// Custom page count is not currently supported.
+const limit = 10
+
+const ThreeDotsIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M5 6.5V5M8.93934 7.56066L10 6.5M10.0103 11.5H11.5103" stroke="#374151" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+const EmptyElement: FC<{ appUrl: string }> = ({ appUrl }) => {
+ const { t } = useTranslation()
+ const pathname = usePathname()
+ const pathSegments = pathname.split('/')
+ pathSegments.pop()
+ return <div className='flex items-center justify-center h-full'>
+ <div className='bg-gray-50 w-[560px] h-fit box-border px-5 py-4 rounded-2xl'>
+ <span className='text-gray-700 font-semibold'>{t('appLog.table.empty.element.title')}<ThreeDotsIcon className='inline relative -top-3 -left-1.5' /></span>
+ <div className='mt-2 text-gray-500 text-sm font-normal'>
+ <Trans
+ i18nKey="appLog.table.empty.element.content"
+ components={{ shareLink: <Link href={`${pathSegments.join('/')}/overview`} className='text-primary-600' />, testLink: <Link href={appUrl} className='text-primary-600' target='_blank' /> }}
+ />
+ </div>
+ </div>
+ </div>
+}
+
+const Logs: FC<ILogsProps> = ({ appId }) => {
+ const { t } = useTranslation()
+ const [queryParams, setQueryParams] = useState<QueryParam>({ period: 7, annotation_status: 'all' })
+ const [currPage, setCurrPage] = React.useState<number>(0)
+
+ const query = {
+ page: currPage + 1,
+ limit,
+ ...(queryParams.period !== 'all'
+ ? {
+ start: dayjs().subtract(queryParams.period as number, 'day').format('YYYY-MM-DD HH:mm'),
+ end: dayjs().format('YYYY-MM-DD HH:mm'),
+ }
+ : {}),
+ ...omit(queryParams, ['period']),
+ }
+
+ // Get the app type first
+ const { data: appDetail } = useSWR({ url: '/apps', id: appId }, fetchAppDetail)
+ const isChatMode = appDetail?.mode === 'chat'
+
+ // When the details are obtained, proceed to the next request
+ const { data: chatConversations, mutate: mutateChatList } = useSWR(() => isChatMode
+ ? {
+ url: `/apps/${appId}/chat-conversations`,
+ params: query,
+ }
+ : null, fetchChatConversations)
+
+ const { data: completionConversations, mutate: mutateCompletionList } = useSWR(() => !isChatMode
+ ? {
+ url: `/apps/${appId}/completion-conversations`,
+ params: query,
+ }
+ : null, fetchCompletionConversations)
+
+ const total = isChatMode ? chatConversations?.total : completionConversations?.total
+
+ return (
+ <div className='flex flex-col h-full'>
+ <div className='flex flex-col justify-center px-6 pt-4'>
+ <h1 className='flex text-xl font-medium text-gray-900'>{t('appLog.title')}</h1>
+ <p className='flex text-sm font-normal text-gray-500'>{t('appLog.description')}</p>
+ </div>
+ <div className='flex flex-col px-6 py-4 flex-1'>
+ <Filter appId={appId} queryParams={queryParams} setQueryParams={setQueryParams} />
+ {total === undefined
+ ? <Loading type='app' />
+ : total > 0
+ ? <List logs={isChatMode ? chatConversations : completionConversations} appDetail={appDetail} onRefresh={isChatMode ? mutateChatList : mutateCompletionList} />
+ : <EmptyElement appUrl={`${appDetail?.site.app_base_url}/${appDetail?.mode}/${appDetail?.site.access_token}`} />
+ }
+ {/* Show Pagination only if the total is more than the limit */}
+ {(total && total > limit)
+ ? <Pagination
+ className="flex items-center w-full h-10 text-sm select-none mt-8"
+ currentPage={currPage}
+ edgePageCount={2}
+ middlePagesSiblingCount={1}
+ setCurrentPage={setCurrPage}
+ totalPages={Math.ceil(total / limit)}
+ truncableClassName="w-8 px-0.5 text-center"
+ truncableText="..."
+ >
+ <Pagination.PrevButton
+ disabled={currPage === 0}
+ className={`flex items-center mr-2 text-gray-500 focus:outline-none ${currPage === 0 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600 dark:hover:text-gray-200'}`} >
+ <ArrowLeftIcon className="mr-3 h-3 w-3" />
+ {t('appLog.table.pagination.previous')}
+ </Pagination.PrevButton>
+ <div className={`flex items-center justify-center flex-grow ${s.pagination}`}>
+ <Pagination.PageButton
+ activeClassName="bg-primary-50 dark:bg-opacity-0 text-primary-600 dark:text-white"
+ className="flex items-center justify-center h-8 w-8 rounded-full cursor-pointer"
+ inactiveClassName="text-gray-500"
+ />
+ </div>
+ <Pagination.NextButton
+ disabled={currPage === Math.ceil(total / limit) - 1}
+ className={`flex items-center mr-2 text-gray-500 focus:outline-none ${currPage === Math.ceil(total / limit) - 1 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600 dark:hover:text-gray-200'}`} >
+ {t('appLog.table.pagination.next')}
+ <ArrowRightIcon className="ml-3 h-3 w-3" />
+ </Pagination.NextButton>
+ </Pagination>
+ : null}
+ </div>
+ </div>
+ )
+}
+
+export default Logs
diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsx
new file mode 100644
index 00000000000..cfde271d534
--- /dev/null
+++ b/web/app/components/app/log/list.tsx
@@ -0,0 +1,477 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useState } from 'react'
+// import type { Log } from '@/models/log'
+import useSWR from 'swr'
+import {
+ HandThumbDownIcon,
+ HandThumbUpIcon,
+ InformationCircleIcon,
+ XMarkIcon,
+} from '@heroicons/react/24/outline'
+import { SparklesIcon } from '@heroicons/react/24/solid'
+import { get } from 'lodash-es'
+import InfiniteScroll from 'react-infinite-scroll-component'
+import dayjs from 'dayjs'
+import { createContext, useContext } from 'use-context-selector'
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+import { EditIconSolid } from '../chat'
+import { randomString } from '../../app-sidebar/basic'
+import s from './style.module.css'
+import type { FeedbackFunc, Feedbacktype, IChatItem, SubmitAnnotationFunc } from '@/app/components/app/chat'
+import type { Annotation, ChatConversationFullDetailResponse, ChatConversationGeneralDetail, ChatConversationsResponse, ChatMessage, ChatMessagesRequest, CompletionConversationFullDetailResponse, CompletionConversationGeneralDetail, CompletionConversationsResponse } from '@/models/log'
+import type { App } from '@/types/app'
+import Loading from '@/app/components/base/loading'
+import Drawer from '@/app/components/base/drawer'
+import Popover from '@/app/components/base/popover'
+import Chat from '@/app/components/app/chat'
+import Tooltip from '@/app/components/base/tooltip'
+import { ToastContext } from '@/app/components/base/toast'
+import { fetchChatConversationDetail, fetchChatMessages, fetchCompletionConversationDetail, updateLogMessageAnnotations, updateLogMessageFeedbacks } from '@/service/log'
+import { TONE_LIST } from '@/config'
+
+type IConversationList = {
+ logs?: ChatConversationsResponse | CompletionConversationsResponse
+ appDetail?: App
+ onRefresh: () => void
+}
+
+const defaultValue = 'N/A'
+const emptyText = '[Empty]'
+
+type IDrawerContext = {
+ onClose: () => void
+ appDetail?: App
+}
+
+const DrawerContext = createContext<IDrawerContext>({} as IDrawerContext)
+
+export const OpenAIIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <rect width="16" height="16" rx="6" fill="black" />
+ <path d="M13.6553 7.70613C13.7853 7.99625 13.8678 8.30638 13.9016 8.62276C13.9341 8.93913 13.9179 9.25927 13.8503 9.57064C13.7841 9.88202 13.669 10.1809 13.5089 10.456C13.4039 10.6398 13.2801 10.8124 13.1375 10.9712C12.9962 11.1288 12.8387 11.2713 12.6673 11.3964C12.4948 11.5214 12.311 11.6265 12.1159 11.7128C11.922 11.7978 11.7195 11.8628 11.5119 11.9053C11.4143 12.208 11.2693 12.4943 11.0817 12.7519C10.8954 13.0095 10.669 13.2359 10.4114 13.4222C10.1538 13.6098 9.86871 13.7549 9.56608 13.8524C9.26346 13.9512 8.94708 14 8.6282 14C8.41686 14.0012 8.20428 13.9787 7.99669 13.9362C7.79036 13.8924 7.58778 13.8261 7.39395 13.7398C7.20012 13.6536 7.01629 13.546 6.84497 13.421C6.6749 13.2959 6.51734 13.1521 6.37728 12.9933C6.06465 13.0608 5.74452 13.0771 5.42814 13.0446C5.11177 13.0108 4.80164 12.9283 4.51027 12.7982C4.22015 12.6694 3.95129 12.4943 3.71495 12.2805C3.4786 12.0667 3.27727 11.8166 3.11845 11.5414C3.01216 11.3576 2.92462 11.1638 2.85835 10.9625C2.79207 10.7611 2.7483 10.5535 2.72579 10.3422C2.70328 10.1321 2.70453 9.91954 2.72704 9.7082C2.74955 9.49811 2.79582 9.29053 2.8621 9.0892C2.64951 8.85285 2.47444 8.58399 2.34439 8.29387C2.21558 8.0025 2.1318 7.69363 2.09929 7.37725C2.06552 7.06087 2.08303 6.74074 2.14931 6.42936C2.21558 6.11798 2.33063 5.81911 2.4907 5.544C2.59574 5.36017 2.71954 5.18635 2.86085 5.02879C3.00215 4.87122 3.16097 4.72867 3.33229 4.60361C3.50361 4.47856 3.68868 4.37227 3.88251 4.28724C4.07759 4.20095 4.28018 4.13717 4.48776 4.09466C4.5853 3.79078 4.73036 3.50567 4.91669 3.24806C5.10426 2.99046 5.33061 2.76411 5.58821 2.57654C5.84582 2.39021 6.13093 2.24515 6.43356 2.14636C6.73618 2.04882 7.05256 1.9988 7.37144 2.00005C7.58277 1.9988 7.79536 2.02006 8.00295 2.06383C8.21053 2.1076 8.41311 2.17262 8.60694 2.25891C8.80077 2.34644 8.9846 2.45274 9.15592 2.57779C9.32724 2.70409 9.4848 2.84665 9.62486 3.00546C9.93623 2.93919 10.2564 2.92293 10.5727 2.95544C10.8891 2.98796 11.198 3.07174 11.4894 3.20054C11.7795 3.3306 12.0483 3.50442 12.2847 3.71825C12.521 3.93084 12.7224 4.17969 12.8812 4.45605C12.9875 4.63863 13.075 4.83246 13.1413 5.03504C13.2076 5.23637 13.2526 5.44396 13.2738 5.65529C13.2964 5.86663 13.2964 6.07922 13.2726 6.29055C13.2501 6.50189 13.2038 6.70948 13.1375 6.91081C13.3514 7.14715 13.5252 7.41476 13.6553 7.70613ZM9.48855 13.0446C9.76116 12.932 10.0088 12.7657 10.2176 12.5569C10.4264 12.348 10.5928 12.1004 10.7053 11.8266C10.8178 11.554 10.8766 11.2613 10.8766 10.9662V8.17757C10.8758 8.17507 10.875 8.17215 10.8741 8.16882C10.8733 8.16632 10.872 8.16382 10.8704 8.16132C10.8687 8.15882 10.8666 8.15673 10.8641 8.15507C10.8616 8.15256 10.8591 8.1509 10.8566 8.15006L9.84745 7.56733V10.9362C9.84745 10.97 9.84245 11.005 9.83369 11.0375C9.82494 11.0713 9.81243 11.1025 9.79493 11.1325C9.77742 11.1625 9.75741 11.1901 9.7324 11.2138C9.70809 11.238 9.68077 11.2591 9.65112 11.2763L7.26139 12.6557C7.24138 12.6682 7.20762 12.6857 7.19011 12.6957C7.2889 12.7795 7.39645 12.8532 7.50899 12.9183C7.62279 12.9833 7.74034 13.0383 7.86289 13.0833C7.98544 13.1271 8.11174 13.1609 8.23929 13.1834C8.36809 13.2059 8.49815 13.2171 8.6282 13.2171C8.92332 13.2171 9.21594 13.1584 9.48855 13.0446ZM3.79748 11.1513C3.94629 11.4076 4.14262 11.6302 4.37647 11.8103C4.61156 11.9904 4.87792 12.1217 5.16304 12.198C5.44815 12.2742 5.74577 12.2943 6.03839 12.2555C6.33101 12.2167 6.61238 12.1217 6.86873 11.9741L9.28472 10.5798L9.29097 10.5736C9.29264 10.5719 9.29389 10.5694 9.29472 10.566C9.29639 10.5635 9.29764 10.561 9.29847 10.5585V9.38307L6.38228 11.07C6.35227 11.0875 6.32101 11.1 6.2885 11.11C6.25473 11.1188 6.22097 11.1225 6.18595 11.1225C6.15219 11.1225 6.11843 11.1188 6.08466 11.11C6.05215 11.1 6.01964 11.0875 5.98962 11.07L3.5999 9.68944C3.57864 9.67694 3.54738 9.65818 3.52987 9.64692C3.50736 9.77573 3.49611 9.90578 3.49611 10.0358C3.49611 10.1659 3.50861 10.2959 3.53112 10.4247C3.55363 10.5523 3.58864 10.6786 3.63241 10.8011C3.67743 10.9237 3.73245 11.0412 3.79748 11.1538V11.1513ZM3.16972 5.93666C3.02216 6.19301 2.92712 6.47563 2.88836 6.76825C2.84959 7.06087 2.8696 7.35724 2.94588 7.64361C3.02216 7.92872 3.15347 8.19508 3.33354 8.43018C3.51361 8.66402 3.73745 8.86035 3.99256 9.00791L6.40729 10.4035C6.4098 10.4043 6.41271 10.4051 6.41605 10.406H6.4248C6.42814 10.406 6.43105 10.4051 6.43356 10.4035C6.43606 10.4026 6.43856 10.4014 6.44106 10.3997L7.45397 9.81449L4.53778 8.13131C4.50902 8.1138 4.48151 8.09254 4.4565 8.06878C4.43227 8.04447 4.41125 8.01715 4.39397 7.9875C4.37772 7.95748 4.36396 7.92622 4.35521 7.89246C4.34645 7.85994 4.34145 7.82618 4.3427 7.79117V4.95126C4.22015 4.99628 4.10135 5.0513 3.98881 5.11632C3.87626 5.1826 3.76997 5.25763 3.66993 5.34142C3.57114 5.4252 3.4786 5.51774 3.39481 5.61778C3.31103 5.71657 3.23725 5.82411 3.17222 5.93666H3.16972ZM11.4644 7.86745C11.4944 7.88495 11.5219 7.90496 11.5469 7.92997C11.5707 7.95373 11.5919 7.98124 11.6094 8.01126C11.6257 8.04127 11.6394 8.07378 11.6482 8.10629C11.6557 8.14006 11.6607 8.17382 11.6594 8.20884V11.0487C12.0609 10.9012 12.411 10.6423 12.6699 10.3022C12.93 9.96205 13.0863 9.55564 13.1225 9.13046C13.1588 8.70529 13.0738 8.27762 12.8762 7.89871C12.6786 7.51981 12.3772 7.20468 12.0071 6.99209L9.59234 5.59652C9.58984 5.59569 9.58693 5.59485 9.58359 5.59402H9.57484C9.57234 5.59485 9.56942 5.59569 9.56608 5.59652C9.56358 5.59735 9.56108 5.5986 9.55858 5.60027L8.55067 6.18301L11.4669 7.86745H11.4644ZM12.471 6.35433H12.4698V6.35558L12.471 6.35433ZM12.4698 6.35308C12.5423 5.93291 12.4935 5.50023 12.3285 5.10632C12.1646 4.71241 11.8908 4.37352 11.5406 4.12842C11.1905 3.88457 10.7778 3.74451 10.3514 3.72576C9.92373 3.70825 9.50106 3.81204 9.13091 4.02463L6.71617 5.41895C6.71367 5.42062 6.71159 5.4227 6.70992 5.4252L6.70492 5.4327C6.70408 5.4352 6.70325 5.43812 6.70241 5.44146C6.70158 5.44396 6.70116 5.44688 6.70116 5.45021V6.61569L9.61735 4.93125C9.64737 4.91374 9.67988 4.90124 9.71239 4.89123C9.74616 4.88248 9.77992 4.87873 9.81368 4.87873C9.8487 4.87873 9.88246 4.88248 9.91623 4.89123C9.94874 4.90124 9.98 4.91374 10.01 4.93125L12.3997 6.31181C12.421 6.32432 12.4523 6.34182 12.4698 6.35308ZM6.15094 5.06255C6.15094 5.02879 6.15594 4.99502 6.1647 4.96126C6.17345 4.92875 6.18595 4.89623 6.20346 4.86622C6.22097 4.83746 6.24098 4.80995 6.26599 4.78494C6.28975 4.76118 6.31726 4.73992 6.34727 4.72366L8.73699 3.34435C8.7595 3.3306 8.79077 3.31309 8.80827 3.30433C8.48064 3.03047 8.08048 2.8554 7.65655 2.80163C7.23263 2.74661 6.80246 2.81413 6.41605 2.99546C6.02839 3.17678 5.70076 3.46565 5.47191 3.8258C5.24307 4.18719 5.12177 4.60487 5.12177 5.03254V7.82118C5.1226 7.82451 5.12344 7.82743 5.12427 7.82993C5.1251 7.83243 5.12635 7.83493 5.12802 7.83744C5.12969 7.83994 5.13177 7.84244 5.13427 7.84494C5.13594 7.84661 5.13844 7.84827 5.14178 7.84994L6.15094 8.43268V5.06255ZM6.69866 8.74781L7.99794 9.49811L9.29722 8.74781V7.24845L7.99919 6.49814L6.69991 7.24845L6.69866 8.74781Z" fill="white" />
+ </svg>
+}
+
+/**
+ * Icon component with numbers
+ */
+const HandThumbIconWithCount: FC<{ count: number; iconType: 'up' | 'down' }> = ({ count, iconType }) => {
+ const classname = iconType === 'up' ? 'text-primary-600 bg-primary-50' : 'text-red-600 bg-red-50'
+ const Icon = iconType === 'up' ? HandThumbUpIcon : HandThumbDownIcon
+ return <div className={`inline-flex items-center w-fit rounded-md p-1 text-xs ${classname} mr-1 last:mr-0`}>
+ <Icon className={'h-3 w-3 mr-0.5 rounded-md'} />
+ {count > 0 ? count : null}
+ </div>
+}
+
+const PARAM_MAP = {
+ temperature: 'Temperature',
+ top_p: 'Top P',
+ presence_penalty: 'Presence Penalty',
+ max_tokens: 'Max Token',
+ stop: 'Stop',
+ frequency_penalty: 'Frequency Penalty',
+}
+
+// Format interface data for easy display
+const getFormattedChatList = (messages: ChatMessage[]) => {
+ const newChatList: IChatItem[] = []
+ messages.forEach((item: ChatMessage) => {
+ newChatList.push({
+ id: `question-${item.id}`,
+ content: item.query,
+ isAnswer: false,
+ })
+
+ newChatList.push({
+ id: item.id,
+ content: item.answer,
+ feedback: item.feedbacks.find(item => item.from_source === 'user'), // user feedback
+ adminFeedback: item.feedbacks.find(item => item.from_source === 'admin'), // admin feedback
+ feedbackDisabled: false,
+ isAnswer: true,
+ more: {
+ time: dayjs.unix(item.created_at).format('hh:mm A'),
+ tokens: item.answer_tokens,
+ latency: (item.provider_response_latency / 1000).toFixed(2),
+ },
+ annotation: item.annotation,
+ })
+ })
+ return newChatList
+}
+
+// const displayedParams = CompletionParams.slice(0, -2)
+const validatedParams = ['temperature', 'top_p', 'presence_penalty', 'frequency_penalty']
+
+type IDetailPanel<T> = {
+ detail: T
+ onFeedback: FeedbackFunc
+ onSubmitAnnotation: SubmitAnnotationFunc
+}
+
+function DetailPanel<T extends ChatConversationFullDetailResponse | CompletionConversationFullDetailResponse>({ detail, onFeedback, onSubmitAnnotation }: IDetailPanel<T>) {
+ const { onClose, appDetail } = useContext(DrawerContext)
+ const { t } = useTranslation()
+ const [items, setItems] = React.useState<IChatItem[]>([])
+ const [hasMore, setHasMore] = useState(true)
+
+ const fetchData = async () => {
+ try {
+ if (!hasMore)
+ return
+ const params: ChatMessagesRequest = {
+ conversation_id: detail.id,
+ limit: 4,
+ }
+ if (items?.[0]?.id)
+ params.first_id = items?.[0]?.id.replace('question-', '')
+
+ const messageRes = await fetchChatMessages({
+ url: `/apps/${appDetail?.id}/chat-messages`,
+ params,
+ })
+ const newItems = [...getFormattedChatList(messageRes.data), ...items]
+ if (messageRes.has_more === false && detail?.model_config?.configs?.introduction) {
+ newItems.unshift({
+ id: 'introduction',
+ isAnswer: true,
+ isOpeningStatement: true,
+ content: detail?.model_config?.configs?.introduction ?? 'hello',
+ feedbackDisabled: true,
+ })
+ }
+ setItems(newItems)
+ setHasMore(messageRes.has_more)
+ }
+ catch (err) {
+ console.error(err)
+ }
+ }
+
+ useEffect(() => {
+ if (appDetail?.id && detail.id && appDetail?.mode === 'chat')
+ fetchData()
+ }, [appDetail?.id, detail.id])
+
+ const isChatMode = appDetail?.mode === 'chat'
+
+ const targetTone = TONE_LIST.find((item) => {
+ let res = true
+ validatedParams.forEach((param) => {
+ res = item.config?.[param] === detail.model_config?.configs?.completion_params?.[param]
+ })
+ return res
+ })?.name ?? 'custom'
+
+ return (<div className='rounded-xl border-[0.5px] border-gray-200 h-full flex flex-col'>
+ {/* Panel Header */}
+ <div className='border-b border-gray-100 py-4 px-6 flex items-center justify-between'>
+ <div className='flex-1'>
+ <span className='text-gray-500 text-[10px]'>{isChatMode ? t('appLog.detail.conversationId') : t('appLog.detail.time')}</span>
+ <div className='text-gray-800 text-sm'>{isChatMode ? detail.id : dayjs.unix(detail.created_at).format(t('appLog.dateTimeFormat'))}</div>
+ </div>
+ <div className='mr-2 bg-gray-50 py-1.5 px-2.5 rounded-lg flex items-center text-[13px]'><OpenAIIcon className='mr-2' />{detail.model_config.model_id}</div>
+ <Popover
+ position='br'
+ className='!w-[280px]'
+ btnClassName='mr-4 !bg-gray-50 !py-1.5 !px-2.5 border-none font-normal'
+ btnElement={<>
+ <span className='text-[13px]'>{targetTone}</span>
+ <InformationCircleIcon className='h-4 w-4 text-gray-800 ml-1.5' />
+ </>}
+ htmlContent={<div className='w-[280px]'>
+ <div className='flex justify-between py-2 px-4 font-medium text-sm text-gray-700'>
+ <span>Tone of responses</span>
+ <div>{targetTone}</div>
+ </div>
+ {['temperature', 'top_p', 'presence_penalty', 'max_tokens'].map((param, index) => {
+ return <div className='flex justify-between py-2 px-4 bg-gray-50' key={index}>
+ <span className='text-xs text-gray-700'>{PARAM_MAP[param]}</span>
+ <span className='text-gray-800 font-medium text-xs'>{detail?.model_config.model?.completion_params?.[param] || '-'}</span>
+ </div>
+ })}
+ </div>}
+ />
+ <div className='w-6 h-6 rounded-lg flex items-center justify-center hover:cursor-pointer hover:bg-gray-100'>
+ <XMarkIcon className='w-4 h-4 text-gray-500' onClick={onClose} />
+ </div>
+ </div>
+ {/* Panel Body */}
+ <div className='bg-gray-50 border border-gray-100 px-4 py-3 mx-6 my-4 rounded-lg'>
+ <div className='text-gray-500 text-xs flex items-center'>
+ <SparklesIcon className='h-3 w-3 mr-1' />{isChatMode ? t('appLog.detail.promptTemplateBeforeChat') : t('appLog.detail.promptTemplate')}
+ </div>
+ <div className='text-gray-700 font-medium text-sm mt-2'>{detail.model_config?.pre_prompt || emptyText}</div>
+ </div>
+ {!isChatMode
+ ? <div className="px-2.5 py-4 overflow-y-auto">
+ <Chat
+ chatList={getFormattedChatList([detail.message])}
+ isHideSendInput={true}
+ onFeedback={onFeedback}
+ onSubmitAnnotation={onSubmitAnnotation}
+ displayScene='console'
+ />
+ </div>
+ : items.length < 8
+ ? <div className="px-2.5 pt-4 mb-4 overflow-y-auto">
+ <Chat
+ chatList={items}
+ isHideSendInput={true}
+ onFeedback={onFeedback}
+ onSubmitAnnotation={onSubmitAnnotation}
+ displayScene='console'
+ />
+ </div>
+ : <div
+ className="px-2.5 py-4"
+ id="scrollableDiv"
+ style={{
+ height: 1000, // Specify a value
+ overflow: 'auto',
+ display: 'flex',
+ flexDirection: 'column-reverse',
+ }}>
+ {/* Put the scroll bar always on the bottom */}
+ <InfiniteScroll
+ scrollableTarget="scrollableDiv"
+ dataLength={items.length}
+ next={fetchData}
+ hasMore={hasMore}
+ loader={<div className='text-center text-gray-400 text-xs'>{t('appLog.detail.loading')}...</div>}
+ // endMessage={<div className='text-center'>Nothing more to show</div>}
+ // below props only if you need pull down functionality
+ refreshFunction={fetchData}
+ pullDownToRefresh
+ pullDownToRefreshThreshold={50}
+ // pullDownToRefreshContent={
+ // <div className='text-center'>Pull down to refresh</div>
+ // }
+ // releaseToRefreshContent={
+ // <div className='text-center'>Release to refresh</div>
+ // }
+ // To put endMessage and loader to the top.
+ style={{ display: 'flex', flexDirection: 'column-reverse' }}
+ inverse={true}
+ >
+ <Chat
+ chatList={items}
+ isHideSendInput={true}
+ onFeedback={onFeedback}
+ onSubmitAnnotation={onSubmitAnnotation}
+ displayScene='console'
+ />
+ </InfiniteScroll>
+ </div>
+ }
+ </div>)
+}
+
+/**
+ * Text App Conversation Detail Component
+ */
+const CompletionConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
+ // Text Generator App Session Details Including Message List
+ const detailParams = ({ url: `/apps/${appId}/completion-conversations/${conversationId}` })
+ const { data: conversationDetail, mutate: conversationDetailMutate } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchCompletionConversationDetail)
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+
+ const handleFeedback = async (mid: string, { rating }: Feedbacktype): Promise<boolean> => {
+ try {
+ await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
+ conversationDetailMutate()
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ return true
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ return false
+ }
+ }
+
+ const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
+ try {
+ await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
+ conversationDetailMutate()
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ return true
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ return false
+ }
+ }
+
+ if (!conversationDetail)
+ return null
+
+ return <DetailPanel<CompletionConversationFullDetailResponse>
+ detail={conversationDetail}
+ onFeedback={handleFeedback}
+ onSubmitAnnotation={handleAnnotation}
+ />
+}
+
+/**
+ * Chat App Conversation Detail Component
+ */
+const ChatConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
+ const detailParams = { url: `/apps/${appId}/chat-conversations/${conversationId}` }
+ const { data: conversationDetail } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchChatConversationDetail)
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+
+ const handleFeedback = async (mid: string, { rating }: Feedbacktype): Promise<boolean> => {
+ try {
+ await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ return true
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ return false
+ }
+ }
+
+ const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
+ try {
+ await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ return true
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ return false
+ }
+ }
+
+ if (!conversationDetail)
+ return null
+
+ return <DetailPanel<ChatConversationFullDetailResponse>
+ detail={conversationDetail}
+ onFeedback={handleFeedback}
+ onSubmitAnnotation={handleAnnotation}
+ />
+}
+
+/**
+ * Conversation list component including basic information
+ */
+const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh }) => {
+ const { t } = useTranslation()
+ const [showDrawer, setShowDrawer] = useState<boolean>(false) // Whether to display the chat details drawer
+ const [currentConversation, setCurrentConversation] = useState<ChatConversationGeneralDetail | CompletionConversationGeneralDetail | undefined>() // Currently selected conversation
+ const isChatMode = appDetail?.mode === 'chat' // Whether the app is a chat app
+
+ // Annotated data needs to be highlighted
+ const renderTdValue = (value: string | number | null, isEmptyStyle: boolean, isHighlight = false, annotation?: Annotation) => {
+ return (
+ <Tooltip
+ htmlContent={
+ <span className='text-xs text-gray-500 inline-flex items-center'>
+ <EditIconSolid className='mr-1' />{`${t('appLog.detail.annotationTip', { user: annotation?.account?.name })} ${dayjs.unix(annotation?.created_at || dayjs().unix()).format('MM-DD hh:mm A')}`}
+ </span>
+ }
+ className={(isHighlight && !isChatMode) ? '' : '!hidden'}
+ selector={`highlight-${randomString(16)}`}
+ >
+ <div className={classNames(isEmptyStyle ? 'text-gray-400' : 'text-gray-700', !isHighlight ? '' : 'bg-orange-100', 'text-sm overflow-hidden text-ellipsis whitespace-nowrap')}>
+ {value || '-'}
+ </div>
+ </Tooltip>
+ )
+ }
+
+ const onCloseDrawer = () => {
+ onRefresh()
+ setShowDrawer(false)
+ setCurrentConversation(undefined)
+ }
+
+ if (!logs)
+ return <Loading />
+
+ return (
+ <>
+ <table className={`w-full border-collapse border-0 text-sm mt-3 ${s.logTable}`}>
+ <thead className="h-8 leading-8 border-b border-gray-200 text-gray-500 font-bold">
+ <tr>
+ <td className='w-[1.375rem]'></td>
+ <td>{t('appLog.table.header.time')}</td>
+ <td>{t('appLog.table.header.endUser')}</td>
+ <td>{isChatMode ? t('appLog.table.header.summary') : t('appLog.table.header.input')}</td>
+ <td>{isChatMode ? t('appLog.table.header.messageCount') : t('appLog.table.header.output')}</td>
+ <td>{t('appLog.table.header.userRate')}</td>
+ <td>{t('appLog.table.header.adminRate')}</td>
+ </tr>
+ </thead>
+ <tbody className="text-gray-500">
+ {logs.data.map((log) => {
+ const endUser = log.from_end_user_id?.slice(0, 8)
+ const leftValue = get(log, isChatMode ? 'summary' : 'message.query')
+ const rightValue = get(log, isChatMode ? 'message_count' : 'message.answer')
+ return <tr
+ key={log.id}
+ className={`border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer ${currentConversation?.id !== log.id ? '' : 'bg-gray-50'}`}
+ onClick={() => {
+ setShowDrawer(true)
+ setCurrentConversation(log)
+ }}>
+ <td className='text-center align-middle'>{!log.read_at && <span className='inline-block bg-[#3F83F8] h-1.5 w-1.5 rounded'></span>}</td>
+ <td className='w-[160px]'>{dayjs.unix(log.created_at).format(t('appLog.dateTimeFormat'))}</td>
+ <td>{renderTdValue(endUser || defaultValue, !endUser)}</td>
+ <td style={{ maxWidth: isChatMode ? 300 : 200 }}>
+ {renderTdValue(leftValue || t('appLog.table.empty.noChat'), !leftValue, isChatMode && log.annotated)}
+ </td>
+ <td style={{ maxWidth: isChatMode ? 100 : 200 }}>
+ {renderTdValue(rightValue === 0 ? 0 : (rightValue || t('appLog.table.empty.noOutput')), !rightValue, !isChatMode && !!log.annotation?.content, log.annotation)}
+ </td>
+ <td>
+ {(!log.user_feedback_stats.like && !log.user_feedback_stats.dislike)
+ ? renderTdValue(defaultValue, true)
+ : <>
+ {!!log.user_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.user_feedback_stats.like} />}
+ {!!log.user_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.user_feedback_stats.dislike} />}
+ </>
+ }
+ </td>
+ <td>
+ {(!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike)
+ ? renderTdValue(defaultValue, true)
+ : <>
+ {!!log.admin_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.admin_feedback_stats.like} />}
+ {!!log.admin_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.admin_feedback_stats.dislike} />}
+ </>
+ }
+ </td>
+ </tr>
+ })}
+ </tbody>
+ </table>
+ <Drawer
+ isOpen={showDrawer}
+ onClose={onCloseDrawer}
+ mask={false}
+ footer={null}
+ panelClassname='mt-16 mr-2 mb-3 !p-0 !max-w-[640px] rounded-b-xl'
+ >
+ <DrawerContext.Provider value={{
+ onClose: onCloseDrawer,
+ appDetail,
+ }}>
+ {isChatMode
+ ? <ChatConversationDetailComp appId={appDetail?.id} conversationId={currentConversation?.id} />
+ : <CompletionConversationDetailComp appId={appDetail?.id} conversationId={currentConversation?.id} />
+ }
+ </DrawerContext.Provider>
+ </Drawer>
+ </>
+ )
+}
+
+export default ConversationList
diff --git a/web/app/components/app/log/style.module.css b/web/app/components/app/log/style.module.css
new file mode 100644
index 00000000000..67a9fe3bf5d
--- /dev/null
+++ b/web/app/components/app/log/style.module.css
@@ -0,0 +1,9 @@
+.logTable td {
+ padding: 7px 8px;
+ box-sizing: border-box;
+ max-width: 200px;
+}
+
+.pagination li {
+ list-style: none;
+}
diff --git a/web/app/components/app/overview/appCard.tsx b/web/app/components/app/overview/appCard.tsx
new file mode 100644
index 00000000000..663383f0478
--- /dev/null
+++ b/web/app/components/app/overview/appCard.tsx
@@ -0,0 +1,211 @@
+'use client'
+import React, { useState } from 'react'
+import {
+ Cog8ToothIcon,
+ DocumentTextIcon,
+ RocketLaunchIcon,
+ ShareIcon,
+} from '@heroicons/react/24/outline'
+import { SparklesIcon } from '@heroicons/react/24/solid'
+import { usePathname, useRouter } from 'next/navigation'
+import { useTranslation } from 'react-i18next'
+import SettingsModal from './settings'
+import ShareLink from './share-link'
+import CustomizeModal from './customize'
+import Tooltip from '@/app/components/base/tooltip'
+import AppBasic, { randomString } from '@/app/components/app-sidebar/basic'
+import Button from '@/app/components/base/button'
+import Tag from '@/app/components/base/tag'
+import Switch from '@/app/components/base/switch'
+import type { AppDetailResponse } from '@/models/app'
+
+export type IAppCardProps = {
+ className?: string
+ appInfo: AppDetailResponse
+ cardType?: 'app' | 'api'
+ customBgColor?: string
+ onChangeStatus: (val: boolean) => Promise<any>
+ onSaveSiteConfig?: (params: any) => Promise<any>
+ onGenerateCode?: () => Promise<any>
+}
+
+// todo: get image url from appInfo
+const defaultUrl = 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80'
+
+function AppCard({
+ appInfo,
+ cardType = 'app',
+ customBgColor,
+ onChangeStatus,
+ onSaveSiteConfig,
+ onGenerateCode,
+ className,
+}: IAppCardProps) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const [showSettingsModal, setShowSettingsModal] = useState(false)
+ const [showShareModal, setShowShareModal] = useState(false)
+ const [showCustomizeModal, setShowCustomizeModal] = useState(false)
+ const { t } = useTranslation()
+
+ const OPERATIONS_MAP = {
+ app: [
+ { opName: t('appOverview.overview.appInfo.preview'), opIcon: RocketLaunchIcon },
+ { opName: t('appOverview.overview.appInfo.share.entry'), opIcon: ShareIcon },
+ { opName: t('appOverview.overview.appInfo.settings.entry'), opIcon: Cog8ToothIcon },
+ ],
+ api: [{ opName: t('appOverview.overview.apiInfo.doc'), opIcon: DocumentTextIcon }],
+ }
+
+ const isApp = cardType === 'app'
+ const basicName = isApp ? appInfo?.site?.title : t('appOverview.overview.apiInfo.title')
+ const runningStatus = isApp ? appInfo.enable_site : appInfo.enable_api
+ const { app_base_url, access_token } = appInfo.site ?? {}
+ const appUrl = `${app_base_url}/${appInfo.mode}/${access_token}`
+ const apiUrl = appInfo?.api_base_url
+
+ let bgColor = 'bg-primary-50 bg-opacity-40'
+ if (cardType === 'api')
+ bgColor = 'bg-purple-50'
+
+ const genClickFuncByName = (opName: string) => {
+ switch (opName) {
+ case t('appOverview.overview.appInfo.preview'):
+ return () => {
+ window.open(appUrl, '_blank')
+ }
+ case t('appOverview.overview.appInfo.share.entry'):
+ return () => {
+ setShowShareModal(true)
+ }
+ case t('appOverview.overview.appInfo.settings.entry'):
+ return () => {
+ setShowSettingsModal(true)
+ }
+ default:
+ // jump to page develop
+ return () => {
+ const pathSegments = pathname.split('/')
+ pathSegments.pop()
+ router.push(`${pathSegments.join('/')}/develop`)
+ }
+ }
+ }
+
+ const onClickCustomize = () => {
+ setShowCustomizeModal(true)
+ }
+
+ return (
+ <div
+ className={`flex flex-col w-full shadow-sm border-[0.5px] rounded-lg border-gray-200 ${className ?? ''}`}
+ >
+ <div className={`px-6 py-4 ${customBgColor ?? bgColor} rounded-lg`}>
+ <div className="mb-2.5 flex flex-row items-start justify-between">
+ <AppBasic
+ iconType={isApp ? 'app' : 'api'}
+ iconUrl={defaultUrl}
+ name={basicName}
+ type={
+ isApp
+ ? t('appOverview.overview.appInfo.explanation')
+ : t('appOverview.overview.apiInfo.explanation')
+ }
+ />
+ <div className="flex flex-row items-center h-9">
+ <Tag className="mr-2" color={runningStatus ? 'green' : 'yellow'}>
+ {runningStatus ? t('appOverview.overview.status.running') : t('appOverview.overview.status.disable')}
+ </Tag>
+ <Switch defaultValue={runningStatus} onChange={onChangeStatus} />
+ </div>
+ </div>
+ <div className="flex flex-col justify-center py-2">
+ <div className="py-1">
+ <div className="pb-1 text-xs text-gray-500">
+ {isApp ? t('appOverview.overview.appInfo.accessibleAddress') : t('appOverview.overview.apiInfo.accessibleAddress')}
+ </div>
+ <div className="text-sm text-gray-800">
+ {isApp ? appUrl : apiUrl}
+ </div>
+ </div>
+ </div>
+ <div
+ className={`pt-2 flex flex-row items-center ${!isApp ? 'mb-[calc(2rem_+_1px)]' : ''
+ }`}
+ >
+ {OPERATIONS_MAP[cardType].map((op) => {
+ return (
+ <Button
+ className="mr-2 text-gray-800"
+ key={op.opName}
+ onClick={genClickFuncByName(op.opName)}
+ disabled={
+ [t('appOverview.overview.appInfo.preview'), t('appOverview.overview.appInfo.share.entry')].includes(op.opName) && !runningStatus
+ }
+ >
+ <Tooltip
+ content={t('appOverview.overview.appInfo.preUseReminder') ?? ''}
+ selector={`op-btn-${randomString(16)}`}
+ className={
+ ([t('appOverview.overview.appInfo.preview'), t('appOverview.overview.appInfo.share.entry')].includes(op.opName) && !runningStatus)
+ ? 'mt-[-8px]'
+ : '!hidden'
+ }
+ >
+ <div className="flex flex-row items-center">
+ <op.opIcon className="h-4 w-4 mr-1.5" />
+ <span className="text-xs">{op.opName}</span>
+ </div>
+ </Tooltip>
+ </Button>
+ )
+ })}
+ </div>
+ </div>
+ {isApp
+ ? (
+ <div
+ className={
+ 'flex items-center px-6 py-2 box-border text-xs text-gray-500 bg-opacity-50 bg-white border-t-[0.5px] border-primary-50'
+ }
+ >
+ <div
+ className="flex items-center hover:text-primary-600 hover:cursor-pointer"
+ onClick={onClickCustomize}
+ >
+ <SparklesIcon className="w-4 h-4 mr-1" />
+ {t('appOverview.overview.appInfo.customize.entry')}
+ </div>
+ </div>
+ )
+ : null}
+ {isApp
+ ? (
+ <div>
+ <ShareLink
+ isShow={showShareModal}
+ onClose={() => setShowShareModal(false)}
+ linkUrl={appUrl}
+ onGenerateCode={onGenerateCode}
+ />
+ <SettingsModal
+ appInfo={appInfo}
+ isShow={showSettingsModal}
+ onClose={() => setShowSettingsModal(false)}
+ onSave={onSaveSiteConfig}
+ />
+ <CustomizeModal
+ isShow={showCustomizeModal}
+ linkUrl=""
+ onClose={() => setShowCustomizeModal(false)}
+ appId={appInfo.id}
+ mode={appInfo.mode}
+ />
+ </div>
+ )
+ : null}
+ </div>
+ )
+}
+
+export default AppCard
diff --git a/web/app/components/app/overview/appChart.tsx b/web/app/components/app/overview/appChart.tsx
new file mode 100644
index 00000000000..a8dae564e6c
--- /dev/null
+++ b/web/app/components/app/overview/appChart.tsx
@@ -0,0 +1,291 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import ReactECharts from 'echarts-for-react'
+import type { EChartsOption } from 'echarts'
+import useSWR from 'swr'
+import dayjs from 'dayjs'
+import { get } from 'lodash-es'
+import { formatNumber } from '@/utils/format'
+import { useTranslation } from 'react-i18next'
+import Basic from '@/app/components/app-sidebar/basic'
+import Loading from '@/app/components/base/loading'
+import type { AppDailyConversationsResponse, AppDailyEndUsersResponse, AppTokenCostsResponse } from '@/models/app'
+import { getAppDailyConversations, getAppDailyEndUsers, getAppTokenCosts } from '@/service/apps'
+const valueFormatter = (v: string | number) => v
+
+const COLOR_TYPE_MAP = {
+ green: {
+ lineColor: 'rgba(6, 148, 162, 1)',
+ bgColor: ['rgba(6, 148, 162, 0.2)', 'rgba(67, 174, 185, 0.08)'],
+ },
+ orange: {
+ lineColor: 'rgba(255, 138, 76, 1)',
+ bgColor: ['rgba(254, 145, 87, 0.2)', 'rgba(255, 138, 76, 0.1)'],
+ },
+ blue: {
+ lineColor: 'rgba(28, 100, 242, 1)',
+ bgColor: ['rgba(28, 100, 242, 0.3)', 'rgba(28, 100, 242, 0.1)'],
+ },
+}
+
+const COMMON_COLOR_MAP = {
+ label: '#9CA3AF',
+ splitLineLight: '#F3F4F6',
+ splitLineDark: '#E5E7EB',
+}
+
+type IColorType = 'green' | 'orange' | 'blue'
+type IChartType = 'conversations' | 'endUsers' | 'costs'
+type IChartConfigType = { colorType: IColorType; showTokens?: boolean }
+
+const commonDateFormat = 'MMM D, YYYY'
+
+const CHART_TYPE_CONFIG: Record<string, IChartConfigType> = {
+ conversations: {
+ colorType: 'green',
+ },
+ endUsers: {
+ colorType: 'orange',
+ },
+ costs: {
+ colorType: 'blue',
+ showTokens: true,
+ },
+}
+
+const sum = (arr: number[]): number => {
+ return arr.reduce((acr, cur) => {
+ return acr + cur
+ })
+}
+
+export type PeriodParams = {
+ name: string
+ query: {
+ start: string
+ end: string
+ }
+}
+
+export type IBizChartProps = {
+ period: PeriodParams
+ id: string
+}
+
+export type IChartProps = {
+ className?: string
+ basicInfo: { title: string; explanation: string; timePeriod: string }
+ yMax?: number
+ chartType: IChartType
+ chartData: AppDailyConversationsResponse | AppDailyEndUsersResponse | AppTokenCostsResponse | { data: Array<{ date: string; count: number }> }
+}
+
+const Chart: React.FC<IChartProps> = ({
+ basicInfo: { title, explanation, timePeriod },
+ chartType = 'conversations',
+ chartData,
+ yMax,
+ className,
+}) => {
+ const { t } = useTranslation()
+ const statistics = chartData.data
+ const statisticsLen = statistics.length
+ const extraDataForMarkLine = new Array(statisticsLen >= 2 ? statisticsLen - 2 : statisticsLen).fill('1')
+ extraDataForMarkLine.push('')
+ extraDataForMarkLine.unshift('')
+
+ const xData = statistics.map(({ date }) => date)
+ const yField = Object.keys(statistics[0]).find(name => name.includes('count')) || ''
+ const yData = statistics.map((item) => {
+ // @ts-expect-error field is valid
+ return item[yField] || 0
+ })
+
+ const options: EChartsOption = {
+ dataset: {
+ dimensions: ['date', yField],
+ source: statistics,
+ },
+ grid: { top: 8, right: 36, bottom: 0, left: 0, containLabel: true },
+ tooltip: {
+ trigger: 'item',
+ position: 'top',
+ borderWidth: 0,
+ },
+ xAxis: [{
+ type: 'category',
+ boundaryGap: false,
+ axisLabel: {
+ color: COMMON_COLOR_MAP.label,
+ hideOverlap: true,
+ overflow: 'break',
+ formatter(value) {
+ return dayjs(value).format(commonDateFormat)
+ },
+ },
+ axisLine: { show: false },
+ axisTick: { show: false },
+ splitLine: {
+ show: true,
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineLight,
+ width: 1,
+ type: [10, 10],
+ },
+ interval(index) {
+ return index === 0 || index === xData.length - 1
+ },
+ },
+ }, {
+ position: 'bottom',
+ boundaryGap: false,
+ data: extraDataForMarkLine,
+ axisLabel: { show: false },
+ axisLine: { show: false },
+ axisTick: { show: false },
+ splitLine: {
+ show: true,
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineDark,
+ },
+ interval(index, value) {
+ return !!value
+ },
+ },
+ }],
+ yAxis: {
+ max: yMax ?? 'dataMax',
+ type: 'value',
+ axisLabel: { color: COMMON_COLOR_MAP.label, hideOverlap: true },
+ splitLine: {
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineLight,
+ },
+ },
+ },
+ series: [
+ {
+ type: 'line',
+ showSymbol: true,
+ // symbol: 'circle',
+ // triggerLineEvent: true,
+ symbolSize: 4,
+ lineStyle: {
+ color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].lineColor,
+ width: 2,
+ },
+ itemStyle: {
+ color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].lineColor,
+ },
+ areaStyle: {
+ color: {
+ type: 'linear',
+ x: 0,
+ y: 0,
+ x2: 0,
+ y2: 1,
+ colorStops: [{
+ offset: 0, color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].bgColor[0],
+ }, {
+ offset: 1, color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].bgColor[1],
+ }],
+ global: false,
+ },
+ },
+ tooltip: {
+ padding: [8, 12, 8, 12],
+ formatter(params) {
+ return `<div style='color:#6B7280;font-size:12px'>${params.name}</div>
+ <div style='font-size:14px;color:#1F2A37'>${valueFormatter((params.data as any)[yField])}
+ ${!CHART_TYPE_CONFIG[chartType].showTokens
+ ? ''
+ : `<span style='font-size:12px'>
+ <span style='margin-left:4px;color:#6B7280'>(</span>
+ <span style='color:#FF8A4C'>~$${get(params.data, 'total_price', 0)}</span>
+ <span style='color:#6B7280'>)</span>
+ </span>`}
+ </div>`
+ },
+ },
+ },
+ ],
+ }
+
+ const sumData = sum(yData)
+
+ return (
+ <div className={`flex flex-col w-full px-6 py-4 border-[0.5px] rounded-lg border-gray-200 shadow-sm ${className ?? ''}`}>
+ <div className='mb-3'>
+ <Basic name={title} type={timePeriod} hoverTip={explanation} />
+ </div>
+ <div className='mb-4'>
+ <Basic
+ name={chartType !== 'costs' ? sumData.toLocaleString() : `${sumData < 1000 ? sumData : (formatNumber(Math.round(sumData / 1000)) + 'k')}`}
+ type={!CHART_TYPE_CONFIG[chartType].showTokens
+ ? ''
+ : <span>{t('appOverview.analysis.tokenUsage.consumed')} Tokens<span className='text-sm'>
+ <span className='ml-1 text-gray-500'>(</span>
+ <span className='text-orange-400'>~{sum(statistics.map(item => parseFloat(get(item, 'total_price', '0')))).toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 4 })}</span>
+ <span className='text-gray-500'>)</span>
+ </span></span>}
+ textStyle={{ main: `!text-3xl !font-normal ${sumData === 0 ? '!text-gray-300' : ''}` }} />
+ </div>
+ <ReactECharts option={options} style={{ height: 160 }} />
+ </div>
+ )
+}
+
+const getDefaultChartData = ({ start, end }: { start: string; end: string }) => {
+ const diffDays = dayjs(end).diff(dayjs(start), 'day')
+ return Array.from({ length: diffDays || 1 }, () => ({ date: '', count: 0 })).map((item, index) => {
+ item.date = dayjs(start).add(index, 'day').format(commonDateFormat)
+ return item
+ })
+}
+
+export const ConversationsChart: FC<IBizChartProps> = ({ id, period }) => {
+ const { t } = useTranslation()
+ const { data: response } = useSWR({ url: `/apps/${id}/statistics/daily-conversations`, params: period.query }, getAppDailyConversations)
+ if (!response)
+ return <Loading />
+ const noDataFlag = !response.data || response.data.length === 0
+ return <Chart
+ basicInfo={{ title: t('appOverview.analysis.totalMessages.title'), explanation: t('appOverview.analysis.totalMessages.explanation'), timePeriod: period.name }}
+ chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query) }}
+ chartType='conversations'
+ {...(noDataFlag && { yMax: 500 })}
+ />
+}
+
+export const EndUsersChart: FC<IBizChartProps> = ({ id, period }) => {
+ const { t } = useTranslation()
+
+ const { data: response } = useSWR({ url: `/apps/${id}/statistics/daily-end-users`, id, params: period.query }, getAppDailyEndUsers)
+ if (!response)
+ return <Loading />
+ const noDataFlag = !response.data || response.data.length === 0
+ return <Chart
+ basicInfo={{ title: t('appOverview.analysis.activeUsers.title'), explanation: t('appOverview.analysis.activeUsers.explanation'), timePeriod: period.name }}
+ chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query) }}
+ chartType='endUsers'
+ {...(noDataFlag && { yMax: 500 })}
+ />
+}
+
+export const CostChart: FC<IBizChartProps> = ({ id, period }) => {
+ const { t } = useTranslation()
+
+ const { data: response } = useSWR({ url: `/apps/${id}/statistics/token-costs`, params: period.query }, getAppTokenCosts)
+ if (!response)
+ return <Loading />
+ const noDataFlag = !response.data || response.data.length === 0
+ return <Chart
+ basicInfo={{ title: t('appOverview.analysis.tokenUsage.title'), explanation: t('appOverview.analysis.tokenUsage.explanation'), timePeriod: period.name }}
+ chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query) }}
+ chartType='costs'
+ {...(noDataFlag && { yMax: 100 })}
+ />
+}
+
+export default Chart
diff --git a/web/app/components/app/overview/customize/index.tsx b/web/app/components/app/overview/customize/index.tsx
new file mode 100644
index 00000000000..a1d46ff0b22
--- /dev/null
+++ b/web/app/components/app/overview/customize/index.tsx
@@ -0,0 +1,108 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { AppMode } from '@/types/app'
+import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import I18n from '@/context/i18n'
+import Button from '@/app/components/base/button'
+import Modal from '@/app/components/base/modal'
+import Tag from '@/app/components/base/tag'
+
+type IShareLinkProps = {
+ isShow: boolean
+ onClose: () => void
+ linkUrl: string
+ appId: string
+ mode: AppMode
+}
+
+const StepNum: FC<{ children: React.ReactNode }> = ({ children }) =>
+ <div className='h-7 w-7 flex justify-center items-center flex-shrink-0 mr-3 text-primary-600 bg-primary-50 rounded-2xl'>
+ {children}
+ </div>
+
+
+
+const GithubIcon = ({ className }: { className: string }) => {
+ return (
+ <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
+ <path d="M5.80078 13.7109C5.80078 13.6406 5.73047 13.5703 5.625 13.5703C5.51953 13.5703 5.44922 13.6406 5.44922 13.7109C5.44922 13.7812 5.51953 13.8516 5.625 13.8164C5.73047 13.8164 5.80078 13.7812 5.80078 13.7109ZM4.71094 13.5352C4.71094 13.6055 4.78125 13.7109 4.88672 13.7109C4.95703 13.7461 5.0625 13.7109 5.09766 13.6406C5.09766 13.5703 5.0625 13.5 4.95703 13.4648C4.85156 13.4297 4.74609 13.4648 4.71094 13.5352ZM6.29297 13.5C6.1875 13.5 6.11719 13.5703 6.11719 13.6758C6.11719 13.7461 6.22266 13.7812 6.32812 13.7461C6.43359 13.7109 6.50391 13.6758 6.46875 13.6055C6.46875 13.5352 6.36328 13.4648 6.29297 13.5ZM8.57812 0C3.72656 0 0 3.72656 0 8.57812C0 12.4805 2.42578 15.8203 5.94141 17.0156C6.39844 17.0859 6.53906 16.8047 6.53906 16.5938C6.53906 16.3477 6.53906 15.1523 6.53906 14.4141C6.53906 14.4141 4.07812 14.9414 3.55078 13.3594C3.55078 13.3594 3.16406 12.3398 2.60156 12.0938C2.60156 12.0938 1.79297 11.5312 2.63672 11.5312C2.63672 11.5312 3.51562 11.6016 4.00781 12.4453C4.78125 13.8164 6.04688 13.4297 6.57422 13.1836C6.64453 12.6211 6.85547 12.2344 7.13672 11.9883C5.16797 11.7773 3.16406 11.4961 3.16406 8.12109C3.16406 7.13672 3.44531 6.67969 4.00781 6.04688C3.90234 5.80078 3.62109 4.88672 4.11328 3.65625C4.81641 3.44531 6.53906 4.60547 6.53906 4.60547C7.24219 4.39453 7.98047 4.32422 8.71875 4.32422C9.49219 4.32422 10.2305 4.39453 10.9336 4.60547C10.9336 4.60547 12.6211 3.41016 13.3594 3.65625C13.8516 4.88672 13.5352 5.80078 13.4648 6.04688C14.0273 6.67969 14.3789 7.13672 14.3789 8.12109C14.3789 11.4961 12.3047 11.7773 10.3359 11.9883C10.6523 12.2695 10.9336 12.7969 10.9336 13.6406C10.9336 14.8008 10.8984 16.2773 10.8984 16.5586C10.8984 16.8047 11.0742 17.0859 11.5312 16.9805C15.0469 15.8203 17.4375 12.4805 17.4375 8.57812C17.4375 3.72656 13.4648 0 8.57812 0ZM3.41016 12.1289C3.33984 12.1641 3.375 12.2695 3.41016 12.3398C3.48047 12.375 3.55078 12.4102 3.62109 12.375C3.65625 12.3398 3.65625 12.2344 3.58594 12.1641C3.51562 12.1289 3.44531 12.0938 3.41016 12.1289ZM3.02344 11.8477C2.98828 11.918 3.02344 11.9531 3.09375 11.9883C3.16406 12.0234 3.23438 12.0234 3.26953 11.9531C3.26953 11.918 3.23438 11.8828 3.16406 11.8477C3.09375 11.8125 3.05859 11.8125 3.02344 11.8477ZM4.14844 13.1133C4.11328 13.1484 4.11328 13.2539 4.21875 13.3242C4.28906 13.3945 4.39453 13.4297 4.42969 13.3594C4.46484 13.3242 4.46484 13.2188 4.39453 13.1484C4.32422 13.0781 4.21875 13.043 4.14844 13.1133ZM3.76172 12.5859C3.69141 12.6211 3.69141 12.7266 3.76172 12.7969C3.83203 12.8672 3.90234 12.9023 3.97266 12.8672C4.00781 12.832 4.00781 12.7266 3.97266 12.6562C3.90234 12.5859 3.83203 12.5508 3.76172 12.5859Z" fill="#1F2A37" />
+ </svg>
+ )
+}
+
+const prefixCustomize = 'appOverview.overview.appInfo.customize'
+
+const CustomizeModal: FC<IShareLinkProps> = ({
+ isShow,
+ onClose,
+ appId,
+ mode,
+}) => {
+ const { t } = useTranslation()
+ const { locale } = useContext(I18n)
+ const isChatApp = mode === 'chat'
+
+ return <Modal
+ title={t(`${prefixCustomize}.title`)}
+ description={t(`${prefixCustomize}.explanation`)}
+ isShow={isShow}
+ onClose={onClose}
+ className='!max-w-2xl w-[640px]'
+ closable={true}
+ >
+ <div className='w-full mt-4 px-6 py-5 border-gray-200 rounded-lg border-[0.5px]'>
+ <Tag bordered={true} hideBg={true} className='text-primary-600 border-primary-600 uppercase'>{t(`${prefixCustomize}.way`)} 1</Tag>
+ <p className='my-2 text-base font-medium text-gray-800'>{t(`${prefixCustomize}.way1.name`)}</p>
+ <div className='flex py-4'>
+ <StepNum>1</StepNum>
+ <div className='flex flex-col'>
+ <div className='text-gray-900'>{t(`${prefixCustomize}.way1.step1`)}</div>
+ <div className='text-gray-500 text-xs mt-1 mb-2'>{t(`${prefixCustomize}.way1.step1Tip`)}</div>
+ <a href={`https://github.com/langgenius/${isChatApp ? 'webapp-conversation' : 'webapp-text-generator'}`} target='_blank'>
+ <Button className='text-gray-800 text-sm w-fit'><GithubIcon className='text-gray-800 mr-2' />{t(`${prefixCustomize}.way1.step1Operation`)}</Button>
+ </a>
+ </div>
+ </div>
+ <div className='flex py-4'>
+ <StepNum>2</StepNum>
+ <div className='flex flex-col w-full'>
+ <div className='text-gray-900'>{t(`${prefixCustomize}.way1.step2`)}</div>
+ <div className='text-gray-500 text-xs mt-1 mb-2'>{t(`${prefixCustomize}.way1.step2Tip`)}</div>
+ <pre className='box-border py-3 px-4 bg-gray-100 text-xs font-medium rounded-lg'>
+ export const APP_ID = '{appId}'<br />
+ export const API_KEY = {`'<Web API Key From Dify>'`}
+ </pre>
+ </div>
+ </div>
+ <div className='flex pt-4'>
+ <StepNum>3</StepNum>
+ <div className='flex flex-col'>
+ <div className='text-gray-900'>{t(`${prefixCustomize}.way1.step3`)}</div>
+ <div className='text-gray-500 text-xs mt-1 mb-2'>{t(`${prefixCustomize}.way1.step3Tip`)}</div>
+ <a href="https://vercel.com/docs/concepts/deployments/git/vercel-for-github" target='_blank'>
+ <Button className='text-gray-800 text-sm w-fit'>
+ <div className='mr-1.5 border-solid border-t-0 border-r-[7px] border-l-[7px] border-b-[12px] border-r-transparent border-b-black border-l-transparent border-t-transparent'></div>
+ <span>{t(`${prefixCustomize}.way1.step3Operation`)}</span>
+ </Button>
+ </a>
+ </div>
+ </div>
+ </div>
+ <div className='w-full mt-4 px-6 py-5 border-gray-200 rounded-lg border-[0.5px]'>
+ <Tag bordered={true} hideBg={true} className='text-primary-600 border-primary-600 uppercase'>{t(`${prefixCustomize}.way`)} 2</Tag>
+ <p className='mt-2 text-base font-medium text-gray-800'>{t(`${prefixCustomize}.way2.name`)}</p>
+ <Button
+ className='w-36 mt-2'
+ onClick={() => window.open(`https://docs.dify.ai/${locale.toLowerCase()}/application/developing-with-apis`, '_blank')}
+ >
+ <span className='text-sm text-gray-800'>{t(`${prefixCustomize}.way2.operation`)}</span>
+ <ArrowTopRightOnSquareIcon className='w-4 h-4 ml-1 text-gray-800 shrink-0' />
+ </Button>
+ </div>
+ </Modal>
+}
+
+export default CustomizeModal
diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsx
new file mode 100644
index 00000000000..19e76041af1
--- /dev/null
+++ b/web/app/components/app/overview/settings/index.tsx
@@ -0,0 +1,145 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import { ChevronRightIcon } from '@heroicons/react/20/solid'
+import Link from 'next/link'
+import { Trans, useTranslation } from 'react-i18next'
+import s from './style.module.css'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import Switch from '@/app/components/base/switch'
+import AppIcon from '@/app/components/base/app-icon'
+import { SimpleSelect } from '@/app/components/base/select'
+import type { AppDetailResponse } from '@/models/app'
+import type { Language } from '@/types/app'
+
+export type ISettingsModalProps = {
+ appInfo: AppDetailResponse
+ isShow: boolean
+ defaultValue?: string
+ onClose: () => void
+ onSave: (params: ConfigParams) => Promise<any>
+}
+
+export type ConfigParams = {
+ title: string
+ description: string
+ default_language: string
+ prompt_public: boolean
+}
+
+const LANGUAGE_MAP: Record<Language, string> = {
+ 'en-US': 'English(United States)',
+ 'zh-Hans': '简体中文',
+}
+
+const prefixSettings = 'appOverview.overview.appInfo.settings'
+
+const SettingsModal: FC<ISettingsModalProps> = ({
+ appInfo,
+ isShow = false,
+ onClose,
+ onSave,
+}) => {
+ const [isShowMore, setIsShowMore] = useState(false)
+ const { title, description, copyright, privacy_policy, default_language } = appInfo.site
+ const [inputInfo, setInputInfo] = useState({ title, desc: description, copyright, privacyPolicy: privacy_policy })
+ const [language, setLanguage] = useState(default_language)
+ const [saveLoading, setSaveLoading] = useState(false)
+ const { t } = useTranslation()
+
+ const onHide = () => {
+ onClose()
+ setTimeout(() => {
+ setIsShowMore(false)
+ }, 200)
+ }
+
+ const onClickSave = async () => {
+ setSaveLoading(true)
+ const params = {
+ title: inputInfo.title,
+ description: inputInfo.desc,
+ default_language: language,
+ prompt_public: false,
+ copyright: inputInfo.copyright,
+ privacy_policy: inputInfo.privacyPolicy,
+ }
+ await onSave(params)
+ setSaveLoading(false)
+ onHide()
+ }
+
+ const onChange = (field: string) => {
+ return (e: any) => {
+ setInputInfo(item => ({ ...item, [field]: e.target.value }))
+ }
+ }
+
+ return (
+ <Modal
+ title={t(`${prefixSettings}.title`)}
+ isShow={isShow}
+ onClose={onHide}
+ className={`${s.settingsModal}`}
+ >
+ <div className={`mt-6 font-medium ${s.settingTitle} text-gray-900`}>{t(`${prefixSettings}.webName`)}</div>
+ <div className='flex mt-2'>
+ <AppIcon className='!mr-3 self-center' />
+ <input className={`flex-grow rounded-lg h-10 box-border px-3 ${s.projectName} bg-gray-100`}
+ value={inputInfo.title}
+ onChange={onChange('title')} />
+ </div>
+ <div className={`mt-6 font-medium ${s.settingTitle} text-gray-900 `}>{t(`${prefixSettings}.webDesc`)}</div>
+ <p className={`mt-1 ${s.settingsTip} text-gray-500`}>{t(`${prefixSettings}.webDescTip`)}</p>
+ <textarea
+ rows={3}
+ className={`mt-2 pt-2 pb-2 px-3 rounded-lg bg-gray-100 w-full ${s.settingsTip} text-gray-900`}
+ value={inputInfo.desc}
+ onChange={onChange('desc')}
+ placeholder={t(`${prefixSettings}.webDescPlaceholder`) as string}
+ />
+ <div className={`mt-6 mb-2 font-medium ${s.settingTitle} text-gray-900 `}>{t(`${prefixSettings}.language`)}</div>
+ <SimpleSelect
+ items={Object.keys(LANGUAGE_MAP).map(lang => ({ name: LANGUAGE_MAP[lang as Language], value: lang }))}
+ defaultValue={language}
+ onSelect={item => setLanguage(item.value as Language)}
+ />
+ {!isShowMore && <div className='w-full cursor-pointer mt-8' onClick={() => setIsShowMore(true)}>
+ <div className='flex justify-between'>
+ <div className={`font-medium ${s.settingTitle} flex-grow text-gray-900`}>{t(`${prefixSettings}.more.entry`)}</div>
+ <div className='flex-shrink-0 w-4 h-4 text-gray-500'>
+ <ChevronRightIcon />
+ </div>
+ </div>
+ <p className={`mt-1 ${s.policy} text-gray-500`}>{t(`${prefixSettings}.more.copyright`)} & {t(`${prefixSettings}.more.privacyPolicy`)}</p>
+ </div>}
+ {isShowMore && <>
+ <hr className='w-full mt-6' />
+ <div className={`mt-6 font-medium ${s.settingTitle} text-gray-900`}>{t(`${prefixSettings}.more.copyright`)}</div>
+ <input className={`w-full mt-2 rounded-lg h-10 box-border px-3 ${s.projectName} bg-gray-100`}
+ value={inputInfo.copyright}
+ onChange={onChange('copyright')}
+ placeholder={t(`${prefixSettings}.more.copyRightPlaceholder`) as string}
+ />
+ <div className={`mt-8 font-medium ${s.settingTitle} text-gray-900`}>{t(`${prefixSettings}.more.privacyPolicy`)}</div>
+ <p className={`mt-1 ${s.settingsTip} text-gray-500`}>
+ <Trans
+ i18nKey={`${prefixSettings}.more.privacyPolicyTip`}
+ components={{ privacyPolicyLink: <Link href={'https://langgenius.ai/privacy-policy'} target='_blank' className='text-primary-600' /> }}
+ />
+ </p>
+ <input className={`w-full mt-2 rounded-lg h-10 box-border px-3 ${s.projectName} bg-gray-100`}
+ value={inputInfo.privacyPolicy}
+ onChange={onChange('privacyPolicy')}
+ placeholder={t(`${prefixSettings}.more.privacyPolicyPlaceholder`) as string}
+ />
+ </>}
+ <div className='mt-10 flex justify-end'>
+ <Button className='mr-2 flex-shrink-0' onClick={onHide}>{t('common.operation.cancel')}</Button>
+ <Button type='primary' className='flex-shrink-0' onClick={onClickSave} loading={saveLoading}>{t('common.operation.save')}</Button>
+ </div>
+ </Modal >
+ )
+}
+export default React.memo(SettingsModal)
diff --git a/web/app/components/app/overview/settings/style.module.css b/web/app/components/app/overview/settings/style.module.css
new file mode 100644
index 00000000000..d1fe960befa
--- /dev/null
+++ b/web/app/components/app/overview/settings/style.module.css
@@ -0,0 +1,23 @@
+.settingsModal {
+ max-width: 32.5rem !important;
+}
+
+.settingTitle {
+ line-height: 21px;
+ font-size: 0.875rem;
+}
+
+.settingsTip {
+ line-height: 1.125rem;
+ font-size: 0.75rem;
+}
+
+.policy {
+ font-size: 0.75rem;
+ line-height: 1.125rem;
+}
+
+.projectName {
+ font-size: 0.875rem;
+ line-height: 2.5rem;
+}
\ No newline at end of file
diff --git a/web/app/components/app/overview/share-link.tsx b/web/app/components/app/overview/share-link.tsx
new file mode 100644
index 00000000000..771523abd80
--- /dev/null
+++ b/web/app/components/app/overview/share-link.tsx
@@ -0,0 +1,63 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import {
+ ArrowPathIcon,
+ LinkIcon,
+} from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import useCopyToClipboard from '@/hooks/use-copy-to-clipboard'
+
+import './style.css'
+
+type IShareLinkProps = {
+ isShow: boolean
+ onClose: () => void
+ onGenerateCode: () => Promise<void>
+ linkUrl: string
+}
+const ShareLinkModal: FC<IShareLinkProps> = ({
+ linkUrl,
+ isShow,
+ onClose,
+ onGenerateCode,
+}) => {
+ const [_, copy] = useCopyToClipboard()
+ const [genLoading, setGenLoading] = useState(false)
+ const { t } = useTranslation()
+ return <Modal
+ title={t('appOverview.overview.appInfo.share.explanation')}
+ isShow={isShow}
+ onClose={onClose}
+ >
+ {/* share url */}
+ <p className='mt-5 text-xs font-medium text-gray-500'>{t('appOverview.overview.appInfo.share.shareUrl')}</p>
+ {/* input share url */}
+ <input disabled type='text' value={linkUrl} className='mt-1 w-full bg-gray-50 p-2 text-primary-600 text-xs font-normal outline-gray-50 hover:outline-gray-50 cursor-pointer' />
+ {/* button copy link/ button regenerate */}
+ <div className='mt-4 flex gap-3'>
+ <Button
+ type="primary"
+ className='w-32'
+ onClick={() => {
+ copy(linkUrl)
+ }}
+ >
+ <LinkIcon className='w-4 h-4 mr-2' />
+ {t('appOverview.overview.appInfo.share.copyLink')}
+ </Button>
+ <Button className='w-32' onClick={async () => {
+ setGenLoading(true)
+ await onGenerateCode()
+ setGenLoading(false)
+ }}>
+ <ArrowPathIcon className={`w-4 h-4 mr-2 ${genLoading ? 'generateLogo' : ''}`} />
+ {t('appOverview.overview.appInfo.share.regenerate')}
+ </Button>
+ </div>
+ </Modal>
+}
+
+export default ShareLinkModal
diff --git a/web/app/components/app/overview/style.css b/web/app/components/app/overview/style.css
new file mode 100644
index 00000000000..d081c45e385
--- /dev/null
+++ b/web/app/components/app/overview/style.css
@@ -0,0 +1,13 @@
+.generateLogo {
+ animation: 2s rotate linear infinite;
+}
+
+@keyframes rotate {
+ from {
+ transform: rotate(0deg);
+ }
+
+ to {
+ transform: rotate(360deg);
+ }
+}
diff --git a/web/app/components/app/text-generate/index.tsx b/web/app/components/app/text-generate/index.tsx
new file mode 100644
index 00000000000..447830d8018
--- /dev/null
+++ b/web/app/components/app/text-generate/index.tsx
@@ -0,0 +1,26 @@
+'use client'
+import type { FC } from 'react'
+import { format } from '@/service/base'
+import React from 'react'
+
+export type ITextGenerationProps = {
+ value: string
+ className?: string
+}
+
+const TextGeneration: FC<ITextGenerationProps> = ({
+ value,
+ className,
+}) => {
+ return (
+ <div
+ className={className}
+ dangerouslySetInnerHTML={{
+ __html: format(value)
+ }}
+ >
+ </div>
+ )
+}
+
+export default React.memo(TextGeneration)
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
new file mode 100644
index 00000000000..f63ede0cae5
--- /dev/null
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -0,0 +1,242 @@
+'use client'
+import React, { FC, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import cn from 'classnames'
+import { Markdown } from '@/app/components/base/markdown'
+import Loading from '@/app/components/base/loading'
+import copy from 'copy-to-clipboard'
+import Toast from '@/app/components/base/toast'
+import { Feedbacktype } from '@/app/components/app/chat'
+import { HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
+import { useBoolean } from 'ahooks'
+import { fetcMoreLikeThis, updateFeedback } from '@/service/share'
+
+const MAX_DEPTH = 3
+export interface IGenerationItemProps {
+ className?: string
+ content: string
+ messageId?: string | null
+ isLoading?: boolean
+ isInWebApp?: boolean
+ moreLikeThis?: boolean
+ depth?: number
+ feedback?: Feedbacktype
+ onFeedback?: (feedback: Feedbacktype) => void
+ onSave?: (messageId: string) => void
+ isMobile?: boolean
+}
+
+export const SimpleBtn = ({ className, onClick, children }: {
+ className?: string
+ onClick?: () => void,
+ children: React.ReactNode
+}) => (
+ <div
+ className={cn(className, 'flex items-center h-7 px-3 rounded-md border border-gray-200 text-xs text-gray-700 font-medium cursor-pointer hover:shadow-sm hover:border-gray-300')}
+ onClick={() => onClick?.()}
+ >
+ {children}
+ </div>
+)
+
+export const copyIcon = (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M9.3335 2.33341C9.87598 2.33341 10.1472 2.33341 10.3698 2.39304C10.9737 2.55486 11.4454 3.02657 11.6072 3.63048C11.6668 3.85302 11.6668 4.12426 11.6668 4.66675V10.0334C11.6668 11.0135 11.6668 11.5036 11.4761 11.8779C11.3083 12.2072 11.0406 12.4749 10.7113 12.6427C10.337 12.8334 9.84692 12.8334 8.86683 12.8334H5.1335C4.1534 12.8334 3.66336 12.8334 3.28901 12.6427C2.95973 12.4749 2.69201 12.2072 2.52423 11.8779C2.3335 11.5036 2.3335 11.0135 2.3335 10.0334V4.66675C2.3335 4.12426 2.3335 3.85302 2.39313 3.63048C2.55494 3.02657 3.02665 2.55486 3.63056 2.39304C3.8531 2.33341 4.12435 2.33341 4.66683 2.33341M5.60016 3.50008H8.40016C8.72686 3.50008 8.89021 3.50008 9.01499 3.4365C9.12475 3.38058 9.21399 3.29134 9.26992 3.18158C9.3335 3.05679 9.3335 2.89345 9.3335 2.56675V2.10008C9.3335 1.77338 9.3335 1.61004 9.26992 1.48525C9.21399 1.37549 9.12475 1.28625 9.01499 1.23033C8.89021 1.16675 8.72686 1.16675 8.40016 1.16675H5.60016C5.27347 1.16675 5.11012 1.16675 4.98534 1.23033C4.87557 1.28625 4.78634 1.37549 4.73041 1.48525C4.66683 1.61004 4.66683 1.77338 4.66683 2.10008V2.56675C4.66683 2.89345 4.66683 3.05679 4.73041 3.18158C4.78634 3.29134 4.87557 3.38058 4.98534 3.4365C5.11012 3.50008 5.27347 3.50008 5.60016 3.50008Z" stroke="#344054" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const moreLikeThisIcon = (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g clipPath="url(#clip0_4138_1944)">
+ <path d="M2.62533 12.8337V9.91699M2.62533 4.08366V1.16699M1.16699 2.62533H4.08366M1.16699 11.3753H4.08366M7.58366 1.75033L6.57206 4.38049C6.40755 4.80821 6.32529 5.02207 6.19738 5.20196C6.08402 5.36139 5.94472 5.50069 5.78529 5.61405C5.6054 5.74196 5.39155 5.82421 4.96383 5.98872L2.33366 7.00033L4.96383 8.01193C5.39155 8.17644 5.60541 8.25869 5.78529 8.3866C5.94472 8.49996 6.08402 8.63926 6.19738 8.79869C6.32529 8.97858 6.40755 9.19244 6.57206 9.62016L7.58366 12.2503L8.59526 9.62015C8.75977 9.19244 8.84202 8.97858 8.96993 8.79869C9.0833 8.63926 9.22259 8.49996 9.38203 8.3866C9.56191 8.25869 9.77577 8.17644 10.2035 8.01193L12.8337 7.00033L10.2035 5.98872C9.77577 5.82421 9.56191 5.74196 9.38203 5.61405C9.22259 5.50069 9.0833 5.36139 8.96993 5.20196C8.84202 5.02207 8.75977 4.80821 8.59526 4.38049L7.58366 1.75033Z" stroke="#344054" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
+ </g>
+ <defs>
+ <clipPath id="clip0_4138_1944">
+ <rect width="14" height="14" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+)
+
+const saveIcon = (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M11.0837 12.25L7.00033 9.33333L2.91699 12.25V2.91667C2.91699 2.60725 3.03991 2.3105 3.2587 2.09171C3.47749 1.87292 3.77424 1.75 4.08366 1.75H9.91699C10.2264 1.75 10.5232 1.87292 10.7419 2.09171C10.9607 2.3105 11.0837 2.60725 11.0837 2.91667V12.25Z" stroke="#344054" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const GenerationItem: FC<IGenerationItemProps> = ({
+ className,
+ content,
+ messageId,
+ isLoading,
+ moreLikeThis,
+ isInWebApp = false,
+ feedback,
+ onFeedback,
+ onSave,
+ depth = 1,
+ isMobile
+}) => {
+ const { t } = useTranslation()
+ const isTop = depth === 1
+
+ const [completionRes, setCompletionRes] = useState('')
+ const [childMessageId, setChildMessageId] = useState<string | null>(null)
+ const hasChild = !!childMessageId
+ const [childFeedback, setChildFeedback] = useState<Feedbacktype>({
+ rating: null
+ })
+
+ const handleFeedback = async (childFeedback: Feedbacktype) => {
+ await updateFeedback({ url: `/messages/${childMessageId}/feedbacks`, body: { rating: childFeedback.rating } })
+ setChildFeedback(childFeedback)
+ }
+
+ const [isQuerying, { setTrue: startQuerying, setFalse: stopQuerying }] = useBoolean(false)
+
+ const childProps = {
+ isInWebApp: true,
+ content: completionRes,
+ messageId: childMessageId,
+ depth: depth + 1,
+ moreLikeThis: true,
+ onFeedback: handleFeedback,
+ isLoading: isQuerying,
+ feedback: childFeedback,
+ onSave,
+ isMobile
+ }
+
+ const handleMoreLikeThis = async () => {
+ if (isQuerying || !messageId) {
+ Toast.notify({ type: 'warning', message: t('appDebug.errorMessage.waitForResponse') })
+ return
+ }
+ startQuerying()
+ const res: any = await fetcMoreLikeThis(messageId as string)
+ setCompletionRes(res.answer)
+ setChildMessageId(res.id)
+ stopQuerying()
+ }
+
+ const mainStyle = (() => {
+ const res: any = !isTop ? {
+ background: depth % 2 === 0 ? 'linear-gradient(90.07deg, #F9FAFB 0.05%, rgba(249, 250, 251, 0) 99.93%)' : '#fff'
+ } : {}
+
+ if (hasChild) {
+ res.boxShadow = '0px 1px 2px rgba(16, 24, 40, 0.05)'
+ }
+ return res
+ })()
+ return (
+ <div className={cn(className, isTop ? 'rounded-xl border border-gray-200 bg-white' : 'rounded-br-xl !mt-0')}
+ style={isTop ? {
+ boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.05)'
+ } : {}}
+ >
+ {isLoading ? (
+ <div className='flex items-center h-10'><Loading type='area' /></div>
+ ) : (
+ <div
+ className={cn(!isTop && 'rounded-br-xl border-l-2 border-primary-400', 'p-4')}
+ style={mainStyle}
+ >
+ <Markdown content={content} />
+ {messageId && (
+ <div className='flex items-center justify-between mt-3'>
+ <div className='flex items-center'>
+ <SimpleBtn
+ className={cn(isMobile && '!px-1.5', 'space-x-1')}
+ onClick={() => {
+ copy(content)
+ Toast.notify({ type: 'success', message: t('common.actionMsg.copySuccessfully') })
+ }}>
+ {copyIcon}
+ {!isMobile && <div>{t('common.operation.copy')}</div>}
+ </SimpleBtn>
+ {isInWebApp && (
+ <>
+ <SimpleBtn
+ className={cn(isMobile && '!px-1.5', 'ml-2 space-x-1')}
+ onClick={() => { onSave?.(messageId as string) }}
+ >
+ {saveIcon}
+ {!isMobile && <div>{t('common.operation.save')}</div>}
+ </SimpleBtn>
+ {(moreLikeThis && depth < MAX_DEPTH) && (
+ <SimpleBtn
+ className={cn(isMobile && '!px-1.5', 'ml-2 space-x-1')}
+ onClick={handleMoreLikeThis}
+ >
+ {moreLikeThisIcon}
+ {!isMobile && <div>{t('appDebug.feature.moreLikeThis.title')}</div>}
+ </SimpleBtn>)}
+ <div className="mx-3 w-[1px] h-[14px] bg-gray-200"></div>
+ {!feedback?.rating && (
+ <SimpleBtn className="!px-0">
+ <>
+ <div
+ onClick={() => {
+ onFeedback?.({
+ rating: 'like'
+ })
+ }}
+ className='flex w-6 h-6 items-center justify-center rounded-md cursor-pointer hover:bg-gray-100'>
+ <HandThumbUpIcon width={16} height={16} />
+ </div>
+ <div
+ onClick={() => {
+ onFeedback?.({
+ rating: 'dislike'
+ })
+ }}
+ className='flex w-6 h-6 items-center justify-center rounded-md cursor-pointer hover:bg-gray-100'>
+ <HandThumbDownIcon width={16} height={16} />
+ </div>
+ </>
+ </SimpleBtn>
+ )}
+ {feedback?.rating === 'like' && (
+ <div
+ onClick={() => {
+ onFeedback?.({
+ rating: null
+ })
+ }}
+ className='flex w-7 h-7 items-center justify-center rounded-md cursor-pointer !text-primary-600 border border-primary-200 bg-primary-100 hover:border-primary-300 hover:bg-primary-200'>
+ <HandThumbUpIcon width={16} height={16} />
+ </div>
+ )}
+ {feedback?.rating === 'dislike' && (
+ <div
+ onClick={() => {
+ onFeedback?.({
+ rating: null
+ })
+ }}
+ className='flex w-7 h-7 items-center justify-center rounded-md cursor-pointer !text-red-600 border border-red-200 bg-red-100 hover:border-red-300 hover:bg-red-200'>
+ <HandThumbDownIcon width={16} height={16} />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <div className='text-xs text-gray-500'>{content?.length} {t('common.unit.char')}</div>
+ </div>
+ )}
+
+ </div>
+ )}
+
+
+ {((childMessageId || isQuerying) && depth < 3) && (
+ <div className='pl-4'>
+ <GenerationItem {...childProps} />
+ </div>
+ )}
+
+ </div>
+ )
+}
+export default React.memo(GenerationItem)
diff --git a/web/app/components/app/text-generate/saved-items/index.tsx b/web/app/components/app/text-generate/saved-items/index.tsx
new file mode 100644
index 00000000000..5c3a5dd8f8b
--- /dev/null
+++ b/web/app/components/app/text-generate/saved-items/index.tsx
@@ -0,0 +1,79 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import cn from 'classnames'
+import type { SavedMessage } from '@/models/debug'
+import { Markdown } from '@/app/components/base/markdown'
+import { SimpleBtn, copyIcon } from '@/app/components/app/text-generate/item'
+import copy from 'copy-to-clipboard'
+import Toast from '@/app/components/base/toast'
+import NoData from './no-data'
+
+export interface ISavedItemsProps {
+ className?: string
+ list: SavedMessage[],
+ onRemove: (id: string) => void
+ onStartCreateContent: () => void
+}
+
+const removeIcon = (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5.25 1.75H8.75M1.75 3.5H12.25M11.0833 3.5L10.6742 9.63625C10.6129 10.5569 10.5822 11.0172 10.3833 11.3663C10.2083 11.6735 9.94422 11.9206 9.62597 12.0748C9.26448 12.25 8.80314 12.25 7.88045 12.25H6.11955C5.19686 12.25 4.73552 12.25 4.37403 12.0748C4.05577 11.9206 3.79172 11.6735 3.61666 11.3663C3.41781 11.0172 3.38713 10.5569 3.32575 9.63625L2.91667 3.5M5.83333 6.125V9.04167M8.16667 6.125V9.04167" stroke="#344054" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const SavedItems: FC<ISavedItemsProps> = ({
+ className,
+ list,
+ onRemove,
+ onStartCreateContent
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className={cn(className, 'space-y-3')}>
+ {list.length === 0 ? (
+ <div className='px-6'>
+ <NoData onStartCreateContent={onStartCreateContent} />
+ </div>
+ ) : (<>
+ {list.map(({ id, answer }) => (
+ <div
+ key={id}
+ className='p-4 rounded-xl bg-gray-50'
+ style={{
+ boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.05)'
+ }}
+ >
+ <Markdown content={answer} />
+ <div className='flex items-center justify-between mt-3'>
+ <div className='flex items-center space-x-2'>
+ <SimpleBtn
+ className='space-x-1'
+ onClick={() => {
+ copy(answer)
+ Toast.notify({ type: 'success', message: t('common.actionMsg.copySuccessfully') })
+ }}>
+ {copyIcon}
+ <div>{t('common.operation.copy')}</div>
+ </SimpleBtn>
+
+ <SimpleBtn
+ className='space-x-1'
+ onClick={() => {
+ onRemove(id)
+ }}>
+ {removeIcon}
+ <div>{t('common.operation.remove')}</div>
+ </SimpleBtn>
+ </div>
+ <div className='text-xs text-gray-500'>{answer?.length} {t('common.unit.char')}</div>
+ </div>
+ </div>
+ ))}
+ </>)}
+
+ </div>
+ )
+}
+export default React.memo(SavedItems)
diff --git a/web/app/components/app/text-generate/saved-items/no-data/index.tsx b/web/app/components/app/text-generate/saved-items/no-data/index.tsx
new file mode 100644
index 00000000000..bd7fe29bc1b
--- /dev/null
+++ b/web/app/components/app/text-generate/saved-items/no-data/index.tsx
@@ -0,0 +1,50 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import { PlusIcon } from '@heroicons/react/24/outline'
+export interface INoDataProps {
+ onStartCreateContent: () => void
+}
+
+const markIcon = (
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M4.16699 6.5C4.16699 5.09987 4.16699 4.3998 4.43948 3.86502C4.67916 3.39462 5.06161 3.01217 5.53202 2.77248C6.0668 2.5 6.76686 2.5 8.16699 2.5H11.8337C13.2338 2.5 13.9339 2.5 14.4686 2.77248C14.939 3.01217 15.3215 3.39462 15.5612 3.86502C15.8337 4.3998 15.8337 5.09987 15.8337 6.5V17.5L10.0003 14.1667L4.16699 17.5V6.5Z" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+)
+
+const lightIcon = (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className="inline relative -top-3 -left-1.5"><path d="M5 6.5V5M8.93934 7.56066L10 6.5M10.0103 11.5H11.5103" stroke="#374151" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
+)
+
+const NoData: FC<INoDataProps> = ({
+ onStartCreateContent
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className='mt-[60px] px-5 py-4 rounded-2xl bg-gray-50 '>
+ <div className='flex items-center justify-center w-11 h-11 border border-gray-100 rounded-lg'>
+ {markIcon}
+ </div>
+ <div className='mt-2'>
+ <span className='text-gray-700 font-semibold'>{t('share.generation.savedNoData.title')}</span>
+ {lightIcon}
+ </div>
+ <div className='mt-2 text-gray-500 text-[13px] font-normal'>
+ {t('share.generation.savedNoData.description')}
+ </div>
+ <Button
+ className='mt-4 !h-8 !px-3'
+ onClick={onStartCreateContent}
+ >
+ <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
+ <PlusIcon className='w-4 h-4' />
+ <span>{t('share.generation.savedNoData.startCreateContent')}</span>
+ </div>
+ </Button>
+ </div>
+ )
+}
+
+export default React.memo(NoData)
diff --git a/web/app/components/base/app-icon/index.tsx b/web/app/components/base/app-icon/index.tsx
new file mode 100644
index 00000000000..d85bfca286c
--- /dev/null
+++ b/web/app/components/base/app-icon/index.tsx
@@ -0,0 +1,38 @@
+import type { FC } from 'react'
+import classNames from 'classnames'
+import style from './style.module.css'
+
+export type AppIconProps = {
+ size?: 'tiny' | 'small' | 'medium' | 'large'
+ rounded?: boolean
+ icon?: string
+ background?: string
+ className?: string
+ innerIcon?: React.ReactNode
+}
+
+const AppIcon: FC<AppIconProps> = ({
+ size = 'medium',
+ rounded = false,
+ background,
+ className,
+ innerIcon,
+}) => {
+ return (
+ <span
+ className={classNames(
+ style.appIcon,
+ size !== 'medium' && style[size],
+ rounded && style.rounded,
+ className ?? '',
+ )}
+ style={{
+ background,
+ }}
+ >
+ {innerIcon ? innerIcon : <>🤖</>}
+ </span>
+ )
+}
+
+export default AppIcon
diff --git a/web/app/components/base/app-icon/style.module.css b/web/app/components/base/app-icon/style.module.css
new file mode 100644
index 00000000000..43098fd9557
--- /dev/null
+++ b/web/app/components/base/app-icon/style.module.css
@@ -0,0 +1,15 @@
+.appIcon {
+ @apply flex items-center justify-center relative w-9 h-9 text-lg bg-teal-100 rounded-lg grow-0 shrink-0;
+}
+.appIcon.large {
+ @apply w-10 h-10;
+}
+.appIcon.small {
+ @apply w-8 h-8;
+}
+.appIcon.tiny {
+ @apply w-6 h-6 text-base;
+}
+.appIcon.rounded {
+ @apply rounded-full;
+}
diff --git a/web/app/components/base/app-unavailable.tsx b/web/app/components/base/app-unavailable.tsx
new file mode 100644
index 00000000000..037a6d69286
--- /dev/null
+++ b/web/app/components/base/app-unavailable.tsx
@@ -0,0 +1,28 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+
+interface IAppUnavailableProps {
+ code?: number
+ isUnknwonReason?: boolean
+ unknownReason?: string
+}
+
+const AppUnavailable: FC<IAppUnavailableProps> = ({
+ code = 404,
+ isUnknwonReason,
+ unknownReason,
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className='flex items-center justify-center w-screen h-screen'>
+ <h1 className='mr-5 h-[50px] leading-[50px] pr-5 text-[24px] font-medium'
+ style={{
+ borderRight: '1px solid rgba(0,0,0,.3)',
+ }}>{code}</h1>
+ <div className='text-sm'>{unknownReason || (isUnknwonReason ? t('share.common.appUnkonwError') : t('share.common.appUnavailable'))}</div>
+ </div>
+ )
+}
+export default React.memo(AppUnavailable)
diff --git a/web/app/components/base/auto-height-textarea/index.tsx b/web/app/components/base/auto-height-textarea/index.tsx
new file mode 100644
index 00000000000..42fd9ccf35e
--- /dev/null
+++ b/web/app/components/base/auto-height-textarea/index.tsx
@@ -0,0 +1,75 @@
+import { forwardRef, useEffect, useRef } from 'react'
+import cn from 'classnames'
+
+type IProps = {
+ placeholder?: string
+ value: string
+ onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
+ className?: string
+ minHeight?: number
+ maxHeight?: number
+ autoFocus?: boolean
+ controlFocus?: number
+ onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
+ onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
+}
+
+const AutoHeightTextarea = forwardRef(
+ (
+ { value, onChange, placeholder, className, minHeight = 36, maxHeight = 96, autoFocus, controlFocus, onKeyDown, onKeyUp }: IProps,
+ outerRef: any,
+ ) => {
+ const ref = outerRef || useRef<HTMLTextAreaElement>(null)
+
+ const doFocus = () => {
+ if (ref.current) {
+ // console.log('focus')
+ ref.current.setSelectionRange(value.length, value.length)
+ ref.current.focus()
+ return true
+ }
+ // console.log(autoFocus, 'not focus')
+ return false
+ }
+
+ const focus = () => {
+ if (!doFocus()) {
+ let hasFocus = false
+ const runId = setInterval(() => {
+ hasFocus = doFocus()
+ if (hasFocus)
+ clearInterval(runId)
+ }, 100)
+ }
+ }
+
+ useEffect(() => {
+ if (autoFocus)
+ focus()
+ }, [])
+ useEffect(() => {
+ if (controlFocus)
+ focus()
+ }, [controlFocus])
+
+ return (
+ <div className='relative'>
+ <div className={cn(className, 'invisible whitespace-pre-wrap break-all overflow-y-auto')} style={{ minHeight, maxHeight }}>
+ {!value ? placeholder : value.replace(/\n$/, '\n ')}
+ </div>
+ <textarea
+ ref={ref}
+ autoFocus={autoFocus}
+ className={cn(className, 'absolute inset-0 resize-none overflow-hidden')}
+ placeholder={placeholder}
+ onChange={onChange}
+ onKeyDown={onKeyDown}
+ onKeyUp={onKeyUp}
+ value={value}
+ />
+ </div>
+ )
+ },
+)
+
+export default AutoHeightTextarea
diff --git a/web/app/components/base/auto-height-textarea/style.module.scss b/web/app/components/base/auto-height-textarea/style.module.scss
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/web/app/components/base/avatar/index.tsx b/web/app/components/base/avatar/index.tsx
new file mode 100644
index 00000000000..cd8177eb06d
--- /dev/null
+++ b/web/app/components/base/avatar/index.tsx
@@ -0,0 +1,45 @@
+'use client'
+import cn from 'classnames'
+
+interface IAvatarProps {
+ name: string
+ avatar?: string
+ size?: number
+ className?: string
+}
+const Avatar = ({
+ name,
+ avatar,
+ size = 30,
+ className
+}: IAvatarProps) => {
+ const avatarClassName = `shrink-0 flex items-center rounded-full bg-primary-600`
+ const style = { width: `${size}px`, height:`${size}px`, fontSize: `${size}px`, lineHeight: `${size}px` }
+
+ if (avatar) {
+ return (
+ <img
+ className={cn(avatarClassName, className)}
+ style={style}
+ alt={name}
+ src={avatar}
+ />
+ )
+ }
+
+ return (
+ <div
+ className={cn(avatarClassName, className)}
+ style={style}
+ >
+ <div
+ className={`text-center text-white scale-[0.4]`}
+ style={style}
+ >
+ {name[0].toLocaleUpperCase()}
+ </div>
+ </div>
+ )
+}
+
+export default Avatar
\ No newline at end of file
diff --git a/web/app/components/base/block-input/index.tsx b/web/app/components/base/block-input/index.tsx
new file mode 100644
index 00000000000..6722da8ea30
--- /dev/null
+++ b/web/app/components/base/block-input/index.tsx
@@ -0,0 +1,174 @@
+'use client'
+
+import type { ChangeEvent, FC } from 'react'
+import React, { useCallback, useEffect, useRef, useState } from 'react'
+import classNames from 'classnames'
+import { checkKeys } from '@/utils/var'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import Toast from '../toast'
+import { varHighlightHTML } from '../../app/configuration/base/var-highlight'
+
+// regex to match the {{}} and replace it with a span
+const regex = /\{\{([^}]+)\}\}/g
+
+export const getInputKeys = (value: string) => {
+ const keys = value.match(regex)?.map((item) => {
+ return item.replace('{{', '').replace('}}', '')
+ }) || []
+ const keyObj: Record<string, boolean> = {}
+ // remove duplicate keys
+ const res: string[] = []
+ keys.forEach((key) => {
+ if (keyObj[key])
+ return
+
+ keyObj[key] = true
+ res.push(key)
+ })
+ return res
+}
+
+export type IBlockInputProps = {
+ value: string
+ className?: string // wrapper class
+ highLightClassName?: string // class for the highlighted text default is text-blue-500
+ onConfirm?: (value: string, keys: string[]) => void
+}
+
+const BlockInput: FC<IBlockInputProps> = ({
+ value = '',
+ className,
+ onConfirm,
+}) => {
+ const { t } = useTranslation()
+ // current is used to store the current value of the contentEditable element
+ const [currentValue, setCurrentValue] = useState<string>(value)
+ useEffect(() => {
+ setCurrentValue(value)
+ }, [value])
+
+ const isContentChanged = value !== currentValue
+
+ const contentEditableRef = useRef<HTMLTextAreaElement>(null)
+ const [isEditing, setIsEditing] = useState<boolean>(false)
+ useEffect(() => {
+ if (isEditing && contentEditableRef.current) {
+ // TODO: Focus at the click positon
+ if (currentValue) {
+ contentEditableRef.current.setSelectionRange(currentValue.length, currentValue.length)
+ }
+ contentEditableRef.current.focus()
+ }
+ }, [isEditing])
+
+ const style = classNames({
+ 'block px-4 py-1 w-full h-full text-sm text-gray-900 outline-0 border-0': true,
+ 'block-input--editing': isEditing,
+ })
+
+ const coloredContent = (currentValue || '')
+ .replace(regex, varHighlightHTML({ name: '$1' })) // `<span class="${highLightClassName}">{{$1}}</span>`
+ .replace(/\n/g, '<br />')
+
+ // Not use useCallback. That will cause out callback get old data.
+ const handleSubmit = () => {
+ if (onConfirm) {
+ const value = currentValue
+ const keys = getInputKeys(value)
+ const { isValid, errorKey, errorMessageKey } = checkKeys(keys)
+ if (!isValid) {
+ Toast.notify({
+ type: 'error',
+ message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey })
+ })
+ return
+ }
+ onConfirm(value, keys)
+ setIsEditing(false)
+ }
+ }
+
+ const handleCancel = useCallback(() => {
+ setIsEditing(false)
+ setCurrentValue(value)
+ }, [value])
+
+ const onValueChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
+ setCurrentValue(e.target.value)
+ }, [])
+
+ // Prevent rerendering caused cursor to jump to the start of the contentEditable element
+ const TextAreaContentView = () => {
+ return <div
+ className={classNames(style, className)}
+ dangerouslySetInnerHTML={{ __html: coloredContent }}
+ suppressContentEditableWarning={true}
+ />
+ }
+
+ const placeholder = ''
+ const editAreaClassName = 'focus:outline-none bg-transparent text-sm'
+
+ const textAreaContent = (
+ <div className='h-[180px] overflow-y-auto' onClick={() => setIsEditing(true)}>
+ {isEditing
+ ? <div className='h-full px-4 py-1'>
+ <textarea
+ ref={contentEditableRef}
+ className={classNames(editAreaClassName, 'block w-full h-full absolut3e resize-none')}
+ placeholder={placeholder}
+ onChange={onValueChange}
+ value={currentValue}
+ onBlur={() => {
+ blur()
+ if (!isContentChanged) {
+ setIsEditing(false)
+ }
+ // click confirm also make blur. Then outter value is change. So below code has problem.
+ // setTimeout(() => {
+ // handleCancel()
+ // }, 1000)
+ }}
+ />
+ </div>
+ : <TextAreaContentView />}
+ </div>)
+
+ return (
+ <div className={classNames('block-input w-full overflow-y-auto border-none rounded-lg')}>
+ {textAreaContent}
+ {/* footer */}
+ <div className='flex item-center h-14 px-4'>
+ {isContentChanged ? (
+ <div className='flex items-center justify-between w-full'>
+ <div className="h-[18px] leading-[18px] px-1 rounded-md bg-gray-100 text-xs text-gray-500">{currentValue.length}</div>
+ <div className='flex space-x-2'>
+ <Button
+ onClick={handleCancel}
+ className='w-20 !h-8 !text-[13px]'
+ >
+ {t('common.operation.cancel')}
+ </Button>
+ <Button
+ onClick={handleSubmit}
+ type="primary"
+ className='w-20 !h-8 !text-[13px]'
+ >
+ {t('common.operation.confirm')}
+ </Button>
+ </div>
+
+ </div>
+ ) : (
+ <p className="leading-5 text-xs text-gray-500">
+ {t('appDebug.promptTip')}
+ </p>
+ )}
+ </div>
+
+ </div>
+ )
+}
+
+export default React.memo(BlockInput)
diff --git a/web/app/components/base/button/index.tsx b/web/app/components/base/button/index.tsx
new file mode 100644
index 00000000000..cbf1533eb62
--- /dev/null
+++ b/web/app/components/base/button/index.tsx
@@ -0,0 +1,47 @@
+import type { FC, MouseEventHandler } from 'react'
+import React from 'react'
+import Spinner from '../spinner'
+
+export type IButtonProps = {
+ type?: string
+ className?: string
+ disabled?: boolean
+ loading?: boolean
+ children: React.ReactNode
+ onClick?: MouseEventHandler<HTMLDivElement>
+}
+
+const Button: FC<IButtonProps> = ({
+ type,
+ disabled,
+ children,
+ className,
+ onClick,
+ loading = false,
+}) => {
+ let style = 'cursor-pointer'
+ switch (type) {
+ case 'primary':
+ style = (disabled || loading) ? 'bg-primary-200 cursor-not-allowed text-white' : 'bg-primary-600 hover:bg-primary-600/75 hover:shadow-md cursor-pointer text-white hover:shadow-sm'
+ break
+ case 'warning':
+ style = (disabled || loading) ? 'bg-red-600/75 cursor-not-allowed text-white' : 'bg-red-600 hover:bg-red-600/75 hover:shadow-md cursor-pointer text-white hover:shadow-sm'
+ break
+ default:
+ style = disabled ? 'border-solid border border-gray-200 bg-gray-200 cursor-not-allowed text-gray-800' : 'border-solid border border-gray-200 cursor-pointer text-gray-500 hover:bg-white hover:shadow-sm hover:border-gray-300'
+ break
+ }
+
+ return (
+ <div
+ className={`inline-flex justify-center items-center content-center h-9 leading-5 rounded-lg px-4 py-2 text-base ${style} ${className && className}`}
+ onClick={disabled ? undefined : onClick}
+ >
+ {children}
+ {/* Spinner is hidden when loading is false */}
+ <Spinner loading={loading} className='!text-white !h-3 !w-3 !border-2 !ml-1' />
+ </div>
+ )
+}
+
+export default React.memo(Button)
diff --git a/web/app/components/base/confirm-ui/index.tsx b/web/app/components/base/confirm-ui/index.tsx
new file mode 100644
index 00000000000..3b74386d9f8
--- /dev/null
+++ b/web/app/components/base/confirm-ui/index.tsx
@@ -0,0 +1,51 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+
+export type IConfirmUIProps = {
+ type: 'info' | 'warning'
+ title: string
+ content: string
+ confirmText?: string
+ onConfirm: () => void
+ cancelText?: string
+ onCancel: () => void
+}
+
+const ConfirmUI: FC<IConfirmUIProps> = ({
+ type,
+ title,
+ content,
+ confirmText,
+ cancelText,
+ onConfirm,
+ onCancel,
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div className="w-[420px] rounded-lg p-7 bg-white">
+ <div className='flex items-center'>
+ {type === 'info' && (<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M17.3333 21.3333H16V16H14.6667M16 10.6667H16.0133M28 16C28 17.5759 27.6896 19.1363 27.0866 20.5922C26.4835 22.0481 25.5996 23.371 24.4853 24.4853C23.371 25.5996 22.0481 26.4835 20.5922 27.0866C19.1363 27.6896 17.5759 28 16 28C14.4241 28 12.8637 27.6896 11.4078 27.0866C9.95189 26.4835 8.62902 25.5996 7.51472 24.4853C6.40042 23.371 5.5165 22.0481 4.91345 20.5922C4.31039 19.1363 4 17.5759 4 16C4 12.8174 5.26428 9.76516 7.51472 7.51472C9.76516 5.26428 12.8174 4 16 4C19.1826 4 22.2348 5.26428 24.4853 7.51472C26.7357 9.76516 28 12.8174 28 16Z" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>)}
+ {type === 'warning' && (<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M16 10.6667V16M16 21.3333H16.0133M28 16C28 17.5759 27.6896 19.1363 27.0866 20.5922C26.4835 22.0481 25.5996 23.371 24.4853 24.4853C23.371 25.5996 22.0481 26.4835 20.5922 27.0866C19.1363 27.6896 17.5759 28 16 28C14.4241 28 12.8637 27.6896 11.4078 27.0866C9.95189 26.4835 8.62902 25.5996 7.51472 24.4853C6.40042 23.371 5.5165 22.0481 4.91345 20.5922C4.31039 19.1363 4 17.5759 4 16C4 12.8174 5.26428 9.76516 7.51472 7.51472C9.76516 5.26428 12.8174 4 16 4C19.1826 4 22.2348 5.26428 24.4853 7.51472C26.7357 9.76516 28 12.8174 28 16Z" stroke="#FACA15" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ )}
+ <div className='ml-4 text-lg text-gray-900'>{title}</div>
+ </div>
+
+ <div className='mt-1 ml-12'>
+ <div className='text-sm leading-normal text-gray-500'>{content}</div>
+ </div>
+
+ <div className='flex gap-3 mt-4 ml-12'>
+ <div onClick={onConfirm} className='w-20 leading-9 text-center text-white border rounded-lg cursor-pointer h-9 border-color-primary-700 bg-primary-700'>{confirmText || t('common.operation.confirm')}</div>
+ <div onClick={onCancel} className='w-20 leading-9 text-center text-gray-500 border rounded-lg cursor-pointer h-9 border-color-gray-200'>{cancelText || t('common.operation.cancel')}</div>
+ </div>
+ </div>
+
+ )
+}
+export default React.memo(ConfirmUI)
diff --git a/web/app/components/base/confirm/index.tsx b/web/app/components/base/confirm/index.tsx
new file mode 100644
index 00000000000..7d61ee8f62c
--- /dev/null
+++ b/web/app/components/base/confirm/index.tsx
@@ -0,0 +1,79 @@
+import { Dialog, Transition } from '@headlessui/react'
+import { Fragment } from 'react'
+import ConfirmUI from '../confirm-ui'
+import { useTranslation } from 'react-i18next'
+
+// https://headlessui.com/react/dialog
+
+type IConfirm = {
+ className?: string
+ isShow: boolean
+ onClose: () => void
+ type?: 'info' | 'warning'
+ title: string
+ content: string
+ confirmText?: string
+ onConfirm: () => void
+ cancelText?: string
+ onCancel: () => void
+}
+
+export default function Confirm({
+ isShow,
+ onClose,
+ type = 'warning',
+ title,
+ content,
+ confirmText,
+ cancelText,
+ onConfirm,
+ onCancel,
+}: IConfirm) {
+ const { t } = useTranslation()
+ const confirmTxt = confirmText || `${t('common.operation.confirm')}`
+ const cancelTxt = cancelText || `${t('common.operation.cancel')}`
+ return (
+ <Transition appear show={isShow} as={Fragment}>
+ <Dialog as="div" className="relative z-10" onClose={onClose} onClick={e => e.preventDefault()}>
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0"
+ enterTo="opacity-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100"
+ leaveTo="opacity-0"
+ >
+ <div className="fixed inset-0 bg-black bg-opacity-25" />
+ </Transition.Child>
+
+ <div className="fixed inset-0 overflow-y-auto">
+ <div className="flex items-center justify-center min-h-full p-4 text-center">
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0 scale-95"
+ enterTo="opacity-100 scale-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100 scale-100"
+ leaveTo="opacity-0 scale-95"
+ >
+ <Dialog.Panel className={'w-full max-w-md transform overflow-hidden rounded-2xl bg-white text-left align-middle shadow-xl transition-all'}>
+ <ConfirmUI
+ type={type}
+ title={title}
+ content={content}
+ confirmText={confirmTxt}
+ cancelText={cancelTxt}
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ />
+ </Dialog.Panel>
+ </Transition.Child>
+
+ </div>
+ </div>
+ </Dialog>
+ </Transition>
+ )
+}
diff --git a/web/app/components/base/custom-icon/index.tsx b/web/app/components/base/custom-icon/index.tsx
new file mode 100644
index 00000000000..c3afee952b3
--- /dev/null
+++ b/web/app/components/base/custom-icon/index.tsx
@@ -0,0 +1,16 @@
+import type { FC } from 'react'
+import React from 'react'
+
+type IconProps = {
+ icon: any
+ className?: string
+ [key: string]: any
+}
+
+const Icon: FC<IconProps> = ({ icon, className, ...other }) => {
+ return (
+ <img src={icon} className={`h-3 w-3 ${className}`} {...other} alt="icon" />
+ )
+}
+
+export default Icon
diff --git a/web/app/components/base/dialog/index.tsx b/web/app/components/base/dialog/index.tsx
new file mode 100644
index 00000000000..9e208d55ec6
--- /dev/null
+++ b/web/app/components/base/dialog/index.tsx
@@ -0,0 +1,86 @@
+import { Fragment, useCallback } from 'react'
+import type { ElementType, ReactNode } from 'react'
+import { Dialog, Transition } from '@headlessui/react'
+import classNames from 'classnames'
+
+// https://headlessui.com/react/dialog
+
+type DialogProps = {
+ className?: string
+ titleClassName?: string
+ bodyClassName?: string
+ footerClassName?: string
+ titleAs?: ElementType
+ title?: ReactNode
+ children: ReactNode
+ footer?: ReactNode
+ show: boolean
+ onClose?: () => void
+}
+
+const CustomDialog = ({
+ className,
+ titleClassName,
+ bodyClassName,
+ footerClassName,
+ titleAs,
+ title,
+ children,
+ footer,
+ show,
+ onClose,
+}: DialogProps) => {
+ const close = useCallback(() => onClose?.(), [onClose])
+ return (
+ <Transition appear show={show} as={Fragment}>
+ <Dialog as="div" className="relative z-10" onClose={close}>
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0"
+ enterTo="opacity-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100"
+ leaveTo="opacity-0"
+ >
+ <div className="fixed inset-0 bg-black bg-opacity-25" />
+ </Transition.Child>
+
+ <div className="fixed inset-0 overflow-y-auto">
+ <div className="flex items-center justify-center min-h-full p-4 text-center">
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0 scale-95"
+ enterTo="opacity-100 scale-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100 scale-100"
+ leaveTo="opacity-0 scale-95"
+ >
+ <Dialog.Panel className={classNames('w-full max-w-[800px] p-0 overflow-hidden text-left text-gray-900 align-middle transition-all transform bg-white shadow-xl rounded-2xl', className)}>
+ {Boolean(title) && (
+ <Dialog.Title
+ as={titleAs || 'h3'}
+ className={classNames('px-8 py-6 text-lg font-medium leading-6 text-gray-900', titleClassName)}
+ >
+ {title}
+ </Dialog.Title>
+ )}
+ <div className={classNames('px-8 text-lg font-medium leading-6', bodyClassName)}>
+ {children}
+ </div>
+ {Boolean(footer) && (
+ <div className={classNames('flex items-center justify-end gap-2 px-8 py-6', footerClassName)}>
+ {footer}
+ </div>
+ )}
+ </Dialog.Panel>
+ </Transition.Child>
+ </div>
+ </div>
+ </Dialog>
+ </Transition >
+ )
+}
+
+export default CustomDialog
diff --git a/web/app/components/base/divider/index.tsx b/web/app/components/base/divider/index.tsx
new file mode 100644
index 00000000000..85ce8861996
--- /dev/null
+++ b/web/app/components/base/divider/index.tsx
@@ -0,0 +1,18 @@
+import type { CSSProperties, FC } from 'react'
+import React from 'react'
+import s from './style.module.css'
+
+type Props = {
+ type?: 'horizontal' | 'vertical'
+ // orientation?: 'left' | 'right' | 'center'
+ className?: string
+ style?: CSSProperties
+}
+
+const Divider: FC<Props> = ({ type = 'horizontal', className = '', style }) => {
+ return (
+ <div className={`${s.divider} ${s[type]} ${className}`} style={style}></div>
+ )
+}
+
+export default Divider
diff --git a/web/app/components/base/divider/style.module.css b/web/app/components/base/divider/style.module.css
new file mode 100644
index 00000000000..9cb2601b1f9
--- /dev/null
+++ b/web/app/components/base/divider/style.module.css
@@ -0,0 +1,9 @@
+.divider {
+ @apply bg-gray-200;
+}
+.horizontal {
+ @apply w-full h-[0.5px] my-2;
+}
+.vertical {
+ @apply w-[1px] h-full mx-2;
+}
diff --git a/web/app/components/base/drawer/index.tsx b/web/app/components/base/drawer/index.tsx
new file mode 100644
index 00000000000..7518b4d4f0b
--- /dev/null
+++ b/web/app/components/base/drawer/index.tsx
@@ -0,0 +1,75 @@
+'use client'
+import { Dialog } from '@headlessui/react'
+import { useTranslation } from 'react-i18next'
+import Button from '../button'
+
+type DrawerProps = {
+ title?: string
+ description?: string
+ panelClassname?: string
+ children: React.ReactNode
+ footer?: React.ReactNode
+ mask?: boolean
+ isOpen: boolean
+ // closable: boolean
+ onClose: () => void
+ onCancel?: () => void
+ onOk?: () => void
+}
+
+export default function Drawer({
+ title = '',
+ description = '',
+ panelClassname = '',
+ children,
+ footer,
+ mask = true,
+ isOpen,
+ onClose,
+ onCancel,
+ onOk,
+}: DrawerProps) {
+ const { t } = useTranslation()
+ return (
+ <Dialog
+ unmount={false}
+ open={isOpen}
+ onClose={() => onClose()}
+ className="fixed z-30 inset-0 overflow-y-auto"
+ >
+ <div className="flex w-screen h-screen justify-end">
+ {/* mask */}
+ <Dialog.Overlay
+ className={`z-40 fixed inset-0 ${!mask ? '' : 'bg-black bg-opacity-30'}`}
+ />
+ <div className={`z-50 flex flex-col justify-between bg-white w-full
+ max-w-sm p-6 overflow-hidden text-left align-middle
+ shadow-xl ${panelClassname}`}>
+ <>
+ {title && <Dialog.Title
+ as="h3"
+ className="text-lg font-medium leading-6 text-gray-900"
+ >
+ {title}
+ </Dialog.Title>}
+ {description && <Dialog.Description className='text-gray-500 text-xs font-normal mt-2'>{description}</Dialog.Description>}
+ {children}
+ </>
+ {footer || (footer === null
+ ? null
+ : <div className="mt-10 flex flex-row justify-end">
+ <Button
+ className='mr-2'
+ onClick={() => {
+ onCancel && onCancel()
+ }}>{t('common.operation.cancel')}</Button>
+ <Button
+ onClick={() => {
+ onOk && onOk()
+ }}>{t('common.operation.save')}</Button>
+ </div>)}
+ </div>
+ </div>
+ </Dialog>
+ )
+}
diff --git a/web/app/components/base/ga/index.tsx b/web/app/components/base/ga/index.tsx
new file mode 100644
index 00000000000..379e98c5381
--- /dev/null
+++ b/web/app/components/base/ga/index.tsx
@@ -0,0 +1,37 @@
+import React, { FC } from 'react'
+import Script from 'next/script'
+
+export enum GaType {
+ admin = 'admin',
+ webapp = 'webapp',
+}
+
+const gaIdMaps = {
+ [GaType.admin]: 'G-DM9497FN4V',
+ [GaType.webapp]: 'G-2MFWXK7WYT',
+}
+
+export interface IGAProps {
+ gaType: GaType
+}
+
+
+const GA: FC<IGAProps> = ({
+ gaType
+}) => {
+ return (
+ <Script
+ id="gtag-base"
+ strategy="beforeInteractive"
+ dangerouslySetInnerHTML={{
+ __html: `
+ (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
+ new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
+ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
+ 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
+ })(window,document,'script','dataLayer', '${gaIdMaps[gaType]}');
+ `,
+ }} />
+ )
+}
+export default React.memo(GA)
diff --git a/web/app/components/base/input/index.tsx b/web/app/components/base/input/index.tsx
new file mode 100644
index 00000000000..eff2cee7492
--- /dev/null
+++ b/web/app/components/base/input/index.tsx
@@ -0,0 +1,45 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import s from './style.module.css'
+
+type InputProps = {
+ placeholder?: string
+ value?: string
+ defaultValue?: string
+ onChange?: (v: any) => void
+ className?: string
+ wrapperClassName?: string
+ type?: string
+ showPrefix?: React.ReactNode
+ prefixIcon?: React.ReactNode
+}
+
+const GlassIcon: FC<{ className?: string }> = ({ className }) => (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M12.25 12.25L10.2084 10.2083M11.6667 6.70833C11.6667 9.44675 9.44675 11.6667 6.70833 11.6667C3.96992 11.6667 1.75 9.44675 1.75 6.70833C1.75 3.96992 3.96992 1.75 6.70833 1.75C9.44675 1.75 11.6667 3.96992 11.6667 6.70833Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+)
+
+const Input: FC<InputProps> = ({ value, defaultValue, onChange, className = '', wrapperClassName = '', placeholder, type, showPrefix, prefixIcon }) => {
+ const [localValue, setLocalValue] = useState(value ?? defaultValue)
+ const { t } = useTranslation()
+ return (
+ <div className={`relative inline-flex w-full ${wrapperClassName}`}>
+ {showPrefix && <span className={s.prefix}>{prefixIcon ?? <GlassIcon className='h-3.5 w-3.5 stroke-current text-gray-700 stroke-2' />}</span>}
+ <input
+ type={type ?? 'text'}
+ className={`${s.input} ${showPrefix ? '!pl-7' : ''} ${className}`}
+ placeholder={placeholder ?? (showPrefix ? t('common.operation.search') : 'please input')}
+ value={localValue}
+ onChange={(e) => {
+ setLocalValue(e.target.value)
+ onChange && onChange(e.target.value)
+ }}
+ />
+ </div>
+ )
+}
+
+export default Input
diff --git a/web/app/components/base/input/style.module.css b/web/app/components/base/input/style.module.css
new file mode 100644
index 00000000000..5f2782777d6
--- /dev/null
+++ b/web/app/components/base/input/style.module.css
@@ -0,0 +1,7 @@
+.input {
+ @apply inline-flex h-7 w-full py-1 px-2 rounded-lg text-xs leading-normal;
+ @apply bg-gray-100 caret-primary-600 hover:bg-gray-100 focus:ring-1 focus:ring-inset focus:ring-gray-200 focus-visible:outline-none focus:bg-white placeholder:text-gray-400;
+}
+.prefix {
+ @apply whitespace-nowrap absolute left-2 self-center
+}
diff --git a/web/app/components/base/loading/index.tsx b/web/app/components/base/loading/index.tsx
new file mode 100644
index 00000000000..366a139d060
--- /dev/null
+++ b/web/app/components/base/loading/index.tsx
@@ -0,0 +1,29 @@
+import React from 'react'
+
+import './style.css'
+interface ILoadingProps {
+ type?: 'area' | 'app'
+}
+const Loading = (
+ { type = 'area' }: ILoadingProps = { type: 'area' }
+) => {
+ return (
+ <div className={`flex w-full justify-center items-center ${type === 'app' ? 'h-full' : ''}`}>
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className='spin-animation'>
+ <g clipPath="url(#clip0_324_2488)">
+ <path d="M15 0H10C9.44772 0 9 0.447715 9 1V6C9 6.55228 9.44772 7 10 7H15C15.5523 7 16 6.55228 16 6V1C16 0.447715 15.5523 0 15 0Z" fill="#1C64F2" />
+ <path opacity="0.5" d="M15 9H10C9.44772 9 9 9.44772 9 10V15C9 15.5523 9.44772 16 10 16H15C15.5523 16 16 15.5523 16 15V10C16 9.44772 15.5523 9 15 9Z" fill="#1C64F2" />
+ <path opacity="0.1" d="M6 9H1C0.447715 9 0 9.44772 0 10V15C0 15.5523 0.447715 16 1 16H6C6.55228 16 7 15.5523 7 15V10C7 9.44772 6.55228 9 6 9Z" fill="#1C64F2" />
+ <path opacity="0.2" d="M6 0H1C0.447715 0 0 0.447715 0 1V6C0 6.55228 0.447715 7 1 7H6C6.55228 7 7 6.55228 7 6V1C7 0.447715 6.55228 0 6 0Z" fill="#1C64F2" />
+ </g>
+ <defs>
+ <clipPath id="clip0_324_2488">
+ <rect width="16" height="16" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+
+ </div>
+ )
+}
+export default Loading
diff --git a/web/app/components/base/loading/style.css b/web/app/components/base/loading/style.css
new file mode 100644
index 00000000000..40402e1a9d9
--- /dev/null
+++ b/web/app/components/base/loading/style.css
@@ -0,0 +1,41 @@
+.spin-animation path {
+ animation: custom 2s linear infinite;
+}
+
+@keyframes custom {
+ 0% {
+ opacity: 0;
+ }
+
+ 25% {
+ opacity: 0.1;
+ }
+
+ 50% {
+ opacity: 0.2;
+ }
+
+ 75% {
+ opacity: 0.5;
+ }
+
+ 100% {
+ opacity: 1;
+ }
+}
+
+.spin-animation path:nth-child(1) {
+ animation-delay: 0s;
+}
+
+.spin-animation path:nth-child(2) {
+ animation-delay: 0.5s;
+}
+
+.spin-animation path:nth-child(3) {
+ animation-delay: 1s;
+}
+
+.spin-animation path:nth-child(4) {
+ animation-delay: 1.5s;
+}
\ No newline at end of file
diff --git a/web/app/components/base/markdown.tsx b/web/app/components/base/markdown.tsx
new file mode 100644
index 00000000000..ca2cc35814f
--- /dev/null
+++ b/web/app/components/base/markdown.tsx
@@ -0,0 +1,87 @@
+import ReactMarkdown from "react-markdown";
+import "katex/dist/katex.min.css";
+import RemarkMath from "remark-math";
+import RemarkBreaks from "remark-breaks";
+import RehypeKatex from "rehype-katex";
+import RemarkGfm from "remark-gfm";
+import SyntaxHighlighter from 'react-syntax-highlighter'
+import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
+import { useRef, useState, RefObject, useEffect } from "react";
+// import { copyToClipboard } from "../utils";
+
+export function PreCode(props: { children: any }) {
+ const ref = useRef<HTMLPreElement>(null);
+
+ return (
+ <pre ref={ref}>
+ <span
+ className="copy-code-button"
+ onClick={() => {
+ if (ref.current) {
+ const code = ref.current.innerText;
+ // copyToClipboard(code);
+ }
+ }}
+ ></span>
+ {props.children}
+ </pre>
+ );
+}
+
+const useLazyLoad = (ref: RefObject<Element>): boolean => {
+ const [isIntersecting, setIntersecting] = useState<boolean>(false);
+
+ useEffect(() => {
+ const observer = new IntersectionObserver(([entry]) => {
+ if (entry.isIntersecting) {
+ setIntersecting(true);
+ observer.disconnect();
+ }
+ });
+
+ if (ref.current) {
+ observer.observe(ref.current);
+ }
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [ref]);
+
+ return isIntersecting;
+};
+
+export function Markdown(props: { content: string }) {
+ return (
+ <div className="markdown-body">
+ <ReactMarkdown
+ remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
+ rehypePlugins={[
+ RehypeKatex,
+ ]}
+ components={{
+ code({ node, inline, className, children, ...props }) {
+ const match = /language-(\w+)/.exec(className || '')
+ return !inline && match ? (
+ <SyntaxHighlighter
+ {...props}
+ children={String(children).replace(/\n$/, '')}
+ style={atelierHeathLight}
+ language={match[1]}
+ showLineNumbers
+ PreTag="div"
+ />
+ ) : (
+ <code {...props} className={className}>
+ {children}
+ </code>
+ )
+ }
+ }}
+ linkTarget={"_blank"}
+ >
+ {props.content}
+ </ReactMarkdown>
+ </div>
+ );
+}
diff --git a/web/app/components/base/modal/index.tsx b/web/app/components/base/modal/index.tsx
new file mode 100644
index 00000000000..bc33ac8e0a3
--- /dev/null
+++ b/web/app/components/base/modal/index.tsx
@@ -0,0 +1,73 @@
+import { Dialog, Transition } from '@headlessui/react'
+import { Fragment } from 'react'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+// https://headlessui.com/react/dialog
+
+type IModal = {
+ className?: string
+ isShow: boolean
+ onClose: () => void
+ title?: React.ReactNode
+ description?: React.ReactNode
+ children: React.ReactNode
+ closable?: boolean
+}
+
+export default function Modal({
+ className,
+ isShow,
+ onClose,
+ title,
+ description,
+ children,
+ closable = false,
+}: IModal) {
+ return (
+ <Transition appear show={isShow} as={Fragment}>
+ <Dialog as="div" className="relative z-10" onClose={onClose}>
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0"
+ enterTo="opacity-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100"
+ leaveTo="opacity-0"
+ >
+ <div className="fixed inset-0 bg-black bg-opacity-25" />
+ </Transition.Child>
+
+ <div className="fixed inset-0 overflow-y-auto">
+ <div className="flex min-h-full items-center justify-center p-4 text-center">
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0 scale-95"
+ enterTo="opacity-100 scale-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100 scale-100"
+ leaveTo="opacity-0 scale-95"
+ >
+ <Dialog.Panel className={`w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all ${className}`}>
+ {title && <Dialog.Title
+ as="h3"
+ className="text-lg font-medium leading-6 text-gray-900"
+ >
+ {title}
+ </Dialog.Title>}
+ {description && <Dialog.Description className='text-gray-500 text-xs font-normal mt-2'>
+ {description}
+ </Dialog.Description>}
+ {closable
+ && <div className='absolute top-6 right-6 w-5 h-5 rounded-2xl flex items-center justify-center hover:cursor-pointer hover:bg-gray-100'>
+ <XMarkIcon className='w-4 h-4 text-gray-500' onClick={onClose} />
+ </div>}
+ {children}
+ </Dialog.Panel>
+ </Transition.Child>
+ </div>
+ </div>
+ </Dialog>
+ </Transition>
+ )
+}
diff --git a/web/app/components/base/pagination/index.tsx b/web/app/components/base/pagination/index.tsx
new file mode 100644
index 00000000000..98b1e266ae0
--- /dev/null
+++ b/web/app/components/base/pagination/index.tsx
@@ -0,0 +1,52 @@
+import type { FC } from 'react'
+import React from 'react'
+import { Pagination } from 'react-headless-pagination'
+import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import s from './style.module.css'
+
+type Props = {
+ current: number
+ onChange: (cur: number) => void
+ total: number
+ limit?: number
+}
+
+const CustomizedPagination: FC<Props> = ({ current, onChange, total, limit = 10 }) => {
+ const { t } = useTranslation()
+ const totalPages = Math.ceil(total / limit)
+ return (
+ <Pagination
+ className="flex items-center w-full h-10 text-sm select-none mt-8"
+ currentPage={current}
+ edgePageCount={2}
+ middlePagesSiblingCount={1}
+ setCurrentPage={onChange}
+ totalPages={totalPages}
+ truncableClassName="w-8 px-0.5 text-center"
+ truncableText="..."
+ >
+ <Pagination.PrevButton
+ disabled={current === 0}
+ className={`flex items-center mr-2 text-gray-500 focus:outline-none ${current === 0 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600'}`} >
+ <ArrowLeftIcon className="mr-3 h-3 w-3" />
+ {t('appLog.table.pagination.previous')}
+ </Pagination.PrevButton>
+ <div className={`flex items-center justify-center flex-grow ${s.pagination}`}>
+ <Pagination.PageButton
+ activeClassName="bg-primary-50 text-primary-600"
+ className="flex items-center justify-center h-8 w-8 rounded-lg cursor-pointer"
+ inactiveClassName="text-gray-500"
+ />
+ </div>
+ <Pagination.NextButton
+ disabled={current === totalPages - 1}
+ className={`flex items-center mr-2 text-gray-500 focus:outline-none ${current === totalPages - 1 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600'}`} >
+ {t('appLog.table.pagination.next')}
+ <ArrowRightIcon className="ml-3 h-3 w-3" />
+ </Pagination.NextButton>
+ </Pagination>
+ )
+}
+
+export default CustomizedPagination
diff --git a/web/app/components/base/pagination/style.module.css b/web/app/components/base/pagination/style.module.css
new file mode 100644
index 00000000000..adb32a39db8
--- /dev/null
+++ b/web/app/components/base/pagination/style.module.css
@@ -0,0 +1,3 @@
+.pagination li {
+ list-style: none;
+}
diff --git a/web/app/components/base/panel/index.tsx b/web/app/components/base/panel/index.tsx
new file mode 100644
index 00000000000..0b30d91778b
--- /dev/null
+++ b/web/app/components/base/panel/index.tsx
@@ -0,0 +1,80 @@
+'use client'
+import React, { FC, useEffect } from 'react'
+import cn from 'classnames'
+import { useBoolean } from 'ahooks'
+import { ChevronRightIcon } from '@heroicons/react/24/outline'
+
+
+export interface IPanelProps {
+ className?: string
+ headerIcon: React.ReactNode
+ title: React.ReactNode
+ headerRight?: React.ReactNode
+ bodyClassName?: string
+ children: React.ReactNode
+ keepUnFold?: boolean
+ foldDisabled?: boolean
+ onFoldChange?: (fold: boolean) => void
+ controlUnFold?: number
+ controlFold?: number
+}
+
+const Panel: FC<IPanelProps> = ({
+ className,
+ headerIcon,
+ title,
+ headerRight,
+ bodyClassName,
+ children,
+ keepUnFold,
+ foldDisabled = false,
+ onFoldChange,
+ controlUnFold,
+ controlFold
+}) => {
+ const [fold, { setTrue: setFold, setFalse: setUnFold, toggle: toggleFold }] = useBoolean(keepUnFold ? false : true)
+ useEffect(() => {
+ onFoldChange?.(fold)
+ }, [fold])
+
+ useEffect(() => {
+ if (controlUnFold) {
+ setUnFold()
+ }
+ }, [controlUnFold])
+
+ useEffect(() => {
+ if (controlFold) {
+ setFold()
+ }
+ }, [controlFold])
+
+ // overflow-hidden
+ return (
+ <div className={cn(className, 'w-full rounded-xl border border-gray-100 overflow-hidden select-none')}>
+ {/* Header */}
+ <div
+ onClick={() => (!foldDisabled && !keepUnFold) && toggleFold()}
+ className={cn(!fold && 'border-b border-gray-100', 'flex justify-between items-center h-12 bg-gray-50 pl-4 pr-2')}>
+ <div className='flex items-center gap-2'>
+ {headerIcon}
+ <div className='text-gray-900 text-sm'>{title}</div>
+ </div>
+ {(fold && headerRight) ? headerRight : ''}
+ {!headerRight && !keepUnFold && (
+ <ChevronRightIcon className={cn(!fold && 'rotate-90', 'mr-2 cursor-pointer')} width="16" height="16">
+ </ChevronRightIcon>
+ )}
+ </div>
+
+ {/* Main Content */}
+
+ {!fold && !foldDisabled && (
+ <div className={cn(bodyClassName)}>
+ {children}
+ </div>
+ )}
+ </div>
+ )
+}
+export default React.memo(Panel)
diff --git a/web/app/components/base/popover/index.tsx b/web/app/components/base/popover/index.tsx
new file mode 100644
index 00000000000..c83c9cd57d6
--- /dev/null
+++ b/web/app/components/base/popover/index.tsx
@@ -0,0 +1,98 @@
+import { Popover, Transition } from '@headlessui/react'
+import { Fragment, cloneElement, useRef } from 'react'
+import s from './style.module.css'
+
+type IPopover = {
+ className?: string
+ htmlContent: React.ReactNode
+ trigger?: 'click' | 'hover'
+ position?: 'bottom' | 'br'
+ btnElement?: string | React.ReactNode
+ btnClassName?: string | ((open: boolean) => string)
+}
+
+const timeoutDuration = 100
+
+export default function CustomPopover({
+ trigger = 'hover',
+ position = 'bottom',
+ htmlContent,
+ btnElement,
+ className,
+ btnClassName,
+}: IPopover) {
+ const buttonRef = useRef<HTMLButtonElement>(null)
+ const timeOutRef = useRef<NodeJS.Timeout | null>(null)
+
+ const onMouseEnter = (isOpen: boolean) => {
+ timeOutRef.current && clearTimeout(timeOutRef.current)
+ !isOpen && buttonRef.current?.click()
+ }
+
+ const onMouseLeave = (isOpen: boolean) => {
+ timeOutRef.current = setTimeout(() => {
+ isOpen && buttonRef.current?.click()
+ }, timeoutDuration)
+ }
+
+ return (
+ <Popover className="relative">
+ {({ open }: { open: boolean }) => {
+ return (
+ <>
+ <div
+ {...(trigger !== 'hover'
+ ? {}
+ : {
+ onMouseLeave: () => onMouseLeave(open),
+ onMouseEnter: () => onMouseEnter(open),
+ })
+ }
+ >
+ <Popover.Button
+ ref={buttonRef}
+ className={`group ${s.popupBtn} ${open ? '' : 'bg-gray-100'} ${!btnClassName ? '' : typeof btnClassName === 'string' ? btnClassName : btnClassName?.(open)}`}
+ >
+ {btnElement}
+ </Popover.Button>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-200"
+ enterFrom="opacity-0 translate-y-1"
+ enterTo="opacity-100 translate-y-0"
+ leave="transition ease-in duration-150"
+ leaveFrom="opacity-100 translate-y-0"
+ leaveTo="opacity-0 translate-y-1"
+ >
+ <Popover.Panel
+ className={`${s.popupPanel} ${position === 'br' ? 'right-0' : 'transform -translate-x-1/2 left-1/2'} ${className}`}
+ {...(trigger !== 'hover'
+ ? {}
+ : {
+ onMouseLeave: () => onMouseLeave(open),
+ onMouseEnter: () => onMouseEnter(open),
+ })
+ }>
+ <div
+ className={s.panelContainer}
+ {...(trigger !== 'hover'
+ ? {}
+ : {
+ onMouseLeave: () => onMouseLeave(open),
+ onMouseEnter: () => onMouseEnter(open),
+ })
+ }
+ >
+ {cloneElement(htmlContent as React.ReactElement, {
+ onClose: () => onMouseLeave(open),
+ })}
+ </div>
+ </Popover.Panel>
+ </Transition>
+ </div>
+ </>
+ )
+ }}
+ </Popover>
+ )
+}
diff --git a/web/app/components/base/popover/style.module.css b/web/app/components/base/popover/style.module.css
new file mode 100644
index 00000000000..cea72901f3f
--- /dev/null
+++ b/web/app/components/base/popover/style.module.css
@@ -0,0 +1,9 @@
+.popupBtn {
+ @apply inline-flex items-center bg-white px-3 py-2 rounded-lg text-base border border-gray-200 font-medium hover:bg-gray-100 focus:outline-none
+}
+.popupPanel {
+ @apply absolute z-10 w-full max-w-sm px-4 mt-1 sm:px-0 lg:max-w-3xl
+}
+.panelContainer {
+ @apply overflow-hidden bg-white w-full rounded-lg shadow-lg ring-1 ring-black ring-opacity-5
+}
diff --git a/web/app/components/base/portal-to-follow-elem/index.tsx b/web/app/components/base/portal-to-follow-elem/index.tsx
new file mode 100644
index 00000000000..912114fd98e
--- /dev/null
+++ b/web/app/components/base/portal-to-follow-elem/index.tsx
@@ -0,0 +1,84 @@
+'use client'
+import { useBoolean } from 'ahooks'
+import React, { FC, useEffect, useState, useRef } from 'react'
+import { createRoot } from 'react-dom/client'
+
+export interface IPortalToFollowElementProps {
+ portalElem: React.ReactNode
+ children: React.ReactNode
+ controlShow?: number
+ controlHide?: number
+}
+
+const PortalToFollowElement: FC<IPortalToFollowElementProps> = ({
+ portalElem,
+ children,
+ controlShow,
+ controlHide
+}) => {
+ const [isShowContent, { setTrue: showContent, setFalse: hideContent, toggle: toggleContent }] = useBoolean(false)
+ const [wrapElem, setWrapElem] = useState<HTMLDivElement | null>(null)
+
+ useEffect(() => {
+ if (controlShow) {
+ showContent()
+ }
+ }, [controlShow])
+
+ useEffect(() => {
+ if (controlHide) {
+ hideContent()
+ }
+ }, [controlHide])
+
+ // todo use click outside hidden
+ const triggerElemRef = useRef<HTMLElement>(null)
+
+ const calLoc = () => {
+ const triggerElem = triggerElemRef.current
+ if (!triggerElem) {
+ return {
+ display: 'none'
+ }
+ }
+ const {
+ left: triggerLeft,
+ top: triggerTop,
+ height
+ } = triggerElem.getBoundingClientRect();
+
+ return {
+ position: 'fixed',
+ left: triggerLeft,
+ top: triggerTop + height,
+ zIndex: 999
+ }
+ }
+
+ useEffect(() => {
+ if (isShowContent) {
+ const holder = document.createElement('div')
+ const root = createRoot(holder)
+ const style = calLoc()
+ root.render(
+ <div style={style as React.CSSProperties}>
+ {portalElem}
+ </div>
+ )
+ document.body.appendChild(holder)
+ setWrapElem(holder)
+ console.log(holder)
+ } else {
+ wrapElem?.remove?.()
+ setWrapElem(null)
+ }
+ }, [isShowContent])
+
+ return (
+ <div ref={triggerElemRef as any} onClick={toggleContent}>
+ {children}
+ </div>
+ )
+}
+
+export default React.memo(PortalToFollowElement)
diff --git a/web/app/components/base/radio/component/group/index.tsx b/web/app/components/base/radio/component/group/index.tsx
new file mode 100644
index 00000000000..6c75619660c
--- /dev/null
+++ b/web/app/components/base/radio/component/group/index.tsx
@@ -0,0 +1,24 @@
+import type { ReactElement } from 'react'
+import cn from 'classnames'
+import RadioGroupContext from '../../context'
+import s from '../../style.module.css'
+
+export type TRadioGroupProps = {
+ children?: ReactElement | ReactElement[]
+ value?: string | number
+ className?: string
+ onChange?: (value: any) => void
+}
+
+export default function Group({ children, value, onChange, className = '' }: TRadioGroupProps): JSX.Element {
+ const onRadioChange = (value: any) => {
+ onChange?.(value)
+ }
+ return (
+ <div className={cn('flex items-center bg-gray-50', s.container, className)}>
+ <RadioGroupContext.Provider value={{ value, onChange: onRadioChange }}>
+ {children}
+ </RadioGroupContext.Provider>
+ </div>
+ )
+}
diff --git a/web/app/components/base/radio/component/radio/index.tsx b/web/app/components/base/radio/component/radio/index.tsx
new file mode 100644
index 00000000000..32d52fcd170
--- /dev/null
+++ b/web/app/components/base/radio/component/radio/index.tsx
@@ -0,0 +1,61 @@
+import type { ReactElement } from 'react'
+import { useId } from 'react'
+import cn from 'classnames'
+import { useContext } from 'use-context-selector'
+import RadioGroupContext from '../../context'
+import s from '../../style.module.css'
+
+export type IRadioProps = {
+ className?: string
+ children?: string | ReactElement
+ checked?: boolean
+ value?: string | number
+ disabled?: boolean
+ onChange?: (e: any) => void
+}
+
+export default function Radio({
+ className = '',
+ children = '',
+ checked,
+ value,
+ disabled,
+ onChange,
+}: IRadioProps): JSX.Element {
+ const groupContext = useContext(RadioGroupContext)
+ const labelId = useId()
+ const handleChange = (e: any) => {
+ if (disabled)
+ return
+
+ onChange?.(e)
+ groupContext?.onChange(e)
+ }
+
+ const isChecked = groupContext ? groupContext.value === value : checked
+ const divClassName = `
+ flex items-center py-1 relative
+ px-7 cursor-pointer hover:bg-gray-200 rounded
+ `
+
+ return (
+ <div className={cn(
+ s.label,
+ disabled ? s.disabled : '',
+ isChecked ? 'bg-white shadow' : '',
+ divClassName,
+ className)}
+ onClick={() => handleChange(value)}
+ >
+ {children && (
+ <label className={
+ cn('text-sm cursor-pointer')
+ }
+ id={labelId}
+ >
+ {children}
+ </label>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/components/base/radio/context/index.tsx b/web/app/components/base/radio/context/index.tsx
new file mode 100644
index 00000000000..10d11934e27
--- /dev/null
+++ b/web/app/components/base/radio/context/index.tsx
@@ -0,0 +1,6 @@
+'use client'
+
+import { createContext } from 'use-context-selector'
+
+const RadioGroupContext = createContext<any>(null)
+export default RadioGroupContext
diff --git a/web/app/components/base/radio/index.tsx b/web/app/components/base/radio/index.tsx
new file mode 100644
index 00000000000..9aed85096df
--- /dev/null
+++ b/web/app/components/base/radio/index.tsx
@@ -0,0 +1,15 @@
+import type React from 'react'
+import type { IRadioProps } from './component/radio'
+import RadioComps from './component/radio'
+import Group from './component/group'
+
+type CompoundedComponent = {
+ Group: typeof Group
+} & React.ForwardRefExoticComponent<IRadioProps & React.RefAttributes<HTMLElement>>
+
+const Radio = RadioComps as CompoundedComponent
+/**
+ * Radio 组件出现一般是以一组的形式出现
+ */
+Radio.Group = Group
+export default Radio
diff --git a/web/app/components/base/radio/style.module.css b/web/app/components/base/radio/style.module.css
new file mode 100644
index 00000000000..3e6bcdf418c
--- /dev/null
+++ b/web/app/components/base/radio/style.module.css
@@ -0,0 +1,13 @@
+.container {
+ padding: 4px;
+ border-radius: 4px;
+}
+
+.label {
+ position: relative;
+ margin-right: 3px;
+}
+
+.label:last-child {
+ margin-right: 0;
+}
diff --git a/web/app/components/base/select-support-portal/index.tsx b/web/app/components/base/select-support-portal/index.tsx
new file mode 100644
index 00000000000..64eb8deaf32
--- /dev/null
+++ b/web/app/components/base/select-support-portal/index.tsx
@@ -0,0 +1,73 @@
+'use client'
+import React, { FC, useState } from 'react'
+import PortalToFollowElem from '../portal-to-follow-elem'
+import { ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline'
+import cn from 'classnames'
+
+export interface ISelectProps<T> {
+ value: T
+ items: { value: T, name: string }[]
+ onChange: (value: T) => void
+}
+
+const Select: FC<ISelectProps<string | number>> = ({
+ value,
+ items,
+ onChange
+}) => {
+ const [controlHide, setControlHide] = useState(0)
+ const itemsElement = items.map(item => {
+ const isSelected = item.value === value
+ return (
+ <div
+ key={item.value}
+ className={cn('relative h-9 leading-9 px-10 rounded-lg text-sm text-gray-700 hover:bg-gray-100')}
+ onClick={() => {
+ onChange(item.value)
+ setControlHide(Date.now())
+ }}
+ >
+ {isSelected && (
+ <div className='absolute left-4 top-1/2 translate-y-[-50%] flex items-center justify-center w-4 h-4 text-primary-600'>
+ <CheckIcon width={16} height={16}></CheckIcon>
+ </div>
+ )}
+ {item.name}
+ </div>
+ )
+ })
+ return (
+ <div>
+ <PortalToFollowElem
+ portalElem={(
+ <div
+ className='p-1 rounded-lg bg-white cursor-pointer'
+ style={{
+ boxShadow: '0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px rgba(0, 0, 0, 0.05)'
+ }}
+ >
+ {itemsElement}
+ </div>
+ )}
+ controlHide={controlHide}
+ >
+ <div className='relative '>
+ <div className='flex items-center h-9 px-3 gap-1 cursor-pointer hover:bg-gray-50'>
+ <div className='text-sm text-gray-700'>{items.find(i => i.value === value)?.name}</div>
+ <ChevronDownIcon width={16} height={16} />
+ </div>
+ {/* <div
+ className='absolute z-50 left-0 top-9 p-1 w-[112px] rounded-lg bg-white'
+ style={{
+ boxShadow: '0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px rgba(0, 0, 0, 0.05)'
+ }}
+ >
+ {itemsElement}
+ </div> */}
+ </div>
+ </PortalToFollowElem>
+ </div>
+
+ )
+}
+export default React.memo(Select)
diff --git a/web/app/components/base/select/index.tsx b/web/app/components/base/select/index.tsx
new file mode 100644
index 00000000000..02b73ffe0e2
--- /dev/null
+++ b/web/app/components/base/select/index.tsx
@@ -0,0 +1,224 @@
+'use client'
+import type { FC } from 'react'
+import React, { Fragment, useEffect, useState } from 'react'
+import { Combobox, Listbox, Transition } from '@headlessui/react'
+import classNames from 'classnames'
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/20/solid'
+import { useTranslation } from 'react-i18next'
+
+const defaultItems = [
+ { value: 1, name: 'option1' },
+ { value: 2, name: 'option2' },
+ { value: 3, name: 'option3' },
+ { value: 4, name: 'option4' },
+ { value: 5, name: 'option5' },
+ { value: 6, name: 'option6' },
+ { value: 7, name: 'option7' },
+]
+
+export type Item = {
+ value: number | string
+ name: string
+}
+
+export type ISelectProps = {
+ className?: string
+ wrapperClassName?: string
+ items?: Item[]
+ defaultValue?: number | string
+ disabled?: boolean
+ onSelect: (value: Item) => void
+ allowSearch?: boolean
+ bgClassName?: string
+ placeholder?: string
+}
+const Select: FC<ISelectProps> = ({
+ className,
+ items = defaultItems,
+ defaultValue = 1,
+ disabled = false,
+ onSelect,
+ allowSearch = true,
+ bgClassName = 'bg-gray-100',
+}) => {
+ const [query, setQuery] = useState('')
+ const [open, setOpen] = useState(false)
+
+ const [selectedItem, setSelectedItem] = useState<Item | null>(null)
+ useEffect(() => {
+ let defaultSelect = null
+ const existed = items.find((item: Item) => item.value === defaultValue)
+ if (existed) {
+ defaultSelect = existed
+ }
+ setSelectedItem(defaultSelect)
+ }, [defaultValue])
+
+ const filteredItems: Item[]
+ = query === ''
+ ? items
+ : items.filter((item) => {
+ return item.name.toLowerCase().includes(query.toLowerCase())
+ })
+
+ return (
+ <Combobox
+ as="div"
+ disabled={disabled}
+ value={selectedItem}
+ className={className}
+ onChange={(value: Item) => {
+ if (!disabled) {
+ setSelectedItem(value)
+ setOpen(false)
+ onSelect(value)
+ }
+ }}>
+ <div className={classNames('relative')}>
+ <div className='group text-gray-800'>
+ {allowSearch
+ ? <Combobox.Input
+ className={`w-full rounded-lg border-0 ${bgClassName} py-1.5 pl-3 pr-10 shadow-sm sm:text-sm sm:leading-6 focus-visible:outline-none focus-visible:bg-gray-200 group-hover:bg-gray-200 cursor-not-allowed`}
+ onChange={(event) => {
+ if (!disabled)
+ setQuery(event.target.value)
+ }}
+ displayValue={(item: Item) => item?.name}
+ />
+ : <Combobox.Button onClick={
+ () => {
+ if (!disabled)
+ setOpen(!open)
+ }
+ } className={`flex items-center h-9 w-full rounded-lg border-0 ${bgClassName} py-1.5 pl-3 pr-10 shadow-sm sm:text-sm sm:leading-6 focus-visible:outline-none focus-visible:bg-gray-200 group-hover:bg-gray-200`}>
+ {selectedItem?.name}
+ </Combobox.Button>}
+ <Combobox.Button className="absolute inset-y-0 right-0 flex items-center rounded-r-md px-2 focus:outline-none group-hover:bg-gray-200" onClick={
+ () => {
+ if (!disabled)
+ setOpen(!open)
+ }
+ }>
+ {open ? <ChevronUpIcon className="h-5 w-5" /> : <ChevronDownIcon className="h-5 w-5" />}
+ </Combobox.Button>
+ </div>
+
+ {filteredItems.length > 0 && (
+ <Combobox.Options className="absolute z-10 mt-1 px-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg border-gray-200 border-[0.5px] focus:outline-none sm:text-sm">
+ {filteredItems.map((item: Item) => (
+ <Combobox.Option
+ key={item.value}
+ value={item}
+ className={({ active }: { active: boolean }) =>
+ classNames(
+ 'relative cursor-default select-none py-2 pl-3 pr-9 rounded-lg hover:bg-gray-100 text-gray-700',
+ active ? 'bg-gray-100' : '',
+ )
+ }
+ >
+ {({ /* active, */ selected }) => (
+ <>
+ <span className={classNames('block truncate', selected && 'font-normal')}>{item.name}</span>
+ {selected && (
+ <span
+ className={classNames(
+ 'absolute inset-y-0 right-0 flex items-center pr-4 text-gray-700',
+ )}
+ >
+ <CheckIcon className="h-5 w-5" aria-hidden="true" />
+ </span>
+ )}
+ </>
+ )}
+ </Combobox.Option>
+ ))}
+ </Combobox.Options>
+ )}
+ </div>
+ </Combobox >
+ )
+}
+
+const SimpleSelect: FC<ISelectProps> = ({
+ className,
+ wrapperClassName,
+ items = defaultItems,
+ defaultValue = 1,
+ disabled = false,
+ onSelect,
+ placeholder,
+}) => {
+ const { t } = useTranslation()
+ const localPlaceholder = placeholder || t('common.placeholder.select')
+
+ const [selectedItem, setSelectedItem] = useState<Item | null>(null)
+ useEffect(() => {
+ let defaultSelect = null
+ const existed = items.find((item: Item) => item.value === defaultValue)
+ if (existed) {
+ defaultSelect = existed
+ }
+ setSelectedItem(defaultSelect)
+ }, [defaultValue])
+
+ return (
+ <Listbox
+ value={selectedItem}
+ onChange={(value: Item) => {
+ if (!disabled) {
+ setSelectedItem(value)
+ onSelect(value)
+ }
+ }}
+ >
+ <div className={`relative h-9 ${wrapperClassName}`}>
+ <Listbox.Button className={`w-full h-full rounded-lg border-0 bg-gray-100 py-1.5 pl-3 pr-10 shadow-sm sm:text-sm sm:leading-6 focus-visible:outline-none focus-visible:bg-gray-200 group-hover:bg-gray-200 cursor-pointer ${className}`}>
+ <span className={classNames("block truncate text-left", !selectedItem?.name && 'text-gray-400')}>{selectedItem?.name ?? localPlaceholder}</span>
+ <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
+ <ChevronDownIcon
+ className="h-5 w-5 text-gray-400"
+ aria-hidden="true"
+ />
+ </span>
+ </Listbox.Button>
+ <Transition
+ as={Fragment}
+ leave="transition ease-in duration-100"
+ leaveFrom="opacity-100"
+ leaveTo="opacity-0"
+ >
+ <Listbox.Options className="absolute z-10 mt-1 px-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg border-gray-200 border-[0.5px] focus:outline-none sm:text-sm">
+ {items.map((item: Item) => (
+ <Listbox.Option
+ key={item.value}
+ className={({ active }) =>
+ `relative cursor-pointer select-none py-2 pl-3 pr-9 rounded-lg hover:bg-gray-100 text-gray-700 ${active ? 'bg-gray-100' : ''
+ }`
+ }
+ value={item}
+ disabled={disabled}
+ >
+ {({ /* active, */ selected }) => (
+ <>
+ <span className={classNames('block truncate', selected && 'font-normal')}>{item.name}</span>
+ {selected && (
+ <span
+ className={classNames(
+ 'absolute inset-y-0 right-0 flex items-center pr-4 text-gray-700',
+ )}
+ >
+ <CheckIcon className="h-5 w-5" aria-hidden="true" />
+ </span>
+ )}
+ </>
+ )}
+ </Listbox.Option>
+ ))}
+ </Listbox.Options>
+ </Transition>
+ </div>
+ </Listbox>
+ )
+}
+export { SimpleSelect }
+export default React.memo(Select)
diff --git a/web/app/components/base/select/locale.tsx b/web/app/components/base/select/locale.tsx
new file mode 100644
index 00000000000..b6f2194a8cc
--- /dev/null
+++ b/web/app/components/base/select/locale.tsx
@@ -0,0 +1,125 @@
+'use client'
+import { Menu, Transition } from '@headlessui/react'
+import { Fragment } from 'react'
+import { GlobeAltIcon } from '@heroicons/react/24/outline'
+
+export const LOCALES = [
+ { value: 'en', name: 'EN' },
+ { value: 'zh-Hans', name: '简体中文' },
+]
+export const RFC_LOCALES = [
+ { value: 'en-US', name: 'EN' },
+ { value: 'zh-Hans', name: '简体中文' },
+]
+interface ISelectProps {
+ items: Array<{ value: string; name: string }>
+ value?: string
+ className?: string
+ onChange?: (value: string) => void
+}
+
+export default function Select({
+ items,
+ value,
+ onChange
+}: ISelectProps) {
+ const item = items.filter(item => item.value === value)[0]
+
+ return (
+ <div className="w-56 text-right">
+ <Menu as="div" className="relative inline-block text-left">
+ <div>
+ <Menu.Button className="inline-flex w-full justify-center items-center
+ rounded-lg px-2 py-1
+ text-gray-600 text-xs font-medium
+ border border-gray-200">
+ <GlobeAltIcon className="w-5 h-5 mr-2 " aria-hidden="true" />
+ {item?.name}
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items className="absolute right-0 mt-2 w-28 origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
+ <div className="px-1 py-1 ">
+ {items.map((item) => {
+ return <Menu.Item key={item.value}>
+ {({ active }) => (
+ <button
+ className={`${active ? 'bg-gray-100' : ''
+ } group flex w-full items-center rounded-md px-2 py-2 text-sm`}
+ onClick={(evt) => {
+ evt.preventDefault()
+ onChange && onChange(item.value)
+ }}
+ >
+ {item.name}
+ </button>
+ )}
+ </Menu.Item>
+ })}
+
+ </div>
+
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ </div>
+ )
+}
+
+export function InputSelect({
+ items,
+ value,
+ onChange
+}: ISelectProps) {
+ const item = items.filter(item => item.value === value)[0]
+ return (
+ <div className="w-full">
+ <Menu as="div" className="w-full">
+ <div>
+ <Menu.Button className="iappearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 sm:text-sm h-[38px] text-left">
+ {item?.name}
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items className="absolute right-0 mt-2 w-full origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
+ <div className="px-1 py-1 ">
+ {items.map((item) => {
+ return <Menu.Item key={item.value}>
+ {({ active }) => (
+ <button
+ className={`${active ? 'bg-gray-100' : ''
+ } group flex w-full items-center rounded-md px-2 py-2 text-sm`}
+ onClick={() => {
+ onChange && onChange(item.value)
+ }}
+ >
+ {item.name}
+ </button>
+ )}
+ </Menu.Item>
+ })}
+
+ </div>
+
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/web/app/components/base/slider/index.tsx b/web/app/components/base/slider/index.tsx
new file mode 100644
index 00000000000..eb9fecd9592
--- /dev/null
+++ b/web/app/components/base/slider/index.tsx
@@ -0,0 +1,24 @@
+import ReactSlider from 'react-slider'
+import './style.css'
+type ISliderProps = {
+ value: number
+ max?: number
+ min?: number
+ step?: number
+ onChange: (value: number) => void
+}
+
+const Slider: React.FC<ISliderProps> = ({ max, min, step, value, onChange }) => {
+ return <ReactSlider
+ value={value}
+ min={min || 0}
+ max={max || 100}
+ step={step || 1}
+ className="slider"
+ thumbClassName="slider-thumb"
+ trackClassName="slider-track"
+ onChange={onChange}
+ />
+}
+
+export default Slider
diff --git a/web/app/components/base/slider/style.css b/web/app/components/base/slider/style.css
new file mode 100644
index 00000000000..2eb2510301a
--- /dev/null
+++ b/web/app/components/base/slider/style.css
@@ -0,0 +1,28 @@
+.slider {
+ position: relative;
+}
+
+.slider-thumb {
+ width: 18px;
+ height: 18px;
+ background-color: white;
+ border-radius: 50%;
+ position: absolute;
+ top: -9px;
+ box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.08);
+ cursor: pointer;
+
+}
+
+.slider-thumb:focus {
+ outline: none;
+}
+
+.slider-track {
+ background-color: #9CA3AF;
+ height: 2px;
+}
+
+.slider-track-1 {
+ background-color: #E5E7EB;
+}
diff --git a/web/app/components/base/spinner/index.tsx b/web/app/components/base/spinner/index.tsx
new file mode 100644
index 00000000000..53de4eda43e
--- /dev/null
+++ b/web/app/components/base/spinner/index.tsx
@@ -0,0 +1,24 @@
+import type { FC } from 'react'
+import React from 'react'
+
+type Props = {
+ loading?: boolean
+ className?: string
+ children?: React.ReactNode | string
+}
+
+const Spinner: FC<Props> = ({ loading = false, children, className }) => {
+ return (
+ <div
+ className={`inline-block text-gray-200 h-4 w-4 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] ${loading ? 'motion-reduce:animate-[spin_1.5s_linear_infinite]' : 'hidden'} ${className ?? ''}`}
+ role="status"
+ >
+ <span
+ className="!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]"
+ >Loading...</span>
+ {children}
+ </div>
+ )
+}
+
+export default Spinner
diff --git a/web/app/components/base/switch/index.tsx b/web/app/components/base/switch/index.tsx
new file mode 100644
index 00000000000..45bf7e4428e
--- /dev/null
+++ b/web/app/components/base/switch/index.tsx
@@ -0,0 +1,55 @@
+'use client'
+import React, { useState } from 'react'
+import classNames from 'classnames'
+import { Switch as OriginalSwitch } from '@headlessui/react'
+
+type SwitchProps = {
+ onChange: (value: boolean) => void
+ size?: 'md' | 'lg'
+ defaultValue?: boolean
+ disabled?: boolean
+}
+
+const Switch = ({ onChange, size = 'lg', defaultValue = false, disabled = false }: SwitchProps) => {
+ const [enabled, setEnabled] = useState(defaultValue)
+ const wrapStyle = {
+ lg: 'h-6 w-11',
+ md: 'h-4 w-7'
+ }
+
+ const circleStyle = {
+ lg: 'h-5 w-5',
+ md: 'h-3 w-3'
+ }
+
+ const translateLeft = {
+ lg: 'translate-x-5',
+ md: 'translate-x-3'
+ }
+ return (
+ <OriginalSwitch
+ checked={enabled}
+ onChange={(checked: boolean) => {
+ if (disabled) return;
+ setEnabled(checked)
+ onChange(checked)
+ }}
+ className={classNames(
+ wrapStyle[size],
+ enabled ? 'bg-blue-600' : 'bg-gray-200',
+ 'relative inline-flex flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out',
+ disabled ? '!opacity-50 !cursor-not-allowed' : '',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={classNames(
+ circleStyle[size],
+ enabled ? translateLeft[size] : 'translate-x-0',
+ 'pointer-events-none inline-block transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
+ )}
+ />
+ </OriginalSwitch>
+ )
+}
+export default React.memo(Switch)
diff --git a/web/app/components/base/tab-header/index.tsx b/web/app/components/base/tab-header/index.tsx
new file mode 100644
index 00000000000..aedc3816e47
--- /dev/null
+++ b/web/app/components/base/tab-header/index.tsx
@@ -0,0 +1,37 @@
+'use client'
+import React, { FC } from 'react'
+import cn from 'classnames'
+
+import s from './style.module.css'
+
+export interface ITabHeaderProps {
+ items: {
+ id: string
+ name: string
+ extra?: React.ReactNode
+ }[]
+ value: string
+ onChange: (value: string) => void
+}
+
+const TabHeader: FC<ITabHeaderProps> = ({
+ items,
+ value,
+ onChange
+}) => {
+ return (
+ <div className='flex space-x-4 border-b border-gray-200 '>
+ {items.map(({ id, name, extra }) => (
+ <div
+ key={id}
+ className={cn(id === value ? `${s.itemActive} text-gray-900` : 'text-gray-500', 'relative flex items-center pb-1.5 leading-6 cursor-pointer')}
+ onClick={() => onChange(id)}
+ >
+ <div className='text-base font-semibold'>{name}</div>
+ {extra ? extra : ''}
+ </div>
+ ))}
+ </div>
+ )
+}
+export default React.memo(TabHeader)
diff --git a/web/app/components/base/tab-header/style.module.css b/web/app/components/base/tab-header/style.module.css
new file mode 100644
index 00000000000..09844207a54
--- /dev/null
+++ b/web/app/components/base/tab-header/style.module.css
@@ -0,0 +1,9 @@
+.itemActive::after {
+ content: '';
+ position: absolute;
+ bottom: -1px;
+ left: 0;
+ width: 100%;
+ height: 2px;
+ background-color: #155EEF;
+}
\ No newline at end of file
diff --git a/web/app/components/base/tag/index.tsx b/web/app/components/base/tag/index.tsx
new file mode 100644
index 00000000000..21c1d8038ce
--- /dev/null
+++ b/web/app/components/base/tag/index.tsx
@@ -0,0 +1,42 @@
+import React from 'react'
+import classNames from 'classnames'
+
+export type ITagProps = {
+ children: string | React.ReactNode
+ color?: keyof typeof COLOR_MAP
+ className?: string
+ bordered?: boolean
+ hideBg?: boolean
+}
+
+const COLOR_MAP = {
+ green: {
+ text: 'text-green-800',
+ bg: 'bg-green-100',
+ },
+ yellow: {
+ text: 'text-yellow-800',
+ bg: 'bg-yellow-100',
+ },
+ red: {
+ text: 'text-red-800',
+ bg: 'bg-red-100',
+ },
+ gray: {
+ text: 'text-gray-800',
+ bg: 'bg-gray-100',
+ },
+}
+
+export default function Tag({ children, color = 'green', className = '', bordered = false, hideBg = false }: ITagProps) {
+ return (
+ <div className={
+ classNames('px-2.5 py-px text-xs leading-5 rounded-md inline-flex items-center flex-shrink-0',
+ COLOR_MAP[color] ? `${COLOR_MAP[color].text} ${COLOR_MAP[color].bg}` : '',
+ bordered ? 'border-[1px]' : '',
+ hideBg ? 'bg-opacity-0' : '',
+ className)} >
+ {children}
+ </div>
+ )
+}
diff --git a/web/app/components/base/toast/index.tsx b/web/app/components/base/toast/index.tsx
new file mode 100644
index 00000000000..e907058ec7c
--- /dev/null
+++ b/web/app/components/base/toast/index.tsx
@@ -0,0 +1,131 @@
+'use client'
+import classNames from 'classnames'
+import type { ReactNode } from 'react'
+import React, { useEffect, useState } from 'react'
+import { createRoot } from 'react-dom/client'
+import {
+ CheckCircleIcon,
+ ExclamationTriangleIcon,
+ InformationCircleIcon,
+ XCircleIcon,
+} from '@heroicons/react/20/solid'
+import { createContext } from 'use-context-selector'
+
+export type IToastProps = {
+ type?: 'success' | 'error' | 'warning' | 'info'
+ duration?: number
+ message: string
+ children?: ReactNode
+ onClose?: () => void
+}
+type IToastContext = {
+ notify: (props: IToastProps) => void
+}
+const defaultDuring = 3000
+
+export const ToastContext = createContext<IToastContext>({} as IToastContext)
+const Toast = ({
+ type = 'info',
+ duration,
+ message,
+ children,
+}: IToastProps) => {
+ // sometimes message is react node array. Not handle it.
+ if (typeof message !== 'string') {
+ return null
+ }
+ return <div className={classNames(
+ 'fixed rounded-md p-4 my-4 mx-8 z-50',
+ 'top-0',
+ 'right-0',
+ type === 'success' ? 'bg-green-50' : '',
+ type === 'error' ? 'bg-red-50' : '',
+ type === 'warning' ? 'bg-yellow-50' : '',
+ type === 'info' ? 'bg-blue-50' : '',
+ )}>
+ <div className="flex">
+ <div className="flex-shrink-0">
+ {type === 'success' && <CheckCircleIcon className="w-5 h-5 text-green-400" aria-hidden="true" />}
+ {type === 'error' && <XCircleIcon className="w-5 h-5 text-red-400" aria-hidden="true" />}
+ {type === 'warning' && <ExclamationTriangleIcon className="w-5 h-5 text-yellow-400" aria-hidden="true" />}
+ {type === 'info' && <InformationCircleIcon className="w-5 h-5 text-blue-400" aria-hidden="true" />}
+ </div>
+ <div className="ml-3">
+ <h3 className={
+ classNames(
+ 'text-sm font-medium',
+ type === 'success' ? 'text-green-800' : '',
+ type === 'error' ? 'text-red-800' : '',
+ type === 'warning' ? 'text-yellow-800' : '',
+ type === 'info' ? 'text-blue-800' : '',
+ )
+ }>{message}</h3>
+ {children && <div className={
+ classNames(
+ 'mt-2 text-sm',
+ type === 'success' ? 'text-green-700' : '',
+ type === 'error' ? 'text-red-700' : '',
+ type === 'warning' ? 'text-yellow-700' : '',
+ type === 'info' ? 'text-blue-700' : '',
+ )
+ }>
+ {children}
+ </div>
+ }
+ </div>
+ </div>
+ </div>
+}
+
+export const ToastProvider = ({
+ children,
+}: {
+ children: ReactNode
+}) => {
+ const placeholder: IToastProps = {
+ type: 'info',
+ message: 'Toast message',
+ duration: 3000,
+ }
+ const [params, setParams] = React.useState<IToastProps>(placeholder)
+
+ const [mounted, setMounted] = useState(false)
+
+ useEffect(() => {
+ if (mounted) {
+ setTimeout(() => {
+ setMounted(false)
+ }, params.duration || defaultDuring)
+ }
+ }, [mounted])
+
+ return <ToastContext.Provider value={{
+ notify: (props) => {
+ setMounted(true)
+ setParams(props)
+ },
+ }}>
+ {mounted && <Toast {...params} />}
+ {children}
+ </ToastContext.Provider>
+}
+
+Toast.notify = ({
+ type,
+ message,
+ duration,
+}: Pick<IToastProps, 'type' | 'message' | 'duration'>) => {
+ if (typeof window === 'object') {
+ const holder = document.createElement('div')
+ const root = createRoot(holder)
+
+ root.render(<Toast type={type} message={message} duration={duration} />)
+ document.body.appendChild(holder)
+ setTimeout(() => {
+ if (holder)
+ holder.remove()
+ }, duration || defaultDuring)
+ }
+}
+
+export default Toast
diff --git a/web/app/components/base/toast/style.module.css b/web/app/components/base/toast/style.module.css
new file mode 100644
index 00000000000..a6c9cdba41c
--- /dev/null
+++ b/web/app/components/base/toast/style.module.css
@@ -0,0 +1,44 @@
+.toast {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ position: fixed;
+ z-index: 99999999;
+ width: 1.84rem;
+ height: 1.80rem;
+ left: 50%;
+ top: 50%;
+ transform: translateX(-50%) translateY(-50%);
+ background: #000000;
+ box-shadow: 0 -.04rem .1rem 1px rgba(255, 255, 255, 0.1);
+ border-radius: .1rem .1rem .1rem .1rem;
+}
+
+.main {
+ width: 2rem;
+}
+
+.icon {
+ margin-bottom: .2rem;
+ height: .4rem;
+ background: center center no-repeat;
+ background-size: contain;
+}
+
+/* .success {
+ background-image: url('./icons/success.svg');
+}
+
+.warning {
+ background-image: url('./icons/warning.svg');
+}
+
+.error {
+ background-image: url('./icons/error.svg');
+} */
+
+.text {
+ text-align: center;
+ font-size: .2rem;
+ color: rgba(255, 255, 255, 0.86);
+}
\ No newline at end of file
diff --git a/web/app/components/base/tooltip/index.tsx b/web/app/components/base/tooltip/index.tsx
new file mode 100644
index 00000000000..df802e4fe24
--- /dev/null
+++ b/web/app/components/base/tooltip/index.tsx
@@ -0,0 +1,49 @@
+'use client'
+import classNames from 'classnames'
+import type { FC } from 'react'
+import React from 'react'
+import { Tooltip as ReactTooltip } from 'react-tooltip' // fixed version to 5.8.3 https://github.com/ReactTooltip/react-tooltip/issues/972
+import 'react-tooltip/dist/react-tooltip.css'
+
+type TooltipProps = {
+ selector: string
+ content?: string
+ disabled?: boolean
+ htmlContent?: React.ReactNode
+ className?: string // This should use !impornant to override the default styles eg: '!bg-white'
+ position?: 'top' | 'right' | 'bottom' | 'left'
+ clickable?: boolean
+ children: React.ReactNode
+}
+
+const Tooltip: FC<TooltipProps> = ({
+ selector,
+ content,
+ disabled,
+ position = 'top',
+ children,
+ htmlContent,
+ className,
+ clickable,
+}) => {
+ return (
+ <div className='tooltip-container'>
+ {React.cloneElement(children as React.ReactElement, {
+ 'data-tooltip-id': selector,
+ })
+ }
+ <ReactTooltip
+ id={selector}
+ content={content}
+ className={classNames('!bg-white !text-xs !font-normal !text-gray-700 !shadow-lg !opacity-100', className)}
+ place={position}
+ clickable={clickable}
+ isOpen={disabled ? false : undefined}
+ >
+ {htmlContent && htmlContent}
+ </ReactTooltip>
+ </div>
+ )
+}
+
+export default Tooltip
diff --git a/web/app/components/datasets/api/index.tsx b/web/app/components/datasets/api/index.tsx
new file mode 100644
index 00000000000..e5c5f7f1826
--- /dev/null
+++ b/web/app/components/datasets/api/index.tsx
@@ -0,0 +1,11 @@
+import React from 'react'
+
+type Props = {}
+
+const index = (props: Props) => {
+ return (
+ <div>index</div>
+ )
+}
+
+export default index
diff --git a/web/app/components/datasets/create/assets/Loading.svg b/web/app/components/datasets/create/assets/Loading.svg
new file mode 100644
index 00000000000..9bce91eee90
--- /dev/null
+++ b/web/app/components/datasets/create/assets/Loading.svg
@@ -0,0 +1,16 @@
+<svg width="464" height="180" viewBox="0 0 464 180" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="464" height="180" rx="12" fill="#F9FAFB"/>
+<rect y="6" width="464" height="8" rx="3" fill="#EAECF0"/>
+<rect y="26" width="464" height="8" rx="3" fill="#EAECF0"/>
+<rect y="46" width="464" height="8" rx="3" fill="#EAECF0"/>
+<rect y="66" width="464" height="8" rx="3" fill="#EAECF0"/>
+<rect y="86" width="464" height="8" rx="3" fill="#EAECF0"/>
+<rect y="106" width="256" height="8" rx="3" fill="#EAECF0"/>
+<path d="M0 60H464V168C464 174.627 458.627 180 452 180H12C5.3726 180 0 174.627 0 168V60Z" fill="url(#paint0_linear_2131_10881)"/>
+<defs>
+<linearGradient id="paint0_linear_2131_10881" x1="232" y1="60" x2="232" y2="180" gradientUnits="userSpaceOnUse">
+<stop stop-color="#FCFCFD" stop-opacity="0"/>
+<stop offset="0.741486" stop-color="#FCFCFD"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/alert-triangle.svg b/web/app/components/datasets/create/assets/alert-triangle.svg
new file mode 100644
index 00000000000..5ba07318407
--- /dev/null
+++ b/web/app/components/datasets/create/assets/alert-triangle.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M6.40616 0.834307C6.14751 0.719294 5.85222 0.719294 5.59356 0.834307C5.3938 0.923133 5.26403 1.07959 5.17373 1.20708C5.08495 1.33242 4.9899 1.49664 4.88536 1.67723L0.751783 8.81705C0.646828 8.9983 0.551451 9.16302 0.486781 9.3028C0.421056 9.44487 0.349754 9.63584 0.372478 9.85381C0.401884 10.1359 0.549654 10.3922 0.779012 10.5589C0.956259 10.6878 1.15726 10.7218 1.31314 10.7361C1.46651 10.7501 1.65684 10.7501 1.86628 10.7501H10.1334C10.3429 10.7501 10.5332 10.7501 10.6866 10.7361C10.8425 10.7218 11.0435 10.6878 11.2207 10.5589C11.4501 10.3922 11.5978 10.1359 11.6272 9.85381C11.65 9.63584 11.5787 9.44487 11.5129 9.3028C11.4483 9.16303 11.3529 8.99833 11.248 8.81709L7.11436 1.67722C7.00983 1.49663 6.91477 1.33242 6.82599 1.20708C6.73569 1.07959 6.60593 0.923133 6.40616 0.834307ZM6.49988 4.50012C6.49988 4.22398 6.27602 4.00012 5.99988 4.00012C5.72374 4.00012 5.49988 4.22398 5.49988 4.50012V6.50012C5.49988 6.77626 5.72374 7.00012 5.99988 7.00012C6.27602 7.00012 6.49988 6.77626 6.49988 6.50012V4.50012ZM5.99988 8.00012C5.72374 8.00012 5.49988 8.22398 5.49988 8.50012C5.49988 8.77626 5.72374 9.00012 5.99988 9.00012H6.00488C6.28102 9.00012 6.50488 8.77626 6.50488 8.50012C6.50488 8.22398 6.28102 8.00012 6.00488 8.00012H5.99988Z" fill="#F79009"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/annotation-info.svg b/web/app/components/datasets/create/assets/annotation-info.svg
new file mode 100644
index 00000000000..2ffbc240859
--- /dev/null
+++ b/web/app/components/datasets/create/assets/annotation-info.svg
@@ -0,0 +1,3 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M16.2413 2H7.7587C6.95374 1.99999 6.28937 1.99998 5.74818 2.04419C5.18608 2.09012 4.66937 2.18868 4.18404 2.43598C3.43139 2.81947 2.81947 3.43139 2.43598 4.18404C2.18868 4.66937 2.09012 5.18608 2.04419 5.74818C1.99998 6.28937 1.99999 6.95372 2 7.75869V13.5343C1.99999 14.2041 1.99999 14.7569 2.03087 15.2095C2.06289 15.6788 2.13142 16.1129 2.30448 16.5307C2.71046 17.5108 3.48916 18.2895 4.46927 18.6955C4.88708 18.8686 5.32118 18.9371 5.79046 18.9691C6.24307 19 6.79594 19 7.46573 19H7.5C8.03656 19 8.14307 19.0063 8.22975 19.0268C8.38085 19.0624 8.52156 19.1328 8.64075 19.2322C8.70913 19.2893 8.77806 19.3708 9.1 19.8L10.5769 21.7692C10.6703 21.8938 10.7758 22.0346 10.8774 22.1476C10.9894 22.2721 11.1756 22.4555 11.4563 22.5647C11.806 22.7007 12.194 22.7007 12.5437 22.5647C12.8244 22.4555 13.0106 22.2721 13.1226 22.1476C13.2242 22.0346 13.3297 21.8938 13.4231 21.7692L14.9 19.8C15.2219 19.3708 15.2909 19.2893 15.3593 19.2322C15.4784 19.1328 15.6192 19.0624 15.7702 19.0268C15.8569 19.0063 15.9634 19 16.5 19H16.5343C17.2041 19 17.7569 19 18.2095 18.9691C18.6788 18.9371 19.1129 18.8686 19.5307 18.6955C20.5108 18.2895 21.2895 17.5108 21.6955 16.5307C21.8686 16.1129 21.9371 15.6788 21.9691 15.2095C22 14.7569 22 14.2041 22 13.5343V7.75868C22 6.95372 22 6.28937 21.9558 5.74818C21.9099 5.18608 21.8113 4.66937 21.564 4.18404C21.1805 3.43139 20.5686 2.81947 19.816 2.43598C19.3306 2.18868 18.8139 2.09012 18.2518 2.04419C17.7106 1.99998 17.0463 1.99999 16.2413 2ZM12 6C11.4477 6 11 6.44772 11 7C11 7.55229 11.4477 8 12 8H12.01C12.5623 8 13.01 7.55229 13.01 7C13.01 6.44772 12.5623 6 12.01 6H12ZM13 10.5C13 9.94772 12.5523 9.5 12 9.5C11.4477 9.5 11 9.94772 11 10.5V14C11 14.5523 11.4477 15 12 15C12.5523 15 13 14.5523 13 14V10.5Z" fill="#155EEF"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/arrow-narrow-left.svg b/web/app/components/datasets/create/assets/arrow-narrow-left.svg
new file mode 100644
index 00000000000..5c37df2f2af
--- /dev/null
+++ b/web/app/components/datasets/create/assets/arrow-narrow-left.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M13.3332 8H2.6665M2.6665 8L6.6665 12M2.6665 8L6.6665 4" stroke="#155EEF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/book-open-01.svg b/web/app/components/datasets/create/assets/book-open-01.svg
new file mode 100644
index 00000000000..2f43afc5c5d
--- /dev/null
+++ b/web/app/components/datasets/create/assets/book-open-01.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.12" d="M1.33337 4.13333C1.33337 3.3866 1.33337 3.01323 1.4787 2.72801C1.60653 2.47713 1.8105 2.27316 2.06139 2.14532C2.3466 2 2.71997 2 3.46671 2H3.73337C5.22685 2 5.97358 2 6.54401 2.29065C7.04578 2.54631 7.45373 2.95426 7.70939 3.45603C8.00004 4.02646 8.00004 4.77319 8.00004 6.26667V14L7.93334 13.8999C7.47024 13.2053 7.2387 12.858 6.93277 12.6065C6.66195 12.3839 6.34988 12.2169 6.01444 12.1151C5.63554 12 5.21811 12 4.38326 12H3.46671C2.71997 12 2.3466 12 2.06139 11.8547C1.8105 11.7268 1.60653 11.5229 1.4787 11.272C1.33337 10.9868 1.33337 10.6134 1.33337 9.86667V4.13333Z" fill="#155EEF"/>
+<path d="M8.00004 14L7.93334 13.8999C7.47024 13.2053 7.2387 12.858 6.93278 12.6065C6.66195 12.3839 6.34988 12.2169 6.01444 12.1151C5.63554 12 5.21811 12 4.38326 12H3.46671C2.71997 12 2.3466 12 2.06139 11.8547C1.8105 11.7268 1.60653 11.5229 1.4787 11.272C1.33337 10.9868 1.33337 10.6134 1.33337 9.86667V4.13333C1.33337 3.3866 1.33337 3.01323 1.4787 2.72801C1.60653 2.47713 1.8105 2.27316 2.06139 2.14532C2.3466 2 2.71997 2 3.46671 2H3.73337C5.22685 2 5.97358 2 6.54402 2.29065C7.04578 2.54631 7.45373 2.95426 7.70939 3.45603C8.00004 4.02646 8.00004 4.77319 8.00004 6.26667M8.00004 14V6.26667M8.00004 14L8.06674 13.8999C8.52984 13.2053 8.76139 12.858 9.06731 12.6065C9.33814 12.3839 9.6502 12.2169 9.98564 12.1151C10.3645 12 10.782 12 11.6168 12H12.5334C13.2801 12 13.6535 12 13.9387 11.8547C14.1896 11.7268 14.3936 11.5229 14.5214 11.272C14.6667 10.9868 14.6667 10.6134 14.6667 9.86667V4.13333C14.6667 3.3866 14.6667 3.01323 14.5214 2.72801C14.3936 2.47713 14.1896 2.27316 13.9387 2.14532C13.6535 2 13.2801 2 12.5334 2H12.2667C10.7732 2 10.0265 2 9.45607 2.29065C8.9543 2.54631 8.54635 2.95426 8.29069 3.45603C8.00004 4.02646 8.00004 4.77319 8.00004 6.26667" stroke="#155EEF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/check.svg b/web/app/components/datasets/create/assets/check.svg
new file mode 100644
index 00000000000..ae91c47f49b
--- /dev/null
+++ b/web/app/components/datasets/create/assets/check.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M10 3L4.5 8.5L2 6" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/close.svg b/web/app/components/datasets/create/assets/close.svg
new file mode 100644
index 00000000000..7a8ef6bd72c
--- /dev/null
+++ b/web/app/components/datasets/create/assets/close.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M12 4L4 12M4 4L12 12" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/file.svg b/web/app/components/datasets/create/assets/file.svg
new file mode 100644
index 00000000000..137086a2032
--- /dev/null
+++ b/web/app/components/datasets/create/assets/file.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M8.66667 1.34356C8.66667 1.32602 8.66667 1.31725 8.66591 1.30135C8.65018 0.972168 8.3607 0.682824 8.03151 0.667251C8.01562 0.666499 8.0104 0.666501 8.00001 0.666504H5.8391C5.30248 0.666497 4.85957 0.666491 4.49878 0.695968C4.12405 0.726585 3.77958 0.792295 3.45603 0.957155C2.95426 1.21282 2.54631 1.62077 2.29065 2.12253C2.12579 2.44609 2.06008 2.79056 2.02946 3.16529C1.99999 3.52608 1.99999 3.96899 2 4.50562V11.494C1.99999 12.0307 1.99999 12.4736 2.02946 12.8344C2.06008 13.2091 2.12579 13.5536 2.29065 13.8771C2.54631 14.3789 2.95426 14.7869 3.45603 15.0425C3.77958 15.2074 4.12405 15.2731 4.49878 15.3037C4.85958 15.3332 5.30248 15.3332 5.83912 15.3332H10.1609C10.6975 15.3332 11.1404 15.3332 11.5012 15.3037C11.8759 15.2731 12.2204 15.2074 12.544 15.0425C13.0457 14.7869 13.4537 14.3789 13.7093 13.8771C13.8742 13.5536 13.9399 13.2091 13.9705 12.8344C14 12.4736 14 12.0307 14 11.4941V6.66646C14 6.65611 14 6.65093 13.9993 6.63505C13.9837 6.30583 13.6943 6.01631 13.3651 6.0006C13.3492 5.99985 13.3405 5.99985 13.323 5.99985L10.3787 5.99985C10.2105 5.99987 10.0466 5.99989 9.90785 5.98855C9.75545 5.9761 9.57563 5.94672 9.39468 5.85452C9.1438 5.72669 8.93983 5.52272 8.81199 5.27183C8.7198 5.09088 8.69042 4.91106 8.67797 4.75867C8.66663 4.61989 8.66665 4.45603 8.66667 4.28778L8.66667 1.34356ZM5.33333 8.6665C4.96514 8.6665 4.66667 8.96498 4.66667 9.33317C4.66667 9.70136 4.96514 9.99984 5.33333 9.99984H10.6667C11.0349 9.99984 11.3333 9.70136 11.3333 9.33317C11.3333 8.96498 11.0349 8.6665 10.6667 8.6665H5.33333ZM5.33333 11.3332C4.96514 11.3332 4.66667 11.6316 4.66667 11.9998C4.66667 12.368 4.96514 12.6665 5.33333 12.6665H9.33333C9.70152 12.6665 10 12.368 10 11.9998C10 11.6316 9.70152 11.3332 9.33333 11.3332H5.33333Z" fill="#444CE7"/>
+<path d="M12.6053 4.6665C12.8011 4.6665 12.8989 4.6665 12.9791 4.61735C13.0923 4.54794 13.16 4.3844 13.129 4.25526C13.107 4.16382 13.0432 4.10006 12.9155 3.97253L10.694 1.75098C10.5664 1.62333 10.5027 1.5595 10.4112 1.53752C10.2821 1.50648 10.1186 1.57417 10.0492 1.6874C10 1.76757 10 1.86545 10 2.0612L10 4.13315C10 4.31982 10 4.41316 10.0363 4.48446C10.0683 4.54718 10.1193 4.59818 10.182 4.63014C10.2533 4.66647 10.3466 4.66647 10.5333 4.66647L12.6053 4.6665Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/folder-plus.svg b/web/app/components/datasets/create/assets/folder-plus.svg
new file mode 100644
index 00000000000..c63a58b426c
--- /dev/null
+++ b/web/app/components/datasets/create/assets/folder-plus.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M8.66683 4.66667L7.92314 3.17928C7.7091 2.7512 7.60207 2.53715 7.44241 2.38078C7.30122 2.24249 7.13105 2.13732 6.94421 2.07287C6.73294 2 6.49363 2 6.01502 2H3.46683C2.72009 2 2.34672 2 2.06151 2.14532C1.81063 2.27316 1.60665 2.47713 1.47882 2.72801C1.3335 3.01323 1.3335 3.3866 1.3335 4.13333V4.66667M1.3335 4.66667H11.4668C12.5869 4.66667 13.147 4.66667 13.5748 4.88465C13.9511 5.0764 14.2571 5.38236 14.4488 5.75869C14.6668 6.18651 14.6668 6.74656 14.6668 7.86667V10.8C14.6668 11.9201 14.6668 12.4802 14.4488 12.908C14.2571 13.2843 13.9511 13.5903 13.5748 13.782C13.147 14 12.5869 14 11.4668 14H4.5335C3.41339 14 2.85334 14 2.42552 13.782C2.04919 13.5903 1.74323 13.2843 1.55148 12.908C1.3335 12.4802 1.3335 11.9201 1.3335 10.8V4.66667ZM8.00016 11.3333V7.33333M6.00016 9.33333H10.0002" stroke="#155EEF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/html.svg b/web/app/components/datasets/create/assets/html.svg
new file mode 100644
index 00000000000..f4db500dc55
--- /dev/null
+++ b/web/app/components/datasets/create/assets/html.svg
@@ -0,0 +1,23 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3055_14424)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#EC5B27"/>
+</g>
+<g opacity="0.96">
+<path d="M10.2704 24.0002V18.3042H8.87042V20.4962H7.38242V18.3042H5.98242V24.0002H7.38242V21.7442H8.87042V24.0002H10.2704Z" fill="white"/>
+<path d="M15.2839 19.5522V18.3042H11.0839V19.5522H12.4839V24.0002H13.8839V19.5522H15.2839Z" fill="white"/>
+<path d="M21.4116 24.0002V18.3042H20.0356L18.7556 20.8162L17.4756 18.3042H16.0996V24.0002H17.4996V21.2722L18.3076 22.6802H19.2036L20.0116 21.2722V24.0002H21.4116Z" fill="white"/>
+<path d="M26.3525 24.0002V22.7522H23.9605V18.3042H22.5605V24.0002H26.3525Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3055_14424" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3055_14424"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3055_14424" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/json.svg b/web/app/components/datasets/create/assets/json.svg
new file mode 100644
index 00000000000..087682844dd
--- /dev/null
+++ b/web/app/components/datasets/create/assets/json.svg
@@ -0,0 +1,23 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3055_14428)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#2D2D2E"/>
+</g>
+<g opacity="0.96">
+<path d="M9.83907 22.0479V18.3039H8.43907V22.0159C8.43907 22.5599 8.12707 22.7999 7.69507 22.7999C7.38307 22.7999 7.23907 22.6879 7.06307 22.5119L6.14307 23.4239C6.60707 23.8879 7.03107 24.0479 7.69507 24.0479C8.76707 24.0479 9.83907 23.3999 9.83907 22.0479Z" fill="white"/>
+<path d="M14.7321 22.2559C14.7321 21.7279 14.6121 21.3039 14.3081 21.0079C14.0681 20.7679 13.7001 20.6079 13.1881 20.5359L12.5001 20.4399C12.3001 20.4159 12.1801 20.3439 12.1081 20.2719C12.0201 20.1839 11.9961 20.0799 11.9961 20.0079C11.9961 19.7599 12.1961 19.4799 12.6841 19.4799C12.9321 19.4799 13.4041 19.4559 13.7641 19.8159L14.6441 18.9359C14.1561 18.4479 13.5401 18.2559 12.7241 18.2559C11.4281 18.2559 10.6441 19.0159 10.6441 20.0559C10.6441 20.5439 10.7721 20.9279 11.0361 21.1999C11.2921 21.4639 11.6761 21.6319 12.1801 21.7039L12.8681 21.7999C13.0521 21.8239 13.1721 21.8799 13.2441 21.9519C13.3241 22.0399 13.3561 22.1519 13.3561 22.2879C13.3561 22.6159 13.0921 22.7999 12.5401 22.7999C12.0841 22.7999 11.5641 22.6959 11.2681 22.3999L10.3721 23.2959C10.9481 23.8879 11.6601 24.0479 12.5321 24.0479C13.7321 24.0479 14.7321 23.4159 14.7321 22.2559Z" fill="white"/>
+<path d="M19.8023 21.1519C19.8023 20.2959 19.8263 19.4959 19.2263 18.8959C18.8103 18.4799 18.3303 18.2559 17.6343 18.2559C16.9383 18.2559 16.4583 18.4799 16.0423 18.8959C15.4423 19.4959 15.4663 20.2959 15.4663 21.1519C15.4663 22.0079 15.4423 22.8079 16.0423 23.4079C16.4583 23.8239 16.9383 24.0479 17.6343 24.0479C18.3303 24.0479 18.8103 23.8239 19.2263 23.4079C19.8263 22.8079 19.8023 22.0079 19.8023 21.1519ZM18.4023 21.1519C18.4023 22.1919 18.3223 22.3759 18.1943 22.5439C18.0903 22.6799 17.8903 22.7999 17.6343 22.7999C17.3783 22.7999 17.1783 22.6799 17.0743 22.5439C16.9463 22.3759 16.8663 22.1919 16.8663 21.1519C16.8663 20.1119 16.9463 19.9199 17.0743 19.7519C17.1783 19.6159 17.3783 19.5039 17.6343 19.5039C17.8903 19.5039 18.0903 19.6159 18.1943 19.7519C18.3223 19.9199 18.4023 20.1119 18.4023 21.1519Z" fill="white"/>
+<path d="M25.2154 23.9999V18.3039H23.8154V21.1679L21.9914 18.3039H20.7674V23.9999H22.1674V21.1359L23.9914 23.9999H25.2154Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3055_14428" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3055_14428"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3055_14428" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/md.svg b/web/app/components/datasets/create/assets/md.svg
new file mode 100644
index 00000000000..d730b5a966b
--- /dev/null
+++ b/web/app/components/datasets/create/assets/md.svg
@@ -0,0 +1,18 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3777_37339)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#309BEC"/>
+</g>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M21.9904 25.3335H10.0096C9.45202 25.3335 9 24.9138 9 24.396V18.271C9 17.7532 9.45202 17.3335 10.0096 17.3335H21.9904C22.548 17.3335 23 17.7532 23 18.271V24.396C23 24.9138 22.548 25.3335 21.9904 25.3335ZM12.3654 23.4585V21.021L13.7115 22.5835L15.0577 21.021V23.4585H16.4038V19.2085H15.0577L13.7115 20.771L12.3654 19.2085H11.0192V23.4585H12.3654ZM20.0385 21.3335H21.3846L19.3654 23.521L17.3462 21.3335H18.6923V19.2085H20.0385V21.3335Z" fill="white"/>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3777_37339" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3777_37339"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3777_37339" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/notion.svg b/web/app/components/datasets/create/assets/notion.svg
new file mode 100644
index 00000000000..84a45b93af9
--- /dev/null
+++ b/web/app/components/datasets/create/assets/notion.svg
@@ -0,0 +1,12 @@
+<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2942_529)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M3.90599 18.2611L1.75639 15.5832C1.2392 14.9389 0.958496 14.1466 0.958496 13.3312V3.63437C0.958496 2.4129 1.93574 1.39936 3.19644 1.31328L13.1661 0.632614C13.8904 0.583164 14.6103 0.775682 15.2052 1.17794L18.708 3.5462C19.335 3.97012 19.7085 4.66312 19.7085 5.40266V16.427C19.7085 17.6223 18.7476 18.6121 17.5133 18.688L6.44808 19.3692C5.46308 19.4298 4.51099 19.0148 3.90599 18.2611Z" fill="white"/>
+<path d="M7.36355 8.48663V8.35968C7.36355 8.03787 7.62129 7.77098 7.95347 7.7488L10.3731 7.58726L13.7191 12.5146V8.19003L12.8579 8.07522V8.01492C12.8579 7.68933 13.1215 7.42068 13.4579 7.40344L15.6595 7.29066V7.60749C15.6595 7.75622 15.5489 7.88343 15.3973 7.90907L14.8675 7.99868V15.0022L14.2026 15.2309C13.6471 15.4219 13.0287 15.2174 12.7107 14.7376L9.46228 9.83568V14.5143L10.4622 14.7056L10.4482 14.7984C10.4046 15.0889 10.1538 15.3086 9.85036 15.3221L7.36355 15.4328C7.33068 15.1204 7.56481 14.8409 7.88781 14.807L8.21492 14.7726V8.53447L7.36355 8.48663Z" fill="black"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M13.2553 1.85418L3.28567 2.53485C2.68849 2.57562 2.22559 3.05572 2.22559 3.63431V13.3311C2.22559 13.8748 2.41272 14.4029 2.75752 14.8325L4.90712 17.5104C5.25467 17.9433 5.80161 18.1817 6.36747 18.1469L17.4326 17.4658C17.9998 17.4309 18.4413 16.9761 18.4413 16.4269V5.4026C18.4413 5.06281 18.2697 4.74441 17.9816 4.54963L14.4788 2.18137C14.1218 1.94002 13.6899 1.82451 13.2553 1.85418ZM3.78004 3.78556C3.64138 3.6829 3.70737 3.46903 3.88156 3.45654L13.3224 2.77938C13.6232 2.75781 13.9221 2.84064 14.1653 3.01299L16.0595 4.35502C16.1315 4.40597 16.0977 4.51596 16.0087 4.5208L6.01092 5.06454C5.70835 5.081 5.4097 4.99211 5.16913 4.814L3.78004 3.78556ZM5.54198 6.76913C5.54198 6.44433 5.80438 6.17604 6.13991 6.15777L16.7104 5.5821C17.0374 5.56429 17.3127 5.81577 17.3127 6.13232V15.6782C17.3127 16.0024 17.0512 16.2705 16.7164 16.2895L6.2128 16.8871C5.84887 16.9079 5.54198 16.6282 5.54198 16.2759V6.76913Z" fill="black"/>
+</g>
+<defs>
+<clipPath id="clip0_2942_529">
+<rect width="20" height="20" fill="white" transform="translate(0.333496)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/pdf.svg b/web/app/components/datasets/create/assets/pdf.svg
new file mode 100644
index 00000000000..bc6322949e0
--- /dev/null
+++ b/web/app/components/datasets/create/assets/pdf.svg
@@ -0,0 +1,22 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3055_14420)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#DD3633"/>
+</g>
+<g opacity="0.96">
+<path d="M13.2801 20.1362C13.2801 19.2002 12.6001 18.3042 11.3361 18.3042H9.08008V24.0002H10.4801V21.9682H11.3361C12.6001 21.9682 13.2801 21.0722 13.2801 20.1362ZM11.8801 20.1362C11.8801 20.4322 11.6561 20.7122 11.2721 20.7122H10.4801V19.5602H11.2721C11.6561 19.5602 11.8801 19.8402 11.8801 20.1362Z" fill="white"/>
+<path d="M18.3357 21.1522C18.3357 20.2562 18.4077 19.5282 17.7437 18.8642C17.3517 18.4722 16.7997 18.3042 16.2077 18.3042H14.0957V24.0002H16.2077C16.7997 24.0002 17.3517 23.8322 17.7437 23.4402C18.4077 22.7762 18.3357 22.0482 18.3357 21.1522ZM16.9357 21.1522C16.9357 22.1202 16.8957 22.2722 16.7837 22.4322C16.6557 22.6242 16.4637 22.7522 16.1117 22.7522H15.4957V19.5522H16.1117C16.4637 19.5522 16.6557 19.6802 16.7837 19.8722C16.8957 20.0322 16.9357 20.1922 16.9357 21.1522Z" fill="white"/>
+<path d="M23.1786 19.5522V18.3042H19.3066V24.0002H20.7066V21.8002H22.8186V20.5522H20.7066V19.5522H23.1786Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3055_14420" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3055_14420"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3055_14420" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/piggy-bank-01.svg b/web/app/components/datasets/create/assets/piggy-bank-01.svg
new file mode 100644
index 00000000000..f59858699b9
--- /dev/null
+++ b/web/app/components/datasets/create/assets/piggy-bank-01.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M7.66675 6.00004C8.95541 6.00004 10.0001 4.95537 10.0001 3.66671C10.0001 2.37804 8.95541 1.33337 7.66675 1.33337C6.37808 1.33337 5.33341 2.37804 5.33341 3.66671C5.33341 4.95537 6.37808 6.00004 7.66675 6.00004Z" fill="#444CE7"/>
+<path d="M4.65042 5.75205C4.49131 5.52233 4.41175 5.40747 4.32605 5.36953C4.24913 5.33547 4.16814 5.3313 4.08813 5.35729C3.99899 5.38624 3.92889 5.46803 3.78869 5.6316C3.22609 6.28801 2.84238 7.10277 2.71398 8.00016H2.66675C2.29856 8.00016 2.00008 7.70168 2.00008 7.33349C2.00008 7.08757 2.13289 6.87188 2.3339 6.75561C2.65261 6.57125 2.76151 6.16343 2.57715 5.84472C2.39279 5.52601 1.98497 5.4171 1.66626 5.60147C1.0702 5.94627 0.666748 6.59237 0.666748 7.33349C0.666748 8.43806 1.56218 9.33349 2.66675 9.33349H2.71402C2.85798 10.339 3.32264 11.2416 4.00004 11.9329L4.00004 13.4823C4.00001 13.5617 3.99997 13.6565 4.0068 13.7401C4.01471 13.8369 4.035 13.9756 4.10903 14.1209C4.20491 14.309 4.35789 14.462 4.54605 14.5579C4.69135 14.6319 4.83001 14.6522 4.92682 14.6601C5.01034 14.6669 5.10517 14.6669 5.18456 14.6669H6.48214C6.56153 14.6669 6.6564 14.6669 6.73993 14.6601C6.83674 14.6522 6.9754 14.6319 7.1207 14.5579C7.30886 14.462 7.46184 14.309 7.55771 14.1209C7.63175 13.9756 7.65204 13.8369 7.65995 13.7401C7.66678 13.6565 7.66674 13.5617 7.66671 13.4823L7.66671 13.3335H8.33338L8.33338 13.482C8.33335 13.5615 8.33331 13.6563 8.34014 13.7398C8.34805 13.8366 8.36834 13.9753 8.44238 14.1206C8.53825 14.3088 8.69123 14.4618 8.87939 14.5576C9.02469 14.6317 9.16335 14.652 9.26016 14.6599C9.34368 14.6667 9.43849 14.6667 9.51788 14.6666H10.8155C10.8949 14.6667 10.9898 14.6667 11.0733 14.6599C11.1701 14.652 11.3088 14.6317 11.4541 14.5576C11.6422 14.4618 11.7952 14.3088 11.8911 14.1206C11.9651 13.9753 11.9854 13.8366 11.9933 13.7398C12.0002 13.6563 12.0001 13.5615 12.0001 13.482L12.0001 12.884C12.7376 12.5338 13.3679 11.9963 13.8302 11.3333L14.1488 11.3333C14.2283 11.3333 14.3231 11.3334 14.4066 11.3265C14.5035 11.3186 14.6421 11.2983 14.7874 11.2243C14.9756 11.1284 15.1286 10.9754 15.2244 10.7873C15.2985 10.642 15.3188 10.5033 15.3267 10.4065C15.3335 10.323 15.3335 10.2282 15.3334 10.1488V7.84245C15.3335 7.76683 15.3335 7.67651 15.3273 7.59685C15.3201 7.50472 15.3017 7.37257 15.2344 7.23269C15.1361 7.02862 14.9714 6.86396 14.7674 6.76567C14.6275 6.6983 14.4953 6.67993 14.4032 6.67276C14.3437 6.66813 14.2783 6.66697 14.2175 6.66669C13.9938 6.19554 13.6937 5.76825 13.3334 5.40063L13.3334 4.68824C13.3335 4.58502 13.3335 4.46819 13.3245 4.36769C13.3147 4.25673 13.2888 4.08518 13.1835 3.91515C13.0521 3.70315 12.8463 3.54789 12.6064 3.47982C12.4139 3.42523 12.2419 3.44753 12.1325 3.4685C12.0334 3.48749 11.921 3.51963 11.8218 3.54801L11.7179 3.57769C11.5813 3.61674 11.513 3.63626 11.4649 3.67145C11.4185 3.70542 11.3901 3.73891 11.3642 3.79026C11.3374 3.84344 11.3281 3.92456 11.3096 4.08678C11.1012 5.91399 9.54973 7.33337 7.66675 7.33337C6.41642 7.33337 5.31225 6.70755 4.65042 5.75205Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/sliders-02.svg b/web/app/components/datasets/create/assets/sliders-02.svg
new file mode 100644
index 00000000000..ed05e9734f5
--- /dev/null
+++ b/web/app/components/datasets/create/assets/sliders-02.svg
@@ -0,0 +1,8 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M1.33325 12.6666C1.33325 12.2984 1.63173 12 1.99992 12H4.66659C5.03478 12 5.33325 12.2984 5.33325 12.6666C5.33325 13.0348 5.03478 13.3333 4.66659 13.3333H1.99992C1.63173 13.3333 1.33325 13.0348 1.33325 12.6666Z" fill="#155EEF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M10.5528 12C10.2782 11.2232 9.5374 10.6666 8.66659 10.6666C7.56202 10.6666 6.66659 11.5621 6.66659 12.6666C6.66659 13.7712 7.56202 14.6666 8.66659 14.6666C9.5374 14.6666 10.2782 14.1101 10.5528 13.3333L13.9999 13.3333C14.3681 13.3333 14.6666 13.0348 14.6666 12.6666C14.6666 12.2984 14.3681 12 13.9999 12L10.5528 12Z" fill="#155EEF"/>
+<path d="M9.99992 7.33329C9.63173 7.33329 9.33325 7.63177 9.33325 7.99996C9.33325 8.36815 9.63173 8.66663 9.99992 8.66663H13.9999C14.3681 8.66663 14.6666 8.36815 14.6666 7.99996C14.6666 7.63177 14.3681 7.33329 13.9999 7.33329H9.99992Z" fill="#155EEF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M1.33325 7.99996C1.33325 7.63177 1.63173 7.33329 1.99992 7.33329H4.11372C4.38828 6.5565 5.12911 5.99996 5.99992 5.99996C7.10449 5.99996 7.99992 6.89539 7.99992 7.99996C7.99992 9.10453 7.10449 9.99996 5.99992 9.99996C5.12911 9.99996 4.38828 9.44342 4.11372 8.66663H1.99992C1.63173 8.66663 1.33325 8.36815 1.33325 7.99996Z" fill="#155EEF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M9.99992 1.33329C10.8707 1.33329 11.6116 1.88983 11.8861 2.66663H13.9999C14.3681 2.66663 14.6666 2.9651 14.6666 3.33329C14.6666 3.70148 14.3681 3.99996 13.9999 3.99996H11.8861C11.6116 4.77675 10.8707 5.33329 9.99992 5.33329C8.89535 5.33329 7.99992 4.43786 7.99992 3.33329C7.99992 2.22872 8.89535 1.33329 9.99992 1.33329Z" fill="#155EEF"/>
+<path d="M1.33325 3.33329C1.33325 2.9651 1.63173 2.66663 1.99992 2.66663H5.99992C6.36811 2.66663 6.66659 2.9651 6.66659 3.33329C6.66659 3.70148 6.36811 3.99996 5.99992 3.99996H1.99992C1.63173 3.99996 1.33325 3.70148 1.33325 3.33329Z" fill="#155EEF"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/star-07.svg b/web/app/components/datasets/create/assets/star-07.svg
new file mode 100644
index 00000000000..f043ae60353
--- /dev/null
+++ b/web/app/components/datasets/create/assets/star-07.svg
@@ -0,0 +1,11 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M8.00008 0.666626C8.36827 0.666626 8.66675 0.965103 8.66675 1.33329V2.66663C8.66675 3.03482 8.36827 3.33329 8.00008 3.33329C7.63189 3.33329 7.33341 3.03482 7.33341 2.66663V1.33329C7.33341 0.965103 7.63189 0.666626 8.00008 0.666626Z" fill="#FB6514"/>
+<path d="M3.75729 2.81452C3.49694 2.55418 3.07483 2.55418 2.81448 2.81452C2.55413 3.07487 2.55413 3.49698 2.81448 3.75733L3.75729 4.70014C4.01764 4.96049 4.43975 4.96049 4.7001 4.70014C4.96045 4.43979 4.96045 4.01768 4.7001 3.75733L3.75729 2.81452Z" fill="#FB6514"/>
+<path d="M0.666748 7.99996C0.666748 7.63177 0.965225 7.33329 1.33341 7.33329H2.66675C3.03494 7.33329 3.33341 7.63177 3.33341 7.99996C3.33341 8.36815 3.03494 8.66663 2.66675 8.66663H1.33341C0.965225 8.66663 0.666748 8.36815 0.666748 7.99996Z" fill="#FB6514"/>
+<path d="M13.3334 7.33329C12.9652 7.33329 12.6667 7.63177 12.6667 7.99996C12.6667 8.36815 12.9652 8.66663 13.3334 8.66663H14.6667C15.0349 8.66663 15.3334 8.36815 15.3334 7.99996C15.3334 7.63177 15.0349 7.33329 14.6667 7.33329H13.3334Z" fill="#FB6514"/>
+<path d="M12.2426 11.2997C11.9823 11.0394 11.5602 11.0394 11.2998 11.2997C11.0395 11.5601 11.0395 11.9822 11.2998 12.2425L12.2426 13.1853C12.503 13.4457 12.9251 13.4457 13.1855 13.1853C13.4458 12.925 13.4458 12.5029 13.1855 12.2425L12.2426 11.2997Z" fill="#FB6514"/>
+<path d="M13.1855 3.75733C13.4458 3.49698 13.4458 3.07487 13.1855 2.81452C12.9251 2.55418 12.503 2.55418 12.2426 2.81452L11.2998 3.75733C11.0395 4.01768 11.0395 4.43979 11.2998 4.70014C11.5602 4.96049 11.9823 4.96049 12.2426 4.70014L13.1855 3.75733Z" fill="#FB6514"/>
+<path d="M8.00008 12.6666C8.36827 12.6666 8.66675 12.9651 8.66675 13.3333V14.6666C8.66675 15.0348 8.36827 15.3333 8.00008 15.3333C7.63189 15.3333 7.33341 15.0348 7.33341 14.6666V13.3333C7.33341 12.9651 7.63189 12.6666 8.00008 12.6666Z" fill="#FB6514"/>
+<path d="M4.7001 12.2425C4.96045 11.9822 4.96045 11.5601 4.7001 11.2997C4.43975 11.0394 4.01764 11.0394 3.75729 11.2997L2.81448 12.2425C2.55413 12.5029 2.55413 12.925 2.81448 13.1853C3.07483 13.4457 3.49694 13.4457 3.75729 13.1853L4.7001 12.2425Z" fill="#FB6514"/>
+<path d="M8.59791 4.37154C8.48559 4.14401 8.25385 3.99996 8.0001 3.99996C7.74635 3.99996 7.51461 4.14401 7.4023 4.37154L6.52726 6.14427L4.57035 6.4303C4.31931 6.46699 4.11085 6.643 4.0326 6.88434C3.95435 7.12567 4.01987 7.39051 4.20161 7.56753L5.61709 8.9462L5.28303 10.8939C5.24013 11.1441 5.34296 11.3968 5.54828 11.546C5.7536 11.6951 6.02579 11.7148 6.2504 11.5967L8.0001 10.6765L9.7498 11.5967C9.97441 11.7148 10.2466 11.6951 10.4519 11.546C10.6572 11.3968 10.7601 11.1441 10.7172 10.8939L10.3831 8.9462L11.7986 7.56753C11.9803 7.39051 12.0458 7.12567 11.9676 6.88434C11.8893 6.643 11.6809 6.46699 11.4299 6.4303L9.47294 6.14427L8.59791 4.37154Z" fill="#FB6514"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/trash.svg b/web/app/components/datasets/create/assets/trash.svg
new file mode 100644
index 00000000000..00c29894f68
--- /dev/null
+++ b/web/app/components/datasets/create/assets/trash.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6 2H10M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4M6.66667 7V10.3333M9.33333 7V10.3333" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/txt.svg b/web/app/components/datasets/create/assets/txt.svg
new file mode 100644
index 00000000000..d1b6a8c3c70
--- /dev/null
+++ b/web/app/components/datasets/create/assets/txt.svg
@@ -0,0 +1,23 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3055_14432)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#E3E5E8"/>
+<path d="M4.25 7.73349C4.25 6.60926 4.25019 5.78113 4.30367 5.12666C4.3569 4.47511 4.46169 4.01774 4.65873 3.63103C5.01825 2.92542 5.59193 2.35175 6.29754 1.99222C6.68424 1.79518 7.14162 1.6904 7.79317 1.63716C8.44763 1.58369 9.27577 1.5835 10.4 1.5835H18.5631L27.75 10.7704V24.2668C27.75 25.3911 27.7498 26.2192 27.6963 26.8737C27.6431 27.5252 27.5383 27.9826 27.3413 28.3693C26.9817 29.0749 26.4081 29.6486 25.7025 30.0081C25.3158 30.2051 24.8584 30.3099 24.2068 30.3632C23.5524 30.4166 22.7242 30.4168 21.6 30.4168H10.4C9.27577 30.4168 8.44763 30.4166 7.79317 30.3632C7.14162 30.3099 6.68424 30.2051 6.29754 30.0081C5.59193 29.6486 5.01825 29.0749 4.65873 28.3693C4.46169 27.9826 4.3569 27.5252 4.30367 26.8737C4.25019 26.2192 4.25 25.3911 4.25 24.2668V7.73349Z" stroke="black" stroke-opacity="0.03" stroke-width="0.5"/>
+</g>
+<g opacity="0.96">
+<path d="M13.2254 19.5522V18.3042H9.02539V19.5522H10.4254V24.0002H11.8254V19.5522H13.2254Z" fill="#667085"/>
+<path d="M18.5371 24.0002L16.7611 21.0802L18.4251 18.3042H16.8331L16.0011 19.9122L15.1691 18.3042H13.5771L15.2411 21.0802L13.4651 24.0002H15.0651L16.0011 22.2482L16.9371 24.0002H18.5371Z" fill="#667085"/>
+<path d="M22.9754 19.5522V18.3042H18.7754V19.5522H20.1754V24.0002H21.5754V19.5522H22.9754Z" fill="#667085"/>
+</g>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3055_14432" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3055_14432"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3055_14432" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/unknow.svg b/web/app/components/datasets/create/assets/unknow.svg
new file mode 100644
index 00000000000..6daa2432054
--- /dev/null
+++ b/web/app/components/datasets/create/assets/unknow.svg
@@ -0,0 +1,23 @@
+<svg width="32" height="34" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3055_14436)">
+<path d="M4 7.73349C4 5.49329 4 4.37318 4.43597 3.51753C4.81947 2.76489 5.43139 2.15296 6.18404 1.76947C7.03969 1.3335 8.15979 1.3335 10.4 1.3335H18.6667L28 10.6668V24.2668C28 26.507 28 27.6271 27.564 28.4828C27.1805 29.2354 26.5686 29.8474 25.816 30.2309C24.9603 30.6668 23.8402 30.6668 21.6 30.6668H10.4C8.15979 30.6668 7.03969 30.6668 6.18404 30.2309C5.43139 29.8474 4.81947 29.2354 4.43597 28.4828C4 27.6271 4 26.507 4 24.2668V7.73349Z" fill="#E3E5E8"/>
+<path d="M4.25 7.73349C4.25 6.60926 4.25019 5.78113 4.30367 5.12666C4.3569 4.47511 4.46169 4.01774 4.65873 3.63103C5.01825 2.92542 5.59193 2.35175 6.29754 1.99222C6.68424 1.79518 7.14162 1.6904 7.79317 1.63716C8.44763 1.58369 9.27577 1.5835 10.4 1.5835H18.5631L27.75 10.7704V24.2668C27.75 25.3911 27.7498 26.2192 27.6963 26.8737C27.6431 27.5252 27.5383 27.9826 27.3413 28.3693C26.9817 29.0749 26.4081 29.6486 25.7025 30.0081C25.3158 30.2051 24.8584 30.3099 24.2068 30.3632C23.5524 30.4166 22.7242 30.4168 21.6 30.4168H10.4C9.27577 30.4168 8.44763 30.4166 7.79317 30.3632C7.14162 30.3099 6.68424 30.2051 6.29754 30.0081C5.59193 29.6486 5.01825 29.0749 4.65873 28.3693C4.46169 27.9826 4.3569 27.5252 4.30367 26.8737C4.25019 26.2192 4.25 25.3911 4.25 24.2668V7.73349Z" stroke="black" stroke-opacity="0.03" stroke-width="0.5"/>
+</g>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M15.9998 23.1992C15.8014 23.1992 15.6039 23.1968 15.4077 23.1924V24.0549C15.4077 24.3819 15.6728 24.647 15.9998 24.647C16.3268 24.647 16.592 24.3819 16.592 24.0549V23.1924C16.3957 23.1968 16.1983 23.1992 15.9998 23.1992Z" fill="#98A2B3"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0984 22.8838L11.757 23.8593C11.649 24.168 11.8117 24.5058 12.1203 24.6138C12.185 24.6364 12.251 24.6472 12.3159 24.6472C12.5605 24.6472 12.7894 24.4944 12.8747 24.2505L13.2936 23.0534C12.8807 23.0073 12.481 22.9506 12.0984 22.8838Z" fill="#98A2B3"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M20.2431 23.8593L19.9018 22.8838C19.5192 22.9506 19.1195 23.0073 18.7065 23.0534L19.1254 24.2505C19.2108 24.4944 19.4396 24.6472 19.6843 24.6472C19.7491 24.6472 19.8151 24.6364 19.8798 24.6138C20.1885 24.5058 20.3511 24.168 20.2431 23.8593Z" fill="#98A2B3"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M20.1624 17.2634C20.2697 17.6416 20.3254 18.0369 20.3254 18.4409C20.3254 18.9087 20.05 19.3327 19.6226 19.5228C19.5564 19.5522 17.9801 20.2436 16.0359 20.2436C14.0917 20.2436 12.5153 19.5522 12.4492 19.5228C12.0218 19.3327 11.7464 18.9086 11.7464 18.4409C11.7464 18.0312 11.8037 17.6305 11.914 17.2476C10.3343 17.5645 8.5 18.2009 8.5 19.4464C8.5 20.2859 9.32512 20.9477 10.9525 21.4134C11.4194 21.547 11.9381 21.66 12.4949 21.7506C12.8783 21.813 13.28 21.8648 13.6953 21.9056C14.2455 21.9597 14.8197 21.9942 15.4079 22.0082C15.6039 22.0128 15.8013 22.0153 16 22.0153C16.1987 22.0153 16.3962 22.0128 16.5921 22.0082C17.1803 21.9943 17.7545 21.9596 18.3047 21.9056C18.72 21.8648 19.1217 21.8131 19.5051 21.7506C20.062 21.66 20.5807 21.547 21.0476 21.4134C22.6749 20.9477 23.5 20.2859 23.5 19.4464C23.5 18.2187 21.7108 17.5833 20.1624 17.2634Z" fill="#98A2B3"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M18.8441 17.1144C18.7585 16.9335 18.6559 16.7622 18.5384 16.6025C18.4174 16.4382 18.2809 16.286 18.1307 16.1486C17.5784 15.6437 16.8433 15.3354 16.036 15.3354C15.2318 15.3354 14.499 15.6411 13.9476 16.1426C13.7974 16.2791 13.6609 16.4303 13.5399 16.5937C13.4217 16.753 13.3185 16.924 13.2322 17.1048C13.039 17.5095 12.9307 17.9624 12.9307 18.4407C12.9307 18.4407 14.321 19.0592 16.036 19.0592C17.751 19.0592 19.1412 18.4407 19.1412 18.4407C19.1412 17.9662 19.0344 17.5167 18.8441 17.1144Z" fill="#98A2B3"/>
+<path opacity="0.5" d="M18.6665 1.3335L27.9998 10.6668H21.3332C19.8604 10.6668 18.6665 9.47292 18.6665 8.00016V1.3335Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3055_14436" x="2" y="0.333496" width="28" height="33.3335" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3055_14436"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3055_14436" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/create/assets/upload-cloud-01.svg b/web/app/components/datasets/create/assets/upload-cloud-01.svg
new file mode 100644
index 00000000000..4df53cf58c9
--- /dev/null
+++ b/web/app/components/datasets/create/assets/upload-cloud-01.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.4" d="M4 16.2422C2.79401 15.435 2 14.0602 2 12.5C2 10.1564 3.79151 8.23129 6.07974 8.01937C6.54781 5.17213 9.02024 3 12 3C14.9798 3 17.4522 5.17213 17.9203 8.01937C20.2085 8.23129 22 10.1564 22 12.5C22 14.0602 21.206 15.435 20 16.2422" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M8 16L12 12M12 12L16 16M12 12L12 21" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/web.svg b/web/app/components/datasets/create/assets/web.svg
new file mode 100644
index 00000000000..a9bac511b6d
--- /dev/null
+++ b/web/app/components/datasets/create/assets/web.svg
@@ -0,0 +1,4 @@
+<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M7.06124 2.21694C7.57213 2.07545 8.11041 1.99984 8.66634 1.99984C9.97432 1.99984 11.1845 2.41837 12.1704 3.12881C11.6459 3.4755 11.2546 3.85196 10.9834 4.25446C10.569 4.86947 10.4628 5.50546 10.5486 6.08575C10.632 6.64928 10.8907 7.13053 11.1627 7.48656C11.4265 7.83177 11.7501 8.12048 12.0351 8.26293C12.7526 8.62164 13.5806 8.80129 14.1996 8.89387C14.7596 8.97762 15.9468 9.2579 15.9907 8.36596C15.9967 8.24461 15.9997 8.12255 15.9997 7.99984C15.9997 3.94975 12.7164 0.666504 8.66634 0.666504C4.61625 0.666504 1.33301 3.94975 1.33301 7.99984C1.33301 12.0499 4.61625 15.3332 8.66634 15.3332C8.78906 15.3332 8.91112 15.3301 9.03246 15.3242C9.40021 15.3061 9.68364 14.9933 9.66553 14.6255C9.64743 14.2578 9.33463 13.9743 8.96689 13.9925C8.86737 13.9974 8.76717 13.9998 8.66634 13.9998C6.32676 13.9998 4.29993 12.6608 3.31046 10.7073L3.95617 10.3345L6.33797 10.7803C6.95507 10.8958 7.52471 10.4207 7.52192 9.79289L7.51258 7.69081L8.72983 5.60684C8.92705 5.2692 8.90938 4.84758 8.68459 4.52762L7.06124 2.21694Z" fill="#1570EF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M9.96344 8.43724C9.71815 8.3442 9.4411 8.40367 9.2556 8.58917C9.07009 8.77467 9.01063 9.05172 9.10367 9.29701L11.2149 14.8629C11.3123 15.1198 11.5575 15.2906 11.8323 15.2931C12.1071 15.2955 12.3552 15.1291 12.4572 14.8739L13.3377 12.6713L15.5403 11.7908C15.7955 11.6888 15.9619 11.4407 15.9595 11.1659C15.9571 10.891 15.7862 10.6459 15.5293 10.5484L9.96344 8.43724Z" fill="#1570EF"/>
+</svg>
diff --git a/web/app/components/datasets/create/assets/zap-fast.svg b/web/app/components/datasets/create/assets/zap-fast.svg
new file mode 100644
index 00000000000..7c67cf96e4c
--- /dev/null
+++ b/web/app/components/datasets/create/assets/zap-fast.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M1.66675 11.6666C1.66675 11.2985 1.96522 11 2.33341 11H6.00008C6.36827 11 6.66675 11.2985 6.66675 11.6666C6.66675 12.0348 6.36827 12.3333 6.00008 12.3333H2.33341C1.96522 12.3333 1.66675 12.0348 1.66675 11.6666Z" fill="#7839EE"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M0.666748 7.99997C0.666748 7.63178 0.965225 7.33331 1.33341 7.33331H4.33341C4.7016 7.33331 5.00008 7.63178 5.00008 7.99997C5.00008 8.36816 4.7016 8.66664 4.33341 8.66664H1.33341C0.965225 8.66664 0.666748 8.36816 0.666748 7.99997Z" fill="#7839EE"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M2.00008 4.33331C2.00008 3.96512 2.29856 3.66664 2.66675 3.66664H6.00008C6.36827 3.66664 6.66675 3.96512 6.66675 4.33331C6.66675 4.7015 6.36827 4.99997 6.00008 4.99997H2.66675C2.29856 4.99997 2.00008 4.7015 2.00008 4.33331Z" fill="#7839EE"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M11.5785 1.37998C11.8632 1.49253 12.0347 1.78458 11.9942 2.08808L11.4282 6.33331H13.9637C13.9714 6.33331 13.979 6.33331 13.9867 6.3333C14.1339 6.33327 14.2864 6.33324 14.4124 6.34476C14.5363 6.35609 14.7618 6.38612 14.9633 6.54167C15.1984 6.72308 15.3407 6.99955 15.3517 7.29625C15.3611 7.55067 15.2545 7.7516 15.1917 7.85904C15.1278 7.96825 15.0391 8.09234 14.9536 8.21207C14.9491 8.21833 14.9446 8.22457 14.9402 8.23079L10.5426 14.3875C10.3646 14.6366 10.0398 14.7325 9.75503 14.62C9.47027 14.5074 9.29879 14.2154 9.33926 13.9119L9.90529 9.66664H7.36978C7.36213 9.66664 7.35447 9.66664 7.34679 9.66664C7.19962 9.66668 7.0471 9.66671 6.92111 9.65519C6.79717 9.64386 6.5717 9.61383 6.37015 9.45828C6.13511 9.27687 5.99283 9.0004 5.98183 8.7037C5.9724 8.44928 6.07901 8.24835 6.14183 8.14091C6.20569 8.0317 6.29437 7.9076 6.37993 7.78787C6.3844 7.78162 6.38886 7.77538 6.3933 7.76915L10.7909 1.61248C10.9689 1.36332 11.2937 1.26743 11.5785 1.37998Z" fill="#7839EE"/>
+</svg>
diff --git a/web/app/components/datasets/create/empty-dataset-creation-modal/index.module.css b/web/app/components/datasets/create/empty-dataset-creation-modal/index.module.css
new file mode 100644
index 00000000000..37f971eb9dd
--- /dev/null
+++ b/web/app/components/datasets/create/empty-dataset-creation-modal/index.module.css
@@ -0,0 +1,38 @@
+.modal {
+ position: relative;
+}
+
+.modalHeader {
+ @apply flex items-center place-content-between h-8;
+}
+.modalHeader .title {
+ @apply grow;
+ font-weight: 600;
+ font-size: 20px;
+ line-height: 32px;
+ color: #101828;
+}
+.modalHeader .close {
+ @apply shrink-0 h-4 w-4 bg-center bg-no-repeat cursor-pointer;
+ background-image: url(../assets/close.svg);
+ background-size: 16px;
+}
+
+.modal .tip {
+ @apply mt-1 mb-8;
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 18px;
+ color: #667085;
+}
+
+.form {
+ @apply mb-8;
+}
+.form .label {
+ @apply mb-2;
+ font-weight: 500;
+ font-size: 14px;
+ line-height: 20px;
+ color: #101828;
+}
diff --git a/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx
new file mode 100644
index 00000000000..b6dade73d3b
--- /dev/null
+++ b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx
@@ -0,0 +1,73 @@
+'use client'
+import React, { useState } from 'react'
+import { useRouter } from 'next/navigation'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import Modal from '@/app/components/base/modal'
+import Input from '@/app/components/base/input'
+import Button from '@/app/components/base/button'
+
+import { ToastContext } from '@/app/components/base/toast'
+import { createEmptyDataset } from '@/service/datasets'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IProps = {
+ show: boolean,
+ onHide: () => void,
+}
+
+const EmptyDatasetCreationModal = ({
+ show = false,
+ onHide,
+}: IProps) => {
+ const [inputValue, setInputValue] = useState('')
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+ const router = useRouter()
+
+ const submit = async () => {
+ if (!inputValue) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.modal.nameNotEmpty') })
+ return
+ }
+ if (inputValue.length > 40) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.modal.nameLengthInvaild') })
+ return
+ }
+ try {
+ const dataset = await createEmptyDataset({ name: inputValue })
+ onHide()
+ router.push(`/datasets/${dataset.id}/documents`)
+ }
+ catch (err) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.modal.failed') })
+ return
+ }
+ }
+
+ return (
+ <Modal
+ isShow={show}
+ onClose={onHide}
+ className={cn(s.modal, '!max-w-[520px]', 'px-8')}
+ >
+ <div className={s.modalHeader}>
+ <div className={s.title}>{t('datasetCreation.stepOne.modal.title')}</div>
+ <span className={s.close} onClick={onHide}/>
+ </div>
+ <div className={s.tip}>{t('datasetCreation.stepOne.modal.tip')}</div>
+ <div className={s.form}>
+ <div className={s.label}>{t('datasetCreation.stepOne.modal.input')}</div>
+ <Input className='!h-8' value={inputValue} placeholder={t('datasetCreation.stepOne.modal.placeholder') || ''} onChange={setInputValue} />
+ </div>
+ <div className='flex flex-row-reverse'>
+ <Button className='w-24 ml-2' type='primary' onClick={submit}>{t('datasetCreation.stepOne.modal.confirmButton')}</Button>
+ <Button className='w-24' onClick={onHide}>{t('datasetCreation.stepOne.modal.cancelButton')}</Button>
+ </div>
+ </Modal>
+ )
+}
+
+export default EmptyDatasetCreationModal
diff --git a/web/app/components/datasets/create/file-preview/index.module.css b/web/app/components/datasets/create/file-preview/index.module.css
new file mode 100644
index 00000000000..8c2e767848f
--- /dev/null
+++ b/web/app/components/datasets/create/file-preview/index.module.css
@@ -0,0 +1,46 @@
+.filePreview {
+ @apply flex flex-col border-l border-gray-200 shrink-0;
+ width: 528px;
+ background-color: #fcfcfd;
+ }
+
+ .previewHeader {
+ @apply border-b border-gray-200 shrink-0;
+ margin: 42px 32px 0;
+ padding-bottom: 16px;
+ }
+
+ .previewHeader .title {
+ color: #101828;
+ font-weight: 600;
+ font-size: 18px;
+ line-height: 28px;
+ }
+
+ .previewHeader .fileName {
+ font-weight: 400;
+ font-size: 12px;
+ line-height: 18px;
+ color: #1D2939;
+ }
+
+ .previewHeader .filetype {
+ color: #667085;
+ }
+
+ .previewContent {
+ @apply overflow-y-auto grow;
+ padding: 20px 32px;
+ font-weight: 400;
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+ }
+
+ .previewContent .loading {
+ width: 100%;
+ height: 180px;
+ background: #f9fafb center no-repeat url(../assets/Loading.svg);
+ background-size: contain;
+ }
+
\ No newline at end of file
diff --git a/web/app/components/datasets/create/file-preview/index.tsx b/web/app/components/datasets/create/file-preview/index.tsx
new file mode 100644
index 00000000000..ad9f866c160
--- /dev/null
+++ b/web/app/components/datasets/create/file-preview/index.tsx
@@ -0,0 +1,62 @@
+'use client'
+import React, { useState, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { File } from '@/models/datasets'
+import { fetchFilePreview } from '@/service/common'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IProps = {
+ file?: File,
+}
+
+const FilePreview = ({
+ file,
+}: IProps) => {
+ const { t } = useTranslation()
+ const [previewContent, setPreviewContent] = useState('')
+ const [loading, setLoading] = useState(true)
+
+ const getPreviewContent = async (fileID: string) => {
+ try {
+ const res = await fetchFilePreview({ fileID })
+ setPreviewContent(res.content)
+ setLoading(false)
+ }
+ catch {}
+ }
+
+ const getFileName = (currentFile?: File) => {
+ if (!currentFile) {
+ return ''
+ }
+ const arr = currentFile.name.split('.')
+ return arr.slice(0, -1).join()
+ }
+
+ useEffect(() => {
+ if (file) {
+ getPreviewContent(file.id)
+ }
+ }, [file])
+
+ return (
+ <div className={cn(s.filePreview)}>
+ <div className={cn(s.previewHeader)}>
+ <div className={cn(s.title)}>{t('datasetCreation.stepOne.filePreview')}</div>
+ <div className={cn(s.fileName)}>
+ <span>{getFileName(file)}</span><span className={cn(s.filetype)}>.{file?.extension}</span>
+ </div>
+ </div>
+ <div className={cn(s.previewContent)}>
+ {loading && <div className={cn(s.loading)}/>}
+ {!loading && (
+ <div className={cn(s.fileContent)}>{previewContent}</div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+export default FilePreview
diff --git a/web/app/components/datasets/create/file-uploader/index.module.css b/web/app/components/datasets/create/file-uploader/index.module.css
new file mode 100644
index 00000000000..9f04b6ffbaa
--- /dev/null
+++ b/web/app/components/datasets/create/file-uploader/index.module.css
@@ -0,0 +1,171 @@
+.fileUploader {
+ @apply mb-9;
+}
+.fileUploader .title {
+ @apply mb-2;
+ font-weight: 500;
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+}
+.fileUploader .tip {
+ @apply mt-2;
+ font-weight: 400;
+ font-size: 12px;
+ line-height: 26px;
+ color: #667085;
+}
+.uploader {
+ @apply relative box-border flex justify-center items-center;
+ max-width: 640px;
+ height: 80px;
+ background: #F9FAFB;
+ border: 1px dashed #EAECF0;
+ border-radius: 12px;
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #667085;
+}
+.uploader.dragging {
+ background: #F5F8FF;
+ border: 1px dashed #B2CCFF;
+}
+.uploader .draggingCover {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+}
+.uploader::before {
+ content: '';
+ display: block;
+ margin-right: 8px;
+ width: 24px;
+ height: 24px;
+ background: center no-repeat url(../assets/upload-cloud-01.svg);
+ background-size: contain;
+}
+.uploader .browse{
+ @apply pl-1 cursor-pointer;
+ color: #155eef;
+}
+
+.file {
+ @apply box-border relative flex items-center;
+ padding: 21px 24px 21px 64px;
+ max-width: 640px;
+ height: 80px;
+ background: #F9FAFB;
+ border: 1px solid #F2F4F7;
+ border-radius: 12px;
+ overflow: hidden;
+}
+.progressbar {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ background-color: #F2F4F7;
+}
+.file:hover {
+ background: #F5F8FF;
+ border: 1px solid #D1E0FF;
+}
+.file:hover .actionWrapper .buttonWrapper {
+ display: flex;
+ align-items: center;
+}
+.file:hover .actionWrapper .divider {
+ display: block;
+}
+.file.uploading,
+.file.uploading:hover {
+ background: #FCFCFD;
+ border: 1px solid #EAECF0;
+}
+.file.uploading:hover .actionWrapper .percent {
+ padding: 8px;
+}
+.file.uploading:hover .actionWrapper .buttonWrapper {
+ display: flex;
+ align-items: center;
+}
+.fileIcon {
+ @apply w-8 h-8 bg-center bg-no-repeat;
+ position: absolute;
+ top: 24px;
+ left: 24px;
+ background-image: url(../assets/unknow.svg);
+ background-size: 32px;
+}
+.fileIcon.pdf {
+ background-image: url(../assets/pdf.svg);
+}
+.fileIcon.html,
+.fileIcon.htm {
+ background-image: url(../assets/html.svg);
+}
+.fileIcon.md,
+.fileIcon.markdown {
+ background-image: url(../assets/md.svg);
+}
+.fileIcon.txt {
+ background-image: url(../assets/txt.svg);
+}
+.fileIcon.json {
+ background-image: url(../assets/json.svg);
+}
+.fileInfo {
+ @apply grow;
+ z-index: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.filename {
+ font-weight: 500;
+ font-size: 14px;
+ line-height: 20px;
+}
+.name {
+ color: #1D2939;
+ line-height: 20px;
+}
+.extension {
+ color: #667085;
+ line-height: 20px;
+}
+.fileExtraInfo {
+ color: #667085;
+ font-size: 12px;
+ line-height: 18px;
+}
+.actionWrapper {
+ @apply flex items-center shrink-0;
+ z-index: 1;
+}
+.actionWrapper .percent {
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+}
+.actionWrapper .divider {
+ display: none;
+ margin: 0 8px;
+ width: 1px;
+ height: 16px;
+ background: #FEE4E2;
+}
+.actionWrapper .remove {
+ width: 32px;
+ height: 32px;
+ background: center no-repeat url(../assets/trash.svg);
+ background-size: 16px;
+ cursor: pointer;
+}
+.actionWrapper .buttonWrapper {
+ @apply flex items-center;
+ display: none;
+}
\ No newline at end of file
diff --git a/web/app/components/datasets/create/file-uploader/index.tsx b/web/app/components/datasets/create/file-uploader/index.tsx
new file mode 100644
index 00000000000..cb750c678c9
--- /dev/null
+++ b/web/app/components/datasets/create/file-uploader/index.tsx
@@ -0,0 +1,265 @@
+'use client'
+import React, { useState, useRef, useEffect, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { File as FileEntity } from '@/models/datasets'
+import { useContext } from 'use-context-selector'
+import { ToastContext } from '@/app/components/base/toast'
+import Button from '@/app/components/base/button'
+
+import { upload } from '@/service/base'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IFileUploaderProps = {
+ file?: FileEntity;
+ onFileUpdate: (file?: FileEntity) => void;
+}
+
+const ACCEPTS = [
+ '.pdf',
+ '.html',
+ '.htm',
+ '.md',
+ '.markdown',
+ '.txt',
+]
+
+const MAX_SIZE = 15 * 1024 *1024
+
+const FileUploader = ({ file, onFileUpdate }: IFileUploaderProps) => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+ const [dragging, setDragging] = useState(false)
+ const dropRef = useRef<HTMLDivElement>(null)
+ const dragRef = useRef<HTMLDivElement>(null)
+ const fileUploader = useRef<HTMLInputElement>(null)
+ const uploadPromise = useRef<any>(null)
+ const [currentFile, setCurrentFile] = useState<File>()
+ const [uploading, setUploading] = useState(false)
+ const [percent, setPercent] = useState(0)
+
+ const handleDragEnter = (e: DragEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ e.target !== dragRef.current && setDragging(true)
+ }
+ const handleDragOver = (e: DragEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ }
+ const handleDragLeave = (e: DragEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ e.target === dragRef.current && setDragging(false)
+ }
+ const handleDrop = (e: DragEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setDragging(false)
+ if (!e.dataTransfer) {
+ return
+ }
+ const files = [...e.dataTransfer.files]
+ if (files.length > 1) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.count') })
+ return;
+ }
+ onFileUpdate()
+ fileUpload(files[0])
+ }
+
+ const selectHandle = () => {
+ if (fileUploader.current) {
+ fileUploader.current.click();
+ }
+ }
+ const removeFile = () => {
+ if (fileUploader.current) {
+ fileUploader.current.value = ''
+ }
+ setCurrentFile(undefined)
+ onFileUpdate()
+ }
+ const fileChangeHandle = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const currentFile = e.target.files?.[0]
+ onFileUpdate()
+ fileUpload(currentFile)
+ }
+ const fileUpload = async (file?: File) => {
+ if (!file) {
+ return
+ }
+ if (!isValid(file)) {
+ return
+ }
+ setCurrentFile(file)
+ setUploading(true)
+ const formData = new FormData()
+ formData.append('file', file)
+ // store for abort
+ const currentXHR = new XMLHttpRequest()
+ uploadPromise.current = currentXHR
+ try {
+ const result = await upload({
+ xhr: currentXHR,
+ data: formData,
+ onprogress: onProgress,
+ }) as FileEntity;
+ onFileUpdate(result)
+ setUploading(false)
+ }
+ catch (xhr: any) {
+ setUploading(false)
+ // abort handle
+ if (xhr.readyState === 0 && xhr.status === 0) {
+ if (fileUploader.current) {
+ fileUploader.current.value = ''
+ }
+ setCurrentFile(undefined)
+ return
+ }
+ notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.failed') })
+ return
+ }
+ }
+ const onProgress = useCallback((e: ProgressEvent) => {
+ if (e.lengthComputable) {
+ const percent = Math.floor(e.loaded / e.total * 100)
+ setPercent(percent)
+ }
+ }, [setPercent])
+ const abort = () => {
+ const currentXHR = uploadPromise.current
+ currentXHR.abort();
+ }
+
+ // utils
+ const getFileType = (currentFile: File) => {
+ if (!currentFile) {
+ return ''
+ }
+ const arr = currentFile.name.split('.')
+ return arr[arr.length-1]
+ }
+ const getFileName = (name: string) => {
+ const arr = name.split('.')
+ return arr.slice(0, -1).join()
+ }
+ const getFileSize = (size: number) => {
+ if (size / 1024 < 10) {
+ return `${(size / 1024).toFixed(2)}KB`
+ }
+ return `${(size / 1024 / 1024).toFixed(2)}MB`
+ }
+ const isValid = (file: File) => {
+ const { size } = file
+ const ext = `.${getFileType(file)}`
+ const isValidType = ACCEPTS.includes(ext)
+ if (!isValidType) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.typeError') })
+ }
+ const isValidSize = size <= MAX_SIZE;
+ if (!isValidSize) {
+ notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.size') })
+ }
+ return isValidType && isValidSize;
+ }
+
+ useEffect(() => {
+ dropRef.current?.addEventListener('dragenter', handleDragEnter);
+ dropRef.current?.addEventListener('dragover', handleDragOver);
+ dropRef.current?.addEventListener('dragleave', handleDragLeave);
+ dropRef.current?.addEventListener('drop', handleDrop);
+ return () => {
+ dropRef.current?.removeEventListener('dragenter', handleDragEnter);
+ dropRef.current?.removeEventListener('dragover', handleDragOver);
+ dropRef.current?.removeEventListener('dragleave', handleDragLeave);
+ dropRef.current?.removeEventListener('drop', handleDrop);
+ }
+ }, [])
+
+ return (
+ <div className={s.fileUploader}>
+ <input
+ ref={fileUploader}
+ style={{ display: 'none' }}
+ type="file"
+ id="fileUploader"
+ accept={ACCEPTS.join(',')}
+ onChange={fileChangeHandle}
+ />
+ <div className={s.title}>{t('datasetCreation.stepOne.uploader.title')}</div>
+ {!currentFile && !file && (
+ <div ref={dropRef} className={cn(s.uploader, dragging && s.dragging)}>
+ <span>{t('datasetCreation.stepOne.uploader.button')}</span>
+ <label className={s.browse} onClick={selectHandle}>{t('datasetCreation.stepOne.uploader.browse')}</label>
+ {dragging && <div ref={dragRef} className={s.draggingCover}/>}
+ </div>
+ )}
+ {currentFile && (
+ <div className={cn(s.file, uploading && s.uploading)}>
+ {uploading && (
+ <div className={s.progressbar} style={{ width: `${percent}%`}}/>
+ )}
+ <div className={cn(s.fileIcon, s[getFileType(currentFile)])}/>
+ <div className={s.fileInfo}>
+ <div className={s.filename}>
+ <span className={s.name}>{getFileName(currentFile.name)}</span>
+ <span className={s.extension}>{`.${getFileType(currentFile)}`}</span>
+ </div>
+ <div className={s.fileExtraInfo}>
+ <span className={s.size}>{getFileSize(currentFile.size)}</span>
+ <span className={s.error}></span>
+ </div>
+ </div>
+ <div className={s.actionWrapper}>
+ {uploading && (
+ <>
+ <div className={s.percent}>{`${percent}%`}</div>
+ <div className={s.divider}/>
+ <div className={s.buttonWrapper}>
+ <Button className={cn(s.button, 'ml-2 !h-8 bg-white')} onClick={abort}>{t('datasetCreation.stepOne.uploader.cancel')}</Button>
+ </div>
+ </>
+ )}
+ {!uploading && (
+ <>
+ <div className={s.buttonWrapper}>
+ <Button className={cn(s.button, 'ml-2 !h-8 bg-white')} onClick={selectHandle}>{t('datasetCreation.stepOne.uploader.change')}</Button>
+ <div className={s.divider}/>
+ <div className={s.remove} onClick={removeFile}/>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )}
+ {!currentFile && file && (
+ <div className={cn(s.file)}>
+ <div className={cn(s.fileIcon, s[file.extension])}/>
+ <div className={s.fileInfo}>
+ <div className={s.filename}>
+ <span className={s.name}>{getFileName(file.name)}</span>
+ <span className={s.extension}>{`.${file.extension}`}</span>
+ </div>
+ <div className={s.fileExtraInfo}>
+ <span className={s.size}>{getFileSize(file.size)}</span>
+ <span className={s.error}></span>
+ </div>
+ </div>
+ <div className={s.actionWrapper}>
+ <div className={s.buttonWrapper}>
+ <Button className={cn(s.button, 'ml-2 !h-8 bg-white')} onClick={selectHandle}>{t('datasetCreation.stepOne.uploader.change')}</Button>
+ <div className={s.divider}/>
+ <div className={s.remove} onClick={removeFile}/>
+ </div>
+ </div>
+ </div>
+ )}
+ <div className={s.tip}>{t('datasetCreation.stepOne.uploader.tip')}</div>
+ </div>
+ )
+}
+
+export default FileUploader;
diff --git a/web/app/components/datasets/create/index.module.css b/web/app/components/datasets/create/index.module.css
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/web/app/components/datasets/create/index.tsx b/web/app/components/datasets/create/index.tsx
new file mode 100644
index 00000000000..344e7ee8647
--- /dev/null
+++ b/web/app/components/datasets/create/index.tsx
@@ -0,0 +1,113 @@
+'use client'
+import React, { useState, useCallback, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useBoolean } from 'ahooks'
+import type { DataSet, File, createDocumentResponse } from '@/models/datasets'
+import { fetchTenantInfo } from '@/service/common'
+import { fetchDataDetail } from '@/service/datasets'
+
+import StepsNavBar from './steps-nav-bar'
+import StepOne from './step-one'
+import StepTwo from './step-two'
+import StepThree from './step-three'
+import AccountSetting from '@/app/components/header/account-setting'
+import AppUnavailable from '../../base/app-unavailable'
+
+type DatasetUpdateFormProps = {
+ datasetId?: string;
+}
+
+const DatasetUpdateForm = ({ datasetId }: DatasetUpdateFormProps) => {
+ const { t } = useTranslation()
+ const [hasSetAPIKEY, setHasSetAPIKEY] = useState(true)
+ const [isShowSetAPIKey, { setTrue: showSetAPIKey, setFalse: hideSetAPIkey }] = useBoolean()
+ const [step, setStep] = useState(1)
+ const [indexingTypeCache, setIndexTypeCache] = useState('')
+ const [file, setFile] = useState<File | undefined>()
+ const [result, setResult] = useState<createDocumentResponse | undefined>()
+ const [hasError, setHasError] = useState(false)
+
+ const updateFile = (file?: File) => {
+ setFile(file)
+ }
+ const updateIndexingTypeCache = (type: string) => {
+ setIndexTypeCache(type)
+ }
+ const updateResultCache = (res?: createDocumentResponse) => {
+ setResult(res)
+ }
+
+ const nextStep = useCallback(() => {
+ setStep(step + 1)
+ }, [step, setStep])
+
+ const changeStep = useCallback((delta: number) => {
+ setStep(step + delta)
+ }, [step, setStep])
+
+ const checkAPIKey = async () => {
+ const data = await fetchTenantInfo({ url: '/info' })
+ const hasSetKey = data.providers.some(({ is_valid }) => is_valid)
+ setHasSetAPIKEY(hasSetKey)
+ }
+
+ useEffect(() => {
+ checkAPIKey()
+ }, [])
+
+ const [detail, setDetail] = useState<DataSet | null>(null)
+ useEffect(() => {
+ (async () => {
+ if (datasetId) {
+ try {
+ const detail = await fetchDataDetail(datasetId)
+ setDetail(detail)
+ } catch (e) {
+ setHasError(true)
+ }
+ }
+ })()
+ }, [datasetId])
+
+ if (hasError) {
+ return <AppUnavailable code={500} unknownReason={t('datasetCreation.error.unavailable') as string} />
+ }
+
+ return (
+ <div className='flex' style={{ height: 'calc(100vh - 56px)' }}>
+ <div className="flex flex-col w-56 overflow-y-auto bg-white border-r border-gray-200 shrink-0">
+ <StepsNavBar step={step} datasetId={datasetId} />
+ </div>
+ <div className="grow bg-white">
+ {step === 1 && <StepOne
+ datasetId={datasetId}
+ file={file}
+ updateFile={updateFile}
+ onStepChange={nextStep}
+ />}
+ {(step === 2 && (!datasetId || (datasetId && !!detail))) && <StepTwo
+ hasSetAPIKEY={hasSetAPIKEY}
+ onSetting={showSetAPIKey}
+ indexingType={detail?.indexing_technique || ''}
+ datasetId={datasetId}
+ file={file}
+ onStepChange={changeStep}
+ updateIndexingTypeCache={updateIndexingTypeCache}
+ updateResultCache={updateResultCache}
+ />}
+ {step === 3 && <StepThree
+ datasetId={datasetId}
+ datasetName={detail?.name}
+ indexingType={detail?.indexing_technique || indexingTypeCache}
+ creationCache={result}
+ />}
+ </div>
+ {isShowSetAPIKey && <AccountSetting activeTab="provider" onCancel={async () => {
+ await checkAPIKey()
+ hideSetAPIkey()
+ }} />}
+ </div>
+ )
+}
+
+export default DatasetUpdateForm
diff --git a/web/app/components/datasets/create/step-one/index.module.css b/web/app/components/datasets/create/step-one/index.module.css
new file mode 100644
index 00000000000..bf391bf8dd4
--- /dev/null
+++ b/web/app/components/datasets/create/step-one/index.module.css
@@ -0,0 +1,109 @@
+.stepHeader {
+ position: sticky;
+ top: 0;
+ left: 0;
+ padding: 42px 64px 12px;
+ font-weight: 600;
+ font-size: 18px;
+ line-height: 28px;
+ color: #101828;
+}
+
+.form {
+ padding: 12px 64px;
+}
+
+.dataSourceTypeList {
+ @apply flex items-center mb-8;
+}
+.dataSourceItem {
+ @apply box-border relative shrink-0 flex items-center mr-3 p-3 h-14 bg-white rounded-xl cursor-pointer;
+ border: 0.5px solid #EAECF0;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ font-weight: 500;
+ font-size: 14px;
+ line-height: 20px;
+ color: #101828;
+}
+.dataSourceItem:hover {
+ background-color: #f5f8ff;
+ border: 0.5px solid #B2CCFF;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
+.dataSourceItem.active {
+ background-color: #f5f8ff;
+ border: 1.5px solid #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+.dataSourceItem.disabled {
+ background-color: #f9fafb;
+ border: 0.5px solid #EAECF0;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ cursor: default;
+}
+.dataSourceItem.disabled:hover {
+ background-color: #f9fafb;
+ border: 0.5px solid #EAECF0;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+}
+.comingTag {
+ @apply flex justify-center items-center bg-white;
+ position: absolute;
+ right: 8px;
+ top: -10px;
+ padding: 1px 6px;
+ height: 20px;
+ border: 1px solid #E0EAFF;
+ border-radius: 6px;
+ font-weight: 500;
+ font-size: 12px;
+ line-height: 18px;
+ color: #444CE7;
+}
+.datasetIcon {
+ @apply flex mr-2 w-8 h-8 rounded-lg bg-center bg-no-repeat;
+ background-color: #F5FAFF;
+ background-image: url(../assets/file.svg);
+ background-size: 16px;
+ border: 0.5px solid #D1E9FF;
+}
+.dataSourceItem:active .datasetIcon,
+.dataSourceItem:hover .datasetIcon {
+ background-color: #F5F8FF;
+ border: 0.5px solid #E0EAFF;
+}
+.datasetIcon.notion {
+ background-image: url(../assets/notion.svg);
+ background-size: 20px;
+}
+.datasetIcon.web {
+ background-image: url(../assets/web.svg);
+}
+
+.submitButton {
+ width: 120px;
+}
+
+.dividerLine {
+ margin: 32px 0;
+ max-width: 640px;
+ height: 1px;
+ background-color: #eaecf0;
+}
+
+.OtherCreationOption {
+ @apply flex items-center cursor-pointer;
+ font-weight: 500;
+ font-size: 13px;
+ line-height: 18px;
+ color: #155EEF;
+}
+.OtherCreationOption::before {
+ content: '';
+ display: block;
+ margin-right: 4px;
+ width: 16px;
+ height: 16px;
+ background: center no-repeat url(../assets/folder-plus.svg);
+ background-size: contain;
+}
diff --git a/web/app/components/datasets/create/step-one/index.tsx b/web/app/components/datasets/create/step-one/index.tsx
new file mode 100644
index 00000000000..b93fba9104a
--- /dev/null
+++ b/web/app/components/datasets/create/step-one/index.tsx
@@ -0,0 +1,80 @@
+'use client'
+import React, { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { File } from '@/models/datasets'
+import FilePreview from '../file-preview'
+import FileUploader from '../file-uploader'
+import EmptyDatasetCreationModal from '../empty-dataset-creation-modal'
+import Button from '@/app/components/base/button'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IStepOneProps = {
+ datasetId?: string,
+ file?: File,
+ updateFile: (file?: File) => void,
+ onStepChange: () => void,
+}
+
+const StepOne = ({
+ datasetId,
+ onStepChange,
+ file,
+ updateFile,
+}: IStepOneProps) => {
+ const [dataSourceType, setDataSourceType] = useState('FILE')
+ const [showModal, setShowModal] = useState(false)
+ const { t } = useTranslation()
+
+ const modalShowHandle = () => setShowModal(true)
+
+ const modalCloseHandle = () => setShowModal(false)
+
+ return (
+ <div className='flex w-full h-full'>
+ <div className='grow overflow-y-auto relative'>
+ <div className={s.stepHeader}>{t('datasetCreation.steps.one')}</div>
+ <div className={s.form}>
+ <div className={s.dataSourceTypeList}>
+ <div
+ className={cn(s.dataSourceItem, dataSourceType === 'FILE' && s.active)}
+ onClick={() => setDataSourceType('FILE')}
+ >
+ <span className={cn(s.datasetIcon)}/>
+ {t('datasetCreation.stepOne.dataSourceType.file')}
+ </div>
+ <div
+ className={cn(s.dataSourceItem, s.disabled, dataSourceType === 'notion' && s.active)}
+ // onClick={() => setDataSourceType('notion')}
+ >
+ <span className={s.comingTag}>Coming soon</span>
+ <span className={cn(s.datasetIcon, s.notion)}/>
+ {t('datasetCreation.stepOne.dataSourceType.notion')}
+ </div>
+ <div
+ className={cn(s.dataSourceItem, s.disabled, dataSourceType === 'web' && s.active)}
+ // onClick={() => setDataSourceType('web')}
+ >
+ <span className={s.comingTag}>Coming soon</span>
+ <span className={cn(s.datasetIcon, s.web)}/>
+ {t('datasetCreation.stepOne.dataSourceType.web')}
+ </div>
+ </div>
+ <FileUploader onFileUpdate={updateFile} file={file} />
+ <Button disabled={!file} className={s.submitButton} type='primary' onClick={onStepChange}>{t('datasetCreation.stepOne.button')}</Button>
+ {!datasetId && (
+ <>
+ <div className={s.dividerLine}/>
+ <div onClick={modalShowHandle} className={s.OtherCreationOption}>{t('datasetCreation.stepOne.emptyDatasetCreation')}</div>
+ </>
+ )}
+ </div>
+ <EmptyDatasetCreationModal show={showModal} onHide={modalCloseHandle}/>
+ </div>
+ {file && <FilePreview file={file} />}
+ </div>
+ )
+}
+
+export default StepOne
diff --git a/web/app/components/datasets/create/step-three/index.module.css b/web/app/components/datasets/create/step-three/index.module.css
new file mode 100644
index 00000000000..57fe7050c78
--- /dev/null
+++ b/web/app/components/datasets/create/step-three/index.module.css
@@ -0,0 +1,75 @@
+.creationInfo {
+ padding-top: 42px;
+}
+.creationInfo .title {
+ @apply mb-2;
+ font-weight: 500;
+ font-size: 20px;
+ line-height: 30px;
+ color: #101828;
+}
+.creationInfo .content {
+ margin-bottom: 44px;
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #667085;
+}
+.creationInfo .label {
+ @apply mb-2;
+ font-weight: 500;
+ font-size: 14px;
+ line-height: 20px;
+ color: #101828;
+}
+.datasetName {
+ padding: 8px 12px;
+ background: #F9FAFB;
+ border-radius: 8px;
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #101828;
+ word-break: break-all;
+}
+
+.dividerLine {
+ margin: 24px 0;
+ height: 1px;
+ background-color: #eaecf0;
+}
+
+.sideTip {
+ @apply flex flex-col items-center shrink-0 ;
+ padding-top: 108px;
+ width: 524px;
+ border-left: 0.5px solid #F2F4F7;
+}
+.tipCard {
+ @apply flex flex-col items-start p-6;
+ width: 320px;
+ background-color: #F9FAFB;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ border-radius: 12px;
+}
+.tipCard .icon {
+ width: 32px;
+ height: 32px;
+ border: 1px solid #EAECF0;
+ border-radius: 6px;
+ background: center no-repeat url(../assets/book-open-01.svg);
+ background-size: 16px;
+}
+.tipCard .title {
+ margin: 12px 0;
+ font-weight: 500;
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+}
+.tipCard .content {
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #344054;
+}
diff --git a/web/app/components/datasets/create/step-three/index.tsx b/web/app/components/datasets/create/step-three/index.tsx
new file mode 100644
index 00000000000..04eab14e53d
--- /dev/null
+++ b/web/app/components/datasets/create/step-three/index.tsx
@@ -0,0 +1,61 @@
+'use client'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import type { createDocumentResponse } from '@/models/datasets'
+import EmbeddingDetail from '../../documents/detail/embedding'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type StepThreeProps = {
+ datasetId?: string,
+ datasetName?: string,
+ indexingType?: string,
+ creationCache?: createDocumentResponse
+}
+
+const StepThree = ({ datasetId, datasetName, indexingType, creationCache }: StepThreeProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className='flex w-full h-full'>
+ <div className={'h-full w-full overflow-y-scroll px-16'}>
+ <div className='max-w-[636px]'>
+ {!datasetId && (
+ <>
+ <div className={s.creationInfo}>
+ <div className={s.title}>{t('datasetCreation.stepThree.creationTitle')}</div>
+ <div className={s.content}>{t('datasetCreation.stepThree.creationContent')}</div>
+ <div className={s.label}>{t('datasetCreation.stepThree.label')}</div>
+ <div className={s.datasetName}>{datasetName || creationCache?.dataset?.name}</div>
+ </div>
+ <div className={s.dividerLine}/>
+ </>
+ )}
+ {datasetId && (
+ <div className={s.creationInfo}>
+ <div className={s.title}>{t('datasetCreation.stepThree.additionTitle')}</div>
+ <div className={s.content}>{`${t('datasetCreation.stepThree.additionP1')} ${datasetName || creationCache?.dataset?.name} ${t('datasetCreation.stepThree.additionP2')}`}</div>
+ </div>
+ )}
+ <EmbeddingDetail
+ datasetId={datasetId || creationCache?.dataset?.id}
+ documentId={creationCache?.document.id}
+ indexingType={indexingType || creationCache?.dataset?.indexing_technique}
+ stopPosition='bottom'
+ detail={creationCache?.document}
+ />
+ </div>
+ </div>
+ <div className={cn(s.sideTip)}>
+ <div className={s.tipCard}>
+ <span className={s.icon}/>
+ <div className={s.title}>{t('datasetCreation.stepThree.sideTipTitle')}</div>
+ <div className={s.content}>{t('datasetCreation.stepThree.sideTipContent')}</div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default StepThree;
diff --git a/web/app/components/datasets/create/step-two/index.module.css b/web/app/components/datasets/create/step-two/index.module.css
new file mode 100644
index 00000000000..14df7839076
--- /dev/null
+++ b/web/app/components/datasets/create/step-two/index.module.css
@@ -0,0 +1,382 @@
+.pageHeader {
+ @apply px-16;
+ position: sticky;
+ top: 0;
+ left: 0;
+ padding-top: 42px;
+ padding-bottom: 12px;
+ background-color: #fff;
+ font-weight: 600;
+ font-size: 18px;
+ line-height: 28px;
+ color: #101828;
+ z-index: 10;
+}
+
+.fixed {
+ background: rgba(255, 255, 255, 0.9);
+ border-bottom: 0.5px solid #EAECF0;
+ backdrop-filter: blur(4px);
+}
+
+.form {
+ @apply px-16 pb-8;
+}
+
+.form .label {
+ @apply pt-6 pb-2;
+ font-weight: 500;
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+}
+
+.segmentationItem {
+ min-height: 68px;
+}
+
+.indexItem {
+ min-height: 146px;
+}
+
+.indexItem .disableMask {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(255, 255, 255, 0.5);
+ border-radius: 12px;
+ z-index: 2;
+}
+
+.indexItem .warningTip {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ padding: 8px 20px 8px 40px;
+ background: #FFFAEB;
+ border-top: 0.5px solid #FEF0C7;
+ border-radius: 12px;
+ font-size: 12px;
+ line-height: 18px;
+ color: #344054;
+ z-index: 3;
+}
+
+.indexItem .warningTip::before {
+ content: '';
+ position: absolute;
+ top: 11px;
+ left: 20px;
+ width: 12px;
+ height: 12px;
+ background: center no-repeat url(../assets/alert-triangle.svg);
+ background-size: 12px;
+}
+
+.indexItem .warningTip .click {
+ color: #155EEF;
+ cursor: pointer;
+}
+
+.indexItem.disabled:hover {
+ background-color: #fcfcfd;
+ border-color: #f2f4f7;
+ box-shadow: none;
+ cursor: default;
+}
+
+.indexItem.disabled:hover .radio {
+ @apply w-4 h-4 border-[2px] border-gray-200 rounded-full;
+}
+
+.radioItem {
+ @apply relative mb-2 rounded-xl border border-gray-100 cursor-pointer;
+ background-color: #fcfcfd;
+}
+
+.radioItem.segmentationItem.custom {
+ height: auto;
+}
+
+.radioItem.segmentationItem.custom .typeHeader {
+ /* height: 65px; */
+}
+
+.radioItem.indexItem .typeHeader {
+ @apply py-4 pr-5;
+}
+
+.radioItem.indexItem.active .typeHeader {
+ padding: 15.5px 19.5px 15.5px 63.5px;
+}
+
+.radioItem.indexItem .radio {
+ top: 16px;
+ right: 20px;
+}
+
+.radioItem.indexItem.active .radio {
+ top: 16px;
+ right: 19.5px;
+}
+
+.radioItem.indexItem .typeHeader .title {
+ @apply pb-1;
+}
+
+.radioItem.indexItem .typeHeader .tip {
+ @apply pb-3;
+}
+
+.radioItem .typeIcon {
+ position: absolute;
+ top: 18px;
+ left: 20px;
+ width: 32px;
+ height: 32px;
+ background: #EEF4FF center no-repeat;
+ border-radius: 8px;
+}
+
+.typeIcon.auto {
+ background-color: #F5F3FF;
+ background-image: url(../assets/zap-fast.svg);
+}
+
+.typeIcon.customize {
+ background-image: url(../assets/sliders-02.svg);
+}
+
+.typeIcon.qualified {
+ background-color: #FFF6ED;
+ background-image: url(../assets/star-07.svg);
+}
+
+.typeIcon.economical {
+ background-image: url(../assets/piggy-bank-01.svg);
+}
+
+.radioItem .radio {
+ @apply w-4 h-4 border-[2px] border-gray-200 rounded-full;
+ position: absolute;
+ top: 26px;
+ right: 20px;
+}
+
+.radioItem:hover {
+ background-color: #ffffff;
+ border-color: #B2CCFF;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
+
+.radioItem:hover .radio {
+ border-color: #155eef;
+}
+
+.radioItem.active {
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+.radioItem.active .radio {
+ top: 25.5px;
+ right: 19.5px;
+ border-width: 5px;
+ border-color: #155EEF;
+}
+
+.radioItem.active:hover {
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+.radioItem.active .typeIcon {
+ top: 17.5px;
+ left: 19.5px;
+}
+
+.radioItem.active .typeHeader {
+ padding: 11.5px 63.5px;
+}
+
+.typeHeader {
+ @apply flex flex-col px-16 py-3 justify-center;
+}
+
+.typeHeader .title {
+ display: flex;
+ align-items: center;
+ padding-bottom: 2px;
+ font-weight: 500;
+ font-size: 16px;
+ line-height: 24px;
+ color: #101828;
+}
+
+.typeHeader .tip {
+ font-weight: 400;
+ font-size: 13px;
+ line-height: 18px;
+ color: #667085;
+}
+
+.recommendTag {
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ padding: 0 6px;
+ margin-left: 4px;
+ border: 1px solid #E0EAFF;
+ border-radius: 6px;
+ font-weight: 500;
+ font-size: 12px;
+ line-height: 20px;
+ color: #444CE7;
+}
+
+.typeFormBody {
+ @apply px-16;
+ border-top: 1px solid #F2F4F7;
+}
+
+.formRow {
+ @apply flex justify-between mt-6;
+}
+
+.formRow .label {
+ @apply mb-2 p-0;
+ font-weight: 500;
+ font-size: 14px;
+ line-height: 20px;
+ color: #101828;
+}
+
+.ruleItem {
+ @apply flex items-center h-7;
+}
+
+.formFooter {
+ padding: 16px 0 28px;
+}
+
+.formFooter .button {
+ font-size: 13px;
+ line-height: 18px;
+}
+.input {
+ @apply inline-flex h-9 w-full py-1 px-2 rounded-lg text-xs leading-normal;
+ @apply bg-gray-100 caret-primary-600 hover:bg-gray-100 focus:ring-1 focus:ring-inset focus:ring-gray-200 focus-visible:outline-none focus:bg-white placeholder:text-gray-400;
+}
+
+.file {
+ @apply flex justify-between items-center mt-8 px-6 py-4 rounded-xl bg-gray-50;
+}
+
+.file .divider {
+ @apply shrink-0 mx-4 w-px bg-gray-200;
+ height: 42px;
+}
+
+.fileIcon {
+ @apply inline-flex mr-1 w-6 h-6 bg-center bg-no-repeat;
+ background-image: url(../assets/pdf.svg);
+ background-size: 24px;
+}
+
+.fileIcon.pdf {
+ background-image: url(../assets/pdf.svg);
+}
+
+.fileIcon.html,
+.fileIcon.htm {
+ background-image: url(../assets/html.svg);
+}
+
+.fileIcon.md,
+.fileIcon.markdown {
+ background-image: url(../assets/md.svg);
+}
+
+.fileIcon.txt {
+ background-image: url(../assets/txt.svg);
+}
+
+.fileIcon.json {
+ background-image: url(../assets/json.svg);
+}
+
+.fileContent {
+ flex: 1 1 50%;
+}
+
+.divider {
+ @apply mx-3 w-px h-4 bg-gray-200;
+}
+
+.calculating {
+ color: #98A2B3;
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.sideTip {
+ @apply flex flex-col items-center shrink-0;
+ padding-top: 108px;
+ width: 524px;
+ border-left: 0.5px solid #F2F4F7;
+}
+
+.tipCard {
+ @apply flex flex-col items-start p-6;
+ width: 320px;
+ background-color: #F9FAFB;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ border-radius: 12px;
+}
+
+.tipCard .icon {
+ width: 32px;
+ height: 32px;
+ border: 1px solid #EAECF0;
+ border-radius: 6px;
+ background: center no-repeat url(../assets/book-open-01.svg);
+ background-size: 16px;
+}
+
+.tipCard .title {
+ margin: 12px 0;
+ font-weight: 500;
+ font-size: 16px;
+ line-height: 24px;
+ color: #344054;
+}
+
+.tipCard .content {
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #344054;
+}
+
+.previewWrap {
+ flex-shrink: 0;
+ width: 524px;
+}
+
+.previewHeader {
+ position: sticky;
+ top: 0;
+ left: 0;
+ padding-top: 42px;
+ background-color: #fff;
+ font-weight: 600;
+ font-size: 18px;
+ line-height: 28px;
+ color: #101828;
+ z-index: 10;
+}
\ No newline at end of file
diff --git a/web/app/components/datasets/create/step-two/index.tsx b/web/app/components/datasets/create/step-two/index.tsx
new file mode 100644
index 00000000000..b13a8ad6566
--- /dev/null
+++ b/web/app/components/datasets/create/step-two/index.tsx
@@ -0,0 +1,491 @@
+'use client'
+import React, { useState, useRef, useEffect, useLayoutEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useBoolean } from 'ahooks'
+import type { File, PreProcessingRule, Rules, FileIndexingEstimateResponse as IndexingEstimateResponse } from '@/models/datasets'
+import {
+ fetchDefaultProcessRule,
+ createFirstDocument,
+ createDocument,
+ fetchFileIndexingEstimate as didFetchFileIndexingEstimate,
+} from '@/service/datasets'
+import type { CreateDocumentReq, createDocumentResponse } from '@/models/datasets'
+import Button from '@/app/components/base/button'
+import PreviewItem from './preview-item'
+import Loading from '@/app/components/base/loading'
+import { XMarkIcon } from '@heroicons/react/20/solid'
+
+import cn from 'classnames'
+import s from './index.module.css'
+import Link from 'next/link'
+import Toast from '@/app/components/base/toast'
+import { formatNumber } from '@/utils/format'
+
+type StepTwoProps = {
+ hasSetAPIKEY: boolean,
+ onSetting: () => void,
+ datasetId?: string,
+ indexingType?: string,
+ file?: File,
+ onStepChange: (delta: number) => void,
+ updateIndexingTypeCache: (type: string) => void,
+ updateResultCache: (res: createDocumentResponse) => void
+}
+
+enum SegmentType {
+ AUTO = 'automatic',
+ CUSTOM = 'custom',
+}
+enum IndexingType {
+ QUALIFIED = 'high_quality',
+ ECONOMICAL = 'economy',
+}
+
+const StepTwo = ({
+ hasSetAPIKEY,
+ onSetting,
+ datasetId,
+ indexingType,
+ file,
+ onStepChange,
+ updateIndexingTypeCache,
+ updateResultCache,
+}: StepTwoProps) => {
+ const { t } = useTranslation()
+ const scrollRef = useRef<HTMLDivElement>(null)
+ const [scrolled, setScrolled] = useState(false)
+ const previewScrollRef = useRef<HTMLDivElement>(null)
+ const [previewScrolled, setPreviewScrolled] = useState(false)
+ const [segmentationType, setSegmentationType] = useState<SegmentType>(SegmentType.AUTO)
+ const [segmentIdentifier, setSegmentIdentifier] = useState('\\n')
+ const [max, setMax] = useState(1000)
+ const [rules, setRules] = useState<PreProcessingRule[]>([])
+ const [defaultConfig, setDefaultConfig] = useState<Rules>()
+ const hasSetIndexType = !!indexingType
+ const [indexType, setIndexType] = useState<IndexingType>(
+ indexingType ||
+ hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL
+ )
+ const [showPreview, { setTrue: setShowPreview, setFalse: hidePreview }] = useBoolean()
+ const [customFileIndexingEstimate, setCustomFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
+ const [automaticFileIndexingEstimate, setAutomaticFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
+ const fileIndexingEstimate = (() => {
+ return segmentationType === SegmentType.AUTO ? automaticFileIndexingEstimate : customFileIndexingEstimate
+ })()
+
+ const scrollHandle = (e: any) => {
+ if (e.target.scrollTop > 0) {
+ setScrolled(true)
+ } else {
+ setScrolled(false)
+ }
+ }
+
+ const previewScrollHandle = (e: any) => {
+ if (e.target.scrollTop > 0) {
+ setPreviewScrolled(true)
+ } else {
+ setPreviewScrolled(false)
+ }
+ }
+ const getFileName = (name: string) => {
+ const arr = name.split('.')
+ return arr.slice(0, -1).join('.')
+ }
+
+ const getRuleName = (key: string) => {
+ if (key === 'remove_extra_spaces') {
+ return t('datasetCreation.stepTwo.removeExtraSpaces')
+ }
+ if (key === 'remove_urls_emails') {
+ return t('datasetCreation.stepTwo.removeUrlEmails')
+ }
+ if (key === 'remove_stopwords') {
+ return t('datasetCreation.stepTwo.removeStopwords')
+ }
+ }
+ const ruleChangeHandle = (id: string) => {
+ const newRules = rules.map(rule => {
+ if (rule.id === id) {
+ return {
+ id: rule.id,
+ enabled: !rule.enabled,
+ }
+ }
+ return rule
+ })
+ setRules(newRules)
+ }
+ const resetRules = () => {
+ if (defaultConfig) {
+ setSegmentIdentifier(defaultConfig.segmentation.separator === '\n' ? '\\n' : defaultConfig.segmentation.separator || '\\n')
+ setMax(defaultConfig.segmentation.max_tokens)
+ setRules(defaultConfig.pre_processing_rules)
+ }
+ }
+
+ const confirmChangeCustomConfig = async () => {
+ setCustomFileIndexingEstimate(null)
+ setShowPreview()
+ await fetchFileIndexingEstimate()
+ }
+
+ const getIndexing_technique = () => indexingType ? indexingType : indexType
+
+ const getProcessRule = () => {
+ const processRule: any = {
+ rules: {}, // api will check this. It will be removed after api refactored.
+ mode: segmentationType,
+ }
+ if (segmentationType === SegmentType.CUSTOM) {
+ const ruleObj = {
+ pre_processing_rules: rules,
+ segmentation: {
+ separator: segmentIdentifier === '\\n' ? '\n' : segmentIdentifier,
+ max_tokens: max,
+ },
+ }
+ processRule.rules = ruleObj
+ }
+ return processRule
+ }
+
+ const getFileIndexingEstimateParams = () => {
+ const params = {
+ file_id: file?.id,
+ dataset_id: datasetId,
+ indexing_technique: getIndexing_technique(),
+ process_rule: getProcessRule(),
+ }
+ return params
+ }
+
+ const fetchFileIndexingEstimate = async () => {
+ const res = await didFetchFileIndexingEstimate(getFileIndexingEstimateParams())
+ if (segmentationType === SegmentType.CUSTOM) {
+ setCustomFileIndexingEstimate(res)
+ }
+ else {
+ setAutomaticFileIndexingEstimate(res)
+ }
+ }
+
+ const getCreationParams = () => {
+ const params = {
+ data_source: {
+ type: 'upload_file',
+ info: file?.id,
+ name: file?.name,
+ },
+ indexing_technique: getIndexing_technique(),
+ process_rule: getProcessRule(),
+ } as CreateDocumentReq
+ return params
+ }
+
+ const getRules = async () => {
+ try {
+ const res = await fetchDefaultProcessRule({ url: '/datasets/process-rule' })
+ const separator = res.rules.segmentation.separator
+ setSegmentIdentifier(separator === '\n' ? '\\n' : separator || '\\n')
+ setMax(res.rules.segmentation.max_tokens)
+ setRules(res.rules.pre_processing_rules)
+ setDefaultConfig(res.rules)
+ }
+ catch (err) {
+ console.log(err)
+ }
+ }
+ const createHandle = async () => {
+ try {
+ let res;
+ const params = getCreationParams()
+ if (!datasetId) {
+ res = await createFirstDocument({
+ body: params
+ })
+ updateIndexingTypeCache(indexType)
+ updateResultCache(res)
+ } else {
+ res = await createDocument({
+ datasetId,
+ body: params
+ })
+ updateIndexingTypeCache(indexType)
+ updateResultCache({
+ document: res,
+ })
+ }
+ onStepChange(+1)
+ }
+ catch (err) {
+ Toast.notify({
+ type: 'error',
+ message: err + '',
+ })
+ }
+ }
+
+ useEffect(() => {
+ // fetch rules
+ getRules()
+ }, [])
+
+ useEffect(() => {
+ scrollRef.current?.addEventListener('scroll', scrollHandle);
+ return () => {
+ scrollRef.current?.removeEventListener('scroll', scrollHandle);
+ }
+ }, [])
+
+ useLayoutEffect(() => {
+ if (showPreview) {
+ previewScrollRef.current?.addEventListener('scroll', previewScrollHandle);
+ return () => {
+ previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle);
+ }
+ }
+ }, [showPreview])
+
+ useEffect(() => {
+ // get indexing type by props
+ if (indexingType) {
+ setIndexType(indexingType as IndexingType)
+ } else {
+ setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
+ }
+ }, [hasSetAPIKEY, indexingType, datasetId])
+
+ useEffect(() => {
+ if (segmentationType === SegmentType.AUTO) {
+ setAutomaticFileIndexingEstimate(null)
+ setShowPreview()
+ fetchFileIndexingEstimate()
+ } else {
+ hidePreview()
+ setCustomFileIndexingEstimate(null)
+ }
+ }, [segmentationType, indexType])
+
+ return (
+ <div className='flex w-full h-full'>
+ <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
+ <div className={cn(s.pageHeader, scrolled && s.fixed)}>{t('datasetCreation.steps.two')}</div>
+ <div className={cn(s.form)}>
+ <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
+ <div className='max-w-[640px]'>
+
+ <div
+ className={cn(
+ s.radioItem,
+ s.segmentationItem,
+ segmentationType === SegmentType.AUTO && s.active
+ )}
+ onClick={() => setSegmentationType(SegmentType.AUTO)}
+ >
+ <span className={cn(s.typeIcon, s.auto)} />
+ <span className={cn(s.radio)} />
+ <div className={s.typeHeader}>
+ <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
+ <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
+ </div>
+ </div>
+ <div
+ className={cn(
+ s.radioItem,
+ s.segmentationItem,
+ segmentationType === SegmentType.CUSTOM && s.active,
+ segmentationType === SegmentType.CUSTOM && s.custom,
+ )}
+ onClick={() => setSegmentationType(SegmentType.CUSTOM)}
+ >
+ <span className={cn(s.typeIcon, s.customize)} />
+ <span className={cn(s.radio)} />
+ <div className={s.typeHeader}>
+ <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
+ <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
+ </div>
+ {segmentationType === SegmentType.CUSTOM && (
+ <div className={s.typeFormBody}>
+ <div className={s.formRow}>
+ <div className='w-full'>
+ <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
+ <input
+ type="text"
+ className={s.input}
+ placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
+ onChange={(e) => setSegmentIdentifier(e.target.value)}
+ />
+ </div>
+ </div>
+ <div className={s.formRow}>
+ <div className='w-full'>
+ <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
+ <input
+ type="number"
+ className={s.input}
+ placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={max}
+ onChange={(e) => setMax(Number(e.target.value))}
+ />
+ </div>
+ </div>
+ <div className={s.formRow}>
+ <div className='w-full'>
+ <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
+ {rules.map(rule => (
+ <div key={rule.id} className={s.ruleItem}>
+ <input id={rule.id} type="checkbox" defaultChecked={rule.enabled} onChange={() => ruleChangeHandle(rule.id)} className="w-4 h-4 rounded border-gray-300 text-blue-700 focus:ring-blue-700" />
+ <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className={s.formFooter}>
+ <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
+ <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
+ <div className='max-w-[640px]'>
+ <div className='flex items-center gap-3'>
+ {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
+ <div
+ className={cn(
+ s.radioItem,
+ s.indexItem,
+ !hasSetAPIKEY && s.disabled,
+ !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
+ hasSetIndexType && s.disabled,
+ hasSetIndexType && '!w-full',
+ )}
+ onClick={() => {
+ if (hasSetAPIKEY) {
+ setIndexType(IndexingType.QUALIFIED)
+ }
+ }}
+ >
+ <span className={cn(s.typeIcon, s.qualified)} />
+ {!hasSetIndexType && <span className={cn(s.radio)} />}
+ <div className={s.typeHeader}>
+ <div className={s.title}>
+ {t('datasetCreation.stepTwo.qualified')}
+ {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
+ </div>
+ <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
+ <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
+ {
+ !!fileIndexingEstimate ? (
+ <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(fileIndexingEstimate.total_price)}</span>)</div>
+ ) : (
+ <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
+ )
+ }
+ </div>
+ {!hasSetAPIKEY && (
+ <div className={s.warningTip}>
+ <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
+ <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
+ </div>
+ )}
+ </div>
+ )}
+
+
+ {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
+ <div
+ className={cn(
+ s.radioItem,
+ s.indexItem,
+ !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
+ hasSetIndexType && s.disabled,
+ hasSetIndexType && '!w-full',
+ )}
+ onClick={() => !hasSetIndexType && setIndexType(IndexingType.ECONOMICAL)}
+ >
+ <span className={cn(s.typeIcon, s.economical)} />
+ {!hasSetIndexType && <span className={cn(s.radio)} />}
+ <div className={s.typeHeader}>
+ <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
+ <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
+ <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
+ <div className='text-xs font-medium text-gray-800'>0 tokens</div>
+ </div>
+ </div>
+ )}
+ </div>
+ {hasSetIndexType && (
+ <div className='mt-2 text-xs text-gray-500 font-medium'>
+ {t('datasetCreation.stepTwo.indexSettedTip')}
+ <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
+ </div>
+ )}
+ <div className={s.file}>
+ <div className={s.fileContent}>
+ <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileName')}</div>
+ <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
+ <span className={cn(s.fileIcon, file && s[file.extension])} />
+ {getFileName(file?.name || '')}
+ </div>
+ </div>
+ <div className={s.divider} />
+ <div className={s.fileContent}>
+ <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
+ <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
+ {
+ !!fileIndexingEstimate ? (
+ <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
+ ) : (
+ <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
+ )
+ }
+ </div>
+ </div>
+ </div>
+ <div className='flex items-center mt-8 py-2'>
+ <Button onClick={() => onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
+ <div className={s.divider} />
+ <Button type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ {(showPreview) ? (
+ <div ref={previewScrollRef} className={cn(s.previewWrap, 'relativeh-full overflow-y-scroll border-l border-[#F2F4F7]')}>
+ <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`, ' flex items-center justify-between px-8')}>
+ <span>{t('datasetCreation.stepTwo.previewTitle')}</span>
+ <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
+ <XMarkIcon className='h-4 w-4'></XMarkIcon>
+ </div>
+ </div>
+ <div className='my-4 px-8 space-y-4'>
+ {fileIndexingEstimate?.preview ? (
+ <>
+ {fileIndexingEstimate?.preview.map((item, index) => (
+ <PreviewItem key={item} content={item} index={index + 1} />
+ ))}
+ </>
+ ) : <div className='flex items-center justify-center h-[200px]'><Loading type='area'></Loading></div>
+ }
+ </div>
+ </div>
+ ) :
+ (<div className={cn(s.sideTip)}>
+ <div className={s.tipCard}>
+ <span className={s.icon} />
+ <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
+ <div className={s.content}>
+ <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
+ <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
+ <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
+ <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
+ </div>
+ </div>
+ </div>)}
+ </div>
+ )
+}
+
+export default StepTwo
diff --git a/web/app/components/datasets/create/step-two/preview-item/index.tsx b/web/app/components/datasets/create/step-two/preview-item/index.tsx
new file mode 100644
index 00000000000..4108ef4807c
--- /dev/null
+++ b/web/app/components/datasets/create/step-two/preview-item/index.tsx
@@ -0,0 +1,49 @@
+'use client'
+import React, { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export interface IPreviewItemProps {
+ index: number
+ content: string
+}
+
+const sharpIcon = (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M4.74999 1.5L3.24999 10.5M8.74998 1.5L7.24998 10.5M10.25 4H1.75M9.75 8H1.25" stroke="#98A2B3" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+)
+
+const textIcon = (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M4 3.5H8M6 3.5V8.5M3.9 10.5H8.1C8.94008 10.5 9.36012 10.5 9.68099 10.3365C9.96323 10.1927 10.1927 9.96323 10.3365 9.68099C10.5 9.36012 10.5 8.94008 10.5 8.1V3.9C10.5 3.05992 10.5 2.63988 10.3365 2.31901C10.1927 2.03677 9.96323 1.8073 9.68099 1.66349C9.36012 1.5 8.94008 1.5 8.1 1.5H3.9C3.05992 1.5 2.63988 1.5 2.31901 1.66349C2.03677 1.8073 1.8073 2.03677 1.66349 2.31901C1.5 2.63988 1.5 3.05992 1.5 3.9V8.1C1.5 8.94008 1.5 9.36012 1.66349 9.68099C1.8073 9.96323 2.03677 10.1927 2.31901 10.3365C2.63988 10.5 3.05992 10.5 3.9 10.5Z" stroke="#667085" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+
+)
+
+const PreviewItem: FC<IPreviewItemProps> = ({
+ index,
+ content,
+}) => {
+ const { t } = useTranslation()
+ const charNums = (content || '').length
+ const formatedIndex = (() => (index + '').padStart(3, '0'))()
+
+ return (
+ <div className='p-4 rounded-xl bg-gray-50'>
+ <div className='flex items-center justify-between h-5 text-xs text-gray-500'>
+ <div className='flex items-center h-[18px] space-x-1 border border-gray-200 box-border rounded-md italic pl-1 pr-1.5 font-medium'>
+ {sharpIcon}
+ <span>{formatedIndex}</span>
+ </div>
+ <div className='flex items-center space-x-1'>
+ {textIcon}
+ <span>{charNums} {t('datasetCreation.stepTwo.characters')}</span>
+ </div>
+ </div>
+ <div className='mt-2 max-h-[120px] line-clamp-6 overflow-hidden text-sm text-gray-800'>
+ {content}
+ </div>
+ </div>
+ )
+}
+export default React.memo(PreviewItem)
diff --git a/web/app/components/datasets/create/steps-nav-bar/index.module.css b/web/app/components/datasets/create/steps-nav-bar/index.module.css
new file mode 100644
index 00000000000..b1d15988ab4
--- /dev/null
+++ b/web/app/components/datasets/create/steps-nav-bar/index.module.css
@@ -0,0 +1,106 @@
+.stepsHeader {
+ @apply flex items-center px-6 py-6;
+ color: #344054;
+ font-weight: 600;
+ font-size: 14px;
+ line-height: 20px;
+}
+.navBack {
+ @apply box-border flex justify-center items-center mr-3 w-8 h-8 bg-white bg-center bg-no-repeat cursor-pointer hover:border-gray-300;
+ border: 0.5px solid #F2F4F7;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+ border-radius: 32px;
+ background-image: url(../assets/arrow-narrow-left.svg);
+ background-size: 16px;
+}
+.stepList {
+ @apply p-4;
+ line-height: 18px;
+}
+
+.stepItem {
+ @apply relative flex justify-items-start pt-3 pr-0 pb-3;
+ padding-left: 52px;
+ font-size: 13px;
+}
+
+.stepItem.step1::before {
+ content: '';
+ position: absolute;
+ bottom: 0;
+ left: 23px;
+ width: 2px;
+ height: 7px;
+ background-color: #f2f4f7;
+}
+
+.stepItem.step2::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 23px;
+ width: 2px;
+ height: 100%;
+ background-color: #f2f4f7;
+}
+.stepItem.step2::after {
+ content: '';
+ position: absolute;
+ top: 6px;
+ left: 23px;
+ width: 2px;
+ height: 28px;
+ background-color: #fff;
+}
+
+.stepItem.step3::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 23px;
+ width: 2px;
+ height: 7px;
+ background-color: #f2f4f7;
+}
+
+.stepNum {
+ @apply box-border absolute top-2 left-3 flex justify-center items-center w-6 h-6;
+ color: #98a2b3;
+ font-size: 12px;
+ border: 1px solid #F2F4F7;
+ border-radius: 24px;
+ z-index: 1;
+}
+
+.stepName {
+ color: #98a2b3;
+}
+
+.stepItem.active .stepNum {
+ color: #1c64f2;
+ background-color: #EFF4FF;
+ border: none;
+}
+
+.stepItem.active .stepName {
+ color: #1c64f2;
+}
+
+.stepItem.done .stepNum {
+ color: #667085;
+ background-color: #f2f4f7;
+ border: none;
+}
+
+.stepItem.done .stepNum::after {
+ content: '';
+ display: flex;
+ width: 12px;
+ height: 12px;
+ background: center no-repeat url(../assets/check.svg);
+ background-size: 12px;
+}
+
+.stepItem.done .stepName {
+ color: #667085;
+}
diff --git a/web/app/components/datasets/create/steps-nav-bar/index.tsx b/web/app/components/datasets/create/steps-nav-bar/index.tsx
new file mode 100644
index 00000000000..53b81b033ce
--- /dev/null
+++ b/web/app/components/datasets/create/steps-nav-bar/index.tsx
@@ -0,0 +1,51 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { useRouter } from 'next/navigation'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IStepsNavBarProps = {
+ step: number,
+ datasetId?: string,
+}
+
+const StepsNavBar = ({
+ step,
+ datasetId,
+}: IStepsNavBarProps) => {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const navBackHandle = () => {
+ if (!datasetId) {
+ router.replace('/datasets')
+ } else {
+ router.replace(`/datasets/${datasetId}/documents`)
+ }
+ }
+
+ return (
+ <div className='w-full pt-4'>
+ <div className={s.stepsHeader}>
+ <div onClick={navBackHandle} className={s.navBack} />
+ {!datasetId ? t('datasetCreation.steps.header.creation') : t('datasetCreation.steps.header.update')}
+ </div>
+ <div className={cn(s.stepList)}>
+ <div className={cn(s.stepItem, s.step1, step === 1 && s.active, step !== 1 && s.done)}>
+ <div className={cn(s.stepNum)}>{step === 1 ? 1 : ''}</div>
+ <div className={cn(s.stepName)}>{t('datasetCreation.steps.one')}</div>
+ </div>
+ <div className={cn(s.stepItem, s.step2, step === 2 && s.active, step === 3 && s.done)}>
+ <div className={cn(s.stepNum)}>{step !== 3 ? 2 : ''}</div>
+ <div className={cn(s.stepName)}>{t('datasetCreation.steps.two')}</div>
+ </div>
+ <div className={cn(s.stepItem, s.step3, step === 3 && s.active)}>
+ <div className={cn(s.stepNum)}>3</div>
+ <div className={cn(s.stepName)}>{t('datasetCreation.steps.three')}</div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default StepsNavBar
diff --git a/web/app/components/datasets/create/stop-embedding-modal/index.module.css b/web/app/components/datasets/create/stop-embedding-modal/index.module.css
new file mode 100644
index 00000000000..95f999d60a1
--- /dev/null
+++ b/web/app/components/datasets/create/stop-embedding-modal/index.module.css
@@ -0,0 +1,37 @@
+.modal {
+ position: relative;
+}
+.modal .icon {
+ width: 48px;
+ height: 48px;
+ background: rgba(255, 255, 255, 0.9) center no-repeat url(../assets/annotation-info.svg);
+ background-size: 24px;
+ border: 0.5px solid #F2F4F7;
+ box-shadow: 0px 20px 24px -4px rgba(16, 24, 40, 0.08), 0px 8px 8px -4px rgba(16, 24, 40, 0.03);
+ border-radius: 12px;
+}
+.modal .close {
+ position: absolute;
+ right: 16px;
+ top: 16px;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ background: center no-repeat url(../assets/close.svg);
+ background-size: 16px;
+ cursor: pointer;
+}
+.modal .title {
+ @apply mt-3 mb-1;
+ font-weight: 600;
+ font-size: 20px;
+ line-height: 30px;
+ color: #101828;
+}
+.modal .content {
+ @apply mb-10;
+ font-weight: 400;
+ font-size: 14px;
+ line-height: 20px;
+ color: #667085;
+}
diff --git a/web/app/components/datasets/create/stop-embedding-modal/index.tsx b/web/app/components/datasets/create/stop-embedding-modal/index.tsx
new file mode 100644
index 00000000000..434ed5e6699
--- /dev/null
+++ b/web/app/components/datasets/create/stop-embedding-modal/index.tsx
@@ -0,0 +1,46 @@
+'use client'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+
+import cn from 'classnames'
+import s from './index.module.css'
+
+type IProps = {
+ show: boolean,
+ onConfirm: () => void,
+ onHide: () => void,
+}
+
+const StopEmbeddingModal = ({
+ show = false,
+ onConfirm,
+ onHide,
+}: IProps) => {
+ const { t } = useTranslation()
+
+ const submit = () => {
+ onConfirm()
+ onHide()
+ }
+
+ return (
+ <Modal
+ isShow={show}
+ onClose={onHide}
+ className={cn(s.modal, '!max-w-[480px]', 'px-8')}
+ >
+ <div className={s.icon}/>
+ <span className={s.close} onClick={onHide}/>
+ <div className={s.title}>{t('datasetCreation.stepThree.modelTitle')}</div>
+ <div className={s.content}>{t('datasetCreation.stepThree.modelContent')}</div>
+ <div className='flex flex-row-reverse'>
+ <Button className='w-24 ml-2' type='primary' onClick={submit}>{t('datasetCreation.stepThree.modelButtonConfirm')}</Button>
+ <Button className='w-24' onClick={onHide}>{t('datasetCreation.stepThree.modelButtonCancel')}</Button>
+ </div>
+ </Modal>
+ )
+}
+
+export default StopEmbeddingModal
diff --git a/web/app/components/datasets/documents/assets/action.svg b/web/app/components/datasets/documents/assets/action.svg
new file mode 100644
index 00000000000..ae3f48e2edd
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/action.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M6.66667 8.00008C6.66667 7.2637 7.26362 6.66675 8 6.66675C8.73638 6.66675 9.33333 7.2637 9.33333 8.00008C9.33333 8.73646 8.73638 9.33341 8 9.33341C7.26362 9.33341 6.66667 8.73646 6.66667 8.00008Z" fill="#667085" />
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M11.3333 8.00008C11.3333 7.2637 11.9303 6.66675 12.6667 6.66675C13.403 6.66675 14 7.2637 14 8.00008C14 8.73646 13.403 9.33341 12.6667 9.33341C11.9303 9.33341 11.3333 8.73646 11.3333 8.00008Z" fill="#667085" />
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M2 8.00008C2 7.2637 2.59695 6.66675 3.33333 6.66675C4.06971 6.66675 4.66667 7.2637 4.66667 8.00008C4.66667 8.73646 4.06971 9.33341 3.33333 9.33341C2.59695 9.33341 2 8.73646 2 8.00008Z" fill="#667085" />
+ </svg>
diff --git a/web/app/components/datasets/documents/assets/atSign.svg b/web/app/components/datasets/documents/assets/atSign.svg
new file mode 100644
index 00000000000..49bf6061e32
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/atSign.svg
@@ -0,0 +1,10 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2427_26665)">
+<path d="M10.6668 5.33333V8.66666C10.6668 9.19709 10.8776 9.7058 11.2526 10.0809C11.6277 10.4559 12.1364 10.6667 12.6668 10.6667C13.1973 10.6667 13.706 10.4559 14.0811 10.0809C14.4561 9.7058 14.6668 9.19709 14.6668 8.66666V7.99999C14.6667 6.49535 14.1577 5.03498 13.2224 3.85635C12.287 2.67772 10.9805 1.85014 9.51526 1.50819C8.04999 1.16624 6.51213 1.33002 5.15173 1.9729C3.79134 2.61579 2.68843 3.69996 2.02234 5.04914C1.35625 6.39832 1.16615 7.93315 1.48295 9.40407C1.79975 10.875 2.60482 12.1955 3.76726 13.1508C4.92969 14.1062 6.38112 14.6402 7.88555 14.6661C9.38997 14.692 10.8589 14.2082 12.0535 13.2933M10.6668 7.99999C10.6668 9.47275 9.47293 10.6667 8.00017 10.6667C6.52741 10.6667 5.3335 9.47275 5.3335 7.99999C5.3335 6.52723 6.52741 5.33333 8.00017 5.33333C9.47293 5.33333 10.6668 6.52723 10.6668 7.99999Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<clipPath id="clip0_2427_26665">
+<rect width="16" height="16" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/bezierCurve.svg b/web/app/components/datasets/documents/assets/bezierCurve.svg
new file mode 100644
index 00000000000..f2d1a3bf0d2
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/bezierCurve.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5.42857 3.5L2.57143 8.5M3 9.5H8.9999M9.42857 8.5L6.57143 3.5M1.8 10.5H2.2C2.48003 10.5 2.62004 10.5 2.727 10.4455C2.82108 10.3976 2.89757 10.3211 2.9455 10.227C3 10.12 3 9.98003 3 9.7V9.3C3 9.01997 3 8.87996 2.9455 8.773C2.89757 8.67892 2.82108 8.60243 2.727 8.5545C2.62004 8.5 2.48003 8.5 2.2 8.5H1.8C1.51997 8.5 1.37996 8.5 1.273 8.5545C1.17892 8.60243 1.10243 8.67892 1.0545 8.773C1 8.87996 1 9.01997 1 9.3V9.7C1 9.98003 1 10.12 1.0545 10.227C1.10243 10.3211 1.17892 10.3976 1.273 10.4455C1.37996 10.5 1.51997 10.5 1.8 10.5ZM9.8 10.5H10.2C10.48 10.5 10.62 10.5 10.727 10.4455C10.8211 10.3976 10.8976 10.3211 10.9455 10.227C11 10.12 11 9.98003 11 9.7V9.3C11 9.01997 11 8.87996 10.9455 8.773C10.8976 8.67892 10.8211 8.60243 10.727 8.5545C10.62 8.5 10.48 8.5 10.2 8.5H9.8C9.51997 8.5 9.37996 8.5 9.273 8.5545C9.17892 8.60243 9.10243 8.67892 9.0545 8.773C9 8.87996 9 9.01997 9 9.3V9.7C9 9.98003 9 10.12 9.0545 10.227C9.10243 10.3211 9.17892 10.3976 9.273 10.4455C9.37996 10.5 9.51997 10.5 9.8 10.5ZM5.8 3.5H6.2C6.48003 3.5 6.62004 3.5 6.727 3.4455C6.82108 3.39757 6.89757 3.32108 6.9455 3.227C7 3.12004 7 2.98003 7 2.7V2.3C7 2.01997 7 1.87996 6.9455 1.773C6.89757 1.67892 6.82108 1.60243 6.727 1.5545C6.62004 1.5 6.48003 1.5 6.2 1.5H5.8C5.51997 1.5 5.37996 1.5 5.273 1.5545C5.17892 1.60243 5.10243 1.67892 5.0545 1.773C5 1.87996 5 2.01997 5 2.3V2.7C5 2.98003 5 3.12004 5.0545 3.227C5.10243 3.32108 5.17892 3.39757 5.273 3.4455C5.37996 3.5 5.51997 3.5 5.8 3.5Z" stroke="#667085" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
diff --git a/web/app/components/datasets/documents/assets/bookOpen.svg b/web/app/components/datasets/documents/assets/bookOpen.svg
new file mode 100644
index 00000000000..04a38fba056
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/bookOpen.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M8.00016 14L7.93346 13.8999C7.47037 13.2053 7.23882 12.858 6.9329 12.6065C6.66207 12.3839 6.35001 12.2169 6.01457 12.1151C5.63566 12 5.21823 12 4.38338 12H3.46683C2.72009 12 2.34672 12 2.06151 11.8547C1.81063 11.7268 1.60665 11.5229 1.47882 11.272C1.3335 10.9868 1.3335 10.6134 1.3335 9.86667V4.13333C1.3335 3.3866 1.3335 3.01323 1.47882 2.72801C1.60665 2.47713 1.81063 2.27316 2.06151 2.14532C2.34672 2 2.72009 2 3.46683 2H3.7335C5.22697 2 5.97371 2 6.54414 2.29065C7.0459 2.54631 7.45385 2.95426 7.70951 3.45603C8.00016 4.02646 8.00016 4.77319 8.00016 6.26667M8.00016 14V6.26667M8.00016 14L8.06687 13.8999C8.52996 13.2053 8.76151 12.858 9.06743 12.6065C9.33826 12.3839 9.65032 12.2169 9.98576 12.1151C10.3647 12 10.7821 12 11.6169 12H12.5335C13.2802 12 13.6536 12 13.9388 11.8547C14.1897 11.7268 14.3937 11.5229 14.5215 11.272C14.6668 10.9868 14.6668 10.6134 14.6668 9.86667V4.13333C14.6668 3.3866 14.6668 3.01323 14.5215 2.72801C14.3937 2.47713 14.1897 2.27316 13.9388 2.14532C13.6536 2 13.2802 2 12.5335 2H12.2668C10.7734 2 10.0266 2 9.45619 2.29065C8.95442 2.54631 8.54647 2.95426 8.29081 3.45603C8.00016 4.02646 8.00016 4.77319 8.00016 6.26667" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/briefcase.svg b/web/app/components/datasets/documents/assets/briefcase.svg
new file mode 100644
index 00000000000..7ec1aa48bcb
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/briefcase.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.3335 14V4.66667C5.3335 4.04669 5.3335 3.7367 5.40164 3.48236C5.58658 2.79218 6.12567 2.25308 6.81586 2.06815C7.07019 2 7.38018 2 8.00016 2C8.62014 2 8.93013 2 9.18447 2.06815C9.87465 2.25308 10.4137 2.79218 10.5987 3.48236C10.6668 3.7367 10.6668 4.04669 10.6668 4.66667V14M3.46683 14H12.5335C13.2802 14 13.6536 14 13.9388 13.8547C14.1897 13.7268 14.3937 13.5229 14.5215 13.272C14.6668 12.9868 14.6668 12.6134 14.6668 11.8667V6.8C14.6668 6.05326 14.6668 5.6799 14.5215 5.39468C14.3937 5.1438 14.1897 4.93982 13.9388 4.81199C13.6536 4.66667 13.2802 4.66667 12.5335 4.66667H3.46683C2.72009 4.66667 2.34672 4.66667 2.06151 4.81199C1.81063 4.93982 1.60665 5.1438 1.47882 5.39468C1.3335 5.6799 1.3335 6.05326 1.3335 6.8V11.8667C1.3335 12.6134 1.3335 12.9868 1.47882 13.272C1.60665 13.5229 1.81063 13.7268 2.06151 13.8547C2.34672 14 2.72009 14 3.46683 14Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/cardLoading.svg b/web/app/components/datasets/documents/assets/cardLoading.svg
new file mode 100644
index 00000000000..76ba4d7d875
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/cardLoading.svg
@@ -0,0 +1,15 @@
+<svg width="232" height="120" viewBox="0 0 232 120" preserveAspectRatio="none" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect y="6" width="232" height="8" rx="3" fill="#EAECF0"/>
+<rect y="26" width="232" height="8" rx="3" fill="#EAECF0"/>
+<rect y="46" width="232" height="8" rx="3" fill="#EAECF0"/>
+<rect y="66" width="232" height="8" rx="3" fill="#EAECF0"/>
+<rect y="86" width="232" height="8" rx="3" fill="#EAECF0"/>
+<g clip-path="url(#clip0_2368_22256)">
+<rect y="106" width="256" height="8" rx="3" fill="#EAECF0"/>
+</g>
+<defs>
+<clipPath id="clip0_2368_22256">
+<rect width="232" height="20" fill="white" transform="translate(0 100)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/file.svg b/web/app/components/datasets/documents/assets/file.svg
new file mode 100644
index 00000000000..32fb8051ec2
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/file.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M9.33317 1.51306V4.26676C9.33317 4.64012 9.33317 4.82681 9.40583 4.96942C9.46975 5.09486 9.57173 5.19684 9.69718 5.26076C9.83978 5.33342 10.0265 5.33342 10.3998 5.33342H13.1535M10.6665 8.66671H5.33317M10.6665 11.3334H5.33317M6.6665 6.00004H5.33317M9.33317 1.33337H5.8665C4.7464 1.33337 4.18635 1.33337 3.75852 1.55136C3.3822 1.74311 3.07624 2.04907 2.88449 2.42539C2.6665 2.85322 2.6665 3.41327 2.6665 4.53337V11.4667C2.6665 12.5868 2.6665 13.1469 2.88449 13.5747C3.07624 13.951 3.3822 14.257 3.75852 14.4487C4.18635 14.6667 4.7464 14.6667 5.8665 14.6667H10.1332C11.2533 14.6667 11.8133 14.6667 12.2412 14.4487C12.6175 14.257 12.9234 13.951 13.1152 13.5747C13.3332 13.1469 13.3332 12.5868 13.3332 11.4667V5.33337L9.33317 1.33337Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/globe.svg b/web/app/components/datasets/documents/assets/globe.svg
new file mode 100644
index 00000000000..457c9242219
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/globe.svg
@@ -0,0 +1,10 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_2427_26661)">
+<path d="M1.79133 10.4301L3.06346 9.69574C3.13237 9.65596 3.21323 9.64214 3.29143 9.65678L5.79443 10.1252C6.00013 10.1637 6.19001 10.0054 6.18908 9.7961L6.17934 7.60301C6.17907 7.54342 6.19478 7.48486 6.22484 7.43341L7.48799 5.27085C7.55373 5.1583 7.54784 5.01776 7.47291 4.91111L5.34611 1.88383M12.667 3.23941C9.0003 5.00007 11.0002 7.3334 11.667 7.66674C12.9184 8.29232 14.6586 8.33337 14.6586 8.33337C14.664 8.22294 14.6668 8.11182 14.6668 8.00004C14.6668 4.31814 11.6821 1.33337 8.00016 1.33337C4.31826 1.33337 1.3335 4.31814 1.3335 8.00004C1.3335 11.6819 4.31826 14.6667 8.00016 14.6667C8.11194 14.6667 8.22307 14.664 8.3335 14.6585M11.172 14.6266L9.06083 9.06071L14.6267 11.1719L12.1586 12.1585L11.172 14.6266Z" stroke="#155EEF" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<clipPath id="clip0_2427_26661">
+<rect width="16" height="16" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/graduationHat.svg b/web/app/components/datasets/documents/assets/graduationHat.svg
new file mode 100644
index 00000000000..405a377be06
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/graduationHat.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M11.3335 9.66667V7.66295C11.3335 7.5433 11.3335 7.48348 11.3153 7.43066C11.2992 7.38395 11.2729 7.34141 11.2383 7.30611C11.1992 7.26619 11.1457 7.23944 11.0387 7.18593L8.00016 5.66667M2.66683 6.33334V10.8711C2.66683 11.119 2.66683 11.243 2.70551 11.3515C2.7397 11.4475 2.79543 11.5343 2.86842 11.6054C2.95097 11.6858 3.06368 11.7374 3.28906 11.8408L7.55573 13.7963C7.71922 13.8712 7.80097 13.9087 7.88612 13.9235C7.96159 13.9366 8.03874 13.9366 8.1142 13.9235C8.19936 13.9087 8.28111 13.8712 8.44459 13.7963L12.7113 11.8408C12.9367 11.7374 13.0494 11.6858 13.1319 11.6054C13.2049 11.5343 13.2606 11.4475 13.2948 11.3515C13.3335 11.243 13.3335 11.119 13.3335 10.8711V6.33334M1.3335 5.66667L7.76165 2.45259C7.8491 2.40887 7.89283 2.387 7.9387 2.3784C7.97932 2.37078 8.02101 2.37078 8.06163 2.3784C8.1075 2.387 8.15122 2.40887 8.23868 2.45259L14.6668 5.66667L8.23868 8.88075C8.15122 8.92447 8.1075 8.94634 8.06163 8.95494C8.02101 8.96256 7.97932 8.96256 7.9387 8.95494C7.89283 8.94634 7.8491 8.92447 7.76165 8.88075L1.3335 5.66667Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/hitLoading.svg b/web/app/components/datasets/documents/assets/hitLoading.svg
new file mode 100644
index 00000000000..713b6a2b727
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/hitLoading.svg
@@ -0,0 +1,15 @@
+<svg width="252" height="120" viewBox="0 0 252 120" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect y="6" width="252" height="8" rx="3" fill="#EAECF0"/>
+<rect y="26" width="252" height="8" rx="3" fill="#EAECF0"/>
+<rect y="46" width="252" height="8" rx="3" fill="#EAECF0"/>
+<rect y="66" width="252" height="8" rx="3" fill="#EAECF0"/>
+<rect y="86" width="252" height="8" rx="3" fill="#EAECF0"/>
+<g clip-path="url(#clip0_1562_6752)">
+<rect y="106" width="256" height="8" rx="3" fill="#EAECF0"/>
+</g>
+<defs>
+<clipPath id="clip0_1562_6752">
+<rect width="252" height="20" fill="white" transform="translate(0 100)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/html.svg b/web/app/components/datasets/documents/assets/html.svg
new file mode 100644
index 00000000000..023ad9e8b81
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/html.svg
@@ -0,0 +1,23 @@
+<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3434_4797)">
+<path d="M2.75 4.38325C2.75 3.40316 2.75 2.91311 2.94074 2.53877C3.10852 2.20948 3.37623 1.94177 3.70552 1.77399C4.07986 1.58325 4.56991 1.58325 5.55 1.58325H9.16667L13.25 5.66659V11.6166C13.25 12.5967 13.25 13.0867 13.0593 13.4611C12.8915 13.7904 12.6238 14.0581 12.2945 14.2258C11.9201 14.4166 11.4301 14.4166 10.45 14.4166H5.55C4.56991 14.4166 4.07986 14.4166 3.70552 14.2258C3.37623 14.0581 3.10852 13.7904 2.94074 13.4611C2.75 13.0867 2.75 12.5967 2.75 11.6166V4.38325Z" fill="#EC5B27"/>
+</g>
+<g opacity="0.96">
+<path d="M5.49319 11.5001V9.00806H4.88069V9.96706H4.22969V9.00806H3.61719V11.5001H4.22969V10.5131H4.88069V11.5001H5.49319Z" fill="white"/>
+<path d="M7.68659 9.55406V9.00806H5.84909V9.55406H6.46159V11.5001H7.07409V9.55406H7.68659Z" fill="white"/>
+<path d="M10.3675 11.5001V9.00806H9.76546L9.20546 10.1071L8.64546 9.00806H8.04346V11.5001H8.65596V10.3066L9.00946 10.9226H9.40146L9.75496 10.3066V11.5001H10.3675Z" fill="white"/>
+<path d="M12.5291 11.5001V10.9541H11.4826V9.00806H10.8701V11.5001H12.5291Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M9.1665 1.58325L13.2498 5.66658H10.3332C9.68884 5.66658 9.1665 5.14425 9.1665 4.49992V1.58325Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3434_4797" x="0.75" y="0.583252" width="14.5" height="16.8333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3434_4797"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3434_4797" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/json.svg b/web/app/components/datasets/documents/assets/json.svg
new file mode 100644
index 00000000000..98316f84d54
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/json.svg
@@ -0,0 +1,23 @@
+<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3434_2726)">
+<path d="M2.75 4.38325C2.75 3.40316 2.75 2.91311 2.94074 2.53877C3.10852 2.20948 3.37623 1.94177 3.70552 1.77399C4.07986 1.58325 4.56991 1.58325 5.55 1.58325H9.16667L13.25 5.66659V11.6166C13.25 12.5967 13.25 13.0867 13.0593 13.4611C12.8915 13.7904 12.6238 14.0581 12.2945 14.2258C11.9201 14.4166 11.4301 14.4166 10.45 14.4166H5.55C4.56991 14.4166 4.07986 14.4166 3.70552 14.2258C3.37623 14.0581 3.10852 13.7904 2.94074 13.4611C2.75 13.0867 2.75 12.5967 2.75 11.6166V4.38325Z" fill="#2D2D2E"/>
+</g>
+<g opacity="0.96">
+<path d="M5.3045 10.6461V9.00806H4.692V10.6321C4.692 10.8701 4.5555 10.9751 4.3665 10.9751C4.23 10.9751 4.167 10.9261 4.09 10.8491L3.6875 11.2481C3.8905 11.4511 4.076 11.5211 4.3665 11.5211C4.8355 11.5211 5.3045 11.2376 5.3045 10.6461Z" fill="white"/>
+<path d="M7.44519 10.7371C7.44519 10.5061 7.39269 10.3206 7.25969 10.1911C7.15469 10.0861 6.99369 10.0161 6.76969 9.98456L6.46869 9.94256C6.38119 9.93206 6.32869 9.90056 6.29719 9.86906C6.25869 9.83056 6.24819 9.78506 6.24819 9.75356C6.24819 9.64506 6.33569 9.52256 6.54919 9.52256C6.65769 9.52256 6.86419 9.51206 7.02169 9.66956L7.40669 9.28456C7.19319 9.07106 6.92369 8.98706 6.56669 8.98706C5.99969 8.98706 5.65669 9.31956 5.65669 9.77456C5.65669 9.98806 5.71269 10.1561 5.82819 10.2751C5.94019 10.3906 6.10819 10.4641 6.32869 10.4956L6.62969 10.5376C6.71019 10.5481 6.76269 10.5726 6.79419 10.6041C6.82919 10.6426 6.84319 10.6916 6.84319 10.7511C6.84319 10.8946 6.72769 10.9751 6.48619 10.9751C6.28669 10.9751 6.05919 10.9296 5.92969 10.8001L5.53769 11.1921C5.78969 11.4511 6.10119 11.5211 6.48269 11.5211C7.00769 11.5211 7.44519 11.2446 7.44519 10.7371Z" fill="white"/>
+<path d="M9.66339 10.2541C9.66339 9.87956 9.67389 9.52956 9.41139 9.26706C9.22939 9.08506 9.01939 8.98706 8.71489 8.98706C8.41039 8.98706 8.20039 9.08506 8.01839 9.26706C7.75589 9.52956 7.76639 9.87956 7.76639 10.2541C7.76639 10.6286 7.75589 10.9786 8.01839 11.2411C8.20039 11.4231 8.41039 11.5211 8.71489 11.5211C9.01939 11.5211 9.22939 11.4231 9.41139 11.2411C9.67389 10.9786 9.66339 10.6286 9.66339 10.2541ZM9.05089 10.2541C9.05089 10.7091 9.01589 10.7896 8.95989 10.8631C8.91439 10.9226 8.82689 10.9751 8.71489 10.9751C8.60289 10.9751 8.51539 10.9226 8.46989 10.8631C8.41389 10.7896 8.37889 10.7091 8.37889 10.2541C8.37889 9.79906 8.41389 9.71506 8.46989 9.64156C8.51539 9.58206 8.60289 9.53306 8.71489 9.53306C8.82689 9.53306 8.91439 9.58206 8.95989 9.64156C9.01589 9.71506 9.05089 9.79906 9.05089 10.2541Z" fill="white"/>
+<path d="M12.0317 11.5001V9.00806H11.4192V10.2611L10.6212 9.00806H10.0857V11.5001H10.6982V10.2471L11.4962 11.5001H12.0317Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M9.1665 1.58325L13.2498 5.66658H10.3332C9.68884 5.66658 9.1665 5.14425 9.1665 4.49992V1.58325Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3434_2726" x="0.75" y="0.583252" width="14.5" height="16.8333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3434_2726"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3434_2726" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/layoutRightClose.svg b/web/app/components/datasets/documents/assets/layoutRightClose.svg
new file mode 100644
index 00000000000..b247d1006af
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/layoutRightClose.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.12" d="M10 2H10.8C11.9201 2 12.4802 2 12.908 2.21799C13.2843 2.40973 13.5903 2.71569 13.782 3.09202C14 3.51984 14 4.0799 14 5.2V10.8C14 11.9201 14 12.4802 13.782 12.908C13.5903 13.2843 13.2843 13.5903 12.908 13.782C12.4802 14 11.9201 14 10.8 14H10V2Z" fill="#344054"/>
+<path d="M10 2V14M5.2 2H10.8C11.9201 2 12.4802 2 12.908 2.21799C13.2843 2.40973 13.5903 2.71569 13.782 3.09202C14 3.51984 14 4.0799 14 5.2V10.8C14 11.9201 14 12.4802 13.782 12.908C13.5903 13.2843 13.2843 13.5903 12.908 13.782C12.4802 14 11.9201 14 10.8 14H5.2C4.07989 14 3.51984 14 3.09202 13.782C2.71569 13.5903 2.40973 13.2843 2.21799 12.908C2 12.4802 2 11.9201 2 10.8V5.2C2 4.07989 2 3.51984 2.21799 3.09202C2.40973 2.71569 2.71569 2.40973 3.09202 2.21799C3.51984 2 4.0799 2 5.2 2Z" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/layoutRightShow.svg b/web/app/components/datasets/documents/assets/layoutRightShow.svg
new file mode 100644
index 00000000000..889e4698c1f
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/layoutRightShow.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.12" d="M10 2H10.8C11.9201 2 12.4802 2 12.908 2.21799C13.2843 2.40973 13.5903 2.71569 13.782 3.09202C14 3.51984 14 4.0799 14 5.2V10.8C14 11.9201 14 12.4802 13.782 12.908C13.5903 13.2843 13.2843 13.5903 12.908 13.782C12.4802 14 11.9201 14 10.8 14H10V2Z" fill="#004EEB"/>
+<path d="M10 2V14M5.2 2H10.8C11.9201 2 12.4802 2 12.908 2.21799C13.2843 2.40973 13.5903 2.71569 13.782 3.09202C14 3.51984 14 4.0799 14 5.2V10.8C14 11.9201 14 12.4802 13.782 12.908C13.5903 13.2843 13.2843 13.5903 12.908 13.782C12.4802 14 11.9201 14 10.8 14H5.2C4.07989 14 3.51984 14 3.09202 13.782C2.71569 13.5903 2.40973 13.2843 2.21799 12.908C2 12.4802 2 11.9201 2 10.8V5.2C2 4.07989 2 3.51984 2.21799 3.09202C2.40973 2.71569 2.71569 2.40973 3.09202 2.21799C3.51984 2 4.0799 2 5.2 2Z" stroke="#155EEF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/md.svg b/web/app/components/datasets/documents/assets/md.svg
new file mode 100644
index 00000000000..9e60161a6da
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/md.svg
@@ -0,0 +1,18 @@
+<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3434_2745)">
+<path d="M2.75 4.38325C2.75 3.40316 2.75 2.91311 2.94074 2.53877C3.10852 2.20949 3.37623 1.94177 3.70552 1.77399C4.07986 1.58325 4.56991 1.58325 5.55 1.58325H9.16667L13.25 5.66659V11.6166C13.25 12.5967 13.25 13.0867 13.0593 13.4611C12.8915 13.7904 12.6238 14.0581 12.2945 14.2258C11.9201 14.4166 11.4301 14.4166 10.45 14.4166H5.55C4.56991 14.4166 4.07986 14.4166 3.70552 14.2258C3.37623 14.0581 3.10852 13.7904 2.94074 13.4611C2.75 13.0867 2.75 12.5967 2.75 11.6166V4.38325Z" fill="#309BEC"/>
+</g>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M10.6208 12.0833H5.37921C5.13526 12.0833 4.9375 11.8996 4.9375 11.6731V8.99341C4.9375 8.76689 5.13526 8.58325 5.37921 8.58325H10.6208C10.8647 8.58325 11.0625 8.76689 11.0625 8.99341V11.6731C11.0625 11.8996 10.8647 12.0833 10.6208 12.0833ZM6.40986 11.2629V10.1965L6.9988 10.8801L7.58774 10.1965V11.2629H8.17668V9.40356H7.58774L6.9988 10.0872L6.40986 9.40356H5.82091V11.2629H6.40986ZM9.76683 10.3333H10.3558L9.47236 11.2903L8.58894 10.3333H9.17788V9.40356H9.76683V10.3333Z" fill="white"/>
+<path opacity="0.5" d="M9.1665 1.58325L13.2498 5.66658H10.3332C9.68884 5.66658 9.1665 5.14425 9.1665 4.49992V1.58325Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3434_2745" x="0.75" y="0.583252" width="14.5" height="16.8333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3434_2745"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3434_2745" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/messageTextCircle.svg b/web/app/components/datasets/documents/assets/messageTextCircle.svg
new file mode 100644
index 00000000000..e2c508cf030
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/messageTextCircle.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.33333 6.33333H8M5.33333 8.66667H10M8 14C11.3137 14 14 11.3137 14 8C14 4.68629 11.3137 2 8 2C4.68629 2 2 4.68629 2 8C2 8.7981 2.15582 9.5598 2.43871 10.2563C2.49285 10.3897 2.51992 10.4563 2.532 10.5102C2.54381 10.5629 2.54813 10.6019 2.54814 10.6559C2.54814 10.7111 2.53812 10.7713 2.51807 10.8916L2.12275 13.2635C2.08135 13.5119 2.06065 13.6361 2.09917 13.7259C2.13289 13.8045 2.19552 13.8671 2.27412 13.9008C2.36393 13.9393 2.48812 13.9186 2.73651 13.8772L5.10843 13.4819C5.22872 13.4619 5.28887 13.4519 5.34409 13.4519C5.3981 13.4519 5.43711 13.4562 5.48981 13.468C5.54369 13.4801 5.61035 13.5072 5.74366 13.5613C6.4402 13.8442 7.2019 14 8 14Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/normal.svg b/web/app/components/datasets/documents/assets/normal.svg
new file mode 100644
index 00000000000..1d94adffec7
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/normal.svg
@@ -0,0 +1,4 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.75 4.5C6.7165 4.5 7.5 3.7165 7.5 2.75C7.5 1.7835 6.7165 1 5.75 1C4.7835 1 4 1.7835 4 2.75C4 3.7165 4.7835 4.5 5.75 4.5Z" fill="#444CE7"/>
+<path d="M3.48775 4.314C3.36842 4.14172 3.30875 4.05558 3.24448 4.02712C3.18679 4.00157 3.12605 3.99844 3.06603 4.01794C2.99918 4.03965 2.94661 4.10099 2.84146 4.22367C2.41951 4.71598 2.13172 5.32705 2.03543 6.00009H2C1.72386 6.00009 1.5 5.77623 1.5 5.50009C1.5 5.31565 1.59961 5.15388 1.75036 5.06668C1.98939 4.9284 2.07107 4.62254 1.9328 4.38351C1.79453 4.14448 1.48867 4.0628 1.24964 4.20107C0.802591 4.45967 0.5 4.94425 0.5 5.50009C0.5 6.32852 1.17157 7.00009 2 7.00009H2.03545C2.14342 7.75422 2.49192 8.43113 2.99997 8.94961L2.99997 10.1117C2.99994 10.1712 2.99992 10.2424 3.00504 10.305C3.01097 10.3776 3.02619 10.4816 3.08171 10.5906C3.15362 10.7317 3.26835 10.8465 3.40948 10.9184C3.51845 10.9739 3.62245 10.9891 3.69505 10.9951C3.7577 11.0002 3.82881 11.0001 3.88836 11.0001H4.86154C4.92109 11.0001 4.99224 11.0002 5.05488 10.9951C5.12749 10.9891 5.23149 10.9739 5.34046 10.9184C5.48158 10.8465 5.59632 10.7317 5.66822 10.5906C5.72375 10.4816 5.73897 10.3776 5.7449 10.305C5.75002 10.2424 5.75 10.1712 5.74997 10.1117L5.74997 10.0001H6.24998L6.24997 10.1115C6.24995 10.1711 6.24992 10.2422 6.25504 10.3048C6.26097 10.3775 6.2762 10.4815 6.33172 10.5904C6.40363 10.7315 6.51836 10.8463 6.65948 10.9182C6.76846 10.9737 6.87245 10.9889 6.94506 10.9949C7.0077 11 7.0788 11 7.13835 10.9999H8.11159C8.17113 11 8.24229 11 8.30493 10.9949C8.37753 10.9889 8.48153 10.9737 8.5905 10.9182C8.73162 10.8463 8.84636 10.7315 8.91827 10.5904C8.97379 10.4815 8.98901 10.3775 8.99494 10.3048C9.00006 10.2422 9.00004 10.1711 9.00001 10.1115L9.00001 9.66299C9.55312 9.40029 10.0258 8.99721 10.3726 8.49993L10.6116 8.49994C10.6711 8.49996 10.7423 8.49999 10.8049 8.49487C10.8775 8.48893 10.9815 8.47371 11.0905 8.41819C11.2316 8.34628 11.3464 8.23155 11.4183 8.09043C11.4738 7.98145 11.489 7.87746 11.4949 7.80485C11.5001 7.74221 11.5 7.67109 11.5 7.61154V5.88181C11.5 5.82509 11.5001 5.75735 11.4954 5.69761C11.49 5.62851 11.4763 5.5294 11.4257 5.42448C11.352 5.27143 11.2285 5.14794 11.0755 5.07422C10.9705 5.02369 10.8714 5.00992 10.8023 5.00454C10.7577 5.00106 10.7087 5.0002 10.6631 4.99999C10.4953 4.64662 10.2702 4.32616 10 4.05044L10 3.51615C10 3.43874 10.0001 3.35111 9.99335 3.27574C9.98593 3.19252 9.96656 3.06385 9.88754 2.93633C9.78902 2.77733 9.63465 2.66089 9.4547 2.60984C9.31038 2.56889 9.18134 2.58561 9.09929 2.60134C9.02497 2.61559 8.94073 2.63969 8.8663 2.66098L8.78839 2.68324C8.6859 2.71252 8.63465 2.72716 8.59861 2.75356C8.5638 2.77904 8.54252 2.80415 8.52309 2.84266C8.50297 2.88255 8.49603 2.94339 8.48215 3.06506C8.32585 4.43546 7.16224 5.5 5.75 5.5C4.81225 5.5 3.98413 5.03063 3.48775 4.314Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/pdf.svg b/web/app/components/datasets/documents/assets/pdf.svg
new file mode 100644
index 00000000000..8684e588711
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/pdf.svg
@@ -0,0 +1,22 @@
+<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3434_9549)">
+<path d="M2.75 4.38325C2.75 3.40316 2.75 2.91311 2.94074 2.53877C3.10852 2.20948 3.37623 1.94177 3.70552 1.77399C4.07986 1.58325 4.56991 1.58325 5.55 1.58325H9.16667L13.25 5.66659V11.6166C13.25 12.5967 13.25 13.0867 13.0593 13.4611C12.8915 13.7904 12.6238 14.0581 12.2945 14.2258C11.9201 14.4166 11.4301 14.4166 10.45 14.4166H5.55C4.56991 14.4166 4.07986 14.4166 3.70552 14.2258C3.37623 14.0581 3.10852 13.7904 2.94074 13.4611C2.75 13.0867 2.75 12.5967 2.75 11.6166V4.38325Z" fill="#DD3633"/>
+</g>
+<g opacity="0.96">
+<path d="M6.81016 9.80956C6.81016 9.40006 6.51266 9.00806 5.95966 9.00806H4.97266V11.5001H5.58516V10.6111H5.95966C6.51266 10.6111 6.81016 10.2191 6.81016 9.80956ZM6.19766 9.80956C6.19766 9.93906 6.09966 10.0616 5.93166 10.0616H5.58516V9.55756H5.93166C6.09966 9.55756 6.19766 9.68006 6.19766 9.80956Z" fill="white"/>
+<path d="M9.02199 10.2541C9.02199 9.86206 9.05349 9.54356 8.76299 9.25306C8.59149 9.08156 8.34999 9.00806 8.09099 9.00806H7.16699V11.5001H8.09099C8.34999 11.5001 8.59149 11.4266 8.76299 11.2551C9.05349 10.9646 9.02199 10.6461 9.02199 10.2541ZM8.40949 10.2541C8.40949 10.6776 8.39199 10.7441 8.34299 10.8141C8.28699 10.8981 8.20299 10.9541 8.04899 10.9541H7.77949V9.55406H8.04899C8.20299 9.55406 8.28699 9.61006 8.34299 9.69406C8.39199 9.76406 8.40949 9.83406 8.40949 10.2541Z" fill="white"/>
+<path d="M11.1408 9.55406V9.00806H9.44678V11.5001H10.0593V10.5376H10.9833V9.99156H10.0593V9.55406H11.1408Z" fill="white"/>
+</g>
+<path opacity="0.5" d="M9.1665 1.58325L13.2498 5.66658H10.3332C9.68884 5.66658 9.1665 5.14425 9.1665 4.49992V1.58325Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3434_9549" x="0.75" y="0.583252" width="14.5" height="16.8333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3434_9549"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3434_9549" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/star.svg b/web/app/components/datasets/documents/assets/star.svg
new file mode 100644
index 00000000000..3ffda57944c
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/star.svg
@@ -0,0 +1,11 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6 0.5C6.27614 0.5 6.5 0.723858 6.5 1V2C6.5 2.27614 6.27614 2.5 6 2.5C5.72386 2.5 5.5 2.27614 5.5 2V1C5.5 0.723858 5.72386 0.5 6 0.5Z" fill="#FB6514"/>
+<path d="M2.81791 2.11092C2.62265 1.91566 2.30606 1.91566 2.1108 2.11092C1.91554 2.30619 1.91554 2.62277 2.1108 2.81803L2.81791 3.52514C3.01317 3.7204 3.32975 3.7204 3.52502 3.52514C3.72028 3.32988 3.72028 3.01329 3.52502 2.81803L2.81791 2.11092Z" fill="#FB6514"/>
+<path d="M0.5 6C0.5 5.72386 0.723858 5.5 1 5.5H2C2.27614 5.5 2.5 5.72386 2.5 6C2.5 6.27614 2.27614 6.5 2 6.5H1C0.723858 6.5 0.5 6.27614 0.5 6Z" fill="#FB6514"/>
+<path d="M10 5.5C9.72386 5.5 9.5 5.72386 9.5 6C9.5 6.27614 9.72386 6.5 10 6.5H11C11.2761 6.5 11.5 6.27614 11.5 6C11.5 5.72386 11.2761 5.5 11 5.5H10Z" fill="#FB6514"/>
+<path d="M9.18192 8.47482C8.98666 8.27955 8.67008 8.27955 8.47482 8.47482C8.27955 8.67008 8.27955 8.98666 8.47482 9.18192L9.18192 9.88903C9.37718 10.0843 9.69377 10.0843 9.88903 9.88903C10.0843 9.69377 10.0843 9.37718 9.88903 9.18192L9.18192 8.47482Z" fill="#FB6514"/>
+<path d="M9.88903 2.81803C10.0843 2.62277 10.0843 2.30619 9.88903 2.11092C9.69377 1.91566 9.37718 1.91566 9.18192 2.11092L8.47482 2.81803C8.27955 3.01329 8.27955 3.32988 8.47482 3.52514C8.67008 3.7204 8.98666 3.7204 9.18192 3.52514L9.88903 2.81803Z" fill="#FB6514"/>
+<path d="M6 9.5C6.27614 9.5 6.5 9.72386 6.5 10V11C6.5 11.2761 6.27614 11.5 6 11.5C5.72386 11.5 5.5 11.2761 5.5 11V10C5.5 9.72386 5.72386 9.5 6 9.5Z" fill="#FB6514"/>
+<path d="M3.52502 9.18192C3.72028 8.98666 3.72028 8.67008 3.52502 8.47482C3.32975 8.27955 3.01317 8.27955 2.81791 8.47482L2.1108 9.18192C1.91554 9.37718 1.91554 9.69377 2.1108 9.88903C2.30606 10.0843 2.62265 10.0843 2.81791 9.88903L3.52502 9.18192Z" fill="#FB6514"/>
+<path d="M6.44837 3.27869C6.36413 3.10804 6.19032 3 6.00001 3C5.8097 3 5.6359 3.10804 5.55166 3.27869L4.89538 4.60823L3.4277 4.82276C3.23942 4.85028 3.08308 4.98228 3.02439 5.16328C2.9657 5.34429 3.01484 5.54291 3.15115 5.67568L4.21275 6.70968L3.96221 8.17048C3.93004 8.35807 4.00716 8.54766 4.16115 8.65953C4.31514 8.77139 4.51928 8.78613 4.68774 8.69754L6.00001 8.00742L7.31229 8.69754C7.48075 8.78613 7.68489 8.77139 7.83888 8.65953C7.99287 8.54766 8.06999 8.35807 8.03782 8.17048L7.78728 6.70968L8.84888 5.67568C8.98519 5.54291 9.03433 5.34429 8.97564 5.16328C8.91695 4.98228 8.76061 4.85028 8.57233 4.82276L7.10465 4.60823L6.44837 3.27869Z" fill="#FB6514"/>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/target.svg b/web/app/components/datasets/documents/assets/target.svg
new file mode 100644
index 00000000000..cb74c9e4356
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/target.svg
@@ -0,0 +1,10 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g clip-path="url(#clip0_1745_6117)">
+ <path d="M7.99998 4V2.5L9.49998 1L9.99998 2L11 2.5L9.49998 4H7.99998ZM7.99998 4L5.99999 5.99997M11 6C11 8.76142 8.76142 11 6 11C3.23858 11 1 8.76142 1 6C1 3.23858 3.23858 1 6 1M8.5 6C8.5 7.38071 7.38071 8.5 6 8.5C4.61929 8.5 3.5 7.38071 3.5 6C3.5 4.61929 4.61929 3.5 6 3.5" stroke="#667085" stroke-linecap="round" stroke-linejoin="round" />
+ </g>
+ <defs>
+ <clipPath id="clip0_1745_6117">
+ <rect width="12" height="12" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
diff --git a/web/app/components/datasets/documents/assets/txt.svg b/web/app/components/datasets/documents/assets/txt.svg
new file mode 100644
index 00000000000..117ef5b9921
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/txt.svg
@@ -0,0 +1,23 @@
+<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_d_3434_4808)">
+<path d="M2.75 4.38325C2.75 3.40316 2.75 2.91311 2.94074 2.53877C3.10852 2.20948 3.37623 1.94177 3.70552 1.77399C4.07986 1.58325 4.56991 1.58325 5.55 1.58325H9.16667L13.25 5.66659V11.6166C13.25 12.5967 13.25 13.0867 13.0593 13.4611C12.8915 13.7904 12.6238 14.0581 12.2945 14.2258C11.9201 14.4166 11.4301 14.4166 10.45 14.4166H5.55C4.56991 14.4166 4.07986 14.4166 3.70552 14.2258C3.37623 14.0581 3.10852 13.7904 2.94074 13.4611C2.75 13.0867 2.75 12.5967 2.75 11.6166V4.38325Z" fill="#E3E5E8"/>
+<path d="M3 4.38325C3 3.88908 3.00019 3.53349 3.02301 3.25421C3.04559 2.97786 3.08907 2.79832 3.16349 2.65227C3.3073 2.37002 3.53677 2.14055 3.81901 1.99674C3.96507 1.92232 4.14461 1.87884 4.42096 1.85626C4.70024 1.83345 5.05583 1.83325 5.55 1.83325H9.06311L13 5.77014V11.6166C13 12.1108 12.9998 12.4664 12.977 12.7456C12.9544 13.022 12.9109 13.2015 12.8365 13.3476C12.6927 13.6298 12.4632 13.8593 12.181 14.0031C12.0349 14.0775 11.8554 14.121 11.579 14.1436C11.2998 14.1664 10.9442 14.1666 10.45 14.1666H5.55C5.05583 14.1666 4.70024 14.1664 4.42096 14.1436C4.14461 14.121 3.96507 14.0775 3.81901 14.0031C3.53677 13.8593 3.3073 13.6298 3.16349 13.3476C3.08907 13.2015 3.04559 13.022 3.02301 12.7456C3.00019 12.4664 3 12.1108 3 11.6166V4.38325Z" stroke="black" stroke-opacity="0.03" stroke-width="0.5"/>
+</g>
+<g opacity="0.96">
+<path d="M6.78623 9.55406V9.00806H4.94873V9.55406H5.56123V11.5001H6.17373V9.55406H6.78623Z" fill="#667085"/>
+<path d="M9.11009 11.5001L8.33309 10.2226L9.06109 9.00806H8.36459L8.00059 9.71156L7.63659 9.00806H6.94009L7.66809 10.2226L6.89109 11.5001H7.59109L8.00059 10.7336L8.41009 11.5001H9.11009Z" fill="#667085"/>
+<path d="M11.0519 9.55406V9.00806H9.21436V9.55406H9.82686V11.5001H10.4394V9.55406H11.0519Z" fill="#667085"/>
+</g>
+<path opacity="0.5" d="M9.1665 1.58325L13.2498 5.66658H10.3332C9.68884 5.66658 9.1665 5.14425 9.1665 4.49992V1.58325Z" fill="white"/>
+<defs>
+<filter id="filter0_d_3434_4808" x="0.75" y="0.583252" width="14.5" height="16.8333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3434_4808"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3434_4808" result="shape"/>
+</filter>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/documents/assets/typeSquare.svg b/web/app/components/datasets/documents/assets/typeSquare.svg
new file mode 100644
index 00000000000..d1588e85663
--- /dev/null
+++ b/web/app/components/datasets/documents/assets/typeSquare.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M4 3.5H8M6 3.5V8.5M3.9 10.5H8.1C8.94008 10.5 9.36012 10.5 9.68099 10.3365C9.96323 10.1927 10.1927 9.96323 10.3365 9.68099C10.5 9.36012 10.5 8.94008 10.5 8.1V3.9C10.5 3.05992 10.5 2.63988 10.3365 2.31901C10.1927 2.03677 9.96323 1.8073 9.68099 1.66349C9.36012 1.5 8.94008 1.5 8.1 1.5H3.9C3.05992 1.5 2.63988 1.5 2.31901 1.66349C2.03677 1.8073 1.8073 2.03677 1.66349 2.31901C1.5 2.63988 1.5 3.05992 1.5 3.9V8.1C1.5 8.94008 1.5 9.36012 1.66349 9.68099C1.8073 9.96323 2.03677 10.1927 2.31901 10.3365C2.63988 10.5 3.05992 10.5 3.9 10.5Z" stroke="#667085" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
diff --git a/web/app/components/datasets/documents/detail/completed/InfiniteVirtualList.tsx b/web/app/components/datasets/documents/detail/completed/InfiniteVirtualList.tsx
new file mode 100644
index 00000000000..98eff202521
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/completed/InfiniteVirtualList.tsx
@@ -0,0 +1,87 @@
+import React, { FC, CSSProperties } from "react";
+import { FixedSizeList as List } from "react-window";
+import InfiniteLoader from "react-window-infinite-loader";
+import type { SegmentDetailModel } from "@/models/datasets";
+import SegmentCard from "./SegmentCard";
+import s from "./style.module.css";
+
+type IInfiniteVirtualListProps = {
+ hasNextPage?: boolean; // Are there more items to load? (This information comes from the most recent API request.)
+ isNextPageLoading: boolean; // Are we currently loading a page of items? (This may be an in-flight flag in your Redux store for example.)
+ items: Array<SegmentDetailModel[]>; // Array of items loaded so far.
+ loadNextPage: () => Promise<any>; // Callback function responsible for loading the next page of items.
+ onClick: (detail: SegmentDetailModel) => void;
+ onChangeSwitch: (segId: string, enabled: boolean) => Promise<void>;
+};
+
+const InfiniteVirtualList: FC<IInfiniteVirtualListProps> = ({
+ hasNextPage,
+ isNextPageLoading,
+ items,
+ loadNextPage,
+ onClick: onClickCard,
+ onChangeSwitch,
+}) => {
+ // If there are more items to be loaded then add an extra row to hold a loading indicator.
+ const itemCount = hasNextPage ? items.length + 1 : items.length;
+
+ // Only load 1 page of items at a time.
+ // Pass an empty callback to InfiniteLoader in case it asks us to load more than once.
+ const loadMoreItems = isNextPageLoading ? () => { } : loadNextPage;
+
+ // Every row is loaded except for our loading indicator row.
+ const isItemLoaded = (index: number) => !hasNextPage || index < items.length;
+
+ // Render an item or a loading indicator.
+ const Item = ({ index, style }: { index: number; style: CSSProperties }) => {
+ let content;
+ if (!isItemLoaded(index)) {
+ content = (
+ <>
+ {[1, 2, 3].map((v) => (
+ <SegmentCard loading={true} detail={{ position: v } as any} />
+ ))}
+ </>
+ );
+ } else {
+ content = items[index].map((segItem) => (
+ <SegmentCard
+ key={segItem.id}
+ detail={segItem}
+ onClick={() => onClickCard(segItem)}
+ onChangeSwitch={onChangeSwitch}
+ loading={false}
+ />
+ ));
+ }
+
+ return (
+ <div style={style} className={s.cardWrapper}>
+ {content}
+ </div>
+ );
+ };
+
+ return (
+ <InfiniteLoader
+ itemCount={itemCount}
+ isItemLoaded={isItemLoaded}
+ loadMoreItems={loadMoreItems}
+ >
+ {({ onItemsRendered, ref }) => (
+ <List
+ ref={ref}
+ className="List"
+ height={800}
+ width={"100%"}
+ itemSize={200}
+ itemCount={itemCount}
+ onItemsRendered={onItemsRendered}
+ >
+ {Item}
+ </List>
+ )}
+ </InfiniteLoader>
+ );
+};
+export default InfiniteVirtualList;
diff --git a/web/app/components/datasets/documents/detail/completed/SegmentCard.tsx b/web/app/components/datasets/documents/detail/completed/SegmentCard.tsx
new file mode 100644
index 00000000000..beeee1ebebf
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/completed/SegmentCard.tsx
@@ -0,0 +1,166 @@
+import type { FC } from "react";
+import React from "react";
+import cn from "classnames";
+import { ArrowUpRightIcon } from "@heroicons/react/24/outline";
+import Switch from "@/app/components/base/switch";
+import Divider from "@/app/components/base/divider";
+import Indicator from "@/app/components/header/indicator";
+import { formatNumber } from "@/utils/format";
+import type { SegmentDetailModel } from "@/models/datasets";
+import { StatusItem } from "../../list";
+import s from "./style.module.css";
+import { SegmentIndexTag } from "./index";
+import { DocumentTitle } from '../index'
+import { useTranslation } from "react-i18next";
+
+const ProgressBar: FC<{ percent: number; loading: boolean }> = ({ percent, loading }) => {
+ return (
+ <div className={s.progressWrapper}>
+ <div className={cn(s.progress, loading ? s.progressLoading : '')}>
+ <div
+ className={s.progressInner}
+ style={{ width: `${loading ? 0 : (percent * 100).toFixed(2)}%` }}
+ />
+ </div>
+ <div className={loading ? s.progressTextLoading : s.progressText}>{loading ? null : percent.toFixed(2)}</div>
+ </div>
+ )
+}
+
+export type UsageScene = 'doc' | 'hitTesting'
+
+type ISegmentCardProps = {
+ loading: boolean;
+ detail?: SegmentDetailModel & { document: { name: string } };
+ score?: number
+ onClick?: () => void;
+ onChangeSwitch?: (segId: string, enabled: boolean) => Promise<void>;
+ scene?: UsageScene
+ className?: string;
+};
+
+const SegmentCard: FC<ISegmentCardProps> = ({
+ detail = {},
+ score,
+ onClick,
+ onChangeSwitch,
+ loading = true,
+ scene = 'doc',
+ className = ''
+}) => {
+ const { t } = useTranslation()
+ const {
+ id,
+ position,
+ enabled,
+ content,
+ word_count,
+ hit_count,
+ index_node_hash,
+ } = detail as any;
+ const isDocScene = scene === 'doc'
+
+ return (
+ <div
+ className={cn(
+ s.segWrapper,
+ isDocScene && !enabled ? "bg-gray-25" : "",
+ "group",
+ !loading ? "pb-4" : "",
+ className,
+ )}
+ onClick={() => onClick?.()}
+ >
+ <div className={s.segTitleWrapper}>
+ {isDocScene ? <>
+ <SegmentIndexTag positionId={position} className={cn("w-fit group-hover:opacity-100", isDocScene && !enabled ? 'opacity-50' : '')} />
+ <div className={s.segStatusWrapper}>
+ {loading ? (
+ <Indicator
+ color="gray"
+ className="bg-gray-200 border-gray-300 shadow-none"
+ />
+ ) : (
+ <>
+ <StatusItem status={enabled ? "enabled" : "disabled"} reverse textCls="text-gray-500 text-xs" />
+ <div className="hidden group-hover:inline-flex items-center">
+ <Divider type="vertical" className="!h-2" />
+ <div
+ onClick={(e: React.MouseEvent<HTMLDivElement, MouseEvent>) =>
+ e.stopPropagation()
+ }
+ className="inline-flex items-center"
+ >
+ <Switch
+ size='md'
+ defaultValue={enabled}
+ onChange={async (val) => {
+ await onChangeSwitch?.(id, val)
+ }}
+ />
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ </> : <div className={s.hitTitleWrapper}>
+ <div className={cn(s.commonIcon, s.targetIcon, loading ? '!bg-gray-300' : '', '!w-3.5 !h-3.5')} />
+ <ProgressBar percent={score ?? 0} loading={loading} />
+ </div>}
+ </div>
+ {loading ? (
+ <div className={cn(s.cardLoadingWrapper, s.cardLoadingIcon)}>
+ <div className={cn(s.cardLoadingBg)} />
+ </div>
+ ) : (
+ isDocScene ? <>
+ <div
+ className={cn(
+ s.segContent,
+ enabled ? "" : "opacity-50",
+ "group-hover:text-transparent group-hover:bg-clip-text group-hover:bg-gradient-to-b"
+ )}
+ >
+ {content}
+ </div>
+ <div className={cn('group-hover:flex', s.segData)}>
+ <div className="flex items-center mr-6">
+ <div className={cn(s.commonIcon, s.typeSquareIcon)}></div>
+ <div className={s.segDataText}>{formatNumber(word_count)}</div>
+ </div>
+ <div className="flex items-center mr-6">
+ <div className={cn(s.commonIcon, s.targetIcon)} />
+ <div className={s.segDataText}>{formatNumber(hit_count)}</div>
+ </div>
+ <div className="flex items-center">
+ <div className={cn(s.commonIcon, s.bezierCurveIcon)} />
+ <div className={s.segDataText}>{index_node_hash}</div>
+ </div>
+ </div>
+ </> : <>
+ <div className="h-[140px] overflow-hidden text-ellipsis text-sm font-normal text-gray-800">
+ {content}
+ </div>
+ <div className={cn("w-full bg-gray-50 group-hover:bg-white")}>
+ <Divider />
+ <div className="relative flex items-center w-full">
+ <DocumentTitle
+ name={detail?.document?.name || ''}
+ extension={(detail?.document?.name || '').split('.').pop() || 'txt'}
+ wrapperCls='w-full'
+ iconCls="!h-4 !w-4 !bg-contain"
+ textCls="text-xs text-gray-700 !font-normal overflow-hidden whitespace-nowrap text-ellipsis"
+ />
+ <div className={cn(s.chartLinkText, 'group-hover:inline-flex')}>
+ {t('datasetHitTesting.viewChart')}
+ <ArrowUpRightIcon className="w-3 h-3 ml-1 stroke-current stroke-2" />
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+};
+
+export default SegmentCard;
diff --git a/web/app/components/datasets/documents/detail/completed/index.tsx b/web/app/components/datasets/documents/detail/completed/index.tsx
new file mode 100644
index 00000000000..c308ffee315
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/completed/index.tsx
@@ -0,0 +1,206 @@
+'use client'
+import type { FC } from 'react'
+import React, { memo, useState, useEffect, useMemo } from 'react'
+import { HashtagIcon } from '@heroicons/react/24/solid'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import { omitBy, isNil, debounce } from 'lodash-es'
+import { formatNumber } from '@/utils/format'
+import { StatusItem } from '../../list'
+import { DocumentContext } from '../index'
+import s from './style.module.css'
+import Modal from '@/app/components/base/modal'
+import Switch from '@/app/components/base/switch'
+import Divider from '@/app/components/base/divider'
+import Input from '@/app/components/base/input'
+import Loading from '@/app/components/base/loading'
+import { ToastContext } from '@/app/components/base/toast'
+import { SimpleSelect, Item } from '@/app/components/base/select'
+import { disableSegment, enableSegment, fetchSegments } from '@/service/datasets'
+import type { SegmentDetailModel, SegmentsResponse, SegmentsQuery } from '@/models/datasets'
+import { asyncRunSafe } from '@/utils'
+import type { CommonResponse } from '@/models/common'
+import InfiniteVirtualList from "./InfiniteVirtualList";
+import cn from 'classnames'
+
+export const SegmentIndexTag: FC<{ positionId: string | number; className?: string }> = ({ positionId, className }) => {
+ const localPositionId = useMemo(() => {
+ const positionIdStr = String(positionId)
+ if (positionIdStr.length >= 3)
+ return positionId
+ return positionIdStr.padStart(3, '0')
+ }, [positionId])
+ return (
+ <div className={`text-gray-500 border border-gray-200 box-border flex items-center rounded-md italic text-[11px] pl-1 pr-1.5 font-medium ${className ?? ''}`}>
+ <HashtagIcon className='w-3 h-3 text-gray-400 fill-current mr-1 stroke-current stroke-1' />
+ {localPositionId}
+ </div>
+ )
+}
+
+type ISegmentDetailProps = {
+ segInfo?: Partial<SegmentDetailModel> & { id: string }
+ onChangeSwitch?: (segId: string, enabled: boolean) => Promise<void>
+}
+/**
+ * Show all the contents of the segment
+ */
+export const SegmentDetail: FC<ISegmentDetailProps> = memo(({
+ segInfo,
+ onChangeSwitch }) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className={'flex flex-col'}>
+ <SegmentIndexTag positionId={segInfo?.position || ''} className='w-fit mb-6' />
+ <div className={s.segModalContent}>{segInfo?.content}</div>
+ <div className={s.keywordTitle}>{t('datasetDocuments.segment.keywords')}</div>
+ <div className={s.keywordWrapper}>
+ {!segInfo?.keywords?.length
+ ? '-'
+ : segInfo?.keywords?.map((word: any) => {
+ return <div className={s.keyword}>{word}</div>
+ })}
+ </div>
+ <div className={cn(s.footer, s.numberInfo)}>
+ <div className='flex items-center'>
+ <div className={cn(s.commonIcon, s.typeSquareIcon)} /><span className='mr-8'>{formatNumber(segInfo?.word_count as any)} {t('datasetDocuments.segment.characters')}</span>
+ <div className={cn(s.commonIcon, s.targetIcon)} /><span className='mr-8'>{formatNumber(segInfo?.hit_count as any)} {t('datasetDocuments.segment.hitCount')}</span>
+ <div className={cn(s.commonIcon, s.bezierCurveIcon)} /><span className={s.hashText}>{t('datasetDocuments.segment.vectorHash')}{segInfo?.index_node_hash}</span>
+ </div>
+ <div className='flex items-center'>
+ <StatusItem status={segInfo?.enabled ? 'enabled' : 'disabled'} reverse textCls='text-gray-500 text-xs' />
+ <Divider type='vertical' className='!h-2' />
+ <Switch
+ size='md'
+ defaultValue={segInfo?.enabled}
+ onChange={async val => {
+ await onChangeSwitch?.(segInfo?.id || '', val)
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ )
+})
+
+export const splitArray = (arr: any[], size = 3) => {
+ if (!arr || !arr.length)
+ return []
+ const result = []
+ for (let i = 0; i < arr.length; i += size)
+ result.push(arr.slice(i, i + size))
+ return result
+}
+
+type ICompletedProps = {
+ // data: Array<{}> // all/part segments
+}
+/**
+ * Embedding done, show list of all segments
+ * Support search and filter
+ */
+const Completed: FC<ICompletedProps> = () => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+ const { datasetId = '', documentId = '' } = useContext(DocumentContext)
+ // the current segment id and whether to show the modal
+ const [currSegment, setCurrSegment] = useState<{ segInfo?: SegmentDetailModel; showModal: boolean }>({ showModal: false })
+
+ const [searchValue, setSearchValue] = useState() // the search value
+ const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
+
+ const [lastSegmentsRes, setLastSegmentsRes] = useState<SegmentsResponse | undefined>(undefined)
+ const [allSegments, setAllSegments] = useState<Array<SegmentDetailModel[]>>([]) // all segments data
+ const [loading, setLoading] = useState(false)
+ const [total, setTotal] = useState<number | undefined>()
+
+ useEffect(() => {
+ if (lastSegmentsRes !== undefined) {
+ getSegments(false)
+ }
+ }, [selectedStatus, searchValue])
+
+ const onChangeStatus = ({ value }: Item) => {
+ setSelectedStatus(value === 'all' ? 'all' : !!value)
+ }
+
+ const getSegments = async (needLastId?: boolean) => {
+ const finalLastId = lastSegmentsRes?.data?.[lastSegmentsRes.data.length - 1]?.id || '';
+ setLoading(true)
+ const [e, res] = await asyncRunSafe<SegmentsResponse>(fetchSegments({
+ datasetId,
+ documentId,
+ params: omitBy({
+ last_id: !needLastId ? undefined : finalLastId,
+ limit: 9,
+ keyword: searchValue,
+ enabled: selectedStatus === 'all' ? 'all' : !!selectedStatus,
+ }, isNil) as SegmentsQuery
+ }) as Promise<SegmentsResponse>)
+ if (!e) {
+ setAllSegments([...(!needLastId ? [] : allSegments), ...splitArray(res.data || [])])
+ setLastSegmentsRes(res)
+ if (!lastSegmentsRes) { setTotal(res?.total || 0) }
+ }
+ setLoading(false)
+ }
+
+ const onClickCard = (detail: SegmentDetailModel) => {
+ setCurrSegment({ segInfo: detail, showModal: true })
+ }
+
+ const onCloseModal = () => {
+ setCurrSegment({ ...currSegment, showModal: false })
+ }
+
+ const onChangeSwitch = async (segId: string, enabled: boolean) => {
+ const opApi = enabled ? enableSegment : disableSegment
+ const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, segmentId: segId }) as Promise<CommonResponse>)
+ if (!e) {
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ for (const item of allSegments) {
+ for (const seg of item) {
+ if (seg.id === segId) {
+ seg.enabled = enabled
+ }
+ }
+ }
+ setAllSegments([...allSegments])
+ } else {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ }
+ }
+
+ return (
+ <>
+ <div className={s.docSearchWrapper}>
+ <div className={s.totalText}>{total ? formatNumber(total) : '--'} {t('datasetDocuments.segment.paragraphs')}</div>
+ <SimpleSelect
+ onSelect={onChangeStatus}
+ items={[
+ { value: 'all', name: t('datasetDocuments.list.index.all') },
+ { value: 0, name: t('datasetDocuments.list.status.disabled') },
+ { value: 1, name: t('datasetDocuments.list.status.enabled') },
+ ]}
+ defaultValue={'all'}
+ className={s.select}
+ wrapperClassName='h-fit w-[120px] mr-2' />
+ <Input showPrefix wrapperClassName='!w-52' className='!h-8' onChange={debounce(setSearchValue, 500)} />
+ </div>
+ <InfiniteVirtualList
+ hasNextPage={lastSegmentsRes?.has_more ?? true}
+ isNextPageLoading={loading}
+ items={allSegments}
+ loadNextPage={getSegments}
+ onChangeSwitch={onChangeSwitch}
+ onClick={onClickCard}
+ />
+ <Modal isShow={currSegment.showModal} onClose={onCloseModal} className='!max-w-[640px]' closable>
+ <SegmentDetail segInfo={currSegment.segInfo ?? { id: '' }} onChangeSwitch={onChangeSwitch} />
+ </Modal>
+ </>
+ )
+}
+
+export default Completed
diff --git a/web/app/components/datasets/documents/detail/completed/style.module.css b/web/app/components/datasets/documents/detail/completed/style.module.css
new file mode 100644
index 00000000000..d1eeaf67263
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/completed/style.module.css
@@ -0,0 +1,130 @@
+/* .cardWrapper {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(290px, auto));
+ grid-gap: 16px;
+ grid-auto-rows: 180px;
+} */
+.totalText {
+ @apply text-gray-900 font-medium text-base flex-1;
+}
+.docSearchWrapper {
+ @apply sticky w-full h-10 -top-3 bg-white flex items-center mb-3 justify-between z-10;
+}
+.listContainer {
+ height: calc(100% - 3.25rem);
+ @apply box-border pb-[30px];
+}
+.cardWrapper {
+ @apply grid gap-4 grid-cols-3 min-w-[902px] last:mb-[30px];
+}
+.segWrapper {
+ @apply box-border h-[180px] min-w-[290px] bg-gray-50 px-4 pt-4 flex flex-col text-opacity-50 rounded-xl border border-transparent hover:border-gray-200 hover:shadow-lg hover:cursor-pointer hover:bg-white;
+}
+.segTitleWrapper {
+ @apply flex items-center justify-between;
+}
+.segStatusWrapper {
+ @apply flex items-center box-border;
+}
+.segContent {
+ white-space: wrap;
+ @apply flex-1 h-0 min-h-0 mt-2 text-sm text-gray-800 overflow-ellipsis overflow-hidden from-gray-800 to-white;
+}
+.segData {
+ @apply hidden text-gray-500 text-xs pt-2;
+}
+.segDataText {
+ @apply max-w-[80px] truncate;
+}
+.chartLinkText {
+ background: linear-gradient(to left, white, 90%, transparent);
+ @apply text-primary-600 font-semibold text-xs absolute right-0 hidden h-12 pl-12 items-center;
+}
+.select {
+ @apply h-8 py-0 bg-gray-50 hover:bg-gray-100 rounded-lg shadow-none !important;
+}
+.segModalContent {
+ @apply h-96 text-gray-800 text-base overflow-y-scroll;
+}
+.footer {
+ @apply flex items-center justify-between box-border border-t-gray-200 border-t-[0.5px] pt-3 mt-4;
+}
+.numberInfo {
+ @apply text-gray-500 text-xs font-medium;
+}
+.keywordTitle {
+ @apply text-gray-500 mb-2 mt-1 text-xs uppercase;
+}
+.keywordWrapper {
+ @apply text-gray-700 w-full max-h-[200px] overflow-auto flex flex-wrap;
+}
+.keyword {
+ @apply text-sm border border-gray-200 max-w-[200px] max-h-[100px] whitespace-pre-line overflow-y-auto mr-1 mb-2 last:mr-0 px-2 py-1 rounded-lg;
+}
+.hashText {
+ @apply w-48 inline-block truncate;
+}
+.commonIcon {
+ @apply w-3 h-3 inline-block align-middle mr-1 bg-gray-500;
+ mask-repeat: no-repeat;
+ mask-size: contain;
+ mask-position: center center;
+}
+.targetIcon {
+ mask-image: url(../../assets/target.svg);
+}
+.typeSquareIcon {
+ mask-image: url(../../assets/typeSquare.svg);
+}
+.bezierCurveIcon {
+ mask-image: url(../../assets/bezierCurve.svg);
+}
+.cardLoadingWrapper {
+ @apply relative w-full h-full inline-block rounded-b-xl;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 100% 100%;
+ background-origin: content-box;
+}
+.cardLoadingIcon {
+ background-image: url(../../assets/cardLoading.svg);
+}
+/* .hitLoadingIcon {
+ background-image: url(../../assets/hitLoading.svg);
+} */
+.cardLoadingBg {
+ @apply h-full relative rounded-b-xl mt-4;
+ left: calc(-1rem - 1px);
+ width: calc(100% + 2rem + 2px);
+ height: calc(100% - 1rem + 1px);
+ background: linear-gradient(
+ 180deg,
+ rgba(252, 252, 253, 0) 0%,
+ #fcfcfd 74.15%
+ );
+}
+
+.hitTitleWrapper {
+ @apply w-full flex items-center justify-between mb-2;
+}
+.progressWrapper {
+ @apply flex items-center justify-between w-full;
+}
+.progress {
+ border-radius: 3px;
+ @apply relative h-1.5 box-border border border-gray-300 flex-1 mr-2;
+}
+.progressLoading {
+ @apply border-[#EAECF0] bg-[#EAECF0];
+}
+.progressInner {
+ @apply absolute top-0 h-full bg-gray-300;
+}
+.progressText {
+ font-size: 13px;
+ @apply text-gray-700 font-bold;
+}
+.progressTextLoading {
+ border-radius: 5px;
+ @apply h-3.5 w-3.5 bg-[#EAECF0];
+}
diff --git a/web/app/components/datasets/documents/detail/embedding/index.tsx b/web/app/components/datasets/documents/detail/embedding/index.tsx
new file mode 100644
index 00000000000..40ce2713e7c
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/embedding/index.tsx
@@ -0,0 +1,268 @@
+import { FC, useCallback, useMemo, useState } from 'react'
+import React from 'react'
+import useSWR from 'swr'
+import { useRouter } from 'next/navigation'
+import { useContext } from 'use-context-selector'
+import { useTranslation } from 'react-i18next'
+import { omit } from 'lodash-es'
+import cn from 'classnames'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import Loading from '@/app/components/base/loading'
+import { ToastContext } from '@/app/components/base/toast'
+import { FullDocumentDetail, ProcessRuleResponse } from '@/models/datasets'
+import type { CommonResponse } from '@/models/common'
+import { asyncRunSafe } from '@/utils'
+import { formatNumber } from '@/utils/format'
+import { fetchProcessRule, fetchIndexingEstimate, fetchIndexingStatus, pauseDocIndexing, resumeDocIndexing } from '@/service/datasets'
+import SegmentCard from '../completed/SegmentCard'
+import { FieldInfo } from '../metadata'
+import s from './style.module.css'
+import style from '../completed/style.module.css'
+import { DocumentContext } from '../index'
+import DatasetDetailContext from '@/context/dataset-detail'
+import StopEmbeddingModal from '@/app/components/datasets/create/stop-embedding-modal'
+import { ArrowRightIcon } from '@heroicons/react/24/solid'
+
+type Props = {
+ detail?: FullDocumentDetail
+ stopPosition?: 'top' | 'bottom'
+ datasetId?: string
+ documentId?: string
+ indexingType?: string
+}
+
+const StopIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <g clip-path="url(#clip0_2328_2798)">
+ <path d="M1.5 3.9C1.5 3.05992 1.5 2.63988 1.66349 2.31901C1.8073 2.03677 2.03677 1.8073 2.31901 1.66349C2.63988 1.5 3.05992 1.5 3.9 1.5H8.1C8.94008 1.5 9.36012 1.5 9.68099 1.66349C9.96323 1.8073 10.1927 2.03677 10.3365 2.31901C10.5 2.63988 10.5 3.05992 10.5 3.9V8.1C10.5 8.94008 10.5 9.36012 10.3365 9.68099C10.1927 9.96323 9.96323 10.1927 9.68099 10.3365C9.36012 10.5 8.94008 10.5 8.1 10.5H3.9C3.05992 10.5 2.63988 10.5 2.31901 10.3365C2.03677 10.1927 1.8073 9.96323 1.66349 9.68099C1.5 9.36012 1.5 8.94008 1.5 8.1V3.9Z" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </g>
+ <defs>
+ <clipPath id="clip0_2328_2798">
+ <rect width="12" height="12" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+}
+
+const ResumeIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M10 3.5H5C3.34315 3.5 2 4.84315 2 6.5C2 8.15685 3.34315 9.5 5 9.5H10M10 3.5L8 1.5M10 3.5L8 5.5" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+
+}
+
+const RuleDetail: FC<{ sourceData?: ProcessRuleResponse; docName?: string }> = ({ sourceData, docName }) => {
+ const { t } = useTranslation()
+
+ const segmentationRuleMap = {
+ docName: t('datasetDocuments.embedding.docName'),
+ mode: t('datasetDocuments.embedding.mode'),
+ segmentLength: t('datasetDocuments.embedding.segmentLength'),
+ textCleaning: t('datasetDocuments.embedding.textCleaning'),
+ }
+ const getValue = useCallback((field: string) => {
+ let value: string | number | undefined = '-';
+ switch (field) {
+ case 'docName':
+ value = docName
+ break;
+ case 'mode':
+ value = sourceData?.mode === 'automatic' ? (t('datasetDocuments.embedding.automatic') as string) : (t('datasetDocuments.embedding.custom') as string);
+ break;
+ case 'segmentLength':
+ value = sourceData?.rules?.segmentation?.max_tokens
+ break;
+ default:
+ value = sourceData?.mode === 'automatic' ?
+ (t('datasetDocuments.embedding.automatic') as string) :
+ sourceData?.rules?.pre_processing_rules?.map(rule => {
+ if (rule.enabled) {
+ return getRuleName(rule.id)
+ }
+ }).filter(Boolean).join(';')
+ break;
+ }
+ return value
+ }, [sourceData, docName])
+
+ const getRuleName = (key: string) => {
+ if (key === 'remove_extra_spaces') {
+ return t('datasetCreation.stepTwo.removeExtraSpaces')
+ }
+ if (key === 'remove_urls_emails') {
+ return t('datasetCreation.stepTwo.removeUrlEmails')
+ }
+ if (key === 'remove_stopwords') {
+ return t('datasetCreation.stepTwo.removeStopwords')
+ }
+ }
+
+ return <div className='flex flex-col pt-8 pb-10 first:mt-0'>
+ {Object.keys(segmentationRuleMap).map((field) => {
+ return <FieldInfo
+ key={field}
+ label={segmentationRuleMap[field as keyof typeof segmentationRuleMap]}
+ displayedValue={String(getValue(field))}
+ />
+ })}
+ </div>
+}
+
+const EmbeddingDetail: FC<Props> = ({ detail, stopPosition = 'top', datasetId: dstId, documentId: docId, indexingType }) => {
+ const onTop = stopPosition === 'top'
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+
+ const { datasetId = '', documentId = '' } = useContext(DocumentContext)
+ const { indexingTechnique } = useContext(DatasetDetailContext)
+ const localDatasetId = dstId ?? datasetId
+ const localDocumentId = docId ?? documentId
+ const localIndexingTechnique = indexingType ?? indexingTechnique
+
+ const { data: indexingStatusDetail, error: indexingStatusErr, mutate: statusMutate } = useSWR({
+ action: 'fetchIndexingStatus',
+ datasetId: localDatasetId,
+ documentId: localDocumentId,
+ }, apiParams => fetchIndexingStatus(omit(apiParams, 'action')), {
+ refreshInterval: 5000,
+ revalidateOnFocus: false,
+ })
+
+ const { data: indexingEstimateDetail, error: indexingEstimateErr } = useSWR({
+ action: 'fetchIndexingEstimate',
+ datasetId: localDatasetId,
+ documentId: localDocumentId,
+ }, apiParams => fetchIndexingEstimate(omit(apiParams, 'action')), {
+ revalidateOnFocus: false
+ })
+
+ const { data: ruleDetail, error: ruleError } = useSWR({
+ action: 'fetchProcessRule',
+ params: { documentId: localDocumentId }
+ }, apiParams => fetchProcessRule(omit(apiParams, 'action')), {
+ revalidateOnFocus: false,
+ })
+
+ const [showModal, setShowModal] = useState(false)
+ const modalShowHandle = () => setShowModal(true)
+ const modalCloseHandle = () => setShowModal(false)
+ const router = useRouter()
+ const navToDocument = () => {
+ router.push(`/datasets/${localDatasetId}/documents/${localDocumentId}`)
+ }
+
+ const isEmbedding = useMemo(() => ['indexing', 'splitting', 'parsing', 'cleaning'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
+ const isEmbeddingCompleted = useMemo(() => ['completed'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
+ const isEmbeddingPaused = useMemo(() => ['paused'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
+ const isEmbeddingError = useMemo(() => ['error'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
+ const percent = useMemo(() => {
+ const completedCount = indexingStatusDetail?.completed_segments || 0
+ const totalCount = indexingStatusDetail?.total_segments || 0
+ if (totalCount === 0) return 0
+ const percent = Math.round(completedCount * 100 / totalCount)
+ return percent > 100 ? 100 : percent
+ }, [indexingStatusDetail])
+
+ const handleSwitch = async () => {
+ const opApi = isEmbedding ? pauseDocIndexing : resumeDocIndexing
+ const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId: localDatasetId, documentId: localDocumentId }) as Promise<CommonResponse>)
+ if (!e) {
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ statusMutate()
+ } else {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ }
+ }
+
+ // if (!ruleDetail && !error)
+ // return <Loading type='app' />
+
+ return (
+ <>
+ <div className={s.embeddingStatus}>
+ {isEmbedding && t('datasetDocuments.embedding.processing')}
+ {isEmbeddingCompleted && t('datasetDocuments.embedding.completed')}
+ {isEmbeddingPaused && t('datasetDocuments.embedding.paused')}
+ {isEmbeddingError && t('datasetDocuments.embedding.error')}
+ {onTop && isEmbedding && (
+ <Button onClick={handleSwitch} className={s.opBtn}>
+ <StopIcon className={s.opIcon} />
+ {t('datasetDocuments.embedding.stop')}
+ </Button>
+ )}
+ {onTop && isEmbeddingPaused && (
+ <Button onClick={handleSwitch} className={s.opBtn}>
+ <ResumeIcon className={s.opIcon} />
+ {t('datasetDocuments.embedding.resume')}
+ </Button>
+ )}
+ </div>
+ {/* progress bar */}
+ <div className={s.progressContainer}>
+ {new Array(10).fill('').map((_, idx) => <div
+ key={idx}
+ className={cn(s.progressBgItem, isEmbedding ? 'bg-primary-50' : 'bg-gray-100')}
+ />)}
+ <div className={
+ cn('rounded-l-md',
+ s.progressBar,
+ (isEmbedding || isEmbeddingCompleted) && s.barProcessing,
+ (isEmbeddingPaused || isEmbeddingError) && s.barPaused,
+ indexingStatusDetail?.indexing_status === 'completed' && 'rounded-r-md')
+ }
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ <div className={s.progressData}>
+ <div>{t('datasetDocuments.embedding.segments')} {indexingStatusDetail?.completed_segments}/{indexingStatusDetail?.total_segments} · {percent}%</div>
+ {localIndexingTechnique === 'high_quaility' && (
+ <div className='flex items-center'>
+ <div className={cn(s.commonIcon, s.highIcon)} />
+ {t('datasetDocuments.embedding.highQuality')} · {t('datasetDocuments.embedding.estimate')}
+ <span className={s.tokens}>{formatNumber(indexingEstimateDetail?.tokens || 0)}</span>tokens
+ (<span className={s.price}>${formatNumber(indexingEstimateDetail?.total_price || 0)}</span>)
+ </div>
+ )}
+ {localIndexingTechnique === 'economy' && (
+ <div className='flex items-center'>
+ <div className={cn(s.commonIcon, s.economyIcon)} />
+ {t('datasetDocuments.embedding.economy')} · {t('datasetDocuments.embedding.estimate')}
+ <span className={s.tokens}>0</span>tokens
+ </div>
+ )}
+ </div>
+ <RuleDetail sourceData={ruleDetail} docName={detail?.name} />
+ {!onTop && (
+ <div className='flex items-center gap-2 mt-10'>
+ {isEmbedding && (
+ <Button onClick={modalShowHandle} className='w-fit'>
+ {t('datasetCreation.stepThree.stop')}
+ </Button>
+ )}
+ {isEmbeddingPaused && (
+ <Button onClick={handleSwitch} className='w-fit'>
+ {t('datasetCreation.stepThree.resume')}
+ </Button>
+ )}
+ <Button className='w-fit' type='primary' onClick={navToDocument}>
+ <span>{t('datasetCreation.stepThree.navTo')}</span>
+ <ArrowRightIcon className='h-4 w-4 ml-2 stroke-current stroke-1' />
+ </Button>
+ </div>
+ )}
+ {onTop && <>
+ <Divider />
+ <div className={s.previewTip}>{t('datasetDocuments.embedding.previewTip')}</div>
+ <div className={style.cardWrapper}>
+ {[1, 2, 3].map((v) => (
+ <SegmentCard loading={true} detail={{ position: v } as any} />
+ ))}
+ </div>
+ </>}
+ <StopEmbeddingModal show={showModal} onConfirm={handleSwitch} onHide={modalCloseHandle} />
+ </>
+ )
+}
+
+export default EmbeddingDetail
diff --git a/web/app/components/datasets/documents/detail/embedding/style.module.css b/web/app/components/datasets/documents/detail/embedding/style.module.css
new file mode 100644
index 00000000000..6dc1a5e80b8
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/embedding/style.module.css
@@ -0,0 +1,59 @@
+.progressBar {
+ @apply absolute top-0 h-4;
+}
+.barPaused {
+ background: linear-gradient(
+ 270deg,
+ rgba(208, 213, 221, 0.8) -2.21%,
+ rgba(208, 213, 221, 0.5) 100%
+ );
+}
+.barProcessing {
+ background: linear-gradient(
+ 90deg,
+ rgba(41, 112, 255, 0.9) 0%,
+ rgba(21, 94, 239, 0.9) 100%
+ );
+}
+.opBtn {
+ @apply w-fit h-6 text-xs px-2 py-1 text-gray-700 rounded-md !important;
+}
+.opIcon {
+ @apply mr-1 stroke-current text-gray-700 w-3 h-3;
+}
+.progressContainer {
+ @apply relative flex mb-2 h-4 rounded-md w-full;
+}
+.progressBgItem {
+ @apply flex-1 border-r border-r-white first:rounded-l-md;
+}
+.progressBgItem:nth-last-child(2) {
+ @apply rounded-r-md;
+}
+.progressData {
+ @apply w-full flex justify-between items-center text-xs text-gray-700;
+}
+.previewTip {
+ @apply pb-1 pt-12 text-gray-900 text-sm font-medium;
+}
+.embeddingStatus {
+ @apply flex items-center justify-between text-gray-900 font-medium text-base mb-3;
+}
+.commonIcon {
+ @apply w-3 h-3 mr-1 inline-block align-middle;
+}
+.highIcon {
+ mask-image: url(../../assets/star.svg);
+ @apply bg-orange-500;
+}
+.economyIcon {
+ background-color: #444ce7;
+ mask-image: url(../../assets/normal.svg);
+}
+.tokens {
+ @apply text-xs font-medium px-1;
+}
+.price {
+ color: #f79009;
+ @apply text-xs font-medium;
+}
diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsx
new file mode 100644
index 00000000000..b865a4f4caf
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/index.tsx
@@ -0,0 +1,121 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState } from 'react'
+import useSWR from 'swr'
+import { ArrowLeftIcon } from '@heroicons/react/24/solid'
+import { createContext } from 'use-context-selector'
+import { useTranslation } from 'react-i18next'
+import { useRouter } from 'next/navigation'
+import { omit } from 'lodash-es'
+import cn from 'classnames'
+import Divider from '@/app/components/base/divider'
+import Loading from '@/app/components/base/loading'
+import { fetchDocumentDetail, MetadataType } from '@/service/datasets'
+import { OperationAction, StatusItem } from '../list'
+import Completed from './completed'
+import Embedding from './embedding'
+import Metadata from './metadata'
+import s from '../style.module.css'
+import style from './style.module.css'
+
+export const BackCircleBtn: FC<{ onClick: () => void }> = ({ onClick }) => {
+ return (
+ <div onClick={onClick} className={'rounded-full w-8 h-8 flex justify-center items-center border-gray-100 cursor-pointer border hover:border-gray-300 shadow-[0px_12px_16px_-4px_rgba(16,24,40,0.08),0px_4px_6px_-2px_rgba(16,24,40,0.03)]'}>
+ <ArrowLeftIcon className='text-primary-600 fill-current stroke-current h-4 w-4' />
+ </div>
+ )
+}
+
+export const DocumentContext = createContext<{ datasetId?: string; documentId?: string }>({})
+
+type DocumentTitleProps = {
+ extension?: string;
+ name?: string;
+ iconCls?: string;
+ textCls?: string;
+ wrapperCls?: string;
+}
+
+export const DocumentTitle: FC<DocumentTitleProps> = ({ extension, name, iconCls, textCls, wrapperCls }) => {
+ const localExtension = extension?.toLowerCase() || name?.split('.')?.pop()?.toLowerCase()
+ return <div className={cn('flex items-center justify-start flex-1', wrapperCls)}>
+ <div className={cn(s[`${localExtension || 'txt'}Icon`], style.titleIcon, iconCls)}></div>
+ <span className={cn('font-semibold text-lg text-gray-900 ml-1', textCls)}> {name || '--'}</span>
+ </div>
+}
+
+type Props = {
+ datasetId: string
+ documentId: string
+}
+
+const DocumentDetail: FC<Props> = ({ datasetId, documentId }) => {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const [showMetadata, setShowMetadata] = useState(true)
+
+ const { data: documentDetail, error, mutate: detailMutate } = useSWR({
+ action: 'fetchDocumentDetail',
+ datasetId,
+ documentId,
+ params: { metadata: 'without' as MetadataType }
+ }, apiParams => fetchDocumentDetail(omit(apiParams, 'action')))
+
+ const { data: documentMetadata, error: metadataErr, mutate: metadataMutate } = useSWR({
+ action: 'fetchDocumentDetail',
+ datasetId,
+ documentId,
+ params: { metadata: 'only' as MetadataType }
+ }, apiParams => fetchDocumentDetail(omit(apiParams, 'action')))
+
+ const backToPrev = () => {
+ router.push(`/datasets/${datasetId}/documents`)
+ }
+
+ const isDetailLoading = !documentDetail && !error
+ const isMetadataLoading = !documentMetadata && !metadataErr
+
+ const embedding = ['queuing', 'indexing', 'paused'].includes((documentDetail?.display_status || '').toLowerCase())
+
+ return (
+ <DocumentContext.Provider value={{ datasetId, documentId }}>
+ <div className='flex flex-col h-full'>
+ <div className='flex h-16 border-b-gray-100 border-b items-center p-4'>
+ <BackCircleBtn onClick={backToPrev} />
+ <Divider className='!h-4' type='vertical' />
+ <DocumentTitle extension={documentDetail?.data_source_info?.upload_file?.extension} name={documentDetail?.name} />
+ <StatusItem status={documentDetail?.display_status || 'available'} scene='detail' />
+ <OperationAction
+ scene='detail'
+ detail={{
+ enabled: documentDetail?.enabled || false,
+ archived: documentDetail?.archived || false,
+ id: documentId
+ }}
+ datasetId={datasetId}
+ onUpdate={detailMutate}
+ className='!w-[216px]'
+ />
+ <button
+ className={cn(style.layoutRightIcon, showMetadata ? style.iconShow : style.iconClose)}
+ onClick={() => setShowMetadata(!showMetadata)}
+ />
+ </div>
+ <div className='flex flex-row flex-1' style={{ height: 'calc(100% - 4rem)' }}>
+ {isDetailLoading ? <Loading type='app' /> :
+ <div className={`box-border h-full w-full overflow-y-scroll ${embedding ? 'py-12 px-16' : 'pb-[30px] pt-3 px-6'}`}>
+ {embedding ? <Embedding detail={documentDetail} /> : <Completed />}
+ </div>
+ }
+ {showMetadata && <Metadata
+ docDetail={{ ...documentDetail, ...documentMetadata } as any}
+ loading={isMetadataLoading}
+ onUpdate={metadataMutate}
+ />}
+ </div>
+ </div>
+ </DocumentContext.Provider>
+ )
+}
+
+export default DocumentDetail
diff --git a/web/app/components/datasets/documents/detail/metadata/index.tsx b/web/app/components/datasets/documents/detail/metadata/index.tsx
new file mode 100644
index 00000000000..aebc35c8062
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/metadata/index.tsx
@@ -0,0 +1,363 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState, useEffect } from 'react'
+import { PencilIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import { get } from 'lodash-es'
+import cn from 'classnames'
+import Input from '@/app/components/base/input'
+import Button from '@/app/components/base/button'
+import Tooltip from '@/app/components/base/tooltip'
+import Radio from '@/app/components/base/radio'
+import Divider from '@/app/components/base/divider'
+import { ToastContext } from '@/app/components/base/toast'
+import { SimpleSelect } from '@/app/components/base/select'
+import Loading from '@/app/components/base/loading'
+import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
+import { asyncRunSafe, getTextWidthWithCanvas } from '@/utils'
+import { modifyDocMetadata } from '@/service/datasets'
+import type { CommonResponse } from '@/models/common'
+import type { FullDocumentDetail, DocType } from '@/models/datasets'
+import { CUSTOMIZABLE_DOC_TYPES } from '@/models/datasets'
+import type { metadataType, inputType } from '@/hooks/use-metadata'
+import { useMetadataMap, useLanguages, useBookCategories, usePersonalDocCategories, useBusinessDocCategories } from '@/hooks/use-metadata'
+import { DocumentContext } from '../index'
+import s from './style.module.css'
+
+const map2Options = (map: { [key: string]: string }) => {
+ return Object.keys(map).map(key => ({ value: key, name: map[key] }))
+}
+
+type IFieldInfoProps = {
+ label: string
+ value?: string
+ displayedValue?: string
+ defaultValue?: string
+ showEdit?: boolean
+ inputType?: inputType
+ selectOptions?: Array<{ value: string; name: string }>
+ onUpdate?: (v: any) => void
+}
+
+export const FieldInfo: FC<IFieldInfoProps> = ({
+ label,
+ value = '',
+ displayedValue = '',
+ defaultValue,
+ showEdit = false,
+ inputType = 'input',
+ selectOptions = [],
+ onUpdate
+}) => {
+ const { t } = useTranslation()
+ const textNeedWrap = getTextWidthWithCanvas(displayedValue) > 190
+ const editAlignTop = showEdit && inputType === 'textarea'
+ const readAlignTop = !showEdit && textNeedWrap
+
+ return (
+ <div className={cn(s.fieldInfo, editAlignTop && `!items-start`, readAlignTop && '!items-start pt-1')}>
+ <div className={cn(s.label, editAlignTop && 'pt-1')}>{label}</div>
+ <div className={s.value}>
+ {!showEdit
+ ? displayedValue
+ : inputType === 'select'
+ ? <SimpleSelect
+ onSelect={({ value }) => onUpdate && onUpdate(value as string)}
+ items={selectOptions}
+ defaultValue={value}
+ className={s.select}
+ wrapperClassName={s.selectWrapper}
+ placeholder={`${t('datasetDocuments.metadata.placeholder.select')}${label}`}
+ />
+ : inputType === 'textarea'
+ ? <AutoHeightTextarea
+ onChange={e => onUpdate && onUpdate(e.target.value)}
+ value={value}
+ className={s.textArea}
+ placeholder={`${t('datasetDocuments.metadata.placeholder.add')}${label}`}
+ />
+ : <Input
+ className={s.input}
+ onChange={onUpdate}
+ value={value}
+ defaultValue={defaultValue}
+ placeholder={`${t('datasetDocuments.metadata.placeholder.add')}${label}`}
+ />
+ }
+ </div>
+ </div>
+ )
+}
+
+const TypeIcon: FC<{ iconName: string; className?: string }> = ({ iconName, className = '' }) => {
+ return <div className={cn(s.commonIcon, s[`${iconName}Icon`], className)}
+ />
+}
+
+const IconButton: FC<{
+ type: DocType
+ isChecked: boolean
+}> = ({ type, isChecked = false }) => {
+ const metadataMap = useMetadataMap()
+
+ return (
+ <Tooltip content={metadataMap[type].text} selector={`doc-metadata-${type}`}>
+ <button className={cn(s.iconWrapper, 'group', isChecked ? s.iconCheck : '')}>
+ <TypeIcon
+ iconName={metadataMap[type].iconName || ''}
+ className={`group-hover:bg-primary-600 ${isChecked ? '!bg-primary-600' : ''}`}
+ />
+ </button>
+ </Tooltip>
+ )
+}
+
+type IMetadataProps = {
+ docDetail?: FullDocumentDetail
+ loading: boolean
+ onUpdate: () => void
+}
+
+const Metadata: FC<IMetadataProps> = ({ docDetail, loading, onUpdate }) => {
+ const { doc_metadata = {} } = docDetail || {}
+ const doc_type = docDetail?.doc_type || ''
+
+ const { t } = useTranslation()
+ const metadataMap = useMetadataMap()
+ const languageMap = useLanguages()
+ const bookCategoryMap = useBookCategories()
+ const personalDocCategoryMap = usePersonalDocCategories()
+ const businessDocCategoryMap = useBusinessDocCategories()
+ const [editStatus, setEditStatus] = useState(!doc_type) // if no documentType, in editing status by default
+ // the initial values are according to the documentType
+ const [metadataParams, setMetadataParams] = useState<{
+ documentType?: DocType | '';
+ metadata: { [key: string]: string }
+ }>(
+ doc_type ? {
+ documentType: doc_type,
+ metadata: doc_metadata || {}
+ } : { metadata: {} })
+ const [showDocTypes, setShowDocTypes] = useState(!doc_type) // whether show doc types
+ const [tempDocType, setTempDocType] = useState<DocType | undefined | ''>('') // for remember icon click
+ const [saveLoading, setSaveLoading] = useState(false)
+
+ const { notify } = useContext(ToastContext)
+ const { datasetId = '', documentId = '' } = useContext(DocumentContext)
+
+ useEffect(() => {
+ if (docDetail?.doc_type) {
+ setEditStatus(false)
+ setShowDocTypes(false)
+ setTempDocType(docDetail?.doc_type)
+ setMetadataParams({
+ documentType: docDetail?.doc_type,
+ metadata: docDetail?.doc_metadata || {}
+ })
+ }
+ }, [docDetail?.doc_type])
+
+ // confirm doc type
+ const confirmDocType = () => {
+ if (!tempDocType) return;
+ setMetadataParams({
+ documentType: tempDocType,
+ metadata: tempDocType === metadataParams.documentType ? metadataParams.metadata : {} // change doc type, clear metadata
+ })
+ setEditStatus(true)
+ setShowDocTypes(false)
+ }
+
+ // cancel doc type
+ const cancelDocType = () => {
+ setTempDocType(metadataParams.documentType)
+ setEditStatus(true)
+ setShowDocTypes(false)
+ }
+
+ // show doc type select
+ const renderSelectDocType = () => {
+ const { documentType } = metadataParams
+
+ return (
+ <>
+ {!doc_type && !documentType && <>
+ <div className={s.desc}>{t('datasetDocuments.metadata.desc')}</div>
+ </>}
+ <div className={s.operationWrapper}>
+ {!doc_type && !documentType && <>
+ <span className={s.title}>{t('datasetDocuments.metadata.docTypeSelectTitle')}</span>
+ </>}
+ {documentType && <>
+ <span className={s.title}>{t('datasetDocuments.metadata.docTypeChangeTitle')}</span>
+ <span className={s.changeTip}>{t('datasetDocuments.metadata.docTypeSelectWarning')}</span>
+ </>}
+ <Radio.Group value={tempDocType ?? documentType} onChange={setTempDocType} className={s.radioGroup}>
+ {CUSTOMIZABLE_DOC_TYPES.map((type) => {
+ const currValue = tempDocType ?? documentType
+ return <Radio value={type} className={`${s.radio} ${currValue === type ? 'shadow-none' : ''}`}>
+ <IconButton
+ type={type}
+ isChecked={currValue === type}
+ />
+ </Radio>
+ })}
+ </Radio.Group>
+ {!doc_type && !documentType && (
+ <Button type='primary'
+ onClick={confirmDocType}
+ disabled={!tempDocType}
+ >
+ {t('datasetDocuments.metadata.firstMetaAction')}
+ </Button>
+ )}
+ {documentType && <div className={s.opBtnWrapper}>
+ <Button onClick={confirmDocType} className={`${s.opBtn} ${s.opSaveBtn}`} type='primary' >{t('common.operation.save')}</Button>
+ <Button onClick={cancelDocType} className={`${s.opBtn} ${s.opCancelBtn}`}>{t('common.operation.cancel')}</Button>
+ </div>}
+ </div >
+ </>
+ )
+ }
+
+ // show metadata info and edit
+ const renderFieldInfos = ({ mainField = 'book', canEdit }: { mainField?: metadataType | ''; canEdit?: boolean }) => {
+ if (!mainField) return null
+ const fieldMap = metadataMap[mainField]?.subFieldsMap
+ const sourceData = ['originInfo', 'technicalParameters'].includes(mainField) ? docDetail : metadataParams.metadata
+
+ const getTargetMap = (field: string) => {
+ if (field === 'language') return languageMap
+ if (field === 'category' && mainField === 'book') {
+ return bookCategoryMap
+ }
+ if (field === 'document_type') {
+ if (mainField === 'personal_document') return personalDocCategoryMap
+ if (mainField === 'business_document') return businessDocCategoryMap
+ }
+ return {} as any
+ }
+
+ const getTargetValue = (field: string) => {
+ const val = get(sourceData, field, '')
+ if (!val && val !== 0) return '-'
+ if (fieldMap[field]?.inputType === 'select')
+ return getTargetMap(field)[val]
+ if (fieldMap[field]?.render)
+ return fieldMap[field]?.render?.(val, field === 'hit_count' ? get(sourceData, 'segment_count', 0) as number : undefined)
+ return val
+ }
+
+ return <div className='flex flex-col gap-1'>
+ {Object.keys(fieldMap).map((field) => {
+ return <FieldInfo
+ key={fieldMap[field]?.label}
+ label={fieldMap[field]?.label}
+ displayedValue={getTargetValue(field)}
+ value={get(sourceData, field, '')}
+ inputType={fieldMap[field]?.inputType || 'input'}
+ showEdit={canEdit}
+ onUpdate={(val) => {
+ setMetadataParams(pre => ({ ...pre, metadata: { ...pre.metadata, [field]: val } }))
+ }}
+ selectOptions={map2Options(getTargetMap(field))}
+ />
+ })}
+ </div>
+ }
+
+ const enabledEdit = () => {
+ setEditStatus(true)
+ }
+
+ const onCancel = () => {
+ setMetadataParams({ documentType: doc_type || '', metadata: { ...(docDetail?.doc_metadata || {}) } })
+ setEditStatus(!doc_type)
+ if (!doc_type)
+ setShowDocTypes(true)
+ }
+
+ const onSave = async () => {
+ console.log('metadataParams:', metadataParams)
+ setSaveLoading(true)
+ const [e] = await asyncRunSafe<CommonResponse>(modifyDocMetadata({
+ datasetId,
+ documentId,
+ body: {
+ doc_type: metadataParams.documentType || doc_type || '',
+ doc_metadata: metadataParams.metadata
+ }
+ }) as Promise<CommonResponse>)
+ if (!e)
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ else
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ onUpdate?.()
+ setEditStatus(false)
+ setSaveLoading(false)
+ }
+
+ return (
+ <div className={`${s.main} ${editStatus ? 'bg-white' : 'bg-gray-25'}`}>
+ {loading ? <Loading type='app' /> : (
+ <>
+ <div className={s.titleWrapper}>
+ <span className={s.title}>{t('datasetDocuments.metadata.title')}</span>
+ {!editStatus
+ ? <Button onClick={enabledEdit} className={`${s.opBtn} ${s.opEditBtn}`}>
+ <PencilIcon className={s.opIcon} />
+ {t('common.operation.edit')}
+ </Button>
+ : showDocTypes
+ ? null
+ : <div className={s.opBtnWrapper}>
+ <Button onClick={onCancel} className={`${s.opBtn} ${s.opCancelBtn}`}>{t('common.operation.cancel')}</Button>
+ <Button onClick={onSave}
+ className={`${s.opBtn} ${s.opSaveBtn}`}
+ type='primary'
+ loading={saveLoading}
+ >
+ {t('common.operation.save')}
+ </Button>
+ </div>}
+ </div>
+ {/* show selected doc type and changing entry */}
+ {!editStatus
+ ? <div className={s.documentTypeShow}>
+ <TypeIcon iconName={metadataMap[doc_type || 'book']?.iconName || ''} className={s.iconShow} />
+ {metadataMap[doc_type || 'book'].text}
+ </div>
+ : showDocTypes
+ ? null
+ : <div className={s.documentTypeShow}>
+ {metadataParams.documentType && <>
+ <TypeIcon iconName={metadataMap[metadataParams.documentType || 'book'].iconName || ''} className={s.iconShow} />
+ {metadataMap[metadataParams.documentType || 'book'].text}
+ {editStatus && <div className='inline-flex items-center gap-1 ml-1'>
+ ·
+ <div
+ onClick={() => { setShowDocTypes(true) }}
+ className='cursor-pointer hover:text-[#155EEF]'
+ >
+ {t('common.operation.change')}
+ </div>
+ </div>}
+ </>}
+ </div>
+ }
+ {(!doc_type && showDocTypes) ? null : <Divider />}
+ {showDocTypes ? renderSelectDocType() : renderFieldInfos({ mainField: metadataParams.documentType, canEdit: editStatus })}
+ {/* show fixed fields */}
+ <Divider />
+ {renderFieldInfos({ mainField: 'originInfo', canEdit: false })}
+ <div className={`${s.title} mt-8`}>{metadataMap.technicalParameters.text}</div>
+ <Divider />
+ {renderFieldInfos({ mainField: 'technicalParameters', canEdit: false })}
+ </>
+ )}
+ </div>
+ )
+}
+
+export default Metadata
diff --git a/web/app/components/datasets/documents/detail/metadata/style.module.css b/web/app/components/datasets/documents/detail/metadata/style.module.css
new file mode 100644
index 00000000000..ca01bdb95af
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/metadata/style.module.css
@@ -0,0 +1,114 @@
+.main {
+ @apply w-96 xl:w-[360px] flex-shrink-0 px-6 py-5 overflow-y-auto border-l-gray-100 border-l;
+}
+.operationWrapper {
+ @apply flex flex-col items-center gap-4 mt-7 mb-8;
+}
+.iconWrapper {
+ @apply box-border cursor-pointer h-8 w-8 inline-flex items-center justify-center;
+ @apply border-[#EAECF5] border rounded-lg hover:border-primary-200 hover:bg-primary-25 hover:shadow-[0px_4px_8px_-2px_rgba(16,24,40,0.1),0px_2px_4px_-2px_rgba(16,24,40,0.06)];
+}
+.icon {
+ @apply h-4 w-4 stroke-current stroke-[2px] text-gray-700 group-hover:stroke-primary-600;
+}
+.iconCheck {
+ @apply border-primary-400 border-[1.5px] bg-primary-25 shadow-[0px_1px_3px_rgba(16,24,40,0.1),0px_1px_2px_rgba(16,24,40,0.06)] !important;
+}
+.commonIcon {
+ @apply w-4 h-4 inline-block align-middle bg-gray-700 hover:bg-primary-600;
+}
+.bookOpenIcon {
+ mask-image: url(../../assets/bookOpen.svg);
+}
+.globeIcon {
+ mask-image: url(../../assets/globe.svg);
+}
+.graduationHatIcon {
+ mask-image: url(../../assets/graduationHat.svg);
+}
+.fileIcon {
+ mask-image: url(../../assets/file.svg);
+}
+.briefcaseIcon {
+ mask-image: url(../../assets/briefcase.svg);
+}
+.atSignIcon {
+ mask-image: url(../../assets/atSign.svg);
+}
+.messageTextCircleIcon {
+ mask-image: url(../../assets/messageTextCircle.svg);
+}
+.radioGroup {
+ @apply !bg-transparent !gap-2;
+}
+.radio {
+ @apply !p-0 !mr-0 hover:bg-transparent !rounded-lg;
+}
+.title {
+ @apply text-sm text-gray-800 font-medium leading-6;
+}
+.titleWrapper {
+ @apply flex items-center justify-between;
+}
+.desc {
+ @apply text-gray-500 text-xs;
+}
+.fieldInfo {
+ /* height: 1.75rem; */
+ min-height: 1.75rem;
+ @apply flex flex-row items-center gap-4;
+}
+.fieldInfo > .label {
+ @apply w-2/5 max-w-[128px] text-gray-500 text-xs font-medium overflow-hidden text-ellipsis whitespace-nowrap;
+}
+.fieldInfo > .value {
+ overflow-wrap: anywhere;
+ @apply w-3/5 text-gray-700 font-normal text-xs;
+}
+.changeTip {
+ @apply text-[#D92D20] text-xs text-center;
+}
+.opBtnWrapper {
+ @apply flex items-center justify-center gap-1;
+}
+.opBtn {
+ @apply h-6 w-14 px-0 text-xs font-medium rounded-md !important;
+}
+.opEditBtn {
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ @apply border-[0.5px] border-gray-200 bg-white !important;
+}
+.opCancelBtn {
+ @apply border-none bg-gray-50 font-medium text-gray-700 hover:bg-gray-100 !important;
+}
+.opSaveBtn {
+ @apply border-primary-700 border-[0.5px] font-medium hover:border-none !important;
+}
+.opIcon {
+ @apply h-3 w-3 stroke-current stroke-2 mr-1;
+}
+.select {
+ @apply h-7 py-0 pl-2 text-xs bg-gray-50 hover:bg-gray-100 rounded-md shadow-none !important;
+}
+.selectWrapper {
+ @apply !h-7 w-full
+}
+.selectWrapper ul {
+ @apply text-xs
+}
+.selectWrapper li {
+ @apply flex items-center h-8
+}
+.documentTypeShow {
+ @apply flex items-center text-xs text-gray-500;
+}
+.iconShow {
+ mask-size: contain;
+ @apply w-3 h-3 bg-gray-500 hover:bg-none mr-1 !important;
+}
+.textArea {
+ @apply placeholder:text-gray-400 bg-gray-50 px-2 py-1 caret-primary-600 rounded-md hover:bg-gray-100 focus-visible:outline-none focus-visible:bg-white focus-visible:border focus-visible:border-gray-300 hover:shadow-[0_1px_2px_rgba(16,24,40,0.05);];
+}
+.input {
+ @apply bg-gray-50 hover:bg-gray-100 focus-visible:bg-white !important
+}
diff --git a/web/app/components/datasets/documents/detail/style.module.css b/web/app/components/datasets/documents/detail/style.module.css
new file mode 100644
index 00000000000..69295ab31c3
--- /dev/null
+++ b/web/app/components/datasets/documents/detail/style.module.css
@@ -0,0 +1,15 @@
+.titleIcon {
+ background-position-x: center;
+ background-repeat: no-repeat;
+ background-size: 28px 28px;
+ @apply h-6 w-6 !important;
+}
+.layoutRightIcon {
+ @apply w-8 h-8 ml-2 box-border border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer hover:shadow-[0_1px_2px_rgba(16,24,40,0.05)];
+}
+.iconShow {
+ background: center center url(../assets/layoutRightShow.svg) no-repeat;
+}
+.iconClose {
+ background: center center url(../assets/layoutRightClose.svg) no-repeat;
+}
diff --git a/web/app/components/datasets/documents/index.tsx b/web/app/components/datasets/documents/index.tsx
new file mode 100644
index 00000000000..6434dcedebc
--- /dev/null
+++ b/web/app/components/datasets/documents/index.tsx
@@ -0,0 +1,135 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState, useMemo } from 'react'
+import useSWR from 'swr'
+import { useTranslation } from 'react-i18next'
+import { useRouter } from 'next/navigation'
+import { debounce } from 'lodash-es'
+// import Link from 'next/link'
+import { PlusIcon } from '@heroicons/react/24/solid'
+import { omit } from 'lodash-es'
+import List from './list'
+import s from './style.module.css'
+import Loading from '@/app/components/base/loading'
+import Button from '@/app/components/base/button'
+import Input from '@/app/components/base/input'
+import Pagination from '@/app/components/base/pagination'
+import { get } from '@/service/base'
+import { fetchDocuments } from '@/service/datasets'
+
+// Custom page count is not currently supported.
+const limit = 15
+
+const FolderPlusIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M10.8332 5.83333L9.90355 3.9741C9.63601 3.439 9.50222 3.17144 9.30265 2.97597C9.12615 2.80311 8.91344 2.67164 8.6799 2.59109C8.41581 2.5 8.11668 2.5 7.51841 2.5H4.33317C3.39975 2.5 2.93304 2.5 2.57652 2.68166C2.26292 2.84144 2.00795 3.09641 1.84816 3.41002C1.6665 3.76654 1.6665 4.23325 1.6665 5.16667V5.83333M1.6665 5.83333H14.3332C15.7333 5.83333 16.4334 5.83333 16.9681 6.10582C17.4386 6.3455 17.821 6.72795 18.0607 7.19836C18.3332 7.73314 18.3332 8.4332 18.3332 9.83333V13.5C18.3332 14.9001 18.3332 15.6002 18.0607 16.135C17.821 16.6054 17.4386 16.9878 16.9681 17.2275C16.4334 17.5 15.7333 17.5 14.3332 17.5H5.6665C4.26637 17.5 3.56631 17.5 3.03153 17.2275C2.56112 16.9878 2.17867 16.6054 1.93899 16.135C1.6665 15.6002 1.6665 14.9001 1.6665 13.5V5.83333ZM9.99984 14.1667V9.16667M7.49984 11.6667H12.4998" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+const ThreeDotsIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M5 6.5V5M8.93934 7.56066L10 6.5M10.0103 11.5H11.5103" stroke="#374151" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+const NotionIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <g clip-path="url(#clip0_2164_11263)">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M3.5725 18.2611L1.4229 15.5832C0.905706 14.9389 0.625 14.1466 0.625 13.3312V3.63437C0.625 2.4129 1.60224 1.39936 2.86295 1.31328L12.8326 0.632614C13.5569 0.583164 14.2768 0.775682 14.8717 1.17794L18.3745 3.5462C19.0015 3.97012 19.375 4.66312 19.375 5.40266V16.427C19.375 17.6223 18.4141 18.6121 17.1798 18.688L6.11458 19.3692C5.12958 19.4298 4.17749 19.0148 3.5725 18.2611Z" fill="white" />
+ <path d="M7.03006 8.48669V8.35974C7.03006 8.03794 7.28779 7.77104 7.61997 7.74886L10.0396 7.58733L13.3857 12.5147V8.19009L12.5244 8.07528V8.01498C12.5244 7.68939 12.788 7.42074 13.1244 7.4035L15.326 7.29073V7.60755C15.326 7.75628 15.2154 7.88349 15.0638 7.90913L14.534 7.99874V15.0023L13.8691 15.231C13.3136 15.422 12.6952 15.2175 12.3772 14.7377L9.12879 9.83574V14.5144L10.1287 14.7057L10.1147 14.7985C10.0711 15.089 9.82028 15.3087 9.51687 15.3222L7.03006 15.4329C6.99718 15.1205 7.23132 14.841 7.55431 14.807L7.88143 14.7727V8.53453L7.03006 8.48669Z" fill="black" />
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M12.9218 1.85424L2.95217 2.53491C2.35499 2.57568 1.89209 3.05578 1.89209 3.63437V13.3312C1.89209 13.8748 2.07923 14.403 2.42402 14.8325L4.57362 17.5104C4.92117 17.9434 5.46812 18.1818 6.03397 18.147L17.0991 17.4658C17.6663 17.4309 18.1078 16.9762 18.1078 16.427V5.40266C18.1078 5.06287 17.9362 4.74447 17.6481 4.54969L14.1453 2.18143C13.7883 1.94008 13.3564 1.82457 12.9218 1.85424ZM3.44654 3.78562C3.30788 3.68296 3.37387 3.46909 3.54806 3.4566L12.9889 2.77944C13.2897 2.75787 13.5886 2.8407 13.8318 3.01305L15.7261 4.35508C15.798 4.40603 15.7642 4.51602 15.6752 4.52086L5.67742 5.0646C5.37485 5.08106 5.0762 4.99217 4.83563 4.81406L3.44654 3.78562ZM5.20848 6.76919C5.20848 6.4444 5.47088 6.1761 5.80642 6.15783L16.3769 5.58216C16.7039 5.56435 16.9792 5.81583 16.9792 6.13239V15.6783C16.9792 16.0025 16.7177 16.2705 16.3829 16.2896L5.8793 16.8872C5.51537 16.9079 5.20848 16.6283 5.20848 16.2759V6.76919Z" fill="black" />
+ </g>
+ <defs>
+ <clipPath id="clip0_2164_11263">
+ <rect width="20" height="20" fill="white" />
+ </clipPath>
+ </defs>
+ </svg>
+}
+
+const EmptyElement: FC<{ onClick: () => void; type?: 'upload' | 'sync' }> = ({ onClick, type = 'upload' }) => {
+ const { t } = useTranslation()
+ return <div className={s.emptyWrapper}>
+ <div className={s.emptyElement}>
+ <div className={s.emptySymbolIconWrapper}>
+ {type === 'upload' ? <FolderPlusIcon /> : <NotionIcon />}
+ </div>
+ <span className={s.emptyTitle}>{t('datasetDocuments.list.empty.title')}<ThreeDotsIcon className='inline relative -top-3 -left-1.5' /></span>
+ <div className={s.emptyTip}>
+ {t(`datasetDocuments.list.empty.${type}.tip`)}
+ </div>
+ {type === 'upload' && <Button onClick={onClick} className={s.addFileBtn}>
+ <PlusIcon className={s.plusIcon} />{t('datasetDocuments.list.addFile')}
+ </Button>}
+ </div>
+ </div>
+}
+
+type IDocumentsProps = {
+ datasetId: string
+}
+
+export const fetcher = (url: string) => get(url, {}, { isMock: true })
+
+const Documents: FC<IDocumentsProps> = ({ datasetId }) => {
+ const { t } = useTranslation()
+ const [searchValue, setSearchValue] = useState<string>('')
+ const [currPage, setCurrPage] = React.useState<number>(0)
+ const router = useRouter()
+
+ const query = useMemo(() => {
+ return { page: currPage + 1, limit, keyword: searchValue }
+ }, [searchValue, currPage])
+
+ const { data: documentsRes, error, mutate } = useSWR({
+ action: 'fetchDocuments',
+ datasetId,
+ params: query,
+ }, apiParams => fetchDocuments(omit(apiParams, 'action')))
+
+ const total = documentsRes?.total || 0
+
+ const routeToDocCreate = () => {
+ router.push(`/datasets/${datasetId}/documents/create`)
+ }
+
+ router.prefetch(`/datasets/${datasetId}/documents/create`)
+
+ const isLoading = !documentsRes && !error
+
+ return (
+ <div className='flex flex-col h-full overflow-y-auto'>
+ <div className='flex flex-col justify-center gap-1 px-6 pt-4'>
+ <h1 className={s.title}>{t('datasetDocuments.list.title')}</h1>
+ <p className={s.desc}>{t('datasetDocuments.list.desc')}</p>
+ </div>
+ <div className='flex flex-col px-6 py-4 flex-1'>
+ <div className='flex items-center justify-between'>
+ <Input
+ showPrefix
+ wrapperClassName='!w-[200px]'
+ className='!h-8 !text-[13px]'
+ onChange={debounce(setSearchValue, 500)}
+ value={searchValue}
+ />
+ <Button type='primary' onClick={routeToDocCreate} className='!h-8 !text-[13px]'>
+ <PlusIcon className='h-4 w-4 mr-2 stroke-current' />
+ {t('datasetDocuments.list.addFile')}
+ </Button>
+ </div>
+ {isLoading
+ ? <Loading type='app' />
+ : total > 0
+ ? <List documents={documentsRes?.data || []} datasetId={datasetId} onUpdate={mutate} />
+ : <EmptyElement onClick={routeToDocCreate} />
+ }
+ {/* Show Pagination only if the total is more than the limit */}
+ {(total && total > limit)
+ ? <Pagination current={currPage} onChange={setCurrPage} total={total} limit={limit} />
+ : null}
+ </div>
+ </div>
+ )
+}
+
+export default Documents
diff --git a/web/app/components/datasets/documents/list.tsx b/web/app/components/datasets/documents/list.tsx
new file mode 100644
index 00000000000..f53c63f0327
--- /dev/null
+++ b/web/app/components/datasets/documents/list.tsx
@@ -0,0 +1,318 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState, useEffect } from 'react'
+import { TrashIcon, ArrowDownIcon } from '@heroicons/react/24/outline'
+import { ExclamationCircleIcon } from '@heroicons/react/24/solid'
+import dayjs from 'dayjs'
+import { pick } from 'lodash-es'
+import { useContext } from 'use-context-selector'
+import { useRouter } from 'next/navigation'
+import { useTranslation } from 'react-i18next'
+import Switch from '@/app/components/base/switch'
+import Divider from '@/app/components/base/divider'
+import Popover from '@/app/components/base/popover'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import Tooltip from '@/app/components/base/tooltip'
+import { ToastContext } from '@/app/components/base/toast'
+import type { IndicatorProps } from '@/app/components/header/indicator'
+import Indicator from '@/app/components/header/indicator'
+import { asyncRunSafe } from '@/utils'
+import { formatNumber } from '@/utils/format'
+import { archiveDocument, deleteDocument, disableDocument, enableDocument } from '@/service/datasets'
+import type { DocumentListResponse, DocumentDisplayStatus } from '@/models/datasets'
+import type { CommonResponse } from '@/models/common'
+import cn from 'classnames'
+import s from './style.module.css'
+
+export const SettingsIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M2 5.33325L10 5.33325M10 5.33325C10 6.43782 10.8954 7.33325 12 7.33325C13.1046 7.33325 14 6.43782 14 5.33325C14 4.22868 13.1046 3.33325 12 3.33325C10.8954 3.33325 10 4.22868 10 5.33325ZM6 10.6666L14 10.6666M6 10.6666C6 11.7712 5.10457 12.6666 4 12.6666C2.89543 12.6666 2 11.7712 2 10.6666C2 9.56202 2.89543 8.66659 4 8.66659C5.10457 8.66659 6 9.56202 6 10.6666Z" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+export const FilePlusIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M13.3332 6.99992V4.53325C13.3332 3.41315 13.3332 2.85309 13.1152 2.42527C12.9234 2.04895 12.6175 1.74299 12.2412 1.55124C11.8133 1.33325 11.2533 1.33325 10.1332 1.33325H5.8665C4.7464 1.33325 4.18635 1.33325 3.75852 1.55124C3.3822 1.74299 3.07624 2.04895 2.88449 2.42527C2.6665 2.85309 2.6665 3.41315 2.6665 4.53325V11.4666C2.6665 12.5867 2.6665 13.1467 2.88449 13.5746C3.07624 13.9509 3.3822 14.2569 3.75852 14.4486C4.18635 14.6666 4.7464 14.6666 5.8665 14.6666H7.99984M9.33317 7.33325H5.33317M6.6665 9.99992H5.33317M10.6665 4.66659H5.33317M11.9998 13.9999V9.99992M9.99984 11.9999H13.9998" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+export const ArchiveIcon: FC<{ className?: string }> = ({ className }) => {
+ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
+ <path d="M2.66683 5.33106C2.55749 5.32824 2.47809 5.32191 2.40671 5.30771C1.87779 5.2025 1.46432 4.78904 1.35912 4.26012C1.3335 4.13132 1.3335 3.97644 1.3335 3.66667C1.3335 3.3569 1.3335 3.20201 1.35912 3.07321C1.46432 2.54429 1.87779 2.13083 2.40671 2.02562C2.53551 2 2.69039 2 3.00016 2H13.0002C13.3099 2 13.4648 2 13.5936 2.02562C14.1225 2.13083 14.536 2.54429 14.6412 3.07321C14.6668 3.20201 14.6668 3.3569 14.6668 3.66667C14.6668 3.97644 14.6668 4.13132 14.6412 4.26012C14.536 4.78904 14.1225 5.2025 13.5936 5.30771C13.5222 5.32191 13.4428 5.32824 13.3335 5.33106M6.66683 8.66667H9.3335M2.66683 5.33333H13.3335V10.8C13.3335 11.9201 13.3335 12.4802 13.1155 12.908C12.9238 13.2843 12.6178 13.5903 12.2415 13.782C11.8137 14 11.2536 14 10.1335 14H5.86683C4.74672 14 4.18667 14 3.75885 13.782C3.38252 13.5903 3.07656 13.2843 2.88482 12.908C2.66683 12.4802 2.66683 11.9201 2.66683 10.8V5.33333Z" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+}
+
+export const useIndexStatus = () => {
+ const { t } = useTranslation()
+ return {
+ queuing: { color: 'orange', text: t('datasetDocuments.list.status.queuing') }, // waiting
+ indexing: { color: 'blue', text: t('datasetDocuments.list.status.indexing') }, // indexing splitting parsing cleaning
+ paused: { color: 'orange', text: t('datasetDocuments.list.status.parsed') }, // paused
+ error: { color: 'red', text: t('datasetDocuments.list.status.error') }, // error
+ available: { color: 'green', text: t('datasetDocuments.list.status.available') }, // completed,archived = false,enabled = true
+ enabled: { color: 'green', text: t('datasetDocuments.list.status.enabled') }, // completed,archived = false,enabled = true
+ disabled: { color: 'gray', text: t('datasetDocuments.list.status.disabled') }, // completed,archived = false,enabled = false
+ archived: { color: 'gray', text: t('datasetDocuments.list.status.archived') }, // completed,archived = true
+ }
+}
+
+// status item for list
+export const StatusItem: FC<{
+ status: DocumentDisplayStatus;
+ reverse?: boolean;
+ scene?: 'list' | 'detail'
+ textCls?: string
+}> = ({ status, reverse = false, scene = 'list', textCls = '' }) => {
+ const DOC_INDEX_STATUS_MAP = useIndexStatus();
+ const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP
+ return <div className={
+ cn('flex items-center',
+ reverse ? 'flex-row-reverse' : '',
+ scene === 'detail' ? s.statusItemDetail : '')
+ }>
+ <Indicator color={DOC_INDEX_STATUS_MAP[localStatus]?.color as IndicatorProps['color']} className={reverse ? 'ml-2' : 'mr-2'} />
+ <span className={cn('text-gray-700 text-sm', textCls)}>{DOC_INDEX_STATUS_MAP[localStatus]?.text}</span>
+ </div>
+}
+
+type OperationName = 'delete' | 'archive' | 'enable' | 'disable'
+
+// operation action for list and detail
+export const OperationAction: FC<{
+ detail: {
+ enabled: boolean;
+ archived: boolean;
+ id: string
+ }
+ datasetId: string;
+ onUpdate: () => void
+ scene?: 'list' | 'detail'
+ className?: string
+}> = ({ datasetId, detail, onUpdate, scene = 'list', className = '' }) => {
+ const { id, enabled = false, archived = false } = detail || {}
+ const [showModal, setShowModal] = useState(false)
+ const { notify } = useContext(ToastContext)
+ const { t } = useTranslation()
+
+ const isListScene = scene === 'list';
+
+ const onOperate = async (operationName: OperationName) => {
+ let opApi = deleteDocument
+ switch (operationName) {
+ case 'archive':
+ opApi = archiveDocument
+ break
+ case 'enable':
+ opApi = enableDocument
+ break
+ case 'disable':
+ opApi = disableDocument
+ break
+ default:
+ opApi = deleteDocument
+ break
+ }
+ const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
+ if (!e)
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ else
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ onUpdate()
+ }
+
+ return <div
+ className='flex items-center'
+ onClick={(e) => e.stopPropagation()}
+ >
+ {isListScene && <>
+ {archived ?
+ <Tooltip selector={`list-switch-${id}`} content={t('datasetDocuments.list.action.enableWarning') as string} className='!font-semibold'>
+ <div>
+ <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
+ </div>
+ </Tooltip> :
+ <Switch defaultValue={enabled} onChange={v => onOperate(v ? 'enable' : 'disable')} size='md' />
+ }
+ <Divider className='!ml-4 !mr-2 !h-3' type='vertical' />
+ </>}
+ <Popover
+ htmlContent={
+ <div className='w-full py-1'>
+ {!isListScene && <>
+ <div className='flex justify-between items-center mx-4 pt-2'>
+ <span className={cn(s.actionName, 'font-medium')}>
+ {!archived && enabled ? t('datasetDocuments.list.index.enable') : t('datasetDocuments.list.index.disable')}
+ </span>
+ <Tooltip
+ selector={`detail-switch-${id}`}
+ content={t('datasetDocuments.list.action.enableWarning') as string}
+ className='!font-semibold'
+ disabled={!archived}
+ >
+ <div>
+ <Switch
+ defaultValue={archived ? false : enabled}
+ onChange={v => !archived && onOperate(v ? 'enable' : 'disable')}
+ disabled={archived}
+ size='md'
+ />
+ </div>
+ </Tooltip>
+ </div>
+ <div className='mx-4 pb-1 pt-0.5 text-xs text-gray-500'>
+ {!archived && enabled ? t('datasetDocuments.list.index.enableTip') : t('datasetDocuments.list.index.disableTip')}
+ </div>
+ <Divider />
+ </>}
+ {/* <div className={s.actionItem}>
+ <SettingsIcon />
+ <span className={s.actionName}>{t('datasetDocuments.list.action.settings')}</span>
+ </div>
+ <div className={s.actionItem} onClick={() => router.push(`/datasets/${datasetId}/documents/create`)}>
+ <FilePlusIcon />
+ <span className={s.actionName}>{t('datasetDocuments.list.action.uploadFile')}</span>
+ </div>
+ <Divider className='my-1' /> */}
+ {!archived && <div className={s.actionItem} onClick={() => onOperate('archive')}>
+ <ArchiveIcon />
+ <span className={s.actionName}>{t('datasetDocuments.list.action.archive')}</span>
+ </div>}
+ <div className={cn(s.actionItem, s.deleteActionItem, 'group')} onClick={() => setShowModal(true)}>
+ <TrashIcon className={'w-4 h-4 stroke-current text-gray-500 stroke-2 group-hover:text-red-500'} />
+ <span className={cn(s.actionName, 'group-hover:text-red-500')}>{t('datasetDocuments.list.action.delete')}</span>
+ </div>
+ </div>
+ }
+ trigger='click'
+ position='br'
+ btnElement={<div className={cn(s.actionIcon, s.commonIcon)} />}
+ btnClassName={(open) => cn(isListScene ? s.actionIconWrapperList : s.actionIconWrapperDetail, open ? '!bg-gray-100 !shadow-none' : '!bg-transparent')}
+ className={`!w-[200px] h-fit !z-20 ${className}`}
+ />
+ {showModal && <Modal isShow={showModal} onClose={() => setShowModal(false)} className={s.delModal} closable>
+ <div>
+ <div className={s.warningWrapper}>
+ <ExclamationCircleIcon className={s.warningIcon} />
+ </div>
+ <div className='text-xl font-semibold text-gray-900 mb-1'>{t('datasetDocuments.list.delete.title')}</div>
+ <div className='text-sm text-gray-500 mb-10'>{t('datasetDocuments.list.delete.content')}</div>
+ <div className='flex gap-2 justify-end'>
+ <Button onClick={() => setShowModal(false)}>{t('common.operation.cancel')}</Button>
+ <Button
+ type='warning'
+ onClick={() => onOperate('delete')}
+ className='border-red-700 border-[0.5px]'
+ >
+ {t('common.operation.sure')}
+ </Button>
+ </div>
+ </div>
+ </Modal>}
+ </div>
+}
+
+export const renderTdValue = (value: string | number | null, isEmptyStyle = false) => {
+ return (
+ <div className={cn(isEmptyStyle ? 'text-gray-400' : 'text-gray-700', s.tdValue)}>
+ {value ?? '-'}
+ </div>
+ )
+}
+
+const renderCount = (count: number | undefined) => {
+ if (!count) {
+ return renderTdValue(0, true)
+ }
+ if (count < 1000) {
+ return count;
+ }
+ return `${formatNumber((count / 1000).toFixed(1))}k`
+}
+
+type IDocumentListProps = {
+ documents: DocumentListResponse['data']
+ datasetId: string
+ onUpdate: () => void
+}
+
+/**
+ * Document list component including basic information
+ */
+const DocumentList: FC<IDocumentListProps> = ({ documents = [], datasetId, onUpdate }) => {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const [localDocs, setLocalDocs] = useState<DocumentListResponse['data']>(documents);
+ const [enableSort, setEnableSort] = useState(false);
+
+ useEffect(() => {
+ setLocalDocs(documents)
+ }, [documents])
+
+ const onClickSort = () => {
+ setEnableSort(!enableSort);
+ if (!enableSort) {
+ const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1);
+ setLocalDocs(sortedDocs);
+ } else {
+ setLocalDocs(documents);
+ }
+ }
+
+ return (
+ <>
+ <table className={`w-full border-collapse border-0 text-sm mt-3 ${s.documentTable}`}>
+ <thead className="h-8 leading-8 border-b border-gray-200 text-gray-500 font-medium text-xs uppercase">
+ <tr>
+ <td className='w-12'>#</td>
+ <td>{t('datasetDocuments.list.table.header.fileName')}</td>
+ <td className='w-24'>{t('datasetDocuments.list.table.header.words')}</td>
+ <td className='w-24'>{t('datasetDocuments.list.table.header.hitCount')}</td>
+ <td className='w-44'>
+ <div className='flex justify-between items-center'>
+ {t('datasetDocuments.list.table.header.uploadTime')}
+ <ArrowDownIcon className={cn('h-3 w-3 stroke-current stroke-2 cursor-pointer', enableSort ? 'text-gray-500' : 'text-gray-300')} onClick={onClickSort} />
+ </div>
+ </td>
+ <td className='w-40'>{t('datasetDocuments.list.table.header.status')}</td>
+ <td className='w-20'>{t('datasetDocuments.list.table.header.action')}</td>
+ </tr>
+ </thead>
+ <tbody className="text-gray-700">
+ {localDocs.map((doc) => {
+ const suffix = doc.name.split('.').pop() || 'txt'
+ return <tr
+ key={doc.id}
+ className={'border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer'}
+ onClick={() => {
+ router.push(`datasets/${datasetId}/documents/${doc.id}`)
+ }}>
+ <td className='text-left align-middle text-gray-500 text-xs'>{doc.position}</td>
+ <td className={s.tdValue}>
+ <div className={cn(s[`${doc?.data_source_info?.upload_file?.extension ?? suffix}Icon`], s.commonIcon, 'mr-1.5')}></div>
+ <span>{doc?.name?.replace(/\.[^/.]+$/, "")}<span className='text-gray-500'>.{suffix}</span></span>
+ </td>
+ <td>{renderCount(doc.word_count)}</td>
+ <td>{renderCount(doc.hit_count)}</td>
+ <td className='text-gray-500 text-[13px]'>
+ {dayjs.unix(doc.created_at).format(t('datasetHitTesting.dateTimeFormat') as string)}
+ </td>
+ <td>
+ <StatusItem status={doc.display_status} />
+ </td>
+ <td>
+ <OperationAction
+ datasetId={datasetId}
+ detail={pick(doc, ['enabled', 'archived', 'id'])}
+ onUpdate={onUpdate}
+ />
+ </td>
+ </tr>
+ })}
+ </tbody>
+ </table>
+ </>
+ )
+}
+
+export default DocumentList
diff --git a/web/app/components/datasets/documents/style.module.css b/web/app/components/datasets/documents/style.module.css
new file mode 100644
index 00000000000..76327d83f6b
--- /dev/null
+++ b/web/app/components/datasets/documents/style.module.css
@@ -0,0 +1,103 @@
+.documentTable tbody td {
+ padding: 5px 10px 5px 12px;
+ box-sizing: border-box;
+ max-width: 200px;
+}
+.documentTable thead td {
+ padding: 0px 10px 0px 12px;
+ box-sizing: border-box;
+ max-width: 200px;
+}
+.title {
+ @apply text-xl font-medium text-gray-900;
+}
+.desc {
+ @apply text-sm font-normal text-gray-500;
+}
+.actionIconWrapperList {
+ @apply h-6 w-6 rounded-md border-none p-1 hover:bg-gray-100 !important;
+}
+.actionIconWrapperDetail {
+ @apply h-8 w-8 p-2 hover:bg-gray-50 border border-gray-200 hover:border-gray-300 hover:shadow-[0_1px_2px_rgba(16,24,40,0.05)] !important;
+}
+.actionItem {
+ @apply h-9 py-2 px-3 mx-1 flex items-center gap-2 hover:bg-gray-100 rounded-lg cursor-pointer;
+}
+.deleteActionItem {
+ @apply hover:bg-red-50 !important;
+}
+.actionName {
+ @apply text-gray-700 text-sm;
+}
+.addFileBtn {
+ @apply mt-4 w-fit !text-[13px] text-primary-600 font-medium bg-white border-[0.5px];
+}
+.plusIcon {
+ @apply w-4 h-4 mr-2 stroke-current stroke-[1.5px];
+}
+.emptyWrapper {
+ @apply flex items-center justify-center h-full;
+}
+.emptyElement {
+ @apply bg-gray-50 w-[560px] h-fit box-border px-5 py-4 rounded-2xl;
+}
+.emptyTitle {
+ @apply text-gray-700 font-semibold;
+}
+.emptyTip {
+ @apply mt-2 text-gray-500 text-sm font-normal;
+}
+.emptySymbolIconWrapper {
+ @apply w-[44px] h-[44px] border border-solid border-gray-100 rounded-lg flex items-center justify-center mb-2;
+}
+.commonIcon {
+ @apply w-4 h-4 inline-block align-middle;
+ background-repeat: no-repeat;
+ background-position: center center;
+ background-size: contain;
+}
+.actionIcon {
+ @apply bg-gray-500;
+ mask-image: url(./assets/action.svg);
+}
+.pdfIcon {
+ background-image: url(./assets/pdf.svg);
+}
+.jsonIcon {
+ background-image: url(./assets/json.svg);
+}
+.htmlIcon {
+ background-image: url(./assets/html.svg);
+}
+.txtIcon {
+ background-image: url(./assets/txt.svg);
+}
+.mdIcon {
+ background-image: url(./assets/md.svg);
+}
+.statusItemDetail {
+ @apply h-8 font-medium border border-gray-200 inline-flex items-center rounded-lg pl-3 pr-4 mr-2;
+}
+.tdValue {
+ @apply text-sm overflow-hidden text-ellipsis whitespace-nowrap;
+}
+.delModal {
+ background: linear-gradient(
+ 180deg,
+ rgba(217, 45, 32, 0.05) 0%,
+ rgba(217, 45, 32, 0) 24.02%
+ ),
+ #f9fafb;
+ box-shadow: 0px 20px 24px -4px rgba(16, 24, 40, 0.08),
+ 0px 8px 8px -4px rgba(16, 24, 40, 0.03);
+ @apply rounded-2xl p-8;
+}
+.warningWrapper {
+ box-shadow: 0px 20px 24px -4px rgba(16, 24, 40, 0.08),
+ 0px 8px 8px -4px rgba(16, 24, 40, 0.03);
+ background: rgba(255, 255, 255, 0.9);
+ @apply h-12 w-12 border-[0.5px] border-gray-100 rounded-xl mb-3 flex items-center justify-center;
+}
+.warningIcon {
+ @apply w-[22px] h-[22px] fill-current text-red-600;
+}
diff --git a/web/app/components/datasets/hit-testing/assets/clock.svg b/web/app/components/datasets/hit-testing/assets/clock.svg
new file mode 100644
index 00000000000..b81dbecf106
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/assets/clock.svg
@@ -0,0 +1,3 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M18.9166 9.58333L17.2505 11.25L15.5833 9.58333M17.4542 10.8333C17.4845 10.5597 17.5 10.2817 17.5 10C17.5 5.85786 14.1421 2.5 10 2.5C5.85786 2.5 2.5 5.85786 2.5 10C2.5 14.1421 5.85786 17.5 10 17.5C12.3561 17.5 14.4584 16.4136 15.8333 14.7144M10 5.83333V10L12.5 11.6667" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/hit-testing/assets/grid.svg b/web/app/components/datasets/hit-testing/assets/grid.svg
new file mode 100644
index 00000000000..a165677afdc
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/assets/grid.svg
@@ -0,0 +1,6 @@
+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M4.9 1.75H2.68333C2.35664 1.75 2.19329 1.75 2.06851 1.81358C1.95874 1.86951 1.86951 1.95874 1.81358 2.06851C1.75 2.19329 1.75 2.35664 1.75 2.68333V4.9C1.75 5.2267 1.75 5.39005 1.81358 5.51483C1.86951 5.62459 1.95874 5.71383 2.06851 5.76975C2.19329 5.83333 2.35664 5.83333 2.68333 5.83333H4.9C5.2267 5.83333 5.39005 5.83333 5.51483 5.76975C5.62459 5.71383 5.71383 5.62459 5.76975 5.51483C5.83333 5.39005 5.83333 5.2267 5.83333 4.9V2.68333C5.83333 2.35664 5.83333 2.19329 5.76975 2.06851C5.71383 1.95874 5.62459 1.86951 5.51483 1.81358C5.39005 1.75 5.2267 1.75 4.9 1.75Z" stroke="#667085" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M11.3167 1.75H9.1C8.7733 1.75 8.60995 1.75 8.48517 1.81358C8.37541 1.86951 8.28617 1.95874 8.23025 2.06851C8.16667 2.19329 8.16667 2.35664 8.16667 2.68333V4.9C8.16667 5.2267 8.16667 5.39005 8.23025 5.51483C8.28617 5.62459 8.37541 5.71383 8.48517 5.76975C8.60995 5.83333 8.7733 5.83333 9.1 5.83333H11.3167C11.6434 5.83333 11.8067 5.83333 11.9315 5.76975C12.0413 5.71383 12.1305 5.62459 12.1864 5.51483C12.25 5.39005 12.25 5.2267 12.25 4.9V2.68333C12.25 2.35664 12.25 2.19329 12.1864 2.06851C12.1305 1.95874 12.0413 1.86951 11.9315 1.81358C11.8067 1.75 11.6434 1.75 11.3167 1.75Z" stroke="#667085" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M11.3167 8.16667H9.1C8.7733 8.16667 8.60995 8.16667 8.48517 8.23025C8.37541 8.28617 8.28617 8.37541 8.23025 8.48517C8.16667 8.60995 8.16667 8.7733 8.16667 9.1V11.3167C8.16667 11.6434 8.16667 11.8067 8.23025 11.9315C8.28617 12.0413 8.37541 12.1305 8.48517 12.1864C8.60995 12.25 8.7733 12.25 9.1 12.25H11.3167C11.6434 12.25 11.8067 12.25 11.9315 12.1864C12.0413 12.1305 12.1305 12.0413 12.1864 11.9315C12.25 11.8067 12.25 11.6434 12.25 11.3167V9.1C12.25 8.7733 12.25 8.60995 12.1864 8.48517C12.1305 8.37541 12.0413 8.28617 11.9315 8.23025C11.8067 8.16667 11.6434 8.16667 11.3167 8.16667Z" stroke="#667085" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M4.9 8.16667H2.68333C2.35664 8.16667 2.19329 8.16667 2.06851 8.23025C1.95874 8.28617 1.86951 8.37541 1.81358 8.48517C1.75 8.60995 1.75 8.7733 1.75 9.1V11.3167C1.75 11.6434 1.75 11.8067 1.81358 11.9315C1.86951 12.0413 1.95874 12.1305 2.06851 12.1864C2.19329 12.25 2.35664 12.25 2.68333 12.25H4.9C5.2267 12.25 5.39005 12.25 5.51483 12.1864C5.62459 12.1305 5.71383 12.0413 5.76975 11.9315C5.83333 11.8067 5.83333 11.6434 5.83333 11.3167V9.1C5.83333 8.7733 5.83333 8.60995 5.76975 8.48517C5.71383 8.37541 5.62459 8.28617 5.51483 8.23025C5.39005 8.16667 5.2267 8.16667 4.9 8.16667Z" stroke="#667085" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/datasets/hit-testing/assets/plugin.svg b/web/app/components/datasets/hit-testing/assets/plugin.svg
new file mode 100644
index 00000000000..2bd15edf18d
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/assets/plugin.svg
@@ -0,0 +1,10 @@
+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_4151_6854)">
+<path d="M4.37484 2.62484C4.37484 1.81942 5.02776 1.1665 5.83317 1.1665C6.63859 1.1665 7.2915 1.81942 7.2915 2.62484V3.49984H7.87484C8.69023 3.49984 9.09793 3.49984 9.41953 3.63305C9.84833 3.81066 10.189 4.15134 10.3666 4.58014C10.4998 4.90174 10.4998 5.30944 10.4998 6.12484H11.3748C12.1803 6.12484 12.8332 6.77776 12.8332 7.58317C12.8332 8.38859 12.1803 9.0415 11.3748 9.0415H10.4998V10.0332C10.4998 11.0133 10.4998 11.5033 10.3091 11.8777C10.1413 12.2069 9.8736 12.4747 9.54432 12.6424C9.16997 12.8332 8.67993 12.8332 7.69984 12.8332H7.2915V11.8123C7.2915 11.0875 6.70388 10.4998 5.979 10.4998C5.25413 10.4998 4.6665 11.0875 4.6665 11.8123V12.8332H3.9665C2.98641 12.8332 2.49637 12.8332 2.12202 12.6424C1.79274 12.4747 1.52502 12.2069 1.35724 11.8777C1.1665 11.5033 1.1665 11.0133 1.1665 10.0332V9.0415H2.0415C2.84692 9.0415 3.49984 8.38859 3.49984 7.58317C3.49984 6.77776 2.84692 6.12484 2.0415 6.12484H1.1665C1.1665 5.30944 1.1665 4.90174 1.29971 4.58014C1.47733 4.15134 1.81801 3.81066 2.24681 3.63305C2.56841 3.49984 2.97611 3.49984 3.7915 3.49984H4.37484V2.62484Z" stroke="#667085" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<clipPath id="clip0_4151_6854">
+<rect width="14" height="14" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/datasets/hit-testing/hit-detail.tsx b/web/app/components/datasets/hit-testing/hit-detail.tsx
new file mode 100644
index 00000000000..3eecdb8ac53
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/hit-detail.tsx
@@ -0,0 +1,99 @@
+import React, { FC } from "react";
+import cn from "classnames";
+import { SegmentDetailModel } from "@/models/datasets";
+import { useTranslation } from "react-i18next";
+import Divider from "@/app/components/base/divider";
+import { SegmentIndexTag } from "../documents/detail/completed";
+import s from "../documents/detail/completed/style.module.css";
+import ReactECharts from "echarts-for-react";
+
+type IScatterChartProps = {
+ data: Array<number[]>
+ curr: Array<number[]>
+}
+
+const ScatterChart: FC<IScatterChartProps> = ({ data, curr }) => {
+ const option = {
+ xAxis: {},
+ yAxis: {},
+ tooltip: {
+ trigger: 'item',
+ axisPointer: {
+ type: 'cross'
+ }
+ },
+ series: [
+ {
+ type: 'effectScatter',
+ symbolSize: 5,
+ data: curr,
+ },
+ {
+ type: 'scatter',
+ symbolSize: 5,
+ data,
+ }
+ ]
+ };
+ return (
+ <ReactECharts option={option} style={{ height: 380, width: 430 }} />
+ )
+}
+
+type IHitDetailProps = {
+ segInfo?: Partial<SegmentDetailModel> & { id: string };
+ vectorInfo?: { curr: Array<number[]>; points: Array<number[]> };
+};
+
+const HitDetail: FC<IHitDetailProps> = ({ segInfo, vectorInfo }) => {
+ const { t } = useTranslation();
+
+ return (
+ <div className={"flex flex-row"}>
+ <div className="flex-1 bg-gray-25 p-6">
+ <div className="flex items-center">
+ <SegmentIndexTag
+ positionId={segInfo?.position || ""}
+ className="w-fit mr-6"
+ />
+ <div className={cn(s.commonIcon, s.typeSquareIcon)} />
+ <span className={cn("mr-6", s.numberInfo)}>
+ {segInfo?.word_count} {t("datasetDocuments.segment.characters")}
+ </span>
+ <div className={cn(s.commonIcon, s.targetIcon)} />
+ <span className={s.numberInfo}>
+ {segInfo?.hit_count} {t("datasetDocuments.segment.hitCount")}
+ </span>
+ </div>
+ <Divider />
+ <div className={s.segModalContent}>{segInfo?.content}</div>
+ <div className={s.keywordTitle}>
+ {t("datasetDocuments.segment.keywords")}
+ </div>
+ <div className={s.keywordWrapper}>
+ {!segInfo?.keywords?.length
+ ? "-"
+ : segInfo?.keywords?.map((word: any) => {
+ return <div className={s.keyword}>{word}</div>;
+ })}
+ </div>
+ </div>
+ <div className="flex-1 bg-white p-6">
+ <div className="flex items-center">
+ <div className={cn(s.commonIcon, s.bezierCurveIcon)} />
+ <span className={s.numberInfo}>
+ {t("datasetDocuments.segment.vectorHash")}
+ </span>
+ </div>
+ <div
+ className={cn(s.numberInfo, "w-[400px] truncate text-gray-700 mt-1")}
+ >
+ {segInfo?.index_node_hash}
+ </div>
+ <ScatterChart data={vectorInfo?.points || []} curr={vectorInfo?.curr || []} />
+ </div>
+ </div>
+ );
+};
+
+export default HitDetail;
diff --git a/web/app/components/datasets/hit-testing/index.tsx b/web/app/components/datasets/hit-testing/index.tsx
new file mode 100644
index 00000000000..fae98b7cefe
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/index.tsx
@@ -0,0 +1,174 @@
+'use client'
+import React, { useState, FC, useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import useSWR from 'swr'
+import { fetchTestingRecords } from '@/service/datasets'
+import { omit } from 'lodash-es'
+import Pagination from '@/app/components/base/pagination'
+import Modal from '@/app/components/base/modal'
+import Loading from '@/app/components/base/loading'
+import type { HitTestingResponse, HitTesting } from '@/models/datasets'
+import cn from 'classnames'
+import dayjs from 'dayjs'
+import SegmentCard from '../documents/detail/completed/SegmentCard'
+import docStyle from '../documents/detail/completed/style.module.css'
+import Textarea from './textarea'
+import s from './style.module.css'
+import HitDetail from './hit-detail'
+
+const limit = 10;
+
+type Props = {
+ datasetId: string
+}
+
+const RecordsEmpty: FC = () => {
+ const { t } = useTranslation()
+ return <div className='bg-gray-50 rounded-2xl p-5'>
+ <div className={s.clockWrapper}>
+ <div className={cn(s.clockIcon, 'w-5 h-5')}></div>
+ </div>
+ <div className='my-2 text-gray-500 text-sm'>{t('datasetHitTesting.noRecentTip')}</div>
+ </div>
+}
+
+const HitTesting: FC<Props> = ({ datasetId }: Props) => {
+ const { t } = useTranslation()
+ const [hitResult, setHitResult] = useState<HitTestingResponse | undefined>(); // 初始化记录为空数组
+ const [submitLoading, setSubmitLoading] = useState(false);
+ const [currParagraph, setCurrParagraph] = useState<{ paraInfo?: HitTesting; showModal: boolean }>({ showModal: false })
+ const [text, setText] = useState('');
+
+ const [currPage, setCurrPage] = React.useState<number>(0)
+ const { data: recordsRes, error, mutate: recordsMutate } = useSWR({
+ action: 'fetchTestingRecords',
+ datasetId,
+ params: { limit, page: currPage + 1, }
+ }, apiParams => fetchTestingRecords(omit(apiParams, 'action')))
+
+ const total = recordsRes?.total || 0
+
+ const points = useMemo(() => (hitResult?.records.map((v) => [v.tsne_position.x, v.tsne_position.y]) || []), [hitResult?.records])
+
+ const onClickCard = (detail: HitTesting) => {
+ setCurrParagraph({ paraInfo: detail, showModal: true })
+ }
+
+ return (
+ <div className={s.container}>
+ <div className={s.leftDiv}>
+ <div className={s.titleWrapper}>
+ <h1 className={s.title}>{t('datasetHitTesting.title')}</h1>
+ <p className={s.desc}>{t('datasetHitTesting.desc')}</p>
+ </div>
+ <Textarea
+ datasetId={datasetId}
+ setHitResult={setHitResult}
+ onUpdateList={recordsMutate}
+ loading={submitLoading}
+ setLoading={setSubmitLoading}
+ setText={setText}
+ text={text}
+ />
+ <div className={cn(s.title, 'mt-8 mb-2')}>{t('datasetHitTesting.recents')}</div>
+ {!recordsRes && !error ? (
+ <div className='flex-1'><Loading type='app' /></div>
+ ) : recordsRes?.data?.length ? (
+ <>
+ <table className={`w-full border-collapse border-0 mt-3 ${s.table}`}>
+ <thead className="h-8 leading-8 border-b border-gray-200 text-gray-500 font-bold">
+ <tr>
+ <td className='w-28'>{t('datasetHitTesting.table.header.source')}</td>
+ <td>{t('datasetHitTesting.table.header.text')}</td>
+ <td className='w-48'>{t('datasetHitTesting.table.header.time')}</td>
+ </tr>
+ </thead>
+ <tbody className="text-gray-500">
+ {recordsRes?.data?.map((record) => {
+ return <tr
+ key={record.id}
+ className='group border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer'
+ onClick={() => setText(record.content)}
+ >
+ <td className='w-24'>
+ <div className='flex items-center'>
+ <div className={cn(s[`${record.source}_icon`], s.commonIcon, 'mr-1')} />
+ <span className='capitalize'>{record.source.replace('_', ' ')}</span>
+ </div>
+ </td>
+ <td className='max-w-xs group-hover:text-primary-600'>{record.content}</td>
+ <td className='w-36'>
+ {dayjs.unix(record.created_at).format(t('datasetHitTesting.dateTimeFormat') as string)}
+ </td>
+ </tr>
+ })}
+ </tbody>
+ </table>
+ {(total && total > limit)
+ ? <Pagination current={currPage} onChange={setCurrPage} total={total} limit={limit} />
+ : null}
+ </>
+ ) : (
+ <RecordsEmpty />
+ )}
+ </div>
+ <div className={s.rightDiv}>
+ {submitLoading ?
+ <div className={s.cardWrapper}>
+ <SegmentCard
+ loading={true}
+ scene='hitTesting'
+ className='h-[216px]'
+ />
+ <SegmentCard
+ loading={true}
+ scene='hitTesting'
+ className='h-[216px]'
+ />
+ </div> : !hitResult?.records.length ? (
+ <div className='h-full flex flex-col justify-center items-center'>
+ <div className={cn(docStyle.commonIcon, docStyle.targetIcon, '!bg-gray-200 !h-14 !w-14')} />
+ <div className='text-gray-300 text-[13px] mt-3'>
+ {t('datasetHitTesting.hit.emptyTip')}
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className='text-gray-600 font-semibold mb-4'>{t('datasetHitTesting.hit.title')}</div>
+ <div className='overflow-auto flex-1'>
+ <div className={s.cardWrapper}>
+ {hitResult?.records.map((record) => {
+ return <SegmentCard
+ loading={false}
+ detail={record.segment as any}
+ score={record.score}
+ scene='hitTesting'
+ className='h-[216px] mb-4'
+ onClick={() => onClickCard(record as any)}
+ />
+ })}
+ </div>
+ </div>
+ </>
+ )
+ }
+ </div>
+ <Modal
+ className='!max-w-[960px] !p-0'
+ closable
+ onClose={() => setCurrParagraph({ showModal: false })}
+ isShow={currParagraph.showModal}
+ >
+ {currParagraph.showModal && <HitDetail
+ segInfo={currParagraph.paraInfo?.segment}
+ vectorInfo={{
+ curr: [[currParagraph.paraInfo?.tsne_position?.x || 0, currParagraph.paraInfo?.tsne_position.y || 0]],
+ points,
+ }}
+ />}
+ </Modal>
+ </div>
+ )
+}
+
+export default HitTesting
diff --git a/web/app/components/datasets/hit-testing/style.module.css b/web/app/components/datasets/hit-testing/style.module.css
new file mode 100644
index 00000000000..4c05f2be3cc
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/style.module.css
@@ -0,0 +1,65 @@
+.container {
+ @apply flex h-full w-full relative;
+}
+.container > div {
+ @apply flex-1 h-full;
+}
+.leftDiv {
+ @apply border-r border-gray-100 px-6 py-3 flex flex-col;
+}
+.rightDiv {
+ @apply px-8 pt-[42px] pb-[26px] flex flex-col;
+}
+.titleWrapper {
+ @apply flex flex-col justify-center gap-1 mb-5;
+}
+.title {
+ @apply text-xl font-medium text-gray-900;
+}
+.desc {
+ @apply text-sm font-normal text-gray-500;
+}
+.textarea {
+ min-height: 96px;
+ @apply border-none resize-none font-normal caret-primary-600 text-gray-700 text-sm w-full bg-gray-25 focus-visible:outline-none placeholder:text-gray-300 placeholder:text-sm placeholder:font-normal !important;
+}
+.table {
+ @apply text-[13px] text-gray-500;
+}
+.table td {
+ @apply whitespace-nowrap overflow-hidden text-ellipsis;
+}
+.commonIcon {
+ @apply w-3.5 h-3.5 inline-block align-middle;
+ background-repeat: no-repeat;
+ background-position: center center;
+ background-size: contain;
+}
+.app_icon {
+ background-image: url(./assets/grid.svg);
+}
+.hit_testing_icon {
+ background-image: url(../documents/assets/target.svg);
+}
+.plugin_icon {
+ background-image: url(./assets/plugin.svg);
+}
+
+.wrapper {
+ @apply relative border border-primary-600 min-h-[200px] rounded-xl pt-3 pb-14 px-4 bg-gray-25;
+}
+
+.cardWrapper {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(284px, auto));
+ grid-gap: 16px;
+ grid-auto-rows: 216px;
+}
+.clockWrapper {
+ border: 0.5px solid #eaecf5;
+ @apply rounded-lg w-11 h-11 flex justify-center items-center;
+}
+.clockIcon {
+ mask-image: url(./assets/clock.svg);
+ @apply bg-gray-500;
+}
diff --git a/web/app/components/datasets/hit-testing/textarea.tsx b/web/app/components/datasets/hit-testing/textarea.tsx
new file mode 100644
index 00000000000..4dcacf11f66
--- /dev/null
+++ b/web/app/components/datasets/hit-testing/textarea.tsx
@@ -0,0 +1,116 @@
+import type { FC } from "react";
+import { useContext } from 'use-context-selector'
+import { DocumentTextIcon } from "@heroicons/react/24/solid";
+import { useTranslation } from "react-i18next";
+import { hitTesting } from "@/service/datasets";
+import DatasetDetailContext from '@/context/dataset-detail'
+import { HitTestingResponse } from "@/models/datasets";
+import cn from "classnames";
+import Button from "../../base/button";
+import Tag from "../../base/tag";
+import Tooltip from "../../base/tooltip";
+import s from "./style.module.css";
+import { asyncRunSafe } from "@/utils";
+
+type Props = {
+ datasetId: string;
+ onUpdateList: () => void;
+ setHitResult: (res: HitTestingResponse) => void;
+ loading: boolean;
+ setLoading: (v: boolean) => void;
+ text: string;
+ setText: (v: string) => void;
+};
+
+const TextAreaWithButton: FC<Props> = ({
+ datasetId,
+ onUpdateList,
+ setHitResult,
+ setLoading,
+ loading,
+ text,
+ setText,
+}) => {
+ const { t } = useTranslation();
+ const { indexingTechnique } = useContext(DatasetDetailContext)
+
+ // 处理文本框内容变化的函数
+ function handleTextChange(event: any) {
+ setText(event.target.value);
+ }
+
+ // 处理按钮点击的函数
+ const onSubmit = async () => {
+ setLoading(true);
+ const [e, res] = await asyncRunSafe<HitTestingResponse>(
+ hitTesting({ datasetId, queryText: text }) as Promise<HitTestingResponse>
+ );
+ if (!e) {
+ setHitResult(res);
+ onUpdateList?.();
+ }
+ setLoading(false);
+ };
+
+ return (
+ <>
+ <div className={s.wrapper}>
+ <div className="flex items-center mb-3">
+ <DocumentTextIcon className="w-4 h-4 text-primary-600 mr-2" />
+ <span className="text-gray-800 font-semibold text-sm">
+ {t("datasetHitTesting.input.title")}
+ </span>
+ </div>
+ <textarea
+ value={text}
+ onChange={handleTextChange}
+ placeholder={t("datasetHitTesting.input.placeholder") as string}
+ className={s.textarea}
+ />
+ <div className="absolute inset-x-0 bottom-0 flex items-center justify-between mx-4 mt-2 mb-4">
+ {text?.length > 200 ? (
+ <Tooltip
+ content={t("datasetHitTesting.input.countWarning") as string}
+ selector="hit-testing-warning"
+ >
+ <div>
+ <Tag color="red" className="!text-red-600">
+ {text?.length}
+ <span className="text-red-300 mx-0.5">/</span>
+ 200
+ </Tag>
+ </div>
+ </Tooltip>
+ ) : (
+ <Tag
+ color="gray"
+ className={cn("!text-gray-500", text?.length ? "" : "opacity-50")}
+ >
+ {text?.length}
+ <span className="text-gray-300 mx-0.5">/</span>
+ 200
+ </Tag>
+ )}
+ <Tooltip
+ selector="hit-testing-submit"
+ disabled={indexingTechnique === 'high_quality'}
+ content={t("datasetHitTesting.input.indexWarning") as string}
+ >
+ <div>
+ <Button
+ onClick={onSubmit}
+ type="primary"
+ loading={loading}
+ disabled={indexingTechnique !== 'high_quality' ? true : (!text?.length || text?.length > 200)}
+ >
+ {t("datasetHitTesting.input.testing")}
+ </Button>
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ </>
+ );
+};
+
+export default TextAreaWithButton;
diff --git a/web/app/components/datasets/settings/form/index.tsx b/web/app/components/datasets/settings/form/index.tsx
new file mode 100644
index 00000000000..15dfadf127f
--- /dev/null
+++ b/web/app/components/datasets/settings/form/index.tsx
@@ -0,0 +1,127 @@
+'use client'
+import { useState } from 'react'
+import { useContext } from 'use-context-selector'
+import { BookOpenIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import { ToastContext } from '@/app/components/base/toast'
+import PermissionsRadio from '../permissions-radio'
+import IndexMethodRadio from '../index-method-radio'
+import Button from '@/app/components/base/button'
+import { useDatasetsContext } from '@/context/datasets-context'
+import { updateDatasetSetting } from '@/service/datasets'
+
+const rowClass = `
+ flex justify-between py-4
+`
+const labelClass = `
+ flex items-center w-[168px] h-9
+`
+const inputClass = `
+ w-[480px] px-3 bg-gray-100 text-sm text-gray-800 rounded-lg outline-none appearance-none
+`
+
+const Form = () => {
+ const { t } = useTranslation()
+ const { notify } = useContext(ToastContext)
+ const { currentDataset, mutateDatasets } = useDatasetsContext()
+ const [loading, setLoading] = useState(false)
+ const [name, setName] = useState(currentDataset?.name)
+ const [description, setDescription] = useState(currentDataset?.description)
+ const [permission, setPermission] = useState(currentDataset?.permission)
+ const [indexMethod, setIndexMethod] = useState(currentDataset?.indexing_technique)
+
+ const handleSave = async () => {
+ if (loading) return
+ if (!name?.trim()) {
+ notify({ type: 'error', message: t('datasetSettings.form.nameError') })
+ return
+ }
+ try {
+ setLoading(true)
+ await updateDatasetSetting({
+ datasetId: currentDataset!.id,
+ body: {
+ name,
+ description,
+ permission,
+ indexing_technique: indexMethod
+ }
+ })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ mutateDatasets()
+ } catch (e) {
+ notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ return (
+ <div className='w-[800px] px-16 py-6'>
+ <div className={rowClass}>
+ <div className={labelClass}>
+ <div>{t('datasetSettings.form.name')}</div>
+ </div>
+ <input
+ className={inputClass}
+ value={name}
+ onChange={e => setName(e.target.value)}
+ />
+ </div>
+ <div className={rowClass}>
+ <div className={labelClass}>
+ <div>{t('datasetSettings.form.desc')}</div>
+ </div>
+ <div>
+ <textarea
+ className={`${inputClass} block mb-2 h-[120px] py-2 resize-none`}
+ placeholder={t('datasetSettings.form.descPlaceholder') || ''}
+ value={description}
+ onChange={e => setDescription(e.target.value)}
+ />
+ <a className='flex items-center h-[18px] px-3 text-xs text-gray-500' href="https://docs.dify.ai/advanced/datasets#how-to-write-a-good-dataset-description" target='_blank'>
+ <BookOpenIcon className='w-3 h-[18px] mr-1' />
+ {t('datasetSettings.form.descWrite')}
+ </a>
+ </div>
+ </div>
+ <div className={rowClass}>
+ <div className={labelClass}>
+ <div>{t('datasetSettings.form.permissions')}</div>
+ </div>
+ <div className='w-[480px]'>
+ <PermissionsRadio
+ value={permission}
+ onChange={v => setPermission(v)}
+ />
+ </div>
+ </div>
+ <div className='w-full h-0 border-b-[0.5px] border-b-gray-200 my-2' />
+ <div className={rowClass}>
+ <div className={labelClass}>
+ <div>{t('datasetSettings.form.indexMethod')}</div>
+ </div>
+ <div className='w-[480px]'>
+ <IndexMethodRadio
+ value={indexMethod}
+ onChange={v => setIndexMethod(v)}
+ />
+ </div>
+ </div>
+ <div className={rowClass}>
+ <div className={labelClass} />
+ <div className='w-[480px]'>
+ <Button
+ className='min-w-24 text-sm'
+ type='primary'
+ onClick={handleSave}
+ >
+ {t('datasetSettings.form.save')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default Form
\ No newline at end of file
diff --git a/web/app/components/datasets/settings/index-method-radio/assets/economy.svg b/web/app/components/datasets/settings/index-method-radio/assets/economy.svg
new file mode 100644
index 00000000000..6b135bf1970
--- /dev/null
+++ b/web/app/components/datasets/settings/index-method-radio/assets/economy.svg
@@ -0,0 +1,5 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="8" fill="#EEF4FF"/>
+<path d="M11.6665 9.99998C12.9552 9.99998 13.9998 8.95531 13.9998 7.66665C13.9998 6.37798 12.9552 5.33331 11.6665 5.33331C10.3778 5.33331 9.33317 6.37798 9.33317 7.66665C9.33317 8.95531 10.3778 9.99998 11.6665 9.99998Z" fill="#444CE7"/>
+<path d="M8.65017 9.75198C8.49106 9.52227 8.4115 9.40741 8.32581 9.36947C8.24888 9.33541 8.1679 9.33124 8.08788 9.35723C7.99875 9.38618 7.92865 9.46797 7.78845 9.63154C7.22585 10.2879 6.84213 11.1027 6.71374 12.0001H6.6665C6.29831 12.0001 5.99984 11.7016 5.99984 11.3334C5.99984 11.0875 6.13265 10.8718 6.33365 10.7555C6.65236 10.5712 6.76127 10.1634 6.57691 9.84466C6.39255 9.52595 5.98473 9.41704 5.66602 9.60141C5.06996 9.94621 4.6665 10.5923 4.6665 11.3334C4.6665 12.438 5.56193 13.3334 6.6665 13.3334H6.71377C6.85773 14.3389 7.32239 15.2415 7.9998 15.9328L7.99979 17.4822C7.99976 17.5616 7.99973 17.6565 8.00655 17.74C8.01446 17.8368 8.03476 17.9755 8.10879 18.1208C8.20466 18.309 8.35764 18.4619 8.54581 18.5578C8.6911 18.6318 8.82976 18.6521 8.92658 18.6601C9.0101 18.6669 9.10492 18.6668 9.18432 18.6668H10.4819C10.5613 18.6668 10.6562 18.6669 10.7397 18.6601C10.8365 18.6521 10.9752 18.6318 11.1205 18.5578C11.3086 18.4619 11.4616 18.309 11.5575 18.1208C11.6315 17.9755 11.6518 17.8368 11.6597 17.74C11.6665 17.6565 11.6665 17.5616 11.6665 17.4822L11.6665 17.3335H12.3331L12.3331 17.482C12.3331 17.5614 12.3331 17.6562 12.3399 17.7398C12.3478 17.8366 12.3681 17.9753 12.4421 18.1205C12.538 18.3087 12.691 18.4617 12.8791 18.5576C13.0244 18.6316 13.1631 18.6519 13.2599 18.6598C13.3434 18.6666 13.4382 18.6666 13.5176 18.6666H14.8153C14.8947 18.6666 14.9896 18.6666 15.0731 18.6598C15.1699 18.6519 15.3085 18.6316 15.4538 18.5576C15.642 18.4617 15.795 18.3087 15.8909 18.1205C15.9649 17.9753 15.9852 17.8366 15.9931 17.7398C15.9999 17.6562 15.9999 17.5614 15.9999 17.482L15.9999 16.884C16.7373 16.5337 17.3676 15.9963 17.83 15.3332L18.1486 15.3332C18.228 15.3333 18.3229 15.3333 18.4064 15.3265C18.5032 15.3186 18.6419 15.2983 18.7872 15.2242C18.9753 15.1284 19.1283 14.9754 19.2242 14.7872C19.2982 14.6419 19.3185 14.5033 19.3264 14.4064C19.3333 14.3229 19.3332 14.2281 19.3332 14.1487V11.8424C19.3332 11.7668 19.3332 11.6765 19.327 11.5968C19.3199 11.5047 19.3015 11.3725 19.2341 11.2326C19.1358 11.0286 18.9712 10.8639 18.7671 10.7656C18.6272 10.6982 18.4951 10.6799 18.403 10.6727C18.3435 10.6681 18.2781 10.6669 18.2173 10.6666C17.9935 10.1955 17.6934 9.76819 17.3332 9.40057L17.3332 8.68818C17.3332 8.58496 17.3333 8.46813 17.3243 8.36763C17.3144 8.25667 17.2886 8.08512 17.1832 7.91509C17.0519 7.70309 16.846 7.54783 16.6061 7.47976C16.4137 7.42517 16.2416 7.44747 16.1322 7.46844C16.0331 7.48743 15.9208 7.51956 15.8216 7.54795L15.7177 7.57763C15.581 7.61667 15.5127 7.6362 15.4646 7.67139C15.4182 7.70536 15.3899 7.73885 15.364 7.7902C15.3371 7.84338 15.3279 7.92449 15.3094 8.08672C15.101 9.91393 13.5495 11.3333 11.6665 11.3333C10.4162 11.3333 9.31201 10.7075 8.65017 9.75198Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/datasets/settings/index-method-radio/assets/high-quality.svg b/web/app/components/datasets/settings/index-method-radio/assets/high-quality.svg
new file mode 100644
index 00000000000..dcb9aa2447f
--- /dev/null
+++ b/web/app/components/datasets/settings/index-method-radio/assets/high-quality.svg
@@ -0,0 +1,12 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="8" fill="#FFF6ED"/>
+<path d="M11.9998 4.66669C12.368 4.66669 12.6665 4.96516 12.6665 5.33335V6.66669C12.6665 7.03488 12.368 7.33335 11.9998 7.33335C11.6316 7.33335 11.3332 7.03488 11.3332 6.66669V5.33335C11.3332 4.96516 11.6316 4.66669 11.9998 4.66669Z" fill="#FB6514"/>
+<path d="M7.75705 6.81459C7.4967 6.55424 7.07459 6.55424 6.81424 6.81459C6.55389 7.07494 6.55389 7.49705 6.81424 7.75739L7.75705 8.7002C8.0174 8.96055 8.43951 8.96055 8.69986 8.7002C8.96021 8.43985 8.96021 8.01774 8.69986 7.75739L7.75705 6.81459Z" fill="#FB6514"/>
+<path d="M4.6665 12C4.6665 11.6318 4.96498 11.3334 5.33317 11.3334H6.6665C7.03469 11.3334 7.33317 11.6318 7.33317 12C7.33317 12.3682 7.03469 12.6667 6.6665 12.6667H5.33317C4.96498 12.6667 4.6665 12.3682 4.6665 12Z" fill="#FB6514"/>
+<path d="M17.3332 11.3334C16.965 11.3334 16.6665 11.6318 16.6665 12C16.6665 12.3682 16.965 12.6667 17.3332 12.6667H18.6665C19.0347 12.6667 19.3332 12.3682 19.3332 12C19.3332 11.6318 19.0347 11.3334 18.6665 11.3334H17.3332Z" fill="#FB6514"/>
+<path d="M16.2424 15.2998C15.982 15.0394 15.5599 15.0394 15.2996 15.2998C15.0392 15.5601 15.0392 15.9822 15.2996 16.2426L16.2424 17.1854C16.5027 17.4457 16.9249 17.4457 17.1852 17.1854C17.4456 16.925 17.4456 16.5029 17.1852 16.2426L16.2424 15.2998Z" fill="#FB6514"/>
+<path d="M17.1852 7.75739C17.4456 7.49705 17.4456 7.07494 17.1852 6.81459C16.9249 6.55424 16.5027 6.55424 16.2424 6.81459L15.2996 7.75739C15.0392 8.01774 15.0392 8.43985 15.2996 8.7002C15.5599 8.96055 15.982 8.96055 16.2424 8.7002L17.1852 7.75739Z" fill="#FB6514"/>
+<path d="M11.9998 16.6667C12.368 16.6667 12.6665 16.9652 12.6665 17.3334V18.6667C12.6665 19.0349 12.368 19.3334 11.9998 19.3334C11.6316 19.3334 11.3332 19.0349 11.3332 18.6667V17.3334C11.3332 16.9652 11.6316 16.6667 11.9998 16.6667Z" fill="#FB6514"/>
+<path d="M8.69986 16.2426C8.96021 15.9822 8.96021 15.5601 8.69986 15.2998C8.43951 15.0394 8.0174 15.0394 7.75705 15.2998L6.81424 16.2426C6.55389 16.5029 6.55389 16.925 6.81424 17.1854C7.07459 17.4457 7.4967 17.4457 7.75705 17.1854L8.69986 16.2426Z" fill="#FB6514"/>
+<path d="M12.5977 8.3716C12.4853 8.14407 12.2536 8.00002 11.9999 8.00002C11.7461 8.00002 11.5144 8.14407 11.4021 8.3716L10.527 10.1443L8.5701 10.4304C8.31906 10.4671 8.11061 10.6431 8.03236 10.8844C7.95411 11.1257 8.01962 11.3906 8.20137 11.5676L9.61684 12.9463L9.28278 14.894C9.23988 15.1441 9.34271 15.3969 9.54803 15.5461C9.75335 15.6952 10.0255 15.7149 10.2502 15.5967L11.9999 14.6766L13.7496 15.5967C13.9742 15.7149 14.2464 15.6952 14.4517 15.5461C14.657 15.3969 14.7598 15.1441 14.7169 14.894L14.3829 12.9463L15.7983 11.5676C15.9801 11.3906 16.0456 11.1257 15.9674 10.8844C15.8891 10.6431 15.6806 10.4671 15.4296 10.4304L13.4727 10.1443L12.5977 8.3716Z" fill="#FB6514"/>
+</svg>
diff --git a/web/app/components/datasets/settings/index-method-radio/index.module.css b/web/app/components/datasets/settings/index-method-radio/index.module.css
new file mode 100644
index 00000000000..d18327e60ed
--- /dev/null
+++ b/web/app/components/datasets/settings/index-method-radio/index.module.css
@@ -0,0 +1,38 @@
+.icon {
+ margin-right: 12px;
+ width: 24px;
+ height: 24px;
+ background: center center no-repeat;
+ background-size: contain;
+}
+
+.high-quality-icon {
+ background-image: url(./assets/high-quality.svg);
+}
+.economy-icon {
+ background-image: url(./assets/economy.svg);
+}
+
+.wrapper .item:hover {
+ background-color: #ffffff;
+ border-color: #B2CCFF;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
+
+.wrapper .item-active {
+ background-color: #ffffff;
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+.wrapper .item-active .radio {
+ border-width: 5px;
+ border-color: #155EEF;
+}
+
+.wrapper .item-active:hover {
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
\ No newline at end of file
diff --git a/web/app/components/datasets/settings/index-method-radio/index.tsx b/web/app/components/datasets/settings/index-method-radio/index.tsx
new file mode 100644
index 00000000000..e5285b36879
--- /dev/null
+++ b/web/app/components/datasets/settings/index-method-radio/index.tsx
@@ -0,0 +1,64 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import classNames from 'classnames'
+import s from './index.module.css'
+import { DataSet } from '@/models/datasets'
+
+const itemClass = `
+ w-[234px] p-3 rounded-xl bg-gray-25 border border-gray-100 cursor-pointer
+`
+const radioClass = `
+ w-4 h-4 border-[2px] border-gray-200 rounded-full
+`
+type IIndexMethodRadioProps = {
+ value?: DataSet['indexing_technique']
+ onChange: (v?: DataSet['indexing_technique']) => void
+}
+
+const IndexMethodRadio = ({
+ value,
+ onChange
+}: IIndexMethodRadioProps) => {
+ const { t } = useTranslation()
+ const options = [
+ {
+ key: 'high_quality',
+ text: t('datasetSettings.form.indexMethodHighQuality'),
+ desc: t('datasetSettings.form.indexMethodHighQualityTip'),
+ icon: 'high-quality'
+ },
+ {
+ key: 'economy',
+ text: t('datasetSettings.form.indexMethodEconomy'),
+ desc: t('datasetSettings.form.indexMethodEconomyTip'),
+ icon: 'economy'
+ }
+ ]
+
+ return (
+ <div className={classNames(s.wrapper, 'flex justify-between w-full')}>
+ {
+ options.map(option => (
+ <div
+ key={option.key}
+ className={classNames(
+ option.key === value && s['item-active'],
+ s.item,
+ itemClass
+ )}
+ onClick={() => onChange(option.key as DataSet['indexing_technique'])}
+ >
+ <div className='flex items-center mb-1'>
+ <div className={classNames(s.icon, s[`${option.icon}-icon`])} />
+ <div className='grow text-sm text-gray-900'>{option.text}</div>
+ <div className={classNames(radioClass, s.radio)} />
+ </div>
+ <div className='pl-9 text-xs text-gray-500 leading-[18px]'>{option.desc}</div>
+ </div>
+ ))
+ }
+ </div>
+ )
+}
+
+export default IndexMethodRadio
diff --git a/web/app/components/datasets/settings/permissions-radio/assets/user.svg b/web/app/components/datasets/settings/permissions-radio/assets/user.svg
new file mode 100644
index 00000000000..f5974c94a8f
--- /dev/null
+++ b/web/app/components/datasets/settings/permissions-radio/assets/user.svg
@@ -0,0 +1,7 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="8" fill="#EEF4FF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M15.4043 14.2586C15.5696 13.9296 15.9703 13.7969 16.2993 13.9622C17.3889 14.5095 18.31 15.381 18.9766 16.4548C19.0776 16.6174 19.2246 16.8347 19.2702 17.1291C19.3191 17.4443 19.2335 17.7457 19.1061 17.9749C18.9786 18.2041 18.7676 18.4357 18.4741 18.5605C18.1949 18.6791 17.8913 18.6666 17.6667 18.6666C17.2985 18.6666 17.0001 18.3682 17.0001 18C17.0001 17.6318 17.2985 17.3333 17.6667 17.3333C17.8102 17.3333 17.8856 17.3329 17.9395 17.3292L17.9409 17.3268C17.9536 17.3038 17.8568 17.1789 17.8438 17.158C17.2956 16.2749 16.5524 15.5814 15.7008 15.1536C15.3718 14.9884 15.2391 14.5877 15.4043 14.2586Z" fill="#444CE7"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M14.0697 6.01513C14.2336 5.68541 14.6337 5.55095 14.9634 5.71481C16.1691 6.314 17.0001 7.55934 17.0001 8.99998C17.0001 10.4406 16.1691 11.686 14.9634 12.2851C14.6337 12.449 14.2336 12.3145 14.0697 11.9848C13.9059 11.6551 14.0403 11.255 14.37 11.0911C15.14 10.7085 15.6667 9.91515 15.6667 8.99998C15.6667 8.08481 15.14 7.29144 14.37 6.90883C14.0403 6.74497 13.9059 6.34485 14.0697 6.01513Z" fill="#444CE7"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M6.66673 8.99998C6.66673 6.97494 8.30835 5.33331 10.3334 5.33331C12.3584 5.33331 14.0001 6.97494 14.0001 8.99998C14.0001 11.025 12.3584 12.6666 10.3334 12.6666C8.30835 12.6666 6.66673 11.025 6.66673 8.99998Z" fill="#444CE7"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M10.3334 13.3333C12.4642 13.3333 14.3691 14.5361 15.5315 16.2801C15.6339 16.4337 15.7431 16.5976 15.8194 16.7533C15.9113 16.9407 15.9773 17.156 15.9619 17.4132C15.9496 17.6183 15.8816 17.8086 15.8007 17.9597C15.7198 18.1107 15.5991 18.2728 15.4352 18.3968C15.2157 18.5628 14.9791 18.621 14.77 18.6453C14.5858 18.6667 14.3677 18.6667 14.148 18.6667C11.6059 18.6662 9.06185 18.6662 6.51877 18.6667C6.29908 18.6667 6.08098 18.6667 5.89682 18.6453C5.68769 18.621 5.4511 18.5628 5.23155 18.3968C5.06767 18.2728 4.94702 18.1107 4.86612 17.9597C4.78523 17.8086 4.71719 17.6183 4.70488 17.4132C4.68945 17.156 4.75545 16.9407 4.84734 16.7533C4.92369 16.5976 5.0329 16.4337 5.13531 16.2801C6.2977 14.5361 8.20257 13.3333 10.3334 13.3333Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/datasets/settings/permissions-radio/index.module.css b/web/app/components/datasets/settings/permissions-radio/index.module.css
new file mode 100644
index 00000000000..0c1d86409bf
--- /dev/null
+++ b/web/app/components/datasets/settings/permissions-radio/index.module.css
@@ -0,0 +1,30 @@
+.user-icon {
+ width: 24px;
+ height: 24px;
+ background: url(./assets/user.svg) center center;
+ background-size: contain;
+}
+
+.wrapper .item:hover {
+ background-color: #ffffff;
+ border-color: #B2CCFF;
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
+
+.wrapper .item-active {
+ background-color: #ffffff;
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
+
+.wrapper .item-active .radio {
+ border-width: 5px;
+ border-color: #155EEF;
+}
+
+.wrapper .item-active:hover {
+ border-width: 1.5px;
+ border-color: #528BFF;
+ box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1), 0px 1px 2px rgba(16, 24, 40, 0.06);
+}
\ No newline at end of file
diff --git a/web/app/components/datasets/settings/permissions-radio/index.tsx b/web/app/components/datasets/settings/permissions-radio/index.tsx
new file mode 100644
index 00000000000..6726bd245ff
--- /dev/null
+++ b/web/app/components/datasets/settings/permissions-radio/index.tsx
@@ -0,0 +1,57 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import classNames from 'classnames'
+import s from './index.module.css'
+import { DataSet } from '@/models/datasets'
+
+const itemClass = `
+ flex items-center w-[234px] h-12 px-3 rounded-xl bg-gray-25 border border-gray-100 cursor-pointer
+`
+const radioClass = `
+ w-4 h-4 border-[2px] border-gray-200 rounded-full
+`
+type IPermissionsRadioProps = {
+ value?: DataSet['permission']
+ onChange: (v?: DataSet['permission']) => void
+}
+
+const PermissionsRadio = ({
+ value,
+ onChange
+}: IPermissionsRadioProps) => {
+ const { t } = useTranslation()
+ const options = [
+ {
+ key: 'only_me',
+ text: t('datasetSettings.form.permissionsOnlyMe')
+ },
+ {
+ key: 'all_team_members',
+ text: t('datasetSettings.form.permissionsAllMember')
+ }
+ ]
+
+ return (
+ <div className={classNames(s.wrapper, 'flex justify-between w-full')}>
+ {
+ options.map(option => (
+ <div
+ key={option.key}
+ className={classNames(
+ option.key === value && s['item-active'],
+ itemClass,
+ s.item
+ )}
+ onClick={() => onChange(option.key as DataSet['permission'])}
+ >
+ <div className={classNames(s['user-icon'], 'mr-3')} />
+ <div className='grow text-sm text-gray-900'>{option.text}</div>
+ <div className={classNames(radioClass, s.radio)} />
+ </div>
+ ))
+ }
+ </div>
+ )
+}
+
+export default PermissionsRadio
diff --git a/web/app/components/develop/code.tsx b/web/app/components/develop/code.tsx
new file mode 100644
index 00000000000..8d841d9f7f0
--- /dev/null
+++ b/web/app/components/develop/code.tsx
@@ -0,0 +1,305 @@
+'use client'
+import {
+ Children,
+ createContext,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react'
+import { Tab } from '@headlessui/react'
+import classNames from 'classnames'
+
+import { Tag } from './tag'
+
+const languageNames = {
+ js: 'JavaScript',
+ ts: 'TypeScript',
+ javascript: 'JavaScript',
+ typescript: 'TypeScript',
+ php: 'PHP',
+ python: 'Python',
+ ruby: 'Ruby',
+ go: 'Go',
+} as { [key: string]: string }
+
+type IChildrenProps = {
+ children: React.ReactElement
+ [key: string]: any
+}
+
+function getPanelTitle({ className }: { className: string }) {
+ const language = className.split('-')[1]
+ return languageNames[language] ?? 'Code'
+}
+
+function ClipboardIcon(props: any) {
+ return (
+ <svg viewBox="0 0 20 20" aria-hidden="true" {...props}>
+ <path
+ strokeWidth="0"
+ d="M5.5 13.5v-5a2 2 0 0 1 2-2l.447-.894A2 2 0 0 1 9.737 4.5h.527a2 2 0 0 1 1.789 1.106l.447.894a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2Z"
+ />
+ <path
+ fill="none"
+ strokeLinejoin="round"
+ d="M12.5 6.5a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2m5 0-.447-.894a2 2 0 0 0-1.79-1.106h-.527a2 2 0 0 0-1.789 1.106L7.5 6.5m5 0-1 1h-3l-1-1"
+ />
+ </svg>
+ )
+}
+
+function CopyButton({ code }: { code: string }) {
+ const [copyCount, setCopyCount] = useState(0)
+ const copied = copyCount > 0
+
+ useEffect(() => {
+ if (copyCount > 0) {
+ const timeout = setTimeout(() => setCopyCount(0), 1000)
+ return () => {
+ clearTimeout(timeout)
+ }
+ }
+ }, [copyCount])
+
+ return (
+ <button
+ type="button"
+ className={classNames(
+ 'group/button absolute top-3.5 right-4 overflow-hidden rounded-full py-1 pl-2 pr-3 text-2xs font-medium opacity-0 backdrop-blur transition focus:opacity-100 group-hover:opacity-100',
+ copied
+ ? 'bg-emerald-400/10 ring-1 ring-inset ring-emerald-400/20'
+ : 'bg-white/5 hover:bg-white/7.5 dark:bg-white/2.5 dark:hover:bg-white/5',
+ )}
+ onClick={() => {
+ window.navigator.clipboard.writeText(code).then(() => {
+ setCopyCount(count => count + 1)
+ })
+ }}
+ >
+ <span
+ aria-hidden={copied}
+ className={classNames(
+ 'pointer-events-none flex items-center gap-0.5 text-zinc-400 transition duration-300',
+ copied && '-translate-y-1.5 opacity-0',
+ )}
+ >
+ <ClipboardIcon className="w-5 h-5 transition-colors fill-zinc-500/20 stroke-zinc-500 group-hover/button:stroke-zinc-400" />
+ Copy
+ </span>
+ <span
+ aria-hidden={!copied}
+ className={classNames(
+ 'pointer-events-none absolute inset-0 flex items-center justify-center text-emerald-400 transition duration-300',
+ !copied && 'translate-y-1.5 opacity-0',
+ )}
+ >
+ Copied!
+ </span>
+ </button>
+ )
+}
+
+function CodePanelHeader({ tag, label }: { tag: string; label: string }) {
+ if (!tag && !label)
+ return null
+
+ return (
+ <div className="flex h-9 items-center gap-2 border-y border-t-transparent border-b-white/7.5 bg-zinc-900 bg-white/2.5 px-4 dark:border-b-white/5 dark:bg-white/1">
+ {tag && (
+ <div className="flex dark">
+ <Tag variant="small">{tag}</Tag>
+ </div>
+ )}
+ {tag && label && (
+ <span className="h-0.5 w-0.5 rounded-full bg-zinc-500" />
+ )}
+ {label && (
+ <span className="font-mono text-xs text-zinc-400">{label}</span>
+ )}
+ </div>
+ )
+}
+
+type ICodePanelProps = {
+ children: React.ReactElement
+ tag?: string
+ code?: string
+ label?: string
+ targetCode?: string
+}
+function CodePanel({ tag, label, code, children, targetCode }: ICodePanelProps) {
+ const child = Children.only(children)
+
+ return (
+ <div className="group dark:bg-white/2.5">
+ <CodePanelHeader
+ tag={child.props.tag ?? tag}
+ label={child.props.label ?? label}
+ />
+ <div className="relative">
+ {/* <pre className="p-4 overflow-x-auto text-xs text-white">{children}</pre> */}
+ {/* <CopyButton code={child.props.code ?? code} /> */}
+ {/* <CopyButton code={child.props.children.props.children} /> */}
+ <pre className="p-4 overflow-x-auto text-xs text-white">{targetCode || children}</pre>
+ <CopyButton code={targetCode || child.props.children.props.children} />
+ </div>
+ </div>
+ )
+}
+
+function CodeGroupHeader({ title, children, selectedIndex }: IChildrenProps) {
+ const hasTabs = Children.count(children) > 1
+
+ if (!title && !hasTabs)
+ return null
+
+ return (
+ <div className="flex min-h-[calc(theme(spacing.12)+1px)] flex-wrap items-start gap-x-4 border-b border-zinc-700 bg-zinc-800 px-4 dark:border-zinc-800 dark:bg-transparent">
+ {title && (
+ <h3 className="pt-3 mr-auto text-xs font-semibold text-white">
+ {title}
+ </h3>
+ )}
+ {hasTabs && (
+ <Tab.List className="flex gap-4 -mb-px text-xs font-medium">
+ {Children.map(children, (child, childIndex) => (
+ <Tab
+ className={classNames(
+ 'border-b py-3 transition focus:[&:not(:focus-visible)]:outline-none',
+ childIndex === selectedIndex
+ ? 'border-emerald-500 text-emerald-400'
+ : 'border-transparent text-zinc-400 hover:text-zinc-300',
+ )}
+ >
+ {getPanelTitle(child.props.children.props)}
+ </Tab>
+ ))}
+ </Tab.List>
+ )}
+ </div>
+ )
+}
+
+type ICodeGroupPanelsProps = {
+ children: React.ReactElement
+ [key: string]: any
+}
+function CodeGroupPanels({ children, targetCode, ...props }: ICodeGroupPanelsProps) {
+ const hasTabs = Children.count(children) > 1
+
+ if (hasTabs) {
+ return (
+ <Tab.Panels>
+ {Children.map(children, child => (
+ <Tab.Panel>
+ <CodePanel {...props}>{child}</CodePanel>
+ </Tab.Panel>
+ ))}
+ </Tab.Panels>
+ )
+ }
+
+ return <CodePanel {...props} targetCode={targetCode}>{children}</CodePanel>
+}
+
+function usePreventLayoutShift() {
+ const positionRef = useRef<any>()
+ const rafRef = useRef<any>()
+
+ useEffect(() => {
+ return () => {
+ window.cancelAnimationFrame(rafRef.current)
+ }
+ }, [])
+
+ return {
+ positionRef,
+ preventLayoutShift(callback: () => {}) {
+ const initialTop = positionRef.current.getBoundingClientRect().top
+
+ callback()
+
+ rafRef.current = window.requestAnimationFrame(() => {
+ const newTop = positionRef.current.getBoundingClientRect().top
+ window.scrollBy(0, newTop - initialTop)
+ })
+ },
+ }
+}
+
+function useTabGroupProps(availableLanguages: string[]) {
+ const [preferredLanguages, addPreferredLanguage] = useState<any>([])
+ const [selectedIndex, setSelectedIndex] = useState(0)
+ const activeLanguage = [...availableLanguages].sort(
+ (a, z) => preferredLanguages.indexOf(z) - preferredLanguages.indexOf(a),
+ )[0]
+ const languageIndex = availableLanguages.indexOf(activeLanguage)
+ const newSelectedIndex = languageIndex === -1 ? selectedIndex : languageIndex
+ if (newSelectedIndex !== selectedIndex)
+ setSelectedIndex(newSelectedIndex)
+
+ const { positionRef, preventLayoutShift } = usePreventLayoutShift()
+
+ return {
+ as: 'div',
+ ref: positionRef,
+ selectedIndex,
+ onChange: (newSelectedIndex: number) => {
+ preventLayoutShift(() =>
+ (addPreferredLanguage(availableLanguages[newSelectedIndex]) as any),
+ )
+ },
+ }
+}
+
+const CodeGroupContext = createContext(false)
+
+export function CodeGroup({ children, title, inputs, targetCode, ...props }: IChildrenProps) {
+ const languages = Children.map(children, child =>
+ getPanelTitle(child.props.children.props)
+ )
+ const tabGroupProps = useTabGroupProps(languages)
+ const hasTabs = Children.count(children) > 1
+ const Container = hasTabs ? Tab.Group : 'div'
+ const containerProps = hasTabs ? tabGroupProps : {}
+ const headerProps = hasTabs
+ ? { selectedIndex: tabGroupProps.selectedIndex }
+ : {}
+
+ return (
+ <CodeGroupContext.Provider value={true}>
+ <Container
+ {...containerProps}
+ className="my-6 overflow-hidden shadow-md not-prose rounded-2xl bg-zinc-900 dark:ring-1 dark:ring-white/10"
+ >
+ <CodeGroupHeader title={title} {...headerProps}>
+ {children}
+ </CodeGroupHeader>
+ <CodeGroupPanels {...props} targetCode={targetCode}>{children}</CodeGroupPanels>
+ </Container>
+ </CodeGroupContext.Provider>
+ )
+}
+
+type IChildProps = {
+ children: string
+ [key: string]: any
+}
+export function Code({ children, ...props }: IChildProps) {
+ const isGrouped = useContext(CodeGroupContext)
+
+ if (isGrouped)
+ return <code {...props} dangerouslySetInnerHTML={{ __html: children }} />
+
+ return <code {...props}>{children}</code>
+}
+
+export function Pre({ children, ...props }: IChildrenProps) {
+ const isGrouped = useContext(CodeGroupContext)
+
+ if (isGrouped)
+ return children
+
+ return <CodeGroup {...props}>{children}</CodeGroup>
+}
diff --git a/web/app/components/develop/doc.tsx b/web/app/components/develop/doc.tsx
new file mode 100644
index 00000000000..ce1f95001f1
--- /dev/null
+++ b/web/app/components/develop/doc.tsx
@@ -0,0 +1,33 @@
+'use client'
+import TemplateEn from './template/template.en.mdx'
+import TemplateZh from './template/template.zh.mdx'
+import TemplateChatEn from './template/template_chat.en.mdx'
+import TemplateChatZh from './template/template_chat.zh.mdx'
+import { useContext } from 'use-context-selector'
+import I18n from '@/context/i18n'
+
+type IDocProps = {
+ appDetail: any
+}
+
+const Doc = ({ appDetail }: IDocProps) => {
+ const { locale } = useContext(I18n)
+ const variables = appDetail?.model_config?.configs?.prompt_variables || []
+ const inputs = variables.reduce((res: any, variable: any) => {
+ res[variable.key] = variable.name || '';
+ return res
+ }, {})
+
+ return (
+ <article className="prose prose-xl" >
+ {appDetail?.mode === 'completion' ? (
+ locale === 'en' ? <TemplateEn appDetail={appDetail} variables={variables} inputs={inputs} /> : <TemplateZh appDetail={appDetail} variables={variables} inputs={inputs} />
+ ) : (
+ locale === 'en' ? <TemplateChatEn appDetail={appDetail} variables={variables} inputs={inputs} /> : <TemplateChatZh appDetail={appDetail} variables={variables} inputs={inputs} />
+ )}
+ </article>
+ )
+
+}
+
+export default Doc
diff --git a/web/app/components/develop/index.tsx b/web/app/components/develop/index.tsx
new file mode 100644
index 00000000000..0882453be64
--- /dev/null
+++ b/web/app/components/develop/index.tsx
@@ -0,0 +1,47 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import useSWR from 'swr'
+import Doc from '@/app/components/develop/doc'
+import InputCopy from '@/app/components/develop/secret-key/input-copy'
+import SecretKeyButton from '@/app/components/develop/secret-key/secret-key-button'
+import { fetchAppDetail } from '@/service/apps'
+import s from './secret-key/style.module.css'
+
+type IDevelopMainProps = {
+ appId: string
+ dictionary: any
+}
+
+const DevelopMain = ({ appId, dictionary }: IDevelopMainProps) => {
+ const commonParams = { url: '/apps', id: appId }
+ const { data: appDetail } = useSWR(commonParams, fetchAppDetail)
+ const { t } = useTranslation()
+
+ // const serverApi = `${appDetail?.site?.app_base_url}/api/${appDetail?.site?.access_token}`
+
+ return (
+ <div className='relative flex flex-col h-full overflow-hidden'>
+ <div className='flex items-center justify-between flex-shrink-0 px-6 border-b border-solid h-14 border-b-gray-100'>
+ <div className='text-lg font-medium text-gray-900'>{dictionary.app?.develop?.title}</div>
+ <div className='flex items-center'>
+ <InputCopy className={`flex-shrink-0 mr-1 w-60 ${s.w320}`} value={appDetail?.api_base_url}>
+ <div className={`ml-2 border border-gray-200 border-solid flex-shrink-0 px-2 py-0.5 rounded-[6px] text-gray-500 text-[0.625rem] ${s.customApi}`}>
+ {t('appApi.apiServer')}
+ </div>
+ </InputCopy>
+ <div className={`flex items-center h-9 px-3 rounded-lg
+ text-[13px] font-normal mr-2 ${appDetail?.enable_api ? 'text-green-500 bg-green-50' : 'text-yellow-500 bg-yellow-50'}`}>
+ <div className='mr-1'>{t('appApi.status')}</div>
+ <div className='font-semibold'>{appDetail?.enable_api ? `${t('appApi.ok')}` : `${t('appApi.disabled')}`}</div>
+ </div>
+ <SecretKeyButton className='flex-shrink-0' appId={appId} />
+ </div>
+ </div>
+ <div className='px-10 py-4 overflow-auto grow'>
+ <Doc appDetail={appDetail} />
+ </div>
+ </div>
+ )
+}
+
+export default DevelopMain
diff --git a/web/app/components/develop/md.tsx b/web/app/components/develop/md.tsx
new file mode 100644
index 00000000000..508a0fd7f65
--- /dev/null
+++ b/web/app/components/develop/md.tsx
@@ -0,0 +1,140 @@
+'use client'
+import classNames from 'classnames'
+
+type IChildrenProps = {
+ children: React.ReactNode
+ id?: string
+ tag?: any
+ label?: any
+ anchor: boolean
+}
+
+type IHeaderingProps = {
+ url: string
+ method: 'PUT' | 'DELETE' | 'GET' | 'POST'
+ title: string
+ name: string
+}
+
+export const Heading = function H2({
+ url,
+ method,
+ title,
+ name,
+}: IHeaderingProps) {
+ let style = '';
+ switch (method) {
+ case 'PUT':
+ style = 'ring-amber-300 bg-amber-400/10 text-amber-500 dark:ring-amber-400/30 dark:bg-amber-400/10 dark:text-amber-400';
+ break;
+ case 'DELETE':
+ style = 'ring-rose-200 bg-rose-50 text-red-500 dark:ring-rose-500/20 dark:bg-rose-400/10 dark:text-rose-400';
+ break;
+ case 'POST':
+ style = 'ring-sky-300 bg-sky-400/10 text-sky-500 dark:ring-sky-400/30 dark:bg-sky-400/10 dark:text-sky-400';
+ break;
+ default:
+ style = 'ring-emerald-300 dark:ring-emerald-400/30 bg-emerald-400/10 text-emerald-500 dark:text-emerald-400';
+ break;
+ }
+ return (
+ <>
+ <div className="flex items-center gap-x-3" >
+ <span className={`font-mono text-[0.625rem] font-semibold leading-6 rounded-lg px-1.5 ring-1 ring-inset ${style}`}>{method}</span>
+ {/* <span className="h-0.5 w-0.5 rounded-full bg-zinc-300 dark:bg-zinc-600"></span> */}
+ <span className="font-mono text-xs text-zinc-400">{url}</span>
+ </div>
+ <h2 className='mt-2 scroll-mt-32'>
+ <a href={name} className='no-underline group text-inherit hover:text-inherit'>{title}</a>
+ </h2>
+ </>
+
+ )
+}
+
+export function Row({ children }: IChildrenProps) {
+ return (
+ <div className="grid items-start grid-cols-1 gap-x-16 gap-y-10 xl:max-w-none xl:grid-cols-2">
+ {children}
+ </div>
+ )
+}
+
+type IColProps = IChildrenProps & {
+ sticky: boolean
+}
+export function Col({ children, sticky = false }: IColProps) {
+ return (
+ <div
+ className={classNames(
+ '[&>:first-child]:mt-0 [&>:last-child]:mb-0',
+ sticky && 'xl:sticky xl:top-24',
+ )}
+ >
+ {children}
+ </div>
+ )
+}
+
+export function Properties({ children }: IChildrenProps) {
+ return (
+ <div className="my-6">
+ <ul
+ role="list"
+ className="m-0 max-w-[calc(theme(maxWidth.lg)-theme(spacing.8))] list-none divide-y divide-zinc-900/5 p-0 dark:divide-white/5"
+ >
+ {children}
+ </ul>
+ </div>
+ )
+}
+
+type IProperty = IChildrenProps & {
+ name: string
+ type: string
+}
+export function Property({ name, type, children }: IProperty) {
+ return (
+ <li className="px-0 py-4 m-0 first:pt-0 last:pb-0">
+ <dl className="flex flex-wrap items-center m-0 gap-x-3 gap-y-2">
+ <dt className="sr-only">Name</dt>
+ <dd>
+ <code>{name}</code>
+ </dd>
+ <dt className="sr-only">Type</dt>
+ <dd className="font-mono text-xs text-zinc-400 dark:text-zinc-500">
+ {type}
+ </dd>
+ <dt className="sr-only">Description</dt>
+ <dd className="w-full flex-none [&>:first-child]:mt-0 [&>:last-child]:mb-0">
+ {children}
+ </dd>
+ </dl>
+ </li>
+ )
+}
+
+type ISubProperty = IChildrenProps & {
+ name: string
+ type: string
+}
+export function SubProperty({ name, type, children }: ISubProperty) {
+ return (
+ <li className="px-0 py-1 m-0 last:pb-0">
+ <dl className="flex flex-wrap items-center m-0 gap-x-3">
+ <dt className="sr-only">Name</dt>
+ <dd>
+ <code>{name}</code>
+ </dd>
+ <dt className="sr-only">Type</dt>
+ <dd className="font-mono text-xs text-zinc-400 dark:text-zinc-500">
+ {type}
+ </dd>
+ <dt className="sr-only">Description</dt>
+ <dd className="w-full flex-none [&>:first-child]:mt-0 [&>:last-child]:mb-0">
+ {children}
+ </dd>
+ </dl>
+ </li>
+ )
+}
diff --git a/web/app/components/develop/secret-key/assets/copied.svg b/web/app/components/develop/secret-key/assets/copied.svg
new file mode 100644
index 00000000000..de5f86cc197
--- /dev/null
+++ b/web/app/components/develop/secret-key/assets/copied.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10.6665 2.66683C11.2865 2.66683 11.5965 2.66683 11.8508 2.73498C12.541 2.91991 13.0801 3.45901 13.265 4.14919C13.3332 4.40352 13.3332 4.71352 13.3332 5.3335V11.4668C13.3332 12.5869 13.3332 13.147 13.1152 13.5748C12.9234 13.9511 12.6175 14.2571 12.2412 14.4488C11.8133 14.6668 11.2533 14.6668 10.1332 14.6668H5.8665C4.7464 14.6668 4.18635 14.6668 3.75852 14.4488C3.3822 14.2571 3.07624 13.9511 2.88449 13.5748C2.6665 13.147 2.6665 12.5869 2.6665 11.4668V5.3335C2.6665 4.71352 2.6665 4.40352 2.73465 4.14919C2.91959 3.45901 3.45868 2.91991 4.14887 2.73498C4.4032 2.66683 4.71319 2.66683 5.33317 2.66683M5.99984 10.0002L7.33317 11.3335L10.3332 8.3335M6.39984 4.00016H9.59984C9.9732 4.00016 10.1599 4.00016 10.3025 3.9275C10.4279 3.86359 10.5299 3.7616 10.5938 3.63616C10.6665 3.49355 10.6665 3.30686 10.6665 2.9335V2.40016C10.6665 2.02679 10.6665 1.84011 10.5938 1.6975C10.5299 1.57206 10.4279 1.47007 10.3025 1.40616C10.1599 1.3335 9.97321 1.3335 9.59984 1.3335H6.39984C6.02647 1.3335 5.83978 1.3335 5.69718 1.40616C5.57174 1.47007 5.46975 1.57206 5.40583 1.6975C5.33317 1.84011 5.33317 2.02679 5.33317 2.40016V2.9335C5.33317 3.30686 5.33317 3.49355 5.40583 3.63616C5.46975 3.7616 5.57174 3.86359 5.69718 3.9275C5.83978 4.00016 6.02647 4.00016 6.39984 4.00016Z" stroke="#1D2939" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/develop/secret-key/assets/copy-hover.svg b/web/app/components/develop/secret-key/assets/copy-hover.svg
new file mode 100644
index 00000000000..ca8334aed24
--- /dev/null
+++ b/web/app/components/develop/secret-key/assets/copy-hover.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10.6665 2.66634H11.9998C12.3535 2.66634 12.6926 2.80682 12.9426 3.05687C13.1927 3.30691 13.3332 3.64605 13.3332 3.99967V13.333C13.3332 13.6866 13.1927 14.0258 12.9426 14.2758C12.6926 14.5259 12.3535 14.6663 11.9998 14.6663H3.99984C3.64622 14.6663 3.30708 14.5259 3.05703 14.2758C2.80698 14.0258 2.6665 13.6866 2.6665 13.333V3.99967C2.6665 3.64605 2.80698 3.30691 3.05703 3.05687C3.30708 2.80682 3.64622 2.66634 3.99984 2.66634H5.33317M5.99984 1.33301H9.99984C10.368 1.33301 10.6665 1.63148 10.6665 1.99967V3.33301C10.6665 3.7012 10.368 3.99967 9.99984 3.99967H5.99984C5.63165 3.99967 5.33317 3.7012 5.33317 3.33301V1.99967C5.33317 1.63148 5.63165 1.33301 5.99984 1.33301Z" stroke="#1D2939" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/develop/secret-key/assets/copy.svg b/web/app/components/develop/secret-key/assets/copy.svg
new file mode 100644
index 00000000000..18d2b4e7fcd
--- /dev/null
+++ b/web/app/components/develop/secret-key/assets/copy.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10.6665 2.66634H11.9998C12.3535 2.66634 12.6926 2.80682 12.9426 3.05687C13.1927 3.30691 13.3332 3.64605 13.3332 3.99967V13.333C13.3332 13.6866 13.1927 14.0258 12.9426 14.2758C12.6926 14.5259 12.3535 14.6663 11.9998 14.6663H3.99984C3.64622 14.6663 3.30708 14.5259 3.05703 14.2758C2.80698 14.0258 2.6665 13.6866 2.6665 13.333V3.99967C2.6665 3.64605 2.80698 3.30691 3.05703 3.05687C3.30708 2.80682 3.64622 2.66634 3.99984 2.66634H5.33317M5.99984 1.33301H9.99984C10.368 1.33301 10.6665 1.63148 10.6665 1.99967V3.33301C10.6665 3.7012 10.368 3.99967 9.99984 3.99967H5.99984C5.63165 3.99967 5.33317 3.7012 5.33317 3.33301V1.99967C5.33317 1.63148 5.63165 1.33301 5.99984 1.33301Z" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/develop/secret-key/assets/trash-gray.svg b/web/app/components/develop/secret-key/assets/trash-gray.svg
new file mode 100644
index 00000000000..ef65c30e909
--- /dev/null
+++ b/web/app/components/develop/secret-key/assets/trash-gray.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M6 2H10M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4M6.66667 7V10.3333M9.33333 7V10.3333" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/develop/secret-key/assets/trash-red.svg b/web/app/components/develop/secret-key/assets/trash-red.svg
new file mode 100644
index 00000000000..4266dde6edb
--- /dev/null
+++ b/web/app/components/develop/secret-key/assets/trash-red.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M6 2H10M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4M6.66667 7V10.3333M9.33333 7V10.3333" stroke="#D92D20" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/web/app/components/develop/secret-key/input-copy.tsx b/web/app/components/develop/secret-key/input-copy.tsx
new file mode 100644
index 00000000000..7cb88138fa0
--- /dev/null
+++ b/web/app/components/develop/secret-key/input-copy.tsx
@@ -0,0 +1,71 @@
+'use client'
+import React, { useEffect, useState } from 'react'
+import useCopyToClipboard from '@/hooks/use-copy-to-clipboard'
+import Tooltip from '@/app/components/base/tooltip'
+import { t } from 'i18next'
+import s from './style.module.css'
+
+type IInputCopyProps = {
+ value?: string
+ className?: string
+ readOnly?: boolean
+ children?: React.ReactNode
+}
+
+const InputCopy = ({
+ value,
+ className,
+ readOnly = true,
+ children,
+}: IInputCopyProps) => {
+ const [_, copy] = useCopyToClipboard()
+ const [isCopied, setIsCopied] = useState(false)
+
+ useEffect(() => {
+ if (isCopied) {
+ const timeout = setTimeout(() => {
+ setIsCopied(false)
+ }, 1000)
+
+ return () => {
+ clearTimeout(timeout)
+ }
+ }
+ }, [isCopied])
+
+ return (
+ <div className={`flex rounded-lg bg-gray-50 hover:bg-gray-50 py-2 items-center ${className}`}>
+ <div className="flex items-center flex-grow h-5">
+ {children}
+ <div className='flex-grow bg-gray-50 text-[13px] relative h-full'>
+ <Tooltip
+ selector="top-uniq"
+ content={isCopied ? `${t('appApi.copied')}` : `${t('appApi.copy')}`}
+ className='z-10'
+ >
+ <div className='absolute top-0 left-0 w-full pl-2 pr-2 truncate cursor-pointer r-0' onClick={() => {
+ copy(value)
+ setIsCopied(true)
+ }}>{value}</div>
+ </Tooltip>
+ </div>
+ <div className="flex-shrink-0 h-4 bg-gray-200 border" />
+ <Tooltip
+ selector="top-uniq"
+ content={isCopied ? `${t('appApi.copied')}` : `${t('appApi.copy')}`}
+ className='z-10'
+ >
+ <div className="px-0.5 flex-shrink-0">
+ <div className={`box-border w-[30px] h-[30px] flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer ${s.copyIcon} ${isCopied ? s.copied : ''}`} onClick={() => {
+ copy(value)
+ setIsCopied(true)
+ }}>
+ </div>
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ )
+}
+
+export default InputCopy
diff --git a/web/app/components/develop/secret-key/secret-key-button.tsx b/web/app/components/develop/secret-key/secret-key-button.tsx
new file mode 100644
index 00000000000..7532a1247bc
--- /dev/null
+++ b/web/app/components/develop/secret-key/secret-key-button.tsx
@@ -0,0 +1,31 @@
+'use client'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import SecretKeyModal from '@/app/components/develop/secret-key/secret-key-modal'
+// import { KeyIcon } from '@heroicons/react/20/solid'
+
+type ISecretKeyButtonProps = {
+ className?: string
+ appId: string
+}
+
+const SecretKeyButton = ({ className, appId }: ISecretKeyButtonProps) => {
+ const [isVisible, setVisible] = useState(false)
+ const { t } = useTranslation()
+ return (
+ <>
+ <Button className={`px-3 ${className}`} type='default' onClick={() => setVisible(true)}>
+ <div className='flex items-center justify-center w-4 h-4 mr-2'>
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M9 3.66672C9.35362 3.66672 9.69276 3.80719 9.94281 4.05724C10.1929 4.30729 10.3333 4.64643 10.3333 5.00005M13 5.00005C13.0002 5.62483 12.854 6.24097 12.5732 6.79908C12.2924 7.3572 11.8847 7.84177 11.3829 8.21397C10.8811 8.58617 10.2991 8.83564 9.68347 8.94239C9.06788 9.04915 8.43584 9.01022 7.838 8.82872L6.33333 10.3334H5V11.6667H3.66667V13.0001H1.66667C1.48986 13.0001 1.32029 12.9298 1.19526 12.8048C1.07024 12.6798 1 12.5102 1 12.3334V10.6094C1.00004 10.4326 1.0703 10.263 1.19533 10.1381L5.17133 6.16205C5.00497 5.61206 4.95904 5.03268 5.0367 4.46335C5.11435 3.89402 5.31375 3.3481 5.62133 2.86275C5.92891 2.3774 6.33744 1.96401 6.81913 1.65073C7.30082 1.33745 7.84434 1.13162 8.41272 1.04725C8.9811 0.96289 9.56098 1.00197 10.1129 1.16184C10.6648 1.32171 11.1758 1.59861 11.6111 1.97369C12.0464 2.34878 12.3958 2.81324 12.6354 3.33548C12.8751 3.85771 12.9994 4.42545 13 5.00005Z" stroke="#1F2A37" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </div>
+ <div className='text-[13px] text-gray-800'>{t('appApi.apiKey')}</div>
+ </Button>
+ <SecretKeyModal isShow={isVisible} onClose={() => setVisible(false)} appId={appId} />
+ </>
+ )
+}
+
+export default SecretKeyButton
diff --git a/web/app/components/develop/secret-key/secret-key-generate.tsx b/web/app/components/develop/secret-key/secret-key-generate.tsx
new file mode 100644
index 00000000000..baac8341b2e
--- /dev/null
+++ b/web/app/components/develop/secret-key/secret-key-generate.tsx
@@ -0,0 +1,41 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { XMarkIcon } from '@heroicons/react/20/solid'
+import InputCopy from './input-copy'
+import s from './style.module.css'
+import Button from '@/app/components/base/button'
+import Modal from '@/app/components/base/modal'
+import type { CreateApiKeyResponse } from '@/models/app'
+
+type ISecretKeyGenerateModalProps = {
+ isShow: boolean
+ onClose: () => void
+ newKey?: CreateApiKeyResponse
+ className?: string
+}
+
+const SecretKeyGenerateModal = ({
+ isShow = false,
+ onClose,
+ newKey,
+ className
+}: ISecretKeyGenerateModalProps) => {
+ const { t } = useTranslation()
+ return (
+ <Modal isShow={isShow} onClose={onClose} title={`${t('appApi.apiKeyModal.apiSecretKey')}`} className={`px-8 ${className}`}>
+ <XMarkIcon className={`w-6 h-6 absolute cursor-pointer text-gray-500 ${s.close}`} onClick={onClose} />
+ <p className='mt-1 text-[13px] text-gray-500 font-normal leading-5'>{t('appApi.apiKeyModal.generateTips')}</p>
+ <div className='my-4'>
+ <InputCopy className='w-full' value={newKey?.token} />
+ </div>
+ <div className='flex justify-end my-4'>
+ <Button type='default' className={`flex-shrink-0 ${s.w64}`} onClick={onClose}>
+ <span className='text-xs font-medium text-gray-800'>{t('appApi.actionMsg.ok')}</span>
+ </Button>
+ </div>
+
+ </Modal >
+ )
+}
+
+export default SecretKeyGenerateModal
diff --git a/web/app/components/develop/secret-key/secret-key-modal.tsx b/web/app/components/develop/secret-key/secret-key-modal.tsx
new file mode 100644
index 00000000000..f120d59ac5e
--- /dev/null
+++ b/web/app/components/develop/secret-key/secret-key-modal.tsx
@@ -0,0 +1,165 @@
+'use client'
+import {
+ useEffect,
+ useState,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import { PlusIcon, XMarkIcon } from '@heroicons/react/20/solid'
+import useSWR, { useSWRConfig } from 'swr'
+import SecretKeyGenerateModal from './secret-key-generate'
+import s from './style.module.css'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import { createApikey, delApikey, fetchApiKeysList } from '@/service/apps'
+import type { CreateApiKeyResponse } from '@/models/app'
+import Tooltip from '@/app/components/base/tooltip'
+import Loading from '@/app/components/base/loading'
+import Confirm from '@/app/components/base/confirm'
+import useCopyToClipboard from '@/hooks/use-copy-to-clipboard'
+import { useContext } from 'use-context-selector'
+import I18n from '@/context/i18n'
+
+type ISecretKeyModalProps = {
+ isShow: boolean
+ appId: string
+ onClose: () => void
+}
+
+const SecretKeyModal = ({
+ isShow = false,
+ appId,
+ onClose,
+}: ISecretKeyModalProps) => {
+ const { t } = useTranslation()
+ const [showConfirmDelete, setShowConfirmDelete] = useState(false)
+ const [isVisible, setVisible] = useState(false)
+ const [newKey, setNewKey] = useState<CreateApiKeyResponse | undefined>(undefined)
+ const { mutate } = useSWRConfig()
+ const commonParams = { url: `/apps/${appId}/api-keys`, params: {} }
+ const { data: apiKeysList } = useSWR(commonParams, fetchApiKeysList)
+
+ const [delKeyID, setDelKeyId] = useState('')
+ const [_, copy] = useCopyToClipboard()
+
+ const { locale } = useContext(I18n)
+
+ // const [isCopied, setIsCopied] = useState(false)
+ const [copyValue, setCopyValue] = useState('')
+
+ useEffect(() => {
+ if (copyValue) {
+ const timeout = setTimeout(() => {
+ setCopyValue('')
+ }, 1000)
+
+ return () => {
+ clearTimeout(timeout)
+ }
+ }
+ }, [copyValue])
+
+
+ const onDel = async () => {
+ setShowConfirmDelete(false)
+ if (!delKeyID) {
+ return
+ }
+ await delApikey({ url: `/apps/${appId}/api-keys/${delKeyID}`, params: {} })
+ mutate(commonParams)
+ }
+
+ const onCreate = async () => {
+ const res = await createApikey({ url: `/apps/${appId}/api-keys`, body: {} })
+ setVisible(true)
+ setNewKey(res)
+ mutate(commonParams)
+ }
+
+ const generateToken = (token: string) => {
+ return `${token.slice(0, 3)}...${token.slice(-20)}`
+ }
+
+ const formatDate = (timestamp: any) => {
+ if (locale === 'en') {
+ return new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' }).format((+timestamp) * 1000)
+ } else {
+ return new Intl.DateTimeFormat('fr-CA', { year: 'numeric', month: '2-digit', day: '2-digit' }).format((+timestamp) * 1000)
+ }
+ }
+
+ return (
+ <Modal isShow={isShow} onClose={onClose} title={`${t('appApi.apiKeyModal.apiSecretKey')}`} className={`${s.customModal} px-8 flex flex-col`}>
+ <XMarkIcon className={`w-6 h-6 absolute cursor-pointer text-gray-500 ${s.close}`} onClick={onClose} />
+ <p className='mt-1 text-[13px] text-gray-500 font-normal leading-5 flex-shrink-0'>{t('appApi.apiKeyModal.apiSecretKeyTips')}</p>
+ {!apiKeysList && <div className='mt-4'><Loading /></div>}
+ {
+ !!apiKeysList?.data?.length && (
+ <div className='flex flex-col flex-grow mt-4 overflow-hidden'>
+ <div className='flex items-center flex-shrink-0 text-xs font-semibold text-gray-500 border-b border-solid h-9'>
+ <div className='flex-shrink-0 w-64 px-3'>{t('appApi.apiKeyModal.secretKey')}</div>
+ <div className='flex-shrink-0 px-3 w-28'>{t('appApi.apiKeyModal.created')}</div>
+ <div className='flex-shrink-0 px-3 w-28'>{t('appApi.apiKeyModal.lastUsed')}</div>
+ <div className='flex-grow px-3'></div>
+ </div>
+ <div className='flex-grow overflow-auto'>
+ {apiKeysList.data.map(api => (
+ <div className='flex items-center text-sm font-normal text-gray-700 border-b border-solid h-9' key={api.id}>
+ <div className='flex-shrink-0 w-64 px-3 font-mono truncate'>{generateToken(api.token)}</div>
+ <div className='flex-shrink-0 px-3 truncate w-28'>{formatDate(api.created_at)}</div>
+ {/* <div className='flex-shrink-0 px-3 truncate w-28'>{dayjs((+api.created_at) * 1000).format('MMM D, YYYY')}</div> */}
+ {/* <div className='flex-shrink-0 px-3 truncate w-28'>{api.last_used_at ? dayjs((+api.last_used_at) * 1000).format('MMM D, YYYY') : 'Never'}</div> */}
+ <div className='flex-shrink-0 px-3 truncate w-28'>{api.last_used_at ? formatDate(api.last_used_at) : t('appApi.never')}</div>
+ <div className='flex flex-grow px-3'>
+ <Tooltip
+ selector="top-uniq"
+ content={copyValue === api.token ? `${t('appApi.copied')}` : `${t('appApi.copy')}`}
+ className='z-10'
+ >
+ <div className={`flex items-center justify-center flex-shrink-0 w-6 h-6 mr-1 rounded-lg cursor-pointer hover:bg-gray-100 ${s.copyIcon} ${copyValue === api.token ? s.copied : ''}`} onClick={() => {
+ // setIsCopied(true)
+ copy(api.token)
+ setCopyValue(api.token)
+ }}></div>
+ </Tooltip>
+ <div className={`flex items-center justify-center flex-shrink-0 w-6 h-6 rounded-lg cursor-pointer ${s.trashIcon}`} onClick={() => {
+ setDelKeyId(api.id)
+ setShowConfirmDelete(true)
+ }}>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+ }
+ <div className='flex'>
+ <Button type='default' className={`flex flex-shrink-0 mt-4 ${s.autoWidth}`} onClick={() =>
+ onCreate()
+ }>
+ <PlusIcon className='flex flex-shrink-0 w-4 h-4' />
+ <div className='text-xs font-medium text-gray-800'>{t('appApi.apiKeyModal.createNewSecretKey')}</div>
+ </Button>
+ </div>
+ <SecretKeyGenerateModal className='flex-shrink-0' isShow={isVisible} onClose={() => setVisible(false)} newKey={newKey} />
+ {showConfirmDelete && (
+ <Confirm
+ title={`${t('appApi.actionMsg.deleteConfirmTitle')}`}
+ content={`${t('appApi.actionMsg.deleteConfirmTips')}`}
+ isShow={showConfirmDelete}
+ onClose={() => {
+ setDelKeyId('')
+ setShowConfirmDelete(false)
+ }}
+ onConfirm={onDel}
+ onCancel={() => {
+ setDelKeyId('')
+ setShowConfirmDelete(false)
+ }}
+ />
+ )}
+ </Modal >
+ )
+}
+
+export default SecretKeyModal
diff --git a/web/app/components/develop/secret-key/style.module.css b/web/app/components/develop/secret-key/style.module.css
new file mode 100644
index 00000000000..095bbac1290
--- /dev/null
+++ b/web/app/components/develop/secret-key/style.module.css
@@ -0,0 +1,61 @@
+.customModal {
+ max-width: 40rem !important;
+ max-height: calc(100vh - 80px);
+}
+
+.close {
+ top: 1.5rem;
+ right: 1.5rem;
+}
+
+.trash {
+ color: transparent;
+}
+
+.w64 {
+ width: 4rem;
+}
+
+.w320 {
+ width: 20rem;
+}
+
+.customApi {
+ font-size: 11px;
+}
+
+.autoWidth {
+ width: auto;
+}
+
+.trashIcon {
+ background-color: transparent;
+ background-image: url(./assets/trash-gray.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 16px 16px;
+}
+
+.trashIcon:hover {
+ background-color: rgba(254, 228, 226, 1);
+ background-image: url(./assets/trash-red.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 16px 16px;
+}
+
+.copyIcon {
+ background-image: url(./assets/copy.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+}
+
+.copyIcon:hover {
+ background-image: url(./assets/copy-hover.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+}
+
+.copyIcon.copied {
+ background-image: url(./assets/copied.svg);
+}
\ No newline at end of file
diff --git a/web/app/components/develop/tag.tsx b/web/app/components/develop/tag.tsx
new file mode 100644
index 00000000000..c7816fafbcc
--- /dev/null
+++ b/web/app/components/develop/tag.tsx
@@ -0,0 +1,65 @@
+'use client'
+import classNames from 'classnames'
+
+const variantStyles = {
+ medium: 'rounded-lg px-1.5 ring-1 ring-inset',
+} as { [key: string]: string }
+
+const colorStyles = {
+ emerald: {
+ small: 'text-emerald-500 dark:text-emerald-400',
+ medium:
+ 'ring-emerald-300 dark:ring-emerald-400/30 bg-emerald-400/10 text-emerald-500 dark:text-emerald-400',
+ },
+ sky: {
+ small: 'text-sky-500',
+ medium:
+ 'ring-sky-300 bg-sky-400/10 text-sky-500 dark:ring-sky-400/30 dark:bg-sky-400/10 dark:text-sky-400',
+ },
+ amber: {
+ small: 'text-amber-500',
+ medium:
+ 'ring-amber-300 bg-amber-400/10 text-amber-500 dark:ring-amber-400/30 dark:bg-amber-400/10 dark:text-amber-400',
+ },
+ rose: {
+ small: 'text-red-500 dark:text-rose-500',
+ medium:
+ 'ring-rose-200 bg-rose-50 text-red-500 dark:ring-rose-500/20 dark:bg-rose-400/10 dark:text-rose-400',
+ },
+ zinc: {
+ small: 'text-zinc-400 dark:text-zinc-500',
+ medium:
+ 'ring-zinc-200 bg-zinc-50 text-zinc-500 dark:ring-zinc-500/20 dark:bg-zinc-400/10 dark:text-zinc-400',
+ },
+} as { [key: string]: { [key: string]: string } }
+
+const valueColorMap = {
+ get: 'emerald',
+ post: 'sky',
+ put: 'amber',
+ delete: 'rose',
+} as { [key: string]: string }
+
+type ITagProps = {
+ children: string
+ color?: string
+ variant?: string
+}
+
+export function Tag({
+ children,
+ variant = 'medium',
+ color = valueColorMap[children.toLowerCase()] ?? 'emerald',
+}: ITagProps) {
+ return (
+ <span
+ className={classNames(
+ 'font-mono text-[0.625rem] font-semibold leading-6',
+ variantStyles[variant],
+ colorStyles[color][variant],
+ )}
+ >
+ {children}
+ </span>
+ )
+}
diff --git a/web/app/components/develop/template/template.en.mdx b/web/app/components/develop/template/template.en.mdx
new file mode 100644
index 00000000000..98b9f8c5860
--- /dev/null
+++ b/web/app/components/develop/template/template.en.mdx
@@ -0,0 +1,206 @@
+import { CodeGroup } from '../code.tsx'
+import { Row, Col, Properties, Property, Heading, SubProperty, Paragraph } from '../md.tsx'
+
+# Completion App API
+
+For high-quality text generation, such as articles, summaries, and translations, use the completion-messages API with user input. Text generation relies on the model parameters and prompt templates set in LangGenius Prompt Engineering.
+
+<Heading
+ url='/completion-messages'
+ method='POST'
+ title='Create Completion Message'
+ name='#Create-Completion-Message'
+/>
+<Row>
+ <Col>
+ Create a Completion Message to support the question-and-answer mode.
+
+ ### Request Body
+
+ <Properties>
+ <Property name='inputs' type='object' key='inputs'>
+ (Optional) Provide user input fields as key-value pairs, corresponding to variables in Prompt Eng. Key is the variable name, Value is the parameter value. If the field type is Select, the submitted Value must be one of the preset choices.
+ <ul>
+ {!!props.variables.length && props.variables.map(
+ val => (
+ <SubProperty name={val.key} type={val.type} key={val.key}>
+ {val.name ? `${val.name}` : ''}
+ </SubProperty>
+ )
+ )}
+ </ul>
+ </Property>
+ <Property name='query' type='string' key='query'>
+ User input text content.
+ </Property>
+ <Property name='response_mode' type='string' key='response_mode'>
+ - Blocking type, waiting for execution to complete and returning results. (Requests may be interrupted if the process is long)
+ - streaming returns. Implementation of streaming return based on SSE (**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**).
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/completion-messages" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/completion-messages' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "inputs": ${JSON.stringify(props.inputs)},\n "query": "Hi",\n "response_mode": "streaming"\n "user": "abc-123"\n}'\n`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/completion-messages' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "inputs": {},
+ "query": "Hi",
+ "response_mode": "streaming",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+ ### blocking
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "id": "0b089b9a-24d9-48cc-94f8-762677276261",
+ "answer": "how are you?",
+ "created_at": 1679586667
+ }
+ ```
+ </CodeGroup>
+ ### streaming
+ <CodeGroup title="Response">
+ ```streaming {{ title: 'Response' }}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages/{message_id}/feedbacks'
+ method='POST'
+ title='Message feedback (like)'
+ name='#feedbacks'
+/>
+<Row>
+ <Col>
+ Rate received messages on behalf of end-users with likes or dislikes. This data is visible in the Logs & Annotations page and used for future model fine-tuning.
+
+ ### Path Params
+
+ <Properties>
+ <Property name='message_id' type='string' key='message_id'>
+ Message ID
+ </Property>
+ </Properties>
+
+ ### Request Body
+
+ <Properties>
+ <Property name='rating' type='string' key='rating'>
+ like or dislike, null is undo
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/messages/{message_id}/feedbacks" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/messages/{message_id}/feedbacks \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n --data-raw '{ \n "rating": "like",\n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/messages/{message_id}/feedbacks' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "rating": "like",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/parameters'
+ method='GET'
+ title='Obtain application parameter information'
+ name='#parameters'
+/>
+<Row>
+ <Col>
+ Retrieve configured Input parameters, including variable names, field names, types, and default values. Typically used for displaying these fields in a form or filling in default values after the client loads.
+
+ ### Query
+
+ <Properties>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/parameters" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/parameters?user=abc-123' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/parameters?user=abc-123' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "introduction": "nice to meet you",
+ "variables": [
+ {
+ "key": "book",
+ "name": "Which book?",
+ "description": null,
+ "type": "string",
+ "default": null,
+ "options": null
+ },
+ {
+ // ...
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
diff --git a/web/app/components/develop/template/template.zh.mdx b/web/app/components/develop/template/template.zh.mdx
new file mode 100644
index 00000000000..dd1183bfea1
--- /dev/null
+++ b/web/app/components/develop/template/template.zh.mdx
@@ -0,0 +1,206 @@
+import { CodeGroup } from '../code.tsx'
+import { Row, Col, Properties, Property, Heading, SubProperty } from '../md.tsx'
+
+# 文本生成型应用 API
+
+可用于生成高质量文本的应用,例如生成文章、摘要、翻译等,通过调用 completion-messages 接口,发送用户输入得到生成文本结果。用于生成文本的模型参数和提示词模版取决于开发者在 LangGenius 提示词编排页的设置。
+
+<Heading
+ url='/completion-messages'
+ method='POST'
+ title='创建文本补全消息'
+ name='#Create-Completion-Message'
+/>
+<Row>
+ <Col>
+ 创建文本补全消息,支持一问一答模式。
+
+ ### Request Body
+
+ <Properties>
+ <Property name='inputs' type='object' key='inputs'>
+ (选填)以键值对方式提供用户输入字段,与提示词编排中的变量对应。Key 为变量名称,Value 是参数值。如果字段类型为 Select,传入的 Value 需为预设选项之一。
+ <ul>
+ {!!props.variables.length && props.variables.map(
+ val => (
+ <SubProperty name={val.key} type={val.type} key={val.key}>
+ {val.name ? `${val.name}` : ''}
+ </SubProperty>
+ )
+ )}
+ </ul>
+ </Property>
+ <Property name='query' type='string' key='query'>
+ 用户输入的文本正文。
+ </Property>
+ <Property name='response_mode' type='string' key='response_mode'>
+ - blocking 阻塞型,等待执行完毕后返回结果。(请求若流程较长可能会被中断)
+ - streaming 流式返回。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现流式返回。
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/completion-messages" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/completion-messages' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "inputs": ${JSON.stringify(props.inputs)},\n "query": "Hi",\n "response_mode": "streaming",\n "user": "abc-123"\n}'\n`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/completion-messages' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "inputs": {},
+ "query": "Hi",
+ "response_mode": "streaming",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+ ### blocking
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "id": "0b089b9a-24d9-48cc-94f8-762677276261",
+ "answer": "how are you?",
+ "created_at": 1679586667
+ }
+ ```
+ </CodeGroup>
+ ### streaming
+ <CodeGroup title="Response">
+ ```streaming {{ title: 'Response' }}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages/{message_id}/feedbacks'
+ method='POST'
+ title='消息反馈(点赞)'
+ name='#feedbacks'
+/>
+<Row>
+ <Col>
+ 代表最终用户对返回消息进行评价,可以点赞与点踩,该数据将在“日志与标注”页中可见,并用于后续的模型微调。
+
+ ### Path Params
+
+ <Properties>
+ <Property name='message_id' type='string' key='message_id'>
+ 消息 ID
+ </Property>
+ </Properties>
+
+ ### Request Body
+
+ <Properties>
+ <Property name='rating' type='string' key='rating'>
+ like 或 dislike, 空值为撤销
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/messages/{message_id}/feedbacks" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/messages/{message_id}/feedbacks \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n --data-raw '{ \n "rating": "like",\n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/messages/{message_id}/feedbacks' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "rating": "like",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/parameters'
+ method='GET'
+ title='获取应用配置信息'
+ name='#parameters'
+/>
+<Row>
+ <Col>
+ 获取已配置的 Input 参数,包括变量名、字段名称、类型与默认值。通常用于客户端加载后显示这些字段的表单或填入默认值。
+
+ ### Query
+
+ <Properties>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/parameters" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/parameters?user=abc-123' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/parameters?user=abc-123' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "introduction": "nice to meet you",
+ "variables": [
+ {
+ "key": "book",
+ "name": "Which book?",
+ "description": null,
+ "type": "string",
+ "default": null,
+ "options": null
+ },
+ {
+ // ...
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
diff --git a/web/app/components/develop/template/template_chat.en.mdx b/web/app/components/develop/template/template_chat.en.mdx
new file mode 100644
index 00000000000..fd3ee37efba
--- /dev/null
+++ b/web/app/components/develop/template/template_chat.en.mdx
@@ -0,0 +1,391 @@
+import { CodeGroup } from '../code.tsx'
+import { Row, Col, Properties, Property, Heading, SubProperty, Paragraph } from '../md.tsx'
+
+# Chat App API
+
+For versatile conversational apps using a Q&A format, call the chat-messages API to initiate dialogue. Maintain ongoing conversations by passing the returned conversation_id. Response parameters and templates depend on LangGenius Prompt Eng. settings.
+
+<Heading
+ url='/chat-messages'
+ method='POST'
+ title='Create chat message'
+ name='#Create-Chat-Message'
+/>
+<Row>
+ <Col>
+ Create a new conversation message or continue an existing dialogue.
+
+ ### Request Body
+
+ <Properties>
+ <Property name='inputs' type='object' key='inputs'>
+ (Optional) Provide user input fields as key-value pairs, corresponding to variables in Prompt Eng. Key is the variable name, Value is the parameter value. If the field type is Select, the submitted Value must be one of the preset choices.
+ <ul>
+ {!!props.variables.length && props.variables.map(
+ val => (
+ <SubProperty name={val.key} type={val.type} key={val.key}>
+ {val.name ? `${val.name}` : ''}
+ </SubProperty>
+ )
+ )}
+ </ul>
+ </Property>
+ <Property name='query' type='string' key='query'>
+ User input/question content
+ </Property>
+ <Property name='response_mode' type='string' key='response_mode'>
+ - Blocking type, waiting for execution to complete and returning results. (Requests may be interrupted if the process is long)
+ - streaming returns. Implementation of streaming return based on SSE (**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**).
+ </Property>
+ <Property name='conversation_id' type='string' key='conversation_id'>
+ (Optional) Conversation ID: leave empty for first-time conversation; pass conversation_id from context to continue dialogue.
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/chat-messages" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/chat-messages' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "inputs": ${JSON.stringify(props.inputs)},\n "query": "eh",\n "response_mode": "streaming",\n "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",\n "user": "abc-123"\n}'\n`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/chat-messages' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "inputs": {},
+ "query": "eh",
+ "response_mode": "streaming",
+ "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+ ### blocking
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "answer": "Hi, is there anything I can help you?",
+ "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
+ "created_at": 1679587005,
+ "id": "059f87d9-15c0-473a-870c-fde95cdcc1e4"
+ }
+ ```
+ </CodeGroup>
+ ### streaming
+ <CodeGroup title="Response">
+ ```streaming {{ title: 'Response' }}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages/{message_id}/feedbacks'
+ method='POST'
+ title='Message terminal user feedback, like'
+ name='#feedbacks'
+/>
+<Row>
+ <Col>
+ Rate received messages on behalf of end-users with likes or dislikes. This data is visible in the Logs & Annotations page and used for future model fine-tuning.
+
+ ### Path Params
+ <Properties>
+ <Property name='message_id' type='string' key='message_id'>
+ Message ID
+ </Property>
+ </Properties>
+
+ ### Request Body
+
+ <Properties>
+ <Property name='rating' type='string' key='rating'>
+ like or dislike, null is undo
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/messages/{message_id}/feedbacks" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/messages/{message_id}/feedbacks \\\n --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "rating": "like",\n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/messages/{message_id}/feedbacks' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "rating": "like",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages'
+ method='GET'
+ title='Get the chat history message'
+ name='#messages'
+/>
+<Row>
+ <Col>
+ The first page returns the latest `limit` bar, which is in reverse order.
+
+ ### Query
+
+ <Properties>
+ <Property name='conversation_id' type='string' key='conversation_id'>
+ Conversation ID
+ </Property>
+ <Property name='first_id' type='string' key='first_id'>
+ ID of the first chat record on the current page. The default is none.
+ </Property>
+ <Property name='limit' type='int' key='limit'>
+ How many chats are returned in one request
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/messages" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/messages?user=abc-123&conversation_id='\\\n --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/messages?user=abc-123&conversation_id='
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/conversations'
+ method='GET'
+ title='Get conversation list'
+ name='#conversations'
+/>
+<Row>
+ <Col>
+ Gets the session list of the current user. By default, the last 20 sessions are returned.
+
+ ### Query
+
+ <Properties>
+ <Property name='last_id' type='string' key='last_id'>
+ The ID of the last record on the current page, default none.
+ </Property>
+ <Property name='limit' type='int' key='limit'>
+ "How many chats are returned in one request
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/conversations" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/conversations?user=abc-123&last_id=&limit=20'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/conversations?user=abc-123&last_id=&limit=20' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "limit": 20,
+ "has_more": false,
+ "data": [
+ {
+ "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54",
+ "name": "New chat",
+ "inputs": {
+ "book": "book",
+ "myName": "Lucy"
+ },
+ "status": "normal",
+ "created_at": 1679667915
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/conversations/{converation_id}/name'
+ method='POST'
+ title='Conversation renaming'
+ name='#rename'
+/>
+<Row>
+ <Col>
+ Rename conversations; the name is displayed in multi-session client interfaces.
+
+ ### Request Body
+
+ <Properties>
+ <Property name='name' type='string' key='name'>
+ New name
+ </Property>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/conversations/{converation_id}/name" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/conversations/name' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{ \n "name": "", \n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/conversations/name' \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --data-raw '{
+ "name": "",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "result": "success"
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+
+---
+
+<Heading
+ url='/parameters'
+ method='GET'
+ title='Obtain application parameter information'
+ name='#rename'
+/>
+<Row>
+ <Col>
+ Retrieve configured Input parameters, including variable names, field names, types, and default values. Typically used for displaying these fields in a form or filling in default values after the client loads.
+
+ ### Query
+
+ <Properties>
+ <Property name='user' type='string' key='user'>
+ The user identifier, defined by the developer, must ensure uniqueness within the app.
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/parameters" targetCode={` curl --location --request GET '${props.appDetail.api_base_url}/parameters?user=abc-123'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/parameters?user=abc-123' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "introduction": "nice to meet you",
+ "variables": [
+ {
+ "key": "book",
+ "name": "book",
+ "description": null,
+ "type": "string",
+ "default": null,
+ "options": null
+ },
+ {
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
diff --git a/web/app/components/develop/template/template_chat.zh.mdx b/web/app/components/develop/template/template_chat.zh.mdx
new file mode 100644
index 00000000000..421d6da126b
--- /dev/null
+++ b/web/app/components/develop/template/template_chat.zh.mdx
@@ -0,0 +1,391 @@
+import { CodeGroup } from '../code.tsx'
+import { Row, Col, Properties, Property, Heading, SubProperty } from '../md.tsx'
+
+# 对话型应用 API
+
+可用于大部分场景的对话型应用,采用一问一答模式与用户持续对话。要开始一个对话请调用 chat-messages 接口,通过继续传入返回的 conversation_id 可持续保持该会话。
+
+<Heading
+ url='/chat-messages'
+ method='POST'
+ title='发送对话消息'
+ name='#Create-Chat-Message'
+/>
+<Row>
+ <Col>
+ 创建会话消息,或基于此前的对话继续发送消息。
+
+ ### Request Body
+
+ <Properties>
+ <Property name='inputs' type='object' key='inputs'>
+ (选填)以键值对方式提供用户输入字段,与提示词编排中的变量对应。Key 为变量名称,Value 是参数值。如果字段类型为 Select,传入的 Value 需为预设选项之一。
+ <ul>
+ {!!props.variables.length && props.variables.map(
+ val => (
+ <SubProperty name={val.key} type={val.type} key={val.key}>
+ {val.name ? `${val.name}` : ''}
+ </SubProperty>
+ )
+ )}
+ </ul>
+ </Property>
+ <Property name='query' type='string' key='query'>
+ 用户输入/提问内容
+ </Property>
+ <Property name='response_mode' type='string' key='response_mode'>
+ - blocking 阻塞型,等待执行完毕后返回结果。(请求若流程较长可能会被中断)
+ - streaming 流式返回。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现流式返回。
+ </Property>
+ <Property name='conversation_id' type='string' key='conversation_id'>
+ (选填)会话标识符,首次对话可为空,如果要继续对话请传入上下文返回的 conversation_id
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/chat-messages" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/chat-messages' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "inputs": ${JSON.stringify(props.inputs)},\n "query": "eh",\n "response_mode": "streaming",\n "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",\n "user": "abc-123"\n}'\n`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/chat-messages' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "inputs": {},
+ "query": "eh",
+ "response_mode": "streaming",
+ "conversation_id": "1c7e55fb-1ba2-4e10-81b5-30addcea2276",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+ ### blocking
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "answer": "Hi, is there anything I can help you?",
+ "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
+ "created_at": 1679587005,
+ "id": "059f87d9-15c0-473a-870c-fde95cdcc1e4"
+ }
+ ```
+ </CodeGroup>
+ ### streaming
+ <CodeGroup title="Response">
+ ```streaming {{ title: 'Response' }}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595}
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages/{message_id}/feedbacks'
+ method='POST'
+ title='消息反馈(点赞)'
+ name='#feedbacks'
+/>
+<Row>
+ <Col>
+ 代表最终用户对返回消息进行评价,可以点赞与点踩,该数据将在“日志与标注”页中可见,并用于后续的模型微调。
+
+ ### Path Params
+ <Properties>
+ <Property name='message_id' type='string' key='message_id'>
+ 消息 ID
+ </Property>
+ </Properties>
+
+ ### Request Body
+
+ <Properties>
+ <Property name='rating' type='string' key='rating'>
+ like 或 dislike, 空值为撤销
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/messages/{message_id}/feedbacks" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/messages/{message_id}/feedbacks \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n "rating": "like",\n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/messages/{message_id}/feedbacks' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "rating": "like",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/messages'
+ method='GET'
+ title='获取会话历史消息'
+ name='#messages'
+/>
+<Row>
+ <Col>
+ 滚动加载形式返回历史聊天记录,第一页返回最新 `limit` 条,即:倒序返回。
+
+ ### Query
+
+ <Properties>
+ <Property name='conversation_id' type='string' key='conversation_id'>
+ 会话 ID
+ </Property>
+ <Property name='first_id' type='string' key='first_id'>
+ 当前页第一条聊天记录的 ID,默认 none
+ </Property>
+ <Property name='limit' type='int' key='limit'>
+ 一次请求返回多少条聊天记录
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/messages" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/messages?user=abc-123&conversation_id=' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/messages?user=abc-123&conversation_id='
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "has_more": false,
+ "data": [
+ {
+ "id": "WAz8eIbvDR60rouK",
+ "username": "FrankMcCallister",
+ "phone_number": "1-800-759-3000",
+ "avatar_url": "https://assets.protocol.chat/avatars/frank.jpg",
+ "display_name": null,
+ "conversation_id": "xgQQXg3hrtjh7AvZ",
+ "last_active_at": 705103200,
+ "created_at": 692233200
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/conversations'
+ method='GET'
+ title='获取会话列表'
+ name='#conversations'
+/>
+<Row>
+ <Col>
+ 获取当前用户的会话列表,默认返回最近的 20 条。
+
+ ### Query
+
+ <Properties>
+ <Property name='last_id' type='string' key='last_id'>
+ 当前页最后面一条记录的 ID,默认 none
+ </Property>
+ <Property name='limit' type='int' key='limit'>
+ 一次请求返回多少条记录
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/conversations" targetCode={`curl --location --request GET '${props.appDetail.api_base_url}/conversations?user=abc-123&last_id=&limit=20'\\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/conversations?user=abc-123&last_id=&limit=20' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "limit": 20,
+ "has_more": false,
+ "data": [
+ {
+ "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54",
+ "name": "New chat",
+ "inputs": {
+ "book": "book",
+ "myName": "Lucy"
+ },
+ "status": "normal",
+ "created_at": 1679667915
+ },
+ {
+ "id": "hSIhXBhNe8X1d8Et"
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+---
+
+<Heading
+ url='/conversations/{converation_id}/name'
+ method='POST'
+ title='会话重命名'
+ name='#rename'
+/>
+<Row>
+ <Col>
+ 对会话进行重命名,会话名称用于显示在支持多会话的客户端上。
+
+ ### Request Body
+
+ <Properties>
+ <Property name='name' type='string' key='name'>
+ 新的名称
+ </Property>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="POST" label="/conversations/{converation_id}/name" targetCode={`curl --location --request POST '${props.appDetail.api_base_url}/conversations/name' \\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{ \n "name": "", \n "user": "abc-123"\n}'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request POST 'https://cloud.langgenius.dev/api/conversations/name' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "name": "",
+ "user": "abc-123"
+ }'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "result": "success"
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
+
+
+---
+
+<Heading
+ url='/parameters'
+ method='GET'
+ title='获取应用配置信息'
+ name='#rename'
+/>
+<Row>
+ <Col>
+ 获取已配置的 Input 参数,包括变量名、字段名称、类型与默认值。通常用于客户端加载后显示这些字段的表单或填入默认值。
+
+ ### Query
+
+ <Properties>
+ <Property name='user' type='string' key='user'>
+ 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。
+ </Property>
+ </Properties>
+ </Col>
+ <Col sticky>
+
+ <CodeGroup title="Request" tag="GET" label="/parameters" targetCode={` curl --location --request GET '${props.appDetail.api_base_url}/parameters'\\\n--header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'`}>
+
+ ```bash {{ title: 'cURL' }}
+ curl --location --request GET 'https://cloud.langgenius.dev/api/parameters?user=abc-123' \
+ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY'
+ ```
+
+ </CodeGroup>
+
+ <CodeGroup title="Response">
+ ```json {{ title: 'Response' }}
+ {
+ "introduction": "nice to meet you",
+ "variables": [
+ {
+ "key": "book",
+ "name": "book",
+ "description": null,
+ "type": "string",
+ "default": null,
+ "options": null
+ },
+ {
+ // ...
+ }
+ ]
+ }
+ ```
+ </CodeGroup>
+ </Col>
+</Row>
diff --git a/web/app/components/header/account-about/index.module.css b/web/app/components/header/account-about/index.module.css
new file mode 100644
index 00000000000..1c5e123fc0c
--- /dev/null
+++ b/web/app/components/header/account-about/index.module.css
@@ -0,0 +1,18 @@
+.logo-icon {
+ background: url(../assets/logo-icon.png) center center no-repeat;
+ background-size: contain;
+ box-shadow: 0px 4px 6px -1px rgba(0, 0, 0, 0.05), 0px 2px 4px -2px rgba(0, 0, 0, 0.05);
+}
+
+.logo-text {
+ width: 74.09px;
+ height: 15.32px;
+ background: url(../assets/logo-text.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.modal {
+ max-width: 480px !important;
+ width: 480px !important;
+ padding: 24px 32px !important;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-about/index.tsx b/web/app/components/header/account-about/index.tsx
new file mode 100644
index 00000000000..8de2ee99a20
--- /dev/null
+++ b/web/app/components/header/account-about/index.tsx
@@ -0,0 +1,91 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+import classNames from 'classnames'
+import Link from 'next/link'
+import s from './index.module.css'
+import Modal from '@/app/components/base/modal'
+import type { LangGeniusVersionResponse } from '@/models/common'
+import { IS_CE_EDITION } from '@/config'
+
+type IAccountSettingProps = {
+ langeniusVersionInfo: LangGeniusVersionResponse
+ onCancel: () => void
+}
+const buttonClassName = `
+shrink-0 flex items-center h-8 px-3 rounded-lg border border-gray-200
+text-xs text-gray-800 font-medium
+`
+export default function AccountAbout({
+ langeniusVersionInfo,
+ onCancel,
+}: IAccountSettingProps) {
+ const { t } = useTranslation()
+ const isLatest = langeniusVersionInfo.current_version === langeniusVersionInfo.latest_version
+
+ return (
+ <Modal
+ isShow
+ onClose={() => { }}
+ className={s.modal}
+ >
+ <div className='relative'>
+ <XMarkIcon className='absolute top-0 -right-2 w-4 h-4 cursor-pointer' onClick={onCancel} />
+ <div>
+ <div className={classNames(
+ s['logo-icon'],
+ 'mx-auto mb-3 w-12 h-12 bg-white rounded border border-gray-200',
+ )} />
+ <div className={classNames(
+ s['logo-text'],
+ 'mx-auto mb-2',
+ )} />
+ <div className='mb-3 text-center text-xs font-normal text-gray-500'>Version {langeniusVersionInfo?.current_version}</div>
+ <div className='mb-4 text-center text-xs font-normal text-gray-700'>
+ <div>© 2023 LangGenius, Inc., Contributors.</div>
+ <div className='text-[#1C64F2]'>
+ {
+ IS_CE_EDITION
+ ? <Link href={'https://github.com/langgenius/dify/blob/main/LICENSE'} target='_blank'>Open Source License</Link>
+ : <>
+ <Link href={'https://docs.dify.ai/user-agreement/privacy-policy'} target='_blank'>Privacy Policy</Link>,
+ <Link href={'https://docs.dify.ai/user-agreement/terms-of-service'} target='_blank'>Terms of Service</Link>
+ </>
+ }
+ </div>
+ </div>
+ </div>
+ <div className='mb-4 h-0 border-[0.5px] border-gray-200' />
+ <div className='flex justify-between items-center'>
+ <div className='text-xs font-medium text-gray-800'>
+ {
+ isLatest
+ ? t('common.about.latestAvailable', { version: langeniusVersionInfo.latest_version })
+ : t('common.about.nowAvailable', { version: langeniusVersionInfo.latest_version })
+ }
+ </div>
+ <div className='flex items-center'>
+ <Link
+ className={classNames(buttonClassName, 'mr-2')}
+ href={'https://github.com/langgenius'}
+ target='_blank'
+ >
+ {t('common.about.changeLog')}
+ </Link>
+ {
+ !isLatest && !IS_CE_EDITION && (
+ <Link
+ className={classNames(buttonClassName, 'text-primary-600')}
+ href={langeniusVersionInfo.release_notes}
+ target='_blank'
+ >
+ {t('common.about.updateNow')}
+ </Link>
+ )
+ }
+ </div>
+ </div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/web/app/components/header/account-dropdown/index.tsx b/web/app/components/header/account-dropdown/index.tsx
new file mode 100644
index 00000000000..2be1ad55590
--- /dev/null
+++ b/web/app/components/header/account-dropdown/index.tsx
@@ -0,0 +1,130 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { Fragment, useState } from 'react'
+import { useContext } from 'use-context-selector'
+import classNames from 'classnames'
+import Link from 'next/link'
+import { ArrowRightOnRectangleIcon, ArrowTopRightOnSquareIcon, ChevronDownIcon } from '@heroicons/react/24/solid'
+import { Menu, Transition } from '@headlessui/react'
+import Indicator from '../indicator'
+import AccountSetting from '../account-setting'
+import AccountAbout from '../account-about'
+import type { LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
+import I18n from '@/context/i18n'
+import WorkplaceSelector from './workplace-selector'
+import Avatar from '@/app/components/base/avatar'
+
+type IAppSelectorProps = {
+ userProfile: UserProfileResponse
+ onLogout: () => void
+ langeniusVersionInfo: LangGeniusVersionResponse
+}
+
+export default function AppSelector({ userProfile, onLogout, langeniusVersionInfo }: IAppSelectorProps) {
+ const itemClassName = `
+ flex items-center w-full h-10 px-3 text-gray-700 text-[14px]
+ rounded-lg font-normal hover:bg-gray-100 cursor-pointer
+ `
+ const [settingVisible, setSettingVisible] = useState(false)
+ const [aboutVisible, setAboutVisible] = useState(false)
+
+ const { locale } = useContext(I18n)
+ const { t } = useTranslation()
+
+ return (
+ <div className="">
+ <Menu as="div" className="relative inline-block text-left">
+ <div>
+ <Menu.Button
+ className="
+ inline-flex items-center h-[38px]
+ rounded-xl pl-2 pr-2.5 text-[14px] font-normal
+ text-gray-800 hover:bg-gray-200
+ "
+ >
+ <Avatar name={userProfile.name} className='mr-2' />
+ {userProfile.name}
+ <ChevronDownIcon
+ className="w-3 h-3 ml-1"
+ aria-hidden="true"
+ />
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className="
+ absolute right-0 mt-1.5 w-60 max-w-80
+ divide-y divide-gray-100 origin-top-right rounded-lg bg-white
+ shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_rgba(0,0,0,0.05)]
+ "
+ >
+ <Menu.Item>
+ <div className='flex flex-nowrap items-center px-4 py-[13px]'>
+ <Avatar name={userProfile.name} size={36} className='mr-3' />
+ <div className='grow'>
+ <div className='leading-5 font-normal text-[14px] text-gray-800 break-all'>{userProfile.name}</div>
+ <div className='leading-[18px] text-xs font-normal text-gray-500 break-all'>{userProfile.email}</div>
+ </div>
+ </div>
+ </Menu.Item>
+ <div className='px-1 py-1'>
+ <div className='mt-2 px-3 text-xs font-medium text-gray-500'>{t('common.userProfile.workspace')}</div>
+ <WorkplaceSelector />
+ </div>
+ <div className="px-1 py-1">
+ <Menu.Item>
+ <div className={itemClassName} onClick={() => setSettingVisible(true)}>
+ <div>{t('common.userProfile.settings')}</div>
+ </div>
+ </Menu.Item>
+ <Menu.Item>
+ <Link
+ className={classNames(itemClassName, 'group justify-between')}
+ href={
+ locale === 'zh-Hans' ? 'https://docs.dify.ai/zh-hans/' : 'https://docs.dify.ai/en/'
+ }
+ target='_blank'>
+ <div>{t('common.userProfile.helpCenter')}</div>
+ <ArrowTopRightOnSquareIcon className='hidden w-4 h-4 group-hover:flex' />
+ </Link>
+ </Menu.Item>
+ <Menu.Item>
+ <div className={classNames(itemClassName, 'justify-between')} onClick={() => setAboutVisible(true)}>
+ <div>{t('common.userProfile.about')}</div>
+ <div className='flex items-center'>
+ <div className='mr-2 text-xs font-normal text-gray-500'>{langeniusVersionInfo.current_version}</div>
+ <Indicator color={langeniusVersionInfo.current_version === langeniusVersionInfo.latest_version ? 'green' : 'orange'} />
+ </div>
+ </div>
+ </Menu.Item>
+ </div>
+ <Menu.Item>
+ <div className='p-1' onClick={() => onLogout()}>
+ <div
+ className='flex items-center justify-between h-12 px-3 rounded-lg cursor-pointer group hover:bg-gray-100'
+ >
+ <div className='font-normal text-[14px] text-gray-700'>{t('common.userProfile.logout')}</div>
+ <ArrowRightOnRectangleIcon className='hidden w-4 h-4 group-hover:flex' />
+ </div>
+ </div>
+ </Menu.Item>
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ {
+ settingVisible && <AccountSetting onCancel={() => setSettingVisible(false)} />
+ }
+ {
+ aboutVisible && <AccountAbout onCancel={() => setAboutVisible(false)} langeniusVersionInfo={langeniusVersionInfo} />
+ }
+ </div >
+ )
+}
diff --git a/web/app/components/header/account-dropdown/workplace-selector/index.module.css b/web/app/components/header/account-dropdown/workplace-selector/index.module.css
new file mode 100644
index 00000000000..f3840ea0189
--- /dev/null
+++ b/web/app/components/header/account-dropdown/workplace-selector/index.module.css
@@ -0,0 +1,5 @@
+.popup {
+ left: 4px;
+ transform: translateX(-100%);
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-dropdown/workplace-selector/index.tsx b/web/app/components/header/account-dropdown/workplace-selector/index.tsx
new file mode 100644
index 00000000000..a791188158a
--- /dev/null
+++ b/web/app/components/header/account-dropdown/workplace-selector/index.tsx
@@ -0,0 +1,97 @@
+import { Fragment } from 'react'
+import { switchWorkspace } from '@/service/common'
+import { Menu, Transition } from '@headlessui/react'
+import { ChevronRightIcon, CheckIcon } from '@heroicons/react/24/outline'
+import cn from 'classnames'
+import s from './index.module.css'
+import { useContext } from 'use-context-selector'
+import { ToastContext } from '@/app/components/base/toast'
+import { useTranslation } from 'react-i18next'
+import { useRouter } from 'next/navigation'
+import { useWorkspacesContext } from '@/context/workspace-context'
+
+const itemClassName = `
+ flex items-center px-3 py-2 h-10 cursor-pointer
+`
+const itemIconClassName = `
+ shrink-0 mr-2 w-6 h-6 bg-[#EFF4FF] rounded-md
+`
+const itemNameClassName = `
+ grow mr-2 text-sm text-gray-700 text-left
+`
+const itemCheckClassName = `
+ shrink-0 w-4 h-4 text-primary-600
+`
+
+const WorkplaceSelector = () => {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const { notify } = useContext(ToastContext)
+ const { workspaces } = useWorkspacesContext()
+ const currentWrokspace = workspaces.filter(item => item.current)?.[0]
+
+ const handleSwitchWorkspace = async (tenant_id: string) => {
+ try {
+ await switchWorkspace({ url: `/workspaces/switch`, body: { tenant_id } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ router.replace('/apps')
+ } catch (e) {
+ notify({ type: 'error', message: t('common.provider.saveFailed') })
+ } finally {
+ }
+ }
+
+ return (
+ <Menu as="div" className="relative w-full h-full">
+ {
+ ({ open }) => (
+ <>
+ <Menu.Button className={cn(
+ `
+ ${itemClassName} w-full
+ group hover:bg-gray-50 cursor-pointer ${open && 'bg-gray-50'}
+ `
+ )}>
+ <div className={itemIconClassName} />
+ <div className={`${itemNameClassName} truncate`}>{currentWrokspace?.name}</div>
+ <ChevronRightIcon className='shrink-0 w-[14px] h-[14px]' />
+ </Menu.Button>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className={cn(
+ `
+ absolute top-[1px] min-w-[200px] z-10 bg-white border-[0.5px] border-gray-200
+ divide-y divide-gray-100 origin-top-right rounded-xl
+ `,
+ s.popup
+ )}
+ >
+ <div className="px-1 py-1">
+ {
+ workspaces.map(workspace => (
+ <div className={itemClassName} key={workspace.id} onClick={() => handleSwitchWorkspace(workspace.id)}>
+ <div className={itemIconClassName} />
+ <div className={itemNameClassName}>{workspace.name}</div>
+ {workspace.current && <CheckIcon className={itemCheckClassName} />}
+ </div>
+ ))
+ }
+ </div>
+ </Menu.Items>
+ </Transition>
+ </>
+ )
+ }
+ </Menu>
+ )
+}
+
+export default WorkplaceSelector
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/Integrations-page/index.module.css b/web/app/components/header/account-setting/Integrations-page/index.module.css
new file mode 100644
index 00000000000..5b7ef2cce37
--- /dev/null
+++ b/web/app/components/header/account-setting/Integrations-page/index.module.css
@@ -0,0 +1,24 @@
+.google-icon {
+ background: url(../../assets/google.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.github-icon {
+ background: url(../../assets/github.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.twitter-icon {
+ background: url(../../assets/twitter.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.bitbucket-icon {
+ background: url(../../assets/bitbucket.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.salesforce-icon {
+ background: url(../../assets/salesforce.svg) center center no-repeat;
+ background-size: 24px auto;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/Integrations-page/index.tsx b/web/app/components/header/account-setting/Integrations-page/index.tsx
new file mode 100644
index 00000000000..ab27bc1f95b
--- /dev/null
+++ b/web/app/components/header/account-setting/Integrations-page/index.tsx
@@ -0,0 +1,74 @@
+'use client'
+
+import { useTranslation } from 'react-i18next'
+import classNames from 'classnames'
+import s from './index.module.css'
+import useSWR from 'swr'
+import Link from 'next/link'
+import { fetchAccountIntegrates } from '@/service/common'
+
+const titleClassName = `
+ mb-2 text-sm font-medium text-gray-900
+`
+
+export default function IntegrationsPage() {
+ const { t } = useTranslation()
+
+ const integrateMap = {
+ google: {
+ name: t('common.integrations.google'),
+ description: t('common.integrations.googleAccount'),
+ },
+ github: {
+ name: t('common.integrations.github'),
+ description: t('common.integrations.githubAccount'),
+ },
+ }
+
+ const { data } = useSWR({ url: '/account/integrates' }, fetchAccountIntegrates)
+ const integrates = data?.data?.length ? data.data : []
+
+ return (
+ <>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.integrations.connected')}</div>
+ {
+ integrates.map(integrate => (
+ <div key={integrate.provider} className='mb-2 flex items-center px-3 py-2 bg-gray-50 border-[0.5px] border-gray-200 rounded-lg'>
+ <div className={classNames('w-8 h-8 mr-3 bg-white rounded-lg border border-gray-100', s[`${integrate.provider}-icon`])} />
+ <div className='grow'>
+ <div className='leading-[21px] text-sm font-medium text-gray-800'>{integrateMap[integrate.provider].name}</div>
+ <div className='leading-[18px] text-xs font-normal text-gray-500'>{integrateMap[integrate.provider].description}</div>
+ </div>
+ {
+ !integrate.is_bound && (
+ <Link
+ className='flex items-center h-8 px-[7px] bg-white rounded-lg border border-gray-200 text-xs font-medium text-gray-700 cursor-pointer'
+ href={integrate.link}
+ target={'_blank'}>
+ {t('common.integrations.connect')}
+ </Link>
+ )
+ }
+ </div>
+ ))
+ }
+ </div>
+ {/* <div className='mb-8'>
+ <div className={titleClassName}>Add a service </div>
+ {
+ services.map(service => (
+ <div key={service.key} className='mb-2 flex items-center px-3 py-2 bg-gray-50 border-[0.5px] border-gray-200 rounded-lg'>
+ <div className={classNames('w-8 h-8 mr-3 bg-white rounded-lg border border-gray-100', s[`${service.key}-icon`])} />
+ <div className='grow'>
+ <div className='leading-[21px] text-sm font-medium text-gray-800'>{service.name}</div>
+ <div className='leading-[18px] text-xs font-normal text-gray-500'>{service.description}</div>
+ </div>
+ <Button className='text-xs font-medium text-gray-800'>Connect</Button>
+ </div>
+ ))
+ }
+ </div> */}
+ </>
+ )
+}
diff --git a/web/app/components/header/account-setting/account-page/index.module.css b/web/app/components/header/account-setting/account-page/index.module.css
new file mode 100644
index 00000000000..2e21f3b6198
--- /dev/null
+++ b/web/app/components/header/account-setting/account-page/index.module.css
@@ -0,0 +1,4 @@
+.modal {
+ padding: 24px 32px !important;
+ width: 400px !important;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/account-page/index.tsx b/web/app/components/header/account-setting/account-page/index.tsx
new file mode 100644
index 00000000000..9410e971e29
--- /dev/null
+++ b/web/app/components/header/account-setting/account-page/index.tsx
@@ -0,0 +1,130 @@
+'use client'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import classNames from 'classnames'
+import { useContext } from 'use-context-selector'
+import Collapse from '../collapse'
+import type { IItem } from '../collapse'
+import s from './index.module.css'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import { updateUserProfile } from '@/service/common'
+import { useAppContext } from '@/context/app-context'
+import { ToastContext } from '@/app/components/base/toast'
+import AppIcon from '@/app/components/base/app-icon'
+import Avatar from '@/app/components/base/avatar'
+
+const titleClassName = `
+ text-sm font-medium text-gray-900
+`
+const descriptionClassName = `
+ mt-1 text-xs font-normal text-gray-500
+`
+const inputClassName = `
+ mt-2 w-full px-3 py-2 bg-gray-100 rounded
+ text-sm font-normal text-gray-800
+`
+
+export default function AccountPage() {
+ const { mutateUserProfile, userProfile, apps } = useAppContext()
+ const { notify } = useContext(ToastContext)
+ const [editNameModalVisible, setEditNameModalVisible] = useState(false)
+ const [editName, setEditName] = useState('')
+ const [editing, setEditing] = useState(false)
+ const { t } = useTranslation()
+
+ const handleEditName = () => {
+ setEditNameModalVisible(true)
+ setEditName(userProfile.name)
+ }
+ const handleSaveName = async () => {
+ try {
+ setEditing(true)
+ await updateUserProfile({ url: 'account/name', body: { name: editName } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ mutateUserProfile()
+ setEditNameModalVisible(false)
+ setEditing(false)
+ }
+ catch (e) {
+ notify({ type: 'error', message: (e as Error).message })
+ setEditNameModalVisible(false)
+ setEditing(false)
+ }
+ }
+ const renderAppItem = (item: IItem) => {
+ return (
+ <div className='flex px-3 py-1'>
+ <div className='mr-3'>
+ <AppIcon size='tiny' />
+ </div>
+ <div className='mt-[3px] text-xs font-medium text-gray-700 leading-[18px]'>{item.name}</div>
+ </div>
+ )
+ }
+
+ return (
+ <>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.account.avatar')}</div>
+ <Avatar name={userProfile.name} size={64} className='mt-2' />
+ </div>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.account.name')}</div>
+ <div className={classNames('flex items-center justify-between mt-2 w-full h-9 px-3 bg-gray-100 rounded text-sm font-normal text-gray-800 cursor-pointer group')}>
+ {userProfile.name}
+ <div className='items-center hidden h-6 px-2 text-xs font-normal bg-white border border-gray-200 rounded-md group-hover:flex' onClick={handleEditName}>{t('common.operation.edit')}</div>
+ </div>
+ </div>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.account.email')}</div>
+ <div className={classNames(inputClassName, 'cursor-pointer')}>{userProfile.email}</div>
+ </div>
+ {
+ !!apps.length && (
+ <>
+ <div className='mb-6 border-[0.5px] border-gray-100' />
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.account.langGeniusAccount')}</div>
+ <div className={descriptionClassName}>{t('common.account.langGeniusAccountTip')}</div>
+ <Collapse
+ title={`${t('common.account.showAppLength', { length: apps.length })}`}
+ items={apps.map(app => ({ key: app.id, name: app.name }))}
+ renderItem={renderAppItem}
+ wrapperClassName='mt-2'
+ />
+ </div>
+ </>
+ )
+ }
+ {
+ editNameModalVisible && (
+ <Modal
+ isShow
+ onClose={() => setEditNameModalVisible(false)}
+ className={s.modal}
+ >
+ <div className='mb-6 text-lg font-medium text-gray-900'>{t('common.account.editName')}</div>
+ <div className={titleClassName}>{t('common.account.name')}</div>
+ <input
+ className={inputClassName}
+ value={editName}
+ onChange={e => setEditName(e.target.value)}
+ />
+ <div className='flex justify-end mt-10'>
+ <Button className='mr-2 text-sm font-medium' onClick={() => setEditNameModalVisible(false)}>{t('common.operation.cancel')}</Button>
+ <Button
+ disabled={editing || !editName}
+ type='primary'
+ className='text-sm font-medium'
+ onClick={handleSaveName}
+ >
+ {t('common.operation.save')}
+ </Button>
+ </div>
+ </Modal>
+ )
+ }
+ </>
+ )
+}
diff --git a/web/app/components/header/account-setting/collapse/index.tsx b/web/app/components/header/account-setting/collapse/index.tsx
new file mode 100644
index 00000000000..837a4aeb16c
--- /dev/null
+++ b/web/app/components/header/account-setting/collapse/index.tsx
@@ -0,0 +1,54 @@
+import { useState } from 'react'
+import { ChevronDownIcon, ChevronRightIcon } from '@heroicons/react/24/outline'
+import classNames from 'classnames'
+
+export type IItem = {
+ key: string
+ name: string
+}
+type ICollapse = {
+ title: string | undefined
+ items: IItem[]
+ renderItem: (item: IItem) => React.ReactNode
+ onSelect?: (item: IItem) => void
+ wrapperClassName?: string
+}
+const Collapse = ({
+ title,
+ items,
+ renderItem,
+ onSelect,
+ wrapperClassName,
+}: ICollapse) => {
+ const [open, setOpen] = useState(false)
+
+ const toggle = () => setOpen(!open)
+
+ return (
+ <div className={classNames('border border-gray-200 bg-gray-50 rounded-lg', wrapperClassName)}>
+ <div className='flex items-center justify-between leading-[18px] px-3 py-2 text-xs font-medium text-gray-800 cursor-pointer' onClick={toggle}>
+ {title}
+ {
+ open
+ ? <ChevronDownIcon className='w-3 h-3 text-gray-400' />
+ : <ChevronRightIcon className='w-3 h-3 text-gray-400' />
+ }
+ </div>
+ {
+ open && (
+ <div className='py-2 border-t border-t-gray-100'>
+ {
+ items.map(item => (
+ <div key={item.key} onClick={() => onSelect && onSelect(item)}>
+ {renderItem(item)}
+ </div>
+ ))
+ }
+ </div>
+ )
+ }
+ </div>
+ )
+}
+
+export default Collapse
diff --git a/web/app/components/header/account-setting/index.module.css b/web/app/components/header/account-setting/index.module.css
new file mode 100644
index 00000000000..e7d1ef61e6e
--- /dev/null
+++ b/web/app/components/header/account-setting/index.module.css
@@ -0,0 +1,5 @@
+.modal {
+ max-width: 720px !important;
+ padding: 0 !important;
+ overflow-y: auto;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsx
new file mode 100644
index 00000000000..8b1c51fbebb
--- /dev/null
+++ b/web/app/components/header/account-setting/index.tsx
@@ -0,0 +1,132 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { useState } from 'react'
+import { AtSymbolIcon, GlobeAltIcon, UserIcon, XMarkIcon, CubeTransparentIcon, UsersIcon } from '@heroicons/react/24/outline'
+import { GlobeAltIcon as GlobalAltIconSolid, UserIcon as UserIconSolid, UsersIcon as UsersIconSolid } from '@heroicons/react/24/solid'
+import AccountPage from './account-page'
+import MembersPage from './members-page'
+import IntegrationsPage from './Integrations-page'
+import LanguagePage from './language-page'
+import ProviderPage from './provider-page'
+import s from './index.module.css'
+import Modal from '@/app/components/base/modal'
+
+const iconClassName = `
+ w-[18px] h-[18px] ml-3 mr-2
+`
+
+type IAccountSettingProps = {
+ onCancel: () => void
+ activeTab?: string
+}
+export default function AccountSetting({
+ onCancel,
+ activeTab = 'account',
+}: IAccountSettingProps) {
+ const [activeMenu, setActiveMenu] = useState(activeTab)
+ const { t } = useTranslation()
+ const menuItems = [
+ {
+ key: 'account-group',
+ name: t('common.settings.accountGroup'),
+ items: [
+ {
+ key: 'account',
+ name: t('common.settings.account'),
+ icon: <UserIcon className={iconClassName} />,
+ activeIcon: <UserIconSolid className={iconClassName} />,
+ },
+ {
+ key: 'integrations',
+ name: t('common.settings.integrations'),
+ icon: <AtSymbolIcon className={iconClassName} />,
+ activeIcon: <AtSymbolIcon className={iconClassName} />,
+ },
+ {
+ key: 'language',
+ name: t('common.settings.language'),
+ icon: <GlobeAltIcon className={iconClassName} />,
+ activeIcon: <GlobalAltIconSolid className={iconClassName} />,
+ },
+ ]
+ },
+ {
+ key: 'workspace-group',
+ name: t('common.settings.workplaceGroup'),
+ items: [
+ {
+ key: 'members',
+ name: t('common.settings.members'),
+ icon: <UsersIcon className={iconClassName} />,
+ activeIcon: <UsersIconSolid className={iconClassName} />,
+ },
+ {
+ key: 'provider',
+ name: t('common.settings.provider'),
+ icon: <CubeTransparentIcon className={iconClassName} />,
+ activeIcon: <CubeTransparentIcon className={iconClassName} />,
+ },
+ ]
+ }
+ ]
+
+ return (
+ <Modal
+ isShow
+ onClose={() => { }}
+ className={s.modal}
+ >
+ <div className='flex'>
+ <div className='w-[200px] p-4 border border-gray-100'>
+ <div className='mb-8 ml-2 text-base font-medium leading-6 text-gray-900'>{t('common.userProfile.settings')}</div>
+ <div>
+ {
+ menuItems.map(menuItem => (
+ <div key={menuItem.key} className='mb-4'>
+ <div className='px-2 mb-[6px] text-xs font-medium text-gray-500'>{menuItem.name}</div>
+ <div>
+ {
+ menuItem.items.map(item => (
+ <div
+ key={item.key}
+ className={`
+ flex items-center h-[37px] mb-[2px] text-sm cursor-pointer rounded-lg
+ ${activeMenu === item.key ? 'font-semibold text-primary-600 bg-primary-50' : 'font-light text-gray-700'}
+ `}
+ onClick={() => setActiveMenu(item.key)}
+ >
+ {activeMenu === item.key ? item.activeIcon : item.icon}{item.name}
+ </div>
+ ))
+ }
+ </div>
+ </div>
+ ))
+ }
+ </div>
+ </div>
+ <div className='w-[520px] h-[580px] px-6 py-4 overflow-y-auto'>
+ <div className='flex items-center justify-between h-6 mb-8 text-base font-medium text-gray-900 '>
+ {[...menuItems[0].items, ...menuItems[1].items].find(item => item.key === activeMenu)?.name}
+ <XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
+ </div>
+ {
+ activeMenu === 'account' && <AccountPage />
+ }
+ {
+ activeMenu === 'members' && <MembersPage />
+ }
+ {
+ activeMenu === 'integrations' && <IntegrationsPage />
+ }
+ {
+ activeMenu === 'language' && <LanguagePage />
+ }
+ {
+ activeMenu === 'provider' && <ProviderPage />
+ }
+ </div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/web/app/components/header/account-setting/language-page/index.module.css b/web/app/components/header/account-setting/language-page/index.module.css
new file mode 100644
index 00000000000..5b7ef2cce37
--- /dev/null
+++ b/web/app/components/header/account-setting/language-page/index.module.css
@@ -0,0 +1,24 @@
+.google-icon {
+ background: url(../../assets/google.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.github-icon {
+ background: url(../../assets/github.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.twitter-icon {
+ background: url(../../assets/twitter.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.bitbucket-icon {
+ background: url(../../assets/bitbucket.svg) center center no-repeat;
+ background-size: 16px 16px;
+}
+
+.salesforce-icon {
+ background: url(../../assets/salesforce.svg) center center no-repeat;
+ background-size: 24px auto;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/language-page/index.tsx b/web/app/components/header/account-setting/language-page/index.tsx
new file mode 100644
index 00000000000..51608fabe59
--- /dev/null
+++ b/web/app/components/header/account-setting/language-page/index.tsx
@@ -0,0 +1,72 @@
+'use client'
+
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import { useAppContext } from '@/context/app-context'
+import { SimpleSelect } from '@/app/components/base/select'
+import type { Item } from '@/app/components/base/select'
+import { updateUserProfile } from '@/service/common'
+import { ToastContext } from '@/app/components/base/toast'
+import I18n from '@/context/i18n'
+import { timezones } from '@/utils/timezone'
+import { languageMaps, languages } from '@/utils/language'
+
+const titleClassName = `
+ mb-2 text-sm font-medium text-gray-900
+`
+
+export default function LanguagePage() {
+ const { locale, setLocaleOnClient } = useContext(I18n)
+ const { userProfile, mutateUserProfile } = useAppContext()
+ const { notify } = useContext(ToastContext)
+ const [editing, setEditing] = useState(false)
+ const { t } = useTranslation()
+ const handleSelect = async (type: string, item: Item) => {
+ let url = ''
+ let bodyKey = ''
+ if (type === 'language') {
+ url = '/account/interface-language'
+ bodyKey = 'interface_language'
+ setLocaleOnClient(item.value === 'en-US' ? 'en' : 'zh-Hans')
+ }
+ if (type === 'timezone') {
+ url = '/account/timezone'
+ bodyKey = 'timezone'
+ }
+ try {
+ setEditing(true)
+ await updateUserProfile({ url, body: { [bodyKey]: item.value } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ mutateUserProfile()
+ setEditing(false)
+ }
+ catch (e) {
+ notify({ type: 'error', message: (e as Error).message })
+ setEditing(false)
+ }
+ }
+
+ return (
+ <>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.language.displayLanguage')}</div>
+ <SimpleSelect
+ defaultValue={languageMaps[locale] || userProfile.interface_language}
+ items={languages}
+ onSelect={item => handleSelect('language', item)}
+ disabled={editing}
+ />
+ </div>
+ <div className='mb-8'>
+ <div className={titleClassName}>{t('common.language.timezone')}</div>
+ <SimpleSelect
+ defaultValue={userProfile.timezone}
+ items={timezones}
+ onSelect={item => handleSelect('timezone', item)}
+ disabled={editing}
+ />
+ </div>
+ </>
+ )
+}
diff --git a/web/app/components/header/account-setting/members-page/index.module.css b/web/app/components/header/account-setting/members-page/index.module.css
new file mode 100644
index 00000000000..5b89686291b
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/index.module.css
@@ -0,0 +1,9 @@
+.logo-icon {
+ width: 40px;
+ height: 40px;
+ background: #ffffff url(../../assets/logo-icon.png) center center no-repeat;
+ background-size: contain;
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+ border-radius: 8px;
+ border: 0.5px solid rgba(0, 0, 0, 0.05);
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsx
new file mode 100644
index 00000000000..e78328972a3
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/index.tsx
@@ -0,0 +1,114 @@
+'use client'
+import { useState } from 'react'
+import s from './index.module.css'
+import cn from 'classnames'
+import useSWR from 'swr'
+import dayjs from 'dayjs'
+import 'dayjs/locale/zh-cn'
+import relativeTime from 'dayjs/plugin/relativeTime'
+import I18n from '@/context/i18n'
+import { useContext } from 'use-context-selector'
+import { fetchMembers } from '@/service/common'
+import { UserPlusIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import InviteModal from './invite-modal'
+import InvitedModal from './invited-modal'
+import Operation from './operation'
+import { useAppContext } from '@/context/app-context'
+import Avatar from '@/app/components/base/avatar'
+import { useWorkspacesContext } from '@/context/workspace-context'
+
+dayjs.extend(relativeTime)
+const MembersPage = () => {
+ const { t } = useTranslation()
+ const RoleMap = {
+ owner: t('common.members.owner'),
+ admin: t('common.members.admin'),
+ normal: t('common.members.normal'),
+ }
+ const { locale } = useContext(I18n)
+ const { userProfile } = useAppContext()
+ const { data, mutate } = useSWR({ url: '/workspaces/current/members' }, fetchMembers)
+ const [inviteModalVisible, setInviteModalVisible] = useState(false)
+ const [invitedModalVisible, setInvitedModalVisible] = useState(false)
+ const accounts = data?.accounts || []
+ const owner = accounts.filter(account => account.role === 'owner')?.[0]?.email === userProfile.email
+ const { workspaces } = useWorkspacesContext()
+ const currentWrokspace = workspaces.filter(item => item.current)?.[0]
+
+ return (
+ <>
+ <div>
+ <div className='flex items-center mb-4 p-3 bg-gray-50 rounded-2xl'>
+ <div className={cn(s['logo-icon'], 'shrink-0')}></div>
+ <div className='grow mx-2'>
+ <div className='text-sm font-medium text-gray-900'>{currentWrokspace.name}</div>
+ <div className='text-xs text-gray-500'>{t('common.userProfile.workspace')}</div>
+ </div>
+ <div className='
+ shrink-0 flex items-center py-[7px] px-3 border-[0.5px] border-gray-200
+ text-[13px] font-medium text-primary-600 bg-white
+ shadow-[0_1px_2px_rgba(16,24,40,0.05)] rounded-lg cursor-pointer
+ ' onClick={() => setInviteModalVisible(true)}>
+ <UserPlusIcon className='w-4 h-4 mr-2 ' />
+ {t('common.members.invite')}
+ </div>
+ </div>
+ <div>
+ <div className='flex items-center py-[7px] border-b border-gray-200'>
+ <div className='grow px-3 text-xs font-medium text-gray-500'>{t('common.members.name')}</div>
+ <div className='shrink-0 w-[104px] text-xs font-medium text-gray-500'>{t('common.members.lastActive')}</div>
+ <div className='shrink-0 w-[96px] px-3 text-xs font-medium text-gray-500'>{t('common.members.role')}</div>
+ </div>
+ <div>
+ {
+ accounts.map(account => (
+ <div key={account.id} className='flex border-b border-gray-100'>
+ <div className='grow flex items-center py-2 px-3'>
+ <Avatar size={24} className='mr-2' name={account.name} />
+ <div className=''>
+ <div className='text-[13px] font-medium text-gray-700 leading-[18px]'>
+ {account.name}
+ {account.status === 'pending' && <span className='ml-1 text-xs text-[#DC6803]'>{t('common.members.pending')}</span>}
+ {userProfile.email === account.email && <span className='text-xs text-gray-500'>{t('common.members.you')}</span>}
+ </div>
+ <div className='text-xs text-gray-500 leading-[18px]'>{account.email}</div>
+ </div>
+ </div>
+ <div className='shrink-0 flex items-center w-[104px] py-2 text-[13px] text-gray-700'>{dayjs(Number((account.last_login_at || account.created_at)) * 1000).locale(locale === 'zh-Hans' ? 'zh-cn' : 'en').fromNow()}</div>
+ <div className='shrink-0 w-[96px] flex items-center'>
+ {
+ owner && account.role !== 'owner'
+ ? <Operation member={account} onOperate={() => mutate()} />
+ : <div className='px-3 text-[13px] text-gray-700'>{RoleMap[account.role] || RoleMap.normal}</div>
+ }
+ </div>
+ </div>
+ ))
+ }
+ </div>
+ </div>
+ </div>
+ {
+ inviteModalVisible && (
+ <InviteModal
+ onCancel={() => setInviteModalVisible(false)}
+ onSend={() => {
+ setInvitedModalVisible(true)
+ mutate()
+ }}
+ />
+ )
+ }
+ {
+ invitedModalVisible && (
+ <InvitedModal
+ onCancel={() => setInvitedModalVisible(false)}
+ />
+ )
+ }
+ </>
+ )
+}
+
+export default MembersPage
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/index.module.css b/web/app/components/header/account-setting/members-page/invite-modal/index.module.css
new file mode 100644
index 00000000000..2e21f3b6198
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/invite-modal/index.module.css
@@ -0,0 +1,4 @@
+.modal {
+ padding: 24px 32px !important;
+ width: 400px !important;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx
new file mode 100644
index 00000000000..353a0b373df
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx
@@ -0,0 +1,74 @@
+'use client'
+import { useState } from 'react'
+import { useContext } from 'use-context-selector'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import s from './index.module.css'
+import { inviteMember } from '@/service/common'
+import { emailRegex } from '@/config'
+import { ToastContext } from '@/app/components/base/toast'
+
+interface IInviteModalProps {
+ onCancel: () => void,
+ onSend: () => void,
+}
+const InviteModal = ({
+ onCancel,
+ onSend,
+}: IInviteModalProps) => {
+ const { t } = useTranslation()
+ const [email, setEmail] = useState('')
+ const { notify } = useContext(ToastContext)
+
+ const handleSend = async () => {
+ if (emailRegex.test(email)) {
+ try {
+ const res = await inviteMember({ url: '/workspaces/current/members/invite-email', body: { email, role: 'admin'} })
+
+ if (res.result === 'success') {
+ onCancel()
+ onSend()
+ }
+ } catch (e) {
+
+ }
+ } else {
+ notify({ type: 'error', message: t('common.members.emailInvalid') })
+ }
+ }
+
+ return (
+ <div className={s.wrap}>
+ <Modal isShow onClose={() => {}} className={s.modal}>
+ <div className='flex justify-between mb-2'>
+ <div className='text-xl font-semibold text-gray-900'>{t('common.members.inviteTeamMember')}</div>
+ <XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
+ </div>
+ <div className='mb-7 text-[13px] text-gray-500'>{t('common.members.inviteTeamMemberTip')}</div>
+ <div>
+ <div className='mb-2 text-sm font-medium text-gray-900'>{t('common.members.email')}</div>
+ <input
+ className='
+ block w-full py-2 mb-9 px-3 bg-gray-50 outline-none border-none
+ appearance-none text-sm text-gray-900 rounded-lg
+ '
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ placeholder={t('common.members.emailPlaceholder') || ''}
+ />
+ <Button
+ className='w-full text-sm font-medium'
+ onClick={handleSend}
+ type='primary'
+ >
+ {t('common.members.sendInvite')}
+ </Button>
+ </div>
+ </Modal>
+ </div>
+ )
+}
+
+export default InviteModal
diff --git a/web/app/components/header/account-setting/members-page/invited-modal/index.module.css b/web/app/components/header/account-setting/members-page/invited-modal/index.module.css
new file mode 100644
index 00000000000..4bb0be97e74
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/invited-modal/index.module.css
@@ -0,0 +1,5 @@
+.modal {
+ padding: 32px !important;
+ width: 480px !important;
+ background: linear-gradient(180deg, rgba(3, 152, 85, 0.05) 0%, rgba(3, 152, 85, 0) 22.44%), #F9FAFB !important;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/invited-modal/index.tsx b/web/app/components/header/account-setting/members-page/invited-modal/index.tsx
new file mode 100644
index 00000000000..71fd4196ff2
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/invited-modal/index.tsx
@@ -0,0 +1,45 @@
+import { CheckCircleIcon } from '@heroicons/react/24/solid'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import Modal from '@/app/components/base/modal'
+import Button from '@/app/components/base/button'
+import s from './index.module.css'
+
+interface IInvitedModalProps {
+ onCancel: () => void,
+}
+const InvitedModal = ({
+ onCancel
+}: IInvitedModalProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className={s.wrap}>
+ <Modal isShow onClose={() => {}} className={s.modal}>
+ <div className='flex justify-between mb-3'>
+ <div className='
+ w-12 h-12 flex items-center justify-center rounded-xl
+ bg-white border-[0.5px] border-gray-100
+ shadow-[0px_20px_24px_-4px_rgba(16,24,40,0.08),0px_8px_8px_-4px_rgba(16,24,40,0.03)]
+ '>
+ <CheckCircleIcon className='w-[22px] h-[22px] text-[#039855]' />
+ </div>
+ <XMarkIcon className='w-4 h-4 cursor-pointer' onClick={onCancel} />
+ </div>
+ <div className='mb-1 text-xl font-semibold text-gray-900'>{t('common.members.invitationSent')}</div>
+ <div className='mb-10 text-sm text-gray-500'>{t('common.members.invitationSentTip')}</div>
+ <div className='flex justify-end'>
+ <Button
+ className='w-[96px] text-sm font-medium'
+ onClick={onCancel}
+ type='primary'
+ >
+ {t('common.members.ok')}
+ </Button>
+ </div>
+ </Modal>
+ </div>
+ )
+}
+
+export default InvitedModal
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/operation/index.module.css b/web/app/components/header/account-setting/members-page/operation/index.module.css
new file mode 100644
index 00000000000..0189b046a36
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/operation/index.module.css
@@ -0,0 +1,3 @@
+.popup {
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/members-page/operation/index.tsx b/web/app/components/header/account-setting/members-page/operation/index.tsx
new file mode 100644
index 00000000000..f97dcc73978
--- /dev/null
+++ b/web/app/components/header/account-setting/members-page/operation/index.tsx
@@ -0,0 +1,136 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { Fragment } from 'react'
+import { useContext } from 'use-context-selector'
+import { Menu, Transition } from '@headlessui/react'
+import type { Member } from '@/models/common'
+import { deleteMemberOrCancelInvitation, updateMemberRole } from '@/service/common'
+import { ToastContext } from '@/app/components/base/toast'
+import s from './index.module.css'
+import cn from 'classnames'
+import { ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline'
+
+const itemClassName = `
+ flex px-3 py-2 cursor-pointer hover:bg-gray-50 rounded-lg
+`
+const itemIconClassName = `
+ w-4 h-4 mt-[2px] mr-1 text-primary-600
+`
+const itemTitleClassName = `
+ leading-[20px] text-sm text-gray-700 whitespace-nowrap
+`
+const itemDescClassName = `
+ leading-[18px] text-xs text-gray-500 whitespace-nowrap
+`
+
+interface IOperationProps {
+ member: Member
+ onOperate: () => void
+}
+
+const Operation = ({
+ member,
+ onOperate
+}: IOperationProps) => {
+ const { t } = useTranslation()
+ const RoleMap = {
+ owner: t('common.members.owner'),
+ admin: t('common.members.admin'),
+ normal: t('common.members.normal'),
+ }
+ const { notify } = useContext(ToastContext)
+ const handleDeleteMemberOrCancelInvitation = async () => {
+ try {
+ await deleteMemberOrCancelInvitation({ url: `/workspaces/current/members/${member.id}` })
+ onOperate()
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ } catch (e) {
+
+ }
+ }
+ const handleUpdateMemberRole = async (role: string) => {
+ try {
+ await updateMemberRole({
+ url: `/workspaces/current/members/${member.id}/update-role`,
+ body: { role }
+ })
+ onOperate()
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ } catch (e) {
+
+ }
+ }
+
+ return (
+ <Menu as="div" className="relative w-full h-full">
+ {
+ ({ open }) => (
+ <>
+ <Menu.Button className={cn(
+ `
+ group flex items-center justify-between w-full h-full justify-center
+ hover:bg-gray-100 cursor-pointer ${open && 'bg-gray-100'}
+ text-[13px] text-gray-700 px-3
+ `
+ )}>
+ {RoleMap[member.role] || RoleMap.normal}
+ <ChevronDownIcon className={`w-4 h-4 group-hover:block ${open ? 'block' : 'hidden'}`} />
+ </Menu.Button>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className={cn(
+ `
+ absolute right-0 top-[52px] z-10 bg-white border-[0.5px] border-gray-200
+ divide-y divide-gray-100 origin-top-right rounded-lg
+ `,
+ s.popup
+ )}
+ >
+ <div className="px-1 py-1">
+ {
+ ['admin', 'normal'].map(role => (
+ <Menu.Item>
+ <div className={itemClassName} onClick={() => handleUpdateMemberRole(role)}>
+ {
+ role === member.role
+ ? <CheckIcon className={itemIconClassName} />
+ : <div className={itemIconClassName} />
+ }
+ <div>
+ <div className={itemTitleClassName}>{t(`common.members.${role}`)}</div>
+ <div className={itemDescClassName}>{t(`common.members.${role}Tip`)}</div>
+ </div>
+ </div>
+ </Menu.Item>
+ ))
+ }
+ </div>
+ <Menu.Item>
+ <div className='px-1 py-1'>
+ <div className={itemClassName} onClick={handleDeleteMemberOrCancelInvitation}>
+ <div className={itemIconClassName} />
+ <div>
+ <div className={itemTitleClassName}>{t('common.members.removeFromTeam')}</div>
+ <div className={itemDescClassName}>{t('common.members.removeFromTeamTip')}</div>
+ </div>
+ </div>
+ </div>
+ </Menu.Item>
+ </Menu.Items>
+ </Transition>
+ </>
+ )
+ }
+ </Menu>
+ )
+}
+
+export default Operation
diff --git a/web/app/components/header/account-setting/provider-page/azure-provider/index.tsx b/web/app/components/header/account-setting/provider-page/azure-provider/index.tsx
new file mode 100644
index 00000000000..71236120e51
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/azure-provider/index.tsx
@@ -0,0 +1,75 @@
+import type { Provider, ProviderAzureToken } from '@/models/common'
+import { useTranslation } from 'react-i18next'
+import Link from 'next/link'
+import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
+import ProviderInput, { ProviderValidateTokenInput} from '../provider-input'
+import { useState } from 'react'
+import { ValidatedStatus } from '../provider-input/useValidateToken'
+
+interface IAzureProviderProps {
+ provider: Provider
+ onValidatedStatus: (status?: ValidatedStatus) => void
+ onTokenChange: (token: ProviderAzureToken) => void
+}
+const AzureProvider = ({
+ provider,
+ onTokenChange,
+ onValidatedStatus
+}: IAzureProviderProps) => {
+ const { t } = useTranslation()
+ const [token, setToken] = useState(provider.token as ProviderAzureToken || {})
+ const handleFocus = () => {
+ if (token === provider.token) {
+ token.azure_api_key = ''
+ setToken({...token})
+ onTokenChange({...token})
+ }
+ }
+ const handleChange = (type: keyof ProviderAzureToken, v: string) => {
+ token[type] = v
+ setToken({...token})
+ onTokenChange({...token})
+ }
+
+ return (
+ <div className='px-4 py-3'>
+ <ProviderInput
+ className='mb-4'
+ name={t('common.provider.azure.resourceName')}
+ placeholder={t('common.provider.azure.resourceNamePlaceholder')}
+ value={token.azure_api_base}
+ onChange={(v) => handleChange('azure_api_base', v)}
+ />
+ <ProviderInput
+ className='mb-4'
+ name={t('common.provider.azure.deploymentId')}
+ placeholder={t('common.provider.azure.deploymentIdPlaceholder')}
+ value={token.azure_api_type}
+ onChange={v => handleChange('azure_api_type', v)}
+ />
+ <ProviderInput
+ className='mb-4'
+ name={t('common.provider.azure.apiVersion')}
+ placeholder={t('common.provider.azure.apiVersionPlaceholder')}
+ value={token.azure_api_version}
+ onChange={v => handleChange('azure_api_version', v)}
+ />
+ <ProviderValidateTokenInput
+ className='mb-4'
+ name={t('common.provider.azure.apiKey')}
+ placeholder={t('common.provider.azure.apiKeyPlaceholder')}
+ value={token.azure_api_key}
+ onChange={v => handleChange('azure_api_key', v)}
+ onFocus={handleFocus}
+ onValidatedStatus={onValidatedStatus}
+ providerName={provider.provider_name}
+ />
+ <Link className="flex items-center text-xs cursor-pointer text-primary-600" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
+ {t('common.provider.azure.helpTip')}
+ <ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
+ </Link>
+ </div>
+ )
+}
+
+export default AzureProvider
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/index.module.css b/web/app/components/header/account-setting/provider-page/index.module.css
new file mode 100644
index 00000000000..c7a113a431e
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/index.module.css
@@ -0,0 +1,17 @@
+.wrapper .button {
+ height: 24px;
+ font-size: 12px;
+ border-radius: 6px;
+}
+
+.gpt-icon {
+ margin-right: 12px;
+ width: 20px;
+ height: 20px;
+ background: url(../../assets/gpt.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.input {
+ box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/index.tsx b/web/app/components/header/account-setting/provider-page/index.tsx
new file mode 100644
index 00000000000..c1bce2c54cd
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/index.tsx
@@ -0,0 +1,112 @@
+import { useState } from 'react'
+import useSWR from 'swr'
+import { fetchProviders } from '@/service/common'
+import ProviderItem from './provider-item'
+import OpenaiHostedProvider from './openai-hosted-provider'
+import type { ProviderHosted } from '@/models/common'
+import { LockClosedIcon } from '@heroicons/react/24/solid'
+import { useTranslation } from 'react-i18next'
+import Link from 'next/link'
+import { IS_CE_EDITION } from '@/config'
+
+const providersMap: {[k: string]: any} = {
+ 'openai-custom': {
+ icon: 'openai',
+ name: 'OpenAI',
+ },
+ 'azure_openai-custom': {
+ icon: 'azure',
+ name: 'Azure OpenAI Service',
+ }
+}
+
+// const providersList = [
+// {
+// id: 'openai',
+// name: 'OpenAI',
+// providerKey: '1',
+// status: '',
+// child: <OpenaiProvider />
+// },
+// {
+// id: 'azure',
+// name: 'Azure OpenAI Service',
+// providerKey: '1',
+// status: 'error',
+// child: <AzureProvider />
+// },
+// {
+// id: 'anthropic',
+// name: 'Anthropic',
+// providerKey: '',
+// status: '',
+// child: <div>placeholder</div>
+// },
+// {
+// id: 'hugging-face',
+// name: 'Hugging Face Hub',
+// providerKey: '',
+// comingSoon: true,
+// status: '',
+// child: <div>placeholder</div>
+// }
+// ]
+
+const ProviderPage = () => {
+ const { t } = useTranslation()
+ const [activeProviderId, setActiveProviderId] = useState('')
+ const { data, mutate } = useSWR({ url: '/workspaces/current/providers' }, fetchProviders)
+ const providers = data?.filter(provider => providersMap[`${provider.provider_name}-${provider.provider_type}`])?.map(provider => {
+ const providerKey = `${provider.provider_name}-${provider.provider_type}`
+ return {
+ provider,
+ icon: providersMap[providerKey].icon,
+ name: providersMap[providerKey].name,
+ }
+ })
+ const providerHosted = data?.filter(provider => provider.provider_name === 'openai' && provider.provider_type === 'system')?.[0]
+
+ return (
+ <div>
+ {
+ providerHosted && !IS_CE_EDITION && (
+ <>
+ <div>
+ <OpenaiHostedProvider provider={providerHosted as ProviderHosted} />
+ </div>
+ <div className='my-5 w-full h-0 border-[0.5px] border-gray-100' />
+ </>
+ )
+ }
+ <div>
+ {
+ providers?.map(providerItem => (
+ <ProviderItem
+ key={`${providerItem.provider.provider_name}-${providerItem.provider.provider_type}`}
+ icon={providerItem.icon}
+ name={providerItem.name}
+ provider={providerItem.provider}
+ activeId={activeProviderId}
+ onActive={aid => setActiveProviderId(aid)}
+ onSave={() => mutate()}
+ />
+ ))
+ }
+ </div>
+ <div className='absolute bottom-0 w-full h-[42px] flex items-center bg-white text-xs text-gray-500'>
+ <LockClosedIcon className='w-3 h-3 mr-1' />
+ {t('common.provider.encrypted.front')}
+ <Link
+ className='text-primary-600 mx-1'
+ target={'_blank'}
+ href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
+ >
+ PKCS1_OAEP
+ </Link>
+ {t('common.provider.encrypted.back')}
+ </div>
+ </div>
+ )
+}
+
+export default ProviderPage
diff --git a/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.module.css b/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.module.css
new file mode 100644
index 00000000000..2c5eb75b9d5
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.module.css
@@ -0,0 +1,24 @@
+.icon {
+ width: 24px;
+ height: 24px;
+ margin-right: 12px;
+ background: url(../../../assets/gpt.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.bar {
+ background: linear-gradient(90deg, rgba(41, 112, 255, 0.9) 0%, rgba(21, 94, 239, 0.9) 100%);
+}
+
+.bar-error {
+ background: linear-gradient(90deg, rgba(240, 68, 56, 0.72) 0%, rgba(217, 45, 32, 0.9) 100%);
+}
+
+.bar-item {
+ width: 10%;
+ border-right: 1px solid rgba(255, 255, 255, 0.5);
+}
+
+.bar-item:last-of-type {
+ border-right: 0;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.tsx b/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.tsx
new file mode 100644
index 00000000000..5a4e93f9b40
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/openai-hosted-provider/index.tsx
@@ -0,0 +1,65 @@
+import { useTranslation } from 'react-i18next'
+import s from './index.module.css'
+import cn from 'classnames'
+import type { ProviderHosted } from '@/models/common'
+
+interface IOpenaiHostedProviderProps {
+ provider: ProviderHosted
+}
+const OpenaiHostedProvider = ({
+ provider
+}: IOpenaiHostedProviderProps) => {
+ const { t } = useTranslation()
+ const exhausted = provider.quota_used > provider.quota_limit
+
+ return (
+ <div className={`
+ border-[0.5px] border-gray-200 rounded-xl
+ ${exhausted ? 'bg-[#FFFBFA]' : 'bg-gray-50'}
+ `}>
+ <div className='pt-4 px-4 pb-3'>
+ <div className='flex items-center mb-3'>
+ <div className={s.icon} />
+ <div className='grow text-sm font-medium text-gray-800'>
+ {t('common.provider.openaiHosted.openaiHosted')}
+ </div>
+ <div className={`
+ px-2 h-[22px] flex items-center rounded-md border
+ text-xs font-semibold
+ ${exhausted ? 'border-[#D92D20] text-[#D92D20]' : 'border-primary-600 text-primary-600'}
+ `}>
+ {exhausted ? t('common.provider.openaiHosted.exhausted') : t('common.provider.openaiHosted.onTrial')}
+ </div>
+ </div>
+ <div className='text-[13px] text-gray-500'>{t('common.provider.openaiHosted.desc')}</div>
+ </div>
+ <div className='flex items-center h-[42px] px-4 border-t-[0.5px] border-t-[rgba(0, 0, 0, 0.05)]'>
+ <div className='text-[13px] text-gray-700'>{t('common.provider.openaiHosted.callTimes')}</div>
+ <div className='relative grow h-2 flex bg-gray-200 rounded-md mx-2 overflow-hidden'>
+ <div
+ className={cn(s.bar, exhausted && s['bar-error'], 'absolute top-0 left-0 right-0 bottom-0')}
+ style={{ width: `${(provider.quota_used / provider.quota_limit * 100).toFixed(2)}%` }}
+ />
+ {Array(10).fill(0).map((i, k) => (
+ <div key={k} className={s['bar-item']} />
+ ))}
+ </div>
+ <div className={`
+ text-[13px] font-medium ${exhausted ? 'text-[#D92D20]' : 'text-gray-700'}
+ `}>{provider.quota_used}/{provider.quota_limit}</div>
+ </div>
+ {
+ exhausted && (
+ <div className='
+ px-4 py-3 leading-[18px] flex items-center text-[13px] text-gray-700 font-medium
+ bg-[#FFFAEB] border-t border-t-[rgba(0, 0, 0, 0.05)] rounded-b-xl
+ '>
+ {t('common.provider.openaiHosted.usedUp')}
+ </div>
+ )
+ }
+ </div>
+ )
+}
+
+export default OpenaiHostedProvider
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/openai-provider/index.module.css b/web/app/components/header/account-setting/provider-page/openai-provider/index.module.css
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/web/app/components/header/account-setting/provider-page/openai-provider/index.tsx b/web/app/components/header/account-setting/provider-page/openai-provider/index.tsx
new file mode 100644
index 00000000000..adff6bdf302
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/openai-provider/index.tsx
@@ -0,0 +1,223 @@
+import { ChangeEvent, useEffect, useRef, useState } from 'react'
+import { useContext } from 'use-context-selector'
+import { useTranslation } from 'react-i18next'
+import { debounce } from 'lodash-es'
+import Link from 'next/link'
+import useSWR from 'swr'
+import { ArrowTopRightOnSquareIcon, PencilIcon } from '@heroicons/react/24/outline'
+import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/solid'
+import Button from '@/app/components/base/button'
+import s from './index.module.css'
+import classNames from 'classnames'
+import { fetchTenantInfo, validateProviderKey, updateProviderAIKey } from '@/service/common'
+import { ToastContext } from '@/app/components/base/toast'
+import Indicator from '../../../indicator'
+import I18n from '@/context/i18n'
+
+type IStatusType = 'normal' | 'verified' | 'error' | 'error-api-key-exceed-bill'
+
+type TInputWithStatusProps = {
+ value: string
+ onChange: (v: string) => void
+ onValidating: (validating: boolean) => void
+ verifiedStatus: IStatusType
+ onVerified: (verified: IStatusType) => void
+}
+const InputWithStatus = ({
+ value,
+ onChange,
+ onValidating,
+ verifiedStatus,
+ onVerified
+}: TInputWithStatusProps) => {
+ const { t } = useTranslation()
+ const validateKey = useRef(debounce(async (token: string) => {
+ if (!token) return
+ onValidating(true)
+ try {
+ const res = await validateProviderKey({ url: '/workspaces/current/providers/openai/token-validate', body: { token } })
+ onVerified(res.result === 'success' ? 'verified' : 'error')
+ } catch (e: any) {
+ if (e.status === 400) {
+ e.json().then(({ code }: any) => {
+ if (code === 'provider_request_failed') {
+ onVerified('error-api-key-exceed-bill')
+ }
+ })
+ } else {
+ onVerified('error')
+ }
+ } finally {
+ onValidating(false)
+ }
+ }, 500))
+
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ const inputValue = e.target.value
+ onChange(inputValue)
+ if (!inputValue) {
+ onVerified('normal')
+ }
+ validateKey.current(inputValue)
+ }
+ return (
+ <div className={classNames('flex items-center h-9 px-3 bg-white border border-gray-300 rounded-lg', s.input)}>
+ <input
+ value={value}
+ placeholder={t('common.provider.enterYourKey') || ''}
+ className='w-full h-9 mr-2 appearance-none outline-none bg-transparent text-xs'
+ onChange={handleChange}
+ />
+ {
+ verifiedStatus === 'error' && <ExclamationCircleIcon className='w-4 h-4 text-[#D92D20]' />
+ }
+ {
+ verifiedStatus === 'verified' && <CheckCircleIcon className='w-4 h-4 text-[#039855]' />
+ }
+ </div>
+ )
+}
+
+const OpenaiProvider = () => {
+ const { t } = useTranslation()
+ const { locale } = useContext(I18n)
+ const { data: userInfo, mutate } = useSWR({ url: '/info' }, fetchTenantInfo)
+ const [inputValue, setInputValue] = useState<string>('')
+ const [validating, setValidating] = useState(false)
+ const [editStatus, setEditStatus] = useState<IStatusType>('normal')
+ const [loading, setLoading] = useState(false)
+ const [editing, setEditing] = useState(false)
+ const [invalidStatus, setInvalidStatus] = useState(false)
+ const { notify } = useContext(ToastContext)
+ const provider = userInfo?.providers?.find(({ provider }) => provider === 'openai')
+
+ const handleReset = () => {
+ setInputValue('')
+ setValidating(false)
+ setEditStatus('normal')
+ setLoading(false)
+ setEditing(false)
+ }
+ const handleSave = async () => {
+ if (editStatus === 'verified') {
+ try {
+ setLoading(true)
+ await updateProviderAIKey({ url: '/workspaces/current/providers/openai/token', body: { token: inputValue ?? '' } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ } catch (e) {
+ notify({ type: 'error', message: t('common.provider.saveFailed') })
+ } finally {
+ setLoading(false)
+ handleReset()
+ mutate()
+ }
+ }
+ }
+ useEffect(() => {
+ if (provider && !provider.token_is_valid && provider.token_is_set) {
+ setInvalidStatus(true)
+ }
+ }, [userInfo])
+
+ const showInvalidStatus = invalidStatus && !editing
+ const renderErrorMessage = () => {
+ if (validating) {
+ return (
+ <div className={`mt-2 text-primary-600 text-xs font-normal`}>
+ {t('common.provider.validating')}
+ </div>
+ )
+ }
+ if (editStatus === 'error-api-key-exceed-bill') {
+ return (
+ <div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
+ {t('common.provider.apiKeyExceedBill')}&nbsp;
+ <Link
+ className='underline'
+ href="https://platform.openai.com/account/api-keys"
+ target={'_blank'}>
+ {locale === 'en' ? 'this link' : '这篇文档'}
+ </Link>
+ </div>
+ )
+ }
+ if (showInvalidStatus || editStatus === 'error') {
+ return (
+ <div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
+ {t('common.provider.invalidKey')}
+ </div>
+ )
+ }
+ return null
+ }
+
+ return (
+ <div className='px-4 pt-3 pb-4'>
+ <div className='flex items-center mb-2 h-6'>
+ <div className='grow text-[13px] text-gray-800 font-medium'>
+ {t('common.provider.apiKey')}
+ </div>
+ {
+ provider && !editing && (
+ <div
+ className='
+ flex items-center h-6 px-2 rounded-md border border-gray-200
+ text-xs font-medium text-gray-700 cursor-pointer
+ '
+ onClick={() => setEditing(true)}
+ >
+ <PencilIcon className='mr-1 w-3 h-3 text-gray-500' />
+ {t('common.operation.edit')}
+ </div>
+ )
+ }
+ {
+ (inputValue || editing) && (
+ <>
+ <Button
+ className={classNames('mr-1', s.button)}
+ loading={loading}
+ onClick={handleReset}
+ >
+ {t('common.operation.cancel')}
+ </Button>
+ <Button
+ type='primary'
+ className={classNames(s.button)}
+ loading={loading}
+ onClick={handleSave}>
+ {t('common.operation.save')}
+ </Button>
+ </>
+ )
+ }
+ </div>
+ {
+ (!provider || (provider && editing)) && (
+ <InputWithStatus
+ value={inputValue}
+ onChange={v => setInputValue(v)}
+ verifiedStatus={editStatus}
+ onVerified={v => setEditStatus(v)}
+ onValidating={v => setValidating(v)}
+ />
+ )
+ }
+ {
+ (provider && !editing) && (
+ <div className={classNames('flex justify-between items-center bg-white px-3 h-9 rounded-lg text-gray-800 text-xs font-medium', s.input)}>
+ sk-0C...skuA
+ <Indicator color={(provider.token_is_set && provider.token_is_valid) ? 'green' : 'orange'} />
+ </div>
+ )
+ }
+ {renderErrorMessage()}
+ <Link className="inline-flex items-center mt-3 text-xs font-normal cursor-pointer text-primary-600 w-fit" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
+ {t('appOverview.welcome.getKeyTip')}
+ <ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
+ </Link>
+ </div>
+ )
+}
+
+export default OpenaiProvider
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/openai-provider/provider.tsx b/web/app/components/header/account-setting/provider-page/openai-provider/provider.tsx
new file mode 100644
index 00000000000..45747cb3a81
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/openai-provider/provider.tsx
@@ -0,0 +1,52 @@
+import type { Provider } from '@/models/common'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { ProviderValidateTokenInput } from '../provider-input'
+import Link from 'next/link'
+import { ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'
+import { ValidatedStatus } from '../provider-input/useValidateToken'
+
+interface IOpenaiProviderProps {
+ provider: Provider
+ onValidatedStatus: (status?: ValidatedStatus) => void
+ onTokenChange: (token: string) => void
+}
+
+const OpenaiProvider = ({
+ provider,
+ onValidatedStatus,
+ onTokenChange
+}: IOpenaiProviderProps) => {
+ const { t } = useTranslation()
+ const [token, setToken] = useState(provider.token as string || '')
+ const handleFocus = () => {
+ if (token === provider.token) {
+ setToken('')
+ onTokenChange('')
+ }
+ }
+ const handleChange = (v: string) => {
+ setToken(v)
+ onTokenChange(v)
+ }
+
+ return (
+ <div className='px-4 pt-3 pb-4'>
+ <ProviderValidateTokenInput
+ value={token}
+ name={t('common.provider.apiKey')}
+ placeholder={t('common.provider.enterYourKey')}
+ onChange={handleChange}
+ onFocus={handleFocus}
+ onValidatedStatus={onValidatedStatus}
+ providerName={provider.provider_name}
+ />
+ <Link className="inline-flex items-center mt-3 text-xs font-normal cursor-pointer text-primary-600 w-fit" href="https://platform.openai.com/account/api-keys" target={'_blank'}>
+ {t('appOverview.welcome.getKeyTip')}
+ <ArrowTopRightOnSquareIcon className='w-3 h-3 ml-1 text-primary-600' aria-hidden="true" />
+ </Link>
+ </div>
+ )
+}
+
+export default OpenaiProvider
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/provider-input/index.tsx b/web/app/components/header/account-setting/provider-page/provider-input/index.tsx
new file mode 100644
index 00000000000..5a489d17f27
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/provider-input/index.tsx
@@ -0,0 +1,143 @@
+import { ChangeEvent, useEffect } from 'react'
+import Link from 'next/link'
+import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/solid'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import I18n from '@/context/i18n'
+import useValidateToken, { ValidatedStatus } from './useValidateToken'
+
+interface IProviderInputProps {
+ value?: string
+ name: string
+ placeholder: string
+ className?: string
+ onChange: (v: string) => void
+ onFocus?: () => void
+}
+
+const ProviderInput = ({
+ value,
+ name,
+ placeholder,
+ className,
+ onChange,
+ onFocus,
+}: IProviderInputProps) => {
+
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ const inputValue = e.target.value
+ onChange(inputValue)
+ }
+
+ return (
+ <div className={className}>
+ <div className="mb-2 text-[13px] font-medium text-gray-800">{name}</div>
+ <div className='
+ flex items-center px-3 bg-white rounded-lg
+ shadow-[0_1px_2px_rgba(16,24,40,0.05)]
+ '>
+ <input
+ className='
+ w-full py-[9px]
+ text-xs font-medium text-gray-700 leading-[18px]
+ appearance-none outline-none bg-transparent
+ '
+ value={value}
+ placeholder={placeholder}
+ onChange={handleChange}
+ onFocus={onFocus}
+ />
+ </div>
+ </div>
+ )
+}
+
+type TproviderInputProps = IProviderInputProps
+ & {
+ onValidatedStatus?: (status?: ValidatedStatus) => void
+ providerName: string
+ }
+export const ProviderValidateTokenInput = ({
+ value,
+ name,
+ placeholder,
+ className,
+ onChange,
+ onFocus,
+ onValidatedStatus,
+ providerName
+}: TproviderInputProps) => {
+ const { t } = useTranslation()
+ const { locale } = useContext(I18n)
+ const [ validating, validatedStatus, validate ] = useValidateToken(providerName)
+
+ useEffect(() => {
+ if (typeof onValidatedStatus === 'function') {
+ onValidatedStatus(validatedStatus)
+ }
+ }, [validatedStatus])
+
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ const inputValue = e.target.value
+ onChange(inputValue)
+
+ validate(inputValue)
+ }
+
+ return (
+ <div className={className}>
+ <div className="mb-2 text-[13px] font-medium text-gray-800">{name}</div>
+ <div className='
+ flex items-center px-3 bg-white rounded-lg
+ shadow-[0_1px_2px_rgba(16,24,40,0.05)]
+ '>
+ <input
+ className='
+ w-full py-[9px]
+ text-xs font-medium text-gray-700 leading-[18px]
+ appearance-none outline-none bg-transparent
+ '
+ value={value}
+ placeholder={placeholder}
+ onChange={handleChange}
+ onFocus={onFocus}
+ />
+ {
+ validatedStatus === ValidatedStatus.Error && <ExclamationCircleIcon className='w-4 h-4 text-[#D92D20]' />
+ }
+ {
+ validatedStatus === ValidatedStatus.Success && <CheckCircleIcon className='w-4 h-4 text-[#039855]' />
+ }
+ </div>
+ {
+ validating && (
+ <div className={`mt-2 text-primary-600 text-xs font-normal`}>
+ {t('common.provider.validating')}
+ </div>
+ )
+ }
+ {
+ validatedStatus === ValidatedStatus.Exceed && !validating && (
+ <div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
+ {t('common.provider.apiKeyExceedBill')}&nbsp;
+ <Link
+ className='underline'
+ href="https://platform.openai.com/account/api-keys"
+ target={'_blank'}>
+ {locale === 'en' ? 'this link' : '这篇文档'}
+ </Link>
+ </div>
+ )
+ }
+ {
+ validatedStatus === ValidatedStatus.Error && !validating && (
+ <div className={`mt-2 text-[#D92D20] text-xs font-normal`}>
+ {t('common.provider.invalidKey')}
+ </div>
+ )
+ }
+ </div>
+ )
+}
+
+export default ProviderInput
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/provider-input/useValidateToken.ts b/web/app/components/header/account-setting/provider-page/provider-input/useValidateToken.ts
new file mode 100644
index 00000000000..d6337fa21c1
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/provider-input/useValidateToken.ts
@@ -0,0 +1,46 @@
+import { useState, useCallback } from 'react'
+import debounce from 'lodash/debounce'
+import { DebouncedFunc } from 'lodash'
+import { validateProviderKey } from '@/service/common'
+
+export enum ValidatedStatus {
+ Success = 'success',
+ Error = 'error',
+ Exceed = 'exceed'
+}
+
+const useValidateToken = (providerName: string): [boolean, ValidatedStatus | undefined, DebouncedFunc<(token: string) => Promise<void>>] => {
+ const [validating, setValidating] = useState(false)
+ const [validatedStatus, setValidatedStatus] = useState<ValidatedStatus | undefined>()
+ const validate = useCallback(debounce(async (token: string) => {
+ if (!token) {
+ setValidatedStatus(undefined)
+ return
+ }
+ setValidating(true)
+ try {
+ const res = await validateProviderKey({ url: `/workspaces/current/providers/${providerName}/token-validate`, body: { token } })
+ setValidatedStatus(res.result === 'success' ? ValidatedStatus.Success : ValidatedStatus.Error)
+ } catch (e: any) {
+ if (e.status === 400) {
+ e.json().then(({ code }: any) => {
+ if (code === 'provider_request_failed') {
+ setValidatedStatus(ValidatedStatus.Exceed)
+ }
+ })
+ } else {
+ setValidatedStatus(ValidatedStatus.Error)
+ }
+ } finally {
+ setValidating(false)
+ }
+ }, 500), [])
+
+ return [
+ validating,
+ validatedStatus,
+ validate,
+ ]
+}
+
+export default useValidateToken
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/provider-item/index.module.css b/web/app/components/header/account-setting/provider-page/provider-item/index.module.css
new file mode 100644
index 00000000000..313078ba8b6
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/provider-item/index.module.css
@@ -0,0 +1,19 @@
+.icon-openai {
+ background: url(../../../assets/gpt.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.icon-azure {
+ background: url(../../../assets/azure.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.icon-anthropic {
+ background: url(../../../assets/anthropic.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.icon-hugging-face {
+ background: url(../../../assets/hugging-face.svg) center center no-repeat;
+ background-size: contain;
+}
\ No newline at end of file
diff --git a/web/app/components/header/account-setting/provider-page/provider-item/index.tsx b/web/app/components/header/account-setting/provider-page/provider-item/index.tsx
new file mode 100644
index 00000000000..4e8ef532e3e
--- /dev/null
+++ b/web/app/components/header/account-setting/provider-page/provider-item/index.tsx
@@ -0,0 +1,138 @@
+import { useState } from 'react'
+import cn from 'classnames'
+import s from './index.module.css'
+import { useContext } from 'use-context-selector'
+import Indicator from '../../../indicator'
+import { useTranslation } from 'react-i18next'
+import type { Provider, ProviderAzureToken } from '@/models/common'
+import OpenaiProvider from '../openai-provider/provider'
+import AzureProvider from '../azure-provider'
+import { ValidatedStatus } from '../provider-input/useValidateToken'
+import { updateProviderAIKey } from '@/service/common'
+import { ToastContext } from '@/app/components/base/toast'
+
+interface IProviderItemProps {
+ icon: string
+ name: string
+ provider: Provider
+ activeId: string
+ onActive: (v: string) => void
+ onSave: () => void
+}
+const ProviderItem = ({
+ activeId,
+ icon,
+ name,
+ provider,
+ onActive,
+ onSave
+}: IProviderItemProps) => {
+ const { t } = useTranslation()
+ const [validatedStatus, setValidatedStatus] = useState<ValidatedStatus>()
+ const [loading, setLoading] = useState(false)
+ const { notify } = useContext(ToastContext)
+ const [token, setToken] = useState<ProviderAzureToken | string>(
+ provider.provider_name === 'azure_openai'
+ ? { azure_api_base: '', azure_api_type: '', azure_api_version: '', azure_api_key: '' }
+ : ''
+ )
+ const id = `${provider.provider_name}-${provider.provider_type}`
+ const isOpen = id === activeId
+ const providerKey = provider.provider_name === 'azure_openai' ? (provider.token as ProviderAzureToken)?.azure_api_key : provider.token
+ const comingSoon = false
+ const isValid = provider.is_valid
+
+ const handleUpdateToken = async () => {
+ if (loading) return
+ if (validatedStatus === ValidatedStatus.Success || !token) {
+ try {
+ setLoading(true)
+ await updateProviderAIKey({ url: `/workspaces/current/providers/${provider.provider_name}/token`, body: { token } })
+ notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
+ onActive('')
+ } catch (e) {
+ notify({ type: 'error', message: t('common.provider.saveFailed') })
+ } finally {
+ setLoading(false)
+ onSave()
+ }
+ }
+ }
+
+ return (
+ <div className='mb-2 border-[0.5px] border-gray-200 bg-gray-50 rounded-md'>
+ <div className='flex items-center px-4 h-[52px] cursor-pointer border-b-[0.5px] border-b-gray-200'>
+ <div className={cn(s[`icon-${icon}`], 'mr-3 w-6 h-6 rounded-md')} />
+ <div className='grow text-sm font-medium text-gray-800'>{name}</div>
+ {
+ providerKey && !comingSoon && !isOpen && (
+ <div className='flex items-center mr-4'>
+ {!isValid && <div className='text-xs text-[#D92D20]'>{t('common.provider.invalidApiKey')}</div>}
+ <Indicator color={!isValid ? 'red' : 'green'} className='ml-2' />
+ </div>
+ )
+ }
+ {
+ !comingSoon && !isOpen && (
+ <div className='
+ px-3 h-[28px] bg-white border border-gray-200 rounded-md cursor-pointer
+ text-xs font-medium text-gray-700 flex items-center
+ ' onClick={() => onActive(id)}>
+ {providerKey ? t('common.provider.editKey') : t('common.provider.addKey')}
+ </div>
+ )
+ }
+ {
+ comingSoon && !isOpen && (
+ <div className='
+ flex items-center px-2 h-[22px] border border-[#444CE7] rounded-md
+ text-xs font-medium text-[#444CE7]
+ '>
+ {t('common.provider.comingSoon')}
+ </div>
+ )
+ }
+ {
+ isOpen && (
+ <div className='flex items-center'>
+ <div className='
+ flex items-center
+ mr-[5px] px-3 h-7 rounded-md cursor-pointer
+ text-xs font-medium text-gray-700
+ ' onClick={() => onActive('')} >
+ {t('common.operation.cancel')}
+ </div>
+ <div className='
+ flex items-center
+ px-3 h-7 rounded-md cursor-pointer bg-primary-700
+ text-xs font-medium text-white
+ ' onClick={handleUpdateToken}>
+ {t('common.operation.save')}
+ </div>
+ </div>
+ )
+ }
+ </div>
+ {
+ provider.provider_name === 'openai' && isOpen && (
+ <OpenaiProvider
+ provider={provider}
+ onValidatedStatus={v => setValidatedStatus(v)}
+ onTokenChange={v => setToken(v)}
+ />
+ )
+ }
+ {
+ provider.provider_name === 'azure_openai' && isOpen && (
+ <AzureProvider
+ provider={provider}
+ onValidatedStatus={v => setValidatedStatus(v)}
+ onTokenChange={v => setToken(v)}
+ />
+ )
+ }
+ </div>
+ )
+}
+
+export default ProviderItem
\ No newline at end of file
diff --git a/web/app/components/header/app-back/index.tsx b/web/app/components/header/app-back/index.tsx
new file mode 100644
index 00000000000..374711eb938
--- /dev/null
+++ b/web/app/components/header/app-back/index.tsx
@@ -0,0 +1,37 @@
+'use client'
+
+import React, { useState } from 'react'
+import classNames from 'classnames'
+import { useTranslation } from 'react-i18next'
+import { ArrowLeftIcon, Squares2X2Icon } from '@heroicons/react/24/solid'
+import type { AppDetailResponse } from '@/models/app'
+
+
+type IAppBackProps = {
+ curApp: AppDetailResponse
+}
+export default function AppBack({ curApp }: IAppBackProps) {
+ const { t } = useTranslation()
+
+ const [hovered, setHovered] = useState(false)
+
+ return (
+ <div
+ className={classNames(`
+ flex items-center h-7 pl-2.5 pr-2
+ text-[#1C64F2] font-semibold cursor-pointer
+ rounded-[10px]
+ ${curApp && 'hover:bg-[#EBF5FF]'}
+ `)}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ >
+ {
+ (hovered && curApp)
+ ? <ArrowLeftIcon className='mr-1 w-[18px] h-[18px]' />
+ : <Squares2X2Icon className='mr-1 w-[18px] h-[18px]' />
+ }
+ {t('common.menus.apps')}
+ </div>
+ )
+}
diff --git a/web/app/components/header/app-selector/index.tsx b/web/app/components/header/app-selector/index.tsx
new file mode 100644
index 00000000000..be0b4c4875f
--- /dev/null
+++ b/web/app/components/header/app-selector/index.tsx
@@ -0,0 +1,104 @@
+'use client'
+import { useTranslation } from 'react-i18next'
+import { Fragment, useState } from 'react'
+import { ChevronDownIcon, PlusIcon } from '@heroicons/react/24/solid'
+import { Menu, Transition } from '@headlessui/react'
+import { useRouter } from 'next/navigation'
+import Indicator from '../indicator'
+import type { AppDetailResponse } from '@/models/app'
+import NewAppDialog from '@/app/(commonLayout)/apps/NewAppDialog'
+import AppIcon from '@/app/components/base/app-icon'
+
+type IAppSelectorProps = {
+ appItems: AppDetailResponse[]
+ curApp: AppDetailResponse
+}
+
+export default function AppSelector({ appItems, curApp }: IAppSelectorProps) {
+ const router = useRouter()
+ const [showNewAppDialog, setShowNewAppDialog] = useState(false)
+ const { t } = useTranslation()
+
+ const itemClassName = `
+ flex items-center w-full h-10 px-3 text-gray-700 text-[14px]
+ rounded-lg font-normal hover:bg-gray-100 cursor-pointer
+ `
+
+ return (
+ <div className="">
+ <Menu as="div" className="relative inline-block text-left">
+ <div>
+ <Menu.Button
+ className="
+ inline-flex items-center w-full h-7 justify-center
+ rounded-[10px] pl-2 pr-2.5 text-[14px] font-semibold
+ text-[#1C64F2] hover:bg-[#EBF5FF]
+ "
+ >
+ {curApp?.name}
+ <ChevronDownIcon
+ className="w-3 h-3 ml-1"
+ aria-hidden="true"
+ />
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className="
+ absolute -left-11 right-0 mt-1.5 w-60 max-w-80
+ divide-y divide-gray-100 origin-top-right rounded-lg bg-white
+ shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_rgba(0,0,0,0.05)]
+ "
+ >
+ {!!appItems.length && (<div className="px-1 py-1 overflow-auto" style={{ maxHeight: '50vh' }}>
+ {
+ appItems.map((app: AppDetailResponse) => (
+ <Menu.Item key={app.id}>
+ <div className={itemClassName} onClick={() =>
+ router.push(`/app/${app.id}/overview`)
+ }>
+ <div className='relative w-6 h-6 mr-2 bg-[#D5F5F6] rounded-[6px]'>
+ <AppIcon size='tiny' />
+ <div className='flex justify-center items-center absolute -right-0.5 -bottom-0.5 w-2.5 h-2.5 bg-white rounded'>
+ <Indicator />
+ </div>
+ </div>
+ {app.name}
+ </div>
+ </Menu.Item>
+ ))
+ }
+ </div>)}
+ <Menu.Item>
+ <div className='p-1' onClick={() => setShowNewAppDialog(true)}>
+ <div
+ className='flex items-center h-12 rounded-lg cursor-pointer hover:bg-gray-100'
+ >
+ <div
+ className='
+ flex justify-center items-center
+ ml-4 mr-2 w-6 h-6 bg-gray-100 rounded-[6px]
+ border-[0.5px] border-gray-200 border-dashed
+ '
+ >
+ <PlusIcon className='w-4 h-4 text-gray-500' />
+ </div>
+ <div className='font-normal text-[14px] text-gray-700'>{t('common.menus.newApp')}</div>
+ </div>
+ </div>
+ </Menu.Item>
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ <NewAppDialog show={showNewAppDialog} onClose={() => setShowNewAppDialog(false)} />
+ </div>
+ )
+}
diff --git a/web/app/components/header/assets/alpha.svg b/web/app/components/header/assets/alpha.svg
new file mode 100644
index 00000000000..3be0fdbd3c4
--- /dev/null
+++ b/web/app/components/header/assets/alpha.svg
@@ -0,0 +1,4 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6 5.24975C5.58579 5.24975 5.25 5.58554 5.25 5.99975C5.25 6.41396 5.58579 6.74975 6 6.74975C6.41421 6.74975 6.75 6.41396 6.75 5.99975C6.75 5.58554 6.41421 5.24975 6 5.24975Z" fill="#344054"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M7.55961 1.2874C7.06059 1.49287 6.53398 1.7771 5.99996 2.13007C5.46595 1.77712 4.93936 1.4929 4.44036 1.28743C3.8603 1.04858 3.29372 0.906291 2.7826 0.902457C2.269 0.898605 1.77103 1.03634 1.40379 1.40358C1.03655 1.77082 0.89882 2.26879 0.902672 2.78238C0.906505 3.2935 1.0488 3.86008 1.28765 4.44015C1.49312 4.93915 1.77733 5.46574 2.13029 5.99975C1.77733 6.53376 1.49311 7.06036 1.28764 7.55936C1.04879 8.13942 0.9065 8.706 0.902666 9.21712C0.898814 9.73072 1.03655 10.2287 1.40379 10.5959C1.77103 10.9632 2.269 11.1009 2.78259 11.097C3.29371 11.0932 3.86029 10.9509 4.44035 10.7121C4.93935 10.5066 5.46595 10.2224 5.99996 9.86944C6.53398 10.2224 7.06059 10.5066 7.55961 10.7121C8.13967 10.951 8.70625 11.0933 9.21737 11.0971C9.73097 11.1009 10.2289 10.9632 10.5962 10.596C10.9634 10.2287 11.1012 9.73075 11.0973 9.21716C11.0935 8.70604 10.9512 8.13946 10.7123 7.5594C10.5068 7.06038 10.2226 6.53377 9.86966 5.99975C10.2226 5.46573 10.5068 4.93912 10.7123 4.44011C10.9512 3.86005 11.0935 3.29347 11.0973 2.78235C11.1011 2.26875 10.9634 1.77078 10.5962 1.40354C10.2289 1.0363 9.73096 0.89857 9.21737 0.902422C8.70625 0.906256 8.13967 1.04855 7.55961 1.2874ZM7.94035 2.21207C7.60184 2.35146 7.2419 2.53581 6.87023 2.7619C7.29274 3.09639 7.71306 3.47021 8.12131 3.87845C8.52954 4.28668 8.90334 4.70698 9.23781 5.12947C9.46391 4.75781 9.64826 4.39787 9.78764 4.05936C9.99666 3.55175 10.0948 3.11609 10.0973 2.77485C10.0999 2.43608 10.01 2.23156 9.88907 2.11065C9.76815 1.98973 9.56364 1.89985 9.22487 1.90239C8.88362 1.90495 8.44796 2.00306 7.94035 2.21207ZM2.21232 4.0594C2.35171 4.39789 2.53604 4.75782 2.76213 5.12947C3.09661 4.70697 3.47042 4.28665 3.87866 3.87842C4.28689 3.47019 4.70719 3.09639 5.12968 2.76191C4.75803 2.53582 4.3981 2.35149 4.05961 2.21211C3.552 2.00309 3.11634 1.90499 2.7751 1.90243C2.43633 1.89989 2.23181 1.98977 2.1109 2.11068C1.98998 2.2316 1.9001 2.43611 1.90264 2.77488C1.9052 3.11613 2.00331 3.55179 2.21232 4.0594ZM4.58577 4.58552C4.11988 5.05141 3.70722 5.5288 3.35371 5.99975C3.70722 6.4707 4.11988 6.94809 4.58577 7.41398C5.05165 7.87986 5.52902 8.29251 5.99996 8.64601C6.47091 8.2925 6.9483 7.87984 7.41419 7.41395C7.88007 6.94807 8.29272 6.47069 8.64623 5.99975C8.29272 5.52881 7.88008 5.05143 7.4142 4.58556C6.94831 4.11966 6.47091 3.70701 5.99996 3.35349C5.52902 3.707 5.05164 4.11965 4.58577 4.58552ZM2.21232 7.94011C2.3517 7.60161 2.53604 7.24168 2.76213 6.87003C3.09661 7.29253 3.47042 7.71285 3.87866 8.12109C4.28689 8.52932 4.70719 8.90312 5.12968 9.23759C4.75803 9.46368 4.3981 9.64802 4.05961 9.7874C3.552 9.99641 3.11634 10.0945 2.77509 10.0971C2.43632 10.0996 2.23181 10.0097 2.11089 9.88882C1.98998 9.76791 1.9001 9.5634 1.90264 9.22462C1.9052 8.88338 2.0033 8.44772 2.21232 7.94011ZM7.94036 9.78743C7.60185 9.64804 7.2419 9.4637 6.87023 9.2376C7.29274 8.90311 7.71306 8.5293 8.1213 8.12106C8.52953 7.71282 8.90334 7.29252 9.23782 6.87003C9.46392 7.24169 9.64826 7.60163 9.78765 7.94015C9.99666 8.44775 10.0948 8.88342 10.0973 9.22466C10.0999 9.56343 10.01 9.76794 9.88907 9.88886C9.76816 10.0098 9.56364 10.0997 9.22487 10.0971C8.88363 10.0946 8.44797 9.99645 7.94036 9.78743Z" fill="#344054"/>
+</svg>
diff --git a/web/app/components/header/assets/anthropic.svg b/web/app/components/header/assets/anthropic.svg
new file mode 100644
index 00000000000..c0ec02d118c
--- /dev/null
+++ b/web/app/components/header/assets/anthropic.svg
@@ -0,0 +1,11 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="6" fill="#CA9F7B"/>
+<g clip-path="url(#clip0_3907_39360)">
+<path d="M14.9613 7.13043H12.8476L16.7022 16.8696H18.8159L14.9613 7.13043ZM8.85457 7.13043L5 16.8696H7.15539L7.94365 14.8243H11.9763L12.7645 16.8696H14.9199L11.0653 7.13043H8.85457ZM8.64091 13.0156L9.95996 9.59291L11.279 13.0156H8.64091Z" fill="#191918"/>
+</g>
+<defs>
+<clipPath id="clip0_3907_39360">
+<rect width="14" height="9.73913" fill="white" transform="translate(5 7.13043)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/header/assets/azure.svg b/web/app/components/header/assets/azure.svg
new file mode 100644
index 00000000000..3cfe3917ab0
--- /dev/null
+++ b/web/app/components/header/assets/azure.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="6" fill="#3980C5"/>
+<path d="M18.5963 11.6572C18.748 11.9956 18.8443 12.3574 18.8836 12.7264C18.9216 13.0954 18.9026 13.4689 18.8238 13.8321C18.7465 14.1953 18.6123 14.5439 18.4256 14.8648C18.3031 15.0792 18.1587 15.2805 17.9924 15.4657C17.8276 15.6495 17.6438 15.8158 17.444 15.9617C17.2427 16.1075 17.0283 16.2301 16.8007 16.3307C16.5746 16.4299 16.3383 16.5057 16.0962 16.5553C15.9824 16.9083 15.8132 17.2423 15.5944 17.5428C15.3771 17.8433 15.1131 18.1073 14.8126 18.3247C14.5121 18.5435 14.1795 18.7127 13.8266 18.8264C13.4736 18.9417 13.1045 18.9985 12.7326 18.9985C12.4861 19 12.2381 18.9738 11.996 18.9242C11.7553 18.8731 11.519 18.7958 11.2929 18.6952C11.0668 18.5945 10.8524 18.4691 10.6526 18.3232C10.4542 18.1773 10.2704 18.0096 10.107 17.8243C9.74237 17.9031 9.36896 17.9221 8.99992 17.8841C8.63089 17.8448 8.26914 17.7485 7.92928 17.5968C7.59088 17.4466 7.27727 17.2423 7.00159 16.9929C6.72591 16.7435 6.49107 16.4518 6.30582 16.1309C6.18184 15.9164 6.07973 15.6904 6.00242 15.4555C5.92511 15.2207 5.87406 14.9785 5.84781 14.732C5.82155 14.487 5.82301 14.239 5.84927 13.9925C5.87552 13.7475 5.92949 13.5053 6.0068 13.2705C5.75883 12.9948 5.55462 12.6812 5.40292 12.3428C5.25268 12.0029 5.15495 11.6426 5.11703 11.2736C5.07765 10.9046 5.09807 10.5312 5.17538 10.168C5.25268 9.80476 5.38688 9.45614 5.57358 9.13524C5.69611 8.92082 5.84051 8.71807 6.00534 8.53428C6.17017 8.3505 6.35541 8.18421 6.55525 8.03835C6.75508 7.89248 6.97096 7.7685 7.19705 7.66931C7.42459 7.56867 7.66089 7.49428 7.90303 7.44468C8.0168 7.09023 8.186 6.75766 8.40334 6.45718C8.62213 6.15671 8.88615 5.89269 9.18663 5.6739C9.48711 5.45656 9.81968 5.28736 10.1727 5.17213C10.5257 5.05835 10.8947 5.00001 11.2666 5.00146C11.5132 5.00001 11.7611 5.0248 12.0033 5.07586C12.2454 5.12691 12.4817 5.20276 12.7078 5.3034C12.9339 5.40551 13.1483 5.52949 13.3481 5.67535C13.548 5.82268 13.7317 5.98896 13.8951 6.17421C14.2583 6.0969 14.6317 6.07794 15.0008 6.11586C15.3698 6.15379 15.7301 6.25152 16.0699 6.40176C16.4083 6.55345 16.7219 6.75621 16.9976 7.00563C17.2733 7.2536 17.5082 7.54387 17.6934 7.86623C17.8174 8.07919 17.9195 8.30528 17.9968 8.54158C18.0741 8.77642 18.1266 9.01855 18.1514 9.26506C18.1777 9.51157 18.1777 9.75954 18.15 10.006C18.1237 10.2526 18.0697 10.4947 17.9924 10.7295C18.2418 11.0052 18.4446 11.3174 18.5963 11.6572ZM13.7361 17.8841C14.0541 17.7529 14.3429 17.5589 14.5865 17.3153C14.8301 17.0717 15.0241 16.7829 15.1554 16.4634C15.2866 16.1455 15.3552 15.8041 15.3552 15.4599V12.2071C15.3542 12.2042 15.3533 12.2008 15.3523 12.1969C15.3513 12.194 15.3499 12.1911 15.3479 12.1882C15.346 12.1853 15.3435 12.1828 15.3406 12.1809C15.3377 12.178 15.3348 12.176 15.3319 12.175L14.1547 11.4953V15.4249C14.1547 15.4643 14.1489 15.5051 14.1387 15.543C14.1285 15.5824 14.1139 15.6189 14.0935 15.6539C14.0731 15.6889 14.0497 15.721 14.0206 15.7487C13.9922 15.777 13.9603 15.8015 13.9257 15.8216L11.1383 17.4305C11.1149 17.4451 11.0756 17.4655 11.0551 17.4772C11.1704 17.5749 11.2958 17.661 11.4271 17.7368C11.5598 17.8127 11.6969 17.8769 11.8399 17.9294C11.9828 17.9804 12.1302 18.0198 12.2789 18.0461C12.4292 18.0723 12.5809 18.0854 12.7326 18.0854C13.0768 18.0854 13.4181 18.0169 13.7361 17.8841ZM7.09786 15.6758C7.27144 15.9748 7.50044 16.2344 7.77321 16.4445C8.04743 16.6545 8.35812 16.8077 8.69069 16.8967C9.02326 16.9856 9.37042 17.009 9.71174 16.9637C10.0531 16.9185 10.3813 16.8077 10.6803 16.6356L13.4984 15.0092L13.5057 15.0019C13.5076 14.9999 13.5091 14.997 13.51 14.9931C13.512 14.9902 13.5134 14.9873 13.5144 14.9844V13.6133L10.1129 15.581C10.0779 15.6014 10.0414 15.616 10.0035 15.6276C9.96408 15.6378 9.9247 15.6422 9.88386 15.6422C9.84447 15.6422 9.80509 15.6378 9.76571 15.6276C9.72778 15.616 9.68986 15.6014 9.65485 15.581L6.86739 13.9706C6.8426 13.956 6.80613 13.9342 6.78571 13.921C6.75946 14.0713 6.74633 14.223 6.74633 14.3747C6.74633 14.5264 6.76091 14.6781 6.78717 14.8283C6.81342 14.9771 6.85427 15.1244 6.90532 15.2674C6.95783 15.4103 7.02201 15.5474 7.09786 15.6787V15.6758ZM6.36562 9.59325C6.1935 9.89228 6.08265 10.2219 6.03743 10.5632C5.99221 10.9046 6.01555 11.2503 6.10453 11.5843C6.1935 11.9169 6.34666 12.2276 6.5567 12.5018C6.76675 12.7745 7.02784 13.0035 7.32541 13.1757L10.142 14.8035C10.145 14.8045 10.1484 14.8055 10.1522 14.8064H10.1625C10.1663 14.8064 10.1697 14.8055 10.1727 14.8035C10.1756 14.8025 10.1785 14.8011 10.1814 14.7991L11.3629 14.1165L7.96137 12.1532C7.92782 12.1327 7.89573 12.1079 7.86656 12.0802C7.8383 12.0519 7.81379 12.02 7.79363 11.9854C7.77467 11.9504 7.75862 11.9139 7.74841 11.8746C7.7382 11.8366 7.73237 11.7973 7.73383 11.7564V8.44385C7.59088 8.49636 7.45231 8.56054 7.32103 8.63639C7.18975 8.7137 7.06577 8.80121 6.94908 8.89894C6.83385 8.99667 6.72591 9.10461 6.62818 9.2213C6.53045 9.33653 6.44439 9.46198 6.36854 9.59325H6.36562ZM16.0408 11.8454C16.0758 11.8658 16.1079 11.8892 16.137 11.9183C16.1647 11.946 16.1895 11.9781 16.21 12.0131C16.2289 12.0481 16.245 12.0861 16.2552 12.124C16.2639 12.1634 16.2698 12.2028 16.2683 12.2436V15.5562C16.7365 15.384 17.145 15.0821 17.4469 14.6854C17.7503 14.2886 17.9326 13.8146 17.9749 13.3186C18.0172 12.8227 17.918 12.3238 17.6876 11.8819C17.4571 11.4399 17.1056 11.0723 16.6738 10.8243L13.8572 9.19651C13.8543 9.19553 13.8509 9.19456 13.847 9.19359H13.8368C13.8338 9.19456 13.8304 9.19553 13.8266 9.19651C13.8236 9.19748 13.8207 9.19894 13.8178 9.20088L12.6421 9.88061L16.0437 11.8454H16.0408ZM17.215 10.0804H17.2135V10.0819L17.215 10.0804ZM17.2135 10.079C17.2981 9.58888 17.2412 9.08419 17.0487 8.62472C16.8576 8.16525 16.5382 7.76996 16.1297 7.48407C15.7213 7.19963 15.24 7.03626 14.7426 7.01438C14.2437 6.99396 13.7507 7.11503 13.3189 7.363L10.5023 8.98938C10.4994 8.99132 10.497 8.99375 10.495 8.99667L10.4892 9.00542C10.4882 9.00834 10.4872 9.01174 10.4863 9.01563C10.4853 9.01855 10.4848 9.02196 10.4848 9.02585V10.3853L13.8864 8.42051C13.9214 8.40009 13.9593 8.3855 13.9972 8.37383C14.0366 8.36362 14.076 8.35925 14.1154 8.35925C14.1562 8.35925 14.1956 8.36362 14.235 8.37383C14.2729 8.3855 14.3094 8.40009 14.3444 8.42051L17.1318 10.0308C17.1566 10.0454 17.1931 10.0659 17.2135 10.079ZM9.84301 8.57367C9.84301 8.53428 9.84885 8.4949 9.85906 8.45552C9.86927 8.41759 9.88386 8.37967 9.90428 8.34466C9.9247 8.31111 9.94804 8.27902 9.97721 8.24985C10.0049 8.22214 10.037 8.19734 10.072 8.17838L12.8595 6.5695C12.8857 6.55345 12.9222 6.53303 12.9426 6.52282C12.5605 6.20338 12.0937 5.99917 11.5992 5.93645C11.1047 5.87227 10.603 5.95104 10.1522 6.16254C9.70007 6.37404 9.3179 6.71099 9.05097 7.13107C8.78404 7.55262 8.64256 8.03981 8.64256 8.53866V11.7914C8.64353 11.7953 8.6445 11.7987 8.64547 11.8016C8.64645 11.8045 8.6479 11.8075 8.64985 11.8104C8.65179 11.8133 8.65422 11.8162 8.65714 11.8191C8.65909 11.8211 8.662 11.823 8.66589 11.825L9.84301 12.5047V8.57367ZM10.4819 12.8723L11.9974 13.7475L13.5129 12.8723V11.1234L11.9989 10.2482L10.4834 11.1234L10.4819 12.8723Z" fill="white"/>
+</svg>
diff --git a/web/app/components/header/assets/beaker.svg b/web/app/components/header/assets/beaker.svg
new file mode 100644
index 00000000000..c0b0f907443
--- /dev/null
+++ b/web/app/components/header/assets/beaker.svg
@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M4.13856 0.500003H7.8617C7.92126 0.49998 7.99238 0.499953 8.05504 0.505073C8.12765 0.511005 8.23165 0.526227 8.34062 0.581751C8.48174 0.653656 8.59648 0.768392 8.66838 0.909513C8.72391 1.01849 8.73913 1.12248 8.74506 1.19509C8.75018 1.25775 8.75015 1.32888 8.75013 1.38844V2.61157C8.75015 2.67113 8.75018 2.74226 8.74506 2.80492C8.73913 2.87753 8.72391 2.98153 8.66838 3.0905C8.59648 3.23162 8.48174 3.34636 8.34062 3.41826C8.23165 3.47379 8.12765 3.48901 8.05504 3.49494C8.03725 3.49639 8.01877 3.49743 8.00006 3.49817V5.2506C8.00006 5.55312 8.00408 5.61265 8.01723 5.66153C8.03245 5.71807 8.05747 5.7715 8.09117 5.81939C8.1203 5.86078 8.16346 5.90197 8.39586 6.09564L10.2807 7.66627C10.4566 7.81255 10.6116 7.94145 10.7267 8.10509C10.8278 8.24875 10.9029 8.40904 10.9486 8.57867C11.0005 8.7719 11.0003 8.97351 11.0001 9.2023C11.0001 9.39886 11.0002 9.59542 11.0002 9.79198C11.0003 9.98232 11.0005 10.1463 10.9713 10.2927C10.853 10.8877 10.3878 11.3529 9.7928 11.4712C9.64637 11.5003 9.48246 11.5002 9.29211 11.5001H2.70822C2.51787 11.5002 2.35396 11.5003 2.20753 11.4712C1.98473 11.4269 1.78014 11.334 1.60515 11.2038C1.42854 11.0725 1.28221 10.9034 1.17753 10.7077C1.10892 10.5796 1.05831 10.4401 1.02899 10.2927C0.999862 10.1463 0.999992 9.98233 1.00014 9.79199C1.00014 9.59542 1.00006 9.39886 1.00003 9.20229C0.999794 8.97351 0.999584 8.7719 1.05157 8.57867C1.09721 8.40904 1.17229 8.24875 1.27338 8.10509C1.38855 7.94145 1.54356 7.81255 1.71947 7.66627L3.60427 6.09564C3.83667 5.90197 3.87983 5.86078 3.90896 5.81939C3.94266 5.7715 3.96768 5.71807 3.9829 5.66153C3.99605 5.61265 4.00006 5.55312 4.00006 5.2506V3.49817C3.9814 3.49743 3.96297 3.49639 3.94521 3.49494C3.8726 3.48901 3.76861 3.47379 3.65964 3.41826C3.51851 3.34636 3.40378 3.23162 3.33187 3.0905C3.27635 2.98153 3.26113 2.87753 3.25519 2.80492C3.25008 2.74226 3.2501 2.67113 3.25013 2.61158V1.38844C3.2501 1.32888 3.25008 1.25775 3.25519 1.19509C3.26113 1.12248 3.27635 1.01849 3.33187 0.909513C3.40378 0.768392 3.51851 0.653656 3.65964 0.581751C3.76861 0.526227 3.8726 0.511005 3.94521 0.505073C4.00787 0.499953 4.079 0.49998 4.13856 0.500003ZM9.11909 8.00004H2.88104L4.28066 6.83373C4.45657 6.68745 4.61158 6.55855 4.72675 6.39491C4.82784 6.25125 4.90292 6.09096 4.94856 5.92133C5.00054 5.7281 5.00033 5.52649 5.0001 5.29771L5.00006 3.50001H7.00006L7.00003 5.29771C6.99979 5.52649 6.99958 5.7281 7.05157 5.92133C7.09721 6.09096 7.17229 6.25125 7.27338 6.39491C7.38855 6.55855 7.54356 6.68745 7.71947 6.83373L9.11909 8.00004Z" fill="#0E7090"/>
+</svg>
diff --git a/web/app/components/header/assets/bitbucket.svg b/web/app/components/header/assets/bitbucket.svg
new file mode 100644
index 00000000000..4d28ea72e91
--- /dev/null
+++ b/web/app/components/header/assets/bitbucket.svg
@@ -0,0 +1,10 @@
+<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_660_1978)">
+<path d="M16.1064 1.77422C16.1184 1.7048 16.115 1.63359 16.0965 1.56561C16.078 1.49763 16.0448 1.43453 15.9993 1.38074C15.9538 1.32696 15.8971 1.2838 15.8331 1.25431C15.7691 1.22481 15.6994 1.20969 15.629 1.21001H0.602662C0.531806 1.20898 0.461593 1.22358 0.397019 1.25276C0.332445 1.28195 0.275097 1.32501 0.229055 1.37888C0.183014 1.43275 0.14941 1.4961 0.130636 1.56443C0.111861 1.63276 0.108377 1.70439 0.120432 1.77422L2.31458 15.2285C2.33294 15.3417 2.3911 15.4448 2.47861 15.519C2.56611 15.5933 2.67723 15.6339 2.79199 15.6335H13.4493C13.6904 15.6335 13.8929 15.4648 13.9315 15.2285L16.1064 1.77422ZM9.78916 10.7823H6.4473L5.54553 6.05643H10.5993L9.78916 10.7823Z" fill="#2684FF"/>
+</g>
+<defs>
+<clipPath id="clip0_660_1978">
+<rect width="16" height="16" fill="white" transform="translate(0 0.5)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/header/assets/github.svg b/web/app/components/header/assets/github.svg
new file mode 100644
index 00000000000..f03798b5e1d
--- /dev/null
+++ b/web/app/components/header/assets/github.svg
@@ -0,0 +1,17 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_131_1011)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0003 0.5C9.15149 0.501478 6.39613 1.51046 4.22687 3.34652C2.05761 5.18259 0.615903 7.72601 0.159545 10.522C-0.296814 13.318 0.261927 16.1842 1.73587 18.6082C3.20981 21.0321 5.50284 22.8558 8.20493 23.753C8.80105 23.8636 9.0256 23.4941 9.0256 23.18C9.0256 22.8658 9.01367 21.955 9.0097 20.9592C5.6714 21.6804 4.96599 19.5505 4.96599 19.5505C4.42152 18.1674 3.63464 17.8039 3.63464 17.8039C2.54571 17.065 3.71611 17.0788 3.71611 17.0788C4.92227 17.1637 5.55616 18.3097 5.55616 18.3097C6.62521 20.1333 8.36389 19.6058 9.04745 19.2976C9.15475 18.5251 9.46673 17.9995 9.8105 17.7012C7.14383 17.4008 4.34204 16.3774 4.34204 11.8054C4.32551 10.6197 4.76802 9.47305 5.57801 8.60268C5.45481 8.30236 5.04348 7.08923 5.69524 5.44143C5.69524 5.44143 6.7027 5.12135 8.9958 6.66444C10.9627 6.12962 13.0379 6.12962 15.0047 6.66444C17.2958 5.12135 18.3013 5.44143 18.3013 5.44143C18.9551 7.08528 18.5437 8.29841 18.4205 8.60268C19.2331 9.47319 19.6765 10.6218 19.6585 11.8094C19.6585 16.3912 16.8507 17.4008 14.1801 17.6952C14.6093 18.0667 14.9928 18.7918 14.9928 19.9061C14.9928 21.5026 14.9789 22.7868 14.9789 23.18C14.9789 23.4981 15.1955 23.8695 15.8035 23.753C18.5059 22.8557 20.7992 21.0317 22.2731 18.6073C23.747 16.183 24.3055 13.3163 23.8486 10.5201C23.3917 7.7238 21.9493 5.18035 19.7793 3.34461C17.6093 1.50886 14.8533 0.500541 12.0042 0.5H12.0003Z" fill="#191717"/>
+<path d="M4.54444 17.6321C4.5186 17.6914 4.42322 17.7092 4.34573 17.6677C4.26823 17.6262 4.21061 17.5491 4.23843 17.4879C4.26625 17.4266 4.35964 17.4108 4.43714 17.4523C4.51463 17.4938 4.57424 17.5729 4.54444 17.6321Z" fill="#191717"/>
+<path d="M5.03123 18.1714C4.99008 18.192 4.943 18.1978 4.89805 18.1877C4.8531 18.1776 4.81308 18.1523 4.78483 18.1161C4.70734 18.0331 4.69143 17.9185 4.75104 17.8671C4.81066 17.8157 4.91797 17.8395 4.99546 17.9224C5.07296 18.0054 5.09084 18.12 5.03123 18.1714Z" fill="#191717"/>
+<path d="M5.50425 18.857C5.43072 18.9084 5.30553 18.857 5.23598 18.7543C5.21675 18.7359 5.20146 18.7138 5.19101 18.6893C5.18056 18.6649 5.17517 18.6386 5.17517 18.612C5.17517 18.5855 5.18056 18.5592 5.19101 18.5347C5.20146 18.5103 5.21675 18.4882 5.23598 18.4698C5.3095 18.4204 5.4347 18.4698 5.50425 18.5705C5.57379 18.6713 5.57578 18.8057 5.50425 18.857V18.857Z" fill="#191717"/>
+<path d="M6.14612 19.5207C6.08054 19.5939 5.94741 19.5741 5.83812 19.4753C5.72883 19.3765 5.70299 19.2422 5.76857 19.171C5.83414 19.0999 5.96727 19.1197 6.08054 19.2165C6.1938 19.3133 6.21566 19.4496 6.14612 19.5207V19.5207Z" fill="#191717"/>
+<path d="M7.04617 19.9081C7.01637 20.001 6.88124 20.0425 6.74612 20.003C6.611 19.9635 6.52158 19.8528 6.54741 19.758C6.57325 19.6631 6.71036 19.6197 6.84747 19.6631C6.98457 19.7066 7.07201 19.8113 7.04617 19.9081Z" fill="#191717"/>
+<path d="M8.02783 19.9752C8.02783 20.072 7.91656 20.155 7.77349 20.1569C7.63042 20.1589 7.51318 20.0799 7.51318 19.9831C7.51318 19.8863 7.62445 19.8033 7.76752 19.8013C7.91059 19.7993 8.02783 19.8764 8.02783 19.9752Z" fill="#191717"/>
+<path d="M8.9419 19.8232C8.95978 19.92 8.86042 20.0207 8.71735 20.0445C8.57428 20.0682 8.4491 20.0109 8.43121 19.916C8.41333 19.8212 8.51666 19.7185 8.65576 19.6928C8.79485 19.6671 8.92401 19.7264 8.9419 19.8232Z" fill="#191717"/>
+</g>
+<defs>
+<clipPath id="clip0_131_1011">
+<rect width="24" height="24" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/header/assets/google.svg b/web/app/components/header/assets/google.svg
new file mode 100644
index 00000000000..6bcacfcddc0
--- /dev/null
+++ b/web/app/components/header/assets/google.svg
@@ -0,0 +1,13 @@
+<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_729_2080)">
+<path d="M20.3052 10.2302C20.3052 9.55044 20.2501 8.86699 20.1325 8.19824H10.7002V12.0491H16.1016C15.8775 13.291 15.1573 14.3897 14.1027 15.0878V17.5864H17.3252C19.2176 15.8448 20.3052 13.2726 20.3052 10.2302Z" fill="#4285F4"/>
+<path d="M10.6999 20.0008C13.397 20.0008 15.6714 19.1152 17.3286 17.5867L14.1061 15.088C13.2096 15.698 12.0521 16.0434 10.7036 16.0434C8.09474 16.0434 5.88272 14.2833 5.08904 11.917H1.76367V14.4928C3.46127 17.8696 6.91892 20.0008 10.6999 20.0008Z" fill="#34A853"/>
+<path d="M5.08564 11.9172C4.66676 10.6753 4.66676 9.33044 5.08564 8.08848V5.5127H1.76395C0.345611 8.33834 0.345611 11.6674 1.76395 14.493L5.08564 11.9172Z" fill="#FBBC04"/>
+<path d="M10.6999 3.95805C12.1256 3.936 13.5035 4.47247 14.536 5.45722L17.3911 2.60218C15.5833 0.904587 13.1838 -0.0287217 10.6999 0.000673888C6.91892 0.000673888 3.46126 2.13185 1.76367 5.51234L5.08537 8.08813C5.87537 5.71811 8.09106 3.95805 10.6999 3.95805Z" fill="#EA4335"/>
+</g>
+<defs>
+<clipPath id="clip0_729_2080">
+<rect width="20" height="20" fill="white" transform="translate(0.5)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/header/assets/gpt.svg b/web/app/components/header/assets/gpt.svg
new file mode 100644
index 00000000000..c20df23e00e
--- /dev/null
+++ b/web/app/components/header/assets/gpt.svg
@@ -0,0 +1,4 @@
+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="20" height="20" rx="6" fill="black"/>
+<path d="M16.5965 9.65778C16.7482 9.99618 16.8444 10.3579 16.8838 10.727C16.9218 11.096 16.9028 11.4694 16.824 11.8326C16.7467 12.1958 16.6125 12.5444 16.4258 12.8653C16.3033 13.0797 16.1589 13.281 15.9926 13.4663C15.8278 13.6501 15.644 13.8163 15.4442 13.9622C15.2429 14.1081 15.0284 14.2306 14.8009 14.3312C14.5748 14.4304 14.3385 14.5063 14.0964 14.5559C13.9826 14.9089 13.8134 15.2429 13.5946 15.5434C13.3773 15.8439 13.1133 16.1079 12.8128 16.3252C12.5123 16.544 12.1797 16.7132 11.8267 16.827C11.4737 16.9422 11.1047 16.9991 10.7328 16.9991C10.4862 17.0006 10.2383 16.9743 9.99615 16.9247C9.75547 16.8737 9.51917 16.7963 9.29308 16.6957C9.06699 16.5951 8.85257 16.4696 8.65274 16.3237C8.45437 16.1779 8.27058 16.0101 8.10721 15.8249C7.74255 15.9037 7.36914 15.9226 7.00011 15.8847C6.63107 15.8453 6.26933 15.749 5.92947 15.5973C5.59106 15.4471 5.27745 15.2429 5.00177 14.9935C4.72609 14.744 4.49125 14.4523 4.306 14.1314C4.18202 13.917 4.07991 13.6909 4.00261 13.4561C3.9253 13.2212 3.87425 12.9791 3.84799 12.7326C3.82173 12.4875 3.82319 12.2396 3.84945 11.9931C3.8757 11.748 3.92967 11.5059 4.00698 11.271C3.75901 10.9953 3.5548 10.6817 3.40311 10.3433C3.25287 10.0035 3.15514 9.64319 3.11721 9.27415C3.07783 8.90512 3.09825 8.53171 3.17556 8.16851C3.25287 7.80531 3.38706 7.45669 3.57377 7.13579C3.69629 6.92137 3.8407 6.71862 4.00552 6.53483C4.17035 6.35104 4.3556 6.18476 4.55543 6.0389C4.75526 5.89303 4.97114 5.76905 5.19723 5.66986C5.42478 5.56922 5.66108 5.49482 5.90321 5.44523C6.01698 5.09078 6.18619 4.75821 6.40352 4.45773C6.62232 4.15725 6.88633 3.89324 7.18681 3.67445C7.48729 3.45711 7.81986 3.28791 8.17285 3.17267C8.52584 3.0589 8.89488 3.00056 9.26683 3.00201C9.51334 3.00056 9.76131 3.02535 10.0034 3.0764C10.2456 3.12746 10.4819 3.20331 10.708 3.30395C10.934 3.40606 11.1485 3.53004 11.3483 3.6759C11.5481 3.82323 11.7319 3.98951 11.8953 4.17476C12.2585 4.09745 12.6319 4.07849 13.0009 4.11641C13.37 4.15434 13.7303 4.25207 14.0701 4.40231C14.4085 4.554 14.7221 4.75675 14.9978 5.00618C15.2735 5.25415 15.5083 5.54442 15.6936 5.86678C15.8176 6.07974 15.9197 6.30583 15.997 6.54213C16.0743 6.77697 16.1268 7.0191 16.1516 7.26561C16.1778 7.51212 16.1778 7.76009 16.1501 8.0066C16.1239 8.25311 16.0699 8.49524 15.9926 8.73008C16.242 9.00576 16.4448 9.31791 16.5965 9.65778ZM11.7363 15.8847C12.0543 15.7534 12.3431 15.5594 12.5867 15.3158C12.8303 15.0722 13.0243 14.7834 13.1556 14.464C13.2868 14.146 13.3554 13.8047 13.3554 13.4604V10.2077C13.3544 10.2048 13.3534 10.2014 13.3525 10.1975C13.3515 10.1946 13.35 10.1916 13.3481 10.1887C13.3461 10.1858 13.3437 10.1834 13.3408 10.1814C13.3379 10.1785 13.335 10.1766 13.332 10.1756L12.1549 9.49587V13.4254C12.1549 13.4648 12.1491 13.5057 12.1389 13.5436C12.1287 13.583 12.1141 13.6194 12.0937 13.6544C12.0732 13.6894 12.0499 13.7215 12.0207 13.7493C11.9924 13.7775 11.9605 13.802 11.9259 13.8222L9.13847 15.4311C9.11513 15.4456 9.07575 15.4661 9.05533 15.4777C9.17056 15.5755 9.296 15.6615 9.42728 15.7374C9.56001 15.8132 9.69713 15.8774 9.84007 15.9299C9.98302 15.981 10.1303 16.0204 10.2791 16.0466C10.4294 16.0729 10.5811 16.086 10.7328 16.086C11.077 16.086 11.4183 16.0174 11.7363 15.8847ZM5.09804 13.6763C5.27162 13.9753 5.50063 14.235 5.77339 14.445C6.04762 14.6551 6.3583 14.8082 6.69087 14.8972C7.02344 14.9862 7.3706 15.0095 7.71192 14.9643C8.05324 14.9191 8.38143 14.8082 8.68046 14.6361L11.4985 13.0097L11.5058 13.0024C11.5078 13.0005 11.5092 12.9976 11.5102 12.9937C11.5122 12.9908 11.5136 12.9878 11.5146 12.9849V11.6138L8.11305 13.5815C8.07804 13.6019 8.04157 13.6165 8.00365 13.6282C7.96426 13.6384 7.92488 13.6428 7.88404 13.6428C7.84466 13.6428 7.80527 13.6384 7.76589 13.6282C7.72797 13.6165 7.69004 13.6019 7.65503 13.5815L4.86758 11.9712C4.84278 11.9566 4.80631 11.9347 4.78589 11.9216C4.75964 12.0718 4.74651 12.2235 4.74651 12.3752C4.74651 12.5269 4.7611 12.6786 4.78735 12.8289C4.81361 12.9776 4.85445 13.125 4.9055 13.2679C4.95801 13.4108 5.02219 13.548 5.09804 13.6792V13.6763ZM4.36581 7.5938C4.19369 7.89282 4.08283 8.22248 4.03761 8.5638C3.9924 8.90512 4.01573 9.25082 4.10471 9.58484C4.19369 9.91741 4.34684 10.2281 4.55689 10.5023C4.76693 10.7751 5.02803 11.0041 5.32559 11.1762L8.14222 12.8041C8.14514 12.805 8.14854 12.806 8.15243 12.807H8.16264C8.16653 12.807 8.16993 12.806 8.17285 12.8041C8.17577 12.8031 8.17868 12.8016 8.1816 12.7997L9.3631 12.117L5.96156 10.1537C5.92801 10.1333 5.89592 10.1085 5.86674 10.0808C5.83848 10.0524 5.81397 10.0206 5.79381 9.98597C5.77485 9.95096 5.75881 9.9145 5.74859 9.87511C5.73838 9.83719 5.73255 9.7978 5.73401 9.75696V6.4444C5.59106 6.49691 5.45249 6.56109 5.32121 6.63694C5.18994 6.71425 5.06595 6.80176 4.94926 6.89949C4.83403 6.99722 4.72609 7.10516 4.62836 7.22185C4.53063 7.33708 4.44457 7.46253 4.36872 7.5938H4.36581ZM14.0409 9.84594C14.076 9.86636 14.108 9.8897 14.1372 9.91887C14.1649 9.94659 14.1897 9.97868 14.2101 10.0137C14.2291 10.0487 14.2452 10.0866 14.2554 10.1245C14.2641 10.1639 14.27 10.2033 14.2685 10.2441V13.5567C14.7367 13.3846 15.1451 13.0827 15.4471 12.6859C15.7505 12.2892 15.9328 11.8151 15.9751 11.3192C16.0174 10.8232 15.9182 10.3244 15.6877 9.88241C15.4573 9.44044 15.1058 9.07286 14.674 8.82489L11.8574 7.19705C11.8544 7.19608 11.851 7.19511 11.8472 7.19414H11.8369C11.834 7.19511 11.8306 7.19608 11.8267 7.19705C11.8238 7.19803 11.8209 7.19949 11.818 7.20143L10.6423 7.88116L14.0439 9.84594H14.0409ZM15.2151 8.08099H15.2137V8.08245L15.2151 8.08099ZM15.2137 8.07953C15.2983 7.58943 15.2414 7.08474 15.0489 6.62527C14.8578 6.1658 14.5383 5.77051 14.1299 5.48461C13.7215 5.20018 13.2402 5.03681 12.7428 5.01493C12.2439 4.99451 11.7509 5.11558 11.3191 5.36355L8.5025 6.98993C8.49958 6.99187 8.49715 6.9943 8.49521 6.99722L8.48937 7.00597C8.4884 7.00889 8.48743 7.01229 8.48646 7.01618C8.48548 7.0191 8.485 7.0225 8.485 7.02639V8.38584L11.8865 6.42106C11.9215 6.40064 11.9595 6.38605 11.9974 6.37438C12.0368 6.36417 12.0762 6.3598 12.1155 6.3598C12.1564 6.3598 12.1958 6.36417 12.2352 6.37438C12.2731 6.38605 12.3095 6.40064 12.3446 6.42106L15.132 8.03139C15.1568 8.04598 15.1933 8.0664 15.2137 8.07953ZM7.8432 6.57422C7.8432 6.53483 7.84903 6.49545 7.85924 6.45607C7.86945 6.41814 7.88404 6.38022 7.90446 6.34521C7.92488 6.31166 7.94822 6.27957 7.97739 6.2504C8.00511 6.22268 8.0372 6.19789 8.0722 6.17893L10.8597 4.57005C10.8859 4.554 10.9224 4.53358 10.9428 4.52337C10.5606 4.20393 10.0939 3.99972 9.5994 3.937C9.10492 3.87282 8.60315 3.95159 8.15243 4.16309C7.70025 4.37459 7.31809 4.71154 7.05116 5.13162C6.78423 5.55317 6.64274 6.04036 6.64274 6.53921V9.79197C6.64371 9.79586 6.64468 9.79926 6.64566 9.80218C6.64663 9.8051 6.64809 9.80802 6.65003 9.81093C6.65198 9.81385 6.65441 9.81677 6.65733 9.81968C6.65927 9.82163 6.66219 9.82357 6.66608 9.82552L7.8432 10.5052V6.57422ZM8.48208 10.8728L9.9976 11.748L11.5131 10.8728V9.12391L9.99906 8.24873L8.48354 9.12391L8.48208 10.8728Z" fill="white"/>
+</svg>
diff --git a/web/app/components/header/assets/hugging-face.svg b/web/app/components/header/assets/hugging-face.svg
new file mode 100644
index 00000000000..1f53ec0ac78
--- /dev/null
+++ b/web/app/components/header/assets/hugging-face.svg
@@ -0,0 +1,21 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="24" height="24" rx="6" fill="white"/>
+<path d="M11.9514 17.4737C15.1838 17.4737 17.8041 14.8534 17.8041 11.6211C17.8041 8.38874 15.1838 5.76843 11.9514 5.76843C8.71913 5.76843 6.09882 8.38874 6.09882 11.6211C6.09882 14.8534 8.71913 17.4737 11.9514 17.4737Z" fill="#FFD21E"/>
+<path d="M17.8041 11.621C17.8041 8.38872 15.1838 5.76841 11.9515 5.76841C8.71917 5.76841 6.09886 8.38872 6.09886 11.621C6.09886 14.8534 8.71917 17.4737 11.9515 17.4737C15.1838 17.4737 17.8041 14.8534 17.8041 11.621ZM5.42517 11.621C5.42517 8.01666 8.3471 5.09473 11.9515 5.09473C15.5559 5.09473 18.4778 8.01666 18.4778 11.621C18.4778 15.2254 15.5559 18.1474 11.9515 18.1474C8.3471 18.1474 5.42517 15.2254 5.42517 11.621Z" fill="#FF9D0B"/>
+<path d="M13.853 10.028C14.0676 10.1038 14.1531 10.5451 14.3699 10.4298C14.7805 10.2114 14.9364 9.70155 14.7181 9.29091C14.4997 8.88028 13.9898 8.72439 13.5792 8.94273C13.1685 9.16107 13.0127 9.67097 13.231 10.0816C13.3341 10.2754 13.6611 9.96028 13.853 10.028Z" fill="#3A3B45"/>
+<path d="M9.88553 10.028C9.6709 10.1038 9.58551 10.5451 9.36868 10.4298C8.95804 10.2114 8.80215 9.70155 9.02049 9.29091C9.23883 8.88028 9.74873 8.72439 10.1594 8.94273C10.57 9.16107 10.7259 9.67097 10.5076 10.0816C10.4045 10.2754 10.0774 9.96028 9.88553 10.028Z" fill="#3A3B45"/>
+<path d="M11.9094 14.0697C13.5647 14.0697 14.0989 12.5938 14.0989 11.836C14.0989 11.4421 13.8341 11.5661 13.41 11.776C13.0181 11.97 12.4901 12.2375 11.9094 12.2375C10.7002 12.2375 9.71991 11.0781 9.71991 11.836C9.71991 12.5938 10.2541 14.0697 11.9094 14.0697Z" fill="#3A3B45"/>
+<mask id="mask0_3907_39368" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="9" y="11" width="6" height="4">
+<path d="M11.9094 14.0697C13.5647 14.0697 14.0989 12.5938 14.0989 11.836C14.0989 11.4421 13.8341 11.5661 13.41 11.776C13.0181 11.97 12.4901 12.2375 11.9094 12.2375C10.7002 12.2375 9.71991 11.0781 9.71991 11.836C9.71991 12.5938 10.2541 14.0697 11.9094 14.0697Z" fill="white"/>
+</mask>
+<g mask="url(#mask0_3907_39368)">
+<path d="M11.9515 15.7894C12.7582 15.7894 13.4122 15.1354 13.4122 14.3287C13.4122 13.7004 13.0154 13.1647 12.4588 12.9585C12.4383 12.9509 12.4176 12.9438 12.3967 12.9371C12.2563 12.8922 12.1068 13.3747 11.9515 13.3747C11.8064 13.3747 11.6663 12.8892 11.534 12.9285C10.9307 13.1081 10.4908 13.6671 10.4908 14.3287C10.4908 15.1354 11.1448 15.7894 11.9515 15.7894Z" fill="#F94040"/>
+</g>
+<path d="M15.9094 10.8211C16.2117 10.8211 16.4567 10.576 16.4567 10.2737C16.4567 9.97139 16.2117 9.72632 15.9094 9.72632C15.6071 9.72632 15.362 9.97139 15.362 10.2737C15.362 10.576 15.6071 10.8211 15.9094 10.8211Z" fill="#FF9D0B"/>
+<path d="M8.07776 10.8211C8.38006 10.8211 8.62513 10.576 8.62513 10.2737C8.62513 9.97139 8.38006 9.72632 8.07776 9.72632C7.77545 9.72632 7.5304 9.97139 7.5304 10.2737C7.5304 10.576 7.77545 10.8211 8.07776 10.8211Z" fill="#FF9D0B"/>
+<path d="M6.9514 12.6737C6.67872 12.6737 6.43502 12.7857 6.26508 12.9888C6.15999 13.1146 6.05018 13.3174 6.04125 13.6211C5.92689 13.5882 5.81691 13.5699 5.71418 13.5699C5.45312 13.5699 5.21733 13.6699 5.0506 13.8516C4.83636 14.0849 4.74121 14.3716 4.78264 14.6584C4.80234 14.795 4.84799 14.9174 4.9162 15.0308C4.77236 15.1471 4.66643 15.3092 4.61523 15.504C4.57514 15.6568 4.53405 15.9749 4.74862 16.3027C4.73498 16.3241 4.72218 16.3463 4.71022 16.369C4.58121 16.6139 4.57295 16.8906 4.68681 17.1483C4.85944 17.5389 5.28841 17.8466 6.12142 18.1769C6.63965 18.3823 7.11375 18.5137 7.11796 18.5149C7.8031 18.6926 8.42272 18.7828 8.95914 18.7828C9.94508 18.7828 10.6509 18.4809 11.0572 17.8853C11.711 16.9263 11.6175 16.0492 10.7715 15.2037C10.3033 14.7359 9.99207 14.046 9.92723 13.8946C9.79653 13.4463 9.45093 12.9479 8.87645 12.9479C8.82811 12.9479 8.7791 12.9518 8.73093 12.9593C8.47931 12.9989 8.25935 13.1438 8.10222 13.3617C7.93262 13.1508 7.7679 12.9831 7.61885 12.8884C7.39418 12.746 7.16967 12.6737 6.9514 12.6737ZM6.9514 13.3474C7.03729 13.3474 7.14222 13.3839 7.25792 13.4574C7.61716 13.6852 8.31039 14.8768 8.5642 15.3403C8.64925 15.4956 8.7946 15.5613 8.92546 15.5613C9.18516 15.5613 9.38794 15.3031 8.94921 14.975C8.2895 14.4814 8.52091 13.6745 8.83586 13.6248C8.84967 13.6226 8.86331 13.6216 8.87645 13.6216C9.16277 13.6216 9.28908 14.1151 9.28908 14.1151C9.28908 14.1151 9.65927 15.0447 10.2952 15.6802C10.9312 16.3158 10.964 16.826 10.5005 17.5057C10.1844 17.9692 9.57927 18.1092 8.95914 18.1092C8.31594 18.1092 7.65658 17.9586 7.28706 17.8628C7.26887 17.858 5.02163 17.2233 5.30626 16.683C5.35409 16.5922 5.43291 16.5558 5.53211 16.5558C5.93295 16.5558 6.66205 17.1524 6.97548 17.1524C7.04554 17.1524 7.09489 17.1225 7.1151 17.0498C7.24866 16.5706 5.08445 16.3692 5.26685 15.6751C5.29902 15.5524 5.38626 15.5025 5.50887 15.5027C6.03855 15.5027 7.22693 16.4342 7.47603 16.4342C7.49506 16.4342 7.5087 16.4287 7.51611 16.4169C7.64091 16.2154 7.57253 16.0748 6.69287 15.5424C5.81321 15.0099 5.19578 14.6895 5.54693 14.3072C5.58735 14.2631 5.64462 14.2436 5.71418 14.2436C6.24824 14.2437 7.51005 15.392 7.51005 15.392C7.51005 15.392 7.8506 15.7462 8.05658 15.7462C8.1039 15.7462 8.14415 15.7275 8.17144 15.6814C8.31746 15.4351 6.81514 14.2966 6.73043 13.8269C6.673 13.5086 6.77068 13.3474 6.9514 13.3474Z" fill="#FF9D0B"/>
+<path d="M10.5005 17.5057C10.964 16.8259 10.9312 16.3158 10.2952 15.6802C9.65925 15.0447 9.28906 14.115 9.28906 14.115C9.28906 14.115 9.15079 13.5751 8.83584 13.6247C8.5209 13.6744 8.28965 14.4813 8.94936 14.975C9.60907 15.4685 8.81799 15.8038 8.56418 15.3403C8.31037 14.8768 7.61732 13.6852 7.25791 13.4573C6.89866 13.2295 6.6457 13.3571 6.73041 13.8269C6.81513 14.2966 8.31761 15.4351 8.17142 15.6815C8.02523 15.9277 7.51003 15.392 7.51003 15.392C7.51003 15.392 5.89791 13.9249 5.54691 14.3072C5.19592 14.6895 5.81319 15.0098 6.69285 15.5424C7.57269 16.0748 7.6409 16.2154 7.5161 16.4168C7.39113 16.6183 5.44922 14.981 5.26682 15.6751C5.08459 16.3692 7.24864 16.5706 7.11509 17.0498C6.98153 17.5291 5.5907 16.1428 5.30624 16.6829C5.0216 17.2232 7.26885 17.858 7.28704 17.8627C8.01294 18.051 9.85648 18.45 10.5005 17.5057Z" fill="#FFD21E"/>
+<path d="M17.0358 12.6737C17.3084 12.6737 17.5521 12.7857 17.7221 12.9888C17.8272 13.1146 17.937 13.3174 17.9459 13.6211C18.0603 13.5882 18.1702 13.5699 18.273 13.5699C18.534 13.5699 18.7698 13.6699 18.9366 13.8516C19.1508 14.0849 19.2459 14.3716 19.2045 14.6584C19.1848 14.795 19.1392 14.9174 19.071 15.0308C19.2148 15.1471 19.3207 15.3092 19.3719 15.504C19.412 15.6568 19.4531 15.9749 19.2385 16.3027C19.2522 16.3241 19.265 16.3463 19.2769 16.369C19.4059 16.6139 19.4142 16.8906 19.3003 17.1483C19.1277 17.5389 18.6987 17.8466 17.8657 18.1769C17.3475 18.3823 16.8734 18.5137 16.8692 18.5149C16.1841 18.6926 15.5644 18.7828 15.028 18.7828C14.0421 18.7828 13.3362 18.4809 12.93 17.8853C12.2762 16.9263 12.3697 16.0492 13.2156 15.2037C13.6838 14.7359 13.9951 14.046 14.0599 13.8946C14.1906 13.4463 14.5362 12.9479 15.1107 12.9479C15.159 12.9479 15.2081 12.9518 15.2562 12.9593C15.5078 12.9989 15.7278 13.1438 15.8849 13.3617C16.0545 13.1508 16.2193 12.9831 16.3683 12.8884C16.593 12.746 16.8175 12.6737 17.0358 12.6737ZM17.0358 13.3474C16.9499 13.3474 16.8449 13.3839 16.7292 13.4574C16.37 13.6852 15.6768 14.8768 15.423 15.3403C15.3379 15.4956 15.1926 15.5613 15.0617 15.5613C14.802 15.5613 14.5992 15.3031 15.0379 14.975C15.6977 14.4814 15.4662 13.6745 15.1513 13.6248C15.1375 13.6226 15.1238 13.6216 15.1107 13.6216C14.8244 13.6216 14.6981 14.1151 14.6981 14.1151C14.6981 14.1151 14.3279 15.0447 13.6919 15.6802C13.056 16.3158 13.0231 16.826 13.4866 17.5057C13.8027 17.9692 14.4079 18.1092 15.028 18.1092C15.6712 18.1092 16.3306 17.9586 16.7001 17.8628C16.7183 17.858 18.9655 17.2233 18.6809 16.683C18.6331 16.5922 18.5542 16.5558 18.455 16.5558C18.0542 16.5558 17.3251 17.1524 17.0117 17.1524C16.9416 17.1524 16.8923 17.1225 16.8721 17.0498C16.7385 16.5706 18.9027 16.3692 18.7203 15.6751C18.6881 15.5524 18.6009 15.5025 18.4783 15.5027C17.9486 15.5027 16.7602 16.4342 16.5111 16.4342C16.4921 16.4342 16.4785 16.4287 16.471 16.4169C16.3462 16.2154 16.4146 16.0748 17.2943 15.5424C18.1739 15.0099 18.7914 14.6895 18.4402 14.3072C18.3998 14.2631 18.3425 14.2436 18.273 14.2436C17.7389 14.2437 16.4771 15.392 16.4771 15.392C16.4771 15.392 16.1366 15.7462 15.9306 15.7462C15.8833 15.7462 15.843 15.7275 15.8157 15.6814C15.6697 15.4351 17.172 14.2966 17.2567 13.8269C17.3142 13.5086 17.2165 13.3474 17.0358 13.3474Z" fill="#FF9D0B"/>
+<path d="M13.4867 17.5057C13.0232 16.8259 13.056 16.3158 13.692 15.6802C14.3279 15.0447 14.6981 14.115 14.6981 14.115C14.6981 14.115 14.8364 13.5751 15.1513 13.6247C15.4663 13.6744 15.6975 14.4813 15.0378 14.975C14.3781 15.4685 15.1692 15.8038 15.423 15.3403C15.6768 14.8768 16.3699 13.6852 16.7293 13.4573C17.0885 13.2295 17.3415 13.3571 17.2568 13.8269C17.1721 14.2966 15.6696 15.4351 15.8158 15.6815C15.962 15.9277 16.4772 15.392 16.4772 15.392C16.4772 15.392 18.0893 13.9249 18.4403 14.3072C18.7913 14.6895 18.174 15.0098 17.2943 15.5424C16.4145 16.0748 16.3463 16.2154 16.4711 16.4168C16.5961 16.6183 18.538 14.981 18.7204 15.6751C18.9026 16.3692 16.7385 16.5706 16.8721 17.0498C17.0057 17.5291 18.3965 16.1428 18.6809 16.6829C18.9656 17.2232 16.7183 17.858 16.7001 17.8627C15.9743 18.051 14.1307 18.45 13.4867 17.5057Z" fill="#FFD21E"/>
+<rect x="0.25" y="0.25" width="23.5" height="23.5" rx="5.75" stroke="black" stroke-opacity="0.05" stroke-width="0.5"/>
+</svg>
diff --git a/web/app/components/header/assets/logo-icon.png b/web/app/components/header/assets/logo-icon.png
new file mode 100644
index 00000000000..76db2319cdd
Binary files /dev/null and b/web/app/components/header/assets/logo-icon.png differ
diff --git a/web/app/components/header/assets/logo-text.svg b/web/app/components/header/assets/logo-text.svg
new file mode 100644
index 00000000000..69d5a23be40
--- /dev/null
+++ b/web/app/components/header/assets/logo-text.svg
@@ -0,0 +1,6 @@
+<svg width="50" height="26" viewBox="0 0 50 26" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.61796 2.064C8.37796 2.064 9.92196 2.408 11.25 3.096C12.594 3.784 13.626 4.768 14.346 6.048C15.082 7.312 15.45 8.784 15.45 10.464C15.45 12.144 15.082 13.616 14.346 14.88C13.626 16.128 12.594 17.096 11.25 17.784C9.92196 18.472 8.37796 18.816 6.61796 18.816H0.761963V2.064H6.61796ZM6.49796 15.96C8.25796 15.96 9.61796 15.48 10.578 14.52C11.538 13.56 12.018 12.208 12.018 10.464C12.018 8.72 11.538 7.36 10.578 6.384C9.61796 5.392 8.25796 4.896 6.49796 4.896H4.12196V15.96H6.49796Z" fill="#1D2939"/>
+<path d="M20.8691 3.936C20.2771 3.936 19.7811 3.752 19.3811 3.384C18.9971 3 18.8051 2.528 18.8051 1.968C18.8051 1.408 18.9971 0.944 19.3811 0.576C19.7811 0.192 20.2771 0 20.8691 0C21.4611 0 21.9491 0.192 22.3331 0.576C22.7331 0.944 22.9331 1.408 22.9331 1.968C22.9331 2.528 22.7331 3 22.3331 3.384C21.9491 3.752 21.4611 3.936 20.8691 3.936ZM22.5251 5.52V18.816H19.1651V5.52H22.5251Z" fill="#1D2939"/>
+<path d="M33.1408 8.28H30.8128V18.816H27.4048V8.28H25.8928V5.52H27.4048V4.848C27.4048 3.216 27.8688 2.016 28.7968 1.248C29.7248 0.48 31.1248 0.12 32.9968 0.168001V3C32.1808 2.984 31.6128 3.12 31.2928 3.408C30.9728 3.696 30.8128 4.216 30.8128 4.968V5.52H33.1408V8.28Z" fill="#1D2939"/>
+<path d="M49.2382 5.52L41.0062 25.104H37.4302L40.3102 18.48L34.9822 5.52H38.7502L42.1822 14.808L45.6622 5.52H49.2382Z" fill="#1D2939"/>
+</svg>
diff --git a/web/app/components/header/assets/logo.png b/web/app/components/header/assets/logo.png
new file mode 100644
index 00000000000..ad98291826b
Binary files /dev/null and b/web/app/components/header/assets/logo.png differ
diff --git a/web/app/components/header/assets/salesforce.svg b/web/app/components/header/assets/salesforce.svg
new file mode 100644
index 00000000000..1deebd9f03b
--- /dev/null
+++ b/web/app/components/header/assets/salesforce.svg
@@ -0,0 +1,12 @@
+<svg width="24" height="17" viewBox="0 0 24 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_660_2015)">
+<path d="M9.98736 1.91633C10.7614 1.10782 11.839 0.60636 13.0308 0.60636C14.6151 0.60636 15.9973 1.49199 16.7334 2.80672C17.373 2.52021 18.0811 2.36082 18.826 2.36082C21.6834 2.36082 24 4.70345 24 7.59305C24 10.483 21.6834 12.8256 18.826 12.8256C18.4837 12.8258 18.1423 12.7917 17.8068 12.7238C17.1587 13.8829 15.9234 14.6661 14.5057 14.6661C13.9121 14.6661 13.3508 14.5287 12.851 14.2843C12.1939 15.8338 10.6629 16.9203 8.87863 16.9203C7.02052 16.9203 5.43692 15.7416 4.82907 14.0886C4.56344 14.1451 4.28822 14.1746 4.00581 14.1746C1.79351 14.1746 0 12.3581 0 10.117C0 8.61511 0.805814 7.30378 2.00308 6.6022C1.75659 6.03362 1.61948 5.40606 1.61948 4.74627C1.61948 2.1689 3.70667 0.0795898 6.28103 0.0795898C7.79248 0.0795898 9.13574 0.800021 9.98736 1.91633Z" fill="#00A1E0"/>
+<path d="M3.47612 8.81302C3.46109 8.85245 3.4816 8.86068 3.48638 8.86752C3.5315 8.90042 3.57734 8.9241 3.62349 8.95047C3.86827 9.08069 4.0994 9.11872 4.34111 9.11872C4.83341 9.11872 5.13904 8.8562 5.13904 8.4336V8.42539C5.13904 8.03464 4.79411 7.89276 4.47033 7.79028L4.42829 7.77658C4.18418 7.69705 3.97359 7.62854 3.97359 7.46744V7.45889C3.97359 7.3211 4.09666 7.21963 4.28744 7.21963C4.4994 7.21963 4.75103 7.29025 4.91307 7.38003C4.91307 7.38003 4.96059 7.41089 4.97803 7.36462C4.9876 7.33993 5.06966 7.11853 5.07821 7.09454C5.08744 7.06848 5.07103 7.04929 5.05429 7.039C4.86933 6.92624 4.61359 6.84912 4.34899 6.84912L4.29976 6.84946C3.84917 6.84946 3.53465 7.12228 3.53465 7.51334V7.52158C3.53465 7.93388 3.88165 8.06754 4.20679 8.16077L4.25909 8.17688C4.49602 8.24988 4.70012 8.3126 4.70012 8.47986V8.4881C4.70012 8.64096 4.56749 8.75474 4.35346 8.75474C4.27038 8.75474 4.00542 8.75303 3.71927 8.5717C3.68473 8.55147 3.66457 8.53675 3.6379 8.52064C3.6239 8.51173 3.58868 8.49629 3.5733 8.54292L3.47612 8.81302ZM10.6833 8.81302C10.6682 8.85245 10.6888 8.86068 10.6935 8.86752C10.7387 8.90042 10.7845 8.9241 10.8306 8.95047C11.0754 9.08069 11.3066 9.11872 11.5482 9.11872C12.0405 9.11872 12.3462 8.8562 12.3462 8.4336V8.42539C12.3462 8.03464 12.0012 7.89276 11.6775 7.79028L11.6354 7.77658C11.3913 7.69705 11.1807 7.62854 11.1807 7.46744V7.45889C11.1807 7.3211 11.3038 7.21963 11.4946 7.21963C11.7065 7.21963 11.9581 7.29025 12.1202 7.38003C12.1202 7.38003 12.1677 7.41089 12.1851 7.36462C12.1947 7.33993 12.2768 7.11853 12.2853 7.09454C12.2946 7.06848 12.2781 7.04929 12.2614 7.039C12.0764 6.92624 11.8207 6.84912 11.5561 6.84912L11.5069 6.84946C11.0563 6.84946 10.7417 7.12228 10.7417 7.51334V7.52158C10.7417 7.93388 11.0887 8.06754 11.4139 8.16077L11.4662 8.17688C11.7031 8.24988 11.9076 8.3126 11.9076 8.47986V8.4881C11.9076 8.64096 11.7746 8.75474 11.5605 8.75474C11.4775 8.75474 11.2125 8.75303 10.9264 8.5717C10.8918 8.55147 10.8713 8.53743 10.8454 8.52064C10.8365 8.51481 10.7948 8.4987 10.7804 8.54292L10.6833 8.81302ZM15.6034 7.98525C15.6034 8.22414 15.559 8.41228 15.4715 8.54528C15.385 8.6769 15.254 8.74099 15.0715 8.74099C14.8886 8.74099 14.7583 8.67724 14.6732 8.54528C14.587 8.41265 14.5433 8.22414 14.5433 7.98525C14.5433 7.74672 14.587 7.55888 14.6732 7.42726C14.7583 7.29704 14.8886 7.23363 15.0715 7.23363C15.254 7.23363 15.385 7.29704 15.4718 7.42726C15.559 7.55886 15.6034 7.74669 15.6034 7.98525ZM16.0144 7.54243C15.974 7.40566 15.9111 7.28502 15.8274 7.18461C15.7436 7.08385 15.6376 7.00297 15.5118 6.94401C15.3863 6.88542 15.238 6.8556 15.0715 6.8556C14.9046 6.8556 14.7563 6.88542 14.6308 6.94401C14.505 7.00297 14.399 7.08387 14.3149 7.18461C14.2315 7.28538 14.1686 7.40602 14.1279 7.54243C14.0879 7.67849 14.0677 7.82723 14.0677 7.98525C14.0677 8.14326 14.0879 8.29235 14.1279 8.42806C14.1686 8.56447 14.2312 8.68513 14.3153 8.78588C14.399 8.88665 14.5053 8.96718 14.6308 9.02441C14.7566 9.08166 14.9046 9.11077 15.0715 9.11077C15.238 9.11077 15.386 9.08166 15.5118 9.02441C15.6373 8.96718 15.7436 8.88662 15.8274 8.78588C15.9112 8.68545 15.974 8.56481 16.0144 8.42806C16.0548 8.29201 16.0749 8.1429 16.0749 7.98525C16.0749 7.82759 16.0547 7.67849 16.0144 7.54243ZM19.389 8.67719C19.3753 8.63709 19.3367 8.65216 19.3367 8.65216C19.2768 8.67514 19.2132 8.69638 19.1456 8.707C19.0768 8.7176 19.0013 8.72312 18.9202 8.72312C18.7213 8.72312 18.5633 8.66382 18.4502 8.5466C18.3367 8.42938 18.2731 8.23987 18.2737 7.98349C18.2744 7.75009 18.3305 7.57459 18.4314 7.44094C18.5315 7.30797 18.684 7.23974 18.8874 7.23974C19.057 7.23974 19.1862 7.25928 19.3216 7.30212C19.3216 7.30212 19.3541 7.31616 19.3695 7.27368C19.4053 7.17358 19.432 7.10196 19.4703 6.99194C19.4813 6.96075 19.4546 6.94738 19.445 6.9436C19.3917 6.9227 19.2659 6.88879 19.1708 6.87439C19.0819 6.86068 18.978 6.85348 18.8625 6.85348C18.6898 6.85348 18.5359 6.88296 18.4043 6.94192C18.273 7.00052 18.1616 7.08139 18.0734 7.18218C17.9852 7.28295 17.9182 7.40356 17.8734 7.53998C17.829 7.67603 17.8064 7.82547 17.8064 7.98349C17.8064 8.3252 17.8984 8.60142 18.0799 8.80365C18.2618 9.00656 18.535 9.10972 18.8912 9.10972C19.1018 9.10972 19.3179 9.06689 19.4731 9.00553C19.4731 9.00553 19.5028 8.99112 19.4898 8.95654L19.389 8.67719ZM20.108 7.7564C20.1275 7.62377 20.1641 7.51339 20.2205 7.42738C20.3056 7.2968 20.4355 7.22517 20.6181 7.22517C20.8007 7.22517 20.9213 7.29714 21.0078 7.42738C21.0653 7.51339 21.0902 7.62858 21.1001 7.7564H20.108ZM21.4916 7.46471C21.4567 7.33276 21.3702 7.19943 21.3135 7.13842C21.2239 7.04177 21.1364 6.97426 21.0495 6.93655C20.936 6.88787 20.7999 6.85567 20.6509 6.85567C20.4772 6.85567 20.3196 6.88481 20.1918 6.94512C20.0636 7.00545 19.9559 7.08772 19.8714 7.1902C19.7869 7.29232 19.7234 7.41399 19.683 7.55212C19.6423 7.68957 19.6218 7.83934 19.6218 7.99731C19.6218 8.15808 19.643 8.30785 19.6851 8.44253C19.7275 8.57827 19.7952 8.69788 19.8868 8.79691C19.9781 8.89667 20.0957 8.97482 20.2365 9.02927C20.3764 9.08344 20.5463 9.11155 20.7415 9.11118C21.1432 9.10981 21.3548 9.02003 21.442 8.97169C21.4574 8.96314 21.4721 8.94806 21.4536 8.90488L21.3627 8.64951C21.349 8.61149 21.3104 8.62553 21.3104 8.62553C21.2109 8.66254 21.0694 8.72904 20.7394 8.72837C20.5237 8.72803 20.3637 8.66428 20.2635 8.56452C20.1606 8.4624 20.1104 8.31226 20.1015 8.10047L21.4926 8.10184C21.4926 8.10184 21.5291 8.10116 21.5329 8.0655C21.5343 8.05047 21.5808 7.77901 21.4916 7.46471ZM8.9672 7.7564C8.98702 7.62377 9.02327 7.51339 9.07968 7.42738C9.1648 7.2968 9.29472 7.22517 9.47728 7.22517C9.65984 7.22517 9.78053 7.29714 9.86735 7.42738C9.92444 7.51339 9.9494 7.62858 9.95932 7.7564H8.9672ZM10.3504 7.46471C10.3156 7.33276 10.2294 7.19943 10.1727 7.13842C10.0831 7.04177 9.99557 6.97426 9.90875 6.93655C9.79524 6.88787 9.65919 6.85567 9.51012 6.85567C9.33678 6.85567 9.17883 6.88481 9.05097 6.94512C8.92278 7.00545 8.81508 7.08772 8.73063 7.1902C8.64619 7.29232 8.5826 7.41399 8.54226 7.55212C8.50193 7.68957 8.48107 7.83934 8.48107 7.99731C8.48107 8.15808 8.50226 8.30785 8.54433 8.44253C8.58673 8.57827 8.65443 8.69788 8.74603 8.79691C8.83733 8.89667 8.95492 8.97482 9.09578 9.02927C9.23562 9.08344 9.40552 9.11155 9.60074 9.11118C10.0024 9.10981 10.2141 9.02003 10.3013 8.97169C10.3167 8.96314 10.3313 8.94806 10.3129 8.90488L10.2223 8.64951C10.2083 8.61149 10.1696 8.62553 10.1696 8.62553C10.0702 8.66254 9.92895 8.72904 9.59836 8.72837C9.38298 8.72803 9.22298 8.66428 9.1228 8.56452C9.01988 8.4624 8.96965 8.31226 8.96074 8.10047L10.3518 8.10184C10.3518 8.10184 10.3884 8.10116 10.3922 8.0655C10.3935 8.05047 10.44 7.77901 10.3504 7.46471ZM5.96033 8.66955C5.90596 8.62601 5.89844 8.61505 5.87999 8.58694C5.85263 8.5441 5.83862 8.48309 5.83862 8.40564C5.83862 8.28293 5.87896 8.19485 5.96273 8.13556C5.96172 8.13592 6.08239 8.03103 6.36614 8.03479C6.56545 8.03753 6.74356 8.06701 6.74356 8.06701V8.70108H6.7439C6.7439 8.70108 6.56715 8.73911 6.36818 8.7511C6.08511 8.76825 5.9593 8.66922 5.96033 8.66955ZM6.51382 7.68966C6.45741 7.68554 6.38423 7.68313 6.29671 7.68313C6.17741 7.68313 6.06219 7.69821 5.95415 7.72735C5.84545 7.75647 5.74767 7.80209 5.66356 7.86237C5.57958 7.92246 5.51056 8.00116 5.46185 8.09235C5.41263 8.18421 5.38767 8.29251 5.38767 8.41385C5.38767 8.53723 5.40886 8.6445 5.45126 8.73227C5.49366 8.82034 5.55485 8.89368 5.63278 8.95025C5.71005 9.0068 5.80545 9.04825 5.9162 9.07328C6.02527 9.0983 6.14901 9.11097 6.28441 9.11097C6.42697 9.11097 6.56919 9.09934 6.70697 9.07566C6.84338 9.05235 7.0109 9.01841 7.05739 9.00782C7.08998 8.99994 7.12247 8.9916 7.15483 8.98279C7.18937 8.97424 7.18663 8.9372 7.18663 8.9372L7.18594 7.66189C7.18594 7.3822 7.11142 7.17484 6.96475 7.04632C6.81875 6.91815 6.60372 6.85334 6.32578 6.85334C6.22149 6.85334 6.05364 6.86776 5.95312 6.88797C5.95312 6.88797 5.64919 6.94693 5.52405 7.04495C5.52405 7.04495 5.49671 7.0621 5.51175 7.10049L5.61023 7.36578C5.62253 7.40005 5.6557 7.38839 5.6557 7.38839C5.6557 7.38839 5.6663 7.38427 5.67862 7.37707C5.94632 7.23107 6.28477 7.23553 6.28477 7.23553C6.43521 7.23553 6.55077 7.26568 6.6287 7.32565C6.70459 7.38391 6.74322 7.47199 6.74322 7.65775V7.71671C6.62356 7.69958 6.51382 7.68966 6.51382 7.68966ZM17.7337 6.97108C17.7443 6.93953 17.7221 6.92446 17.7129 6.92104C17.6893 6.91179 17.571 6.88677 17.4797 6.88094C17.305 6.87032 17.2079 6.89979 17.1211 6.93886C17.0349 6.97792 16.9392 7.04098 16.8859 7.11263V6.94298C16.8859 6.91933 16.8691 6.90047 16.8459 6.90047H16.4893C16.466 6.90047 16.4493 6.9193 16.4493 6.94298V9.02304C16.4493 9.04635 16.4684 9.06555 16.4917 9.06555H16.8571C16.8683 9.06548 16.879 9.06097 16.8869 9.053C16.8948 9.04503 16.8992 9.03426 16.8992 9.02304V7.98387C16.8992 7.84438 16.9146 7.70524 16.9454 7.61784C16.9754 7.53145 17.0165 7.46223 17.0671 7.41252C17.118 7.36318 17.1758 7.32857 17.239 7.30903C17.3036 7.28914 17.3751 7.28264 17.4257 7.28264C17.4985 7.28264 17.5785 7.30147 17.5785 7.30147C17.6052 7.30455 17.6202 7.2881 17.6291 7.26378C17.653 7.20003 17.7207 7.00911 17.7337 6.97108Z" fill="white"/>
+<path d="M14.3032 6.00677C14.2588 5.99307 14.2184 5.9838 14.1658 5.97387C14.1124 5.96429 14.0489 5.95947 13.9767 5.95947C13.7251 5.95947 13.5268 6.03076 13.3877 6.17127C13.2492 6.31113 13.1552 6.52396 13.108 6.80399L13.0909 6.89823H12.775C12.775 6.89823 12.7367 6.89685 12.7285 6.93869L12.6769 7.22898C12.6731 7.25641 12.6851 7.27387 12.722 7.27387H13.0294L12.7176 9.01909C12.6933 9.15962 12.6652 9.27513 12.6341 9.36284C12.6037 9.44923 12.574 9.51399 12.537 9.56129C12.5015 9.60655 12.468 9.64012 12.4098 9.65965C12.362 9.67577 12.3066 9.6833 12.2461 9.6833C12.2126 9.6833 12.1678 9.67779 12.1346 9.67095C12.1018 9.66442 12.0844 9.65725 12.0594 9.6466C12.0594 9.6466 12.0235 9.63292 12.0092 9.6689C11.9979 9.69872 11.9158 9.92456 11.9059 9.95235C11.8964 9.98009 11.91 10.0017 11.9274 10.0082C11.9685 10.0226 11.9989 10.0322 12.0546 10.0456C12.1319 10.0637 12.1972 10.0648 12.2584 10.0648C12.3862 10.0648 12.5032 10.0466 12.5999 10.0116C12.697 9.97634 12.7818 9.91497 12.857 9.83205C12.938 9.74224 12.989 9.64833 13.0375 9.51982C13.0857 9.39299 13.1271 9.23534 13.1599 9.05165L13.4734 7.27387H13.9315C13.9315 7.27387 13.9702 7.27524 13.9781 7.23309L14.03 6.94314C14.0334 6.9154 14.0218 6.89825 13.9845 6.89825H13.5397C13.5421 6.88833 13.5623 6.73132 13.6133 6.58364C13.6351 6.52092 13.6761 6.46984 13.7107 6.43487C13.7449 6.4006 13.7842 6.37627 13.8273 6.36221C13.8714 6.34781 13.9217 6.34097 13.9767 6.34097C14.0184 6.34097 14.0598 6.34576 14.0909 6.35226C14.1339 6.36153 14.1507 6.36633 14.162 6.36977C14.2075 6.38348 14.2136 6.37011 14.2225 6.34819L14.3289 6.0555C14.3398 6.0239 14.3128 6.01053 14.3032 6.00677ZM8.08869 9.02287C8.08869 9.04618 8.07194 9.06504 8.04869 9.06504H7.6798C7.65655 9.06504 7.64014 9.04618 7.64014 9.02287V6.04654C7.64014 6.02325 7.65655 6.00439 7.6798 6.00439H8.04869C8.07194 6.00439 8.08869 6.02325 8.08869 6.04654V9.02287Z" fill="white"/>
+</g>
+<defs>
+<clipPath id="clip0_660_2015">
+<rect width="24" height="16.8421" fill="white" transform="translate(0 0.0791016)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/header/assets/twitter.svg b/web/app/components/header/assets/twitter.svg
new file mode 100644
index 00000000000..3cdbcd0e92f
--- /dev/null
+++ b/web/app/components/header/assets/twitter.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.03168 15.0003C11.0694 15.0003 14.3718 9.9981 14.3718 5.66018C14.3718 5.5181 14.3718 5.37666 14.3622 5.23586C15.0047 4.77117 15.5593 4.19579 16 3.53666C15.4009 3.80227 14.7654 3.97637 14.1146 4.05314C14.7999 3.64294 15.3128 2.99767 15.5578 2.23746C14.9134 2.61987 14.2084 2.88935 13.4733 3.03426C12.9783 2.50798 12.3237 2.15949 11.6108 2.04272C10.8978 1.92595 10.1663 2.04741 9.52931 2.3883C8.89234 2.72919 8.38548 3.27051 8.08716 3.9285C7.78884 4.58648 7.71569 5.32444 7.87904 6.02818C6.57393 5.96272 5.29717 5.62354 4.13164 5.03267C2.9661 4.4418 1.93784 3.61244 1.1136 2.59842C0.693819 3.32109 0.565248 4.17658 0.754066 4.99071C0.942885 5.80484 1.43489 6.51639 2.12992 6.9805C1.60749 6.9652 1.09643 6.82426 0.64 6.56962V6.61122C0.640207 7.36912 0.902567 8.10362 1.38258 8.69014C1.86259 9.27665 2.53071 9.67907 3.2736 9.82914C2.79032 9.96097 2.28325 9.98024 1.79136 9.88546C2.00121 10.5377 2.40962 11.108 2.95949 11.5168C3.50937 11.9255 4.17322 12.1522 4.85824 12.1651C4.17763 12.7001 3.39821 13.0957 2.56458 13.3291C1.73096 13.5626 0.859476 13.6294 0 13.5258C1.50122 14.4891 3.24795 15.0001 5.03168 14.9978" fill="#1DA1F2"/>
+</svg>
diff --git a/web/app/components/header/index.module.css b/web/app/components/header/index.module.css
new file mode 100644
index 00000000000..1c065608cc6
--- /dev/null
+++ b/web/app/components/header/index.module.css
@@ -0,0 +1,36 @@
+.header-DEVELOPMENT {
+ background: linear-gradient(180deg, rgba(253, 176, 34, 0.08) 0%, rgba(253, 176, 34, 0) 100%);
+ border-top: 4px solid #FDB022;
+}
+
+.header-TESTING {
+ background: linear-gradient(180deg, rgba(6, 174, 212, 0.08) 0%, rgba(6, 174, 212, 0) 100%);
+ border-top: 4px solid #06AED4;
+}
+
+.logo {
+ width: 96px;
+ height: 40px;
+ background: url(~@/app/components/share/chat/welcome/icons/logo.png) center center no-repeat;
+ background-size: contain;
+}
+
+.github-icon {
+ width: 16px;
+ height: 16px;
+ background: url(./assets/github.svg) center center no-repeat;
+}
+
+.alpha {
+ width: 12px;
+ height: 12px;
+ background: url(./assets/alpha.svg) center center no-repeat;
+}
+
+.beaker-icon {
+ width: 12px;
+ height: 12px;
+ margin-right: 4px;
+ background: url(./assets/beaker.svg) center center no-repeat;
+ background-size: contain;
+}
\ No newline at end of file
diff --git a/web/app/components/header/index.tsx b/web/app/components/header/index.tsx
new file mode 100644
index 00000000000..f188eaf1caf
--- /dev/null
+++ b/web/app/components/header/index.tsx
@@ -0,0 +1,139 @@
+import type { FC } from 'react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSelectedLayoutSegment, useRouter } from 'next/navigation'
+import classNames from 'classnames'
+import { CircleStackIcon, PuzzlePieceIcon } from '@heroicons/react/24/outline'
+import { CommandLineIcon, Squares2X2Icon } from '@heroicons/react/24/solid'
+import Link from 'next/link'
+import AccountDropdown from './account-dropdown'
+import Nav from './nav'
+import s from './index.module.css'
+import type { AppDetailResponse } from '@/models/app'
+import type { LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
+import NewAppDialog from '@/app/(commonLayout)/apps/NewAppDialog'
+import { WorkspaceProvider } from '@/context/workspace-context'
+import { useDatasetsContext } from '@/context/datasets-context'
+
+export type IHeaderProps = {
+ appItems: AppDetailResponse[]
+ curApp: AppDetailResponse
+ userProfile: UserProfileResponse
+ onLogout: () => void
+ langeniusVersionInfo: LangGeniusVersionResponse
+ isBordered: boolean
+}
+const navClassName = `
+ flex items-center relative mr-3 px-3 h-8 rounded-xl
+ font-medium text-[14px]
+ cursor-pointer
+`
+const headerEnvClassName: { [k: string]: string } = {
+ DEVELOPMENT: 'bg-[#FEC84B] border-[#FDB022] text-[#93370D]',
+ TESTING: 'bg-[#A5F0FC] border-[#67E3F9] text-[#164C63]',
+}
+const Header: FC<IHeaderProps> = ({ appItems, curApp, userProfile, onLogout, langeniusVersionInfo, isBordered }) => {
+ const { t } = useTranslation()
+ const [showNewAppDialog, setShowNewAppDialog] = useState(false)
+ const { datasets, currentDataset } = useDatasetsContext()
+ const router = useRouter()
+ const showEnvTag = langeniusVersionInfo.current_env === 'TESTING' || langeniusVersionInfo.current_env === 'DEVELOPMENT'
+ const isPluginsComingSoon = useSelectedLayoutSegment() === 'plugins-coming-soon'
+
+ return (
+ <div className={classNames(
+ 'sticky top-0 left-0 right-0 z-20 flex bg-gray-100 grow-0 shrink-0 basis-auto h-14',
+ s.header,
+ isBordered ? 'border-b border-gray-200' : ''
+ )}>
+ <div className={classNames(
+ s[`header-${langeniusVersionInfo.current_env}`],
+ 'flex flex-1 items-center justify-between px-4'
+ )}>
+ <div className='flex items-center'>
+ <Link href="/apps" className='flex items-center mr-3'>
+ <div className={s['logo']} />
+ </Link>
+ {/* Add it when has many stars */}
+ <div className='
+ flex items-center h-[26px] px-2 bg-white
+ border border-solid border-[#E5E7EB] rounded-l-[6px] rounded-r-[6px]
+ '>
+ <div className={s['alpha']} />
+ <div className='ml-1 text-xs font-semibold text-gray-700'>{t('common.menus.status')}</div>
+ </div>
+ </div>
+ <div className='flex items-center'>
+ <Nav
+ icon={<Squares2X2Icon className='mr-1 w-[18px] h-[18px]' />}
+ text={t('common.menus.apps')}
+ activeSegment={['apps', 'app']}
+ link='/apps'
+ curNav={curApp && { id: curApp.id, name: curApp.name }}
+ navs={appItems.map(item => ({
+ id: item.id,
+ name: item.name,
+ link: `/app/${item.id}/overview`
+ }))}
+ createText={t('common.menus.newApp')}
+ onCreate={() => setShowNewAppDialog(true)}
+ />
+ <Link href="/plugins-coming-soon" className={classNames(
+ navClassName, 'group',
+ isPluginsComingSoon && 'bg-white shadow-[0_2px_5px_-1px_rgba(0,0,0,0.05),0_2px_4px_-2px_rgba(0,0,0,0.05)]',
+ isPluginsComingSoon ? 'text-primary-600' : 'text-gray-500 hover:bg-gray-200 hover:text-gray-700'
+ )}>
+ <PuzzlePieceIcon className='mr-1 w-[18px] h-[18px]' />
+ {t('common.menus.plugins')}
+ </Link>
+ <Nav
+ icon={<CircleStackIcon className='mr-1 w-[18px] h-[18px]' />}
+ text={t('common.menus.datasets')}
+ activeSegment='datasets'
+ link='/datasets'
+ curNav={currentDataset && { id: currentDataset.id, name: currentDataset.name }}
+ navs={datasets.map(dataset => ({
+ id: dataset.id,
+ name: dataset.name,
+ link: `/datasets/${dataset.id}/documents`
+ }))}
+ createText={t('common.menus.newDataset')}
+ onCreate={() => router.push('/datasets/create')}
+ />
+ </div>
+ <div className='flex items-center flex-shrink-0'>
+ {
+ showEnvTag && (
+ <div className={`
+ flex items-center h-[22px] mr-4 rounded-md px-2 text-xs font-medium border
+ ${headerEnvClassName[langeniusVersionInfo.current_env]}
+ `}>
+ {
+ langeniusVersionInfo.current_env === 'TESTING' && (
+ <>
+ <div className={s['beaker-icon']} />
+ {t('common.environment.testing')}
+ </>
+ )
+ }
+ {
+ langeniusVersionInfo.current_env === 'DEVELOPMENT' && (
+ <>
+ <CommandLineIcon className='w-3 h-3 mr-1' />
+ {t('common.environment.development')}
+ </>
+ )
+ }
+ </div>
+ )
+ }
+ <WorkspaceProvider>
+ <AccountDropdown userProfile={userProfile} onLogout={onLogout} langeniusVersionInfo={langeniusVersionInfo} />
+ </WorkspaceProvider>
+ </div>
+ </div>
+ <NewAppDialog show={showNewAppDialog} onClose={() => setShowNewAppDialog(false)} />
+ </div>
+ )
+}
+export default Header
diff --git a/web/app/components/header/indicator/index.tsx b/web/app/components/header/indicator/index.tsx
new file mode 100644
index 00000000000..89e3c455cbf
--- /dev/null
+++ b/web/app/components/header/indicator/index.tsx
@@ -0,0 +1,59 @@
+'use client'
+
+import classNames from 'classnames'
+
+export type IndicatorProps = {
+ color?: 'green' | 'orange' | 'red' | 'blue' | 'yellow' | 'gray'
+ className?: string
+}
+
+type ColorMap = {
+ green: string
+ orange: string
+ red: string
+ blue: string
+ yellow: string
+ gray: string
+}
+
+const BACKGROUND_MAP: ColorMap = {
+ green: 'bg-[#31C48D]',
+ orange: 'bg-[#FF5A1F]',
+ red: 'bg-[#F04438]',
+ blue: 'bg-[#36BFFA]',
+ yellow: 'bg-[#FDB022]',
+ gray: 'bg-[#D0D5DD]',
+}
+const BORDER_MAP: ColorMap = {
+ green: 'border-[#0E9F6E]',
+ orange: 'border-[#D03801]',
+ red: 'border-[#D92D20]',
+ blue: 'border-[#0BA5EC]',
+ yellow: 'border-[#F79009]',
+ gray: 'border-[#98A2B3]',
+}
+const SHADOW_MAP: ColorMap = {
+ green: 'shadow-[0_0_5px_-3px_rgba(14,159,110,0.1),0.5px_0.5px_3px_rgba(14,159,110,0.3),inset_1.5px_1.5px_0px_rgba(255,255,255,0.2)]',
+ orange: 'shadow-[0_0_5px_-3px_rgba(255,90,31,0.2),0.5px_0.5px_3px_rgba(255, 90, 31, 0.3), inset_1.5px_1.5px_0_rgba(255, 255, 255, 0.2)]',
+ red: 'shadow-[0_0_5px_-3px_rgba(249,112,102,0.1),0.5px_0.5px_3px_rgba(249, 112, 102, 0.2), inset_1.5px_1.5px_0_rgba(255, 255, 255, 0.4)]',
+ blue: 'shadow-[0_0_5px_-3px_rgba(208, 213, 221, 0.1),0.5px_0.5px_3px_rgba(208, 213, 221, 0.3), inset_1.5px_1.5px_0_rgba(255, 255, 255, 0.2)]',
+ yellow: 'shadow-[0_0_5px_-3px_rgba(253, 176, 34, 0.1),0.5px_0.5px_3px_rgba(253, 176, 34, 0.3), inset_1.5px_1.5px_0_rgba(255, 255, 255, 0.2)]',
+ gray: 'shadow-[0_0_5px_-3px_rgba(208, 213, 221, 0.1),0.5px_0.5px_3px_rgba(208, 213, 221, 0.3), inset_1.5px_1.5px_0_rgba(255, 255, 255, 0.2)]',
+}
+
+export default function Indicator({
+ color = 'green',
+ className = '',
+}: IndicatorProps) {
+ return (
+ <div className={classNames(
+ 'w-2 h-2 border border-solid rounded-[3px]',
+ BACKGROUND_MAP[color],
+ BORDER_MAP[color],
+ SHADOW_MAP[color],
+ className,
+ )}>
+
+ </div>
+ )
+}
diff --git a/web/app/components/header/nav/index.module.css b/web/app/components/header/nav/index.module.css
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/web/app/components/header/nav/index.tsx b/web/app/components/header/nav/index.tsx
new file mode 100644
index 00000000000..9c2d2dcc7b2
--- /dev/null
+++ b/web/app/components/header/nav/index.tsx
@@ -0,0 +1,73 @@
+'use client'
+
+import React, { useState } from 'react'
+import Link from 'next/link'
+import { useSelectedLayoutSegment } from 'next/navigation'
+import classNames from 'classnames'
+import { ArrowLeftIcon } from '@heroicons/react/24/solid'
+import type { INavSelectorProps } from './nav-selector'
+import NavSelector from './nav-selector'
+
+type INavProps = {
+ icon: React.ReactNode
+ text: string
+ activeSegment: string | string[]
+ link: string
+} & INavSelectorProps
+
+const Nav = ({
+ icon,
+ text,
+ activeSegment,
+ link,
+ curNav,
+ navs,
+ createText,
+ onCreate,
+}: INavProps) => {
+ const [hovered, setHovered] = useState(false)
+ const segment = useSelectedLayoutSegment()
+ const isActived = Array.isArray(activeSegment) ? activeSegment.includes(segment!) : segment === activeSegment
+
+ return (
+ <div className={`
+ flex items-center h-8 mr-3 px-0.5 rounded-xl text-[14px] shrink-0
+ ${isActived && 'bg-white shadow-[0_2px_5px_-1px_rgba(0,0,0,0.05),0_2px_4px_-2px_rgba(0,0,0,0.05)]'}
+ `}>
+ <Link href={link}>
+ <div
+ className={classNames(`
+ flex items-center h-8 pl-2.5 pr-2
+ font-semibold cursor-pointer rounded-[10px]
+ ${isActived ? 'text-[#1C64F2]' : 'text-gray-500 hover:bg-gray-200'}
+ ${curNav && isActived && 'hover:bg-[#EBF5FF]'}
+ `)}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ >
+ {
+ (hovered && curNav && isActived)
+ ? <ArrowLeftIcon className='mr-1 w-[18px] h-[18px]' />
+ : icon
+ }
+ {text}
+ </div>
+ </Link>
+ {
+ curNav && isActived && (
+ <>
+ <div className='font-light text-gray-300 '>/</div>
+ <NavSelector
+ curNav={curNav}
+ navs={navs}
+ createText={createText}
+ onCreate={onCreate}
+ />
+ </>
+ )
+ }
+ </div>
+ )
+}
+
+export default Nav
diff --git a/web/app/components/header/nav/nav-selector/index.tsx b/web/app/components/header/nav/nav-selector/index.tsx
new file mode 100644
index 00000000000..ed2bb99668b
--- /dev/null
+++ b/web/app/components/header/nav/nav-selector/index.tsx
@@ -0,0 +1,105 @@
+'use client'
+import { Fragment } from 'react'
+import { ChevronDownIcon, PlusIcon } from '@heroicons/react/24/solid'
+import { Menu, Transition } from '@headlessui/react'
+import { useRouter } from 'next/navigation'
+import Indicator from '../../indicator'
+import AppIcon from '@/app/components/base/app-icon'
+
+type NavItem = {
+ id: string
+ name: string
+ link: string
+}
+export interface INavSelectorProps {
+ navs: NavItem[]
+ curNav?: Omit<NavItem, 'link'>
+ createText: string
+ onCreate: () => void
+}
+
+const itemClassName = `
+ flex items-center w-full h-10 px-3 text-gray-700 text-[14px]
+ rounded-lg font-normal hover:bg-gray-100 cursor-pointer
+`
+
+const NavSelector = ({ curNav, navs, createText, onCreate }: INavSelectorProps) => {
+ const router = useRouter()
+
+ return (
+ <div className="">
+ <Menu as="div" className="relative inline-block text-left">
+ <div>
+ <Menu.Button
+ className="
+ inline-flex items-center w-full h-7 justify-center
+ rounded-[10px] pl-2 pr-2.5 text-[14px] font-semibold
+ text-[#1C64F2] hover:bg-[#EBF5FF]
+ "
+ >
+ {curNav?.name}
+ <ChevronDownIcon
+ className="w-3 h-3 ml-1"
+ aria-hidden="true"
+ />
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className="
+ absolute -left-11 right-0 mt-1.5 w-60 max-w-80
+ divide-y divide-gray-100 origin-top-right rounded-lg bg-white
+ shadow-[0_10px_15px_-3px_rgba(0,0,0,0.1),0_4px_6px_rgba(0,0,0,0.05)]
+ "
+ >
+ <div className="px-1 py-1 overflow-auto" style={{ maxHeight: '50vh' }}>
+ {
+ navs.map((nav) => (
+ <Menu.Item key={nav.id}>
+ <div className={itemClassName} onClick={() => router.push(nav.link)}>
+ <div className='relative w-6 h-6 mr-2 bg-[#D5F5F6] rounded-[6px]'>
+ <AppIcon size='tiny' />
+ <div className='flex justify-center items-center absolute -right-0.5 -bottom-0.5 w-2.5 h-2.5 bg-white rounded'>
+ <Indicator />
+ </div>
+ </div>
+ {nav.name}
+ </div>
+ </Menu.Item>
+ ))
+ }
+ </div>
+ <Menu.Item>
+ <div className='p-1' onClick={onCreate}>
+ <div
+ className='flex items-center h-12 rounded-lg cursor-pointer hover:bg-gray-100'
+ >
+ <div
+ className='
+ flex justify-center items-center
+ ml-4 mr-2 w-6 h-6 bg-gray-100 rounded-[6px]
+ border-[0.5px] border-gray-200 border-dashed
+ '
+ >
+ <PlusIcon className='w-4 h-4 text-gray-500' />
+ </div>
+ <div className='font-normal text-[14px] text-gray-700'>{createText}</div>
+ </div>
+ </div>
+ </Menu.Item>
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ </div>
+ )
+}
+
+export default NavSelector
\ No newline at end of file
diff --git a/web/app/components/i18n-server.tsx b/web/app/components/i18n-server.tsx
new file mode 100644
index 00000000000..5707fa82c59
--- /dev/null
+++ b/web/app/components/i18n-server.tsx
@@ -0,0 +1,25 @@
+import React from 'react'
+import I18N from './i18n'
+import { ToastProvider } from './base/toast'
+import { getDictionary, getLocaleOnServer } from '@/i18n/server'
+
+export type II18NServerProps = {
+ // locale: Locale
+ children: React.ReactNode
+}
+
+const I18NServer = async ({
+ // locale,
+ children,
+}: II18NServerProps) => {
+ const locale = getLocaleOnServer()
+ const dictionary = await getDictionary(locale)
+
+ return (
+ <I18N {...{ locale, dictionary }}>
+ <ToastProvider>{children}</ToastProvider>
+ </I18N>
+ )
+}
+
+export default I18NServer
diff --git a/web/app/components/i18n.tsx b/web/app/components/i18n.tsx
new file mode 100644
index 00000000000..e64f958b309
--- /dev/null
+++ b/web/app/components/i18n.tsx
@@ -0,0 +1,31 @@
+'use client'
+
+import type { FC } from 'react'
+import React from 'react'
+import '@/i18n/i18next-config'
+import I18NContext from '@/context/i18n'
+import type { Locale } from '@/i18n'
+import { getLocaleOnClient, setLocaleOnClient } from '@/i18n/client'
+
+export type II18nProps = {
+ locale: Locale
+ dictionary: Record<string, any>
+ children: React.ReactNode
+ setLocaleOnClient: (locale: Locale) => void
+}
+const I18n: FC<II18nProps> = ({
+ dictionary,
+ children,
+}) => {
+ const locale = getLocaleOnClient()
+ return (
+ <I18NContext.Provider value={{
+ locale,
+ i18n: dictionary,
+ setLocaleOnClient,
+ }}>
+ {children}
+ </I18NContext.Provider>
+ )
+}
+export default React.memo(I18n)
diff --git a/web/app/components/locale-switcher.tsx b/web/app/components/locale-switcher.tsx
new file mode 100644
index 00000000000..018b3f907f3
--- /dev/null
+++ b/web/app/components/locale-switcher.tsx
@@ -0,0 +1,23 @@
+'use client'
+
+import { i18n } from '@/i18n'
+import { setLocaleOnClient } from '@/i18n/client'
+
+const LocaleSwitcher = () => {
+ return (
+ <div className="mt-4">
+ <p>Locale switcher:</p>
+ <ul>
+ {i18n.locales.map((locale) => {
+ return (
+ <li key={locale}>
+ <div className='cursor-pointer ' onClick={() => setLocaleOnClient(locale)}>{locale}</div>
+ </li>
+ )
+ })}
+ </ul>
+ </div>
+ )
+}
+
+export default LocaleSwitcher
diff --git a/web/app/components/share/chat/config-scence/index.tsx b/web/app/components/share/chat/config-scence/index.tsx
new file mode 100644
index 00000000000..e22933ce5d5
--- /dev/null
+++ b/web/app/components/share/chat/config-scence/index.tsx
@@ -0,0 +1,13 @@
+import type { FC } from 'react'
+import React from 'react'
+import type { IWelcomeProps } from '../welcome'
+import Welcome from '../welcome'
+
+const ConfigSence: FC<IWelcomeProps> = (props) => {
+ return (
+ <div className='mb-5 antialiased font-sans overflow-hidden shrink-0'>
+ <Welcome {...props} />
+ </div>
+ )
+}
+export default React.memo(ConfigSence)
diff --git a/web/app/components/share/chat/hooks/use-conversation.ts b/web/app/components/share/chat/hooks/use-conversation.ts
new file mode 100644
index 00000000000..9c48efc3724
--- /dev/null
+++ b/web/app/components/share/chat/hooks/use-conversation.ts
@@ -0,0 +1,66 @@
+import { useState } from 'react'
+import type { ConversationItem } from '@/models/share'
+import produce from 'immer'
+
+const storageConversationIdKey = 'conversationIdInfo'
+
+type ConversationInfoType = Omit<ConversationItem, 'inputs' | 'id'>
+function useConversation() {
+ const [conversationList, setConversationList] = useState<ConversationItem[]>([])
+ const [currConversationId, doSetCurrConversationId] = useState<string>('-1')
+ // when set conversation id, we do not have set appId
+ const setCurrConversationId = (id: string, appId: string, isSetToLocalStroge = true, newConversationName = '') => {
+ doSetCurrConversationId(id)
+ if (isSetToLocalStroge && id !== '-1') {
+ // conversationIdInfo: {[appId1]: conversationId1, [appId2]: conversationId2}
+ const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {}
+ conversationIdInfo[appId] = id
+ globalThis.localStorage?.setItem(storageConversationIdKey, JSON.stringify(conversationIdInfo))
+ }
+ }
+
+ const getConversationIdFromStorage = (appId: string) => {
+ const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {}
+ const id = conversationIdInfo[appId]
+ return id
+ }
+
+ const isNewConversation = currConversationId === '-1'
+ // input can be updated by user
+ const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any> | null>(null)
+ const resetNewConversationInputs = () => {
+ if (!newConversationInputs) return
+ setNewConversationInputs(produce(newConversationInputs, draft => {
+ Object.keys(draft).forEach(key => {
+ draft[key] = ''
+ })
+ }))
+ }
+ const [existConversationInputs, setExistConversationInputs] = useState<Record<string, any> | null>(null)
+ const currInputs = isNewConversation ? newConversationInputs : existConversationInputs
+ const setCurrInputs = isNewConversation ? setNewConversationInputs : setExistConversationInputs
+
+ // info is muted
+ const [newConversationInfo, setNewConversationInfo] = useState<ConversationInfoType | null>(null)
+ const [existConversationInfo, setExistConversationInfo] = useState<ConversationInfoType | null>(null)
+ const currConversationInfo = isNewConversation ? newConversationInfo : existConversationInfo
+
+ return {
+ conversationList,
+ setConversationList,
+ currConversationId,
+ setCurrConversationId,
+ getConversationIdFromStorage,
+ isNewConversation,
+ currInputs,
+ newConversationInputs,
+ existConversationInputs,
+ resetNewConversationInputs,
+ setCurrInputs,
+ currConversationInfo,
+ setNewConversationInfo,
+ setExistConversationInfo
+ }
+}
+
+export default useConversation;
\ No newline at end of file
diff --git a/web/app/components/share/chat/index.tsx b/web/app/components/share/chat/index.tsx
new file mode 100644
index 00000000000..6d1c80fd847
--- /dev/null
+++ b/web/app/components/share/chat/index.tsx
@@ -0,0 +1,506 @@
+'use client'
+import type { FC } from 'react'
+import React, { useEffect, useState, useRef } from 'react'
+import cn from 'classnames'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import produce from 'immer'
+import { useBoolean, useGetState } from 'ahooks'
+import useConversation from './hooks/use-conversation'
+import { ToastContext } from '@/app/components/base/toast'
+import Sidebar from '@/app/components/share/chat/sidebar'
+import ConfigSence from '@/app/components/share/chat/config-scence'
+import Header from '@/app/components/share/header'
+import { fetchAppInfo, fetchAppParams, fetchChatList, fetchConversations, sendChatMessage, updateFeedback, fetchSuggestedQuestions } from '@/service/share'
+import type { ConversationItem, SiteInfo } from '@/models/share'
+import type { PromptConfig } from '@/models/debug'
+import type { Feedbacktype, IChatItem } from '@/app/components/app/chat'
+import Chat from '@/app/components/app/chat'
+import { changeLanguage } from '@/i18n/i18next-config'
+import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
+import Loading from '@/app/components/base/loading'
+import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
+import AppUnavailable from '../../base/app-unavailable'
+import { userInputsFormToPromptVariables } from '@/utils/model-config'
+import { SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
+export type IMainProps = {
+ params: {
+ locale: string
+ appId: string
+ conversationId: string
+ token: string
+ }
+}
+
+const Main: FC<IMainProps> = () => {
+ const { t } = useTranslation()
+ const media = useBreakpoints()
+ const isMobile = media === MediaType.mobile
+
+ /*
+ * app info
+ */
+ const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
+ const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
+ const [appId, setAppId] = useState<string>('')
+ const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
+ const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
+ const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
+ const [inited, setInited] = useState<boolean>(false)
+ const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
+ // in mobile, show sidebar by click button
+ const [isShowSidebar, { setTrue: showSidebar, setFalse: hideSidebar }] = useBoolean(false)
+ // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
+ useEffect(() => {
+ if (siteInfo?.title) {
+ if (plan !== 'basic')
+ document.title = `${siteInfo.title}`
+ else
+ document.title = `${siteInfo.title} - Powered by Dify`
+ }
+
+ }, [siteInfo?.title, plan])
+
+ /*
+ * conversation info
+ */
+ const {
+ conversationList,
+ setConversationList,
+ currConversationId,
+ setCurrConversationId,
+ getConversationIdFromStorage,
+ isNewConversation,
+ currConversationInfo,
+ currInputs,
+ newConversationInputs,
+ // existConversationInputs,
+ resetNewConversationInputs,
+ setCurrInputs,
+ setNewConversationInfo,
+ setExistConversationInfo
+ } = useConversation()
+ const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
+
+ const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
+ const [isChatStarted, { setTrue: setChatStarted, setFalse: setChatNotStarted }] = useBoolean(false)
+ const handleStartChat = (inputs: Record<string, any>) => {
+ createNewChat()
+ setConversationIdChangeBecauseOfNew(true)
+ setCurrInputs(inputs)
+ setChatStarted()
+ // parse variables in introduction
+ setChatList(generateNewChatListWithOpenstatement('', inputs))
+ }
+ const hasSetInputs = (() => {
+ if (!isNewConversation) {
+ return true
+ }
+ return isChatStarted
+ })()
+
+ const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
+ const conversationIntroduction = currConversationInfo?.introduction || ''
+
+ const handleConversationSwitch = () => {
+ if (!inited) return
+ if (!appId) {
+ // wait for appId
+ setTimeout(handleConversationSwitch, 100)
+ return
+ }
+
+ // update inputs of current conversation
+ let notSyncToStateIntroduction = ''
+ let notSyncToStateInputs: Record<string, any> | undefined | null = {}
+ if (!isNewConversation) {
+ const item = conversationList.find(item => item.id === currConversationId)
+ notSyncToStateInputs = item?.inputs || {}
+ setCurrInputs(notSyncToStateInputs)
+ notSyncToStateIntroduction = item?.introduction || ''
+ setExistConversationInfo({
+ name: item?.name || '',
+ introduction: notSyncToStateIntroduction,
+ })
+ } else {
+ notSyncToStateInputs = newConversationInputs
+ setCurrInputs(notSyncToStateInputs)
+ }
+
+ // update chat list of current conversation
+ if (!isNewConversation && !conversationIdChangeBecauseOfNew && !isResponsing) {
+ fetchChatList(currConversationId).then((res: any) => {
+ const { data } = res
+ const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
+
+ data.forEach((item: any) => {
+ newChatList.push({
+ id: `question-${item.id}`,
+ content: item.query,
+ isAnswer: false,
+ })
+ newChatList.push({
+ id: item.id,
+ content: item.answer,
+ feedback: item.feedback,
+ isAnswer: true,
+ })
+ })
+ setChatList(newChatList)
+ })
+ }
+
+ if (isNewConversation && isChatStarted) {
+ setChatList(generateNewChatListWithOpenstatement())
+ }
+
+ setControlFocus(Date.now())
+ }
+ useEffect(handleConversationSwitch, [currConversationId, inited])
+
+ const handleConversationIdChange = (id: string) => {
+ if (id === '-1') {
+ createNewChat()
+ setConversationIdChangeBecauseOfNew(true)
+ } else {
+ setConversationIdChangeBecauseOfNew(false)
+ }
+ // trigger handleConversationSwitch
+ setCurrConversationId(id, appId)
+ setIsShowSuggestion(false)
+ hideSidebar()
+ }
+
+ /*
+ * chat info. chat is under conversation.
+ */
+ const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
+ const chatListDomRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ // scroll to bottom
+ if (chatListDomRef.current) {
+ chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
+ }
+ }, [chatList, currConversationId])
+ // user can not edit inputs if user had send message
+ const canEditInpus = !chatList.some(item => item.isAnswer === false) && isNewConversation
+ const createNewChat = () => {
+ // if new chat is already exist, do not create new chat
+ abortController?.abort()
+ setResponsingFalse()
+ if (conversationList.some(item => item.id === '-1')) {
+ return
+ }
+ setConversationList(produce(conversationList, draft => {
+ draft.unshift({
+ id: '-1',
+ name: t('share.chat.newChatDefaultName'),
+ inputs: newConversationInputs,
+ introduction: conversationIntroduction
+ })
+ }))
+ }
+
+ // sometime introduction is not applied to state
+ const generateNewChatListWithOpenstatement = (introduction?: string, inputs?: Record<string, any> | null) => {
+ let caculatedIntroduction = introduction || conversationIntroduction || ''
+ const caculatedPromptVariables = inputs || currInputs || null
+ if (caculatedIntroduction && caculatedPromptVariables) {
+ caculatedIntroduction = replaceStringWithValues(caculatedIntroduction, promptConfig?.prompt_variables || [], caculatedPromptVariables)
+ }
+ // console.log(isPublicVersion)
+ const openstatement = {
+ id: `${Date.now()}`,
+ content: caculatedIntroduction,
+ isAnswer: true,
+ feedbackDisabled: true,
+ isOpeningStatement: isPublicVersion
+ }
+ if (caculatedIntroduction) {
+ return [openstatement]
+ }
+ return []
+ }
+
+
+ // init
+ useEffect(() => {
+ (async () => {
+ try {
+ const [appData, conversationData, appParams] = await Promise.all([fetchAppInfo(), fetchConversations(), fetchAppParams()])
+ const { app_id: appId, site: siteInfo, model_config, plan }: any = appData
+ setAppId(appId)
+ setPlan(plan)
+ const tempIsPublicVersion = siteInfo.prompt_public
+ setIsPublicVersion(tempIsPublicVersion)
+ const prompt_template = tempIsPublicVersion ? model_config.pre_prompt : ''
+
+ // handle current conversation id
+ const { data: conversations } = conversationData as { data: ConversationItem[] }
+ const _conversationId = getConversationIdFromStorage(appId)
+ const isNotNewConversation = conversations.some(item => item.id === _conversationId)
+
+ // fetch new conversation info
+ const { user_input_form, opening_statement: introduction, suggested_questions_after_answer }: any = appParams
+ const prompt_variables = userInputsFormToPromptVariables(user_input_form)
+ changeLanguage(siteInfo.default_language)
+ setNewConversationInfo({
+ name: t('share.chat.newChatDefaultName'),
+ introduction,
+ })
+ setSiteInfo(siteInfo as SiteInfo)
+ setPromptConfig({
+ prompt_template,
+ prompt_variables: prompt_variables,
+ } as PromptConfig)
+ setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
+
+ setConversationList(conversations as ConversationItem[])
+
+ if (isNotNewConversation) {
+ setCurrConversationId(_conversationId, appId, false)
+ }
+ setInited(true)
+ } catch (e: any) {
+ if (e.status === 404) {
+ setAppUnavailable(true)
+ } else {
+ setIsUnknwonReason(true)
+ setAppUnavailable(true)
+ }
+ }
+ })()
+ }, [])
+
+ const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
+ const [abortController, setAbortController] = useState<AbortController | null>(null)
+ const { notify } = useContext(ToastContext)
+ const logError = (message: string) => {
+ notify({ type: 'error', message })
+ }
+
+ const checkCanSend = () => {
+ const prompt_variables = promptConfig?.prompt_variables
+ const inputs = currInputs
+ if (!inputs || !prompt_variables || prompt_variables?.length === 0) {
+ return true
+ }
+ let hasEmptyInput = false
+ const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
+ const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
+ return res
+ }) || [] // compatible with old version
+ requiredVars.forEach(({ key }) => {
+ if (hasEmptyInput) {
+ return
+ }
+ if (!inputs?.[key]) {
+ hasEmptyInput = true
+ }
+ })
+
+ if (hasEmptyInput) {
+ logError(t('appDebug.errorMessage.valueOfVarRequired'))
+ return false
+ }
+ return !hasEmptyInput
+ }
+
+ const [controlFocus, setControlFocus] = useState(0)
+ const [isShowSuggestion, setIsShowSuggestion] = useState(false)
+ const doShowSuggestion = isShowSuggestion && !isResponsing
+ const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
+ const handleSend = async (message: string) => {
+ if (isResponsing) {
+ notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
+ return
+ }
+ const data = {
+ inputs: currInputs,
+ query: message,
+ conversation_id: isNewConversation ? null : currConversationId,
+ }
+
+ // qustion
+ const questionId = `question-${Date.now()}`
+ const questionItem = {
+ id: questionId,
+ content: message,
+ isAnswer: false,
+ }
+
+ const placeholderAnswerId = `answer-placeholder-${Date.now()}`
+ const placeholderAnswerItem = {
+ id: placeholderAnswerId,
+ content: '',
+ isAnswer: true,
+ }
+
+ const newList = [...getChatList(), questionItem, placeholderAnswerItem]
+ setChatList(newList)
+
+ // answer
+ const responseItem = {
+ id: `${Date.now()}`,
+ content: '',
+ isAnswer: true,
+ }
+
+ let tempNewConversationId = ''
+
+ setResponsingTrue()
+ setIsShowSuggestion(false)
+ sendChatMessage(data, {
+ getAbortController: (abortController) => {
+ setAbortController(abortController)
+ },
+ onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId }: any) => {
+ responseItem.content = responseItem.content + message
+ responseItem.id = messageId
+ if (isFirstMessage && newConversationId) {
+ tempNewConversationId = newConversationId
+ }
+
+ // closesure new list is outdated.
+ const newListWithAnswer = produce(
+ getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
+ (draft) => {
+ if (!draft.find(item => item.id === questionId))
+ draft.push({ ...questionItem })
+
+ draft.push({ ...responseItem })
+ })
+ setChatList(newListWithAnswer)
+ },
+ async onCompleted(hasError?: boolean) {
+ setResponsingFalse()
+ if (hasError) {
+ return
+ }
+ let currChatList = conversationList
+ if (getConversationIdChangeBecauseOfNew()) {
+ const { data: conversations }: any = await fetchConversations()
+ setConversationList(conversations as ConversationItem[])
+ currChatList = conversations
+ }
+ setConversationIdChangeBecauseOfNew(false)
+ resetNewConversationInputs()
+ setChatNotStarted()
+ setCurrConversationId(tempNewConversationId, appId, true)
+ if (suggestedQuestionsAfterAnswerConfig?.enabled) {
+ const { data }: any = await fetchSuggestedQuestions(responseItem.id)
+ setSuggestQuestions(data)
+ setIsShowSuggestion(true)
+ }
+ },
+ onError() {
+ setResponsingFalse()
+ // role back placeholder answer
+ setChatList(produce(getChatList(), draft => {
+ draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
+ }))
+ },
+ })
+ }
+
+ const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
+ await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } })
+ const newChatList = chatList.map((item) => {
+ if (item.id === messageId) {
+ return {
+ ...item,
+ feedback,
+ }
+ }
+ return item
+ })
+ setChatList(newChatList)
+ notify({ type: 'success', message: t('common.api.success') })
+ }
+
+ const renderSidebar = () => {
+ if (!appId || !siteInfo || !promptConfig)
+ return null
+ return (
+ <Sidebar
+ list={conversationList}
+ onCurrentIdChange={handleConversationIdChange}
+ currentId={currConversationId}
+ copyRight={siteInfo.copyright || siteInfo.title}
+ />
+ )
+ }
+
+ if (appUnavailable)
+ return <AppUnavailable isUnknwonReason={isUnknwonReason} />
+
+ if (!appId || !siteInfo || !promptConfig)
+ return <Loading type='app' />
+
+ return (
+ <div className='bg-gray-100'>
+ <Header
+ title={siteInfo.title}
+ isMobile={isMobile}
+ onShowSideBar={showSidebar}
+ onCreateNewChat={() => handleConversationIdChange('-1')}
+ />
+ {/* {isNewConversation ? 'new' : 'exist'}
+ {JSON.stringify(newConversationInputs ? newConversationInputs : {})}
+ {JSON.stringify(existConversationInputs ? existConversationInputs : {})} */}
+ <div className="flex rounded-t-2xl bg-white overflow-hidden">
+ {/* sidebar */}
+ {!isMobile && renderSidebar()}
+ {isMobile && isShowSidebar && (
+ <div className='fixed inset-0 z-50'
+ style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
+ onClick={hideSidebar}
+ >
+ <div className='inline-block' onClick={e => e.stopPropagation()}>
+ {renderSidebar()}
+ </div>
+ </div>
+ )}
+ {/* main */}
+ <div className='flex-grow flex flex-col h-[calc(100vh_-_3rem)] overflow-y-auto'>
+ <ConfigSence
+ conversationName={conversationName}
+ hasSetInputs={hasSetInputs}
+ isPublicVersion={isPublicVersion}
+ siteInfo={siteInfo}
+ promptConfig={promptConfig}
+ onStartChat={handleStartChat}
+ canEidtInpus={canEditInpus}
+ savedInputs={currInputs as Record<string, any>}
+ onInputsChange={setCurrInputs}
+ plan={plan}
+ ></ConfigSence>
+
+ {
+ hasSetInputs && (
+ <div className={cn(doShowSuggestion ? 'pb-[140px]' : 'pb-[66px]', 'relative grow h-[200px] pc:w-[794px] max-w-full mobile:w-full mx-auto mb-3.5 overflow-hidden')}>
+ <div className='h-full overflow-y-auto' ref={chatListDomRef}>
+ <Chat
+ chatList={chatList}
+ onSend={handleSend}
+ isHideFeedbackEdit
+ onFeedback={handleFeedback}
+ isResponsing={isResponsing}
+ abortResponsing={() => {
+ abortController?.abort()
+ setResponsingFalse()
+ }}
+ checkCanSend={checkCanSend}
+ controlFocus={controlFocus}
+ isShowSuggestion={doShowSuggestion}
+ suggestionList={suggestQuestions}
+ />
+ </div>
+ </div>)
+ }
+ </div>
+ </div>
+ </div>
+ )
+}
+export default React.memo(Main)
diff --git a/web/app/components/share/chat/sidebar/card.module.css b/web/app/components/share/chat/sidebar/card.module.css
new file mode 100644
index 00000000000..c917cb4db6c
--- /dev/null
+++ b/web/app/components/share/chat/sidebar/card.module.css
@@ -0,0 +1,3 @@
+.card:hover {
+ background: linear-gradient(0deg, rgba(235, 245, 255, 0.4), rgba(235, 245, 255, 0.4)), #FFFFFF;
+}
\ No newline at end of file
diff --git a/web/app/components/share/chat/sidebar/card.tsx b/web/app/components/share/chat/sidebar/card.tsx
new file mode 100644
index 00000000000..7457315a0d3
--- /dev/null
+++ b/web/app/components/share/chat/sidebar/card.tsx
@@ -0,0 +1,19 @@
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import s from './card.module.css'
+
+type PropType = {
+ children: React.ReactNode
+ text?: string
+}
+function Card({ children, text }: PropType) {
+ const { t } = useTranslation()
+ return (
+ <div className={`${s.card} box-border w-full flex flex-col items-start px-4 py-3 rounded-lg border-solid border border-gray-200 cursor-pointer hover:border-primary-300`}>
+ <div className='text-gray-400 font-medium text-xs mb-2'>{text ?? t('share.chat.powerBy')}</div>
+ {children}
+ </div>
+ )
+}
+
+export default Card
diff --git a/web/app/components/share/chat/sidebar/index.tsx b/web/app/components/share/chat/sidebar/index.tsx
new file mode 100644
index 00000000000..248ac0b5148
--- /dev/null
+++ b/web/app/components/share/chat/sidebar/index.tsx
@@ -0,0 +1,83 @@
+import React from 'react'
+import type { FC } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ ChatBubbleOvalLeftEllipsisIcon,
+ PencilSquareIcon
+} from '@heroicons/react/24/outline'
+import { ChatBubbleOvalLeftEllipsisIcon as ChatBubbleOvalLeftEllipsisSolidIcon, } from '@heroicons/react/24/solid'
+import Button from '../../../base/button'
+// import Card from './card'
+import type { ConversationItem } from '@/models/share'
+
+function classNames(...classes: any[]) {
+ return classes.filter(Boolean).join(' ')
+}
+
+const MAX_CONVERSATION_LENTH = 20
+
+export type ISidebarProps = {
+ copyRight: string
+ currentId: string
+ onCurrentIdChange: (id: string) => void
+ list: ConversationItem[]
+}
+
+const Sidebar: FC<ISidebarProps> = ({
+ copyRight,
+ currentId,
+ onCurrentIdChange,
+ list }) => {
+ const { t } = useTranslation()
+ return (
+ <div
+ className="shrink-0 flex flex-col overflow-y-auto bg-white pc:w-[244px] tablet:w-[192px] mobile:w-[240px] border-r border-gray-200 tablet:h-[calc(100vh_-_3rem)] mobile:h-screen"
+ >
+ {list.length < MAX_CONVERSATION_LENTH && (
+ <div className="flex flex-shrink-0 p-4 !pb-0">
+ <Button
+ onClick={() => { onCurrentIdChange('-1') }}
+ className="group block w-full flex-shrink-0 !justify-start !h-9 text-primary-600 items-center text-sm">
+ <PencilSquareIcon className="mr-2 h-4 w-4" /> {t('share.chat.newChat')}
+ </Button>
+ </div>
+ )}
+
+ <nav className="mt-4 flex-1 space-y-1 bg-white p-4 !pt-0">
+ {list.map((item) => {
+ const isCurrent = item.id === currentId
+ const ItemIcon
+ = isCurrent ? ChatBubbleOvalLeftEllipsisSolidIcon : ChatBubbleOvalLeftEllipsisIcon
+ return (
+ <div
+ onClick={() => onCurrentIdChange(item.id)}
+ key={item.id}
+ className={classNames(
+ isCurrent
+ ? 'bg-primary-50 text-primary-600'
+ : 'text-gray-700 hover:bg-gray-100 hover:text-gray-700',
+ 'group flex items-center rounded-md px-2 py-2 text-sm font-medium cursor-pointer',
+ )}
+ >
+ <ItemIcon
+ className={classNames(
+ isCurrent
+ ? 'text-primary-600'
+ : 'text-gray-400 group-hover:text-gray-500',
+ 'mr-3 h-5 w-5 flex-shrink-0',
+ )}
+ aria-hidden="true"
+ />
+ {item.name}
+ </div>
+ )
+ })}
+ </nav>
+ <div className="flex flex-shrink-0 pr-4 pb-4 pl-4">
+ <div className="text-gray-400 font-normal text-xs">© {copyRight} {(new Date()).getFullYear()}</div>
+ </div>
+ </div>
+ )
+}
+
+export default React.memo(Sidebar)
diff --git a/web/app/components/share/chat/value-panel/index.tsx b/web/app/components/share/chat/value-panel/index.tsx
new file mode 100644
index 00000000000..ff4aaedab4c
--- /dev/null
+++ b/web/app/components/share/chat/value-panel/index.tsx
@@ -0,0 +1,79 @@
+'use client'
+import React, { FC, ReactNode } from 'react'
+import cn from 'classnames'
+import { StarIcon } from '@/app/components/share/chat/welcome/massive-component'
+import Button from '@/app/components/base/button'
+import { useTranslation } from 'react-i18next'
+
+import s from './style.module.css'
+
+export interface ITemplateVarPanelProps {
+ className?: string
+ header: ReactNode
+ children?: ReactNode | null
+ isFold: boolean
+}
+
+const TemplateVarPanel: FC<ITemplateVarPanelProps> = ({
+ className,
+ header,
+ children,
+ isFold
+}) => {
+ return (
+ <div className={cn(isFold ? 'border border-indigo-100' : s.boxShodow, className, 'rounded-xl ')}>
+ {/* header */}
+ <div
+ className={cn(isFold && 'rounded-b-xl', 'rounded-t-xl px-6 py-4 bg-indigo-25 text-xs')}
+ >
+ {header}
+ </div>
+ {/* body */}
+ {!isFold && children && (
+ <div className='rounded-b-xl p-6'>
+ {children}
+ </div>
+ )}
+ </div>
+ )
+}
+
+export const PanelTitle: FC<{ title: string, className?: string }> = ({
+ title,
+ className
+}) => {
+ return (
+ <div className={cn(className, 'flex items-center space-x-1 text-indigo-600')}>
+ <StarIcon />
+ <span className='text-xs'>{title}</span>
+ </div>
+ )
+}
+
+export const VarOpBtnGroup: FC<{ className?: string, onConfirm: () => void, onCancel: () => void }> = ({
+ className,
+ onConfirm,
+ onCancel
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className={cn(className, 'flex mt-3 space-x-2 mobile:ml-0 tablet:ml-[128px] text-sm')}>
+ <Button
+ className='text-sm'
+ type='primary'
+ onClick={onConfirm}
+ >
+ {t('common.operation.save')}
+ </Button>
+ <Button
+ className='text-sm'
+ onClick={onCancel}
+ >
+ {t('common.operation.cancel')}
+ </Button>
+ </div >
+ )
+}
+
+export default React.memo(TemplateVarPanel)
diff --git a/web/app/components/share/chat/value-panel/style.module.css b/web/app/components/share/chat/value-panel/style.module.css
new file mode 100644
index 00000000000..c7613c44a41
--- /dev/null
+++ b/web/app/components/share/chat/value-panel/style.module.css
@@ -0,0 +1,3 @@
+.boxShodow {
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
\ No newline at end of file
diff --git a/web/app/components/share/chat/welcome/icons/logo.png b/web/app/components/share/chat/welcome/icons/logo.png
new file mode 100644
index 00000000000..800a0709063
Binary files /dev/null and b/web/app/components/share/chat/welcome/icons/logo.png differ
diff --git a/web/app/components/share/chat/welcome/index.tsx b/web/app/components/share/chat/welcome/index.tsx
new file mode 100644
index 00000000000..415bc3bd81d
--- /dev/null
+++ b/web/app/components/share/chat/welcome/index.tsx
@@ -0,0 +1,352 @@
+'use client'
+import type { FC } from 'react'
+import React, { useState, useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useContext } from 'use-context-selector'
+import s from './style.module.css'
+import type { SiteInfo } from '@/models/share'
+import type { PromptConfig } from '@/models/debug'
+import { ToastContext } from '@/app/components/base/toast'
+import Select from '@/app/components/base/select'
+import { DEFAULT_VALUE_MAX_LEN } from '@/config'
+import TemplateVarPanel, { PanelTitle, VarOpBtnGroup } from '../value-panel'
+import { AppInfo, PromptTemplate, ChatBtn, EditBtn, FootLogo } from './massive-component'
+
+// regex to match the {{}} and replace it with a span
+const regex = /\{\{([^}]+)\}\}/g
+
+export type IWelcomeProps = {
+ conversationName: string
+ hasSetInputs: boolean
+ isPublicVersion: boolean
+ siteInfo: SiteInfo
+ promptConfig: PromptConfig
+ onStartChat: (inputs: Record<string, any>) => void
+ canEidtInpus: boolean
+ savedInputs: Record<string, any>
+ onInputsChange: (inputs: Record<string, any>) => void
+ plan: string
+}
+
+const Welcome: FC<IWelcomeProps> = ({
+ conversationName,
+ hasSetInputs,
+ isPublicVersion,
+ siteInfo,
+ plan,
+ promptConfig,
+ onStartChat,
+ canEidtInpus,
+ savedInputs,
+ onInputsChange
+}) => {
+ const { t } = useTranslation()
+ const hasVar = promptConfig.prompt_variables.length > 0
+ const [isFold, setIsFold] = useState<boolean>(true)
+ const [inputs, setInputs] = useState<Record<string, any>>((() => {
+ if (hasSetInputs) {
+ return savedInputs
+ }
+ const res: Record<string, any> = {}
+ if (promptConfig) {
+ promptConfig.prompt_variables.forEach((item) => {
+ res[item.key] = ''
+ })
+ }
+ // debugger
+ return res
+ })())
+ useEffect(() => {
+ if (!savedInputs) {
+ const res: Record<string, any> = {}
+ if (promptConfig) {
+ promptConfig.prompt_variables.forEach((item) => {
+ res[item.key] = ''
+ })
+ }
+ setInputs(res)
+ } else {
+ setInputs(savedInputs)
+ }
+ }, [savedInputs])
+
+ const highLightPromoptTemplate = (() => {
+ if (!promptConfig)
+ return ''
+ const res = promptConfig.prompt_template.replace(regex, (match, p1) => {
+ return `<span class='text-gray-800 font-bold'>${inputs?.[p1] ? inputs?.[p1] : match}</span>`
+ })
+ return res
+ })()
+
+ const { notify } = useContext(ToastContext)
+ const logError = (message: string) => {
+ notify({ type: 'error', message, duration: 3000 })
+ }
+
+ const renderHeader = () => {
+ return (
+ <div className='absolute top-0 left-0 right-0 flex items-center justify-between border-b border-gray-100 mobile:h-12 tablet:h-16 px-8 bg-white'>
+ <div className='text-gray-900'>{conversationName}</div>
+ </div>
+ )
+ }
+
+ const renderInputs = () => {
+ return (
+ <div className='space-y-3'>
+ {promptConfig.prompt_variables.map(item => (
+ <div className='tablet:flex tablet:!h-9 mobile:space-y-2 tablet:space-y-0 mobile:text-xs tablet:text-sm' key={item.key}>
+ <label className={`flex-shrink-0 flex items-center mobile:text-gray-700 tablet:text-gray-900 mobile:font-medium pc:font-normal ${s.formLabel}`}>{item.name}</label>
+ {item.type === 'select' ? (
+ <Select
+ className='w-full'
+ defaultValue={inputs?.[item.key]}
+ onSelect={(i) => { setInputs({ ...inputs, [item.key]: i.value }) }}
+ items={(item.options || []).map(i => ({ name: i, value: i }))}
+ allowSearch={false}
+ bgClassName='bg-gray-50'
+ />
+ ) : (
+ <input
+ placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
+ value={inputs?.[item.key] || ''}
+ onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}
+ className={`w-full flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50`}
+ maxLength={item.max_length || DEFAULT_VALUE_MAX_LEN}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ )
+ }
+
+ const canChat = () => {
+ const prompt_variables = promptConfig?.prompt_variables
+ if (!inputs || !prompt_variables || prompt_variables?.length === 0) {
+ return true
+ }
+ let hasEmptyInput = false
+ const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
+ const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
+ return res
+ }) || [] // compatible with old version
+ requiredVars.forEach(({ key }) => {
+ if (hasEmptyInput) {
+ return
+ }
+ if (!inputs?.[key]) {
+ hasEmptyInput = true
+ }
+ })
+
+ if (hasEmptyInput) {
+ logError(t('appDebug.errorMessage.valueOfVarRequired'))
+ return false
+ }
+ return !hasEmptyInput
+ }
+
+ const handleChat = () => {
+ if (!canChat()) {
+ return
+ }
+ onStartChat(inputs)
+ }
+
+ const renderNoVarPanel = () => {
+ if (isPublicVersion) {
+ return (
+ <div>
+ <AppInfo siteInfo={siteInfo} />
+ <TemplateVarPanel
+ isFold={false}
+ header={
+ <>
+ <PanelTitle
+ title={t('share.chat.publicPromptConfigTitle')}
+ className='mb-1'
+ />
+ <PromptTemplate html={highLightPromoptTemplate} />
+ </>
+ }
+ >
+ <ChatBtn onClick={handleChat} />
+ </TemplateVarPanel>
+ </div>
+ )
+ }
+ // private version
+ return (
+ <TemplateVarPanel
+ isFold={false}
+ header={
+ <AppInfo siteInfo={siteInfo} />
+ }
+ >
+ <ChatBtn onClick={handleChat} />
+ </TemplateVarPanel>
+ )
+ }
+
+ const renderVarPanel = () => {
+ return (
+ <TemplateVarPanel
+ isFold={false}
+ header={
+ <AppInfo siteInfo={siteInfo} />
+ }
+ >
+ {renderInputs()}
+ <ChatBtn
+ className='mt-3 mobile:ml-0 tablet:ml-[128px]'
+ onClick={handleChat}
+ />
+ </TemplateVarPanel>
+ )
+ }
+
+ const renderVarOpBtnGroup = () => {
+ return (
+ <VarOpBtnGroup
+ onConfirm={() => {
+ if (!canChat()) {
+ return
+ }
+ onInputsChange(inputs)
+ setIsFold(true)
+ }}
+ onCancel={() => {
+ setInputs(savedInputs)
+ setIsFold(true)
+ }}
+ />
+ )
+ }
+
+ const renderHasSetInputsPublic = () => {
+ if (!canEidtInpus) {
+ return (
+ <TemplateVarPanel
+ isFold={false}
+ header={
+ <>
+ <PanelTitle
+ title={t('share.chat.publicPromptConfigTitle')}
+ className='mb-1'
+ />
+ <PromptTemplate html={highLightPromoptTemplate} />
+ </>
+ }
+ />
+ )
+ }
+
+ return (
+ <TemplateVarPanel
+ isFold={isFold}
+ header={
+ <>
+ <PanelTitle
+ title={t('share.chat.publicPromptConfigTitle')}
+ className='mb-1'
+ />
+ <PromptTemplate html={highLightPromoptTemplate} />
+ {isFold && (
+ <div className='flex items-center justify-between mt-3 border-t border-indigo-100 pt-4 text-xs text-indigo-600'>
+ <span className='text-gray-700'>{t('share.chat.configStatusDes')}</span>
+ <EditBtn onClick={() => setIsFold(false)} />
+ </div>
+ )}
+ </>
+ }
+ >
+ {renderInputs()}
+ {renderVarOpBtnGroup()}
+ </TemplateVarPanel>
+ )
+ }
+
+ const renderHasSetInputsPrivate = () => {
+ if (!canEidtInpus || !hasVar) {
+ return null
+ }
+ return (
+ <TemplateVarPanel
+ isFold={isFold}
+ header={
+ <div className='flex items-center justify-between text-indigo-600'>
+ <PanelTitle
+ title={!isFold ? t('share.chat.privatePromptConfigTitle') : t('share.chat.configStatusDes')}
+ />
+ {isFold && (
+ <EditBtn onClick={() => setIsFold(false)} />
+ )}
+ </div>
+ }
+ >
+ {renderInputs()}
+ {renderVarOpBtnGroup()}
+ </TemplateVarPanel>
+ )
+ }
+
+ const renderHasSetInputs = () => {
+ if (!isPublicVersion && !canEidtInpus || !hasVar) {
+ return null
+ }
+ return (
+ <div
+ className='pt-[88px] mb-5'
+ >
+ {isPublicVersion ? renderHasSetInputsPublic() : renderHasSetInputsPrivate()}
+ </div>)
+ }
+
+ return (
+ <div className='relative mobile:min-h-[48px] tablet:min-h-[64px]'>
+ {hasSetInputs && renderHeader()}
+ <div className='mx-auto pc:w-[794px] max-w-full mobile:w-full px-3.5'>
+ {/* Has't set inputs */}
+ {
+ !hasSetInputs && (
+ <div className='mobile:pt-[72px] tablet:pt-[128px] pc:pt-[200px]'>
+ {hasVar ? (
+ renderVarPanel()
+ ) : (
+ renderNoVarPanel()
+ )}
+ </div>
+ )
+ }
+
+ {/* Has set inputs */}
+ {hasSetInputs && renderHasSetInputs()}
+
+ {/* foot */}
+ {!hasSetInputs && (
+ <div className='mt-4 flex justify-between items-center h-8 text-xs text-gray-400'>
+
+ {siteInfo.privacy_policy
+ ? <div>{t('share.chat.privacyPolicyLeft')}
+ <a
+ className='text-gray-500'
+ href={siteInfo.privacy_policy}
+ target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
+ {t('share.chat.privacyPolicyRight')}
+ </div>
+ : <div>
+ </div>}
+ {plan === 'basic' && <a className='flex items-center pr-3 space-x-3' href="https://dify.ai/" target="_blank">
+ <span className='uppercase'>{t('share.chat.powerBy')}</span>
+ <FootLogo />
+ </a>}
+ </div>
+ )}
+ </div>
+ </div >
+ )
+}
+
+export default React.memo(Welcome)
diff --git a/web/app/components/share/chat/welcome/massive-component.tsx b/web/app/components/share/chat/welcome/massive-component.tsx
new file mode 100644
index 00000000000..a4df7759333
--- /dev/null
+++ b/web/app/components/share/chat/welcome/massive-component.tsx
@@ -0,0 +1,75 @@
+'use client'
+import React, { FC } from 'react'
+import cn from 'classnames'
+import { useTranslation } from 'react-i18next'
+import type { SiteInfo } from '@/models/share'
+import Button from '@/app/components/base/button'
+import {
+ PencilIcon
+} from '@heroicons/react/24/solid'
+
+import s from './style.module.css'
+
+export const AppInfo: FC<{ siteInfo: SiteInfo }> = ({ siteInfo }) => {
+ const { t } = useTranslation()
+ return (
+ <div>
+ <div className='flex items-center py-2 text-xl font-medium text-gray-700 rounded-md'>👏 {t('share.common.welcome')} {siteInfo.title}</div>
+ <p className='text-sm text-gray-500'>{siteInfo.description}</p>
+ </div>
+ )
+}
+
+export const PromptTemplate: FC<{ html: string }> = ({ html }) => {
+ return (
+ <div
+ className={' box-border text-sm text-gray-700'}
+ dangerouslySetInnerHTML={{ __html: html }}
+ ></div>
+ )
+}
+
+export const StarIcon = () => (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M2.75 1C2.75 0.723858 2.52614 0.5 2.25 0.5C1.97386 0.5 1.75 0.723858 1.75 1V1.75H1C0.723858 1.75 0.5 1.97386 0.5 2.25C0.5 2.52614 0.723858 2.75 1 2.75H1.75V3.5C1.75 3.77614 1.97386 4 2.25 4C2.52614 4 2.75 3.77614 2.75 3.5V2.75H3.5C3.77614 2.75 4 2.52614 4 2.25C4 1.97386 3.77614 1.75 3.5 1.75H2.75V1Z" fill="#444CE7" />
+ <path d="M2.75 8.5C2.75 8.22386 2.52614 8 2.25 8C1.97386 8 1.75 8.22386 1.75 8.5V9.25H1C0.723858 9.25 0.5 9.47386 0.5 9.75C0.5 10.0261 0.723858 10.25 1 10.25H1.75V11C1.75 11.2761 1.97386 11.5 2.25 11.5C2.52614 11.5 2.75 11.2761 2.75 11V10.25H3.5C3.77614 10.25 4 10.0261 4 9.75C4 9.47386 3.77614 9.25 3.5 9.25H2.75V8.5Z" fill="#444CE7" />
+ <path d="M6.96667 1.32051C6.8924 1.12741 6.70689 1 6.5 1C6.29311 1 6.10759 1.12741 6.03333 1.32051L5.16624 3.57494C5.01604 3.96546 4.96884 4.078 4.90428 4.1688C4.8395 4.2599 4.7599 4.3395 4.6688 4.40428C4.578 4.46884 4.46546 4.51604 4.07494 4.66624L1.82051 5.53333C1.62741 5.60759 1.5 5.79311 1.5 6C1.5 6.20689 1.62741 6.39241 1.82051 6.46667L4.07494 7.33376C4.46546 7.48396 4.578 7.53116 4.6688 7.59572C4.7599 7.6605 4.8395 7.7401 4.90428 7.8312C4.96884 7.922 5.01604 8.03454 5.16624 8.42506L6.03333 10.6795C6.1076 10.8726 6.29311 11 6.5 11C6.70689 11 6.89241 10.8726 6.96667 10.6795L7.83376 8.42506C7.98396 8.03454 8.03116 7.922 8.09572 7.8312C8.1605 7.7401 8.2401 7.6605 8.3312 7.59572C8.422 7.53116 8.53454 7.48396 8.92506 7.33376L11.1795 6.46667C11.3726 6.39241 11.5 6.20689 11.5 6C11.5 5.79311 11.3726 5.60759 11.1795 5.53333L8.92506 4.66624C8.53454 4.51604 8.422 4.46884 8.3312 4.40428C8.2401 4.3395 8.1605 4.2599 8.09572 4.1688C8.03116 4.078 7.98396 3.96546 7.83376 3.57494L6.96667 1.32051Z" fill="#444CE7" />
+ </svg>
+)
+
+export const ChatBtn: FC<{ onClick: () => void, className?: string }> = ({
+ className,
+ onClick
+}) => {
+ const { t } = useTranslation()
+ return (
+ <Button
+ type='primary'
+ className={cn(className, `space-x-2 flex items-center ${s.customBtn}`)}
+ onClick={onClick}>
+ <svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fillRule="evenodd" clipRule="evenodd" d="M18 10.5C18 14.366 14.418 17.5 10 17.5C8.58005 17.506 7.17955 17.1698 5.917 16.52L2 17.5L3.338 14.377C2.493 13.267 2 11.934 2 10.5C2 6.634 5.582 3.5 10 3.5C14.418 3.5 18 6.634 18 10.5ZM7 9.5H5V11.5H7V9.5ZM15 9.5H13V11.5H15V9.5ZM9 9.5H11V11.5H9V9.5Z" fill="white" />
+ </svg>
+ {t('share.chat.startChat')}
+ </Button>
+ )
+}
+
+export const EditBtn = ({ className, onClick }: { className?: string, onClick: () => void }) => {
+ const { t } = useTranslation()
+
+ return (
+ <div
+ className={cn('px-2 flex space-x-1 items-center rounded-md cursor-pointer', className)}
+ onClick={onClick}
+ >
+ <PencilIcon className='w-3 h-3' />
+ <span>{t('common.operation.edit')}</span>
+ </div>
+ )
+}
+
+export const FootLogo = () => (
+ <div className={s.logo} />
+)
+
diff --git a/web/app/components/share/chat/welcome/style.module.css b/web/app/components/share/chat/welcome/style.module.css
new file mode 100644
index 00000000000..b007bf23a01
--- /dev/null
+++ b/web/app/components/share/chat/welcome/style.module.css
@@ -0,0 +1,29 @@
+.boxShodow {
+ box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
+}
+
+.bgGrayColor {
+ background-color: #F9FAFB;
+}
+
+.headerBg {
+ height: 3.5rem;
+ padding-left: 1.5rem;
+ padding-right: 1.5rem;
+}
+
+.formLabel {
+ width: 120px;
+ margin-right: 8px;
+}
+
+.customBtn {
+ width: 136px;
+}
+
+.logo {
+ width: 48px;
+ height: 20px;
+ background: url(./icons/logo.png) center center no-repeat;
+ background-size: contain;
+}
\ No newline at end of file
diff --git a/web/app/components/share/header.tsx b/web/app/components/share/header.tsx
new file mode 100644
index 00000000000..0ad2247d2f2
--- /dev/null
+++ b/web/app/components/share/header.tsx
@@ -0,0 +1,44 @@
+import type { FC } from 'react'
+import React from 'react'
+import AppIcon from '@/app/components/base/app-icon'
+import {
+ Bars3Icon,
+ PencilSquareIcon,
+} from '@heroicons/react/24/solid'
+export type IHeaderProps = {
+ title: string
+ isMobile?: boolean
+ onShowSideBar?: () => void
+ onCreateNewChat?: () => void
+}
+const Header: FC<IHeaderProps> = ({
+ title,
+ isMobile,
+ onShowSideBar,
+ onCreateNewChat,
+}) => {
+ return (
+ <div className="shrink-0 flex items-center justify-between h-12 px-3 bg-gray-100">
+ {isMobile ? (
+ <div
+ className='flex items-center justify-center h-8 w-8 cursor-pointer'
+ onClick={() => onShowSideBar?.()}
+ >
+ <Bars3Icon className="h-4 w-4 text-gray-500" />
+ </div>
+ ) : <div></div>}
+ <div className='flex items-center space-x-2'>
+ <AppIcon size="small" />
+ <div className=" text-sm text-gray-800 font-bold">{title}</div>
+ </div>
+ {isMobile ? (
+ <div className='flex items-center justify-center h-8 w-8 cursor-pointer'
+ onClick={() => onCreateNewChat?.()}
+ >
+ <PencilSquareIcon className="h-4 w-4 text-gray-500" />
+ </div>) : <div></div>}
+ </div>
+ )
+}
+
+export default React.memo(Header)
diff --git a/web/app/components/share/text-generation/config-scence/index.tsx b/web/app/components/share/text-generation/config-scence/index.tsx
new file mode 100644
index 00000000000..5c5681e4a81
--- /dev/null
+++ b/web/app/components/share/text-generation/config-scence/index.tsx
@@ -0,0 +1,100 @@
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ PlayIcon,
+} from '@heroicons/react/24/solid'
+import Select from '@/app/components/base/select'
+import type { SiteInfo } from '@/models/share'
+import type { PromptConfig } from '@/models/debug'
+import Button from '@/app/components/base/button'
+import { DEFAULT_VALUE_MAX_LEN } from '@/config'
+
+export type IConfigSenceProps = {
+ siteInfo: SiteInfo
+ promptConfig: PromptConfig
+ inputs: Record<string, any>
+ onInputsChange: (inputs: Record<string, any>) => void
+ query: string
+ onQueryChange: (query: string) => void
+ onSend: () => void
+}
+const ConfigSence: FC<IConfigSenceProps> = ({
+ promptConfig,
+ inputs,
+ onInputsChange,
+ query,
+ onQueryChange,
+ onSend,
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="">
+ <section>
+ {/* input form */}
+ <form>
+ {promptConfig.prompt_variables.map(item => (
+ <div className='w-full mt-4' key={item.key}>
+ <label className='text-gray-900 text-sm font-medium'>{item.name}</label>
+ <div className='mt-2'>
+ {item.type === 'select' ? (
+ <Select
+ className='w-full'
+ defaultValue={inputs[item.key]}
+ onSelect={(i) => { onInputsChange({ ...inputs, [item.key]: i.value }) }}
+ items={(item.options || []).map(i => ({ name: i, value: i }))}
+ allowSearch={false}
+ bgClassName='bg-gray-50'
+ />
+ ) : (
+ <input
+ type="text"
+ className="block w-full p-2 text-gray-900 border border-gray-300 rounded-lg bg-gray-50 sm:text-xs focus:ring-blue-500 focus:border-blue-500 "
+ placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
+ value={inputs[item.key]}
+ onChange={(e) => { onInputsChange({ ...inputs, [item.key]: e.target.value }) }}
+ maxLength={item.max_length || DEFAULT_VALUE_MAX_LEN}
+ />
+ )}
+ </div>
+ </div>
+ ))}
+
+ <div className='mt-6 h-[1px] bg-gray-100'></div>
+ <div className='w-full mt-5'>
+ <label className='text-gray-900 text-sm font-medium'>{t('share.generation.queryTitle')}</label>
+ <div className="mt-2 overflow-hidden rounded-lg bg-gray-50 ">
+ <div className="px-4 py-2 bg-gray-50 rounded-t-lg">
+ <textarea
+ value={query}
+ onChange={(e) => { onQueryChange(e.target.value) }}
+ rows={4}
+ className="w-full px-0 text-sm text-gray-900 border-0 bg-gray-50 focus:outline-none placeholder:bg-gray-50"
+ placeholder={t('share.generation.queryPlaceholder') as string}
+ required
+ >
+ </textarea>
+ </div>
+ <div className="flex items-center justify-between px-3 py-2">
+ <div className="flex pl-0 space-x-1 sm:pl-2">
+ <span className="bg-gray-100 text-gray-500 text-xs font-medium mr-2 px-2.5 py-0.5 rounded cursor-pointer">{query?.length}</span>
+ </div>
+ <Button
+ type="primary"
+ className='w-[80px] !h-8'
+ onClick={onSend}
+ disabled={!query || query === ''}
+ >
+ <PlayIcon className="shrink-0 w-4 h-4 mr-1" aria-hidden="true" />
+ <span className='uppercase text-[13px]'>{t('share.generation.run')}</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </form>
+ </section>
+ </div>
+ )
+}
+export default React.memo(ConfigSence)
diff --git a/web/app/components/share/text-generation/history/index.tsx b/web/app/components/share/text-generation/history/index.tsx
new file mode 100644
index 00000000000..a100c98a177
--- /dev/null
+++ b/web/app/components/share/text-generation/history/index.tsx
@@ -0,0 +1,79 @@
+'use client'
+import React, { useState } from 'react'
+import useSWR from 'swr'
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+} from '@heroicons/react/24/outline'
+import { fetchHistories } from '@/models/history'
+import type { History as HistoryItem } from '@/models/history'
+import Loading from '@/app/components/base/loading'
+import { mockAPI } from '@/test/test_util'
+
+mockAPI()
+
+export type IHistoryProps = {
+ dictionary: any
+}
+
+const HistoryCard = (
+ { history }: { history: HistoryItem },
+) => {
+ return (
+ <div className='p-4 h-32 bg-gray-50 border-gray-200 rounded-lg relative flex flex-col justify-between items-center cursor-pointer'>
+ <div className='text-gray-700 text-sm'>
+ {history.source}
+ </div>
+ <div className="absolute inset-0 flex items-center m-4" aria-hidden="true">
+ <div className="w-full border-t border-gray-100" />
+ </div>
+ <div className='text-gray-700 text-sm'>
+ {history.target}
+ </div>
+ </div>
+ )
+}
+
+const History = ({
+ dictionary,
+}: IHistoryProps) => {
+ const { data, error } = useSWR('http://localhost:3000/api/histories', fetchHistories)
+ const [showHistory, setShowHistory] = useState(false)
+
+ const DivideLine = () => {
+ return <div className="mt-6 relative">
+ {/* divider line */}
+ <div className="absolute inset-0 flex items-center" aria-hidden="true">
+ <div className="w-full border-t border-gray-300" />
+ </div>
+ <div className="relative flex justify-center flex-col items-center">
+ {!showHistory ? <ChevronUpIcon className="h-3 w-3 text-gray-500" aria-hidden="true" /> : <div className='h-3 w-3' />}
+ <span className="px-2 bg-white text-sm font-medium text-gray-600 cursor-pointer">{dictionary.app.textGeneration.history}</span>
+ {!showHistory ? <div className='h-3 w-3' /> : <ChevronDownIcon className="h-3 w-3 text-gray-500" aria-hidden="true" />}
+ </div>
+ </div>
+ }
+
+ if (error)
+ return <div>failed to load</div>
+ if (!data)
+ return <Loading />
+ return showHistory
+ ? <div className='w-1/2 block fixed bottom-0 right-0 px-10 py-4' onClick={
+ () => setShowHistory(v => !v)
+ }>
+ <DivideLine />
+ <div
+ className='mt-4 grid grid-cols-3 space-x-4 h-[400px] overflow-auto'
+ >
+ {data.histories.map((item: HistoryItem) =>
+ <HistoryCard key={item.id} history={item} />)}
+ </div>
+ </div>
+ : <div className='w-1/2 block fixed bottom-0 right-0 px-10 py-4' onClick={
+ () => setShowHistory(true)
+ }>
+ <DivideLine />
+ </div>
+}
+export default History
diff --git a/web/app/components/share/text-generation/icons/app-icon.svg b/web/app/components/share/text-generation/icons/app-icon.svg
new file mode 100644
index 00000000000..209299b5820
--- /dev/null
+++ b/web/app/components/share/text-generation/icons/app-icon.svg
@@ -0,0 +1,22 @@
+<svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+<g filter="url(#filter0_d_3468_34550)">
+<rect x="2" y="1" width="32" height="32" rx="8" fill="#FFE4E8"/>
+<path d="M9 26.26H27V8.26H9V26.26Z" fill="url(#pattern0)"/>
+<rect x="2.25" y="1.25" width="31.5" height="31.5" rx="7.75" stroke="black" stroke-opacity="0.05" stroke-width="0.5"/>
+</g>
+<defs>
+<filter id="filter0_d_3468_34550" x="0" y="0" width="36" height="36" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0.0627451 0 0 0 0 0.0941176 0 0 0 0 0.156863 0 0 0 0.05 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_3468_34550"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_3468_34550" result="shape"/>
+</filter>
+<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
+<use xlink:href="#image0_3468_34550" transform="scale(0.00625)"/>
+</pattern>
+<image id="image0_3468_34550" width="160" height="160" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAYAAACLz2ctAABK4UlEQVR4nO29ebBl21kf9lvDns54z+3b0+t+3f0GvaenAYkYEALZEGxCxYkiTCAEKIINTqriuMjgYIwdCMaYOJYHUqaSOKlghsJF7FRcioMhKjtFkIOEJhCW9CQkvQm916+ne++Z995ryh9rrb3X3ufc4b13bt/OVX9dp+85e1x77d/+5u/bBA/pWPRLz7w5nkq5k1J2OaJ0JwKG5+I4BkDuClFqYCK1vvcH8/nNN/d6dwDkpz3mB52+/9ln30zMaY/iAaa/88QTj7250/3aUsl37UTRW/uMPs4MLnAggzGx304DMISUwpi8AO4KY56/p/SzE60+OpHyYwA+d3pX8WAT+bmnnjrtMTxQFBn0e4x96/k4+vYdxv7oAORGDAOjNLTRMFoDcKAzBuEDbAgBoRQGgKEUJSFYELxyW6r/9+Wy/MBtIT4I4M4pXNYDS+SvPv74aY/hgaARIVtbcfxdb07T/+AcId8Qa021UpBawxgDGA1jAIs4AzjwGWMAQuBXaUIAWICCUhBKQRhDSSluG/PJW0r9yq4QvwrgldO50geLyM8+/fRpj+HUaUTIdz6Vpv/ZZca+kUoJJSW01rBAA2BM8AFAUAMQze8GBJoY95dYTkkJQCgo55CcYxf4vU8vl3/v96fTXwYgTumyHwgiP/jII6c9hlOjr+p0nviqbvcvX+f8T0dSUikFoC3QiHHC1RgQD8SAGsBz2+oAiJqQ6rcmFJoAilIYaoGYc46XlPrff3s8/ikAn7pf1/ygEfnha9dOewynQk8lybe9q997/yWQt8uyhFYKxAAEBgQAMQYExHI7ACDEgpIQCzwDJ5adODam1gsd8BQCMAJQhNgPJQBloHGM25Q+/8n5/L8C8A9PZSJOmfiFJDntMdx3usbYf/xHut2/PlBqVJYFiDGgxoACICAgBCCUWtC5D5xuZ6VvDToYA6MUjDGgWlcg1G5b7bgpccC1ACZQ2kBojZ0oeuzrO51/8CohjwP46VOblFM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Ut2BE2wNW/YCsvzKw4/CfE6pv1Zc4T2diFrCw5tGphBfRQg5HL1ygAcB5Jnu/66Wtv7ut6GfDZYLTMF2s9PPdA119NYD1RPtPdOuDSr6WQ8e+G5L/wpAP/8kIvYOJFNNSl/LTQ6t/OdV65e/5/6/cHI95KpRct6Vfw4inq47ZHbvV5F61gHX3eCQ074WpTLtfuu4eoIHpTgp3/QfV9rIQWmk0n5yst/+BcA/NwxzrhRIhcu3D8R3DgxIX/y0uUrP7M12n5HHNku8NUUtnQ0L3UaAG30dSGNHcM2taHY8RylfZxqX7jdHNet9TV3nqY62WTKr+kROR6OD637eANktIFUEmVZYDLe/9Kd27d+CsAvbfxExyBy6dKV0zgvAEBrfa3T6/3AcLj13jRNn6GE9RpSKdi28SCHkgmtjQ6RUu2NSSXe10s00zqe3S5UC1onDX+bNevW7mNaOkLzYar/mODBbIwy0CUDnaM9CYHarKRc5Hn+pcl0/M+m4/1fArCxGo/XSsQAbwbwudMaAABceuTKiBH2Fh7FVzlnMansyDX6T2tGSbC+LW3MmiWeo4VHam8BU1vXTeAHKbRVxyuycr8b2wYGEwFcM6U1qCCt39W+q9poY3wNq8Zt1xhQQ2IQKaUoivxVrfSzADbzjo43QP8fgoHC7+OrrPcAAAAASUVORK5CYII="/>
+</defs>
+</svg>
diff --git a/web/app/components/share/text-generation/icons/star.svg b/web/app/components/share/text-generation/icons/star.svg
new file mode 100644
index 00000000000..e86a14285e4
--- /dev/null
+++ b/web/app/components/share/text-generation/icons/star.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M3.66699 1.33366C3.66699 0.965469 3.36852 0.666992 3.00033 0.666992C2.63214 0.666992 2.33366 0.965469 2.33366 1.33366V2.33366H1.33366C0.965469 2.33366 0.666992 2.63214 0.666992 3.00033C0.666992 3.36852 0.965469 3.66699 1.33366 3.66699H2.33366V4.66699C2.33366 5.03518 2.63214 5.33366 3.00033 5.33366C3.36852 5.33366 3.66699 5.03518 3.66699 4.66699V3.66699H4.66699C5.03518 3.66699 5.33366 3.36852 5.33366 3.00033C5.33366 2.63214 5.03518 2.33366 4.66699 2.33366H3.66699V1.33366Z" fill="#444CE7"/>
+<path d="M3.66699 11.3337C3.66699 10.9655 3.36852 10.667 3.00033 10.667C2.63214 10.667 2.33366 10.9655 2.33366 11.3337V12.3337H1.33366C0.965469 12.3337 0.666992 12.6321 0.666992 13.0003C0.666992 13.3685 0.965469 13.667 1.33366 13.667H2.33366V14.667C2.33366 15.0352 2.63214 15.3337 3.00033 15.3337C3.36852 15.3337 3.66699 15.0352 3.66699 14.667V13.667H4.66699C5.03518 13.667 5.33366 13.3685 5.33366 13.0003C5.33366 12.6321 5.03518 12.3337 4.66699 12.3337H3.66699V11.3337Z" fill="#444CE7"/>
+<path d="M9.28922 1.76101C9.1902 1.50354 8.94284 1.33366 8.66699 1.33366C8.39114 1.33366 8.14378 1.50354 8.04476 1.76101L6.88864 4.76691C6.68837 5.28761 6.62544 5.43766 6.53936 5.55872C6.45299 5.68019 6.34686 5.78632 6.22539 5.87269C6.10432 5.95878 5.95428 6.02171 5.43358 6.22198L2.42767 7.37809C2.17021 7.47712 2.00033 7.72448 2.00033 8.00033C2.00033 8.27617 2.17021 8.52353 2.42767 8.62256L5.43358 9.77867C5.95428 9.97894 6.10432 10.0419 6.22539 10.128C6.34686 10.2143 6.45299 10.3205 6.53936 10.4419C6.62544 10.563 6.68837 10.713 6.88864 11.2337L8.04476 14.2396C8.14379 14.4971 8.39114 14.667 8.66699 14.667C8.94284 14.667 9.1902 14.4971 9.28922 14.2396L10.4453 11.2337C10.6456 10.713 10.7085 10.563 10.7946 10.4419C10.881 10.3205 10.9871 10.2143 11.1086 10.128C11.2297 10.0419 11.3797 9.97894 11.9004 9.77867L14.9063 8.62256C15.1638 8.52353 15.3337 8.27617 15.3337 8.00033C15.3337 7.72448 15.1638 7.47712 14.9063 7.37809L11.9004 6.22198C11.3797 6.02171 11.2297 5.95878 11.1086 5.87269C10.9871 5.78632 10.881 5.68019 10.7946 5.55872C10.7085 5.43766 10.6456 5.28761 10.4453 4.76691L9.28922 1.76101Z" fill="#444CE7"/>
+</svg>
diff --git a/web/app/components/share/text-generation/index.tsx b/web/app/components/share/text-generation/index.tsx
new file mode 100644
index 00000000000..011143ed726
--- /dev/null
+++ b/web/app/components/share/text-generation/index.tsx
@@ -0,0 +1,349 @@
+'use client'
+import React, { useEffect, useState, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
+import cn from 'classnames'
+import { useBoolean, useClickAway } from 'ahooks'
+import { useContext } from 'use-context-selector'
+import ConfigScence from '@/app/components/share/text-generation/config-scence'
+import NoData from '@/app/components/share/text-generation/no-data'
+// import History from '@/app/components/share/text-generation/history'
+import { fetchAppInfo, fetchAppParams, sendCompletionMessage, updateFeedback, saveMessage, fetchSavedMessage as doFetchSavedMessage, removeMessage } from '@/service/share'
+import type { SiteInfo } from '@/models/share'
+import type { PromptConfig, MoreLikeThisConfig, SavedMessage } from '@/models/debug'
+import Toast from '@/app/components/base/toast'
+import { Feedbacktype } from '@/app/components/app/chat'
+import { changeLanguage } from '@/i18n/i18next-config'
+import Loading from '@/app/components/base/loading'
+import { userInputsFormToPromptVariables } from '@/utils/model-config'
+import TextGenerationRes from '@/app/components/app/text-generate/item'
+import SavedItems from '@/app/components/app/text-generate/saved-items'
+import TabHeader from '../../base/tab-header'
+import { XMarkIcon } from '@heroicons/react/24/outline'
+import s from './style.module.css'
+import Button from '../../base/button'
+
+const TextGeneration = () => {
+ const { t } = useTranslation()
+ const media = useBreakpoints()
+ const isPC = media === MediaType.pc
+ const isTablet = media === MediaType.tablet
+ const isMoble = media === MediaType.mobile
+
+ const [currTab, setCurrTab] = useState<string>('create')
+
+ const [inputs, setInputs] = useState<Record<string, any>>({})
+ const [appId, setAppId] = useState<string>('')
+ const [siteInfo, setSiteInfo] = useState<SiteInfo | null>(null)
+ const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
+ const [moreLikeThisConifg, setMoreLikeThisConifg] = useState<MoreLikeThisConfig | null>(null)
+ const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
+ const [query, setQuery] = useState('')
+ const [completionRes, setCompletionRes] = useState('')
+ const { notify } = Toast
+ const isNoData = !completionRes
+
+ const [messageId, setMessageId] = useState<string | null>(null)
+ const [feedback, setFeedback] = useState<Feedbacktype>({
+ rating: null
+ })
+
+ const handleFeedback = async (feedback: Feedbacktype) => {
+ await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } })
+ setFeedback(feedback)
+ }
+
+ const [savedMessages, setSavedMessages] = useState<SavedMessage[]>([])
+
+ const fetchSavedMessage = async () => {
+ const res: any = await doFetchSavedMessage()
+ setSavedMessages(res.data)
+ }
+
+ useEffect(() => {
+ fetchSavedMessage()
+ }, [])
+
+ const handleSaveMessage = async (messageId: string) => {
+ await saveMessage(messageId)
+ notify({ type: 'success', message: t('common.api.saved') })
+ fetchSavedMessage()
+ }
+
+ const handleRemoveSavedMessage = async (messageId: string) => {
+ await removeMessage(messageId)
+ notify({ type: 'success', message: t('common.api.remove') })
+ fetchSavedMessage()
+ }
+
+ const logError = (message: string) => {
+ notify({ type: 'error', message })
+ }
+
+ const checkCanSend = () => {
+ const prompt_variables = promptConfig?.prompt_variables
+ if (!prompt_variables || prompt_variables?.length === 0) {
+ return true
+ }
+ let hasEmptyInput = false
+ const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
+ const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
+ return res
+ }) || [] // compatible with old version
+ requiredVars.forEach(({ key }) => {
+ if (hasEmptyInput) {
+ return
+ }
+ if (!inputs[key]) {
+ hasEmptyInput = true
+ }
+ })
+
+ if (hasEmptyInput) {
+ logError(t('appDebug.errorMessage.valueOfVarRequired'))
+ return false
+ }
+ return !hasEmptyInput
+ }
+
+ const handleSend = async () => {
+ if (isResponsing) {
+ notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
+ return false
+ }
+
+ if (!checkCanSend())
+ return
+
+ if (!query) {
+ logError(t('appDebug.errorMessage.queryRequired'))
+ return false
+ }
+
+ const data = {
+ inputs,
+ query,
+ }
+
+ setMessageId(null)
+ setFeedback({
+ rating: null
+ })
+ setCompletionRes('')
+
+ const res: string[] = []
+ let tempMessageId = ''
+
+ if (!isPC) {
+ showResSidebar()
+ }
+ setResponsingTrue()
+ sendCompletionMessage(data, {
+ onData: (data: string, _isFirstMessage: boolean, { messageId }: any) => {
+ tempMessageId = messageId
+ res.push(data)
+ setCompletionRes(res.join(''))
+ },
+ onCompleted: () => {
+ setResponsingFalse()
+ setMessageId(tempMessageId)
+ },
+ onError() {
+ setResponsingFalse()
+ }
+ })
+ }
+
+ useEffect(() => {
+ (async () => {
+ const [appData, appParams]: any = await Promise.all([fetchAppInfo(), fetchAppParams()])
+ const { app_id: appId, site: siteInfo } = appData
+ setAppId(appId)
+ setSiteInfo(siteInfo as SiteInfo)
+ changeLanguage(siteInfo.default_language)
+
+ const { user_input_form, more_like_this }: any = appParams
+ const prompt_variables = userInputsFormToPromptVariables(user_input_form)
+ setPromptConfig({
+ prompt_template: '', // placeholder for feture
+ prompt_variables,
+ } as PromptConfig)
+ setMoreLikeThisConifg(more_like_this)
+ })()
+ }, [])
+
+ // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
+ useEffect(() => {
+ if (siteInfo?.title)
+ document.title = `${siteInfo.title} - Powered by Dify`
+ }, [siteInfo?.title])
+
+ const [isShowResSidebar, { setTrue: showResSidebar, setFalse: hideResSidebar }] = useBoolean(false)
+ const resRef = useRef<HTMLDivElement>(null)
+ useClickAway(() => {
+ hideResSidebar();
+ }, resRef)
+
+ const renderRes = (
+ <div
+ ref={resRef}
+ className={
+ cn("flex flex-col h-full shrink-0",
+ isPC ? 'px-10 py-8' : 'bg-gray-50',
+ isTablet && 'p-6', isMoble && 'p-4')}
+ >
+ <>
+ <div className='shrink-0 flex items-center justify-between'>
+ <div className='flex items-center space-x-3'>
+ <div className={s.starIcon}></div>
+ <div className='text-lg text-gray-800 font-semibold'>{t('share.generation.title')}</div>
+ </div>
+ {!isPC && (
+ <div
+ className='flex items-center justify-center cursor-pointer'
+ onClick={hideResSidebar}
+ >
+ <XMarkIcon className='w-4 h-4 text-gray-800' />
+ </div>
+ )}
+ </div>
+
+ <div className='grow'>
+ {(isResponsing && !completionRes) ? (
+ <div className='flex h-full w-full justify-center items-center'>
+ <Loading type='area' />
+ </div>) : (
+ <>
+ {isNoData
+ ? <NoData />
+ : (
+ <TextGenerationRes
+ className='mt-3'
+ content={completionRes}
+ messageId={messageId}
+ isInWebApp
+ moreLikeThis={moreLikeThisConifg?.enabled}
+ onFeedback={handleFeedback}
+ feedback={feedback}
+ onSave={handleSaveMessage}
+ isMobile={isMoble}
+ />
+ )
+ }
+ </>
+ )}
+ </div>
+ </>
+ </div>
+ )
+
+ if (!appId || !siteInfo || !promptConfig)
+ return <Loading type='app' />
+
+
+ return (
+ <>
+ <div className={cn(isPC && 'flex', 'h-screen bg-gray-50')}>
+ {/* Left */}
+ <div className={cn(isPC ? 'w-[600px] max-w-[50%] p-8' : 'p-4', "shrink-0 relative flex flex-col pb-10 h-full border-r border-gray-100 bg-white")}>
+ <div className='mb-6'>
+ <div className='flex justify-between items-center'>
+ <div className='flex items-center space-x-3'>
+ <div className={cn(s.appIcon, 'shrink-0')}></div>
+ <div className='text-lg text-gray-800 font-semibold'>{siteInfo.title}</div>
+ </div>
+ {!isPC && (
+ <Button
+ className='shrink-0 !h-8 !px-3 ml-2'
+ onClick={showResSidebar}
+ >
+ <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
+ <div className={s.starIcon}></div>
+ <span>{t('share.generation.title')}</span>
+ </div>
+ </Button>
+ )}
+ </div>
+ {siteInfo.description && (
+ <div className='mt-2 text-xs text-gray-500'>{siteInfo.description}</div>
+ )}
+ </div>
+ <TabHeader
+ items={[
+ { id: 'create', name: t('share.generation.tabs.create') },
+ {
+ id: 'saved', name: t('share.generation.tabs.saved'), extra: savedMessages.length > 0 ? (
+ <div className='ml-1 flext items-center h-5 px-1.5 rounded-md border border-gray-200 text-gray-500 text-xs font-medium'>
+ {savedMessages.length}
+ </div>
+ ) : null
+ }
+ ]}
+ value={currTab}
+ onChange={setCurrTab}
+ />
+ <div className='grow h-20 overflow-y-auto'>
+ {currTab === 'create' && (
+ <ConfigScence
+ siteInfo={siteInfo}
+ inputs={inputs}
+ onInputsChange={setInputs}
+ promptConfig={promptConfig}
+ query={query}
+ onQueryChange={setQuery}
+ onSend={handleSend}
+ />
+ )}
+
+ {currTab === 'saved' && (
+ <SavedItems
+ className='mt-4'
+ list={savedMessages}
+ onRemove={handleRemoveSavedMessage}
+ onStartCreateContent={() => setCurrTab('create')}
+ />
+ )}
+ </div>
+
+
+ {/* copyright */}
+ <div className='fixed left-8 bottom-4 flex space-x-2 text-gray-400 font-normal text-xs'>
+ <div className="">© {siteInfo.copyright || siteInfo.title} {(new Date()).getFullYear()}</div>
+ {siteInfo.privacy_policy && (
+ <>
+ <div>·</div>
+ <div>{t('share.chat.privacyPolicyLeft')}
+ <a
+ className='text-gray-500'
+ href={siteInfo.privacy_policy}
+ target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
+ {t('share.chat.privacyPolicyRight')}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Result */}
+ {isPC && (
+ <div className='grow h-full'>
+ {renderRes}
+ </div>
+ )}
+
+ {(!isPC && isShowResSidebar) && (
+ <div
+ className={cn('fixed z-50 inset-0', isTablet ? 'pl-[128px]' : 'pl-6')}
+ style={{
+ background: 'rgba(35, 56, 118, 0.2)'
+ }}
+ >
+ {renderRes}
+ </div>
+ )}
+ </div>
+ </>
+ )
+}
+
+export default TextGeneration
diff --git a/web/app/components/share/text-generation/no-data/index.tsx b/web/app/components/share/text-generation/no-data/index.tsx
new file mode 100644
index 00000000000..7492614131e
--- /dev/null
+++ b/web/app/components/share/text-generation/no-data/index.tsx
@@ -0,0 +1,26 @@
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+
+const StarIcon = (
+ <svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M7.50033 48.3337V36.667M7.50033 13.3337V1.66699M1.66699 7.50033H13.3337M1.66699 42.5003H13.3337M27.3337 4.00032L23.2872 14.521C22.6292 16.2319 22.3002 17.0873 21.7886 17.8069C21.3351 18.4446 20.7779 19.0018 20.1402 19.4552C19.4206 19.9669 18.5652 20.2959 16.8543 20.9539L6.33366 25.0003L16.8543 29.0467C18.5652 29.7048 19.4206 30.0338 20.1402 30.5454C20.7779 30.9989 21.3351 31.5561 21.7886 32.1938C22.3002 32.9133 22.6292 33.7688 23.2872 35.4796L27.3337 46.0003L31.3801 35.4796C32.0381 33.7688 32.3671 32.9133 32.8788 32.1938C33.3322 31.5561 33.8894 30.9989 34.5271 30.5454C35.2467 30.0338 36.1021 29.7048 37.813 29.0467L48.3337 25.0003L37.813 20.9539C36.1021 20.2959 35.2467 19.9669 34.5271 19.4552C33.8894 19.0018 33.3322 18.4446 32.8788 17.8069C32.3671 17.0873 32.0381 16.2319 31.3801 14.521L27.3337 4.00032Z" stroke="#EAECF0" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+
+)
+
+export type INoDataProps = {}
+const NoData: FC<INoDataProps> = () => {
+ const { t } = useTranslation()
+ return (
+ <div className='flex flex-col h-full w-full justify-center items-center'>
+ {StarIcon}
+ <div
+ className='mt-3 text-gray-300 text-xs leading-3'
+ >
+ {t('share.generation.noData')}
+ </div>
+ </div>
+ )
+}
+export default React.memo(NoData)
diff --git a/web/app/components/share/text-generation/result/header.tsx b/web/app/components/share/text-generation/result/header.tsx
new file mode 100644
index 00000000000..09393344b5a
--- /dev/null
+++ b/web/app/components/share/text-generation/result/header.tsx
@@ -0,0 +1,116 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import { ClipboardDocumentIcon, HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
+import { Feedbacktype } from '@/app/components/app/chat'
+import Button from '@/app/components/base/button'
+import Toast from '@/app/components/base/toast'
+import Tooltip from '@/app/components/base/tooltip'
+
+// import useCopyToClipboard from '@/hooks/use-copy-to-clipboard'
+import copy from 'copy-to-clipboard'
+type IResultHeaderProps = {
+ result: string
+ showFeedback: boolean
+ feedback: Feedbacktype
+ onFeedback: (feedback: Feedbacktype) => void
+}
+
+const Header: FC<IResultHeaderProps> = ({
+ feedback,
+ showFeedback,
+ onFeedback,
+ result,
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div className='flex w-full justify-between items-center '>
+ <div className='text-gray-800 text-2xl leading-4 font-normal'>{t('share.generation.resultTitle')}</div>
+ <div className='flex items-center space-x-2'>
+ <Button
+ className='flex items-center !h-7 !p-[2px] !pr-2'
+ onClick={() => {
+ copy(result)
+ Toast.notify({ type: 'success', message: 'copied' })
+ }}
+ >
+ <>
+ <ClipboardDocumentIcon className='text-gray-500 w-4 h-3 mr-1' />
+ <span className='text-gray-500 text-xs leading-3'>{t('share.generation.copy')}</span>
+ </>
+ </Button>
+
+ {showFeedback && feedback.rating && feedback.rating === 'like' && (
+ <Tooltip
+ selector="undo-feedback-like"
+ content="Undo Great Rating"
+ >
+ <div
+ onClick={() => {
+ onFeedback({
+ rating: null
+ })
+ }}
+ className='flex w-7 h-7 items-center justify-center rounded-md cursor-pointer !text-primary-600 border border-primary-200 bg-primary-100 hover:border-primary-300 hover:bg-primary-200'>
+ <HandThumbUpIcon width={16} height={16} />
+ </div>
+ </Tooltip>
+ )}
+
+ {showFeedback && feedback.rating && feedback.rating === 'dislike' && (
+ <Tooltip
+ selector="undo-feedback-dislike"
+ content="Undo Undesirable Response"
+ >
+ <div
+ onClick={() => {
+ onFeedback({
+ rating: null
+ })
+ }}
+ className='flex w-7 h-7 items-center justify-center rounded-md cursor-pointer !text-red-600 border border-red-200 bg-red-100 hover:border-red-300 hover:bg-red-200'>
+ <HandThumbDownIcon width={16} height={16} />
+ </div>
+ </Tooltip>
+ )}
+
+ {showFeedback && !feedback.rating && (
+ <div className='flex rounded-lg border border-gray-200 p-[1px] space-x-1'>
+ <Tooltip
+ selector="feedback-like"
+ content="Great Rating"
+ >
+ <div
+ onClick={() => {
+ onFeedback({
+ rating: 'like'
+ })
+ }}
+ className='flex w-6 h-6 items-center justify-center rounded-md cursor-pointer hover:bg-gray-100'>
+ <HandThumbUpIcon width={16} height={16} />
+ </div>
+ </Tooltip>
+ <Tooltip
+ selector="feedback-dislike"
+ content="Undesirable Response"
+ >
+ <div
+ onClick={() => {
+ onFeedback({
+ rating: 'dislike'
+ })
+ }}
+ className='flex w-6 h-6 items-center justify-center rounded-md cursor-pointer hover:bg-gray-100'>
+ <HandThumbDownIcon width={16} height={16} />
+ </div>
+ </Tooltip>
+ </div>
+ )}
+ </div>
+
+ </div>
+ )
+}
+
+export default React.memo(Header)
diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsx
new file mode 100644
index 00000000000..2e5ecf4af19
--- /dev/null
+++ b/web/app/components/share/text-generation/result/index.tsx
@@ -0,0 +1,34 @@
+import type { FC } from 'react'
+import React from 'react'
+import Header from './header'
+import { Feedbacktype } from '@/app/components/app/chat'
+import { format } from '@/service/base'
+
+export type IResultProps = {
+ content: string
+ showFeedback: boolean
+ feedback: Feedbacktype
+ onFeedback: (feedback: Feedbacktype) => void
+}
+const Result: FC<IResultProps> = ({
+ content,
+ showFeedback,
+ feedback,
+ onFeedback
+}) => {
+ return (
+ <div className='basis-3/4 h-max'>
+ <Header result={content} showFeedback={showFeedback} feedback={feedback} onFeedback={onFeedback} />
+ <div
+ className='mt-4 w-full flex text-sm leading-5 overflow-scroll font-normal text-gray-900'
+ style={{
+ maxHeight: '70vh'
+ }}
+ dangerouslySetInnerHTML={{
+ __html: format(content)
+ }}
+ ></div>
+ </div>
+ )
+}
+export default React.memo(Result)
diff --git a/web/app/components/share/text-generation/style.module.css b/web/app/components/share/text-generation/style.module.css
new file mode 100644
index 00000000000..60376aa1af6
--- /dev/null
+++ b/web/app/components/share/text-generation/style.module.css
@@ -0,0 +1,13 @@
+.appIcon {
+ width: 32px;
+ height: 32px;
+ background: url(./icons/app-icon.svg) center center no-repeat;
+ background-size: contain;
+}
+
+.starIcon {
+ width: 16px;
+ height: 16px;
+ background: url(./icons/star.svg) center center no-repeat;
+ background-size: contain;
+}
\ No newline at end of file
diff --git a/web/app/components/with-i18n.tsx b/web/app/components/with-i18n.tsx
new file mode 100644
index 00000000000..b06024d51ca
--- /dev/null
+++ b/web/app/components/with-i18n.tsx
@@ -0,0 +1,20 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { useContext } from 'use-context-selector'
+import I18NContext from '@/context/i18n'
+
+export type II18NHocProps = {
+ children: ReactNode
+}
+
+const withI18N = (Component: any) => {
+ return (props: any) => {
+ const { i18n } = useContext(I18NContext)
+ return (
+ <Component {...props} i18n={i18n} />
+ )
+ }
+}
+
+export default withI18N
diff --git a/web/app/install/installForm.tsx b/web/app/install/installForm.tsx
new file mode 100644
index 00000000000..749719e9e99
--- /dev/null
+++ b/web/app/install/installForm.tsx
@@ -0,0 +1,155 @@
+'use client'
+import React from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import Link from 'next/link'
+import { useRouter } from 'next/navigation'
+import Toast from '../components/base/toast'
+import { setup } from '@/service/common'
+
+const validEmailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
+const validPassword = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
+
+const InstallForm = () => {
+ const { t } = useTranslation()
+ const router = useRouter()
+
+ const [email, setEmail] = React.useState('')
+ const [name, setName] = React.useState('')
+ const [password, setPassword] = React.useState('')
+ const showErrorMessage = (message: string) => {
+ Toast.notify({
+ type: 'error',
+ message,
+ })
+ }
+ const valid = () => {
+ if (!email) {
+ showErrorMessage(t('login.error.emailEmpty'))
+ return false
+ }
+ if (!validEmailReg.test(email)) {
+ showErrorMessage(t('login.error.emailInValid'))
+ return false
+ }
+ if (!name.trim()) {
+ showErrorMessage(t('login.error.nameEmpty'))
+ return false
+ }
+ if (!password.trim()) {
+ showErrorMessage(t('login.error.passwordEmpty'))
+ return false
+ }
+ if (!validPassword.test(password)) {
+ showErrorMessage(t('login.error.passwordInvalid'))
+ }
+ return true
+ }
+ const handleSetting = async () => {
+ if (!valid()) return
+ await setup({
+ body: {
+ email,
+ name,
+ password
+ }
+ })
+ router.push('/signin')
+ }
+ return (
+ <>
+ <div className="sm:mx-auto sm:w-full sm:max-w-md">
+ <h2 className="text-3xl font-normal text-gray-900">{t('login.setAdminAccount')}</h2>
+ <p className='
+ mt-2 text-sm text-gray-600
+ '>{t('login.setAdminAccountDesc')}</p>
+ </div>
+
+ <div className="grow mt-8 sm:mx-auto sm:w-full sm:max-w-md">
+ <div className="bg-white ">
+ <form className="space-y-6" onSubmit={() => { }}>
+ <div>
+ <label htmlFor="email" className="block text-sm font-medium text-gray-700">
+ {t('login.email')}
+ </label>
+ <div className="mt-1">
+ <input
+ id="email"
+ type="email"
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ className={'appearance-none block w-full px-3 py-2 border border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 rounded-md shadow-sm placeholder-gray-400 sm:text-sm'}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label htmlFor="name" className="block text-sm font-medium text-gray-700">
+ {t('login.name')}
+ </label>
+ <div className="mt-1 relative rounded-md shadow-sm">
+ <input
+ id="name"
+ type="text"
+ value={name}
+ onChange={e => setName(e.target.value)}
+ className={'appearance-none block w-full px-3 py-2 border border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 rounded-md shadow-sm placeholder-gray-400 sm:text-sm pr-10'}
+ />
+
+ </div>
+ </div>
+ <div>
+ <label htmlFor="password" className="block text-sm font-medium text-gray-700">
+ {t('login.password')}
+ </label>
+ <div className="mt-1 relative rounded-md shadow-sm">
+ <input
+ id="password"
+ type='password'
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ className={'appearance-none block w-full px-3 py-2 border border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 rounded-md shadow-sm placeholder-gray-400 sm:text-sm pr-10'}
+ />
+ </div>
+ <div className='mt-1 text-xs text-gray-500'>{t('login.error.passwordInvalid')}</div>
+
+ </div>
+
+ {/* <div className="flex items-center justify-between">
+ <div className="text-sm">
+ <div className="flex items-center mb-4">
+ <input id="default-checkbox" type="checkbox" className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 rounded" />
+ <label htmlFor="default-checkbox" className="ml-2 text-sm font-medium cursor-pointer text-primary-600 hover:text-gray-500">{t('login.acceptPP')}</label>
+ </div>
+ </div>
+ </div> */}
+ {/* agree to our Terms and Privacy Policy. */}
+ <div className="block mt-6 text-xs text-gray-600">
+ {t('login.tosDesc')}
+ &nbsp;
+ <Link
+ className='text-primary-600'
+ target={'_blank'}
+ href='https://docs.dify.ai/user-agreement/terms-of-service'
+ >{t('login.tos')}</Link>
+ &nbsp;&&nbsp;
+ <Link
+ className='text-primary-600'
+ target={'_blank'}
+ href='https://langgenius.ai/privacy-policy'
+ >{t('login.pp')}</Link>
+ </div>
+
+ <div>
+ <Button type='primary' onClick={handleSetting}>
+ {t('login.installBtn')}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default InstallForm
diff --git a/web/app/install/page.tsx b/web/app/install/page.tsx
new file mode 100644
index 00000000000..8e9f31229f5
--- /dev/null
+++ b/web/app/install/page.tsx
@@ -0,0 +1,36 @@
+import React from 'react'
+import InstallForm from './installForm'
+import Header from '../signin/_header'
+import style from '../signin/page.module.css'
+import classNames from 'classnames'
+
+const SignIn = () => {
+
+ return (
+ <>
+ <div className={classNames(
+ style.background,
+ 'flex w-full min-h-screen',
+ 'p-4 lg:p-8',
+ 'gap-x-20',
+ 'justify-center lg:justify-start'
+ )}>
+ <div className={
+ classNames(
+ 'flex w-full flex-col bg-white shadow rounded-2xl shrink-0',
+ 'md:w-[608px] space-between'
+ )
+ }>
+ <Header />
+ <InstallForm />
+ <div className='px-8 py-6 text-sm font-normal text-gray-500'>
+ © {new Date().getFullYear()} Dify, Inc. All rights reserved.
+ </div>
+ </div>
+ </div>
+
+ </>
+ )
+}
+
+export default SignIn
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
new file mode 100644
index 00000000000..1629ca2d09d
--- /dev/null
+++ b/web/app/layout.tsx
@@ -0,0 +1,32 @@
+import I18nServer from './components/i18n-server'
+import { getLocaleOnServer } from '@/i18n/server'
+
+import './styles/globals.css'
+import './styles/markdown.scss'
+
+export const metadata = {
+ title: 'Dify',
+}
+
+const LocaleLayout = ({
+ children,
+}: {
+ children: React.ReactNode
+}) => {
+ const locale = getLocaleOnServer()
+ return (
+ <html lang={locale ?? 'en'} className="h-full">
+ <body
+ className="h-full"
+ data-api-prefix={process.env.NEXT_PUBLIC_API_PREFIX}
+ data-pubic-api-prefix={process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX}
+ data-public-edition={process.env.NEXT_PUBLIC_EDITION}
+ >
+ {/* @ts-expect-error Async Server Component */}
+ <I18nServer locale={locale}>{children}</I18nServer>
+ </body>
+ </html>
+ )
+}
+
+export default LocaleLayout
diff --git a/web/app/page.module.css b/web/app/page.module.css
new file mode 100644
index 00000000000..90fa1554c0e
--- /dev/null
+++ b/web/app/page.module.css
@@ -0,0 +1,266 @@
+.main {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ align-items: center;
+ padding: 6rem;
+ min-height: 100vh;
+}
+
+.description {
+ display: inherit;
+ justify-content: inherit;
+ align-items: inherit;
+ font-size: 0.85rem;
+ max-width: var(--max-width);
+ width: 100%;
+ z-index: 2;
+ font-family: var(--font-mono);
+}
+
+.description a {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+}
+
+.description p {
+ position: relative;
+ margin: 0;
+ padding: 1rem;
+ background-color: rgba(var(--callout-rgb), 0.5);
+ border: 1px solid rgba(var(--callout-border-rgb), 0.3);
+ border-radius: var(--border-radius);
+}
+
+.code {
+ font-weight: 700;
+ font-family: var(--font-mono);
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(33%, auto));
+ width: var(--max-width);
+ max-width: 100%;
+}
+
+.card {
+ padding: 1rem 1.2rem;
+ border-radius: var(--border-radius);
+ background: rgba(var(--card-rgb), 0);
+ border: 1px solid rgba(var(--card-border-rgb), 0);
+ transition: background 200ms, border 200ms;
+}
+
+.card span {
+ display: inline-block;
+ transition: transform 200ms;
+}
+
+.card h2 {
+ font-weight: 600;
+ margin-bottom: 0.7rem;
+}
+
+.card p {
+ margin: 0;
+ opacity: 0.6;
+ font-size: 0.9rem;
+ line-height: 1.5;
+ max-width: 34ch;
+}
+
+.center {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ position: relative;
+ padding: 4rem 0;
+}
+
+.center::before {
+ background: var(--secondary-glow);
+ border-radius: 50%;
+ width: 480px;
+ height: 360px;
+ margin-left: -400px;
+}
+
+.center::after {
+ background: var(--primary-glow);
+ width: 240px;
+ height: 180px;
+ z-index: -1;
+}
+
+.center::before,
+.center::after {
+ content: '';
+ left: 50%;
+ position: absolute;
+ filter: blur(45px);
+ transform: translateZ(0);
+}
+
+.logo,
+.thirteen {
+ position: relative;
+}
+
+.thirteen {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 75px;
+ height: 75px;
+ padding: 25px 10px;
+ margin-left: 16px;
+ transform: translateZ(0);
+ border-radius: var(--border-radius);
+ overflow: hidden;
+ box-shadow: 0px 2px 8px -1px #0000001a;
+}
+
+.thirteen::before,
+.thirteen::after {
+ content: '';
+ position: absolute;
+ z-index: -1;
+}
+
+/* Conic Gradient Animation */
+.thirteen::before {
+ animation: 6s rotate linear infinite;
+ width: 200%;
+ height: 200%;
+ background: var(--tile-border);
+}
+
+/* Inner Square */
+.thirteen::after {
+ inset: 0;
+ padding: 1px;
+ border-radius: var(--border-radius);
+ background: linear-gradient(to bottom right,
+ rgba(var(--tile-start-rgb), 1),
+ rgba(var(--tile-end-rgb), 1));
+ background-clip: content-box;
+}
+
+/* Enable hover only on non-touch devices */
+@media (hover: hover) and (pointer: fine) {
+ .card:hover {
+ background: rgba(var(--card-rgb), 0.1);
+ border: 1px solid rgba(var(--card-border-rgb), 0.15);
+ }
+
+ .card:hover span {
+ transform: translateX(4px);
+ }
+}
+
+@media (prefers-reduced-motion) {
+ .thirteen::before {
+ animation: none;
+ }
+
+ .card:hover span {
+ transform: none;
+ }
+}
+
+/* Mobile and Tablet */
+@media (max-width: 1023px) {
+ .content {
+ padding: 4rem;
+ }
+
+ .grid {
+ grid-template-columns: 1fr;
+ margin-bottom: 120px;
+ max-width: 320px;
+ text-align: center;
+ }
+
+ .card {
+ padding: 1rem 2.5rem;
+ }
+
+ .card h2 {
+ margin-bottom: 0.5rem;
+ }
+
+ .center {
+ padding: 8rem 0 6rem;
+ }
+
+ .center::before {
+ transform: none;
+ height: 300px;
+ }
+
+ .description {
+ font-size: 0.8rem;
+ }
+
+ .description a {
+ padding: 1rem;
+ }
+
+ .description p,
+ .description div {
+ display: flex;
+ justify-content: center;
+ position: fixed;
+ width: 100%;
+ }
+
+ .description p {
+ align-items: center;
+ inset: 0 0 auto;
+ padding: 2rem 1rem 1.4rem;
+ border-radius: 0;
+ border: none;
+ border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.25);
+ background: linear-gradient(to bottom,
+ rgba(var(--background-start-rgb), 1),
+ rgba(var(--callout-rgb), 0.5));
+ background-clip: padding-box;
+ backdrop-filter: blur(24px);
+ }
+
+ .description div {
+ align-items: flex-end;
+ pointer-events: none;
+ inset: auto 0 0;
+ padding: 2rem;
+ height: 200px;
+ background: linear-gradient(to bottom,
+ transparent 0%,
+ rgb(var(--background-end-rgb)) 40%);
+ z-index: 1;
+ }
+}
+
+@media (prefers-color-scheme: dark) {
+ .vercelLogo {
+ filter: invert(1);
+ }
+
+ .logo,
+ .thirteen img {
+ filter: invert(1) drop-shadow(0 0 0.3rem #ffffff70);
+ }
+}
+
+@keyframes rotate {
+ from {
+ transform: rotate(360deg);
+ }
+
+ to {
+ transform: rotate(0deg);
+ }
+}
\ No newline at end of file
diff --git a/web/app/page.tsx b/web/app/page.tsx
new file mode 100644
index 00000000000..c63d9d12340
--- /dev/null
+++ b/web/app/page.tsx
@@ -0,0 +1,18 @@
+import Link from 'next/link'
+import Loading from '@/app/components/base/loading'
+
+const Home = async () => {
+ return (
+ <div className="flex flex-col justify-center min-h-screen py-12 sm:px-6 lg:px-8">
+
+ <div className="sm:mx-auto sm:w-full sm:max-w-md">
+ <Loading type='area' />
+ <div className="mt-10 text-center">
+ <Link href='/apps'>🚀</Link>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default Home
diff --git a/web/app/signin/_header.tsx b/web/app/signin/_header.tsx
new file mode 100644
index 00000000000..14cb298226c
--- /dev/null
+++ b/web/app/signin/_header.tsx
@@ -0,0 +1,30 @@
+'use client'
+import React from 'react'
+import style from './page.module.css'
+import Select, { LOCALES } from '@/app/components/base/select/locale'
+import { type Locale } from '@/i18n'
+import I18n from '@/context/i18n'
+import { setLocaleOnClient } from '@/i18n/client'
+import { useContext } from 'use-context-selector'
+
+
+type IHeaderProps = {
+ locale: string
+}
+
+const Header = () => {
+ const { locale, setLocaleOnClient } = useContext(I18n)
+ return <div className='flex items-center justify-between p-6 w-full'>
+ <div className={style.logo}></div>
+ <Select
+ value={locale}
+ items={LOCALES}
+ onChange={(value) => {
+ setLocaleOnClient(value as Locale)
+ }}
+ />
+
+ </div>
+}
+
+export default Header
diff --git a/web/app/signin/assets/background.png b/web/app/signin/assets/background.png
new file mode 100644
index 00000000000..a410f7e0749
Binary files /dev/null and b/web/app/signin/assets/background.png differ
diff --git a/web/app/signin/assets/github.svg b/web/app/signin/assets/github.svg
new file mode 100644
index 00000000000..f03798b5e1d
--- /dev/null
+++ b/web/app/signin/assets/github.svg
@@ -0,0 +1,17 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_131_1011)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0003 0.5C9.15149 0.501478 6.39613 1.51046 4.22687 3.34652C2.05761 5.18259 0.615903 7.72601 0.159545 10.522C-0.296814 13.318 0.261927 16.1842 1.73587 18.6082C3.20981 21.0321 5.50284 22.8558 8.20493 23.753C8.80105 23.8636 9.0256 23.4941 9.0256 23.18C9.0256 22.8658 9.01367 21.955 9.0097 20.9592C5.6714 21.6804 4.96599 19.5505 4.96599 19.5505C4.42152 18.1674 3.63464 17.8039 3.63464 17.8039C2.54571 17.065 3.71611 17.0788 3.71611 17.0788C4.92227 17.1637 5.55616 18.3097 5.55616 18.3097C6.62521 20.1333 8.36389 19.6058 9.04745 19.2976C9.15475 18.5251 9.46673 17.9995 9.8105 17.7012C7.14383 17.4008 4.34204 16.3774 4.34204 11.8054C4.32551 10.6197 4.76802 9.47305 5.57801 8.60268C5.45481 8.30236 5.04348 7.08923 5.69524 5.44143C5.69524 5.44143 6.7027 5.12135 8.9958 6.66444C10.9627 6.12962 13.0379 6.12962 15.0047 6.66444C17.2958 5.12135 18.3013 5.44143 18.3013 5.44143C18.9551 7.08528 18.5437 8.29841 18.4205 8.60268C19.2331 9.47319 19.6765 10.6218 19.6585 11.8094C19.6585 16.3912 16.8507 17.4008 14.1801 17.6952C14.6093 18.0667 14.9928 18.7918 14.9928 19.9061C14.9928 21.5026 14.9789 22.7868 14.9789 23.18C14.9789 23.4981 15.1955 23.8695 15.8035 23.753C18.5059 22.8557 20.7992 21.0317 22.2731 18.6073C23.747 16.183 24.3055 13.3163 23.8486 10.5201C23.3917 7.7238 21.9493 5.18035 19.7793 3.34461C17.6093 1.50886 14.8533 0.500541 12.0042 0.5H12.0003Z" fill="#191717"/>
+<path d="M4.54444 17.6321C4.5186 17.6914 4.42322 17.7092 4.34573 17.6677C4.26823 17.6262 4.21061 17.5491 4.23843 17.4879C4.26625 17.4266 4.35964 17.4108 4.43714 17.4523C4.51463 17.4938 4.57424 17.5729 4.54444 17.6321Z" fill="#191717"/>
+<path d="M5.03123 18.1714C4.99008 18.192 4.943 18.1978 4.89805 18.1877C4.8531 18.1776 4.81308 18.1523 4.78483 18.1161C4.70734 18.0331 4.69143 17.9185 4.75104 17.8671C4.81066 17.8157 4.91797 17.8395 4.99546 17.9224C5.07296 18.0054 5.09084 18.12 5.03123 18.1714Z" fill="#191717"/>
+<path d="M5.50425 18.857C5.43072 18.9084 5.30553 18.857 5.23598 18.7543C5.21675 18.7359 5.20146 18.7138 5.19101 18.6893C5.18056 18.6649 5.17517 18.6386 5.17517 18.612C5.17517 18.5855 5.18056 18.5592 5.19101 18.5347C5.20146 18.5103 5.21675 18.4882 5.23598 18.4698C5.3095 18.4204 5.4347 18.4698 5.50425 18.5705C5.57379 18.6713 5.57578 18.8057 5.50425 18.857V18.857Z" fill="#191717"/>
+<path d="M6.14612 19.5207C6.08054 19.5939 5.94741 19.5741 5.83812 19.4753C5.72883 19.3765 5.70299 19.2422 5.76857 19.171C5.83414 19.0999 5.96727 19.1197 6.08054 19.2165C6.1938 19.3133 6.21566 19.4496 6.14612 19.5207V19.5207Z" fill="#191717"/>
+<path d="M7.04617 19.9081C7.01637 20.001 6.88124 20.0425 6.74612 20.003C6.611 19.9635 6.52158 19.8528 6.54741 19.758C6.57325 19.6631 6.71036 19.6197 6.84747 19.6631C6.98457 19.7066 7.07201 19.8113 7.04617 19.9081Z" fill="#191717"/>
+<path d="M8.02783 19.9752C8.02783 20.072 7.91656 20.155 7.77349 20.1569C7.63042 20.1589 7.51318 20.0799 7.51318 19.9831C7.51318 19.8863 7.62445 19.8033 7.76752 19.8013C7.91059 19.7993 8.02783 19.8764 8.02783 19.9752Z" fill="#191717"/>
+<path d="M8.9419 19.8232C8.95978 19.92 8.86042 20.0207 8.71735 20.0445C8.57428 20.0682 8.4491 20.0109 8.43121 19.916C8.41333 19.8212 8.51666 19.7185 8.65576 19.6928C8.79485 19.6671 8.92401 19.7264 8.9419 19.8232Z" fill="#191717"/>
+</g>
+<defs>
+<clipPath id="clip0_131_1011">
+<rect width="24" height="24" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/signin/assets/google.svg b/web/app/signin/assets/google.svg
new file mode 100644
index 00000000000..6bcacfcddc0
--- /dev/null
+++ b/web/app/signin/assets/google.svg
@@ -0,0 +1,13 @@
+<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_729_2080)">
+<path d="M20.3052 10.2302C20.3052 9.55044 20.2501 8.86699 20.1325 8.19824H10.7002V12.0491H16.1016C15.8775 13.291 15.1573 14.3897 14.1027 15.0878V17.5864H17.3252C19.2176 15.8448 20.3052 13.2726 20.3052 10.2302Z" fill="#4285F4"/>
+<path d="M10.6999 20.0008C13.397 20.0008 15.6714 19.1152 17.3286 17.5867L14.1061 15.088C13.2096 15.698 12.0521 16.0434 10.7036 16.0434C8.09474 16.0434 5.88272 14.2833 5.08904 11.917H1.76367V14.4928C3.46127 17.8696 6.91892 20.0008 10.6999 20.0008Z" fill="#34A853"/>
+<path d="M5.08564 11.9172C4.66676 10.6753 4.66676 9.33044 5.08564 8.08848V5.5127H1.76395C0.345611 8.33834 0.345611 11.6674 1.76395 14.493L5.08564 11.9172Z" fill="#FBBC04"/>
+<path d="M10.6999 3.95805C12.1256 3.936 13.5035 4.47247 14.536 5.45722L17.3911 2.60218C15.5833 0.904587 13.1838 -0.0287217 10.6999 0.000673888C6.91892 0.000673888 3.46126 2.13185 1.76367 5.51234L5.08537 8.08813C5.87537 5.71811 8.09106 3.95805 10.6999 3.95805Z" fill="#EA4335"/>
+</g>
+<defs>
+<clipPath id="clip0_729_2080">
+<rect width="20" height="20" fill="white" transform="translate(0.5)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/signin/assets/logo-icon.svg b/web/app/signin/assets/logo-icon.svg
new file mode 100644
index 00000000000..4885e8fd672
--- /dev/null
+++ b/web/app/signin/assets/logo-icon.svg
@@ -0,0 +1,5 @@
+<svg width="29" height="28" viewBox="0 0 29 28" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M29 14C29 21.732 22.5081 28 14.5 28C12.5713 28 10.7305 27.6364 9.04718 26.9763C8.72501 26.85 8.56393 26.7869 8.43371 26.7587C8.30634 26.7311 8.21208 26.721 8.08155 26.721C7.9481 26.721 7.80275 26.7444 7.51205 26.7912L1.77989 27.7136C1.17963 27.8102 0.879495 27.8585 0.662464 27.7686C0.472511 27.6899 0.321142 27.5438 0.23967 27.3604C0.146582 27.1508 0.196605 26.861 0.296649 26.2815L1.25201 20.747C1.30046 20.4663 1.32468 20.326 1.32467 20.1971C1.32465 20.0711 1.31421 19.9801 1.28566 19.8571C1.25647 19.7314 1.19105 19.5759 1.06021 19.2648C0.376575 17.6395 0 15.8622 0 14C0 6.26801 6.49187 0 14.5 0C22.5081 0 29 6.26801 29 14Z" fill="#155EEF"/>
+<path opacity="0.72" fill-rule="evenodd" clip-rule="evenodd" d="M24.8346 23.8202L13.2186 23.8202C12.8708 23.8202 12.548 23.6395 12.3662 23.3431L7.06478 14.702C7.01652 14.6234 6.99097 14.5329 6.99097 14.4406V11.7363L13.3252 21.9651C13.4619 22.1858 13.7031 22.3202 13.9628 22.3202H26.1627C25.7565 22.8501 25.3125 23.3513 24.8346 23.8202Z" fill="white"/>
+<path d="M27.9351 19.2764C28.6217 17.6481 29 15.867 29 14.0005C29 13.7095 28.9908 13.4206 28.9727 13.1341H18.7973C18.6231 13.1341 18.4615 13.0435 18.3707 12.8949L14.2258 6.11473C14.1986 6.07015 14.1501 6.04297 14.0979 6.04297H7.43681C7.24156 6.04297 7.12167 6.25678 7.22351 6.42336L14.7884 18.798C14.9701 19.0952 15.2933 19.2764 15.6416 19.2764L27.9351 19.2764Z" fill="white"/>
+</svg>
diff --git a/web/app/signin/assets/logo-text.svg b/web/app/signin/assets/logo-text.svg
new file mode 100644
index 00000000000..8327818bc1e
--- /dev/null
+++ b/web/app/signin/assets/logo-text.svg
@@ -0,0 +1,14 @@
+<svg width="76" height="16" viewBox="0 0 76 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect x="0.956787" y="13.8203" width="20.9866" height="1.5" fill="#1C64F2"/>
+<rect x="32.1108" y="13.8203" width="42.8303" height="1.5" fill="#1C64F2"/>
+<path d="M3.47679 9.522H6.23079V11.646H0.956787V0H3.47679V9.522Z" fill="#1C64F2"/>
+<path d="M11.7995 2.862H13.8335V11.646H11.7995V10.998C11.4275 11.55 10.8095 11.826 9.94554 11.826H9.56754C8.07954 11.826 7.33554 11.034 7.33554 9.45V5.058C7.33554 3.474 8.07954 2.682 9.56754 2.682H9.94554C10.8095 2.682 11.4275 2.958 11.7995 3.51V2.862ZM11.4215 9.738V4.77C11.4215 4.674 11.3855 4.59 11.3135 4.518C11.2535 4.446 11.1755 4.41 11.0795 4.41H10.0895C9.99354 4.41 9.90954 4.446 9.83754 4.518C9.77754 4.59 9.74754 4.674 9.74754 4.77V9.738C9.74754 9.834 9.77754 9.918 9.83754 9.99C9.90954 10.062 9.99354 10.098 10.0895 10.098H11.0795C11.1755 10.098 11.2535 10.062 11.3135 9.99C11.3855 9.918 11.4215 9.834 11.4215 9.738Z" fill="#1C64F2"/>
+<path d="M17.8862 11.646H15.4742V2.862H17.6702V3.312C18.0422 2.892 18.6062 2.682 19.3622 2.682H19.7402C21.2282 2.682 21.9722 3.474 21.9722 5.058V11.646H19.5602V4.77C19.5602 4.674 19.5242 4.59 19.4522 4.518C19.3922 4.446 19.3142 4.41 19.2182 4.41H18.2282C18.1322 4.41 18.0482 4.446 17.9762 4.518C17.9162 4.59 17.8862 4.674 17.8862 4.77V11.646Z" fill="#1C64F2"/>
+<path d="M30.1109 2.862V12.312C30.1109 13.896 29.3669 14.688 27.8789 14.688H26.0789C24.5909 14.688 23.8469 13.896 23.8469 12.312V12.024H26.0249V12.6C26.0249 12.696 26.0549 12.78 26.1149 12.852C26.1869 12.924 26.2709 12.96 26.3669 12.96H27.3569C27.4529 12.96 27.5309 12.924 27.5909 12.852C27.6629 12.78 27.6989 12.696 27.6989 12.6V10.8C27.3269 11.088 26.8349 11.232 26.2229 11.232H25.8449C24.3569 11.232 23.6129 10.44 23.6129 8.856V5.058C23.6129 3.474 24.3569 2.682 25.8449 2.682H26.2229C27.0869 2.682 27.7049 2.958 28.0769 3.51V2.862H30.1109ZM27.6989 9.144V4.77C27.6989 4.674 27.6629 4.59 27.5909 4.518C27.5309 4.446 27.4529 4.41 27.3569 4.41H26.3669C26.2709 4.41 26.1869 4.446 26.1149 4.518C26.0549 4.59 26.0249 4.674 26.0249 4.77V9.144C26.0249 9.24 26.0549 9.324 26.1149 9.396C26.1869 9.468 26.2709 9.504 26.3669 9.504H27.3569C27.4529 9.504 27.5309 9.468 27.5909 9.396C27.6629 9.324 27.6989 9.24 27.6989 9.144Z" fill="#1C64F2"/>
+<path d="M35.5128 7.524V5.67H38.8428V9.954C38.8428 11.538 38.0988 12.33 36.6108 12.33H34.3428C32.8548 12.33 32.1108 11.538 32.1108 9.954V2.7C32.1108 1.116 32.8548 0.324 34.3428 0.324H36.6108C38.0988 0.324 38.8428 1.116 38.8428 2.7V3.798H36.4488V2.394C36.4488 2.298 36.4128 2.214 36.3408 2.142C36.2808 2.07 36.2028 2.034 36.1068 2.034H34.9728C34.8768 2.034 34.7928 2.07 34.7208 2.142C34.6608 2.214 34.6308 2.298 34.6308 2.394V10.242C34.6308 10.338 34.6608 10.422 34.7208 10.494C34.7928 10.566 34.8768 10.602 34.9728 10.602H36.1068C36.2028 10.602 36.2808 10.566 36.3408 10.494C36.4128 10.422 36.4488 10.338 36.4488 10.242V7.524H35.5128Z" fill="#111928"/>
+<path d="M44.4079 3.186C45.8959 3.186 46.6399 3.978 46.6399 5.562V8.406H42.5539V10.242C42.5539 10.338 42.5839 10.422 42.6439 10.494C42.7159 10.566 42.7999 10.602 42.8959 10.602H43.8859C43.9819 10.602 44.0599 10.566 44.1199 10.494C44.1919 10.422 44.2279 10.338 44.2279 10.242V9.27H46.6399V9.954C46.6399 11.538 45.8959 12.33 44.4079 12.33H42.3739C40.8859 12.33 40.1419 11.538 40.1419 9.954V5.562C40.1419 3.978 40.8859 3.186 42.3739 3.186H44.4079ZM42.5539 6.822H44.2279V5.202C44.2279 5.106 44.1919 5.022 44.1199 4.95C44.0599 4.878 43.9819 4.842 43.8859 4.842H42.8959C42.7999 4.842 42.7159 4.878 42.6439 4.95C42.5839 5.022 42.5539 5.106 42.5539 5.202V6.822Z" fill="#111928"/>
+<path d="M50.3762 12.15H47.9642V3.366H50.1602V3.816C50.5322 3.396 51.0962 3.186 51.8522 3.186H52.2302C53.7182 3.186 54.4622 3.978 54.4622 5.562V12.15H52.0502V5.274C52.0502 5.178 52.0142 5.094 51.9422 5.022C51.8822 4.95 51.8042 4.914 51.7082 4.914H50.7182C50.6222 4.914 50.5382 4.95 50.4662 5.022C50.4062 5.094 50.3762 5.178 50.3762 5.274V12.15Z" fill="#111928"/>
+<path d="M58.5509 2.268C58.2989 2.52 57.9929 2.646 57.6329 2.646C57.2729 2.646 56.9609 2.52 56.6969 2.268C56.4329 2.004 56.3009 1.692 56.3009 1.332C56.3009 0.96 56.4329 0.647999 56.6969 0.395999C56.9609 0.131999 57.2729 0 57.6329 0C57.9929 0 58.2989 0.131999 58.5509 0.395999C58.8149 0.647999 58.9469 0.96 58.9469 1.332C58.9469 1.704 58.8149 2.016 58.5509 2.268ZM56.4269 12.15V3.366H58.8389V12.15H56.4269Z" fill="#111928"/>
+<path d="M64.6186 3.366H67.0306V12.15H64.8346V11.7C64.4626 12.12 63.8986 12.33 63.1426 12.33H62.7646C61.2766 12.33 60.5326 11.538 60.5326 9.954V3.366H62.9446V10.242C62.9446 10.338 62.9746 10.422 63.0346 10.494C63.1066 10.566 63.1906 10.602 63.2866 10.602H64.2766C64.3726 10.602 64.4506 10.566 64.5106 10.494C64.5826 10.422 64.6186 10.338 64.6186 10.242V3.366Z" fill="#111928"/>
+<path d="M72.8112 6.642C74.2992 6.642 75.0432 7.434 75.0432 9.018V9.954C75.0432 11.538 74.2992 12.33 72.8112 12.33H70.8132C69.3252 12.33 68.5812 11.538 68.5812 9.954V9.396H70.8132V10.188C70.8132 10.284 70.8432 10.368 70.9032 10.44C70.9752 10.512 71.0592 10.548 71.1552 10.548H72.6312C72.7272 10.548 72.8052 10.512 72.8652 10.44C72.9372 10.368 72.9732 10.284 72.9732 10.188V9.108C72.9732 9.012 72.9372 8.928 72.8652 8.856C72.8052 8.784 72.7272 8.748 72.6312 8.748H70.7772C69.2892 8.748 68.5452 7.956 68.5452 6.372V5.562C68.5452 3.978 69.2892 3.186 70.7772 3.186H72.6672C74.1552 3.186 74.8992 3.978 74.8992 5.562V5.886H72.6672V5.328C72.6672 5.232 72.6312 5.148 72.5592 5.076C72.4992 5.004 72.4212 4.968 72.3252 4.968H70.9572C70.8612 4.968 70.7772 5.004 70.7052 5.076C70.6452 5.148 70.6152 5.232 70.6152 5.328V6.282C70.6152 6.378 70.6452 6.462 70.7052 6.534C70.7772 6.606 70.8612 6.642 70.9572 6.642H72.8112Z" fill="#111928"/>
+</svg>
diff --git a/web/app/signin/forms.tsx b/web/app/signin/forms.tsx
new file mode 100644
index 00000000000..d6cbbe6c3df
--- /dev/null
+++ b/web/app/signin/forms.tsx
@@ -0,0 +1,35 @@
+'use client'
+import React from 'react'
+import { useSearchParams } from 'next/navigation'
+
+import NormalForm from './normalForm'
+import OneMoreStep from './oneMoreStep'
+import classNames from 'classnames'
+
+const Forms = () => {
+ const searchParams = useSearchParams()
+ const step = searchParams.get('step')
+
+ const getForm = () => {
+ switch (step) {
+ case 'next':
+ return <OneMoreStep />
+ default:
+ return <NormalForm />
+ }
+ }
+ return <div className={
+ classNames(
+ 'flex flex-col items-center w-full grow items-center justify-center',
+ 'px-6',
+ 'md:px-[108px]',
+ )
+ }>
+ <div className='flex flex-col md:w-[400px]'>
+ {getForm()}
+ </div>
+
+ </div>
+}
+
+export default Forms
diff --git a/web/app/signin/normalForm.tsx b/web/app/signin/normalForm.tsx
new file mode 100644
index 00000000000..e0626572ac2
--- /dev/null
+++ b/web/app/signin/normalForm.tsx
@@ -0,0 +1,288 @@
+'use client'
+import React, { useEffect, useReducer, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useRouter } from 'next/navigation'
+import { IS_CE_EDITION } from '@/config'
+import classNames from 'classnames'
+import useSWR from 'swr'
+import Link from 'next/link'
+import style from './page.module.css'
+// import Tooltip from '@/app/components/base/tooltip/index'
+import Toast from '../components/base/toast'
+import Button from '@/app/components/base/button'
+import { login, oauth } from '@/service/common'
+import { apiPrefix } from '@/config'
+
+const validEmailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
+
+type IState = {
+ formValid: boolean
+ github: boolean
+ google: boolean
+}
+
+function reducer(state: IState, action: { type: string; payload: any }) {
+ switch (action.type) {
+ case 'login':
+ return {
+ ...state,
+ formValid: true,
+ }
+ case 'login_failed':
+ return {
+ ...state,
+ formValid: true,
+ }
+ case 'github_login':
+ return {
+ ...state,
+ github: true,
+ }
+ case 'github_login_failed':
+ return {
+ ...state,
+ github: false,
+ }
+ case 'google_login':
+ return {
+ ...state,
+ google: true,
+ }
+ case 'google_login_failed':
+ return {
+ ...state,
+ google: false,
+ }
+ default:
+ throw new Error('Unknown action.')
+ }
+}
+
+const NormalForm = () => {
+ const { t } = useTranslation()
+ const router = useRouter()
+
+ const [state, dispatch] = useReducer(reducer, {
+ formValid: false,
+ github: false,
+ google: false,
+ })
+
+ const [showPassword, setShowPassword] = useState(false)
+ const [email, setEmail] = useState('')
+ const [password, setPassword] = useState('')
+
+ const [isLoading, setIsLoading] = useState(false)
+ const handleEmailPasswordLogin = async () => {
+ if (!validEmailReg.test(email)) {
+ Toast.notify({
+ type: 'error',
+ message: t('login.error.emailInValid'),
+ })
+ return
+ }
+ try {
+ setIsLoading(true)
+ await login({
+ url: '/login',
+ body: {
+ email,
+ password,
+ remember_me: true,
+ },
+ })
+ router.push('/')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const { data: github, error: github_error } = useSWR(state.github
+ ? ({
+ url: '/oauth/login/github',
+ // params: {
+ // provider: 'github',
+ // },
+ })
+ : null, oauth)
+
+ const { data: google, error: google_error } = useSWR(state.google
+ ? ({
+ url: '/oauth/login/google',
+ // params: {
+ // provider: 'google',
+ // },
+ })
+ : null, oauth)
+
+ useEffect(() => {
+ if (github_error !== undefined)
+ dispatch({ type: 'github_login_failed', payload: null })
+ if (github)
+ window.location.href = github.redirect_url
+ }, [github, github_error])
+
+ useEffect(() => {
+ if (google_error !== undefined)
+ dispatch({ type: 'google_login_failed', payload: null })
+ if (google)
+ window.location.href = google.redirect_url
+ }, [google, google])
+
+ return (
+ <>
+ <div className="w-full mx-auto">
+ <h2 className="text-3xl font-normal text-gray-900">{t('login.pageTitle')}</h2>
+ <p className='mt-2 text-sm text-gray-600 '>{t('login.welcome')}</p>
+ </div>
+
+ <div className="w-full mx-auto mt-8">
+ <div className="bg-white ">
+ {!IS_CE_EDITION && (
+ <div className="flex flex-col gap-3 mt-6">
+ <div className='w-full'>
+ <a href={`${apiPrefix}/oauth/login/github`}>
+ <Button
+ type='default'
+ disabled={isLoading}
+ className='w-full'
+ >
+ <>
+ <span className={
+ classNames(
+ style.githubIcon,
+ 'w-5 h-5 mr-2',
+ )
+ } />
+ <span className="truncate">{t('login.withGitHub')}</span>
+ </>
+ </Button>
+ </a>
+ </div>
+ <div className='w-full'>
+ <a href={`${apiPrefix}/oauth/login/google`}>
+ <Button
+ type='default'
+ disabled={isLoading}
+ className='w-full'
+ >
+ <>
+ <span className={
+ classNames(
+ style.googleIcon,
+ 'w-5 h-5 mr-2',
+ )
+ } />
+ <span className="truncate">{t('login.withGoogle')}</span>
+ </>
+ </Button>
+ </a>
+ </div>
+ </div>
+ )}
+
+ {
+ IS_CE_EDITION && <>
+ {/* <div className="relative mt-6">
+ <div className="absolute inset-0 flex items-center" aria-hidden="true">
+ <div className="w-full border-t border-gray-300" />
+ </div>
+ <div className="relative flex justify-center text-sm">
+ <span className="px-2 text-gray-300 bg-white">OR</span>
+ </div>
+ </div> */}
+
+ <form className="space-y-6" onSubmit={() => { }}>
+ <div>
+ <label htmlFor="email" className="block text-sm font-medium text-gray-700">
+ {t('login.email')}
+ </label>
+ <div className="mt-1">
+ <input
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ id="email"
+ type="email"
+ autoComplete="email"
+ className={'appearance-none block w-full px-3 py-2 border border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 rounded-md shadow-sm placeholder-gray-400 sm:text-sm'}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label htmlFor="password" className="flex items-center justify-between text-sm font-medium text-gray-700">
+ <span>{t('login.password')}</span>
+ {/* <Tooltip
+ selector='forget-password'
+ htmlContent={
+ <div>
+ <div className='font-medium'>{t('login.forget')}</div>
+ <div className='font-medium text-gray-500'>
+ <code>
+ sudo rm -rf /
+ </code>
+ </div>
+ </div>
+ }
+ >
+ <span className='cursor-pointer text-primary-600'>{t('login.forget')}</span>
+ </Tooltip> */}
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ id="password"
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ type={showPassword ? 'text' : 'password'}
+ autoComplete="current-password"
+ className={`appearance-none block w-full px-3 py-2
+ border border-gray-300
+ focus:outline-none focus:ring-indigo-500 focus:border-indigo-500
+ rounded-md shadow-sm placeholder-gray-400 sm:text-sm pr-10`}
+ />
+ <div className="absolute inset-y-0 right-0 flex items-center pr-3">
+ <button
+ type="button"
+ onClick={() => setShowPassword(!showPassword)}
+ className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500"
+ >
+ {showPassword ? '👀' : '😝'}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ <Button
+ type='primary'
+ onClick={handleEmailPasswordLogin}
+ disabled={isLoading}
+ >{t('login.signBtn')}</Button>
+ </div>
+ </form>
+ </>
+ }
+ {/* agree to our Terms and Privacy Policy. */}
+ <div className="block mt-6 text-xs text-gray-600">
+ {t('login.tosDesc')}
+ &nbsp;
+ <Link
+ className='text-primary-600'
+ target={'_blank'}
+ href='https://docs.dify.ai/user-agreement/terms-of-service'
+ >{t('login.tos')}</Link>
+ &nbsp;&&nbsp;
+ <Link
+ className='text-primary-600'
+ target={'_blank'}
+ href='https://docs.dify.ai/user-agreement/privacy-policy'
+ >{t('login.pp')}</Link>
+ </div>
+
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default NormalForm
diff --git a/web/app/signin/oneMoreStep.tsx b/web/app/signin/oneMoreStep.tsx
new file mode 100644
index 00000000000..9f7f72378b3
--- /dev/null
+++ b/web/app/signin/oneMoreStep.tsx
@@ -0,0 +1,160 @@
+'use client'
+import React, { useEffect, useReducer } from 'react'
+import { useTranslation } from 'react-i18next'
+import useSWR from 'swr'
+import { useRouter } from 'next/navigation'
+import Button from '@/app/components/base/button'
+import Tooltip from '@/app/components/base/tooltip/index'
+
+import { SimpleSelect } from '@/app/components/base/select'
+import { timezones } from '@/utils/timezone'
+import { languageMaps, languages } from '@/utils/language'
+import { oneMoreStep } from '@/service/common'
+import Toast from '@/app/components/base/toast'
+
+type IState = {
+ formState: 'processing' | 'error' | 'success' | 'initial'
+ invitation_code: string
+ interface_language: string
+ timezone: string
+}
+
+const reducer = (state: IState, action: any) => {
+ switch (action.type) {
+ case 'invitation_code':
+ return { ...state, invitation_code: action.value }
+ case 'interface_language':
+ return { ...state, interface_language: action.value }
+ case 'timezone':
+ return { ...state, timezone: action.value }
+ case 'formState':
+ return { ...state, formState: action.value }
+ case 'failed':
+ return {
+ formState: 'initial',
+ invitation_code: '',
+ interface_language: 'en-US',
+ timezone: 'Asia/Shanghai',
+ }
+ default:
+ throw new Error('Unknown action.')
+ }
+}
+
+const OneMoreStep = () => {
+ const { t } = useTranslation()
+ const router = useRouter()
+
+ const [state, dispatch] = useReducer(reducer, {
+ formState: 'initial',
+ invitation_code: '',
+ interface_language: 'en-US',
+ timezone: 'Asia/Shanghai',
+ })
+ const { data, error } = useSWR(state.formState === 'processing'
+ ? {
+ url: '/account/init',
+ body: {
+ invitation_code: state.invitation_code,
+ interface_language: state.interface_language,
+ timezone: state.timezone,
+ },
+ }
+ : null, oneMoreStep)
+
+ useEffect(() => {
+ if (error && error.status === 400) {
+ Toast.notify({ type: 'error', message: t('login.invalidInvitationCode') })
+ dispatch({ type: 'failed', payload: null })
+ }
+ if (data)
+ router.push('/apps')
+ }, [data, error])
+
+ return (
+ <>
+ <div className="w-full mx-auto">
+ <h2 className="text-3xl font-normal text-gray-900">{t('login.oneMoreStep')}</h2>
+ <p className='mt-2 text-sm text-gray-600 '>{t('login.createSample')}</p>
+ </div>
+
+ <div className="w-full mx-auto mt-8">
+ <div className="space-y-6 bg-white">
+ <div className="">
+ <label className="flex items-center justify-between text-sm font-medium text-gray-900">
+ {t('login.invitationCode')}
+ <Tooltip
+ clickable
+ selector='dont-have'
+ htmlContent={
+ <div className='w-[256px] text-xs font-medium'>
+ <div className='font-medium'>{t('login.sendUsMail')}</div>
+ <div className='text-xs font-medium cursor-pointer text-primary-600'>
+ <a href="mailto:[email protected]">[email protected]</a>
+ </div>
+ </div>
+ }
+ >
+ <span className='cursor-pointer text-primary-600'>{t('login.donthave')}</span>
+ </Tooltip>
+ </label>
+ <div className="mt-1">
+ <input
+ id="invitation_code"
+ value={state.invitation_code}
+ type="text"
+ className={'appearance-none block w-full px-3 py-2 border border-gray-300 focus:outline-none focus:ring-primary-600 focus:border-primary-600 rounded-md shadow-sm placeholder-gray-400 sm:text-sm'}
+ onChange={(e) => {
+ dispatch({ type: 'invitation_code', value: e.target.value.trim() })
+ }}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label htmlFor="name" className="block text-sm font-medium text-gray-700">
+ {t('login.interfaceLanguage')}
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <SimpleSelect
+ defaultValue={languageMaps.en}
+ items={languages}
+ onSelect={(item) => {
+ dispatch({ type: 'interface_language', value: item.value })
+ }}
+ />
+ </div>
+ </div>
+ <div>
+
+ <label htmlFor="timezone" className="block text-sm font-medium text-gray-700">
+ {t('login.timezone')}
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <SimpleSelect
+ defaultValue={state.timezone}
+ items={timezones}
+ onSelect={(item) => {
+ dispatch({ type: 'timezone', value: item.value })
+ }}
+ />
+ </div>
+ </div>
+ <div>
+ <Button
+ type='primary'
+ disabled={state.formState === 'processing'}
+ onClick={() => {
+ dispatch({ type: 'formState', value: 'processing' })
+ }}
+ >
+ {t('login.go')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default OneMoreStep
diff --git a/web/app/signin/page.module.css b/web/app/signin/page.module.css
new file mode 100644
index 00000000000..7bf2611f373
--- /dev/null
+++ b/web/app/signin/page.module.css
@@ -0,0 +1,19 @@
+.githubIcon {
+ background: center/contain url('./assets/github.svg');
+}
+
+.googleIcon {
+ background: center/contain url('./assets/google.svg');
+}
+
+.logo {
+ width: 96px;
+ height: 40px;
+ background: url(~@/app/components/share/chat/welcome/icons/logo.png) center center no-repeat;
+ background-size: contain;
+}
+
+.background {
+ background-image: url('./assets/background.png');
+ background-size: cover;
+}
\ No newline at end of file
diff --git a/web/app/signin/page.tsx b/web/app/signin/page.tsx
new file mode 100644
index 00000000000..ec413265d19
--- /dev/null
+++ b/web/app/signin/page.tsx
@@ -0,0 +1,37 @@
+import React from 'react'
+import Forms from './forms'
+import Header from './_header'
+import style from './page.module.css'
+import classNames from 'classnames'
+
+const SignIn = () => {
+
+ return (
+ <>
+ <div className={classNames(
+ style.background,
+ 'flex w-full min-h-screen',
+ 'sm:p-4 lg:p-8',
+ 'gap-x-20',
+ 'justify-center lg:justify-start'
+ )}>
+ <div className={
+ classNames(
+ 'flex w-full flex-col bg-white shadow rounded-2xl shrink-0',
+ 'space-between'
+ )
+ }>
+ <Header />
+ <Forms />
+ <div className='px-8 py-6 text-sm font-normal text-gray-500'>
+ © {new Date().getFullYear()} Dify, Inc. All rights reserved.
+ </div>
+ </div>
+
+ </div>
+
+ </>
+ )
+}
+
+export default SignIn
diff --git a/web/app/styles/globals.css b/web/app/styles/globals.css
new file mode 100644
index 00000000000..f4710b02759
--- /dev/null
+++ b/web/app/styles/globals.css
@@ -0,0 +1,134 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+:root {
+ --max-width: 1100px;
+ --border-radius: 12px;
+ --font-mono: ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono",
+ "Roboto Mono", "Oxygen Mono", "Ubuntu Monospace", "Source Code Pro",
+ "Fira Mono", "Droid Sans Mono", "Courier New", monospace;
+
+ --foreground-rgb: 0, 0, 0;
+ --background-start-rgb: 214, 219, 220;
+ --background-end-rgb: 255, 255, 255;
+
+ --primary-glow: conic-gradient(from 180deg at 50% 50%,
+ #16abff33 0deg,
+ #0885ff33 55deg,
+ #54d6ff33 120deg,
+ #0071ff33 160deg,
+ transparent 360deg);
+ --secondary-glow: radial-gradient(rgba(255, 255, 255, 1),
+ rgba(255, 255, 255, 0));
+
+ --tile-start-rgb: 239, 245, 249;
+ --tile-end-rgb: 228, 232, 233;
+ --tile-border: conic-gradient(#00000080,
+ #00000040,
+ #00000030,
+ #00000020,
+ #00000010,
+ #00000010,
+ #00000080);
+
+ --callout-rgb: 238, 240, 241;
+ --callout-border-rgb: 172, 175, 176;
+ --card-rgb: 180, 185, 188;
+ --card-border-rgb: 131, 134, 135;
+}
+
+/* @media (prefers-color-scheme: dark) {
+ :root {
+ --foreground-rgb: 255, 255, 255;
+ --background-start-rgb: 0, 0, 0;
+ --background-end-rgb: 0, 0, 0;
+
+ --primary-glow: radial-gradient(rgba(1, 65, 255, 0.4), rgba(1, 65, 255, 0));
+ --secondary-glow: linear-gradient(to bottom right,
+ rgba(1, 65, 255, 0),
+ rgba(1, 65, 255, 0),
+ rgba(1, 65, 255, 0.3));
+
+ --tile-start-rgb: 2, 13, 46;
+ --tile-end-rgb: 2, 5, 19;
+ --tile-border: conic-gradient(#ffffff80,
+ #ffffff40,
+ #ffffff30,
+ #ffffff20,
+ #ffffff10,
+ #ffffff10,
+ #ffffff80);
+
+ --callout-rgb: 20, 20, 20;
+ --callout-border-rgb: 108, 108, 108;
+ --card-rgb: 100, 100, 100;
+ --card-border-rgb: 200, 200, 200;
+ }
+} */
+
+* {
+ box-sizing: border-box;
+ padding: 0;
+ margin: 0;
+}
+
+html,
+body {
+ max-width: 100vw;
+ overflow-x: hidden;
+}
+
+body {
+ color: rgb(var(--foreground-rgb));
+ user-select: none;
+ /* background: linear-gradient(
+ to bottom,
+ transparent,
+ rgb(var(--background-end-rgb))
+ )
+ rgb(var(--background-start-rgb)); */
+}
+
+a {
+ color: inherit;
+ text-decoration: none;
+ outline: none;
+}
+
+button:focus-within {
+ outline: none;
+}
+
+/* @media (prefers-color-scheme: dark) {
+ html {
+ color-scheme: dark;
+ }
+} */
+
+/* CSS Utils */
+.h1 {
+ padding-bottom: 1.5rem;
+ line-height: 1.5;
+ font-size: 1.125rem;
+ color: #111928;
+}
+
+.h2 {
+ font-size: 14px;
+ font-weight: 500;
+ color: #111928;
+ line-height: 1.5;
+}
+
+.link {
+ @apply text-blue-600 cursor-pointer hover:opacity-80 transition-opacity duration-200 ease-in-out;
+}
+
+.text-gradient {
+ background: linear-gradient(91.58deg, #2250F2 -29.55%, #0EBCF3 75.22%);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+ text-fill-color: transparent;
+}
\ No newline at end of file
diff --git a/web/app/styles/markdown.scss b/web/app/styles/markdown.scss
new file mode 100644
index 00000000000..fdfaae0cf93
--- /dev/null
+++ b/web/app/styles/markdown.scss
@@ -0,0 +1,1042 @@
+@mixin light {
+ color-scheme: light;
+ --color-prettylights-syntax-comment: #6e7781;
+ --color-prettylights-syntax-constant: #0550ae;
+ --color-prettylights-syntax-entity: #8250df;
+ --color-prettylights-syntax-storage-modifier-import: #24292f;
+ --color-prettylights-syntax-entity-tag: #116329;
+ --color-prettylights-syntax-keyword: #cf222e;
+ --color-prettylights-syntax-string: #0a3069;
+ --color-prettylights-syntax-variable: #953800;
+ --color-prettylights-syntax-brackethighlighter-unmatched: #82071e;
+ --color-prettylights-syntax-invalid-illegal-text: #f6f8fa;
+ --color-prettylights-syntax-invalid-illegal-bg: #82071e;
+ --color-prettylights-syntax-carriage-return-text: #f6f8fa;
+ --color-prettylights-syntax-carriage-return-bg: #cf222e;
+ --color-prettylights-syntax-string-regexp: #116329;
+ --color-prettylights-syntax-markup-list: #3b2300;
+ --color-prettylights-syntax-markup-heading: #0550ae;
+ --color-prettylights-syntax-markup-italic: #24292f;
+ --color-prettylights-syntax-markup-bold: #24292f;
+ --color-prettylights-syntax-markup-deleted-text: #82071e;
+ --color-prettylights-syntax-markup-deleted-bg: #ffebe9;
+ --color-prettylights-syntax-markup-inserted-text: #116329;
+ --color-prettylights-syntax-markup-inserted-bg: #dafbe1;
+ --color-prettylights-syntax-markup-changed-text: #953800;
+ --color-prettylights-syntax-markup-changed-bg: #ffd8b5;
+ --color-prettylights-syntax-markup-ignored-text: #eaeef2;
+ --color-prettylights-syntax-markup-ignored-bg: #0550ae;
+ --color-prettylights-syntax-meta-diff-range: #8250df;
+ --color-prettylights-syntax-brackethighlighter-angle: #57606a;
+ --color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f;
+ --color-prettylights-syntax-constant-other-reference-link: #0a3069;
+ --color-fg-default: #24292f;
+ --color-fg-muted: #57606a;
+ --color-fg-subtle: #6e7781;
+ --color-canvas-default: transparent;
+ --color-canvas-subtle: #f6f8fa;
+ --color-border-default: #d0d7de;
+ --color-border-muted: hsla(210, 18%, 87%, 1);
+ --color-neutral-muted: rgba(175, 184, 193, 0.2);
+ --color-accent-fg: #0969da;
+ --color-accent-emphasis: #0969da;
+ --color-attention-subtle: #fff8c5;
+ --color-danger-fg: #cf222e;
+}
+
+.markdown-body {
+ -ms-text-size-adjust: 100%;
+ -webkit-text-size-adjust: 100%;
+ margin: 0;
+ color: #101828;
+ background-color: var(--color-canvas-default);
+ font-size: 14px;
+ font-weight: 400;
+ line-height: 1.5;
+ word-wrap: break-word;
+ user-select: text;
+}
+
+.light {
+ @include light;
+}
+
+:root {
+ @include light;
+}
+
+@media (prefers-color-scheme: light) {
+ :root {
+ @include light;
+ }
+}
+
+.markdown-body .octicon {
+ display: inline-block;
+ fill: currentColor;
+ vertical-align: text-bottom;
+}
+
+.markdown-body h1:hover .anchor .octicon-link:before,
+.markdown-body h2:hover .anchor .octicon-link:before,
+.markdown-body h3:hover .anchor .octicon-link:before,
+.markdown-body h4:hover .anchor .octicon-link:before,
+.markdown-body h5:hover .anchor .octicon-link:before,
+.markdown-body h6:hover .anchor .octicon-link:before {
+ width: 16px;
+ height: 16px;
+ content: " ";
+ display: inline-block;
+ background-color: currentColor;
+ -webkit-mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>");
+ mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' aria-hidden='true'><path fill-rule='evenodd' d='M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z'></path></svg>");
+}
+
+.markdown-body details,
+.markdown-body figcaption,
+.markdown-body figure {
+ display: block;
+}
+
+.markdown-body summary {
+ display: list-item;
+}
+
+.markdown-body [hidden] {
+ display: none !important;
+}
+
+.markdown-body a {
+ background-color: transparent;
+ color: var(--color-accent-fg);
+ text-decoration: none;
+}
+
+.markdown-body abbr[title] {
+ border-bottom: none;
+ text-decoration: underline dotted;
+}
+
+.markdown-body b,
+.markdown-body strong {
+ font-weight: var(--base-text-weight-semibold, 600);
+}
+
+.markdown-body dfn {
+ font-style: italic;
+}
+
+.markdown-body mark {
+ background-color: var(--color-attention-subtle);
+ color: var(--color-fg-default);
+}
+
+.markdown-body small {
+ font-size: 90%;
+}
+
+.markdown-body sub,
+.markdown-body sup {
+ font-size: 75%;
+ line-height: 0;
+ position: relative;
+ vertical-align: baseline;
+}
+
+.markdown-body sub {
+ bottom: -0.25em;
+}
+
+.markdown-body sup {
+ top: -0.5em;
+}
+
+.markdown-body img {
+ border-style: none;
+ max-width: 100%;
+ box-sizing: content-box;
+ background-color: var(--color-canvas-default);
+}
+
+.markdown-body code,
+.markdown-body kbd,
+.markdown-body pre,
+.markdown-body samp {
+ font-family: monospace;
+ font-size: 1em;
+}
+
+.markdown-body figure {
+ margin: 1em 40px;
+}
+
+.markdown-body hr {
+ box-sizing: content-box;
+ overflow: hidden;
+ background: transparent;
+ border-bottom: 1px solid var(--color-border-muted);
+ height: 0.25em;
+ padding: 0;
+ margin: 24px 0;
+ background-color: var(--color-border-default);
+ border: 0;
+}
+
+.markdown-body input {
+ font: inherit;
+ margin: 0;
+ overflow: visible;
+ font-family: inherit;
+ font-size: inherit;
+ line-height: inherit;
+}
+
+.markdown-body [type="button"],
+.markdown-body [type="reset"],
+.markdown-body [type="submit"] {
+ -webkit-appearance: button;
+}
+
+.markdown-body [type="checkbox"],
+.markdown-body [type="radio"] {
+ box-sizing: border-box;
+ padding: 0;
+}
+
+.markdown-body [type="number"]::-webkit-inner-spin-button,
+.markdown-body [type="number"]::-webkit-outer-spin-button {
+ height: auto;
+}
+
+.markdown-body [type="search"]::-webkit-search-cancel-button,
+.markdown-body [type="search"]::-webkit-search-decoration {
+ -webkit-appearance: none;
+}
+
+.markdown-body ::-webkit-input-placeholder {
+ color: inherit;
+ opacity: 0.54;
+}
+
+.markdown-body ::-webkit-file-upload-button {
+ -webkit-appearance: button;
+ font: inherit;
+}
+
+.markdown-body a:hover {
+ text-decoration: underline;
+}
+
+.markdown-body ::placeholder {
+ color: var(--color-fg-subtle);
+ opacity: 1;
+}
+
+.markdown-body hr::before {
+ display: table;
+ content: "";
+}
+
+.markdown-body hr::after {
+ display: table;
+ clear: both;
+ content: "";
+}
+
+.markdown-body table {
+ border-spacing: 0;
+ border-collapse: collapse;
+ display: block;
+ width: max-content;
+ max-width: 100%;
+ overflow: auto;
+}
+
+.markdown-body td,
+.markdown-body th {
+ padding: 0;
+}
+
+.markdown-body details summary {
+ cursor: pointer;
+}
+
+.markdown-body details:not([open])>*:not(summary) {
+ display: none !important;
+}
+
+.markdown-body a:focus,
+.markdown-body [role="button"]:focus,
+.markdown-body input[type="radio"]:focus,
+.markdown-body input[type="checkbox"]:focus {
+ outline: 2px solid var(--color-accent-fg);
+ outline-offset: -2px;
+ box-shadow: none;
+}
+
+.markdown-body a:focus:not(:focus-visible),
+.markdown-body [role="button"]:focus:not(:focus-visible),
+.markdown-body input[type="radio"]:focus:not(:focus-visible),
+.markdown-body input[type="checkbox"]:focus:not(:focus-visible) {
+ outline: solid 1px transparent;
+}
+
+.markdown-body a:focus-visible,
+.markdown-body [role="button"]:focus-visible,
+.markdown-body input[type="radio"]:focus-visible,
+.markdown-body input[type="checkbox"]:focus-visible {
+ outline: 2px solid var(--color-accent-fg);
+ outline-offset: -2px;
+ box-shadow: none;
+}
+
+.markdown-body a:not([class]):focus,
+.markdown-body a:not([class]):focus-visible,
+.markdown-body input[type="radio"]:focus,
+.markdown-body input[type="radio"]:focus-visible,
+.markdown-body input[type="checkbox"]:focus,
+.markdown-body input[type="checkbox"]:focus-visible {
+ outline-offset: 0;
+}
+
+.markdown-body kbd {
+ display: inline-block;
+ padding: 3px 5px;
+ font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas,
+ Liberation Mono, monospace;
+ line-height: 10px;
+ color: var(--color-fg-default);
+ vertical-align: middle;
+ background-color: var(--color-canvas-subtle);
+ border: solid 1px var(--color-neutral-muted);
+ border-bottom-color: var(--color-neutral-muted);
+ border-radius: 6px;
+ box-shadow: inset 0 -1px 0 var(--color-neutral-muted);
+}
+
+.markdown-body h1,
+.markdown-body h2,
+.markdown-body h3,
+.markdown-body h4,
+.markdown-body h5,
+.markdown-body h6 {
+ margin-top: 24px;
+ margin-bottom: 16px;
+ font-weight: var(--base-text-weight-semibold, 600);
+ line-height: 1.25;
+}
+
+
+.markdown-body p {
+ margin-top: 0;
+ margin-bottom: 10px;
+}
+
+.markdown-body blockquote {
+ margin: 0;
+ padding: 0 8px;
+ border-left: 2px solid #2970FF;
+}
+
+.markdown-body ul,
+.markdown-body ol {
+ margin-top: 0;
+ margin-bottom: 0;
+ padding-left: 2em;
+}
+
+.markdown-body ol {
+ list-style: decimal;
+}
+
+.markdown-body ul {
+ list-style: disc;
+}
+
+.markdown-body ol ol,
+.markdown-body ul ol {
+ list-style-type: lower-roman;
+}
+
+.markdown-body ul ul ol,
+.markdown-body ul ol ol,
+.markdown-body ol ul ol,
+.markdown-body ol ol ol {
+ list-style-type: lower-alpha;
+}
+
+.markdown-body dd {
+ margin-left: 0;
+}
+
+.markdown-body tt,
+.markdown-body code,
+.markdown-body samp {
+ font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas,
+ Liberation Mono, monospace;
+ font-size: 12px;
+}
+
+.markdown-body pre {
+ margin-top: 0;
+ margin-bottom: 0;
+ font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas,
+ Liberation Mono, monospace;
+ font-size: 12px;
+ word-wrap: normal;
+}
+
+.markdown-body .octicon {
+ display: inline-block;
+ overflow: visible !important;
+ vertical-align: text-bottom;
+ fill: currentColor;
+}
+
+.markdown-body input::-webkit-outer-spin-button,
+.markdown-body input::-webkit-inner-spin-button {
+ margin: 0;
+ -webkit-appearance: none;
+ appearance: none;
+}
+
+.markdown-body::before {
+ display: table;
+ content: "";
+}
+
+.markdown-body::after {
+ display: table;
+ clear: both;
+ content: "";
+}
+
+.markdown-body>*:first-child {
+ margin-top: 0 !important;
+}
+
+.markdown-body>*:last-child {
+ margin-bottom: 0 !important;
+}
+
+.markdown-body a:not([href]) {
+ color: inherit;
+ text-decoration: none;
+}
+
+.markdown-body .absent {
+ color: var(--color-danger-fg);
+}
+
+.markdown-body .anchor {
+ float: left;
+ padding-right: 4px;
+ margin-left: -20px;
+ line-height: 1;
+}
+
+.markdown-body .anchor:focus {
+ outline: none;
+}
+
+.markdown-body p,
+.markdown-body blockquote,
+.markdown-body ul,
+.markdown-body ol,
+.markdown-body dl,
+.markdown-body table,
+.markdown-body pre,
+.markdown-body details {
+ margin-top: 0;
+ margin-bottom: 16px;
+}
+
+.markdown-body blockquote> :first-child {
+ margin-top: 0;
+}
+
+.markdown-body blockquote> :last-child {
+ margin-bottom: 0;
+}
+
+.markdown-body h1 .octicon-link,
+.markdown-body h2 .octicon-link,
+.markdown-body h3 .octicon-link,
+.markdown-body h4 .octicon-link,
+.markdown-body h5 .octicon-link,
+.markdown-body h6 .octicon-link {
+ color: var(--color-fg-default);
+ vertical-align: middle;
+ visibility: hidden;
+}
+
+.markdown-body h1:hover .anchor,
+.markdown-body h2:hover .anchor,
+.markdown-body h3:hover .anchor,
+.markdown-body h4:hover .anchor,
+.markdown-body h5:hover .anchor,
+.markdown-body h6:hover .anchor {
+ text-decoration: none;
+}
+
+.markdown-body h1:hover .anchor .octicon-link,
+.markdown-body h2:hover .anchor .octicon-link,
+.markdown-body h3:hover .anchor .octicon-link,
+.markdown-body h4:hover .anchor .octicon-link,
+.markdown-body h5:hover .anchor .octicon-link,
+.markdown-body h6:hover .anchor .octicon-link {
+ visibility: visible;
+}
+
+.markdown-body h1 tt,
+.markdown-body h1 code,
+.markdown-body h2 tt,
+.markdown-body h2 code,
+.markdown-body h3 tt,
+.markdown-body h3 code,
+.markdown-body h4 tt,
+.markdown-body h4 code,
+.markdown-body h5 tt,
+.markdown-body h5 code,
+.markdown-body h6 tt,
+.markdown-body h6 code {
+ padding: 0 0.2em;
+ font-size: inherit;
+}
+
+.markdown-body summary h1,
+.markdown-body summary h2,
+.markdown-body summary h3,
+.markdown-body summary h4,
+.markdown-body summary h5,
+.markdown-body summary h6 {
+ display: inline-block;
+}
+
+.markdown-body summary h1 .anchor,
+.markdown-body summary h2 .anchor,
+.markdown-body summary h3 .anchor,
+.markdown-body summary h4 .anchor,
+.markdown-body summary h5 .anchor,
+.markdown-body summary h6 .anchor {
+ margin-left: -40px;
+}
+
+.markdown-body summary h1,
+.markdown-body summary h2 {
+ padding-bottom: 0;
+ border-bottom: 0;
+}
+
+.markdown-body ul.no-list,
+.markdown-body ol.no-list {
+ padding: 0;
+ list-style-type: none;
+}
+
+.markdown-body ol[type="a"] {
+ list-style-type: lower-alpha;
+}
+
+.markdown-body ol[type="A"] {
+ list-style-type: upper-alpha;
+}
+
+.markdown-body ol[type="i"] {
+ list-style-type: lower-roman;
+}
+
+.markdown-body ol[type="I"] {
+ list-style-type: upper-roman;
+}
+
+.markdown-body ol[type="1"] {
+ list-style-type: decimal;
+}
+
+.markdown-body div>ol:not([type]) {
+ list-style-type: decimal;
+}
+
+.markdown-body ul ul,
+.markdown-body ul ol,
+.markdown-body ol ol,
+.markdown-body ol ul {
+ margin-top: 0;
+ margin-bottom: 0;
+}
+
+.markdown-body li>p {
+ margin-top: 16px;
+}
+
+.markdown-body li+li {
+ margin-top: 0.25em;
+}
+
+.markdown-body dl {
+ padding: 0;
+}
+
+.markdown-body dl dt {
+ padding: 0;
+ margin-top: 16px;
+ font-size: 1em;
+ font-style: italic;
+ font-weight: var(--base-text-weight-semibold, 600);
+}
+
+.markdown-body dl dd {
+ padding: 0 16px;
+ margin-bottom: 16px;
+}
+
+.markdown-body table th {
+ font-weight: var(--base-text-weight-semibold, 600);
+}
+
+.markdown-body table th,
+.markdown-body table td {
+ padding: 6px 13px;
+ border: 1px solid var(--color-border-default);
+}
+
+.markdown-body table tr {
+ background-color: var(--color-canvas-default);
+ border-top: 1px solid var(--color-border-muted);
+}
+
+.markdown-body table tr:nth-child(2n) {
+ background-color: var(--color-canvas-subtle);
+}
+
+.markdown-body table img {
+ background-color: transparent;
+}
+
+.markdown-body img[align="right"] {
+ padding-left: 20px;
+}
+
+.markdown-body img[align="left"] {
+ padding-right: 20px;
+}
+
+.markdown-body .emoji {
+ max-width: none;
+ vertical-align: text-top;
+ background-color: transparent;
+}
+
+.markdown-body span.frame {
+ display: block;
+ overflow: hidden;
+}
+
+.markdown-body span.frame>span {
+ display: block;
+ float: left;
+ width: auto;
+ padding: 7px;
+ margin: 13px 0 0;
+ overflow: hidden;
+ border: 1px solid var(--color-border-default);
+}
+
+.markdown-body span.frame span img {
+ display: block;
+ float: left;
+}
+
+.markdown-body span.frame span span {
+ display: block;
+ padding: 5px 0 0;
+ clear: both;
+ color: var(--color-fg-default);
+}
+
+.markdown-body span.align-center {
+ display: block;
+ overflow: hidden;
+ clear: both;
+}
+
+.markdown-body span.align-center>span {
+ display: block;
+ margin: 13px auto 0;
+ overflow: hidden;
+ text-align: center;
+}
+
+.markdown-body span.align-center span img {
+ margin: 0 auto;
+ text-align: center;
+}
+
+.markdown-body span.align-right {
+ display: block;
+ overflow: hidden;
+ clear: both;
+}
+
+.markdown-body span.align-right>span {
+ display: block;
+ margin: 13px 0 0;
+ overflow: hidden;
+ text-align: right;
+}
+
+.markdown-body span.align-right span img {
+ margin: 0;
+ text-align: right;
+}
+
+.markdown-body span.float-left {
+ display: block;
+ float: left;
+ margin-right: 13px;
+ overflow: hidden;
+}
+
+.markdown-body span.float-left span {
+ margin: 13px 0 0;
+}
+
+.markdown-body span.float-right {
+ display: block;
+ float: right;
+ margin-left: 13px;
+ overflow: hidden;
+}
+
+.markdown-body span.float-right>span {
+ display: block;
+ margin: 13px auto 0;
+ overflow: hidden;
+ text-align: right;
+}
+
+.markdown-body code,
+.markdown-body tt {
+ padding: 0.2em 0.4em;
+ margin: 0;
+ font-size: 85%;
+ white-space: break-spaces;
+ background-color: var(--color-neutral-muted);
+ border-radius: 6px;
+}
+
+.markdown-body code br,
+.markdown-body tt br {
+ display: none;
+}
+
+.markdown-body del code {
+ text-decoration: inherit;
+}
+
+.markdown-body samp {
+ font-size: 85%;
+}
+
+.markdown-body pre code {
+ font-size: 100%;
+}
+
+.markdown-body pre>code {
+ padding: 0;
+ margin: 0;
+ word-break: normal;
+ white-space: pre;
+ background: transparent;
+ border: 0;
+}
+
+.markdown-body .highlight {
+ margin-bottom: 16px;
+}
+
+.markdown-body .highlight pre {
+ margin-bottom: 0;
+ word-break: normal;
+}
+
+.markdown-body .highlight pre,
+.markdown-body pre {
+ padding: 16px;
+ background: #fff;
+ overflow: auto;
+ font-size: 85%;
+ line-height: 1.45;
+ border-radius: 6px;
+}
+
+.markdown-body pre code,
+.markdown-body pre tt {
+ display: inline-block;
+ max-width: 100%;
+ padding: 0;
+ margin: 0;
+ overflow-x: scroll;
+ line-height: inherit;
+ word-wrap: normal;
+ background-color: transparent;
+ border: 0;
+}
+
+.markdown-body .csv-data td,
+.markdown-body .csv-data th {
+ padding: 5px;
+ overflow: hidden;
+ font-size: 12px;
+ line-height: 1;
+ text-align: left;
+ white-space: nowrap;
+}
+
+.markdown-body .csv-data .blob-num {
+ padding: 10px 8px 9px;
+ text-align: right;
+ background: var(--color-canvas-default);
+ border: 0;
+}
+
+.markdown-body .csv-data tr {
+ border-top: 0;
+}
+
+.markdown-body .csv-data th {
+ font-weight: var(--base-text-weight-semibold, 600);
+ background: var(--color-canvas-subtle);
+ border-top: 0;
+}
+
+.markdown-body [data-footnote-ref]::before {
+ content: "[";
+}
+
+.markdown-body [data-footnote-ref]::after {
+ content: "]";
+}
+
+.markdown-body .footnotes {
+ font-size: 12px;
+ color: var(--color-fg-muted);
+ border-top: 1px solid var(--color-border-default);
+}
+
+.markdown-body .footnotes ol {
+ padding-left: 16px;
+}
+
+.markdown-body .footnotes ol ul {
+ display: inline-block;
+ padding-left: 16px;
+ margin-top: 16px;
+}
+
+.markdown-body .footnotes li {
+ position: relative;
+}
+
+.markdown-body .footnotes li:target::before {
+ position: absolute;
+ top: -8px;
+ right: -8px;
+ bottom: -8px;
+ left: -24px;
+ pointer-events: none;
+ content: "";
+ border: 2px solid var(--color-accent-emphasis);
+ border-radius: 6px;
+}
+
+.markdown-body .footnotes li:target {
+ color: var(--color-fg-default);
+}
+
+.markdown-body .footnotes .data-footnote-backref g-emoji {
+ font-family: monospace;
+}
+
+.markdown-body .pl-c {
+ color: var(--color-prettylights-syntax-comment);
+}
+
+.markdown-body .pl-c1,
+.markdown-body .pl-s .pl-v {
+ color: var(--color-prettylights-syntax-constant);
+}
+
+.markdown-body .pl-e,
+.markdown-body .pl-en {
+ color: var(--color-prettylights-syntax-entity);
+}
+
+.markdown-body .pl-smi,
+.markdown-body .pl-s .pl-s1 {
+ color: var(--color-prettylights-syntax-storage-modifier-import);
+}
+
+.markdown-body .pl-ent {
+ color: var(--color-prettylights-syntax-entity-tag);
+}
+
+.markdown-body .pl-k {
+ color: var(--color-prettylights-syntax-keyword);
+}
+
+.markdown-body .pl-s,
+.markdown-body .pl-pds,
+.markdown-body .pl-s .pl-pse .pl-s1,
+.markdown-body .pl-sr,
+.markdown-body .pl-sr .pl-cce,
+.markdown-body .pl-sr .pl-sre,
+.markdown-body .pl-sr .pl-sra {
+ color: var(--color-prettylights-syntax-string);
+}
+
+.markdown-body .pl-v,
+.markdown-body .pl-smw {
+ color: var(--color-prettylights-syntax-variable);
+}
+
+.markdown-body .pl-bu {
+ color: var(--color-prettylights-syntax-brackethighlighter-unmatched);
+}
+
+.markdown-body .pl-ii {
+ color: var(--color-prettylights-syntax-invalid-illegal-text);
+ background-color: var(--color-prettylights-syntax-invalid-illegal-bg);
+}
+
+.markdown-body .pl-c2 {
+ color: var(--color-prettylights-syntax-carriage-return-text);
+ background-color: var(--color-prettylights-syntax-carriage-return-bg);
+}
+
+.markdown-body .pl-sr .pl-cce {
+ font-weight: bold;
+ color: var(--color-prettylights-syntax-string-regexp);
+}
+
+.markdown-body .pl-ml {
+ color: var(--color-prettylights-syntax-markup-list);
+}
+
+.markdown-body .pl-mh,
+.markdown-body .pl-mh .pl-en,
+.markdown-body .pl-ms {
+ font-weight: bold;
+ color: var(--color-prettylights-syntax-markup-heading);
+}
+
+.markdown-body .pl-mi {
+ font-style: italic;
+ color: var(--color-prettylights-syntax-markup-italic);
+}
+
+.markdown-body .pl-mb {
+ font-weight: bold;
+ color: var(--color-prettylights-syntax-markup-bold);
+}
+
+.markdown-body .pl-md {
+ color: var(--color-prettylights-syntax-markup-deleted-text);
+ background-color: var(--color-prettylights-syntax-markup-deleted-bg);
+}
+
+.markdown-body .pl-mi1 {
+ color: var(--color-prettylights-syntax-markup-inserted-text);
+ background-color: var(--color-prettylights-syntax-markup-inserted-bg);
+}
+
+.markdown-body .pl-mc {
+ color: var(--color-prettylights-syntax-markup-changed-text);
+ background-color: var(--color-prettylights-syntax-markup-changed-bg);
+}
+
+.markdown-body .pl-mi2 {
+ color: var(--color-prettylights-syntax-markup-ignored-text);
+ background-color: var(--color-prettylights-syntax-markup-ignored-bg);
+}
+
+.markdown-body .pl-mdr {
+ font-weight: bold;
+ color: var(--color-prettylights-syntax-meta-diff-range);
+}
+
+.markdown-body .pl-ba {
+ color: var(--color-prettylights-syntax-brackethighlighter-angle);
+}
+
+.markdown-body .pl-sg {
+ color: var(--color-prettylights-syntax-sublimelinter-gutter-mark);
+}
+
+.markdown-body .pl-corl {
+ text-decoration: underline;
+ color: var(--color-prettylights-syntax-constant-other-reference-link);
+}
+
+.markdown-body g-emoji {
+ display: inline-block;
+ min-width: 1ch;
+ font-family: "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
+ font-size: 1em;
+ font-style: normal !important;
+ font-weight: var(--base-text-weight-normal, 400);
+ line-height: 1;
+ vertical-align: -0.075em;
+}
+
+.markdown-body g-emoji img {
+ width: 1em;
+ height: 1em;
+}
+
+.markdown-body .task-list-item {
+ list-style-type: none;
+}
+
+.markdown-body .task-list-item label {
+ font-weight: var(--base-text-weight-normal, 400);
+}
+
+.markdown-body .task-list-item.enabled label {
+ cursor: pointer;
+}
+
+.markdown-body .task-list-item+.task-list-item {
+ margin-top: 4px;
+}
+
+.markdown-body .task-list-item .handle {
+ display: none;
+}
+
+.markdown-body .task-list-item-checkbox {
+ margin: 0 0.2em 0.25em -1.4em;
+ vertical-align: middle;
+}
+
+.markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox {
+ margin: 0 -1.6em 0.25em 0.2em;
+}
+
+.markdown-body .contains-task-list {
+ position: relative;
+}
+
+.markdown-body .contains-task-list:hover .task-list-item-convert-container,
+.markdown-body .contains-task-list:focus-within .task-list-item-convert-container {
+ display: block;
+ width: auto;
+ height: 24px;
+ overflow: visible;
+ clip: auto;
+}
+
+.markdown-body ::-webkit-calendar-picker-indicator {
+ filter: invert(50%);
+}
\ No newline at end of file
diff --git a/web/config/index.ts b/web/config/index.ts
new file mode 100644
index 00000000000..f5a85b52a49
--- /dev/null
+++ b/web/config/index.ts
@@ -0,0 +1,104 @@
+const isDevelopment = process.env.NODE_ENV === 'development';
+
+export let apiPrefix = '';
+let publicApiPrefix = '';
+
+// NEXT_PUBLIC_API_PREFIX=/console/api NEXT_PUBLIC_PUBLIC_API_PREFIX=/api npm run start
+if (process.env.NEXT_PUBLIC_API_PREFIX && process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX) {
+ apiPrefix = process.env.NEXT_PUBLIC_API_PREFIX;
+ publicApiPrefix = process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX;
+} else if (
+ globalThis.document?.body?.getAttribute('data-api-prefix') &&
+ globalThis.document?.body?.getAttribute('data-pubic-api-prefix')
+) {
+ // Not bulild can not get env from process.env.NEXT_PUBLIC_ in browser https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
+ apiPrefix = globalThis.document.body.getAttribute('data-api-prefix') as string
+ publicApiPrefix = globalThis.document.body.getAttribute('data-pubic-api-prefix') as string
+} else {
+ if (isDevelopment) {
+ apiPrefix = 'https://cloud.dify.dev/console/api';
+ publicApiPrefix = 'https://dev.udify.app/api';
+ } else {
+ // const domainParts = globalThis.location?.host?.split('.');
+ // in production env, the host is dify.app . In other env, the host is [dev].dify.app
+ // const env = domainParts.length === 2 ? 'ai' : domainParts?.[0];
+ apiPrefix = '/console/api';
+ publicApiPrefix = `/api`; // avoid browser private mode api cross origin
+ }
+}
+
+
+export const API_PREFIX: string = apiPrefix;
+export const PUBLIC_API_PREFIX: string = publicApiPrefix;
+
+// mock server
+export const MOCK_API_PREFIX = 'http://127.0.0.1:3001'
+
+const EDITION = process.env.NEXT_PUBLIC_EDITION || globalThis.document?.body?.getAttribute('data-public-edition')
+export const IS_CE_EDITION = EDITION === 'SELF_HOSTED'
+
+export const TONE_LIST = [
+ {
+ id: 1,
+ name: 'Creative',
+ config: {
+ temperature: 0.8,
+ top_p: 0.9,
+ presence_penalty: 0.1,
+ frequency_penalty: 0.1,
+ },
+ },
+ {
+ id: 2,
+ name: 'Balanced',
+ config: {
+ temperature: 0.5,
+ top_p: 0.85,
+ presence_penalty: 0.2,
+ frequency_penalty: 0.3,
+ },
+ },
+ {
+ id: 3,
+ name: 'Precise',
+ config: {
+ temperature: 0.2,
+ top_p: 0.75,
+ presence_penalty: 0.5,
+ frequency_penalty: 0.5,
+ },
+ },
+ {
+ id: 4,
+ name: 'Custom',
+ },
+]
+
+export const LOCALE_COOKIE_NAME = 'locale'
+
+export const DEFAULT_VALUE_MAX_LEN = 48
+
+export const zhRegex = /^[\u4e00-\u9fa5]$/gm
+export const emojiRegex = /^[\uD800-\uDBFF][\uDC00-\uDFFF]$/gm
+export const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
+const MAX_ZN_VAR_NAME_LENGHT = 8
+const MAX_EN_VAR_VALUE_LENGHT = 16
+export const getMaxVarNameLength = (value: string) => {
+ if (zhRegex.test(value)) {
+ return MAX_ZN_VAR_NAME_LENGHT
+ }
+ return MAX_EN_VAR_VALUE_LENGHT
+}
+
+export const MAX_VAR_KEY_LENGHT = 16
+
+export const VAR_ITEM_TEMPLATE = {
+ key: '',
+ name: '',
+ type: 'string',
+ max_length: DEFAULT_VALUE_MAX_LEN,
+ required: true
+}
+
+
+
diff --git a/web/context/app-context.ts b/web/context/app-context.ts
new file mode 100644
index 00000000000..d31b9fedca0
--- /dev/null
+++ b/web/context/app-context.ts
@@ -0,0 +1,27 @@
+'use client'
+
+import { createContext, useContext } from 'use-context-selector'
+import type { App } from '@/types/app'
+import type { UserProfileResponse } from '@/models/common'
+
+export type AppContextValue = {
+ apps: App[]
+ mutateApps: () => void
+ userProfile: UserProfileResponse
+ mutateUserProfile: () => void
+}
+
+const AppContext = createContext<AppContextValue>({
+ apps: [],
+ mutateApps: () => { },
+ userProfile: {
+ id: '',
+ name: '',
+ email: '',
+ },
+ mutateUserProfile: () => { },
+})
+
+export const useAppContext = () => useContext(AppContext)
+
+export default AppContext
diff --git a/web/context/dataset-detail.ts b/web/context/dataset-detail.ts
new file mode 100644
index 00000000000..b507fbcc4cd
--- /dev/null
+++ b/web/context/dataset-detail.ts
@@ -0,0 +1,5 @@
+import { createContext } from 'use-context-selector'
+
+const DatasetDetailContext = createContext<{ indexingTechnique?: string; }>({})
+
+export default DatasetDetailContext
diff --git a/web/context/datasets-context.tsx b/web/context/datasets-context.tsx
new file mode 100644
index 00000000000..a954d612d4c
--- /dev/null
+++ b/web/context/datasets-context.tsx
@@ -0,0 +1,20 @@
+'use client'
+
+import { createContext, useContext } from 'use-context-selector'
+import type { DataSet } from '@/models/datasets'
+
+export type DatasetsContextValue = {
+ datasets: DataSet[]
+ mutateDatasets: () => void
+ currentDataset?: DataSet
+}
+
+const DatasetsContext = createContext<DatasetsContextValue>({
+ datasets: [],
+ mutateDatasets: () => {},
+ currentDataset: undefined
+})
+
+export const useDatasetsContext = () => useContext(DatasetsContext)
+
+export default DatasetsContext
diff --git a/web/context/debug-configuration.ts b/web/context/debug-configuration.ts
new file mode 100644
index 00000000000..bcf7ccd02f7
--- /dev/null
+++ b/web/context/debug-configuration.ts
@@ -0,0 +1,89 @@
+import { createContext } from 'use-context-selector'
+import type { CompletionParams, Inputs, ModelConfig, PromptConfig, MoreLikeThisConfig, SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
+import type { DataSet } from '@/models/datasets'
+
+type IDebugConfiguration = {
+ appId: string
+ hasSetAPIKEY: boolean
+ isTrailFinished: boolean
+ mode: string
+ conversationId: string | null // after first chat send
+ setConversationId: (conversationId: string | null) => void
+ introduction: string
+ setIntroduction: (introduction: string) => void
+ controlClearChatMessage: number
+ setControlClearChatMessage: (controlClearChatMessage: number) => void
+ prevPromptConfig: PromptConfig
+ setPrevPromptConfig: (prevPromptConfig: PromptConfig) => void
+ moreLikeThisConifg: MoreLikeThisConfig,
+ setMoreLikeThisConifg: (moreLikeThisConfig: MoreLikeThisConfig) => void
+ suggestedQuestionsAfterAnswerConfig: SuggestedQuestionsAfterAnswerConfig,
+ setSuggestedQuestionsAfterAnswerConfig: (suggestedQuestionsAfterAnswerConfig: SuggestedQuestionsAfterAnswerConfig) => void
+ formattingChanged: boolean
+ setFormattingChanged: (formattingChanged: boolean) => void
+ inputs: Inputs
+ setInputs: (inputs: Inputs) => void
+ query: string // user question
+ setQuery: (query: string) => void
+ // Belows are draft infos
+ completionParams: CompletionParams
+ setCompletionParams: (completionParams: CompletionParams) => void
+ // model_config
+ modelConfig: ModelConfig
+ setModelConfig: (modelConfig: ModelConfig) => void
+ dataSets: DataSet[]
+ setDataSets: (dataSet: DataSet[]) => void
+}
+
+const DebugConfigurationContext = createContext<IDebugConfiguration>({
+ appId: '',
+ hasSetAPIKEY: false,
+ isTrailFinished: false,
+ mode: '',
+ conversationId: '',
+ setConversationId: () => { },
+ introduction: '',
+ setIntroduction: () => { },
+ controlClearChatMessage: 0,
+ setControlClearChatMessage: () => { },
+ prevPromptConfig: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ setPrevPromptConfig: () => { },
+ moreLikeThisConifg: {
+ enabled: false,
+ },
+ setMoreLikeThisConifg: () => { },
+ suggestedQuestionsAfterAnswerConfig: {
+ enabled: false,
+ },
+ setSuggestedQuestionsAfterAnswerConfig: () => { },
+ formattingChanged: false,
+ setFormattingChanged: () => { },
+ inputs: {},
+ setInputs: () => { },
+ query: '',
+ setQuery: () => { },
+ completionParams: {
+ max_tokens: 16,
+ temperature: 1, // 0-2
+ top_p: 1,
+ presence_penalty: 1, // -2-2
+ frequency_penalty: 1, // -2-2
+ },
+ setCompletionParams: () => { },
+ modelConfig: {
+ provider: 'OPENAI', // 'OPENAI'
+ model_id: 'gpt-3.5-turbo', // 'gpt-3.5-turbo'
+ configs: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ },
+ setModelConfig: () => { },
+ dataSets: [],
+ setDataSets: () => { },
+})
+
+export default DebugConfigurationContext
diff --git a/web/context/i18n.ts b/web/context/i18n.ts
new file mode 100644
index 00000000000..1870b65302a
--- /dev/null
+++ b/web/context/i18n.ts
@@ -0,0 +1,18 @@
+import { createContext } from 'use-context-selector'
+import type { Locale } from '@/i18n'
+
+type II18NContext = {
+ locale: Locale
+ i18n: Record<string, any>,
+ setLocaleOnClient: (locale: Locale) => void
+ // setI8N: (i18n: Record<string, string>) => void,
+}
+
+const I18NContext = createContext<II18NContext>({
+ locale: 'en',
+ i18n: {},
+ setLocaleOnClient: (lang: Locale) => { }
+ // setI8N: () => {},
+})
+
+export default I18NContext
diff --git a/web/context/workspace-context.tsx b/web/context/workspace-context.tsx
new file mode 100644
index 00000000000..d25fe3c2a4e
--- /dev/null
+++ b/web/context/workspace-context.tsx
@@ -0,0 +1,35 @@
+'use client'
+
+import { createContext, useContext } from 'use-context-selector'
+import useSWR from 'swr'
+import { fetchWorkspaces } from '@/service/common'
+import type { IWorkspace } from '@/models/common'
+
+export type WorkspacesContextValue = {
+ workspaces: IWorkspace[]
+}
+
+const WorkspacesContext = createContext<WorkspacesContextValue>({
+ workspaces: []
+})
+
+interface IWorkspaceProviderProps {
+ children: React.ReactNode
+}
+export const WorkspaceProvider = ({
+ children
+}: IWorkspaceProviderProps) => {
+ const { data } = useSWR({ url: '/workspaces' }, fetchWorkspaces)
+
+ return (
+ <WorkspacesContext.Provider value={{
+ workspaces: data?.workspaces || []
+ }}>
+ {children}
+ </WorkspacesContext.Provider>
+ )
+}
+
+export const useWorkspacesContext = () => useContext(WorkspacesContext)
+
+export default WorkspacesContext
diff --git a/web/dictionaries/en.json b/web/dictionaries/en.json
new file mode 100644
index 00000000000..2ec65fce675
--- /dev/null
+++ b/web/dictionaries/en.json
@@ -0,0 +1,27 @@
+{
+ "common": {
+ "confrim": "Confirm",
+ "cancel": "Cancel",
+ "refresh": "Refresh"
+ },
+ "index": {
+ "welcome": "Welcome to "
+ },
+ "signin": {},
+ "app": {
+ "overview": {
+ "title": "Overview",
+ "To get started,": "To get started,",
+ "enter your OpenAI API key below": "enter your OpenAI API key below",
+ "Get your API key from OpenAI dashboard": "Get your API key from OpenAI dashboard",
+ "Token Usage": "Token Usage"
+ },
+ "logs": {
+ "title": "Logs",
+ "description": "You can review and annotate the conversation and response text of the LLM, which will be used for subsequent model fine-tuning."
+ },
+ "textGeneration": {
+ "history": "History"
+ }
+ }
+}
\ No newline at end of file
diff --git a/web/dictionaries/zh-Hans.json b/web/dictionaries/zh-Hans.json
new file mode 100644
index 00000000000..e88b03b733d
--- /dev/null
+++ b/web/dictionaries/zh-Hans.json
@@ -0,0 +1,27 @@
+{
+ "common": {
+ "confrim": "确定",
+ "cancel": "取消",
+ "refresh": "刷新"
+ },
+ "index": {
+ "welcome": "欢迎来到 "
+ },
+ "signin": {},
+ "app": {
+ "overview": {
+ "title": "概览",
+ "To get started,": "从这里开始",
+ "enter your OpenAI API key below 👇": "输入你的 OpenAI API 密钥👇",
+ "Get your API key from OpenAI dashboard": "去 OpenAI 管理面板获取",
+ "Token Usage": "Token 消耗"
+ },
+ "logs": {
+ "title": "日志",
+ "description": "日志记录了应用的运行情况,包括用户的输入和 AI 的回复。"
+ },
+ "textGeneration": {
+ "history": "历史"
+ }
+ }
+}
\ No newline at end of file
diff --git a/web/docker/entrypoint.sh b/web/docker/entrypoint.sh
new file mode 100644
index 00000000000..d22db21473e
--- /dev/null
+++ b/web/docker/entrypoint.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+set -e
+
+export NEXT_PUBLIC_DEPLOY_ENV=${DEPLOY_ENV}
+export NEXT_PUBLIC_EDITION=${EDITION}
+export NEXT_PUBLIC_API_PREFIX=${CONSOLE_URL}/console/api
+export NEXT_PUBLIC_PUBLIC_API_PREFIX=${APP_URL}/api
+
+/usr/local/bin/pm2 -v
+/usr/local/bin/pm2-runtime start /app/web/pm2.json
diff --git a/web/docker/pm2.json b/web/docker/pm2.json
new file mode 100644
index 00000000000..7929a8315d1
--- /dev/null
+++ b/web/docker/pm2.json
@@ -0,0 +1,12 @@
+{
+ "apps": [
+ {
+ "name": "WebApp",
+ "exec_mode": "cluster",
+ "instances": 1,
+ "script": "./node_modules/next/dist/bin/next",
+ "cwd": "/app/web",
+ "args": "start"
+ }
+ ]
+ }
diff --git a/web/hooks/use-breakpoints.ts b/web/hooks/use-breakpoints.ts
new file mode 100644
index 00000000000..1aab56a9fdb
--- /dev/null
+++ b/web/hooks/use-breakpoints.ts
@@ -0,0 +1,27 @@
+'use client'
+import React from 'react'
+
+export enum MediaType {
+ mobile = 'mobile',
+ tablet = 'tablet',
+ pc = 'pc',
+}
+
+const useBreakpoints = () => {
+ const [width, setWidth] = React.useState(globalThis.innerWidth);
+ const media = (() => {
+ if (width <= 640) return MediaType.mobile;
+ if (width <= 768) return MediaType.tablet;
+ return MediaType.pc;
+ })();
+
+ React.useEffect(() => {
+ const handleWindowResize = () => setWidth(window.innerWidth);
+ window.addEventListener("resize", handleWindowResize);
+ return () => window.removeEventListener("resize", handleWindowResize);
+ }, []);
+
+ return media;
+}
+
+export default useBreakpoints
\ No newline at end of file
diff --git a/web/hooks/use-copy-to-clipboard.ts b/web/hooks/use-copy-to-clipboard.ts
new file mode 100644
index 00000000000..76f792c6b47
--- /dev/null
+++ b/web/hooks/use-copy-to-clipboard.ts
@@ -0,0 +1,29 @@
+import { useState } from 'react'
+
+type CopiedValue = string | null
+type CopyFn = (text: string) => Promise<boolean>
+
+function useCopyToClipboard(): [CopiedValue, CopyFn] {
+ const [copiedText, setCopiedText] = useState<CopiedValue>(null)
+
+ const copy: CopyFn = async text => {
+ if (!navigator?.clipboard) {
+ console.warn('Clipboard not supported')
+ return false
+ }
+
+ try {
+ await navigator.clipboard.writeText(text)
+ setCopiedText(text)
+ return true
+ } catch (error) {
+ console.warn('Copy failed', error)
+ setCopiedText(null)
+ return false
+ }
+ }
+
+ return [copiedText, copy]
+}
+
+export default useCopyToClipboard
\ No newline at end of file
diff --git a/web/hooks/use-metadata.ts b/web/hooks/use-metadata.ts
new file mode 100644
index 00000000000..516047fda58
--- /dev/null
+++ b/web/hooks/use-metadata.ts
@@ -0,0 +1,391 @@
+"use client";
+import { useTranslation } from "react-i18next";
+import dayjs from "dayjs";
+import { formatNumber, formatFileSize, formatTime } from '@/utils/format'
+import type { DocType } from '@/models/datasets'
+
+export type inputType = 'input' | 'select' | 'textarea'
+export type metadataType = DocType | 'originInfo' | 'technicalParameters'
+
+type MetadataMap = Record<
+ metadataType,
+ {
+ text: string;
+ allowEdit?: boolean;
+ icon?: React.ReactNode;
+ iconName?: string;
+ subFieldsMap: Record<
+ string,
+ {
+ label: string;
+ inputType?: inputType;
+ field?: string;
+ render?: (value: any, total?: number) => React.ReactNode | string
+ }
+ >;
+ }
+>;
+
+const fieldPrefix = "datasetDocuments.metadata.field";
+
+export const useMetadataMap = (): MetadataMap => {
+ const { t } = useTranslation();
+ return {
+ book: {
+ text: t("datasetDocuments.metadata.type.book"),
+ iconName: "bookOpen",
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.book.title`) },
+ language: {
+ label: t(`${fieldPrefix}.book.language`),
+ inputType: "select",
+ },
+ author: { label: t(`${fieldPrefix}.book.author`) },
+ publisher: { label: t(`${fieldPrefix}.book.publisher`) },
+ publication_date: { label: t(`${fieldPrefix}.book.publicationDate`) },
+ isbn: { label: t(`${fieldPrefix}.book.ISBN`) },
+ category: {
+ label: t(`${fieldPrefix}.book.category`),
+ inputType: "select",
+ },
+ },
+ },
+ web_page: {
+ text: t("datasetDocuments.metadata.type.webPage"),
+ iconName: "globe",
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.webPage.title`) },
+ url: { label: t(`${fieldPrefix}.webPage.url`) },
+ language: {
+ label: t(`${fieldPrefix}.webPage.language`),
+ inputType: "select",
+ },
+ ['author/publisher']: { label: t(`${fieldPrefix}.webPage.authorPublisher`) },
+ publish_date: { label: t(`${fieldPrefix}.webPage.publishDate`) },
+ ['topics/keywords']: { label: t(`${fieldPrefix}.webPage.topicsKeywords`) },
+ description: { label: t(`${fieldPrefix}.webPage.description`) },
+ },
+ },
+ paper: {
+ text: t("datasetDocuments.metadata.type.paper"),
+ iconName: "graduationHat",
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.paper.title`) },
+ language: {
+ label: t(`${fieldPrefix}.paper.language`),
+ inputType: "select",
+ },
+ author: { label: t(`${fieldPrefix}.paper.author`) },
+ publish_date: { label: t(`${fieldPrefix}.paper.publishDate`) },
+ ['journal/conference_name']: {
+ label: t(`${fieldPrefix}.paper.journalConferenceName`),
+ },
+ ['volume/issue/page_numbers']: { label: t(`${fieldPrefix}.paper.volumeIssuePage`) },
+ doi: { label: t(`${fieldPrefix}.paper.DOI`) },
+ ['topics/keywords']: { label: t(`${fieldPrefix}.paper.topicsKeywords`) },
+ abstract: {
+ label: t(`${fieldPrefix}.paper.abstract`),
+ inputType: "textarea",
+ },
+ },
+ },
+ social_media_post: {
+ text: t("datasetDocuments.metadata.type.socialMediaPost"),
+ iconName: "atSign",
+ subFieldsMap: {
+ platform: { label: t(`${fieldPrefix}.socialMediaPost.platform`) },
+ ['author/username']: {
+ label: t(`${fieldPrefix}.socialMediaPost.authorUsername`),
+ },
+ publish_date: { label: t(`${fieldPrefix}.socialMediaPost.publishDate`) },
+ post_url: { label: t(`${fieldPrefix}.socialMediaPost.postURL`) },
+ ['topics/tags']: { label: t(`${fieldPrefix}.socialMediaPost.topicsTags`) },
+ },
+ },
+ personal_document: {
+ text: t("datasetDocuments.metadata.type.personalDocument"),
+ iconName: "file",
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.personalDocument.title`) },
+ author: { label: t(`${fieldPrefix}.personalDocument.author`) },
+ creation_date: {
+ label: t(`${fieldPrefix}.personalDocument.creationDate`),
+ },
+ last_modified_date: {
+ label: t(`${fieldPrefix}.personalDocument.lastModifiedDate`),
+ },
+ document_type: {
+ label: t(`${fieldPrefix}.personalDocument.documentType`),
+ inputType: "select",
+ },
+ ['tags/category']: {
+ label: t(`${fieldPrefix}.personalDocument.tagsCategory`),
+ },
+ },
+ },
+ business_document: {
+ text: t("datasetDocuments.metadata.type.businessDocument"),
+ iconName: "briefcase",
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.businessDocument.title`) },
+ author: { label: t(`${fieldPrefix}.businessDocument.author`) },
+ creation_date: {
+ label: t(`${fieldPrefix}.businessDocument.creationDate`),
+ },
+ last_modified_date: {
+ label: t(`${fieldPrefix}.businessDocument.lastModifiedDate`),
+ },
+ document_type: {
+ label: t(`${fieldPrefix}.businessDocument.documentType`),
+ inputType: "select",
+ },
+ ['department/team']: {
+ label: t(`${fieldPrefix}.businessDocument.departmentTeam`),
+ },
+ },
+ },
+ im_chat_log: {
+ text: t("datasetDocuments.metadata.type.IMChat"),
+ iconName: "messageTextCircle",
+ subFieldsMap: {
+ chat_platform: { label: t(`${fieldPrefix}.IMChat.chatPlatform`) },
+ ['chat_participants/group_name']: {
+ label: t(`${fieldPrefix}.IMChat.chatPartiesGroupName`),
+ },
+ start_date: { label: t(`${fieldPrefix}.IMChat.startDate`) },
+ end_date: { label: t(`${fieldPrefix}.IMChat.endDate`) },
+ participants: { label: t(`${fieldPrefix}.IMChat.participants`) },
+ topicsKeywords: {
+ label: t(`${fieldPrefix}.IMChat.topicsKeywords`),
+ inputType: "textarea",
+ },
+ fileType: { label: t(`${fieldPrefix}.IMChat.fileType`) },
+ },
+ },
+ wikipedia_entry: {
+ text: t("datasetDocuments.metadata.type.wikipediaEntry"),
+ allowEdit: false,
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.wikipediaEntry.title`) },
+ language: {
+ label: t(`${fieldPrefix}.wikipediaEntry.language`),
+ inputType: "select",
+ },
+ web_page_url: { label: t(`${fieldPrefix}.wikipediaEntry.webpageURL`) },
+ ['editor/contributor']: {
+ label: t(`${fieldPrefix}.wikipediaEntry.editorContributor`),
+ },
+ last_edit_date: {
+ label: t(`${fieldPrefix}.wikipediaEntry.lastEditDate`),
+ },
+ ['summary/introduction']: {
+ label: t(`${fieldPrefix}.wikipediaEntry.summaryIntroduction`),
+ inputType: "textarea",
+ },
+ },
+ },
+ synced_from_notion: {
+ text: t("datasetDocuments.metadata.type.notion"),
+ allowEdit: false,
+ subFieldsMap: {
+ title: { label: t(`${fieldPrefix}.notion.title`) },
+ language: { label: t(`${fieldPrefix}.notion.lang`), inputType: "select" },
+ ['author/creator']: { label: t(`${fieldPrefix}.notion.author`) },
+ creation_date: { label: t(`${fieldPrefix}.notion.createdTime`) },
+ last_modified_date: {
+ label: t(`${fieldPrefix}.notion.lastModifiedTime`),
+ },
+ notion_page_link: { label: t(`${fieldPrefix}.notion.url`) },
+ ['category/tags']: { label: t(`${fieldPrefix}.notion.tag`) },
+ description: { label: t(`${fieldPrefix}.notion.desc`) },
+ },
+ },
+ synced_from_github: {
+ text: t("datasetDocuments.metadata.type.github"),
+ allowEdit: false,
+ subFieldsMap: {
+ repository_name: { label: t(`${fieldPrefix}.github.repoName`) },
+ repository_description: { label: t(`${fieldPrefix}.github.repoDesc`) },
+ ['repository_owner/organization']: { label: t(`${fieldPrefix}.github.repoOwner`) },
+ code_filename: { label: t(`${fieldPrefix}.github.fileName`) },
+ code_file_path: { label: t(`${fieldPrefix}.github.filePath`) },
+ programming_language: { label: t(`${fieldPrefix}.github.programmingLang`) },
+ github_link: { label: t(`${fieldPrefix}.github.url`) },
+ open_source_license: { label: t(`${fieldPrefix}.github.license`) },
+ commit_date: { label: t(`${fieldPrefix}.github.lastCommitTime`) },
+ commit_author: {
+ label: t(`${fieldPrefix}.github.lastCommitAuthor`),
+ },
+ },
+ },
+ originInfo: {
+ text: "",
+ allowEdit: false,
+ subFieldsMap: {
+ name: { label: t(`${fieldPrefix}.originInfo.originalFilename`) },
+ "data_source_info.upload_file.size": {
+ label: t(`${fieldPrefix}.originInfo.originalFileSize`),
+ render: (value) => formatFileSize(value)
+ },
+ created_at: {
+ label: t(`${fieldPrefix}.originInfo.uploadDate`),
+ render: (value) => dayjs.unix(value).format(t('datasetDocuments.metadata.dateTimeFormat') as string)
+ },
+ completed_at: {
+ label: t(`${fieldPrefix}.originInfo.lastUpdateDate`),
+ render: (value) => dayjs.unix(value).format(t('datasetDocuments.metadata.dateTimeFormat') as string)
+ },
+ data_source_type: {
+ label: t(`${fieldPrefix}.originInfo.source`),
+ render: (value) => t(`datasetDocuments.metadata.source.${value}`)
+ },
+ },
+ },
+ technicalParameters: {
+ text: t("datasetDocuments.metadata.type.technicalParameters"),
+ allowEdit: false,
+ subFieldsMap: {
+ 'dataset_process_rule.mode': {
+ label: t(`${fieldPrefix}.technicalParameters.segmentSpecification`),
+ render: value => value === 'automatic' ? (t('datasetDocuments.embedding.automatic') as string) : (t('datasetDocuments.embedding.custom') as string)
+ },
+ 'dataset_process_rule.rules.segmentation.max_tokens': {
+ label: t(`${fieldPrefix}.technicalParameters.segmentLength`),
+ render: value => formatNumber(value)
+ },
+ average_segment_length: {
+ label: t(`${fieldPrefix}.technicalParameters.avgParagraphLength`),
+ render: (value) => `${formatNumber(value)} characters`
+ },
+ segment_count: {
+ label: t(`${fieldPrefix}.technicalParameters.paragraphs`),
+ render: (value) => `${formatNumber(value)} paragraphs`
+ },
+ hit_count: {
+ label: t(`${fieldPrefix}.technicalParameters.hitCount`),
+ render: (value, total) => {
+ const v = value || 0;
+ return `${!total ? 0 : ((v / total) * 100).toFixed(2)}% (${v}/${total})`
+ }
+ },
+ indexing_latency: {
+ label: t(`${fieldPrefix}.technicalParameters.embeddingTime`),
+ render: (value) => formatTime(value)
+ },
+ tokens: {
+ label: t(`${fieldPrefix}.technicalParameters.embeddedSpend`),
+ render: (value) => `${formatNumber(value)} tokens`
+ },
+ },
+ },
+ };
+};
+
+const langPrefix = "datasetDocuments.metadata.languageMap.";
+
+export const useLanguages = () => {
+ const { t } = useTranslation();
+ return {
+ zh: t(langPrefix + "zh"),
+ en: t(langPrefix + "en"),
+ es: t(langPrefix + "es"),
+ fr: t(langPrefix + "fr"),
+ de: t(langPrefix + "de"),
+ ja: t(langPrefix + "ja"),
+ ko: t(langPrefix + "ko"),
+ ru: t(langPrefix + "ru"),
+ ar: t(langPrefix + "ar"),
+ pt: t(langPrefix + "pt"),
+ it: t(langPrefix + "it"),
+ nl: t(langPrefix + "nl"),
+ pl: t(langPrefix + "pl"),
+ sv: t(langPrefix + "sv"),
+ tr: t(langPrefix + "tr"),
+ he: t(langPrefix + "he"),
+ hi: t(langPrefix + "hi"),
+ da: t(langPrefix + "da"),
+ fi: t(langPrefix + "fi"),
+ no: t(langPrefix + "no"),
+ hu: t(langPrefix + "hu"),
+ el: t(langPrefix + "el"),
+ cs: t(langPrefix + "cs"),
+ th: t(langPrefix + "th"),
+ id: t(langPrefix + "id"),
+ };
+};
+
+const bookCategoryPrefix = "datasetDocuments.metadata.categoryMap.book.";
+
+export const useBookCategories = () => {
+ const { t } = useTranslation();
+ return {
+ fiction: t(bookCategoryPrefix + "fiction"),
+ biography: t(bookCategoryPrefix + "biography"),
+ history: t(bookCategoryPrefix + "history"),
+ science: t(bookCategoryPrefix + "science"),
+ technology: t(bookCategoryPrefix + "technology"),
+ education: t(bookCategoryPrefix + "education"),
+ philosophy: t(bookCategoryPrefix + "philosophy"),
+ religion: t(bookCategoryPrefix + "religion"),
+ socialSciences: t(bookCategoryPrefix + "socialSciences"),
+ art: t(bookCategoryPrefix + "art"),
+ travel: t(bookCategoryPrefix + "travel"),
+ health: t(bookCategoryPrefix + "health"),
+ selfHelp: t(bookCategoryPrefix + "selfHelp"),
+ businessEconomics: t(bookCategoryPrefix + "businessEconomics"),
+ cooking: t(bookCategoryPrefix + "cooking"),
+ childrenYoungAdults: t(bookCategoryPrefix + "childrenYoungAdults"),
+ comicsGraphicNovels: t(bookCategoryPrefix + "comicsGraphicNovels"),
+ poetry: t(bookCategoryPrefix + "poetry"),
+ drama: t(bookCategoryPrefix + "drama"),
+ other: t(bookCategoryPrefix + "other"),
+ };
+};
+
+const personalDocCategoryPrefix =
+ "datasetDocuments.metadata.categoryMap.personalDoc.";
+
+export const usePersonalDocCategories = () => {
+ const { t } = useTranslation();
+ return {
+ notes: t(personalDocCategoryPrefix + "notes"),
+ blogDraft: t(personalDocCategoryPrefix + "blogDraft"),
+ diary: t(personalDocCategoryPrefix + "diary"),
+ researchReport: t(personalDocCategoryPrefix + "researchReport"),
+ bookExcerpt: t(personalDocCategoryPrefix + "bookExcerpt"),
+ schedule: t(personalDocCategoryPrefix + "schedule"),
+ list: t(personalDocCategoryPrefix + "list"),
+ projectOverview: t(personalDocCategoryPrefix + "projectOverview"),
+ photoCollection: t(personalDocCategoryPrefix + "photoCollection"),
+ creativeWriting: t(personalDocCategoryPrefix + "creativeWriting"),
+ codeSnippet: t(personalDocCategoryPrefix + "codeSnippet"),
+ designDraft: t(personalDocCategoryPrefix + "designDraft"),
+ personalResume: t(personalDocCategoryPrefix + "personalResume"),
+ other: t(personalDocCategoryPrefix + "other"),
+ };
+};
+
+const businessDocCategoryPrefix =
+ "datasetDocuments.metadata.categoryMap.businessDoc.";
+
+export const useBusinessDocCategories = () => {
+ const { t } = useTranslation();
+ return {
+ meetingMinutes: t(businessDocCategoryPrefix + "meetingMinutes"),
+ researchReport: t(businessDocCategoryPrefix + "researchReport"),
+ proposal: t(businessDocCategoryPrefix + "proposal"),
+ employeeHandbook: t(businessDocCategoryPrefix + "employeeHandbook"),
+ trainingMaterials: t(businessDocCategoryPrefix + "trainingMaterials"),
+ requirementsDocument: t(businessDocCategoryPrefix + "requirementsDocument"),
+ designDocument: t(businessDocCategoryPrefix + "designDocument"),
+ productSpecification: t(businessDocCategoryPrefix + "productSpecification"),
+ financialReport: t(businessDocCategoryPrefix + "financialReport"),
+ marketAnalysis: t(businessDocCategoryPrefix + "marketAnalysis"),
+ projectPlan: t(businessDocCategoryPrefix + "projectPlan"),
+ teamStructure: t(businessDocCategoryPrefix + "teamStructure"),
+ policiesProcedures: t(businessDocCategoryPrefix + "policiesProcedures"),
+ contractsAgreements: t(businessDocCategoryPrefix + "contractsAgreements"),
+ emailCorrespondence: t(businessDocCategoryPrefix + "emailCorrespondence"),
+ other: t(businessDocCategoryPrefix + "other"),
+ };
+};
diff --git a/web/i18n/client.ts b/web/i18n/client.ts
new file mode 100644
index 00000000000..39b6d016562
--- /dev/null
+++ b/web/i18n/client.ts
@@ -0,0 +1,16 @@
+import Cookies from 'js-cookie'
+import type { Locale } from '.'
+import { i18n } from '.'
+import { LOCALE_COOKIE_NAME } from '@/config'
+import { changeLanguage } from '@/i18n/i18next-config'
+
+// same logic as server
+export const getLocaleOnClient = (): Locale => {
+ return Cookies.get(LOCALE_COOKIE_NAME) as Locale || i18n.defaultLocale
+}
+
+export const setLocaleOnClient = (locale: Locale) => {
+ Cookies.set(LOCALE_COOKIE_NAME, locale)
+ changeLanguage(locale)
+ location.reload()
+}
diff --git a/web/i18n/i18next-config.ts b/web/i18n/i18next-config.ts
new file mode 100644
index 00000000000..49d729e7c74
--- /dev/null
+++ b/web/i18n/i18next-config.ts
@@ -0,0 +1,92 @@
+'use client'
+import i18n from 'i18next'
+import { initReactI18next } from 'react-i18next'
+import commonEn from './lang/common.en'
+import commonZh from './lang/common.zh'
+import loginEn from './lang/login.en'
+import loginZh from './lang/login.zh'
+import registerEn from './lang/register.en'
+import registerZh from './lang/register.zh'
+import layoutEn from './lang/layout.en'
+import layoutZh from './lang/layout.zh'
+import appEn from './lang/app.en'
+import appZh from './lang/app.zh'
+import appOverviewEn from './lang/app-overview.en'
+import appOverviewZh from './lang/app-overview.zh'
+import appDebugEn from './lang/app-debug.en'
+import appDebugZh from './lang/app-debug.zh'
+import appApiEn from './lang/app-api.en'
+import appApiZh from './lang/app-api.zh'
+import appLogEn from './lang/app-log.en'
+import appLogZh from './lang/app-log.zh'
+import shareEn from './lang/share-app.en'
+import shareZh from './lang/share-app.zh'
+import datasetEn from './lang/dataset.en'
+import datasetZh from './lang/dataset.zh'
+import datasetDocumentsEn from './lang/dataset-documents.en'
+import datasetDocumentsZh from './lang/dataset-documents.zh'
+import datasetHitTestingEn from './lang/dataset-hit-testing.en'
+import datasetHitTestingZh from './lang/dataset-hit-testing.zh'
+import datasetSettingsEn from './lang/dataset-settings.en'
+import datasetSettingsZh from './lang/dataset-settings.zh'
+import datasetCreationEn from './lang/dataset-creation.en'
+import datasetCreationZh from './lang/dataset-creation.zh'
+import { getLocaleOnClient } from '@/i18n/client'
+
+const resources = {
+ 'en': {
+ translation: {
+ common: commonEn,
+ layout: layoutEn, // page layout
+ login: loginEn,
+ register: registerEn,
+ // app
+ app: appEn,
+ appOverview: appOverviewEn,
+ appDebug: appDebugEn,
+ appApi: appApiEn,
+ appLog: appLogEn,
+ // share
+ share: shareEn,
+ dataset: datasetEn,
+ datasetDocuments: datasetDocumentsEn,
+ datasetHitTesting: datasetHitTestingEn,
+ datasetSettings: datasetSettingsEn,
+ datasetCreation: datasetCreationEn,
+ },
+ },
+ 'zh-Hans': {
+ translation: {
+ common: commonZh,
+ layout: layoutZh,
+ login: loginZh,
+ register: registerZh,
+ // app
+ app: appZh,
+ appOverview: appOverviewZh,
+ appDebug: appDebugZh,
+ appApi: appApiZh,
+ appLog: appLogZh,
+ // share
+ share: shareZh,
+ dataset: datasetZh,
+ datasetDocuments: datasetDocumentsZh,
+ datasetHitTesting: datasetHitTestingZh,
+ datasetSettings: datasetSettingsZh,
+ datasetCreation: datasetCreationZh,
+ },
+ },
+}
+
+i18n.use(initReactI18next)
+ // init i18next
+ // for all options read: https://www.i18next.com/overview/configuration-options
+ .init({
+ lng: getLocaleOnClient(),
+ fallbackLng: 'en',
+ // debug: true,
+ resources,
+ })
+
+export const changeLanguage = i18n.changeLanguage
+export default i18n
diff --git a/web/i18n/i18next-serverside-config.ts b/web/i18n/i18next-serverside-config.ts
new file mode 100644
index 00000000000..fe89475f795
--- /dev/null
+++ b/web/i18n/i18next-serverside-config.ts
@@ -0,0 +1,26 @@
+import { createInstance } from 'i18next'
+import resourcesToBackend from 'i18next-resources-to-backend'
+import { initReactI18next } from 'react-i18next/initReactI18next'
+import { Locale } from '.'
+
+// https://locize.com/blog/next-13-app-dir-i18n/
+const initI18next = async (lng: Locale, ns: string) => {
+ const i18nInstance = createInstance()
+ await i18nInstance
+ .use(initReactI18next)
+ .use(resourcesToBackend((language: string, namespace: string) => import(`./lang/${namespace}.${language}.ts`)))
+ .init({
+ lng: lng === 'zh-Hans' ? 'zh' : lng,
+ ns,
+ fallbackLng: 'en',
+ })
+ return i18nInstance
+}
+
+export async function useTranslation(lng: Locale, ns = '', options: Record<string, any> = {}) {
+ const i18nextInstance = await initI18next(lng, ns)
+ return {
+ t: i18nextInstance.getFixedT(lng, ns, options.keyPrefix),
+ i18n: i18nextInstance
+ }
+}
\ No newline at end of file
diff --git a/web/i18n/index.ts b/web/i18n/index.ts
new file mode 100644
index 00000000000..914b8ae1128
--- /dev/null
+++ b/web/i18n/index.ts
@@ -0,0 +1,6 @@
+export const i18n = {
+ defaultLocale: 'en',
+ locales: ['en', 'zh-Hans'],
+} as const
+
+export type Locale = typeof i18n['locales'][number]
diff --git a/web/i18n/lang/app-api.en.ts b/web/i18n/lang/app-api.en.ts
new file mode 100644
index 00000000000..cf188e0106a
--- /dev/null
+++ b/web/i18n/lang/app-api.en.ts
@@ -0,0 +1,76 @@
+const translation = {
+ apiServer: "API Server",
+ apiKey: "API Key",
+ status: "Status",
+ disabled: "Disabled",
+ ok: "In Service",
+ copy: "Copy",
+ copied: "Copied",
+ never: "Never",
+ apiKeyModal: {
+ apiSecretKey: "API Secret key",
+ apiSecretKeyTips: "To prevent API abuse, protect your API Key. Avoid using it as plain text in front-end code. :)",
+ createNewSecretKey: "Create new Secret key",
+ secretKey: "Secret Key",
+ created: "CREATED",
+ lastUsed: "LAST USED",
+ generateTips: "Keep this key in a secure and accessible place."
+ },
+ actionMsg: {
+ deleteConfirmTitle: "Delete this secret key?",
+ deleteConfirmTips: "This action cannot be undone.",
+ ok: "OK"
+ },
+ completionMode: {
+ title: "Completion App API",
+ info: "For high-quality text generation, such as articles, summaries, and translations, use the completion-messages API with user input. Text generation relies on the model parameters and prompt templates set in Dify Prompt Engineering.",
+ createCompletionApi: "Create Completion Message",
+ createCompletionApiTip: "Create a Completion Message to support the question-and-answer mode.",
+ inputsTips: "(Optional) Provide user input fields as key-value pairs, corresponding to variables in Prompt Eng. Key is the variable name, Value is the parameter value. If the field type is Select, the submitted Value must be one of the preset choices.",
+ queryTips: "User input text content.",
+ blocking: "Blocking type, waiting for execution to complete and returning results. (Requests may be interrupted if the process is long)",
+ streaming: "streaming returns. Implementation of streaming return based on SSE (Server-Sent Events).",
+ messageFeedbackApi: "Message feedback (like)",
+ messageFeedbackApiTip: "Rate received messages on behalf of end-users with likes or dislikes. This data is visible in the Logs & Annotations page and used for future model fine-tuning.",
+ messageIDTip: "Message ID",
+ ratingTip: "like or dislike, null is undo",
+ parametersApi: "Obtain application parameter information",
+ parametersApiTip: "Retrieve configured Input parameters, including variable names, field names, types, and default values. Typically used for displaying these fields in a form or filling in default values after the client loads."
+ },
+ chatMode: {
+ title: "Chat App API",
+ info: "For versatile conversational apps using a Q&A format, call the chat-messages API to initiate dialogue. Maintain ongoing conversations by passing the returned conversation_id. Response parameters and templates depend on Dify Prompt Eng. settings.",
+ createChatApi: "Create chat message",
+ createChatApiTip: "Create a new conversation message or continue an existing dialogue.",
+ inputsTips: "(Optional) Provide user input fields as key-value pairs, corresponding to variables in Prompt Eng. Key is the variable name, Value is the parameter value. If the field type is Select, the submitted Value must be one of the preset choices.",
+ queryTips: "User input/question content",
+ blocking: "Blocking type, waiting for execution to complete and returning results. (Requests may be interrupted if the process is long)",
+ streaming: "streaming returns. Implementation of streaming return based on SSE (Server-Sent Events).",
+ conversationIdTip: "(Optional) Conversation ID: leave empty for first-time conversation; pass conversation_id from context to continue dialogue.",
+ messageFeedbackApi: "Message terminal user feedback, like",
+ messageFeedbackApiTip: "Rate received messages on behalf of end-users with likes or dislikes. This data is visible in the Logs & Annotations page and used for future model fine-tuning.",
+ messageIDTip: "Message ID",
+ ratingTip: "like or dislike, null is undo",
+ chatMsgHistoryApi: "Get the chat history message",
+ chatMsgHistoryApiTip: "The first page returns the latest `limit` bar, which is in reverse order.",
+ chatMsgHistoryConversationIdTip: "Conversation ID",
+ chatMsgHistoryFirstId: "ID of the first chat record on the current page. The default is none.",
+ chatMsgHistoryLimit: "How many chats are returned in one request",
+ conversationsListApi: "Get conversation list",
+ conversationsListApiTip: "Gets the session list of the current user. By default, the last 20 sessions are returned.",
+ conversationsListFirstIdTip: "The ID of the last record on the current page, default none.",
+ conversationsListLimitTip: "How many chats are returned in one request",
+ conversationRenamingApi: "Conversation renaming",
+ conversationRenamingApiTip: "Rename conversations; the name is displayed in multi-session client interfaces.",
+ conversationRenamingNameTip: "New name",
+ parametersApi: "Obtain application parameter information",
+ parametersApiTip: "Retrieve configured Input parameters, including variable names, field names, types, and default values. Typically used for displaying these fields in a form or filling in default values after the client loads."
+ },
+ develop: {
+ requestBody: "Request Body",
+ pathParams: "Path Params",
+ query: "Query"
+ }
+}
+
+export default translation
diff --git a/web/i18n/lang/app-api.zh.ts b/web/i18n/lang/app-api.zh.ts
new file mode 100644
index 00000000000..49dc184ddab
--- /dev/null
+++ b/web/i18n/lang/app-api.zh.ts
@@ -0,0 +1,76 @@
+const translation = {
+ apiServer: "API 服务器",
+ apiKey: "API 密钥",
+ status: "状态",
+ disabled: "已停用",
+ ok: "运行中",
+ copy: "复制",
+ copied: "已复制",
+ never: "从未",
+ apiKeyModal: {
+ apiSecretKey: "API 密钥",
+ apiSecretKeyTips: "如果不想你的应用 API 被滥用,请保护好你的 API Key :) 最佳实践是避免在前端代码中明文引用。",
+ createNewSecretKey: "创建密钥",
+ secretKey: "密钥",
+ created: "创建时间",
+ lastUsed: "最后使用",
+ generateTips: "请将此密钥保存在安全且可访问的地方。"
+ },
+ actionMsg: {
+ deleteConfirmTitle: "删除此密钥?",
+ deleteConfirmTips: "删除密钥无法撤销,正在使用中的应用会受影响。",
+ ok: "好的"
+ },
+ completionMode: {
+ title: "文本生成型应用 API",
+ info: "可用于生成高质量文本的应用,例如生成文章、摘要、翻译等,通过调用 completion-messages 接口,发送用户输入得到生成文本结果。用于生成文本的模型参数和提示词模版取决于开发者在 Dify 提示词编排页的设置。",
+ createCompletionApi: "创建文本补全消息",
+ createCompletionApiTip: "创建文本补全消息,支持一问一答模式。",
+ inputsTips: "(选填)以键值对方式提供用户输入字段,与提示词编排中的变量对应。Key 为变量名称,Value 是参数值。如果字段类型为 Select,传入的 Value 需为预设选项之一。",
+ queryTips: "用户输入的文本正文。",
+ blocking: "blocking 阻塞型,等待执行完毕后返回结果。(请求若流程较长可能会被中断)",
+ streaming: "streaming 流式返回。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现流式返回。",
+ messageFeedbackApi: "消息反馈(点赞)",
+ messageFeedbackApiTip: "代表最终用户对返回消息进行评价,可以点赞与点踩,该数据将在“日志与标注”页中可见,并用于后续的模型微调。",
+ messageIDTip: "消息 ID",
+ ratingTip: "like 或 dislike, 空值为撤销",
+ parametersApi: "获取应用配置信息",
+ parametersApiTip: "获取已配置的 Input 参数,包括变量名、字段名称、类型与默认值。通常用于客户端加载后显示这些字段的表单或填入默认值。"
+ },
+ chatMode: {
+ title: "对话型应用 API",
+ info: "可用于大部分场景的对话型应用,采用一问一答模式与用户持续对话。要开始一个对话请调用 chat-messages 接口,通过继续传入返回的 conversation_id 可持续保持该会话。",
+ createChatApi: "发送对话消息",
+ createChatApiTip: "创建会话消息,或基于此前的对话继续发送消息。",
+ inputsTips: "(选填)以键值对方式提供用户输入字段,与提示词编排中的变量对应。Key 为变量名称,Value 是参数值。如果字段类型为 Select,传入的 Value 需为预设选项之一。",
+ queryTips: " 用户输入/提问内容",
+ blocking: "blocking 阻塞型,等待执行完毕后返回结果。(请求若流程较长可能会被中断)",
+ streaming: "streaming 流式返回。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现流式返回。",
+ conversationIdTip: "(选填)会话标识符,首次对话可为空,如果要继续对话请传入上下文返回的 conversation_id",
+ messageFeedbackApi: "消息反馈(点赞)",
+ messageFeedbackApiTip: "代表最终用户对返回消息进行评价,可以点赞与点踩,该数据将在“日志与标注”页中可见,并用于后续的模型微调。",
+ messageIDTip: "消息 ID",
+ ratingTip: "like 或 dislike, 空值为撤销",
+ chatMsgHistoryApi: "获取会话历史消息",
+ chatMsgHistoryApiTip: "滚动加载形式返回历史聊天记录,第一页返回最新 `limit` 条,即:倒序返回。",
+ chatMsgHistoryConversationIdTip: "会话 ID",
+ chatMsgHistoryFirstId: "当前页第一条聊天记录的 ID,默认 none",
+ chatMsgHistoryLimit: "一次请求返回多少条聊天记录",
+ conversationsListApi: "获取会话列表",
+ conversationsListApiTip: "获取当前用户的会话列表,默认返回最近的 20 条。",
+ conversationsListFirstIdTip: " 当前页最前面一条记录的 ID,默认 none",
+ conversationsListLimitTip: "一次请求返回多少条记录",
+ conversationRenamingApi: "会话重命名",
+ conversationRenamingApiTip: "对会话进行重命名,会话名称用于显示在支持多会话的客户端上。",
+ conversationRenamingNameTip: "新的名称",
+ parametersApi: "获取应用配置信息",
+ parametersApiTip: "获取已配置的 Input 参数,包括变量名、字段名称、类型与默认值。通常用于客户端加载后显示这些字段的表单或填入默认值。"
+ },
+ develop: {
+ requestBody: "Request Body",
+ pathParams: "Path Params",
+ query: "Query"
+ }
+}
+
+export default translation
diff --git a/web/i18n/lang/app-debug.en.ts b/web/i18n/lang/app-debug.en.ts
new file mode 100644
index 00000000000..a7b87a7351e
--- /dev/null
+++ b/web/i18n/lang/app-debug.en.ts
@@ -0,0 +1,139 @@
+const translation = {
+ pageTitle: "Prompt Engineering",
+ operation: {
+ applyConfig: "Publish",
+ resetConfig: "Reset",
+ addFeature: "Add Feature",
+ stopResponding: "Stop responding",
+ },
+ notSetAPIKey: {
+ title: "LLM provider key has not been set",
+ trailFinished: "Trail finished",
+ description: "The LLM provider key has not been set, and it needs to be set before debugging.",
+ settingBtn: "Go to settings",
+ },
+ trailUseGPT4Info: {
+ title: 'Does not support gpt-4 now',
+ description: 'Use gpt-4, please set API Key.',
+ },
+ feature: {
+ groupChat: {
+ title: 'Chat enhance',
+ description: 'Add pre-conversation settings for apps can enhance user experience.'
+ },
+ groupExperience: {
+ title: 'Experience enhance',
+ },
+ conversationOpener: {
+ title: "Conversation remakers",
+ description: "In a chat app, the first sentence that the AI actively speaks to the user is usually used as a welcome."
+ },
+ suggestedQuestionsAfterAnswer: {
+ title: 'Follow-up',
+ description: 'Setting up next questions suggestion can give users a better chat.',
+ resDes: '3 suggestions for user next question.',
+ tryToAsk: 'Try to ask',
+ },
+ moreLikeThis: {
+ title: "More like this",
+ description: "Generate multiple texts at once, and then edit and continue to generate",
+ generateNumTip: "Number of each generated times",
+ tip: "Using this feature will incur additional tokens overhead"
+ },
+ dataSet: {
+ title: "Context",
+ noData: "You can import datasets as context",
+ words: "Words",
+ textBlocks: "Text Blocks",
+ selectTitle: "Select reference dataset",
+ selected: "Datasets selected",
+ noDataSet: "No dataset found",
+ toCreate: "Go to create",
+ notSupportSelectMulti: 'Currently only support one dataset'
+ }
+ },
+ resetConfig: {
+ title: "Confirm reset?",
+ message:
+ "Reset discards changes, restoring the last published configuration.",
+ },
+ errorMessage: {
+ nameOfKeyRequired: "name of the key: {{key}} required",
+ valueOfVarRequired: "Variables value can not be empty",
+ queryRequired: "Request text is required.",
+ waitForResponse:
+ "Please wait for the response to the previous message to complete.",
+ },
+ chatSubTitle: "Pre Prompt",
+ completionSubTitle: "Prefix Prompt",
+ promptTip:
+ "Prompts guide AI responses with instructions and constraints. Insert variables like {{input}}. This prompt won't be visible to users.",
+ formattingChangedTitle: "Formatting changed",
+ formattingChangedText:
+ "Modifying the formatting will reset the debug area, are you sure?",
+ variableTitle: "Variables",
+ variableTip:
+ "Users fill variables in a form, automatically replacing variables in the prompt.",
+ notSetVar: "Variables allow users to introduce prompt words or opening remarks when filling out forms. You can try entering \"{{input}}\" in the prompt words.",
+ autoAddVar: "Undefined variables referenced in pre-prompt, are you want to add them in user input form?",
+ variableTable: {
+ key: "Variable Key",
+ name: "User Input Field Name",
+ optional: "Optional",
+ type: "Input Type",
+ action: "Actions",
+ typeString: "String",
+ typeSelect: "Select",
+ },
+ varKeyError: {
+ canNoBeEmpty: "Variable key can not be empty",
+ tooLong: "Variable key: {{key}} too length. Can not be longer then 16 characters",
+ notValid: "Variable key: {{key}} is invalid. Can only contain letters, numbers, and underscores",
+ notStartWithNumber: "Variable key: {{key}} can not start with a number",
+ },
+ variableConig: {
+ modalTitle: "Field settings",
+ description: "Setting for variable {{varName}}",
+ fieldType: 'Field type',
+ string: 'Text',
+ select: 'Select',
+ notSet: 'Not set, try typing {{input}} in the prefix prompt',
+ stringTitle: "Form text box options",
+ maxLength: "Max length",
+ options: "Options",
+ addOption: "Add option",
+ },
+ openingStatement: {
+ title: "Opening remarks",
+ add: "Add",
+ writeOpner: "Write remarks",
+ placeholder: "Write your remarks message here",
+ noDataPlaceHolder:
+ "Starting the conversation with the user can help AI establish a closer connection with them in conversational applications.",
+ varTip: 'You can use variables, try type {{variable}}',
+ tooShort: "At least 20 words of initial prompt are required to generate an opening remarks for the conversation.",
+ notIncludeKey: "The initial prompt does not include the variable: {{key}}. Please add it to the initial prompt.",
+ },
+ modelConfig: {
+ model: "Model",
+ setTone: "Set tone of responses",
+ title: "Model and Parameters",
+ },
+ inputs: {
+ title: "Debugging and Previewing",
+ noPrompt: "Try write some prompt in pre-prompt input",
+ userInputField: "User Input Field",
+ noVar: "Fill in the value of the variable, which will be automatically replaced in the prompt word every time a new session is started.",
+ chatVarTip:
+ "Fill in the value of the variable, which will be automatically replaced in the prompt word every time a new session is started",
+ completionVarTip:
+ "Fill in the value of the variable, which will be automatically replaced in the prompt words every time a question is submitted.",
+ previewTitle: "Prompt preview",
+ queryTitle: "Query content",
+ queryPlaceholder: "Please enter the request text.",
+ run: "RUN",
+ },
+ result: "Output Text",
+};
+
+export default translation;
diff --git a/web/i18n/lang/app-debug.zh.ts b/web/i18n/lang/app-debug.zh.ts
new file mode 100644
index 00000000000..98db2a2bea3
--- /dev/null
+++ b/web/i18n/lang/app-debug.zh.ts
@@ -0,0 +1,134 @@
+const translation = {
+ pageTitle: "提示词编排",
+ operation: {
+ applyConfig: "发布",
+ resetConfig: "重置",
+ addFeature: "添加功能",
+ stopResponding: "停止响应",
+ },
+ notSetAPIKey: {
+ title: "LLM 提供者的密钥未设置",
+ trailFinished: "试用已结束",
+ description: "在调试之前需要设置 LLM 提供者的密钥。",
+ settingBtn: "去设置",
+ },
+ trailUseGPT4Info: {
+ title: '当前不支持使用 gpt-4',
+ description: '使用 gpt-4,请设置 API Key',
+ },
+ feature: {
+ groupChat: {
+ title: '聊天增强',
+ description: '为聊天型应用添加预对话设置,可以提升用户体验。'
+ },
+ groupExperience: {
+ title: '体验增强',
+ },
+ conversationOpener: {
+ title: "对话开场白",
+ description: "在对话型应用中,让 AI 主动说第一段话可以拉近与用户间的距离。"
+ },
+ suggestedQuestionsAfterAnswer: {
+ title: '下一步问题建议',
+ description: '设置下一步问题建议可以让用户更好的对话。',
+ resDes: '回答结束后系统会给出 3 个建议',
+ tryToAsk: '试着问问',
+ },
+ moreLikeThis: {
+ title: "更多类似的",
+ description: '一次生成多条文本,可在此基础上编辑并继续生成',
+ generateNumTip: "每次生成数",
+ tip: "使用此功能将会额外消耗 tokens"
+ },
+ dataSet: {
+ title: "上下文",
+ noData: "您可以导入数据集作为上下文",
+ words: "词",
+ textBlocks: "文本块",
+ selectTitle: "选择引用数据集",
+ selected: "个数据集被选中",
+ noDataSet: "未找到数据集",
+ toCreate: "去创建",
+ notSupportSelectMulti: '目前只支持引用一个数据集'
+ }
+ },
+ resetConfig: {
+ title: "确认重置?",
+ message: "重置将丢失当前页面所有修改,恢复至上次发布时的配置",
+ },
+ errorMessage: {
+ nameOfKeyRequired: "变量 {{key}} 对应的名称必填",
+ valueOfVarRequired: "变量值必填",
+ queryRequired: "主要文本必填",
+ waitForResponse: "请等待上条信息响应完成",
+ },
+ chatSubTitle: "对话前提示词",
+ completionSubTitle: "前缀提示词",
+ promptTip:
+ "提示词用于对 AI 的回复做出一系列指令和约束。可插入表单变量,例如 {{input}}。这段提示词不会被最终用户所看到。",
+ formattingChangedTitle: "编排已改变",
+ formattingChangedText: "修改编排将重置调试区域,确定吗?",
+ variableTitle: "变量",
+ notSetVar: "变量能使用户输入表单引入提示词或开场白,你可以试试在提示词中输入输入 {{input}}",
+ variableTip:
+ "变量将以表单形式让用户在对话前填写,用户填写的表单内容将自动替换提示词中的变量。",
+ autoAddVar: "提示词中引用了未定义的变量,是否自动添加到用户输入表单中?",
+ variableTable: {
+ key: "变量 Key",
+ name: "字段名称",
+ optional: "可选",
+ type: "类型",
+ action: "操作",
+ typeString: "文本",
+ typeSelect: "下拉选项",
+ },
+ varKeyError: {
+ canNoBeEmpty: "变量不能为空",
+ tooLong: "变量: {{key}} 长度太长。不能超过 16 个字符",
+ notValid: "变量: {{key}} 非法。只能包含英文字符,数字和下划线",
+ notStartWithNumber: "变量: {{key}} 不能以数字开头",
+ },
+ variableConig: {
+ modalTitle: "变量设置",
+ description: "设置变量 {{varName}}",
+ fieldType: '字段类型',
+ string: '文本',
+ select: '下拉选项',
+ notSet: '未设置,在 Prompt 中输入 {{input}} 试试',
+ stringTitle: "文本框设置",
+ maxLength: "最大长度",
+ options: "选项",
+ addOption: "添加选项",
+ },
+ openingStatement: {
+ title: "对话开场白",
+ add: "添加开场白",
+ writeOpner: "编写开场白",
+ placeholder: "请在这里输入开场白",
+ noDataPlaceHolder:
+ "在对话型应用中,让 AI 主动说第一段话可以拉近与用户间的距离。",
+ varTip: '你可以使用变量, 试试输入 {{variable}}',
+ tooShort: "对话前提示词至少 20 字才能生成开场白",
+ notIncludeKey: "前缀提示词中不包含变量 {{key}}。请在前缀提示词中添加该变量",
+ },
+ modelConfig: {
+ model: "语言模型",
+ setTone: "模型设置",
+ title: "模型及参数",
+ },
+ inputs: {
+ title: "调试与预览",
+ noPrompt: "尝试在对话前提示框中编写一些提示词",
+ userInputField: "用户输入",
+ noVar: "填入变量的值,每次启动新会话时该变量将自动替换提示词中的变量。",
+ chatVarTip: "填入变量的值,该值将在每次开启一个新会话时自动替换到提示词中",
+ completionVarTip: "填入变量的值,该值将在每次提交问题时自动替换到提示词中",
+ previewTitle: "提示词预览",
+ queryTitle: "查询内容",
+ queryPlaceholder: "请输入文本内容",
+ run: "运行",
+ },
+ result: "结果",
+};
+
+export default translation;
diff --git a/web/i18n/lang/app-log.en.ts b/web/i18n/lang/app-log.en.ts
new file mode 100644
index 00000000000..9df8cee527c
--- /dev/null
+++ b/web/i18n/lang/app-log.en.ts
@@ -0,0 +1,67 @@
+const translation = {
+ title: 'Logs & Annotations',
+ description: 'The logs record the running status of the application, including user inputs and AI replies.',
+ dateTimeFormat: 'MM/DD/YYYY hh:mm A',
+ table: {
+ header: {
+ time: 'Time',
+ endUser: 'End User',
+ input: 'Input',
+ output: 'Output',
+ summary: 'Summary',
+ messageCount: 'Message Count',
+ userRate: 'User Rate',
+ adminRate: 'Op. Rate',
+ },
+ pagination: {
+ previous: 'Prev',
+ next: 'Next',
+ },
+ empty: {
+ noChat: 'No conversation yet',
+ noOutput: 'No output',
+ element: {
+ title: 'Is anyone there?',
+ content: 'Observe and annotate interactions between end-users and AI applications here to continuously improve AI accuracy. You can try <shareLink>sharing</shareLink> or <testLink>testing</testLink> the Web App yourself, then return to this page.',
+ },
+ },
+ },
+ detail: {
+ time: 'Time',
+ conversationId: 'Conversation ID',
+ promptTemplate: 'Prompt Template',
+ promptTemplateBeforeChat: 'Prompt Template Before Chat · As System Message',
+ annotationTip: 'Improvements Marked by {{user}}',
+ timeConsuming: '',
+ second: 's',
+ tokenCost: 'Token spent',
+ loading: 'loading',
+ operation: {
+ like: 'like',
+ dislike: 'dislike',
+ addAnnotation: 'Add Improvement',
+ editAnnotation: 'Edit Improvement',
+ annotationPlaceholder: 'Enter the expected answer that you want AI to reply, which can be used for model fine-tuning and continuous improvement of text generation quality in the future.',
+ },
+ },
+ filter: {
+ period: {
+ today: 'Today',
+ last7days: 'Last 7 Days',
+ last4weeks: 'Last 4 weeks',
+ last3months: 'Last 3 months',
+ last12months: 'Last 12 months',
+ monthToDate: 'Month to date',
+ quarterToDate: 'Quarter to date',
+ yearToDate: 'Year to date',
+ allTime: 'All time',
+ },
+ annotation: {
+ all: 'All',
+ annotated: 'Annotated Improvements ({{count}} items)',
+ not_annotated: 'Not Annotated',
+ },
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/app-log.zh.ts b/web/i18n/lang/app-log.zh.ts
new file mode 100644
index 00000000000..4e8874d7141
--- /dev/null
+++ b/web/i18n/lang/app-log.zh.ts
@@ -0,0 +1,67 @@
+const translation = {
+ title: '日志与标注',
+ description: '日志记录了应用的运行情况,包括用户的输入和 AI 的回复。',
+ dateTimeFormat: 'YYYY-MM-DD HH:mm',
+ table: {
+ header: {
+ time: '时间',
+ endUser: '用户',
+ input: '输入',
+ output: '输出',
+ summary: '摘要',
+ messageCount: '消息数',
+ userRate: '用户反馈',
+ adminRate: '管理员反馈',
+ },
+ pagination: {
+ previous: '上一页',
+ next: '下一页',
+ },
+ empty: {
+ noChat: '未开始的对话',
+ noOutput: '无输出',
+ element: {
+ title: '这里有人吗',
+ content: '在这里观测和标注最终用户和 AI 应用程序之间的交互,以不断提高 AI 的准确性。您可以<testLink>试试</testLink> WebApp 或<shareLink>分享</shareLink>出去,然后返回此页面。',
+ },
+ },
+ },
+ detail: {
+ time: '时间',
+ conversationId: '对话 ID',
+ promptTemplate: '前缀提示词',
+ promptTemplateBeforeChat: '对话前提示词 · 以系统消息提交',
+ annotationTip: '{{user}} 标记的改进回复',
+ timeConsuming: '耗时',
+ second: ' 秒',
+ tokenCost: '花费 Token',
+ loading: '加载中',
+ operation: {
+ like: '赞同',
+ dislike: '反对',
+ addAnnotation: '标记改进回复',
+ editAnnotation: '编辑改进回复',
+ annotationPlaceholder: '输入你希望 AI 回复的预期答案,这在今后可用于模型微调,持续改进文本生成质量。',
+ },
+ },
+ filter: {
+ period: {
+ today: '今天',
+ last7days: '过去 7 天',
+ last4weeks: '过去 4 周',
+ last3months: '过去 3 月',
+ last12months: '过去 12 月',
+ monthToDate: '本月至今',
+ quarterToDate: '本季度至今',
+ yearToDate: '本年至今',
+ allTime: '所有时间',
+ },
+ annotation: {
+ all: '全部',
+ annotated: '已标注改进({{count}} 项)',
+ not_annotated: '未标注',
+ },
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/app-overview.en.ts b/web/i18n/lang/app-overview.en.ts
new file mode 100644
index 00000000000..97136db98c5
--- /dev/null
+++ b/web/i18n/lang/app-overview.en.ts
@@ -0,0 +1,102 @@
+const translation = {
+ welcome: {
+ firstStepTip: 'To get started,',
+ enterKeyTip: 'enter your OpenAI API Key below',
+ getKeyTip: 'Get your API Key from OpenAI dashboard',
+ placeholder: 'Your OpenAI API Key(eg.sk-xxxx)',
+ },
+ overview: {
+ title: 'Overview',
+ appInfo: {
+ explanation: 'Ready-to-use AI WebApp',
+ accessibleAddress: 'Public URL',
+ preview: 'Preview',
+ share: {
+ entry: 'Share',
+ explanation: 'Share the following URL to invite more people to access the application.',
+ shareUrl: 'Share URL',
+ copyLink: 'Copy Link',
+ regenerate: 'Regenerate',
+ },
+ preUseReminder: 'Please enable WebApp before continuing.',
+ settings: {
+ entry: 'Settings',
+ title: 'WebApp Settings',
+ webName: 'WebApp Name',
+ webDesc: 'WebApp Description',
+ webDescTip: 'This text will be displayed on the client side, providing basic guidance on how to use the application',
+ webDescPlaceholder: 'Enter the description of the WebApp',
+ language: 'Language',
+ more: {
+ entry: 'Show more settings',
+ copyright: 'Copyright',
+ copyRightPlaceholder: 'Enter the name of the author or organization',
+ privacyPolicy: 'Privacy Policy',
+ privacyPolicyPlaceholder: 'Enter the privacy policy',
+ privacyPolicyTip: 'Helps visitors understand the data the application collects, see Dify\'s <privacyPolicyLink>Privacy Policy</privacyPolicyLink>.',
+ },
+ },
+ customize: {
+ way: 'way',
+ entry: 'Want to customize your WebApp?',
+ title: 'Customize AI WebApp',
+ explanation: 'You can customize the frontend of the Web App to fit your scenario and style needs.',
+ way1: {
+ name: 'Fork the client code, modify it and deploy to Vercel (recommended)',
+ step1: 'Fork the client code and modify it',
+ step1Tip: 'Click here to fork the source code into your GitHub account and modify the code',
+ step1Operation: 'Dify-WebClient',
+ step2: 'Configure the Web',
+ step2Tip: 'Copy the Web API and APP ID,then paste them into the client code config/index.ts',
+ step3: 'Deploy to Vercel',
+ step3Tip: 'Click here to import the repository into Vercel and deploy',
+ step3Operation: 'Import repository',
+ },
+ way2: {
+ name: 'Write client-side code to call the API and deploy it to a server',
+ operation: 'Documentation',
+ },
+ },
+ },
+ apiInfo: {
+ title: 'Backend service API',
+ explanation: 'Easily integrated into your application',
+ accessibleAddress: 'API Token',
+ doc: 'API Reference',
+ },
+ status: {
+ running: 'In service',
+ disable: 'Disable',
+ },
+ },
+ analysis: {
+ title: 'Analysis',
+ totalMessages: {
+ title: 'Total Messages',
+ explanation: 'Daily AI interactions count; prompt engineering/debugging excluded.',
+ },
+ activeUsers: {
+ title: 'Active Users',
+ explanation: 'Unique users engaging in Q&A with AI; prompt engineering/debugging excluded.',
+ },
+ tokenUsage: {
+ title: 'Token Usage',
+ explanation: 'Reflects the daily token usage of the language model for the application, useful for cost control purposes.',
+ consumed: 'Consumed',
+ },
+ avgSessionInteractions: {
+ title: 'Avg. Session Interactions',
+ explanation: 'Continuous user-AI communication count; for conversation-based apps.',
+ },
+ userSatisfactionRate: {
+ title: 'User Satisfaction Rate',
+ explanation: 'The number of likes per 1,000 messages. This indicates the proportion of answers that users are highly satisfied with.',
+ },
+ avgResponseTime: {
+ title: 'Avg. Response Time',
+ explanation: 'Time (ms) for AI to process/respond; for text-based apps.',
+ },
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/app-overview.zh.ts b/web/i18n/lang/app-overview.zh.ts
new file mode 100644
index 00000000000..3a045602f92
--- /dev/null
+++ b/web/i18n/lang/app-overview.zh.ts
@@ -0,0 +1,102 @@
+const translation = {
+ welcome: {
+ firstStepTip: '开始之前,',
+ enterKeyTip: '请先在下方输入你的 OpenAI API Key',
+ getKeyTip: '从 OpenAI 获取你的 API Key',
+ placeholder: '你的 OpenAI API Key(例如 sk-xxxx)',
+ },
+ overview: {
+ title: '概览',
+ appInfo: {
+ explanation: '开箱即用的 AI WebApp',
+ accessibleAddress: '公开访问 URL',
+ preview: '预览',
+ share: {
+ entry: '分享',
+ explanation: '将以下网址分享出去,让更多人访问该应用',
+ shareUrl: '分享 URL',
+ copyLink: '复制链接',
+ regenerate: '重新生成',
+ },
+ preUseReminder: '使用前请先打开开关',
+ settings: {
+ entry: '设置',
+ title: 'WebApp 设置',
+ webName: 'WebApp 名称',
+ webDesc: 'WebApp 描述',
+ webDescTip: '以下文字将展示在客户端中,对应用进行说明和使用上的基本引导',
+ webDescPlaceholder: '请输入 WebApp 的描述',
+ language: '语言',
+ more: {
+ entry: '展示更多设置',
+ copyright: '版权',
+ copyRightPlaceholder: '请输入作者或组织名称',
+ privacyPolicy: '隐私政策',
+ privacyPolicyPlaceholder: '请输入隐私政策',
+ privacyPolicyTip: '帮助访问者了解该应用收集的数据,可参考 Dify 的<privacyPolicyLink>隐私政策</privacyPolicyLink>。',
+ },
+ },
+ customize: {
+ way: '方法',
+ entry: '想要进一步自定义 WebApp?',
+ title: '定制化 AI WebApp',
+ explanation: '你可以定制化 Web App 前端以符合你的情景与风格需求',
+ way1: {
+ name: 'Fork 客户端代码修改后部署到 Vercel(推荐)',
+ step1: 'Fork 客户端代码并修改',
+ step1Tip: '点击此处 Fork 源码到你的 GitHub 中,然后修改代码',
+ step1Operation: 'Dify-WebClient',
+ step2: '配置 Web APP',
+ step2Tip: '复制 Web API 秘钥 和 APP ID 拷贝到客户端代码 config/index.ts 中',
+ step3: '部署到 Vercel 中',
+ step3Tip: '点击此处将仓库导入到 Vercel 中部署',
+ step3Operation: '导入仓库',
+ },
+ way2: {
+ name: '编写客户端调用 API 并部署到服务器中',
+ operation: '查看文档',
+ },
+ },
+ },
+ apiInfo: {
+ title: '后端服务 API',
+ explanation: '可集成至你的应用的后端即服务',
+ accessibleAddress: 'API 访问凭据',
+ doc: '查阅 API 文档',
+ },
+ status: {
+ running: '运行中',
+ disable: '已停用',
+ },
+ },
+ analysis: {
+ title: '分析',
+ totalMessages: {
+ title: '全部消息数',
+ explanation: '反映 AI 每天的互动总次数,每回答用户一个问题算一条 Message。提示词编排和调试的消息不计入。',
+ },
+ activeUsers: {
+ title: '活跃用户数',
+ explanation: '与 AI 有效互动,即有一问一答以上的唯一用户数。提示词编排和调试的会话不计入。',
+ },
+ tokenUsage: {
+ title: '费用消耗',
+ explanation: '反映每日该应用请求语言模型的 Tokens 花费,用于成本控制。',
+ consumed: '耗费',
+ },
+ avgSessionInteractions: {
+ title: '平均会话互动数',
+ explanation: '反应每个会话用户的持续沟通次数,如果用户与 AI 问答了 10 轮,即为 10。该指标反映了用户粘性。仅在对话型应用提供。',
+ },
+ userSatisfactionRate: {
+ title: '用户满意度',
+ explanation: '每 1000 条消息的点赞数。反应了用户对回答十分满意的比例。',
+ },
+ avgResponseTime: {
+ title: '平均响应时间',
+ explanation: '衡量 AI 应用处理和回复用户请求所花费的平均时间,单位为毫秒,反映性能和用户体验。仅在文本型应用提供。',
+ },
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/app.en.ts b/web/i18n/lang/app.en.ts
new file mode 100644
index 00000000000..73c2a5b1b6b
--- /dev/null
+++ b/web/i18n/lang/app.en.ts
@@ -0,0 +1,40 @@
+const translation = {
+ createApp: 'Create new App',
+ modes: {
+ completion: 'Text Generator',
+ chat: 'Chat App',
+ },
+ createFromConfigFile: 'Create app from config file',
+ deleteAppConfirmTitle: 'Delete this app?',
+ deleteAppConfirmContent:
+ 'Deleting the app is irreversible. Users will no longer be able to access your app, and all prompt configurations and logs will be permanently deleted.',
+ appDeleted: 'App deleted',
+ appDeleteFailed: 'Failed to delete app',
+ join: 'Join the community',
+ communityIntro:
+ 'Discuss with team members, contributors and developers on different channels.',
+ roadmap: 'See our roadmap',
+ newApp: {
+ startToCreate: 'Let\'s start with your new app',
+ captionName: 'Give your app a name',
+ captionAppType: 'What kind of app do you want?',
+ previewDemo: 'Preview demo',
+ chatApp: 'Chat App',
+ chatAppIntro:
+ 'I want to build a chat-based application. This app uses a question-and-answer format, allowing for multiple rounds of continuous conversation.',
+ completeApp: 'Text Generator',
+ completeAppIntro:
+ 'I want to create an application that generates high-quality text based on prompts, such as generating articles, summaries, translations, and more.',
+ showTemplates: 'I want to choose from a template',
+ hideTemplates: 'Go back to mode selection',
+ Create: 'Create',
+ Cancel: 'Cancel',
+ nameNotEmpty: 'Name cannot be empty',
+ appTemplateNotSelected: 'Please select a template',
+ appTypeRequired: 'Please select an app type',
+ appCreated: 'App created',
+ appCreateFailed: 'Failed to create app',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/app.zh.ts b/web/i18n/lang/app.zh.ts
new file mode 100644
index 00000000000..03fde52c35c
--- /dev/null
+++ b/web/i18n/lang/app.zh.ts
@@ -0,0 +1,39 @@
+const translation = {
+ createApp: '创建应用',
+ modes: {
+ completion: '文本生成型',
+ chat: '对话型',
+ },
+ createFromConfigFile: '通过导入应用配置文件创建',
+ deleteAppConfirmTitle: '确认删除应用?',
+ deleteAppConfirmContent:
+ '删除应用将无法撤销。用户将不能访问你的应用,所有 Prompt 编排配置和日志均将一并被删除。',
+ appDeleted: '应用已删除',
+ appDeleteFailed: '应用删除失败',
+ join: '参与社区',
+ communityIntro: '与团队成员、贡献者和开发者在不同频道中交流',
+ roadmap: '产品路线图',
+ newApp: {
+ startToCreate: '开始创建一个新应用',
+ captionName: '给应用起个名字',
+ captionAppType: '想要哪种应用类型?',
+ previewDemo: '预览 Demo',
+ chatApp: '对话型应用',
+ chatAppIntro:
+ '我要构建一个聊天场景的应用。该应用采用一问一答模式与用户持续对话。',
+ completeApp: '文本生成应用',
+ completeAppIntro:
+ '我要构建一个根据提示生成高质量文本的应用,例如生成文章、摘要、翻译等',
+ showTemplates: '我想从范例模板中选择',
+ hideTemplates: '返回应用类型选择',
+ Create: '创建',
+ Cancel: '取消',
+ nameNotEmpty: '名称不能为空',
+ appTemplateNotSelected: '请选择应用模版',
+ appTypeRequired: '请选择应用类型',
+ appCreated: '应用已创建',
+ appCreateFailed: '应用创建失败',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/common.en.ts b/web/i18n/lang/common.en.ts
new file mode 100644
index 00000000000..6771cbc42c2
--- /dev/null
+++ b/web/i18n/lang/common.en.ts
@@ -0,0 +1,205 @@
+const translation = {
+ api: {
+ success: 'Success',
+ saved: 'Saved',
+ create: 'Created',
+ remove: 'Removed',
+ },
+ operation: {
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ clear: 'Clear',
+ save: 'Save',
+ edit: 'Edit',
+ add: 'Add',
+ refresh: 'Restart',
+ search: 'Search',
+ change: 'Change',
+ remove: 'Remove',
+ send: 'Send',
+ copy: 'Copy',
+ lineBreak: 'Line break',
+ sure: 'I\'m sure',
+ },
+ placeholder: {
+ input: 'Please enter',
+ select: 'Please select',
+ },
+ unit: {
+ char: 'chars',
+ },
+ actionMsg: {
+ modifiedSuccessfully: 'Modified successfully',
+ modificationFailed: 'Modification failed',
+ copySuccessfully: 'Copied successfully',
+ },
+ model: {
+ params: {
+ temperature: 'Temperature',
+ temperatureTip:
+ 'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',
+ topP: 'Top P',
+ topPTip:
+ 'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered.',
+ presencePenalty: 'Presence penalty',
+ presencePenaltyTip:
+ 'How much to penalize new tokens based on whether they appear in the text so far. Increases the model\'s likelihood to talk about new topics.',
+ frequencyPenalty: 'Frequency penalty',
+ frequencyPenaltyTip:
+ 'How much to penalize new tokens based on their existing frequency in the text so far. Decreases the model\'s likelihood to repeat the same line verbatim.',
+ maxToken: 'Max token',
+ maxTokenTip:
+ 'Max tokens generated is 2,048 or 4,000, depending on the model. Prompt and completion share this limit. One token is roughly 1 English character.',
+ },
+ tone: {
+ Creative: 'Creative',
+ Balanced: 'Balanced',
+ Precise: 'Precise',
+ Custom: 'Custom',
+ },
+ },
+ menus: {
+ status: 'beta',
+ apps: 'Apps',
+ plugins: 'Plugins',
+ pluginsTips: 'Integrate third-party plugins or create ChatGPT-compatible AI-Plugins.',
+ datasets: 'Datasets',
+ datasetsTips: 'COMING SOON: Import your own text data or write data in real-time via Webhook for LLM context enhancement.',
+ newApp: 'New App',
+ newDataset: 'Create dataset',
+ },
+ userProfile: {
+ settings: 'Settings',
+ workspace: 'Workspace',
+ createWorkspace: 'Create Workspace',
+ helpCenter: 'Help Document',
+ about: 'About',
+ logout: 'Log out',
+ },
+ settings: {
+ accountGroup: 'ACCOUNT',
+ workplaceGroup: 'WORKPLACE',
+ account: "My account",
+ members: "Members",
+ integrations: "Integrations",
+ language: "Language",
+ provider: "Model Provider"
+ },
+ account: {
+ avatar: 'Avatar',
+ name: 'Name',
+ email: 'Email',
+ langGeniusAccount: 'Dify account',
+ langGeniusAccountTip: 'Your Dify account and associated user data.',
+ editName: 'Edit Name',
+ showAppLength: 'Show {{length}} apps',
+ },
+ members: {
+ team: 'Team',
+ invite: 'Invite',
+ name: 'NAME',
+ lastActive: 'LAST ACTIVE',
+ role: 'ROLES',
+ pending: 'Pending...',
+ owner: 'Owner',
+ admin: 'Admin',
+ adminTip: 'Can build apps & manage team settings',
+ normal: 'Normal',
+ normalTip: 'Only can use apps,can not build apps',
+ inviteTeamMember: 'Invite team member',
+ inviteTeamMemberTip: 'The other person will receive an email. If he\'s already a Dify user, he can access your team data directly after signing in.',
+ email: 'Email',
+ emailInvalid: 'Invalid Email Format',
+ emailPlaceholder: 'Input Email',
+ sendInvite: 'Send Invite',
+ invitationSent: 'Invitation sent',
+ invitationSentTip: 'The invitation is sent, and they can sign in to Dify to access your team data.',
+ ok: 'OK',
+ removeFromTeam: 'Remove from team',
+ removeFromTeamTip: 'Will remove team access',
+ setAdmin: 'Set as administrator',
+ setMember: 'Set to ordinary member',
+ disinvite: 'Cancel the invitation',
+ deleteMember: 'Delete Member',
+ you: '(You)',
+ },
+ integrations: {
+ connected: 'Connected',
+ google: 'Google',
+ googleAccount: 'Login with Google account',
+ github: 'GitHub',
+ githubAccount: 'Login with GitHub account',
+ connect: 'Connect'
+ },
+ language: {
+ displayLanguage: 'Display Language',
+ timezone: 'Time Zone',
+ },
+ provider: {
+ apiKey: "API Key",
+ enterYourKey: "Enter your API key here",
+ invalidKey: "Invalid OpenAI API key",
+ validating: "Validating key...",
+ saveFailed: "Save api key failed",
+ apiKeyExceedBill: "This API KEY has no quota available, please read",
+ addKey: 'Add Key',
+ comingSoon: 'Coming Soon',
+ editKey: 'Edit',
+ invalidApiKey: 'Invalid API key',
+ azure: {
+ resourceName: 'Resource Name',
+ resourceNamePlaceholder: 'The name of your Azure OpenAI Resource.',
+ deploymentId: 'Deployment ID',
+ deploymentIdPlaceholder: 'The deployment name you chose when you deployed the model.',
+ apiVersion: 'API Version',
+ apiVersionPlaceholder: 'The API version to use for this operation.',
+ apiKey: 'API Key',
+ apiKeyPlaceholder: 'Enter your API key here',
+ helpTip: 'Learn Azure OpenAI Service',
+ },
+ openaiHosted: {
+ openaiHosted: 'Hosted OpenAI',
+ onTrial: 'ON TRIAL',
+ exhausted: 'QUOTA EXHAUSTED',
+ desc: 'The OpenAI hosting service provided by Dify allows you to use models such as GPT-3.5. Before your trial quota is used up, you need to set up other model providers.',
+ callTimes: 'Call times',
+ usedUp: 'Trial quota used up. Add own Model Provider.',
+ useYourModel: 'Currently using own Model Provider.',
+ close: 'Close',
+ },
+ encrypted: {
+ front: 'Your API KEY will be encrypted and stored using',
+ back: ' technology.',
+ }
+ },
+ about: {
+ changeLog: 'Changlog',
+ updateNow: 'Update now',
+ nowAvailable: 'Dify {{version}} is now available.',
+ latestAvailable: 'Dify {{version}} is the latest version available.',
+ },
+ appMenus: {
+ overview: 'Overview',
+ promptEng: 'Prompt Eng.',
+ apiAccess: 'API Access',
+ logAndAnn: 'Logs & Ann.',
+ },
+ environment: {
+ testing: 'TESTING',
+ development: 'DEVELOPMENT',
+ },
+ appModes: {
+ completionApp: 'Text Generator',
+ chatApp: 'Chat App',
+ },
+ datasetMenus: {
+ documents: 'Documents',
+ hitTesting: 'Hit Testing',
+ settings: 'Settings',
+ emptyTip: 'The data set has not been associated, please go to the application or plug-in to complete the association.',
+ viewDoc: 'View documentation',
+ relatedApp: 'linked apps',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/common.zh.ts b/web/i18n/lang/common.zh.ts
new file mode 100644
index 00000000000..a2f03a1bc16
--- /dev/null
+++ b/web/i18n/lang/common.zh.ts
@@ -0,0 +1,206 @@
+const translation = {
+ api: {
+ success: '成功',
+ saved: '已保存',
+ create: '已创建',
+ remove: '已移除',
+ },
+ operation: {
+ confirm: '确认',
+ cancel: '取消',
+ clear: '清空',
+ save: '保存',
+ edit: '编辑',
+ add: '添加',
+ refresh: '重新开始',
+ search: '搜索',
+ change: '更改',
+ remove: '移除',
+ send: '发送',
+ copy: '复制',
+ lineBreak: '换行',
+ sure: '我确定',
+ },
+ placeholder: {
+ input: '请输入',
+ select: '请选择',
+ },
+ unit: {
+ char: '个字符',
+ },
+ actionMsg: {
+ modifiedSuccessfully: '修改成功',
+ modificationFailed: '修改失败',
+ copySuccessfully: '复制成功',
+ },
+ model: {
+ params: {
+ temperature: '多样性',
+ temperatureTip:
+ '较高的 Temperature 设置将导致更多样和创造性的输出,而较低的 Temperature 将产生更保守的输出并且类似于训练数据。',
+ topP: '采样范围',
+ topPTip:
+ 'Top P值越高,输出与训练文本越相似,Top P值越低,输出越有创意和变化。它可用于使输出更适合特定用例。',
+ presencePenalty: '词汇控制',
+ presencePenaltyTip:
+ 'Presence penalty 是根据新词是否出现在目前的文本中来对其进行惩罚。正值将降低模型谈论新话题的可能性。',
+ frequencyPenalty: '重复控制',
+ frequencyPenaltyTip:
+ 'Frequency penalty 是根据重复词在目前文本中的出现频率来对其进行惩罚。正值将不太可能重复常用单词和短语。',
+ maxToken: '最大 Token',
+ maxTokenTip:
+ '生成的最大令牌数为 2,048 或 4,000,取决于模型。提示和完成共享令牌数限制。一个令牌约等于 1 个英文或 4 个中文字符。',
+ },
+ tone: {
+ Creative: '创意',
+ Balanced: '平衡',
+ Precise: '精确',
+ Custom: '自定义',
+ },
+ },
+ menus: {
+ status: 'beta',
+ apps: '应用',
+ plugins: '插件',
+ pluginsTips: '集成第三方插件或创建与 ChatGPT 兼容的 AI 插件。',
+ datasets: '数据集',
+ datasetsTips: '即将到来: 上传自己的长文本数据,或通过 Webhook 集成自己的数据源',
+ newApp: '创建应用',
+ newDataset: '创建数据集',
+ },
+ userProfile: {
+ settings: '设置',
+ workspace: '工作空间',
+ createWorkspace: '创建工作空间',
+ helpCenter: '帮助文档',
+ about: '关于',
+ logout: '登出',
+ },
+ settings: {
+ accountGroup: '账户',
+ workplaceGroup: '工作空间',
+ account: "我的账户",
+ members: "成员",
+ integrations: "集成",
+ language: "语言",
+ provider: "模型供应商"
+ },
+ account: {
+ avatar: '头像',
+ name: '用户名',
+ email: '邮箱',
+ edit: '编辑',
+ langGeniusAccount: 'Dify 账号',
+ langGeniusAccountTip: '您的 Dify 账号和相关的用户数据。',
+ editName: '编辑名字',
+ showAppLength: '显示 {{length}} 个应用',
+ },
+ members: {
+ team: '团队',
+ invite: '邀请',
+ name: '姓名',
+ lastActive: '上次活动时间',
+ role: '角色',
+ pending: '待定...',
+ owner: '所有者',
+ admin: '管理员',
+ adminTip: '能够建立应用程序和管理团队设置',
+ normal: '正常人',
+ normalTip: '只能使用应用程序,不能建立应用程序',
+ inviteTeamMember: '邀请团队成员',
+ inviteTeamMemberTip: '对方会收到一封邮件。如果他已经是 Dify 用户则可直接在登录后访问你的团队数据。',
+ email: '邮箱',
+ emailInvalid: '邮箱格式无效',
+ emailPlaceholder: '输入邮箱',
+ sendInvite: '发送邀请',
+ invitationSent: '邀请已发送',
+ invitationSentTip: '邀请已发送,对方登录 Dify 后即可访问你的团队数据。',
+ ok: '好的',
+ removeFromTeam: '移除团队',
+ removeFromTeamTip: '将取消团队访问',
+ setAdmin: '设为管理员',
+ setMember: '设为普通成员',
+ disinvite: '取消邀请',
+ deleteMember: '删除成员',
+ you: '(你)',
+ },
+ integrations: {
+ connected: '登录方式',
+ google: 'Google',
+ googleAccount: 'Google 账号登录',
+ github: 'GitHub',
+ githubAccount: 'GitHub 账号登录',
+ connect: '绑定'
+ },
+ language: {
+ displayLanguage: '界面语言',
+ timezone: '时区',
+ },
+ provider: {
+ apiKey: "API 密钥",
+ enterYourKey: "输入你的 API 密钥",
+ invalidKey: '无效的 OpenAI API 密钥',
+ validating: "验证密钥中...",
+ saveFailed: "API 密钥保存失败",
+ apiKeyExceedBill: "此 API KEY 已没有可用配额,请阅读",
+ addKey: '添加 密钥',
+ comingSoon: '即将推出',
+ editKey: '编辑',
+ invalidApiKey: '无效的 API 密钥',
+ azure: {
+ resourceName: 'Resource Name',
+ resourceNamePlaceholder: 'The name of your Azure OpenAI Resource.',
+ deploymentId: 'Deployment ID',
+ deploymentIdPlaceholder: 'The deployment name you chose when you deployed the model.',
+ apiVersion: 'API Version',
+ apiVersionPlaceholder: 'The API version to use for this operation.',
+ apiKey: 'API Key',
+ apiKeyPlaceholder: 'Enter your API key here',
+ helpTip: '了解 Azure OpenAI Service',
+ },
+ openaiHosted: {
+ openaiHosted: '托管 OpenAI',
+ onTrial: '体验',
+ exhausted: '超出限额',
+ desc: '托管 OpenAI 由 Dify 提供的托管 OpenAI 服务,你可以使用 GPT-3.5 等模型,在体验额度消耗完毕前你需要设置其它模型供应商。',
+ callTimes: '调用次数',
+ usedUp: '试用额度已用完,请在下方添加自己的模型供应商',
+ useYourModel: '当前正在使用你自己的模型供应商。',
+ close: '关闭',
+ },
+ encrypted: {
+ front: '密钥将使用 ',
+ back: ' 技术进行加密和存储。',
+ }
+ },
+ about: {
+ changeLog: '更新日志',
+ updateNow: '现在更新',
+ nowAvailable: 'Dify {{version}} 现已可用。',
+ latestAvailable: 'Dify {{version}} 已是最新版本。',
+ },
+ appMenus: {
+ overview: '概览',
+ promptEng: '提示词编排',
+ apiAccess: '访问 API',
+ logAndAnn: '日志与标注',
+ },
+ environment: {
+ testing: '测试环境',
+ development: '开发环境',
+ },
+ appModes: {
+ completionApp: '文本生成型应用',
+ chatApp: '对话型应用',
+ },
+ datasetMenus: {
+ documents: '文档',
+ hitTesting: '命中测试',
+ settings: '设置',
+ emptyTip: ' 数据集尚未关联,请前往应用程序或插件完成关联。',
+ viewDoc: '查看文档',
+ relatedApp: '个关联应用',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset-creation.en.ts b/web/i18n/lang/dataset-creation.en.ts
new file mode 100644
index 00000000000..2a0ecf574f6
--- /dev/null
+++ b/web/i18n/lang/dataset-creation.en.ts
@@ -0,0 +1,108 @@
+const translation = {
+ steps: {
+ header: {
+ creation: 'Create Dataset',
+ update: 'Add data',
+ },
+ one: 'Choose data source',
+ two: 'Text Preprocessing and Cleaning',
+ three: 'Execute and finish',
+ },
+ error: {
+ unavailable: 'This dataset is not avaliable',
+ },
+ stepOne: {
+ filePreview: 'File Preview',
+ dataSourceType: {
+ file: 'Import from text file',
+ notion: 'Sync from Notion',
+ web: 'Sync from web site',
+ },
+ uploader: {
+ title: 'Upload text file',
+ button: 'Drag and drop file, or',
+ browse: 'Browse',
+ tip: 'Supports txt, html, markdown, and pdf.',
+ validation: {
+ typeError: 'File type not supported',
+ size: 'File too large. Maximum is 15MB',
+ count: 'Multiple files not supported',
+ },
+ cancel: 'Cancel',
+ change: 'Change',
+ failed: 'Upload failed',
+ },
+ button: 'next',
+ emptyDatasetCreation: 'I want to create an empty dataset',
+ modal: {
+ title: 'Create an empty dataset',
+ tip: 'An empty dataset will contain no documents, and you can upload documents any time.',
+ input: 'Dataset name',
+ placeholder: 'Please input',
+ nameNotEmpty: 'Name cannot be empty',
+ nameLengthInvaild: 'Name must be between 1 to 40 characters',
+ cancelButton: 'Cancel',
+ confirmButton: 'Create',
+ failed: 'Creation failed',
+ },
+ },
+ stepTwo: {
+ segmentation: 'Segmentation settings',
+ auto: 'Automatic',
+ autoDescription: 'Automatically set segmentation and preprocessing rules. Unfamiliar users are recommended to select this.',
+ custom: 'Custom',
+ customDescription: 'Customize segmentation rules, segmentation length, and preprocessing rules, etc.',
+ separator: 'Segment identifier',
+ separatorPlaceholder: 'For example, newline (\\\\n) or special separator (such as "***")',
+ maxLength: 'Maximum segment length',
+ rules: 'Text preprocessing rules',
+ removeExtraSpaces: 'Replace consecutive spaces, newlines and tabs',
+ removeUrlEmails: 'Delete all URLs and email addresses',
+ removeStopwords: 'Remove stopwords such as "a", "an", "the"',
+ preview: 'Confirm & Preview',
+ reset: 'Reset',
+ indexMode: 'Index mode',
+ qualified: 'High Quality',
+ recommend: 'Recommend',
+ qualifiedTip: 'Call OpenAI\'s embedding interface for processing to provide higher accuracy when users query.',
+ warning: 'Please set up the model provider API key first.',
+ click: 'Go to settings',
+ economical: 'Economical',
+ economicalTip: 'Use offline vector engines, keyword indexes, etc. to reduce accuracy without spending tokens',
+ emstimateCost: 'Estimation',
+ emstimateSegment: 'Estimated segments',
+ segmentCount: 'segments',
+ calculating: 'Calculating...',
+ fileName: 'Preprocess document',
+ lastStep: 'Last step',
+ nextStep: 'Save & Process',
+ sideTipTitle: 'Why segment and preprocess?',
+ sideTipP1: 'When processing text data, segmentation and cleaning are two important preprocessing steps.',
+ sideTipP2: 'Segmentation splits long text into paragraphs so models can understand better. This improves the quality and relevance of model results.',
+ sideTipP3: 'Cleaning removes unnecessary characters and formats, making datasets cleaner and easier to parse.',
+ sideTipP4: 'Proper segmentation and cleaning improve model performance, providing more accurate and valuable results.',
+ previewTitle: 'Preview',
+ characters: 'characters',
+ indexSettedTip: 'To change the index method, please go to the ',
+ datasetSettingLink: 'dataset settings.',
+ },
+ stepThree: {
+ creationTitle: '🎉 Dataset created',
+ creationContent: 'We automatically named the dataset, you can modify it at any time',
+ label: 'Dataset name',
+ additionTitle: '🎉 Document uploaded',
+ additionP1: 'The document has been uploaded to the dataset',
+ additionP2: ', you can find it in the document list of the dataset。',
+ stop: 'Stop processing',
+ resume: 'Resume processing',
+ navTo: 'Go to document',
+ sideTipTitle: 'What\'s next',
+ sideTipContent: 'After the document finishes indexing, the dataset can be integrated into the application as context, you can find the context setting in the prompt orchestration page. You can also create it as an independent ChatGPT indexing plugin for release.',
+ modelTitle: 'Are you sure to stop embedding?',
+ modelContent: 'If you need to resume processing later, you will continue from where you left off.',
+ modelButtonConfirm: "Confirm",
+ modelButtonCancel: 'Cancel'
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset-creation.zh.ts b/web/i18n/lang/dataset-creation.zh.ts
new file mode 100644
index 00000000000..4fbaea96617
--- /dev/null
+++ b/web/i18n/lang/dataset-creation.zh.ts
@@ -0,0 +1,108 @@
+const translation = {
+ steps: {
+ header: {
+ creation: '创建数据集',
+ update: '上传文件',
+ },
+ one: '选择数据源',
+ two: '文本分段与清洗',
+ three: '处理并完成',
+ },
+ error: {
+ unavailable: '该数据集不可用',
+ },
+ stepOne: {
+ filePreview: '文件预览',
+ dataSourceType: {
+ file: '导入已有文本',
+ notion: '同步自 Notion 内容',
+ web: '同步自 Web 站点',
+ },
+ uploader: {
+ title: '上传文本文件',
+ button: '拖拽文件至此,或者',
+ browse: '选择文件',
+ tip: '已支持 TXT, HTML, Markdown, PDF',
+ validation: {
+ typeError: '文件类型不支持',
+ size: '文件太大了,不能超过 15MB',
+ count: '暂不支持多个文件',
+ },
+ cancel: '取消',
+ change: '更改文件',
+ failed: '上传失败',
+ },
+ button: '下一步',
+ emptyDatasetCreation: '创建一个空数据集',
+ modal: {
+ title: '创建空数据集',
+ tip: '空数据集中还没有文档,你可以在今后任何时候上传文档至该数据集。',
+ input: '数据集名称',
+ placeholder: '请输入数据集名称',
+ nameNotEmpty: '名称不能为空',
+ nameLengthInvaild: '名称长度不能超过 40 个字符',
+ cancelButton: '取消',
+ confirmButton: '创建',
+ failed: '创建失败',
+ },
+ },
+ stepTwo: {
+ segmentation: '分段设置',
+ auto: '自动分段与清洗',
+ autoDescription: '自动设置分段规则与预处理规则,如果不了解这些参数建议选择此项',
+ custom: '自定义',
+ customDescription: '自定义分段规则、分段长度以及预处理规则等参数',
+ separator: '分段标识符',
+ separatorPlaceholder: '例如换行符(\n)或特定的分隔符(如 "***")',
+ maxLength: '分段最大长度',
+ rules: '文本预处理规则',
+ removeExtraSpaces: '替换掉连续的空格、换行符和制表符',
+ removeUrlEmails: '删除所有 URL 和电子邮件地址',
+ removeStopwords: '去除停用词,例如 “a”,“an”,“the” 等',
+ preview: '确认并预览',
+ reset: '重置',
+ indexMode: '索引方式',
+ qualified: '高质量',
+ recommend: '推荐',
+ qualifiedTip: '调用 OpenAI 的嵌入接口进行处理,以在用户查询时提供更高的准确度',
+ warning: '请先完成模型供应商的 API KEY 设置。.',
+ click: '前往设置',
+ economical: '经济',
+ economicalTip: '使用离线的向量引擎、关键词索引等方式,降低了准确度但无需花费 Token',
+ emstimateCost: '执行嵌入预估消耗',
+ emstimateSegment: '预估分段数',
+ segmentCount: '段',
+ calculating: '计算中...',
+ fileName: '预处理文档',
+ lastStep: '上一步',
+ nextStep: '保存并处理',
+ sideTipTitle: '为什么要分段和预处理?',
+ sideTipP1: '在处理文本数据时,分段和清洗是两个重要的预处理步骤。',
+ sideTipP2: '分段的目的是将长文本拆分成较小的段落,以便模型更有效地处理和理解。这有助于提高模型生成的结果的质量和相关性。',
+ sideTipP3: '清洗则是对文本进行预处理,删除不必要的字符、符号或格式,使数据集更加干净、整洁,便于模型解析。',
+ sideTipP4: '通过对数据集进行适当的分段和清洗,可以提高模型在实际应用中的表现,从而为用户提供更准确、更有价值的结果。',
+ previewTitle: '分段预览',
+ characters: '字符',
+ indexSettedTip: '要更改索引方法,请转到',
+ datasetSettingLink: '数据集设置。',
+ },
+ stepThree: {
+ creationTitle: '🎉 数据集已创建',
+ creationContent: '我们自动为该数据集起了个名称,您也可以随时修改',
+ label: '数据集名称',
+ additionTitle: '🎉 文档已上传',
+ additionP1: '文档已上传至数据集:',
+ additionP2: ',你可以在数据集的文档列表中找到它。',
+ stop: '停止处理',
+ resume: '恢复处理',
+ navTo: '前往文档',
+ sideTipTitle: '接下来做什么',
+ sideTipContent: '当文档完成索引处理后,数据集即可集成至应用内作为上下文使用,你可以在提示词编排页找到上下文设置。你也可以创建成可独立使用的 ChatGPT 索引插件发布。',
+ modelTitle: '确认停止索引过程吗?',
+ modelContent:'如果您需要稍后恢复处理,则从停止处继续。',
+ modelButtonConfirm: "确认停止",
+ modelButtonCancel: '取消'
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset-documents.en.ts b/web/i18n/lang/dataset-documents.en.ts
new file mode 100644
index 00000000000..1892ecdebcb
--- /dev/null
+++ b/web/i18n/lang/dataset-documents.en.ts
@@ -0,0 +1,314 @@
+const translation = {
+ list: {
+ title: "Documents",
+ desc: "All files of the dataset are shown here, and the entire dataset can be linked to Dify citations or indexed via the Chat plugin.",
+ addFile: "add file",
+ table: {
+ header: {
+ fileName: "FILE NAME",
+ words: "WORDS",
+ hitCount: "HIT COUNT",
+ uploadTime: "UPLOAD TIME",
+ status: "STATUS",
+ action: "ACTION",
+ },
+ },
+ action: {
+ uploadFile: 'Upload new file',
+ settings: 'Segment settings',
+ archive: 'Archive',
+ delete: "Delete",
+ enableWarning: 'Archived file cannot be enabled',
+ },
+ index: {
+ enable: 'Enable',
+ disable: 'Disable',
+ all: 'All',
+ enableTip: 'The file can be indexed',
+ disableTip: 'The file cannot be indexed',
+ },
+ status: {
+ queuing: 'Queuing',
+ indexing: 'Indexing',
+ parsed: 'Parsed',
+ error: 'Error',
+ available: 'Available',
+ enabled: 'Enabled',
+ disabled: 'Disabled',
+ archived: 'Archived',
+ },
+ empty: {
+ title: "There is no documentation yet",
+ upload: {
+ tip: "You can upload files, sync from the website, or from webb apps like Notion, GitHub, etc.",
+ },
+ sync: {
+ tip: "Dify will periodically download files from your Notion and complete processing.",
+ },
+ },
+ delete: {
+ title: 'Are you sure Delete?',
+ content: 'If you need to resume processing later, you will continue from where you left off'
+ }
+ },
+ metadata: {
+ title: "Metadata",
+ desc: "Labeling metadata for documents allows AI to access them in a timely manner and exposes the source of references for users.",
+ dateTimeFormat: 'MMMM D, YYYY hh:mm A',
+ docTypeSelectTitle: "Please select a document type",
+ docTypeChangeTitle: "Change document type",
+ docTypeSelectWarning:
+ "If the document type is changed, the now filled metadata will no longer be preserved",
+ firstMetaAction: "Let's go",
+ placeholder: {
+ add: 'Add ',
+ select: 'Select ',
+ },
+ source: {
+ upload_file: 'Upload File',
+ notion: "Sync form Notion",
+ github: "Sync form Github",
+ },
+ type: {
+ book: "Book",
+ webPage: "Web Page",
+ paper: "Paper",
+ socialMediaPost: "Social Media Post",
+ personalDocument: "Personal Document",
+ businessDocument: "Business Document",
+ IMChat: "IM Chat",
+ wikipediaEntry: "Wikipedia Entry",
+ notion: "Sync form Notion",
+ github: "Sync form Github",
+ technicalParameters: 'Technical Parameters',
+ },
+ field: {
+ processRule: {
+ processDoc: 'Process Document',
+ segmentRule: 'Segment Rule',
+ segmentLength: 'Segment Length',
+ processClean: 'Text Process Clean',
+ },
+ book: {
+ title: "Title",
+ language: "Language",
+ author: "Author",
+ publisher: "Publisher",
+ publicationDate: "Publication Date",
+ ISBN: "ISBN",
+ category: "Category",
+ },
+ webPage: {
+ title: "Title",
+ url: "URL",
+ language: "Language",
+ authorPublisher: "Author/Publisher",
+ publishDate: "Publish Date",
+ topicsKeywords: "Topics/Keywords",
+ description: "Description",
+ },
+ paper: {
+ title: "Title",
+ language: "Language",
+ author: "Author",
+ publishDate: "Publish Date",
+ journalConferenceName: "Journal/Conference Name",
+ volumeIssuePage: "Volume/Issue/Page",
+ DOI: "DOI",
+ topicsKeywords: "Topics/Keywords",
+ abstract: "Abstract",
+ },
+ socialMediaPost: {
+ platform: "Platform",
+ authorUsername: "Author/Username",
+ publishDate: "Publish Date",
+ postURL: "Post URL",
+ topicsTags: "Topics/Tags",
+ },
+ personalDocument: {
+ title: "Title",
+ author: "Author",
+ creationDate: "Creation Date",
+ lastModifiedDate: "Last Modified Date",
+ documentType: "Document Type",
+ tagsCategory: "Tags/Category",
+ },
+ businessDocument: {
+ title: "Title",
+ author: "Author",
+ creationDate: "Creation Date",
+ lastModifiedDate: "Last Modified Date",
+ documentType: "Document Type",
+ departmentTeam: "Department/Team",
+ },
+ IMChat: {
+ chatPlatform: "Chat Platform",
+ chatPartiesGroupName: "Chat Parties/Group Name",
+ participants: "Participants",
+ startDate: "Start Date",
+ endDate: "End Date",
+ topicsKeywords: "Topics/Keywords",
+ fileType: "File Type",
+ },
+ wikipediaEntry: {
+ title: "Title",
+ language: "Language",
+ webpageURL: "Webpage URL",
+ editorContributor: "Editor/Contributor",
+ lastEditDate: "Last Edit Date",
+ summaryIntroduction: "Summary/Introduction",
+ },
+ notion: {
+ title: "Title",
+ language: "Language",
+ author: "Author",
+ createdTime: "Created Time",
+ lastModifiedTime: "Last Modified Time",
+ url: "URL",
+ tag: "Tag",
+ description: "Description",
+ },
+ github: {
+ repoName: "Repo Name",
+ repoDesc: "Repo Description",
+ repoOwner: "Repo Owner",
+ fileName: "File Name",
+ filePath: "File Path",
+ programmingLang: "Programming Language",
+ url: "URL",
+ license: "License",
+ lastCommitTime: "Last Commit Time",
+ lastCommitAuthor: "Last Commit Author",
+ },
+ originInfo: {
+ originalFilename: "Original filename",
+ originalFileSize: "Original file size",
+ uploadDate: "Upload date",
+ lastUpdateDate: "Last update date",
+ source: "Source",
+ },
+ technicalParameters: {
+ segmentSpecification: 'Segment specification',
+ segmentLength: 'Segment length',
+ avgParagraphLength: 'Avg. paragraph length',
+ paragraphs: 'Paragraphs',
+ hitCount: 'Hit count',
+ embeddingTime: 'Embedding time',
+ embeddedSpend: 'Embedded spend'
+ }
+ },
+ languageMap: {
+ zh: "Chinese",
+ en: "English",
+ es: "Spanish",
+ fr: "French",
+ de: "German",
+ ja: "Japanese",
+ ko: "Korean",
+ ru: "Russian",
+ ar: "Arabic",
+ pt: "Portuguese",
+ it: "Italian",
+ nl: "Dutch",
+ pl: "Polish",
+ sv: "Swedish",
+ tr: "Turkish",
+ he: "Hebrew",
+ hi: "Hindi",
+ da: "Danish",
+ fi: "Finnish",
+ no: "Norwegian",
+ hu: "Hungarian",
+ el: "Greek",
+ cs: "Czech",
+ th: "Thai",
+ id: "Indonesian",
+ },
+ categoryMap: {
+ book: {
+ fiction: "Fiction",
+ biography: "Biography",
+ history: "History",
+ science: "Science",
+ technology: "Technology",
+ education: "Education",
+ philosophy: "Philosophy",
+ religion: "Religion",
+ socialSciences: "SocialSciences",
+ art: "Art",
+ travel: "Travel",
+ health: "Health",
+ selfHelp: "SelfHelp",
+ businessEconomics: "BusinessEconomics",
+ cooking: "Cooking",
+ childrenYoungAdults: "ChildrenYoungAdults",
+ comicsGraphicNovels: "ComicsGraphicNovels",
+ poetry: "Poetry",
+ drama: "Drama",
+ other: "Other",
+ },
+ personalDoc: {
+ notes: "Notes",
+ blogDraft: "Blog Draft",
+ diary: "Diary",
+ researchReport: "Research Report",
+ bookExcerpt: "Book Excerpt",
+ schedule: "Schedule",
+ list: "List",
+ projectOverview: "Project Overview",
+ photoCollection: "Photo Collection",
+ creativeWriting: "Creative Writing",
+ codeSnippet: "Code Snippet",
+ designDraft: "Design Draft",
+ personalResume: "Personal Resume",
+ other: "Other",
+ },
+ businessDoc: {
+ meetingMinutes: "Meeting Minutes",
+ researchReport: "Research Report",
+ proposal: "Proposal",
+ employeeHandbook: "Employee Handbook",
+ trainingMaterials: "Training Materials",
+ requirementsDocument: "Requirements Document",
+ designDocument: "Design Document",
+ productSpecification: "Product Specification",
+ financialReport: "Financial Report",
+ marketAnalysis: "Market Analysis",
+ projectPlan: "Project Plan",
+ teamStructure: "Team Structure",
+ policiesProcedures: "Policies & Procedures",
+ contractsAgreements: "Contracts & Agreements",
+ emailCorrespondence: "Email Correspondence",
+ other: "Other",
+ },
+ },
+ },
+ embedding: {
+ processing: 'Embedding processing...',
+ paused: 'Embedding paused',
+ completed: 'Embedding completed',
+ error: 'Embedding error',
+ docName: 'Preprocessing document',
+ mode: 'Segmentation rule',
+ segmentLength: 'Segmentation length',
+ textCleaning: 'Text pre-definition and cleaning',
+ segments: 'Paragraphs',
+ highQuality: 'High-quality mode',
+ economy: 'Economy mode',
+ estimate: 'Estimated consumption',
+ stop: 'Stop processing',
+ resume: 'Resume processing',
+ automatic: 'Automatic',
+ custom: 'Custom',
+ previewTip: 'Paragraph preview will be available after embedding is complete'
+ },
+ segment: {
+ paragraphs: 'Paragraphs',
+ keywords: 'Key Words',
+ characters: 'characters',
+ hitCount: 'hit count',
+ vectorHash: 'Vector hash: ',
+ }
+};
+
+export default translation;
diff --git a/web/i18n/lang/dataset-documents.zh.ts b/web/i18n/lang/dataset-documents.zh.ts
new file mode 100644
index 00000000000..d295a896bba
--- /dev/null
+++ b/web/i18n/lang/dataset-documents.zh.ts
@@ -0,0 +1,313 @@
+const translation = {
+ list: {
+ title: "文档",
+ desc: "数据集的所有文件都在这里显示,整个数据集都可以链接到 Dify 引用或通过 Chat 插件进行索引。",
+ addFile: "添加文件",
+ table: {
+ header: {
+ fileName: "文件名",
+ words: "字符数",
+ hitCount: "命中次数",
+ uploadTime: "上传时间",
+ status: "状态",
+ action: "操作",
+ },
+ },
+ action: {
+ uploadFile: '上传新文件',
+ settings: '分段设置',
+ archive: '归档',
+ delete: "删除",
+ enableWarning: '归档的文件无法启用',
+ },
+ index: {
+ enable: '启用中',
+ disable: '禁用中',
+ all: '全部',
+ enableTip: '该文件可以被索引',
+ disableTip: '该文件无法被索引',
+ },
+ status: {
+ queuing: '排队中',
+ indexing: '索引中',
+ parsed: '已解析',
+ error: '错误',
+ available: '可用',
+ enabled: '已启用',
+ disabled: '已禁用',
+ archived: '已归档',
+ },
+ empty: {
+ title: "还没有文档",
+ upload: {
+ tip: "您可以上传文件,从网站同步,或者从网络应用程序(如概念、GitHub 等)同步。",
+ },
+ sync: {
+ tip: "Dify 会定期从您的 Notion 中下载文件并完成处理。",
+ },
+ },
+ delete: {
+ title: '确定删除吗?',
+ content: '如果您需要稍后恢复处理,您将从您离开的地方继续'
+ }
+ },
+ metadata: {
+ title: "元数据",
+ desc: "标记文档的元数据允许 AI 及时访问它们并为用户公开参考来源。",
+ dateTimeFormat: 'YYYY-MM-DD HH:mm',
+ docTypeSelectTitle: "请选择一种文档类型",
+ docTypeChangeTitle: "更换文档类型",
+ docTypeSelectWarning: "如果更改文档类型,将不再保留现在填充的元数据",
+ firstMetaAction: "开始",
+ placeholder: {
+ add: '输入',
+ select: '选择',
+ },
+ source: {
+ upload_file: '文件上传',
+ notion: "从 Notion 同步的文档",
+ github: "从 Github 同步的代码",
+ },
+ type: {
+ book: "书籍",
+ webPage: "网页",
+ paper: "论文",
+ socialMediaPost: "社交媒体帖子",
+ personalDocument: "个人文档",
+ businessDocument: "商务文档",
+ IMChat: "IM 聊天记录",
+ wikipediaEntry: "维基百科条目",
+ notion: "从 Notion 同步的文档",
+ github: "从 Github 同步的代码",
+ technicalParameters: '技术参数',
+ },
+ field: {
+ processRule: {
+ processDoc: '预处理文档',
+ segmentRule: '分段规则',
+ segmentLength: '分段长度',
+ processClean: '文本预处理与清洗',
+ },
+ book: {
+ title: "标题",
+ language: "语言",
+ author: "作者",
+ publisher: "出版商",
+ publicationDate: "出版日期",
+ ISBN: "ISBN",
+ category: "类别",
+ },
+ webPage: {
+ title: "标题",
+ url: "网址",
+ language: "语言",
+ authorPublisher: "作者/出版商",
+ publishDate: "发布日期",
+ topicsKeywords: "主题/关键词",
+ description: "描述",
+ },
+ paper: {
+ title: "标题",
+ language: "语言",
+ author: "作者",
+ publishDate: "发布日期",
+ journalConferenceName: "期刊/会议名称",
+ volumeIssuePage: "卷/期/页码",
+ DOI: "DOI",
+ topicsKeywords: "主题/关键词",
+ abstract: "摘要",
+ },
+ socialMediaPost: {
+ platform: "平台",
+ authorUsername: "作者/用户名",
+ publishDate: "发布日期",
+ postURL: "帖子网址",
+ topicsTags: "主题/标签",
+ },
+ personalDocument: {
+ title: "标题",
+ author: "作者",
+ creationDate: "创建日期",
+ lastModifiedDate: "最后修改日期",
+ documentType: "文档类型",
+ tagsCategory: "标签/类别",
+ },
+ businessDocument: {
+ title: "标题",
+ author: "作者",
+ creationDate: "创建日期",
+ lastModifiedDate: "最后修改日期",
+ documentType: "文档类型",
+ departmentTeam: "部门/团队",
+ },
+ IMChat: {
+ chatPlatform: "聊天平台",
+ chatPartiesGroupName: "聊天参与方/群组名称",
+ participants: "参与者",
+ startDate: "开始日期",
+ endDate: "结束日期",
+ topicsKeywords: "主题/关键词",
+ fileType: "文件类型",
+ },
+ wikipediaEntry: {
+ title: "标题",
+ language: "语言",
+ webpageURL: "网页网址",
+ editorContributor: "编辑/贡献者",
+ lastEditDate: "最后编辑日期",
+ summaryIntroduction: "摘要/介绍",
+ },
+ notion: {
+ title: "标题",
+ language: "语言",
+ author: "作者",
+ createdTime: "创建时间",
+ lastModifiedTime: "最后修改时间",
+ url: "网址",
+ tag: "标签",
+ description: "描述",
+ },
+ github: {
+ repoName: "仓库名",
+ repoDesc: "仓库描述",
+ repoOwner: "仓库所有者",
+ fileName: "文件名",
+ filePath: "文件路径",
+ programmingLang: "编程语言",
+ url: "网址",
+ license: "许可证",
+ lastCommitTime: "最后提交时间",
+ lastCommitAuthor: "最后提交者",
+ },
+ originInfo: {
+ originalFilename: "原始文件名称",
+ originalFileSize: "原始文件大小",
+ uploadDate: "上传日期",
+ lastUpdateDate: "最后更新日期",
+ source: "来源",
+ },
+ technicalParameters: {
+ segmentSpecification: '分段规则',
+ segmentLength: '段落长度',
+ avgParagraphLength: '平均段落长度',
+ paragraphs: '段落数量',
+ hitCount: '命中次数',
+ embeddingTime: '嵌入时间',
+ embeddedSpend: '嵌入花费',
+ }
+ },
+ languageMap: {
+ zh: "中文",
+ en: "英文",
+ es: "西班牙语",
+ fr: "法语",
+ de: "德语",
+ ja: "日语",
+ ko: "韩语",
+ ru: "俄语",
+ ar: "阿拉伯语",
+ pt: "葡萄牙语",
+ it: "意大利语",
+ nl: "荷兰语",
+ pl: "波兰语",
+ sv: "瑞典语",
+ tr: "土耳其语",
+ he: "希伯来语",
+ hi: "印地语",
+ da: "丹麦语",
+ fi: "芬兰语",
+ no: "挪威语",
+ hu: "匈牙利语",
+ el: "希腊语",
+ cs: "捷克语",
+ th: "泰语",
+ id: "印度尼西亚语",
+ },
+ categoryMap: {
+ book: {
+ fiction: "小说",
+ biography: "传记",
+ history: "历史",
+ science: "科学",
+ technology: "技术",
+ education: "教育",
+ philosophy: "哲学",
+ religion: "宗教",
+ socialSciences: "社会科学",
+ art: "艺术",
+ travel: "旅行",
+ health: "健康",
+ selfHelp: "自助",
+ businessEconomics: "商业/经济",
+ cooking: "烹饪",
+ childrenYoungAdults: "儿童/青少年",
+ comicsGraphicNovels: "漫画/图形小说",
+ poetry: "诗歌",
+ drama: "戏剧",
+ other: "其他",
+ },
+ personalDoc: {
+ notes: "笔记",
+ blogDraft: "博客草稿",
+ diary: "日记",
+ researchReport: "研究报告",
+ bookExcerpt: "书籍摘录",
+ schedule: "日程安排",
+ list: "列表",
+ projectOverview: "项目概述",
+ photoCollection: "照片集",
+ creativeWriting: "创意写作",
+ codeSnippet: "代码片段",
+ designDraft: "设计草稿",
+ personalResume: "个人简历",
+ other: "其他",
+ },
+ businessDoc: {
+ meetingMinutes: "会议纪要",
+ researchReport: "研究报告",
+ proposal: "提案",
+ employeeHandbook: "员工手册",
+ trainingMaterials: "培训材料",
+ requirementsDocument: "需求文档",
+ designDocument: "设计文档",
+ productSpecification: "产品规格",
+ financialReport: "财务报告",
+ marketAnalysis: "市场分析",
+ projectPlan: "项目计划",
+ teamStructure: "团队结构",
+ policiesProcedures: "政策和流程",
+ contractsAgreements: "合同和协议",
+ emailCorrespondence: "邮件往来",
+ other: "其他",
+ },
+ },
+ },
+ embedding: {
+ processing: '嵌入处理中...',
+ paused: '嵌入已停止',
+ completed: '嵌入已完成',
+ error: '嵌入发生错误',
+ docName: '预处理文档',
+ mode: '分段规则',
+ segmentLength: '分段长度',
+ textCleaning: '文本预定义与清洗',
+ segments: '段落',
+ highQuality: '高质量模式',
+ economy: '经济模式',
+ estimate: '预估消耗',
+ stop: '停止处理',
+ resume: '恢复处理',
+ automatic: '自动',
+ custom: '自定义',
+ previewTip: '段落预览将在嵌入完成后可用'
+ },
+ segment: {
+ paragraphs: '段落',
+ keywords: '关键词',
+ characters: '字符',
+ hitCount: '命中次数',
+ vectorHash: '向量哈希:',
+ }
+};
+
+export default translation;
diff --git a/web/i18n/lang/dataset-hit-testing.en.ts b/web/i18n/lang/dataset-hit-testing.en.ts
new file mode 100644
index 00000000000..4946b59d83c
--- /dev/null
+++ b/web/i18n/lang/dataset-hit-testing.en.ts
@@ -0,0 +1,28 @@
+const translation = {
+ title: "Hit Testing",
+ desc: "Test the hitting effect of the dataset based on the given query text.",
+ dateTimeFormat: 'MM/DD/YYYY hh:mm A',
+ recents: 'Recents',
+ table: {
+ header: {
+ source: "Source",
+ text: "Text",
+ time: "Time",
+ },
+ },
+ input: {
+ title: 'Source text',
+ placeholder: 'Please enter a text, a short declarative sentence is recommended.',
+ countWarning: 'Up to 200 characters.',
+ indexWarning: 'High quality dataset only.',
+ testing: 'Testing',
+ },
+ hit: {
+ title: "HIT PARAGRAPHS",
+ emptyTip: 'Hit Testing results will show here',
+ },
+ noRecentTip: 'No recent query results here',
+ viewChart: 'View VECTOR CHART',
+};
+
+export default translation;
diff --git a/web/i18n/lang/dataset-hit-testing.zh.ts b/web/i18n/lang/dataset-hit-testing.zh.ts
new file mode 100644
index 00000000000..0ef23cbd9bd
--- /dev/null
+++ b/web/i18n/lang/dataset-hit-testing.zh.ts
@@ -0,0 +1,28 @@
+const translation = {
+ title: '命中测试',
+ desc: '基于给定的查询文本测试数据集的命中效果。',
+ dateTimeFormat: 'YYYY-MM-DD HH:mm',
+ recents: '最近查询',
+ table: {
+ header: {
+ source: "数据源",
+ text: "文本",
+ time: "时间",
+ },
+ },
+ input: {
+ title: '源文本',
+ placeholder: '请输入文本,建议使用简短的陈述句。',
+ countWarning: '不超过 200 个字符',
+ indexWarning: '仅支持高质量模式数据集',
+ testing: '测试',
+ },
+ hit: {
+ title: "命中段落",
+ emptyTip: '命中测试结果将展示在这里',
+ },
+ noRecentTip: '最近无查询结果',
+ viewChart: '查看向量图表',
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset-settings.en.ts b/web/i18n/lang/dataset-settings.en.ts
new file mode 100644
index 00000000000..1337383ad4d
--- /dev/null
+++ b/web/i18n/lang/dataset-settings.en.ts
@@ -0,0 +1,22 @@
+const translation = {
+ title: 'Dataset settings',
+ desc: 'Here you can modify the properties and working methods of the dataset.',
+ form: {
+ name: 'Dataset Name',
+ nameError: 'Name cannot be empty',
+ desc: 'Dataset description',
+ descPlaceholder: 'Describe what is in this data set. A detailed description allows AI to access the content of the data set in a timely manner. If empty, Dify will use the default hit strategy.',
+ descWrite: 'Learn how to write a good dataset description.',
+ permissions: 'Permissions',
+ permissionsOnlyMe: 'Only me',
+ permissionsAllMember: 'All team members',
+ indexMethod: 'Index Method',
+ indexMethodHighQuality: 'High Quality',
+ indexMethodHighQualityTip: 'Call OpenAI\'s embedding interface for processing to provide higher accuracy when users query.',
+ indexMethodEconomy: 'Economical',
+ indexMethodEconomyTip: 'Use offline vector engines, keyword indexes, etc. to reduce accuracy without spending tokens',
+ save: 'Save',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset-settings.zh.ts b/web/i18n/lang/dataset-settings.zh.ts
new file mode 100644
index 00000000000..0818836d79b
--- /dev/null
+++ b/web/i18n/lang/dataset-settings.zh.ts
@@ -0,0 +1,22 @@
+const translation = {
+ title: '数据集设置',
+ desc: '在这里您可以修改数据集的工作方式以及其它设置。',
+ form: {
+ name: '数据集名称',
+ nameError: '名称不能为空',
+ desc: '数据集描述',
+ descPlaceholder: '描述这个数据集中的内容。详细的描述可以让 AI 及时访问数据集的内容。如果为空,Dify 将使用默认的命中策略。',
+ descWrite: '了解如何编写更好的数据集描述。',
+ permissions: '可见权限',
+ permissionsOnlyMe: '只有我',
+ permissionsAllMember: '所有团队成员',
+ indexMethod: '索引模式',
+ indexMethodHighQuality: '高质量',
+ indexMethodHighQualityTip: '调用 OpenAI 的嵌入接口进行处理,以在用户查询时提供更高的准确度',
+ indexMethodEconomy: '经济',
+ indexMethodEconomyTip: '使用离线的向量引擎、关键词索引等方式,降低了准确度但无需花费 Token',
+ save: '保存',
+ },
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset.en.ts b/web/i18n/lang/dataset.en.ts
new file mode 100644
index 00000000000..94d98c22065
--- /dev/null
+++ b/web/i18n/lang/dataset.en.ts
@@ -0,0 +1,21 @@
+const translation = {
+ documentCount: ' docs',
+ wordCount: 'k words',
+ appCount: ' linked apps',
+ createDataset: 'Create Dataset',
+ createDatasetIntro: 'Import your own text data or write data in real-time via Webhook for LLM context enhancement.',
+ deleteDatasetConfirmTitle: 'Delete this app?',
+ deleteDatasetConfirmContent:
+ 'Deleting the dataset is irreversible. Users will no longer be able to access your dataset, and all prompt configurations and logs will be permanently deleted.',
+ datasetDeleted: 'Dataset deleted',
+ datasetDeleteFailed: 'Failed to delete dataset',
+ didYouKnow: 'Did you know?',
+ intro1: 'The dataset can be integrated into the Dify application ',
+ intro2: 'as a context',
+ intro3: ',',
+ intro4: 'or it ',
+ intro5: 'can be created',
+ intro6: ' as a standalone ChatGPT index plug-in to publish',
+}
+
+export default translation
diff --git a/web/i18n/lang/dataset.zh.ts b/web/i18n/lang/dataset.zh.ts
new file mode 100644
index 00000000000..b74eabab7ed
--- /dev/null
+++ b/web/i18n/lang/dataset.zh.ts
@@ -0,0 +1,21 @@
+const translation = {
+ documentCount: ' 文档',
+ wordCount: '千字符',
+ appCount: ' 关联应用',
+ createDataset: '创建数据集',
+ createDatasetIntro: '导入您自己的文本数据或通过 Webhook 实时写入数据以增强 LLM 的上下文。',
+ deleteDatasetConfirmTitle: '要删除数据集吗?',
+ deleteDatasetConfirmContent:
+ '删除数据集是不可逆的。用户将无法再访问您的数据集,所有的提示配置和日志将被永久删除。',
+ datasetDeleted: '数据集已删除',
+ datasetDeleteFailed: '删除数据集失败',
+ didYouKnow: '你知道吗??',
+ intro1: '数据集可以被集成到 Dify 应用中',
+ intro2: '作为上下文',
+ intro3: ',',
+ intro4: '或可以',
+ intro5: '创建',
+ intro6: '为独立的 ChatGPT 插件发布使用',
+}
+
+export default translation
diff --git a/web/i18n/lang/layout.en.ts b/web/i18n/lang/layout.en.ts
new file mode 100644
index 00000000000..928649474b4
--- /dev/null
+++ b/web/i18n/lang/layout.en.ts
@@ -0,0 +1,4 @@
+const translation = {
+}
+
+export default translation
diff --git a/web/i18n/lang/layout.zh.ts b/web/i18n/lang/layout.zh.ts
new file mode 100644
index 00000000000..928649474b4
--- /dev/null
+++ b/web/i18n/lang/layout.zh.ts
@@ -0,0 +1,4 @@
+const translation = {
+}
+
+export default translation
diff --git a/web/i18n/lang/login.en.ts b/web/i18n/lang/login.en.ts
new file mode 100644
index 00000000000..ae40e01ea1e
--- /dev/null
+++ b/web/i18n/lang/login.en.ts
@@ -0,0 +1,41 @@
+const translation = {
+ "pageTitle": "Hey, let's get started!👋",
+ "welcome": "Welcome to Dify, please log in to continue.",
+ "email": "Email address",
+ "password": "Password",
+ "name": "Name",
+ "forget": "Forgot your password?",
+ "signBtn": "Sign in",
+ "installBtn": "Setting",
+ "setAdminAccount": "Setting up an admin account",
+ "setAdminAccountDesc": "Maximum privileges for admin account, which can be used to create applications and manage LLM providers, etc.",
+ "createAndSignIn": "Create and sign in",
+ "oneMoreStep": "One more step",
+ "createSample": "Based on this information, we’ll create sample application for you",
+ "invitationCode": "Invitation Code",
+ "interfaceLanguage": "Interface Dify",
+ "timezone": "Time zone",
+ "go": "Go to Dify",
+ "sendUsMail": "Email us your introduction, and we'll handle the invitation request.",
+ "acceptPP": "I have read and accept the privacy policy",
+ "reset": "Please run following command to reset your password",
+ "withGitHub": "Continue with GitHub",
+ "withGoogle": "Continue with Google",
+ "rightTitle": "Unlock the full potential of LLM",
+ "rightDesc": "Effortlessly build visually captivating, operable, and improvable AI applications.",
+ "tos": "Terms of Service",
+ "pp": "Privacy Policy",
+ "tosDesc": "By signing up, you agree to our",
+ "donthave": "Don't have?",
+ "invalidInvitationCode": "Invalid invitation code",
+ "accountAlreadyInited": "Account already inited",
+ "error": {
+ "emailEmpty": "Email address is required",
+ "emailInValid": "Please enter a valid email address",
+ "nameEmpty": "Name is required",
+ "passwordEmpty": "Password is required",
+ "passwordInvalid": "Password must contain letters and numbers, and the length must be greater than 8",
+ }
+}
+
+export default translation
diff --git a/web/i18n/lang/login.zh.ts b/web/i18n/lang/login.zh.ts
new file mode 100644
index 00000000000..a7da82c13f6
--- /dev/null
+++ b/web/i18n/lang/login.zh.ts
@@ -0,0 +1,41 @@
+const translation = {
+ "pageTitle": "嗨,近来可好 👋",
+ "welcome": "欢迎来到 Dify, 登录以继续",
+ "email": "邮箱",
+ "password": "密码",
+ "name": "用户名",
+ "forget": "忘记密码?",
+ "signBtn": "登录",
+ "installBtn": "设置",
+ "setAdminAccount": "设置管理员账户",
+ "setAdminAccountDesc": "管理员拥有的最大权限,可用于创建应用和管理 LLM 供应商等。",
+ "createAndSignIn": "创建账户",
+ "oneMoreStep": "还差一步",
+ "createSample": "基于这些信息,我们将为您创建一个示例应用",
+ "invitationCode": "邀请码",
+ "interfaceLanguage": "界面语言",
+ "timezone": "时区",
+ "go": "跳转至 Dify",
+ "sendUsMail": "发封邮件介绍你自己,我们会尽快处理。",
+ "acceptPP": "我已阅读并接受隐私政策",
+ "reset": "请运行以下命令重置密码",
+ "withGitHub": "使用 GitHub 登录",
+ "withGoogle": "使用 Google 登录",
+ "rightTitle": "释放大型语言模型的全部潜能",
+ "rightDesc": "简单构建可视化、可运营、可改进的 AI 应用",
+ "tos": "使用协议",
+ "pp": "隐私政策",
+ "tosDesc": "使用即代表你并同意我们的",
+ "donthave": "还没有邀请码?",
+ "invalidInvitationCode": "无效的邀请码",
+ "accountAlreadyInited": "账户已经初始化",
+ "error": {
+ "emailEmpty": "邮箱不能为空",
+ "emailInValid": "请输入有效的邮箱地址",
+ "nameEmpty": "用户名不能为空",
+ "passwordEmpty": "密码不能为空",
+ "passwordInvalid": "密码必须包含字母和数字,且长度不小于8位",
+ }
+}
+
+export default translation
diff --git a/web/i18n/lang/register.en.ts b/web/i18n/lang/register.en.ts
new file mode 100644
index 00000000000..928649474b4
--- /dev/null
+++ b/web/i18n/lang/register.en.ts
@@ -0,0 +1,4 @@
+const translation = {
+}
+
+export default translation
diff --git a/web/i18n/lang/register.zh.ts b/web/i18n/lang/register.zh.ts
new file mode 100644
index 00000000000..928649474b4
--- /dev/null
+++ b/web/i18n/lang/register.zh.ts
@@ -0,0 +1,4 @@
+const translation = {
+}
+
+export default translation
diff --git a/web/i18n/lang/share-app.en.ts b/web/i18n/lang/share-app.en.ts
new file mode 100644
index 00000000000..3e641222b5b
--- /dev/null
+++ b/web/i18n/lang/share-app.en.ts
@@ -0,0 +1,45 @@
+const translation = {
+ common: {
+ welcome: "Welcome to use",
+ appUnavailable: "App is unavailable",
+ appUnkonwError: "App is unavailable"
+ },
+ chat: {
+ newChat: "New chat",
+ newChatDefaultName: "New conversation",
+ powerBy: "Powered by",
+ prompt: "Prompt",
+ privatePromptConfigTitle: "Conversation settings",
+ publicPromptConfigTitle: "Initial Prompt",
+ configStatusDes: "Before start, you can modify conversation settings",
+ configDisabled:
+ "Previous session settings have been used for this session.",
+ startChat: "Start Chat",
+ privacyPolicyLeft:
+ "Please read the ",
+ privacyPolicyMiddle:
+ "privacy policy",
+ privacyPolicyRight:
+ " provided by the app developer.",
+ },
+ generation: {
+ tabs: {
+ create: "Create",
+ saved: "Saved",
+ },
+ savedNoData: {
+ title: "You haven't saved a result yet!",
+ description: 'Start generating content, and find your saved results here.',
+ startCreateContent: 'Start create content'
+ },
+ title: "AI Completion",
+ queryTitle: "Query content",
+ queryPlaceholder: "Write your query content...",
+ run: "RUN",
+ copy: "Copy",
+ resultTitle: "AI Completion",
+ noData: "AI will give you what you want here.",
+ },
+};
+
+export default translation;
diff --git a/web/i18n/lang/share-app.zh.ts b/web/i18n/lang/share-app.zh.ts
new file mode 100644
index 00000000000..031bedf03af
--- /dev/null
+++ b/web/i18n/lang/share-app.zh.ts
@@ -0,0 +1,41 @@
+const translation = {
+ common: {
+ welcome: "欢迎使用",
+ appUnavailable: "应用不可用",
+ appUnkonwError: "应用不可用",
+ },
+ chat: {
+ newChat: "新对话",
+ newChatDefaultName: "新的对话",
+ powerBy: "Powered by",
+ prompt: "提示词",
+ privatePromptConfigTitle: "对话设置",
+ publicPromptConfigTitle: "对话前提示词",
+ configStatusDes: "开始前,您可以修改对话设置",
+ configDisabled: "此次会话已使用上次会话表单",
+ startChat: "开始对话",
+ privacyPolicyLeft: "请阅读由该应用开发者提供的",
+ privacyPolicyMiddle: "隐私政策",
+ privacyPolicyRight: "。",
+ },
+ generation: {
+ tabs: {
+ create: "创建",
+ saved: "已保存",
+ },
+ savedNoData: {
+ title: "您还没有保存结果!",
+ description: '开始生成内容,您可以在这里找到保存的结果。',
+ startCreateContent: '开始生成内容'
+ },
+ title: "AI 智能书写",
+ queryTitle: "查询内容",
+ queryPlaceholder: "请输入文本内容",
+ run: "运行",
+ copy: "拷贝",
+ resultTitle: "AI 书写",
+ noData: "AI 会在这里给你惊喜。",
+ },
+};
+
+export default translation;
diff --git a/web/i18n/server.ts b/web/i18n/server.ts
new file mode 100644
index 00000000000..ac9630dd499
--- /dev/null
+++ b/web/i18n/server.ts
@@ -0,0 +1,43 @@
+import 'server-only'
+
+import { cookies, headers } from 'next/headers'
+import Negotiator from 'negotiator'
+import { match } from '@formatjs/intl-localematcher'
+import type { Locale } from '.'
+import { i18n } from '.'
+
+export const getLocaleOnServer = (): Locale => {
+ // @ts-expect-error locales are readonly
+ const locales: string[] = i18n.locales
+
+ let languages: string[] | undefined
+ // get locale from cookie
+ const localeCookie = cookies().get('locale')
+ languages = localeCookie?.value ? [localeCookie.value] : []
+
+ if (!languages.length) {
+ // Negotiator expects plain object so we need to transform headers
+ const negotiatorHeaders: Record<string, string> = {}
+ headers().forEach((value, key) => (negotiatorHeaders[key] = value))
+ // Use negotiator and intl-localematcher to get best locale
+ languages = new Negotiator({ headers: negotiatorHeaders }).languages()
+ }
+
+ // match locale
+ const matchedLocale = match(languages, locales, i18n.defaultLocale) as Locale
+ return matchedLocale
+}
+
+// We enumerate all dictionaries here for better linting and typescript support
+// We also get the default import for cleaner types
+const dictionaries = {
+ 'en': () => import('@/dictionaries/en.json').then(module => module.default),
+ 'zh-Hans': () => import('@/dictionaries/zh-Hans.json').then(module => module.default),
+} as { [locale: string]: () => Promise<any> }
+
+export const getDictionary = async (locale: Locale = 'en') => {
+ try {
+ return await dictionaries[locale]()
+ }
+ catch (e) { console.error('locale not found', locale) }
+}
diff --git a/web/middleware.ts b/web/middleware.ts
new file mode 100644
index 00000000000..5b17cbd6736
--- /dev/null
+++ b/web/middleware.ts
@@ -0,0 +1,39 @@
+import { match } from '@formatjs/intl-localematcher'
+import Negotiator from 'negotiator'
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+import type { Locale } from './i18n'
+import { i18n } from './i18n'
+
+export const getLocale = (request: NextRequest): Locale => {
+ // @ts-expect-error locales are readonly
+ const locales: Locale[] = i18n.locales
+
+ let languages: string[] | undefined
+ // get locale from cookie
+ const localeCookie = request.cookies.get('locale')
+ languages = localeCookie?.value ? [localeCookie.value] : []
+
+ if (!languages.length) {
+ // Negotiator expects plain object so we need to transform headers
+ const negotiatorHeaders: Record<string, string> = {}
+ request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
+ // Use negotiator and intl-localematcher to get best locale
+ languages = new Negotiator({ headers: negotiatorHeaders }).languages()
+ }
+
+ // match locale
+ const matchedLocale = match(languages, locales, i18n.defaultLocale) as Locale
+ return matchedLocale
+}
+
+export const middleware = async (request: NextRequest) => {
+ const pathname = request.nextUrl.pathname
+ if (/\.(css|js(on)?|ico|svg|png)$/.test(pathname))
+ return
+
+ const locale = getLocale(request)
+ const response = NextResponse.next()
+ response.cookies.set('locale', locale)
+ return response
+}
diff --git a/web/models/app.ts b/web/models/app.ts
new file mode 100644
index 00000000000..ddafdfbc722
--- /dev/null
+++ b/web/models/app.ts
@@ -0,0 +1,118 @@
+import type { App, AppTemplate, SiteConfig } from '@/types/app'
+
+export type AppMode = 'chat' | 'completion'
+
+/* export type App = {
+ id: string
+ name: string
+ decription: string
+ mode: AppMode
+ enable_site: boolean
+ enable_api: boolean
+ api_rpm: number
+ api_rph: number
+ is_demo: boolean
+ model_config: AppModelConfig
+ providers: Array<{ provider: string; token_is_set: boolean }>
+ site: SiteConfig
+ created_at: string
+}
+
+export type AppModelConfig = {
+ provider: string
+ model_id: string
+ configs: {
+ prompt_template: string
+ prompt_variables: Array<PromptVariable>
+ completion_params: CompletionParam
+ }
+}
+
+export type PromptVariable = {
+ key: string
+ name: string
+ description: string
+ type: string | number
+ default: string
+ options: string[]
+}
+
+export type CompletionParam = {
+ max_tokens: number
+ temperature: number
+ top_p: number
+ echo: boolean
+ stop: string[]
+ presence_penalty: number
+ frequency_penalty: number
+}
+
+export type SiteConfig = {
+ access_token: string
+ title: string
+ author: string
+ support_email: string
+ default_language: string
+ customize_domain: string
+ theme: string
+ customize_token_strategy: 'must' | 'allow' | 'not_allow'
+ prompt_public: boolean
+} */
+
+export type AppListResponse = {
+ data: App[]
+}
+
+export type AppDetailResponse = App
+
+export type AppTemplatesResponse = {
+ data: AppTemplate[]
+}
+
+export type CreateAppResponse = App
+
+export type UpdateAppNameResponse = App
+
+export type UpdateAppSiteCodeResponse = { app_id: string } & SiteConfig
+
+export type AppDailyConversationsResponse = {
+ data: Array<{ date: string; conversation_count: number }>
+}
+
+export type AppDailyEndUsersResponse = {
+ data: Array<{ date: string; terminal_count: number }>
+}
+
+export type AppTokenCostsResponse = {
+ data: Array<{ date: string; token_count: number; total_price: number; currency: number }>
+}
+
+export type UpdateAppModelConfigResponse = { result: string }
+
+export type ApikeyItemResponse = {
+ id: string
+ token: string
+ last_used_at: string
+ created_at: string
+}
+
+export type ApikeysListResponse = {
+ data: ApikeyItemResponse[]
+}
+
+export type CreateApiKeyResponse = {
+ id: string
+ token: string
+ created_at: string
+}
+
+export type ValidateOpenAIKeyResponse = {
+ result: string
+ error?: string
+}
+
+export type UpdateOpenAIKeyResponse = ValidateOpenAIKeyResponse
+
+export type GenerationIntroductionResponse = {
+ introduction: string
+}
diff --git a/web/models/common.ts b/web/models/common.ts
new file mode 100644
index 00000000000..21a74447e10
--- /dev/null
+++ b/web/models/common.ts
@@ -0,0 +1,92 @@
+export type CommonResponse = {
+ result: 'success' | 'fail'
+}
+
+export type OauthResponse = {
+ redirect_url: string
+}
+
+export type UserProfileResponse = {
+ id: string
+ name: string
+ email: string
+ interface_language?: string
+ interface_theme?: string
+ timezone?: string
+ last_login_at?: string
+ last_login_ip?: string
+ created_at?: string
+}
+
+export type UserProfileOriginResponse = {
+ json: () => Promise<UserProfileResponse>
+ bodyUsed: boolean
+ headers: any
+}
+
+export type LangGeniusVersionResponse = {
+ current_version: string
+ latest_version: string
+ version: string
+ release_date: string
+ release_notes: string
+ can_auto_update: boolean
+ current_env: string
+}
+
+export type TenantInfoResponse = {
+ name: string
+ created_at: string
+ providers: Array<{
+ provider: string
+ provider_name: string
+ token_is_set: boolean
+ is_valid: boolean
+ token_is_valid: boolean
+ }>
+ in_trail: boolean
+ trial_end_reason: null | 'trial_exceeded' | 'using_custom'
+}
+
+export type Member = Pick<UserProfileResponse, 'id' | 'name' | 'email' | 'last_login_at' | 'created_at'> & {
+ avatar: string
+ status: 'pending' | 'active' | 'banned' | 'closed'
+ role: 'owner' | 'admin' | 'normal'
+}
+
+export type ProviderAzureToken = {
+ azure_api_base: string
+ azure_api_key: string
+ azure_api_type: string
+ azure_api_version: string
+}
+export type Provider = {
+ provider_name: string
+ provider_type: string
+ is_valid: boolean
+ is_enabled: boolean
+ last_used: string
+ token?: string | ProviderAzureToken
+}
+
+export type ProviderHosted = Provider & {
+ quota_type: string
+ quota_limit: number
+ quota_used: number
+}
+
+export type AccountIntegrate = {
+ provider: 'google' | 'github'
+ created_at: number
+ is_bound: boolean
+ link: string
+}
+
+export interface IWorkspace {
+ id: string
+ name: string
+ plan: string
+ status: string
+ created_at: number
+ current: boolean
+}
diff --git a/web/models/datasets.ts b/web/models/datasets.ts
new file mode 100644
index 00000000000..8295e77a55d
--- /dev/null
+++ b/web/models/datasets.ts
@@ -0,0 +1,339 @@
+import { AppMode } from './app'
+
+export type DataSet = {
+ id: string
+ name: string
+ description: string
+ permission: 'only_me' | 'all_team_members'
+ data_source_type: 'upload_file'
+ indexing_technique: 'high_quality' | 'economy'
+ created_by: string
+ updated_by: string
+ updated_at: number
+ app_count: number
+ document_count: number
+ word_count: number
+}
+
+export type File = {
+ id: string
+ name: string
+ size: number
+ extension: string
+ mime_type: string
+ created_by: string
+ created_at: number
+}
+
+export type DataSetListResponse = {
+ data: DataSet[]
+}
+
+export type IndexingEstimateResponse = {
+ tokens: number
+ total_price: number
+ currency: string
+ total_segments: number
+ preview: string[]
+}
+
+export interface FileIndexingEstimateResponse extends IndexingEstimateResponse {
+ total_nodes: number
+}
+
+export type IndexingStatusResponse = {
+ id: string
+ indexing_status: DocumentIndexingStatus
+ processing_started_at: number
+ parsing_completed_at: number
+ cleaning_completed_at: number
+ splitting_completed_at: number
+ completed_at: any
+ paused_at: any
+ error: any
+ stopped_at: any
+ completed_segments: number
+ total_segments: number
+}
+
+export type ProcessMode = 'automatic' | 'custom'
+
+export type ProcessRuleResponse = {
+ mode: ProcessMode
+ rules: Rules
+}
+
+export type Rules = {
+ pre_processing_rules: PreProcessingRule[]
+ segmentation: Segmentation
+}
+
+export type PreProcessingRule = {
+ id: string
+ enabled: boolean
+}
+
+export type Segmentation = {
+ separator: string
+ max_tokens: number
+}
+
+export const DocumentIndexingStatusList = [
+ 'waiting',
+ 'parsing',
+ 'cleaning',
+ 'splitting',
+ 'indexing',
+ 'paused',
+ 'error',
+ 'completed',
+] as const
+
+export type DocumentIndexingStatus = typeof DocumentIndexingStatusList[number]
+
+export const DisplayStatusList = [
+ "queuing",
+ "indexing",
+ "paused",
+ "error",
+ "available",
+ "enabled",
+ "disabled",
+ "archived",
+] as const;
+
+export type DocumentDisplayStatus = typeof DisplayStatusList[number];
+
+export type DataSourceInfo = {
+ upload_file: {
+ id: string
+ name: string
+ size: number
+ mime_type: string
+ created_at: number
+ created_by: string
+ extension: string
+ }
+}
+
+export type InitialDocumentDetail = {
+ id: string
+ position: number
+ dataset_id: string
+ data_source_type: 'upload_file'
+ data_source_info: DataSourceInfo
+ dataset_process_rule_id: string
+ name: string
+ created_from: 'api' | 'web'
+ created_by: string
+ created_at: number
+ indexing_status: DocumentIndexingStatus
+ display_status: DocumentDisplayStatus
+}
+
+export type SimpleDocumentDetail = InitialDocumentDetail & {
+ enabled: boolean
+ word_count: number
+ error?: string | null
+ archived: boolean
+ updated_at: number
+ hit_count: number
+ dataset_process_rule_id?: string
+}
+
+export type DocumentListResponse = {
+ data: SimpleDocumentDetail[]
+ has_more: boolean
+ total: number
+ page: number
+ limit: number
+}
+
+export type CreateDocumentReq = {
+ original_document_id?: string
+ indexing_technique?: string;
+ name: string
+ data_source: DataSource
+ process_rule: ProcessRule
+}
+
+export type DataSource = {
+ type: string
+ info: string // upload_file_id
+ name: string
+}
+
+export type ProcessRule = {
+ mode: string
+ rules: Rules
+}
+
+export type createDocumentResponse = {
+ dataset?: DataSet
+ document: InitialDocumentDetail
+}
+
+export type FullDocumentDetail = SimpleDocumentDetail & {
+ batch: string
+ created_api_request_id: string
+ processing_started_at: number
+ parsing_completed_at: number
+ cleaning_completed_at: number
+ splitting_completed_at: number
+ tokens: number
+ indexing_latency: number
+ completed_at: number
+ paused_by: string
+ paused_at: number
+ stopped_at: number
+ indexing_status: string
+ disabled_at: number
+ disabled_by: string
+ archived_reason: 'rule_modified' | 're_upload'
+ archived_by: string
+ archived_at: number
+ doc_type?: DocType | null
+ doc_metadata?: DocMetadata | null
+ segment_count: number
+ [key: string]: any
+}
+
+export type DocMetadata = {
+ title: string
+ language: string
+ author: string
+ publisher: string
+ publicationDate: string
+ ISBN: string
+ category: string
+ [key: string]: string
+}
+
+export const CUSTOMIZABLE_DOC_TYPES = [
+ "book",
+ "web_page",
+ "paper",
+ "social_media_post",
+ "personal_document",
+ "business_document",
+ "im_chat_log",
+] as const;
+
+export const FIXED_DOC_TYPES = ["synced_from_github", "synced_from_notion", "wikipedia_entry"] as const;
+
+export type CustomizableDocType = typeof CUSTOMIZABLE_DOC_TYPES[number];
+export type FixedDocType = typeof FIXED_DOC_TYPES[number];
+export type DocType = CustomizableDocType | FixedDocType;
+
+export type DocumentDetailResponse = FullDocumentDetail
+
+export const SEGMENT_STATUS_LIST = ['waiting', 'completed', 'error', 'indexing']
+export type SegmentStatus = typeof SEGMENT_STATUS_LIST[number]
+
+export type SegmentsQuery = {
+ last_id?: string
+ limit: number
+ // status?: SegmentStatus
+ hit_count_gte?: number
+ keyword?: string
+ enabled?: boolean
+}
+
+export type SegmentDetailModel = {
+ id: string
+ position: number
+ document_id: string
+ content: string
+ word_count: number
+ tokens: number
+ keywords: string[]
+ index_node_id: string
+ index_node_hash: string
+ hit_count: number
+ enabled: boolean
+ disabled_at: number
+ disabled_by: string
+ status: SegmentStatus
+ created_by: string
+ created_at: number
+ indexing_at: number
+ completed_at: number
+ error: string | null
+ stopped_at: number
+}
+
+export type SegmentsResponse = {
+ data: SegmentDetailModel[]
+ has_more: boolean
+ limit: number
+ total: number
+}
+
+export type HitTestingRecord = {
+ id: string
+ content: string
+ source: 'app' | 'hit_testing' | 'plugin'
+ source_app_id: string
+ created_by_role: 'account' | 'end_user'
+ created_by: string
+ created_at: number
+}
+
+export type HitTesting = {
+ segment: Segment
+ score: number
+ tsne_position: TsnePosition
+}
+
+export type Segment = {
+ id: string
+ document: Document
+ content: string
+ position: number
+ word_count: number
+ tokens: number
+ keywords: string[]
+ hit_count: number
+ index_node_hash: string
+}
+
+export type Document = {
+ id: string
+ data_source_type: string
+ name: string
+ doc_type: DocType
+}
+
+export type HitTestingRecordsResponse = {
+ data: HitTestingRecord[]
+ has_more: boolean
+ limit: number
+ total: number
+ page: number
+}
+
+export type TsnePosition = {
+ x: number
+ y: number
+}
+
+export type HitTestingResponse = {
+ query: {
+ content: string
+ tsne_position: TsnePosition
+ }
+ records: Array<HitTesting>
+}
+
+export type RelatedApp = {
+ id: string
+ name: string
+ mode: AppMode
+ icon: string
+ icon_background: string
+}
+
+export type RelatedAppResponse = {
+ data: Array<RelatedApp>
+ total: number
+}
diff --git a/web/models/debug.ts b/web/models/debug.ts
new file mode 100644
index 00000000000..cde30cdd711
--- /dev/null
+++ b/web/models/debug.ts
@@ -0,0 +1,115 @@
+export type Inputs = Record<string, string | number | object>
+
+export type PromptVariable = {
+ key: string,
+ name: string,
+ type: string, // "string" | "number" | "select",
+ default?: string | number,
+ required: boolean,
+ options?: string[]
+ max_length?: number
+}
+
+export type CompletionParams = {
+ max_tokens: number,
+ temperature: number,
+ top_p: number,
+ presence_penalty: number,
+ frequency_penalty: number,
+}
+
+export type ModelId = "gpt-3.5-turbo" | "text-davinci-003"
+
+export type PromptConfig = {
+ prompt_template: string,
+ prompt_variables: PromptVariable[],
+}
+
+export type MoreLikeThisConfig = {
+ enabled: boolean
+}
+
+export type SuggestedQuestionsAfterAnswerConfig = MoreLikeThisConfig
+
+// frontend use. Not the same as backend
+export type ModelConfig = {
+ provider: string, // LLM Provider: for example "OPENAI"
+ model_id: string,
+ configs: PromptConfig
+}
+
+export type DebugRequestBody = {
+ inputs: Inputs,
+ query: string,
+ completion_params: CompletionParams,
+ model_config: ModelConfig
+}
+
+export type DebugResponse = {
+ id: string,
+ answer: string,
+ created_at: string,
+}
+
+
+export type DebugResponseStream = {
+ id: string,
+ data: string,
+ created_at: string,
+}
+
+
+export type FeedBackRequestBody = {
+ message_id: string,
+ rating: 'like' | 'dislike',
+ content?: string,
+ from_source: 'api' | 'log'
+}
+
+
+export type FeedBackResponse = {
+ message_id: string,
+ rating: 'like' | 'dislike'
+}
+
+// Log session list
+export type LogSessionListQuery = {
+ keyword?: string,
+ start?: string, // format datetime(YYYY-mm-dd HH:ii)
+ end?: string, // format datetime(YYYY-mm-dd HH:ii)
+ page: number,
+ limit: number, // default 20. 1-100
+}
+
+export type LogSessionListResponse = {
+ data: {
+ id: string,
+ conversation_id: string,
+ query: string, // user's query question
+ message: string, // prompt send to LLM
+ answer: string,
+ creat_at: string,
+ }[],
+ total: number,
+ page: number,
+}
+
+// log session detail and debug
+export type LogSessionDetailResponse = {
+ id: string,
+ cnversation_id: string,
+ model_provider: string,
+ query: string,
+ inputs: Record<string, string | number | object>[],
+ message: string,
+ message_tokens: number, // number of tokens in message
+ answer: string,
+ answer_tokens: number, // number of tokens in answer
+ provider_response_latency: number, // used time in ms
+ from_source: 'api' | 'log',
+}
+
+export type SavedMessage = {
+ id: string,
+ answer: string
+}
\ No newline at end of file
diff --git a/web/models/history.ts b/web/models/history.ts
new file mode 100644
index 00000000000..90d6245cb9e
--- /dev/null
+++ b/web/models/history.ts
@@ -0,0 +1,11 @@
+export type History = {
+ id: string
+ source: string
+ target: string
+}
+export type HistoryResponse = {
+ histories: History[]
+}
+
+export const fetchHistories = (url: string) =>
+ fetch(url).then<HistoryResponse>(r => r.json())
diff --git a/web/models/log.ts b/web/models/log.ts
new file mode 100644
index 00000000000..9f915a3313e
--- /dev/null
+++ b/web/models/log.ts
@@ -0,0 +1,192 @@
+// Log type contains key:string conversation_id:string created_at:string quesiton:string answer:string
+export type Conversation = {
+ id: string
+ key: string
+ conversationId: string
+ question: string
+ answer: string
+ userRate: number
+ adminRate: number
+}
+
+export type ConversationListResponse = {
+ logs: Conversation[]
+}
+
+export const fetchLogs = (url: string) =>
+ fetch(url).then<ConversationListResponse>(r => r.json())
+
+export const CompletionParams = ['temperature', 'top_p', 'presence_penalty', 'max_token', 'stop', 'frequency_penalty'] as const
+
+export type CompletionParamType = typeof CompletionParams[number]
+
+export type CompletionParamsType = {
+ max_tokens: number
+ temperature: number
+ top_p: number
+ stop: string[]
+ presence_penalty: number
+ frequency_penalty: number
+}
+
+export type ModelConfigDetail = {
+ introduction: string
+ prompt_template: string
+ prompt_variables: Array<{
+ key: string
+ name: string
+ description: string
+ type: string | number
+ default: string
+ options: string[]
+ }>
+ completion_params: CompletionParamsType
+}
+
+export type Annotation = {
+ content: string
+ account: {
+ id: string
+ name: string
+ email: string
+ }
+ created_at?: number
+}
+
+export type MessageContent = {
+ id: string
+ conversation_id: string
+ query: string
+ inputs: Record<string, any>
+ // message: Record<string, any>
+ message: string
+ message_tokens: number
+ answer_tokens: number
+ answer: string
+ provider_response_latency: number
+ created_at: number
+ annotation: Annotation
+ feedbacks: Array<{
+ rating: 'like' | 'dislike' | null
+ content: string | null
+ from_source?: 'admin' | 'user'
+ from_end_user_id?: string
+ }>
+}
+
+export type CompletionConversationGeneralDetail = {
+ id: string
+ status: 'normal' | 'finished'
+ from_source: 'api' | 'console'
+ from_end_user_id: string
+ from_account_id: string
+ read_at: Date
+ created_at: number
+ annotation: Annotation
+ user_feedback_stats: {
+ like: number
+ dislike: number
+ }
+ admin_feedback_stats: {
+ like: number
+ dislike: number
+ }
+ model_config: {
+ provider: string
+ model_id: string
+ configs: Pick<ModelConfigDetail, 'prompt_template'>
+ }
+ message: Pick<MessageContent, 'inputs' | 'query' | 'answer' | 'message'>
+}
+
+export type CompletionConversationFullDetailResponse = {
+ id: string
+ status: 'normal' | 'finished'
+ from_source: 'api' | 'console'
+ from_end_user_id: string
+ from_account_id: string
+ // read_at: Date
+ created_at: number
+ model_config: {
+ provider: string
+ model_id: string
+ configs: ModelConfigDetail
+ }
+ message: MessageContent
+}
+
+export type CompletionConversationsResponse = {
+ data: Array<CompletionConversationGeneralDetail>
+ has_more: boolean
+ limit: number
+ total: number
+ page: number
+}
+
+export type CompletionConversationsRequest = {
+ keyword: string
+ start: string
+ end: string
+ annotation_status: string
+ page: number
+ limit: number // The default value is 20 and the range is 1-100
+}
+
+export type ChatConversationGeneralDetail = Omit<CompletionConversationGeneralDetail, 'message' | 'annotation'> & {
+ summary: string
+ message_count: number
+ annotated: boolean
+}
+
+export type ChatConversationsResponse = {
+ data: Array<ChatConversationGeneralDetail>
+ has_more: boolean
+ limit: number
+ total: number
+ page: number
+}
+
+export type ChatConversationsRequest = CompletionConversationsRequest & { message_count: number }
+
+export type ChatConversationFullDetailResponse = Omit<CompletionConversationGeneralDetail, 'message' | 'model_config'> & {
+ message_count: number
+ model_config: {
+ provider: string
+ model_id: string
+ configs: ModelConfigDetail
+ }
+}
+
+export type ChatMessagesRequest = {
+ conversation_id: string
+ first_id?: string
+ limit: number
+}
+export type ChatMessage = MessageContent
+
+export type ChatMessagesResponse = {
+ data: Array<ChatMessage>
+ has_more: boolean
+ limit: number
+}
+
+export const MessageRatings = ['like', 'dislike', null] as const
+export type MessageRating = typeof MessageRatings[number]
+
+export type LogMessageFeedbacksRequest = {
+ message_id: string
+ rating: MessageRating
+ content?: string
+}
+
+export type LogMessageFeedbacksResponse = {
+ result: 'success' | 'error'
+}
+
+export type LogMessageAnnotationsRequest = Omit<LogMessageFeedbacksRequest, 'rating'>
+
+export type LogMessageAnnotationsResponse = LogMessageFeedbacksResponse
+
+export type AnnotationsCountResponse = {
+ count: number
+}
diff --git a/web/models/share.ts b/web/models/share.ts
new file mode 100644
index 00000000000..03eace12fe2
--- /dev/null
+++ b/web/models/share.ts
@@ -0,0 +1,19 @@
+import { Locale } from '@/i18n'
+
+export type ResponseHolder = {}
+
+export type ConversationItem = {
+ id: string
+ name: string
+ inputs: Record<string, any> | null
+ introduction: string,
+}
+
+export type SiteInfo = {
+ title: string
+ description: string
+ default_language: Locale
+ prompt_public: boolean
+ copyright?: string
+ privacy_policy?: string
+}
\ No newline at end of file
diff --git a/web/models/user.ts b/web/models/user.ts
new file mode 100644
index 00000000000..54519809028
--- /dev/null
+++ b/web/models/user.ts
@@ -0,0 +1,17 @@
+export type User = {
+ id: string
+ firstName: string
+ lastName: string
+ name: string
+ phone: string
+ username: string
+ email: string
+ avatar: string
+}
+
+export type UserResponse = {
+ users: User[]
+}
+
+export const fetchUsers = (url: string) =>
+ fetch(url).then<UserResponse>(r => r.json())
diff --git a/web/next.config.js b/web/next.config.js
new file mode 100644
index 00000000000..18ac3e19753
--- /dev/null
+++ b/web/next.config.js
@@ -0,0 +1,43 @@
+const withMDX = require('@next/mdx')({
+ extension: /\.mdx?$/,
+ options: {
+ // If you use remark-gfm, you'll need to use next.config.mjs
+ // as the package is ESM only
+ // https://github.com/remarkjs/remark-gfm#install
+ remarkPlugins: [],
+ rehypePlugins: [],
+ // If you use `MDXProvider`, uncomment the following line.
+ // providerImportSource: "@mdx-js/react",
+ },
+})
+
+/** @type {import('next').NextConfig} */
+const nextConfig = {
+ productionBrowserSourceMaps: false, // enable browser source map generation during the production build
+ // Configure pageExtensions to include md and mdx
+ pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
+ experimental: {
+ appDir: true,
+ },
+ // fix all before production. Now it slow the develop speed.
+ eslint: {
+ // Warning: This allows production builds to successfully complete even if
+ // your project has ESLint errors.
+ ignoreDuringBuilds: true,
+ },
+ typescript: {
+ // https://nextjs.org/docs/api-reference/next.config.js/ignoring-typescript-errors
+ ignoreBuildErrors: true,
+ },
+ async redirects() {
+ return [
+ {
+ source: '/',
+ destination: '/apps',
+ permanent: false,
+ },
+ ]
+ },
+}
+
+module.exports = withMDX(nextConfig)
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 00000000000..c9138c20fee
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,82 @@
+{
+ "name": "dify-web",
+ "version": "0.2.0",
+ "private": true,
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start",
+ "lint": "next lint",
+ "fix": "next lint --fix"
+ },
+ "dependencies": {
+ "@formatjs/intl-localematcher": "^0.2.32",
+ "@headlessui/react": "^1.7.13",
+ "@heroicons/react": "^2.0.16",
+ "@mdx-js/loader": "^2.3.0",
+ "@mdx-js/react": "^2.3.0",
+ "@next/mdx": "^13.2.4",
+ "@tailwindcss/line-clamp": "^0.4.2",
+ "@types/crypto-js": "^4.1.1",
+ "@types/lodash-es": "^4.17.7",
+ "@types/node": "18.15.0",
+ "@types/react": "18.0.28",
+ "@types/react-dom": "18.0.11",
+ "@types/react-slider": "^1.3.1",
+ "@types/react-syntax-highlighter": "^15.5.6",
+ "@types/react-window": "^1.8.5",
+ "@types/react-window-infinite-loader": "^1.0.6",
+ "ahooks": "^3.7.5",
+ "classnames": "^2.3.2",
+ "copy-to-clipboard": "^3.3.3",
+ "crypto-js": "^4.1.1",
+ "dayjs": "^1.11.7",
+ "echarts": "^5.4.1",
+ "echarts-for-react": "^3.0.2",
+ "eslint": "8.36.0",
+ "eslint-config-next": "13.2.4",
+ "i18next": "^22.4.13",
+ "i18next-resources-to-backend": "^1.1.3",
+ "immer": "^9.0.19",
+ "js-cookie": "^3.0.1",
+ "lodash-es": "^4.17.21",
+ "negotiator": "^0.6.3",
+ "next": "13.2.4",
+ "qs": "^6.11.1",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "react-error-boundary": "^4.0.2",
+ "react-headless-pagination": "^1.1.4",
+ "react-i18next": "^12.2.0",
+ "react-infinite-scroll-component": "^6.1.0",
+ "react-markdown": "^8.0.6",
+ "react-slider": "^2.0.4",
+ "react-syntax-highlighter": "^15.5.0",
+ "react-tooltip": "5.8.3",
+ "react-window": "^1.8.9",
+ "react-window-infinite-loader": "^1.0.9",
+ "rehype-katex": "^6.0.2",
+ "remark-breaks": "^3.0.2",
+ "remark-gfm": "^3.0.1",
+ "remark-math": "^5.1.1",
+ "sass": "^1.61.0",
+ "scheduler": "^0.23.0",
+ "server-only": "^0.0.1",
+ "swr": "^2.1.0",
+ "typescript": "4.9.5",
+ "use-context-selector": "^1.4.1"
+ },
+ "devDependencies": {
+ "@antfu/eslint-config": "^0.36.0",
+ "@faker-js/faker": "^7.6.0",
+ "@tailwindcss/typography": "^0.5.9",
+ "@types/js-cookie": "^3.0.3",
+ "@types/negotiator": "^0.6.1",
+ "@types/qs": "^6.9.7",
+ "autoprefixer": "^10.4.14",
+ "eslint-plugin-react-hooks": "^4.6.0",
+ "miragejs": "^0.1.47",
+ "postcss": "^8.4.21",
+ "tailwindcss": "^3.2.7"
+ }
+}
diff --git a/web/postcss.config.js b/web/postcss.config.js
new file mode 100644
index 00000000000..33ad091d26d
--- /dev/null
+++ b/web/postcss.config.js
@@ -0,0 +1,6 @@
+module.exports = {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+}
diff --git a/web/public/favicon.ico b/web/public/favicon.ico
new file mode 100644
index 00000000000..00c1f4fc2b1
Binary files /dev/null and b/web/public/favicon.ico differ
diff --git a/web/service/apps.ts b/web/service/apps.ts
new file mode 100644
index 00000000000..7bb49d4a288
--- /dev/null
+++ b/web/service/apps.ts
@@ -0,0 +1,96 @@
+import type { Fetcher } from 'swr'
+import { del, get, post } from './base'
+import type { ApikeysListResponse, AppDailyConversationsResponse, AppDailyEndUsersResponse, AppDetailResponse, AppListResponse, AppTemplatesResponse, AppTokenCostsResponse, CreateApiKeyResponse, GenerationIntroductionResponse, UpdateAppModelConfigResponse, UpdateAppNameResponse, UpdateAppSiteCodeResponse, UpdateOpenAIKeyResponse, ValidateOpenAIKeyResponse } from '@/models/app'
+import type { CommonResponse } from '@/models/common'
+import type { AppMode, ModelConfig } from '@/types/app'
+
+export const fetchAppList: Fetcher<AppListResponse, { params?: Record<string, any> }> = ({ params }) => {
+ return get('apps', params) as Promise<AppListResponse>
+}
+
+export const fetchAppDetail: Fetcher<AppDetailResponse, { url: string; id: string }> = ({ url, id }) => {
+ return get(`${url}/${id}`) as Promise<AppDetailResponse>
+}
+
+export const fetchAppTemplates: Fetcher<AppTemplatesResponse, { url: string }> = ({ url }) => {
+ return get(url) as Promise<AppTemplatesResponse>
+}
+
+export const createApp: Fetcher<AppDetailResponse, { name: string; mode: AppMode; config?: ModelConfig }> = ({ name, mode, config }) => {
+ return post('apps', { body: { name, mode, model_config: config } }) as Promise<AppDetailResponse>
+}
+
+export const deleteApp: Fetcher<CommonResponse, string> = (appID) => {
+ return del(`apps/${appID}`) as Promise<CommonResponse>
+}
+
+// path: /apps/{appId}/name
+export const updateAppName: Fetcher<UpdateAppNameResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<UpdateAppNameResponse>
+}
+
+export const updateAppSiteStatus: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<AppDetailResponse>
+}
+
+export const updateAppApiStatus: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<AppDetailResponse>
+}
+
+// path: /apps/{appId}/rate-limit
+export const updateAppRateLimit: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<AppDetailResponse>
+}
+
+export const updateAppSiteAccessToken: Fetcher<UpdateAppSiteCodeResponse, { url: string }> = ({ url }) => {
+ return post(url) as Promise<UpdateAppSiteCodeResponse>
+}
+
+export const updateAppSiteConfig: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<AppDetailResponse>
+}
+
+export const getAppDailyConversations: Fetcher<AppDailyConversationsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<AppDailyConversationsResponse>
+}
+
+export const getAppDailyEndUsers: Fetcher<AppDailyEndUsersResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<AppDailyEndUsersResponse>
+}
+
+export const getAppTokenCosts: Fetcher<AppTokenCostsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<AppTokenCostsResponse>
+}
+
+export const updateAppModelConfig: Fetcher<UpdateAppModelConfigResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<UpdateAppModelConfigResponse>
+}
+
+// For temp testing
+export const fetchAppListNoMock: Fetcher<AppListResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, params) as Promise<AppListResponse>
+}
+
+export const fetchApiKeysList: Fetcher<ApikeysListResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, params) as Promise<ApikeysListResponse>
+}
+
+export const delApikey: Fetcher<CommonResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return del(url, params) as Promise<CommonResponse>
+}
+
+export const createApikey: Fetcher<CreateApiKeyResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, body) as Promise<CreateApiKeyResponse>
+}
+
+export const validateOpenAIKey: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<ValidateOpenAIKeyResponse>
+}
+
+export const updateOpenAIKey: Fetcher<UpdateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<UpdateOpenAIKeyResponse>
+}
+
+export const generationIntroduction: Fetcher<GenerationIntroductionResponse, { url: string; body: { prompt_template: string } }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<GenerationIntroductionResponse>
+}
diff --git a/web/service/base.ts b/web/service/base.ts
new file mode 100644
index 00000000000..737f8a1c6a2
--- /dev/null
+++ b/web/service/base.ts
@@ -0,0 +1,353 @@
+import { API_PREFIX, MOCK_API_PREFIX, PUBLIC_API_PREFIX, IS_CE_EDITION } from '@/config'
+import Toast from '@/app/components/base/toast'
+
+const TIME_OUT = 100000
+
+const ContentType = {
+ json: 'application/json',
+ stream: 'text/event-stream',
+ form: 'application/x-www-form-urlencoded; charset=UTF-8',
+ download: 'application/octet-stream', // for download
+ upload: 'multipart/form-data', // for upload
+}
+
+const baseOptions = {
+ method: 'GET',
+ mode: 'cors',
+ credentials: 'include', // always send cookies、HTTP Basic authentication.
+ headers: new Headers({
+ 'Content-Type': ContentType.json,
+ }),
+ redirect: 'follow',
+}
+
+export type IOnDataMoreInfo = {
+ conversationId: string | undefined
+ messageId: string
+ errorMessage?: string
+}
+
+export type IOnData = (message: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => void
+export type IOnCompleted = (hasError?: boolean) => void
+export type IOnError = (msg: string) => void
+
+type IOtherOptions = {
+ isPublicAPI?: boolean
+ isMock?: boolean
+ needAllResponseContent?: boolean
+ onData?: IOnData // for stream
+ onError?: IOnError
+ onCompleted?: IOnCompleted // for stream
+ getAbortController?: (abortController: AbortController) => void
+}
+
+function unicodeToChar(text: string) {
+ return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
+ return String.fromCharCode(parseInt(p1, 16))
+ })
+}
+
+
+export function format(text: string) {
+ let res = text.trim()
+ if (res.startsWith('\n')) {
+ res = res.replace('\n', '')
+ }
+ return res.replaceAll('\n', '<br/>').replaceAll('```', '')
+}
+
+const handleStream = (response: any, onData: IOnData, onCompleted?: IOnCompleted) => {
+ if (!response.ok)
+ throw new Error('Network response was not ok')
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder('utf-8')
+ let buffer = ''
+ let bufferObj: any
+ let isFirstMessage = true
+ function read() {
+ let hasError = false
+ reader.read().then((result: any) => {
+ if (result.done) {
+ onCompleted && onCompleted()
+ return
+ }
+ buffer += decoder.decode(result.value, { stream: true })
+ const lines = buffer.split('\n')
+ try {
+ lines.forEach((message) => {
+ if (message.startsWith('data: ')) { // check if it starts with data:
+ // console.log(message);
+ bufferObj = JSON.parse(message.substring(6)) // remove data: and parse as json
+ if (bufferObj.status === 400) {
+ onData('', false, {
+ conversationId: undefined,
+ messageId: '',
+ errorMessage: bufferObj.message
+ })
+ hasError = true
+ onCompleted && onCompleted(true)
+ return
+ }
+ // can not use format here. Because message is splited.
+ onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
+ conversationId: bufferObj.conversation_id,
+ messageId: bufferObj.id,
+ })
+ isFirstMessage = false
+ }
+ })
+ buffer = lines[lines.length - 1]
+ } catch (e) {
+ onData('', false, {
+ conversationId: undefined,
+ messageId: '',
+ errorMessage: e + ''
+ })
+ hasError = true
+ onCompleted && onCompleted(true)
+ return
+ }
+ if (!hasError) {
+ read()
+ }
+ })
+ }
+ read()
+}
+
+const baseFetch = (url: string, fetchOptions: any, { isPublicAPI = false, isMock = false, needAllResponseContent }: IOtherOptions) => {
+ const options = Object.assign({}, baseOptions, fetchOptions)
+ if (isPublicAPI) {
+ const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
+ options.headers.set('Authorization', `bearer ${sharedToken}`)
+ }
+
+ let urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
+ if (isMock)
+ urlPrefix = MOCK_API_PREFIX
+
+ let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
+
+ const { method, params, body } = options
+ // handle query
+ if (method === 'GET' && params) {
+ const paramsArray: string[] = []
+ Object.keys(params).forEach(key =>
+ paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
+ )
+ if (urlWithPrefix.search(/\?/) === -1)
+ urlWithPrefix += `?${paramsArray.join('&')}`
+
+ else
+ urlWithPrefix += `&${paramsArray.join('&')}`
+
+ delete options.params
+ }
+
+ if (body)
+ options.body = JSON.stringify(body)
+
+ // Handle timeout
+ return Promise.race([
+ new Promise((resolve, reject) => {
+ setTimeout(() => {
+ reject(new Error('request timeout'))
+ }, TIME_OUT)
+ }),
+ new Promise((resolve, reject) => {
+ globalThis.fetch(urlWithPrefix, options)
+ .then((res: any) => {
+ const resClone = res.clone()
+ // Error handler
+ if (!/^(2|3)\d{2}$/.test(res.status)) {
+ const bodyJson = res.json()
+ switch (res.status) {
+ case 401: {
+ if (isPublicAPI) {
+ Toast.notify({ type: 'error', message: 'Invalid token' })
+ return
+ }
+ const loginUrl = `${globalThis.location.origin}/signin`
+ if (IS_CE_EDITION) {
+ bodyJson.then((data: any) => {
+ if (data.code === 'not_setup') {
+ globalThis.location.href = `${globalThis.location.origin}/install`
+ } else {
+ if (location.pathname === '/signin') {
+ bodyJson.then((data: any) => {
+ Toast.notify({ type: 'error', message: data.message })
+ })
+ } else {
+ globalThis.location.href = loginUrl
+ }
+ }
+ })
+ return Promise.reject()
+ }
+ globalThis.location.href = loginUrl
+ break
+ }
+ case 403:
+ new Promise(() => {
+ bodyJson.then((data: any) => {
+ Toast.notify({ type: 'error', message: data.message })
+ if (data.code === 'already_setup') {
+ globalThis.location.href = `${globalThis.location.origin}/signin`
+ }
+ })
+ })
+ break
+ // fall through
+ default:
+ // eslint-disable-next-line no-new
+ new Promise(() => {
+ bodyJson.then((data: any) => {
+ Toast.notify({ type: 'error', message: data.message })
+ })
+ })
+ }
+ return Promise.reject(resClone)
+ }
+
+ // handle delete api. Delete api not return content.
+ if (res.status === 204) {
+ resolve({ result: "success" })
+ return
+ }
+
+ // return data
+ const data = options.headers.get('Content-type') === ContentType.download ? res.blob() : res.json()
+
+ resolve(needAllResponseContent ? resClone : data)
+ })
+ .catch((err) => {
+ Toast.notify({ type: 'error', message: err })
+ reject(err)
+ })
+ }),
+ ])
+}
+
+export const upload = (options: any): Promise<any> => {
+ const defaultOptions = {
+ method: 'POST',
+ url: `${API_PREFIX}/files/upload`,
+ headers: {},
+ data: {},
+ }
+ options = {
+ ...defaultOptions,
+ ...options,
+ headers: { ...defaultOptions.headers, ...options.headers },
+ };
+ return new Promise(function (resolve, reject) {
+ const xhr = options.xhr
+ xhr.open(options.method, options.url);
+ for (const key in options.headers) {
+ xhr.setRequestHeader(key, options.headers[key]);
+ }
+ xhr.withCredentials = true
+ xhr.responseType = 'json'
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.status === 201) {
+ resolve(xhr.response)
+ } else {
+ reject(xhr)
+ }
+ }
+ }
+ xhr.upload.onprogress = options.onprogress
+ xhr.send(options.data)
+ })
+}
+
+export const ssePost = (url: string, fetchOptions: any, { isPublicAPI = false, onData, onCompleted, onError, getAbortController }: IOtherOptions) => {
+ const abortController = new AbortController()
+
+ const options = Object.assign({}, baseOptions, {
+ method: 'POST',
+ signal: abortController.signal,
+ }, fetchOptions)
+
+ getAbortController?.(abortController)
+
+ const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
+ const urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
+
+ const { body } = options
+ if (body)
+ options.body = JSON.stringify(body)
+
+ globalThis.fetch(urlWithPrefix, options)
+ .then((res: any) => {
+ // debugger
+ if (!/^(2|3)\d{2}$/.test(res.status)) {
+ // eslint-disable-next-line no-new
+ new Promise(() => {
+ res.json().then((data: any) => {
+ Toast.notify({ type: 'error', message: data.message || 'Server Error' })
+ })
+ })
+ onError?.('Server Error')
+ return
+ }
+ return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
+ if (moreInfo.errorMessage) {
+ Toast.notify({ type: 'error', message: moreInfo.errorMessage })
+ return
+ }
+ onData?.(str, isFirstMessage, moreInfo)
+ }, onCompleted)
+ }).catch((e) => {
+ // debugger
+ Toast.notify({ type: 'error', message: e })
+ onError?.(e)
+ })
+}
+
+export const request = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return baseFetch(url, options, otherOptions || {})
+}
+
+export const get = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return request(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
+}
+
+// For public API
+export const getPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return get(url, options, { ...otherOptions, isPublicAPI: true })
+}
+
+export const post = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return request(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
+}
+
+export const postPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return post(url, options, { ...otherOptions, isPublicAPI: true })
+}
+
+export const put = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return request(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
+}
+
+export const putPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return put(url, options, { ...otherOptions, isPublicAPI: true })
+}
+
+export const del = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return request(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
+}
+
+export const delPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return del(url, options, { ...otherOptions, isPublicAPI: true })
+}
+
+export const patch = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return request(url, Object.assign({}, options, { method: 'PATCH' }), otherOptions)
+}
+
+export const patchPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
+ return patch(url, options, { ...otherOptions, isPublicAPI: true })
+}
diff --git a/web/service/common.ts b/web/service/common.ts
new file mode 100644
index 00000000000..4f28cc84d3e
--- /dev/null
+++ b/web/service/common.ts
@@ -0,0 +1,91 @@
+import type { Fetcher } from 'swr'
+import { get, post, del, put } from './base'
+import type {
+ CommonResponse, LangGeniusVersionResponse, OauthResponse,
+ TenantInfoResponse, UserProfileOriginResponse, Member,
+ AccountIntegrate, Provider, ProviderAzureToken, IWorkspace
+} from '@/models/common'
+import type {
+ ValidateOpenAIKeyResponse,
+ UpdateOpenAIKeyResponse
+} from '@/models/app'
+
+export const login: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<CommonResponse>
+}
+
+export const setup: Fetcher<CommonResponse, { body: Record<string, any> }> = ({ body }) => {
+ return post('/setup', { body }) as Promise<CommonResponse>
+}
+
+export const fetchUserProfile: Fetcher<UserProfileOriginResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, params, { needAllResponseContent: true }) as Promise<UserProfileOriginResponse>
+}
+
+export const updateUserProfile: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<CommonResponse>
+}
+
+export const fetchTenantInfo: Fetcher<TenantInfoResponse, { url: string }> = ({ url }) => {
+ return get(url) as Promise<TenantInfoResponse>
+}
+
+export const logout: Fetcher<CommonResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, params) as Promise<CommonResponse>
+}
+
+export const fetchLanggeniusVersion: Fetcher<LangGeniusVersionResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<LangGeniusVersionResponse>
+}
+
+export const oauth: Fetcher<OauthResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<OauthResponse>
+}
+
+export const oneMoreStep: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<CommonResponse>
+}
+
+export const fetchMembers: Fetcher<{ accounts: Member[] | null }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<{ accounts: Member[] | null }>
+}
+
+export const fetchProviders: Fetcher<Provider[] | null, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<Provider[] | null>
+}
+
+export const validateProviderKey: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<ValidateOpenAIKeyResponse>
+}
+export const updateProviderAIKey: Fetcher<UpdateOpenAIKeyResponse, { url: string; body: { token: string | ProviderAzureToken } }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<UpdateOpenAIKeyResponse>
+}
+
+export const fetchAccountIntegrates: Fetcher<{ data: AccountIntegrate[] | null }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<{ data: AccountIntegrate[] | null }>
+}
+
+export const inviteMember: Fetcher<CommonResponse & { account: Member }, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<CommonResponse & { account: Member }>
+}
+
+export const updateMemberRole: Fetcher<CommonResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return put(url, { body }) as Promise<CommonResponse>
+}
+
+export const deleteMemberOrCancelInvitation: Fetcher<CommonResponse, { url: string; }> = ({ url }) => {
+ return del(url) as Promise<CommonResponse>
+}
+
+export const fetchFilePreview: Fetcher<{ content: string }, { fileID: string }> = ({ fileID }) => {
+ return get(`/files/${fileID}/preview`) as Promise<{ content: string }>
+}
+
+export const fetchWorkspaces: Fetcher<{ workspaces: IWorkspace[] }, { url: string; params: Record<string, any> }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<{ workspaces: IWorkspace[] }>
+}
+
+export const switchWorkspace: Fetcher<CommonResponse & { new_tenant: IWorkspace }, { url: string; body: Record<string, any> }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<CommonResponse & { new_tenant: IWorkspace }>
+}
+
diff --git a/web/service/datasets.ts b/web/service/datasets.ts
new file mode 100644
index 00000000000..b633dbf886d
--- /dev/null
+++ b/web/service/datasets.ts
@@ -0,0 +1,127 @@
+import type { Fetcher } from 'swr'
+import { del, get, post, put, patch } from './base'
+import qs from 'qs'
+import type { RelatedAppResponse, DataSet, HitTestingResponse, HitTestingRecordsResponse, DataSetListResponse, CreateDocumentReq, InitialDocumentDetail, DocumentDetailResponse, DocumentListResponse, IndexingEstimateResponse, FileIndexingEstimateResponse, IndexingStatusResponse, ProcessRuleResponse, SegmentsQuery, SegmentsResponse, createDocumentResponse } from '@/models/datasets'
+import type { CommonResponse } from '@/models/common'
+
+// apis for documents in a dataset
+
+type CommonDocReq = {
+ datasetId: string
+ documentId: string
+}
+
+export type SortType = 'created_at' | 'hit_count' | '-created_at' | '-hit_count'
+
+export type MetadataType = 'all' | 'only' | 'without'
+
+export const fetchDataDetail: Fetcher<DataSet, string> = (datasetId: string) => {
+ return get(`/datasets/${datasetId}`) as Promise<DataSet>
+}
+
+export const updateDatasetSetting: Fetcher<DataSet, { datasetId: string, body: Partial<Pick<DataSet, 'name' | 'description' | 'permission' | 'indexing_technique'>>}> = ({ datasetId, body }) => {
+ return patch(`/datasets/${datasetId}`, { body } ) as Promise<DataSet>
+}
+
+export const fetchDatasetRelatedApps: Fetcher<RelatedAppResponse, string> = (datasetId: string) => {
+ return get(`/datasets/${datasetId}/related-apps`) as Promise<RelatedAppResponse>
+}
+
+export const fetchDatasets: Fetcher<DataSetListResponse, { url: string, params: { page: number, ids?: string[], limit?: number } }> = ({ url, params }) => {
+ const urlParams = qs.stringify(params, { indices: false })
+ return get(`${url}?${urlParams}`,) as Promise<DataSetListResponse>
+}
+
+export const createEmptyDataset: Fetcher<DataSet, { name: string }> = ({ name }) => {
+ return post('/datasets', { body: { name } }) as Promise<DataSet>
+}
+
+export const deleteDataset: Fetcher<DataSet, string> = (datasetID) => {
+ return del(`/datasets/${datasetID}`) as Promise<DataSet>
+}
+
+export const fetchDefaultProcessRule: Fetcher<ProcessRuleResponse, { url: string }> = ({ url }) => {
+ return get(url) as Promise<ProcessRuleResponse>
+}
+export const fetchProcessRule: Fetcher<ProcessRuleResponse, { params: { documentId: string } }> = ({ params: { documentId } }) => {
+ return get('/datasets/process-rule', { params: { document_id: documentId } }) as Promise<ProcessRuleResponse>
+}
+
+export const fetchDocuments: Fetcher<DocumentListResponse, { datasetId: string; params: { keyword: string; page: number; limit: number; sort?: SortType } }> = ({ datasetId, params }) => {
+ return get(`/datasets/${datasetId}/documents`, { params }) as Promise<DocumentListResponse>
+}
+
+export const createFirstDocument: Fetcher<createDocumentResponse, { body: CreateDocumentReq }> = ({ body }) => {
+ return post(`/datasets/init`, { body }) as Promise<createDocumentResponse>
+}
+
+export const createDocument: Fetcher<InitialDocumentDetail, { datasetId: string; body: CreateDocumentReq }> = ({ datasetId, body }) => {
+ return post(`/datasets/${datasetId}/documents`, { body }) as Promise<InitialDocumentDetail>
+}
+
+export const fetchIndexingEstimate: Fetcher<IndexingEstimateResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return get(`/datasets/${datasetId}/documents/${documentId}/indexing-estimate`, {}) as Promise<IndexingEstimateResponse>
+}
+
+export const fetchIndexingStatus: Fetcher<IndexingStatusResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return get(`/datasets/${datasetId}/documents/${documentId}/indexing-status`, {}) as Promise<IndexingStatusResponse>
+}
+
+export const fetchDocumentDetail: Fetcher<DocumentDetailResponse, CommonDocReq & { params: { metadata?: MetadataType } }> = ({ datasetId, documentId, params }) => {
+ return get(`/datasets/${datasetId}/documents/${documentId}`, { params }) as Promise<DocumentDetailResponse>
+}
+
+export const pauseDocIndexing: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return patch(`/datasets/${datasetId}/documents/${documentId}/processing/pause`) as Promise<CommonResponse>
+}
+
+export const resumeDocIndexing: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return patch(`/datasets/${datasetId}/documents/${documentId}/processing/resume`) as Promise<CommonResponse>
+}
+
+export const deleteDocument: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return del(`/datasets/${datasetId}/documents/${documentId}`) as Promise<CommonResponse>
+}
+
+export const archiveDocument: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return patch(`/datasets/${datasetId}/documents/${documentId}/status/archive`) as Promise<CommonResponse>
+}
+
+export const enableDocument: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return patch(`/datasets/${datasetId}/documents/${documentId}/status/enable`) as Promise<CommonResponse>
+}
+
+export const disableDocument: Fetcher<CommonResponse, CommonDocReq> = ({ datasetId, documentId }) => {
+ return patch(`/datasets/${datasetId}/documents/${documentId}/status/disable`) as Promise<CommonResponse>
+}
+
+export const modifyDocMetadata: Fetcher<CommonResponse, CommonDocReq & { body: { doc_type: string; doc_metadata: Record<string, any> } }> = ({ datasetId, documentId, body }) => {
+ return put(`/datasets/${datasetId}/documents/${documentId}/metadata`, { body }) as Promise<CommonResponse>
+}
+
+// apis for segments in a document
+
+export const fetchSegments: Fetcher<SegmentsResponse, CommonDocReq & { params: SegmentsQuery }> = ({ datasetId, documentId, params }) => {
+ return get(`/datasets/${datasetId}/documents/${documentId}/segments`, { params }) as Promise<SegmentsResponse>
+}
+
+export const enableSegment: Fetcher<CommonResponse, { datasetId: string; segmentId: string }> = ({ datasetId, segmentId }) => {
+ return patch(`/datasets/${datasetId}/segments/${segmentId}/enable`) as Promise<CommonResponse>
+}
+
+export const disableSegment: Fetcher<CommonResponse, { datasetId: string; segmentId: string }> = ({ datasetId, segmentId }) => {
+ return patch(`/datasets/${datasetId}/segments/${segmentId}/disable`) as Promise<CommonResponse>
+}
+
+// hit testing
+export const hitTesting: Fetcher<HitTestingResponse, { datasetId: string; queryText: string }> = ({ datasetId, queryText }) => {
+ return post(`/datasets/${datasetId}/hit-testing`, { body: { query: queryText } }) as Promise<HitTestingResponse>
+}
+
+export const fetchTestingRecords: Fetcher<HitTestingRecordsResponse, { datasetId: string; params: { page: number; limit: number } }> = ({ datasetId, params }) => {
+ return get(`/datasets/${datasetId}/queries`, { params }) as Promise<HitTestingRecordsResponse>
+}
+
+export const fetchFileIndexingEstimate: Fetcher<FileIndexingEstimateResponse, any> = (body: any) => {
+ return post(`/datasets/file-indexing-estimate`, { body }) as Promise<FileIndexingEstimateResponse>
+}
diff --git a/web/service/debug.ts b/web/service/debug.ts
new file mode 100644
index 00000000000..b6b922f0e05
--- /dev/null
+++ b/web/service/debug.ts
@@ -0,0 +1,40 @@
+import { ssePost, get, IOnData, IOnCompleted, IOnError } from './base'
+
+export const sendChatMessage = async (appId: string, body: Record<string, any>, { onData, onCompleted, onError, getAbortController }: {
+ onData: IOnData
+ onCompleted: IOnCompleted
+ onError: IOnError,
+ getAbortController?: (abortController: AbortController) => void
+}) => {
+ return ssePost(`apps/${appId}/chat-messages`, {
+ body: {
+ ...body,
+ response_mode: 'streaming'
+ }
+ }, { onData, onCompleted, onError, getAbortController })
+}
+
+export const sendCompletionMessage = async (appId: string, body: Record<string, any>, { onData, onCompleted, onError }: {
+ onData: IOnData
+ onCompleted: IOnCompleted
+ onError: IOnError
+}) => {
+ return ssePost(`apps/${appId}/completion-messages`, {
+ body: {
+ ...body,
+ response_mode: 'streaming'
+ }
+ }, { onData, onCompleted, onError })
+}
+
+export const fetchSuggestedQuestions = (appId: string, messageId: string) => {
+ return get(`apps/${appId}/chat-messages/${messageId}/suggested-questions`)
+}
+
+export const fetchConvesationMessages = (appId: string, conversation_id: string) => {
+ return get(`apps/${appId}/chat-messages`, {
+ params: {
+ conversation_id
+ }
+ })
+}
diff --git a/web/service/demo/index.tsx b/web/service/demo/index.tsx
new file mode 100644
index 00000000000..d95c351f19e
--- /dev/null
+++ b/web/service/demo/index.tsx
@@ -0,0 +1,106 @@
+'use client'
+import type { FC } from 'react'
+import React from 'react'
+import useSWR, { useSWRConfig } from 'swr'
+import { createApp, fetchAppDetail, fetchAppList, getAppDailyConversations, getAppDailyEndUsers, updateAppApiStatus, updateAppModelConfig, updateAppName, updateAppRateLimit, updateAppSiteAccessToken, updateAppSiteConfig, updateAppSiteStatus } from '../apps'
+import Loading from '@/app/components/base/loading'
+const Service: FC = () => {
+ const { data: appList, error: appListError } = useSWR({ url: '/apps', params: { page: 1 } }, fetchAppList)
+ const { data: firstApp, error: appDetailError } = useSWR({ url: '/apps', id: '1' }, fetchAppDetail)
+ const { data: appName, error: appNameError } = useSWR({ url: '/apps', id: '1', body: { name: 'new name' } }, updateAppName)
+ const { data: updateAppSiteStatusRes, error: err1 } = useSWR({ url: '/apps', id: '1', body: { enable_site: false } }, updateAppSiteStatus)
+ const { data: updateAppApiStatusRes, error: err2 } = useSWR({ url: '/apps', id: '1', body: { enable_api: true } }, updateAppApiStatus)
+ const { data: updateAppRateLimitRes, error: err3 } = useSWR({ url: '/apps', id: '1', body: { api_rpm: 10, api_rph: 20 } }, updateAppRateLimit)
+ const { data: updateAppSiteCodeRes, error: err4 } = useSWR({ url: '/apps', id: '1', body: {} }, updateAppSiteAccessToken)
+ const { data: updateAppSiteConfigRes, error: err5 } = useSWR({ url: '/apps', id: '1', body: { title: 'title test', author: 'author test' } }, updateAppSiteConfig)
+ const { data: getAppDailyConversationsRes, error: err6 } = useSWR({ url: '/apps', id: '1', body: { start: '1', end: '2' } }, getAppDailyConversations)
+ const { data: getAppDailyEndUsersRes, error: err7 } = useSWR({ url: '/apps', id: '1', body: { start: '1', end: '2' } }, getAppDailyEndUsers)
+ const { data: updateAppModelConfigRes, error: err8 } = useSWR({ url: '/apps', id: '1', body: { model_id: 'gpt-100' } }, updateAppModelConfig)
+
+ const { mutate } = useSWRConfig()
+
+ const handleCreateApp = async () => {
+ await createApp({
+ name: `new app${Math.round(Math.random() * 100)}`,
+ mode: 'chat',
+ })
+ // reload app list
+ mutate({ url: '/apps', params: { page: 1 } })
+ }
+
+ if (appListError || appDetailError || appNameError || err1 || err2 || err3 || err4 || err5 || err6 || err7 || err8)
+ return <div>{JSON.stringify(appNameError)}</div>
+
+ if (!appList || !firstApp || !appName || !updateAppSiteStatusRes || !updateAppApiStatusRes || !updateAppRateLimitRes || !updateAppSiteCodeRes || !updateAppSiteConfigRes || !getAppDailyConversationsRes || !getAppDailyEndUsersRes || !updateAppModelConfigRes)
+ return <Loading />
+
+ return (
+ <div>
+ <div className='flex flex-col gap-3'>
+ <div>
+ <div>1.App list</div>
+ <div>
+ {appList.data.map(item => (
+ <div key={item.id}>{item.id} {item.name}</div>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <div>2.First app detail</div>
+ <div>{JSON.stringify(firstApp)}</div>
+ </div>
+
+ <div>
+ <button onClick={handleCreateApp}>Click me to Create App</button>
+ </div>
+
+ <div>
+ <div>3.updateAppName</div>
+ <div>{JSON.stringify(appName)}</div>
+ </div>
+
+ <div>
+ <div>4.updateAppSiteStatusRes</div>
+ <div>{JSON.stringify(updateAppSiteStatusRes)}</div>
+ </div>
+
+ <div>
+ <div>5.updateAppApiStatusRes</div>
+ <div>{JSON.stringify(updateAppApiStatusRes)}</div>
+ </div>
+
+ <div>
+ <div>6.updateAppRateLimitRes</div>
+ <div>{JSON.stringify(updateAppRateLimitRes)}</div>
+ </div>
+
+ <div>
+ <div>7.updateAppSiteCodeRes</div>
+ <div>{JSON.stringify(updateAppSiteCodeRes)}</div>
+ </div>
+
+ <div>
+ <div>8.updateAppSiteConfigRes</div>
+ <div>{JSON.stringify(updateAppSiteConfigRes)}</div>
+ </div>
+
+ <div>
+ <div>9.getAppDailyConversationsRes</div>
+ <div>{JSON.stringify(getAppDailyConversationsRes)}</div>
+ </div>
+
+ <div>
+ <div>10.getAppDailyEndUsersRes</div>
+ <div>{JSON.stringify(getAppDailyEndUsersRes)}</div>
+ </div>
+
+ <div>
+ <div>11.updateAppModelConfigRes</div>
+ <div>{JSON.stringify(updateAppModelConfigRes)}</div>
+ </div>
+ </div>
+ </div>
+ )
+}
+export default React.memo(Service)
diff --git a/web/service/log.ts b/web/service/log.ts
new file mode 100644
index 00000000000..76ebd3adcd7
--- /dev/null
+++ b/web/service/log.ts
@@ -0,0 +1,59 @@
+import type { Fetcher } from 'swr'
+import { get, post } from './base'
+import type {
+ AnnotationsCountResponse,
+ ChatConversationFullDetailResponse,
+ ChatConversationsRequest,
+ ChatConversationsResponse,
+ ChatMessagesRequest,
+ ChatMessagesResponse,
+ CompletionConversationFullDetailResponse,
+ CompletionConversationsRequest,
+ CompletionConversationsResponse,
+ ConversationListResponse,
+ LogMessageAnnotationsRequest,
+ LogMessageAnnotationsResponse,
+ LogMessageFeedbacksRequest,
+ LogMessageFeedbacksResponse,
+} from '@/models/log'
+
+export const fetchConversationList: Fetcher<ConversationListResponse, { name: string; appId: string; params?: Record<string, any> }> = ({ appId, params }) => {
+ return get(`/console/api/apps/${appId}/messages`, params) as Promise<ConversationListResponse>
+}
+
+// (Text Generation Application) Session List
+export const fetchCompletionConversations: Fetcher<CompletionConversationsResponse, { url: string; params?: CompletionConversationsRequest }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<CompletionConversationsResponse>
+}
+
+// (Text Generation Application) Session Detail
+export const fetchCompletionConversationDetail: Fetcher<CompletionConversationFullDetailResponse, { url: string }> = ({ url }) => {
+ return get(url, {}) as Promise<CompletionConversationFullDetailResponse>
+}
+
+// (Chat Application) Session List
+export const fetchChatConversations: Fetcher<ChatConversationsResponse, { url: string; params?: ChatConversationsRequest }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<ChatConversationsResponse>
+}
+
+// (Chat Application) Session Detail
+export const fetchChatConversationDetail: Fetcher<ChatConversationFullDetailResponse, { url: string }> = ({ url }) => {
+ return get(url, {}) as Promise<ChatConversationFullDetailResponse>
+}
+
+// (Chat Application) Message list in one session
+export const fetchChatMessages: Fetcher<ChatMessagesResponse, { url: string; params: ChatMessagesRequest }> = ({ url, params }) => {
+ return get(url, { params }) as Promise<ChatMessagesResponse>
+}
+
+export const updateLogMessageFeedbacks: Fetcher<LogMessageFeedbacksResponse, { url: string; body: LogMessageFeedbacksRequest }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<LogMessageFeedbacksResponse>
+}
+
+export const updateLogMessageAnnotations: Fetcher<LogMessageAnnotationsResponse, { url: string; body: LogMessageAnnotationsRequest }> = ({ url, body }) => {
+ return post(url, { body }) as Promise<LogMessageAnnotationsResponse>
+}
+
+export const fetchAnnotationsCount: Fetcher<AnnotationsCountResponse, { url: string }> = ({ url }) => {
+ return get(url) as Promise<AnnotationsCountResponse>
+}
diff --git a/web/service/share.ts b/web/service/share.ts
new file mode 100644
index 00000000000..7623be5f804
--- /dev/null
+++ b/web/service/share.ts
@@ -0,0 +1,81 @@
+import type { IOnCompleted, IOnData, IOnError } from './base'
+import { getPublic as get, postPublic as post, ssePost, delPublic as del } from './base'
+import type { Feedbacktype } from '@/app/components/app/chat'
+
+export const sendChatMessage = async (body: Record<string, any>, { onData, onCompleted, onError, getAbortController }: {
+ onData: IOnData
+ onCompleted: IOnCompleted
+ onError: IOnError,
+ getAbortController?: (abortController: AbortController) => void
+}) => {
+ return ssePost('chat-messages', {
+ body: {
+ ...body,
+ response_mode: 'streaming',
+ },
+ }, { onData, onCompleted, isPublicAPI: true, onError, getAbortController })
+}
+
+export const sendCompletionMessage = async (body: Record<string, any>, { onData, onCompleted, onError }: {
+ onData: IOnData
+ onCompleted: IOnCompleted
+ onError: IOnError
+}) => {
+ return ssePost('completion-messages', {
+ body: {
+ ...body,
+ response_mode: 'streaming',
+ },
+ }, { onData, onCompleted, isPublicAPI: true, onError })
+}
+
+export const fetchAppInfo = async () => {
+ return get('/site')
+}
+
+export const fetchConversations = async () => {
+ return get('conversations', { params: { limit: 20, first_id: '' } })
+}
+
+export const fetchChatList = async (conversationId: string) => {
+ return get('messages', { params: { conversation_id: conversationId, limit: 20, last_id: '' } })
+}
+
+// Abandoned API interface
+// export const fetchAppVariables = async () => {
+// return get(`variables`)
+// }
+
+// init value. wait for server update
+export const fetchAppParams = async () => {
+ return get('parameters')
+}
+
+export const updateFeedback = async ({ url, body }: { url: string; body: Feedbacktype }) => {
+ return post(url, { body })
+}
+
+export const fetcMoreLikeThis = async (messageId: string) => {
+ return get(`/messages/${messageId}/more-like-this`, {
+ params: {
+ response_mode: 'blocking',
+ }
+ })
+}
+
+export const saveMessage = (messageId: string) => {
+ return post('/saved-messages', { body: { message_id: messageId } })
+}
+
+export const fetchSavedMessage = async () => {
+ return get(`/saved-messages`)
+}
+
+
+export const removeMessage = (messageId: string) => {
+ return del(`/saved-messages/${messageId}`)
+}
+
+export const fetchSuggestedQuestions = (messageId: string) => {
+ return get(`/messages/${messageId}/suggested-questions`)
+}
diff --git a/web/tailwind.config.js b/web/tailwind.config.js
new file mode 100644
index 00000000000..72bb5503608
--- /dev/null
+++ b/web/tailwind.config.js
@@ -0,0 +1,70 @@
+/** @type {import('tailwindcss').Config} */
+module.exports = {
+ content: [
+ './app/**/*.{js,ts,jsx,tsx}',
+ './components/**/*.{js,ts,jsx,tsx}',
+ ],
+ theme: {
+ typography: require('./typography'),
+ extend: {
+ colors: {
+ gray: {
+ 25: '#FCFCFD',
+ 50: '#F9FAFB',
+ 100: '#F3F4F6',
+ 200: '#E5E7EB',
+ 300: '#D1D5DB',
+ 400: '#9CA3AF',
+ 500: '#6B7280',
+ 700: '#374151',
+ 800: '#1F2A37',
+ 900: '#111928',
+ },
+ primary: {
+ 25: '#F5F8FF',
+ 50: '#EBF5FF',
+ 100: '#E1EFFE',
+ 200: '#C3DDFD',
+ 300: '#A4CAFE',
+ 400: '#528BFF',
+ 600: '#1C64F2',
+ 700: '#1A56DB',
+ },
+ blue: {
+ 500: '#E1EFFE',
+ },
+ green: {
+ 50: '#F3FAF7',
+ 100: '#DEF7EC',
+ 800: '#03543F',
+
+ },
+ yellow: {
+ 100: '#FDF6B2',
+ 800: '#723B13',
+ },
+ purple: {
+ 50: '#F6F5FF',
+ 200: '#DCD7FE',
+ },
+ indigo: {
+ 25: '#F5F8FF',
+ 100: '#E0EAFF',
+ 600: '#444CE7'
+ }
+ },
+ screens: {
+ 'mobile': '100px',
+ // => @media (min-width: 100px) { ... }
+ 'tablet': '640px', // 391
+ // => @media (min-width: 600px) { ... }
+ 'pc': '769px',
+ // => @media (min-width: 769px) { ... }
+ },
+ },
+ },
+ plugins: [
+ require('@tailwindcss/typography'),
+ require('@tailwindcss/line-clamp'),
+ ],
+}
diff --git a/web/test/factories/index.ts b/web/test/factories/index.ts
new file mode 100644
index 00000000000..810e05eb49e
--- /dev/null
+++ b/web/test/factories/index.ts
@@ -0,0 +1,66 @@
+import { Factory } from 'miragejs'
+import { faker } from '@faker-js/faker'
+
+import type { History } from '@/models/history'
+import type { User } from '@/models/user'
+import type { Log } from '@/models/log'
+
+export const seedHistory = () => {
+ return Factory.extend<Partial<History>>({
+ source() {
+ return faker.address.streetAddress()
+ },
+ target() {
+ return faker.address.streetAddress()
+ },
+ })
+}
+
+export const seedUser = () => {
+ return Factory.extend<Partial<User>>({
+ firstName() {
+ return faker.name.firstName()
+ },
+ lastName() {
+ return faker.name.lastName()
+ },
+ name() {
+ return faker.address.streetAddress()
+ },
+ phone() {
+ return faker.phone.number()
+ },
+ email() {
+ return faker.internet.email()
+ },
+ username() {
+ return faker.internet.userName()
+ },
+ avatar() {
+ return faker.internet.avatar()
+ },
+ })
+}
+
+export const seedLog = () => {
+ return Factory.extend<Partial<Log>>({
+ get key() {
+ return faker.datatype.uuid()
+ },
+ get conversationId() {
+ return faker.datatype.uuid()
+ },
+ get question() {
+ return faker.lorem.sentence()
+ },
+ get answer() {
+ return faker.lorem.sentence()
+ },
+ get userRate() {
+ return faker.datatype.number(5)
+ },
+ get adminRate() {
+ return faker.datatype.number(5)
+ }
+ })
+}
\ No newline at end of file
diff --git a/web/test/test_util.ts b/web/test/test_util.ts
new file mode 100644
index 00000000000..f8e293b0a73
--- /dev/null
+++ b/web/test/test_util.ts
@@ -0,0 +1,45 @@
+import { Model, createServer } from 'miragejs'
+import type { User } from '@/models/user'
+import type { History } from '@/models/history'
+import type { Log } from '@/models/log'
+import { seedUser, seedHistory, seedLog } from '@/test/factories'
+
+
+export function mockAPI() {
+ if (process.env.NODE_ENV === 'development') {
+ console.log('in development mode, starting mock server ... ')
+ const server = createServer({
+ environment: process.env.NODE_ENV,
+ factories: {
+ user: seedUser(),
+ history: seedHistory(),
+ log: seedLog(),
+ },
+ models: {
+ user: Model.extend<Partial<User>>({}),
+ history: Model.extend<Partial<History>>({}),
+ log: Model.extend<Partial<Log>>({}),
+ },
+ routes() {
+ this.namespace = '/api'
+ this.get('/users', () => {
+ return this.schema.all('user')
+ })
+ this.get('/histories', () => {
+ return this.schema.all('history')
+ })
+ this.get('/logs', () => {
+ return this.schema.all('log')
+ })
+ },
+ seeds(server) {
+ server.createList('user', 20)
+ server.createList('history', 50)
+ server.createList('log', 50)
+ },
+ })
+ return server
+ }
+ console.log('Not in development mode, not starting mock server ... ')
+ return null
+}
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 00000000000..c3e0bca665e
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,42 @@
+{
+ "compilerOptions": {
+ "target": "es2015",
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
+ "allowJs": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "forceConsistentCasingInFileNames": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "node",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "preserve",
+ "incremental": true,
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@/*": [
+ "./*"
+ ]
+ }
+ },
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ ".next/types/**/*.ts",
+ "app/components/develop/Prose.jsx"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
diff --git a/web/types/app.ts b/web/types/app.ts
new file mode 100644
index 00000000000..33ff1d5c670
--- /dev/null
+++ b/web/types/app.ts
@@ -0,0 +1,227 @@
+export enum AppType {
+ 'chat' = 'chat',
+ 'completion' = 'completion',
+}
+
+export type VariableInput = {
+ key: string
+ name: string
+ value: string
+}
+
+/**
+ * App modes
+ */
+export const AppModes = ['completion', 'chat'] as const
+export type AppMode = typeof AppModes[number]
+
+/**
+ * Variable type
+ */
+export const VariableTypes = ['string', 'number', 'select'] as const
+export type VariableType = typeof VariableTypes[number]
+
+/**
+ * Prompt variable parameter
+ */
+export type PromptVariable = {
+ /** Variable key */
+ key: string
+ /** Variable name */
+ name: string
+ /** Type */
+ type: VariableType
+ required: boolean
+ /** Enumeration of single-selection drop-down values */
+ options?: string[]
+ max_length?: number
+}
+
+export type TextTypeFormItem = {
+ label: string,
+ variable: string,
+ required: boolean
+ max_length: number
+}
+
+export type SelectTypeFormItem = {
+ label: string,
+ variable: string,
+ required: boolean,
+ options: string[]
+}
+/**
+ * User Input Form Item
+ */
+export type UserInputFormItem = {
+ 'text-input': TextTypeFormItem
+} | {
+ 'select': SelectTypeFormItem
+}
+
+
+export type ToolItem = {
+ dataset: {
+ enabled: boolean
+ id: string
+ }
+} | {
+ 'sensitive-word-avoidance': {
+ enabled: boolean
+ words: string[]
+ canned_response: string
+ }
+}
+
+/**
+ * Model configuration. The backend type.
+ */
+export type ModelConfig = {
+ opening_statement: string
+ pre_prompt: string
+ user_input_form: UserInputFormItem[]
+ more_like_this: {
+ enabled: boolean
+ }
+ suggested_questions_after_answer: {
+ enabled: boolean
+ }
+ agent_mode: {
+ enabled: boolean
+ tools: ToolItem[]
+ }
+ model: {
+ /** LLM provider, e.g., OPENAI */
+ provider: string
+ /** Model name, e.g, gpt-3.5.turbo */
+ name: string
+ /** Default Completion call parameters */
+ completion_params: {
+ /** Maximum number of tokens in the answer message returned by Completion */
+ max_tokens: number
+ /**
+ * A number between 0 and 2.
+ * The larger the number, the more random the result;
+ * otherwise, the more deterministic.
+ * When in use, choose either `temperature` or `top_p`.
+ * Default is 1.
+ */
+ temperature: number
+ /**
+ * Represents the proportion of probability mass samples to take,
+ * e.g., 0.1 means taking the top 10% probability mass samples.
+ * The determinism between the samples is basically consistent.
+ * Among these results, the `top_p` probability mass results are taken.
+ * When in use, choose either `temperature` or `top_p`.
+ * Default is 1.
+ */
+ top_p: number
+ /** When enabled, the Completion Text will concatenate the Prompt content together and return it. */
+ echo: boolean
+ /**
+ * Specify up to 4 to automatically stop generating before the text specified in `stop`.
+ * Suitable for use in chat mode.
+ * For example, specify "Q" and "A",
+ * and provide some Q&A examples as context,
+ * and the model will give out in Q&A format and stop generating before Q&A.
+ */
+ stop: string[]
+ /**
+ * A number between -2.0 and 2.0.
+ * The larger the value, the less the model will repeat topics and the more it will provide new topics.
+ */
+ presence_penalty: number
+ /**
+ * A number between -2.0 and 2.0.
+ * A lower setting will make the model appear less cultured,
+ * always repeating expressions.
+ * The difference between `frequency_penalty` and `presence_penalty`
+ * is that `frequency_penalty` penalizes a word based on its frequency in the training data,
+ * while `presence_penalty` penalizes a word based on its occurrence in the input text.
+ */
+ frequency_penalty: number
+ }
+ }
+}
+
+export const LanguagesSupported = ['zh-Hans', 'en-US'] as const
+export type Language = typeof LanguagesSupported[number]
+
+/**
+ * Web Application Configuration
+ */
+export type SiteConfig = {
+ /** Application URL Identifier: `http://dify.app/{access_token}` */
+ access_token: string
+ /** Public Title */
+ title: string
+ /** Application Description will be shown in the Client */
+ description: string
+ /** Author */
+ author: string
+ /** User Support Email Address */
+ support_email: string
+ /**
+ * Default Language, e.g. zh-Hans, en-US
+ * Use standard RFC 4646, see https://www.ruanyifeng.com/blog/2008/02/codes_for_language_names.html
+ */
+ default_language: Language
+ /** Custom Domain */
+ customize_domain: string
+ /** Theme */
+ theme: string
+ /** Custom Token strategy Whether Terminal Users can choose their OpenAI Key */
+ customize_token_strategy: 'must' | 'allow' | 'not_allow'
+ /** Is Prompt Public */
+ prompt_public: boolean
+ /** Web API and APP Base Domain Name */
+ app_base_url: string
+ /** Copyright */
+ copyright: string
+ /** Privacy Policy */
+ privacy_policy: string
+}
+
+/**
+ * App
+ */
+export type App = {
+ /** App ID */
+ id: string
+ /** Name */
+ name: string
+ /** Mode */
+ mode: AppMode
+ /** Enable web app */
+ enable_site: boolean
+ /** Enable web API */
+ enable_api: boolean
+ /** API requests per minute, default is 60 */
+ api_rpm: number
+ /** API requests per hour, default is 3600 */
+ api_rph: number
+ /** Whether it's a demo app */
+ is_demo: boolean
+ /** Model configuration */
+ model_config: ModelConfig
+ /** Timestamp of creation */
+ created_at: number
+ /** Web Application Configuration */
+ site: SiteConfig
+ /** api site url */
+ api_base_url: string
+}
+
+/**
+ * App Template
+ */
+export type AppTemplate = {
+ /** Name */
+ name: string
+ /** Description */
+ description: string
+ /** Mode */
+ mode: AppMode
+ /** Model */
+ model_config: ModelConfig
+}
diff --git a/web/typography.js b/web/typography.js
new file mode 100644
index 00000000000..706e456ddd1
--- /dev/null
+++ b/web/typography.js
@@ -0,0 +1,357 @@
+module.exports = ({ theme }) => ({
+ DEFAULT: {
+ css: {
+ '--tw-prose-body': theme('colors.zinc.700'),
+ '--tw-prose-headings': theme('colors.zinc.900'),
+ '--tw-prose-links': theme('colors.emerald.500'),
+ '--tw-prose-links-hover': theme('colors.emerald.600'),
+ '--tw-prose-links-underline': theme('colors.emerald.500 / 0.3'),
+ '--tw-prose-bold': theme('colors.zinc.900'),
+ '--tw-prose-counters': theme('colors.zinc.500'),
+ '--tw-prose-bullets': theme('colors.zinc.300'),
+ '--tw-prose-hr': theme('colors.zinc.900 / 0.05'),
+ '--tw-prose-quotes': theme('colors.zinc.900'),
+ '--tw-prose-quote-borders': theme('colors.zinc.200'),
+ '--tw-prose-captions': theme('colors.zinc.500'),
+ '--tw-prose-code': theme('colors.zinc.900'),
+ '--tw-prose-code-bg': theme('colors.zinc.100'),
+ '--tw-prose-code-ring': theme('colors.zinc.300'),
+ '--tw-prose-th-borders': theme('colors.zinc.300'),
+ '--tw-prose-td-borders': theme('colors.zinc.200'),
+
+ '--tw-prose-invert-body': theme('colors.zinc.400'),
+ '--tw-prose-invert-headings': theme('colors.white'),
+ '--tw-prose-invert-links': theme('colors.emerald.400'),
+ '--tw-prose-invert-links-hover': theme('colors.emerald.500'),
+ '--tw-prose-invert-links-underline': theme('colors.emerald.500 / 0.3'),
+ '--tw-prose-invert-bold': theme('colors.white'),
+ '--tw-prose-invert-counters': theme('colors.zinc.400'),
+ '--tw-prose-invert-bullets': theme('colors.zinc.600'),
+ '--tw-prose-invert-hr': theme('colors.white / 0.05'),
+ '--tw-prose-invert-quotes': theme('colors.zinc.100'),
+ '--tw-prose-invert-quote-borders': theme('colors.zinc.700'),
+ '--tw-prose-invert-captions': theme('colors.zinc.400'),
+ '--tw-prose-invert-code': theme('colors.white'),
+ '--tw-prose-invert-code-bg': theme('colors.zinc.700 / 0.15'),
+ '--tw-prose-invert-code-ring': theme('colors.white / 0.1'),
+ '--tw-prose-invert-th-borders': theme('colors.zinc.600'),
+ '--tw-prose-invert-td-borders': theme('colors.zinc.700'),
+
+ // Base
+ color: 'var(--tw-prose-body)',
+ fontSize: theme('fontSize.sm')[0],
+ lineHeight: theme('lineHeight.7'),
+
+ // Layout
+ '> *': {
+ maxWidth: theme('maxWidth.2xl'),
+ marginLeft: 'auto',
+ marginRight: 'auto',
+ '@screen lg': {
+ maxWidth: theme('maxWidth.3xl'),
+ marginLeft: `calc(50% - min(50%, ${theme('maxWidth.lg')}))`,
+ marginRight: `calc(50% - min(50%, ${theme('maxWidth.lg')}))`,
+ },
+ },
+
+ // Text
+ p: {
+ marginTop: theme('spacing.6'),
+ marginBottom: theme('spacing.6'),
+ },
+ '[class~="lead"]': {
+ fontSize: theme('fontSize.base')[0],
+ ...theme('fontSize.base')[1],
+ },
+
+ // Lists
+ ol: {
+ listStyleType: 'decimal',
+ marginTop: theme('spacing.5'),
+ marginBottom: theme('spacing.5'),
+ paddingLeft: '1.625rem',
+ },
+ 'ol[type="A"]': {
+ listStyleType: 'upper-alpha',
+ },
+ 'ol[type="a"]': {
+ listStyleType: 'lower-alpha',
+ },
+ 'ol[type="A" s]': {
+ listStyleType: 'upper-alpha',
+ },
+ 'ol[type="a" s]': {
+ listStyleType: 'lower-alpha',
+ },
+ 'ol[type="I"]': {
+ listStyleType: 'upper-roman',
+ },
+ 'ol[type="i"]': {
+ listStyleType: 'lower-roman',
+ },
+ 'ol[type="I" s]': {
+ listStyleType: 'upper-roman',
+ },
+ 'ol[type="i" s]': {
+ listStyleType: 'lower-roman',
+ },
+ 'ol[type="1"]': {
+ listStyleType: 'decimal',
+ },
+ ul: {
+ listStyleType: 'disc',
+ marginTop: theme('spacing.5'),
+ marginBottom: theme('spacing.5'),
+ paddingLeft: '1.625rem',
+ },
+ li: {
+ marginTop: theme('spacing.2'),
+ marginBottom: theme('spacing.2'),
+ },
+ ':is(ol, ul) > li': {
+ paddingLeft: theme('spacing[1.5]'),
+ },
+ 'ol > li::marker': {
+ fontWeight: '400',
+ color: 'var(--tw-prose-counters)',
+ },
+ 'ul > li::marker': {
+ color: 'var(--tw-prose-bullets)',
+ },
+ '> ul > li p': {
+ marginTop: theme('spacing.3'),
+ marginBottom: theme('spacing.3'),
+ },
+ '> ul > li > *:first-child': {
+ marginTop: theme('spacing.5'),
+ },
+ '> ul > li > *:last-child': {
+ marginBottom: theme('spacing.5'),
+ },
+ '> ol > li > *:first-child': {
+ marginTop: theme('spacing.5'),
+ },
+ '> ol > li > *:last-child': {
+ marginBottom: theme('spacing.5'),
+ },
+ 'ul ul, ul ol, ol ul, ol ol': {
+ marginTop: theme('spacing.3'),
+ marginBottom: theme('spacing.3'),
+ },
+
+ // Horizontal rules
+ hr: {
+ borderColor: 'var(--tw-prose-hr)',
+ borderTopWidth: 1,
+ marginTop: theme('spacing.16'),
+ marginBottom: theme('spacing.16'),
+ maxWidth: 'none',
+ marginLeft: `calc(-1 * ${theme('spacing.4')})`,
+ marginRight: `calc(-1 * ${theme('spacing.4')})`,
+ '@screen sm': {
+ marginLeft: `calc(-1 * ${theme('spacing.6')})`,
+ marginRight: `calc(-1 * ${theme('spacing.6')})`,
+ },
+ '@screen lg': {
+ marginLeft: `calc(-1 * ${theme('spacing.8')})`,
+ marginRight: `calc(-1 * ${theme('spacing.8')})`,
+ },
+ },
+
+ // Quotes
+ blockquote: {
+ fontWeight: '500',
+ fontStyle: 'italic',
+ color: 'var(--tw-prose-quotes)',
+ borderLeftWidth: '0.25rem',
+ borderLeftColor: 'var(--tw-prose-quote-borders)',
+ quotes: '"\\201C""\\201D""\\2018""\\2019"',
+ marginTop: theme('spacing.8'),
+ marginBottom: theme('spacing.8'),
+ paddingLeft: theme('spacing.5'),
+ },
+ 'blockquote p:first-of-type::before': {
+ content: 'open-quote',
+ },
+ 'blockquote p:last-of-type::after': {
+ content: 'close-quote',
+ },
+
+ // Headings
+ h1: {
+ color: 'var(--tw-prose-headings)',
+ fontWeight: '700',
+ fontSize: theme('fontSize.2xl')[0],
+ ...theme('fontSize.2xl')[1],
+ marginBottom: theme('spacing.2'),
+ },
+ h2: {
+ color: 'var(--tw-prose-headings)',
+ fontWeight: '600',
+ fontSize: theme('fontSize.lg')[0],
+ ...theme('fontSize.lg')[1],
+ marginTop: theme('spacing.16'),
+ marginBottom: theme('spacing.2'),
+ },
+ h3: {
+ color: 'var(--tw-prose-headings)',
+ fontSize: theme('fontSize.base')[0],
+ ...theme('fontSize.base')[1],
+ fontWeight: '600',
+ marginTop: theme('spacing.10'),
+ marginBottom: theme('spacing.2'),
+ },
+
+ // Media
+ 'img, video, figure': {
+ marginTop: theme('spacing.8'),
+ marginBottom: theme('spacing.8'),
+ },
+ 'figure > *': {
+ marginTop: '0',
+ marginBottom: '0',
+ },
+ figcaption: {
+ color: 'var(--tw-prose-captions)',
+ fontSize: theme('fontSize.xs')[0],
+ ...theme('fontSize.xs')[1],
+ marginTop: theme('spacing.2'),
+ },
+
+ // Tables
+ table: {
+ width: '100%',
+ tableLayout: 'auto',
+ textAlign: 'left',
+ marginTop: theme('spacing.8'),
+ marginBottom: theme('spacing.8'),
+ lineHeight: theme('lineHeight.6'),
+ },
+ thead: {
+ borderBottomWidth: '1px',
+ borderBottomColor: 'var(--tw-prose-th-borders)',
+ },
+ 'thead th': {
+ color: 'var(--tw-prose-headings)',
+ fontWeight: '600',
+ verticalAlign: 'bottom',
+ paddingRight: theme('spacing.2'),
+ paddingBottom: theme('spacing.2'),
+ paddingLeft: theme('spacing.2'),
+ },
+ 'thead th:first-child': {
+ paddingLeft: '0',
+ },
+ 'thead th:last-child': {
+ paddingRight: '0',
+ },
+ 'tbody tr': {
+ borderBottomWidth: '1px',
+ borderBottomColor: 'var(--tw-prose-td-borders)',
+ },
+ 'tbody tr:last-child': {
+ borderBottomWidth: '0',
+ },
+ 'tbody td': {
+ verticalAlign: 'baseline',
+ },
+ tfoot: {
+ borderTopWidth: '1px',
+ borderTopColor: 'var(--tw-prose-th-borders)',
+ },
+ 'tfoot td': {
+ verticalAlign: 'top',
+ },
+ ':is(tbody, tfoot) td': {
+ paddingTop: theme('spacing.2'),
+ paddingRight: theme('spacing.2'),
+ paddingBottom: theme('spacing.2'),
+ paddingLeft: theme('spacing.2'),
+ },
+ ':is(tbody, tfoot) td:first-child': {
+ paddingLeft: '0',
+ },
+ ':is(tbody, tfoot) td:last-child': {
+ paddingRight: '0',
+ },
+
+ // Inline elements
+ a: {
+ color: 'var(--tw-prose-links)',
+ textDecoration: 'underline transparent',
+ fontWeight: '500',
+ transitionProperty: 'color, text-decoration-color',
+ transitionDuration: theme('transitionDuration.DEFAULT'),
+ transitionTimingFunction: theme('transitionTimingFunction.DEFAULT'),
+ '&:hover': {
+ color: 'var(--tw-prose-links-hover)',
+ textDecorationColor: 'var(--tw-prose-links-underline)',
+ },
+ },
+ ':is(h1, h2, h3) a': {
+ fontWeight: 'inherit',
+ },
+ strong: {
+ color: 'var(--tw-prose-bold)',
+ fontWeight: '600',
+ },
+ ':is(a, blockquote, thead th) strong': {
+ color: 'inherit',
+ },
+ code: {
+ color: 'var(--tw-prose-code)',
+ borderRadius: theme('borderRadius.lg'),
+ paddingTop: theme('padding.1'),
+ paddingRight: theme('padding[1.5]'),
+ paddingBottom: theme('padding.1'),
+ paddingLeft: theme('padding[1.5]'),
+ boxShadow: 'inset 0 0 0 1px var(--tw-prose-code-ring)',
+ backgroundColor: 'var(--tw-prose-code-bg)',
+ fontSize: theme('fontSize.2xs'),
+ },
+ ':is(a, h1, h2, h3, blockquote, thead th) code': {
+ color: 'inherit',
+ },
+ 'h2 code': {
+ fontSize: theme('fontSize.base')[0],
+ fontWeight: 'inherit',
+ },
+ 'h3 code': {
+ fontSize: theme('fontSize.sm')[0],
+ fontWeight: 'inherit',
+ },
+
+ // Overrides
+ ':is(h1, h2, h3) + *': {
+ marginTop: '0',
+ },
+ '> :first-child': {
+ marginTop: '0 !important',
+ },
+ '> :last-child': {
+ marginBottom: '0 !important',
+ },
+ },
+ },
+ invert: {
+ css: {
+ '--tw-prose-body': 'var(--tw-prose-invert-body)',
+ '--tw-prose-headings': 'var(--tw-prose-invert-headings)',
+ '--tw-prose-links': 'var(--tw-prose-invert-links)',
+ '--tw-prose-links-hover': 'var(--tw-prose-invert-links-hover)',
+ '--tw-prose-links-underline': 'var(--tw-prose-invert-links-underline)',
+ '--tw-prose-bold': 'var(--tw-prose-invert-bold)',
+ '--tw-prose-counters': 'var(--tw-prose-invert-counters)',
+ '--tw-prose-bullets': 'var(--tw-prose-invert-bullets)',
+ '--tw-prose-hr': 'var(--tw-prose-invert-hr)',
+ '--tw-prose-quotes': 'var(--tw-prose-invert-quotes)',
+ '--tw-prose-quote-borders': 'var(--tw-prose-invert-quote-borders)',
+ '--tw-prose-captions': 'var(--tw-prose-invert-captions)',
+ '--tw-prose-code': 'var(--tw-prose-invert-code)',
+ '--tw-prose-code-bg': 'var(--tw-prose-invert-code-bg)',
+ '--tw-prose-code-ring': 'var(--tw-prose-invert-code-ring)',
+ '--tw-prose-th-borders': 'var(--tw-prose-invert-th-borders)',
+ '--tw-prose-td-borders': 'var(--tw-prose-invert-td-borders)',
+ },
+ },
+})
diff --git a/web/utils/format.ts b/web/utils/format.ts
new file mode 100644
index 00000000000..fc30c623693
--- /dev/null
+++ b/web/utils/format.ts
@@ -0,0 +1,33 @@
+/*
+* Formats a number with comma separators.
+ formatNumber(1234567) will return '1,234,567'
+ formatNumber(1234567.89) will return '1,234,567.89'
+*/
+export const formatNumber = (num: number | string) => {
+ if (!num) return num;
+ let parts = num.toString().split(".");
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
+ return parts.join(".");
+}
+
+export const formatFileSize = (num: number) => {
+ if (!num) return num;
+ const units = ['', 'K', 'M', 'G', 'T', 'P'];
+ let index = 0;
+ while (num >= 1024 && index < units.length) {
+ num = num / 1024;
+ index++;
+ }
+ return num.toFixed(2) + `${units[index]}B`;
+}
+
+export const formatTime = (num: number) => {
+ if (!num) return num;
+ const units = ['sec', 'min', 'h'];
+ let index = 0;
+ while (num >= 60 && index < units.length) {
+ num = num / 60;
+ index++;
+ }
+ return `${num.toFixed(2)} ${units[index]}`;
+}
diff --git a/web/utils/index.ts b/web/utils/index.ts
new file mode 100644
index 00000000000..9965165dcf1
--- /dev/null
+++ b/web/utils/index.ts
@@ -0,0 +1,24 @@
+export const sleep = (ms: number) => {
+ return new Promise(resolve => setTimeout(resolve, ms))
+}
+
+export async function asyncRunSafe<T = any>(fn: Promise<T>): Promise<[Error] | [null, T]> {
+ try {
+ return [null, await fn]
+ }
+ catch (e) {
+ if (e instanceof Error)
+ return [e]
+ return [new Error('unknown error')]
+ }
+}
+
+export const getTextWidthWithCanvas = (text: string, font?: string) => {
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
+ if (ctx) {
+ ctx.font = font ?? '12px Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"';
+ return Number(ctx.measureText(text).width.toFixed(2));
+ }
+ return 0;
+}
diff --git a/web/utils/language.ts b/web/utils/language.ts
new file mode 100644
index 00000000000..c24c1267c4e
--- /dev/null
+++ b/web/utils/language.ts
@@ -0,0 +1,19 @@
+type Item = {
+ value: number | string
+ name: string
+}
+export const languages: Item[] = [
+ {
+ value: 'en-US',
+ name: 'English(United States)',
+ },
+ {
+ value: 'zh-Hans',
+ name: '简体中文',
+ },
+]
+
+export const languageMaps = {
+ 'en': 'en-US',
+ 'zh-Hans': 'zh-Hans',
+}
diff --git a/web/utils/model-config.ts b/web/utils/model-config.ts
new file mode 100644
index 00000000000..1c7594b9fe5
--- /dev/null
+++ b/web/utils/model-config.ts
@@ -0,0 +1,63 @@
+import { UserInputFormItem, } from '@/types/app'
+import { PromptVariable } from '@/models/debug'
+
+export const userInputsFormToPromptVariables = (useInputs: UserInputFormItem[] | null) => {
+ if (!useInputs) return []
+ const promptVariables: PromptVariable[] = []
+ useInputs.forEach((item: any) => {
+ const type = item['text-input'] ? 'string' : 'select'
+ const content = type === 'string' ? item['text-input'] : item['select']
+ if (type === 'string') {
+ promptVariables.push({
+ key: content.variable,
+ name: content.label,
+ required: content.required,
+ type: 'string',
+ max_length: content.max_length,
+ options: [],
+ })
+ } else {
+ promptVariables.push({
+ key: content.variable,
+ name: content.label,
+ required: content.required,
+ type: 'select',
+ options: content.options,
+ })
+ }
+ })
+ return promptVariables
+}
+
+export const promptVariablesToUserInputsForm = (promptVariables: PromptVariable[]) => {
+ const userInputs: UserInputFormItem[] = []
+ promptVariables.filter(({ key, name }) => {
+ if (key && key.trim() && name && name.trim()) {
+ return true
+ }
+ return false
+ }).forEach((item: any) => {
+ if (item.type === 'string') {
+ userInputs.push({
+ 'text-input': {
+ label: item.name,
+ variable: item.key,
+ required: item.required === false ? false : true, // default true
+ max_length: item.max_length,
+ default: ''
+ },
+ } as any)
+ } else {
+ userInputs.push({
+ 'select': {
+ label: item.name,
+ variable: item.key,
+ required: item.required === false ? false : true, // default true
+ options: item.options,
+ default: ''
+ },
+ } as any)
+ }
+ })
+ return userInputs
+}
diff --git a/web/utils/timezone.ts b/web/utils/timezone.ts
new file mode 100644
index 00000000000..b408008db37
--- /dev/null
+++ b/web/utils/timezone.ts
@@ -0,0 +1,330 @@
+type Item = {
+ value: number | string
+ name: string
+}
+export const timezones: Item[] = [
+ {
+ value: 'Pacific/Midway',
+ name: '(GMT-11:00) Midway Island, Samoa',
+ },
+ {
+ value: 'Pacific/Honolulu',
+ name: '(GMT-10:00) Hawaii',
+ },
+ {
+ value: 'America/Juneau',
+ name: '(GMT-8:00) Alaska',
+ },
+ {
+ value: 'America/Dawson',
+ name: '(GMT-7:00) Dawson, Yukon',
+ },
+ {
+ value: 'America/Chihuahua',
+ name: '(GMT-7:00) Chihuahua, La Paz, Mazatlan',
+ },
+ {
+ value: 'America/Phoenix',
+ name: '(GMT-7:00) Arizona',
+ },
+ {
+ value: 'America/Tijuana',
+ name: '(GMT-7:00) Tijuana',
+ },
+ {
+ value: 'America/Los_Angeles',
+ name: '(GMT-7:00) Pacific Time',
+ },
+ {
+ value: 'America/Boise',
+ name: '(GMT-6:00) Mountain Time',
+ },
+ {
+ value: 'America/Regina',
+ name: '(GMT-6:00) Saskatchewan',
+ },
+ {
+ value: 'America/Mexico_City',
+ name: '(GMT-6:00) Guadalajara, Mexico City, Monterrey',
+ },
+ {
+ value: 'America/Belize',
+ name: '(GMT-6:00) Central America',
+ },
+ {
+ value: 'America/Chicago',
+ name: '(GMT-5:00) Central Time',
+ },
+ {
+ value: 'America/Bogota',
+ name: '(GMT-5:00) Bogota, Lima, Quito',
+ },
+ {
+ value: 'America/Lima',
+ name: '(GMT-5:00) Pittsburgh',
+ },
+ {
+ value: 'America/Detroit',
+ name: '(GMT-4:00) Eastern Time',
+ },
+ {
+ value: 'America/Caracas',
+ name: '(GMT-4:00) Caracas, La Paz',
+ },
+ {
+ value: 'America/Santiago',
+ name: '(GMT-3:00) Santiago',
+ },
+ {
+ value: 'America/Sao_Paulo',
+ name: '(GMT-3:00) Brasilia',
+ },
+ {
+ value: 'America/Montevideo',
+ name: '(GMT-3:00) Montevideo',
+ },
+ {
+ value: 'America/Argentina/Buenos_Aires',
+ name: '(GMT-3:00) Buenos Aires, Georgetown',
+ },
+ {
+ value: 'America/St_Johns',
+ name: '(GMT-2:30) Newfoundland and Labrador',
+ },
+ {
+ value: 'America/Godthab',
+ name: '(GMT-2:00) Greenland',
+ },
+ {
+ value: 'Atlantic/Cape_Verde',
+ name: '(GMT-1:00) Cape Verde Islands',
+ },
+ {
+ value: 'Atlantic/Azores',
+ name: '(GMT+0:00) Azores',
+ },
+ {
+ value: 'Etc/GMT',
+ name: '(GMT+0:00) UTC',
+ },
+ {
+ value: 'Africa/Casablanca',
+ name: '(GMT+0:00) Casablanca, Monrovia',
+ },
+ {
+ value: 'Europe/London',
+ name: '(GMT+1:00) Edinburgh, London',
+ },
+ {
+ value: 'Europe/Dublin',
+ name: '(GMT+1:00) Dublin',
+ },
+ {
+ value: 'Europe/Lisbon',
+ name: '(GMT+1:00) Lisbon',
+ },
+ {
+ value: 'Atlantic/Canary',
+ name: '(GMT+1:00) Canary Islands',
+ },
+ {
+ value: 'Africa/Algiers',
+ name: '(GMT+1:00) West Central Africa',
+ },
+ {
+ value: 'Europe/Belgrade',
+ name: '(GMT+2:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
+ },
+ {
+ value: 'Europe/Sarajevo',
+ name: '(GMT+2:00) Sarajevo, Skopje, Warsaw, Zagreb',
+ },
+ {
+ value: 'Europe/Brussels',
+ name: '(GMT+2:00) Brussels, Copenhagen, Madrid, Paris',
+ },
+ {
+ value: 'Europe/Amsterdam',
+ name: '(GMT+2:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
+ },
+ {
+ value: 'Africa/Cairo',
+ name: '(GMT+2:00) Cairo',
+ },
+ {
+ value: 'Africa/Harare',
+ name: '(GMT+2:00) Harare, Pretoria',
+ },
+ {
+ value: 'Europe/Berlin',
+ name: '(GMT+2:00) Frankfurt',
+ },
+ {
+ value: 'Europe/Bucharest',
+ name: '(GMT+3:00) Bucharest',
+ },
+ {
+ value: 'Europe/Helsinki',
+ name: '(GMT+3:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius',
+ },
+ {
+ value: 'Europe/Athens',
+ name: '(GMT+3:00) Athens, Minsk',
+ },
+ {
+ value: 'Asia/Jerusalem',
+ name: '(GMT+3:00) Jerusalem',
+ },
+ {
+ value: 'Europe/Moscow',
+ name: '(GMT+3:00) Istanbul, Moscow, St. Petersburg, Volgograd',
+ },
+ {
+ value: 'Asia/Kuwait',
+ name: '(GMT+3:00) Kuwait, Riyadh',
+ },
+ {
+ value: 'Africa/Nairobi',
+ name: '(GMT+3:00) Nairobi',
+ },
+ {
+ value: 'Asia/Baghdad',
+ name: '(GMT+3:00) Baghdad',
+ },
+ {
+ value: 'Asia/Dubai',
+ name: '(GMT+4:00) Abu Dhabi, Muscat',
+ },
+ {
+ value: 'Asia/Tehran',
+ name: '(GMT+4:30) Tehran',
+ },
+ {
+ value: 'Asia/Kabul',
+ name: '(GMT+4:30) Kabul',
+ },
+ {
+ value: 'Asia/Baku',
+ name: '(GMT+5:00) Baku, Tbilisi, Yerevan',
+ },
+ {
+ value: 'Asia/Yekaterinburg',
+ name: '(GMT+5:00) Ekaterinburg',
+ },
+ {
+ value: 'Asia/Karachi',
+ name: '(GMT+5:00) Islamabad, Karachi, Tashkent',
+ },
+ {
+ value: 'Asia/Kolkata',
+ name: '(GMT+5:30) Chennai, Kolkata, Mumbai, New Delhi',
+ },
+ {
+ value: 'Asia/Colombo',
+ name: '(GMT+5:30) Sri Jayawardenepura',
+ },
+ {
+ value: 'Asia/Kathmandu',
+ name: '(GMT+5:45) Kathmandu',
+ },
+ {
+ value: 'Asia/Dhaka',
+ name: '(GMT+6:00) Astana, Dhaka',
+ },
+ {
+ value: 'Asia/Almaty',
+ name: '(GMT+6:00) Almaty, Novosibirsk',
+ },
+ {
+ value: 'Asia/Rangoon',
+ name: '(GMT+6:30) Yangon Rangoon',
+ },
+ {
+ value: 'Asia/Bangkok',
+ name: '(GMT+7:00) Bangkok, Hanoi, Jakarta',
+ },
+ {
+ value: 'Asia/Krasnoyarsk',
+ name: '(GMT+7:00) Krasnoyarsk',
+ },
+ {
+ value: 'Asia/Shanghai',
+ name: '(GMT+8:00) Beijing, Chongqing, Hong Kong SAR, Urumqi',
+ },
+ {
+ value: 'Asia/Kuala_Lumpur',
+ name: '(GMT+8:00) Kuala Lumpur, Singapore',
+ },
+ {
+ value: 'Asia/Taipei',
+ name: '(GMT+8:00) Taipei',
+ },
+ {
+ value: 'Australia/Perth',
+ name: '(GMT+8:00) Perth',
+ },
+ {
+ value: 'Asia/Irkutsk',
+ name: '(GMT+8:00) Irkutsk, Ulaanbaatar',
+ },
+ {
+ value: 'Asia/Seoul',
+ name: '(GMT+9:00) Seoul',
+ },
+ {
+ value: 'Asia/Tokyo',
+ name: '(GMT+9:00) Osaka, Sapporo, Tokyo',
+ },
+ {
+ value: 'Australia/Darwin',
+ name: '(GMT+9:30) Darwin',
+ },
+ {
+ value: 'Asia/Yakutsk',
+ name: '(GMT+10:00) Yakutsk',
+ },
+ {
+ value: 'Australia/Brisbane',
+ name: '(GMT+10:00) Brisbane',
+ },
+ {
+ value: 'Asia/Vladivostok',
+ name: '(GMT+10:00) Vladivostok',
+ },
+ {
+ value: 'Pacific/Guam',
+ name: '(GMT+10:00) Guam, Port Moresby',
+ },
+ {
+ value: 'Australia/Adelaide',
+ name: '(GMT+10:30) Adelaide',
+ },
+ {
+ value: 'Australia/Sydney',
+ name: '(GMT+11:00) Canberra, Melbourne, Sydney',
+ },
+ {
+ value: 'Australia/Hobart',
+ name: '(GMT+11:00) Hobart',
+ },
+ {
+ value: 'Asia/Magadan',
+ name: '(GMT+11:00) Magadan, Solomon Islands, New Caledonia',
+ },
+ {
+ value: 'Asia/Kamchatka',
+ name: '(GMT+12:00) Kamchatka, Marshall Islands',
+ },
+ {
+ value: 'Pacific/Fiji',
+ name: '(GMT+12:00) Fiji Islands',
+ },
+ {
+ value: 'Pacific/Auckland',
+ name: '(GMT+13:00) Auckland, Wellington',
+ },
+ {
+ value: 'Pacific/Tongatapu',
+ name: '(GMT+13:00) Nuku\'alofa',
+ },
+]
diff --git a/web/utils/var.ts b/web/utils/var.ts
new file mode 100644
index 00000000000..44e2a7b93ed
--- /dev/null
+++ b/web/utils/var.ts
@@ -0,0 +1,47 @@
+import { VAR_ITEM_TEMPLATE, getMaxVarNameLength, zhRegex, emojiRegex, MAX_VAR_KEY_LENGHT } from "@/config"
+const otherAllowedRegex = new RegExp(`^[a-zA-Z0-9_]+$`)
+
+export const getNewVar = (key: string) => {
+ return {
+ ...VAR_ITEM_TEMPLATE,
+ key,
+ name: key.slice(0, getMaxVarNameLength(key)),
+ }
+}
+
+const checkKey = (key: string, canBeEmpty?: boolean) => {
+ if (key.length === 0 && !canBeEmpty) {
+ return 'canNoBeEmpty'
+ }
+ if (canBeEmpty && key === '') {
+ return true
+ }
+ if (key.length > MAX_VAR_KEY_LENGHT) {
+ return 'tooLong'
+ }
+ if (otherAllowedRegex.test(key)) {
+ if (/[0-9]/.test(key[0])) {
+ return 'notStartWithNumber'
+ }
+ return true
+ }
+ return 'notValid'
+}
+
+export const checkKeys = (keys: string[], canBeEmpty?: boolean) => {
+ let isValid = true
+ let errorKey = ''
+ let errorMessageKey = ''
+ keys.forEach((key) => {
+ if (!isValid) {
+ return
+ }
+ const res = checkKey(key, canBeEmpty)
+ if (res !== true) {
+ isValid = false
+ errorKey = key
+ errorMessageKey = res
+ }
+ })
+ return { isValid, errorKey, errorMessageKey }
+}
\ No newline at end of file