-
-
@@ -941,26 +931,6 @@ const imageUpload = ref(null);
// Embedding 维度检测状态
const embeddingDimDetecting = ref(false);
-// 左侧导航区段
-type Section = { id: string; label: string };
-const sections: Section[] = [
- { id: 'ollama', label: 'Ollama 服务' },
- { id: 'llm', label: 'LLM 模型' },
- { id: 'embedding', label: 'Embedding 模型' },
- { id: 'rerank', label: 'Rerank 配置' },
- { id: 'multimodal', label: '多模态配置' },
- { id: 'docsplit', label: '文档分割' },
- { id: 'submit', label: '完成配置' },
-];
-
-const activeSectionId = ref
('ollama');
-const goToSection = (id: string) => {
- const el = document.getElementById(`section-${id}`);
- if (el) {
- el.scrollIntoView({ behavior: 'smooth', block: 'start' });
- activeSectionId.value = id;
- }
-};
// 退出登录
const handleLogout = () => {
@@ -968,19 +938,6 @@ const handleLogout = () => {
router.replace('/login');
};
-// 监听滚动,高亮当前区块
-const onScroll = () => {
- const order = ['ollama','llm','embedding','rerank','multimodal','docsplit','submit'];
- for (const id of order) {
- const el = document.getElementById(`section-${id}`);
- if (!el) continue;
- const rect = el.getBoundingClientRect();
- if (rect.top <= 120 && rect.bottom >= 120) {
- activeSectionId.value = id;
- break;
- }
- }
-};
// 配置回填
const loadCurrentConfig = async () => {
@@ -1004,8 +961,8 @@ const loadCurrentConfig = async () => {
if (config.rerank) {
Object.assign(formData.rerank, config.rerank);
}
- formData.storageType = config.multimodal.storageType;
if (config.multimodal) {
+ formData.storageType = config.multimodal.storageType || 'minio';
formData.multimodal.enabled = config.multimodal.enabled || false;
if (config.multimodal.vlm) {
Object.assign(formData.multimodal.vlm, config.multimodal.vlm);
@@ -1014,11 +971,14 @@ const loadCurrentConfig = async () => {
formData.multimodal.vlm.interfaceType = 'ollama';
}
}
- if (config.multimodal.storageType === 'cos') {
+ if (config.multimodal.storageType === 'cos' && config.multimodal.cos) {
Object.assign(formData.multimodal.cos, config.multimodal.cos);
- } else if (config.multimodal.storageType === 'minio') {
+ } else if (config.multimodal.storageType === 'minio' && config.multimodal.minio) {
Object.assign(formData.multimodal.minio, config.multimodal.minio);
}
+ } else {
+ // 如果没有多模态配置,设置默认存储类型
+ formData.storageType = 'minio';
}
if (config.documentSplitting) {
Object.assign(formData.documentSplitting, config.documentSplitting);
@@ -1351,8 +1311,6 @@ onUnmounted(() => {
clearTimeout(submitDebounceTimer.value);
submitDebounceTimer.value = null;
}
-
- window.removeEventListener('scroll', onScroll);
});
// 事件处理
@@ -1740,6 +1698,23 @@ const handleSubmit = async () => {
// 调用初始化API
const payload: any = JSON.parse(JSON.stringify(formData));
+
+ // 确保存储类型在正确的位置,并只保留选中的存储配置
+ if (payload.multimodal && payload.storageType) {
+ payload.multimodal.storageType = payload.storageType;
+
+ // 根据选择的存储类型,只保留对应的配置,删除其他存储配置
+ if (payload.storageType === 'cos') {
+ // 保留COS配置,删除MinIO配置
+ delete payload.multimodal.minio;
+ } else if (payload.storageType === 'minio') {
+ // 保留MinIO配置,删除COS配置
+ delete payload.multimodal.cos;
+ }
+
+ delete payload.storageType; // 删除顶级的storageType字段
+ }
+
await initializeSystem(payload);
const successMessage = isUpdateMode.value ? '配置更新成功!' : '系统初始化成功!';
@@ -1777,9 +1752,6 @@ onMounted(async () => {
// 检查已配置模型状态
await checkAllConfiguredModels();
-
- // 绑定滚动监听,用于左侧导航高亮
- window.addEventListener('scroll', onScroll, { passive: true });
});
const onRerankChange = () => {
@@ -2347,144 +2319,75 @@ const detectEmbeddingDimension = async () => {
diff --git a/frontend/src/views/settings/SystemSettings.vue b/frontend/src/views/settings/SystemSettings.vue
new file mode 100644
index 00000000..730b3d04
--- /dev/null
+++ b/frontend/src/views/settings/SystemSettings.vue
@@ -0,0 +1,125 @@
+
+
+
+
+
+
+
diff --git a/frontend/src/views/tenant/TenantInfo.vue b/frontend/src/views/tenant/TenantInfo.vue
index 6379b154..1890cb26 100644
--- a/frontend/src/views/tenant/TenantInfo.vue
+++ b/frontend/src/views/tenant/TenantInfo.vue
@@ -311,11 +311,11 @@ onMounted(() => {
.tenant-info-container {
padding: 20px;
background-color: #fff;
- border-radius: 8px;
- margin: 0 20px 20px 20px;
- height: calc(100vh - 40px);
+ margin: 0 20px 0 20px;
+ height: calc(100vh);
overflow-y: auto;
box-sizing: border-box;
+ flex: 1;
}
.tenant-header {
@@ -363,7 +363,7 @@ onMounted(() => {
.api-key-content,
.storage-content,
.doc-content {
-// padding: 16px 0;
+ margin-top: 0;
}
.api-key-input {
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go
index 07078a40..b74fd558 100644
--- a/internal/handler/initialization.go
+++ b/internal/handler/initialization.go
@@ -83,9 +83,7 @@ func NewInitializationHandler(
// InitializationRequest 初始化请求结构
type InitializationRequest struct {
- // 前端传入的存储类型:cos 或 minio
- StorageType string `json:"storageType"`
- LLM struct {
+ LLM struct {
Source string `json:"source" binding:"required"`
ModelName string `json:"modelName" binding:"required"`
BaseURL string `json:"baseUrl"`
@@ -115,7 +113,8 @@ type InitializationRequest struct {
APIKey string `json:"apiKey"`
InterfaceType string `json:"interfaceType"` // "ollama" or "openai"
} `json:"vlm,omitempty"`
- COS *struct {
+ StorageType string `json:"storageType"`
+ COS *struct {
SecretID string `json:"secretId"`
SecretKey string `json:"secretKey"`
Region string `json:"region"`
@@ -210,7 +209,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
// 验证多模态配置
if req.Multimodal.Enabled {
- storageType := strings.ToLower(req.StorageType)
+ storageType := strings.ToLower(req.Multimodal.StorageType)
if req.Multimodal.VLM == nil {
logger.Error(ctx, "Multimodal enabled but missing VLM configuration")
c.Error(errors.NewBadRequestError("启用多模态时需要配置VLM信息"))
@@ -502,11 +501,11 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
InterfaceType: req.Multimodal.VLM.InterfaceType,
},
}
- switch req.StorageType {
+ switch req.Multimodal.StorageType {
case "cos":
if req.Multimodal.COS != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.COS.BucketName,
AppID: req.Multimodal.COS.AppID,
PathPrefix: req.Multimodal.COS.PathPrefix,
@@ -518,7 +517,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
case "minio":
if req.Multimodal.Minio != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.Minio.BucketName,
PathPrefix: req.Multimodal.Minio.PathPrefix,
SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
@@ -560,11 +559,11 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
APIKey: req.Multimodal.VLM.APIKey,
InterfaceType: req.Multimodal.VLM.InterfaceType,
}
- switch req.StorageType {
+ switch req.Multimodal.StorageType {
case "cos":
if req.Multimodal.COS != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
SecretID: req.Multimodal.COS.SecretID,
SecretKey: req.Multimodal.COS.SecretKey,
Region: req.Multimodal.COS.Region,
@@ -576,7 +575,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
case "minio":
if req.Multimodal.Minio != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.Minio.BucketName,
PathPrefix: req.Multimodal.Minio.PathPrefix,
SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
From 66aec78960797c91aee252a65a9aadef40f5a25d Mon Sep 17 00:00:00 2001
From: wizardchen
Date: Tue, 16 Sep 2025 20:18:47 +0800
Subject: [PATCH 08/39] chore(ui): Update Setting page
---
frontend/src/api/initialization/index.ts | 1 +
frontend/src/assets/img/user-green.svg | 4 +
frontend/src/assets/img/user.svg | 4 +
frontend/src/components/menu.vue | 9 +-
frontend/src/router/index.ts | 6 +-
.../initialization/InitializationConfig.vue | 306 +-
.../initialization/InitializationContent.vue | 2712 +++++++++++++++++
.../src/views/settings/SystemSettings.vue | 125 +
frontend/src/views/tenant/TenantInfo.vue | 8 +-
internal/handler/initialization.go | 21 +-
10 files changed, 2944 insertions(+), 252 deletions(-)
create mode 100644 frontend/src/assets/img/user-green.svg
create mode 100644 frontend/src/assets/img/user.svg
create mode 100644 frontend/src/views/initialization/InitializationContent.vue
create mode 100644 frontend/src/views/settings/SystemSettings.vue
diff --git a/frontend/src/api/initialization/index.ts b/frontend/src/api/initialization/index.ts
index 66591c79..c42f1483 100644
--- a/frontend/src/api/initialization/index.ts
+++ b/frontend/src/api/initialization/index.ts
@@ -19,6 +19,7 @@ export interface InitializationConfig {
modelName: string;
baseUrl: string;
apiKey?: string;
+ enabled: boolean;
};
multimodal: {
enabled: boolean;
diff --git a/frontend/src/assets/img/user-green.svg b/frontend/src/assets/img/user-green.svg
new file mode 100644
index 00000000..6685b1b6
--- /dev/null
+++ b/frontend/src/assets/img/user-green.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/frontend/src/assets/img/user.svg b/frontend/src/assets/img/user.svg
new file mode 100644
index 00000000..1e26d1ed
--- /dev/null
+++ b/frontend/src/assets/img/user.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index ede1d29b..afb55ca5 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -201,24 +201,19 @@ let knowledgeIcon = ref('zhishiku-green.svg');
let prefixIcon = ref('prefixIcon.svg');
let settingIcon = ref('setting.svg');
let logoutIcon = ref('logout.svg');
-let tenantIcon = ref('setting.svg'); // 暂时使用setting图标
+let tenantIcon = ref('user.svg'); // 使用专门的用户图标
let pathPrefix = ref(route.name)
const getIcon = (path) => {
fileAddIcon.value = path == 'knowledgeBase' ? 'file-add-green.svg' : 'file-add.svg';
knowledgeIcon.value = path == 'knowledgeBase' ? 'zhishiku-green.svg' : 'zhishiku.svg';
prefixIcon.value = path == 'creatChat' ? 'prefixIcon-green.svg' : path == 'knowledgeBase' ? 'prefixIcon-grey.svg' : 'prefixIcon.svg';
settingIcon.value = path == 'settings' ? 'setting-green.svg' : 'setting.svg';
- tenantIcon.value = path == 'tenant' ? 'setting-green.svg' : 'setting.svg'; // 暂时使用setting图标
+ tenantIcon.value = path == 'tenant' ? 'user-green.svg' : 'user.svg'; // 使用专门的用户图标
logoutIcon.value = 'logout.svg';
}
getIcon(route.name)
const gotopage = (path) => {
pathPrefix.value = path;
- // 如果是系统设置,跳转到初始化配置页面
- if (path === 'settings') {
- router.push('/initialization');
- return;
- }
// 处理退出登录
if (path === 'logout') {
authStore.logout();
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index f0a4b4a6..f1fee076 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -62,9 +62,9 @@ const router = createRouter({
{
path: "settings",
name: "settings",
- component: () => import("../views/settings/Settings.vue"),
- meta: { requiresInit: true }
- },
+ component: () => import("../views/settings/SystemSettings.vue"),
+ meta: { requiresInit: true }
+ },
],
},
],
diff --git a/frontend/src/views/initialization/InitializationConfig.vue b/frontend/src/views/initialization/InitializationConfig.vue
index 8a82a71d..fa26650b 100644
--- a/frontend/src/views/initialization/InitializationConfig.vue
+++ b/frontend/src/views/initialization/InitializationConfig.vue
@@ -2,29 +2,20 @@
-
-
@@ -941,26 +931,6 @@ const imageUpload = ref(null);
// Embedding 维度检测状态
const embeddingDimDetecting = ref(false);
-// 左侧导航区段
-type Section = { id: string; label: string };
-const sections: Section[] = [
- { id: 'ollama', label: 'Ollama 服务' },
- { id: 'llm', label: 'LLM 模型' },
- { id: 'embedding', label: 'Embedding 模型' },
- { id: 'rerank', label: 'Rerank 配置' },
- { id: 'multimodal', label: '多模态配置' },
- { id: 'docsplit', label: '文档分割' },
- { id: 'submit', label: '完成配置' },
-];
-
-const activeSectionId = ref
('ollama');
-const goToSection = (id: string) => {
- const el = document.getElementById(`section-${id}`);
- if (el) {
- el.scrollIntoView({ behavior: 'smooth', block: 'start' });
- activeSectionId.value = id;
- }
-};
// 退出登录
const handleLogout = () => {
@@ -968,19 +938,6 @@ const handleLogout = () => {
router.replace('/login');
};
-// 监听滚动,高亮当前区块
-const onScroll = () => {
- const order = ['ollama','llm','embedding','rerank','multimodal','docsplit','submit'];
- for (const id of order) {
- const el = document.getElementById(`section-${id}`);
- if (!el) continue;
- const rect = el.getBoundingClientRect();
- if (rect.top <= 120 && rect.bottom >= 120) {
- activeSectionId.value = id;
- break;
- }
- }
-};
// 配置回填
const loadCurrentConfig = async () => {
@@ -1004,8 +961,8 @@ const loadCurrentConfig = async () => {
if (config.rerank) {
Object.assign(formData.rerank, config.rerank);
}
- formData.storageType = config.multimodal.storageType;
if (config.multimodal) {
+ formData.storageType = config.multimodal.storageType || 'minio';
formData.multimodal.enabled = config.multimodal.enabled || false;
if (config.multimodal.vlm) {
Object.assign(formData.multimodal.vlm, config.multimodal.vlm);
@@ -1014,11 +971,14 @@ const loadCurrentConfig = async () => {
formData.multimodal.vlm.interfaceType = 'ollama';
}
}
- if (config.multimodal.storageType === 'cos') {
+ if (config.multimodal.storageType === 'cos' && config.multimodal.cos) {
Object.assign(formData.multimodal.cos, config.multimodal.cos);
- } else if (config.multimodal.storageType === 'minio') {
+ } else if (config.multimodal.storageType === 'minio' && config.multimodal.minio) {
Object.assign(formData.multimodal.minio, config.multimodal.minio);
}
+ } else {
+ // 如果没有多模态配置,设置默认存储类型
+ formData.storageType = 'minio';
}
if (config.documentSplitting) {
Object.assign(formData.documentSplitting, config.documentSplitting);
@@ -1351,8 +1311,6 @@ onUnmounted(() => {
clearTimeout(submitDebounceTimer.value);
submitDebounceTimer.value = null;
}
-
- window.removeEventListener('scroll', onScroll);
});
// 事件处理
@@ -1740,6 +1698,23 @@ const handleSubmit = async () => {
// 调用初始化API
const payload: any = JSON.parse(JSON.stringify(formData));
+
+ // 确保存储类型在正确的位置,并只保留选中的存储配置
+ if (payload.multimodal && payload.storageType) {
+ payload.multimodal.storageType = payload.storageType;
+
+ // 根据选择的存储类型,只保留对应的配置,删除其他存储配置
+ if (payload.storageType === 'cos') {
+ // 保留COS配置,删除MinIO配置
+ delete payload.multimodal.minio;
+ } else if (payload.storageType === 'minio') {
+ // 保留MinIO配置,删除COS配置
+ delete payload.multimodal.cos;
+ }
+
+ delete payload.storageType; // 删除顶级的storageType字段
+ }
+
await initializeSystem(payload);
const successMessage = isUpdateMode.value ? '配置更新成功!' : '系统初始化成功!';
@@ -1777,9 +1752,6 @@ onMounted(async () => {
// 检查已配置模型状态
await checkAllConfiguredModels();
-
- // 绑定滚动监听,用于左侧导航高亮
- window.addEventListener('scroll', onScroll, { passive: true });
});
const onRerankChange = () => {
@@ -2347,144 +2319,75 @@ const detectEmbeddingDimension = async () => {
diff --git a/frontend/src/views/settings/SystemSettings.vue b/frontend/src/views/settings/SystemSettings.vue
new file mode 100644
index 00000000..730b3d04
--- /dev/null
+++ b/frontend/src/views/settings/SystemSettings.vue
@@ -0,0 +1,125 @@
+
+
+
+
+
+
+
diff --git a/frontend/src/views/tenant/TenantInfo.vue b/frontend/src/views/tenant/TenantInfo.vue
index 6379b154..1890cb26 100644
--- a/frontend/src/views/tenant/TenantInfo.vue
+++ b/frontend/src/views/tenant/TenantInfo.vue
@@ -311,11 +311,11 @@ onMounted(() => {
.tenant-info-container {
padding: 20px;
background-color: #fff;
- border-radius: 8px;
- margin: 0 20px 20px 20px;
- height: calc(100vh - 40px);
+ margin: 0 20px 0 20px;
+ height: calc(100vh);
overflow-y: auto;
box-sizing: border-box;
+ flex: 1;
}
.tenant-header {
@@ -363,7 +363,7 @@ onMounted(() => {
.api-key-content,
.storage-content,
.doc-content {
-// padding: 16px 0;
+ margin-top: 0;
}
.api-key-input {
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go
index 07078a40..b74fd558 100644
--- a/internal/handler/initialization.go
+++ b/internal/handler/initialization.go
@@ -83,9 +83,7 @@ func NewInitializationHandler(
// InitializationRequest 初始化请求结构
type InitializationRequest struct {
- // 前端传入的存储类型:cos 或 minio
- StorageType string `json:"storageType"`
- LLM struct {
+ LLM struct {
Source string `json:"source" binding:"required"`
ModelName string `json:"modelName" binding:"required"`
BaseURL string `json:"baseUrl"`
@@ -115,7 +113,8 @@ type InitializationRequest struct {
APIKey string `json:"apiKey"`
InterfaceType string `json:"interfaceType"` // "ollama" or "openai"
} `json:"vlm,omitempty"`
- COS *struct {
+ StorageType string `json:"storageType"`
+ COS *struct {
SecretID string `json:"secretId"`
SecretKey string `json:"secretKey"`
Region string `json:"region"`
@@ -210,7 +209,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
// 验证多模态配置
if req.Multimodal.Enabled {
- storageType := strings.ToLower(req.StorageType)
+ storageType := strings.ToLower(req.Multimodal.StorageType)
if req.Multimodal.VLM == nil {
logger.Error(ctx, "Multimodal enabled but missing VLM configuration")
c.Error(errors.NewBadRequestError("启用多模态时需要配置VLM信息"))
@@ -502,11 +501,11 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
InterfaceType: req.Multimodal.VLM.InterfaceType,
},
}
- switch req.StorageType {
+ switch req.Multimodal.StorageType {
case "cos":
if req.Multimodal.COS != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.COS.BucketName,
AppID: req.Multimodal.COS.AppID,
PathPrefix: req.Multimodal.COS.PathPrefix,
@@ -518,7 +517,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
case "minio":
if req.Multimodal.Minio != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.Minio.BucketName,
PathPrefix: req.Multimodal.Minio.PathPrefix,
SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
@@ -560,11 +559,11 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
APIKey: req.Multimodal.VLM.APIKey,
InterfaceType: req.Multimodal.VLM.InterfaceType,
}
- switch req.StorageType {
+ switch req.Multimodal.StorageType {
case "cos":
if req.Multimodal.COS != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
SecretID: req.Multimodal.COS.SecretID,
SecretKey: req.Multimodal.COS.SecretKey,
Region: req.Multimodal.COS.Region,
@@ -576,7 +575,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
case "minio":
if req.Multimodal.Minio != nil {
kb.StorageConfig = types.StorageConfig{
- Provider: req.StorageType,
+ Provider: req.Multimodal.StorageType,
BucketName: req.Multimodal.Minio.BucketName,
PathPrefix: req.Multimodal.Minio.PathPrefix,
SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
From c589a911dcb1a1af40ba6dfd9ef6f7a5672386a1 Mon Sep 17 00:00:00 2001
From: begoniezhao
Date: Tue, 16 Sep 2025 20:53:39 +0800
Subject: [PATCH 09/39] feat: Added multi-data source search engine
configuration and optimization logic
---
internal/application/service/user.go | 71 ++++++++++++++++++++++------
1 file changed, 56 insertions(+), 15 deletions(-)
diff --git a/internal/application/service/user.go b/internal/application/service/user.go
index a0475b6f..671d12e8 100644
--- a/internal/application/service/user.go
+++ b/internal/application/service/user.go
@@ -4,6 +4,8 @@ import (
"context"
"errors"
"fmt"
+ "os"
+ "strings"
"time"
"github.com/golang-jwt/jwt/v5"
@@ -34,6 +36,35 @@ func NewUserService(userRepo interfaces.UserRepository, tokenRepo interfaces.Aut
}
}
+var engine = map[string][]types.RetrieverEngineParams{
+ "postgres": {
+ {
+ RetrieverType: types.KeywordsRetrieverType,
+ RetrieverEngineType: types.PostgresRetrieverEngineType,
+ },
+ {
+ RetrieverType: types.VectorRetrieverType,
+ RetrieverEngineType: types.PostgresRetrieverEngineType,
+ },
+ },
+ "elasticsearch_v7": {
+ {
+ RetrieverType: types.KeywordsRetrieverType,
+ RetrieverEngineType: types.ElasticsearchRetrieverEngineType,
+ },
+ },
+ "elasticsearch_v8": {
+ {
+ RetrieverType: types.KeywordsRetrieverType,
+ RetrieverEngineType: types.ElasticsearchRetrieverEngineType,
+ },
+ {
+ RetrieverType: types.VectorRetrieverType,
+ RetrieverEngineType: types.ElasticsearchRetrieverEngineType,
+ },
+ },
+}
+
// Register creates a new user account
func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error) {
logger.Info(ctx, "Start user registration")
@@ -61,23 +92,21 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
return nil, errors.New("failed to process password")
}
+ egs := []types.RetrieverEngineParams{}
+ for _, driver := range strings.Split(os.Getenv("RETRIEVE_DRIVER"), ",") {
+ if val, ok := engine[driver]; ok {
+ egs = append(egs, val...)
+ }
+ }
+ egs = uniqueRetrieverEngine(egs)
+ logger.Debugf(ctx, "user register retriever engines: %v", egs)
+
// Create default tenant for the user
tenant := &types.Tenant{
- Name: fmt.Sprintf("%s's Workspace", req.Username),
- Description: "Default workspace",
- Status: "active",
- RetrieverEngines: types.RetrieverEngines{
- Engines: []types.RetrieverEngineParams{
- {
- RetrieverType: types.KeywordsRetrieverType,
- RetrieverEngineType: types.PostgresRetrieverEngineType,
- },
- {
- RetrieverType: types.VectorRetrieverType,
- RetrieverEngineType: types.PostgresRetrieverEngineType,
- },
- },
- },
+ Name: fmt.Sprintf("%s's Workspace", req.Username),
+ Description: "Default workspace",
+ Status: "active",
+ RetrieverEngines: types.RetrieverEngines{Engines: egs},
}
createdTenant, err := s.tenantService.CreateTenant(ctx, tenant)
@@ -406,3 +435,15 @@ func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) {
return user, nil
}
+
+func uniqueRetrieverEngine(engine []types.RetrieverEngineParams) []types.RetrieverEngineParams {
+ seen := make(map[types.RetrieverEngineParams]bool)
+ var result []types.RetrieverEngineParams
+ for _, v := range engine {
+ if !seen[v] {
+ seen[v] = true
+ result = append(result, v)
+ }
+ }
+ return result
+}
From 91e65d6445a959cb1586d1e296d8f1307e10c888 Mon Sep 17 00:00:00 2001
From: wizardchen
Date: Wed, 17 Sep 2025 16:02:08 +0800
Subject: [PATCH 10/39] feat(ui): Support multi knowledgebases operation
---
.github/workflows/docker-image.yml | 28 +-
Makefile | 17 +-
config/config.yaml | 2 +-
docker/Dockerfile.app | 14 +-
frontend/src/api/auth/index.ts | 4 +-
frontend/src/api/chat/index.ts | 7 -
frontend/src/api/chat/streame.ts | 18 +-
frontend/src/api/initialization/index.ts | 41 +-
frontend/src/api/knowledge-base/index.ts | 59 +-
frontend/src/api/system/index.ts | 12 +
frontend/src/api/test-data/index.ts | 64 -
frontend/src/components/menu.vue | 528 ++-
frontend/src/hooks/useKnowledgeBase.ts | 69 +-
frontend/src/router/index.ts | 67 +-
frontend/src/stores/auth.ts | 5 -
frontend/src/stores/knowledge.ts | 4 +-
frontend/src/stores/menu.ts | 5 +-
frontend/src/utils/index.ts | 14 +-
frontend/src/utils/request.ts | 22 -
frontend/src/views/auth/Login.vue | 6 -
frontend/src/views/chat/index.vue | 11 +-
frontend/src/views/creatChat/creatChat.vue | 86 +-
.../initialization/InitializationConfig.vue | 3498 -----------------
.../initialization/InitializationContent.vue | 171 +-
.../src/views/knowledge/KnowledgeBase.vue | 143 +-
.../src/views/knowledge/KnowledgeBaseList.vue | 234 ++
.../src/views/settings/SystemSettings.vue | 96 +-
frontend/src/views/tenant/TenantInfo.vue | 57 +-
internal/application/service/evaluation.go | 63 +-
internal/application/service/test_data.go | 444 ---
internal/container/container.go | 3 +-
internal/handler/initialization.go | 471 +--
internal/handler/session.go | 4 -
internal/handler/system.go | 49 +
internal/handler/test_data.go | 87 -
internal/models/chat/remote_api.go | 8 +
internal/router/router.go | 21 +-
scripts/build_images.sh | 39 +
scripts/get_version.sh | 86 +
39 files changed, 1718 insertions(+), 4839 deletions(-)
create mode 100644 frontend/src/api/system/index.ts
delete mode 100644 frontend/src/api/test-data/index.ts
delete mode 100644 frontend/src/views/initialization/InitializationConfig.vue
create mode 100644 frontend/src/views/knowledge/KnowledgeBaseList.vue
delete mode 100644 internal/application/service/test_data.go
create mode 100644 internal/handler/system.go
delete mode 100644 internal/handler/test_data.go
create mode 100755 scripts/get_version.sh
diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml
index d7c121d1..aef205fe 100644
--- a/.github/workflows/docker-image.yml
+++ b/.github/workflows/docker-image.yml
@@ -42,8 +42,25 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- - name: Read VERSION file
- run: echo "VERSION=$(cat VERSION)" >> $GITHUB_ENV
+ - name: Set up Go
+ if: matrix.service_name == 'app'
+ uses: actions/setup-go@v4
+ with:
+ go-version: '1.24'
+
+ - name: Prepare version info
+ id: version
+ run: |
+ # 使用统一的版本管理脚本
+ eval $(./scripts/get_version.sh env)
+
+ echo "version=$VERSION" >> $GITHUB_OUTPUT
+ echo "commit_id=$COMMIT_ID" >> $GITHUB_OUTPUT
+ echo "build_time=$BUILD_TIME" >> $GITHUB_OUTPUT
+ echo "go_version=$GO_VERSION" >> $GITHUB_OUTPUT
+
+ # 显示版本信息
+ ./scripts/get_version.sh info
- name: Build ${{ matrix.service_name }} Image
uses: docker/build-push-action@v3
@@ -52,8 +69,13 @@ jobs:
platforms: ${{ matrix.platform }}
file: ${{ matrix.file }}
context: ${{ matrix.context }}
+ build-args: |
+ ${{ matrix.service_name == 'app' && format('VERSION_ARG={0}', steps.version.outputs.version) || '' }}
+ ${{ matrix.service_name == 'app' && format('COMMIT_ID_ARG={0}', steps.version.outputs.commit_id) || '' }}
+ ${{ matrix.service_name == 'app' && format('BUILD_TIME_ARG={0}', steps.version.outputs.build_time) || '' }}
+ ${{ matrix.service_name == 'app' && format('GO_VERSION_ARG={0}', steps.version.outputs.go_version) || '' }}
tags: |
${{ secrets.DOCKERHUB_USERNAME }}/weknora-${{ matrix.service_name }}:latest
- ${{ secrets.DOCKERHUB_USERNAME }}/weknora-${{ matrix.service_name }}:${{ env.VERSION }}
+ ${{ secrets.DOCKERHUB_USERNAME }}/weknora-${{ matrix.service_name }}:${{ steps.version.outputs.version }}
cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-${{ matrix.service_name }}:cache
cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-${{ matrix.service_name }}:cache,mode=max
\ No newline at end of file
diff --git a/Makefile b/Makefile
index b8d414a6..dde85f42 100644
--- a/Makefile
+++ b/Makefile
@@ -85,7 +85,15 @@ clean:
# Build Docker image
docker-build-app:
- docker build --platform $(PLATFORM) -f docker/Dockerfile.app -t $(DOCKER_IMAGE):$(DOCKER_TAG) .
+ @echo "获取版本信息..."
+ @eval $$(./scripts/get_version.sh env); \
+ ./scripts/get_version.sh info; \
+ docker build --platform $(PLATFORM) \
+ --build-arg VERSION_ARG="$$VERSION" \
+ --build-arg COMMIT_ID_ARG="$$COMMIT_ID" \
+ --build-arg BUILD_TIME_ARG="$$BUILD_TIME" \
+ --build-arg GO_VERSION_ARG="$$GO_VERSION" \
+ -f docker/Dockerfile.app -t $(DOCKER_IMAGE):$(DOCKER_TAG) .
# Build docreader Docker image
docker-build-docreader:
@@ -168,7 +176,12 @@ deps:
# Build for production
build-prod:
- GOOS=linux go build -installsuffix cgo -ldflags="-w -s" -o $(BINARY_NAME) $(MAIN_PATH)
+ @VERSION=$${VERSION:-unknown}; \
+ COMMIT_ID=$${COMMIT_ID:-unknown}; \
+ BUILD_TIME=$${BUILD_TIME:-unknown}; \
+ GO_VERSION=$${GO_VERSION:-unknown}; \
+ LDFLAGS="-X 'github.com/Tencent/WeKnora/internal/handler.Version=$$VERSION' -X 'github.com/Tencent/WeKnora/internal/handler.CommitID=$$COMMIT_ID' -X 'github.com/Tencent/WeKnora/internal/handler.BuildTime=$$BUILD_TIME' -X 'github.com/Tencent/WeKnora/internal/handler.GoVersion=$$GO_VERSION'"; \
+ GOOS=linux go build -installsuffix cgo -ldflags="-w -s $$LDFLAGS" -o $(BINARY_NAME) $(MAIN_PATH)
clean-db:
@echo "Cleaning database..."
diff --git a/config/config.yaml b/config/config.yaml
index d739a835..4caa32c6 100644
--- a/config/config.yaml
+++ b/config/config.yaml
@@ -9,7 +9,7 @@ conversation:
keyword_threshold: 0.3
embedding_top_k: 10
vector_threshold: 0.5
- rerank_threshold: 0.7
+ rerank_threshold: 0.5
rerank_top_k: 5
fallback_strategy: "fixed"
fallback_response: "抱歉,我无法回答这个问题。"
diff --git a/docker/Dockerfile.app b/docker/Dockerfile.app
index 5a9c93bd..7cdc1492 100644
--- a/docker/Dockerfile.app
+++ b/docker/Dockerfile.app
@@ -28,7 +28,19 @@ RUN go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate
# Copy source code
COPY . .
-# Build the application
+# Get version and commit info for build injection
+ARG VERSION_ARG
+ARG COMMIT_ID_ARG
+ARG BUILD_TIME_ARG
+ARG GO_VERSION_ARG
+
+# Set build-time variables
+ENV VERSION=${VERSION_ARG}
+ENV COMMIT_ID=${COMMIT_ID_ARG}
+ENV BUILD_TIME=${BUILD_TIME_ARG}
+ENV GO_VERSION=${GO_VERSION_ARG}
+
+# Build the application with version info
RUN make build-prod
# Final stage
diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts
index 4fe47672..85efb6a5 100644
--- a/frontend/src/api/auth/index.ts
+++ b/frontend/src/api/auth/index.ts
@@ -143,10 +143,10 @@ export async function register(data: RegisterRequest): Promise
/**
* 获取当前用户信息
*/
-export async function getCurrentUser(): Promise<{ success: boolean; data?: UserInfo; message?: string }> {
+export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant: TenantInfo }; message?: string }> {
try {
const response = await get('/api/v1/auth/me')
- return response as unknown as { success: boolean; data?: UserInfo; message?: string }
+ return response as unknown as { success: boolean; data?: { user: UserInfo; tenant: TenantInfo }; message?: string }
} catch (error: any) {
return {
success: false,
diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts
index 32f0b172..2d5fe315 100644
--- a/frontend/src/api/chat/index.ts
+++ b/frontend/src/api/chat/index.ts
@@ -1,30 +1,24 @@
import { get, post, put, del, postChat } from "../../utils/request";
-import { loadTestData } from "../test-data";
export async function createSessions(data = {}) {
- await loadTestData();
return post("/api/v1/sessions", data);
}
export async function getSessionsList(page: number, page_size: number) {
- await loadTestData();
return get(`/api/v1/sessions?page=${page}&page_size=${page_size}`);
}
export async function generateSessionsTitle(session_id: string, data: any) {
- await loadTestData();
return post(`/api/v1/sessions/${session_id}/generate_title`, data);
}
export async function knowledgeChat(data: { session_id: string; query: string; }) {
- await loadTestData();
return postChat(`/api/v1/knowledge-chat/${data.session_id}`, { query: data.query });
}
export async function getMessageList(data: { session_id: string; limit: number, created_at: string }) {
- await loadTestData();
if (data.created_at) {
return get(`/api/v1/messages/${data.session_id}/load?before_time=${encodeURIComponent(data.created_at)}&limit=${data.limit}`);
} else {
@@ -33,6 +27,5 @@ export async function getMessageList(data: { session_id: string; limit: number,
}
export async function delSession(session_id: string) {
- await loadTestData();
return del(`/api/v1/sessions/${session_id}`);
}
\ No newline at end of file
diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts
index f7d8dae9..26cb4901 100644
--- a/frontend/src/api/chat/streame.ts
+++ b/frontend/src/api/chat/streame.ts
@@ -1,8 +1,6 @@
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { ref, type Ref, onUnmounted, nextTick } from 'vue'
import { generateRandomString } from '@/utils/index';
-import { getTestData } from '@/utils/request';
-import { loadTestData } from "../test-data";
@@ -37,16 +35,16 @@ export function useStream() {
isStreaming.value = true;
isLoading.value = true;
- // 使用默认配置
- await loadTestData();
- const testData = getTestData();
- if (!testData) {
- error.value = "测试数据未初始化,无法进行聊天";
+ // 获取API配置
+ const apiUrl = import.meta.env.VITE_IS_DOCKER ? "" : "http://localhost:8080";
+
+ // 获取JWT Token
+ const token = localStorage.getItem('weknora_token');
+ if (!token) {
+ error.value = "未找到登录令牌,请重新登录";
stopStream();
return;
}
- const apiUrl = import.meta.env.VITE_IS_DOCKER ? "" : "http://localhost:8080";
- const apiKey = testData.tenant.api_key;
try {
let url =
@@ -57,7 +55,7 @@ export function useStream() {
method: params.method,
headers: {
"Content-Type": "application/json",
- "X-API-Key": apiKey,
+ "Authorization": `Bearer ${token}`,
"X-Request-ID": `${generateRandomString(12)}`,
},
body:
diff --git a/frontend/src/api/initialization/index.ts b/frontend/src/api/initialization/index.ts
index c42f1483..4231cdb9 100644
--- a/frontend/src/api/initialization/index.ts
+++ b/frontend/src/api/initialization/index.ts
@@ -63,38 +63,19 @@ export interface DownloadTask {
endTime?: string;
}
-// 系统初始化状态检查
-export function checkInitializationStatus(): Promise<{ initialized: boolean }> {
- return new Promise((resolve, reject) => {
- get('/api/v1/initialization/status')
- .then((response: any) => {
- resolve(response.data || { initialized: false });
- })
- .catch((error: any) => {
- // 如果是401,交给全局拦截器去处理(重定向登录),这里不要把它当成未初始化
- if (error && error.status === 401) {
- reject(error);
- return;
- }
- console.warn('检查初始化状态失败,假设需要初始化:', error);
- resolve({ initialized: false });
- });
- });
-}
-// 执行系统初始化
-export function initializeSystem(config: InitializationConfig): Promise {
+
+// 根据知识库ID执行配置更新
+export function initializeSystemByKB(kbId: string, config: InitializationConfig): Promise {
return new Promise((resolve, reject) => {
- console.log('开始系统初始化...', config);
- post('/api/v1/initialization/initialize', config)
+ console.log('开始知识库配置更新...', kbId, config);
+ post(`/api/v1/initialization/initialize/${kbId}`, config)
.then((response: any) => {
- console.log('系统初始化完成', response);
- // 设置本地初始化状态标记
- localStorage.setItem('system_initialized', 'true');
+ console.log('知识库配置更新完成', response);
resolve(response);
})
.catch((error: any) => {
- console.error('系统初始化失败:', error);
+ console.error('知识库配置更新失败:', error);
reject(error);
});
});
@@ -184,15 +165,15 @@ export function listDownloadTasks(): Promise {
});
}
-// 获取当前系统配置
-export function getCurrentConfig(): Promise {
+
+export function getCurrentConfigByKB(kbId: string): Promise {
return new Promise((resolve, reject) => {
- get('/api/v1/initialization/config')
+ get(`/api/v1/initialization/config/${kbId}`)
.then((response: any) => {
resolve(response.data || {});
})
.catch((error: any) => {
- console.error('获取当前配置失败:', error);
+ console.error('获取知识库配置失败:', error);
reject(error);
});
});
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts
index 557a209e..e507d332 100644
--- a/frontend/src/api/knowledge-base/index.ts
+++ b/frontend/src/api/knowledge-base/index.ts
@@ -1,44 +1,55 @@
-import { get, post, put, del, postUpload, getDown, getTestData } from "../../utils/request";
-import { loadTestData } from "../test-data";
-export async function getDefaultKnowledgeBaseId(): Promise {
- // 如果设置中没有知识库ID,则使用测试数据
- await loadTestData();
- const testData = getTestData();
- if (!testData || testData.knowledge_bases.length === 0) {
- throw new Error('没有可用的知识库');
- }
-
- return testData.knowledge_bases[0].id;
+import { get, post, put, del, postUpload, getDown } from "../../utils/request";
+
+// 知识库管理 API(列表、创建、获取、更新、删除、复制)
+export function listKnowledgeBases() {
+ return get(`/api/v1/knowledge-bases`);
}
-export async function uploadKnowledgeBase(data = {}) {
- const kbId = await getDefaultKnowledgeBaseId();
+export function createKnowledgeBase(data: { name: string; description?: string; chunking_config?: any }) {
+ return post(`/api/v1/knowledge-bases`, data);
+}
+
+export function getKnowledgeBaseById(id: string) {
+ return get(`/api/v1/knowledge-bases/${id}`);
+}
+
+export function updateKnowledgeBase(id: string, data: { name: string; description?: string; config: any }) {
+ return put(`/api/v1/knowledge-bases/${id}` , data);
+}
+
+export function deleteKnowledgeBase(id: string) {
+ return del(`/api/v1/knowledge-bases/${id}`);
+}
+
+export function copyKnowledgeBase(data: { source_id: string; target_id?: string }) {
+ return post(`/api/v1/knowledge-bases/copy`, data);
+}
+
+// 知识文件 API(基于具体知识库)
+export function uploadKnowledgeFile(kbId: string, data = {}) {
return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, data);
}
-export async function getKnowledgeBase({page, page_size}: {page: number, page_size: number}) {
- const kbId = await getDefaultKnowledgeBaseId();
- return get(
- `/api/v1/knowledge-bases/${kbId}/knowledge?page=${page}&page_size=${page_size}`
- );
+export function listKnowledgeFiles(kbId: string, { page, page_size }: { page: number; page_size: number }) {
+ return get(`/api/v1/knowledge-bases/${kbId}/knowledge?page=${page}&page_size=${page_size}`);
}
-export function getKnowledgeDetails(id: any) {
+export function getKnowledgeDetails(id: string) {
return get(`/api/v1/knowledge/${id}`);
}
-export function delKnowledgeDetails(id: any) {
+export function delKnowledgeDetails(id: string) {
return del(`/api/v1/knowledge/${id}`);
}
-export function downKnowledgeDetails(id: any) {
+export function downKnowledgeDetails(id: string) {
return getDown(`/api/v1/knowledge/${id}/download`);
}
-export function batchQueryKnowledge(ids: any) {
- return get(`/api/v1/knowledge/batch?${ids}`);
+export function batchQueryKnowledge(idsQueryString: string) {
+ return get(`/api/v1/knowledge/batch?${idsQueryString}`);
}
-export function getKnowledgeDetailsCon(id: any, page: number) {
+export function getKnowledgeDetailsCon(id: string, page: number) {
return get(`/api/v1/chunks/${id}?page=${page}&page_size=25`);
}
\ No newline at end of file
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
new file mode 100644
index 00000000..41011011
--- /dev/null
+++ b/frontend/src/api/system/index.ts
@@ -0,0 +1,12 @@
+import { get } from '@/utils/request'
+
+export interface SystemInfo {
+ version: string
+ commit_id?: string
+ build_time?: string
+ go_version?: string
+}
+
+export function getSystemInfo(): Promise<{ data: SystemInfo }> {
+ return get('/api/v1/system/info')
+}
diff --git a/frontend/src/api/test-data/index.ts b/frontend/src/api/test-data/index.ts
deleted file mode 100644
index ef99e455..00000000
--- a/frontend/src/api/test-data/index.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { get, setTestData } from '../../utils/request';
-
-export interface TestDataResponse {
- success: boolean;
- data: {
- tenant: {
- id: number;
- name: string;
- api_key: string;
- };
- knowledge_bases: Array<{
- id: string;
- name: string;
- description: string;
- }>;
- }
-}
-
-// 是否已加载测试数据
-let isTestDataLoaded = false;
-
-/**
- * 加载测试数据
- * 在API调用前调用此函数以确保测试数据已加载
- * @returns Promise 是否成功加载
- */
-export async function loadTestData(): Promise {
- // 如果已经加载过,直接返回
- if (isTestDataLoaded) {
- return true;
- }
-
- try {
- console.log('开始加载测试数据...');
- const response = await get('/api/v1/test-data');
- console.log('测试数据', response);
-
- if (response && response.data) {
- // 设置测试数据
- setTestData({
- tenant: response.data.tenant,
- knowledge_bases: response.data.knowledge_bases
- });
- isTestDataLoaded = true;
- console.log('测试数据加载成功');
- return true;
- } else {
- console.warn('测试数据响应为空');
- return false;
- }
- } catch (error) {
- console.error('加载测试数据失败:', error);
- return false;
- }
-}
-
-/**
- * 重置测试数据加载状态,在重新登录或需要强制刷新时调用
- */
-export function resetTestDataLoaded() {
- isTestDataLoaded = false;
- // 清空已缓存的测试数据,确保下次调用会重新获取
- setTestData(null);
-}
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index afb55ca5..d5ca73bc 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -1,25 +1,48 @@